From b7f07b9ab58f6081ba89d49c76d20cdd2f1774b8 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 10 Nov 2026 21:51:27 +0100 Subject: [PATCH 1/2] win32: Config.GPU on Windows, a flip-model swap chain on the HWND (D4) Opt-in, mirroring the Cocoa path (gpuPath, startGPU at Run, presentGPU, resizeGPU, stopGPU, GPU, GPUError, the CPU from then on): the widgets record into a gpu2d list through gpupainter, gpu2d v0.11.0's Direct3D 11 renderer draws it and Present copies it into the back buffer of a flip swap chain on the window. While the swap chain exists WM_PAINT only validates (flip model: GDI content is ignored); on any failure the swap chain and device are released and the frame is drawn by GDI again. The live test runs on windows-latest with WARP: a real window, the back buffer read just before the swap chain presents it equals the CPU path's frame, through a resize; a device that will not start and a refused frame fall back. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 10 ++ go.mod | 3 +- go.sum | 10 +- internal/win32/gpu_windows.go | 165 +++++++++++++++++++ internal/win32/gpu_windows_test.go | 249 +++++++++++++++++++++++++++++ internal/win32/win32_windows.go | 43 ++++- open_windows.go | 6 +- window.go | 10 +- 8 files changed, 486 insertions(+), 10 deletions(-) create mode 100644 internal/win32/gpu_windows.go create mode 100644 internal/win32/gpu_windows_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fcb429b..7598ae5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -166,6 +166,16 @@ jobs: - run: go test -count=1 ./... env: CGO_ENABLED: "0" + # Config.GPU on Win32: a real window on this runner, drawn by gpu2d's Direct3D 11 + # renderer on WARP (no GPU here) and presented through a flip-model swap + # chain; the back buffer, read just before the swap chain presents it, must be + # the CPU path's frame, through a resize, and a refused frame must drop the + # window to GDI. What a screen shows is not observed. + - name: Live GPU window (WARP, flip swap chain) + env: + CGO_ENABLED: "0" + WINDOW_WIN32_GPU: "1" + run: go test -count=1 -v -run TestLiveGPUWindow ./internal/win32/ - name: Live display enumeration (no window, no interactive session) env: CGO_ENABLED: "0" diff --git a/go.mod b/go.mod index 00eff1b..a284fc0 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/ebitengine/purego v0.11.3 github.com/go-appdirs/outdir v0.3.0 github.com/go-freedesktop/x11 v0.3.0 - github.com/go-gfx/gpu2d v0.9.2 + github.com/go-gfx/gpu2d v0.11.0 github.com/go-gtk/gtk4 v0.9.0 github.com/go-macos/appkit v0.9.0 github.com/go-macos/metal v0.6.0 @@ -30,6 +30,7 @@ require ( github.com/go-gfx/vulkan v0.2.1 // indirect github.com/go-icons/iconoir v0.3.0 // indirect github.com/go-images/images v0.1.1-0.20261026203936-4ac989d310a1 // indirect + github.com/go-mswin/d3d11 v0.3.0 // indirect github.com/go-opentype/fonts v0.14.0 // indirect github.com/go-opentype/shape v0.7.0 // indirect github.com/go-richdoc/richdoc v0.7.0 // indirect diff --git a/go.sum b/go.sum index 59168af..84d1e97 100644 --- a/go.sum +++ b/go.sum @@ -13,12 +13,12 @@ github.com/go-freedesktop/x11 v0.3.0 h1:DAZN7uAt8eQOyav90VduelaEJyTdWlAZjOTZOKvu github.com/go-freedesktop/x11 v0.3.0/go.mod h1:6GsirPySzG8JmIhqUYc0bDcMfrXuaGf9iRsOWSP8JsU= github.com/go-gfx/gfx v0.41.0 h1:MVEnory0Zx8ypzuVDrTIWz4Cekv8hn5ilcYg3glJPrk= github.com/go-gfx/gfx v0.41.0/go.mod h1:4OenoKrgdht6UXYf5SV8w2tb41hfAdy4QoxJRPsRDz4= -github.com/go-gfx/gpu2d v0.9.2 h1:HittjwReXNOE8RVxIPW1HOwRC7i9ugsNC1SZGPODz5c= -github.com/go-gfx/gpu2d v0.9.2/go.mod h1:xZWTUuYv617mHfkH7CuamDessnKAtFyBFrYqB6akgXM= +github.com/go-gfx/gpu2d v0.11.0 h1:YaA+WRv1F3E5gs9nAy2FxmD5u/l38QpKxD6txSGG0yI= +github.com/go-gfx/gpu2d v0.11.0/go.mod h1:Qc9VYnOd4C0jMsY9aEwalrCPvm11FM1L10UG83n3x80= github.com/go-gfx/vulkan v0.2.1 h1:a6eysWKAUcqB8aDh/4Z+gDrY56+6TaMUu+47d6pZN18= github.com/go-gfx/vulkan v0.2.1/go.mod h1:IYZuEIwS3vtystKZRIp+DtuPWX3Nfq86yMC4gJ5ebhw= -github.com/go-gfx/wgsl v0.8.0 h1:zU4tEy9k2HQ2pQIgEuQqpPlpfPi5M7O8QbAzoSs6EZ0= -github.com/go-gfx/wgsl v0.8.0/go.mod h1:Fzzw0jXvB+zxCqmTDwvcu3B7PkIVJBcygl2dyDyDAgQ= +github.com/go-gfx/wgsl v0.9.0 h1:6luCFFUwJOPpdkLYGnUOMl2Por2YTb/0bDLdJdpaFtw= +github.com/go-gfx/wgsl v0.9.0/go.mod h1:Fzzw0jXvB+zxCqmTDwvcu3B7PkIVJBcygl2dyDyDAgQ= github.com/go-gtk/gtk4 v0.9.0 h1:5Efx48jeWL1LTmKIqqPcseSoa4U8Pf0Sbzo/rU4nmGA= github.com/go-gtk/gtk4 v0.9.0/go.mod h1:BTpReN9ONh5ZO4p2ETjt8n7km3yEYOFW/Q9HprOC13g= github.com/go-icons/iconoir v0.3.0 h1:kHG2sU5IsCvtBS1JICuXgfFo5f8UfwY1m7KYMVy97CI= @@ -33,6 +33,8 @@ 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-macos/virtualdisplay v0.5.0 h1:V2TMkAXLUCYqZSfkfIz7YQkoh2+4/bz+ja4hvYoJut8= github.com/go-macos/virtualdisplay v0.5.0/go.mod h1:3hgrYzzH17hfjFnsZKq/kg0bIuB3mu2FK60BudhBqRc= +github.com/go-mswin/d3d11 v0.3.0 h1:97vwif+uFbTBvOicU1acAb+CqfN1yKIeZBGAlTm77fY= +github.com/go-mswin/d3d11 v0.3.0/go.mod h1:uYoPcvGm3f/S0WDrdrilWO5QagbXaSPPKRjnIzcDedw= github.com/go-mswin/win32 v0.6.0 h1:gapeT3H5/V8eS61WP4r8oqA4tN09qkU1QXmjgOu5VpE= github.com/go-mswin/win32 v0.6.0/go.mod h1:JoPSHnB0eccheGPKPdQyj4jPbBfKANYXrYl/l6xEwxs= github.com/go-opentype/fonts v0.14.0 h1:WHw7k9gkHT1pu9B2yyvd0FWyQqn/4NKFQoKhvMYt3Mo= diff --git a/internal/win32/gpu_windows.go b/internal/win32/gpu_windows.go new file mode 100644 index 0000000..d11b7e1 --- /dev/null +++ b/internal/win32/gpu_windows.go @@ -0,0 +1,165 @@ +// Copyright (c) the go-widgets/window authors. All rights reserved. +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build windows + +package win32 + +import ( + "github.com/go-gfx/gpu2d" + "github.com/go-gfx/gpu2d/d3d11" + "github.com/go-widgets/gpupainter" + "github.com/go-widgets/toolkit" +) + +// gpuPath draws frames on the GPU (Config.GPU), as the Cocoa back-end's does: the +// widgets record into a gpu2d list through gpupainter, gpu2d's Direct3D 11 +// renderer draws it, and a second kernel copies the result into the back buffer +// of a flip-model swap chain on the window's own HWND (go-gfx/gpu2d Present, +// go-mswin/d3d11 v0.3.0). The frame never comes back to the CPU and WM_PAINT has +// nothing to blit. +// +// A flip-model swap chain owns what its window shows ("only Direct3D content in +// flip model swap chains ... are visible"), so while it exists onPaint only +// validates the update region; when the path stops, the swap chain is released +// before GDI draws again. +// +// Opt-in, as on macOS: the Direct3D 11 back-end is proven on WARP in CI and on no +// GPU (go-gfx/gpu2d docs/NATIVE.md, Decisions taken). +type gpuPath struct { + r *d3d11.Renderer + sc *d3d11.SwapChain + list *gpu2d.List + paint *gpupainter.Painter +} + +// gpuOpener is the seam a test replaces to make the GPU path fail to start, or +// to ask for the software device (WARP) on a machine whose adapter is not the +// one being proven. By default it is the default hardware adapter. +var gpuOpener = d3d11.New + +// gpuCapture, when set by a test, receives a copy of each frame's back buffer as +// the device holds it just before the swap chain presents it (the frame the +// window is about to show), with the framebuffer size. It is the proof that the +// presented frame is the CPU path's, with no desktop to take a screenshot from. +var gpuCapture func(frame []byte, w, h int) + +// gpuFault, when set by a test, is asked before each present: an error stops the +// path as a lost device would. +var gpuFault func() error + +// startGPU switches the window to the GPU path, if it was asked for. Any failure +// (no adapter, a device that cannot make a flip swap chain with UAV back +// buffers, a frame too large) leaves the CPU path in place and is recorded in +// GPUError. It runs once the window exists, from Run. +func (w *Window) startGPU() { + if !w.wantGPU || w.gpu != nil || w.hwnd == 0 { + return + } + r, err := gpuOpener(w.w, w.h) + if err != nil { + w.gpuErr = err + return + } + sc, err := r.NewSwapChain(w.hwnd) + if err != nil { + r.Close() + w.gpuErr = err + return + } + list, err := gpu2d.NewList(w.w, w.h) + if err != nil { + sc.Close() + r.Close() + w.gpuErr = err + return + } + w.gpu = &gpuPath{r: r, sc: sc, list: list, paint: gpupainter.New(list)} + w.gpuErr = nil +} + +// stopGPU releases the swap chain and the device, and gives the window back to +// GDI. The window draws on the CPU afterwards. +func (w *Window) stopGPU() { + g := w.gpu + if g == nil { + return + } + w.gpu = nil + g.sc.Close() + g.r.Close() + // Direct3D defers the destruction of what it was using; a flip swap chain + // released but not flushed would still own the window. +} + +// drawGPU records the whole frame: the background, then the root. +func (w *Window) drawGPU() { + g := w.gpu + g.list.Reset() + bg := w.theme.Background + g.list.FillRect(gpu2d.Rect{W: w.w, H: w.h}, gpu2d.RGBA{R: bg.R, G: bg.G, B: bg.B, A: bg.A}) + g.paint.Reset(g.list) + if w.root != nil { + w.root.SetBounds(toolkit.Rect{X: 0, Y: 0, W: w.w, H: w.h}) + w.root.Draw(g.paint, w.theme) + } + g.paint.Flush() +} + +// presentGPU sends the recorded frame to the swap chain. A frame the device +// refuses drops the window to the CPU path for good, and that frame is drawn +// there instead. +func (w *Window) presentGPU() { + g := w.gpu + err := g.list.Err() + if err == nil && gpuFault != nil { + err = gpuFault() + } + if err == nil { + if gpuCapture != nil { + frame := make([]byte, 4*w.w*w.h) + if err = g.r.PresentAndRead(g.list, g.sc, frame); err == nil { + gpuCapture(frame, w.w, w.h) + } + } else { + err = g.r.Present(g.list, g.sc) + } + } + if err != nil { + w.gpuErr = err + w.stopGPU() + w.draw() + w.invalidateAll() + } +} + +// resizeGPU follows a new framebuffer size. +func (w *Window) resizeGPU() { + g := w.gpu + if g == nil { + return + } + list, err := gpu2d.NewList(w.w, w.h) + if err == nil { + err = g.r.Resize(w.w, w.h) + } + if err == nil { + err = g.sc.Resize(w.w, w.h) + } + if err != nil { + w.gpuErr = err + w.stopGPU() + w.draw() + w.invalidateAll() + return + } + g.list = list +} + +// GPU reports whether frames are being drawn on the GPU. +func (w *Window) GPU() bool { return w.gpu != nil } + +// GPUError is why a window that asked for the GPU is not using it: nil when it +// is, or when it never asked. +func (w *Window) GPUError() error { return w.gpuErr } diff --git a/internal/win32/gpu_windows_test.go b/internal/win32/gpu_windows_test.go new file mode 100644 index 0000000..86698a0 --- /dev/null +++ b/internal/win32/gpu_windows_test.go @@ -0,0 +1,249 @@ +// Copyright (c) the go-widgets/window authors. All rights reserved. +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build windows + +package win32 + +import ( + "bytes" + "errors" + "os" + "runtime" + "testing" + "time" + + "github.com/go-gfx/gpu2d/d3d11" + "github.com/go-widgets/painter" + "github.com/go-widgets/toolkit" +) + +// The live GPU proof (Config.GPU on Win32): a real window, created and run on +// this thread, drawn by gpu2d's Direct3D 11 renderer on WARP (the software +// device: windows-latest has no GPU) and presented through a flip-model swap +// chain on the window's own HWND. The proof is the back buffer, read through +// staging just before the swap chain presents it, against the frame the CPU path +// draws from the same widgets. What a screen shows is not observed: a hosted +// runner has no one to look at it. +// +// WINDOW_WIN32_GPU=1 run these tests (the Windows CI lane sets it) + +func skipUnlessGPU(t *testing.T) { + t.Helper() + if os.Getenv("WINDOW_WIN32_GPU") == "" { + t.Skip("set WINDOW_WIN32_GPU=1 to run the live Win32 GPU proof") + } +} + +// warp asks gpuPath for the software device and restores the seams afterwards. +func warp(t *testing.T) { + t.Helper() + oo, oc, of := gpuOpener, gpuCapture, gpuFault + gpuOpener = func(w, h int) (*d3d11.Renderer, error) { + return d3d11.NewWith(w, h, d3d11.Options{Software: true}) + } + t.Cleanup(func() { gpuOpener, gpuCapture, gpuFault = oo, oc, of }) +} + +// gpuProofRoot paints translucent fills, rounded rectangles, strokes and text, so +// the comparison covers blending, coverage and glyph masks, not a flat colour. +type gpuProofRoot struct { + toolkit.Base + onCPU int // frames painted by a CPU painter + drawn int +} + +func (r *gpuProofRoot) Draw(p painter.Painter, _ *toolkit.Theme) { + r.drawn++ + if _, ok := p.(*painter.PixelPainter); ok { + r.onCPU++ + } + b := r.Bounds() + p.FillRect(painter.Rect{X: 4, Y: 4, W: b.W - 8, H: b.H - 8}, painter.RGBA{R: 30, G: 70, B: 120, A: 255}) + p.FillRoundRect(painter.Rect{X: 12, Y: 12, W: b.W - 24, H: b.H / 2}, 14, painter.RGBA{R: 220, G: 60, B: 50, A: 140}) + p.FillRoundRect(painter.Rect{X: 30, Y: b.H / 3, W: b.W / 2, H: b.H / 3}, 9, painter.RGBA{R: 20, G: 200, B: 90, A: 110}) + p.StrokeRoundRect(painter.Rect{X: 8, Y: 8, W: b.W - 16, H: b.H - 16}, 12, painter.RGBA{R: 255, G: 255, B: 255, A: 200}, 1) + p.StrokeRect(painter.Rect{X: 20, Y: 20, W: 60, H: 30}, painter.RGBA{R: 255, G: 220, B: 0, A: 255}, 1) + p.Text(24, 28, "go-widgets gpu", painter.RGBA{R: 255, G: 255, B: 255, A: 255}) + p.PutPixel(3, 3, painter.RGBA{R: 255, A: 255}) +} + +func (r *gpuProofRoot) OnEvent(toolkit.Event) {} + +// cpuFrame is the frame the CPU path draws from root at w × h. +func cpuFrame(root toolkit.Widget, theme *toolkit.Theme, w, h int) []byte { + buf := make([]byte, 4*w*h) + p := painter.NewPixelPainter(buf, w, h) + full := toolkit.Rect{X: 0, Y: 0, W: w, H: h} + p.FillRect(full, theme.Background) + root.SetBounds(full) + root.Draw(p, theme) + return buf +} + +// watchdog closes the window after d, so a message that never arrives fails the +// test instead of hanging it. +func watchdog(w *Window, d time.Duration) (stop func()) { + t := time.AfterFunc(d, func() { w.Close() }) + return func() { t.Stop() } +} + +func TestLiveGPUWindowPresentsTheCPUFrame(t *testing.T) { + skipUnlessGPU(t) + warp(t) + runtime.LockOSThread() // the window belongs to this thread, as Open arranges + defer runtime.UnlockOSThread() + + w, err := NewScaledGPU("go-widgets gpu proof", 320, 200, nil, false, true) + if err != nil { + t.Fatalf("NewScaledGPU: %v", err) + } + root := &gpuProofRoot{} + type seen struct{ w, h int } + var sizes []seen + var gpuWhenCaptured []bool + gpuCapture = func(frame []byte, fw, fh int) { + sizes = append(sizes, seen{fw, fh}) + gpuWhenCaptured = append(gpuWhenCaptured, w.GPU()) + want := cpuFrame(root, w.theme, fw, fh) + if !bytes.Equal(frame, want) { + bad := 0 + for i := range want { + if want[i] != frame[i] { + bad++ + } + } + t.Errorf("frame %d (%d x %d): the back buffer is not the CPU path's frame: %d of %d bytes differ", len(sizes), fw, fh, bad, len(want)) + } + switch len(sizes) { + case 1: + // Resize the window: WM_SIZE reaches onSize on this thread, which resizes + // the renderer and the swap chain and presents a frame at the new size. + procSetWindowPos.Call(w.hwnd, 0, 0, 0, 520, 420, uintptr(swpNoZOrder|swpNoActivate|0x0002 /* SWP_NOMOVE */)) + default: + w.Close() + } + } + defer watchdog(w, 40*time.Second)() + + if err := w.Run(root); err != nil { + t.Fatalf("Run: %v", err) + } + if len(sizes) < 2 { + t.Fatalf("%d presented frames, want the first and one after the resize (GPUError %v)", len(sizes), w.GPUError()) + } + if sizes[0] == sizes[1] { + t.Errorf("the window was not resized: both frames are %d x %d", sizes[0].w, sizes[0].h) + } + for i, g := range gpuWhenCaptured { + if !g { + t.Errorf("frame %d was not drawn by the GPU path", i+1) + } + } + if root.onCPU != len(sizes) { // only the reference frames are painted on the CPU + t.Errorf("%d CPU-painted frames, want exactly the %d reference frames: the window drew on the CPU too", root.onCPU, len(sizes)) + } + t.Logf("%d frames presented through the swap chain on %s, sizes %v, each equal to the CPU path's", len(sizes), "WARP", sizes) +} + +// A device that cannot start leaves the CPU path in place, with the reason. +func TestLiveGPUWindowFallsBackWhenTheDeviceWillNotStart(t *testing.T) { + skipUnlessGPU(t) + warp(t) + boom := errors.New("no device in this test") + gpuOpener = func(int, int) (*d3d11.Renderer, error) { return nil, boom } + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + w, err := NewScaledGPU("go-widgets gpu fallback", 200, 120, nil, false, true) + if err != nil { + t.Fatal(err) + } + root := &closeAfterFirstDraw{w: w} + defer watchdog(w, 30*time.Second)() + if err := w.Run(root); err != nil { + t.Fatal(err) + } + if w.GPU() || !errors.Is(w.GPUError(), boom) { + t.Fatalf("GPU %v, GPUError %v: want the CPU path and the reason", w.GPU(), w.GPUError()) + } + if root.onCPU == 0 { + t.Fatal("the window drew no frame on the CPU") + } +} + +// closeAfterFirstDraw closes its window once it has been drawn, and counts the +// frames a CPU painter drew. +type closeAfterFirstDraw struct { + toolkit.Base + w *Window + onCPU int +} + +func (r *closeAfterFirstDraw) Draw(p painter.Painter, _ *toolkit.Theme) { + if _, ok := p.(*painter.PixelPainter); ok { + r.onCPU++ + } + p.FillRect(r.Bounds(), painter.RGBA{R: 10, G: 20, B: 30, A: 255}) + r.w.Close() +} + +func (r *closeAfterFirstDraw) OnEvent(toolkit.Event) {} + +// A frame the device refuses stops the GPU path for good: that frame and every +// later one is drawn on the CPU, and the swap chain is released so GDI shows. +func TestLiveGPUWindowDropsToTheCPUWhenAFrameIsRefused(t *testing.T) { + skipUnlessGPU(t) + warp(t) + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + w, err := NewScaledGPU("go-widgets gpu fault", 200, 120, nil, false, true) + if err != nil { + t.Fatal(err) + } + root := &gpuProofRoot{} + lost := errors.New("device removed (injected)") + presented := 0 + gpuCapture = func([]byte, int, int) { + presented++ + gpuFault = func() error { return lost } // the next frame is refused + w.Repaint() + } + frames := 0 + defer watchdog(w, 30*time.Second)() + root2 := &faultRoot{gpuProofRoot: root, onFrame: func(onCPU bool) { + frames++ + if onCPU { + w.Close() // the first frame on the CPU after the fault: done + } + }} + if err := w.Run(root2); err != nil { + t.Fatal(err) + } + if presented != 1 { + t.Fatalf("%d frames presented on the GPU before the fault, want 1", presented) + } + if w.GPU() || !errors.Is(w.GPUError(), lost) { + t.Fatalf("GPU %v, GPUError %v: want the CPU path and the injected error", w.GPU(), w.GPUError()) + } + if frames < 3 { // the GPU frame, the refused one (recorded, then redrawn on the CPU), and the CPU frame + t.Logf("frames drawn: %d", frames) + } + if root.onCPU == 0 { + t.Fatal("the refused frame was not drawn on the CPU") + } +} + +// faultRoot reports each frame and which painter drew it. +type faultRoot struct { + *gpuProofRoot + onFrame func(onCPU bool) +} + +func (r *faultRoot) Draw(p painter.Painter, th *toolkit.Theme) { + r.gpuProofRoot.Draw(p, th) + _, cpu := p.(*painter.PixelPainter) + r.onFrame(cpu) +} diff --git a/internal/win32/win32_windows.go b/internal/win32/win32_windows.go index 3217c0a..bda9cdc 100644 --- a/internal/win32/win32_windows.go +++ b/internal/win32/win32_windows.go @@ -184,6 +184,13 @@ type Window struct { // gone is closed as seen from other goroutines, which Show, Hide and Raise // are called from; closed is the UI thread's own. gone atomic.Bool + + // The GPU path (gpu_windows.go, Config.GPU): wantGPU is the request, gpu the + // live path once it started (nil on the CPU path), gpuErr why it did not or + // stopped. All three belong to the UI thread. + wantGPU bool + gpu *gpuPath + gpuErr error } // Repaint asks the message loop for a frame. Implements the window.Repainter @@ -233,6 +240,14 @@ func New(title string, width, height int, theme *toolkit.Theme) (*Window, error) // up-sampled -- and hands the caller the job of laying out for it, which is // what a root that asks RenderScale does. func NewScaled(title string, width, height int, theme *toolkit.Theme, native bool) (*Window, error) { + return NewScaledGPU(title, width, height, theme, native, false) +} + +// NewScaledGPU is NewScaled that also says whether the window asks for the GPU +// path (Config.GPU): frames drawn by gpu2d's Direct3D 11 renderer and presented +// through a flip-model swap chain on the window. It starts when Run does, falls +// back to the CPU path on any failure, and GPU and GPUError say which happened. +func NewScaledGPU(title string, width, height int, theme *toolkit.Theme, native, gpu bool) (*Window, error) { // Per-Monitor-V2 DPI awareness: the window is notified of per-monitor DPI and // its non-client frame scales, so GetDpiForWindow reports the true monitor // DPI and the content stays readable. Best-effort: it also returns false @@ -282,6 +297,7 @@ func NewScaled(title string, width, height int, theme *toolkit.Theme, native boo className: className, scale: 1, native: native, + wantGPU: gpu, } active = w @@ -416,9 +432,18 @@ func (w *Window) Run(root toolkit.Widget) error { // Seed the first frame: paint the whole framebuffer (through the incremental // renderer when the root opts in, so its whole-surface seed damage is // consumed here) and force an immediate full present. - if w.dmg != nil { + // + // A window that asked for the GPU takes it over here, once the root is known; + // it then redraws whole frames (the damage that saves work is the CPU's, and + // the CPU is not drawing). + w.startGPU() + switch { + case w.gpu != nil: + w.drawGPU() + w.presentGPU() + case w.dmg != nil: w.drawIncremental() - } else { + default: w.draw() } w.invalidateAll() @@ -541,6 +566,7 @@ func wndProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uintptr { // thread allowed to do it, and is why Close only posts. w.closed = true w.gone.Store(true) + w.stopGPU() // the swap chain goes before its window w.hwnd = 0 if active == w { active = nil @@ -609,6 +635,12 @@ func (w *Window) onPaint() { if hdc == 0 { return } + if w.gpu != nil { + // The swap chain shows the window; GDI content would be ignored. The + // BeginPaint/EndPaint pair is what validates the update region. + procEndPaint.Call(w.hwnd, uintptr(unsafe.Pointer(&ps))) + return + } w.mu.Lock() bw, bh := w.w, w.h physW, physH := w.physW, w.physH @@ -642,6 +674,7 @@ func (w *Window) onSize(physW, physH int) { return } w.applySize(lw, lh, w.scale) + w.resizeGPU() w.paintFrame(true) } @@ -660,6 +693,7 @@ func (w *Window) onDpiChanged(newDPI uint32) { w.mu.Unlock() w.applySize(lw, lh, scale) // recomputes physW/physH at the new scale w.sizeAndCenter() // resize the physical window/frame to match + w.resizeGPU() w.paintFrame(true) } @@ -731,6 +765,11 @@ func (w *Window) paintFrame(resize bool) { // published from the same place, so the description can never lag the // pixels a sighted user already sees. w.refreshA11y() + if w.gpu != nil { + w.drawGPU() + w.presentGPU() + return + } if w.dmg == nil { w.draw() w.invalidateAll() diff --git a/open_windows.go b/open_windows.go index 6907798..b017771 100644 --- a/open_windows.go +++ b/open_windows.go @@ -32,7 +32,11 @@ func Open(cfg Config) (Backend, error) { // NativeScale asks for the panel's own pixels rather than a logical // framebuffer the OS up-samples. Opt-in, as on every other back-end: it // changes what Size reports and what a point is worth to the widget tree. - w, err := win32.NewScaled(cfg.Title, cfg.Width, cfg.Height, cfg.Theme, cfg.RenderScale == NativeScale) + // + // Config.GPU is opt-in, as on macOS: gpu2d's Direct3D 11 renderer draws the + // frame and a flip-model swap chain on the window presents it, falling back + // to this CPU path on any failure (GPU and GPUError say which happened). + w, err := win32.NewScaledGPU(cfg.Title, cfg.Width, cfg.Height, cfg.Theme, cfg.RenderScale == NativeScale, cfg.GPU) if err != nil { return nil, err } diff --git a/window.go b/window.go index c9b1045..20c2ed8 100644 --- a/window.go +++ b/window.go @@ -200,8 +200,14 @@ type Config struct { // None of this is an error: the window works as without the option, and its // GPU and GPUError methods say which happened. // - // Honoured today by the macOS (Cocoa), X11 and Wayland back-ends; ignored - // elsewhere. + // On Windows (opt-in, like the others) gpu2d's Direct3D 11 renderer draws the + // frame and a flip-model swap chain on the window's HWND presents it, the + // frame never returning to the CPU; a device that cannot make one, or a frame + // it refuses, leaves the window on the GDI path. The Direct3D 11 back-end is + // proven on WARP (the software device) in CI and on no GPU. + // + // Honoured today by the macOS (Cocoa), X11, Wayland and Windows back-ends; + // ignored elsewhere. GPU bool } From 8f76c19e1c2c79231edc168892e488186dd6968a Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 10 Nov 2026 21:54:30 +0100 Subject: [PATCH 2/2] README: Config.GPU on Windows Co-Authored-By: Claude Sonnet 5.5 --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index e80eb04..2e69c09 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,27 @@ Under lavapipe the GPU path costs more CPU time than the CPU path (about ten times) and more wall time (35 to 52 %): there is no GPU to take the work. The fractal run (RADV) that decides whether it pays on a real one is pending. +**On the GPU on Windows (`Config.GPU`, opt-in):** +- **Drawing:** the same recording through gpupainter into a gpu2d list, drawn by + gpu2d's **Direct3D 11** back-end (`gpu2d/d3d11`, over go-mswin/d3d11), and + copied by a second kernel into the back buffer of a **flip-model swap chain** + (`FLIP_DISCARD`, `R8G8B8A8_UNORM`, back buffers used as UAVs) on the window's own + HWND: the frame never returns to the CPU. While the swap chain exists `WM_PAINT` + only validates the update region, because a flip-model window shows nothing but + its swap chain. +- **Proof, and what it is not:** `TestLiveGPUWindowPresentsTheCPUFrame` runs on + `windows-latest`, with a real window and gpu2d's **WARP** (software) device: + the back buffer, read through staging just before the swap chain presents it, + equals the frame `PixelPainter` draws from the same widgets, byte for byte, + before and after a resize. Nothing observed what a screen showed (a hosted + runner has no one to look), and **no Windows GPU has run it**: whether a + given GPU's driver accepts a UAV on a flip-model back buffer is unknown (the + documentation neither promises nor forbids it; WARP accepts it) and is + gpu2d's parity measurement to make. A frame the device refuses, or a device + that will not start, leaves the window on the GDI path, with `GPUError()` + saying why; both are tested. Child controls (the native-control seam) over a + swap chain have not been tried. + ### Windows Win32/GDI backend (`windows`) On Windows `Open` declares **Per-Monitor-V2 DPI awareness**, registers a window