/ proof-of-concept / steelsim21
Sign in
proof-of-concept / steelsim21
steelsim21 / src / render / renderer.ts
187 lines · 7.9 KBCodeBlameHistory
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 1// WebGPU rendering of the displacement field: a 2D color map or a lit 3D height field.
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 3import { type Grid, type PhysParams, holePoint, insideCell, pushPoint, strikePoint } from "../params.ts";
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 4import { lookAt, multiply, perspective } from "./mat4.ts";
5import shaderCode from "./shaders.wgsl?raw";
7export type ViewMode = "2d" | "3d";
9export class Renderer {
10 mode: ViewMode = "2d";
11 /** Vertical exaggeration of the 3D view. */
12 exaggeration = 4;
13 /** Color range |w| [m]; 0 means automatic (from the current maximum). */
14 colorRange = 0;
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 15 /** Add the stress-free initial shape to the 3D height field. */
16 showShape = false;
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 17 camera = { yaw: 0.6, pitch: 0.5, dist: 1.0 };
19 private device: GPUDevice;
20 private canvas: HTMLCanvasElement;
21 private ctx: GPUCanvasContext;
22 private format: GPUTextureFormat;
23 private uniform: GPUBuffer;
24 private pipe2d: GPURenderPipeline;
25 private pipe3d: GPURenderPipeline;
26 private bgLayout: GPUBindGroupLayout;
27 private index: GPUBuffer;
28 private indexCount: number;
29 private depth: GPUTexture | null = null;
30 private grid: Grid;
31 private params: PhysParams;
32 private bindGroups = new Map<GPUBuffer, GPUBindGroup>();
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 34 private w0: GPUBuffer;
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 35 private nw: GPUBuffer;
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 37 constructor(device: GPUDevice, canvas: HTMLCanvasElement, grid: Grid, params: PhysParams, w0: GPUBuffer, nw: GPUBuffer) {
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 38 this.device = device;
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 40 this.nw = nw;
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 41 this.canvas = canvas;
42 this.grid = grid;
43 this.params = params;
44 this.ctx = canvas.getContext("webgpu") as GPUCanvasContext;
45 this.format = navigator.gpu.getPreferredCanvasFormat();
46 this.ctx.configure({ device, format: this.format, alphaMode: "opaque" });
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 47 this.uniform = device.createBuffer({ size: 144, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 48 const module = device.createShaderModule({ code: shaderCode });
49 this.bgLayout = device.createBindGroupLayout({
50 entries: [
51 { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } },
52 { binding: 1, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "read-only-storage" } },
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 53 { binding: 2, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "read-only-storage" } },
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 54 { binding: 3, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "read-only-storage" } },
56 });
57 const layout = device.createPipelineLayout({ bindGroupLayouts: [this.bgLayout] });
58 this.pipe2d = device.createRenderPipeline({
59 layout,
60 vertex: { module, entryPoint: "vs2d" },
61 fragment: { module, entryPoint: "fs2d", targets: [{ format: this.format }] },
62 primitive: { topology: "triangle-list" },
63 });
64 this.pipe3d = device.createRenderPipeline({
65 layout,
66 vertex: { module, entryPoint: "vs3d" },
67 fragment: { module, entryPoint: "fs3d", targets: [{ format: this.format }] },
68 primitive: { topology: "triangle-list", cullMode: "none" },
69 depthStencil: { format: "depth24plus", depthWriteEnabled: true, depthCompare: "less" },
70 });
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 71 // Triangle indices of the height field (cells of the sheet only).
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 72 const { nx, ny } = grid;
73 const idx = new Uint32Array((nx - 1) * (ny - 1) * 6);
74 let k = 0;
75 for (let j = 0; j < ny - 1; j++) {
76 for (let i = 0; i < nx - 1; i++) {
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 77 if (!insideCell(grid, i, j)) continue;
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 78 const a = j * nx + i, b = a + 1, c = a + nx, d = c + 1;
79 idx[k++] = a; idx[k++] = b; idx[k++] = d;
80 idx[k++] = a; idx[k++] = d; idx[k++] = c;
81 }
82 }
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 83 this.indexCount = k;
84 this.index = device.createBuffer({ size: Math.max(16, idx.byteLength), usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 85 device.queue.writeBuffer(this.index, 0, idx);
86 this.installControls();
87 }
89 private installControls(): void {
90 let dragging = false, lastX = 0, lastY = 0;
91 this.canvas.addEventListener("pointerdown", (e) => {
92 dragging = true; lastX = e.clientX; lastY = e.clientY;
93 this.canvas.setPointerCapture(e.pointerId);
94 });
95 this.canvas.addEventListener("pointerup", () => (dragging = false));
96 this.canvas.addEventListener("pointermove", (e) => {
97 if (!dragging || this.mode !== "3d") return;
98 this.camera.yaw += (e.clientX - lastX) * 0.01;
99 this.camera.pitch = Math.max(-1.5, Math.min(1.5, this.camera.pitch + (e.clientY - lastY) * 0.01));
100 lastX = e.clientX; lastY = e.clientY;
101 });
102 this.canvas.addEventListener("wheel", (e) => {
103 if (this.mode !== "3d") return;
104 e.preventDefault();
105 this.camera.dist *= Math.exp(e.deltaY * 0.001);
106 this.camera.dist = Math.max(0.2, Math.min(5, this.camera.dist));
107 }, { passive: false });
108 }
110 private resize(): void {
111 const dpr = window.devicePixelRatio || 1;
112 const w = Math.max(1, Math.floor(this.canvas.clientWidth * dpr));
113 const h = Math.max(1, Math.floor(this.canvas.clientHeight * dpr));
114 if (this.canvas.width !== w || this.canvas.height !== h || !this.depth) {
115 this.canvas.width = w;
116 this.canvas.height = h;
117 this.depth?.destroy();
118 this.depth = this.device.createTexture({ size: [w, h], format: "depth24plus", usage: GPUTextureUsage.RENDER_ATTACHMENT });
119 }
120 }
122 /** Renders the w field held in `wBuffer` (f32 per node). `wmax` drives the automatic color range. */
123 render(encoder: GPUCommandEncoder, wBuffer: GPUBuffer, wmax: number): void {
124 this.resize();
125 const aspect = this.canvas.width / this.canvas.height;
126 const range = this.colorRange > 0 ? this.colorRange : Math.max(wmax, 1e-6);
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 127 const u = new Float32Array(36);
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 128 const ui = new Uint32Array(u.buffer);
129 const eye = [
130 this.camera.dist * Math.cos(this.camera.pitch) * Math.sin(this.camera.yaw),
131 this.camera.dist * Math.sin(this.camera.pitch),
132 this.camera.dist * Math.cos(this.camera.pitch) * Math.cos(this.camera.yaw),
133 ];
134 const mvp = multiply(perspective(0.7, aspect, 0.02, 20), lookAt(eye, [0, 0, 0], [0, 1, 0]));
135 u.set(mvp, 0);
136 ui[16] = this.grid.nx; ui[17] = this.grid.ny;
137 u[18] = this.grid.hx; u[19] = this.grid.hy;
138 u[20] = this.exaggeration; u[21] = range; u[22] = aspect;
139 ui[23] = this.mode === "3d" ? 1 : 0;
140 const p = this.params;
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 141 [u[24], u[25]] = holePoint(p);
10998acDrumstick strike excitation (Hertz contact with a free mass)Jeremy Magland 142 if (p.excitation === "strike") {
143 const [sx, sy] = strikePoint(p);
144 u[26] = sx; u[27] = sy; u[28] = p.contactRadius;
145 } else {
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 146 [u[26], u[27]] = pushPoint(p);
147 u[28] = p.fingerRadius;
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 149 u[29] = 0.4; u[30] = 0.5; u[31] = 1.0;
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 150 ui[32] = this.showShape ? 1 : 0;
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 151 ui[33] = p.shape === "ellipse" ? 1 : 0;
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 152 this.device.queue.writeBuffer(this.uniform, 0, u);
154 let bg = this.bindGroups.get(wBuffer);
155 if (!bg) {
156 bg = this.device.createBindGroup({
157 layout: this.bgLayout,
158 entries: [
159 { binding: 0, resource: { buffer: this.uniform } },
160 { binding: 1, resource: { buffer: wBuffer } },
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 161 { binding: 2, resource: { buffer: this.w0 } },
c63c76aAdd elliptical sheet shape on a masked gridJeremy Magland 162 { binding: 3, resource: { buffer: this.nw } },
164 });
165 this.bindGroups.set(wBuffer, bg);
166 }
167 const view = this.ctx.getCurrentTexture().createView();
168 const clear = { r: 0.11, g: 0.12, b: 0.14, a: 1 };
169 if (this.mode === "2d") {
170 const pass = encoder.beginRenderPass({ colorAttachments: [{ view, clearValue: clear, loadOp: "clear", storeOp: "store" }] });
171 pass.setPipeline(this.pipe2d);
172 pass.setBindGroup(0, bg);
173 pass.draw(3);
174 pass.end();
175 } else {
176 const pass = encoder.beginRenderPass({
177 colorAttachments: [{ view, clearValue: clear, loadOp: "clear", storeOp: "store" }],
178 depthStencilAttachment: { view: this.depth!.createView(), depthClearValue: 1, depthLoadOp: "clear", depthStoreOp: "store" },
179 });
180 pass.setPipeline(this.pipe3d);
181 pass.setBindGroup(0, bg);
182 pass.setIndexBuffer(this.index, "uint32");
183 pass.drawIndexed(this.indexCount);
184 pass.end();
185 }
186 }
↑↓ move↵openescclose