From 5ba8ba5799f527f5ad3e6dd6700b3eeaea2bf5fe Mon Sep 17 00:00:00 2001 From: "J4ck1e:)" Date: Tue, 24 Nov 2026 22:23:22 +0800 Subject: [PATCH] fix(gpu): skip draws after rejected render bindings Invalidate rejected binding slots until a valid rebind, without blocking draws that do not use them. Report rejected binds and skipped draws in debug builds. Fixes #2253 --- changelog.d/gpu-rejected-bindings.md | 3 + docs/architecture/gpu.md | 1 + docs/public/en/testing.md | 2 +- docs/public/zh/testing.md | 2 +- gpu/debug_off.go | 3 + gpu/debug_on.go | 20 ++- gpu/device.go | 170 +++++++++++++----- gpu/render_bindings_test.go | 247 +++++++++++++++++++++++++++ nsgotest/gpu.go | 18 ++ skills/nsgo/references/testing.md | 2 +- 10 files changed, 423 insertions(+), 45 deletions(-) create mode 100644 changelog.d/gpu-rejected-bindings.md create mode 100644 gpu/render_bindings_test.go diff --git a/changelog.d/gpu-rejected-bindings.md b/changelog.d/gpu-rejected-bindings.md new file mode 100644 index 000000000..423b3f248 --- /dev/null +++ b/changelog.d/gpu-rejected-bindings.md @@ -0,0 +1,3 @@ +### Fixed + +- Skip GPU draws that would reuse a rejected render binding (#2253 by @J4ck1e2000). diff --git a/docs/architecture/gpu.md b/docs/architecture/gpu.md index aa0ecaaed..bc7bd0997 100644 --- a/docs/architecture/gpu.md +++ b/docs/architecture/gpu.md @@ -292,6 +292,7 @@ return gpu.View{ - **Disposal via `*core.Scope`**: Every resource created through `Device` (`Buffer`, `Texture`, `Sampler`, `BindGroupLayout`, `BindGroup`, `Pipeline`) implements `Close() error` for immediate release and also registers a cleanup on the `*core.Scope` passed to its constructor. Unmounting `gpu.View`, disposing the owning scope, or closing the engine enqueues release commands for all live handles and cancels any pending `ReadTexture` callbacks. Late backend events targeting released IDs are dropped. - **Validation and error reporting**: Descriptor errors (misaligned uniform offsets, missing usage flags, vertex layout mismatches, invalid shader entry points, or unavailable features) are validated synchronously in Go on the engine goroutine and returned as `error` values from `Create*` and `Compile*` before reaching the backend. Runtime backend errors (driver compilation rejection, GPU out-of-memory) arrive asynchronously on `View.OnError` as `gpu.Error` (`ErrUnsupported`, `ErrInvalidDescriptor`, `ErrShaderCompile`, `ErrOutOfMemory`, `ErrDeviceLost`, `ErrFailed`). +- **Rejected render bindings**: A rejected `SetVertexBuffer` or `SetBindGroup` invalidates only its slot. A draw whose pipeline uses that slot is skipped until a valid bind replaces it. Indexed draws also require a valid `SetIndexBuffer`; rejecting an index buffer does not block non-indexed draws. The recorder never sends the skipped draw to a backend. Builds with `nsgodev` or `nsgotest` log the rejected binds and skipped draws and record them as pass markers. - **Device-loss recovery**: Desktop driver resets (`DXGI_ERROR_DEVICE_REMOVED` on Windows), browser tab/GPU resets (`webglcontextlost`, `GPUDevice.lost`), and Android EGL context destruction (`EGL_CONTEXT_LOST` on Activity pause) all map to one contract: 1. The backend emits `EventGPUDeviceLost` with a reason (`LostReset`, `LostDestroyed`, `LostOutOfMemory`). 2. `core` bumps the surface's device generation, marks all handles from the lost `Device` invalid (subsequent writes/submits become no-ops rather than panicking), and calls `View.OnDeviceLost`. diff --git a/docs/public/en/testing.md b/docs/public/en/testing.md index 0f725e7ff..f86a00fbc 100644 --- a/docs/public/en/testing.md +++ b/docs/public/en/testing.md @@ -102,7 +102,7 @@ Windowless rendering and font registration currently support macOS. Other target `app.Find(selector).Kind` is a `nsgotest.ViewKind`; compare it with constants such as `nsgotest.KindText`, `KindInput`, `KindCanvas` or `KindGPU` when a test needs to inspect the mounted view form. -Headless GPU tests can use `app.Surface("title:Inspector").GPUReadPixels("id:viewport")` for a window's software GPU pixels. `Surface.TriggerGPUDeviceLost` and `Surface.RestoreGPUDevice` simulate loss and recovery in that window, using its pixel ratio. Devices and readback callbacks stay separate even when view IDs repeat across windows; `app.GPUFrames()` records submissions across the whole app. These helpers operate on the headless software GPU model. +Headless GPU tests can use `app.Surface("title:Inspector").GPUReadPixels("id:viewport")` for a window's software GPU pixels. `Surface.TriggerGPUDeviceLost` and `Surface.RestoreGPUDevice` simulate loss and recovery in that window, using its pixel ratio. Devices and readback callbacks stay separate even when view IDs repeat across windows; `app.GPUFrames()` records submissions across the whole app. With `-- -tags=nsgotest`, `app.GPUDebugEvents("id:viewport")` includes `pass_marker` events for rejected render bindings and skipped draws. `nsgotest.UpdaterState(core.UpdaterState{...})` seeds updater capability and preferences before the first render, headless and on native targets. Set `app.Update` to supply each check result; preference changes are modeled without contacting an update feed. diff --git a/docs/public/zh/testing.md b/docs/public/zh/testing.md index 2ef0b5297..4ef3f30a2 100644 --- a/docs/public/zh/testing.md +++ b/docs/public/zh/testing.md @@ -94,7 +94,7 @@ func TestMain(m *testing.M) { `app.Find(selector).Kind` 的类型是 `nsgotest.ViewKind`。需要检查挂载视图的形式时,可将它与 `nsgotest.KindText`、`KindInput`、`KindCanvas` 或 `KindGPU` 等常量比较。 -无头 GPU 测试可用 `app.Surface("title:Inspector").GPUReadPixels("id:viewport")` 读取对应窗口的软件 GPU 像素。`Surface.TriggerGPUDeviceLost` 和 `Surface.RestoreGPUDevice` 模拟该窗口的设备丢失与恢复,并使用该窗口的像素比例。即使不同窗口中的视图 ID 相同,设备和回读回调也各自独立;`app.GPUFrames()` 记录整个应用的提交。这些辅助方法作用于无头软件 GPU 模型。 +无头 GPU 测试可用 `app.Surface("title:Inspector").GPUReadPixels("id:viewport")` 读取对应窗口的软件 GPU 像素。`Surface.TriggerGPUDeviceLost` 和 `Surface.RestoreGPUDevice` 模拟该窗口的设备丢失与恢复,并使用该窗口的像素比例。即使不同窗口中的视图 ID 相同,设备和回读回调也各自独立;`app.GPUFrames()` 记录整个应用的提交。传入 `-- -tags=nsgotest` 后,`app.GPUDebugEvents("id:viewport")` 中的 `pass_marker` 事件会记录被拒绝的渲染绑定和被跳过的绘制。 `nsgotest.UpdaterState(core.UpdaterState{...})` 可在第一次渲染前设置更新器的能力和偏好,适用于无窗口测试及原生目标。通过 `app.Update` 提供每次检查的结果;偏好变更由测试模型处理,不访问更新源。 diff --git a/gpu/debug_off.go b/gpu/debug_off.go index e37f88c06..7dbb15dc7 100644 --- a/gpu/debug_off.go +++ b/gpu/debug_off.go @@ -19,4 +19,7 @@ func (*RenderPass) pushDebugGroup(string) {} func (*RenderPass) popDebugGroup() {} func (*RenderPass) insertDebugMarker(string) {} +func (*RenderPass) debugRejectedBind(string, uint32) {} +func (*RenderPass) debugSkippedDraw(string, string, uint32) {} + func appendFrameDebugOps(*driver.GPUFrame, []driver.GPUDebugOp, int) {} diff --git a/gpu/debug_on.go b/gpu/debug_on.go index d1ace62a4..05bfcc47b 100644 --- a/gpu/debug_on.go +++ b/gpu/debug_on.go @@ -2,7 +2,12 @@ package gpu -import "github.com/nsgo-dev/nsgo/internal/driver" +import ( + "fmt" + "log" + + "github.com/nsgo-dev/nsgo/internal/driver" +) // DebugLabelsEnabled reports whether GPU debug labels, groups, and markers are recorded in this build (true under nsgodev or nsgotest, false in release builds). const DebugLabelsEnabled = true @@ -77,6 +82,19 @@ func (p *RenderPass) insertDebugMarker(label string) { }) } +func (p *RenderPass) debugRejectedBind(operation string, slot uint32) { + p.debugBinding(fmt.Sprintf("gpu.bind_rejected operation=%s slot=%d", operation, slot)) +} + +func (p *RenderPass) debugSkippedDraw(operation, binding string, slot uint32) { + p.debugBinding(fmt.Sprintf("gpu.draw_skipped operation=%s binding=%s slot=%d", operation, binding, slot)) +} + +func (p *RenderPass) debugBinding(label string) { + log.Print(label) + p.insertDebugMarker(label) +} + func appendFrameDebugOps(frame *driver.GPUFrame, ops []driver.GPUDebugOp, passOffset int) { if len(ops) == 0 { return diff --git a/gpu/device.go b/gpu/device.go index 34d61d92e..ecfc726fe 100644 --- a/gpu/device.go +++ b/gpu/device.go @@ -750,16 +750,17 @@ func (g *BindGroup) Close() error { // Pipeline is an immutable vertex+fragment GPU render pipeline. type Pipeline struct { - dev *Device - id driver.GPUID - epoch uint32 - desc PipelineDesc - cacheKey string - retained bool - ready atomic.Bool - done chan struct{} - compileErr error - closed bool + dev *Device + id driver.GPUID + epoch uint32 + desc PipelineDesc + vertexBuffers []driver.GPUVertexBufferLayout + cacheKey string + retained bool + ready atomic.Bool + done chan struct{} + compileErr error + closed bool } // ID returns the pipeline's numeric handle. @@ -1645,13 +1646,14 @@ func (d *Device) CreatePipeline(cx *core.Scope, desc PipelineDesc) (*Pipeline, e close(done) retained := desc.Retained || d.retainResources p := &Pipeline{ - dev: d, - id: id, - epoch: d.generation, - desc: desc, - cacheKey: key, - retained: retained, - done: done, + dev: d, + id: id, + epoch: d.generation, + desc: desc, + vertexBuffers: dd.VertexBuffers, + cacheKey: key, + retained: retained, + done: done, } p.ready.Store(true) if retained { @@ -1681,13 +1683,14 @@ func (d *Device) CreatePipelineAsync(cx *core.Scope, desc PipelineDesc, onReady id := d.nextID() retained := desc.Retained || d.retainResources p := &Pipeline{ - dev: d, - id: id, - epoch: d.generation, - desc: desc, - cacheKey: key, - retained: retained, - done: make(chan struct{}), + dev: d, + id: id, + epoch: d.generation, + desc: desc, + vertexBuffers: dd.VertexBuffers, + cacheKey: key, + retained: retained, + done: make(chan struct{}), } if retained { d.retainedPipelines = append(d.retainedPipelines, p) @@ -2006,6 +2009,7 @@ func (d *Device) restoreRetainedFrom(prev *Device) { p.dev = d p.id = id p.epoch = d.generation + p.vertexBuffers = dd.VertexBuffers p.cacheKey = key p.ready.Store(true) d.retainedPipelines = append(d.retainedPipelines, p) @@ -2605,13 +2609,19 @@ func (e *Encoder) Finish() *CommandBuffer { return &CommandBuffer{dev: e.dev, epoch: e.epoch, copies: e.copies, passes: e.passes, debugOps: e.debugOps} } -// RenderPass records drawing state and draw calls for one render pass. +// RenderPass records drawing state and draw calls for one render pass. A rejected +// buffer or bind group bind prevents subsequent draws that use that binding until +// it is rebound with a valid handle. Indexed draws also need an index buffer. +// Builds with nsgodev or nsgotest report rejected binds and the draws they skip. type RenderPass struct { - enc *Encoder - pass driver.GPUPass - ended bool - invalid bool - pipeValid bool + enc *Encoder + pass driver.GPUPass + ended bool + invalid bool + pipe *Pipeline + indexValid bool + rejectedVertexBuffers map[uint32]struct{} + rejectedBindGroups map[uint32]struct{} } // PushDebugGroup begins a nested debug group inside this render pass. It is a zero-cost no-op in release builds (without nsgodev or nsgotest). @@ -2690,10 +2700,10 @@ func (p *RenderPass) SetPipeline(pipe *Pipeline) { return } if pipe == nil || !pipe.Ready() || p.enc == nil || pipe.dev != p.enc.dev || pipe.epoch != p.enc.epoch { - p.pipeValid = false + p.pipe = nil return } - p.pipeValid = true + p.pipe = pipe p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{ Kind: driver.GPUCmdSetPipeline, ID: pipe.id, @@ -2701,10 +2711,19 @@ func (p *RenderPass) SetPipeline(pipe *Pipeline) { } // SetBindGroup binds group to @group(slot) with optional dynamic offsets. +// A nil, closed, foreign or stale handle invalidates that slot until a valid rebind. func (p *RenderPass) SetBindGroup(slot uint32, group *BindGroup, dynamicOffsets ...uint32) { - if p.ended || p.invalid || group == nil || !group.Valid() || p.enc == nil || group.dev != p.enc.dev || group.epoch != p.enc.epoch { + if p.ended || p.invalid { + return + } + if !group.Valid() || p.enc == nil || group.dev != p.enc.dev || group.epoch != p.enc.epoch { + rejectBinding(&p.rejectedBindGroups, slot) + p.debugRejectedBind("SetBindGroup", slot) return } + if len(p.rejectedBindGroups) != 0 { + delete(p.rejectedBindGroups, slot) + } p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{ Kind: driver.GPUCmdSetBindGroup, Slot: slot, @@ -2714,10 +2733,19 @@ func (p *RenderPass) SetBindGroup(slot uint32, group *BindGroup, dynamicOffsets } // SetVertexBuffer binds buf to vertex buffer slot starting at byte offset. +// A nil, closed, foreign or stale handle invalidates that slot until a valid rebind. func (p *RenderPass) SetVertexBuffer(slot uint32, buf *Buffer, offset uint64) { - if p.ended || p.invalid || buf == nil || !buf.Valid() || p.enc == nil || buf.dev != p.enc.dev || buf.epoch != p.enc.epoch { + if p.ended || p.invalid { + return + } + if !buf.Valid() || p.enc == nil || buf.dev != p.enc.dev || buf.epoch != p.enc.epoch { + rejectBinding(&p.rejectedVertexBuffers, slot) + p.debugRejectedBind("SetVertexBuffer", slot) return } + if len(p.rejectedVertexBuffers) != 0 { + delete(p.rejectedVertexBuffers, slot) + } p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{ Kind: driver.GPUCmdSetVertexBuffer, Slot: slot, @@ -2727,8 +2755,15 @@ func (p *RenderPass) SetVertexBuffer(slot uint32, buf *Buffer, offset uint64) { } // SetIndexBuffer binds buf as the active index buffer. +// A nil, closed, foreign or stale handle invalidates it until a valid rebind. +// Until then indexed draws are skipped; non-indexed draws are unaffected. func (p *RenderPass) SetIndexBuffer(buf *Buffer, format IndexFormat, offset uint64) { - if p.ended || p.invalid || buf == nil || !buf.Valid() || p.enc == nil || buf.dev != p.enc.dev || buf.epoch != p.enc.epoch { + if p.ended || p.invalid { + return + } + p.indexValid = buf.Valid() && p.enc != nil && buf.dev == p.enc.dev && buf.epoch == p.enc.epoch + if !p.indexValid { + p.debugRejectedBind("SetIndexBuffer", 0) return } p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{ @@ -2739,6 +2774,58 @@ func (p *RenderPass) SetIndexBuffer(buf *Buffer, format IndexFormat, offset uint }) } +// Allocate slot tracking only on rejection. Valid binds clear just their own slot. +func rejectBinding(rejected *map[uint32]struct{}, slot uint32) { + if *rejected == nil { + *rejected = make(map[uint32]struct{}) + } + (*rejected)[slot] = struct{}{} +} + +func (p *Pipeline) usesBindGroup(slot uint32) bool { + if len(p.desc.Layouts) != 0 { + return uint64(slot) < uint64(len(p.desc.Layouts)) + } + // Pipelines without explicit layouts can still bind shader resources. + for _, stage := range [...]ShaderStage{p.desc.Vertex, p.desc.Fragment} { + if stage.Module != nil { + for _, binding := range stage.Module.ir.Bindings { + if binding.Group == slot { + return true + } + } + } + } + return false +} + +func (p *RenderPass) canDraw(operation string, indexed bool) bool { + if p.ended || p.invalid || p.pipe == nil { + return false + } + if indexed && !p.indexValid { + p.debugSkippedDraw(operation, "index_buffer", 0) + return false + } + return (len(p.rejectedVertexBuffers) == 0 && len(p.rejectedBindGroups) == 0) || p.rejectedBindingsAllowDraw(operation) +} + +func (p *RenderPass) rejectedBindingsAllowDraw(operation string) bool { + for slot := range p.rejectedVertexBuffers { + if uint64(slot) < uint64(len(p.pipe.vertexBuffers)) && len(p.pipe.vertexBuffers[slot].Attributes) != 0 { + p.debugSkippedDraw(operation, "vertex_buffer", slot) + return false + } + } + for slot := range p.rejectedBindGroups { + if p.pipe.usesBindGroup(slot) { + p.debugSkippedDraw(operation, "bind_group", slot) + return false + } + } + return true +} + // SetStencilReference sets the stencil reference value. func (p *RenderPass) SetStencilReference(ref uint32) { if p.ended || p.invalid { @@ -2763,7 +2850,7 @@ func (p *RenderPass) SetBlendConstant(r, g, b, a float32) { // Draw draws vertexCount non-indexed vertices starting at firstVertex. func (p *RenderPass) Draw(vertexCount, firstVertex uint32) { - if p.ended || p.invalid || !p.pipeValid { + if !p.canDraw("Draw", false) { return } p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{ @@ -2772,9 +2859,9 @@ func (p *RenderPass) Draw(vertexCount, firstVertex uint32) { }) } -// DrawIndexed draws indexCount indexed vertices. +// DrawIndexed draws indexCount indexed vertices if an index buffer is bound. func (p *RenderPass) DrawIndexed(indexCount, firstIndex uint32, baseVertex int32) { - if p.ended || p.invalid || !p.pipeValid { + if !p.canDraw("DrawIndexed", true) { return } p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{ @@ -2785,7 +2872,7 @@ func (p *RenderPass) DrawIndexed(indexCount, firstIndex uint32, baseVertex int32 // DrawInstanced draws instanceCount instances of vertexCount vertices. func (p *RenderPass) DrawInstanced(vertexCount, instanceCount, firstVertex, firstInstance uint32) { - if p.ended || p.invalid || !p.pipeValid { + if !p.canDraw("DrawInstanced", false) { return } p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{ @@ -2794,9 +2881,10 @@ func (p *RenderPass) DrawInstanced(vertexCount, instanceCount, firstVertex, firs }) } -// DrawIndexedInstanced draws instanceCount instances of indexCount indexed vertices. +// DrawIndexedInstanced draws instanceCount instances of indexCount indexed +// vertices if an index buffer is bound. func (p *RenderPass) DrawIndexedInstanced(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32) { - if p.ended || p.invalid || !p.pipeValid { + if !p.canDraw("DrawIndexedInstanced", true) { return } p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{ diff --git a/gpu/render_bindings_test.go b/gpu/render_bindings_test.go new file mode 100644 index 000000000..680a97f73 --- /dev/null +++ b/gpu/render_bindings_test.go @@ -0,0 +1,247 @@ +package gpu_test + +import ( + "slices" + "testing" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/gpu" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func TestRenderPassRejectedBindings(t *testing.T) { + const testID = "render-bindings" + const selector = "id:" + testID + const otherID = "foreign-device" + const otherSelector = "id:" + otherID + var dev, foreign *gpu.Device + var gpuErrors []gpu.Error + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + style := core.Style{Width: core.Pt(8), Height: core.Pt(8)} + return core.View{Children: []core.Node{ + gpu.View(cx, gpu.ViewProps{ + TestID: testID, + Style: style, + OnReady: func(d *gpu.Device) { dev = d }, + OnError: func(err gpu.Error) { gpuErrors = append(gpuErrors, err) }, + }), + gpu.View(cx, gpu.ViewProps{ + TestID: otherID, + Style: style, + OnReady: func(d *gpu.Device) { foreign = d }, + }), + }} + }, nsgotest.Size(16, 16), nsgotest.ManualFrames()) + if dev == nil || foreign == nil { + t.Fatal("headless GPU devices did not become ready") + } + + vertexData := packFloat32s(0, 0, 0, 0.5, 0, 0, 0, 0.5, 0) + indexData := packUint16s(0, 1, 2, 0) + buffer := func(d *gpu.Device, usage gpu.BufferUsage, data []byte) *gpu.Buffer { + t.Helper() + buf, err := d.CreateBuffer(nil, gpu.BufferDesc{Usage: usage, Data: data}) + if err != nil { + t.Fatal(err) + } + return buf + } + + staleVertex := buffer(dev, gpu.UsageVertex, vertexData) + staleIndex := buffer(dev, gpu.UsageIndex, indexData) + app.TriggerGPUDeviceLost(selector, nsgotest.GPULostReset, "test reset") + app.RestoreGPUDevice(selector) + app.TriggerGPUDeviceLost(otherSelector, nsgotest.GPULostReset, "test reset") + app.RestoreGPUDevice(otherSelector) + if foreign == dev || foreign.Epoch() != dev.Epoch() { + t.Fatal("expected two distinct devices at the same epoch") + } + if staleVertex.Valid() || staleIndex.Valid() || dev.Epoch() == staleVertex.Epoch() { + t.Fatal("device reset did not leave the old buffers at an earlier epoch") + } + + // Use distinct, correctly sized buffers so even an erroneously recorded draw + // in these checks never reads out of range. + vertex := buffer(dev, gpu.UsageVertex, vertexData) + colors := buffer(dev, gpu.UsageVertex, packFloat32s( + 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, + )) + index := buffer(dev, gpu.UsageIndex, indexData) + closedVertex := buffer(dev, gpu.UsageVertex, vertexData) + closedIndex := buffer(dev, gpu.UsageIndex, indexData) + if err := closedVertex.Close(); err != nil { + t.Fatal(err) + } + if err := closedIndex.Close(); err != nil { + t.Fatal(err) + } + foreignVertex := buffer(foreign, gpu.UsageVertex, vertexData) + foreignIndex := buffer(foreign, gpu.UsageIndex, indexData) + + uniform := buffer(dev, gpu.UsageUniform, packFloat32s( + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, + )) + layout, err := dev.CreateBindGroupLayout(nil, []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageVertex, Type: gpu.BindingUniform}, + }) + if err != nil { + t.Fatal(err) + } + group, err := dev.CreateBindGroup(nil, layout, []gpu.BindGroupEntry{{Binding: 0, Buffer: uniform}}) + if err != nil { + t.Fatal(err) + } + mod := gpu.MustCompileWGSL(color3DWGSL) + desc := gpu.PipelineDesc{ + Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_main"}, + Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs_main"}, + VertexBuffers: []gpu.VertexBufferLayout{ + {Stride: 12, Attributes: []gpu.VertexAttribute{{Location: 0, Format: gpu.VertexFloat32x3}}}, + {Stride: 16, Attributes: []gpu.VertexAttribute{{Location: 1, Format: gpu.VertexFloat32x4}}}, + }, + Targets: []gpu.ColorTargetState{{Format: dev.SurfaceFormat()}}, + } + pipeline := func(desc gpu.PipelineDesc) *gpu.Pipeline { + t.Helper() + pipe, err := dev.CreatePipeline(nil, desc) + if err != nil { + t.Fatal(err) + } + return pipe + } + autoLayout := pipeline(desc) + desc.Layouts = []*gpu.BindGroupLayout{layout} + pipe := pipeline(desc) + procedural := gpu.MustCompileWGSL(` +@vertex fn vs_main() -> @builtin(position) vec4 { + return vec4(0.0, 0.0, 0.0, 1.0); +} +@fragment fn fs_main() -> @location(0) vec4 { + return vec4(1.0, 0.0, 0.0, 1.0); +}`) + noBindings := pipeline(gpu.PipelineDesc{ + Vertex: gpu.ShaderStage{Module: procedural, EntryPoint: "vs_main"}, + Fragment: gpu.ShaderStage{Module: procedural, EntryPoint: "fs_main"}, + Targets: desc.Targets, + }) + + checkFrame := func(name string, draws int, instances uint64, record func(*gpu.RenderPass), markers ...string) { + t.Helper() + framesBefore := len(app.GPUFrames()) + eventsBefore := len(app.GPUDebugEvents(selector)) + app.Post(func() { + enc := dev.BeginEncoder() + pass := enc.BeginRenderPass(gpu.RenderPassDesc{}) + record(pass) + pass.End() + dev.Submit(enc.Finish()) + }) + app.Settle() + if len(gpuErrors) != 0 { + t.Fatalf("%s: unexpected backend GPU errors: %v", name, gpuErrors) + } + frames := app.GPUFrames()[framesBefore:] + if len(frames) != 1 || frames[0].PassesCount != 1 || frames[0].DrawsCount != draws || frames[0].InstancesCount != instances { + t.Fatalf("%s: got frames %+v, want a single pass with %d draws and %d instances", name, frames, draws, instances) + } + var got []string + for _, event := range app.GPUDebugEvents(selector)[eventsBefore:] { + if event.Kind == "pass_marker" { + got = append(got, event.Label) + } + } + if !gpu.DebugLabelsEnabled { + markers = nil + } + if !slices.Equal(got, markers) { + t.Errorf("%s: debug markers = %q, want %q", name, got, markers) + } + } + bind := func(pass *gpu.RenderPass) { + pass.SetPipeline(pipe) + pass.SetVertexBuffer(0, vertex, 0) + pass.SetVertexBuffer(1, colors, 0) + pass.SetBindGroup(0, group) + } + drawAll := func(pass *gpu.RenderPass) { + pass.Draw(3, 0) + pass.DrawInstanced(3, 2, 0, 0) + pass.DrawIndexed(3, 0, 0) + pass.DrawIndexedInstanced(3, 2, 0, 0, 0) + } + + // Keep the app and its frame steps on the test goroutine. + checkFrame("no index bound", 2, 3, func(pass *gpu.RenderPass) { + bind(pass) + drawAll(pass) + }, "gpu.draw_skipped operation=DrawIndexed binding=index_buffer slot=0", + "gpu.draw_skipped operation=DrawIndexedInstanced binding=index_buffer slot=0") + for _, tc := range []struct { + name string + vertex, index *gpu.Buffer + }{ + {"nil", nil, nil}, + {"closed", closedVertex, closedIndex}, + {"foreign", foreignVertex, foreignIndex}, + {"stale epoch", staleVertex, staleIndex}, + } { + checkFrame(tc.name+" vertex", 5, 7, func(pass *gpu.RenderPass) { + bind(pass) + pass.SetIndexBuffer(index, gpu.IndexUint16, 0) + pass.Draw(3, 0) + pass.SetVertexBuffer(0, tc.vertex, 0) + drawAll(pass) + pass.SetVertexBuffer(1, colors, 0) // Only this slot is repaired. + pass.Draw(3, 0) + pass.SetVertexBuffer(0, vertex, 0) + drawAll(pass) + }, "gpu.bind_rejected operation=SetVertexBuffer slot=0", + "gpu.draw_skipped operation=Draw binding=vertex_buffer slot=0", + "gpu.draw_skipped operation=DrawInstanced binding=vertex_buffer slot=0", + "gpu.draw_skipped operation=DrawIndexed binding=vertex_buffer slot=0", + "gpu.draw_skipped operation=DrawIndexedInstanced binding=vertex_buffer slot=0", + "gpu.draw_skipped operation=Draw binding=vertex_buffer slot=0") + checkFrame(tc.name+" index", 5, 7, func(pass *gpu.RenderPass) { + bind(pass) + pass.SetIndexBuffer(index, gpu.IndexUint16, 0) + pass.DrawIndexed(3, 0, 0) + pass.SetIndexBuffer(tc.index, gpu.IndexUint16, 0) + drawAll(pass) // Non-indexed draws still succeed. + pass.SetVertexBuffer(0, vertex, 0) + pass.DrawIndexed(3, 0, 0) + pass.SetIndexBuffer(index, gpu.IndexUint16, 0) + pass.DrawIndexed(3, 0, 0) + pass.DrawIndexedInstanced(3, 2, 0, 0, 0) + }, "gpu.bind_rejected operation=SetIndexBuffer slot=0", + "gpu.draw_skipped operation=DrawIndexed binding=index_buffer slot=0", + "gpu.draw_skipped operation=DrawIndexedInstanced binding=index_buffer slot=0", + "gpu.draw_skipped operation=DrawIndexed binding=index_buffer slot=0") + } + + checkFrame("active pipeline slots", 4, 4, func(pass *gpu.RenderPass) { + bind(pass) + pass.SetVertexBuffer(3, nil, 0) // Neither slot 3 is used by pipe. + pass.SetBindGroup(3, nil) + pass.Draw(3, 0) + pass.SetVertexBuffer(0, nil, 0) + pass.SetBindGroup(0, nil) + pass.SetPipeline(noBindings) + pass.Draw(3, 0) + pass.SetPipeline(pipe) + pass.Draw(3, 0) + pass.SetVertexBuffer(0, vertex, 0) + pass.Draw(3, 0) // Group 0 is still rejected. + pass.SetPipeline(autoLayout) + pass.Draw(3, 0) // The shader's inferred group 0 is also affected. + pass.SetBindGroup(0, group) + pass.Draw(3, 0) + pass.SetPipeline(pipe) + pass.Draw(3, 0) + }, "gpu.bind_rejected operation=SetVertexBuffer slot=3", + "gpu.bind_rejected operation=SetBindGroup slot=3", + "gpu.bind_rejected operation=SetVertexBuffer slot=0", + "gpu.bind_rejected operation=SetBindGroup slot=0", + "gpu.draw_skipped operation=Draw binding=vertex_buffer slot=0", + "gpu.draw_skipped operation=Draw binding=bind_group slot=0", + "gpu.draw_skipped operation=Draw binding=bind_group slot=0") +} diff --git a/nsgotest/gpu.go b/nsgotest/gpu.go index e7860fc96..6512d49a4 100644 --- a/nsgotest/gpu.go +++ b/nsgotest/gpu.go @@ -296,6 +296,24 @@ func (a *App) GPUReadPixels(selector string) (*image.RGBA, error) { return st.soft.SurfaceImage(), nil } +// GPUDebugEvent is a label, group, or marker observed by a headless GPU view. +type GPUDebugEvent = driver.GPUDebugEvent + +// GPUDebugEvents returns a snapshot of the current headless GPU view's debug +// events, including rejected binds and skipped draws when built with nsgodev +// or nsgotest. It returns nil if the view has no active software device. +func (a *App) GPUDebugEvents(selector string) []GPUDebugEvent { + a.t.Helper() + v := a.Find(selector) + if v == nil || v.Kind != KindGPU { + return nil + } + if st := a.gpuViews[v.ID]; st != nil && st.soft != nil { + return st.soft.DebugEvents() + } + return nil +} + // TriggerGPUDeviceLost simulates a GPU device/context loss on the KindGPU view // matching selector and settles the app. func (a *App) TriggerGPUDeviceLost(selector string, reason GPUDeviceLostReason, message string) { diff --git a/skills/nsgo/references/testing.md b/skills/nsgo/references/testing.md index 39a94ef39..39c7dac3d 100644 --- a/skills/nsgo/references/testing.md +++ b/skills/nsgo/references/testing.md @@ -81,7 +81,7 @@ For a headless platform report no step provides, `app.Report` takes an owned `ns For native headless canvas pixels on macOS, use `nsgotest.Render` on a recorded `Drawing`. Pass `nsgotest.TextEngine(nsgotest.PlatformTextEngine())` to match CoreText metrics, and call `nsgotest.RegisterFont` before starting the app. Rendering waits for images, returns errors and requires resolved view paints and animation slots; other targets return `nsgotest.ErrNoPlayer`. [Windowless drawings](https://nsgo.dev/docs/testing.md#drawings-without-a-window) -For headless GPU checks in another window, use `Surface.GPUReadPixels`, `Surface.TriggerGPUDeviceLost` and `Surface.RestoreGPUDevice`; devices, readbacks and recovery follow that window, including its pixel ratio. `App.GPUFrames` records every window's submissions. +For headless GPU checks in another window, use `Surface.GPUReadPixels`, `Surface.TriggerGPUDeviceLost` and `Surface.RestoreGPUDevice`; devices, readbacks and recovery follow that window, including its pixel ratio. `App.GPUFrames` records every window's submissions. With `-- -tags=nsgotest`, `App.GPUDebugEvents` records markers for rejected render bindings and skipped draws. Read mounted image, input, modal, screen, scroll, video and Picture in Picture settings through `nsgotest` records. `View.Sticky` contains `nsgotest.StickyCell` values. Image variant maps and scroll lists are snapshots.