spi3der 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/APP.md +40 -0
- package/Dockerfile +4 -0
- package/MCP.md +149 -0
- package/PLAYER.md +136 -0
- package/README.md +35 -2
- package/api/mcp.mjs +31 -0
- package/api/store.mjs +158 -0
- package/bin/spi3der.mjs +20 -0
- package/emulator.html +17 -0
- package/engine/8fa668821759/bevel.js +265 -0
- package/engine/8fa668821759/camera.js +76 -0
- package/engine/8fa668821759/character.js +1019 -0
- package/engine/8fa668821759/check.js +83 -0
- package/engine/8fa668821759/csg.js +342 -0
- package/engine/8fa668821759/edit.js +48 -0
- package/engine/8fa668821759/galaxy.js +265 -0
- package/engine/8fa668821759/gl.js +798 -0
- package/engine/8fa668821759/gpu.js +1356 -0
- package/engine/8fa668821759/index.js +48 -0
- package/engine/8fa668821759/instances.js +41 -0
- package/engine/8fa668821759/joints.js +355 -0
- package/engine/8fa668821759/kernel-bytes.js +2 -0
- package/engine/8fa668821759/kernel.js +82 -0
- package/engine/8fa668821759/lathe.js +87 -0
- package/engine/8fa668821759/material.js +19 -0
- package/engine/8fa668821759/mesh.js +131 -0
- package/engine/8fa668821759/order.js +125 -0
- package/engine/8fa668821759/pick.js +85 -0
- package/engine/8fa668821759/place.js +17 -0
- package/engine/8fa668821759/planet.js +376 -0
- package/engine/8fa668821759/rig.js +417 -0
- package/engine/8fa668821759/saw.js +121 -0
- package/engine/8fa668821759/sky.js +428 -0
- package/engine/8fa668821759/svg.js +239 -0
- package/engine/8fa668821759/text.js +231 -0
- package/engine/8fa668821759/triangulate.js +72 -0
- package/engine/8fa668821759/types.js +2 -0
- package/engine/8fa668821759/vec.js +22 -0
- package/engine/8fa668821759/version.js +7 -0
- package/engine/8fa668821759/vrtsh.js +354 -0
- package/engine/8fa668821759/wire.js +346 -0
- package/favicon.svg +15 -0
- package/help.md +289 -0
- package/icons/apple-touch-icon.png +0 -0
- package/icons/favicon-32.png +0 -0
- package/icons/icon-192.png +0 -0
- package/icons/icon-512.png +0 -0
- package/icons/icon-maskable-512.png +0 -0
- package/icons/icon-maskable.svg +13 -0
- package/icons/icon.svg +15 -0
- package/index.html +13730 -0
- package/manifest.webmanifest +37 -0
- package/mcp/engine/bevel.js +265 -0
- package/mcp/engine/camera.js +76 -0
- package/mcp/engine/character.js +1019 -0
- package/mcp/engine/check.js +83 -0
- package/mcp/engine/csg.js +342 -0
- package/mcp/engine/edit.js +48 -0
- package/mcp/engine/galaxy.js +265 -0
- package/mcp/engine/gl.js +798 -0
- package/mcp/engine/gpu.js +1356 -0
- package/mcp/engine/index.js +48 -0
- package/mcp/engine/instances.js +41 -0
- package/mcp/engine/joints.js +355 -0
- package/mcp/engine/kernel-bytes.js +2 -0
- package/mcp/engine/kernel.js +82 -0
- package/mcp/engine/lathe.js +87 -0
- package/mcp/engine/material.js +19 -0
- package/mcp/engine/mesh.js +131 -0
- package/mcp/engine/order.js +125 -0
- package/mcp/engine/pick.js +85 -0
- package/mcp/engine/place.js +17 -0
- package/mcp/engine/planet.js +376 -0
- package/mcp/engine/rig.js +417 -0
- package/mcp/engine/saw.js +121 -0
- package/mcp/engine/sky.js +428 -0
- package/mcp/engine/svg.js +239 -0
- package/mcp/engine/text.js +231 -0
- package/mcp/engine/triangulate.js +72 -0
- package/mcp/engine/types.js +2 -0
- package/mcp/engine/vec.js +22 -0
- package/mcp/engine/version.js +7 -0
- package/mcp/engine/vrtsh.js +354 -0
- package/mcp/engine/wire.js +346 -0
- package/mcp/http.js +292 -0
- package/mcp/live.js +95 -0
- package/mcp/package.json +10 -0
- package/mcp/scene.js +1027 -0
- package/mcp/serve.js +87 -0
- package/mcp/server.js +97 -0
- package/media/face-of-spider.png +0 -0
- package/media/spider-paint-2015.png +0 -0
- package/media/spider-web.png +0 -0
- package/models/deepsky-lark.scene.json +1 -0
- package/models/deepsky.scene.json +1 -0
- package/models/globe.scene.json +1 -0
- package/models/lark-4.scene.json +1 -0
- package/models/lark.game.json +14 -0
- package/models/spider-build-v2.md +215 -0
- package/models/spider-build-v2.mjs +355 -0
- package/models/spider-build-v2.schema.json +1001 -0
- package/nginx.conf +12 -0
- package/package.json +45 -4
- package/player.html +274 -0
- package/sky.html +133 -0
- package/sky.md +285 -0
- package/src/demo.js +92 -0
- package/src/emulator/devices.js +22 -0
- package/src/emulator/xr.js +362 -0
- package/src/math.js +77 -0
- package/sw.js +37 -0
- package/xr-compare.html +332 -0
- package/xr-test.html +248 -0
|
@@ -0,0 +1,1356 @@
|
|
|
1
|
+
// WebGPU renderer: flat-colored faces, one simple lit material, one global light.
|
|
2
|
+
// It draws the same scene through the same camera as the SVG renderer, so picking,
|
|
3
|
+
// the cross marks and the framing all stay valid. The pure helpers (viewProjection,
|
|
4
|
+
// buildVertices) need no GPU and are unit tested; createGpu() needs a browser.
|
|
5
|
+
import { dot, norm } from './vec.js';
|
|
6
|
+
import { bounds, faceNormal } from './mesh.js';
|
|
7
|
+
import { triangulate } from './triangulate.js';
|
|
8
|
+
import { makeCamera } from './camera.js';
|
|
9
|
+
import { surfaceOf } from './material.js';
|
|
10
|
+
import { planetInstances, PLANET_WGSL, PLANET_FLOATS, inv4 } from './planet.js';
|
|
11
|
+
/** Floats per screen vertex: position, then u v. */
|
|
12
|
+
export const SCREEN_FLOATS = 5;
|
|
13
|
+
/** The two triangles of every screen quad (SCREEN_FLOATS per vertex), in `screens` order. */
|
|
14
|
+
export const buildScreenQuads = (screens) => {
|
|
15
|
+
const out = new Float32Array(screens.length * 6 * SCREEN_FLOATS);
|
|
16
|
+
screens.forEach((sc, i) => {
|
|
17
|
+
const [u0, v0, u1, v1] = sc.uv ?? [0, 0, 1, 1];
|
|
18
|
+
const uv = [[u0, v0], [u1, v0], [u1, v1], [u0, v1]];
|
|
19
|
+
[0, 1, 2, 0, 2, 3].forEach((k, j) => out.set([...sc.corners[k], ...uv[k]], (i * 6 + j) * SCREEN_FLOATS));
|
|
20
|
+
});
|
|
21
|
+
return out;
|
|
22
|
+
};
|
|
23
|
+
/** The most joints a GPU skin can have. */
|
|
24
|
+
export const MAX_BONES = 64;
|
|
25
|
+
/** Floats per skinned vertex: the 14 of buildVertices, then four joints and their four weights. */
|
|
26
|
+
export const SKIN_FLOATS = 22;
|
|
27
|
+
/** a × b for column-major 4×4 matrices */
|
|
28
|
+
export const mul4 = (a, b) => {
|
|
29
|
+
const m = new Float32Array(16);
|
|
30
|
+
for (let c = 0; c < 4; c++)
|
|
31
|
+
for (let r = 0; r < 4; r++) {
|
|
32
|
+
let v = 0;
|
|
33
|
+
for (let k = 0; k < 4; k++)
|
|
34
|
+
v += a[k * 4 + r] * b[c * 4 + k];
|
|
35
|
+
m[c * 4 + r] = v;
|
|
36
|
+
}
|
|
37
|
+
return m;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Floats of one mark segment: a (xyz), b (xyz), colour (rgba), width in CSS pixels, dash length in CSS pixels (0: solid), and
|
|
41
|
+
* the distance along its polyline at a and at b (from the polyline's point nearest to the eye).
|
|
42
|
+
*/
|
|
43
|
+
export const MARK_FLOATS = 14;
|
|
44
|
+
const colorOf = (css) => {
|
|
45
|
+
const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((css ?? '#0b7285').trim());
|
|
46
|
+
const h = m ? (m[1].length === 3 ? [...m[1]].map((c) => c + c).join('') : m[1]) : '0b7285';
|
|
47
|
+
return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255);
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* One instance per segment of every polyline of every mark (a zero-length segment is a round point). With `eye` the points are
|
|
51
|
+
* made relative to it here, in doubles, and the renderer draws them with the eye-centred matrix: a float32 world position far
|
|
52
|
+
* from the origin (an orbit 30 AU out, seen from a few thousand km) would snap from frame to frame.
|
|
53
|
+
*/
|
|
54
|
+
export const buildMarks = (marks, eye = [0, 0, 0]) => {
|
|
55
|
+
let n = 0;
|
|
56
|
+
for (const m of marks)
|
|
57
|
+
for (const l of m.lines)
|
|
58
|
+
n += Math.max(1, l.length - 1);
|
|
59
|
+
const out = new Float32Array(n * MARK_FLOATS);
|
|
60
|
+
const [ex, ey, ez] = eye;
|
|
61
|
+
let o = 0;
|
|
62
|
+
for (const m of marks) {
|
|
63
|
+
const [r, g, b] = colorOf(m.color);
|
|
64
|
+
const dash = m.dash && m.dash > 0 ? m.dash : 0;
|
|
65
|
+
for (const l of m.lines) {
|
|
66
|
+
const segs = l.length > 1 ? l.length - 1 : 1;
|
|
67
|
+
// the distance along the line, counted from its point nearest to the eye (small numbers where the dashes are big on screen)
|
|
68
|
+
let s = null;
|
|
69
|
+
if (dash && l.length > 1) {
|
|
70
|
+
s = [0];
|
|
71
|
+
for (let i = 1; i < l.length; i++)
|
|
72
|
+
s.push(s[i - 1] + Math.hypot(l[i][0] - l[i - 1][0], l[i][1] - l[i - 1][1], l[i][2] - l[i - 1][2]));
|
|
73
|
+
let near = 0, nd = Infinity;
|
|
74
|
+
l.forEach((q, i) => {
|
|
75
|
+
const d = (q[0] - ex) ** 2 + (q[1] - ey) ** 2 + (q[2] - ez) ** 2;
|
|
76
|
+
if (d < nd)
|
|
77
|
+
((nd = d), (near = i));
|
|
78
|
+
});
|
|
79
|
+
const s0 = s[near];
|
|
80
|
+
s = s.map((v) => v - s0);
|
|
81
|
+
}
|
|
82
|
+
for (let i = 0; i < segs; i++) {
|
|
83
|
+
const a = l[i];
|
|
84
|
+
const c = l[Math.min(i + 1, l.length - 1)];
|
|
85
|
+
out.set([a[0] - ex, a[1] - ey, a[2] - ez, c[0] - ex, c[1] - ey, c[2] - ez, r, g, b, m.opacity ?? 1, m.width ?? 2, dash, s ? s[i] : 0, s ? s[Math.min(i + 1, l.length - 1)] : 0], o);
|
|
86
|
+
o += MARK_FLOATS;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
};
|
|
92
|
+
/** Line-list endpoints (x y z, x y z) of every edge of every face, each pair of vertices once. */
|
|
93
|
+
export const buildEdges = (mesh) => {
|
|
94
|
+
const seen = new Set();
|
|
95
|
+
const n = mesh.positions.length;
|
|
96
|
+
const out = [];
|
|
97
|
+
for (const f of mesh.faces)
|
|
98
|
+
f.v.forEach((a, i) => {
|
|
99
|
+
const b = f.v[(i + 1) % f.v.length];
|
|
100
|
+
const k = a < b ? a * n + b : b * n + a;
|
|
101
|
+
if (seen.has(k))
|
|
102
|
+
return;
|
|
103
|
+
seen.add(k);
|
|
104
|
+
out.push(...mesh.positions[a], ...mesh.positions[b]);
|
|
105
|
+
});
|
|
106
|
+
return new Float32Array(out);
|
|
107
|
+
};
|
|
108
|
+
const EDGE_LIMIT = 300000; // faces: a bigger scene (a galaxy of super-stars) is drawn without edge lines
|
|
109
|
+
const partEdges = new WeakMap();
|
|
110
|
+
/** The edge lines of a scene: of its parts (kept while a part stays the same Mesh) or of the whole mesh. Empty when the scene is huge. */
|
|
111
|
+
export const sceneEdges = (mesh, parts) => {
|
|
112
|
+
if (parts && parts.length) {
|
|
113
|
+
if (parts.reduce((n, m) => n + m.faces.length, 0) > EDGE_LIMIT)
|
|
114
|
+
return new Float32Array(0);
|
|
115
|
+
const built = parts.map((m) => {
|
|
116
|
+
let e = partEdges.get(m);
|
|
117
|
+
if (!e)
|
|
118
|
+
partEdges.set(m, (e = buildEdges(m)));
|
|
119
|
+
return e;
|
|
120
|
+
});
|
|
121
|
+
const all = new Float32Array(built.reduce((n, e) => n + e.length, 0));
|
|
122
|
+
let at = 0;
|
|
123
|
+
for (const e of built)
|
|
124
|
+
(all.set(e, at), (at += e.length));
|
|
125
|
+
return all;
|
|
126
|
+
}
|
|
127
|
+
return mesh.faces.length > EDGE_LIMIT ? new Float32Array(0) : buildEdges(mesh);
|
|
128
|
+
};
|
|
129
|
+
/** Floats of one glow light: position (3), reach (1), colour times intensity (3), spare (1). */
|
|
130
|
+
export const LIGHT_FLOATS = 8;
|
|
131
|
+
export const MAX_LIGHTS = 16;
|
|
132
|
+
const emitters = new WeakMap();
|
|
133
|
+
/** Every emitting face of a mesh: centre (3), area times emit (1), colour (3), area (1). */
|
|
134
|
+
const emittersOf = (mesh, palette) => {
|
|
135
|
+
const hit = emitters.get(mesh);
|
|
136
|
+
if (hit && hit.palette === palette)
|
|
137
|
+
return hit.data;
|
|
138
|
+
const rows = [];
|
|
139
|
+
for (const face of mesh.faces) {
|
|
140
|
+
const s = surfaceOf(face, palette);
|
|
141
|
+
if (s.emit < 0.05)
|
|
142
|
+
continue;
|
|
143
|
+
const pts = face.v.map((k) => mesh.positions[k]);
|
|
144
|
+
const area = Math.hypot(...(faceNormal(pts))) || 0;
|
|
145
|
+
if (!area)
|
|
146
|
+
continue;
|
|
147
|
+
const c = [0, 1, 2].map((k) => pts.reduce((a, p) => a + p[k], 0) / pts.length);
|
|
148
|
+
const [r, g, b] = colorOf(s.color);
|
|
149
|
+
rows.push(...c, area * s.emit, r, g, b, area);
|
|
150
|
+
}
|
|
151
|
+
const data = new Float32Array(rows);
|
|
152
|
+
emitters.set(mesh, { palette, data });
|
|
153
|
+
return data;
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* Glow: the emitting faces of a scene act as local light sources. Faces close to each other (one cell of a grid) merge into
|
|
157
|
+
* one light at their weighted centre; the brightest MAX_LIGHTS stay. Each light has a reach that grows with the emitting area.
|
|
158
|
+
* Float32Array, LIGHT_FLOATS per light.
|
|
159
|
+
*/
|
|
160
|
+
export const sceneLights = (mesh, parts, palette, skin) => {
|
|
161
|
+
const list = (parts && parts.length ? parts : [mesh]).map((m) => emittersOf(m, palette)).filter((e) => e.length);
|
|
162
|
+
if (skin) {
|
|
163
|
+
const rows = [];
|
|
164
|
+
skin.meshes.forEach((m, mi) => {
|
|
165
|
+
if (!emittersOf(m, palette).length)
|
|
166
|
+
return;
|
|
167
|
+
for (const f of m.faces) {
|
|
168
|
+
const s = surfaceOf(f, palette);
|
|
169
|
+
if (s.emit < 0.05)
|
|
170
|
+
continue;
|
|
171
|
+
let gain = 0;
|
|
172
|
+
const pts = f.v.map((vi) => {
|
|
173
|
+
const p = m.positions[vi], q = [0, 0, 0];
|
|
174
|
+
const top = [...skin.weights[mi][vi]].sort((a, b) => b[1] - a[1]).slice(0, 4);
|
|
175
|
+
const sum = top.reduce((t, w) => t + w[1], 0) || 1;
|
|
176
|
+
for (const [joint, share] of top) {
|
|
177
|
+
const w = share / sum, b = joint * 12;
|
|
178
|
+
for (let k = 0; k < 3; k++)
|
|
179
|
+
q[k] += w * (skin.bones[b + k * 4] * p[0] + skin.bones[b + k * 4 + 1] * p[1] + skin.bones[b + k * 4 + 2] * p[2] + skin.bones[b + k * 4 + 3]);
|
|
180
|
+
gain += w * (skin.emission?.[joint] ?? 1) / f.v.length;
|
|
181
|
+
}
|
|
182
|
+
return q;
|
|
183
|
+
});
|
|
184
|
+
const area = Math.hypot(...(faceNormal(pts))), power = area * s.emit * gain;
|
|
185
|
+
if (power <= 0)
|
|
186
|
+
continue;
|
|
187
|
+
const c = [0, 1, 2].map((k) => pts.reduce((a, p) => a + p[k], 0) / pts.length);
|
|
188
|
+
rows.push(...c, power, ...colorOf(s.color), area);
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
if (rows.length)
|
|
192
|
+
list.push(new Float32Array(rows));
|
|
193
|
+
}
|
|
194
|
+
if (!list.length)
|
|
195
|
+
return new Float32Array(0);
|
|
196
|
+
const lo = [Infinity, Infinity, Infinity];
|
|
197
|
+
const hi = [-Infinity, -Infinity, -Infinity];
|
|
198
|
+
for (const e of list)
|
|
199
|
+
for (let i = 0; i < e.length; i += 8)
|
|
200
|
+
for (let k = 0; k < 3; k++)
|
|
201
|
+
(lo[k] = Math.min(lo[k], e[i + k]), (hi[k] = Math.max(hi[k], e[i + k])));
|
|
202
|
+
const cell = Math.max((Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) / 6) || 1, 1e-3);
|
|
203
|
+
const cells = new Map();
|
|
204
|
+
for (const e of list) {
|
|
205
|
+
for (let i = 0; i < e.length; i += 8) {
|
|
206
|
+
const key = [0, 1, 2].map((k) => Math.floor((e[i + k] - lo[k]) / cell)).join(',');
|
|
207
|
+
const c = cells.get(key) ?? { p: 0, x: 0, y: 0, z: 0, r: 0, g: 0, b: 0, a: 0 };
|
|
208
|
+
const w = e[i + 3];
|
|
209
|
+
c.p += w;
|
|
210
|
+
c.x += e[i] * w;
|
|
211
|
+
c.y += e[i + 1] * w;
|
|
212
|
+
c.z += e[i + 2] * w;
|
|
213
|
+
c.r += e[i + 4] * w;
|
|
214
|
+
c.g += e[i + 5] * w;
|
|
215
|
+
c.b += e[i + 6] * w;
|
|
216
|
+
c.a += e[i + 7];
|
|
217
|
+
cells.set(key, c);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const top = [...cells.values()].sort((a, b) => b.p - a.p).slice(0, MAX_LIGHTS);
|
|
221
|
+
const out = new Float32Array(top.length * LIGHT_FLOATS);
|
|
222
|
+
top.forEach((c, i) => {
|
|
223
|
+
const reach = Math.max(2.5 * Math.sqrt(c.p), 0.05); // a 1 m x 1 m lamp at emit 1 reaches 2.5 m
|
|
224
|
+
out.set([c.x / c.p, c.y / c.p, c.z / c.p, reach, c.r / c.p, c.g / c.p, c.b / c.p, 0], i * LIGHT_FLOATS);
|
|
225
|
+
});
|
|
226
|
+
return out;
|
|
227
|
+
};
|
|
228
|
+
const FLOATS = 14; // position(3) normal(3) color(3) material(4: metal, rough, alpha, emit) soft(1)
|
|
229
|
+
/**
|
|
230
|
+
* Column-major 4x4 matrix (for WebGPU, z in 0..1) that maps world points exactly
|
|
231
|
+
* like camera.project(): the same pixels, plus a depth between near and far.
|
|
232
|
+
*/
|
|
233
|
+
export const viewProjection = (cam, near = 0.03, far = 1e9) => {
|
|
234
|
+
const kk = cam.k / (cam.size / 2);
|
|
235
|
+
const row = (v, s) => [v[0] * s, v[1] * s, v[2] * s, -dot(v, cam.eye) * s];
|
|
236
|
+
const a = cam.ortho ? 1 / (far - near) : far / (far - near);
|
|
237
|
+
const zr = row(cam.f, a);
|
|
238
|
+
zr[3] -= a * near;
|
|
239
|
+
const rows = [row(cam.r, kk), row(cam.u, kk), zr, cam.ortho ? [0, 0, 0, 1] : row(cam.f, 1)];
|
|
240
|
+
const m = new Float32Array(16);
|
|
241
|
+
rows.forEach((r, i) => r.forEach((v, j) => (m[j * 4 + i] = v)));
|
|
242
|
+
return m;
|
|
243
|
+
};
|
|
244
|
+
/**
|
|
245
|
+
* Near plane for a scene seen from `cam`: the usual 0.03, unless everything is very far (a galaxy seen from outside, the
|
|
246
|
+
* nearest point thousands of units away), where a near plane that close would leave no depth precision at all.
|
|
247
|
+
*/
|
|
248
|
+
export const nearPlane = (cam, mesh) => {
|
|
249
|
+
const [ex, ey, ez] = cam.eye;
|
|
250
|
+
const [fx, fy, fz] = cam.f;
|
|
251
|
+
let nearest = Infinity;
|
|
252
|
+
for (const p of mesh.positions) {
|
|
253
|
+
const d = (p[0] - ex) * fx + (p[1] - ey) * fy + (p[2] - ez) * fz;
|
|
254
|
+
if (d > 1e-6 && d < nearest)
|
|
255
|
+
nearest = d;
|
|
256
|
+
}
|
|
257
|
+
return Number.isFinite(nearest) && nearest > 1000 ? nearest * 0.25 : 0.03; // (an empty scene, e.g. only a skin, has no nearest point)
|
|
258
|
+
};
|
|
259
|
+
const rgb = (color) => {
|
|
260
|
+
const h = String(color ?? '').replace('#', '');
|
|
261
|
+
const full = h.length === 3 ? [...h].map((c) => c + c).join('') : h;
|
|
262
|
+
if (!/^[0-9a-f]{6}$/i.test(full))
|
|
263
|
+
return [0.78, 0.78, 0.78];
|
|
264
|
+
return [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16) / 255);
|
|
265
|
+
};
|
|
266
|
+
/**
|
|
267
|
+
* Smooth shading: a normal for every corner of every face. The faces that meet at a point (welded by position, so a
|
|
268
|
+
* crack in the indices does not break it) are averaged, weighted by area, but only those within `crease` degrees of
|
|
269
|
+
* this face: a 90 degree box corner stays sharp, a faceted fuselage becomes round.
|
|
270
|
+
*/
|
|
271
|
+
export const cornerNormals = (mesh, crease, soft) => {
|
|
272
|
+
// the material's soft decides how far its edges may be smoothed: 0 keeps every edge hard, from 0.5 up the whole crease angle is allowed;
|
|
273
|
+
// between two faces the harder one rules
|
|
274
|
+
const cosAt = (i, j) => {
|
|
275
|
+
const k = soft ? Math.min(1, 2 * Math.min(soft[i], soft[j])) : 1;
|
|
276
|
+
return Math.cos((crease * k * Math.PI) / 180);
|
|
277
|
+
};
|
|
278
|
+
const area = mesh.faces.map((f) => faceNormal(f.v.map((k) => mesh.positions[k]))); // length = area
|
|
279
|
+
const unit = area.map((n) => (Math.hypot(...n) > 0 ? norm(n) : [0, 1, 0]));
|
|
280
|
+
const q = (bounds(mesh).radius || 1) * 1e-6;
|
|
281
|
+
const key = (p) => `${Math.round(p[0] / q)},${Math.round(p[1] / q)},${Math.round(p[2] / q)}`;
|
|
282
|
+
const at = new Map();
|
|
283
|
+
mesh.faces.forEach((f, i) => f.v.forEach((k) => {
|
|
284
|
+
const id = key(mesh.positions[k]);
|
|
285
|
+
const list = at.get(id) ?? [];
|
|
286
|
+
if (list[list.length - 1] !== i)
|
|
287
|
+
list.push(i);
|
|
288
|
+
at.set(id, list);
|
|
289
|
+
}));
|
|
290
|
+
return mesh.faces.map((f, i) => f.v.map((k) => {
|
|
291
|
+
const sum = [0, 0, 0];
|
|
292
|
+
for (const j of at.get(key(mesh.positions[k])) ?? []) {
|
|
293
|
+
if (i !== j && (soft ? Math.min(soft[i], soft[j]) <= 0 : false))
|
|
294
|
+
continue;
|
|
295
|
+
if (dot(unit[i], unit[j]) < cosAt(i, j) - 1e-12)
|
|
296
|
+
continue;
|
|
297
|
+
for (let c = 0; c < 3; c++)
|
|
298
|
+
sum[c] += area[j][c];
|
|
299
|
+
}
|
|
300
|
+
return Math.hypot(...sum) > 0 ? norm(sum) : unit[i];
|
|
301
|
+
}));
|
|
302
|
+
};
|
|
303
|
+
/**
|
|
304
|
+
* Triangle list for the GPU: face normals (flat, or smoothed with `smooth` degrees), face colors and materials.
|
|
305
|
+
* Float32Array, 14 floats per vertex.
|
|
306
|
+
*/
|
|
307
|
+
export const buildVertices = (mesh, palette, { smooth = 0 } = {}) => {
|
|
308
|
+
let tris = 0;
|
|
309
|
+
for (const f of mesh.faces)
|
|
310
|
+
tris += Math.max(0, f.v.length - 2);
|
|
311
|
+
const out = new Float32Array(tris * 3 * FLOATS);
|
|
312
|
+
const corners = smooth > 0 ? cornerNormals(mesh, smooth, mesh.faces.map((f) => surfaceOf(f, palette).soft)) : null;
|
|
313
|
+
let o = 0;
|
|
314
|
+
mesh.faces.forEach((face, fi) => {
|
|
315
|
+
const pts = face.v.map((k) => mesh.positions[k]);
|
|
316
|
+
const flat = norm(faceNormal(pts));
|
|
317
|
+
const s = surfaceOf(face, palette);
|
|
318
|
+
const c = rgb(s.color);
|
|
319
|
+
const mat = [s.metal, s.rough, s.alpha, s.emit];
|
|
320
|
+
for (const tri of triangulate(pts)) {
|
|
321
|
+
for (const k of tri) {
|
|
322
|
+
out.set([...pts[k], ...(corners ? corners[fi][k] : flat), ...c, ...mat, s.soft], o);
|
|
323
|
+
o += FLOATS;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
return out;
|
|
328
|
+
};
|
|
329
|
+
/**
|
|
330
|
+
* Triangle list of a skinned figure in its bind pose: buildVertices' 14 floats per vertex, then the indices of its four
|
|
331
|
+
* strongest joints and their weights (summing to 1). The shader moves each vertex by its joints' bone matrices.
|
|
332
|
+
*/
|
|
333
|
+
export const buildSkinVertices = (meshes, weights, palette, { smooth = 0 } = {}) => {
|
|
334
|
+
let tris = 0;
|
|
335
|
+
for (const m of meshes)
|
|
336
|
+
for (const f of m.faces)
|
|
337
|
+
tris += Math.max(0, f.v.length - 2);
|
|
338
|
+
const out = new Float32Array(tris * 3 * SKIN_FLOATS);
|
|
339
|
+
let o = 0;
|
|
340
|
+
meshes.forEach((mesh, m) => {
|
|
341
|
+
const skin = weights[m];
|
|
342
|
+
if (!skin || skin.length !== mesh.positions.length)
|
|
343
|
+
throw new Error(`skin: mesh ${m} has ${mesh.positions.length} points, the weights know ${skin?.length ?? 0}`);
|
|
344
|
+
const four = skin.map((w) => {
|
|
345
|
+
const top = [...w].sort((a, b) => b[1] - a[1]).slice(0, 4);
|
|
346
|
+
const sum = top.reduce((t, x) => t + x[1], 0) || 1;
|
|
347
|
+
const j = [0, 0, 0, 0];
|
|
348
|
+
const k = [0, 0, 0, 0];
|
|
349
|
+
top.forEach(([joint, share], c) => {
|
|
350
|
+
if (joint >= MAX_BONES)
|
|
351
|
+
throw new Error(`skin: joint ${joint} is over the limit of ${MAX_BONES}`);
|
|
352
|
+
j[c] = joint;
|
|
353
|
+
k[c] = share / sum;
|
|
354
|
+
});
|
|
355
|
+
return [...j, ...k];
|
|
356
|
+
});
|
|
357
|
+
const corners = smooth > 0 ? cornerNormals(mesh, smooth, mesh.faces.map((f) => surfaceOf(f, palette).soft)) : null;
|
|
358
|
+
mesh.faces.forEach((face, fi) => {
|
|
359
|
+
const pts = face.v.map((k) => mesh.positions[k]);
|
|
360
|
+
const flat = norm(faceNormal(pts));
|
|
361
|
+
const s = surfaceOf(face, palette);
|
|
362
|
+
const c = rgb(s.color);
|
|
363
|
+
const mat = [s.metal, s.rough, s.alpha, s.emit];
|
|
364
|
+
for (const tri of triangulate(pts)) {
|
|
365
|
+
for (const k of tri) {
|
|
366
|
+
out.set([...pts[k], ...(corners ? corners[fi][k] : flat), ...c, ...mat, s.soft, ...four[face.v[k]]], o);
|
|
367
|
+
o += SKIN_FLOATS;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
return out;
|
|
373
|
+
};
|
|
374
|
+
/** Splits a triangle list into the opaque triangles and the see-through ones (alpha < 1, float 11 of a vertex). */
|
|
375
|
+
export const splitGlass = (all, floats) => {
|
|
376
|
+
const tri = 3 * floats;
|
|
377
|
+
const solid = new Float32Array(all.length);
|
|
378
|
+
const glass = new Float32Array(all.length);
|
|
379
|
+
let a = 0;
|
|
380
|
+
let b = 0;
|
|
381
|
+
for (let o = 0; o < all.length; o += tri) {
|
|
382
|
+
if (all[o + 11] < 1)
|
|
383
|
+
(glass.set(all.subarray(o, o + tri), b), (b += tri));
|
|
384
|
+
else
|
|
385
|
+
(solid.set(all.subarray(o, o + tri), a), (a += tri));
|
|
386
|
+
}
|
|
387
|
+
return { solid: solid.subarray(0, a), glass: glass.subarray(0, b) };
|
|
388
|
+
};
|
|
389
|
+
/** A skin's vertices, kept while its meshes, palette and smoothing stay the same. */
|
|
390
|
+
export const skinCache = () => {
|
|
391
|
+
let key = null;
|
|
392
|
+
let data = null;
|
|
393
|
+
return (skin, palette, crease) => {
|
|
394
|
+
const same = key &&
|
|
395
|
+
key.palette === palette &&
|
|
396
|
+
key.crease === crease &&
|
|
397
|
+
key.weights === skin.weights &&
|
|
398
|
+
key.meshes.length === skin.meshes.length &&
|
|
399
|
+
key.meshes.every((m, i) => m === skin.meshes[i]);
|
|
400
|
+
if (same && data)
|
|
401
|
+
return { ...data, fresh: false };
|
|
402
|
+
data = splitGlass(buildSkinVertices(skin.meshes, skin.weights, palette, { smooth: crease }), SKIN_FLOATS);
|
|
403
|
+
key = { meshes: [...skin.meshes], weights: skin.weights, palette, crease };
|
|
404
|
+
return { ...data, fresh: true };
|
|
405
|
+
};
|
|
406
|
+
};
|
|
407
|
+
const INSTANCE_FLOATS = 15; // at(3) ex(3) ey(3) ez(3) color(3)
|
|
408
|
+
/**
|
|
409
|
+
* Per-instance data for drawInstances: one entry { at, axes: [ex, ey, ez], color } per copy of a
|
|
410
|
+
* prototype mesh (modelled around the origin). Float32Array, 15 floats per instance.
|
|
411
|
+
*/
|
|
412
|
+
export const buildInstances = (items) => {
|
|
413
|
+
const out = new Float32Array(items.length * INSTANCE_FLOATS);
|
|
414
|
+
items.forEach((it, i) => out.set([...it.at, ...it.axes[0], ...it.axes[1], ...it.axes[2], ...rgb(it.color)], i * INSTANCE_FLOATS));
|
|
415
|
+
return out;
|
|
416
|
+
};
|
|
417
|
+
export const defaultLight = { direction: norm([0.5, 0.8, 0.6]), sky: [1, 0.97, 0.92], ground: [0.42, 0.38, 0.36] };
|
|
418
|
+
export const defaultMaterial = { ambient: 0.62, diffuse: 0.78, specular: 0.2, shininess: 30 };
|
|
419
|
+
const SHADER = /* wgsl */ `
|
|
420
|
+
struct U {
|
|
421
|
+
vp : mat4x4<f32>,
|
|
422
|
+
light : vec4<f32>, // xyz: direction towards the light
|
|
423
|
+
sky : vec4<f32>,
|
|
424
|
+
ground : vec4<f32>,
|
|
425
|
+
eye : vec4<f32>,
|
|
426
|
+
mat : vec4<f32>, // ambient, diffuse, specular, shininess
|
|
427
|
+
fx : vec4<f32>, // filmic (0 or 1), exposure, emission gain, studio (0 or 1)
|
|
428
|
+
fill : vec4<f32>, // studio: xyz direction towards the fill light, w intensity
|
|
429
|
+
rim : vec4<f32>, // studio: xyz direction towards the rim light, w intensity
|
|
430
|
+
res : vec4<f32>, // marks: canvas pixels (x, y), device pixels per CSS pixel (z); w: number of glow lights
|
|
431
|
+
lpos : array<vec4<f32>, 16>, // glow lights: xyz position, w reach
|
|
432
|
+
lcol : array<vec4<f32>, 16>, // rgb colour times intensity
|
|
433
|
+
vpe : mat4x4<f32>, // the marks: the view-projection with the eye at the origin (their points come relative to the eye)
|
|
434
|
+
mk : vec4<f32>, // the marks: x = device pixels per unit of (length / depth) (the focal length in pixels)
|
|
435
|
+
};
|
|
436
|
+
@group(0) @binding(0) var<uniform> u : U;
|
|
437
|
+
// logarithmic depth (u.eye.w = 1 / the smallest distance that needs depth; 0: the usual depth from the projection)
|
|
438
|
+
fn ld(p0 : vec4<f32>) -> vec4<f32> {
|
|
439
|
+
var p = p0;
|
|
440
|
+
if (u.eye.w > 0.0) { p.z = log2(max(1e-6, u.eye.w * p.w + 1.0)) / log2(u.eye.w * 1e12 + 1.0) * p.w; }
|
|
441
|
+
return p;
|
|
442
|
+
}
|
|
443
|
+
struct Bones { r : array<vec4<f32>, ${3 * 64}>, emission : array<vec4<f32>, 16> }; // three rows per joint, then emission gains
|
|
444
|
+
@group(0) @binding(1) var<uniform> bones : Bones;
|
|
445
|
+
|
|
446
|
+
struct VIn { @location(0) pos : vec3<f32>, @location(1) nrm : vec3<f32>, @location(2) col : vec3<f32>, @location(8) mat : vec4<f32>, @location(9) soft : f32 };
|
|
447
|
+
struct VOut {
|
|
448
|
+
@builtin(position) p : vec4<f32>,
|
|
449
|
+
@location(0) n : vec3<f32>,
|
|
450
|
+
@location(1) c : vec3<f32>,
|
|
451
|
+
@location(2) w : vec3<f32>,
|
|
452
|
+
@location(3) m : vec4<f32>, // metal, rough, alpha, emit
|
|
453
|
+
@location(4) s : f32, // soft
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
@vertex fn vs(i : VIn) -> VOut {
|
|
457
|
+
var o : VOut;
|
|
458
|
+
o.p = ld(u.vp * vec4<f32>(i.pos, 1.0));
|
|
459
|
+
o.n = i.nrm;
|
|
460
|
+
o.c = i.col;
|
|
461
|
+
o.w = i.pos;
|
|
462
|
+
o.m = i.mat;
|
|
463
|
+
o.s = i.soft;
|
|
464
|
+
return o;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
struct SIn {
|
|
468
|
+
@location(0) pos : vec3<f32>, @location(1) nrm : vec3<f32>, @location(2) col : vec3<f32>, @location(8) mat : vec4<f32>, @location(9) soft : f32,
|
|
469
|
+
@location(10) j : vec4<f32>, @location(11) wt : vec4<f32>,
|
|
470
|
+
};
|
|
471
|
+
fn bone(k : u32, p : vec4<f32>) -> vec3<f32> {
|
|
472
|
+
return vec3<f32>(dot(bones.r[k * 3u], p), dot(bones.r[k * 3u + 1u], p), dot(bones.r[k * 3u + 2u], p));
|
|
473
|
+
}
|
|
474
|
+
// a skinned figure: every vertex is moved by up to four joints, mixed by its weights (the normal by their turns)
|
|
475
|
+
@vertex fn vss(i : SIn) -> VOut {
|
|
476
|
+
var o : VOut;
|
|
477
|
+
var p = vec3<f32>(0.0);
|
|
478
|
+
var n = vec3<f32>(0.0);
|
|
479
|
+
var emission = 0.0;
|
|
480
|
+
for (var c = 0u; c < 4u; c = c + 1u) {
|
|
481
|
+
let w = i.wt[c];
|
|
482
|
+
if (w > 0.0) {
|
|
483
|
+
let k = u32(i.j[c] + 0.5);
|
|
484
|
+
p = p + bone(k, vec4<f32>(i.pos, 1.0)) * w;
|
|
485
|
+
n = n + bone(k, vec4<f32>(i.nrm, 0.0)) * w;
|
|
486
|
+
emission = emission + bones.emission[k / 4u][k % 4u] * w;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
o.p = ld(u.vp * vec4<f32>(p, 1.0));
|
|
490
|
+
o.n = n;
|
|
491
|
+
o.c = i.col;
|
|
492
|
+
o.w = p;
|
|
493
|
+
o.m = i.mat;
|
|
494
|
+
o.m.w = o.m.w * emission;
|
|
495
|
+
o.s = i.soft;
|
|
496
|
+
return o;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// a screen: a picture on a quad, as it is (a display does not take the scene's light)
|
|
500
|
+
@group(1) @binding(0) var scrSampler : sampler;
|
|
501
|
+
@group(1) @binding(1) var scrTex : texture_2d<f32>;
|
|
502
|
+
struct QOut { @builtin(position) p : vec4<f32>, @location(0) uv : vec2<f32> };
|
|
503
|
+
@vertex fn vsq(@location(0) pos : vec3<f32>, @location(1) uv : vec2<f32>) -> QOut {
|
|
504
|
+
var o : QOut;
|
|
505
|
+
o.p = ld(u.vp * vec4<f32>(pos, 1.0));
|
|
506
|
+
o.uv = uv;
|
|
507
|
+
return o;
|
|
508
|
+
}
|
|
509
|
+
@fragment fn fsq(i : QOut) -> @location(0) vec4<f32> {
|
|
510
|
+
return vec4<f32>(textureSample(scrTex, scrSampler, i.uv).rgb, 1.0);
|
|
511
|
+
}
|
|
512
|
+
// a hole: transparent, so what lies behind the canvas shows through
|
|
513
|
+
@fragment fn fsh(i : QOut) -> @location(0) vec4<f32> {
|
|
514
|
+
return vec4<f32>(0.0);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
struct IIn {
|
|
518
|
+
@location(0) pos : vec3<f32>, @location(1) nrm : vec3<f32>,
|
|
519
|
+
@location(3) at : vec3<f32>, @location(4) ex : vec3<f32>, @location(5) ey : vec3<f32>, @location(6) ez : vec3<f32>,
|
|
520
|
+
@location(7) col : vec3<f32>,
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
// the same prototype drawn many times: its frame (ex, ey, ez, scaled axes scale it) and position come per instance
|
|
524
|
+
@vertex fn vsi(i : IIn) -> VOut {
|
|
525
|
+
var o : VOut;
|
|
526
|
+
let w = i.at + i.ex * i.pos.x + i.ey * i.pos.y + i.ez * i.pos.z;
|
|
527
|
+
o.p = ld(u.vp * vec4<f32>(w, 1.0));
|
|
528
|
+
// the axes may be scaled (a thin long bar from the same prototype): normals follow the unit axes
|
|
529
|
+
o.n = normalize(i.ex) * i.nrm.x + normalize(i.ey) * i.nrm.y + normalize(i.ez) * i.nrm.z;
|
|
530
|
+
o.c = i.col;
|
|
531
|
+
o.w = w;
|
|
532
|
+
o.m = vec4<f32>(0.0, 0.7, 1.0, 0.0);
|
|
533
|
+
o.s = 0.0;
|
|
534
|
+
return o;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// the edge lines: 1 pixel, nudged a hair towards the eye so they win against the faces they lie on
|
|
538
|
+
@vertex fn vsl(@location(0) pos : vec3<f32>) -> @builtin(position) vec4<f32> {
|
|
539
|
+
var p = ld(u.vp * vec4<f32>(pos, 1.0));
|
|
540
|
+
p.z = p.z - 0.0002 * p.w;
|
|
541
|
+
return p;
|
|
542
|
+
}
|
|
543
|
+
@fragment fn fsl() -> @location(0) vec4<f32> {
|
|
544
|
+
// dark lines on the lit picture; with no light the picture is dark, so the lines turn light
|
|
545
|
+
let g = select(0.0, 0.85, u.light.w > 0.5);
|
|
546
|
+
return vec4<f32>(g, g, g, select(0.4, 0.55, u.light.w > 0.5));
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// the marks: thick round-capped segments, expanded to screen-space quads, drawn over everything (no depth test)
|
|
550
|
+
struct MOut { @builtin(position) p : vec4<f32>, @location(0) q : vec2<f32>, @location(1) c : vec4<f32>, @location(2) h : vec3<f32>, @location(3) dsh : vec2<f32> };
|
|
551
|
+
@vertex fn vsm(@builtin(vertex_index) vi : u32, @location(0) a : vec3<f32>, @location(1) b : vec3<f32>, @location(2) col : vec4<f32>, @location(3) wd : f32, @location(4) dl : vec3<f32>) -> MOut {
|
|
552
|
+
var o : MOut;
|
|
553
|
+
// the points are relative to the eye (buildMarks, in doubles): the eye-centred matrix keeps them exact near the camera
|
|
554
|
+
var ca = u.vpe * vec4<f32>(a, 1.0);
|
|
555
|
+
var cb = u.vpe * vec4<f32>(b, 1.0);
|
|
556
|
+
var sa = dl.y;
|
|
557
|
+
var sb = dl.z;
|
|
558
|
+
// the near cut: with log depth anything just in front of the eye is drawn, but never nearer than 1e-5 of the segment's far end
|
|
559
|
+
// (a point cut at w ~ 0 lands ~1e15 px away, where float32 loses the line's direction: stray lines across the screen)
|
|
560
|
+
let e = max(select(0.001, 1e-13, u.eye.w > 0.0), 1e-5 * max(ca.w, cb.w));
|
|
561
|
+
o.p = vec4<f32>(2.0, 2.0, 2.0, 1.0);
|
|
562
|
+
if (ca.w < e && cb.w < e) { return o; }
|
|
563
|
+
if (ca.w < e) { let k = (e - ca.w) / (cb.w - ca.w); ca = mix(ca, cb, k); sa = mix(sa, sb, k); }
|
|
564
|
+
if (cb.w < e) { let k = (e - cb.w) / (ca.w - cb.w); cb = mix(cb, ca, k); sb = mix(sb, sa, k); }
|
|
565
|
+
let half = vec2<f32>(u.res.x, u.res.y) * 0.5;
|
|
566
|
+
var pa = ca.xy / ca.w * half;
|
|
567
|
+
var pb = cb.xy / cb.w * half;
|
|
568
|
+
// the screen guard band: the segment is cut to 4x the picture before the quad is built, so no corner lies far off screen (a real
|
|
569
|
+
// GPU's rasteriser may mangle a triangle with a corner ~1e12 px away: a stray line across the picture)
|
|
570
|
+
{
|
|
571
|
+
let G = max(half.x, half.y) * 4.0;
|
|
572
|
+
let dd = pb - pa;
|
|
573
|
+
var t0 = 0.0;
|
|
574
|
+
var t1 = 1.0;
|
|
575
|
+
let ps = array<f32, 4>(-dd.x, dd.x, -dd.y, dd.y);
|
|
576
|
+
let qs = array<f32, 4>(pa.x + G, G - pa.x, pa.y + G, G - pa.y);
|
|
577
|
+
for (var k = 0; k < 4; k++) {
|
|
578
|
+
let pp = ps[k];
|
|
579
|
+
let qq = qs[k];
|
|
580
|
+
if (abs(pp) < 1e-20) { if (qq < 0.0) { return o; } }
|
|
581
|
+
else { let r = qq / pp; if (pp < 0.0) { t0 = max(t0, r); } else { t1 = min(t1, r); } }
|
|
582
|
+
}
|
|
583
|
+
if (t0 > t1) { return o; }
|
|
584
|
+
let na = pa + dd * t0;
|
|
585
|
+
let nb = pa + dd * t1;
|
|
586
|
+
// the dash distance and the depth follow the cut (s / w is linear on screen)
|
|
587
|
+
let qa = sa / ca.w;
|
|
588
|
+
let qb = sb / cb.w;
|
|
589
|
+
let ia = 1.0 / ca.w;
|
|
590
|
+
let ib = 1.0 / cb.w;
|
|
591
|
+
let ja = mix(ia, ib, t0);
|
|
592
|
+
let jb = mix(ia, ib, t1);
|
|
593
|
+
sa = mix(qa, qb, t0) / ja;
|
|
594
|
+
sb = mix(qa, qb, t1) / jb;
|
|
595
|
+
ca.w = 1.0 / ja;
|
|
596
|
+
cb.w = 1.0 / jb;
|
|
597
|
+
pa = na;
|
|
598
|
+
pb = nb;
|
|
599
|
+
}
|
|
600
|
+
let len = length(pb - pa);
|
|
601
|
+
var d = vec2<f32>(1.0, 0.0);
|
|
602
|
+
if (len > 0.0001) { d = (pb - pa) / len; }
|
|
603
|
+
let hw = wd * u.res.z * 0.5;
|
|
604
|
+
let n = vec2<f32>(-d.y, d.x);
|
|
605
|
+
let cx = array<f32, 6>(0.0, 1.0, 0.0, 1.0, 1.0, 0.0);
|
|
606
|
+
let cy = array<f32, 6>(-1.0, -1.0, 1.0, -1.0, 1.0, 1.0);
|
|
607
|
+
let t = cx[vi];
|
|
608
|
+
let s = cy[vi];
|
|
609
|
+
let ext = hw + 1.0;
|
|
610
|
+
let along = mix(-ext, len + ext, t);
|
|
611
|
+
let across = s * ext;
|
|
612
|
+
let pos = pa + d * along + n * across;
|
|
613
|
+
o.p = vec4<f32>(pos / half, 0.0, 1.0);
|
|
614
|
+
o.q = vec2<f32>(along, across);
|
|
615
|
+
o.c = col;
|
|
616
|
+
o.h = vec3<f32>(len, hw, 0.0);
|
|
617
|
+
// the dash phase in pixels: length along the line over depth, times the focal length; s / w interpolates linearly on screen,
|
|
618
|
+
// so the pattern runs on across the joints between the segments
|
|
619
|
+
let f = select(along / len, t, len <= 0.0001);
|
|
620
|
+
o.dsh = vec2<f32>(mix(sa / ca.w, sb / cb.w, f) * u.mk.x, dl.x * u.res.z);
|
|
621
|
+
return o;
|
|
622
|
+
}
|
|
623
|
+
@fragment fn fsm(i : MOut) -> @location(0) vec4<f32> {
|
|
624
|
+
let dx = max(max(-i.q.x, i.q.x - i.h.x), 0.0);
|
|
625
|
+
let dist = length(vec2<f32>(dx, i.q.y));
|
|
626
|
+
var cov = clamp(i.h.y + 0.5 - dist, 0.0, 1.0);
|
|
627
|
+
if (i.dsh.y > 0.0) {
|
|
628
|
+
// a dash, then a gap of the same length; half a pixel of soft edge
|
|
629
|
+
let m = i.dsh.x / (2.0 * i.dsh.y) - floor(i.dsh.x / (2.0 * i.dsh.y));
|
|
630
|
+
let px = m * 2.0 * i.dsh.y;
|
|
631
|
+
cov = cov * clamp(min(px, i.dsh.y - px) + 0.5, 0.0, 1.0);
|
|
632
|
+
}
|
|
633
|
+
return vec4<f32>(i.c.rgb, i.c.a * cov);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
fn toLinear(c : vec3<f32>) -> vec3<f32> {
|
|
637
|
+
return select(pow((c + 0.055) / 1.055, vec3<f32>(2.4)), c / 12.92, c <= vec3<f32>(0.04045));
|
|
638
|
+
}
|
|
639
|
+
fn toSrgb(c : vec3<f32>) -> vec3<f32> {
|
|
640
|
+
return select(1.055 * pow(c, vec3<f32>(1.0 / 2.4)) - 0.055, c * 12.92, c <= vec3<f32>(0.0031308));
|
|
641
|
+
}
|
|
642
|
+
// ACES filmic curve (Narkowicz fit): highlights roll off softly instead of clipping
|
|
643
|
+
fn aces(x : vec3<f32>) -> vec3<f32> {
|
|
644
|
+
return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), vec3<f32>(0.0), vec3<f32>(1.0));
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// Direct light, shared by both looks: x diffuse, y highlight, z scattered light (soft materials).
|
|
648
|
+
// Studio: the key light is u.light (placed by the camera), plus a softer fill and a rim light that only edges the shape.
|
|
649
|
+
fn lights(n : vec3<f32>, v : vec3<f32>, shin : f32, soft : f32) -> vec3<f32> {
|
|
650
|
+
let key = normalize(u.light.xyz);
|
|
651
|
+
let ndl = dot(n, key);
|
|
652
|
+
// soft: the light wraps round the form, and a warm band of scattered light sits where light turns to shade
|
|
653
|
+
var diff = max((ndl + soft) / (1.0 + soft), 0.0);
|
|
654
|
+
let h = normalize(key + v);
|
|
655
|
+
var spec = pow(max(dot(n, h), 0.0), shin) * step(0.0, ndl);
|
|
656
|
+
let scat = soft * exp(-ndl * ndl * 5.0);
|
|
657
|
+
if (u.fx.w > 0.5) {
|
|
658
|
+
diff = diff * 0.85; // three lights add up: the key takes a little less
|
|
659
|
+
let fl = normalize(u.fill.xyz);
|
|
660
|
+
diff = diff + max((dot(n, fl) + soft) / (1.0 + soft), 0.0) * u.fill.w;
|
|
661
|
+
let rl = normalize(u.rim.xyz);
|
|
662
|
+
let edge = pow(1.0 - max(dot(n, v), 0.0), 2.5);
|
|
663
|
+
diff = diff + max(dot(n, rl), 0.0) * edge * u.rim.w * 2.0;
|
|
664
|
+
let rh = normalize(rl + v);
|
|
665
|
+
spec = spec + pow(max(dot(n, rh), 0.0), shin) * step(0.0, dot(n, rl)) * u.rim.w * 0.6 * edge;
|
|
666
|
+
}
|
|
667
|
+
return vec3<f32>(diff, spec, scat);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// Glow: every emitting cluster is a local light with a smooth falloff to zero at its reach, a little wrap so shade edges soften
|
|
671
|
+
fn glowAt(p : vec3<f32>, n : vec3<f32>) -> vec3<f32> {
|
|
672
|
+
var sum = vec3<f32>(0.0);
|
|
673
|
+
let cnt = u32(u.res.w);
|
|
674
|
+
for (var k = 0u; k < cnt; k = k + 1u) {
|
|
675
|
+
let d = u.lpos[k].xyz - p;
|
|
676
|
+
let dist = max(length(d), 0.001);
|
|
677
|
+
let reach = u.lpos[k].w;
|
|
678
|
+
let x = dist / reach;
|
|
679
|
+
var win = clamp(1.0 - x * x * x * x, 0.0, 1.0);
|
|
680
|
+
win = win * win;
|
|
681
|
+
let s = dist / (reach * 0.25);
|
|
682
|
+
let wrap = max((dot(n, d / dist) + 0.3) / 1.3, 0.0);
|
|
683
|
+
sum = sum + u.lcol[k].rgb * (win / (1.0 + s * s)) * wrap * 1.6;
|
|
684
|
+
}
|
|
685
|
+
return sum;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// The filmic path: the same light model, but in linear colour with HDR light and emission, then tone mapped.
|
|
689
|
+
fn filmic(i : VOut, n : vec3<f32>, l : vec3<f32>, v : vec3<f32>) -> vec4<f32> {
|
|
690
|
+
let metal = i.m.x;
|
|
691
|
+
let rough = i.m.y;
|
|
692
|
+
let albedo = toLinear(i.c);
|
|
693
|
+
let hemi = mix(toLinear(u.ground.rgb), toLinear(u.sky.rgb), n.y * 0.5 + 0.5) * u.mat.x * select(1.0, 0.7, u.fx.w > 0.5);
|
|
694
|
+
let shin = mix(u.mat.w * 7.0, u.mat.w * 0.15, rough);
|
|
695
|
+
let lt = lights(n, v, shin, i.s);
|
|
696
|
+
let diff = lt.x * u.mat.y * 1.6;
|
|
697
|
+
let spec = lt.y * mix(u.mat.z, 1.0, metal) * mix(1.0, 0.35, rough) * 2.5;
|
|
698
|
+
let r = reflect(-v, n);
|
|
699
|
+
// Schlick: edges mirror more, metal keeps its tint
|
|
700
|
+
let f0 = mix(vec3<f32>(0.04), albedo, metal);
|
|
701
|
+
let fres = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - max(dot(n, v), 0.0), 5.0) * (1.0 - rough);
|
|
702
|
+
let env = mix(toLinear(u.ground.rgb) * 1.2, toLinear(u.sky.rgb) * 1.5, smoothstep(-0.25 - rough * 0.5, 0.25 + rough * 0.5, r.y));
|
|
703
|
+
var lit = albedo * (hemi + vec3<f32>(diff)) * (1.0 - metal)
|
|
704
|
+
+ albedo * env * metal * (1.0 - 0.6 * rough)
|
|
705
|
+
+ env * fres * (1.0 - rough) * 0.5
|
|
706
|
+
+ vec3<f32>(spec) * mix(vec3<f32>(1.0), albedo, metal);
|
|
707
|
+
// emission adds light, so a lamp can go above 1.0 and still keep its colour after tone mapping
|
|
708
|
+
lit = lit + albedo * vec3<f32>(1.0, 0.38, 0.26) * lt.z * 0.5 * (1.0 - metal); // soft: the warm scattered band
|
|
709
|
+
lit = lit + albedo * toLinear(vec3<f32>(1.0)) * glowAt(i.w, n) * (1.0 - metal);
|
|
710
|
+
lit = lit + albedo * i.m.w * u.fx.z;
|
|
711
|
+
return vec4<f32>(toSrgb(aces(lit * u.fx.y)), i.m.z);
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
@fragment fn fs(i : VOut, @builtin(front_facing) front : bool) -> @location(0) vec4<f32> {
|
|
715
|
+
var n = normalize(i.n);
|
|
716
|
+
if (!front) { n = -n; }
|
|
717
|
+
let l = normalize(u.light.xyz);
|
|
718
|
+
let v = normalize(u.eye.xyz - i.w);
|
|
719
|
+
if (u.light.w > 0.5) {
|
|
720
|
+
// unlit: no light in the scene, only what glows
|
|
721
|
+
let g = glowAt(i.w, n) * (1.0 - i.m.x);
|
|
722
|
+
if (u.fx.x > 0.5) { return vec4<f32>(toSrgb(aces((toLinear(i.c) * (i.m.w * u.fx.z + g)) * u.fx.y)), i.m.z); }
|
|
723
|
+
return vec4<f32>(clamp(i.c * (min(i.m.w, 1.0) + g), vec3<f32>(0.0), vec3<f32>(1.0)), i.m.z);
|
|
724
|
+
}
|
|
725
|
+
if (u.fx.x > 0.5) { return filmic(i, n, l, v); }
|
|
726
|
+
let metal = i.m.x;
|
|
727
|
+
let rough = i.m.y;
|
|
728
|
+
let hemi = mix(u.ground.rgb, u.sky.rgb, n.y * 0.5 + 0.5) * u.mat.x * select(1.0, 0.7, u.fx.w > 0.5);
|
|
729
|
+
// roughness widens the highlight; metal makes it strong and tinted by the color
|
|
730
|
+
let shin = mix(u.mat.w * 7.0, u.mat.w * 0.15, rough);
|
|
731
|
+
let lt = lights(n, v, shin, i.s);
|
|
732
|
+
let diff = lt.x * u.mat.y;
|
|
733
|
+
let spec = lt.y * mix(u.mat.z, 1.0, metal) * mix(1.0, 0.35, rough);
|
|
734
|
+
// metal mirrors the sky above and the ground below, blurred by roughness
|
|
735
|
+
let r = reflect(-v, n);
|
|
736
|
+
let env = mix(u.ground.rgb * 1.2, u.sky.rgb * 1.5, smoothstep(-0.25 - rough * 0.5, 0.25 + rough * 0.5, r.y));
|
|
737
|
+
var lit = i.c * (hemi + vec3<f32>(diff)) * (1.0 - metal)
|
|
738
|
+
+ i.c * env * metal * (1.0 - 0.6 * rough)
|
|
739
|
+
+ vec3<f32>(spec) * mix(vec3<f32>(1.0), i.c, metal)
|
|
740
|
+
+ i.c * vec3<f32>(1.0, 0.38, 0.26) * lt.z * 0.25 * (1.0 - metal);
|
|
741
|
+
lit = lit + i.c * glowAt(i.w, n) * (1.0 - metal);
|
|
742
|
+
lit = mix(lit, i.c * 1.15, min(i.m.w, 1.0)); // the plain look: emit 0..1 fades to flat colour, more does not add
|
|
743
|
+
return vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)), i.m.z);
|
|
744
|
+
}
|
|
745
|
+
`;
|
|
746
|
+
/**
|
|
747
|
+
* Sets up WebGPU on a canvas. Rejects when WebGPU is not available.
|
|
748
|
+
* Returns { render(mesh, view, options), destroy() }.
|
|
749
|
+
* render options: size (CSS px, the canvas is made size x size), fit, instances { mesh, data } (many copies of one
|
|
750
|
+
* prototype mesh, data from buildInstances; drawn after the mesh), background [r,g,b] 0..1,
|
|
751
|
+
* light { direction, sky, ground }, material { ambient, diffuse, specular, shininess }, dpr.
|
|
752
|
+
*/
|
|
753
|
+
export const createGpu = async (canvas, { sampleCount = 4, onError } = {}) => {
|
|
754
|
+
if (!globalThis.navigator?.gpu)
|
|
755
|
+
throw new Error('WebGPU is not available in this browser');
|
|
756
|
+
const adapter = await navigator.gpu.requestAdapter();
|
|
757
|
+
if (!adapter)
|
|
758
|
+
throw new Error('No WebGPU adapter found');
|
|
759
|
+
const device = await adapter.requestDevice();
|
|
760
|
+
device.addEventListener('uncapturederror', (e) => {
|
|
761
|
+
const message = String(e.error?.message ?? e);
|
|
762
|
+
console.error('WebGPU:', message);
|
|
763
|
+
onError?.(message);
|
|
764
|
+
});
|
|
765
|
+
device.lost.then((info) => console.error('WebGPU device lost:', info.reason, info.message));
|
|
766
|
+
const context = canvas.getContext('webgpu');
|
|
767
|
+
if (!context)
|
|
768
|
+
throw new Error('Could not get a WebGPU canvas context');
|
|
769
|
+
const format = navigator.gpu.getPreferredCanvasFormat();
|
|
770
|
+
context.configure({ device, format, alphaMode: 'premultiplied' }); // opaque everywhere but where a screen punches a hole
|
|
771
|
+
const module = device.createShaderModule({ code: SHADER });
|
|
772
|
+
// shader compile errors are reported to onError too (the browser only logs them to the console)
|
|
773
|
+
module.getCompilationInfo?.().then((info) => {
|
|
774
|
+
for (const m of info.messages ?? [])
|
|
775
|
+
if (m.type === 'error')
|
|
776
|
+
onError?.(`shader line ${m.lineNum}: ${m.message}`);
|
|
777
|
+
});
|
|
778
|
+
const meshLayout = {
|
|
779
|
+
arrayStride: FLOATS * 4,
|
|
780
|
+
attributes: [
|
|
781
|
+
{ shaderLocation: 0, offset: 0, format: 'float32x3' },
|
|
782
|
+
{ shaderLocation: 1, offset: 12, format: 'float32x3' },
|
|
783
|
+
{ shaderLocation: 2, offset: 24, format: 'float32x3' },
|
|
784
|
+
{ shaderLocation: 8, offset: 36, format: 'float32x4' },
|
|
785
|
+
{ shaderLocation: 9, offset: 52, format: 'float32' },
|
|
786
|
+
],
|
|
787
|
+
};
|
|
788
|
+
const instanceLayout = {
|
|
789
|
+
arrayStride: INSTANCE_FLOATS * 4,
|
|
790
|
+
stepMode: 'instance',
|
|
791
|
+
attributes: [3, 4, 5, 6, 7].map((loc, k) => ({ shaderLocation: loc, offset: k * 12, format: 'float32x3' })),
|
|
792
|
+
};
|
|
793
|
+
// ONE explicit layout for every pipeline: with 'auto' each pipeline gets its own, and a bind group made for one is refused by the others
|
|
794
|
+
const bindLayout = device.createBindGroupLayout({
|
|
795
|
+
// visibility 1 | 2 = GPUShaderStage.VERTEX | FRAGMENT
|
|
796
|
+
entries: [
|
|
797
|
+
{ binding: 0, visibility: 1 | 2, buffer: { type: 'uniform' } },
|
|
798
|
+
{ binding: 1, visibility: 1, buffer: { type: 'uniform' } }, // the bones of a skin
|
|
799
|
+
],
|
|
800
|
+
});
|
|
801
|
+
const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [bindLayout] });
|
|
802
|
+
const make = (entry, buffers, glass = false) => device.createRenderPipeline({
|
|
803
|
+
layout: pipelineLayout,
|
|
804
|
+
vertex: { module, entryPoint: entry, buffers },
|
|
805
|
+
fragment: {
|
|
806
|
+
module,
|
|
807
|
+
entryPoint: 'fs',
|
|
808
|
+
targets: [
|
|
809
|
+
glass
|
|
810
|
+
? {
|
|
811
|
+
format,
|
|
812
|
+
blend: {
|
|
813
|
+
color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' },
|
|
814
|
+
alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },
|
|
815
|
+
},
|
|
816
|
+
}
|
|
817
|
+
: { format },
|
|
818
|
+
],
|
|
819
|
+
},
|
|
820
|
+
primitive: { topology: 'triangle-list', cullMode: 'none' },
|
|
821
|
+
// see-through faces (alpha < 1) are blended over what is behind them: they test depth but do not write it
|
|
822
|
+
depthStencil: { format: 'depth24plus', depthWriteEnabled: !glass, depthCompare: 'less' },
|
|
823
|
+
multisample: { count: sampleCount },
|
|
824
|
+
});
|
|
825
|
+
const pipeline = make('vs', [meshLayout]);
|
|
826
|
+
const skinLayout = {
|
|
827
|
+
arrayStride: SKIN_FLOATS * 4,
|
|
828
|
+
attributes: [...meshLayout.attributes, { shaderLocation: 10, offset: 56, format: 'float32x4' }, { shaderLocation: 11, offset: 72, format: 'float32x4' }],
|
|
829
|
+
};
|
|
830
|
+
const skinPipeline = make('vss', [skinLayout]);
|
|
831
|
+
const skinGlassPipeline = make('vss', [skinLayout], true);
|
|
832
|
+
// screens: a second bind group with the picture (one texture per screen)
|
|
833
|
+
const texLayout = device.createBindGroupLayout({
|
|
834
|
+
entries: [
|
|
835
|
+
{ binding: 0, visibility: 2, sampler: {} },
|
|
836
|
+
{ binding: 1, visibility: 2, texture: {} },
|
|
837
|
+
],
|
|
838
|
+
});
|
|
839
|
+
const screenPipeline = device.createRenderPipeline({
|
|
840
|
+
layout: device.createPipelineLayout({ bindGroupLayouts: [bindLayout, texLayout] }),
|
|
841
|
+
vertex: {
|
|
842
|
+
module,
|
|
843
|
+
entryPoint: 'vsq',
|
|
844
|
+
buffers: [{ arrayStride: SCREEN_FLOATS * 4, attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x3' }, { shaderLocation: 1, offset: 12, format: 'float32x2' }] }],
|
|
845
|
+
},
|
|
846
|
+
fragment: { module, entryPoint: 'fsq', targets: [{ format }] },
|
|
847
|
+
primitive: { topology: 'triangle-list', cullMode: 'none' },
|
|
848
|
+
depthStencil: { format: 'depth24plus', depthWriteEnabled: true, depthCompare: 'less' },
|
|
849
|
+
multisample: { count: sampleCount },
|
|
850
|
+
});
|
|
851
|
+
const holePipeline = device.createRenderPipeline({
|
|
852
|
+
layout: pipelineLayout,
|
|
853
|
+
vertex: {
|
|
854
|
+
module,
|
|
855
|
+
entryPoint: 'vsq',
|
|
856
|
+
buffers: [{ arrayStride: SCREEN_FLOATS * 4, attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x3' }, { shaderLocation: 1, offset: 12, format: 'float32x2' }] }],
|
|
857
|
+
},
|
|
858
|
+
fragment: { module, entryPoint: 'fsh', targets: [{ format }] },
|
|
859
|
+
primitive: { topology: 'triangle-list', cullMode: 'none' },
|
|
860
|
+
depthStencil: { format: 'depth24plus', depthWriteEnabled: true, depthCompare: 'less' },
|
|
861
|
+
multisample: { count: sampleCount },
|
|
862
|
+
});
|
|
863
|
+
const screenSampler = device.createSampler({ magFilter: 'linear', minFilter: 'linear' });
|
|
864
|
+
const screenTex = [];
|
|
865
|
+
let screenBuffer = null;
|
|
866
|
+
let screenCap = 0;
|
|
867
|
+
let screenCount = 0;
|
|
868
|
+
const glassPipeline = make('vs', [meshLayout], true);
|
|
869
|
+
// the instanced pipeline reads position and normal only from the prototype (locations 0, 1)
|
|
870
|
+
const instPipeline = make('vsi', [{ ...meshLayout, attributes: meshLayout.attributes.slice(0, 2) }, instanceLayout]);
|
|
871
|
+
const linePipeline = device.createRenderPipeline({
|
|
872
|
+
layout: pipelineLayout,
|
|
873
|
+
vertex: { module, entryPoint: 'vsl', buffers: [{ arrayStride: 12, attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x3' }] }] },
|
|
874
|
+
fragment: {
|
|
875
|
+
module,
|
|
876
|
+
entryPoint: 'fsl',
|
|
877
|
+
targets: [{ format, blend: { color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' }, alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' } } }],
|
|
878
|
+
},
|
|
879
|
+
primitive: { topology: 'line-list' },
|
|
880
|
+
depthStencil: { format: 'depth24plus', depthWriteEnabled: false, depthCompare: 'less-equal' },
|
|
881
|
+
multisample: { count: sampleCount },
|
|
882
|
+
});
|
|
883
|
+
const markPipeline = device.createRenderPipeline({
|
|
884
|
+
layout: pipelineLayout,
|
|
885
|
+
vertex: {
|
|
886
|
+
module,
|
|
887
|
+
entryPoint: 'vsm',
|
|
888
|
+
buffers: [
|
|
889
|
+
{
|
|
890
|
+
arrayStride: MARK_FLOATS * 4,
|
|
891
|
+
stepMode: 'instance',
|
|
892
|
+
attributes: [
|
|
893
|
+
{ shaderLocation: 0, offset: 0, format: 'float32x3' },
|
|
894
|
+
{ shaderLocation: 1, offset: 12, format: 'float32x3' },
|
|
895
|
+
{ shaderLocation: 2, offset: 24, format: 'float32x4' },
|
|
896
|
+
{ shaderLocation: 3, offset: 40, format: 'float32' },
|
|
897
|
+
{ shaderLocation: 4, offset: 44, format: 'float32x3' },
|
|
898
|
+
],
|
|
899
|
+
},
|
|
900
|
+
],
|
|
901
|
+
},
|
|
902
|
+
fragment: {
|
|
903
|
+
module,
|
|
904
|
+
entryPoint: 'fsm',
|
|
905
|
+
targets: [{ format, blend: { color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' }, alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' } } }],
|
|
906
|
+
},
|
|
907
|
+
primitive: { topology: 'triangle-list', cullMode: 'none' },
|
|
908
|
+
depthStencil: { format: 'depth24plus', depthWriteEnabled: false, depthCompare: 'always' },
|
|
909
|
+
multisample: { count: sampleCount },
|
|
910
|
+
});
|
|
911
|
+
const uniforms = device.createBuffer({ size: 800, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
|
|
912
|
+
const boneBuffer = device.createBuffer({ size: MAX_BONES * 52, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
|
|
913
|
+
const emission = new Float32Array(MAX_BONES);
|
|
914
|
+
const entries = [{ binding: 0, resource: { buffer: uniforms } }, { binding: 1, resource: { buffer: boneBuffer } }];
|
|
915
|
+
const bind = device.createBindGroup({ layout: bindLayout, entries });
|
|
916
|
+
const instBind = device.createBindGroup({ layout: bindLayout, entries });
|
|
917
|
+
const skinVerts = skinCache();
|
|
918
|
+
let skinSolid = null;
|
|
919
|
+
let skinSolidCap = 0;
|
|
920
|
+
let skinGlass = null;
|
|
921
|
+
let skinGlassCap = 0;
|
|
922
|
+
let skinSolidCount = 0;
|
|
923
|
+
let skinGlassCount = 0;
|
|
924
|
+
// Geometry that did not change since the last frame is not rebuilt or uploaded again.
|
|
925
|
+
let uploaded = null; // the mesh now in vertexBuffer
|
|
926
|
+
let uploadedPalette; // and the palette it was built with
|
|
927
|
+
let uploadedSmooth = 0; // and the smoothing
|
|
928
|
+
let partCache = new WeakMap(); // vertices per part mesh (see `parts`)
|
|
929
|
+
let partPalette;
|
|
930
|
+
let partSmooth = 0;
|
|
931
|
+
let vertexCount = 0;
|
|
932
|
+
let protoMesh = null;
|
|
933
|
+
let protoBuffer = null;
|
|
934
|
+
let protoCount = 0;
|
|
935
|
+
let instBuffer = null;
|
|
936
|
+
let instCapacity = 0;
|
|
937
|
+
let instData = null;
|
|
938
|
+
let instCount = 0;
|
|
939
|
+
let vertexBuffer = null;
|
|
940
|
+
let capacity = 0;
|
|
941
|
+
let markBuffer = null;
|
|
942
|
+
let markCapacity = 0;
|
|
943
|
+
// the shader planets (planet.ts): their own module, uniforms (the ray matrix, the depth matrix, the size) and instance buffer
|
|
944
|
+
const planetModule = device.createShaderModule({ code: PLANET_WGSL });
|
|
945
|
+
const planetUniforms = device.createBuffer({ size: 144, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
|
|
946
|
+
const planetLayout = device.createBindGroupLayout({ entries: [{ binding: 0, visibility: 3, buffer: {} }] });
|
|
947
|
+
const planetBind = device.createBindGroup({ layout: planetLayout, entries: [{ binding: 0, resource: { buffer: planetUniforms } }] });
|
|
948
|
+
const planetPipeline = device.createRenderPipeline({
|
|
949
|
+
layout: device.createPipelineLayout({ bindGroupLayouts: [planetLayout] }),
|
|
950
|
+
vertex: { module: planetModule, entryPoint: 'vsp', buffers: [{ arrayStride: PLANET_FLOATS * 4, stepMode: 'instance', attributes: Array.from({ length: 9 }, (_, k) => ({ shaderLocation: k, offset: k * 16, format: 'float32x4' })) }] },
|
|
951
|
+
fragment: { module: planetModule, entryPoint: 'fsp', targets: [{ format, blend: { color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' }, alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' } } }] },
|
|
952
|
+
primitive: { topology: 'triangle-list', cullMode: 'none' },
|
|
953
|
+
depthStencil: { format: 'depth24plus', depthWriteEnabled: true, depthCompare: 'less' },
|
|
954
|
+
multisample: { count: sampleCount },
|
|
955
|
+
});
|
|
956
|
+
let planetBuffer = null;
|
|
957
|
+
let planetCap = 0;
|
|
958
|
+
let planetCount = 0;
|
|
959
|
+
let markCount = 0;
|
|
960
|
+
let edgeBuffer = null;
|
|
961
|
+
let edgeCapacity = 0;
|
|
962
|
+
let edgeCount = 0; // vertices (two per line)
|
|
963
|
+
let edgeMesh = null;
|
|
964
|
+
let edgeParts;
|
|
965
|
+
let edgeOn = false;
|
|
966
|
+
let glassBuffer = null; // the see-through triangles, sorted far to near for the eye
|
|
967
|
+
let glassCapacity = 0;
|
|
968
|
+
let glassTris = []; // centroid and offset (in floats) in glassSource
|
|
969
|
+
let glassSource = new Float32Array(0);
|
|
970
|
+
let glassCount = 0;
|
|
971
|
+
let glassEye = '';
|
|
972
|
+
let px = 0;
|
|
973
|
+
let depth = null;
|
|
974
|
+
let color = null;
|
|
975
|
+
const targets = (n) => {
|
|
976
|
+
if (n === px)
|
|
977
|
+
return;
|
|
978
|
+
px = n;
|
|
979
|
+
canvas.width = n;
|
|
980
|
+
canvas.height = n;
|
|
981
|
+
depth?.destroy();
|
|
982
|
+
color?.destroy();
|
|
983
|
+
depth = device.createTexture({ size: [n, n], format: 'depth24plus', sampleCount, usage: GPUTextureUsage.RENDER_ATTACHMENT });
|
|
984
|
+
color = sampleCount > 1 ? device.createTexture({ size: [n, n], format, sampleCount, usage: GPUTextureUsage.RENDER_ATTACHMENT }) : null;
|
|
985
|
+
};
|
|
986
|
+
const draw = (mesh, view, { size = 400, fit, background = [0.98, 0.98, 0.97], transparent = false, light = {}, material = {}, palette, dpr = globalThis.devicePixelRatio || 1, instances, parts, tonemap = false, smooth = false, studio = false, edges = false, marks, unlit = false, glow = false, skin, screens, logDepth = 0, planets } = {}, readback = false) => {
|
|
987
|
+
const L = { ...defaultLight, ...light };
|
|
988
|
+
const filmic = tonemap ? { exposure: 1, emit: 2, ...(tonemap === true ? {} : tonemap) } : null;
|
|
989
|
+
const M = { ...defaultMaterial, ...material };
|
|
990
|
+
const cam = makeCamera(view, mesh, size, fit);
|
|
991
|
+
targets(Math.max(1, Math.round(size * dpr)));
|
|
992
|
+
const crease = smooth === true ? 40 : smooth || 0;
|
|
993
|
+
if (mesh !== uploaded || palette !== uploadedPalette || crease !== uploadedSmooth) {
|
|
994
|
+
uploadedSmooth = crease;
|
|
995
|
+
let all;
|
|
996
|
+
if (parts && parts.length) {
|
|
997
|
+
if (palette !== partPalette || crease !== partSmooth) {
|
|
998
|
+
partCache = new WeakMap();
|
|
999
|
+
partPalette = palette;
|
|
1000
|
+
partSmooth = crease;
|
|
1001
|
+
}
|
|
1002
|
+
const built = parts.map((m) => {
|
|
1003
|
+
let v = partCache.get(m);
|
|
1004
|
+
if (!v)
|
|
1005
|
+
partCache.set(m, (v = buildVertices(m, palette, { smooth: crease })));
|
|
1006
|
+
return v;
|
|
1007
|
+
});
|
|
1008
|
+
all = new Float32Array(built.reduce((n, v) => n + v.length, 0));
|
|
1009
|
+
let at = 0;
|
|
1010
|
+
for (const v of built) {
|
|
1011
|
+
all.set(v, at);
|
|
1012
|
+
at += v.length;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
else
|
|
1016
|
+
all = buildVertices(mesh, palette, { smooth: crease });
|
|
1017
|
+
// split: solid triangles are drawn first; triangles with alpha < 1 are kept apart and blended afterwards
|
|
1018
|
+
const tri = 3 * FLOATS;
|
|
1019
|
+
const solid = new Float32Array(all.length);
|
|
1020
|
+
let solidLen = 0;
|
|
1021
|
+
glassTris = [];
|
|
1022
|
+
for (let o = 0; o < all.length; o += tri) {
|
|
1023
|
+
if (all[o + 11] < 1) {
|
|
1024
|
+
const c = [0, 1, 2].map((k) => (all[o + k] + all[o + FLOATS + k] + all[o + 2 * FLOATS + k]) / 3);
|
|
1025
|
+
glassTris.push({ c, at: o });
|
|
1026
|
+
}
|
|
1027
|
+
else {
|
|
1028
|
+
solid.set(all.subarray(o, o + tri), solidLen);
|
|
1029
|
+
solidLen += tri;
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
glassSource = all;
|
|
1033
|
+
glassEye = '';
|
|
1034
|
+
const verts = solid.subarray(0, solidLen);
|
|
1035
|
+
if (verts.byteLength > capacity) {
|
|
1036
|
+
vertexBuffer?.destroy();
|
|
1037
|
+
capacity = Math.max(verts.byteLength, 4096);
|
|
1038
|
+
vertexBuffer = device.createBuffer({ size: capacity, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1039
|
+
}
|
|
1040
|
+
if (verts.byteLength)
|
|
1041
|
+
device.queue.writeBuffer(vertexBuffer, 0, verts);
|
|
1042
|
+
vertexCount = verts.length / FLOATS;
|
|
1043
|
+
uploaded = mesh;
|
|
1044
|
+
uploadedPalette = palette;
|
|
1045
|
+
}
|
|
1046
|
+
if (!edges)
|
|
1047
|
+
edgeCount = 0;
|
|
1048
|
+
else if (mesh !== edgeMesh || parts !== edgeParts || !edgeOn) {
|
|
1049
|
+
const e = sceneEdges(mesh, parts);
|
|
1050
|
+
if (e.byteLength > edgeCapacity) {
|
|
1051
|
+
edgeBuffer?.destroy();
|
|
1052
|
+
edgeCapacity = Math.max(e.byteLength, 4096);
|
|
1053
|
+
edgeBuffer = device.createBuffer({ size: edgeCapacity, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1054
|
+
}
|
|
1055
|
+
if (e.byteLength)
|
|
1056
|
+
device.queue.writeBuffer(edgeBuffer, 0, e);
|
|
1057
|
+
edgeCount = e.length / 3;
|
|
1058
|
+
edgeMesh = mesh;
|
|
1059
|
+
edgeParts = parts;
|
|
1060
|
+
}
|
|
1061
|
+
edgeOn = edges;
|
|
1062
|
+
if (instances?.mesh && instances.mesh !== protoMesh) {
|
|
1063
|
+
const v = buildVertices(instances.mesh);
|
|
1064
|
+
protoBuffer?.destroy();
|
|
1065
|
+
protoBuffer = device.createBuffer({ size: Math.max(v.byteLength, 256), usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1066
|
+
device.queue.writeBuffer(protoBuffer, 0, v);
|
|
1067
|
+
protoCount = v.length / FLOATS;
|
|
1068
|
+
protoMesh = instances.mesh;
|
|
1069
|
+
}
|
|
1070
|
+
if (instances?.data && instances.data !== instData) {
|
|
1071
|
+
const d = instances.data;
|
|
1072
|
+
if (d.byteLength > instCapacity) {
|
|
1073
|
+
instBuffer?.destroy();
|
|
1074
|
+
instCapacity = Math.max(d.byteLength, 4096);
|
|
1075
|
+
instBuffer = device.createBuffer({ size: instCapacity, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1076
|
+
}
|
|
1077
|
+
if (d.byteLength)
|
|
1078
|
+
device.queue.writeBuffer(instBuffer, 0, d);
|
|
1079
|
+
instData = d;
|
|
1080
|
+
instCount = d.length / INSTANCE_FLOATS;
|
|
1081
|
+
}
|
|
1082
|
+
if (!instances)
|
|
1083
|
+
instCount = 0;
|
|
1084
|
+
if (skin && skin.meshes.length) {
|
|
1085
|
+
const v = skinVerts(skin, palette, crease);
|
|
1086
|
+
if (v.fresh) {
|
|
1087
|
+
if (v.solid.byteLength > skinSolidCap) {
|
|
1088
|
+
skinSolid?.destroy();
|
|
1089
|
+
skinSolidCap = Math.max(v.solid.byteLength, 4096);
|
|
1090
|
+
skinSolid = device.createBuffer({ size: skinSolidCap, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1091
|
+
}
|
|
1092
|
+
if (v.solid.byteLength)
|
|
1093
|
+
device.queue.writeBuffer(skinSolid, 0, v.solid);
|
|
1094
|
+
if (v.glass.byteLength > skinGlassCap) {
|
|
1095
|
+
skinGlass?.destroy();
|
|
1096
|
+
skinGlassCap = Math.max(v.glass.byteLength, 4096);
|
|
1097
|
+
skinGlass = device.createBuffer({ size: skinGlassCap, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1098
|
+
}
|
|
1099
|
+
if (v.glass.byteLength)
|
|
1100
|
+
device.queue.writeBuffer(skinGlass, 0, v.glass);
|
|
1101
|
+
skinSolidCount = v.solid.length / SKIN_FLOATS;
|
|
1102
|
+
skinGlassCount = v.glass.length / SKIN_FLOATS;
|
|
1103
|
+
}
|
|
1104
|
+
const b = skin.bones.subarray(0, MAX_BONES * 12);
|
|
1105
|
+
if (b.byteLength)
|
|
1106
|
+
device.queue.writeBuffer(boneBuffer, 0, b);
|
|
1107
|
+
emission.fill(1);
|
|
1108
|
+
if (skin.emission)
|
|
1109
|
+
emission.set(skin.emission.subarray(0, MAX_BONES));
|
|
1110
|
+
device.queue.writeBuffer(boneBuffer, MAX_BONES * 48, emission);
|
|
1111
|
+
}
|
|
1112
|
+
else
|
|
1113
|
+
skinSolidCount = skinGlassCount = 0;
|
|
1114
|
+
const eyeKey = cam.eye.join(',');
|
|
1115
|
+
if (glassTris.length && eyeKey !== glassEye) {
|
|
1116
|
+
glassEye = eyeKey;
|
|
1117
|
+
const [ex, ey, ez] = cam.eye;
|
|
1118
|
+
const far = (t) => (t.c[0] - ex) ** 2 + (t.c[1] - ey) ** 2 + (t.c[2] - ez) ** 2;
|
|
1119
|
+
const sorted = [...glassTris].sort((a, b) => far(b) - far(a)); // far first
|
|
1120
|
+
const out = new Float32Array(sorted.length * 3 * FLOATS);
|
|
1121
|
+
sorted.forEach((t, k) => out.set(glassSource.subarray(t.at, t.at + 3 * FLOATS), k * 3 * FLOATS));
|
|
1122
|
+
if (out.byteLength > glassCapacity) {
|
|
1123
|
+
glassBuffer?.destroy();
|
|
1124
|
+
glassCapacity = Math.max(out.byteLength, 4096);
|
|
1125
|
+
glassBuffer = device.createBuffer({ size: glassCapacity, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1126
|
+
}
|
|
1127
|
+
device.queue.writeBuffer(glassBuffer, 0, out);
|
|
1128
|
+
glassCount = sorted.length * 3;
|
|
1129
|
+
}
|
|
1130
|
+
if (!glassTris.length)
|
|
1131
|
+
glassCount = 0;
|
|
1132
|
+
// studio rig, relative to the camera: key upper left in front, fill from the right, rim from behind and above
|
|
1133
|
+
const rig = (f, r, up) => norm([0, 1, 2].map((k) => -cam.f[k] * f + cam.r[k] * r + cam.u[k] * up));
|
|
1134
|
+
const S = studio ? { fill: 0.4, rim: 1, ...(studio === true ? {} : studio) } : null;
|
|
1135
|
+
const u = new Float32Array(52 + MAX_LIGHTS * 8 + 20);
|
|
1136
|
+
u.set(viewProjection(cam, nearPlane(cam, mesh)), 0);
|
|
1137
|
+
u.set(viewProjection({ ...cam, eye: [0, 0, 0] }, nearPlane(cam, mesh)), 52 + MAX_LIGHTS * 8); // the marks' eye-centred matrix
|
|
1138
|
+
u.set([cam.ortho ? 0 : cam.k * (px / size), 0, 0, 0], 52 + MAX_LIGHTS * 8 + 16);
|
|
1139
|
+
u.set([...(S ? rig(0.7, -0.5, 0.6) : norm(L.direction)), unlit ? 1 : 0], 16);
|
|
1140
|
+
u.set([...L.sky, 0], 20);
|
|
1141
|
+
u.set([...L.ground, 0], 24);
|
|
1142
|
+
u.set([...cam.eye, logDepth > 0 && !cam.ortho ? logDepth : 0], 28);
|
|
1143
|
+
u.set([M.ambient, M.diffuse, M.specular, M.shininess], 32);
|
|
1144
|
+
u.set([filmic ? 1 : 0, filmic ? filmic.exposure : 1, filmic ? filmic.emit : 0, S ? 1 : 0], 36);
|
|
1145
|
+
u.set([...rig(0.6, 0.8, 0.1), S ? S.fill : 0], 40);
|
|
1146
|
+
u.set([...rig(-0.8, 0.3, 0.5), S ? S.rim : 0], 44);
|
|
1147
|
+
const lights = glow ? sceneLights(mesh, parts, palette, skin) : new Float32Array(0);
|
|
1148
|
+
u.set([px, px, px / size, lights.length / LIGHT_FLOATS], 48);
|
|
1149
|
+
for (let k = 0; k < lights.length / LIGHT_FLOATS; k++) {
|
|
1150
|
+
u.set(lights.subarray(k * LIGHT_FLOATS, k * LIGHT_FLOATS + 4), 52 + k * 4);
|
|
1151
|
+
u.set([...lights.subarray(k * LIGHT_FLOATS + 4, k * LIGHT_FLOATS + 7), 0], 52 + MAX_LIGHTS * 4 + k * 4);
|
|
1152
|
+
}
|
|
1153
|
+
device.queue.writeBuffer(uniforms, 0, u);
|
|
1154
|
+
planetCount = 0;
|
|
1155
|
+
if (planets?.length && !cam.ortho) {
|
|
1156
|
+
const vpRot = viewProjection({ ...cam, eye: [0, 0, 0] }, nearPlane(cam, mesh));
|
|
1157
|
+
const inv = inv4(vpRot);
|
|
1158
|
+
const pi = inv ? planetInstances(planets, cam.eye, vpRot) : null;
|
|
1159
|
+
if (pi?.count && inv) {
|
|
1160
|
+
if (pi.data.byteLength > planetCap) {
|
|
1161
|
+
planetBuffer?.destroy();
|
|
1162
|
+
planetCap = Math.max(pi.data.byteLength, PLANET_FLOATS * 4 * 16);
|
|
1163
|
+
planetBuffer = device.createBuffer({ size: planetCap, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1164
|
+
}
|
|
1165
|
+
device.queue.writeBuffer(planetBuffer, 0, pi.data);
|
|
1166
|
+
const pu = new Float32Array(36);
|
|
1167
|
+
pu.set(inv, 0);
|
|
1168
|
+
pu.set(vpRot, 16);
|
|
1169
|
+
pu.set([px, px, logDepth > 0 ? logDepth : 0, 0], 32);
|
|
1170
|
+
device.queue.writeBuffer(planetUniforms, 0, pu);
|
|
1171
|
+
planetCount = pi.count;
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
const markData = marks?.length ? buildMarks(marks, cam.eye) : null;
|
|
1175
|
+
markCount = markData ? markData.length / MARK_FLOATS : 0;
|
|
1176
|
+
if (markData && markData.byteLength) {
|
|
1177
|
+
if (markData.byteLength > markCapacity) {
|
|
1178
|
+
markBuffer?.destroy();
|
|
1179
|
+
markCapacity = Math.ceil(markData.byteLength * 1.5);
|
|
1180
|
+
markBuffer = device.createBuffer({ size: markCapacity, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1181
|
+
}
|
|
1182
|
+
device.queue.writeBuffer(markBuffer, 0, markData);
|
|
1183
|
+
}
|
|
1184
|
+
// screens: copy each picture into its texture (made again when its size changes) and the quads into one buffer
|
|
1185
|
+
screenCount = 0;
|
|
1186
|
+
const shown = [];
|
|
1187
|
+
const holes = [];
|
|
1188
|
+
(screens ?? []).forEach((sc, i) => {
|
|
1189
|
+
if (sc.hole)
|
|
1190
|
+
return void holes.push(i);
|
|
1191
|
+
const w = sc.source?.width | 0;
|
|
1192
|
+
const h = sc.source?.height | 0;
|
|
1193
|
+
if (!w || !h)
|
|
1194
|
+
return;
|
|
1195
|
+
let t = screenTex[i];
|
|
1196
|
+
if (!t || t.w !== w || t.h !== h) {
|
|
1197
|
+
t?.tex.destroy();
|
|
1198
|
+
const tex = device.createTexture({ size: [w, h], format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT });
|
|
1199
|
+
const group = device.createBindGroup({ layout: texLayout, entries: [{ binding: 0, resource: screenSampler }, { binding: 1, resource: tex.createView() }] });
|
|
1200
|
+
t = screenTex[i] = { tex, w, h, group };
|
|
1201
|
+
}
|
|
1202
|
+
try {
|
|
1203
|
+
device.queue.copyExternalImageToTexture({ source: sc.source }, { texture: t.tex }, [w, h]);
|
|
1204
|
+
shown.push(i);
|
|
1205
|
+
}
|
|
1206
|
+
catch (err) {
|
|
1207
|
+
onError?.(`screen ${i}: ${err.message}`);
|
|
1208
|
+
}
|
|
1209
|
+
});
|
|
1210
|
+
if (shown.length || holes.length) {
|
|
1211
|
+
const quads = buildScreenQuads(screens);
|
|
1212
|
+
if (quads.byteLength > screenCap) {
|
|
1213
|
+
screenBuffer?.destroy();
|
|
1214
|
+
screenCap = quads.byteLength;
|
|
1215
|
+
screenBuffer = device.createBuffer({ size: screenCap, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
|
1216
|
+
}
|
|
1217
|
+
device.queue.writeBuffer(screenBuffer, 0, quads);
|
|
1218
|
+
screenCount = shown.length + holes.length;
|
|
1219
|
+
}
|
|
1220
|
+
const encoder = device.createCommandEncoder();
|
|
1221
|
+
const offscreen = readback
|
|
1222
|
+
? device.createTexture({ size: [px, px], format, usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC })
|
|
1223
|
+
: null;
|
|
1224
|
+
const target = (offscreen ?? context.getCurrentTexture()).createView();
|
|
1225
|
+
const pass = encoder.beginRenderPass({
|
|
1226
|
+
colorAttachments: [
|
|
1227
|
+
{
|
|
1228
|
+
view: color ? color.createView() : target,
|
|
1229
|
+
resolveTarget: color ? target : undefined,
|
|
1230
|
+
clearValue: transparent ? { r: 0, g: 0, b: 0, a: 0 } : { r: background[0], g: background[1], b: background[2], a: 1 },
|
|
1231
|
+
loadOp: 'clear',
|
|
1232
|
+
storeOp: color ? 'discard' : 'store',
|
|
1233
|
+
},
|
|
1234
|
+
],
|
|
1235
|
+
depthStencilAttachment: { view: depth.createView(), depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'discard' },
|
|
1236
|
+
});
|
|
1237
|
+
if (vertexCount) {
|
|
1238
|
+
pass.setPipeline(pipeline);
|
|
1239
|
+
pass.setBindGroup(0, bind);
|
|
1240
|
+
pass.setVertexBuffer(0, vertexBuffer);
|
|
1241
|
+
pass.draw(vertexCount);
|
|
1242
|
+
}
|
|
1243
|
+
if (instCount && protoCount) {
|
|
1244
|
+
pass.setPipeline(instPipeline);
|
|
1245
|
+
pass.setBindGroup(0, instBind);
|
|
1246
|
+
pass.setVertexBuffer(0, protoBuffer);
|
|
1247
|
+
pass.setVertexBuffer(1, instBuffer);
|
|
1248
|
+
pass.draw(protoCount, instCount);
|
|
1249
|
+
}
|
|
1250
|
+
if (shown.length) {
|
|
1251
|
+
pass.setPipeline(screenPipeline);
|
|
1252
|
+
pass.setBindGroup(0, bind);
|
|
1253
|
+
pass.setVertexBuffer(0, screenBuffer);
|
|
1254
|
+
for (const i of shown) {
|
|
1255
|
+
pass.setBindGroup(1, screenTex[i].group);
|
|
1256
|
+
pass.draw(6, 1, i * 6);
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
if (holes.length) {
|
|
1260
|
+
pass.setPipeline(holePipeline);
|
|
1261
|
+
pass.setBindGroup(0, bind);
|
|
1262
|
+
pass.setVertexBuffer(0, screenBuffer);
|
|
1263
|
+
for (const i of holes)
|
|
1264
|
+
pass.draw(6, 1, i * 6);
|
|
1265
|
+
}
|
|
1266
|
+
if (skinSolidCount) {
|
|
1267
|
+
pass.setPipeline(skinPipeline);
|
|
1268
|
+
pass.setBindGroup(0, bind);
|
|
1269
|
+
pass.setVertexBuffer(0, skinSolid);
|
|
1270
|
+
pass.draw(skinSolidCount);
|
|
1271
|
+
}
|
|
1272
|
+
if (planetCount) {
|
|
1273
|
+
pass.setPipeline(planetPipeline);
|
|
1274
|
+
pass.setBindGroup(0, planetBind);
|
|
1275
|
+
pass.setVertexBuffer(0, planetBuffer);
|
|
1276
|
+
pass.draw(6, planetCount);
|
|
1277
|
+
}
|
|
1278
|
+
if (edgeCount) {
|
|
1279
|
+
pass.setPipeline(linePipeline);
|
|
1280
|
+
pass.setBindGroup(0, bind);
|
|
1281
|
+
pass.setVertexBuffer(0, edgeBuffer);
|
|
1282
|
+
pass.draw(edgeCount);
|
|
1283
|
+
}
|
|
1284
|
+
if (glassCount) {
|
|
1285
|
+
// after everything solid (and the instances): see-through faces, far to near
|
|
1286
|
+
pass.setPipeline(glassPipeline);
|
|
1287
|
+
pass.setBindGroup(0, bind);
|
|
1288
|
+
pass.setVertexBuffer(0, glassBuffer);
|
|
1289
|
+
pass.draw(glassCount);
|
|
1290
|
+
}
|
|
1291
|
+
if (skinGlassCount) {
|
|
1292
|
+
pass.setPipeline(skinGlassPipeline);
|
|
1293
|
+
pass.setBindGroup(0, bind);
|
|
1294
|
+
pass.setVertexBuffer(0, skinGlass);
|
|
1295
|
+
pass.draw(skinGlassCount);
|
|
1296
|
+
}
|
|
1297
|
+
if (markCount) {
|
|
1298
|
+
pass.setPipeline(markPipeline);
|
|
1299
|
+
pass.setBindGroup(0, bind);
|
|
1300
|
+
pass.setVertexBuffer(0, markBuffer);
|
|
1301
|
+
pass.draw(6, markCount);
|
|
1302
|
+
}
|
|
1303
|
+
pass.end();
|
|
1304
|
+
if (!offscreen) {
|
|
1305
|
+
device.queue.submit([encoder.finish()]);
|
|
1306
|
+
return null;
|
|
1307
|
+
}
|
|
1308
|
+
const row = Math.ceil((px * 4) / 256) * 256;
|
|
1309
|
+
const out = device.createBuffer({ size: row * px, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
|
|
1310
|
+
encoder.copyTextureToBuffer({ texture: offscreen }, { buffer: out, bytesPerRow: row }, [px, px]);
|
|
1311
|
+
device.queue.submit([encoder.finish()]);
|
|
1312
|
+
return out.mapAsync(GPUMapMode.READ).then(() => {
|
|
1313
|
+
const raw = new Uint8Array(out.getMappedRange());
|
|
1314
|
+
const data = new Uint8ClampedArray(px * px * 4);
|
|
1315
|
+
const swap = format.startsWith('bgra');
|
|
1316
|
+
for (let y = 0; y < px; y++) {
|
|
1317
|
+
for (let x = 0; x < px; x++) {
|
|
1318
|
+
const i = y * row + x * 4;
|
|
1319
|
+
const o = (y * px + x) * 4;
|
|
1320
|
+
data[o] = raw[i + (swap ? 2 : 0)];
|
|
1321
|
+
data[o + 1] = raw[i + 1];
|
|
1322
|
+
data[o + 2] = raw[i + (swap ? 0 : 2)];
|
|
1323
|
+
data[o + 3] = transparent ? raw[i + 3] : 255;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
out.unmap();
|
|
1327
|
+
out.destroy();
|
|
1328
|
+
offscreen.destroy();
|
|
1329
|
+
return { width: px, height: px, data };
|
|
1330
|
+
});
|
|
1331
|
+
};
|
|
1332
|
+
/** Draws a frame onto the canvas. */
|
|
1333
|
+
const render = (mesh, view, options) => {
|
|
1334
|
+
draw(mesh, view, options);
|
|
1335
|
+
};
|
|
1336
|
+
/** Draws a frame into an offscreen texture and reads it back: Promise<{ width, height, data: RGBA }>. */
|
|
1337
|
+
const pixels = (mesh, view, options) => draw(mesh, view, options, true);
|
|
1338
|
+
const destroy = () => {
|
|
1339
|
+
vertexBuffer?.destroy();
|
|
1340
|
+
glassBuffer?.destroy();
|
|
1341
|
+
markBuffer?.destroy();
|
|
1342
|
+
protoBuffer?.destroy();
|
|
1343
|
+
instBuffer?.destroy();
|
|
1344
|
+
skinSolid?.destroy();
|
|
1345
|
+
skinGlass?.destroy();
|
|
1346
|
+
screenBuffer?.destroy();
|
|
1347
|
+
for (const t of screenTex)
|
|
1348
|
+
t?.tex.destroy();
|
|
1349
|
+
boneBuffer.destroy();
|
|
1350
|
+
depth?.destroy();
|
|
1351
|
+
color?.destroy();
|
|
1352
|
+
uniforms.destroy();
|
|
1353
|
+
device.destroy();
|
|
1354
|
+
};
|
|
1355
|
+
return { render, pixels, destroy, device, adapter };
|
|
1356
|
+
};
|