diff --git a/bench/go.mod b/bench/go.mod index acfab14..4c7d7f4 100644 --- a/bench/go.mod +++ b/bench/go.mod @@ -32,7 +32,7 @@ require ( github.com/go-images/jpeg2000 v0.14.0 // indirect github.com/go-images/png v0.2.0 // indirect github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 // indirect - github.com/go-macos/metal v0.7.0 // indirect + github.com/go-macos/metal v0.8.0 // indirect github.com/go-macos/objc v0.12.0 // indirect github.com/go-opentype/fonts v0.14.0 // indirect github.com/go-opentype/opentype v0.21.1 // indirect diff --git a/bench/go.sum b/bench/go.sum index 27b9db2..930ef48 100644 --- a/bench/go.sum +++ b/bench/go.sum @@ -41,8 +41,8 @@ github.com/go-images/png v0.2.0 h1:RFPkHPuRYRvrDJol/Mmn9P1DSaLV8VPmEQ8BkZoCpL0= github.com/go-images/png v0.2.0/go.mod h1:g1qayDmWLClHo9R5KQ+RrcUNTBcaA4c1thaIfEoS3vg= github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 h1:UADEEmDKgfXbtnGJZ97beY5XLo9ZechG1nlU4KnRrkE= github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg= -github.com/go-macos/metal v0.7.0 h1:c/ymPqCzoLcDxcZ3i6cNSgOScsOlIz4yVbik5asVp+w= -github.com/go-macos/metal v0.7.0/go.mod h1:BiclSGJgONDekug12CQtlINic9zMmXF7m/iA7bQn4hM= +github.com/go-macos/metal v0.8.0 h1:BWv+rlHEwvbBwFtHuZzLvnjoqb14hvIftmHMhWP4MOA= +github.com/go-macos/metal v0.8.0/go.mod h1:BiclSGJgONDekug12CQtlINic9zMmXF7m/iA7bQn4hM= github.com/go-macos/objc v0.12.0 h1:/WmB4C1CQd5RkqBRvnHNljEFtOTvytPA9fkD87xuJVQ= github.com/go-macos/objc v0.12.0/go.mod h1:ao+SmTFBrkZdP+488hFTrSFvCtJ36McKKhNNOlcFXrQ= github.com/go-opentype/fonts v0.14.0 h1:WHw7k9gkHT1pu9B2yyvd0FWyQqn/4NKFQoKhvMYt3Mo= diff --git a/go.mod b/go.mod index 9f02030..9fd4a13 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/go-gfx/oksvg v0.4.0 github.com/go-gfx/wgsl v0.4.0 github.com/go-images/images v0.1.1-0.20261026203936-4ac989d310a1 - github.com/go-macos/metal v0.7.0 + github.com/go-macos/metal v0.8.0 github.com/go-opentype/fonts v0.14.0 github.com/go-opentype/opentype v0.21.1 github.com/go-pdfkit/pdfkit v0.21.0 diff --git a/go.sum b/go.sum index df967b9..864eaaa 100644 --- a/go.sum +++ b/go.sum @@ -33,8 +33,8 @@ github.com/go-images/jpeg2000 v0.14.0 h1:/nH3l5r95E7OkNZCfq7gmoDQvJzVAhmSw6rd2If github.com/go-images/jpeg2000 v0.14.0/go.mod h1:4/Pp3Jp2es5lA8/Ema8F7dFwl0vZprCj9MyznIz9Gdc= github.com/go-images/png v0.2.0 h1:RFPkHPuRYRvrDJol/Mmn9P1DSaLV8VPmEQ8BkZoCpL0= github.com/go-images/png v0.2.0/go.mod h1:g1qayDmWLClHo9R5KQ+RrcUNTBcaA4c1thaIfEoS3vg= -github.com/go-macos/metal v0.7.0 h1:c/ymPqCzoLcDxcZ3i6cNSgOScsOlIz4yVbik5asVp+w= -github.com/go-macos/metal v0.7.0/go.mod h1:BiclSGJgONDekug12CQtlINic9zMmXF7m/iA7bQn4hM= +github.com/go-macos/metal v0.8.0 h1:BWv+rlHEwvbBwFtHuZzLvnjoqb14hvIftmHMhWP4MOA= +github.com/go-macos/metal v0.8.0/go.mod h1:BiclSGJgONDekug12CQtlINic9zMmXF7m/iA7bQn4hM= github.com/go-macos/objc v0.12.0 h1:/WmB4C1CQd5RkqBRvnHNljEFtOTvytPA9fkD87xuJVQ= github.com/go-macos/objc v0.12.0/go.mod h1:ao+SmTFBrkZdP+488hFTrSFvCtJ36McKKhNNOlcFXrQ= github.com/go-opentype/fonts v0.14.0 h1:WHw7k9gkHT1pu9B2yyvd0FWyQqn/4NKFQoKhvMYt3Mo= diff --git a/js/js.go b/js/js.go index 292e902..1c5880e 100644 --- a/js/js.go +++ b/js/js.go @@ -432,6 +432,15 @@ type binder struct { // its own ordered bindGroupLayouts — see gpuCreatePipelineLayout's own // doc comment (webgpu.go). gpuPipelineLayouts map[*goja.Object][]*goja.Object + // gpuTextures/gpuTextureViews/gpuRenderPipelines are the same + // by-object-identity registry shape as gpuBuffers, for engine#415's + // render-pipeline surface (webgpu.go): a GPUTextureView shares its + // GPUTexture's own gpuTextureState (a view never has independent + // state of its own in this binding's restricted, single-mip/ + // single-layer scope — see gpuTextureCreateView's own doc comment). + gpuTextures map[*goja.Object]*gpuTextureState + gpuTextureViews map[*goja.Object]*gpuTextureState + gpuRenderPipelines map[*goja.Object]*gpuRenderPipelineState // gpuErrorScopes is one GPUDevice's own error-scope stack and // "uncapturederror" listener, keyed by the *metal.Device it wraps — // see gpuErrorScopeState/gpuGuard's own doc comments (webgpu.go) for diff --git a/js/webgpu.go b/js/webgpu.go index ed089f3..f87b450 100644 --- a/js/webgpu.go +++ b/js/webgpu.go @@ -307,6 +307,32 @@ func (b *binder) newGPUShaderStage() *goja.Object { return o } +// gpuTextureUsage* are WebGPU's own GPUTextureUsage flag values (WebGPU +// §3.3: `namespace GPUTextureUsage { const GPUFlagsConstant COPY_SRC = +// 0x01; … }`), named here (rather than inlined) so gpuCreateTexture's own +// usage -> metal.TextureUsage mapping and newGPUTextureUsage's own object +// literal cannot drift apart. +const ( + gpuTextureUsageCopySrc = 0x01 + gpuTextureUsageCopyDst = 0x02 + gpuTextureUsageTextureBinding = 0x04 + gpuTextureUsageStorageBinding = 0x08 + gpuTextureUsageRenderAttachment = 0x10 +) + +// newGPUTextureUsage builds the GPUTextureUsage namespace — engine#415's +// own counterpart to newGPUBufferUsage, installed the same way (a global +// alongside navigator.gpu, gated on Options.EnableWebGPU). +func (b *binder) newGPUTextureUsage() *goja.Object { + o := b.vm.NewObject() + o.Set("COPY_SRC", gpuTextureUsageCopySrc) + o.Set("COPY_DST", gpuTextureUsageCopyDst) + o.Set("TEXTURE_BINDING", gpuTextureUsageTextureBinding) + o.Set("STORAGE_BINDING", gpuTextureUsageStorageBinding) + o.Set("RENDER_ATTACHMENT", gpuTextureUsageRenderAttachment) + return o +} + // newGPU builds navigator.gpu (HTML/WebGPU: `[Exposed=(Window, Worker)] // interface GPU`). Installed only when Options.EnableWebGPU is set — see // its own doc comment for the opt-in rationale. @@ -519,6 +545,16 @@ func (b *binder) newGPUDevice(dev *metal.Device) *goja.Object { o.Set("createCommandEncoder", func(call goja.FunctionCall) goja.Value { return b.wrapGPUCommandEncoder(&gpuCommandEncoderState{dev: dev}) }) + o.Set("createTexture", func(call goja.FunctionCall) goja.Value { + return b.gpuGuard(dev, goja.Undefined(), func() goja.Value { + return b.gpuCreateTexture(dev, call) + }) + }) + o.Set("createRenderPipeline", func(call goja.FunctionCall) goja.Value { + return b.gpuGuard(dev, goja.Undefined(), func() goja.Value { + return b.gpuCreateRenderPipeline(dev, call) + }) + }) queue := b.vm.NewObject() queue.Set("writeBuffer", func(call goja.FunctionCall) goja.Value { @@ -526,6 +562,11 @@ func (b *binder) newGPUDevice(dev *metal.Device) *goja.Object { return b.gpuQueueWriteBuffer(call) }) }) + queue.Set("writeTexture", func(call goja.FunctionCall) goja.Value { + return b.gpuGuard(dev, goja.Undefined(), func() goja.Value { + return b.gpuQueueWriteTexture(call) + }) + }) queue.Set("submit", func(call goja.FunctionCall) goja.Value { return b.gpuGuard(dev, goja.Undefined(), func() goja.Value { return b.gpuQueueSubmit(dev, call) @@ -574,8 +615,16 @@ func (b *binder) gpuCreateBuffer(dev *metal.Device, call goja.FunctionCall) goja if desc == nil { panic(b.vm.NewTypeError("createBuffer: a GPUBufferDescriptor is required")) } - size := int(desc.Get("size").ToInteger()) - usage := int(desc.Get("usage").ToInteger()) + sizeVal := desc.Get("size") + if sizeVal == nil || goja.IsUndefined(sizeVal) { + panic(b.vm.NewTypeError("createBuffer: size is required")) + } + usageVal := desc.Get("usage") + if usageVal == nil || goja.IsUndefined(usageVal) { + panic(b.vm.NewTypeError("createBuffer: usage is required")) + } + size := int(sizeVal.ToInteger()) + usage := int(usageVal.ToInteger()) mappedAtCreation := optBool(desc, "mappedAtCreation") if size <= 0 { panic(b.vm.NewTypeError("createBuffer: size must be positive")) @@ -940,6 +989,27 @@ func (b *binder) gpuBuildComputePipeline(dev *metal.Device, call goja.FunctionCa } else { result = modState.result } + // engine#447 review bug #5: wgslmsl itself legitimately accepts a + // texture_2d handle resource in a @compute entry point (a direct + // go-macos/metal caller can bind a real Metal texture at its + // resolved index — see wgslmsl's own TestTranslateTextureLoadEndToEnd), + // but THIS binding's own dispatch path cannot: gpuDispatchWorkgroups + // treats every resolved Binding as a Metal buffer, and + // gpuCreateBindGroup only ever accepts a GPUBufferBinding resource + // (its own "samplers/textures are not supported" rejection below). + // Left unrejected, a texture resource's Metal index — allocated from + // the SEPARATE tr.textureCount counter inside wgslmsl, independent of + // tr.bufferCount — collides with a real buffer resource assigned the + // same index, and gpuDispatchWorkgroups' buffers map silently + // delivers one resource's bytes under the other's binding instead of + // failing. Named rejection here, exactly like + // gpuCreateRenderPipeline's own "a shader resource is not supported" + // check just below it. + for _, bnd := range result.Bindings { + if bnd.Kind == wgslmsl.BindingTexture { + return nil, b.vm.NewTypeError("createComputePipeline: a texture resource (@group/@binding) is not supported in a compute pipeline") + } + } lib, err := dev.Compile(result.MSL) if err != nil { b.panicValidation("createComputePipeline: Metal rejected the generated shader: " + err.Error()) @@ -1195,9 +1265,10 @@ func (b *binder) gpuCreateBindGroup(call goja.FunctionCall) goja.Value { // GPUCommandEncoder/GPUCommandBuffer — this binding uses the SAME Go value // for both (finish() just stops further recording and hands back a new JS // object identity over the identical state), since nothing here needs them -// to be distinct beyond that. Deliberately scoped to AT MOST ONE compute -// pass per encoder — the realistic shape every test and real usage needs so -// far; a second beginComputePass() is a clear, named rejection, not a +// to be distinct beyond that. Deliberately scoped to AT MOST ONE pass per +// encoder, compute OR render (engine#415 M7 added the render half) — the +// realistic shape every test and real usage needs so far; a second +// beginComputePass()/beginRenderPass() is a clear, named rejection, not a // silent no-op. type gpuCommandEncoderState struct { dev *metal.Device @@ -1213,11 +1284,14 @@ type gpuCommandEncoderState struct { // directly needed by go-wasmcontainers for their own readback-via- // mapAsync batch path) interleave freely per spec, so both go through // this ONE ordered list rather than two separate ones gpuQueueSubmit -// would otherwise have to merge by guesswork. Exactly one of -// dispatch/copy is non-nil. +// would otherwise have to merge by guesswork. engine#415 M7 added render +// and textureCopy alongside the original dispatch/copy — exactly one of +// the four is non-nil. type gpuRecordedCommand struct { - dispatch *gpuRecordedDispatch - copy *gpuRecordedCopy + dispatch *gpuRecordedDispatch + copy *gpuRecordedCopy + render *gpuRecordedRenderPass + textureCopy *gpuRecordedTextureCopy } // gpuRecordedDispatch is one dispatchWorkgroups() call, fully resolved at @@ -1268,10 +1342,29 @@ func (b *binder) wrapGPUCommandEncoder(st *gpuCommandEncoderState) *goja.Object o.Set("copyBufferToBuffer", func(call goja.FunctionCall) goja.Value { return b.gpuCopyBufferToBuffer(st, call) }) + o.Set("beginRenderPass", func(call goja.FunctionCall) goja.Value { + return b.gpuGuard(st.dev, goja.Undefined(), func() goja.Value { + return b.gpuBeginRenderPass(st, call) + }) + }) + o.Set("copyTextureToBuffer", func(call goja.FunctionCall) goja.Value { + return b.gpuGuard(st.dev, goja.Undefined(), func() goja.Value { + return b.gpuCopyTextureToBuffer(st, call) + }) + }) o.Set("finish", func(call goja.FunctionCall) goja.Value { if st.finished { panic(b.vm.NewTypeError("finish: this command encoder has already finished")) } + // engine#447 review bug #7: a pass begun but never end()ed must + // not be silently dropped — every dispatch/draw recorded against + // it is either already in st.commands (dispatchWorkgroups) or + // still sitting unflushed in the render pass's own state.draws, + // about to be lost the moment finish() hands back a command + // buffer with no reference to it at all. + if st.passOpen { + panic(b.vm.NewTypeError("finish: a pass (compute or render) is still open")) + } st.finished = true cbObj := b.vm.NewObject() if b.gpuCommandBuffers == nil { @@ -1315,10 +1408,27 @@ func (b *binder) wrapGPUComputePassEncoder(enc *gpuCommandEncoderState) *goja.Ob }) o.Set("dispatchWorkgroups", func(call goja.FunctionCall) goja.Value { return b.gpuGuard(enc.dev, goja.Undefined(), func() goja.Value { + // engine#447 review bug #7: dispatchWorkgroups records + // directly into enc.commands (gpuDispatchWorkgroups's own + // append), so unlike a render pass's draws a call after + // end() would not just be ignored — it would still run, + // against an encoder whose pass has already been handed to + // gpuQueueSubmit's own command list. + if !enc.passOpen { + panic(b.vm.NewTypeError("dispatchWorkgroups: this pass has already ended")) + } return b.gpuDispatchWorkgroups(enc, curPipeline, curBindGroups, call) }) }) o.Set("end", func(call goja.FunctionCall) goja.Value { + // engine#447 review bug #7: without this, end() called twice on + // the same pass is silently accepted both times (passOpen/ + // passEnded already both idempotent-looking booleans), matching + // exactly the named "end() twice re-runs the pass" defect for + // the render-pass encoder just below. + if !enc.passOpen { + panic(b.vm.NewTypeError("end: this pass has already ended")) + } enc.passOpen = false enc.passEnded = true return goja.Undefined() @@ -1491,8 +1601,38 @@ func (b *binder) gpuQueueSubmit(dev *metal.Device, call goja.FunctionCall) goja. if err := runPending(); err != nil { b.panicValidation(err.Error()) } - copy(c.copy.dst.Bytes()[c.copy.dstOffset:c.copy.dstOffset+c.copy.size], - c.copy.src.Bytes()[c.copy.srcOffset:c.copy.srcOffset+c.copy.size]) + switch { + case c.copy != nil: + copy(c.copy.dst.Bytes()[c.copy.dstOffset:c.copy.dstOffset+c.copy.size], + c.copy.src.Bytes()[c.copy.srcOffset:c.copy.srcOffset+c.copy.size]) + case c.render != nil: + err := dev.RunRender(metal.RenderPassDescriptor{ + Target: c.render.target, + Load: c.render.load, + Store: c.render.store, + Clear: c.render.clear, + }, func(e *metal.RenderEncoder) { + for _, d := range c.render.draws { + e.Use(d.pipeline) + for idx, vb := range d.vertexBuffers { + e.VertexBuffer(idx, vb.buf, vb.offset) + } + if d.indexed { + e.DrawIndexed(d.indexCount, d.instanceCount, d.indexBuffer, d.indexBufferOffset, d.baseVertex, d.firstInstance) + } else { + e.Draw(d.vertexCount, d.instanceCount, d.firstVertex, d.firstInstance) + } + } + }) + if err != nil { + b.panicValidation(err.Error()) + } + case c.textureCopy != nil: + tc := c.textureCopy + if err := tc.tex.GetBytes(tc.dst.Bytes()[tc.dstOffset : tc.dstOffset+tc.size]); err != nil { + b.panicValidation(err.Error()) + } + } } if err := runPending(); err != nil { b.panicValidation(err.Error()) @@ -1506,3 +1646,1079 @@ func (b *binder) gpuQueueSubmit(dev *metal.Device, call goja.FunctionCall) goja. func unsupportedJS(b *binder, msg string) goja.Value { return b.vm.NewTypeError("webgpu: unsupported: " + msg) } + +// ---- engine#415 M7: textures and render pipelines ---- + +// gpuTextureState is the Go-level state behind one GPUTexture: the real +// Metal-backed 2D texture and the descriptor fields a GPUTexture's own +// property getters report back. Deliberately bounded scope (see +// gpuCreateTexture's own doc comment for exactly where each restriction +// comes from): a single 2D texture, one mip level, one array layer, +// go-macos/metal's own PixelFormatR8Uint. +type gpuTextureState struct { + tex *metal.Texture + width int + height int + format string + usage int +} + +// gpuExtent is a resolved GPUExtent3D (`{width, height, +// depthOrArrayLayers}` or the equivalent `[width, height, +// depthOrArrayLayers]` sequence form — WebGPU lets either through its own +// dictionary/union coercion) — shared by createTexture's own `size`, +// writeTexture's own `size`, and copyTextureToBuffer's own `copySize`, so +// the two argument shapes are resolved in exactly one place. +type gpuExtent struct{ w, h, d int } + +// gpuGetInt reads an integer property that may be legitimately absent — +// an optional dictionary member (GPUExtent3DDict.height/depthOrArrayLayers +// both default to 1 per spec) or a short GPUExtent3D/GPUOrigin3D sequence +// form. goja's own Object.Get returns a genuine Go nil for a missing +// property (as opposed to goja.Undefined(), a non-nil Value, for one +// explicitly set to undefined) — calling ToInteger() on that nil +// interface panics, so every spec-optional numeric read goes through +// this instead of a raw obj.Get(key).ToInteger(). +func gpuGetInt(obj *goja.Object, key string, def int) int { + v := obj.Get(key) + if v == nil || goja.IsUndefined(v) { + return def + } + return int(v.ToInteger()) +} + +// gpuGetFloat is gpuGetInt's float counterpart, for GPUColor's own r/g/b/a. +func gpuGetFloat(obj *goja.Object, key string, def float64) float64 { + v := obj.Get(key) + if v == nil || goja.IsUndefined(v) { + return def + } + return v.ToFloat() +} + +func gpuReadExtent(v goja.Value) gpuExtent { + obj, ok := v.(*goja.Object) + if !ok { + return gpuExtent{} + } + if w := obj.Get("width"); w != nil && !goja.IsUndefined(w) { + return gpuExtent{ + w: int(w.ToInteger()), + h: gpuGetInt(obj, "height", 1), + d: gpuGetInt(obj, "depthOrArrayLayers", 1), + } + } + return gpuExtent{ + w: gpuGetInt(obj, "0", 0), + h: gpuGetInt(obj, "1", 1), + d: gpuGetInt(obj, "2", 1), + } +} + +// gpuIsZeroOrigin reports whether v (a GPUOrigin3D: `{x, y, z}` or +// `[x, y, z]`, every field defaulting to 0) is the all-zero origin — the +// only one writeTexture/copyTextureToBuffer accept. +func gpuIsZeroOrigin(v goja.Value) bool { + obj, ok := v.(*goja.Object) + if !ok { + return true + } + get := func(k string) int64 { + x := obj.Get(k) + if x == nil || goja.IsUndefined(x) { + return 0 + } + return x.ToInteger() + } + return get("x") == 0 && get("y") == 0 && get("z") == 0 && + get("0") == 0 && get("1") == 0 && get("2") == 0 +} + +// gpuVertexFormat maps a GPUVertexFormat string (WebGPU §9.1) to the +// go-macos/metal MTLVertexFormat it corresponds to, plus the component +// count/scalar kind wgslmsl.RenderResult.VertexInputs reports for the +// shader side of the same attribute — the only 4 formats go-macos/metal +// itself recognizes (metal.VertexFormat's own doc comment), so every other +// GPUVertexFormat string is a named rejection here, never a silently wrong +// MTLVertexFormat guess. +func gpuVertexFormat(format string) (mf metal.VertexFormat, nComponents int, kind wgsl.ScalarKind, ok bool) { + switch format { + case "float32x2": + return metal.VertexFormatFloat32x2, 2, wgsl.KF32, true + case "float32x3": + return metal.VertexFormatFloat32x3, 3, wgsl.KF32, true + case "uint32": + return metal.VertexFormatUint32, 1, wgsl.KU32, true + case "uint32x4": + return metal.VertexFormatUint32x4, 4, wgsl.KU32, true + default: + return 0, 0, 0, false + } +} + +// gpuReadColor resolves a GPUColor (`{r, g, b, a}` or `[r, g, b, a]`) — +// clearValue's own two accepted shapes (WebGPU §19.1's own GPUColor +// union), for beginRenderPass's own colorAttachments[0].clearValue. +func gpuReadColor(v goja.Value) [4]float64 { + obj, ok := v.(*goja.Object) + if !ok { + return [4]float64{} + } + if r := obj.Get("r"); r != nil && !goja.IsUndefined(r) { + return [4]float64{r.ToFloat(), gpuGetFloat(obj, "g", 0), gpuGetFloat(obj, "b", 0), gpuGetFloat(obj, "a", 0)} + } + return [4]float64{gpuGetFloat(obj, "0", 0), gpuGetFloat(obj, "1", 0), gpuGetFloat(obj, "2", 0), gpuGetFloat(obj, "3", 0)} +} + +// gpuCreateTexture implements GPUDevice.createTexture(descriptor) — +// engine#415 M7's own deliberately bounded scope: a single 2D texture (no +// mip chain, no array layers, no 3D/cube), go-macos/metal's own only +// supported GPUTextureFormat ("r8uint" -> metal.PixelFormatR8Uint — see +// metal.PixelFormat's own doc comment for why that is the one format this +// package's whole render path needs so far). A format/dimension/ +// mipLevelCount/sampleCount this binding does not support is a named +// rejection (unsupportedJS), never a silently wrong texture; size.width/ +// height being non-positive is a WebIDL-level argument problem (TypeError, +// matching createBuffer's own size<=0 check); an actual allocation failure +// against go-macos/metal is GPU content validation (panicOutOfMemory, +// matching createBuffer's own). +func (b *binder) gpuCreateTexture(dev *metal.Device, call goja.FunctionCall) goja.Value { + desc, _ := call.Argument(0).(*goja.Object) + if desc == nil { + panic(b.vm.NewTypeError("createTexture: a GPUTextureDescriptor is required")) + } + fmtVal := desc.Get("format") + if fmtVal == nil || goja.IsUndefined(fmtVal) { + panic(b.vm.NewTypeError("createTexture: format is required")) + } + format := fmtVal.String() + if format != "r8uint" { + panic(unsupportedJS(b, "createTexture: unsupported texture format "+format)) + } + if dim := desc.Get("dimension"); dim != nil && !goja.IsUndefined(dim) && dim.String() != "2d" { + panic(unsupportedJS(b, "createTexture: only dimension \"2d\" is supported")) + } + if m := desc.Get("mipLevelCount"); m != nil && !goja.IsUndefined(m) && m.ToInteger() != 1 { + panic(unsupportedJS(b, "createTexture: only mipLevelCount 1 is supported")) + } + if s := desc.Get("sampleCount"); s != nil && !goja.IsUndefined(s) && s.ToInteger() != 1 { + panic(unsupportedJS(b, "createTexture: only sampleCount 1 is supported")) + } + size := gpuReadExtent(desc.Get("size")) + if size.w <= 0 || size.h <= 0 { + panic(b.vm.NewTypeError("createTexture: size.width and size.height must be positive")) + } + if size.d != 1 { + panic(unsupportedJS(b, "createTexture: only a single 2D texture (depthOrArrayLayers 1) is supported")) + } + usageVal := desc.Get("usage") + if usageVal == nil || goja.IsUndefined(usageVal) { + panic(b.vm.NewTypeError("createTexture: usage is required")) + } + usage := int(usageVal.ToInteger()) + var musage metal.TextureUsage + if usage&gpuTextureUsageTextureBinding != 0 { + musage |= metal.TextureUsageShaderRead + } + if usage&gpuTextureUsageStorageBinding != 0 { + musage |= metal.TextureUsageShaderWrite + } + if usage&gpuTextureUsageRenderAttachment != 0 { + musage |= metal.TextureUsageRenderTarget + } + tex, err := dev.NewTexture(size.w, size.h, metal.PixelFormatR8Uint, musage) + if err != nil { + b.panicOutOfMemory(err.Error()) + } + return b.wrapGPUTexture(&gpuTextureState{tex: tex, width: size.w, height: size.h, format: format, usage: usage}) +} + +// wrapGPUTexture builds the JS GPUTexture surface over st, registering it +// in b.gpuTextures (the same by-object-identity registry shape gpuBuffers +// uses) so createView/writeTexture/copyTextureToBuffer/beginRenderPass can +// all recover the real *metal.Texture from the JS object identity alone. +func (b *binder) wrapGPUTexture(st *gpuTextureState) *goja.Object { + o := b.vm.NewObject() + if b.gpuTextures == nil { + b.gpuTextures = map[*goja.Object]*gpuTextureState{} + } + b.gpuTextures[o] = st + o.Set("width", st.width) + o.Set("height", st.height) + o.Set("depthOrArrayLayers", 1) + o.Set("format", st.format) + o.Set("usage", st.usage) + o.Set("dimension", "2d") + o.Set("mipLevelCount", 1) + o.Set("sampleCount", 1) + o.Set("createView", func(call goja.FunctionCall) goja.Value { + return b.gpuTextureCreateView(st, call) + }) + o.Set("destroy", func(call goja.FunctionCall) goja.Value { + st.tex.Close() + return goja.Undefined() + }) + return o +} + +// gpuTextureCreateView implements GPUTexture.createView(descriptor) — +// engine#415 M7's own bounded scope has no mip chain, no array layers and +// no format reinterpretation, so a GPUTextureView is never independent +// Go-level state of its own: it shares st (registered again, under the +// view's own distinct JS object identity, in b.gpuTextureViews) exactly as +// a real one-mip/one-layer texture's only possible view would. Every +// descriptor field that would need this binding to behave differently from +// "the whole texture, as-is" is a named rejection (unsupportedJS). +func (b *binder) gpuTextureCreateView(st *gpuTextureState, call goja.FunctionCall) goja.Value { + if desc, ok := call.Argument(0).(*goja.Object); ok { + if f := desc.Get("format"); f != nil && !goja.IsUndefined(f) && f.String() != st.format { + panic(unsupportedJS(b, "createView: a view format different from the texture's own format is not supported")) + } + if d := desc.Get("dimension"); d != nil && !goja.IsUndefined(d) && d.String() != "2d" { + panic(unsupportedJS(b, "createView: only a \"2d\" view is supported")) + } + if a := desc.Get("aspect"); a != nil && !goja.IsUndefined(a) && a.String() != "all" { + panic(unsupportedJS(b, "createView: only the \"all\" aspect is supported")) + } + if m := desc.Get("baseMipLevel"); m != nil && !goja.IsUndefined(m) && m.ToInteger() != 0 { + panic(unsupportedJS(b, "createView: only baseMipLevel 0 is supported")) + } + if m := desc.Get("mipLevelCount"); m != nil && !goja.IsUndefined(m) && m.ToInteger() != 1 { + panic(unsupportedJS(b, "createView: only a single mip level is supported")) + } + if a := desc.Get("baseArrayLayer"); a != nil && !goja.IsUndefined(a) && a.ToInteger() != 0 { + panic(unsupportedJS(b, "createView: only baseArrayLayer 0 is supported")) + } + if a := desc.Get("arrayLayerCount"); a != nil && !goja.IsUndefined(a) && a.ToInteger() != 1 { + panic(unsupportedJS(b, "createView: only a single array layer is supported")) + } + } + o := b.vm.NewObject() + if b.gpuTextureViews == nil { + b.gpuTextureViews = map[*goja.Object]*gpuTextureState{} + } + b.gpuTextureViews[o] = st + return o +} + +// gpuQueueWriteTexture implements GPUQueue.writeTexture(destination, data, +// dataLayout, size) — restricted to one full-extent, tightly packed write +// at mip 0 with a zero origin, the only shape engine#415 M7 needs so far +// (go-macos/metal's own Texture.Replace has the same restriction — see its +// own doc comment). Anything else is a named rejection (unsupportedJS); a +// data size that does not match offset/copy size is GPU content validation +// (panicValidation), matching writeBuffer's own convention for the same +// kind of bounds mismatch. +func (b *binder) gpuQueueWriteTexture(call goja.FunctionCall) goja.Value { + destObj, _ := call.Argument(0).(*goja.Object) + if destObj == nil { + panic(b.vm.NewTypeError("writeTexture: destination must be a GPUImageCopyTexture")) + } + texObj, _ := destObj.Get("texture").(*goja.Object) + var st *gpuTextureState + if texObj != nil { + st = b.gpuTextures[texObj] + } + if st == nil { + panic(b.vm.NewTypeError("writeTexture: destination.texture must be a GPUTexture")) + } + if mip := destObj.Get("mipLevel"); mip != nil && !goja.IsUndefined(mip) && mip.ToInteger() != 0 { + panic(unsupportedJS(b, "writeTexture: only mipLevel 0 is supported")) + } + if origin := destObj.Get("origin"); origin != nil && !goja.IsUndefined(origin) && !gpuIsZeroOrigin(origin) { + panic(unsupportedJS(b, "writeTexture: only a zero origin (a full-extent write) is supported")) + } + data, ok := bufferSourceBytes(call.Argument(1)) + if !ok { + panic(b.vm.NewTypeError("writeTexture: data must be an ArrayBuffer or typed array view")) + } + layoutObj, _ := call.Argument(2).(*goja.Object) + if layoutObj == nil { + panic(b.vm.NewTypeError("writeTexture: dataLayout is required")) + } + offset := 0 + if o := layoutObj.Get("offset"); o != nil && !goja.IsUndefined(o) { + offset = int(o.ToInteger()) + } + bytesPerRow := st.width + if bpr := layoutObj.Get("bytesPerRow"); bpr != nil && !goja.IsUndefined(bpr) { + bytesPerRow = int(bpr.ToInteger()) + } + if bytesPerRow != st.width { + panic(unsupportedJS(b, "writeTexture: only a tightly packed write (bytesPerRow == texture width) is supported")) + } + size := gpuReadExtent(call.Argument(3)) + if size.w != st.width || size.h != st.height { + panic(unsupportedJS(b, "writeTexture: only a full-extent write is supported")) + } + want := st.width * st.height + if offset < 0 || offset+want > len(data) { + b.panicValidation("writeTexture: data is too small for the given offset and copy size") + } + if err := st.tex.Replace(data[offset : offset+want]); err != nil { + b.panicValidation(err.Error()) + } + return goja.Undefined() +} + +// gpuBoundVertexBuffer is one vertex- or index-buffer binding recorded by +// setVertexBuffer/setIndexBuffer: the real *metal.Buffer and the byte +// offset into it, copied by VALUE at bind time — so a later +// setVertexBuffer rebinding the same slot never retroactively changes a +// draw already recorded against the earlier binding (gpuDraw/ +// gpuDrawIndexed each copy the current map before appending their own +// gpuRecordedDraw). +type gpuBoundVertexBuffer struct { + buf *metal.Buffer + offset int + // size is bst.size at bind time (engine#447 review bug #6): copied + // alongside buf/offset so gpuValidateVertexBuffers/ + // gpuValidateIndexedVertexBuffers can bounds-check a draw against the + // buffer's own real size without re-resolving b.gpuBuffers[bufObj] — + // which setVertexBuffer/setIndexBuffer's own callers no longer have + // once a draw is recorded, by the same by-value-copy reasoning this + // struct's own doc comment above already gives for buf/offset. + size int +} + +// gpuRenderPipelineState is the Go-level state behind one +// GPURenderPipeline: just the compiled go-macos/metal pipeline — unlike +// gpuComputePipelineState, nothing here needs the wgslmsl.RenderResult +// again after creation, since this binding's bounded render scope has no +// bind groups (VertexBindings/FragmentBindings are required empty — see +// gpuCreateRenderPipeline's own doc comment) and so no getBindGroupLayout +// equivalent. +type gpuRenderPipelineState struct { + pipe *metal.RenderPipeline + // vertexSlots is every vertex.buffers[] entry's own buffer index and + // byte stride (engine#447 review bug #6): draw/drawIndexed need this + // at draw time to reject a draw with no buffer bound for a slot the + // pipeline declares, or one too small for the vertices/indices about + // to be read — go-macos/metal's own RenderEncoder does not validate + // either itself, so an unvalidated draw reads past a real buffer's + // end (undefined content, not a crash this binding can rely on + // Metal to catch). + vertexSlots []gpuVertexSlot +} + +// gpuVertexSlot is one vertex.buffers[] entry's own buffer index/stride, +// recorded at createRenderPipeline time (gpuRenderPipelineState's own doc +// comment). +type gpuVertexSlot struct { + index int + stride int +} + +// gpuCreateRenderPipeline implements +// GPUDevice.createRenderPipeline(descriptor) — engine#415 M7's own +// deliberately bounded render-pipeline scope: +// - layout must be "auto" (no explicit GPUPipelineLayout for a render +// pipeline yet). +// - Neither the vertex nor the fragment entry point may read a WGSL +// resource (@group/@binding): go-macos/metal's own RenderEncoder has +// no fragment-stage buffer binding and no bind-group mechanism at all +// — a shader needing one is a named rejection (unsupportedJS), not a +// silently dropped binding. +// - Every vertex.buffers[].attributes[] entry's own GPUVertexFormat must +// be one of the 4 go-macos/metal itself recognizes (gpuVertexFormat) +// AND must match the shader's own @location input by both component +// count and scalar kind — a genuine content mismatch between the +// pipeline's own vertex state and its shader, so panicValidation +// (captured by an open error scope), not a thrown TypeError. +// - fragment.targets[0].format must be "r8uint" (go-macos/metal's own +// only supported color format) and there may be no depthStencil +// state (go-macos/metal's own RenderPipelineDescriptor has no +// counterpart — named rejection). +func (b *binder) gpuCreateRenderPipeline(dev *metal.Device, call goja.FunctionCall) goja.Value { + desc, _ := call.Argument(0).(*goja.Object) + if desc == nil { + panic(b.vm.NewTypeError("createRenderPipeline: a GPURenderPipelineDescriptor is required")) + } + layout := desc.Get("layout") + if _, isObj := layout.(*goja.Object); isObj { + panic(unsupportedJS(b, "createRenderPipeline: an explicit GPUPipelineLayout is not supported for a render pipeline")) + } else if layout == nil || layout.String() != "auto" { + panic(b.vm.NewTypeError("createRenderPipeline: layout must be \"auto\"")) + } + if ds := desc.Get("depthStencil"); ds != nil && !goja.IsUndefined(ds) { + panic(unsupportedJS(b, "createRenderPipeline: depthStencil is not supported")) + } + if prim, ok := desc.Get("primitive").(*goja.Object); ok { + if t := prim.Get("topology"); t != nil && !goja.IsUndefined(t) && t.String() != "triangle-list" { + panic(unsupportedJS(b, "createRenderPipeline: only \"triangle-list\" topology is supported")) + } + // engine#447 review bug #8: cullMode/frontFace/unclippedDepth were + // read nowhere in this function — go-macos/metal's own + // RenderPipelineDescriptor has no counterpart field for any of + // them, so a caller asking for back-face culling (say) would have + // gotten a pipeline that silently never culls anything, with no + // error at all. Named rejections instead, exactly like topology + // above, for any value other than the spec's own default. + if cm := prim.Get("cullMode"); cm != nil && !goja.IsUndefined(cm) && cm.String() != "none" { + panic(unsupportedJS(b, "createRenderPipeline: only \"none\" primitive.cullMode is supported")) + } + if ff := prim.Get("frontFace"); ff != nil && !goja.IsUndefined(ff) && ff.String() != "ccw" { + panic(unsupportedJS(b, "createRenderPipeline: only \"ccw\" primitive.frontFace is supported")) + } + if ud := prim.Get("unclippedDepth"); ud != nil && !goja.IsUndefined(ud) && ud.ToBoolean() { + panic(unsupportedJS(b, "createRenderPipeline: primitive.unclippedDepth is not supported")) + } + } + // engine#447 review bug #8: multisample was read nowhere in this + // function either — a caller requesting a 4x MSAA pipeline (say) got a + // single-sample one with no error, which then mismatches a multisample + // render target's own sample count at draw time deep inside + // go-macos/metal instead of being refused up front, at the one place + // that actually knows the request was made. + if ms, ok := desc.Get("multisample").(*goja.Object); ok { + if c := ms.Get("count"); c != nil && !goja.IsUndefined(c) && c.ToInteger() != 1 { + panic(unsupportedJS(b, "createRenderPipeline: only multisample.count of 1 is supported")) + } + if a := ms.Get("alphaToCoverageEnabled"); a != nil && !goja.IsUndefined(a) && a.ToBoolean() { + panic(unsupportedJS(b, "createRenderPipeline: multisample.alphaToCoverageEnabled is not supported")) + } + } + + vertexObj, _ := desc.Get("vertex").(*goja.Object) + if vertexObj == nil { + panic(b.vm.NewTypeError("createRenderPipeline: a vertex stage (GPUVertexState) is required")) + } + vModObj, _ := vertexObj.Get("module").(*goja.Object) + vModState := b.gpuShaderModules[vModObj] + if vModState == nil { + panic(b.vm.NewTypeError("createRenderPipeline: vertex.module must be a GPUShaderModule")) + } + vEntryPoint := "" + if ep := vertexObj.Get("entryPoint"); ep != nil && !goja.IsUndefined(ep) { + vEntryPoint = ep.String() + } + // engine#447 review bug #8: vertex.constants (pipeline-overridable + // constants) was read nowhere in this function — a caller overriding a + // WGSL `override` value would have had that override silently dropped, + // with the shader always compiled using its own declared default + // instead, no error at all. + if c, ok := vertexObj.Get("constants").(*goja.Object); ok && c != nil { + panic(unsupportedJS(b, "createRenderPipeline: vertex.constants is not supported")) + } + + fragmentObj, _ := desc.Get("fragment").(*goja.Object) + if fragmentObj == nil { + panic(b.vm.NewTypeError("createRenderPipeline: a fragment stage (GPUFragmentState) is required")) + } + fModObj, _ := fragmentObj.Get("module").(*goja.Object) + fModState := b.gpuShaderModules[fModObj] + if fModState == nil { + panic(b.vm.NewTypeError("createRenderPipeline: fragment.module must be a GPUShaderModule")) + } + fEntryPoint := "" + if ep := fragmentObj.Get("entryPoint"); ep != nil && !goja.IsUndefined(ep) { + fEntryPoint = ep.String() + } + if c, ok := fragmentObj.Get("constants").(*goja.Object); ok && c != nil { + panic(unsupportedJS(b, "createRenderPipeline: fragment.constants is not supported")) + } + if vModState.src != fModState.src { + panic(unsupportedJS(b, "createRenderPipeline: vertex.module and fragment.module must be the same GPUShaderModule")) + } + + targetsArr, _ := fragmentObj.Get("targets").(*goja.Object) + if targetsArr == nil || int(targetsArr.Get("length").ToInteger()) != 1 { + panic(unsupportedJS(b, "createRenderPipeline: exactly one fragment.targets entry is supported")) + } + target0, _ := targetsArr.Get("0").(*goja.Object) + if target0 == nil { + panic(unsupportedJS(b, "createRenderPipeline: fragment.targets[0].format must be \"r8uint\"")) + } + target0FormatVal := target0.Get("format") + if target0FormatVal == nil || goja.IsUndefined(target0FormatVal) { + panic(b.vm.NewTypeError("createRenderPipeline: fragment.targets[0].format is required")) + } + if target0FormatVal.String() != "r8uint" { + panic(unsupportedJS(b, "createRenderPipeline: fragment.targets[0].format must be \"r8uint\"")) + } + // engine#447 review bug #8: blend/writeMask were read nowhere in this + // function — go-macos/metal's own RenderPipelineDescriptor has no + // per-target blend or write-mask field at all, so a caller asking for + // alpha blending (say) got a pipeline that silently always overwrites + // (no blending, full write mask), with no error. writeMask's own + // spec default is GPUColorWrite.ALL (0xF); blend's is "no blend state". + if bl := target0.Get("blend"); bl != nil && !goja.IsUndefined(bl) { + panic(unsupportedJS(b, "createRenderPipeline: fragment.targets[0].blend is not supported")) + } + if wm := target0.Get("writeMask"); wm != nil && !goja.IsUndefined(wm) && wm.ToInteger() != 0xF { + panic(unsupportedJS(b, "createRenderPipeline: fragment.targets[0].writeMask must be GPUColorWrite.ALL")) + } + + res, err := wgslmsl.TranslateRender(vModState.src, wgslmsl.RenderOptions{VertexEntryPoint: vEntryPoint, FragmentEntryPoint: fEntryPoint}) + if err != nil { + b.panicValidation("createRenderPipeline: " + err.Error()) + } + if len(res.VertexBindings) != 0 || len(res.FragmentBindings) != 0 { + panic(unsupportedJS(b, "createRenderPipeline: a shader resource (@group/@binding) is not supported in a render pipeline")) + } + + byLocation := map[int]wgslmsl.VertexInputVar{} + for _, in := range res.VertexInputs { + byLocation[in.Location] = in + } + seen := map[int]bool{} + var attrs []metal.VertexAttribute + var layouts []metal.VertexLayout + buffersArr, _ := vertexObj.Get("buffers").(*goja.Object) + if buffersArr != nil { + n := int(buffersArr.Get("length").ToInteger()) + for bi := 0; bi < n; bi++ { + bufLayout, _ := buffersArr.Get(strconv.Itoa(bi)).(*goja.Object) + if bufLayout == nil { + continue + } + strideVal := bufLayout.Get("arrayStride") + if strideVal == nil || goja.IsUndefined(strideVal) { + panic(b.vm.NewTypeError("createRenderPipeline: vertex.buffers[].arrayStride is required")) + } + // engine#447 review bug #8: stepMode was read nowhere in this + // function — metal.VertexLayout has no per-buffer step-rate + // field at all here, so a caller asking for "instance" step + // mode (per-instance, not per-vertex, attribute advance) got + // an ordinary per-vertex layout silently, no error, which only + // shows up as visibly wrong instanced geometry at draw time. + if sm := bufLayout.Get("stepMode"); sm != nil && !goja.IsUndefined(sm) && sm.String() != "vertex" { + panic(unsupportedJS(b, "createRenderPipeline: only \"vertex\" vertex.buffers[].stepMode is supported")) + } + stride := int(strideVal.ToInteger()) + layouts = append(layouts, metal.VertexLayout{BufferIndex: bi, Stride: stride}) + attrsArr, _ := bufLayout.Get("attributes").(*goja.Object) + if attrsArr == nil { + continue + } + an := int(attrsArr.Get("length").ToInteger()) + for ai := 0; ai < an; ai++ { + attr, _ := attrsArr.Get(strconv.Itoa(ai)).(*goja.Object) + if attr == nil { + continue + } + formatVal := attr.Get("format") + if formatVal == nil || goja.IsUndefined(formatVal) { + panic(b.vm.NewTypeError("createRenderPipeline: vertex attribute format is required")) + } + formatStr := formatVal.String() + mf, nc, kind, ok := gpuVertexFormat(formatStr) + if !ok { + panic(unsupportedJS(b, "createRenderPipeline: unsupported vertex format "+formatStr)) + } + locVal := attr.Get("shaderLocation") + if locVal == nil || goja.IsUndefined(locVal) { + panic(b.vm.NewTypeError("createRenderPipeline: vertex attribute shaderLocation is required")) + } + loc := int(locVal.ToInteger()) + in, found := byLocation[loc] + if !found { + b.panicValidation(fmt.Sprintf("createRenderPipeline: shader has no @location(%d) vertex input to match this attribute", loc)) + } + if in.NComponents != nc || in.ScalarKind != kind { + b.panicValidation(fmt.Sprintf("createRenderPipeline: attribute at @location(%d) does not match the shader's own input type", loc)) + } + offsetVal := attr.Get("offset") + if offsetVal == nil || goja.IsUndefined(offsetVal) { + panic(b.vm.NewTypeError("createRenderPipeline: vertex attribute offset is required")) + } + seen[loc] = true + attrs = append(attrs, metal.VertexAttribute{ + Index: loc, + Format: mf, + Offset: int(offsetVal.ToInteger()), + BufferIndex: bi, + }) + } + } + } + for _, in := range res.VertexInputs { + if !seen[in.Location] { + b.panicValidation(fmt.Sprintf("createRenderPipeline: no vertex attribute given for the shader's own @location(%d) input", in.Location)) + } + } + + combinedMSL := res.VertexMSL + "\n" + res.FragmentMSL + lib, err := dev.Compile(combinedMSL) + if err != nil { + b.panicValidation("createRenderPipeline: Metal rejected the generated shader: " + err.Error()) + } + pipe, err := lib.RenderPipeline(metal.RenderPipelineDescriptor{ + VertexFunction: res.VertexEntryPointName, + FragmentFunction: res.FragmentEntryPointName, + Attributes: attrs, + Layouts: layouts, + ColorFormat: metal.PixelFormatR8Uint, + }) + if err != nil { + b.panicValidation(err.Error()) + } + var vertexSlots []gpuVertexSlot + for _, l := range layouts { + vertexSlots = append(vertexSlots, gpuVertexSlot{index: l.BufferIndex, stride: l.Stride}) + } + return b.wrapGPURenderPipeline(&gpuRenderPipelineState{pipe: pipe, vertexSlots: vertexSlots}) +} + +func (b *binder) wrapGPURenderPipeline(st *gpuRenderPipelineState) *goja.Object { + o := b.vm.NewObject() + if b.gpuRenderPipelines == nil { + b.gpuRenderPipelines = map[*goja.Object]*gpuRenderPipelineState{} + } + b.gpuRenderPipelines[o] = st + return o +} + +// gpuRecordedRenderPass is one beginRenderPass()...end() span, recorded as +// a single entry in gpuCommandEncoderState's own ordered commands list +// (gpuRecordedCommand's own doc comment) — the render pass's own target/ +// load/store/clear, plus every draw/drawIndexed call made before end(), in +// order. +type gpuRecordedRenderPass struct { + target *metal.Texture + load metal.LoadAction + store metal.StoreAction + clear [4]float64 + draws []gpuRecordedDraw +} + +// gpuRecordedDraw is one draw()/drawIndexed() call, fully resolved at +// record time: the pipeline and every vertex buffer slot bound at that +// moment (gpuBoundVertexBuffer's own doc comment for why each is copied by +// value), plus either the non-indexed or the indexed draw's own arguments. +type gpuRecordedDraw struct { + pipeline *metal.RenderPipeline + vertexBuffers map[int]gpuBoundVertexBuffer + indexed bool + // non-indexed (draw): + vertexCount, instanceCount, firstVertex, firstInstance int + // indexed (drawIndexed) — firstInstance is shared with the non-indexed + // fields above; indexBufferOffset already folds in firstIndex*4 + // (uint32 indices only — see setIndexBuffer's own doc comment). + indexBuffer *metal.Buffer + indexBufferOffset int + indexCount int + baseVertex int +} + +// gpuRecordedTextureCopy is one copyTextureToBuffer() call — the texture- +// side counterpart of gpuRecordedCopy, executed via go-macos/metal's own +// Texture.GetBytes directly into the destination buffer's own zero-copy +// backing memory at gpuQueueSubmit time (after flushing any pending +// dispatch, exactly like gpuRecordedCopy, so a copy reading a render +// pass's own output always sees the real, GPU-written bytes). +type gpuRecordedTextureCopy struct { + tex *metal.Texture + dst *metal.Buffer + dstOffset int + size int +} + +// gpuBeginRenderPass implements +// GPUCommandEncoder.beginRenderPass(descriptor) — engine#415 M7's own +// bounded scope: exactly one color attachment (go-macos/metal's own +// RenderPassDescriptor has a single Target, no depthStencilAttachment +// counterpart), loadOp/storeOp mapped 1:1 to metal.LoadAction/ +// StoreAction, clearValue resolved by gpuReadColor. Reuses passOpen/ +// passEnded exactly as beginComputePass does (gpuCommandEncoderState's own +// doc comment: at most one pass, compute OR render, per encoder). +func (b *binder) gpuBeginRenderPass(st *gpuCommandEncoderState, call goja.FunctionCall) goja.Value { + if st.finished { + panic(b.vm.NewTypeError("beginRenderPass: this command encoder has already finished")) + } + if st.passOpen || st.passEnded { + panic(unsupportedJS(b, "beginRenderPass: only one pass (compute or render) per command encoder is supported")) + } + desc, _ := call.Argument(0).(*goja.Object) + if desc == nil { + panic(b.vm.NewTypeError("beginRenderPass: a GPURenderPassDescriptor is required")) + } + if ds := desc.Get("depthStencilAttachment"); ds != nil && !goja.IsUndefined(ds) { + panic(unsupportedJS(b, "beginRenderPass: depthStencilAttachment is not supported")) + } + colorsArr, _ := desc.Get("colorAttachments").(*goja.Object) + if colorsArr == nil || int(colorsArr.Get("length").ToInteger()) != 1 { + panic(unsupportedJS(b, "beginRenderPass: exactly one colorAttachments entry is supported")) + } + ca, _ := colorsArr.Get("0").(*goja.Object) + if ca == nil { + panic(b.vm.NewTypeError("beginRenderPass: colorAttachments[0] is required")) + } + viewObj, _ := ca.Get("view").(*goja.Object) + var texSt *gpuTextureState + if viewObj != nil { + texSt = b.gpuTextureViews[viewObj] + if texSt == nil { + texSt = b.gpuTextures[viewObj] + } + } + if texSt == nil { + panic(b.vm.NewTypeError("beginRenderPass: colorAttachments[0].view must be a GPUTextureView")) + } + if texSt.usage&gpuTextureUsageRenderAttachment == 0 { + b.panicValidation("beginRenderPass: the attachment's texture was not created with RENDER_ATTACHMENT usage") + } + load := metal.LoadActionLoad + if lv := ca.Get("loadOp"); lv != nil && !goja.IsUndefined(lv) { + switch lv.String() { + case "clear": + load = metal.LoadActionClear + case "load": + load = metal.LoadActionLoad + default: + panic(unsupportedJS(b, "beginRenderPass: unsupported loadOp "+lv.String())) + } + } + store := metal.StoreActionStore + if sv := ca.Get("storeOp"); sv != nil && !goja.IsUndefined(sv) { + switch sv.String() { + case "store": + store = metal.StoreActionStore + case "discard": + store = metal.StoreActionDontCare + default: + panic(unsupportedJS(b, "beginRenderPass: unsupported storeOp "+sv.String())) + } + } + var clear [4]float64 + if cv := ca.Get("clearValue"); cv != nil && !goja.IsUndefined(cv) { + clear = gpuReadColor(cv) + } + st.passOpen = true + rp := &gpuRecordedRenderPass{target: texSt.tex, load: load, store: store, clear: clear} + return b.wrapGPURenderPassEncoder(st, rp) +} + +// copyVertexBuffers copies vbs by value, so a draw recorded against the +// CURRENT bindings is never retroactively changed by a later +// setVertexBuffer on the same encoder (gpuBoundVertexBuffer's own doc +// comment). +func copyVertexBuffers(vbs map[int]gpuBoundVertexBuffer) map[int]gpuBoundVertexBuffer { + out := make(map[int]gpuBoundVertexBuffer, len(vbs)) + for k, v := range vbs { + out[k] = v + } + return out +} + +// wrapGPURenderPassEncoder builds the GPURenderPassEncoder surface — +// engine#415 M7's own counterpart to wrapGPUComputePassEncoder. Bind +// state (the current pipeline, every vertex buffer slot, the index +// buffer) persists across multiple draw()/drawIndexed() calls within the +// SAME pass, exactly as setPipeline/setBindGroup do for a compute pass. +func (b *binder) wrapGPURenderPassEncoder(enc *gpuCommandEncoderState, state *gpuRecordedRenderPass) *goja.Object { + var curPipeline *gpuRenderPipelineState + vertexBuffers := map[int]gpuBoundVertexBuffer{} + var curIndexBuffer *gpuBoundVertexBuffer + + o := b.vm.NewObject() + o.Set("setPipeline", func(call goja.FunctionCall) goja.Value { + pObj, _ := call.Argument(0).(*goja.Object) + p := b.gpuRenderPipelines[pObj] + if p == nil { + panic(b.vm.NewTypeError("setPipeline: expected a GPURenderPipeline")) + } + curPipeline = p + return goja.Undefined() + }) + o.Set("setVertexBuffer", func(call goja.FunctionCall) goja.Value { + slot := int(call.Argument(0).ToInteger()) + bufObj, _ := call.Argument(1).(*goja.Object) + bst := b.gpuBuffers[bufObj] + if bst == nil { + panic(b.vm.NewTypeError("setVertexBuffer: expected a GPUBuffer")) + } + offset := 0 + if a := call.Argument(2); a != nil && !goja.IsUndefined(a) { + offset = int(a.ToInteger()) + } + if offset < 0 || offset > bst.size { + panic(b.vm.NewTypeError("setVertexBuffer: offset out of range for this buffer")) + } + vertexBuffers[slot] = gpuBoundVertexBuffer{buf: bst.buf, offset: offset, size: bst.size} + return goja.Undefined() + }) + o.Set("setIndexBuffer", func(call goja.FunctionCall) goja.Value { + bufObj, _ := call.Argument(0).(*goja.Object) + bst := b.gpuBuffers[bufObj] + if bst == nil { + panic(b.vm.NewTypeError("setIndexBuffer: expected a GPUBuffer")) + } + format := call.Argument(1).String() + if format != "uint32" { + panic(unsupportedJS(b, "setIndexBuffer: only \"uint32\" indices are supported")) + } + offset := 0 + if a := call.Argument(2); a != nil && !goja.IsUndefined(a) { + offset = int(a.ToInteger()) + } + if offset < 0 || offset > bst.size { + panic(b.vm.NewTypeError("setIndexBuffer: offset out of range for this buffer")) + } + ib := gpuBoundVertexBuffer{buf: bst.buf, offset: offset, size: bst.size} + curIndexBuffer = &ib + return goja.Undefined() + }) + o.Set("draw", func(call goja.FunctionCall) goja.Value { + return b.gpuGuard(enc.dev, goja.Undefined(), func() goja.Value { + // engine#447 review bug #7: draw()/drawIndexed() after end() + // must not still execute — state.draws is only flushed into + // enc.commands by end() (below), but a call reaching here + // after that has already happened would still append to + // state.draws, silently growing a render pass gpuQueueSubmit + // believes is already fully recorded. + if !enc.passOpen { + panic(b.vm.NewTypeError("draw: this pass has already ended")) + } + return b.gpuDraw(state, curPipeline, vertexBuffers, call) + }) + }) + o.Set("drawIndexed", func(call goja.FunctionCall) goja.Value { + return b.gpuGuard(enc.dev, goja.Undefined(), func() goja.Value { + if !enc.passOpen { + panic(b.vm.NewTypeError("drawIndexed: this pass has already ended")) + } + return b.gpuDrawIndexed(state, curPipeline, vertexBuffers, curIndexBuffer, call) + }) + }) + o.Set("end", func(call goja.FunctionCall) goja.Value { + // engine#447 review bug #7: end() called twice must not re-run + // the pass — without this guard, a second end() re-appends the + // SAME state (and its by-now-possibly-grown state.draws, if a + // draw after the first end() was also left unguarded) as a + // second gpuRecordedCommand, executing every one of its draws + // all over again at gpuQueueSubmit time. + if !enc.passOpen { + panic(b.vm.NewTypeError("end: this pass has already ended")) + } + enc.passOpen = false + enc.passEnded = true + enc.commands = append(enc.commands, gpuRecordedCommand{render: state}) + return goja.Undefined() + }) + return o +} + +// gpuDraw implements GPURenderPassEncoder.draw(vertexCount, +// [instanceCount, [firstVertex, [firstInstance]]]). +func (b *binder) gpuDraw(state *gpuRecordedRenderPass, pipeline *gpuRenderPipelineState, vbs map[int]gpuBoundVertexBuffer, call goja.FunctionCall) goja.Value { + if pipeline == nil { + b.panicValidation("draw: no pipeline is set") + } + vertexCount := int(call.Argument(0).ToInteger()) + instanceCount := 1 + if a := call.Argument(1); a != nil && !goja.IsUndefined(a) { + instanceCount = int(a.ToInteger()) + } + firstVertex := 0 + if a := call.Argument(2); a != nil && !goja.IsUndefined(a) { + firstVertex = int(a.ToInteger()) + } + firstInstance := 0 + if a := call.Argument(3); a != nil && !goja.IsUndefined(a) { + firstInstance = int(a.ToInteger()) + } + if vertexCount < 0 || instanceCount < 0 || firstVertex < 0 || firstInstance < 0 { + b.panicValidation("draw: vertexCount, instanceCount, firstVertex and firstInstance must not be negative") + } + b.gpuValidateVertexBuffers("draw", pipeline, vbs, firstVertex, vertexCount) + state.draws = append(state.draws, gpuRecordedDraw{ + pipeline: pipeline.pipe, vertexBuffers: copyVertexBuffers(vbs), + vertexCount: vertexCount, instanceCount: instanceCount, + firstVertex: firstVertex, firstInstance: firstInstance, + }) + return goja.Undefined() +} + +// gpuValidateVertexBuffers is draw's own bounds check (engine#447 review +// bug #6): every slot the pipeline declares (gpuRenderPipelineState's own +// vertexSlots) must have a vertex buffer bound, regardless of +// vertexCount, and — when vertexCount > 0 — that buffer must be large +// enough to supply every vertex in [firstVertex, firstVertex+vertexCount) +// at its own declared stride. Content validation (panicValidation, per +// spec's own error model — never a thrown TypeError), called from BOTH +// draw (firstVertex-based range) and drawIndexed (gpuValidateIndexedVertexBuffers's +// own per-index range, after resolving each actual vertex index through +// baseVertex). +func (b *binder) gpuValidateVertexBuffers(who string, pipeline *gpuRenderPipelineState, vbs map[int]gpuBoundVertexBuffer, firstVertex, vertexCount int) { + for _, slot := range pipeline.vertexSlots { + vb, ok := vbs[slot.index] + if !ok { + b.panicValidation(fmt.Sprintf("%s: no vertex buffer bound for slot %d", who, slot.index)) + } + if vertexCount <= 0 || slot.stride <= 0 { + continue + } + maxIndex := firstVertex + vertexCount - 1 + needed := vb.offset + (maxIndex+1)*slot.stride + if needed > vb.size { + b.panicValidation(fmt.Sprintf("%s: vertex buffer at slot %d is too small for this draw (need %d bytes, have %d)", who, slot.index, needed, vb.size)) + } + } +} + +// gpuValidateIndexedVertexBuffers is drawIndexed's own bounds check +// (engine#447 review bug #6): first confirms every pipeline-declared slot +// has a vertex buffer bound (exactly like gpuValidateVertexBuffers), +// then — when indexCount > 0 — reads every uint32 index the draw is about +// to use directly from the index buffer's own CPU-visible bytes +// (go-macos/metal buffers are unified memory; gpuDispatchWorkgroups +// already reads/writes one the same way for its own _Sizes buffer) and +// checks, for every slot, that baseVertex+index is never negative and +// never reads past that slot's bound buffer. Content validation +// (panicValidation): the buffers, the pipeline and every individual index +// value are each independently legitimate; only the COMBINATION — THIS +// index against THIS buffer — can be out of range, which is exactly what +// go-macos/metal's own RenderEncoder does not check. +func (b *binder) gpuValidateIndexedVertexBuffers(pipeline *gpuRenderPipelineState, vbs map[int]gpuBoundVertexBuffer, ib *gpuBoundVertexBuffer, byteOffset, indexCount, baseVertex int) { + for _, slot := range pipeline.vertexSlots { + if _, ok := vbs[slot.index]; !ok { + b.panicValidation(fmt.Sprintf("drawIndexed: no vertex buffer bound for slot %d", slot.index)) + } + } + // No "indexCount <= 0: return" guard here (mutsweep flagged its + // absence as unobserved, not the other way around — deleted as + // proven dead, not waived): both gpuDrawIndexed call sites below + // already guarantee the two things such a guard would protect. `ib` + // is never nil here (gpuDrawIndexed's own "no index buffer is set" + // check, just above its call to this function, panics first), so + // ib.buf.Bytes() is always safe to call; and indexCount is never + // negative here (gpuDrawIndexed's own negative-value check, also + // above its call to this function, panics first), so the for loop + // below already runs zero iterations on its own for indexCount == 0 — + // exactly what an early return would have produced, with no + // observable difference either way. + raw := ib.buf.Bytes() + for i := 0; i < indexCount; i++ { + off := byteOffset + i*4 + idx := int(int64(baseVertex) + int64(binary.LittleEndian.Uint32(raw[off:off+4]))) + if idx < 0 { + b.panicValidation("drawIndexed: an index plus baseVertex is negative") + } + for _, slot := range pipeline.vertexSlots { + if slot.stride <= 0 { + continue + } + vb := vbs[slot.index] + needed := vb.offset + (idx+1)*slot.stride + if needed > vb.size { + b.panicValidation(fmt.Sprintf("drawIndexed: vertex buffer at slot %d is too small for this draw (need %d bytes, have %d)", slot.index, needed, vb.size)) + } + } + } +} + +// gpuDrawIndexed implements GPURenderPassEncoder.drawIndexed(indexCount, +// [instanceCount, [firstIndex, [baseVertex, [firstInstance]]]]). +// firstIndex*4 is folded into the recorded indexBufferOffset (uint32 +// indices only, this binding's own setIndexBuffer restriction) since +// go-macos/metal's own RenderEncoder.DrawIndexed has no separate +// firstIndex parameter. +func (b *binder) gpuDrawIndexed(state *gpuRecordedRenderPass, pipeline *gpuRenderPipelineState, vbs map[int]gpuBoundVertexBuffer, ib *gpuBoundVertexBuffer, call goja.FunctionCall) goja.Value { + if pipeline == nil { + b.panicValidation("drawIndexed: no pipeline is set") + } + if ib == nil { + b.panicValidation("drawIndexed: no index buffer is set") + } + indexCount := int(call.Argument(0).ToInteger()) + instanceCount := 1 + if a := call.Argument(1); a != nil && !goja.IsUndefined(a) { + instanceCount = int(a.ToInteger()) + } + firstIndex := 0 + if a := call.Argument(2); a != nil && !goja.IsUndefined(a) { + firstIndex = int(a.ToInteger()) + } + baseVertex := 0 + if a := call.Argument(3); a != nil && !goja.IsUndefined(a) { + baseVertex = int(a.ToInteger()) + } + firstInstance := 0 + if a := call.Argument(4); a != nil && !goja.IsUndefined(a) { + firstInstance = int(a.ToInteger()) + } + if indexCount < 0 || instanceCount < 0 || firstIndex < 0 || firstInstance < 0 { + b.panicValidation("drawIndexed: indexCount, instanceCount, firstIndex and firstInstance must not be negative") + } + indexByteOffset := ib.offset + firstIndex*4 + if indexCount > 0 { + if need := indexByteOffset + indexCount*4; need > ib.size { + b.panicValidation(fmt.Sprintf("drawIndexed: index buffer is too small for this draw (need %d bytes, have %d)", need, ib.size)) + } + } + b.gpuValidateIndexedVertexBuffers(pipeline, vbs, ib, indexByteOffset, indexCount, baseVertex) + state.draws = append(state.draws, gpuRecordedDraw{ + pipeline: pipeline.pipe, vertexBuffers: copyVertexBuffers(vbs), indexed: true, + indexBuffer: ib.buf, indexBufferOffset: indexByteOffset, + indexCount: indexCount, instanceCount: instanceCount, + baseVertex: baseVertex, firstInstance: firstInstance, + }) + return goja.Undefined() +} + +// gpuCopyTextureToBuffer implements +// GPUCommandEncoder.copyTextureToBuffer(source, destination, copySize) — +// the texture-side counterpart of gpuCopyBufferToBuffer, with the same +// "only a tightly packed, full-extent, mip-0, zero-origin copy" +// restriction writeTexture itself has (see its own doc comment). Recorded +// into enc.commands, not copied immediately — gpuRecordedTextureCopy's +// own doc comment for why ordering relative to a render pass matters. +func (b *binder) gpuCopyTextureToBuffer(enc *gpuCommandEncoderState, call goja.FunctionCall) goja.Value { + if enc.finished { + panic(b.vm.NewTypeError("copyTextureToBuffer: this command encoder has already finished")) + } + srcObj, _ := call.Argument(0).(*goja.Object) + if srcObj == nil { + panic(b.vm.NewTypeError("copyTextureToBuffer: source must be a GPUImageCopyTexture")) + } + texObj, _ := srcObj.Get("texture").(*goja.Object) + var texSt *gpuTextureState + if texObj != nil { + texSt = b.gpuTextures[texObj] + } + if texSt == nil { + panic(b.vm.NewTypeError("copyTextureToBuffer: source.texture must be a GPUTexture")) + } + if mip := srcObj.Get("mipLevel"); mip != nil && !goja.IsUndefined(mip) && mip.ToInteger() != 0 { + panic(unsupportedJS(b, "copyTextureToBuffer: only mipLevel 0 is supported")) + } + if origin := srcObj.Get("origin"); origin != nil && !goja.IsUndefined(origin) && !gpuIsZeroOrigin(origin) { + panic(unsupportedJS(b, "copyTextureToBuffer: only a zero origin (a full-extent copy) is supported")) + } + dstObj, _ := call.Argument(1).(*goja.Object) + if dstObj == nil { + panic(b.vm.NewTypeError("copyTextureToBuffer: destination must be a GPUImageCopyBuffer")) + } + bufObj, _ := dstObj.Get("buffer").(*goja.Object) + var bufSt *gpuBufferState + if bufObj != nil { + bufSt = b.gpuBuffers[bufObj] + } + if bufSt == nil { + panic(b.vm.NewTypeError("copyTextureToBuffer: destination.buffer must be a GPUBuffer")) + } + offset := 0 + if o := dstObj.Get("offset"); o != nil && !goja.IsUndefined(o) { + offset = int(o.ToInteger()) + } + bytesPerRow := texSt.width + if bpr := dstObj.Get("bytesPerRow"); bpr != nil && !goja.IsUndefined(bpr) { + bytesPerRow = int(bpr.ToInteger()) + } + if bytesPerRow != texSt.width { + panic(unsupportedJS(b, "copyTextureToBuffer: only a tightly packed copy (bytesPerRow == texture width) is supported")) + } + size := gpuReadExtent(call.Argument(2)) + if size.w != texSt.width || size.h != texSt.height { + panic(unsupportedJS(b, "copyTextureToBuffer: only a full-extent copy is supported")) + } + want := texSt.width * texSt.height + if offset < 0 || offset+want > bufSt.size { + panic(b.vm.NewTypeError("copyTextureToBuffer: destination range out of bounds")) + } + enc.commands = append(enc.commands, gpuRecordedCommand{textureCopy: &gpuRecordedTextureCopy{ + tex: texSt.tex, dst: bufSt.buf, dstOffset: offset, size: want, + }}) + return goja.Undefined() +} diff --git a/js/webgpu_test.go b/js/webgpu_test.go index 5a764d9..3dc361f 100644 --- a/js/webgpu_test.go +++ b/js/webgpu_test.go @@ -4,14 +4,71 @@ package js import ( + "fmt" "net/http" "strings" "testing" "time" + "github.com/dop251/goja" "github.com/go-webengine/engine/dom" ) +// renderWGSL is engine#415 M7's own minimal vertex+fragment pair: an +// instance-indexed full-screen quad, writing the instance index back as a +// flat u32 fragment output — reused by every render-pipeline/render-pass +// test below so a single known-good shader is translated and compiled +// each time, matching wgslmsl's own +// TestTranslateRenderVertexFragmentEndToEnd shape exactly (same shader +// text, confirmed to translate and compile there). +const renderWGSL = ` +struct VertexOut { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) value: u32, +} + +@vertex +fn vmain(@location(0) pos: vec2, @builtin(instance_index) iid: u32) -> VertexOut { + var out: VertexOut; + out.position = vec4(pos, 0.0, 1.0); + out.value = iid; + return out; +} + +@fragment +fn fmain(in: VertexOut) -> @location(0) u32 { + return in.value; +} +` + +// renderPipelineSetupJS builds the dev.createShaderModule/createTexture/ +// createRenderPipeline JS, shared by every M7 render test below, so a +// single known-good 4x4 r8uint pipeline setup is never retyped with a +// chance of drifting between tests. +func renderPipelineSetupJS() string { + return fmt.Sprintf(` + var module = dev.createShaderModule({ code: `+"`%s`"+` }); + var tex = dev.createTexture({ + size: { width: 4, height: 4 }, + format: 'r8uint', + usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, + }); + var pipeline = dev.createRenderPipeline({ + layout: 'auto', + vertex: { + module: module, + entryPoint: 'vmain', + buffers: [{ arrayStride: 8, attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] }], + }, + fragment: { + module: module, + entryPoint: 'fmain', + targets: [{ format: 'r8uint' }], + }, + }); + `, renderWGSL) +} + // runWebGPU is runJS with EnableWebGPU set. func runWebGPU(t *testing.T, htmlSrc string) (*dom.Node, []string, Result) { t.Helper() @@ -814,6 +871,52 @@ func TestComputePipelineRejectsExplicitLayout(t *testing.T) { } } +// TestComputePipelineRejectsTextureResource is the regression test for +// engine#447 review bug #5: a @compute entry point declaring a +// texture_2d resource (the one shape wgslmsl's own resolveResources +// legitimately accepts for ANY stage, including compute, directly via +// go-macos/metal — see wgslmsl's own TestTranslateTextureLoadEndToEnd) +// must still be rejected by THIS binding's createComputePipeline: its own +// dispatch path (gpuDispatchWorkgroups) has no texture-binding mechanism +// and would otherwise collide the texture's Metal index — allocated from +// wgslmsl's separate tr.textureCount counter — with a real buffer +// resource's own same-numbered tr.bufferCount index, silently delivering +// one resource's bytes under the other's binding instead of failing. +func TestComputePipelineRejectsTextureResource(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var module = dev.createShaderModule({ code: `+"`"+` + @group(0) @binding(0) var tex: texture_2d; + @group(0) @binding(1) var out: array; + @compute @workgroup_size(1) + fn main(@builtin(global_invocation_id) id: vec3) { + out[id.x] = textureLoad(tex, vec2(0, 0), 0).x; + } + `+"`"+` }); + try { + dev.createComputePipeline({ layout: 'auto', compute: { module: module } }); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q", got, "threw:TypeError") + } +} + // TestDispatchWithoutBindGroupRejected proves a dispatch missing a needed // bind group fails clearly rather than reading/writing an unbound buffer // index. @@ -1325,3 +1428,1656 @@ func TestCreateBindGroupSubRangeBindsDisjointRegionsOfOneBuffer(t *testing.T) { t.Fatalf("data-out = %q, want %q logs=%v (each region written only by its own bind group's own offset and constant, everything else untouched)", got, strings.Join(want, ","), logs) } } + +// TestGPUCreateTextureEndToEnd covers GPUDevice.createTexture's own happy +// path: every descriptor field this binding's bounded scope reports back +// through the resulting GPUTexture's own property getters, then destroy(). +func TestGPUCreateTextureEndToEnd(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ + size: { width: 4, height: 4 }, + format: 'r8uint', + usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, + }); + document.body.setAttribute('data-shape', [ + tex.width, tex.height, tex.depthOrArrayLayers, tex.format, tex.dimension, tex.mipLevelCount, tex.sampleCount, + ].join(',')); + tex.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if got, _ := body.Attribute("data-result"); got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + want := "4,4,1,r8uint,2d,1,1" + if got, _ := body.Attribute("data-shape"); got != want { + t.Fatalf("data-shape = %q, want %q", got, want) + } +} + +// TestGPUCreateTextureUnsupportedFormatRejected proves an unsupported +// GPUTextureFormat is a named, synchronous rejection (unsupportedJS), +// never a silently wrong go-macos/metal PixelFormat. +func TestGPUCreateTextureUnsupportedFormatRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + try { + dev.createTexture({ size: { width: 4, height: 4 }, format: 'rgba8unorm', usage: GPUTextureUsage.COPY_SRC }); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q", got, "threw:TypeError") + } +} + +// TestGPUTextureCreateViewEndToEnd covers GPUTexture.createView()'s own +// happy path: a view object is handed back and is itself usable where a +// GPUTextureView is expected (beginRenderPass's own colorAttachments[0] +// .view, checked by the render-pass tests below). +func TestGPUTextureCreateViewEndToEnd(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ size: { width: 4, height: 4 }, format: 'r8uint', usage: GPUTextureUsage.RENDER_ATTACHMENT }); + var view = tex.createView(); + document.body.setAttribute('data-view-type', typeof view); + tex.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if got, _ := body.Attribute("data-result"); got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-view-type"); got != "object" { + t.Fatalf("data-view-type = %q, want %q", got, "object") + } +} + +// TestGPUTextureCreateViewUnsupportedDimensionRejected proves +// createView's own bounded scope (no mip chain, no array layers, no +// reinterpretation — see its own doc comment) names a rejection rather +// than silently handing back a view of the whole texture anyway. +func TestGPUTextureCreateViewUnsupportedDimensionRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ size: { width: 4, height: 4 }, format: 'r8uint', usage: GPUTextureUsage.RENDER_ATTACHMENT }); + try { + tex.createView({ dimension: '3d' }); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + tex.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q", got, "threw:TypeError") + } +} + +// TestGPURenderPipelineRejectsResourceBinding proves this binding's own +// deliberate render-pipeline scope narrowing (go-macos/metal's own +// RenderEncoder has no fragment-stage buffer binding and no bind-group +// mechanism at all — see gpuCreateRenderPipeline's own doc comment): a +// shader declaring a @group/@binding resource fails pipeline creation. +// Per spec (and exactly like TestCreateComputePipelineBadWGSLCapturedByErrorScope's +// own bad-WGSL case for compute), a pipeline-creation failure is GPU +// content validation — captured by an open error scope, never a +// synchronous throw — so createRenderPipeline rejecting this shader via +// wgslmsl.TranslateRender's own translation error takes the exact same +// path a genuinely bad shader would, confirmed empirically (this shader +// IS valid WGSL; wgslmsl's own render translator just does not support a +// module-scope resource in a render entry point yet). +func TestGPURenderPipelineRejectsResourceBinding(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var module = dev.createShaderModule({ code: `+"`"+` + @group(0) @binding(0) var tint: array; + struct VertexOut { @builtin(position) position: vec4 } + @vertex + fn vmain(@location(0) pos: vec2) -> VertexOut { + var out: VertexOut; + out.position = vec4(pos, 0.0, 1.0); + return out; + } + @fragment + fn fmain(in: VertexOut) -> @location(0) u32 { return u32(tint[0]); } + `+"`"+` }); + dev.pushErrorScope('validation'); + var threw = false; + try { + dev.createRenderPipeline({ + layout: 'auto', + vertex: { module: module, entryPoint: 'vmain', buffers: [{ arrayStride: 8, attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] }] }, + fragment: { module: module, entryPoint: 'fmain', targets: [{ format: 'r8uint' }] }, + }); + } catch (e) { threw = true; } + document.body.setAttribute('data-threw', String(threw)); + return dev.popErrorScope().then(function(err) { + document.body.setAttribute('data-captured-name', err ? err.constructor.name : 'null'); + }); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if skip, _ := body.Attribute("data-result"); skip == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-threw"); got != "false" { + t.Fatalf("data-threw = %q, want %q (a resource-binding render shader must never throw synchronously when a scope is open)", got, "false") + } + if got, _ := body.Attribute("data-captured-name"); got != "GPUValidationError" { + t.Fatalf("data-captured-name = %q, want %q", got, "GPUValidationError") + } +} + +// TestGPURenderPipelineRejectsFixedSizeUniformBinding exercises this +// binding's own EXPLICIT post-translation rejection in +// gpuCreateRenderPipeline (checking res.VertexBindings/FragmentBindings), +// as distinct from TestGPURenderPipelineRejectsResourceBinding's own +// case (a runtime-sized storage array, which wgslmsl.TranslateRender +// itself already refuses to translate at all — see TranslateRender's own +// doc comment). A fixed-size `var` struct DOES translate +// successfully (same doc comment: "may read ONE resource kind beyond +// uniform/storage"), so reaching createRenderPipeline with a real, +// resolved binding is what actually exercises this check — go-macos/ +// metal's own RenderEncoder still has no bind-group mechanism to honour +// it, hence the named, synchronous rejection (unsupportedJS), not a +// captured validation error. +func TestGPURenderPipelineRejectsFixedSizeUniformBinding(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var module = dev.createShaderModule({ code: `+"`"+` + @group(0) @binding(0) var tint: f32; + struct VertexOut { @builtin(position) position: vec4 } + @vertex + fn vmain(@location(0) pos: vec2) -> VertexOut { + var out: VertexOut; + out.position = vec4(pos, 0.0, 1.0); + return out; + } + @fragment + fn fmain(in: VertexOut) -> @location(0) u32 { return u32(tint); } + `+"`"+` }); + try { + dev.createRenderPipeline({ + layout: 'auto', + vertex: { module: module, entryPoint: 'vmain', buffers: [{ arrayStride: 8, attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] }] }, + fragment: { module: module, entryPoint: 'fmain', targets: [{ format: 'r8uint' }] }, + }); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q", got, "threw:TypeError") + } +} + +// TestGPURenderPassEncoderDrawIndexedEndToEnd is the render-pipeline +// counterpart of TestComputePipelineEndToEnd: a full +// beginRenderPass/setPipeline/setVertexBuffer/setIndexBuffer/drawIndexed/ +// end/submit round trip, read back bit-for-bit through +// copyTextureToBuffer + mapAsync — mirroring wgslmsl's own +// TestTranslateRenderVertexFragmentEndToEnd (same shader, same quad, same +// firstInstance-as-pixel-value trick) but driven entirely through this +// package's own JS surface instead of go-macos/metal directly. +func TestGPURenderPassEncoderDrawIndexedEndToEnd(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + `+renderPipelineSetupJS()+` + var vb = dev.createBuffer({ size: 32, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }); + dev.queue.writeBuffer(vb, 0, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1])); + var ib = dev.createBuffer({ size: 24, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST }); + dev.queue.writeBuffer(ib, 0, new Uint32Array([0, 1, 2, 2, 1, 3])); + + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 5, g: 5, b: 5, a: 5 } }], + }); + pass.setPipeline(pipeline); + pass.setVertexBuffer(0, vb); + pass.setIndexBuffer(ib, 'uint32'); + pass.drawIndexed(6, 1, 0, 0, 7); + pass.end(); + + var readback = dev.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); + encoder.copyTextureToBuffer({ texture: tex }, { buffer: readback }, { width: 4, height: 4 }); + dev.queue.submit([encoder.finish()]); + + return readback.mapAsync(GPUMapMode.READ).then(function() { + var out = Array.from(new Uint8Array(readback.getMappedRange())); + document.body.setAttribute('data-out', out.join(',')); + readback.destroy(); + vb.destroy(); + ib.destroy(); + tex.destroy(); + }); + }, function(e) { + document.body.setAttribute('data-result', 'REJECTED:' + e); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if got, _ := body.Attribute("data-result"); got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } else if got != "" { + t.Fatalf("data-result = %q, want empty (no rejection)", got) + } + want := make([]string, 16) + for i := range want { + want[i] = "7" + } + got, _ := body.Attribute("data-out") + if got != strings.Join(want, ",") { + t.Fatalf("data-out = %q, want %q (the quad covers the whole 4x4 target; every pixel must read back firstInstance=7)", got, strings.Join(want, ",")) + } +} + +// TestGPURenderPassEncoderDrawEndToEnd is drawIndexed's own non-indexed +// counterpart: the same quad, as two triangles given directly through +// draw() with no index buffer at all. +func TestGPURenderPassEncoderDrawEndToEnd(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + `+renderPipelineSetupJS()+` + var vb = dev.createBuffer({ size: 48, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }); + dev.queue.writeBuffer(vb, 0, new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1])); + + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 5, g: 5, b: 5, a: 5 } }], + }); + pass.setPipeline(pipeline); + pass.setVertexBuffer(0, vb); + pass.draw(6, 1, 0, 3); + pass.end(); + + var readback = dev.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); + encoder.copyTextureToBuffer({ texture: tex }, { buffer: readback }, { width: 4, height: 4 }); + dev.queue.submit([encoder.finish()]); + + return readback.mapAsync(GPUMapMode.READ).then(function() { + var out = Array.from(new Uint8Array(readback.getMappedRange())); + document.body.setAttribute('data-out', out.join(',')); + readback.destroy(); + vb.destroy(); + tex.destroy(); + }); + }, function(e) { + document.body.setAttribute('data-result', 'REJECTED:' + e); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if got, _ := body.Attribute("data-result"); got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } else if got != "" { + t.Fatalf("data-result = %q, want empty (no rejection)", got) + } + want := make([]string, 16) + for i := range want { + want[i] = "3" + } + got, _ := body.Attribute("data-out") + if got != strings.Join(want, ",") { + t.Fatalf("data-out = %q, want %q (the quad covers the whole 4x4 target; every pixel must read back firstInstance=3)", got, strings.Join(want, ",")) + } +} + +// TestDrawWithoutPipelineCapturedByErrorScope proves draw() with no +// setPipeline call is GPU content validation per spec, never a +// synchronous throw — captured by an open error scope exactly like +// TestQueueWriteBufferOutOfRangeCapturedByErrorScope's own writeBuffer +// case. +func TestDrawWithoutPipelineCapturedByErrorScope(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ size: { width: 4, height: 4 }, format: 'r8uint', usage: GPUTextureUsage.RENDER_ATTACHMENT }); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + dev.pushErrorScope('validation'); + var threw = false; + try { + pass.draw(3, 1, 0, 0); + } catch (e) { threw = true; } + pass.end(); + document.body.setAttribute('data-threw', String(threw)); + return dev.popErrorScope().then(function(err) { + document.body.setAttribute('data-captured-name', err ? err.constructor.name : 'null'); + tex.destroy(); + }); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if skip, _ := body.Attribute("data-result"); skip == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-threw"); got != "false" { + t.Fatalf("data-threw = %q, want %q (draw without a pipeline must never throw synchronously when a scope is open)", got, "false") + } + if got, _ := body.Attribute("data-captured-name"); got != "GPUValidationError" { + t.Fatalf("data-captured-name = %q, want %q", got, "GPUValidationError") + } +} + +// TestGPUDrawRejectsMissingVertexBuffer is the regression test for +// engine#447 review bug #6's "no vertex buffer bound per slot" check: +// renderPipelineSetupJS's own pipeline declares one vertex buffer slot +// (index 0, stride 8), but this test never calls setVertexBuffer at all +// before draw() — GPU content validation (captured by an open error +// scope), exactly like TestDrawWithoutPipelineCapturedByErrorScope's own +// "no pipeline set" case just above. +func TestGPUDrawRejectsMissingVertexBuffer(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + `+renderPipelineSetupJS()+` + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + pass.setPipeline(pipeline); + dev.pushErrorScope('validation'); + var threw = false; + try { + pass.draw(6, 1, 0, 0); + } catch (e) { threw = true; } + pass.end(); + document.body.setAttribute('data-threw', String(threw)); + return dev.popErrorScope().then(function(err) { + document.body.setAttribute('data-captured-name', err ? err.constructor.name : 'null'); + tex.destroy(); + }); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if skip, _ := body.Attribute("data-result"); skip == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-threw"); got != "false" { + t.Fatalf("data-threw = %q, want %q (draw with a slot unbound must never throw synchronously when a scope is open)", got, "false") + } + if got, _ := body.Attribute("data-captured-name"); got != "GPUValidationError" { + t.Fatalf("data-captured-name = %q, want %q", got, "GPUValidationError") + } +} + +// TestGPUDrawRejectsVertexBufferTooSmall is engine#447 review bug #6's +// "count-vs-buffer-size bound" check: a vertex buffer IS bound at slot 0, +// but it holds only 1 vertex (8 bytes, the pipeline's own stride) while +// draw(6, ...) needs 6 — without this check, go-macos/metal's own +// RenderEncoder reads 40 bytes past the buffer's real end. +func TestGPUDrawRejectsVertexBufferTooSmall(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + `+renderPipelineSetupJS()+` + var vb = dev.createBuffer({ size: 8, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + pass.setPipeline(pipeline); + pass.setVertexBuffer(0, vb); + dev.pushErrorScope('validation'); + var threw = false; + try { + pass.draw(6, 1, 0, 0); + } catch (e) { threw = true; } + pass.end(); + document.body.setAttribute('data-threw', String(threw)); + return dev.popErrorScope().then(function(err) { + document.body.setAttribute('data-captured-name', err ? err.constructor.name : 'null'); + vb.destroy(); + tex.destroy(); + }); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if skip, _ := body.Attribute("data-result"); skip == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-threw"); got != "false" { + t.Fatalf("data-threw = %q, want %q (a too-small vertex buffer must never throw synchronously when a scope is open)", got, "false") + } + if got, _ := body.Attribute("data-captured-name"); got != "GPUValidationError" { + t.Fatalf("data-captured-name = %q, want %q", got, "GPUValidationError") + } +} + +// TestGPUDrawRejectsNegativeVertexCount is engine#447 review bug #6's +// "no negative-value check": draw(-1, ...) must be rejected, not passed +// straight through to go-macos/metal as a huge unsigned count. +func TestGPUDrawRejectsNegativeVertexCount(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + `+renderPipelineSetupJS()+` + var vb = dev.createBuffer({ size: 48, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + pass.setPipeline(pipeline); + pass.setVertexBuffer(0, vb); + dev.pushErrorScope('validation'); + var threw = false; + try { + pass.draw(-1, 1, 0, 0); + } catch (e) { threw = true; } + pass.end(); + document.body.setAttribute('data-threw', String(threw)); + return dev.popErrorScope().then(function(err) { + document.body.setAttribute('data-captured-name', err ? err.constructor.name : 'null'); + vb.destroy(); + tex.destroy(); + }); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if skip, _ := body.Attribute("data-result"); skip == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-threw"); got != "false" { + t.Fatalf("data-threw = %q, want %q (a negative count must never throw synchronously when a scope is open)", got, "false") + } + if got, _ := body.Attribute("data-captured-name"); got != "GPUValidationError" { + t.Fatalf("data-captured-name = %q, want %q", got, "GPUValidationError") + } +} + +// TestGPUDrawIndexedRejectsOutOfRangeIndex is engine#447 review bug #6's +// "index range/alignment check": the index buffer's own last index (10) +// points well past the 4-vertex (32-byte) vertex buffer bound at slot 0 — +// without reading the index buffer's own contents at drawIndexed time (as +// gpuValidateIndexedVertexBuffers now does), this would silently read +// vertex attribute data from 48 bytes past the buffer's real end. +func TestGPUDrawIndexedRejectsOutOfRangeIndex(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + `+renderPipelineSetupJS()+` + var vb = dev.createBuffer({ size: 32, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }); + dev.queue.writeBuffer(vb, 0, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1])); + var ib = dev.createBuffer({ size: 24, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST }); + dev.queue.writeBuffer(ib, 0, new Uint32Array([0, 1, 2, 2, 1, 10])); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + pass.setPipeline(pipeline); + pass.setVertexBuffer(0, vb); + pass.setIndexBuffer(ib, 'uint32'); + dev.pushErrorScope('validation'); + var threw = false; + try { + pass.drawIndexed(6, 1, 0, 0, 0); + } catch (e) { threw = true; } + pass.end(); + document.body.setAttribute('data-threw', String(threw)); + return dev.popErrorScope().then(function(err) { + document.body.setAttribute('data-captured-name', err ? err.constructor.name : 'null'); + vb.destroy(); + ib.destroy(); + tex.destroy(); + }); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if skip, _ := body.Attribute("data-result"); skip == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-threw"); got != "false" { + t.Fatalf("data-threw = %q, want %q (an out-of-range index must never throw synchronously when a scope is open)", got, "false") + } + if got, _ := body.Attribute("data-captured-name"); got != "GPUValidationError" { + t.Fatalf("data-captured-name = %q, want %q", got, "GPUValidationError") + } +} + +// TestGPURenderPassEndCalledTwiceRejected is engine#447 review bug #7's +// "end() called twice re-runs the pass" defect: without the enc.passOpen +// guard in wrapGPURenderPassEncoder's own "end" handler, a second end() +// call would re-append the SAME gpuRecordedCommand (and whatever draws it +// holds) a second time, so gpuQueueSubmit would execute every draw in the +// pass twice. The second end() must instead throw a synchronous TypeError +// (this is a usage error, not a GPU validation error, so it is never +// routed through an error scope the way bug #6's draw() checks are). +func TestGPURenderPassEndCalledTwiceRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + `+renderPipelineSetupJS()+` + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + pass.setPipeline(pipeline); + pass.end(); + try { + pass.end(); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + tex.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q (end() called a second time on an already-ended render pass must throw synchronously, not silently re-run it)", got, "threw:TypeError") + } +} + +// TestGPUDrawAfterRenderPassEndRejected is engine#447 review bug #7's +// "draw after end() still executes" defect: draw() records into +// state.draws directly, so without the enc.passOpen guard in "draw"'s own +// handler, a call made after end() has already flushed state into +// enc.commands would still append to that (by-now-submitted) state, +// growing a render pass gpuQueueSubmit already believes is fully +// recorded. +func TestGPUDrawAfterRenderPassEndRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + `+renderPipelineSetupJS()+` + var vb = dev.createBuffer({ size: 48, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + pass.setPipeline(pipeline); + pass.setVertexBuffer(0, vb); + pass.end(); + try { + pass.draw(6, 1, 0, 0); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + vb.destroy(); + tex.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q (draw() after end() must throw synchronously, not silently record into an already-submitted pass)", got, "threw:TypeError") + } +} + +// TestGPUCommandEncoderFinishWithOpenRenderPassRejected is engine#447 +// review bug #7's "a pass begun but never end()ed is silently dropped" +// defect: finish() must reject when a render (or compute) pass is still +// open, since every draw recorded against it is sitting unflushed in the +// render pass's own state.draws and would otherwise be lost the moment +// finish() hands back a command buffer with no reference to it at all. +func TestGPUCommandEncoderFinishWithOpenRenderPassRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + `+renderPipelineSetupJS()+` + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + pass.setPipeline(pipeline); + try { + encoder.finish(); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + tex.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q (finish() with a render pass still open — no end() call — must throw synchronously, not silently drop the pass)", got, "threw:TypeError") + } +} + +// TestGPUComputePassDispatchAfterEndRejected is +// TestGPUDrawAfterRenderPassEndRejected's own compute-pass counterpart: +// dispatchWorkgroups records directly into enc.commands, so a call after +// end() would still run against an encoder whose pass has already been +// handed to gpuQueueSubmit's own command list. +func TestGPUComputePassDispatchAfterEndRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var module = dev.createShaderModule({ code: `+"`"+` + @group(0) @binding(0) var data: array; + @compute @workgroup_size(1) + fn main(@builtin(global_invocation_id) id: vec3) { data[id.x] = 0.0; } + `+"`"+` }); + var pipeline = dev.createComputePipeline({ layout: 'auto', compute: { module: module } }); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginComputePass(); + pass.setPipeline(pipeline); + pass.end(); + try { + pass.dispatchWorkgroups(1); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q (dispatchWorkgroups() after end() must throw synchronously, not silently record into an already-submitted compute pass)", got, "threw:TypeError") + } +} + +// TestGPUComputePassEndCalledTwiceRejected is +// TestGPURenderPassEndCalledTwiceRejected's own compute-pass counterpart: +// without the enc.passOpen guard, a second end() would re-append the same +// dispatch commands a second time (since dispatchWorkgroups already wrote +// them straight into enc.commands, "ending" a second time has no draws +// left to re-flush here, but the guard must still fire symmetrically with +// the render-pass encoder sharing the same gpuCommandEncoderState fields). +func TestGPUComputePassEndCalledTwiceRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var module = dev.createShaderModule({ code: `+"`"+` + @group(0) @binding(0) var data: array; + @compute @workgroup_size(1) + fn main(@builtin(global_invocation_id) id: vec3) { data[id.x] = 0.0; } + `+"`"+` }); + var pipeline = dev.createComputePipeline({ layout: 'auto', compute: { module: module } }); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginComputePass(); + pass.setPipeline(pipeline); + pass.end(); + try { + pass.end(); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q (end() called a second time on an already-ended compute pass must throw synchronously, not silently re-run it)", got, "threw:TypeError") + } +} + +// TestSetIndexBufferUnsupportedFormatRejected proves setIndexBuffer's own +// bounded scope (uint32 indices only — see its own doc comment, and +// gpuDrawIndexed's firstIndex folding, which assumes 4-byte indices) +// names a rejection for "uint16" rather than silently misreading the +// buffer. +func TestSetIndexBufferUnsupportedFormatRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ size: { width: 4, height: 4 }, format: 'r8uint', usage: GPUTextureUsage.RENDER_ATTACHMENT }); + var ib = dev.createBuffer({ size: 24, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST }); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + try { + pass.setIndexBuffer(ib, 'uint16'); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + pass.end(); + ib.destroy(); + tex.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q", got, "threw:TypeError") + } +} + +// TestGPUQueueWriteTextureEndToEnd covers GPUQueue.writeTexture's own +// happy path: a full-extent, tightly packed write, read back bit-for-bit +// through copyTextureToBuffer + mapAsync. +func TestGPUQueueWriteTextureEndToEnd(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ + size: { width: 4, height: 4 }, + format: 'r8uint', + usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC, + }); + var pixels = new Uint8Array([1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]); + dev.queue.writeTexture({ texture: tex }, pixels, {}, { width: 4, height: 4 }); + + var encoder = dev.createCommandEncoder(); + var readback = dev.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); + encoder.copyTextureToBuffer({ texture: tex }, { buffer: readback }, { width: 4, height: 4 }); + dev.queue.submit([encoder.finish()]); + + return readback.mapAsync(GPUMapMode.READ).then(function() { + var out = Array.from(new Uint8Array(readback.getMappedRange())); + document.body.setAttribute('data-out', out.join(',')); + readback.destroy(); + tex.destroy(); + }); + }, function(e) { + document.body.setAttribute('data-result', 'REJECTED:' + e); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if got, _ := body.Attribute("data-result"); got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } else if got != "" { + t.Fatalf("data-result = %q, want empty (no rejection)", got) + } + want := "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" + if got, _ := body.Attribute("data-out"); got != want { + t.Fatalf("data-out = %q, want %q (bit-for-bit round trip)", got, want) + } +} + +// TestGPUQueueWriteTextureBoundsRejectedCapturedByErrorScope proves a +// data buffer too small for the given copy size is GPU content +// validation, captured by an open error scope, never a synchronous +// throw — mirroring writeBuffer's own out-of-range convention exactly +// (gpuQueueWriteTexture's own doc comment). +func TestGPUQueueWriteTextureBoundsRejectedCapturedByErrorScope(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ size: { width: 4, height: 4 }, format: 'r8uint', usage: GPUTextureUsage.COPY_DST }); + dev.pushErrorScope('validation'); + var threw = false; + try { + dev.queue.writeTexture({ texture: tex }, new Uint8Array(4), {}, { width: 4, height: 4 }); // 4 bytes for a 16-byte copy + } catch (e) { threw = true; } + document.body.setAttribute('data-threw', String(threw)); + return dev.popErrorScope().then(function(err) { + document.body.setAttribute('data-captured-name', err ? err.constructor.name : 'null'); + tex.destroy(); + }); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if skip, _ := body.Attribute("data-result"); skip == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-threw"); got != "false" { + t.Fatalf("data-threw = %q, want %q (an out-of-range writeTexture must never throw synchronously when a scope is open)", got, "false") + } + if got, _ := body.Attribute("data-captured-name"); got != "GPUValidationError" { + t.Fatalf("data-captured-name = %q, want %q", got, "GPUValidationError") + } +} + +// TestCopyTextureToBufferOutOfBoundsRejected proves copyTextureToBuffer's +// own destination-range check is a WebIDL-level argument problem (a +// thrown TypeError), mirroring copyBufferToBuffer's own convention for +// the same kind of bounds mismatch exactly (gpuCopyTextureToBuffer's own +// doc comment) rather than GPU content validation. +func TestCopyTextureToBufferOutOfBoundsRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ size: { width: 4, height: 4 }, format: 'r8uint', usage: GPUTextureUsage.COPY_SRC }); + var readback = dev.createBuffer({ size: 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); // too small for a 16-byte copy + var encoder = dev.createCommandEncoder(); + try { + encoder.copyTextureToBuffer({ texture: tex }, { buffer: readback }, { width: 4, height: 4 }); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + tex.destroy(); + readback.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q", got, "threw:TypeError") + } +} + +// TestGPUCreateTextureMissingSizeRejected proves a descriptor with no +// "size" key at all — gpuReadExtent's own non-object input (v is +// undefined, not a *goja.Object) — resolves to the zero extent rather +// than panicking on a nil object, and that zero extent is then rejected +// by createTexture's own size.width/height>0 check, exactly like an +// explicit zero size would be. +func TestGPUCreateTextureMissingSizeRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + try { + dev.createTexture({ format: 'r8uint', usage: GPUTextureUsage.COPY_SRC }); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q", got, "threw:TypeError") + } +} + +// TestGPUQueueWriteTextureNumericOriginTreatedAsZero proves +// gpuIsZeroOrigin's own non-object branch: an origin that is not an +// object at all (here the plain number 0, never a dict or sequence) is +// not a *goja.Object, so the type assertion fails and gpuIsZeroOrigin +// reports it as the zero origin by default, letting the write through — +// the write must still land for real, not be silently skipped. +func TestGPUQueueWriteTextureNumericOriginTreatedAsZero(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ + size: { width: 4, height: 4 }, + format: 'r8uint', + usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC, + }); + var pixels = new Uint8Array([1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]); + dev.queue.writeTexture({ texture: tex, origin: 0 }, pixels, {}, { width: 4, height: 4 }); + + var encoder = dev.createCommandEncoder(); + var readback = dev.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); + encoder.copyTextureToBuffer({ texture: tex }, { buffer: readback }, { width: 4, height: 4 }); + dev.queue.submit([encoder.finish()]); + + return readback.mapAsync(GPUMapMode.READ).then(function() { + var out = Array.from(new Uint8Array(readback.getMappedRange())); + document.body.setAttribute('data-out', out.join(',')); + readback.destroy(); + tex.destroy(); + }); + }, function(e) { + document.body.setAttribute('data-result', 'REJECTED:' + e); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if got, _ := body.Attribute("data-result"); got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } else if got != "" { + t.Fatalf("data-result = %q, want empty (a numeric origin of 0 must be accepted as the zero origin)", got) + } + want := "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" + if got, _ := body.Attribute("data-out"); got != want { + t.Fatalf("data-out = %q, want %q", got, want) + } +} + +// TestGPUQueueWriteTextureNonZeroPartialOriginRejected proves +// gpuIsZeroOrigin's own per-field default (a missing x/y/z/0/1/2 key +// defaults to 0) does not also zero out a field that IS present: an +// origin object giving only "x": 5 (y and z both absent, so both must +// default to 0 on their own) must still read back as non-zero overall +// and be rejected — a defaulting bug that zeroed every field +// unconditionally would wrongly let this through as the zero origin. +func TestGPUQueueWriteTextureNonZeroPartialOriginRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ + size: { width: 4, height: 4 }, + format: 'r8uint', + usage: GPUTextureUsage.COPY_DST, + }); + try { + dev.queue.writeTexture({ texture: tex, origin: { x: 5 } }, new Uint8Array(16), {}, { width: 4, height: 4 }); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + tex.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q", got, "threw:TypeError") + } +} + +// TestGPUQueueWriteTextureOriginMissingFieldsDefaultToZero proves +// gpuIsZeroOrigin's own missing-key default (obj.Get(k) genuinely +// returns Go nil, not a JS "undefined" Value, once a key is absent from +// both the object and its whole prototype chain) for every key besides +// the one given explicitly: an origin of only `{x: 0}` must still walk +// y, z, "0", "1" and "2" — each one genuinely missing — through that +// same default, never short-circuiting before reaching them the way +// `{x: 5}` above does. A guard that stopped defaulting those missing +// keys would call ToInteger() on a nil Value and crash; this must +// instead succeed exactly like the explicit numeric-0 origin case. +func TestGPUQueueWriteTextureOriginMissingFieldsDefaultToZero(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ + size: { width: 4, height: 4 }, + format: 'r8uint', + usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC, + }); + var pixels = new Uint8Array([1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]); + dev.queue.writeTexture({ texture: tex, origin: { x: 0 } }, pixels, {}, { width: 4, height: 4 }); + + var encoder = dev.createCommandEncoder(); + var readback = dev.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); + encoder.copyTextureToBuffer({ texture: tex }, { buffer: readback }, { width: 4, height: 4 }); + dev.queue.submit([encoder.finish()]); + + return readback.mapAsync(GPUMapMode.READ).then(function() { + var out = Array.from(new Uint8Array(readback.getMappedRange())); + document.body.setAttribute('data-out', out.join(',')); + readback.destroy(); + tex.destroy(); + }); + }, function(e) { + document.body.setAttribute('data-result', 'REJECTED:' + e); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if got, _ := body.Attribute("data-result"); got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } else if got != "" { + t.Fatalf("data-result = %q, want empty (an origin of {x: 0}, with y/z/sequence keys entirely absent, must default every missing key to 0 and be accepted as the zero origin)", got) + } + want := "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" + if got, _ := body.Attribute("data-out"); got != want { + t.Fatalf("data-out = %q, want %q", got, want) + } +} + +// TestGPUBeginRenderPassClearValueDictFormVisibleWithoutDraw proves +// gpuReadColor's own dict-keyed branch ("r" present selects {r,g,b,a} +// over the [0,1,2,3] sequence form) by never covering the target with +// any draw at all — the clear colour is the ONLY thing that reaches the +// pixels, unlike every other render-pass test above where draws paint +// over it. Choosing the wrong branch here would read undefined +// "0"/"1"/"2"/"3" properties instead and land a different value (or +// none) in the target. +func TestGPUBeginRenderPassClearValueDictFormVisibleWithoutDraw(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ + size: { width: 4, height: 4 }, + format: 'r8uint', + usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, + }); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 9, g: 9, b: 9, a: 9 } }], + }); + pass.end(); + + var readback = dev.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); + encoder.copyTextureToBuffer({ texture: tex }, { buffer: readback }, { width: 4, height: 4 }); + dev.queue.submit([encoder.finish()]); + + return readback.mapAsync(GPUMapMode.READ).then(function() { + var out = Array.from(new Uint8Array(readback.getMappedRange())); + document.body.setAttribute('data-out', out.join(',')); + readback.destroy(); + tex.destroy(); + }); + }, function(e) { + document.body.setAttribute('data-result', 'REJECTED:' + e); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if got, _ := body.Attribute("data-result"); got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } else if got != "" { + t.Fatalf("data-result = %q, want empty (no rejection)", got) + } + want := make([]string, 16) + for i := range want { + want[i] = "9" + } + got, _ := body.Attribute("data-out") + if got != strings.Join(want, ",") { + t.Fatalf("data-out = %q, want %q (the dict-form clearValue must be read as {r,g,b,a}, not the sequence form)", got, strings.Join(want, ",")) + } +} + +// TestGPUBeginRenderPassClearValueNonObjectDefaultsToZero proves +// gpuReadColor's own non-object branch: a clearValue that is not an +// object at all (here the plain number 5, never a dict or sequence) is +// not a *goja.Object, so the type assertion fails and gpuReadColor +// returns the zero colour by default, rather than panicking on a nil +// object or silently using 5. Same no-draw trick as the dict-form test +// above makes the actual clear colour observable. +func TestGPUBeginRenderPassClearValueNonObjectDefaultsToZero(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ + size: { width: 4, height: 4 }, + format: 'r8uint', + usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, + }); + var encoder = dev.createCommandEncoder(); + var pass = encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: 5 }], + }); + pass.end(); + + var readback = dev.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); + encoder.copyTextureToBuffer({ texture: tex }, { buffer: readback }, { width: 4, height: 4 }); + dev.queue.submit([encoder.finish()]); + + return readback.mapAsync(GPUMapMode.READ).then(function() { + var out = Array.from(new Uint8Array(readback.getMappedRange())); + document.body.setAttribute('data-out', out.join(',')); + readback.destroy(); + tex.destroy(); + }); + }, function(e) { + document.body.setAttribute('data-result', 'REJECTED:' + e); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if got, _ := body.Attribute("data-result"); got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } else if got != "" { + t.Fatalf("data-result = %q, want empty (no rejection)", got) + } + want := make([]string, 16) + for i := range want { + want[i] = "0" + } + got, _ := body.Attribute("data-out") + if got != strings.Join(want, ",") { + t.Fatalf("data-out = %q, want %q (a non-object clearValue must fall back to the zero colour, not 5)", got, strings.Join(want, ",")) + } +} + +// TestGPUBeginRenderPassMissingRenderAttachmentUsageCapturedByErrorScope +// proves beginRenderPass's own panicValidation (a texture not created +// with RENDER_ATTACHMENT usage) is real GPU content validation, captured +// by an open error scope exactly like TestDrawWithoutPipelineCapturedByErrorScope's +// own draw() case — never a raw, unrecovered panic. Before this fix, +// beginRenderPass's registration never wrapped the call in gpuGuard (the +// one mechanism that recovers a panicValidation panic at all), so this +// exact script crashed the whole process instead of rejecting cleanly. +func TestGPUBeginRenderPassMissingRenderAttachmentUsageCapturedByErrorScope(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ size: { width: 4, height: 4 }, format: 'r8uint', usage: GPUTextureUsage.TEXTURE_BINDING }); + var encoder = dev.createCommandEncoder(); + dev.pushErrorScope('validation'); + var threw = false; + try { + encoder.beginRenderPass({ + colorAttachments: [{ view: tex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 } }], + }); + } catch (e) { threw = true; } + document.body.setAttribute('data-threw', String(threw)); + return dev.popErrorScope().then(function(err) { + document.body.setAttribute('data-captured-name', err ? err.constructor.name : 'null'); + tex.destroy(); + }); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if skip, _ := body.Attribute("data-result"); skip == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-threw"); got != "false" { + t.Fatalf("data-threw = %q, want %q (a texture missing RENDER_ATTACHMENT usage is GPU content validation, never a synchronous throw)", got, "false") + } + if got, _ := body.Attribute("data-captured-name"); got != "GPUValidationError" { + t.Fatalf("data-captured-name = %q, want %q", got, "GPUValidationError") + } +} + +// TestGPUCopyTextureToBufferRegistrationGuarded proves +// copyTextureToBuffer's own registration is wrapped the same way as +// beginRenderPass's — a defensive, consistency fix (engine#447 review) +// so any future panicValidation added inside gpuCopyTextureToBuffer is +// caught exactly like every other recording call, instead of silently +// depending on nobody ever adding one. The out-of-bounds case already +// throws a TypeError (see TestCopyTextureToBufferOutOfBoundsRejected) and +// must keep doing so — gpuGuard only ever recovers a panicValidation +// panic, never an ordinary TypeError, so wrapping it must not change that +// behaviour. +func TestGPUCopyTextureToBufferRegistrationGuarded(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var tex = dev.createTexture({ size: { width: 4, height: 4 }, format: 'r8uint', usage: GPUTextureUsage.COPY_SRC }); + var readback = dev.createBuffer({ size: 2, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); + var encoder = dev.createCommandEncoder(); + var threw = false; + try { + encoder.copyTextureToBuffer({ texture: tex }, { buffer: readback }, { width: 4, height: 4 }); + } catch (e) { threw = (e instanceof TypeError); } + document.body.setAttribute('data-threw-typeerror', String(threw)); + tex.destroy(); + readback.destroy(); + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + body := dom.Find(root, "body") + if skip, _ := body.Attribute("data-result"); skip == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got, _ := body.Attribute("data-threw-typeerror"); got != "true" { + t.Fatalf("data-threw-typeerror = %q, want %q (an out-of-bounds copy must still throw a TypeError synchronously after wrapping the registration in gpuGuard)", got, "true") + } +} + +// TestGPUReadExtentMissingHeightDefaultsToOne proves gpuReadExtent's dict +// form (engine#447 review bug #2): height is spec-optional +// (GPUExtent3DDict.height defaults to 1) and, before this fix, +// obj.Get("height") returned a genuine Go nil for the missing property — +// calling ToInteger() on it panicked instead of defaulting. This is a +// plain Go-level unit test (no GPU/JS harness needed): before the fix it +// crashed this whole test binary with an unrecovered nil-pointer panic, +// not merely fail an assertion. +func TestGPUReadExtentMissingHeightDefaultsToOne(t *testing.T) { + vm := goja.New() + obj := vm.NewObject() + obj.Set("width", 4) + got := gpuReadExtent(obj) + want := gpuExtent{w: 4, h: 1, d: 1} + if got != want { + t.Fatalf("gpuReadExtent({width:4}) = %+v, want %+v", got, want) + } +} + +// TestGPUReadExtentSequenceFormMissingTrailingDefaultsToOne is +// gpuReadExtent's sequence-form counterpart: obj.Get("1")/obj.Get("2") +// absent (a short array) must default to 1, not nil-deref. +func TestGPUReadExtentSequenceFormMissingTrailingDefaultsToOne(t *testing.T) { + vm := goja.New() + obj := vm.NewObject() + obj.Set("0", 4) + got := gpuReadExtent(obj) + want := gpuExtent{w: 4, h: 1, d: 1} + if got != want { + t.Fatalf("gpuReadExtent([4]) = %+v, want %+v", got, want) + } +} + +// TestGPUReadColorMissingGBADefaultToZero proves gpuReadColor's dict +// form: g/b/a are spec-optional in this codebase's own "non-crashing +// default over strict WebIDL enforcement" convention (gpuReadColor's own +// doc comment) — obj.Get("g") absent must default to 0, not nil-deref. +func TestGPUReadColorMissingGBADefaultToZero(t *testing.T) { + // A deleted guard at webgpu.go:1693 turns this missing-property read + // into a nil-pointer panic that would crash the whole test binary + // before the assertion below ever ran, masking the result (mutsweep + // would read it as "caught by panic", luck rather than a test). This + // local recover converts that crash into an ordinary failed + // assertion, same as any other wrong value. + defer func() { + if r := recover(); r != nil { + t.Fatalf("gpuReadColor({r:5}) panicked: %v", r) + } + }() + vm := goja.New() + obj := vm.NewObject() + obj.Set("r", 5.0) + got := gpuReadColor(obj) + want := [4]float64{5, 0, 0, 0} + if got != want { + t.Fatalf("gpuReadColor({r:5}) = %v, want %v", got, want) + } +} + +// TestGPUReadColorSequenceFormMissingTrailingDefaultsToZero is +// gpuReadColor's sequence-form counterpart. +func TestGPUReadColorSequenceFormMissingTrailingDefaultsToZero(t *testing.T) { + // Same reasoning as TestGPUReadColorMissingGBADefaultToZero's own + // recover: this exercises the same gpuGetFloat guard (webgpu.go:1693), + // just through the sequence-form branch's "1"/"2"/"3" keys. + defer func() { + if r := recover(); r != nil { + t.Fatalf("gpuReadColor([5]) panicked: %v", r) + } + }() + vm := goja.New() + obj := vm.NewObject() + obj.Set("0", 5.0) + got := gpuReadColor(obj) + want := [4]float64{5, 0, 0, 0} + if got != want { + t.Fatalf("gpuReadColor([5]) = %v, want %v", got, want) + } +} + +// TestGPUReadColorExplicitUndefinedGDefaultsToZero is +// TestGPUReadColorMissingGBADefaultToZero's explicit-undefined +// counterpart (engine#447 review, mutsweep gap on gpuGetFloat's +// `v == nil || goja.IsUndefined(v)` guard at webgpu.go:1693): a property +// set to the literal value `undefined` is NOT the Go nil that a merely +// absent property produces — obj.Get("g") instead returns a non-nil +// goja.Value for which goja.IsUndefined(v) is true. Without the +// IsUndefined half of the guard, gpuGetFloat would call ToFloat() on +// that value instead of defaulting to 0. vm.NewObject()+Set never +// produces this shape (Set always assigns a concrete value), so this +// needs a real script evaluation to get a property whose value is +// `undefined` rather than one that was never set. +func TestGPUReadColorExplicitUndefinedGDefaultsToZero(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("gpuReadColor({r:5, g:undefined, a:2.5}) panicked: %v", r) + } + }() + vm := goja.New() + v, err := vm.RunString(`({r: 5, g: undefined, a: 2.5})`) + if err != nil { + t.Fatalf("RunString: %v", err) + } + got := gpuReadColor(v) + want := [4]float64{5, 0, 0, 2.5} + if got != want { + t.Fatalf("gpuReadColor({r:5, g:undefined, a:2.5}) = %v, want %v", got, want) + } +} + +// TestGPUCreateTextureMissingUsageRejected proves createTexture's own +// usage read (required, no spec default) now throws a clean TypeError +// instead of nil-deref-panicking the whole process when usage is +// omitted. +func TestGPUCreateTextureMissingUsageRejected(t *testing.T) { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + try { + dev.createTexture({ size: { width: 4, height: 4 }, format: 'r8uint' }); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("data-result = %q, want %q", got, "threw:TypeError") + } +} + +// TestGPUCreateRenderPipelineMissingVertexFieldsRejected proves +// createRenderPipeline's own vertex.buffers[] reads (arrayStride, +// attributes[].format, attributes[].shaderLocation, attributes[].offset +// — all required, no spec default) now throw a clean TypeError instead +// of nil-deref-panicking when any one of them is omitted. +func TestGPUCreateRenderPipelineMissingVertexFieldsRejected(t *testing.T) { + cases := []string{ + // missing arrayStride + `{ buffers: [{ attributes: [{ format: 'float32x2', shaderLocation: 0, offset: 0 }] }] }`, + // missing attribute format + `{ buffers: [{ arrayStride: 8, attributes: [{ shaderLocation: 0, offset: 0 }] }] }`, + // missing shaderLocation + `{ buffers: [{ arrayStride: 8, attributes: [{ format: 'float32x2', offset: 0 }] }] }`, + // missing offset + `{ buffers: [{ arrayStride: 8, attributes: [{ format: 'float32x2', shaderLocation: 0 }] }] }`, + } + for _, vertexJS := range cases { + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var mod = dev.createShaderModule({ code: `+"`"+renderWGSL+"`"+` }); + try { + dev.createRenderPipeline({ + vertex: Object.assign({ module: mod }, `+vertexJS+`), + fragment: { module: mod, targets: [{ format: 'r8uint' }] }, + }); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("script failed: %+v logs=%v", res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("case %q: data-result = %q, want %q", vertexJS, got, "threw:TypeError") + } + } +} + +// TestGPUCreateRenderPipelineUnsupportedRenderOptionsRejected is +// engine#447 review bug #8: a whole set of GPURenderPipelineDescriptor +// fields (primitive.cullMode/frontFace/unclippedDepth, multisample.count/ +// alphaToCoverageEnabled, vertex.constants, fragment.constants, +// fragment.targets[0].blend/writeMask, vertex.buffers[].stepMode) were +// read NOWHERE in gpuCreateRenderPipeline before this fix — go-macos/ +// metal's own RenderPipelineDescriptor simply has no field for most of +// them, so a caller asking for back-face culling, 4x MSAA, an instance- +// stepped vertex buffer, alpha blending or a partial colour write mask +// got a pipeline that silently behaved as if none of that had been +// asked for, with no error anywhere — exactly the kind of "unsupported +// option accepted and ignored" shape bug #6/#7 already fixed for draw +// validation and pass lifecycle. Each case here sets exactly one such +// option to a non-default value and must now be a named, synchronous +// TypeError instead. +func TestGPUCreateRenderPipelineUnsupportedRenderOptionsRejected(t *testing.T) { + base := `{ + layout: 'auto', + vertex: Object.assign({ module: mod, entryPoint: 'vmain', buffers: [{ arrayStride: 8, attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] }] }, VEXTRA), + fragment: Object.assign({ module: mod, entryPoint: 'fmain', targets: [Object.assign({ format: 'r8uint' }, TEXTRA)] }, FEXTRA), + }` + cases := []struct { + name string + prim string // primitive object literal, or "" to omit + ms string // multisample object literal, or "" to omit + vextra string // extra vertex.* fields, or "{}" + fextra string // extra fragment.* fields, or "{}" + textra string // extra fragment.targets[0].* fields, or "{}" + }{ + {name: "cullMode", prim: `{ cullMode: 'back' }`}, + {name: "frontFace", prim: `{ frontFace: 'cw' }`}, + {name: "unclippedDepth", prim: `{ unclippedDepth: true }`}, + {name: "multisample.count", ms: `{ count: 4 }`}, + {name: "multisample.alphaToCoverageEnabled", ms: `{ alphaToCoverageEnabled: true }`}, + {name: "vertex.constants", vextra: `{ constants: { x: 1 } }`}, + {name: "fragment.constants", fextra: `{ constants: { x: 1 } }`}, + {name: "fragment.targets[0].blend", textra: `{ blend: { color: { srcFactor: 'one', dstFactor: 'zero', operation: 'add' }, alpha: { srcFactor: 'one', dstFactor: 'zero', operation: 'add' } } }`}, + {name: "fragment.targets[0].writeMask", textra: `{ writeMask: 0x1 }`}, + {name: "vertex.buffers[].stepMode", vextra: `{ buffers: [{ arrayStride: 8, stepMode: 'instance', attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] }] }`}, + } + for _, c := range cases { + prim, ms, vextra, fextra, textra := c.prim, c.ms, c.vextra, c.fextra, c.textra + if vextra == "" { + vextra = "{}" + } + if fextra == "" { + fextra = "{}" + } + if textra == "" { + textra = "{}" + } + descJS := strings.NewReplacer( + "VEXTRA", vextra, + "FEXTRA", fextra, + "TEXTRA", textra, + ).Replace(base) + if prim != "" { + descJS = strings.Replace(descJS, "layout: 'auto',", "layout: 'auto', primitive: "+prim+",", 1) + } + if ms != "" { + descJS = strings.Replace(descJS, "layout: 'auto',", "layout: 'auto', multisample: "+ms+",", 1) + } + root, logs, res := runWebGPU(t, page(` + navigator.gpu.requestAdapter().then(function(a) { + if (a === null) { document.body.setAttribute('data-result', 'skip-no-gpu'); return; } + return a.requestDevice(); + }).then(function(dev) { + if (!dev) return; + var mod = dev.createShaderModule({ code: `+"`"+renderWGSL+"`"+` }); + try { + dev.createRenderPipeline(`+descJS+`); + document.body.setAttribute('data-result', 'should-have-thrown'); + } catch (e) { + document.body.setAttribute('data-result', 'threw:' + e.name); + } + }); + `)) + if res.ScriptsFailed != 0 { + t.Fatalf("case %q: script failed: %+v logs=%v", c.name, res, logs) + } + got, _ := dom.Find(root, "body").Attribute("data-result") + if got == "skip-no-gpu" { + t.Skip("no usable GPU on this machine/platform") + } + if got != "threw:TypeError" { + t.Fatalf("case %q: data-result = %q, want %q (this render option must be a named rejection, not silently ignored)", c.name, got, "threw:TypeError") + } + } +} diff --git a/js/window.go b/js/window.go index 83b6df1..f45bb95 100644 --- a/js/window.go +++ b/js/window.go @@ -101,6 +101,7 @@ func (b *binder) install() { g.Set("GPUShaderStage", b.newGPUShaderStage()) g.Set("GPUBufferUsage", b.newGPUBufferUsage()) g.Set("GPUMapMode", b.newGPUMapMode()) + g.Set("GPUTextureUsage", b.newGPUTextureUsage()) } // __webengineDone(value) — opt-in (Options.EnableDoneSignal), installed // as a global only when set, so a caller not using this feature sees no diff --git a/js/worker.go b/js/worker.go index 943f099..73ddaf3 100644 --- a/js/worker.go +++ b/js/worker.go @@ -187,6 +187,7 @@ func (w *jsWorker) installWorkerGlobals() { g.Set("GPUShaderStage", wb.newGPUShaderStage()) g.Set("GPUBufferUsage", wb.newGPUBufferUsage()) g.Set("GPUMapMode", wb.newGPUMapMode()) + g.Set("GPUTextureUsage", wb.newGPUTextureUsage()) } // Nested Worker (HTML Standard §10.2.6 permits it; confirmed needed // directly by go-wasmcontainers: their own engine spawns workers from diff --git a/wgslmsl/expr.go b/wgslmsl/expr.go index 806dff8..016b896 100644 --- a/wgslmsl/expr.go +++ b/wgslmsl/expr.go @@ -56,6 +56,11 @@ func (tr *translator) expr(e wgsl.Expr) (string, error) { } return "false", nil case *wgsl.Ident: + if po, ok := tr.info.Objects[x].(*wgsl.ParamObj); ok { + if rename, ok := tr.paramRename[po]; ok { + return rename, nil + } + } return identMSL(x.Name), nil case *wgsl.Paren: inner, err := tr.expr(x.X) @@ -257,11 +262,36 @@ func (tr *translator) resourceOf(e wgsl.Expr) (*wgsl.VarObj, bool) { return vo, tracked } -// memberExpr emits x.name: a vector swizzle (the only member-access shape -// this package's bounded scope supports — no user structs). +// memberExpr emits x.name: a vector swizzle, or (engine#415, M7) a WGSL +// struct field access on the ONE user struct type this package ever +// recognizes — an entry point's own vertex/fragment output struct +// (render.go, tr.outputStructType) — rejected for any other struct, since +// every other place in this package still has no story for a user struct +// at all. A fragment entry point's struct-typed INPUT parameter is a +// separate case, checked first: it is never emitted as a real MSL struct +// (translator.go's own inputFlatten doc comment says why), so `in.field` +// is resolved straight to the flattened bare parameter identifier +// stageEntryParams already emitted for it, before either the struct-field +// or swizzle cases below are even considered. func (tr *translator) memberExpr(m *wgsl.Member) (string, error) { + if id, ok := m.X.(*wgsl.Ident); ok { + if po, ok := tr.info.Objects[id].(*wgsl.ParamObj); ok { + if flat, ok := tr.inputFlatten[po]; ok { + if name, ok := flat[m.Name]; ok { + return name, nil + } + } + } + } + if _, ok := tr.exprType(m.X).(*wgsl.StructType); ok { + x, err := tr.expr(m.X) + if err != nil { + return "", err + } + return x + "." + identMSL(m.Name), nil + } if !isSwizzle(m.Name) { - return "", unsupported("member access %q (only vector swizzles are supported; no user structs)", m.Name) + return "", unsupported("member access %q (only vector swizzles and a recognized entry-point struct field are supported)", m.Name) } x, err := tr.expr(m.X) if err != nil { @@ -404,6 +434,62 @@ func (tr *translator) arrayLengthExpr(c *wgsl.Call) (string, error) { return fmt.Sprintf("_sizes.s%d", b.SizesIndex), nil } +// textureLoadExpr implements WGSL's textureLoad(t, coords, level) for the +// one texture shape this package resolves at all — a non-arrayed +// texture_2d resource (resolveResources's own ASHandle case, engine +// #415 M7). Metal's own equivalent is the texture's .read(coords, level) +// method, which always takes a uint2 coordinate and a uint level +// regardless of which overload the WGSL call used — go-gfx/wgsl's own +// texSigs offers both an i32 and a u32 coordinate/level overload for +// textureLoad (builtins_custom.go:351-369) — so this always emits a uint +// cast, exactly value-preserving for the non-negative coordinates a real +// sampled-2D read ever uses. +func (tr *translator) textureLoadExpr(c *wgsl.Call) (string, error) { + // The first argument's own tracked-resource / BindingTexture-kind checks + // that used to live here are dead: resolveResources validates every + // resource reachable from this entry (directly or through a helper) + // before any body statement is translated, so a global reference is + // always tracked and, for a handle resource, always BindingTexture (the + // one shape resolveResources' own ASHandle case accepts — anything else + // makes resolveResources itself fail first). The checker's own textureLoad + // signature check already requires c.Args[0]'s static type to be a + // texture, so it can never resolve to anything else. The two non-global + // shapes a texture value could otherwise reach here through are masked + // the same way: a `let` alias needs mslType on its own declared/inferred + // type to emit the local declaration at all (mslType rejects every + // texture type), and a helper function's texture-typed PARAMETER needs + // mslType(p.Type) in emitHelperFuncs before the helper's body — where this + // call would be — is ever translated. Hand-verified by mutation (engine#447): + // deleting each check left the guard unreachable, never SURVIVED. + // + // An "if len(c.Args) != 3" arity check used to live here too, also + // dead: go-gfx/wgsl's own overload table (builtins_custom.go, the + // "textureLoad" case) ties exactly one arity to each texture Kind — + // 3 for TexSampled/TexDepth/TexMultisampled (non-arrayed), 2 for + // TexStorage, 4 only for an arrayed TexSampled — and + // resolveResources' own ASHandle case accepts exactly one Kind/Dim/ + // Arrayed combination, the one whose own arity is 3 (Kind==TexSampled, + // Dim==Dim2D, !Arrayed). Every other combination that could reach + // this call with a different arity is already rejected before the + // body is ever translated: either by resolveResources itself (a + // checker-valid 4-argument call on an arrayed texture_2d_array + // resource fails resolveResources' Dim/Arrayed guard on sight, before + // this call is reached) or by the checker (a wrong-arity call on the + // one resource type resolveResources accepts, texture_2d, has no + // matching overload at all). Hand-verified both ways (engine#447): + // neither reaches this line. + tex, _ := tr.expr(c.Args[0]) + coords, err := tr.expr(c.Args[1]) + if err != nil { + return "", err + } + level, err := tr.expr(c.Args[2]) + if err != nil { + return "", err + } + return fmt.Sprintf("%s.read(uint2(%s), uint(%s))", tex, coords, level), nil +} + func (tr *translator) callExpr(c *wgsl.Call) (string, error) { if mslName, ok := atomicBuiltinFn[c.Fn.Name]; ok { return tr.atomicCallExpr(mslName, c) @@ -414,6 +500,9 @@ func (tr *translator) callExpr(c *wgsl.Call) (string, error) { if c.Fn.Name == "bitcast" { return tr.bitcastExpr(c) } + if c.Fn.Name == "textureLoad" { + return tr.textureLoadExpr(c) + } args := make([]string, len(c.Args)) for i, a := range c.Args { s, err := tr.expr(a) @@ -424,7 +513,22 @@ func (tr *translator) callExpr(c *wgsl.Call) (string, error) { } joined := strings.Join(args, ", ") - if _, isType := tr.info.TypeSpecs[c.Fn]; isType { + if t, isType := tr.info.TypeSpecs[c.Fn]; isType { + // A call to the recognized output struct's own constructor + // (`VertexOutput(args...)`, engine#415 M7) — the one user struct + // this package ever recognizes (render.go, tr.outputStructType) — + // is a brace-init of the synthesized MSL struct, positional args + // in the struct's own declared field order (the same order + // emitIOStruct emits its fields in, both derived from the same + // underlying *wgsl.StructType). Every other struct constructor + // call is still rejected, matching mslType's own "no user + // structs" scope. + if st, ok := derefType(t).(*wgsl.StructType); ok { + if tr.outputStructType == nil || st != tr.outputStructType { + return "", unsupported("constructing struct type %s", st.String()) + } + return fmt.Sprintf("%s{%s}", tr.outputStructName, joined), nil + } resultType := tr.exprType(c) typeMSL, err := mslType(resultType) if err != nil { diff --git a/wgslmsl/render.go b/wgslmsl/render.go new file mode 100644 index 0000000..ddc85a4 --- /dev/null +++ b/wgslmsl/render.go @@ -0,0 +1,545 @@ +// Copyright (c) the go-webengine/engine authors. +// SPDX-License-Identifier: BSD-3-Clause + +package wgslmsl + +import ( + "fmt" + "sort" + "strings" + + "github.com/go-gfx/wgsl" +) + +// TranslateRender translates src's @vertex and @fragment entry points to +// Metal Shading Language — the render-pipeline counterpart to Translate's +// own @compute path, added for engine#415 (WebGPU roadmap M7: textures and +// render pipelines), under the SAME bounded-scope discipline: an +// unsupported WGSL shape is a named rejection (translateError), never a +// silently wrong translation. +// +// Honest limits, confirmed from the go-gfx/wgsl v0.4.0 source +// (builtins_custom.go, check.go, types.go) rather than assumed: +// - Vertex inputs: a @builtin(vertex_index)/@builtin(instance_index) +// scalar stays its own bare parameter; a @location(N) scalar/vector +// attribute (declared as an individual parameter or as a struct +// parameter's field, either way) is instead GROUPED into one +// synthesized [[stage_in]] struct (stageEntryParams) — confirmed the +// opposite, individually-parameterized shape this package's @compute +// path uses is invalid MSL for a vertex entry's own [[attribute(N)]] +// inputs specifically ("invalid type ... for input declaration in a +// vertex function" from the real compiler). +// - Vertex/fragment outputs: either a user-declared struct mixing +// @builtin(position) and @location(N) fields, or a bare (non-struct) +// single value — but ONLY in the one shape Metal gives an IMPLICIT +// attribute to, since a non-struct return type has no attribute syntax +// at all in MSL (measured directly against the real compiler: every +// spelling tried — after the parameter list, between the return type +// and the function name, before the return type — was rejected with +// "attribute cannot be applied to types"; only a struct FIELD's own +// attribute compiles). That leaves exactly `-> @builtin(position) +// vec4` for a vertex entry and `-> @location(0) T` for a fragment +// entry as viable bare outputs (Metal's own implicit default for each +// stage); any other bare output (a vertex entry without position, a +// fragment @location(N) for N != 0) is rejected — a struct return is +// always available for those instead. +// - Fragment inputs mirror a vertex entry's own output struct fields in +// shape (one @location(N) or @builtin(position) per field), but a +// @builtin(position) input stays its own bare parameter while every +// @location(N) varying is GROUPED into its own synthesized +// [[stage_in]] struct — a different struct TYPE from the vertex +// entry's output struct, never shared between the two MSL functions. +// Confirmed the opposite, individually-parameterized shape *compiles* +// but silently never receives the rasterizer-interpolated value (an +// actual render + pixel-readback test, not just a compile check, +// caught this: every pixel read back the clear colour, as if the +// quad never rendered). +// - A fragment entry point may read ONE resource kind beyond uniform/ +// storage: a non-arrayed `texture_2d` resource, through +// textureLoad only (no sampler, no textureSample*) — go-macos/metal's +// RenderEncoder has no vertex-stage texture binding at all, so the +// same resource in a @vertex entry is rejected. +// - No runtime-sized storage array in either stage (this package's own +// bounds-check machinery, Result.SizeMetalIndex, is a @compute-only +// concept; a render pipeline's own resources are small, fixed-size +// uniforms/textures in every confirmed real shape so far). +// - Exactly the same struct restriction as Translate's own @compute +// path otherwise: the ONE struct type ever recognized is an entry +// point's own return-type struct (see mslTypeTR, memberExpr, +// callExpr's struct-constructor case) — no other user struct, and a +// struct-typed INPUT parameter (a fragment entry taking the vertex +// stage's own output struct) is never emitted as a real MSL struct at +// all: each field becomes its own flattened, individually decorated +// scalar/vector parameter (stageEntryParams, tr.inputFlatten) — doing +// otherwise would need one MSL struct type shared, by C type +// identity, between two independently generated MSL functions, which +// this package deliberately avoids. +type RenderOptions struct { + // VertexEntryPoint and FragmentEntryPoint select which @vertex/ + // @fragment entry point to translate when the module declares more + // than one of that stage. Empty selects the module's only entry point + // of that stage (an error if there is more than one or none). + VertexEntryPoint, FragmentEntryPoint string +} + +// VertexInputVar is one @location vertex-stage input this translation +// resolved — what the host (a later js/webgpu.go PR) needs to build a +// matching MTLVertexDescriptor attribute: NComponents and ScalarKind +// together pick the MTLVertexFormat (e.g. 4 components of KF32 -> +// float4), Location the WGSL/MSL [[attribute(N)]] index. +type VertexInputVar struct { + Location int + NComponents int + ScalarKind wgsl.ScalarKind +} + +// RenderResult is a successful TranslateRender. +type RenderResult struct { + VertexMSL, FragmentMSL string + VertexEntryPointName, FragmentEntryPointName string + // VertexInputs is every @location vertex-stage input, in ep.Inputs + // order, for the host's own MTLVertexDescriptor. + VertexInputs []VertexInputVar + // VertexBindings and FragmentBindings are each stage's OWN resolved + // resource bindings (Binding's own doc comment) — two independent + // lists: a vertex and a fragment entry point are two separate MSL + // functions, each with its own [[buffer(N)]]/[[texture(N)]] index + // space, even when both read what is, in WGSL source, "the same" + // module-scope resource. + VertexBindings, FragmentBindings []Binding +} + +// TranslateRender parses, validates (go-gfx/wgsl) and translates src's +// @vertex and @fragment entry points, selected by opts, to two independent +// Metal Shading Language functions. +func TranslateRender(src string, opts RenderOptions) (*RenderResult, error) { + m, err := wgsl.Parse(src) + if err != nil { + return nil, fmt.Errorf("wgslmsl: parse: %w", err) + } + info, errs := wgsl.Check(m) + if err := errs.Err(); err != nil { + return nil, fmt.Errorf("wgslmsl: check: %w", err) + } + + vep, err := findEntryPoint(info, wgsl.StageVertex, opts.VertexEntryPoint, "VertexEntryPoint") + if err != nil { + return nil, err + } + fep, err := findEntryPoint(info, wgsl.StageFragment, opts.FragmentEntryPoint, "FragmentEntryPoint") + if err != nil { + return nil, err + } + + // sharedHelpers is ONE map instance both translators below write into + // and read from, so a helper function called from both the vertex and + // fragment entry is emitted into the combined MSL exactly once — see + // translator.sharedHelpers' own doc comment for why a second, + // unconditional emission is never safe to leave in (engine#447 review + // bug #4). + sharedHelpers := map[*wgsl.FuncObj]bool{} + + vtr := &translator{info: info, sharedHelpers: sharedHelpers} + vMSL, vInputs, err := vtr.translateStageEntry(vep) + if err != nil { + return nil, fmt.Errorf("wgslmsl: vertex entry %q: %w", vep.Name, err) + } + + ftr := &translator{info: info, sharedHelpers: sharedHelpers} + fMSL, _, err := ftr.translateStageEntry(fep) + if err != nil { + return nil, fmt.Errorf("wgslmsl: fragment entry %q: %w", fep.Name, err) + } + + return &RenderResult{ + VertexMSL: vMSL, + FragmentMSL: fMSL, + VertexEntryPointName: identMSL(vep.Name), + FragmentEntryPointName: identMSL(fep.Name), + VertexInputs: vInputs, + VertexBindings: vtr.bindings, + FragmentBindings: ftr.bindings, + }, nil +} + +// findEntryPoint resolves name (or the module's only entry point of stage +// when name is empty) against info.EntryPoints — the RenderOptions +// counterpart to wgslmsl.go's own selectEntryPoint, parameterized by stage +// since TranslateRender needs this done twice (vertex and fragment). +// optField names the RenderOptions field to mention when more than one +// entry point of stage exists, so the error tells the caller exactly what +// to set. +func findEntryPoint(info *wgsl.Info, stage wgsl.Stage, name, optField string) (*wgsl.EntryPoint, error) { + if name != "" { + for _, ep := range info.EntryPoints { + if ep.Name == name { + if ep.Stage != stage { + return nil, fmt.Errorf("wgslmsl: entry point %q is a @%s shader, not @%s", name, ep.Stage, stage) + } + return ep, nil + } + } + return nil, fmt.Errorf("wgslmsl: no entry point named %q", name) + } + var matched []*wgsl.EntryPoint + for _, ep := range info.EntryPoints { + if ep.Stage == stage { + matched = append(matched, ep) + } + } + switch len(matched) { + case 0: + return nil, fmt.Errorf("wgslmsl: module has no @%s entry point", stage) + case 1: + return matched[0], nil + default: + names := make([]string, len(matched)) + for i, ep := range matched { + names[i] = ep.Name + } + sort.Strings(names) + return nil, fmt.Errorf("wgslmsl: module has %d @%s entry points (%s); pass RenderOptions.%s to pick one", len(matched), stage, strings.Join(names, ", "), optField) + } +} + +// vecShape reports t's own component count and scalar kind — for a +// vertex-stage @location input (VertexInputVar), which the host needs to +// pick a matching MTLVertexFormat. t must be a scalar or vector, exactly +// mslType's own "scalars and vectors" scope. +func vecShape(t wgsl.Type) (n int, kind wgsl.ScalarKind, err error) { + switch tt := derefType(t).(type) { + case *wgsl.ScalarType: + return 1, tt.Kind, nil + case *wgsl.VecType: + return tt.N, tt.Elem.Kind, nil + default: + return 0, 0, unsupported("vertex input type %s (only a scalar or vector)", t.String()) + } +} + +// outputIOAttr is io's own MSL output attribute: [[position]] for the +// position builtin, [[color(N)]] for a fragment's @location(N) (Metal's +// own fragment-output attribute, distinct from a vertex/fragment-input +// varying's [[user(locnN)]] — see ioAttr's own use in stageEntryParams for +// the input side of that same @location), or [[user(locnN)]] (plus +// ", flat" when WGSL's own @interpolate(flat) applies — integer-typed +// varyings always carry it, by WGSL's own spec rule, so this never needs +// to special-case the type) for a vertex's @location(N) output. +func outputIOAttr(io wgsl.IOVar, stage wgsl.Stage) (string, error) { + if io.Builtin == "position" { + return "position", nil + } + if io.Builtin != "" { + return "", unsupported("entry point output builtin %q", io.Builtin) + } + // io.Location == nil is unreachable here: go-gfx/wgsl's entryIO (the + // "io-missing" check) already rejects, with a checker ERROR, any entry + // point IO that has neither a @builtin nor a @location — and + // TranslateRender returns before any translation when wgsl.Check reports + // an error. By the time an IOVar with io.Builtin == "" reaches here, + // io.Location is guaranteed non-nil. Hand-verified by mutation + // (engine#447): deleting this check left it unreachable, never SURVIVED. + loc := int(*io.Location) + if stage == wgsl.StageFragment { + return fmt.Sprintf("color(%d)", loc), nil + } + attr := fmt.Sprintf("user(locn%d)", loc) + if io.Interpolate[0] == "flat" { + attr += ", flat" + } + return attr, nil +} + +// emitIOStruct emits the MSL struct backing an entry point's own +// struct-typed return value (translateStageEntry's own tr.outputStructType +// case): one field per ep.Outputs entry, named after its own struct member +// (io.Member) — a bare, non-struct-member output never reaches here at +// all (translateStageEntry's other branch handles that shape directly, no +// synthesized struct involved). +func (tr *translator) emitIOStruct(name string, vars []wgsl.IOVar, stage wgsl.Stage) error { + tr.line("struct %s {", name) + tr.indent++ + for _, io := range vars { + attr, err := outputIOAttr(io, stage) + if err != nil { + return err + } + fieldMSL, err := mslType(io.Type) + if err != nil { + return err + } + tr.line("%s %s [[%s]];", fieldMSL, identMSL(io.Member), attr) + } + tr.indent-- + tr.line("};") + tr.buf.WriteByte('\n') + return nil +} + +// stageEntryParams builds a @vertex/@fragment entry's own MSL parameter +// list: its resources (resourceEntryParams, identical to the @compute +// path), then one parameter per ep.Inputs entry. A builtin +// (vertex_id/instance_id/position) is always its own bare, individually +// decorated parameter — confirmed valid directly against the real Metal +// compiler, no wrapping struct needed. +// +// A @location input, in EITHER stage, is never left as an individual bare +// parameter — confirmed directly against the real compiler, the hard way: +// a bare [[attribute(N)]] vertex parameter is rejected outright ("invalid +// type ... for input declaration in a vertex function"), and a bare +// [[user(locnN)]] fragment parameter *compiles* but silently never +// receives the rasterizer-interpolated value at all (every pixel read back +// the clear colour, as if the draw never happened — exactly the "compiles, +// renders wrong" failure this package's whole bounded-scope discipline +// exists to catch BEFORE it reaches a caller, not just a syntax check). +// Both stages' own @location inputs are instead grouped into ONE +// synthesized MSL struct marked [[stage_in]] (emitted here, right before +// returning) — never the SAME struct between a vertex and fragment entry +// (render.go's own doc comment on why), just the same grouping mechanism +// independently in each. The attribute text differs by stage: +// [[attribute(N)]] for a vertex input, [[user(locnN)]] (with no ", flat" +// — confirmed that qualifier is rejected outright on anything but a real +// struct FIELD, which this is) for a fragment one. +// +// A struct-typed WGSL input's own field (in.Member != "") is never given +// the struct's WGSL name: it gets its own flattened, uniquely-prefixed MSL +// identifier instead (translator.go's own inputFlatten doc comment says +// why), recorded in tr.inputFlatten so memberExpr can translate the body's +// `in.field` access back to it. A @location input declared as a plain +// top-level parameter instead (no enclosing struct to access through +// `in.field`) is recorded in tr.paramRename instead, keyed directly by its +// own ParamObj, since the WGSL body refers to it by a bare identifier. +// registerStageInputAccessor records how a struct-typed entry input's +// FIELD (in.Member != "") must be rewritten inside the function body — +// to accessor, the bare top-level MSL parameter name a builtin +// (vertex_index/instance_index/position) is always emitted as, exactly +// matching the @location branch's own tr.inputFlatten mechanism below. +// Without this, a builtin struct member (e.g. a struct parameter's own +// `@builtin(position) position: vec4` field) left memberExpr no +// registered accessor to translate `in.position` to, so it fell through +// to the generic struct-member case and emitted `in.position` using the +// struct parameter's OWN WGSL identifier — which this function never +// declares as an MSL parameter (it is flattened into bare parameters +// instead), so Metal rejected the generated source outright +// (engine#447 review bug #3). in.Member == "" (a bare top-level builtin +// parameter, not accessed through a struct) needs no rewrite at all, so +// this is a no-op for that case. +func (tr *translator) registerStageInputAccessor(ep *wgsl.EntryPoint, in wgsl.IOVar, accessor string) { + // No "in.Member == \"\": return" guard here (mutsweep flagged its + // absence as unobserved by any test, not a defect: deleted as proven + // dead, not waived). Without it, a bare top-level builtin input (one + // with in.Member == "") still writes a harmless orphan entry, + // tr.inputFlatten[po][""], because go-gfx/wgsl's own IOVar.Param is a + // valid parameter index for every input, struct field or not (its own + // doc comment: "-1 for outputs" only). That entry is never read back: + // memberExpr (expr.go) only ever looks up flat[m.Name] for an actual + // WGSL `x.name` member access, and WGSL's own grammar has no syntax + // for a member access with an empty name, so the "" key can never be + // the one a lookup asks for. + po := ep.Func.Params[in.Param] + if tr.inputFlatten[po] == nil { + tr.inputFlatten[po] = map[string]string{} + } + tr.inputFlatten[po][in.Member] = accessor +} + +func (tr *translator) stageEntryParams(ep *wgsl.EntryPoint) ([]string, []VertexInputVar, error) { + params, err := tr.resourceEntryParams(ep.Resources) + if err != nil { + return nil, nil, err + } + + tr.inputFlatten = map[*wgsl.ParamObj]map[string]string{} + tr.paramRename = map[*wgsl.ParamObj]string{} + var vInputs []VertexInputVar + var stageInFields []string + const stageInVar = "_in" + stageInType := "_" + identMSL(ep.Name) + "In" + + for _, in := range ep.Inputs { + paramMSL, err := tr.mslTypeTR(in.Type) + if err != nil { + return nil, nil, err + } + + switch { + case in.Builtin == "vertex_index": + paramName := identMSL(in.Name) + params = append(params, fmt.Sprintf("%s %s [[vertex_id]]", paramMSL, paramName)) + tr.registerStageInputAccessor(ep, in, paramName) + case in.Builtin == "instance_index": + paramName := identMSL(in.Name) + params = append(params, fmt.Sprintf("%s %s [[instance_id]]", paramMSL, paramName)) + tr.registerStageInputAccessor(ep, in, paramName) + case in.Builtin == "position": + paramName := identMSL(in.Name) + params = append(params, fmt.Sprintf("%s %s [[position]]", paramMSL, paramName)) + tr.registerStageInputAccessor(ep, in, paramName) + case in.Builtin != "": + return nil, nil, unsupported("entry point input builtin %q", in.Builtin) + case in.Location != nil: + loc := int(*in.Location) + var attr string + if ep.Stage == wgsl.StageVertex { + attr = fmt.Sprintf("attribute(%d)", loc) + // vecShape's own error case (anything but a *wgsl.ScalarType or + // *wgsl.VecType) is unreachable here: go-gfx/wgsl's entryIO + // already requires scalarOf(in.Type) != nil for a @location + // input (the "location-type" checker error otherwise), and + // scalarOf itself only ever returns non-nil for exactly those + // two shapes — the same two vecShape switches on. Hand-verified + // by mutation (engine#447): deleting this check left it + // unreachable, never SURVIVED. + n, kind, _ := vecShape(in.Type) + vInputs = append(vInputs, VertexInputVar{Location: loc, NComponents: n, ScalarKind: kind}) + } else { + attr = fmt.Sprintf("user(locn%d)", loc) + if in.Interpolate[0] == "flat" { + attr += ", flat" + } + } + + fieldName := identMSL(in.Name) + po := ep.Func.Params[in.Param] + if in.Member != "" { + fieldName = fmt.Sprintf("_%s_%s", identMSL(po.Name), identMSL(in.Member)) + } + stageInFields = append(stageInFields, fmt.Sprintf("%s %s [[%s]];", paramMSL, fieldName, attr)) + accessor := stageInVar + "." + fieldName + if in.Member != "" { + if tr.inputFlatten[po] == nil { + tr.inputFlatten[po] = map[string]string{} + } + tr.inputFlatten[po][in.Member] = accessor + } else { + tr.paramRename[po] = accessor + } + default: + return nil, nil, unsupported("entry point input %q has neither a builtin nor a @location", in.Name) + } + } + + if len(stageInFields) > 0 { + tr.line("struct %s {", stageInType) + tr.indent++ + for _, f := range stageInFields { + tr.line("%s", f) + } + tr.indent-- + tr.line("};") + tr.buf.WriteByte('\n') + params = append(params, fmt.Sprintf("%s %s [[stage_in]]", stageInType, stageInVar)) + } + + return params, vInputs, nil +} + +// translateStageEntry translates one @vertex or @fragment entry point to +// a complete MSL source file — the render-pipeline counterpart to +// translator.go's own translateEntryPoint, sharing resolveResources, +// emitHelperFuncs and resourceEntryParams with the @compute path, and +// stmtBlock for the body with every other statement/expression kind +// (stmt.go, expr.go), under the exact same bounded-scope rejections. +func (tr *translator) translateStageEntry(ep *wgsl.EntryPoint) (string, []VertexInputVar, error) { + if err := tr.resolveResources(ep); err != nil { + return "", nil, err + } + if tr.sizesCount > 0 { + return "", nil, unsupported("entry point %q: a runtime-sized storage array resource is not supported in a vertex or fragment stage", ep.Name) + } + if ep.Stage == wgsl.StageVertex { + for _, b := range tr.bindings { + if b.Kind == BindingTexture { + return "", nil, unsupported("entry point %q: a vertex stage cannot read a texture (go-macos/metal's RenderEncoder has no vertex-stage texture binding)", ep.Name) + } + } + } + + tr.line("#include ") + tr.line("#include ") + tr.line("using namespace metal;") + tr.buf.WriteByte('\n') + + if err := tr.emitHelperFuncs(ep); err != nil { + return "", nil, err + } + + var retMSL string + switch { + case ep.Func.Ret == wgsl.Void: + retMSL = "void" + default: + if st, ok := ep.Func.Ret.(*wgsl.StructType); ok { + tr.outputStructType = st + tr.outputStructName = "_" + identMSL(ep.Name) + "Out" + if err := tr.emitIOStruct(tr.outputStructName, ep.Outputs, ep.Stage); err != nil { + return "", nil, err + } + retMSL = tr.outputStructName + break + } + m, err := mslType(ep.Func.Ret) + if err != nil { + return "", nil, err + } + retMSL = m + // len(ep.Outputs) != 1 is unreachable here: this branch is reached + // only when ep.Func.Ret is NOT a *wgsl.StructType (the struct branch, + // above, already returned). go-gfx/wgsl's entryIO calls addIO exactly + // once for a non-struct return value (handle's own struct/non-struct + // dispatch mirrors this branch's — a Predeclared struct, the one case + // addIO itself would still treat as non-struct, can never be + // ep.Func.Ret because its name "cannot be spelled in source"), and + // addIO unconditionally appends to ep.Outputs — so a non-struct, + // non-void return always leaves exactly one entry there. Hand-verified + // by mutation (engine#447): deleting this check left it unreachable, + // never SURVIVED. + // A non-struct MSL return type has NO attribute syntax at all — + // measured directly against the real Metal compiler (every + // spelling tried was rejected with "attribute cannot be applied to + // types"; see this function's own doc comment and + // RenderOptions' doc comment). Metal gives exactly one implicit + // attribute per stage to a bare return: [[position]] for a vertex + // entry, [[color(0)]] for a fragment entry. Anything else needs a + // struct return instead (emitIOStruct's own branch, above). + out := ep.Outputs[0] + switch { + case ep.Stage == wgsl.StageVertex && out.Builtin == "position": + // Implicit; no attribute to emit. + case ep.Stage == wgsl.StageFragment && out.Builtin == "" && out.Location != nil && int(*out.Location) == 0: + // Implicit; no attribute to emit. + default: + return "", nil, unsupported("entry point %q: a bare (non-struct) output must be @builtin(position) in a vertex entry or @location(0) in a fragment entry — Metal has no attribute syntax for any other non-struct return, only these two implicit defaults; use a struct return instead", ep.Name) + } + } + + params, vInputs, err := tr.stageEntryParams(ep) + if err != nil { + return "", nil, err + } + + qualifier := "vertex" + if ep.Stage == wgsl.StageFragment { + qualifier = "fragment" + } + entryName := identMSL(ep.Name) + tr.line("%s %s %s(", qualifier, retMSL, entryName) + tr.indent++ + for i, p := range params { + sep := "," + if i == len(params)-1 { + sep = "" + } + tr.line("%s%s", p, sep) + } + tr.indent-- + tr.line(") {") + tr.indent++ + if err := tr.stmtBlock(ep.Func.Decl.Body); err != nil { + return "", nil, err + } + tr.indent-- + tr.line("}") + + return tr.buf.String(), vInputs, nil +} diff --git a/wgslmsl/render_test.go b/wgslmsl/render_test.go new file mode 100644 index 0000000..d07ac3c --- /dev/null +++ b/wgslmsl/render_test.go @@ -0,0 +1,991 @@ +// Copyright (c) the go-webengine/engine authors. +// SPDX-License-Identifier: BSD-3-Clause + +package wgslmsl + +import ( + "strings" + "testing" + "unsafe" + + "github.com/go-macos/metal" +) + +// renderDevice returns a real Metal device, skipping (not failing) when +// this machine has no usable GPU — the same documented ErrNoDevice/ +// ErrUnsupported skip every other acceptance test in this package uses +// (runOnMetal's own doc comment). +func renderDevice(t *testing.T) *metal.Device { + t.Helper() + dev, err := metal.Default() + if err != nil { + t.Skipf("no usable GPU on this machine: %v", err) + } + return dev +} + +func putFloat32s(dst []byte, src []float32) { + for i, v := range src { + *(*float32)(unsafe.Pointer(&dst[i*4])) = v + } +} + +func putUint32s(dst []byte, src []uint32) { + for i, v := range src { + *(*uint32)(unsafe.Pointer(&dst[i*4])) = v + } +} + +// vertexFragmentWGSL is the shape engine#415 M7 names for a render +// pipeline: a vertex entry taking a @location position and the +// instance_index builtin, outputting a struct that mixes @builtin(position) +// with a flat @location varying; a fragment entry taking that struct as its +// own input and writing a single @location(0) u32 output. It deliberately +// exercises every shape TranslateRender claims to support: a @location +// vertex input (grouped into a synthesized [[stage_in]] struct), a builtin +// vertex input, a struct-typed vertex OUTPUT / fragment INPUT (the one +// struct type this package recognizes at all), and a bare fragment output +// riding Metal's own implicit color(0) default. +const vertexFragmentWGSL = ` +struct VertexOut { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) value: u32, +} + +@vertex +fn vmain(@location(0) pos: vec2, @builtin(instance_index) iid: u32) -> VertexOut { + var out: VertexOut; + out.position = vec4(pos, 0.0, 1.0); + out.value = iid; + return out; +} + +@fragment +fn fmain(in: VertexOut) -> @location(0) u32 { + return in.value; +} +` + +// TestTranslateRenderVertexFragmentEndToEnd runs TranslateRender's output +// through a real Metal render pass end to end: a cleared R8Uint target, a +// pipeline built from the vertex-input shape TranslateRender reports back +// (VertexInputs), two triangles sharing four vertices (quadBuffers' own +// shape, go-macos/metal's render_darwin_test.go), one DrawIndexed call with +// a non-zero firstInstance, read back. Every pixel is covered by the quad, +// so a correct result is uniform firstInstance everywhere — which also +// means a wrong [[stage_in]] struct (an attribute at the wrong offset, a +// field that resolved to the wrong buffer) or a wrong struct-output/ +// struct-input crossing (fmain reading the wrong field, or the wrong one +// entirely) would leave the clear colour showing through, or read back +// some other value, rather than firstInstance everywhere. +func TestTranslateRenderVertexFragmentEndToEnd(t *testing.T) { + res, err := TranslateRender(vertexFragmentWGSL, RenderOptions{}) + if err != nil { + t.Fatalf("TranslateRender: %v", err) + } + if len(res.VertexInputs) != 1 { + t.Fatalf("VertexInputs = %v, want exactly 1", res.VertexInputs) + } + vin := res.VertexInputs[0] + if vin.Location != 0 || vin.NComponents != 2 { + t.Fatalf("VertexInputs[0] = %+v, want Location 0, NComponents 2", vin) + } + + d := renderDevice(t) + defer d.Close() + + combinedMSL := res.VertexMSL + "\n" + res.FragmentMSL + lib, err := d.Compile(combinedMSL) + if err != nil { + t.Fatalf("Metal rejected the generated MSL: %v\n--- vertex ---\n%s\n--- fragment ---\n%s", err, res.VertexMSL, res.FragmentMSL) + } + defer lib.Close() + + pipe, err := lib.RenderPipeline(metal.RenderPipelineDescriptor{ + VertexFunction: res.VertexEntryPointName, + FragmentFunction: res.FragmentEntryPointName, + Attributes: []metal.VertexAttribute{ + {Index: 0, Format: metal.VertexFormatFloat32x2, Offset: 0, BufferIndex: 0}, + }, + Layouts: []metal.VertexLayout{{BufferIndex: 0, Stride: 8}}, + ColorFormat: metal.PixelFormatR8Uint, + }) + if err != nil { + t.Fatalf("RenderPipeline: %v", err) + } + defer pipe.Close() + + vb, err := d.NewBuffer(4 * 8) // 4 vertices, float2 each + if err != nil { + t.Fatal(err) + } + defer vb.Close() + putFloat32s(vb.Bytes(), []float32{-1, -1, 1, -1, -1, 1, 1, 1}) + + ib, err := d.NewBuffer(6 * 4) // 2 triangles, uint32 each + if err != nil { + t.Fatal(err) + } + defer ib.Close() + putUint32s(ib.Bytes(), []uint32{0, 1, 2, 2, 1, 3}) + + const w, h = 4, 4 + tex, err := d.NewTexture(w, h, metal.PixelFormatR8Uint, metal.TextureUsageRenderTarget|metal.TextureUsageShaderRead) + if err != nil { + t.Fatal(err) + } + defer tex.Close() + + const firstInstance = 7 + err = d.RunRender(metal.RenderPassDescriptor{ + Target: tex, + Load: metal.LoadActionClear, + Store: metal.StoreActionStore, + Clear: [4]float64{5, 5, 5, 5}, + }, func(e *metal.RenderEncoder) { + e.Use(pipe) + e.VertexBuffer(0, vb, 0) + e.DrawIndexed(6, 1, ib, 0, 0, firstInstance) + }) + if err != nil { + t.Fatalf("RunRender: %v", err) + } + + got := make([]byte, w*h) + if err := tex.GetBytes(got); err != nil { + t.Fatal(err) + } + for i, v := range got { + if v != firstInstance { + t.Fatalf("pixel %d = %d, want %d (clear colour 5 would mean the quad did not cover it, any other value means the struct output/input crossing read the wrong thing)", i, v, firstInstance) + } + } +} + +// textureLoadComputeWGSL is engine#415's own named shape for a texture read +// from a COMPUTE shader (render.go's own doc comment: "A fragment entry +// point may read ONE resource kind beyond uniform/storage... through +// textureLoad only") — exercised here through Translate's @compute path, +// which resolveResources shares with TranslateRender, since a compute +// kernel is the simplest real host-side harness for it (go-macos/metal's +// own Encoder.Texture, not RenderEncoder's fragment-only texture binding). +const textureLoadComputeWGSL = ` +@group(0) @binding(0) var tex: texture_2d; +@group(0) @binding(1) var out: array; + +@compute @workgroup_size(1) +fn main(@builtin(global_invocation_id) id: vec3) { + let v = textureLoad(tex, vec2(i32(id.x), i32(id.y)), 0); + out[id.y * 4u + id.x] = v.r; +} +` + +// TestTranslateTextureLoadEndToEnd runs a textureLoad kernel through a real +// Metal compute dispatch: a 4x2 R8Uint texture filled with known values, +// read back through the generated MSL's own tex.read(uint2(...), uint(...)) +// call. A wrong coordinate order or a wrong texture/buffer binding index +// would read back something other than the source pixel at (x, y). +func TestTranslateTextureLoadEndToEnd(t *testing.T) { + res, err := Translate(textureLoadComputeWGSL, Options{}) + if err != nil { + t.Fatalf("Translate: %v", err) + } + var texBinding *Binding + for i := range res.Bindings { + if res.Bindings[i].Kind == BindingTexture { + texBinding = &res.Bindings[i] + } + } + if texBinding == nil { + t.Fatalf("no BindingTexture in %+v", res.Bindings) + } + + d := renderDevice(t) + defer d.Close() + + lib, err := d.Compile(res.MSL) + if err != nil { + t.Fatalf("Metal rejected the generated MSL: %v\n--- MSL ---\n%s", err, res.MSL) + } + defer lib.Close() + + pipe, err := lib.Pipeline(res.EntryPointName) + if err != nil { + t.Fatalf("Pipeline(%q): %v", res.EntryPointName, err) + } + defer pipe.Close() + + const w, h = 4, 2 + tex, err := d.NewTexture(w, h, metal.PixelFormatR8Uint, metal.TextureUsageShaderRead) + if err != nil { + t.Fatal(err) + } + defer tex.Close() + in := make([]byte, w*h) + for i := range in { + in[i] = byte(40 + i) + } + if err := tex.Replace(in); err != nil { + t.Fatal(err) + } + + var outBinding *Binding + for i := range res.Bindings { + if res.Bindings[i].Kind == BindingStorageArray { + outBinding = &res.Bindings[i] + } + } + if outBinding == nil { + t.Fatalf("no BindingStorageArray in %+v", res.Bindings) + } + outBuf, err := d.NewBuffer(w * h * 4) + if err != nil { + t.Fatal(err) + } + defer outBuf.Close() + + var sizesBuf *metal.Buffer + if res.SizeMetalIndex >= 0 { + sizesBuf, err = d.NewBuffer(4 * res.SizesCount) + if err != nil { + t.Fatal(err) + } + defer sizesBuf.Close() + putUint32s(sizesBuf.Bytes()[outBinding.SizesIndex*4:], []uint32{w * h}) + } + + if err := d.Run(func(e *metal.Encoder) { + e.Use(pipe) + e.Texture(texBinding.MetalIndex, tex) + e.Buffer(outBinding.MetalIndex, outBuf) + if sizesBuf != nil { + e.Buffer(res.SizeMetalIndex, sizesBuf) + } + e.Dispatch(w, h) + }); err != nil { + t.Fatalf("Run: %v", err) + } + + for i := 0; i < w*h; i++ { + got := *(*uint32)(unsafe.Pointer(&outBuf.Bytes()[i*4])) + if want := uint32(40 + i); got != want { + t.Fatalf("pixel %d = %d, want %d", i, got, want) + } + } +} + +// TestTranslateRenderRejectsVertexTexture confirms render.go's own +// documented limit: go-macos/metal's RenderEncoder has no vertex-stage +// texture binding, so a @vertex entry reading a texture_2d resource is +// a named rejection, not a silently wrong translation. +func TestTranslateRenderRejectsVertexTexture(t *testing.T) { + const src = ` + @group(0) @binding(0) var tex: texture_2d; + @vertex + fn vmain(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { + let v = textureLoad(tex, vec2(0, 0), 0); + return vec4(f32(v.r), 0.0, 0.0, 1.0); + } + @fragment + fn fmain() -> @location(0) u32 { return 0u; } + ` + if _, err := TranslateRender(src, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: vertex stage cannot read a texture") + } +} + +// TestTranslateRenderRejectsNonZeroBareFragmentLocation confirms the other +// honest limit this round's own measurement against the real Metal +// compiler found: a non-struct fragment return has no attribute syntax at +// all beyond Metal's own implicit color(0) default, so @location(1) on a +// bare fragment output is a named rejection, not silently mapped to the +// wrong attachment. +func TestTranslateRenderRejectsNonZeroBareFragmentLocation(t *testing.T) { + const src = ` + @vertex + fn vmain(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { + return vec4(0.0, 0.0, 0.0, 1.0); + } + @fragment + fn fmain() -> @location(1) u32 { return 0u; } + ` + if _, err := TranslateRender(src, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: bare fragment output must be @location(0)") + } +} + +// fragmentStub is the simplest valid @fragment entry point, for a test +// whose own focus is entirely on the @vertex side — TranslateRender always +// needs both. +const fragmentStub = ` +@fragment +fn fmain() -> @location(0) u32 { return 0u; } +` + +// vertexStub is the simplest valid @vertex entry point, the counterpart to +// fragmentStub for a test focused entirely on the @fragment side. +const vertexStub = ` +@vertex +fn vmain() -> @builtin(position) vec4 { return vec4(0.0, 0.0, 0.0, 1.0); } +` + +// TestTranslateRenderRejectsParseError confirms TranslateRender's own parse +// step (wgsl.Parse) surfaces a syntactically malformed source as a +// rejection, not a panic. +func TestTranslateRenderRejectsParseError(t *testing.T) { + // A deleted guard at render.go:117 lets a nil *wgsl.Module reach + // wgsl.Check below it, which crashes the whole test binary before + // this test's own assertion ever runs (mutsweep would read that as + // "caught by panic", luck rather than a test). This local recover + // converts such a crash into an ordinary failed assertion instead. + defer func() { + if r := recover(); r != nil { + t.Fatalf("TranslateRender panicked: %v", r) + } + }() + if _, err := TranslateRender("not valid wgsl {{{", RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a parse error") + } +} + +// TestTranslateRenderRejectsCheckError confirms a syntactically valid but +// semantically invalid source (an undefined identifier) is rejected by +// TranslateRender's own wgsl.Check step, distinct from the parse step above. +func TestTranslateRenderRejectsCheckError(t *testing.T) { + src := ` + @vertex + fn vmain() -> @builtin(position) vec4 { return undefinedThing; } + ` + fragmentStub + if _, err := TranslateRender(src, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a check error (undefined identifier)") + } +} + +// TestTranslateRenderRejectsMissingVertexEntryPoint and +// TestTranslateRenderRejectsMissingFragmentEntryPoint cover findEntryPoint's +// own "module has no @ entry point" case for each stage +// independently — TranslateRender needs both, so a module missing either +// one is its own distinct rejection. +func TestTranslateRenderRejectsMissingVertexEntryPoint(t *testing.T) { + // A deleted guard at render.go:126 lets a nil vep reach + // vtr.translateStageEntry below it, crashing the whole test binary + // before the assertion runs — see TestTranslateRenderRejectsParseError's + // own recover comment for why this matters. + defer func() { + if r := recover(); r != nil { + t.Fatalf("TranslateRender panicked: %v", r) + } + }() + if _, err := TranslateRender(fragmentStub, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: no @vertex entry point") + } +} + +func TestTranslateRenderRejectsMissingFragmentEntryPoint(t *testing.T) { + // Same reasoning, for the deleted guard at render.go:130 and fep. + defer func() { + if r := recover(); r != nil { + t.Fatalf("TranslateRender panicked: %v", r) + } + }() + if _, err := TranslateRender(vertexStub, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: no @fragment entry point") + } +} + +// twoVertexEntriesWGSL declares two @vertex entry points and one @fragment +// entry point — the shape findEntryPoint's own explicit-name selection +// needs: RenderOptions.VertexEntryPoint picks one by name, and the wrong +// name (one that exists but as the OTHER stage) is its own distinct +// rejection. +const twoVertexEntriesWGSL = ` +@vertex +fn vmainA() -> @builtin(position) vec4 { return vec4(0.0, 0.0, 0.0, 1.0); } +@vertex +fn vmainB() -> @builtin(position) vec4 { return vec4(1.0, 0.0, 0.0, 1.0); } +@fragment +fn fmain() -> @location(0) u32 { return 0u; } +` + +// TestTranslateRenderSelectsVertexEntryPointByName confirms +// RenderOptions.VertexEntryPoint picks the NAMED entry point specifically +// (not just "some" entry point of the right stage): vmainB, never vmainA, +// which only an exact-name match (not a negated/forced boolean) can tell +// apart. +func TestTranslateRenderSelectsVertexEntryPointByName(t *testing.T) { + res, err := TranslateRender(twoVertexEntriesWGSL, RenderOptions{VertexEntryPoint: "vmainB"}) + if err != nil { + t.Fatalf("TranslateRender: %v", err) + } + if res.VertexEntryPointName != "vmainB" { + t.Fatalf("VertexEntryPointName = %q, want %q", res.VertexEntryPointName, "vmainB") + } +} + +// TestTranslateRenderRejectsWrongStageEntryPointName confirms naming an +// entry point of the WRONG stage in RenderOptions.VertexEntryPoint is its +// own rejection ("is a @fragment shader, not @vertex"), distinct from the +// name not existing at all. +func TestTranslateRenderRejectsWrongStageEntryPointName(t *testing.T) { + _, err := TranslateRender(twoVertexEntriesWGSL, RenderOptions{VertexEntryPoint: "fmain"}) + if err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: fmain is a @fragment shader, not @vertex") + } + if !strings.Contains(err.Error(), "is a @fragment shader") { + t.Fatalf("error = %v, want it to mention the wrong-stage shape", err) + } +} + +// TestTranslateRenderRejectsFragmentOutputBuiltin confirms outputIOAttr +// rejects a struct-output builtin other than position (here +// @builtin(frag_depth), a genuinely valid WGSL fragment-output builtin) — +// this package's own bounded scope only ever recognizes position. +func TestTranslateRenderRejectsFragmentOutputBuiltin(t *testing.T) { + // A deleted guard at render.go:232 falls through to `*io.Location` + // below it, which is nil for a builtin-typed IOVar — a nil-pointer + // panic that crashes the whole test binary before this test's own + // assertions run. Same reasoning as the recover in + // TestTranslateRenderRejectsParseError. + defer func() { + if r := recover(); r != nil { + t.Fatalf("TranslateRender panicked: %v", r) + } + }() + src := vertexStub + ` + struct FOut { + @location(0) color: u32, + @builtin(frag_depth) depth: f32, + } + @fragment + fn fmain() -> FOut { + var out: FOut; + out.color = 1u; + out.depth = 0.5; + return out; + } + ` + _, err := TranslateRender(src, RenderOptions{}) + if err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: unsupported output builtin frag_depth") + } + if !strings.Contains(err.Error(), "output builtin") { + t.Fatalf("error = %v, want it to mention the output builtin", err) + } +} + +// TestTranslateRenderStructFragmentOutputUsesColorAttribute confirms +// outputIOAttr's fragment branch: a struct-typed fragment output's own +// @location(N) field is emitted as Metal's [[color(N)]] attribute — a shape +// no other existing test exercises (vertexFragmentWGSL's own fragment +// output is a bare, non-struct value). +func TestTranslateRenderStructFragmentOutputUsesColorAttribute(t *testing.T) { + src := vertexStub + ` + struct FOut { + @location(0) color: vec4, + } + @fragment + fn fmain() -> FOut { + var out: FOut; + out.color = vec4(1.0, 0.0, 0.0, 1.0); + return out; + } + ` + res, err := TranslateRender(src, RenderOptions{}) + if err != nil { + t.Fatalf("TranslateRender: %v", err) + } + if !strings.Contains(res.FragmentMSL, "color(0)") { + t.Fatalf("FragmentMSL = %s, want it to contain color(0)", res.FragmentMSL) + } +} + +// TestTranslateRenderRejectsF16UniformResource confirms the asymmetry this +// round measured directly: go-gfx/wgsl's own Check ACCEPTS f16 as a +// var resource type, but this package's own mslType (shared by +// resourceParamDecl, through resourceEntryParams) only ever accepts +// bool/i32/u32/f32 — so an f16 uniform resource used by a @fragment entry +// is rejected downstream of resolveResources, not by it. +func TestTranslateRenderRejectsF16UniformResource(t *testing.T) { + // A deleted guard at render.go:436 (translateStageEntry's own + // resolveResources error check) lets translation continue past an + // unresolved resource: x is never added to tr.bindings/tr.resources, + // so a later lookup like tr.bindings[tr.resources[x]] panics with an + // out-of-range index instead of this test's own assertions ever + // running. Same reasoning as the recover in + // TestTranslateRenderRejectsParseError. + defer func() { + if r := recover(); r != nil { + t.Fatalf("TranslateRender panicked: %v", r) + } + }() + src := ` + enable f16; + ` + vertexStub + ` + @group(0) @binding(0) var x: f16; + @fragment + fn fmain() -> @location(0) u32 { return u32(x); } + ` + _, err := TranslateRender(src, RenderOptions{}) + if err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: f16 uniform resource") + } + if strings.Contains(err.Error(), "parse:") { + t.Fatalf("error = %v, want a resource-type rejection, not a parse error", err) + } +} + +// TestTranslateRenderRejectsF16VertexInput confirms the same f16 asymmetry +// on the vertex-input side: Check accepts f16 as a @location vertex input's +// scalar type, but stageEntryParams's own mslTypeTR (mslType underneath) +// rejects it. +func TestTranslateRenderRejectsF16VertexInput(t *testing.T) { + src := ` + enable f16; + @vertex + fn vmain(@location(0) v: f16) -> @builtin(position) vec4 { + return vec4(f32(v), 0.0, 0.0, 1.0); + } + ` + fragmentStub + if _, err := TranslateRender(src, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: f16 vertex input") + } +} + +// TestTranslateRenderRejectsF16FragmentBareOutput confirms the same f16 +// asymmetry once more on a bare (non-struct) fragment return type: Check +// accepts f16 as a @location(0) bare output's type, but +// translateStageEntry's own "m, err := mslType(ep.Func.Ret); if err != +// nil" check (render.go) rejects it. This check runs while retMSL is +// still being determined, before tr.stmtBlock(ep.Func.Decl.Body) ever +// translates the body's own "return 1.0h" literal — which independently +// fails the same way once this check is bypassed (hand-mutation-confirmed: +// neutralizing it still fails the same input, with "literal of scalar +// kind 6" instead of this check's own "scalar type 6 (only +// bool/i32/u32/f32)" via mslScalar). The specific message distinguishes +// them: only this check's own mslType(ep.Func.Ret) call produces +// "only bool/i32/u32/f32" for this input, so asserting it (not just +// err != nil) isolates render.go's own propagation line from the body's +// later, independent literal-translation rejection. +func TestTranslateRenderRejectsF16FragmentBareOutput(t *testing.T) { + src := ` + enable f16; + ` + vertexStub + ` + @fragment + fn fmain() -> @location(0) f16 { return 1.0h; } + ` + _, err := TranslateRender(src, RenderOptions{}) + if err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: f16 bare fragment output") + } + if !strings.Contains(err.Error(), "only bool/i32/u32/f32") { + t.Fatalf("error = %v, want mslType(ep.Func.Ret)'s own rejection, not a later one", err) + } +} + +// TestTranslateRenderRejectsF16StructOutputField confirms emitIOStruct's +// own "fieldMSL, err := mslType(io.Type); if err != nil" check (render.go) +// is independently reachable, unlike +// TestTranslateRenderRejectsF16FragmentBareOutput's bare-return shape: a +// struct-typed fragment output's field types are all emitted by +// emitIOStruct while translateStageEntry is still building retMSL, before +// tr.stmtBlock(ep.Func.Decl.Body) ever translates a single body statement +// — so an f16 struct field fails here first, with nothing in the body +// (which never assigns the field at all) able to trip any other f16 +// rejection ahead of it. +func TestTranslateRenderRejectsF16StructOutputField(t *testing.T) { + src := ` + enable f16; + ` + vertexStub + ` + struct FOut { + @location(0) v: f16, + } + @fragment + fn fmain() -> FOut { + var out: FOut; + return out; + } + ` + _, err := TranslateRender(src, RenderOptions{}) + if err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: f16 struct output field") + } + if !strings.Contains(err.Error(), "only bool/i32/u32/f32") { + t.Fatalf("error = %v, want the mslScalar f16 rejection", err) + } +} + +// TestTranslateRenderRejectsSwitchInHelperFunction confirms +// translateStageEntry's own "if err := tr.emitHelperFuncs(ep); err != nil" +// propagation (render.go) is independently reachable — unlike +// TestTranslateRenderRejectsMatrixHelperFunctionParam's helper-parameter +// shape (hand-mutation-confirmed redundant with the entry body's own +// matrix-constructor translation), a switch statement is unsupported only +// inside a function BODY (stmt.go's own stmt dispatch), never as part of a +// parameter or return type a caller's own expression translation would +// also have to check — so a helper whose own body uses switch, called +// from a vertex entry whose own body never does, exercises this +// propagation line and nothing else: emitHelperFuncs runs (and fails) +// before the entry's own body is ever translated. +func TestTranslateRenderRejectsSwitchInHelperFunction(t *testing.T) { + src := ` + fn helper(x: u32) -> f32 { + var out: f32 = 0.0; + switch (x) { + case 0u: { out = 1.0; } + default: { out = 2.0; } + } + return out; + } + @vertex + fn vmain() -> @builtin(position) vec4 { + let y = helper(0u); + return vec4(y, 0.0, 0.0, 1.0); + } + ` + fragmentStub + _, err := TranslateRender(src, RenderOptions{}) + if err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: switch statement in helper function") + } + if !strings.Contains(err.Error(), "unsupported: statement") { + t.Fatalf("error = %v, want stmt's own unsupported-statement rejection", err) + } +} + +// TestTranslateRenderRejectsMatrixHelperFunctionParam confirms a helper +// function called from a @vertex entry is translated through the SAME +// emitHelperFuncs this package's @compute path uses — and a helper +// parameter type outside this package's scalar/vector scope (a matrix, +// valid as an ordinary WGSL function parameter, just not as entry IO) is +// rejected there. It does NOT isolate render.go's own +// "if err := tr.emitHelperFuncs(ep); err != nil" propagation +// (hand-mutation-confirmed: neutralizing that check still fails the same +// input, with the SAME "type mat2x2 (only scalars and vectors)" +// message, now wrapped as "vertex entry \"vmain\": ..." instead): any +// matrix value a helper call needs is itself an expression this +// package's shared mslType gate rejects when translating the entry's own +// body, including when the matrix is an inline constructor passed +// directly as the call argument (no local `let` binding required) — so +// a matrix-typed helper parameter can never reach emitHelperFuncs without +// the entry body independently tripping the same rejection first. This +// propagation line is left untested as a structural invariant, not a gap. +func TestTranslateRenderRejectsMatrixHelperFunctionParam(t *testing.T) { + src := ` + fn helper(m: mat2x2) -> f32 { return m[0][0]; } + @vertex + fn vmain() -> @builtin(position) vec4 { + let m = mat2x2(1.0, 0.0, 0.0, 1.0); + let y = helper(m); + return vec4(y, 0.0, 0.0, 1.0); + } + ` + fragmentStub + if _, err := TranslateRender(src, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: matrix helper function parameter") + } +} + +// TestTranslateRenderRejectsFixedSizeStorageArray confirms resolveResources' +// own "fixed-size storage array" rejection (it only ever supports a +// runtime-sized one) is reachable from a render-stage entry point too — +// distinct from TestTranslateRenderRejectsRuntimeStorageArray below, which +// is this package's OWN render-specific rejection of a resource +// resolveResources itself accepts just fine. +func TestTranslateRenderRejectsFixedSizeStorageArray(t *testing.T) { + src := vertexStub + ` + @group(0) @binding(0) var buf: array; + @fragment + fn fmain() -> @location(0) u32 { return u32(buf[0]); } + ` + if _, err := TranslateRender(src, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: fixed-size storage array") + } +} + +// TestTranslateRenderRejectsRuntimeStorageArray confirms +// translateStageEntry's own render-specific rejection: a runtime-sized +// storage array resource resolves fine (resolveResources accepts it, the +// same as the @compute path), but this package's bounds-check machinery +// (Result.SizeMetalIndex) is a @compute-only concept, so render.go rejects +// it outright instead. +func TestTranslateRenderRejectsRuntimeStorageArray(t *testing.T) { + src := vertexStub + ` + @group(0) @binding(0) var buf: array; + @fragment + fn fmain() -> @location(0) u32 { return u32(buf[0]); } + ` + _, err := TranslateRender(src, RenderOptions{}) + if err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: runtime-sized storage array in a render stage") + } + if !strings.Contains(err.Error(), "runtime-sized storage array") { + t.Fatalf("error = %v, want it to mention the runtime-sized storage array", err) + } +} + +// TestTranslateRenderRejectsConstructingAnUnrecognizedStruct confirms +// memberExpr/callExpr's own struct-recognition scope: the ONE struct type +// this package ever recognizes is an entry point's own output struct +// (tr.outputStructType) — a second, unrelated struct declared in the same +// module is still rejected, whether constructed directly or (as here) +// through a field access on that construction, inside the @vertex entry's +// own body (reached through stmtBlock, not through any resource or +// parameter-list path). +func TestTranslateRenderRejectsConstructingAnUnrecognizedStruct(t *testing.T) { + src := ` + struct Aux { v: f32, w: f32 } + @vertex + fn vmain() -> @builtin(position) vec4 { + let a = Aux(1.0, 2.0).v; + return vec4(a, 0.0, 0.0, 1.0); + } + ` + fragmentStub + _, err := TranslateRender(src, RenderOptions{}) + if err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: constructing an unrecognized struct type") + } + if !strings.Contains(err.Error(), "constructing struct type") { + t.Fatalf("error = %v, want it to mention constructing the struct type", err) + } +} + +// textureLoadFragmentStub is the shared @group(0)@binding(0) texture_2d +// resource and FOut output struct every textureLoad-focused test below +// reuses, paired with a plain vertexStub (none of these need the vertex +// side at all). +const textureLoadFragmentFOut = `struct FOut { @location(0) c: u32 }` + +// TestTranslateRenderRejectsTextureLoadPoisonedCoords and +// TestTranslateRenderRejectsTextureLoadPoisonedLevel each poison exactly +// ONE of textureLoad's own coords/level sub-expressions at a time (the +// SAME unrecognized-Aux-struct rejection as the test above, nested inside a +// cast) — never both in the same test, since a single test poisoning both +// could not tell which specific line's error check actually fired: an +// earlier check deleted by a mutant would still be masked by the later one +// independently failing for its own reason. +func TestTranslateRenderRejectsTextureLoadPoisonedCoords(t *testing.T) { + src := vertexStub + ` + struct Aux { v: f32, w: f32 } + @group(0) @binding(0) var tex: texture_2d; + ` + textureLoadFragmentFOut + ` + @fragment + fn fmain() -> FOut { + var out: FOut; + out.c = textureLoad(tex, vec2(i32(Aux(1.0, 2.0).v), 0), 0).x; + return out; + } + ` + if _, err := TranslateRender(src, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: poisoned textureLoad coords") + } +} + +func TestTranslateRenderRejectsTextureLoadPoisonedLevel(t *testing.T) { + src := vertexStub + ` + struct Aux { v: f32, w: f32 } + @group(0) @binding(0) var tex: texture_2d; + ` + textureLoadFragmentFOut + ` + @fragment + fn fmain() -> FOut { + var out: FOut; + out.c = textureLoad(tex, vec2(0, 0), i32(Aux(1.0, 2.0).v)).x; + return out; + } + ` + if _, err := TranslateRender(src, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: poisoned textureLoad level") + } +} + +// TestTranslateRenderRejectsTextureLoadOnLocalAlias confirms a WGSL +// `let t = tex;` local alias of a texture resource is rejected — but NOT, +// as the resourceOf/textureLoadExpr code might suggest, by their own +// "tracked texture resource" check (expr.go:452): emitting the `let` +// statement itself needs t's own MSL type first, and mslType (shared with +// every other scalar/vector-only site in this package) has no texture +// case, so the rejection fires there, before textureLoadExpr is ever +// reached. Confirmed by reading the actual error text this produces +// ("type texture_2d (only scalars and vectors)"), not by assuming it +// from go-gfx/wgsl's own Check accepting the shape. expr.go:452 itself +// stays unreached by any WGSL this package's Check-gated scope admits: any +// identifier that type-checks as textureLoad's first argument is either +// the module-scope resource var itself (always tracked, via ep.Resources) +// or a local/parameter binding of texture type, which mslType rejects +// earlier, exactly as this test demonstrates. +func TestTranslateRenderRejectsTextureLoadOnLocalAlias(t *testing.T) { + src := vertexStub + ` + @group(0) @binding(0) var tex: texture_2d; + ` + textureLoadFragmentFOut + ` + @fragment + fn fmain() -> FOut { + let t = tex; + var out: FOut; + out.c = textureLoad(t, vec2(0, 0), 0).x; + return out; + } + ` + _, err := TranslateRender(src, RenderOptions{}) + if err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: textureLoad on a local texture alias") + } + if !strings.Contains(err.Error(), "only scalars and vectors") { + t.Fatalf("error = %v, want the let-statement's own texture-type rejection", err) + } +} + +// TestTranslateRenderRejectsSamplerResource confirms resolveResources' +// ASHandle case rejects a `sampler` resource outright (declared BEFORE the +// texture it samples, so it is the first ep.Resources entry resolveResources +// reaches): this package's bounded scope never recognizes textureSample or +// any sampler at all, only textureLoad against a texture_2d. +func TestTranslateRenderRejectsSamplerResource(t *testing.T) { + // A deleted guard at translator.go:588 (resolveResources's own + // "is this handle actually a texture?" type assertion) lets `tex` + // stay nil and falls through to `tex.Kind` right below it — a + // nil-pointer panic inside resolveResources itself, before this + // test's own assertion runs. Same reasoning as the recover in + // TestTranslateRenderRejectsParseError. + defer func() { + if r := recover(); r != nil { + t.Fatalf("TranslateRender panicked: %v", r) + } + }() + src := vertexStub + ` + @group(0) @binding(0) var samp: sampler; + @group(0) @binding(1) var tex: texture_2d; + struct FOut { @location(0) c: vec4 } + @fragment + fn fmain() -> FOut { + var out: FOut; + out.c = textureSample(tex, samp, vec2(0.0, 0.0)); + return out; + } + ` + if _, err := TranslateRender(src, RenderOptions{}); err == nil { + t.Fatal("TranslateRender succeeded, want a rejection: sampler resource") + } +} + +// builtinStructMemberWGSL is engine#447 review bug #3's exact +// reproduction: the vertex entry's own instance_index builtin is a FIELD +// of a struct parameter (VertexIn), accessed in the body via `in.iid` — +// never a bare top-level parameter the way every other render test in +// this file writes it. Before the fix, stageEntryParams registered no +// accessor for a struct-typed builtin field (only for a @location one), +// so memberExpr fell through to the generic struct-member case and +// emitted `in.iid` using the struct parameter's own WGSL identifier +// `in` — never declared as an MSL parameter, since instance_index is +// flattened into its own bare [[instance_id]] parameter instead. Real +// Metal rejected the result outright ("use of undeclared identifier +// 'in'"), which is exactly what TestTranslateRenderBuiltinStructMemberCompiles +// below proves no longer happens. +const builtinStructMemberWGSL = ` +struct VertexIn { + @builtin(instance_index) iid: u32, + @location(0) pos: vec2, +} + +struct VertexOut { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) value: u32, +} + +@vertex +fn vmain(in: VertexIn) -> VertexOut { + var out: VertexOut; + out.position = vec4(in.pos, 0.0, 1.0); + out.value = in.iid; + return out; +} + +@fragment +fn fmain(in: VertexOut) -> @location(0) u32 { + return in.value; +} +` + +// TestTranslateRenderBuiltinStructMemberCompiles is the direct +// regression test for engine#447 review bug #3: builtinStructMemberWGSL +// must both translate AND compile against a real Metal device — before +// the fix, translation itself succeeded (no WGSL-level error), and only +// the real Metal compiler rejected the generated MSL, so this test must +// run the fixture all the way through TranslateRender -> device.Compile +// to actually exercise the bug, a pure-Go assertion on TranslateRender's +// error return would not have caught it. +func TestTranslateRenderBuiltinStructMemberCompiles(t *testing.T) { + res, err := TranslateRender(builtinStructMemberWGSL, RenderOptions{}) + if err != nil { + t.Fatalf("TranslateRender: %v", err) + } + + d := renderDevice(t) + defer d.Close() + + combinedMSL := res.VertexMSL + "\n" + res.FragmentMSL + lib, err := d.Compile(combinedMSL) + if err != nil { + t.Fatalf("Metal rejected the generated MSL: %v\n--- vertex ---\n%s\n--- fragment ---\n%s", err, res.VertexMSL, res.FragmentMSL) + } + defer lib.Close() +} + +// sharedHelperWGSL is engine#447 review bug #4's exact reproduction: a +// plain helper function (scaleUp) called from BOTH the vertex and the +// fragment entry point. Before the fix, TranslateRender built vtr/ftr as +// two fully independent *translator instances with no shared +// "already emitted" state at all (TranslateRender's own doc comment +// now explains why sharedHelpers exists) — each one's own +// emitHelperFuncs emitted scaleUp's full MSL text unconditionally, so +// the combined MSL (every real caller's own compile unit — see +// gpuCreateRenderPipeline, TestTranslateRenderVertexFragmentEndToEnd) +// contained TWO textually identical "float scaleUp(float v) { ... }" +// definitions, which real Metal rejects outright as a redefinition. +const sharedHelperWGSL = ` +fn scaleUp(v: f32) -> f32 { + return v * 2.0; +} + +struct VertexOut { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) value: u32, +} + +@vertex +fn vmain(@location(0) pos: vec2) -> VertexOut { + var out: VertexOut; + out.position = vec4(scaleUp(pos.x), scaleUp(pos.y), 0.0, 1.0); + out.value = 0u; + return out; +} + +@fragment +fn fmain(in: VertexOut) -> @location(0) u32 { + return u32(scaleUp(1.0)); +} +` + +// TestTranslateRenderSharedHelperEmittedOnce is the direct regression +// test for engine#447 review bug #4: sharedHelperWGSL's own scaleUp +// helper, called from both stages, must appear in the combined MSL +// exactly once (a textual count, proving the dedup itself happened, not +// merely that Metal tolerated something else) AND the combined MSL must +// still compile against a real Metal device (the actual failure mode +// before the fix: a function redefinition error). +func TestTranslateRenderSharedHelperEmittedOnce(t *testing.T) { + res, err := TranslateRender(sharedHelperWGSL, RenderOptions{}) + if err != nil { + t.Fatalf("TranslateRender: %v", err) + } + + combinedMSL := res.VertexMSL + "\n" + res.FragmentMSL + if n := strings.Count(combinedMSL, "float scaleUp("); n != 1 { + t.Fatalf("combined MSL defines scaleUp %d times, want exactly 1:\n%s", n, combinedMSL) + } + + d := renderDevice(t) + defer d.Close() + + lib, err := d.Compile(combinedMSL) + if err != nil { + t.Fatalf("Metal rejected the generated MSL: %v\n--- combined ---\n%s", err, combinedMSL) + } + defer lib.Close() +} diff --git a/wgslmsl/stmt.go b/wgslmsl/stmt.go index 89eae91..094623b 100644 --- a/wgslmsl/stmt.go +++ b/wgslmsl/stmt.go @@ -115,7 +115,7 @@ func (tr *translator) declStmt(ds *wgsl.DeclStmt) error { switch d := ds.Decl.(type) { case *wgsl.Var: t := tr.info.DeclTypes[d] - typeMSL, err := mslType(t) + typeMSL, err := tr.mslTypeTR(t) if err != nil { return err } @@ -134,7 +134,7 @@ func (tr *translator) declStmt(ds *wgsl.DeclStmt) error { return unsupported("local %s declaration", d.Kind) } t := tr.info.DeclTypes[d] - typeMSL, err := mslType(t) + typeMSL, err := tr.mslTypeTR(t) if err != nil { return err } diff --git a/wgslmsl/translator.go b/wgslmsl/translator.go index 0d8cb6a..5ddebd5 100644 --- a/wgslmsl/translator.go +++ b/wgslmsl/translator.go @@ -85,6 +85,88 @@ type translator struct { flagCounter int indent int buf strings.Builder + // bufferCount and textureCount are the next free Metal [[buffer(N)]] + // and [[texture(N)]] index — two SEPARATE namespaces (Metal itself has + // no shared "resource index" at all; a buffer and a texture bound at + // the same number never collide), so addBinding allocates a resource's + // own MetalIndex from whichever counter matches its Kind. + bufferCount, textureCount int + // outputStructType and outputStructName are set only while translating + // a @vertex or @fragment entry point whose own WGSL return type is a + // user-declared struct (render.go's translateStageEntry) — the ONE + // user struct type this package recognizes at all, matched by pointer + // identity against go-gfx/wgsl's own canonical *StructType object + // (Check resolves one struct declaration to one shared Type value, the + // same object translateStageEntry reads straight off ep.Func.Ret and + // every local variable of that declared type also carries). Both are + // nil/empty for a @compute entry point, which never recognizes any + // struct type at all — mslTypeTR's own struct case cannot match + // anything then, preserving the compute path's existing "no user + // structs" scope exactly. + outputStructType *wgsl.StructType + outputStructName string + // inputFlatten maps a struct-typed entry-point input PARAMETER's own + // ParamObj to {WGSL field name -> the MSL expression stageEntryParams + // actually emitted for it}. Confirmed directly against the real Metal + // compiler (render.go's own doc comment on stageEntryParams): EVERY + // @location input, in a @vertex entry or a @fragment entry alike, + // whether declared as an individual top-level parameter or as a field + // of a struct parameter, is GROUPED into one synthesized [[stage_in]] + // struct (stageEntryParams) — never left as an individual bare + // parameter. A bare [[attribute(N)]] vertex parameter with no + // wrapping [[stage_in]] struct is rejected outright ("invalid type + // ... for input declaration in a vertex function"); a bare + // [[user(locnN)]] fragment parameter compiles but silently never + // receives the rasterizer-interpolated value (confirmed by an actual + // render + pixel-readback test, not just a compile check — this is + // why the fragment side is never given a real MSL struct SHARED with + // the vertex stage either: it gets its OWN synthesized [[stage_in]] + // struct, a different C type from the vertex's). The map value here + // is ".". + // memberExpr consults this map to translate the WGSL body's ordinary + // `in.field` access to the right-hand side recorded here. A + // @location input that was a plain top-level parameter (no enclosing + // struct, so no `in.field` dot access in the WGSL body at all) + // instead goes through paramRename below. + inputFlatten map[*wgsl.ParamObj]map[string]string + // paramRename maps a @vertex or @fragment entry's own top-level + // (non-struct-field) @location input parameter's ParamObj directly to + // the MSL expression standing in for every bare reference to it in + // the WGSL body (the same "." accessor + // inputFlatten above describes) — the identCase counterpart of + // inputFlatten's memberExpr lookup, for when the WGSL body refers to + // the input by its own bare name rather than through a struct field. + paramRename map[*wgsl.ParamObj]string + // sharedHelpers is nil for a @compute translator (emitHelperFuncs runs + // against a single translator there, so nothing to share) and, for a + // render pipeline's own vtr/ftr pair, ONE map instance both share + // (TranslateRender's own doc comment) — set true the first time EITHER + // translator emits a given helper's MSL text, so the second translator + // to reach the SAME helper (a vertex and fragment entry calling the + // same WGSL function) skips re-emitting it. Safe unconditionally, not + // just for a resource-free helper: resourceParamDecl/mslType never + // depend on which stage is asking, so the two emissions would be + // byte-for-byte identical text, and Metal rejects an exact duplicate + // function definition in the same translation unit (engine#447 review + // bug #4) — vertex and fragment MSL are concatenated into one + // compilation unit by every caller (gpuCreateRenderPipeline, + // TestTranslateRenderVertexFragmentEndToEnd), never compiled apart. + sharedHelpers map[*wgsl.FuncObj]bool +} + +// mslTypeTR is t's own Metal Shading Language spelling, exactly like the +// package-level mslType, with one addition: t may be the ONE user struct +// type this translation recognizes (outputStructType) — every other +// struct type is still rejected, matching mslType's own "no user structs" +// scope. +func (tr *translator) mslTypeTR(t wgsl.Type) (string, error) { + if st, ok := derefType(t).(*wgsl.StructType); ok { + if tr.outputStructType != nil && st == tr.outputStructType { + return tr.outputStructName, nil + } + return "", unsupported("struct type %s (only an entry point's own recognized output struct is supported)", st.String()) + } + return mslType(t) } func (tr *translator) line(format string, a ...interface{}) { @@ -109,7 +191,8 @@ func (tr *translator) translateEntryPoint(ep *wgsl.EntryPoint) (*Result, error) sizeIndex := -1 if tr.sizesCount > 0 { - sizeIndex = len(tr.bindings) + sizeIndex = tr.bufferCount + tr.bufferCount++ tr.line("struct _Sizes {") tr.indent++ for i := 0; i < tr.sizesCount; i++ { @@ -204,6 +287,18 @@ func (tr *translator) emitHelperFuncs(ep *wgsl.EntryPoint) error { return err } tr.helperExtra[f] = extra + tr.userFuncs[f] = true + + if tr.sharedHelpers != nil { + if tr.sharedHelpers[f] { + // Already emitted verbatim by the other stage's + // translator earlier in this TranslateRender call — see + // sharedHelpers' own doc comment for why that is always + // safe to skip, not just for a resource-free helper. + continue + } + tr.sharedHelpers[f] = true + } retMSL := "void" if f.Ret != wgsl.Void { @@ -239,7 +334,6 @@ func (tr *translator) emitHelperFuncs(ep *wgsl.EntryPoint) error { tr.indent-- tr.line("}") tr.buf.WriteByte('\n') - tr.userFuncs[f] = true } return nil } @@ -489,16 +583,31 @@ func (tr *translator) resolveResources(ep *wgsl.EntryPoint) error { return unsupported("resource %q of type %s (only a scalar or vector )", r.Name, r.Store.String()) } tr.addBinding(r, BindingUniform, elemBytes) + case wgsl.ASHandle: + tex, ok := derefType(r.Store).(*wgsl.TextureType) + if !ok { + return unsupported("resource %q of type %s (only texture_2d)", r.Name, r.Store.String()) + } + if tex.Kind != wgsl.TexSampled || tex.Dim != wgsl.Dim2D || tex.Arrayed { + return unsupported("resource %q: %s (only a non-arrayed texture_2d is supported)", r.Name, tex.String()) + } + if tex.Sampled == nil || tex.Sampled.Kind != wgsl.KU32 { + return unsupported("resource %q: %s (only texture_2d is supported)", r.Name, tex.String()) + } + tr.addBinding(r, BindingTexture, 4) default: - return unsupported("resource %q in address space %s (only and )", r.Name, r.AS) + return unsupported("resource %q in address space %s (only , and a texture handle)", r.Name, r.AS) } } return nil } -// addBinding records r as a resolved Binding of kind at the next Metal -// buffer index, allocating it a _Sizes struct slot too when kind == -// BindingStorageArray. +// addBinding records r as a resolved Binding of kind, allocating its own +// Metal resource index from whichever of tr.bufferCount/tr.textureCount +// matches kind (translator.go's own doc comment on those fields: a buffer +// and a texture bound at the same number never collide in Metal, so they +// are two separate counters, never one shared index), and a _Sizes struct +// slot too when kind == BindingStorageArray. func (tr *translator) addBinding(r *wgsl.VarObj, kind BindingKind, elemBytes int) { idx := len(tr.bindings) sizesIndex := -1 @@ -506,12 +615,20 @@ func (tr *translator) addBinding(r *wgsl.VarObj, kind BindingKind, elemBytes int sizesIndex = tr.sizesCount tr.sizesCount++ } + var metalIdx int + if kind == BindingTexture { + metalIdx = tr.textureCount + tr.textureCount++ + } else { + metalIdx = tr.bufferCount + tr.bufferCount++ + } tr.resources[r] = idx tr.bindings = append(tr.bindings, Binding{ Group: intOr(r.Group, 0), BindingIndex: intOr(r.Binding, 0), Name: r.Name, - MetalIndex: idx, + MetalIndex: metalIdx, Kind: kind, ElemBytes: elemBytes, SizesIndex: sizesIndex, @@ -558,23 +675,43 @@ func (tr *translator) resourceParamDecl(r *wgsl.VarObj) (string, error) { return "", err } return fmt.Sprintf("constant %s&", uMSL), nil + case BindingTexture: + return "texture2d", nil } return "", unsupported("resource %q: unknown binding kind", r.Name) } -// entryParams builds the kernel function's own parameter list: one -// `[[buffer(N)]]` parameter per resolved resource (its own MSL shape from -// resourceParamDecl), the `_Sizes` struct if sizeIndex >= 0, then one -// builtin parameter per ep.Inputs entry. -func (tr *translator) entryParams(ep *wgsl.EntryPoint, sizeIndex int) ([]string, error) { +// resourceEntryParams is the `[[buffer(N)]]`/`[[texture(N)]]` parameter +// list for resources (resourceParamDecl's own MSL shape, decorated with +// each binding's own resolved Metal index) — shared by entryParams (the +// @compute kernel's own parameter list) and render.go's stageEntryParams +// (a @vertex/@fragment entry's own resource parameters), so the +// buffer-vs-texture attribute choice is made in exactly one place. +func (tr *translator) resourceEntryParams(resources []*wgsl.VarObj) ([]string, error) { var params []string - for _, r := range ep.Resources { + for _, r := range resources { decl, err := tr.resourceParamDecl(r) if err != nil { return nil, err } b := tr.bindings[tr.resources[r]] - params = append(params, fmt.Sprintf("%s %s [[buffer(%d)]]", decl, identMSL(r.Name), b.MetalIndex)) + attr := fmt.Sprintf("buffer(%d)", b.MetalIndex) + if b.Kind == BindingTexture { + attr = fmt.Sprintf("texture(%d)", b.MetalIndex) + } + params = append(params, fmt.Sprintf("%s %s [[%s]]", decl, identMSL(r.Name), attr)) + } + return params, nil +} + +// entryParams builds the kernel function's own parameter list: one +// `[[buffer(N)]]` parameter per resolved resource (its own MSL shape from +// resourceParamDecl), the `_Sizes` struct if sizeIndex >= 0, then one +// builtin parameter per ep.Inputs entry. +func (tr *translator) entryParams(ep *wgsl.EntryPoint, sizeIndex int) ([]string, error) { + params, err := tr.resourceEntryParams(ep.Resources) + if err != nil { + return nil, err } if sizeIndex >= 0 { params = append(params, fmt.Sprintf("constant _Sizes& _sizes [[buffer(%d)]]", sizeIndex)) diff --git a/wgslmsl/wgslmsl.go b/wgslmsl/wgslmsl.go index b74eb8d..eec2dd0 100644 --- a/wgslmsl/wgslmsl.go +++ b/wgslmsl/wgslmsl.go @@ -26,6 +26,13 @@ // separate document. Expand only on a confirmed real need (this package's // own history should read like the rest of this engine's: every capability // here was asked for). +// +// TranslateRender (render.go) is a second, separate entry point added for +// engine#415 (WebGPU roadmap M7): a @vertex or @fragment entry point, +// translated under the SAME bounded-scope discipline as Translate's own +// @compute path (an unsupported WGSL shape is a named rejection, never a +// silent wrong translation) — see render.go's own doc comment for exactly +// what subset of vertex/fragment/texture WGSL it accepts. package wgslmsl import ( @@ -67,6 +74,19 @@ const ( // spec, not assumed), so a uniform resource never needs bounds // accounting either. BindingUniform + // BindingTexture is `var name: texture_2d` (engine#415, M7: the + // one texture shape TranslateRender's @fragment path reads, via + // textureLoad — see its own doc comment) — emitted as a Metal + // `texture2d` parameter, bound at its own [[texture(N)]] index, + // a SEPARATE Metal index namespace from every other BindingKind's own + // [[buffer(N)]] (MetalIndex is never comparable across kinds; the host + // must bind a BindingTexture at Encoder.Texture/RenderEncoder's own + // texture slot, never a buffer slot). Never produced for a @compute + // entry point's own Translate path (resolveResources's ASHandle case + // is reachable from TranslateRender only) and never for a @vertex + // stage either (translateStageEntry rejects it: go-macos/metal's + // RenderEncoder has no vertex-stage texture binding at all). + BindingTexture ) func (k BindingKind) String() string { @@ -77,6 +97,8 @@ func (k BindingKind) String() string { return "atomic" case BindingUniform: return "uniform" + case BindingTexture: + return "texture" default: return "unknown" } diff --git a/wgslmsl/wgslmsl_test.go b/wgslmsl/wgslmsl_test.go index 0507b0a..a8ee093 100644 --- a/wgslmsl/wgslmsl_test.go +++ b/wgslmsl/wgslmsl_test.go @@ -718,6 +718,71 @@ func TestUnsupportedConstructsAreRejected(t *testing.T) { } } `, + // resolveResources's own ASHandle case only ever accepts a + // non-arrayed texture_2d: a texture of another dimension is + // otherwise a legal WGSL handle resource (go-gfx/wgsl's own Check + // accepts it), so this package rejects it itself. texture_3d + // is used here rather than an arrayed texture_2d_array; a + // prior version of this comment claimed the arrayed form's 4-arg + // textureLoad call reached expr.go's own arity check first, + // masking this one — re-measured (engine#447) and found + // backwards: resolveResources runs before any body statement is + // translated and rejects texture_2d_array itself on sight + // ("resource %q: %s (only a non-arrayed texture_2d is + // supported)"), regardless of how the call that follows would + // have been shaped. texture_3d is kept here only because it + // was already hand-mutation-verified to isolate this check + // (translator.go, the ASHandle Dim/Arrayed/Kind guard). + "non-2D texture handle resource": ` + @group(0) @binding(0) var tex: texture_3d; + @group(0) @binding(1) var out: array; + @compute @workgroup_size(1) + fn main(@builtin(global_invocation_id) id: vec3) { + out[id.x] = textureLoad(tex, vec3(0, 0, 0), 0).x; + } + `, + // Same resolveResources case, its sampled-type check: Check accepts + // a texture_2d, this package only ever supports + // texture_2d. + "non-u32 sampled texture handle resource": ` + @group(0) @binding(0) var tex: texture_2d; + @group(0) @binding(1) var out: array; + @compute @workgroup_size(1) + fn main(@builtin(global_invocation_id) id: vec3) { + out[id.x] = textureLoad(tex, vec2(0, 0), 0).x; + } + `, + // entryParams's own resourceEntryParams call rejects an f16 + // uniform resource: Check accepts f16 as a host-shareable + // var type, but this package's own mslType (through + // resourceParamDecl) only ever accepts bool/i32/u32/f32. + "f16 uniform resource": ` + enable f16; + @group(0) @binding(0) var x: f16; + @group(0) @binding(1) var out: array; + @compute @workgroup_size(1) + fn main(@builtin(global_invocation_id) id: vec3) { + out[id.x] = f32(x); + } + `, + // scalarOrVecElemBytes (types.go) does not reject f16 the way + // mslType/mslScalar do — it returns 4 unconditionally for any + // non-bool scalar, including f16 — but this is not a live gap: + // resourceEntryParams always calls resourceParamDecl for every + // resource, and resourceParamDecl's own mslType(arr.Elem) call on + // the SAME element type rejects f16 before entryParams/ + // stageEntryParams can ever return successfully. See + // TestRejectsF16StorageArrayViaResourceParamDecl for the specific + // assertion that it is resourceParamDecl's check, not + // resolveResources' silent ElemBytes=4, that is actually surfaced. + "f16 runtime storage array": ` + enable f16; + @group(0) @binding(0) var data: array; + @compute @workgroup_size(1) + fn main(@builtin(global_invocation_id) id: vec3) { + data[id.x] = data[id.x] + 1.0h; + } + `, } for name, src := range cases { t.Run(name, func(t *testing.T) { @@ -729,6 +794,40 @@ func TestUnsupportedConstructsAreRejected(t *testing.T) { } } +// TestRejectsF16StorageArrayViaResourceParamDecl confirms, with a specific +// message, which of two checks actually rejects an f16 runtime storage +// array (also covered less specifically by TestUnsupportedConstructsAreRejected's +// own "f16 runtime storage array" case above): resolveResources calls +// scalarOrVecElemBytes(store.Elem) on the array's element type before +// addBinding, and that function does NOT reject f16 — it returns 4 +// unconditionally for any non-bool scalar — so resolveResources itself +// accepts an f16 storage array and records a wrong (but never observed) +// ElemBytes. This is not a live correctness gap: resourceEntryParams is +// always the first statement of entryParams/stageEntryParams, and it +// calls resourceParamDecl for every one of ep.Resources; resourceParamDecl's +// own BindingStorageArray case calls mslType(arr.Elem) on the SAME element +// type, which does reject f16, before any success path can return a +// Result. Asserting resourceParamDecl's own message here (not just +// err != nil) confirms this is the check actually surfaced, not +// resolveResources' silent wrong ElemBytes. +func TestRejectsF16StorageArrayViaResourceParamDecl(t *testing.T) { + src := ` + enable f16; + @group(0) @binding(0) var data: array; + @compute @workgroup_size(1) + fn main(@builtin(global_invocation_id) id: vec3) { + data[id.x] = data[id.x] + 1.0h; + } + ` + _, err := Translate(src, Options{}) + if err == nil { + t.Fatal("Translate succeeded, want a rejection: f16 runtime storage array") + } + if !strings.Contains(err.Error(), "only bool/i32/u32/f32") { + t.Fatalf("error = %v, want resourceParamDecl's own mslType rejection", err) + } +} + // TestNoComputeEntryPoint and TestMultipleComputeEntryPointsNeedASelector // cover selectEntryPoint's own two failure shapes. func TestNoComputeEntryPoint(t *testing.T) {