@geastack/gea3d 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.
@@ -0,0 +1,968 @@
1
+ // SPDX-License-Identifier: GPL-3.0-only
2
+ /// <reference lib="dom" />
3
+ // Browser implementation of gea3d's native engine for the DOM web target,
4
+ // which has no native code. Same exports as api.ts; an app selects it in its
5
+ // vite.web.config.ts (see gea3d/README.md):
6
+ //
7
+ // resolve: { alias: [{ find: /^\.\.\/native\/api$/, replacement: '../native/api.web' }] }
8
+ //
9
+ // Frames are drawn with Canvas 2D into a <canvas> behind the app's DOM, so
10
+ // the retained UI stays on top. It is a preview renderer: faces are flat
11
+ // (vertex colours averaged), sorted back to front, and fog, lights, blending,
12
+ // lines, points, sprites and instances follow the native engine.
13
+
14
+ import {
15
+ BACKGROUND_GRADIENT,
16
+ BACKGROUND_NONE,
17
+ FOG_EXP2,
18
+ FOG_LINEAR,
19
+ LIGHT_AMBIENT,
20
+ LIGHT_DIRECTIONAL,
21
+ LIGHT_HEMISPHERE,
22
+ LIGHT_POINT,
23
+ MATERIAL_ADDITIVE,
24
+ MATERIAL_FOG,
25
+ MATERIAL_SIZE_ATTENUATION,
26
+ MATERIAL_TRANSPARENT,
27
+ MATERIAL_VERTEX_COLORS,
28
+ MATERIAL_VISIBLE,
29
+ MATERIAL_WIREFRAME,
30
+ NODE_CAMERA,
31
+ NODE_GROUP,
32
+ NODE_LIGHT,
33
+ NODE_LINE,
34
+ NODE_LINE_SEGMENTS,
35
+ NODE_MESH,
36
+ NODE_POINTS,
37
+ NODE_SPRITE,
38
+ } from './constants'
39
+
40
+ export * from './constants'
41
+
42
+ type Matrix = Float32Array
43
+
44
+ interface WebBuffer {
45
+ f32: Float32Array
46
+ u32: Uint32Array
47
+ }
48
+
49
+ interface WebGeometry {
50
+ position: number
51
+ index: number
52
+ color: number
53
+ normal: number
54
+ }
55
+
56
+ interface WebMaterial {
57
+ shade: number
58
+ color: number[]
59
+ opacity: number
60
+ side: number
61
+ flags: number
62
+ size: number
63
+ }
64
+
65
+ interface WebNode {
66
+ kind: number
67
+ parent: number
68
+ children: number[]
69
+ position: number[]
70
+ quaternion: number[]
71
+ scale: number[]
72
+ local: Matrix
73
+ useMatrix: boolean
74
+ world: Matrix
75
+ visible: boolean
76
+ frustumCulled: boolean
77
+ renderOrder: number
78
+ geometry: number
79
+ material: number
80
+ // An InstancedMesh draws its instances only (none at a count of 0).
81
+ instanced: boolean
82
+ instanceMatrices: number
83
+ instanceColors: number
84
+ instanceCount: number
85
+ lightKind: number
86
+ lightColor: number[]
87
+ intensity: number
88
+ groundColor: number[]
89
+ distance: number
90
+ decay: number
91
+ target: number[]
92
+ projection: Matrix
93
+ near: number
94
+ far: number
95
+ background: number
96
+ backgroundTop: number
97
+ backgroundBottom: number
98
+ fog: number
99
+ fogColor: number
100
+ fogNear: number
101
+ fogFar: number
102
+ fogDensity: number
103
+ }
104
+
105
+ // A primitive in screen space, painted back to front.
106
+ interface Shape {
107
+ depth: number
108
+ xs: number[]
109
+ ys: number[]
110
+ color: string
111
+ alpha: number
112
+ additive: boolean
113
+ // The object's renderOrder: sorted by it first, then back to front.
114
+ layer: number
115
+ line: boolean
116
+ // Stroke width in pixels: a line's width, or the hairline that hides face seams.
117
+ width: number
118
+ }
119
+
120
+ interface Lights {
121
+ ambient: number[]
122
+ directions: number[][]
123
+ directionalColors: number[][]
124
+ points: number[][]
125
+ pointColors: number[][]
126
+ pointRanges: number[][]
127
+ hemisphereUps: number[][]
128
+ skies: number[][]
129
+ grounds: number[][]
130
+ }
131
+
132
+ const buffers: (WebBuffer | null)[] = []
133
+ const geometries: (WebGeometry | null)[] = []
134
+ const materials: (WebMaterial | null)[] = []
135
+ const nodes: (WebNode | null)[] = []
136
+ const stats = [0, 0, 0, 0, 0, 0, 0, 0, 0]
137
+ const rayHit = [0, 0, 0, 0, -1, -1]
138
+ let canvas: HTMLCanvasElement | null = null
139
+
140
+ function allocate<T>(pool: (T | null)[], value: T): number {
141
+ const free = pool.indexOf(null)
142
+ if (free >= 0) {
143
+ pool[free] = value
144
+ return free
145
+ }
146
+ pool.push(value)
147
+ return pool.length - 1
148
+ }
149
+
150
+ function identity(): Matrix {
151
+ const m = new Float32Array(16)
152
+ m[0] = m[5] = m[10] = m[15] = 1
153
+ return m
154
+ }
155
+
156
+ // ---- buffers, geometry, materials
157
+
158
+ export function createBuffer(): number {
159
+ return allocate(buffers, { f32: new Float32Array(0), u32: new Uint32Array(0) })
160
+ }
161
+
162
+ export function deleteBuffer(buffer: number): void {
163
+ if (buffers[buffer]) buffers[buffer] = null
164
+ }
165
+
166
+ export function bufferDataF32(buffer: number, data: Float32Array): void {
167
+ const slot = buffers[buffer]
168
+ if (slot) slot.f32 = new Float32Array(data)
169
+ }
170
+
171
+ export function bufferDataU32(buffer: number, data: Uint32Array): void {
172
+ const slot = buffers[buffer]
173
+ if (slot) slot.u32 = new Uint32Array(data)
174
+ }
175
+
176
+ export function createGeometry(): number {
177
+ return allocate(geometries, { position: -1, index: -1, color: -1, normal: -1 })
178
+ }
179
+
180
+ export function deleteGeometry(geometry: number): void {
181
+ if (geometries[geometry]) geometries[geometry] = null
182
+ }
183
+
184
+ export function geometryBuffers(geometry: number, position: number, index: number, color: number, normal: number): void {
185
+ const slot = geometries[geometry]
186
+ if (slot) Object.assign(slot, { position, index, color, normal })
187
+ }
188
+
189
+ export function createMaterial(): number {
190
+ return allocate(materials, { shade: 1, color: [1, 1, 1], opacity: 1, side: 0, flags: MATERIAL_VISIBLE, size: 1 })
191
+ }
192
+
193
+ export function deleteMaterial(material: number): void {
194
+ if (materials[material]) materials[material] = null
195
+ }
196
+
197
+ export function materialSet(
198
+ material: number,
199
+ shade: number,
200
+ r: number,
201
+ g: number,
202
+ b: number,
203
+ opacity: number,
204
+ side: number,
205
+ flags: number,
206
+ size: number,
207
+ ): void {
208
+ const slot = materials[material]
209
+ if (slot) Object.assign(slot, { shade, color: [r, g, b], opacity, side, flags, size })
210
+ }
211
+
212
+ // ---- nodes
213
+
214
+ export function createNode(kind: number): number {
215
+ return allocate(nodes, {
216
+ kind,
217
+ parent: -1,
218
+ children: [],
219
+ position: [0, 0, 0],
220
+ quaternion: [0, 0, 0, 1],
221
+ scale: [1, 1, 1],
222
+ local: identity(),
223
+ useMatrix: false,
224
+ world: identity(),
225
+ visible: true,
226
+ frustumCulled: true,
227
+ renderOrder: 0,
228
+ geometry: -1,
229
+ material: -1,
230
+ instanced: false,
231
+ instanceMatrices: -1,
232
+ instanceColors: -1,
233
+ instanceCount: 0,
234
+ lightKind: 0,
235
+ lightColor: [1, 1, 1],
236
+ intensity: 1,
237
+ groundColor: [1, 1, 1],
238
+ distance: 0,
239
+ decay: 2,
240
+ target: [0, 0, 0],
241
+ projection: identity(),
242
+ near: 0.1,
243
+ far: 2000,
244
+ background: BACKGROUND_NONE,
245
+ backgroundTop: 0,
246
+ backgroundBottom: 0,
247
+ fog: 0,
248
+ fogColor: 0,
249
+ fogNear: 1,
250
+ fogFar: 1000,
251
+ fogDensity: 0,
252
+ })
253
+ }
254
+
255
+ function detach(id: number): void {
256
+ const node = nodes[id]
257
+ if (!node || node.parent < 0) return
258
+ const parent = nodes[node.parent]
259
+ if (parent) parent.children = parent.children.filter((child) => child !== id)
260
+ node.parent = -1
261
+ }
262
+
263
+ export function deleteNode(node: number): void {
264
+ const slot = nodes[node]
265
+ if (!slot) return
266
+ detach(node)
267
+ for (const child of slot.children) {
268
+ const childNode = nodes[child]
269
+ if (childNode) childNode.parent = -1
270
+ }
271
+ nodes[node] = null
272
+ }
273
+
274
+ export function nodeParent(node: number, parent: number): void {
275
+ const slot = nodes[node]
276
+ if (!slot || slot.parent === parent) return
277
+ detach(node)
278
+ const parentNode = parent >= 0 ? nodes[parent] : null
279
+ if (!parentNode) return
280
+ slot.parent = parent
281
+ parentNode.children.push(node)
282
+ }
283
+
284
+ export function nodeTransform(
285
+ node: number,
286
+ px: number, py: number, pz: number,
287
+ qx: number, qy: number, qz: number, qw: number,
288
+ sx: number, sy: number, sz: number,
289
+ ): void {
290
+ const slot = nodes[node]
291
+ if (!slot) return
292
+ slot.position = [px, py, pz]
293
+ slot.quaternion = [qx, qy, qz, qw]
294
+ slot.scale = [sx, sy, sz]
295
+ slot.useMatrix = false
296
+ }
297
+
298
+ export function nodeMatrix(node: number, elements: Float32Array): void {
299
+ const slot = nodes[node]
300
+ if (!slot) return
301
+ slot.local.set(elements.subarray(0, 16))
302
+ slot.useMatrix = true
303
+ }
304
+
305
+ export function nodeFlags(node: number, visible: number, frustumCulled: number, renderOrder: number): void {
306
+ const slot = nodes[node]
307
+ if (!slot) return
308
+ slot.visible = visible !== 0
309
+ slot.frustumCulled = frustumCulled !== 0
310
+ slot.renderOrder = renderOrder
311
+ }
312
+
313
+ export function nodeGeometry(node: number, geometry: number, material: number): void {
314
+ const slot = nodes[node]
315
+ if (slot) Object.assign(slot, { geometry, material })
316
+ }
317
+
318
+ export function nodeInstances(node: number, matrices: number, colors: number, count: number): void {
319
+ const slot = nodes[node]
320
+ if (slot) Object.assign(slot, { instanced: true, instanceMatrices: matrices, instanceColors: colors, instanceCount: count })
321
+ }
322
+
323
+ export function nodeLight(
324
+ node: number,
325
+ kind: number,
326
+ r: number, g: number, b: number,
327
+ intensity: number,
328
+ groundR: number, groundG: number, groundB: number,
329
+ distance: number,
330
+ decay: number,
331
+ ): void {
332
+ const slot = nodes[node]
333
+ if (slot) Object.assign(slot, { lightKind: kind, lightColor: [r, g, b], intensity, groundColor: [groundR, groundG, groundB], distance, decay })
334
+ }
335
+
336
+ export function nodeLightTarget(node: number, x: number, y: number, z: number): void {
337
+ const slot = nodes[node]
338
+ if (slot) slot.target = [x, y, z]
339
+ }
340
+
341
+ export function cameraProjection(node: number, elements: Float32Array, near: number, far: number): void {
342
+ const slot = nodes[node]
343
+ if (!slot) return
344
+ slot.projection.set(elements.subarray(0, 16))
345
+ slot.near = near
346
+ slot.far = far
347
+ }
348
+
349
+ export function sceneEnvironment(
350
+ scene: number,
351
+ background: number,
352
+ top: number,
353
+ bottom: number,
354
+ fog: number,
355
+ fogColor: number,
356
+ fogNear: number,
357
+ fogFar: number,
358
+ fogDensity: number,
359
+ ): void {
360
+ const slot = nodes[scene]
361
+ if (slot) Object.assign(slot, { background, backgroundTop: top, backgroundBottom: bottom, fog, fogColor, fogNear, fogFar, fogDensity })
362
+ }
363
+
364
+ // ---- frame
365
+
366
+ export function renderOptions(depthBuffer: number, capacity: number): void {
367
+ // Painter's order only in the browser.
368
+ }
369
+
370
+ export function renderTarget(surface: number): void {
371
+ // Always the page canvas in the browser.
372
+ }
373
+
374
+ export function createSurface(width: number, height: number): number {
375
+ return -1
376
+ }
377
+
378
+ export function stat(which: number): number {
379
+ return stats[which] ?? 0
380
+ }
381
+
382
+ export function drawScene(scene: number, camera: number, width: number, height: number): number {
383
+ const sceneNode = nodes[scene]
384
+ const cameraNode = nodes[camera]
385
+ if (!sceneNode || !cameraNode) return 0
386
+
387
+ stats.fill(0)
388
+ updateWorld(scene, null)
389
+ worldOf(camera)
390
+ const view = invertAffine(cameraNode.world)
391
+ const frame = new FrameBuilder(sceneNode, cameraNode, view, width, height)
392
+ frame.collect(scene)
393
+ frame.paint(ensureCanvas(width, height))
394
+ stats[7] = frame.shapes.length
395
+ return frame.shapes.length
396
+ }
397
+
398
+ // ---- raycast
399
+
400
+ export function raycast(
401
+ node: number,
402
+ ox: number, oy: number, oz: number,
403
+ dx: number, dy: number, dz: number,
404
+ near: number,
405
+ far: number,
406
+ ): number {
407
+ const slot = nodes[node]
408
+ const geometry = slot ? geometries[slot.geometry] : null
409
+ const positions = geometry ? buffers[geometry.position] : null
410
+ const material = slot ? materials[slot.material] : null
411
+ if (!slot || slot.kind !== NODE_MESH || !geometry || !positions || !material) return 0
412
+
413
+ const length = Math.hypot(dx, dy, dz)
414
+ if (length === 0) return 0
415
+ const direction = [dx / length, dy / length, dz / length]
416
+ const world = worldOf(node)
417
+ const indexBuffer = buffers[geometry.index]
418
+ const indices = indexBuffer && indexBuffer.u32.length > 0 ? indexBuffer.u32 : null
419
+ const p = positions.f32
420
+ const triangles = Math.floor((indices ? indices.length : p.length / 3) / 3)
421
+ const instances = slot.instanced ? buffers[slot.instanceMatrices] : null
422
+ const instanceCount = slot.instanced ? (instances ? Math.min(slot.instanceCount, Math.floor(instances.f32.length / 16)) : 0) : 1
423
+ let best = far
424
+ let hit = false
425
+ for (let instance = 0; instance < instanceCount; instance++) {
426
+ const m = instances ? multiply(world, instances.f32.subarray(instance * 16, instance * 16 + 16)) : world
427
+ const inverse = invertAffine(m)
428
+ const o = transformPoint(inverse, ox, oy, oz)
429
+ const d = transformDirection(inverse, direction[0], direction[1], direction[2])
430
+ for (let t = 0; t < triangles; t++) {
431
+ const a = (indices ? indices[t * 3] : t * 3) * 3
432
+ const b = (indices ? indices[t * 3 + 1] : t * 3 + 1) * 3
433
+ const c = (indices ? indices[t * 3 + 2] : t * 3 + 2) * 3
434
+ const e1 = [p[b] - p[a], p[b + 1] - p[a + 1], p[b + 2] - p[a + 2]]
435
+ const e2 = [p[c] - p[a], p[c + 1] - p[a + 1], p[c + 2] - p[a + 2]]
436
+ const h = cross(d, e2)
437
+ const det = dot(e1, h)
438
+ if (Math.abs(det) < 1e-9) continue
439
+ if ((material.side === 0 && det < 0) || (material.side === 1 && det > 0)) continue
440
+ const s = [o[0] - p[a], o[1] - p[a + 1], o[2] - p[a + 2]]
441
+ const u = dot(s, h) / det
442
+ if (u < 0 || u > 1) continue
443
+ const q = cross(s, e1)
444
+ const v = dot(d, q) / det
445
+ if (v < 0 || u + v > 1) continue
446
+ const distance = dot(e2, q) / det
447
+ if (distance < near || distance >= best) continue
448
+ best = distance
449
+ hit = true
450
+ rayHit.splice(0, 6, distance, ox + direction[0] * distance, oy + direction[1] * distance, oz + direction[2] * distance, t, instances ? instance : -1)
451
+ }
452
+ }
453
+ return hit ? 1 : 0
454
+ }
455
+
456
+ export function rayResult(which: number): number {
457
+ return rayHit[which] ?? 0
458
+ }
459
+
460
+ // ---- scene graph math
461
+
462
+ function compose(node: WebNode): Matrix {
463
+ const [x, y, z, w] = node.quaternion
464
+ const [sx, sy, sz] = node.scale
465
+ const m = new Float32Array(16)
466
+ m[0] = (1 - 2 * (y * y + z * z)) * sx
467
+ m[1] = 2 * (x * y + w * z) * sx
468
+ m[2] = 2 * (x * z - w * y) * sx
469
+ m[4] = 2 * (x * y - w * z) * sy
470
+ m[5] = (1 - 2 * (x * x + z * z)) * sy
471
+ m[6] = 2 * (y * z + w * x) * sy
472
+ m[8] = 2 * (x * z + w * y) * sz
473
+ m[9] = 2 * (y * z - w * x) * sz
474
+ m[10] = (1 - 2 * (x * x + y * y)) * sz
475
+ m[12] = node.position[0]
476
+ m[13] = node.position[1]
477
+ m[14] = node.position[2]
478
+ m[15] = 1
479
+ return m
480
+ }
481
+
482
+ function localOf(node: WebNode): Matrix {
483
+ return node.useMatrix ? node.local : compose(node)
484
+ }
485
+
486
+ function updateWorld(id: number, parentWorld: Matrix | null): void {
487
+ const node = nodes[id]
488
+ if (!node) return
489
+ node.world = parentWorld ? multiply(parentWorld, localOf(node)) : localOf(node)
490
+ for (const child of node.children) updateWorld(child, node.world)
491
+ }
492
+
493
+ function worldOf(id: number): Matrix {
494
+ const node = nodes[id]
495
+ if (!node) return identity()
496
+ node.world = node.parent >= 0 ? multiply(worldOf(node.parent), localOf(node)) : localOf(node)
497
+ return node.world
498
+ }
499
+
500
+ function multiply(a: Float32Array, b: Float32Array): Matrix {
501
+ const out = new Float32Array(16)
502
+ for (let col = 0; col < 4; col++) {
503
+ for (let row = 0; row < 4; row++) {
504
+ out[col * 4 + row] = a[row] * b[col * 4] + a[4 + row] * b[col * 4 + 1] + a[8 + row] * b[col * 4 + 2] + a[12 + row] * b[col * 4 + 3]
505
+ }
506
+ }
507
+ return out
508
+ }
509
+
510
+ function invertAffine(m: Float32Array): Matrix {
511
+ const [a00, a10, a20] = [m[0], m[1], m[2]]
512
+ const [a01, a11, a21] = [m[4], m[5], m[6]]
513
+ const [a02, a12, a22] = [m[8], m[9], m[10]]
514
+ const c00 = a11 * a22 - a12 * a21
515
+ const c01 = a12 * a20 - a10 * a22
516
+ const c02 = a10 * a21 - a11 * a20
517
+ const det = a00 * c00 + a01 * c01 + a02 * c02
518
+ const out = identity()
519
+ if (det === 0) return out
520
+ const inv = 1 / det
521
+ out[0] = c00 * inv
522
+ out[1] = c01 * inv
523
+ out[2] = c02 * inv
524
+ out[4] = (a02 * a21 - a01 * a22) * inv
525
+ out[5] = (a00 * a22 - a02 * a20) * inv
526
+ out[6] = (a01 * a20 - a00 * a21) * inv
527
+ out[8] = (a01 * a12 - a02 * a11) * inv
528
+ out[9] = (a02 * a10 - a00 * a12) * inv
529
+ out[10] = (a00 * a11 - a01 * a10) * inv
530
+ const [tx, ty, tz] = [m[12], m[13], m[14]]
531
+ out[12] = -(out[0] * tx + out[4] * ty + out[8] * tz)
532
+ out[13] = -(out[1] * tx + out[5] * ty + out[9] * tz)
533
+ out[14] = -(out[2] * tx + out[6] * ty + out[10] * tz)
534
+ return out
535
+ }
536
+
537
+ function transformPoint(m: Float32Array, x: number, y: number, z: number): number[] {
538
+ return [m[0] * x + m[4] * y + m[8] * z + m[12], m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14]]
539
+ }
540
+
541
+ function transformDirection(m: Float32Array, x: number, y: number, z: number): number[] {
542
+ return [m[0] * x + m[4] * y + m[8] * z, m[1] * x + m[5] * y + m[9] * z, m[2] * x + m[6] * y + m[10] * z]
543
+ }
544
+
545
+ function cross(a: number[], b: number[]): number[] {
546
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
547
+ }
548
+
549
+ function dot(a: number[], b: number[]): number {
550
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
551
+ }
552
+
553
+ function normalize(v: number[]): number[] {
554
+ const length = Math.hypot(v[0], v[1], v[2])
555
+ return length > 0 ? [v[0] / length, v[1] / length, v[2] / length] : v
556
+ }
557
+
558
+ function hexChannels(hex: number): number[] {
559
+ return [((hex >> 16) & 255) / 255, ((hex >> 8) & 255) / 255, (hex & 255) / 255]
560
+ }
561
+
562
+ function cssColor(rgb: number[]): string {
563
+ const channel = (value: number) => Math.max(0, Math.min(255, Math.floor(value * 255)))
564
+ return `rgb(${channel(rgb[0])},${channel(rgb[1])},${channel(rgb[2])})`
565
+ }
566
+
567
+ // ---- frame building
568
+
569
+ class FrameBuilder {
570
+ readonly shapes: Shape[] = []
571
+ private readonly lights: Lights = {
572
+ ambient: [0, 0, 0],
573
+ directions: [],
574
+ directionalColors: [],
575
+ points: [],
576
+ pointColors: [],
577
+ pointRanges: [],
578
+ hemisphereUps: [],
579
+ skies: [],
580
+ grounds: [],
581
+ }
582
+ private readonly planes: number[][]
583
+ private readonly near: number
584
+ private readonly orthographic: boolean
585
+ // renderOrder of the node being drawn.
586
+ private layer = 0
587
+
588
+ constructor(
589
+ private readonly scene: WebNode,
590
+ private readonly camera: WebNode,
591
+ private readonly view: Matrix,
592
+ private readonly width: number,
593
+ private readonly height: number,
594
+ ) {
595
+ this.near = Math.max(camera.near, 0.0001)
596
+ const p = camera.projection
597
+ this.orthographic = p[15] === 1 && p[11] === 0
598
+ const rows = [0, 1, 2, 3].map((r) => [p[r], p[4 + r], p[8 + r], p[12 + r]])
599
+ this.planes = []
600
+ for (let i = 0; i < 3; i++) {
601
+ for (const sign of [1, -1]) {
602
+ const plane = rows[3].map((value, k) => value + sign * rows[i][k])
603
+ const length = Math.hypot(plane[0], plane[1], plane[2]) || 1
604
+ this.planes.push(plane.map((value) => value / length))
605
+ }
606
+ }
607
+ }
608
+
609
+ collect(root: number): void {
610
+ const drawables: WebNode[] = []
611
+ const visit = (id: number) => {
612
+ const node = nodes[id]
613
+ if (!node || !node.visible) return
614
+ if (node.kind === NODE_LIGHT) this.addLight(node)
615
+ else if (node.kind !== NODE_GROUP && node.kind !== NODE_CAMERA) drawables.push(node)
616
+ for (const child of node.children) visit(child)
617
+ }
618
+ visit(root)
619
+ for (const node of drawables) this.draw(node)
620
+ }
621
+
622
+ paint(target: HTMLCanvasElement): void {
623
+ const ctx = target.getContext('2d')
624
+ if (!ctx) return
625
+ ctx.clearRect(0, 0, this.width, this.height)
626
+ const scene = this.scene
627
+ if (scene.background !== BACKGROUND_NONE) {
628
+ const top = cssColor(hexChannels(scene.backgroundTop))
629
+ if (scene.background === BACKGROUND_GRADIENT) {
630
+ const gradient = ctx.createLinearGradient(0, 0, 0, this.height)
631
+ gradient.addColorStop(0, top)
632
+ gradient.addColorStop(1, cssColor(hexChannels(scene.backgroundBottom)))
633
+ ctx.fillStyle = gradient
634
+ } else {
635
+ ctx.fillStyle = top
636
+ }
637
+ ctx.fillRect(0, 0, this.width, this.height)
638
+ }
639
+
640
+ this.sortBackToFront()
641
+ ctx.lineJoin = 'round'
642
+ for (const shape of this.shapes) {
643
+ ctx.globalAlpha = shape.alpha
644
+ ctx.globalCompositeOperation = shape.additive ? 'lighter' : 'source-over'
645
+ ctx.beginPath()
646
+ ctx.moveTo(shape.xs[0], shape.ys[0])
647
+ for (let i = 1; i < shape.xs.length; i++) ctx.lineTo(shape.xs[i], shape.ys[i])
648
+ ctx.strokeStyle = shape.color
649
+ ctx.lineWidth = shape.width
650
+ if (shape.line) {
651
+ ctx.stroke()
652
+ continue
653
+ }
654
+ ctx.closePath()
655
+ ctx.fillStyle = shape.color
656
+ ctx.fill()
657
+ // Hairline seams between antialiased neighbours disappear under a
658
+ // stroke of the face's own colour.
659
+ if (shape.alpha >= 1) ctx.stroke()
660
+ }
661
+ ctx.globalAlpha = 1
662
+ ctx.globalCompositeOperation = 'source-over'
663
+ }
664
+
665
+ // Painter's order in the native engine's 1024 depth buckets, quantized
666
+ // from the farthest primitive, so both engines resolve ties alike.
667
+ private sortBackToFront(): void {
668
+ let lo = Infinity
669
+ let hi = -Infinity
670
+ for (const shape of this.shapes) {
671
+ lo = Math.min(lo, shape.depth)
672
+ hi = Math.max(hi, shape.depth)
673
+ }
674
+ const scale = hi - lo > 1e-6 ? 1023 / (hi - lo) : 0
675
+ const bucket = (shape: Shape) => Math.min(1023, Math.floor((hi - shape.depth) * scale))
676
+ this.shapes.sort((a, b) => a.layer - b.layer || bucket(a) - bucket(b))
677
+ }
678
+
679
+ private addLight(node: WebNode): void {
680
+ const lights = this.lights
681
+ const color = node.lightColor.map((value) => value * node.intensity)
682
+ const w = node.world
683
+ if (node.lightKind === LIGHT_AMBIENT) {
684
+ for (let k = 0; k < 3; k++) lights.ambient[k] += color[k]
685
+ } else if (node.lightKind === LIGHT_DIRECTIONAL) {
686
+ lights.directions.push(normalize(transformDirection(this.view, w[12] - node.target[0], w[13] - node.target[1], w[14] - node.target[2])))
687
+ lights.directionalColors.push(color)
688
+ } else if (node.lightKind === LIGHT_POINT) {
689
+ lights.points.push(transformPoint(this.view, w[12], w[13], w[14]))
690
+ lights.pointColors.push(color)
691
+ lights.pointRanges.push([node.distance, node.decay])
692
+ } else if (node.lightKind === LIGHT_HEMISPHERE) {
693
+ lights.hemisphereUps.push(normalize(transformDirection(this.view, w[12], w[13], w[14])))
694
+ lights.skies.push(color)
695
+ lights.grounds.push(node.groundColor.map((value) => value * node.intensity))
696
+ }
697
+ }
698
+
699
+ private light(n: number[], p: number[]): number[] {
700
+ const l = this.lights
701
+ const out = [...l.ambient]
702
+ l.directions.forEach((d, i) => {
703
+ const amount = Math.max(0, dot(n, d))
704
+ for (let k = 0; k < 3; k++) out[k] += amount * l.directionalColors[i][k]
705
+ })
706
+ l.hemisphereUps.forEach((up, i) => {
707
+ const t = dot(n, up) * 0.5 + 0.5
708
+ for (let k = 0; k < 3; k++) out[k] += l.grounds[i][k] + (l.skies[i][k] - l.grounds[i][k]) * t
709
+ })
710
+ l.points.forEach((position, i) => {
711
+ const toLight = [position[0] - p[0], position[1] - p[1], position[2] - p[2]]
712
+ const distance = Math.hypot(toLight[0], toLight[1], toLight[2])
713
+ if (distance === 0) return
714
+ const amount = Math.max(0, dot(n, toLight) / distance)
715
+ const [range, decay] = l.pointRanges[i]
716
+ let falloff = decay > 0 ? 1 / Math.max(Math.pow(distance, decay), 0.01) : 1
717
+ if (range > 0) falloff *= Math.pow(Math.max(0, Math.min(1, 1 - Math.pow(distance / range, 4))), 2)
718
+ for (let k = 0; k < 3; k++) out[k] += amount * falloff * l.pointColors[i][k]
719
+ })
720
+ return out
721
+ }
722
+
723
+ private fogged(rgb: number[], distance: number, material: WebMaterial): number[] {
724
+ const scene = this.scene
725
+ if (!(material.flags & MATERIAL_FOG) || scene.fog === 0) return rgb
726
+ let visibility = 1
727
+ if (scene.fog === FOG_LINEAR && scene.fogFar > scene.fogNear) visibility = (scene.fogFar - distance) / (scene.fogFar - scene.fogNear)
728
+ else if (scene.fog === FOG_EXP2) visibility = Math.exp(-Math.pow(scene.fogDensity * distance, 2))
729
+ visibility = Math.max(0, Math.min(1, visibility))
730
+ const fog = hexChannels(scene.fogColor)
731
+ return rgb.map((value, k) => fog[k] + (value - fog[k]) * visibility)
732
+ }
733
+
734
+ private project(v: number[]): number[] {
735
+ const p = this.camera.projection
736
+ const x = p[0] * v[0] + p[4] * v[1] + p[8] * v[2] + p[12]
737
+ const y = p[1] * v[0] + p[5] * v[1] + p[9] * v[2] + p[13]
738
+ const w = p[3] * v[0] + p[7] * v[1] + p[11] * v[2] + p[15] || 1e-6
739
+ return [(x / w + 1) * this.width * 0.5, (1 - y / w) * this.height * 0.5]
740
+ }
741
+
742
+ private visible(center: number[], radius: number): boolean {
743
+ return this.planes.every((plane) => plane[0] * center[0] + plane[1] * center[1] + plane[2] * center[2] + plane[3] >= -radius)
744
+ }
745
+
746
+ private draw(node: WebNode): void {
747
+ const material = materials[node.material]
748
+ if (!material || !(material.flags & MATERIAL_VISIBLE)) return
749
+
750
+ this.layer = node.renderOrder
751
+ const modelView = multiply(this.view, node.world)
752
+ if (node.kind === NODE_SPRITE) {
753
+ this.drawSprite(modelView, material)
754
+ return
755
+ }
756
+ const geometry = geometries[node.geometry]
757
+ const positions = geometry ? buffers[geometry.position] : null
758
+ if (!geometry || !positions) return
759
+
760
+ const instances = node.instanced ? buffers[node.instanceMatrices] : null
761
+ const tints = instances ? buffers[node.instanceColors] : null
762
+ const count = node.instanced ? (instances ? Math.min(node.instanceCount, Math.floor(instances.f32.length / 16)) : 0) : 1
763
+ for (let i = 0; i < count; i++) {
764
+ const mv = instances ? multiply(modelView, instances.f32.subarray(i * 16, i * 16 + 16)) : modelView
765
+ const tint = tints && tints.f32.length >= (i + 1) * 3 ? Array.from(tints.f32.subarray(i * 3, i * 3 + 3)) : [1, 1, 1]
766
+ if (node.frustumCulled && !this.boundsVisible(positions.f32, mv)) {
767
+ stats[6]++
768
+ continue
769
+ }
770
+ stats[5]++
771
+ this.drawGeometry(node.kind, geometry, positions.f32, material, mv, tint)
772
+ }
773
+ }
774
+
775
+ private boundsVisible(p: Float32Array, mv: Matrix): boolean {
776
+ let lo = [Infinity, Infinity, Infinity]
777
+ let hi = [-Infinity, -Infinity, -Infinity]
778
+ for (let i = 0; i < p.length; i += 3) {
779
+ lo = [Math.min(lo[0], p[i]), Math.min(lo[1], p[i + 1]), Math.min(lo[2], p[i + 2])]
780
+ hi = [Math.max(hi[0], p[i]), Math.max(hi[1], p[i + 1]), Math.max(hi[2], p[i + 2])]
781
+ }
782
+ const center = [(lo[0] + hi[0]) / 2, (lo[1] + hi[1]) / 2, (lo[2] + hi[2]) / 2]
783
+ const radius = Math.hypot(hi[0] - center[0], hi[1] - center[1], hi[2] - center[2])
784
+ const scale = Math.sqrt(Math.max(mv[0] ** 2 + mv[1] ** 2 + mv[2] ** 2, mv[4] ** 2 + mv[5] ** 2 + mv[6] ** 2, mv[8] ** 2 + mv[9] ** 2 + mv[10] ** 2))
785
+ return this.visible(transformPoint(mv, center[0], center[1], center[2]), radius * scale)
786
+ }
787
+
788
+ private drawGeometry(kind: number, geometry: WebGeometry, p: Float32Array, material: WebMaterial, mv: Matrix, tint: number[]): void {
789
+ const vertexCount = Math.floor(p.length / 3)
790
+ const view: number[][] = []
791
+ for (let i = 0; i < vertexCount; i++) view.push(transformPoint(mv, p[i * 3], p[i * 3 + 1], p[i * 3 + 2]))
792
+ const colorBuffer = material.flags & MATERIAL_VERTEX_COLORS ? buffers[geometry.color] : null
793
+ const colors = colorBuffer && colorBuffer.f32.length >= vertexCount * 3 ? colorBuffer.f32 : null
794
+ const base = (i: number) => material.color.map((value, k) => value * tint[k] * (colors ? colors[i * 3 + k] : 1))
795
+ const indexBuffer = buffers[geometry.index]
796
+ const indices = indexBuffer && indexBuffer.u32.length > 0 ? indexBuffer.u32 : null
797
+ const at = (i: number) => (indices ? indices[i] : i)
798
+ const count = indices ? indices.length : vertexCount
799
+
800
+ if (kind === NODE_POINTS) {
801
+ for (let i = 0; i < vertexCount; i++) this.drawPoint(view[i], base(i), material)
802
+ return
803
+ }
804
+ if (kind === NODE_LINE || kind === NODE_LINE_SEGMENTS) {
805
+ const step = kind === NODE_LINE ? 1 : 2
806
+ for (let i = 0; i + 1 < count; i += step) this.drawLine(view[at(i)], view[at(i + 1)], base(at(i)), material)
807
+ return
808
+ }
809
+ stats[0] += Math.floor(count / 3)
810
+ for (let t = 0; t + 2 < count; t += 3) {
811
+ const ids = [at(t), at(t + 1), at(t + 2)]
812
+ const corners = ids.map((id) => view[id])
813
+ if (material.flags & MATERIAL_WIREFRAME) {
814
+ for (let k = 0; k < 3; k++) this.drawLine(corners[k], corners[(k + 1) % 3], base(ids[k]), material)
815
+ continue
816
+ }
817
+ this.drawTriangle(corners, ids.map(base), material)
818
+ }
819
+ }
820
+
821
+ private drawTriangle(corners: number[][], colors: number[][], material: WebMaterial): void {
822
+ const nearZ = -this.near
823
+ if (corners.every((c) => c[2] > nearZ)) {
824
+ stats[1]++
825
+ return
826
+ }
827
+ let n = cross(
828
+ [corners[1][0] - corners[0][0], corners[1][1] - corners[0][1], corners[1][2] - corners[0][2]],
829
+ [corners[2][0] - corners[0][0], corners[2][1] - corners[0][1], corners[2][2] - corners[0][2]],
830
+ )
831
+ const facing = this.orthographic ? -n[2] : dot(n, corners[0])
832
+ const back = facing >= 0
833
+ if ((material.side === 0 && back) || (material.side === 1 && !back)) {
834
+ stats[2]++
835
+ return
836
+ }
837
+ if (back) n = n.map((value) => -value)
838
+ n = normalize(n)
839
+
840
+ const centroid = [0, 1, 2].map((k) => (corners[0][k] + corners[1][k] + corners[2][k]) / 3)
841
+ const average = [0, 1, 2].map((k) => (colors[0][k] + colors[1][k] + colors[2][k]) / 3)
842
+ let rgb = average
843
+ if (material.shade === 1) rgb = average.map((value, k) => value * this.light(n, centroid)[k])
844
+ else if (material.shade === 2) rgb = [n[0] * 0.5 + 0.5, n[1] * 0.5 + 0.5, n[2] * 0.5 + 0.5]
845
+ rgb = this.fogged(rgb, -centroid[2], material)
846
+
847
+ const polygon = this.clip(corners)
848
+ if (polygon.length < 3) {
849
+ stats[3]++
850
+ return
851
+ }
852
+ const screen = polygon.map((c) => this.project(c))
853
+ this.shapes.push({
854
+ depth: Math.max(...polygon.map((c) => -c[2])),
855
+ xs: screen.map((s) => s[0]),
856
+ ys: screen.map((s) => s[1]),
857
+ color: cssColor(rgb),
858
+ alpha: this.alpha(material),
859
+ additive: (material.flags & MATERIAL_ADDITIVE) !== 0,
860
+ layer: this.layer,
861
+ line: false,
862
+ width: 1,
863
+ })
864
+ }
865
+
866
+ // Near-plane clip in view space.
867
+ private clip(corners: number[][]): number[][] {
868
+ const nearZ = -this.near
869
+ const out: number[][] = []
870
+ for (let e = 0; e < corners.length; e++) {
871
+ const a = corners[e]
872
+ const b = corners[(e + 1) % corners.length]
873
+ const aIn = a[2] <= nearZ
874
+ const bIn = b[2] <= nearZ
875
+ if (aIn) out.push(a)
876
+ if (aIn !== bIn) {
877
+ const t = (nearZ - a[2]) / (b[2] - a[2])
878
+ out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, nearZ])
879
+ }
880
+ }
881
+ return out
882
+ }
883
+
884
+ private drawLine(a: number[], b: number[], rgb: number[], material: WebMaterial): void {
885
+ const segment = this.clip([a, b, b]).slice(0, 2)
886
+ if (segment.length < 2) return
887
+ const screen = segment.map((c) => this.project(c))
888
+ this.shapes.push({
889
+ depth: Math.max(-segment[0][2], -segment[1][2]),
890
+ xs: screen.map((s) => s[0]),
891
+ ys: screen.map((s) => s[1]),
892
+ color: cssColor(this.fogged(rgb, -(a[2] + b[2]) / 2, material)),
893
+ alpha: this.alpha(material),
894
+ additive: (material.flags & MATERIAL_ADDITIVE) !== 0,
895
+ layer: this.layer,
896
+ line: true,
897
+ width: Math.min(3, Math.max(1, Math.round(material.size))),
898
+ })
899
+ }
900
+
901
+ private drawPoint(p: number[], rgb: number[], material: WebMaterial): void {
902
+ if (p[2] > -this.near) return
903
+ const attenuate = material.flags & MATERIAL_SIZE_ATTENUATION && !this.orthographic
904
+ const size = Math.max(1, attenuate ? (material.size * this.height * 0.5) / -p[2] : material.size)
905
+ const [x, y] = this.project(p)
906
+ const half = size / 2
907
+ this.shapes.push({
908
+ depth: -p[2],
909
+ xs: [x - half, x + half, x + half, x - half],
910
+ ys: [y - half, y - half, y + half, y + half],
911
+ color: cssColor(this.fogged(rgb, -p[2], material)),
912
+ alpha: this.alpha(material),
913
+ additive: (material.flags & MATERIAL_ADDITIVE) !== 0,
914
+ layer: this.layer,
915
+ line: false,
916
+ width: 1,
917
+ })
918
+ }
919
+
920
+ private drawSprite(mv: Matrix, material: WebMaterial): void {
921
+ const center = transformPoint(mv, 0, 0, 0)
922
+ const halfX = Math.hypot(mv[0], mv[1], mv[2]) / 2
923
+ const halfY = Math.hypot(mv[4], mv[5], mv[6]) / 2
924
+ if (center[2] > -this.near || !this.visible(center, Math.max(halfX, halfY) * 2)) return
925
+ const corners = [
926
+ [center[0] - halfX, center[1] + halfY, center[2]],
927
+ [center[0] + halfX, center[1] + halfY, center[2]],
928
+ [center[0] + halfX, center[1] - halfY, center[2]],
929
+ [center[0] - halfX, center[1] - halfY, center[2]],
930
+ ].map((c) => this.project(c))
931
+ this.shapes.push({
932
+ depth: -center[2],
933
+ xs: corners.map((c) => c[0]),
934
+ ys: corners.map((c) => c[1]),
935
+ color: cssColor(this.fogged(material.color, -center[2], material)),
936
+ alpha: this.alpha(material),
937
+ additive: (material.flags & MATERIAL_ADDITIVE) !== 0,
938
+ layer: this.layer,
939
+ line: false,
940
+ width: 1,
941
+ })
942
+ }
943
+
944
+ private alpha(material: WebMaterial): number {
945
+ return material.flags & MATERIAL_TRANSPARENT ? Math.max(0, Math.min(1, material.opacity)) : 1
946
+ }
947
+ }
948
+
949
+ // The frame canvas: fixed behind the app's DOM, one CSS pixel per pixel.
950
+ function ensureCanvas(width: number, height: number): HTMLCanvasElement {
951
+ if (!canvas) {
952
+ canvas = document.createElement('canvas')
953
+ canvas.style.position = 'fixed'
954
+ canvas.style.left = '0'
955
+ canvas.style.top = '0'
956
+ canvas.style.zIndex = '-1'
957
+ canvas.style.pointerEvents = 'none'
958
+ document.body.prepend(canvas)
959
+ document.body.style.background = 'transparent'
960
+ }
961
+ if (canvas.width !== width || canvas.height !== height) {
962
+ canvas.width = width
963
+ canvas.height = height
964
+ canvas.style.width = `${width}px`
965
+ canvas.style.height = `${height}px`
966
+ }
967
+ return canvas
968
+ }