castle-web-cli 0.4.203 → 0.4.205

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.
Files changed (133) hide show
  1. package/dist/agent-failures.d.ts +3 -1
  2. package/dist/agent-failures.js +19 -0
  3. package/dist/agent-prompts.d.ts +1 -0
  4. package/dist/agent-prompts.js +20 -8
  5. package/dist/agent.d.ts +5 -2
  6. package/dist/agent.js +59 -125
  7. package/dist/castle-host/host.d.ts +17 -0
  8. package/dist/castle-host/host.js +551 -4
  9. package/dist/castleJson.d.ts +1 -0
  10. package/dist/devSessionStorage.js +65 -4
  11. package/dist/effortSupport.d.ts +7 -0
  12. package/dist/effortSupport.js +31 -0
  13. package/dist/init.js +13 -3
  14. package/dist/platformDoc.js +6 -1
  15. package/dist/routerFences.d.ts +22 -0
  16. package/dist/routerFences.js +139 -0
  17. package/dist/serve.js +35 -2
  18. package/dist/shell/assets/index-b_bebkRb.css +1 -0
  19. package/dist/shell/assets/{index-CxrtbzHf.js → index-hWQTC8q6.js} +5 -5
  20. package/dist/shell/index.html +2 -2
  21. package/dist/taskAccount.d.ts +13 -0
  22. package/dist/taskAccount.js +38 -0
  23. package/dist/vitePlugins.js +19 -1
  24. package/kits/base/CLAUDE.md +2 -0
  25. package/kits/base/castle.json +1 -1
  26. package/kits/base/sdk/README.md +131 -0
  27. package/kits/base/sdk/agent.d.ts +6 -0
  28. package/kits/base/sdk/agent.js +70 -0
  29. package/kits/base/sdk/castle.d.ts +4 -0
  30. package/kits/base/sdk/castle.js +2 -0
  31. package/kits/base/sdk/commands.d.ts +106 -0
  32. package/kits/base/sdk/commands.js +21 -0
  33. package/kits/base/sdk/decks.d.ts +7 -0
  34. package/kits/base/sdk/decks.js +31 -0
  35. package/kits/base/sdk/runtime.d.ts +4 -2
  36. package/kits/base/sdk/runtime.js +51 -40
  37. package/kits/base/sdk/server/storage.d.ts +44 -0
  38. package/kits/base/sdk/server/storage.js +54 -0
  39. package/kits/base/sdk/transport.d.ts +5 -1
  40. package/kits/base/sdk/transport.js +106 -23
  41. package/kits/multiplayer-2d/castle.json +4 -4
  42. package/kits/multiplayer-2d/code/client/poses.js +7 -0
  43. package/kits/multiplayer-2d/code/server/limits.js +3 -0
  44. package/kits/multiplayer-2d/code/server/ownership.js +36 -8
  45. package/kits/multiplayer-2d/code/systems/multiplayer.js +23 -2
  46. package/kits/multiplayer-3d/CLAUDE.md +12 -1
  47. package/kits/multiplayer-3d/castle.json +4 -4
  48. package/kits/multiplayer-3d/code/client/avatars.js +7 -1
  49. package/kits/multiplayer-3d/code/client/poses.js +61 -1
  50. package/kits/multiplayer-3d/code/client/steer.js +383 -0
  51. package/kits/multiplayer-3d/code/server/limits.js +3 -0
  52. package/kits/multiplayer-3d/code/server/ownership.js +114 -18
  53. package/kits/multiplayer-3d/code/server/world.js +12 -4
  54. package/kits/multiplayer-3d/code/systems/multiplayer.js +315 -34
  55. package/kits/physics-3d/CLAUDE.md +65 -7
  56. package/kits/physics-3d/castle.json +3 -3
  57. package/kits/physics-3d/docs/pxmodel-format.md +916 -15
  58. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  59. package/kits/physics-3d/engine3d/artobjects.js +218 -0
  60. package/kits/physics-3d/engine3d/blob.js +1058 -0
  61. package/kits/physics-3d/engine3d/branches.js +300 -0
  62. package/kits/physics-3d/engine3d/cage.js +496 -0
  63. package/kits/physics-3d/engine3d/cageops.js +516 -0
  64. package/kits/physics-3d/engine3d/frame.js +669 -0
  65. package/kits/physics-3d/engine3d/look.js +675 -0
  66. package/kits/physics-3d/engine3d/materialpresets.js +486 -0
  67. package/kits/physics-3d/engine3d/modelEditorWorld.js +3 -2
  68. package/kits/physics-3d/engine3d/modelrefs.js +120 -0
  69. package/kits/physics-3d/engine3d/motion.js +560 -0
  70. package/kits/physics-3d/engine3d/objtext.js +37 -0
  71. package/kits/physics-3d/engine3d/optimize.js +1083 -0
  72. package/kits/physics-3d/engine3d/paint.js +674 -0
  73. package/kits/physics-3d/engine3d/partgeometry.js +467 -0
  74. package/kits/physics-3d/engine3d/paths.js +324 -0
  75. package/kits/physics-3d/engine3d/pxmodel.js +429 -26
  76. package/kits/physics-3d/engine3d/scatter.js +102 -0
  77. package/kits/physics-3d/engine3d/sculpt.js +1148 -0
  78. package/kits/physics-3d/engine3d/surfacedetail.js +267 -0
  79. package/kits/physics-3d/engine3d/sweep.js +480 -0
  80. package/kits/physics-3d/engine3d/thumbnails.js +6 -4
  81. package/kits/physics-3d/engine3d/world3d.js +119 -17
  82. package/kits/physics-3d/eslint.config.js +13 -0
  83. package/kits/physics-3d/models/parts/axe.pxmodel +40 -0
  84. package/kits/physics-3d/models/parts/backpack.pxmodel +47 -0
  85. package/kits/physics-3d/models/parts/barrel.pxmodel +22 -0
  86. package/kits/physics-3d/models/parts/bedroll.pxmodel +28 -0
  87. package/kits/physics-3d/models/parts/belt-pouch.pxmodel +22 -0
  88. package/kits/physics-3d/models/parts/bolt.pxmodel +10 -0
  89. package/kits/physics-3d/models/parts/bracer.pxmodel +26 -0
  90. package/kits/physics-3d/models/parts/chain-span.pxmodel +12 -0
  91. package/kits/physics-3d/models/parts/chimney.pxmodel +11 -0
  92. package/kits/physics-3d/models/parts/crate.pxmodel +44 -0
  93. package/kits/physics-3d/models/parts/crystal.pxmodel +22 -0
  94. package/kits/physics-3d/models/parts/door-arched.pxmodel +12 -0
  95. package/kits/physics-3d/models/parts/engine-block.pxmodel +39 -0
  96. package/kits/physics-3d/models/parts/exhaust-pipe.pxmodel +30 -0
  97. package/kits/physics-3d/models/parts/fence-span.pxmodel +10 -0
  98. package/kits/physics-3d/models/parts/fender.pxmodel +19 -0
  99. package/kits/physics-3d/models/parts/headlight.pxmodel +24 -0
  100. package/kits/physics-3d/models/parts/hood.pxmodel +17 -0
  101. package/kits/physics-3d/models/parts/horned-helmet.pxmodel +37 -0
  102. package/kits/physics-3d/models/parts/jerry-can.pxmodel +26 -0
  103. package/kits/physics-3d/models/parts/ladder.pxmodel +10 -0
  104. package/kits/physics-3d/models/parts/lamp.pxmodel +20 -0
  105. package/kits/physics-3d/models/parts/lantern.pxmodel +30 -0
  106. package/kits/physics-3d/models/parts/leaf-cluster.pxmodel +21 -0
  107. package/kits/physics-3d/models/parts/offroad-tire.pxmodel +48 -0
  108. package/kits/physics-3d/models/parts/pauldron.pxmodel +26 -0
  109. package/kits/physics-3d/models/parts/rivet.pxmodel +8 -0
  110. package/kits/physics-3d/models/parts/rock.pxmodel +21 -0
  111. package/kits/physics-3d/models/parts/roll-bar-light.pxmodel +26 -0
  112. package/kits/physics-3d/models/parts/round-shield.pxmodel +31 -0
  113. package/kits/physics-3d/models/parts/saddlebag.pxmodel +30 -0
  114. package/kits/physics-3d/models/parts/spoked-wheel.pxmodel +39 -0
  115. package/kits/physics-3d/models/parts/staff.pxmodel +33 -0
  116. package/kits/physics-3d/models/parts/stepping-stones.pxmodel +8 -0
  117. package/kits/physics-3d/models/parts/stone-base.pxmodel +10 -0
  118. package/kits/physics-3d/models/parts/sword.pxmodel +33 -0
  119. package/kits/physics-3d/models/parts/window-lit.pxmodel +13 -0
  120. package/kits/physics-3d/models/parts/wizard-hat.pxmodel +28 -0
  121. package/kits/physics-3d/models/templates/biped-stout.pxmodel +59 -0
  122. package/kits/physics-3d/models/templates/biped-tall.pxmodel +63 -0
  123. package/kits/physics-3d/models/templates/quadruped.pxmodel +52 -0
  124. package/kits/physics-3d/scripts/render/filmstrip.js +217 -0
  125. package/kits/physics-3d/scripts/render/index.html +20 -0
  126. package/kits/physics-3d/scripts/render/sheet.js +411 -0
  127. package/kits/physics-3d/scripts/render.mjs +646 -0
  128. package/kits/real-time/castle.json +2 -2
  129. package/kits/real-time/code/client/ownership.js +14 -4
  130. package/kits/real-time/code/client/smooth.js +2 -2
  131. package/kits/real-time/code/server/session.js +20 -4
  132. package/package.json +2 -2
  133. package/dist/shell/assets/index-CHMcsJrW.css +0 -1
@@ -0,0 +1,675 @@
1
+ // The stylized look drawn over every `.pxmodel`: a dark outline around each
2
+ // part, a rim of light on edges turned away from the camera, and darkening
3
+ // where parts meet. Seen from the game camera a model is a few dozen pixels
4
+ // tall, and without these its parts share one value band with the ground.
5
+ //
6
+ // A model's `look` sets it for every part, and a part's own `look` is merged
7
+ // over that. `"look": false` turns it off, for the model or for one part.
8
+ //
9
+ // The outline is an inverted hull: a copy of the mesh drawn with its back
10
+ // faces only, pushed out along smoothed normals, in one flat dark color. The
11
+ // rim and the occlusion are patched into the part's own material. Occlusion
12
+ // is baked once per model into a vertex attribute, by marching rays through
13
+ // a coarse grid of the model's surfaces.
14
+
15
+ import * as THREE from 'three';
16
+
17
+ export const LOOK_DEFAULTS = {
18
+ outline: 0.012,
19
+ outlineColor: '#1a1622',
20
+ rim: 0.35,
21
+ ao: 0.6,
22
+ };
23
+
24
+ // An outline is never thinner than this many screen pixels, so it still
25
+ // shows at game size, where 0.012 m is under one pixel.
26
+ const OUTLINE_MIN_PIXELS = 1.1;
27
+
28
+ // Parts smaller than this radius, in meters, get no outline: eyes and
29
+ // buttons would turn into dark dots.
30
+ const OUTLINE_MIN_RADIUS = 0.035;
31
+
32
+ // The occlusion grid has this many cells along the model's longest side, and
33
+ // rays reach this fraction of that side.
34
+ const GRID_CELLS = 48;
35
+ const RAY_REACH = 0.22;
36
+
37
+ //
38
+ // Settings
39
+ //
40
+
41
+ function readLook(value, base) {
42
+ if (value === false) {
43
+ return null;
44
+ }
45
+ if (!value || typeof value !== 'object') {
46
+ return base;
47
+ }
48
+ const look = { ...base };
49
+ for (const key of ['outline', 'rim', 'ao']) {
50
+ if (Number.isFinite(value[key])) {
51
+ look[key] = Math.max(0, value[key]);
52
+ }
53
+ }
54
+ if (typeof value.outlineColor === 'string') {
55
+ look.outlineColor = value.outlineColor;
56
+ }
57
+ return look;
58
+ }
59
+
60
+ // The look of every part of a model, by part id, or null when the model has
61
+ // the look turned off.
62
+ function partLooks(model) {
63
+ const base = readLook(model.look, LOOK_DEFAULTS);
64
+ if (!base) {
65
+ return null;
66
+ }
67
+ const looks = new Map();
68
+ for (const part of model.parts) {
69
+ looks.set(part.id, readLook(part.look, base));
70
+ }
71
+ return { base, looks };
72
+ }
73
+
74
+ //
75
+ // Applying
76
+ //
77
+
78
+ // Add the look to a model built by buildModelNode. Meshes already done (the
79
+ // parts of a referenced model, built with that model's own look) are left
80
+ // as they are.
81
+ // A deck can turn the look off everywhere, e.g. from a settings toggle. The
82
+ // flag is part of every model's signature (modelArtSignature in pxmodel.js),
83
+ // so placed models rebuild when it changes.
84
+ let lookEnabled = true;
85
+
86
+ export function setLookEnabled(enabled) {
87
+ lookEnabled = Boolean(enabled);
88
+ }
89
+
90
+ export function lookIsEnabled() {
91
+ return lookEnabled;
92
+ }
93
+
94
+ export function applyLook(root, model) {
95
+ const settings = lookEnabled ? partLooks(model) : null;
96
+ const meshes = [];
97
+ root.traverse((object) => {
98
+ if (object.isMesh && !object.userData.lookOutline && !object.userData.lookDone) {
99
+ meshes.push(object);
100
+ }
101
+ });
102
+ if (!settings) {
103
+ meshes.forEach((mesh) => (mesh.userData.lookDone = true));
104
+ return;
105
+ }
106
+ const lookOf = (mesh) => {
107
+ const id = mesh.userData.partMesh;
108
+ return settings.looks.has(id) ? settings.looks.get(id) : settings.base;
109
+ };
110
+ const occluded = meshes.filter((mesh) => lookOf(mesh)?.ao > 0);
111
+ if (occluded.length > 0) {
112
+ bakeOcclusion(root, model, occluded);
113
+ }
114
+ for (const mesh of meshes) {
115
+ const look = lookOf(mesh);
116
+ mesh.userData.lookDone = true;
117
+ if (!look) {
118
+ continue;
119
+ }
120
+ for (const material of [mesh.material].flat()) {
121
+ patchMaterial(material, look, mesh.geometry);
122
+ }
123
+ if (look.outline > 0 && wantsOutline(mesh)) {
124
+ mesh.add(makeOutline(mesh.geometry, look, mesh.material));
125
+ }
126
+ }
127
+ }
128
+
129
+ //
130
+ // Rim and occlusion
131
+ //
132
+
133
+ const RIM_VERTEX = /* glsl */ `
134
+ #ifdef LOOK_AO
135
+ attribute float lookOcclusion;
136
+ varying float vLookOcclusion;
137
+ #endif
138
+ `;
139
+
140
+ const RIM_FRAGMENT = /* glsl */ `
141
+ uniform float lookRim;
142
+ uniform float lookAo;
143
+ #ifdef LOOK_AO
144
+ varying float vLookOcclusion;
145
+ #endif
146
+ `;
147
+
148
+ // Occlusion scales the surface color. The rim is added light, strongest where
149
+ // the surface turns edge-on to the camera, in a lighter shade of the surface.
150
+ function patchMaterial(material, look, geometry) {
151
+ if (material.userData.lookPatched) {
152
+ return;
153
+ }
154
+ material.userData.lookPatched = true;
155
+ if (geometry.getAttribute('lookOcclusion') && look.ao > 0) {
156
+ material.defines = { ...(material.defines ?? {}), LOOK_AO: '' };
157
+ }
158
+ const uniforms = {
159
+ lookRim: { value: look.rim },
160
+ lookAo: { value: look.ao },
161
+ };
162
+ const previous = material.onBeforeCompile;
163
+ const previousKey = material.customProgramCacheKey;
164
+ material.onBeforeCompile = (shader, renderer) => {
165
+ previous.call(material, shader, renderer);
166
+ Object.assign(shader.uniforms, uniforms);
167
+ shader.vertexShader = RIM_VERTEX + shader.vertexShader;
168
+ shader.vertexShader = shader.vertexShader.replace(
169
+ '#include <begin_vertex>',
170
+ '#include <begin_vertex>\n#ifdef LOOK_AO\nvLookOcclusion = lookOcclusion;\n#endif'
171
+ );
172
+ shader.fragmentShader = RIM_FRAGMENT + shader.fragmentShader;
173
+ shader.fragmentShader = shader.fragmentShader.replace(
174
+ '#include <color_fragment>',
175
+ '#include <color_fragment>\n#ifdef LOOK_AO\ndiffuseColor.rgb *= mix(1.0, vLookOcclusion, lookAo);\n#endif'
176
+ );
177
+ shader.fragmentShader = shader.fragmentShader.replace(
178
+ '#include <opaque_fragment>',
179
+ [
180
+ 'vec3 lookView = isOrthographic ? vec3(0.0, 0.0, 1.0) : normalize(vViewPosition);',
181
+ 'float lookEdge = pow(1.0 - saturate(dot(normal, lookView)), 3.0);',
182
+ 'outgoingLight += lookRim * lookEdge * mix(diffuseColor.rgb, vec3(1.0), 0.2);',
183
+ '#include <opaque_fragment>',
184
+ ].join('\n')
185
+ );
186
+ };
187
+ material.customProgramCacheKey = () => `look|${previousKey.call(material)}`;
188
+ material.needsUpdate = true;
189
+ }
190
+
191
+ //
192
+ // Outline
193
+ //
194
+
195
+ // Parts too small to outline. A part drawn from both sides (a lathe, an open
196
+ // surface) still gets one: the hull behind it only shows past its edges,
197
+ // because the part's own inner faces are drawn in front of the hull.
198
+ function wantsOutline(mesh) {
199
+ const geometry = mesh.geometry;
200
+ if (!geometry.boundingSphere) {
201
+ geometry.computeBoundingSphere();
202
+ }
203
+ const scale = new THREE.Vector3();
204
+ mesh.updateWorldMatrix(true, false);
205
+ mesh.matrixWorld.decompose(new THREE.Vector3(), new THREE.Quaternion(), scale);
206
+ const largest = Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
207
+
208
+ // A mesh merged from several parts (optimize.js) goes by its smallest part.
209
+ const radius = mesh.userData.partRadius ?? geometry.boundingSphere.radius * largest;
210
+ return radius >= OUTLINE_MIN_RADIUS;
211
+ }
212
+
213
+ // The outline never takes a raycast hit, so picking finds the part itself.
214
+ // Clones stay outlines, since a clone is made with the same constructor.
215
+ class OutlineMesh extends THREE.Mesh {
216
+ raycast() {}
217
+ }
218
+
219
+ const OUTLINE_VERTEX = /* glsl */ `
220
+ attribute vec3 lookOutlineNormal;
221
+ attribute float lookOutlineReach;
222
+ uniform float lookOutline;
223
+ uniform float lookViewportHeight;
224
+ `;
225
+
226
+ // The hull is pushed out in view space, so its width is in meters however
227
+ // the part is scaled, with a floor of OUTLINE_MIN_PIXELS. A pixel at depth z
228
+ // covers 2 z / (projection[1][1] * viewport height) meters. The push never
229
+ // passes the vertex's reach, so wires and thin rods get thin outlines. An
230
+ // instanced copy (optimize.js) turns its normals with its instance.
231
+ const OUTLINE_PUSH = /* glsl */ `
232
+ #include <project_vertex>
233
+ #ifdef USE_INSTANCING
234
+ vec3 lookDirection = mat3(instanceMatrix) * lookOutlineNormal;
235
+ #else
236
+ vec3 lookDirection = lookOutlineNormal;
237
+ #endif
238
+ vec3 lookNormal = normalize(normalMatrix * lookDirection);
239
+ float lookReach = length((modelViewMatrix * vec4(lookDirection * lookOutlineReach, 0.0)).xyz);
240
+ float lookPixel = (isOrthographic ? 2.0 : -2.0 * mvPosition.z) / (projectionMatrix[1][1] * lookViewportHeight);
241
+ float lookWidth = min(max(lookOutline, ${OUTLINE_MIN_PIXELS.toFixed(2)} * lookPixel), lookReach);
242
+ mvPosition.xyz += lookNormal * lookWidth;
243
+ gl_Position = projectionMatrix * mvPosition;
244
+ `;
245
+
246
+ const viewport = new THREE.Vector4();
247
+
248
+ function makeOutline(geometry, look, partMaterial) {
249
+ addOutlineAttributes(geometry);
250
+ const material = new THREE.MeshBasicMaterial({
251
+ color: new THREE.Color(look.outlineColor),
252
+ side: THREE.BackSide,
253
+ });
254
+
255
+ // A part with `alphaTest` (artobjects.js) has holes where its art is clear.
256
+ // The hull takes the same art and cut, so the holes show through it.
257
+ const cut = [partMaterial].flat().find((each) => each?.map && each.alphaTest > 0);
258
+ if (cut) {
259
+ material.map = cut.map;
260
+ material.alphaTest = cut.alphaTest;
261
+ }
262
+ const uniforms = {
263
+ lookOutline: { value: look.outline },
264
+ lookViewportHeight: { value: 720 },
265
+ };
266
+ material.onBeforeCompile = (shader) => {
267
+ Object.assign(shader.uniforms, uniforms);
268
+ shader.vertexShader = OUTLINE_VERTEX + shader.vertexShader;
269
+ shader.vertexShader = shader.vertexShader.replace('#include <project_vertex>', OUTLINE_PUSH);
270
+ };
271
+ material.customProgramCacheKey = () => 'look-outline';
272
+
273
+ // The viewport is in device pixels; the floor is in CSS pixels.
274
+ material.onBeforeRender = (renderer) => {
275
+ renderer.getCurrentViewport(viewport);
276
+ uniforms.lookViewportHeight.value = Math.max(1, viewport.w / renderer.getPixelRatio());
277
+ };
278
+ const outline = new OutlineMesh(geometry, material);
279
+ outline.userData.lookOutline = true;
280
+ outline.castShadow = false;
281
+ outline.receiveShadow = false;
282
+ return outline;
283
+ }
284
+
285
+ // Two attributes for the hull. `lookOutlineNormal` is the normal averaged
286
+ // over every vertex at the same position: a box has three normals at each
287
+ // corner, and pushed apart along them its hull would split open.
288
+ // `lookOutlineReach` is the vertex's radius of curvature, the smallest over
289
+ // its edges: two points a chord d apart on a circle of radius r, with
290
+ // normals n1 and n2, have (n2 - n1) . d = |d|^2 / r where the surface bulges.
291
+ // It is also kept under the push that would turn a triangle over (foldWidth).
292
+ export function addOutlineAttributes(geometry) {
293
+ if (geometry.getAttribute('lookOutlineNormal')) {
294
+ return;
295
+ }
296
+ if (!geometry.getAttribute('normal')) {
297
+ geometry.computeVertexNormals();
298
+ }
299
+ const positions = geometry.getAttribute('position');
300
+ const normals = geometry.getAttribute('normal');
301
+ const { slots, sums } = sumNormalsByPosition(positions, normals);
302
+ const smooth = new Float32Array(positions.count * 3);
303
+ for (let i = 0; i < positions.count; i++) {
304
+ const at = slots[i] * 3;
305
+ const length = Math.hypot(sums[at], sums[at + 1], sums[at + 2]);
306
+
307
+ // Opposite normals cancel out (both faces of a thin sheet); keep the
308
+ // vertex's own normal there.
309
+ if (length < 1e-4) {
310
+ smooth.set([normals.getX(i), normals.getY(i), normals.getZ(i)], i * 3);
311
+ } else {
312
+ smooth.set([sums[at] / length, sums[at + 1] / length, sums[at + 2] / length], i * 3);
313
+ }
314
+ }
315
+ const reach = curvatureRadii(geometry, positions, smooth, slots);
316
+ geometry.setAttribute('lookOutlineNormal', new THREE.BufferAttribute(smooth, 3));
317
+ geometry.setAttribute('lookOutlineReach', new THREE.BufferAttribute(reach, 1));
318
+ }
319
+
320
+ // Vertices at the same position (to 0.1 mm) share a slot; `sums` holds each
321
+ // slot's summed normal.
322
+ function sumNormalsByPosition(positions, normals) {
323
+ const slotOf = new Map();
324
+ const slots = new Uint32Array(positions.count);
325
+ const sums = [];
326
+ for (let i = 0; i < positions.count; i++) {
327
+ const key = `${Math.round(positions.getX(i) * 1e4)},${Math.round(positions.getY(i) * 1e4)},${Math.round(positions.getZ(i) * 1e4)}`;
328
+ let slot = slotOf.get(key);
329
+ if (slot === undefined) {
330
+ slot = slotOf.size;
331
+ slotOf.set(key, slot);
332
+ sums.push(0, 0, 0);
333
+ }
334
+ slots[i] = slot;
335
+ sums[slot * 3] += normals.getX(i);
336
+ sums[slot * 3 + 1] += normals.getY(i);
337
+ sums[slot * 3 + 2] += normals.getZ(i);
338
+ }
339
+ return { slots, sums };
340
+ }
341
+
342
+ function curvatureRadii(geometry, positions, smooth, slots) {
343
+ const index = geometry.getIndex();
344
+ const count = index ? index.count : positions.count;
345
+ const corner = (n) => (index ? index.getX(n) : n);
346
+ const bySlot = new Float32Array(slots.length).fill(1e6);
347
+ const edge = (a, b) => {
348
+ const dx = positions.getX(b) - positions.getX(a);
349
+ const dy = positions.getY(b) - positions.getY(a);
350
+ const dz = positions.getZ(b) - positions.getZ(a);
351
+ const bend =
352
+ (smooth[b * 3] - smooth[a * 3]) * dx +
353
+ (smooth[b * 3 + 1] - smooth[a * 3 + 1]) * dy +
354
+ (smooth[b * 3 + 2] - smooth[a * 3 + 2]) * dz;
355
+
356
+ // A hollow bends the other way and does not limit the push.
357
+ if (bend < 1e-9) {
358
+ return;
359
+ }
360
+ const radius = (dx * dx + dy * dy + dz * dz) / bend;
361
+ bySlot[slots[a]] = Math.min(bySlot[slots[a]], radius);
362
+ bySlot[slots[b]] = Math.min(bySlot[slots[b]], radius);
363
+ };
364
+ for (let n = 0; n + 2 < count; n += 3) {
365
+ const a = corner(n);
366
+ const b = corner(n + 1);
367
+ const c = corner(n + 2);
368
+ edge(a, b);
369
+ edge(b, c);
370
+ edge(c, a);
371
+
372
+ const fold = FOLD_SHARE * foldWidth(positions, smooth, a, b, c);
373
+ for (const at of [a, b, c]) {
374
+ bySlot[slots[at]] = Math.min(bySlot[slots[at]], fold);
375
+ }
376
+ }
377
+ for (let pass = 0; pass < UNEVEN_PASSES; pass++) {
378
+ evenOutFolds(positions, smooth, slots, bySlot, count, corner);
379
+ }
380
+ const reach = new Float32Array(positions.count);
381
+ for (let i = 0; i < positions.count; i++) {
382
+ reach[i] = bySlot[slots[i]];
383
+ }
384
+ return reach;
385
+ }
386
+
387
+ // A hull triangle pushed too far turns over. Its back then faces the camera
388
+ // from in front of the part, and draws as a dark shard. A thin triangle whose
389
+ // corners have different normals turns over soonest; sculpting and surface
390
+ // detail make many. Each corner pushes at most this share of the push that
391
+ // turns one of its triangles over.
392
+ const FOLD_SHARE = 0.5;
393
+ const NO_FOLD = 1e6;
394
+
395
+ const start = new THREE.Vector3();
396
+ const startNormal = new THREE.Vector3();
397
+ const sideB = new THREE.Vector3();
398
+ const sideC = new THREE.Vector3();
399
+ const turnB = new THREE.Vector3();
400
+ const turnC = new THREE.Vector3();
401
+ const facing = new THREE.Vector3();
402
+ const product = new THREE.Vector3();
403
+
404
+ // The push w that turns triangle a b c over, each corner moved w along its
405
+ // smoothed normal n. The triangle faces f . ((B - A + w (nB - nA)) x
406
+ // (C - A + w (nC - nA))), with f its own normal, a quadratic in w that is
407
+ // positive at w = 0; the push is its smallest positive root.
408
+ function foldWidth(positions, smooth, a, b, c) {
409
+ start.fromBufferAttribute(positions, a);
410
+ sideB.fromBufferAttribute(positions, b).sub(start);
411
+ sideC.fromBufferAttribute(positions, c).sub(start);
412
+ startNormal.fromArray(smooth, a * 3);
413
+ turnB.fromArray(smooth, b * 3).sub(startNormal);
414
+ turnC.fromArray(smooth, c * 3).sub(startNormal);
415
+ facing.crossVectors(sideB, sideC);
416
+ const constant = facing.lengthSq();
417
+
418
+ // A triangle with no area is never seen.
419
+ if (constant < 1e-20) {
420
+ return NO_FOLD;
421
+ }
422
+ const linear =
423
+ facing.dot(product.crossVectors(sideB, turnC)) + facing.dot(product.crossVectors(turnB, sideC));
424
+ const square = facing.dot(product.crossVectors(turnB, turnC));
425
+ const discriminant = linear * linear - 4 * square * constant;
426
+ if (discriminant < 0) {
427
+ return NO_FOLD;
428
+ }
429
+
430
+ // The two roots, in a form that stays exact when `square` is near 0.
431
+ const half = -0.5 * (linear + (linear < 0 ? -1 : 1) * Math.sqrt(discriminant));
432
+ const roots = [half / square, constant / half];
433
+ return Math.min(NO_FOLD, ...roots.filter((root) => root > 0 && Number.isFinite(root)));
434
+ }
435
+
436
+ // Corners limited by different triangles push unevenly, and a triangle can
437
+ // still turn over when one corner stops short of the others. Each pass holds
438
+ // every such triangle's corners to the least of their reaches. A pass can
439
+ // make a neighbor uneven in turn, so there are a few.
440
+ const UNEVEN_PASSES = 3;
441
+
442
+ const pushed = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()];
443
+
444
+ function evenOutFolds(positions, smooth, slots, bySlot, count, corner) {
445
+ for (let n = 0; n + 2 < count; n += 3) {
446
+ const corners = [corner(n), corner(n + 1), corner(n + 2)];
447
+ const reaches = corners.map((at) => bySlot[slots[at]]);
448
+ const least = Math.min(...reaches);
449
+
450
+ // The outline width grows past each corner's reach in turn, so the
451
+ // triangle is checked with the push stopped at each of them.
452
+ const folds = reaches.some(
453
+ (limit) =>
454
+ limit > least &&
455
+ turnsOver(positions, smooth, corners, reaches.map((reach) => Math.min(reach, limit)))
456
+ );
457
+ if (folds) {
458
+ corners.forEach((at) => (bySlot[slots[at]] = least));
459
+ }
460
+ }
461
+ }
462
+
463
+ // Whether the triangle faces the other way once each corner is pushed its
464
+ // width along its smoothed normal.
465
+ function turnsOver(positions, smooth, corners, widths) {
466
+ corners.forEach((at, k) => {
467
+ startNormal.fromArray(smooth, at * 3);
468
+ pushed[k].fromBufferAttribute(positions, at).addScaledVector(startNormal, widths[k]);
469
+ });
470
+ start.fromBufferAttribute(positions, corners[0]);
471
+ sideB.fromBufferAttribute(positions, corners[1]).sub(start);
472
+ sideC.fromBufferAttribute(positions, corners[2]).sub(start);
473
+ facing.crossVectors(sideB, sideC);
474
+ if (facing.lengthSq() < 1e-20) {
475
+ return false;
476
+ }
477
+ sideB.subVectors(pushed[1], pushed[0]);
478
+ sideC.subVectors(pushed[2], pushed[0]);
479
+ return facing.dot(product.crossVectors(sideB, sideC)) <= 0;
480
+ }
481
+
482
+ //
483
+ // Occlusion bake
484
+ //
485
+
486
+ // Baked occlusion per model, each entry a list of per-vertex arrays in the
487
+ // order the meshes' geometries are first met. `shape` is the vertex counts,
488
+ // checked before an entry is used.
489
+ const occlusionCache = new WeakMap();
490
+
491
+ // Directions spread evenly over the sphere (a Fibonacci sphere). A vertex
492
+ // casts the ones on its outer side.
493
+ const DIRECTIONS = fibonacciSphere(28);
494
+
495
+ function fibonacciSphere(count) {
496
+ const directions = [];
497
+ const turn = Math.PI * (3 - Math.sqrt(5));
498
+ for (let i = 0; i < count; i++) {
499
+ const y = 1 - ((i + 0.5) / count) * 2;
500
+ const ring = Math.sqrt(1 - y * y);
501
+ directions.push([Math.cos(turn * i) * ring, y, Math.sin(turn * i) * ring]);
502
+ }
503
+ return directions;
504
+ }
505
+
506
+ function bakeOcclusion(root, model, meshes) {
507
+ root.updateMatrixWorld(true);
508
+ const geometries = [];
509
+ const firstMesh = new Map();
510
+ for (const mesh of meshes) {
511
+ if (!firstMesh.has(mesh.geometry)) {
512
+ firstMesh.set(mesh.geometry, mesh);
513
+ geometries.push(mesh.geometry);
514
+ }
515
+ }
516
+ const shape = geometries.map((geometry) => geometry.getAttribute('position').count).join(',');
517
+ let cached = occlusionCache.get(model);
518
+ if (!cached || cached.shape !== shape) {
519
+ const grid = buildGrid(root);
520
+ const values = geometries.map((geometry) =>
521
+ grid ? occlusionOf(firstMesh.get(geometry), grid) : null
522
+ );
523
+ cached = { shape, values };
524
+ occlusionCache.set(model, cached);
525
+ }
526
+ geometries.forEach((geometry, index) => {
527
+ const values = cached.values[index];
528
+ if (values) {
529
+ geometry.setAttribute('lookOcclusion', new THREE.BufferAttribute(values, 1));
530
+ }
531
+ });
532
+ }
533
+
534
+ // Every visible mesh of the model, in the model's own space, marked into a
535
+ // grid of cells. Only surfaces are marked; rays step less than a cell at a
536
+ // time, so none passes through a marked cell unseen.
537
+ function buildGrid(root) {
538
+ const surfaces = [];
539
+ const bounds = new THREE.Box3();
540
+ root.traverseVisible((object) => {
541
+ if (!object.isMesh || object.userData.lookOutline) {
542
+ return;
543
+ }
544
+ const positions = object.geometry.getAttribute('position');
545
+ const index = object.geometry.getIndex();
546
+ const count = index ? index.count : positions.count;
547
+ const world = new Float32Array(positions.count * 3);
548
+ const point = new THREE.Vector3();
549
+ for (let i = 0; i < positions.count; i++) {
550
+ point.fromBufferAttribute(positions, i).applyMatrix4(object.matrixWorld);
551
+ world.set([point.x, point.y, point.z], i * 3);
552
+ bounds.expandByPoint(point);
553
+ }
554
+ surfaces.push({ world, index, count });
555
+ });
556
+ if (bounds.isEmpty()) {
557
+ return null;
558
+ }
559
+ const size = bounds.getSize(new THREE.Vector3());
560
+ const cell = Math.max(size.x, size.y, size.z, 0.01) / GRID_CELLS;
561
+ const padding = 3;
562
+ const origin = bounds.min.clone().subScalar(cell * padding);
563
+ const dims = [size.x, size.y, size.z].map((extent) => Math.ceil(extent / cell) + padding * 2);
564
+ const grid = { origin, cell, dims, filled: new Uint8Array(dims[0] * dims[1] * dims[2]) };
565
+ for (const surface of surfaces) {
566
+ markTriangles(grid, surface);
567
+ }
568
+ return grid;
569
+ }
570
+
571
+ // The cell at a point given in cell units from the grid's origin, or -1
572
+ // outside the grid.
573
+ function cellAt(grid, x, y, z) {
574
+ const i = Math.floor(x);
575
+ const j = Math.floor(y);
576
+ const k = Math.floor(z);
577
+ const [width, height, depth] = grid.dims;
578
+ if (i < 0 || j < 0 || k < 0 || i >= width || j >= height || k >= depth) {
579
+ return -1;
580
+ }
581
+ return i + width * (j + height * k);
582
+ }
583
+
584
+ // Each triangle is sampled at points under a cell apart.
585
+ function markTriangles(grid, { world, index, count }) {
586
+ const { origin, cell, filled } = grid;
587
+ const local = new Float32Array(world.length);
588
+ for (let i = 0; i < world.length; i += 3) {
589
+ local[i] = (world[i] - origin.x) / cell;
590
+ local[i + 1] = (world[i + 1] - origin.y) / cell;
591
+ local[i + 2] = (world[i + 2] - origin.z) / cell;
592
+ }
593
+ for (let n = 0; n + 2 < count; n += 3) {
594
+ const a = (index ? index.getX(n) : n) * 3;
595
+ const b = (index ? index.getX(n + 1) : n + 1) * 3;
596
+ const c = (index ? index.getX(n + 2) : n + 2) * 3;
597
+ const abx = local[b] - local[a];
598
+ const aby = local[b + 1] - local[a + 1];
599
+ const abz = local[b + 2] - local[a + 2];
600
+ const acx = local[c] - local[a];
601
+ const acy = local[c + 1] - local[a + 1];
602
+ const acz = local[c + 2] - local[a + 2];
603
+ const longest = Math.max(
604
+ Math.hypot(abx, aby, abz),
605
+ Math.hypot(acx, acy, acz),
606
+ Math.hypot(abx - acx, aby - acy, abz - acz)
607
+ );
608
+ const steps = Math.min(64, Math.max(1, Math.ceil(longest / 0.7)));
609
+ for (let s = 0; s <= steps; s++) {
610
+ for (let t = 0; s + t <= steps; t++) {
611
+ const u = s / steps;
612
+ const v = t / steps;
613
+ const at = cellAt(
614
+ grid,
615
+ local[a] + abx * u + acx * v,
616
+ local[a + 1] + aby * u + acy * v,
617
+ local[a + 2] + abz * u + acz * v
618
+ );
619
+ if (at >= 0) {
620
+ filled[at] = 1;
621
+ }
622
+ }
623
+ }
624
+ }
625
+ }
626
+
627
+ // For each vertex, the share of its outward rays that reach open air, with
628
+ // near hits counting more than far ones. Rays start two cells out along the
629
+ // normal, clear of the cells the vertex's own surface fills, and step 0.7 of
630
+ // a cell at a time, in cell units.
631
+ function occlusionOf(mesh, grid) {
632
+ const positions = mesh.geometry.getAttribute('position');
633
+ let normals = mesh.geometry.getAttribute('normal');
634
+ if (!normals) {
635
+ mesh.geometry.computeVertexNormals();
636
+ normals = mesh.geometry.getAttribute('normal');
637
+ }
638
+ const normalMatrix = new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld);
639
+ const reach = GRID_CELLS * RAY_REACH;
640
+ const point = new THREE.Vector3();
641
+ const normal = new THREE.Vector3();
642
+ const out = new Float32Array(positions.count);
643
+ for (let i = 0; i < positions.count; i++) {
644
+ point.fromBufferAttribute(positions, i).applyMatrix4(mesh.matrixWorld);
645
+ point.sub(grid.origin).divideScalar(grid.cell);
646
+ normal.fromBufferAttribute(normals, i).applyMatrix3(normalMatrix).normalize();
647
+ point.addScaledVector(normal, 2);
648
+ let blocked = 0;
649
+ let total = 0;
650
+ for (const [dx, dy, dz] of DIRECTIONS) {
651
+ const facing = dx * normal.x + dy * normal.y + dz * normal.z;
652
+ if (facing < 0.3) {
653
+ continue;
654
+ }
655
+ total += facing;
656
+ for (let distance = 0; distance < reach; distance += 0.7) {
657
+ const at = cellAt(
658
+ grid,
659
+ point.x + dx * distance,
660
+ point.y + dy * distance,
661
+ point.z + dz * distance
662
+ );
663
+ if (at < 0) {
664
+ break;
665
+ }
666
+ if (grid.filled[at]) {
667
+ blocked += facing * (1 - distance / reach);
668
+ break;
669
+ }
670
+ }
671
+ }
672
+ out[i] = total > 0 ? 1 - blocked / total : 1;
673
+ }
674
+ return out;
675
+ }