-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
551 lines (482 loc) · 13.9 KB
/
main.go
File metadata and controls
551 lines (482 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// Package main demonstrates RenderBundle for pre-recording render commands.
// RenderBundles are useful for static geometry that doesn't change between frames,
// reducing CPU overhead by pre-recording draw commands.
package main
import (
"fmt"
"log"
"os"
"syscall"
"unsafe"
"github.com/go-webgpu/webgpu/wgpu"
"github.com/gogpu/gputypes"
"golang.org/x/sys/windows"
)
const (
windowWidth = 800
windowHeight = 600
windowTitle = "go-webgpu: RenderBundle Example"
)
// Win32 constants
const (
csHRedraw = 0x0002
csVRedraw = 0x0001
wmDestroy = 0x0002
wmSize = 0x0005
idcArrow = 32512
colorWindow = 5
swShowNormal = 1
pmRemove = 0x0001
wsOverlappedWindow = 0x00CF0000
wsVisible = 0x10000000
cwUseDefault uint32 = 0x80000000
)
var (
user32 = windows.NewLazyDLL("user32.dll")
procRegisterClassExW = user32.NewProc("RegisterClassExW")
procCreateWindowExW = user32.NewProc("CreateWindowExW")
procShowWindow = user32.NewProc("ShowWindow")
procUpdateWindow = user32.NewProc("UpdateWindow")
procPeekMessageW = user32.NewProc("PeekMessageW")
procTranslateMessage = user32.NewProc("TranslateMessage")
procDispatchMessageW = user32.NewProc("DispatchMessageW")
procDefWindowProcW = user32.NewProc("DefWindowProcW")
procPostQuitMessage = user32.NewProc("PostQuitMessage")
procLoadCursorW = user32.NewProc("LoadCursorW")
kernel32 = windows.NewLazyDLL("kernel32.dll")
procGetModuleHandleW = kernel32.NewProc("GetModuleHandleW")
)
// WNDCLASSEXW represents the Win32 WNDCLASSEXW structure.
type WNDCLASSEXW struct {
cbSize uint32
style uint32
lpfnWndProc uintptr
cbClsExtra int32
cbWndExtra int32
hInstance windows.Handle
hIcon windows.Handle
hCursor windows.Handle
hbrBackground windows.Handle
lpszMenuName *uint16
lpszClassName *uint16
hIconSm windows.Handle
}
// MSG represents the Win32 MSG structure.
type MSG struct {
hwnd windows.HWND
message uint32
wParam uintptr
lParam uintptr
time uint32
pt struct{ x, y int32 }
}
// Application state
type App struct {
hwnd windows.HWND
hinstance windows.Handle
instance *wgpu.Instance
adapter *wgpu.Adapter
device *wgpu.Device
queue *wgpu.Queue
surface *wgpu.Surface
pipeline *wgpu.RenderPipeline
renderBundle *wgpu.RenderBundle
width uint32
height uint32
running bool
needsRecreate bool
surfaceTex *wgpu.SurfaceTexture
surfaceTexView *wgpu.TextureView
}
// Shader source (WGSL)
// NOTE: This shader uses a fallback approach for triangle coloring.
// Instead of @builtin(primitive_index) (which requires PRIMITIVE_INDEX GPU capability),
// we calculate the triangle index from vertex_index and pass color via varying.
// This works on ALL GPUs, including older hardware without primitive_index support.
const shaderSource = `
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) color: vec3<f32>,
}
@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOutput {
// Three triangles at different positions
var positions = array<vec2<f32>, 9>(
// Triangle 1 (left)
vec2<f32>(-0.7, 0.3),
vec2<f32>(-0.9, -0.3),
vec2<f32>(-0.5, -0.3),
// Triangle 2 (center)
vec2<f32>(0.0, 0.5),
vec2<f32>(-0.2, -0.1),
vec2<f32>(0.2, -0.1),
// Triangle 3 (right)
vec2<f32>(0.7, 0.3),
vec2<f32>(0.5, -0.3),
vec2<f32>(0.9, -0.3)
);
// Colors for each triangle
var colors = array<vec3<f32>, 3>(
vec3<f32>(1.0, 0.2, 0.2), // Red
vec3<f32>(0.2, 1.0, 0.2), // Green
vec3<f32>(0.2, 0.2, 1.0) // Blue
);
// Calculate triangle index from vertex index (3 vertices per triangle)
// This is the FALLBACK for @builtin(primitive_index)
let tri_idx = idx / 3u;
var out: VertexOutput;
out.position = vec4<f32>(positions[idx], 0.0, 1.0);
out.color = colors[tri_idx];
return out;
}
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
// Use color passed from vertex shader (works on all GPUs!)
return vec4<f32>(in.color, 1.0);
}
`
func main() {
fmt.Println("=== RenderBundle Example ===")
fmt.Println()
fmt.Println("RenderBundles pre-record draw commands for efficient replay.")
fmt.Println("This is useful for static geometry that doesn't change.")
fmt.Println()
fmt.Println("Benefits:")
fmt.Println(" - Reduced CPU overhead (commands recorded once)")
fmt.Println(" - Better driver optimization opportunities")
fmt.Println(" - Useful for static scene elements")
fmt.Println()
fmt.Println("Note: This example uses a FALLBACK approach for per-triangle coloring.")
fmt.Println("Instead of @builtin(primitive_index) (requires PRIMITIVE_INDEX capability),")
fmt.Println("we calculate triangle index from vertex_index in the vertex shader.")
fmt.Println("This works on ALL GPUs, including older hardware.")
fmt.Println()
app := &App{
width: windowWidth,
height: windowHeight,
running: true,
}
if err := app.init(); err != nil {
log.Fatalf("Failed to initialize: %v", err)
}
defer app.cleanup()
app.run()
}
// init initializes the application.
func (app *App) init() error {
// Initialize WebGPU library
if err := wgpu.Init(); err != nil {
return fmt.Errorf("init wgpu: %w", err)
}
// Get HINSTANCE
ret, _, _ := procGetModuleHandleW.Call(0)
app.hinstance = windows.Handle(ret)
// Create window
if err := app.createWindow(); err != nil {
return fmt.Errorf("create window: %w", err)
}
// Initialize WebGPU
if err := app.initWebGPU(); err != nil {
return fmt.Errorf("init webgpu: %w", err)
}
// Configure surface
if err := app.configureSurface(); err != nil {
return fmt.Errorf("configure surface: %w", err)
}
// Create render pipeline
if err := app.createPipeline(); err != nil {
return fmt.Errorf("create pipeline: %w", err)
}
// Create render bundle (pre-recorded commands)
if err := app.createRenderBundle(); err != nil {
return fmt.Errorf("create render bundle: %w", err)
}
return nil
}
// createWindow creates the main window.
func (app *App) createWindow() error {
className, err := windows.UTF16PtrFromString("GoWebGPURenderBundle")
if err != nil {
return err
}
wndClass := WNDCLASSEXW{
cbSize: uint32(unsafe.Sizeof(WNDCLASSEXW{})),
style: csHRedraw | csVRedraw,
lpfnWndProc: syscall.NewCallback(app.wndProc),
hInstance: app.hinstance,
lpszClassName: className,
}
cursor, _, _ := procLoadCursorW.Call(0, uintptr(idcArrow))
wndClass.hCursor = windows.Handle(cursor)
wndClass.hbrBackground = windows.Handle(colorWindow + 1)
ret, _, _ := procRegisterClassExW.Call(uintptr(unsafe.Pointer(&wndClass)))
if ret == 0 {
return fmt.Errorf("RegisterClassExW failed")
}
titlePtr, err := windows.UTF16PtrFromString(windowTitle)
if err != nil {
return err
}
hwnd, _, _ := procCreateWindowExW.Call(
0,
uintptr(unsafe.Pointer(className)),
uintptr(unsafe.Pointer(titlePtr)),
uintptr(wsOverlappedWindow|wsVisible),
uintptr(cwUseDefault),
uintptr(cwUseDefault),
uintptr(app.width),
uintptr(app.height),
0,
0,
uintptr(app.hinstance),
0,
)
if hwnd == 0 {
return fmt.Errorf("CreateWindowExW failed")
}
app.hwnd = windows.HWND(hwnd)
_, _, _ = procShowWindow.Call(uintptr(app.hwnd), swShowNormal)
_, _, _ = procUpdateWindow.Call(uintptr(app.hwnd))
return nil
}
// wndProc is the window procedure callback.
func (app *App) wndProc(hwnd windows.HWND, msg uint32, wParam, lParam uintptr) uintptr {
switch msg {
case wmDestroy:
app.running = false
_, _, _ = procPostQuitMessage.Call(0)
return 0
case wmSize:
newWidth := uint32(lParam & 0xFFFF)
newHeight := uint32((lParam >> 16) & 0xFFFF)
if newWidth != app.width || newHeight != app.height {
app.width = newWidth
app.height = newHeight
app.needsRecreate = true
}
return 0
}
ret, _, _ := procDefWindowProcW.Call(
uintptr(hwnd),
uintptr(msg),
wParam,
lParam,
)
return ret
}
// initWebGPU initializes WebGPU resources.
func (app *App) initWebGPU() error {
inst, err := wgpu.CreateInstance(nil)
if err != nil {
return fmt.Errorf("create instance: %w", err)
}
app.instance = inst
adapter, err := inst.RequestAdapter(nil)
if err != nil {
return fmt.Errorf("request adapter: %w", err)
}
app.adapter = adapter
device, err := adapter.RequestDevice(nil)
if err != nil {
return fmt.Errorf("request device: %w", err)
}
app.device = device
app.queue = device.GetQueue()
surface, err := inst.CreateSurfaceFromWindowsHWND(uintptr(app.hinstance), uintptr(app.hwnd))
if err != nil {
return fmt.Errorf("create surface: %w", err)
}
app.surface = surface
return nil
}
// configureSurface configures the surface for rendering.
func (app *App) configureSurface() error {
app.surface.Configure(&wgpu.SurfaceConfiguration{
Device: app.device,
Format: gputypes.TextureFormatBGRA8Unorm,
Usage: gputypes.TextureUsageRenderAttachment,
Width: app.width,
Height: app.height,
AlphaMode: gputypes.CompositeAlphaModeOpaque,
PresentMode: gputypes.PresentModeFifo,
})
app.needsRecreate = false
return nil
}
// createPipeline creates the render pipeline.
func (app *App) createPipeline() error {
shader := app.device.CreateShaderModuleWGSL(shaderSource)
if shader == nil {
return fmt.Errorf("failed to create shader module")
}
defer shader.Release()
pipeline := app.device.CreateRenderPipelineSimple(
nil,
shader, "vs_main",
shader, "fs_main",
gputypes.TextureFormatBGRA8Unorm,
)
if pipeline == nil {
return fmt.Errorf("failed to create render pipeline")
}
app.pipeline = pipeline
return nil
}
// createRenderBundle creates a pre-recorded render bundle.
func (app *App) createRenderBundle() error {
fmt.Println("Creating RenderBundle with 3 triangles...")
// Create render bundle encoder with matching format
colorFormats := []gputypes.TextureFormat{gputypes.TextureFormatBGRA8Unorm}
bundleEncoder := app.device.CreateRenderBundleEncoderSimple(
colorFormats,
gputypes.TextureFormatUndefined, // no depth
1, // sample count
)
if bundleEncoder == nil {
return fmt.Errorf("failed to create render bundle encoder")
}
// Record draw commands (these will be replayed every frame)
bundleEncoder.SetPipeline(app.pipeline)
bundleEncoder.Draw(9, 1, 0, 0) // 9 vertices = 3 triangles
// Finish recording
bundle := bundleEncoder.Finish(nil)
bundleEncoder.Release()
if bundle == nil {
return fmt.Errorf("failed to finish render bundle")
}
app.renderBundle = bundle
fmt.Println("RenderBundle created successfully!")
return nil
}
// releasePreviousFrame releases resources from the previous frame.
func (app *App) releasePreviousFrame() {
if app.surfaceTexView != nil {
app.surfaceTexView.Release()
app.surfaceTexView = nil
}
if app.surfaceTex != nil && app.surfaceTex.Texture != nil {
app.surfaceTex.Texture.Release()
app.surfaceTex = nil
}
}
// acquireSurfaceTexture gets the current surface texture.
func (app *App) acquireSurfaceTexture() error {
surfaceTex, err := app.surface.GetCurrentTexture()
if err != nil {
if err == wgpu.ErrSurfaceLost || err == wgpu.ErrSurfaceNeedsReconfigure {
app.needsRecreate = true
return nil
}
return fmt.Errorf("get current texture: %w", err)
}
app.surfaceTex = surfaceTex
view := surfaceTex.Texture.CreateView(nil)
if view == nil {
return fmt.Errorf("failed to create texture view")
}
app.surfaceTexView = view
return nil
}
// render draws a frame.
func (app *App) render() error {
if app.needsRecreate {
if err := app.configureSurface(); err != nil {
return fmt.Errorf("reconfigure surface: %w", err)
}
}
app.releasePreviousFrame()
if err := app.acquireSurfaceTexture(); err != nil {
return err
}
if app.surfaceTexView == nil {
return nil
}
encoder := app.device.CreateCommandEncoder(nil)
if encoder == nil {
return fmt.Errorf("failed to create command encoder")
}
defer encoder.Release()
// Begin render pass
pass := encoder.BeginRenderPass(&wgpu.RenderPassDescriptor{
Label: "RenderBundle Pass",
ColorAttachments: []wgpu.RenderPassColorAttachment{{
View: app.surfaceTexView,
LoadOp: gputypes.LoadOpClear,
StoreOp: gputypes.StoreOpStore,
ClearValue: wgpu.Color{
R: 0.1,
G: 0.1,
B: 0.15,
A: 1.0,
},
}},
})
if pass == nil {
return fmt.Errorf("failed to begin render pass")
}
defer pass.Release()
// Execute the pre-recorded render bundle!
// This replays all the recorded draw commands efficiently.
pass.ExecuteBundles([]*wgpu.RenderBundle{app.renderBundle})
pass.End()
cmdBuffer := encoder.Finish(nil)
if cmdBuffer == nil {
return fmt.Errorf("failed to finish command encoder")
}
defer cmdBuffer.Release()
app.queue.Submit(cmdBuffer)
app.surface.Present()
return nil
}
// run is the main application loop.
func (app *App) run() {
for app.running {
var msg MSG
for {
ret, _, _ := procPeekMessageW.Call(
uintptr(unsafe.Pointer(&msg)),
0, 0, 0,
pmRemove,
)
if ret == 0 {
break
}
_, _, _ = procTranslateMessage.Call(uintptr(unsafe.Pointer(&msg)))
_, _, _ = procDispatchMessageW.Call(uintptr(unsafe.Pointer(&msg)))
}
if err := app.render(); err != nil {
fmt.Fprintf(os.Stderr, "Render error: %v\n", err)
app.running = false
}
}
}
// cleanup releases all resources.
func (app *App) cleanup() {
if app.surfaceTexView != nil {
app.surfaceTexView.Release()
}
if app.surfaceTex != nil && app.surfaceTex.Texture != nil {
app.surfaceTex.Texture.Release()
}
if app.renderBundle != nil {
app.renderBundle.Release()
}
if app.pipeline != nil {
app.pipeline.Release()
}
if app.surface != nil {
app.surface.Release()
}
if app.queue != nil {
app.queue.Release()
}
if app.device != nil {
app.device.Release()
}
if app.adapter != nil {
app.adapter.Release()
}
if app.instance != nil {
app.instance.Release()
}
}