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,1058 @@
1
+ // The `blob` part kind: spheres, capsules, tubes and boxes melted into one
2
+ // smooth surface. See docs/pxmodel-format.md for the fields.
3
+ //
4
+ // Each shape is a signed distance function: negative inside, positive
5
+ // outside, and its size the distance to the surface. The shapes are combined
6
+ // in order with a smooth minimum, which rounds the join between two shapes
7
+ // over a width of `blend`. A shape with `subtract` carves instead. The field
8
+ // is sampled on a grid and meshed by the surface nets method: one vertex in
9
+ // every grid cell the surface passes through, joined into quads across every
10
+ // grid edge it crosses. Each vertex is then moved onto the surface, and its
11
+ // normal is the direction the field grows. Shape colors go to the nearest
12
+ // shape at each point, and triangles are cut where the color changes.
13
+
14
+ import * as THREE from 'three';
15
+ import { smallestCell } from './optimize';
16
+
17
+ const DEG = Math.PI / 180;
18
+ const DEFAULT_BLEND = 0.08;
19
+ const DEFAULT_RESOLUTION = 48;
20
+ const MAX_RESOLUTION = 96;
21
+ const MAX_SHAPES = 64;
22
+
23
+ // A blob has at least this many cells along its longest side, however small.
24
+ const MIN_RESOLUTION = 12;
25
+
26
+ const SPHERE = 0;
27
+ const ELLIPSOID = 1;
28
+ const CAPSULE = 2;
29
+ const BOX = 3;
30
+ const TUBE = 4;
31
+
32
+ // A tube is drawn as this many tapered capsules between two of its points,
33
+ // and at most TUBE_PIECES in all.
34
+ const TUBE_STEPS = 8;
35
+ const TUBE_PIECES = 64;
36
+
37
+ // A shape as read from the part: `type`, its fields in world numbers,
38
+ // `subtract`, `blend`, `color` (a THREE.Color or null), and `low` / `high`,
39
+ // the corners of a box around it. Boxes and ellipsoids also carry `inverse`,
40
+ // the 3 x 3 rotation that takes a point into their own axes. A capsule is a
41
+ // `cone`: `start`, `end`, `radius` at the start and `radiusEnd`. A tube keeps
42
+ // a list of cones.
43
+
44
+ //
45
+ // Reading the shapes
46
+ //
47
+
48
+ function vector(value) {
49
+ if (!Array.isArray(value) || !value.slice(0, 3).every(Number.isFinite)) {
50
+ return null;
51
+ }
52
+ return [value[0], value[1], value[2]];
53
+ }
54
+
55
+ function positive(value, fallback) {
56
+ return Number.isFinite(value) && value > 0 ? value : fallback;
57
+ }
58
+
59
+ // The rotation from `rotation` degrees, inverted and kept as 9 numbers, row
60
+ // by row. Null when there is no rotation.
61
+ function inverseRotation(rotation) {
62
+ const angles = vector(rotation);
63
+ if (!angles || angles.every((angle) => angle === 0)) {
64
+ return null;
65
+ }
66
+ const matrix = new THREE.Matrix4().makeRotationFromEuler(
67
+ new THREE.Euler(angles[0] * DEG, angles[1] * DEG, angles[2] * DEG)
68
+ );
69
+ const e = matrix.elements;
70
+
71
+ // Elements are column by column; the transpose of a rotation is its inverse.
72
+ return [e[0], e[1], e[2], e[4], e[5], e[6], e[8], e[9], e[10]];
73
+ }
74
+
75
+ // With no `blend` written, a shape melts in by a share of its own thickness,
76
+ // capped at DEFAULT_BLEND: thin legs and ears on a small animal stay apart
77
+ // instead of melting into one lump.
78
+ const BLEND_SHARE = 0.4;
79
+
80
+ // The narrowest radius (half-size for a box) a shape is written with.
81
+ function thicknessOf(raw) {
82
+ const numbers = [raw.radius, raw.radiusEnd, raw.radii, raw.size && raw.size.map((value) => value / 2)]
83
+ .flat(2)
84
+ .filter((value) => Number.isFinite(value) && value > 0);
85
+ return numbers.length ? Math.min(...numbers) : DEFAULT_BLEND / BLEND_SHARE;
86
+ }
87
+
88
+ function readShape(raw, part) {
89
+ if (!raw || typeof raw !== 'object') {
90
+ return null;
91
+ }
92
+ const shape = readSphere(raw) ?? readCapsule(raw) ?? readTube(raw) ?? readBox(raw);
93
+ if (!shape) {
94
+ return null;
95
+ }
96
+ shape.subtract = raw.subtract === true;
97
+ shape.color = typeof raw.color === 'string' ? new THREE.Color(raw.color) : null;
98
+ if (Number.isFinite(raw.blend)) {
99
+ shape.blend = Math.max(0, raw.blend);
100
+ } else if (part.blend === 0) {
101
+ shape.blend = 0;
102
+ } else if (Number.isFinite(part.blend) && part.blend > 0) {
103
+ shape.blend = part.blend;
104
+ } else {
105
+ shape.blend = Math.min(DEFAULT_BLEND, BLEND_SHARE * thicknessOf(raw));
106
+ }
107
+ prepareShape(shape);
108
+ return shape;
109
+ }
110
+
111
+ // A sphere, or an ellipsoid when `radius` is [x, y, z].
112
+ function readSphere(raw) {
113
+ const center = vector(raw.sphere);
114
+ if (!center) {
115
+ return null;
116
+ }
117
+ const radii = vector(raw.radius);
118
+ if (radii) {
119
+ return {
120
+ type: ELLIPSOID,
121
+ center,
122
+ radii: radii.map((radius) => positive(radius, 0.1)),
123
+ inverse: inverseRotation(raw.rotation),
124
+ };
125
+ }
126
+ return { type: SPHERE, center, radius: positive(raw.radius, 0.1) };
127
+ }
128
+
129
+ function readCapsule(raw) {
130
+ const ends = Array.isArray(raw.capsule) ? raw.capsule.map(vector) : [];
131
+ if (ends.length !== 2 || !ends[0] || !ends[1]) {
132
+ return null;
133
+ }
134
+ const radius = positive(raw.radius, 0.1);
135
+ return {
136
+ type: CAPSULE,
137
+ start: ends[0],
138
+ end: ends[1],
139
+ radius,
140
+ radiusEnd: Number.isFinite(raw.radiusEnd) ? Math.max(0, raw.radiusEnd) : radius,
141
+ };
142
+ }
143
+
144
+ // A smooth curve through the `tube` points, with a radius per point from
145
+ // `radii` eased between points, or `radius` to `radiusEnd` along it.
146
+ function readTube(raw) {
147
+ const points = Array.isArray(raw.tube) ? raw.tube.map(vector).filter(Boolean) : [];
148
+ if (points.length < 2) {
149
+ return null;
150
+ }
151
+ const curve = new THREE.CatmullRomCurve3(
152
+ points.map((point) => new THREE.Vector3(...point)),
153
+ false,
154
+ 'centripetal'
155
+ );
156
+ const radiusAt = tubeRadius(raw, points.length);
157
+ const steps = Math.min(TUBE_PIECES, (points.length - 1) * TUBE_STEPS);
158
+ const cones = [];
159
+ let start = curve.getPoint(0);
160
+ for (let step = 1; step <= steps; step++) {
161
+ const end = curve.getPoint(step / steps);
162
+ cones.push({
163
+ start: start.toArray(),
164
+ end: end.toArray(),
165
+ radius: radiusAt((step - 1) / steps),
166
+ radiusEnd: radiusAt(step / steps),
167
+ });
168
+ start = end;
169
+ }
170
+ return { type: TUBE, cones };
171
+ }
172
+
173
+ // The radius at `t`, 0 at the first point and 1 at the last.
174
+ function tubeRadius(raw, count) {
175
+ const radii =
176
+ Array.isArray(raw.radii) && raw.radii.length === count && raw.radii.every(Number.isFinite)
177
+ ? raw.radii.map((radius) => Math.max(0, radius))
178
+ : null;
179
+ const start = positive(raw.radius, 0.05);
180
+ const end = Number.isFinite(raw.radiusEnd) ? Math.max(0, raw.radiusEnd) : start;
181
+ return (t) => {
182
+ if (!radii) {
183
+ return start + (end - start) * t;
184
+ }
185
+ const at = t * (count - 1);
186
+ const index = Math.min(count - 2, Math.floor(at));
187
+ const blend = at - index;
188
+ const eased = blend * blend * (3 - 2 * blend);
189
+ return radii[index] + (radii[index + 1] - radii[index]) * eased;
190
+ };
191
+ }
192
+
193
+ function readBox(raw) {
194
+ const center = vector(raw.box);
195
+ if (!center) {
196
+ return null;
197
+ }
198
+ const size = vector(raw.size) ?? [0.2, 0.2, 0.2];
199
+ const half = size.map((side) => Math.max(1e-4, side / 2));
200
+ const round = Number.isFinite(raw.round) ? Math.max(0, raw.round) : 0;
201
+ return {
202
+ type: BOX,
203
+ center,
204
+ half,
205
+ round: Math.min(round, ...half),
206
+ inverse: inverseRotation(raw.rotation),
207
+ };
208
+ }
209
+
210
+ // Numbers each distance function needs that depend only on the shape, and
211
+ // the box around it.
212
+ function prepareShape(shape) {
213
+ if (shape.type === CAPSULE) {
214
+ prepareCone(shape);
215
+ return;
216
+ }
217
+ if (shape.type === TUBE) {
218
+ shape.cones.forEach(prepareCone);
219
+ shape.low = [0, 1, 2].map((i) => Math.min(...shape.cones.map((cone) => cone.low[i])));
220
+ shape.high = [0, 1, 2].map((i) => Math.max(...shape.cones.map((cone) => cone.high[i])));
221
+ return;
222
+ }
223
+ let reach;
224
+ if (shape.type === SPHERE) {
225
+ reach = shape.radius;
226
+ } else if (shape.type === ELLIPSOID) {
227
+ reach = Math.max(...shape.radii);
228
+ } else {
229
+ reach = Math.hypot(...shape.half);
230
+ }
231
+ shape.low = shape.center.map((value) => value - reach);
232
+ shape.high = shape.center.map((value) => value + reach);
233
+ }
234
+
235
+ function prepareCone(cone) {
236
+ const [a, b] = [cone.start, cone.end];
237
+ const axis = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
238
+ cone.axis = axis;
239
+ cone.lengthSquared = Math.max(1e-12, axis[0] ** 2 + axis[1] ** 2 + axis[2] ** 2);
240
+ const reach = Math.max(cone.radius, cone.radiusEnd);
241
+ cone.low = [0, 1, 2].map((i) => Math.min(a[i], b[i]) - reach);
242
+ cone.high = [0, 1, 2].map((i) => Math.max(a[i], b[i]) + reach);
243
+ }
244
+
245
+ // The same shape reflected across x = 0.
246
+ function mirrorShape(shape) {
247
+ const copy = { ...shape };
248
+ const flip = (point) => [-point[0], point[1], point[2]];
249
+ if (shape.type === CAPSULE) {
250
+ copy.start = flip(shape.start);
251
+ copy.end = flip(shape.end);
252
+ } else if (shape.type === TUBE) {
253
+ copy.cones = shape.cones.map((cone) => ({
254
+ ...cone,
255
+ start: flip(cone.start),
256
+ end: flip(cone.end),
257
+ }));
258
+ } else {
259
+ copy.center = flip(shape.center);
260
+ }
261
+
262
+ // Reflecting a rotation negates the entries that mix x with y or z.
263
+ if (shape.inverse) {
264
+ const m = shape.inverse;
265
+ copy.inverse = [m[0], -m[1], -m[2], -m[3], m[4], m[5], -m[6], m[7], m[8]];
266
+ }
267
+ prepareShape(copy);
268
+ return copy;
269
+ }
270
+
271
+ // A shape on the middle line is its own reflection and is not copied; a copy
272
+ // would melt into it and swell it.
273
+ function isOnMiddle(shape) {
274
+ const near = (value) => Math.abs(value) < 1e-6;
275
+ if (shape.type === CAPSULE) {
276
+ return near(shape.start[0]) && near(shape.end[0]);
277
+ }
278
+ if (shape.type === TUBE) {
279
+ return shape.cones.every((cone) => near(cone.start[0]) && near(cone.end[0]));
280
+ }
281
+ if (!near(shape.center[0])) {
282
+ return false;
283
+ }
284
+ if (!shape.inverse) {
285
+ return true;
286
+ }
287
+ const m = shape.inverse;
288
+ return near(m[1]) && near(m[2]) && near(m[3]) && near(m[6]);
289
+ }
290
+
291
+ // The shapes in order. With `symmetric: "x"` each shape off the middle is
292
+ // followed by its reflection, unless the shape has `symmetric: false`. A
293
+ // tube becomes one capsule shape per cone, all with the same `group` number:
294
+ // the cones of a group join each other by a plain minimum, and the group
295
+ // joins the rest as one shape.
296
+ function readShapes(part) {
297
+ const list = Array.isArray(part.shapes) ? part.shapes.slice(0, MAX_SHAPES) : [];
298
+ const shapes = [];
299
+ let group = 0;
300
+ const add = (shape) => {
301
+ if (shape.type !== TUBE) {
302
+ shapes.push(shape);
303
+ return;
304
+ }
305
+ group++;
306
+ for (const cone of shape.cones) {
307
+ const { subtract, blend, color } = shape;
308
+ shapes.push({ ...cone, type: CAPSULE, subtract, blend, color, group });
309
+ }
310
+ };
311
+ for (const raw of list) {
312
+ const shape = readShape(raw, part);
313
+ if (!shape) {
314
+ continue;
315
+ }
316
+ add(shape);
317
+ if (part.symmetric === 'x' && raw.symmetric !== false && !isOnMiddle(shape)) {
318
+ add(mirrorShape(shape));
319
+ }
320
+ }
321
+ return shapes;
322
+ }
323
+
324
+ //
325
+ // Distance functions
326
+ //
327
+
328
+ function sphereDistance(shape, x, y, z) {
329
+ const [cx, cy, cz] = shape.center;
330
+ const dx = x - cx;
331
+ const dy = y - cy;
332
+ const dz = z - cz;
333
+ return Math.sqrt(dx * dx + dy * dy + dz * dz) - shape.radius;
334
+ }
335
+
336
+ // The point in the shape's own axes, centered on it.
337
+ function localPoint(shape, x, y, z, out) {
338
+ const dx = x - shape.center[0];
339
+ const dy = y - shape.center[1];
340
+ const dz = z - shape.center[2];
341
+ const m = shape.inverse;
342
+ if (!m) {
343
+ out[0] = dx;
344
+ out[1] = dy;
345
+ out[2] = dz;
346
+ return;
347
+ }
348
+ out[0] = m[0] * dx + m[1] * dy + m[2] * dz;
349
+ out[1] = m[3] * dx + m[4] * dy + m[5] * dz;
350
+ out[2] = m[6] * dx + m[7] * dy + m[8] * dz;
351
+ }
352
+
353
+ const local = [0, 0, 0];
354
+
355
+ // An ellipsoid has no exact distance; this is a close estimate that is exact
356
+ // on the surface.
357
+ function ellipsoidDistance(shape, x, y, z) {
358
+ localPoint(shape, x, y, z, local);
359
+ const [rx, ry, rz] = shape.radii;
360
+ const [ax, ay, az] = [local[0] / rx, local[1] / ry, local[2] / rz];
361
+ const k0 = Math.sqrt(ax * ax + ay * ay + az * az);
362
+ const k1 = Math.sqrt((ax / rx) ** 2 + (ay / ry) ** 2 + (az / rz) ** 2);
363
+ if (k1 < 1e-9) {
364
+ return -Math.min(rx, ry, rz);
365
+ }
366
+ return (k0 * (k0 - 1)) / k1;
367
+ }
368
+
369
+ // A capsule with a different radius at each end, the shape a sphere makes as
370
+ // it moves from one end to the other while changing size. The exact distance
371
+ // from Inigo Quilez's "round cone".
372
+ function capsuleDistance(cone, x, y, z) {
373
+ const [ax, ay, az] = cone.start;
374
+ const [bx, by, bz] = cone.end;
375
+ const r1 = cone.radius;
376
+ const r2 = cone.radiusEnd;
377
+ const l2 = cone.lengthSquared;
378
+ const rr = r1 - r2;
379
+ const a2 = l2 - rr * rr;
380
+
381
+ // With one radius, the distance to the nearest point on the segment.
382
+ if (rr === 0) {
383
+ const [ux, uy, uz] = cone.axis;
384
+ const px = x - ax;
385
+ const py = y - ay;
386
+ const pz = z - az;
387
+ const t = Math.max(0, Math.min(1, (px * ux + py * uy + pz * uz) / l2));
388
+ const dx = px - ux * t;
389
+ const dy = py - uy * t;
390
+ const dz = pz - uz * t;
391
+ return Math.sqrt(dx * dx + dy * dy + dz * dz) - r1;
392
+ }
393
+
394
+ // One sphere holds the other: the capsule is the bigger sphere.
395
+ if (a2 <= 1e-12) {
396
+ return r1 >= r2
397
+ ? Math.hypot(x - ax, y - ay, z - az) - r1
398
+ : Math.hypot(x - bx, y - by, z - bz) - r2;
399
+ }
400
+ const [ux, uy, uz] = cone.axis;
401
+ const px = x - ax;
402
+ const py = y - ay;
403
+ const pz = z - az;
404
+ const along = px * ux + py * uy + pz * uz;
405
+ const past = along - l2;
406
+ const qx = px * l2 - ux * along;
407
+ const qy = py * l2 - uy * along;
408
+ const qz = pz * l2 - uz * along;
409
+ const x2 = qx * qx + qy * qy + qz * qz;
410
+ const y2 = along * along * l2;
411
+ const z2 = past * past * l2;
412
+ const k = Math.sign(rr) * rr * rr * x2;
413
+ if (Math.sign(past) * a2 * z2 > k) {
414
+ return Math.sqrt(x2 + z2) / l2 - r2;
415
+ }
416
+ if (Math.sign(along) * a2 * y2 < k) {
417
+ return Math.sqrt(x2 + y2) / l2 - r1;
418
+ }
419
+ return (Math.sqrt((x2 * a2) / l2) + along * rr) / l2 - r1;
420
+ }
421
+
422
+ function boxDistance(shape, x, y, z) {
423
+ localPoint(shape, x, y, z, local);
424
+ const round = shape.round;
425
+ const qx = Math.abs(local[0]) - shape.half[0] + round;
426
+ const qy = Math.abs(local[1]) - shape.half[1] + round;
427
+ const qz = Math.abs(local[2]) - shape.half[2] + round;
428
+ const ox = Math.max(qx, 0);
429
+ const oy = Math.max(qy, 0);
430
+ const oz = Math.max(qz, 0);
431
+ const outside = Math.sqrt(ox * ox + oy * oy + oz * oz);
432
+ return outside + Math.min(Math.max(qx, qy, qz), 0) - round;
433
+ }
434
+
435
+ function shapeDistance(shape, x, y, z) {
436
+ switch (shape.type) {
437
+ case SPHERE:
438
+ return sphereDistance(shape, x, y, z);
439
+ case ELLIPSOID:
440
+ return ellipsoidDistance(shape, x, y, z);
441
+ case CAPSULE:
442
+ return capsuleDistance(shape, x, y, z);
443
+ default:
444
+ return boxDistance(shape, x, y, z);
445
+ }
446
+ }
447
+
448
+ //
449
+ // Combining
450
+ //
451
+
452
+ // How much the second of two distances wins at a smooth join, from 0 to 1:
453
+ // the polynomial smooth minimum. `blend` is the width of the join.
454
+ function unionWeight(a, b, blend) {
455
+ if (blend <= 0) {
456
+ return b < a ? 1 : 0;
457
+ }
458
+ return Math.max(0, Math.min(1, 0.5 + (0.5 * (a - b)) / blend));
459
+ }
460
+
461
+ function carveWeight(a, b, blend) {
462
+ if (blend <= 0) {
463
+ return -b > a ? 1 : 0;
464
+ }
465
+ return Math.max(0, Math.min(1, 0.5 - (0.5 * (a + b)) / blend));
466
+ }
467
+
468
+ // How far a point is from the box around a shape or cone; it is no nearer.
469
+ function boxGap(shape, x, y, z) {
470
+ const dx = Math.max(shape.low[0] - x, 0, x - shape.high[0]);
471
+ const dy = Math.max(shape.low[1] - y, 0, y - shape.high[1]);
472
+ const dz = Math.max(shape.low[2] - z, 0, z - shape.high[2]);
473
+ return Math.sqrt(dx * dx + dy * dy + dz * dz);
474
+ }
475
+
476
+ // True when the next shape is another cone of the same tube.
477
+ function continuesGroup(shape, next) {
478
+ return shape.group !== undefined && next !== undefined && next.group === shape.group;
479
+ }
480
+
481
+ // A shape is too far to matter when its box is further than the join it
482
+ // would make with the distance so far.
483
+ function isFar(shape, distance, x, y, z) {
484
+ const gap = boxGap(shape, x, y, z);
485
+ return shape.subtract ? gap >= shape.blend - distance : gap >= distance + shape.blend;
486
+ }
487
+
488
+ // The distance so far joined with a shape at distance `d`: the smooth
489
+ // minimum, or for a carving shape the smooth maximum with `-d`.
490
+ function combine(distance, shape, d) {
491
+ if (shape.subtract) {
492
+ if (distance === Infinity) {
493
+ return distance;
494
+ }
495
+ const t = carveWeight(distance, d, shape.blend);
496
+ return distance + (-d - distance) * t + shape.blend * t * (1 - t);
497
+ }
498
+ if (distance === Infinity) {
499
+ return d;
500
+ }
501
+ const t = unionWeight(distance, d, shape.blend);
502
+ return distance + (d - distance) * t - shape.blend * t * (1 - t);
503
+ }
504
+
505
+ // The distance to the blob. Far shapes are skipped, unless `all` is set for
506
+ // a list already cut down to the shapes near the point.
507
+ export function blobDistance(shapes, x, y, z, all = false) {
508
+ let distance = Infinity;
509
+ let piece = Infinity;
510
+ for (let index = 0; index < shapes.length; index++) {
511
+ const shape = shapes[index];
512
+ if (all || distance === Infinity || !isFar(shape, distance, x, y, z)) {
513
+ piece = Math.min(piece, shapeDistance(shape, x, y, z));
514
+ }
515
+ if (continuesGroup(shape, shapes[index + 1]) || piece === Infinity) {
516
+ continue;
517
+ }
518
+ distance = combine(distance, shape, piece);
519
+ piece = Infinity;
520
+ }
521
+ return distance;
522
+ }
523
+
524
+ // The palette index of the shape that wins at a point when every join is
525
+ // hard: the nearest adding shape, or a carving shape where it cuts deeper.
526
+ // Shapes without a color are index 0, the part's color, and a carving shape
527
+ // without one keeps the index that was there.
528
+ function colorIndexAt(shapes, x, y, z) {
529
+ let distance = Infinity;
530
+ let winner = 0;
531
+ for (const shape of shapes) {
532
+ const d = shapeDistance(shape, x, y, z);
533
+ if (!shape.subtract) {
534
+ if (d < distance) {
535
+ distance = d;
536
+ winner = shape.colorIndex;
537
+ }
538
+ } else if (distance !== Infinity && -d > distance) {
539
+ distance = -d;
540
+ winner = shape.colorIndex >= 0 ? shape.colorIndex : winner;
541
+ }
542
+ }
543
+ return winner;
544
+ }
545
+
546
+ // With `colorBlend`, the color at a point mixed the way the distances are,
547
+ // fading from one shape's color to the next over `width` meters.
548
+ function blendedColor(shapes, palette, width, x, y, z, out) {
549
+ let distance = Infinity;
550
+ let piece = Infinity;
551
+ out.copy(palette[0]);
552
+ for (let index = 0; index < shapes.length; index++) {
553
+ const shape = shapes[index];
554
+ piece = Math.min(piece, shapeDistance(shape, x, y, z));
555
+ if (continuesGroup(shape, shapes[index + 1])) {
556
+ continue;
557
+ }
558
+ const color = shape.colorIndex >= 0 ? palette[shape.colorIndex] : null;
559
+ if (shape.subtract) {
560
+ if (distance !== Infinity && color) {
561
+ out.lerp(color, carveWeight(distance, piece, width));
562
+ }
563
+ } else if (distance === Infinity) {
564
+ out.copy(color);
565
+ } else {
566
+ out.lerp(color, unionWeight(distance, piece, width));
567
+ }
568
+ distance = combine(distance, shape, piece);
569
+ piece = Infinity;
570
+ }
571
+ return out;
572
+ }
573
+
574
+ //
575
+ // Sampling
576
+ //
577
+
578
+ // A grid of points around every shape that adds, with room for the blend to
579
+ // swell the surface and two cells to spare, `resolution` cells along its
580
+ // longest side. Cells are never smaller than `smallest`, a couple of pixels
581
+ // on screen, unless the blob would have fewer than MIN_RESOLUTION.
582
+ function makeGrid(shapes, resolution, smallest) {
583
+ const low = [Infinity, Infinity, Infinity];
584
+ const high = [-Infinity, -Infinity, -Infinity];
585
+ for (const shape of shapes) {
586
+ if (shape.subtract) {
587
+ continue;
588
+ }
589
+ for (let i = 0; i < 3; i++) {
590
+ low[i] = Math.min(low[i], shape.low[i] - shape.blend * 0.5);
591
+ high[i] = Math.max(high[i], shape.high[i] + shape.blend * 0.5);
592
+ }
593
+ }
594
+ if (!Number.isFinite(low[0])) {
595
+ return null;
596
+ }
597
+ const extent = Math.max(...[0, 1, 2].map((i) => high[i] - low[i]));
598
+ const cell = Math.max(extent / resolution, Math.min(smallest, extent / MIN_RESOLUTION));
599
+ const origin = low.map((value) => value - cell * 2);
600
+ const counts = [0, 1, 2].map((i) => Math.ceil((high[i] - low[i]) / cell) + 5);
601
+ return { origin, cell, counts };
602
+ }
603
+
604
+ // Most of the grid is far from the surface, where only the sign of the
605
+ // distance matters. The grid is walked in blocks of BLOCK points a side; when
606
+ // the distance at a block's middle is more than the block's reach, the
607
+ // surface cannot pass through or next to it, and every point takes that
608
+ // distance. The reach is doubled because a smooth join or an ellipsoid can
609
+ // change a little faster than one unit per meter.
610
+ const BLOCK = 4;
611
+ const NEAR_CELLS = 3;
612
+
613
+ // Returns the distances and, per block, the shapes near it (null for a block
614
+ // far from the surface).
615
+ function sampleGrid(shapes, grid) {
616
+ const [nx, ny, nz] = grid.counts;
617
+ const values = new Float32Array(nx * ny * nz);
618
+ const reach = (Math.sqrt(3) * (BLOCK - 1) * 0.5 + 1) * grid.cell * 2;
619
+ const nearShapes = [];
620
+ for (let bk = 0; bk < nz; bk += BLOCK) {
621
+ for (let bj = 0; bj < ny; bj += BLOCK) {
622
+ for (let bi = 0; bi < nx; bi += BLOCK) {
623
+ nearShapes.push(sampleBlock(shapes, grid, values, bi, bj, bk, reach));
624
+ }
625
+ }
626
+ }
627
+ return { values, nearShapes };
628
+ }
629
+
630
+ // The shapes near a point, from the list for its block.
631
+ function shapesNear(grid, nearShapes, x, y, z) {
632
+ const [nx, ny] = grid.counts;
633
+ const [bx, by] = [Math.ceil(nx / BLOCK), Math.ceil(ny / BLOCK)];
634
+ const block = (value, axis) => Math.floor((value - grid.origin[axis]) / grid.cell / BLOCK);
635
+ return nearShapes[block(x, 0) + bx * (block(y, 1) + by * block(z, 2))];
636
+ }
637
+
638
+ function sampleBlock(shapes, grid, values, bi, bj, bk, reach) {
639
+ const [nx, ny, nz] = grid.counts;
640
+ const [ox, oy, oz] = grid.origin;
641
+ const cell = grid.cell;
642
+ const middle = (BLOCK - 1) * 0.5;
643
+ const far = blobDistance(
644
+ shapes,
645
+ ox + (bi + middle) * cell,
646
+ oy + (bj + middle) * cell,
647
+ oz + (bk + middle) * cell
648
+ );
649
+ if (Math.abs(far) > reach) {
650
+ fillBlock(grid, values, bi, bj, bk, far);
651
+ return null;
652
+ }
653
+
654
+ // Only points within a cell or so of the surface need exact distances;
655
+ // elsewhere only the sign is used, and a shape further away than its
656
+ // blend cannot change the sign. So a shape more than NEAR_CELLS cells
657
+ // plus its blend from the block is left out.
658
+ const low = [ox + bi * cell, oy + bj * cell, oz + bk * cell];
659
+ const high = low.map((value) => value + (BLOCK - 1) * cell);
660
+ const near = shapes.filter((shape) => {
661
+ let gap = 0;
662
+ for (let axis = 0; axis < 3; axis++) {
663
+ const outside = Math.max(shape.low[axis] - high[axis], 0, low[axis] - shape.high[axis]);
664
+ gap += outside * outside;
665
+ }
666
+ return Math.sqrt(gap) < cell * NEAR_CELLS + shape.blend;
667
+ });
668
+ for (let k = bk; k < Math.min(nz, bk + BLOCK); k++) {
669
+ for (let j = bj; j < Math.min(ny, bj + BLOCK); j++) {
670
+ for (let i = bi; i < Math.min(nx, bi + BLOCK); i++) {
671
+ values[i + nx * (j + ny * k)] = blobDistance(
672
+ near,
673
+ ox + i * cell,
674
+ oy + j * cell,
675
+ oz + k * cell,
676
+ true
677
+ );
678
+ }
679
+ }
680
+ }
681
+ return near;
682
+ }
683
+
684
+ function fillBlock(grid, values, bi, bj, bk, value) {
685
+ const [nx, ny, nz] = grid.counts;
686
+ for (let k = bk; k < Math.min(nz, bk + BLOCK); k++) {
687
+ for (let j = bj; j < Math.min(ny, bj + BLOCK); j++) {
688
+ for (let i = bi; i < Math.min(nx, bi + BLOCK); i++) {
689
+ values[i + nx * (j + ny * k)] = value;
690
+ }
691
+ }
692
+ }
693
+ }
694
+
695
+ //
696
+ // Surface nets
697
+ //
698
+
699
+ // The 12 edges of a cell, as pairs of its 8 corners. Corner c sits at
700
+ // (c & 1, (c >> 1) & 1, (c >> 2) & 1).
701
+ const CELL_EDGES = [
702
+ [0, 1],
703
+ [2, 3],
704
+ [4, 5],
705
+ [6, 7],
706
+ [0, 2],
707
+ [1, 3],
708
+ [4, 6],
709
+ [5, 7],
710
+ [0, 4],
711
+ [1, 5],
712
+ [2, 6],
713
+ [3, 7],
714
+ ];
715
+
716
+ // One vertex in each cell whose corners are not all on one side of the
717
+ // surface, at the average of the points where its edges cross it. Returns
718
+ // the positions and, per cell, the index of its vertex or -1.
719
+ function placeVertices(values, grid) {
720
+ const [nx, ny, nz] = grid.counts;
721
+ const cellIndex = new Int32Array((nx - 1) * (ny - 1) * (nz - 1)).fill(-1);
722
+ const positions = [];
723
+ const corner = new Float32Array(8);
724
+ for (let k = 0; k < nz - 1; k++) {
725
+ for (let j = 0; j < ny - 1; j++) {
726
+ for (let i = 0; i < nx - 1; i++) {
727
+ let inside = 0;
728
+ for (let c = 0; c < 8; c++) {
729
+ const value = values[i + (c & 1) + nx * (j + ((c >> 1) & 1) + ny * (k + ((c >> 2) & 1)))];
730
+ corner[c] = value;
731
+ if (value < 0) {
732
+ inside++;
733
+ }
734
+ }
735
+ if (inside === 0 || inside === 8) {
736
+ continue;
737
+ }
738
+ let sx = 0;
739
+ let sy = 0;
740
+ let sz = 0;
741
+ let crossings = 0;
742
+ for (const [a, b] of CELL_EDGES) {
743
+ if (corner[a] < 0 === corner[b] < 0) {
744
+ continue;
745
+ }
746
+ const t = corner[a] / (corner[a] - corner[b]);
747
+ sx += (a & 1) + ((b & 1) - (a & 1)) * t;
748
+ sy += ((a >> 1) & 1) + (((b >> 1) & 1) - ((a >> 1) & 1)) * t;
749
+ sz += ((a >> 2) & 1) + (((b >> 2) & 1) - ((a >> 2) & 1)) * t;
750
+ crossings++;
751
+ }
752
+ cellIndex[i + (nx - 1) * (j + (ny - 1) * k)] = positions.length / 3;
753
+ positions.push(
754
+ grid.origin[0] + (i + sx / crossings) * grid.cell,
755
+ grid.origin[1] + (j + sy / crossings) * grid.cell,
756
+ grid.origin[2] + (k + sz / crossings) * grid.cell
757
+ );
758
+ }
759
+ }
760
+ }
761
+ return { positions, cellIndex };
762
+ }
763
+
764
+ // Every grid edge the surface crosses is shared by four cells, and their
765
+ // four vertices make a quad. Axes u and v follow the edge's axis in x, y, z
766
+ // order, so the quad's corners in u, v order are counter-clockwise seen from
767
+ // the edge's far end; the quad is flipped when the outside is the near end.
768
+ // Each quad is cut into two triangles along its shorter diagonal.
769
+ function joinVertices(values, grid, positions, cellIndex) {
770
+ const [nx, ny, nz] = grid.counts;
771
+ const indices = [];
772
+
773
+ // How far one step along x, y and z moves in the point and cell arrays.
774
+ const pointStep = [1, nx, nx * ny];
775
+ const cellStep = [1, nx - 1, (nx - 1) * (ny - 1)];
776
+ for (let k = 1; k < nz - 1; k++) {
777
+ for (let j = 1; j < ny - 1; j++) {
778
+ for (let i = 1; i < nx - 1; i++) {
779
+ const point = i + nx * (j + ny * k);
780
+ const cell = i + (nx - 1) * (j + (ny - 1) * k);
781
+ const inside = values[point] < 0;
782
+ for (let axis = 0; axis < 3; axis++) {
783
+ if (inside === values[point + pointStep[axis]] < 0) {
784
+ continue;
785
+ }
786
+ const u = cellStep[(axis + 1) % 3];
787
+ const v = cellStep[(axis + 2) % 3];
788
+ const quad = [
789
+ cellIndex[cell - u - v],
790
+ cellIndex[cell - v],
791
+ cellIndex[cell],
792
+ cellIndex[cell - u],
793
+ ];
794
+ if (quad.some((vertex) => vertex < 0)) {
795
+ continue;
796
+ }
797
+ if (!inside) {
798
+ quad.reverse();
799
+ }
800
+ pushQuad(indices, positions, quad);
801
+ }
802
+ }
803
+ }
804
+ }
805
+ return indices;
806
+ }
807
+
808
+ function pushQuad(indices, positions, [a, b, c, d]) {
809
+ const gap = (p, q) =>
810
+ (positions[p * 3] - positions[q * 3]) ** 2 +
811
+ (positions[p * 3 + 1] - positions[q * 3 + 1]) ** 2 +
812
+ (positions[p * 3 + 2] - positions[q * 3 + 2]) ** 2;
813
+ if (gap(a, c) <= gap(b, d)) {
814
+ indices.push(a, b, c, a, c, d);
815
+ } else {
816
+ indices.push(a, b, d, b, c, d);
817
+ }
818
+ }
819
+
820
+ //
821
+ // Finishing
822
+ //
823
+
824
+ // The direction the field grows fastest, which is the surface normal, from
825
+ // the distance `here` at the point and at points a small step `h` along each
826
+ // axis. Returns how fast it grows.
827
+ function gradient(shapes, x, y, z, here, h, out) {
828
+ out[0] = blobDistance(shapes, x + h, y, z, true) - here;
829
+ out[1] = blobDistance(shapes, x, y + h, z, true) - here;
830
+ out[2] = blobDistance(shapes, x, y, z + h, true) - here;
831
+ const length = Math.sqrt(out[0] * out[0] + out[1] * out[1] + out[2] * out[2]);
832
+ if (length > 1e-12) {
833
+ out[0] /= length;
834
+ out[1] /= length;
835
+ out[2] /= length;
836
+ }
837
+ return length / h;
838
+ }
839
+
840
+ // A point near the surface moved onto it along the normal, by at most half
841
+ // a cell so a point near a sharp carved edge stays in its cell, as
842
+ // [x, y, z, normal x, normal y, normal z]. The normal is taken where the
843
+ // point was, less than half a cell away.
844
+ function settlePoint(shapes, grid, nearShapes, x, y, z) {
845
+ const near = shapesNear(grid, nearShapes, x, y, z) ?? shapes;
846
+ const direction = [0, 0, 0];
847
+ const here = blobDistance(near, x, y, z, true);
848
+ const slope = gradient(near, x, y, z, here, grid.cell * 0.1, direction);
849
+ let step = 0;
850
+ if (slope > 1e-6) {
851
+ const limit = grid.cell * 0.5;
852
+ step = Math.max(-limit, Math.min(limit, here / slope));
853
+ }
854
+ return [
855
+ x - direction[0] * step,
856
+ y - direction[1] * step,
857
+ z - direction[2] * step,
858
+ direction[0],
859
+ direction[1],
860
+ direction[2],
861
+ ];
862
+ }
863
+
864
+ // The vertices settled onto the surface, with a normal each.
865
+ function settleVertices(shapes, grid, nearShapes, placed) {
866
+ const positions = [];
867
+ const normals = [];
868
+ for (let v = 0; v < placed.length; v += 3) {
869
+ const point = settlePoint(shapes, grid, nearShapes, placed[v], placed[v + 1], placed[v + 2]);
870
+ positions.push(point[0], point[1], point[2]);
871
+ normals.push(point[3], point[4], point[5]);
872
+ }
873
+ return { positions, normals };
874
+ }
875
+
876
+ //
877
+ // Colors
878
+ //
879
+
880
+ // The colors in use: the part's color first, then each shape color once.
881
+ // Every shape gets `colorIndex` into it, -1 for a carving shape without a
882
+ // color.
883
+ function makePalette(shapes, part) {
884
+ const palette = [new THREE.Color(typeof part.color === 'string' ? part.color : '#c7cfdd')];
885
+ for (const shape of shapes) {
886
+ if (!shape.color) {
887
+ shape.colorIndex = shape.subtract ? -1 : 0;
888
+ continue;
889
+ }
890
+ let index = palette.findIndex((color) => color.equals(shape.color));
891
+ if (index < 0) {
892
+ index = palette.push(shape.color) - 1;
893
+ }
894
+ shape.colorIndex = index;
895
+ }
896
+ return palette;
897
+ }
898
+
899
+ // Each vertex takes the color of the shape that wins there with hard joins,
900
+ // and a triangle whose corners differ is cut along the line where the color
901
+ // changes. Each edge between two colors gets a point on that line, found by
902
+ // halving the edge, and a triangle with three colors also gets a point at
903
+ // its middle. A cut point is made once per color, so the triangles on either
904
+ // side share its position and normal but not its color, and the edge is
905
+ // sharp.
906
+ function splitColors(shapes, grid, nearShapes, surface) {
907
+ const { positions, normals } = surface;
908
+ const count = positions.length / 3;
909
+ const indexAt = (x, y, z) =>
910
+ colorIndexAt(shapesNear(grid, nearShapes, x, y, z) ?? shapes, x, y, z);
911
+ const colors = [];
912
+ for (let v = 0; v < count; v++) {
913
+ colors.push(indexAt(positions[v * 3], positions[v * 3 + 1], positions[v * 3 + 2]));
914
+ }
915
+ const points = new Map();
916
+ const copies = new Map();
917
+ const copyOf = (key, point, color) => {
918
+ const name = `${key}:${color}`;
919
+ if (!copies.has(name)) {
920
+ copies.set(name, positions.length / 3);
921
+ positions.push(point[0], point[1], point[2]);
922
+ normals.push(point[3], point[4], point[5]);
923
+ colors.push(color);
924
+ }
925
+ return copies.get(name);
926
+ };
927
+
928
+ // The point where the color stops being the color at `a`, on the edge a-b.
929
+ const edgePoint = (a, b, color) => {
930
+ const [low, high] = a < b ? [a, b] : [b, a];
931
+ const key = `${low},${high}`;
932
+ if (!points.has(key)) {
933
+ points.set(key, findCut(low, high));
934
+ }
935
+ return copyOf(key, points.get(key), color);
936
+ };
937
+ const findCut = (a, b) => {
938
+ const at = (t) =>
939
+ [0, 1, 2].map(
940
+ (i) => positions[a * 3 + i] + (positions[b * 3 + i] - positions[a * 3 + i]) * t
941
+ );
942
+ let [inside, outside] = [0, 1];
943
+ for (let step = 0; step < 6; step++) {
944
+ const middle = (inside + outside) / 2;
945
+ if (indexAt(...at(middle)) === colors[a]) {
946
+ inside = middle;
947
+ } else {
948
+ outside = middle;
949
+ }
950
+ }
951
+ return settlePoint(shapes, grid, nearShapes, ...at((inside + outside) / 2));
952
+ };
953
+ const middlePoint = (a, b, c, color, key) => {
954
+ const at = [0, 1, 2].map(
955
+ (i) => (positions[a * 3 + i] + positions[b * 3 + i] + positions[c * 3 + i]) / 3
956
+ );
957
+ if (!points.has(key)) {
958
+ points.set(key, settlePoint(shapes, grid, nearShapes, ...at));
959
+ }
960
+ return copyOf(key, points.get(key), color);
961
+ };
962
+ const indices = [];
963
+ const source = surface.indices;
964
+ for (let i = 0; i < source.length; i += 3) {
965
+ const [a, b, c] = [source[i], source[i + 1], source[i + 2]];
966
+ const [ca, cb, cc] = [colors[a], colors[b], colors[c]];
967
+ if (ca === cb && cb === cc) {
968
+ indices.push(a, b, c);
969
+ } else if (ca !== cb && cb !== cc && ca !== cc) {
970
+ const middle = (color) => middlePoint(a, b, c, color, `m${i}`);
971
+ for (const [p, q, r] of [
972
+ [a, b, c],
973
+ [b, c, a],
974
+ [c, a, b],
975
+ ]) {
976
+ const color = colors[p];
977
+ indices.push(p, edgePoint(p, q, color), middle(color));
978
+ indices.push(p, middle(color), edgePoint(r, p, color));
979
+ }
980
+ } else {
981
+ // The corner with its own color first, keeping the winding.
982
+ let [o, p, q] = [a, b, c];
983
+ if (ca === cb) {
984
+ [o, p, q] = [c, a, b];
985
+ } else if (ca === cc) {
986
+ [o, p, q] = [b, c, a];
987
+ }
988
+ const [co, cp] = [colors[o], colors[p]];
989
+ indices.push(o, edgePoint(o, p, co), edgePoint(o, q, co));
990
+ indices.push(edgePoint(o, p, cp), p, q);
991
+ indices.push(edgePoint(o, p, cp), q, edgePoint(o, q, cp));
992
+ }
993
+ }
994
+ return { indices, colors };
995
+ }
996
+
997
+ // The blob's geometry, with vertex colors when any shape has a color
998
+ // (`userData.vertexColors` is then true), or null when no shape adds.
999
+ export function blobGeometry(part) {
1000
+ const shapes = readShapes(part);
1001
+ const resolution = Number.isFinite(part.resolution)
1002
+ ? Math.max(8, Math.min(MAX_RESOLUTION, Math.round(part.resolution)))
1003
+ : DEFAULT_RESOLUTION;
1004
+ const grid = makeGrid(shapes, resolution, smallestCell(part));
1005
+ if (!grid) {
1006
+ return null;
1007
+ }
1008
+ const { values, nearShapes } = sampleGrid(shapes, grid);
1009
+ const placed = placeVertices(values, grid);
1010
+ const indices = joinVertices(values, grid, placed.positions, placed.cellIndex);
1011
+ if (indices.length === 0) {
1012
+ return null;
1013
+ }
1014
+ const surface = { ...settleVertices(shapes, grid, nearShapes, placed.positions), indices };
1015
+ let colors = null;
1016
+ if (shapes.some((shape) => shape.color)) {
1017
+ colors = paint(shapes, grid, nearShapes, surface, part);
1018
+ }
1019
+ const geometry = new THREE.BufferGeometry();
1020
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(surface.positions, 3));
1021
+ geometry.setAttribute('normal', new THREE.Float32BufferAttribute(surface.normals, 3));
1022
+ geometry.setIndex(surface.indices);
1023
+ if (colors) {
1024
+ geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
1025
+ geometry.userData.vertexColors = true;
1026
+ }
1027
+ return geometry;
1028
+ }
1029
+
1030
+ // Vertex colors, three numbers per vertex. Crisp edges cut the surface's
1031
+ // triangles, so `surface.indices` may be replaced.
1032
+ function paint(shapes, grid, nearShapes, surface, part) {
1033
+ const palette = makePalette(shapes, part);
1034
+ const colors = [];
1035
+ if (part.colorBlend > 0) {
1036
+ const color = new THREE.Color();
1037
+ const { positions } = surface;
1038
+ for (let v = 0; v < positions.length; v += 3) {
1039
+ blendedColor(
1040
+ shapes,
1041
+ palette,
1042
+ part.colorBlend,
1043
+ positions[v],
1044
+ positions[v + 1],
1045
+ positions[v + 2],
1046
+ color
1047
+ );
1048
+ colors.push(color.r, color.g, color.b);
1049
+ }
1050
+ return colors;
1051
+ }
1052
+ const split = splitColors(shapes, grid, nearShapes, surface);
1053
+ surface.indices = split.indices;
1054
+ for (const index of split.colors) {
1055
+ colors.push(palette[index].r, palette[index].g, palette[index].b);
1056
+ }
1057
+ return colors;
1058
+ }