# oneshader Go docs, all pages (oneshader-go 1.0.0) Every page of https://recursiveai.org/oneshader/go/docs/ as markdown, getting started first. Index: https://recursiveai.org/oneshader/go/llms.txt # Getting started with oneshader for Go Install oneshader for Go, compile an HLSL compute shader to SPIR-V, Metal Shading Language and WGSL from a Go program, read a compile error, generate Go bindings with `go generate`, and compile from the command line. oneshader for Go is an HLSL compiler written in Go: modern HLSL (Shader Model 6 style) vertex, pixel and compute shaders in; SPIR-V, Metal Shading Language, WGSL and DXIL out, each with reflection. Every sample on this page was compiled and run with Go 1.26.8 against `recursiveai.org/go/oneshader` v1.0.0 from the Go module proxy; the output under each one is what it printed. ## Install oneshader needs Go 1.24 or newer. ```sh mkdir double && cd double go mod init example.com/double go get recursiveai.org/go/oneshader@v1.0.0 ``` The module has no dependencies (its `go.mod` requires nothing) and no cgo, so it builds with `CGO_ENABLED=0`. The license is MIT or Apache-2.0, at your choice. ## Compile a shader A compute shader that doubles every value in a buffer, `double.hlsl`: ```hlsl RWStructuredBuffer Values : register(u0); [shader("compute")] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { Values[id.x] *= 2.0; } ``` `main.go` compiles it for three targets and prints the WGSL: ```go package main import ( "fmt" "log" "os" "recursiveai.org/go/oneshader" ) func main() { src, err := os.ReadFile("double.hlsl") if err != nil { log.Fatal(err) } res, err := oneshader.Compile(src, oneshader.WithName("double.hlsl"), oneshader.WithTargets( oneshader.TargetSPIRV, oneshader.TargetMSL, oneshader.TargetWGSL)) if err != nil { for _, d := range res.Errors() { fmt.Println(d) } os.Exit(1) } for _, b := range res.Blobs { fmt.Println(b.Entry, b.Stage, b.Target, len(b.Data), "bytes") } wgsl, _ := res.Find("main", oneshader.TargetWGSL) fmt.Print(string(wgsl.Data)) } ``` ```sh go run . ``` ```text main Compute spirv 644 bytes main Compute msl 635 bytes main Compute wgsl 336 bytes @group(0) @binding(0) var Values: array; @compute @workgroup_size(64, 1, 1) fn main(@builtin(global_invocation_id) a_main_id: vec3) { let v0 = a_main_id; let v1 = v0[0]; let v2 = bitcast(Values[(v1 * 4u) >> 2u]); let v3 = v2 * 2.0f; Values[(v1 * 4u) >> 2u] = bitcast(v3); return; } ``` The entry point is found by its `[shader("compute")]` attribute; `WithEntryPoints` names entry points instead. Each `Blob` holds one entry point for one target: a SPIR-V module, or MSL or WGSL source text. `res.Reflection` describes the shader’s resources, push constants, stage variables and byte layouts. `TargetDXIL` adds DXIL containers for Direct3D 12. The same source and options always give byte-identical output. ## Read a compile error Change the multiplier to a name the shader doesn’t declare, `Values[id.x] *= scale;`, and run again. When the source has errors, `Compile` returns a `*DiagnosticsError` and `res.Errors()` lists them: ```text double.hlsl(7,21): error OSH0300: 'scale' is not declared; declare it before this use ``` Each diagnostic has a location, a stable `OSHnnnn` code and what to do about it. A limit on untrusted source (include depth, macro expansion, nesting, program size) is a diagnostic too; `errors.Is(err, oneshader.ErrLimit)` matches it, and `WithLimits` sets the bounds. ## Go bindings with go generate The `oneshader gen` command compiles `*.hlsl` at build time and writes Go next to it: structs laid out to the shader’s buffers, where each resource binds, and the compiled code embedded with `//go:embed`. In a new module (`go mod init example.com/particles` and the same `go get`), `particles.hlsl`: ```hlsl struct Particle { float3 Position; float Life; float3 Velocity; }; cbuffer Params : register(b0) { float Dt; uint Count; }; RWStructuredBuffer Particles : register(u1); [shader("compute")] [numthreads(64, 1, 1)] void Step(uint3 id : SV_DispatchThreadID) { if (id.x >= Count) return; Particle p = Particles[id.x]; p.Position += p.Velocity * Dt; p.Life -= Dt; Particles[id.x] = p; } ``` `main.go` runs the generator from `//go:generate` and prints what it wrote: ```go package main //go:generate go run recursiveai.org/go/oneshader/cmd/oneshader gen -pkg main -targets spirv,msl,wgsl particles.hlsl import ( "fmt" "recursiveai.org/go/oneshader/shader" ) func main() { fmt.Println("Params:", ParticlesParamsSize, "bytes") fmt.Println("Particle:", ParticlesParticleSize, "bytes") fmt.Println("Particles: Vulkan set", ParticlesParticlesBinding.Slots[shader.SPIRV].Set, "binding", ParticlesParticlesBinding.Slots[shader.SPIRV].Binding) fmt.Println("Step workgroup:", ParticlesStep.Workgroup) for t, blob := range ParticlesStep.Blobs { if len(blob) == 0 { continue // a target not passed to -targets } fmt.Printf("%v: %d bytes\n", shader.Target(t), len(blob)) } } ``` ```sh go generate ./... go run . ``` ```text Params: 16 bytes Particle: 32 bytes Particles: Vulkan set 0 binding 1 Step workgroup: [64 1 1] spirv: 1868 bytes msl: 2379 bytes wgsl: 1590 bytes ``` `go generate` wrote `particles_shader.go`, `particles_shader_layout.go`, `particles_reflection.json` and one file per target: `particles_Step.spv`, `particles_Step.metal` and `particles_Step.wgsl`. The structs in `particles_shader.go` carry the padding the shader’s layout has (doc comments left out here): ```go type ParticlesParams struct { Dt float32 `hlsl:"Dt"` Count uint32 `hlsl:"Count"` _ [8]byte } type ParticlesParticle struct { Position [3]float32 `hlsl:"Position"` Life float32 `hlsl:"Life"` Velocity [3]float32 `hlsl:"Velocity"` _ [4]byte } ``` `particles_shader_layout.go` holds constant checks on every struct’s size and field offsets, so a Go type that doesn’t match the shader’s layout fails `go build`. They use `unsafe.Sizeof` and `unsafe.Offsetof` and cost nothing at run time. With `-layout-checks test` the generator writes the same checks as a test through `reflect` instead, and the package imports no `unsafe`. An error in the shader stops `go generate` with the file, line and column: ```text particles.hlsl:24:20: OSH0300: 'Drag' is not declared; declare it before this use main.go:3: running "go": exit status 1 ``` `oneshader gen -h` lists every flag, among them `-D` and `-I` for macros and include folders, `-axes` and `-variant` for shader variants, `-debug` for debug information in SPIR-V and MSL, and `-o` for the output folder. A file argument may be a pattern such as `shaders/**/*.hlsl`. ## The command line Without `gen`, `oneshader` is “a DXC-compatible compiler”: ```sh go install recursiveai.org/go/oneshader/cmd/oneshader@v1.0.0 oneshader -T cs_6_6 -E main -spirv -Fo double.spv double.hlsl oneshader -T cs_6_6 -E main --target msl double.hlsl ``` The first command writes the 644-byte SPIR-V module to `double.spv`. The second prints the Metal Shading Language: ```text // OneShader: Metal Shading Language 2.4 or newer #include using namespace metal; struct Values_buffer_mem { float data[1]; }; #ifdef ONESHADER_CHECK_LAYOUT static_assert(__builtin_offsetof(Values_buffer_mem, data) == 0, "Values_buffer_mem.data offset"); #endif kernel void main0( device Values_buffer_mem& Values [[buffer(0)]], uint3 main_id_in [[thread_position_in_grid]]) { thread uint3 main_id = uint3(main_id_in); uint3 v; uint v_1; float v_2; float v_3; v = main_id; v_1 = v.x; v_2 = Values.data[v_1]; v_3 = v_2 * 2.0f; Values.data[v_1] = v_3; return; } ``` `--target` takes `spirv`, `msl`, `wgsl`, `dxil` or `ir`, and `--reflect file.json` writes the reflection. ## Next - [Overview](https://recursiveai.org/oneshader/go/docs/overview/): the module README, with the two API layers, targets and compile time. - [Changelog](https://recursiveai.org/oneshader/go/docs/changelog/): what is in 1.0.0. - [Package reference on pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/oneshader). # oneshader-go A pure-Go compiler for modern HLSL (Shader Model 6 style): vertex, pixel and compute shaders in; SPIR-V, Metal Shading Language, WGSL and DXIL out, each with reflection, and Go bindings generated from the shaders. Module `recursiveai.org/go/oneshader`. No cgo and no dependencies: every package builds with `CGO_ENABLED=0` on Go 1.24 or later. Status: 1.0.0. ## Install ``` go get recursiveai.org/go/oneshader go install recursiveai.org/go/oneshader/cmd/oneshader@latest ``` ## Compile a shader ```go res, err := oneshader.Compile(src, oneshader.WithName("sprite.hlsl"), oneshader.WithTargets(oneshader.TargetSPIRV, oneshader.TargetMSL)) if err != nil { for _, d := range res.Errors() { fmt.Println(d) // sprite.hlsl(12,5): error OSH0301: ... what to do about it } return err // a *DiagnosticsError when the source has errors } for _, b := range res.Blobs { // one per entry point and target, in source order use(b.Entry, b.Stage, b.Target, b.Data) } refl := res.Reflection // resources, push constants, stage variables, byte layouts ``` Entry points are found by `[shader("vertex"|"pixel"|"compute")]`, or named with `WithEntryPoints`. `CompileFile` and `CompileFileContext` read a file and resolve `#include` from its folder; `WithIncludeFS`, `WithIncludeDirs` and `WithIncludeResolver` say where includes come from. A `Cache` keeps compiles for hot reload. ## Two API layers **The happy path** is `Compile` with its options, `Result` and `Reflection`, and the `oneshader` command below. It is built on the low level, not beside it. **The low level** is every stage as its own package, so a tool can start or stop anywhere: - `preprocess`, `syntax`: the preprocessor with its include resolvers, the lexer, parser and syntax tree. - `layout`: buffer layouts, DXC's Vulkan defaults, one byte layout per buffer on every target. - `ir`: the shader IR (builder, verifier, text and binary forms); `ir/opt`: its optimizer. - `spirv`, `msl`, `wgsl`, `dxil`: the backends, each taking an `ir.Module`. - `pipeline`, `shader`: compiled shaders as a GPU layer consumes them: descriptor set layouts, Metal argument indices, bind group layouts, vertex input. A program that only loads compiled shaders imports these and never the compiler. - `diag`: diagnostics and their stable `OSHnnnn` codes. `gen`, `cmd/oneshader`: binding generation and the command. ## Generated Go bindings The `oneshader` command, run from `//go:generate`, compiles `*.hlsl` files at build time. It fails with `file:line:col` diagnostics, and writes Go structs laid out to the shaders' byte layout (with compile-time size and offset checks), per-resource binding values, and the compiled blobs embedded with `//go:embed`. Output is deterministic. ```go //go:generate go run recursiveai.org/go/oneshader/cmd/oneshader gen -targets spirv,msl,wgsl sprite.hlsl ``` `oneshader gen -h` lists the flags: `-pkg`, `-targets`, `-entries`, `-D`, `-I`, `-16bit`, `-optimize`, `-layout-checks compile|test|none` (`test` keeps `unsafe` out of the generated package), `-debug`, `-axes` and `-variant` for shader variants, `-o`. A file argument may be a pattern such as `shaders/**/*.hlsl`. `examples/particles` shows the generated package. Layout checks: by default (`-layout-checks compile`) `gen` writes `_shader_layout.go`, a file of constant assertions on `unsafe.Sizeof` and `unsafe.Offsetof` for every generated struct and field. They use no pointers and cost nothing at run time; a Go type whose size or field offsets differ from the shader's buffer layout fails `go build`. That file is why the generated package imports `unsafe`. With `-layout-checks test`, `gen` writes `_shader_test.go` instead, a test that checks the same sizes and offsets through `reflect`, so the package imports no `unsafe` and a mismatch is caught by `go test`; `-layout-checks none` writes no checks. Without `gen`, the command is a DXC-compatible compiler: `oneshader -T cs_6_6 -E CSMain -spirv -Fo out.spv file.hlsl`, with `--target spirv|msl|wgsl|dxil|ir` and `--reflect file.json`. ## Targets | Target | Output | Notes | |---|---|---| | `TargetSPIRV` | SPIR-V for Vulkan 1.2 or 1.3 | the default | | `TargetMSL` | Metal Shading Language 2.4 and later (3.1 for bfloat and some atomics) | | | `TargetWGSL` | WGSL | what WebGPU cannot express (binding arrays, `precise`, clip distances) is a diagnostic or a warning | | `TargetDXIL` | DXIL containers, shader model 6.0 to 6.8 | one container per entry point; the DXC validator (`dxv`) accepts them | Every blob, and the reflection beside it, is byte-identical for the same input and options. ## Limits HLSL source is untrusted. `WithLimits` bounds include depth (default 64) and count (4096), macro expansion (5,000,000 steps, nesting 128), output tokens (2,000,000), parser nesting (256), kept errors (100) and lowered IR size (500,000 instructions); each limit has its own diagnostic and no input can recurse or grow without one. `CompileContext` ends a compile early. No library function panics on input. Scope: vertex, pixel and compute stages; geometry, tessellation, mesh and ray-tracing stages, GLSL and Direct3D 9 syntax are not supported. ## Performance Compile time against DXC 1.9.2609, the reference compiler, run as a native process, on a corpus of 106 entry points (105 compile; see below): 29 from a 2D renderer, 26 from a 3D PBR set, 24 compute kernels, 26 language-feature and type probes. Both tools compile one entry point to SPIR-V for Vulkan 1.2 at their default optimization, one process per entry point, with the blob written to disk. Every output passes `spirv-val --target-env vulkan1.2`. | Group | Entry points | Process: DXC median | Process: ours median | Time vs DXC (geometric mean) | Fastest | Slowest | Slower than DXC | In process: median time | Allocations (median) | |---|--:|--:|--:|---|---|---|--:|--:|--:| | 2D renderer | 29 | 6.14 ms | 1.99 ms | 3.02× faster | 3.50× faster | 2.42× faster | 0 | 0.40 ms | 2,798 | | 3D (PBR set) | 26 | 6.72 ms | 2.22 ms | 2.94× faster | 3.50× faster | 2.51× faster | 0 | 0.53 ms | 4,029 | | compute | 24 | 5.99 ms | 2.09 ms | 2.89× faster | 3.32× faster | 2.72× faster | 0 | 0.39 ms | 3,888 | | language features and types | 26 | 7.00 ms | 2.31 ms | 2.81× faster | 3.50× faster | 2.14× faster | 0 | 0.65 ms | 5,738 | | All | 105 | 6.49 ms | 2.17 ms | 2.92× faster | 3.50× faster | 2.14× faster | 0 | 0.47 ms | 3,774 | "Process" is wall-clock time from starting the process to its exit, the median of 15 rounds per entry point; each round runs DXC and `oneshader` back to back for every row, so drift in machine speed affects both alike. The ratio is DXC's time over ours per entry point, summarised by the geometric mean; a time within 5% of DXC's counts as a tie, and no row is slower. "In process" is `Compile` called from Go (`go test -bench CorpusSPIRV -benchmem`, median of 5 runs of 100 iterations), the cost a build tool pays per shader without a process start: the median is 0.47 ms and 3,774 allocations. DXC's allocations are not measured. Per-row figures are in [`bench/RESULTS.md`](https://github.com/recursive-ai-oss/oneshader-go/blob/d03e376789b814cdbbb7c5c2fbde431e763156db/bench/RESULTS.md). Where we lose or do not compete: - **Output size.** The SPIR-V is 8.5% larger than DXC's in total (78,048 words against 71,946; larger on 97 of 105 rows), because names are kept by default; `WithKeepNames(false)` or `--no-names` drops them. - **One row was left out.** `types/byte_address_wide.hlsl` (a struct through `ByteAddressBuffer.Load`) was refused when this run was taken. It compiles now, on every target but WGSL (no 64-bit integers there); the table does not include it. - Only SPIR-V is timed: MSL, WGSL and DXIL have no counterpart in DXC's SPIR-V path. DXIL against DXC's own `-T` output is not measured. There is no pure-Go shader compiler to compare with. Method and machine. One publishable run on 2026-12-04, Go 1.26.8 on Linux 7, an AMD Ryzen 9 7950X3D (16 cores, 32 threads, frequency scaling on) with the machine to itself: the whole machine was reserved for the run and nothing else was started on it. Load average (1 minute) was 1.46 before the run, between 1.39 and 1.86 over the 10 samples taken every 5 seconds during it, and 1.81 afterwards; the 15-minute average was still falling from 7.4 as the machine had just been drained. The corpus is `bench/corpus` (our shaders, `MIT OR Apache-2.0`); the rows are `bench/entries.tsv`, the stage and entry point of each shader the corpus' execution cases compile. One run: treat the numbers as local measurements. To reproduce: `bench/node.sh` after putting `dxc`, its libraries and `spirv-val` under `.benchtools/` (see `bench/README.md`). ## Licence MIT OR Apache-2.0, © Recursive AI, LLC. # Changelog All notable changes to `recursiveai.org/go/oneshader`. Versions follow [Semantic Versioning](https://semver.org/). ## [1.0.0] - 2026-12-04 First release. - Compiler: modern HLSL (structs, functions and overloads, `cbuffer` and `ConstantBuffer`, textures and samplers, structured and byte-address buffers, `groupshared` and barriers, wave and quad intrinsics, cooperative matrices, templates as HLSL 2021 allows, inheritance, bindless resources, 16-, 64-bit and `half` types, the preprocessor) for vertex, pixel and compute stages. - Targets: SPIR-V (Vulkan 1.2 and 1.3), Metal Shading Language, WGSL and DXIL (shader model 6.0 to 6.8), from one IR with a verifier and an optimizer (`ir`, `ir/opt`). - Reflection for every compile: entry points, stage variables, resource slots per target, buffer layouts with byte offsets, push constants, specialization constants, required device features. JSON form with a reader, and `Compatible` to check a reflection against a pipeline layout. - One byte layout per buffer on every target (DXC's Vulkan defaults); push constants; Vulkan, MSL, WGSL and DXIL binding models; `pipeline` turns reflection into descriptor set layouts, Metal argument indices, bind group layouts and vertex input. - The `oneshader` command: DXC-compatible `compile`, and `gen` for `//go:generate`, which writes Go structs laid out to the shared byte layout with compile-time size and offset checks, binding constants, shader variants and `//go:embed`-ed blobs. - Diagnostics as `file(line,col): error OSHnnnn: message` that say what to do; every limit on untrusted input (include depth and count, macro expansion, nesting, IR size) is configurable and has a diagnostic. - Deterministic output: the same input and options give byte-identical blobs, reflection and generated code. - `ByteAddressBuffer.Load` and `Store` take structs, arrays and matrices as well as scalars and vectors, on every target: members at the offsets a structured-buffer element has, matrices as DXC moves them (columns one after another, no padding), at most 4096 scalars per call. - Bit-fields (`uint a : 3;` on `int`, `uint`, `int16_t`, `uint16_t`, `int64_t`, `uint64_t`): consecutive bit-fields of one type share a storage unit from the lowest bit up, a different type or a field that does not fit starts a new unit, as DXC lays them out. The unit is an ordinary member in reflection (named after its first bit-field). Reads sign-extend signed fields, writes drop the bits above the width; compound assignment, `++`, initializer lists and `(S)x` work. `layout.Struct.Slots` and `layout.Member.Bits` describe the units. - `tbuffer` is a read-only storage buffer laid out like a structured-buffer element (reflection kind `ReadOnlyStorageBuffer`), as in DXC's SPIR-V. - Reflection: `ReflectedType.ElementBytes` is the width of a matrix element when it is not 4 bytes (2 for 16-bit types, 8 for 64-bit types); written as `ebytes` in the text form and `elementBytes` in JSON. - Pure Go, no cgo, no dependencies; `go 1.24`.