Repository navigation
Expand file tree
/
Copy pathHelloTriangle.tsx
More file actions
151 lines (129 loc) · 4.42 KB
/
Copy pathHelloTriangle.tsx
File metadata and controls
151 lines (129 loc) · 4.42 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
/**
* Hello Triangle — the minimal Lynx-WebGPU example (ReactLynx).
*
* Resources are built once and only the uniform is refreshed per frame. The commands cross to native in
* one go at `queue.submit()`, so there is one bridge crossing per frame.
*
* Copy `JS/webgpu.js`, `JS/webgpu.d.ts` and `JS/elements.d.ts` into an rspeedy project before using it
* (docs/JS-AUTHORING.md).
*/
import { useEffect, useRef } from '@lynx-js/react'
import gpu, { GPUBufferUsage, startFrameLoop } from './webgpu.js'
import './elements.d.ts'
const SHADER = /* wgsl */ `
struct Uniforms {
angle: f32,
aspect: f32,
};
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
struct VertexOutput {
@builtin(position) position: vec4f,
@location(0) color: vec3f,
};
@vertex
fn vs_main(@location(0) position: vec2f, @location(1) color: vec3f) -> VertexOutput {
let s = sin(uniforms.angle);
let c = cos(uniforms.angle);
let rotated = vec2f(position.x * c - position.y * s, position.x * s + position.y * c);
var out: VertexOutput;
out.position = vec4f(rotated.x / uniforms.aspect, rotated.y, 0.0, 1.0);
out.color = color;
return out;
}
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4f {
return vec4f(in.color, 1.0);
}
`
// Position (x, y) + color (r, g, b) interleaved — stride 20B
const VERTICES = new Float32Array([
0.0, 0.6, 1.0, 0.2, 0.2,
-0.6, -0.5, 0.2, 1.0, 0.2,
0.6, -0.5, 0.2, 0.4, 1.0,
])
export function HelloTriangle() {
const stopRef = useRef<(() => void) | null>(null)
useEffect(() => {
let disposed = false
async function boot() {
const adapter = await gpu.requestAdapter()
if (!adapter) {
console.error('could not obtain a WebGPU adapter')
return
}
const device = await adapter.requestDevice()
device.onError((error) => console.error('WebGPU', error.kind, error.path, error.message))
const context = gpu.getCanvasContext('main')
const format = gpu.getPreferredCanvasFormat()
context.configure({ device, format })
const module = device.createShaderModule({ code: SHADER, label: 'triangle' })
const vertexBuffer = device.createBuffer({
size: VERTICES.byteLength,
usage: GPUBufferUsage.VERTEX,
mappedAtCreation: true,
})
new Float32Array(vertexBuffer.getMappedRange()).set(VERTICES)
vertexBuffer.unmap()
const uniformBuffer = device.createBuffer({
size: 16, // two f32s + padding to 16-byte alignment
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
})
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module,
entryPoint: 'vs_main',
buffers: [{
arrayStride: 20,
attributes: [
{ format: 'float32x2', offset: 0, shaderLocation: 0 },
{ format: 'float32x3', offset: 8, shaderLocation: 1 },
],
}],
},
fragment: { module, entryPoint: 'fs_main', targets: [{ format }] },
primitive: { topology: 'triangle-list' },
})
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: { buffer: uniformBuffer } }],
})
const uniforms = new Float32Array(4)
let angle = 0
const stop = startFrameLoop(({ delta }) => {
if (disposed) return
angle += (delta / 1000) * 1.2
const { width, height } = context.getSize()
if (width === 0 || height === 0) return
uniforms[0] = angle
uniforms[1] = width / height
device.queue.writeBuffer(uniformBuffer, 0, uniforms)
const encoder = device.createCommandEncoder()
const pass = encoder.beginRenderPass({
colorAttachments: [{
view: context.getCurrentTexture().createView(),
loadOp: 'clear',
storeOp: 'store',
clearValue: { r: 0.06, g: 0.07, b: 0.1, a: 1 },
}],
})
pass.setPipeline(pipeline)
pass.setBindGroup(0, bindGroup)
pass.setVertexBuffer(0, vertexBuffer)
pass.draw(3)
pass.end()
device.queue.submit([encoder.finish()])
})
stopRef.current = () => {
stop()
device.destroy()
}
}
boot()
return () => {
disposed = true
stopRef.current?.()
}
}, [])
return <webgpu-canvas canvas-id="main" style={{ width: '100%', height: '100%' }} />
}