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,1148 @@
1
+ // Sculpt strokes: brushes that push and pull a part's finished surface, as in
2
+ // the sculpt mode of a 3d app. See docs/pxmodel-format.md for the fields.
3
+ //
4
+ // The geometry is taken apart into places and corners. A place is a point of
5
+ // the surface; a corner is one of the geometry's own vertices, and several
6
+ // corners share a place where the geometry splits it for a sharp edge or a
7
+ // texture seam. Brushes move places, so every corner at a place moves with it
8
+ // and no cracks open. Before a stroke, the triangles under it are split until
9
+ // their edges are short next to the brush.
10
+ //
11
+ // Splitting puts new places on the flat triangles, and flat triangles shade
12
+ // as facets. So each place also keeps where it was before any brush moved it,
13
+ // and each corner the smooth normal it had there; a corner is shaded with that
14
+ // normal turned by as much as the brushes turned the surface. Where no brush
15
+ // reached, the part shades as it did before. Smooth and flatten make a new
16
+ // surface, whose own normals take over from these.
17
+
18
+ import * as THREE from 'three';
19
+ import { pixelsInPart } from './optimize';
20
+
21
+ const BRUSHES = new Set(['grab', 'inflate', 'smooth', 'flatten', 'pinch', 'crease']);
22
+
23
+ // Refinement stops at this many triangles, and a part takes at most this many
24
+ // strokes.
25
+ const MAX_TRIANGLES = 10000;
26
+ const MAX_STROKES = 64;
27
+
28
+ // Edges under a brush are split until they are this fraction of its radius.
29
+ const EDGE_PER_RADIUS = 1 / 4;
30
+
31
+ // Corners at one place whose normals are within 60 degrees shade as one.
32
+ const SAME_NORMAL = 0.5;
33
+
34
+ const SMOOTH_STEPS = 6;
35
+
36
+ // Corner and place pairs are keyed as one number, low * KEY + high.
37
+ const KEY = 1 << 22;
38
+
39
+ export function hasSculpt(part) {
40
+ return Array.isArray(part.sculpt) && part.sculpt.length > 0;
41
+ }
42
+
43
+ // The part's geometry with its strokes applied, in order. The input is
44
+ // disposed.
45
+ export function sculptGeometry(geometry, part) {
46
+ const steps = strokeSteps(part);
47
+ if (steps.length === 0) {
48
+ return geometry;
49
+ }
50
+ const mesh = takeApart(geometry);
51
+
52
+ // Edges are never split shorter than a game pixel and a half.
53
+ const shortest = pixelsInPart(part, 1.5);
54
+ for (const step of steps) {
55
+ applyStep(mesh, step, shortest);
56
+ }
57
+ const result = putTogether(mesh, geometry);
58
+ geometry.dispose();
59
+ return result;
60
+ }
61
+
62
+ //
63
+ // Strokes
64
+ //
65
+
66
+ // Strength when a stroke leaves it out: meters for inflate and crease (as a
67
+ // fraction of the radius), a fraction of the full effect for the rest.
68
+ const DEFAULT_STRENGTH = {
69
+ grab: 1,
70
+ inflate: 0.25,
71
+ smooth: 0.5,
72
+ flatten: 1,
73
+ pinch: 0.5,
74
+ crease: 0.25,
75
+ };
76
+
77
+ function vector(value) {
78
+ if (!Array.isArray(value) || !value.slice(0, 3).every(Number.isFinite)) {
79
+ return null;
80
+ }
81
+ return [value[0], value[1], value[2]];
82
+ }
83
+
84
+ function readStroke(raw) {
85
+ if (!raw || typeof raw !== 'object' || !BRUSHES.has(raw.brush)) {
86
+ return null;
87
+ }
88
+ const at = vector(raw.at);
89
+ if (!at || !(Number.isFinite(raw.radius) && raw.radius > 0)) {
90
+ return null;
91
+ }
92
+ const { brush, radius } = raw;
93
+ const by = vector(raw.by) ?? [0, 0, 0];
94
+
95
+ // A crease runs along `line`, from `at` to `at + by`.
96
+ const line = [at, at.map((value, axis) => value + by[axis])];
97
+ return { brush, at, radius, strength: strokeStrength(raw), by, line };
98
+ }
99
+
100
+ function strokeStrength({ brush, radius, strength }) {
101
+ if (!Number.isFinite(strength)) {
102
+ const fraction = DEFAULT_STRENGTH[brush];
103
+ return brush === 'inflate' || brush === 'crease' ? fraction * radius : fraction;
104
+ }
105
+ if (brush === 'smooth' || brush === 'flatten' || brush === 'pinch') {
106
+ return Math.max(0, Math.min(1, strength));
107
+ }
108
+ return strength;
109
+ }
110
+
111
+ // Strokes grouped into steps. On a `symmetric: "x"` part a stroke off the
112
+ // middle line comes with its mirror image in the same step. One on the middle
113
+ // line applies once and does not move it sideways; a crease drawn from it
114
+ // sideways is joined with its mirror image into one crease running both ways.
115
+ function strokeSteps(part) {
116
+ const steps = [];
117
+ for (const raw of part.sculpt.slice(0, MAX_STROKES)) {
118
+ const stroke = readStroke(raw);
119
+ if (!stroke) {
120
+ continue;
121
+ }
122
+ if (part.symmetric !== 'x') {
123
+ steps.push([stroke]);
124
+ continue;
125
+ }
126
+ const onMiddle = Math.abs(stroke.at[0]) < 1e-4;
127
+ if (onMiddle) {
128
+ stroke.at[0] = 0;
129
+ }
130
+ const flip = (point) => [-point[0], point[1], point[2]];
131
+ if (onMiddle && stroke.brush === 'crease') {
132
+ stroke.line = [flip(stroke.line[1]), stroke.at, stroke.line[1]];
133
+ }
134
+ if (onMiddle) {
135
+ stroke.by[0] = stroke.brush === 'crease' ? stroke.by[0] : 0;
136
+ steps.push([stroke]);
137
+ continue;
138
+ }
139
+ const mirror = {
140
+ ...stroke,
141
+ at: flip(stroke.at),
142
+ by: flip(stroke.by),
143
+ line: stroke.line.map(flip),
144
+ };
145
+ steps.push([stroke, mirror]);
146
+ }
147
+ return steps;
148
+ }
149
+
150
+ //
151
+ // Places and corners
152
+ //
153
+
154
+ // The working mesh: `positions` and `basePositions` (before any brush) hold
155
+ // three numbers per place; per corner, `cornerPlace`, `cornerNormal` (corners
156
+ // with one normal id shade as one) and each attribute other than position and
157
+ // normal; `baseNormals` holds each normal id's smooth normal before any brush,
158
+ // and `normalPlace` its place; `replaced` is, per place, how far smooth or
159
+ // flatten made a new surface there, 0 to 1; `triangles` holds three corners
160
+ // per triangle, `groups` each triangle's material.
161
+ function takeApart(geometry) {
162
+ if (!geometry.attributes.normal) {
163
+ geometry.computeVertexNormals();
164
+ }
165
+ const position = geometry.attributes.position;
166
+ const normal = geometry.attributes.normal;
167
+ const mesh = {
168
+ positions: [],
169
+ basePositions: [],
170
+ baseNormals: [],
171
+ normalPlace: [],
172
+ replaced: [],
173
+ cornerPlace: [],
174
+ cornerNormal: [],
175
+ normalCount: 0,
176
+ attributes: {},
177
+ triangles: [],
178
+ groups: [],
179
+ };
180
+ for (const [name, attribute] of Object.entries(geometry.attributes)) {
181
+ if (name !== 'position' && name !== 'normal') {
182
+ mesh.attributes[name] = { itemSize: attribute.itemSize, values: [], source: attribute };
183
+ }
184
+ }
185
+ const placeByKey = new Map();
186
+ const normalsAt = [];
187
+ for (let i = 0; i < position.count; i++) {
188
+ const [x, y, z] = [position.getX(i), position.getY(i), position.getZ(i)];
189
+ const key = `${Math.round(x * 1e5)},${Math.round(y * 1e5)},${Math.round(z * 1e5)}`;
190
+ let place = placeByKey.get(key);
191
+ if (place === undefined) {
192
+ place = mesh.positions.length / 3;
193
+ mesh.positions.push(x, y, z);
194
+ mesh.basePositions.push(x, y, z);
195
+ mesh.replaced.push(0);
196
+ placeByKey.set(key, place);
197
+ normalsAt.push([]);
198
+ }
199
+ mesh.cornerPlace.push(place);
200
+
201
+ // A corner joins the shading of another corner at its place when their
202
+ // normals agree, so a sphere's texture seam stays smooth and a box's
203
+ // edges stay sharp.
204
+ const n = [normal.getX(i), normal.getY(i), normal.getZ(i)];
205
+ const match = normalsAt[place].find(
206
+ (entry) => entry.n[0] * n[0] + entry.n[1] * n[1] + entry.n[2] * n[2] > SAME_NORMAL
207
+ );
208
+ if (match) {
209
+ mesh.cornerNormal.push(match.id);
210
+ } else {
211
+ normalsAt[place].push({ id: mesh.normalCount, n });
212
+ const length = Math.hypot(...n) || 1;
213
+ mesh.baseNormals.push(n[0] / length, n[1] / length, n[2] / length);
214
+ mesh.normalPlace.push(place);
215
+ mesh.cornerNormal.push(mesh.normalCount++);
216
+ }
217
+ }
218
+ readAttributes(mesh);
219
+ readTriangles(mesh, geometry);
220
+ return mesh;
221
+ }
222
+
223
+ function readAttributes(mesh) {
224
+ for (const attribute of Object.values(mesh.attributes)) {
225
+ const { source, itemSize, values } = attribute;
226
+ for (let i = 0; i < source.count; i++) {
227
+ for (let k = 0; k < itemSize; k++) {
228
+ values.push(source.getComponent(i, k));
229
+ }
230
+ }
231
+ delete attribute.source;
232
+ }
233
+ }
234
+
235
+ function readTriangles(mesh, geometry) {
236
+ const position = geometry.attributes.position;
237
+ if (geometry.index) {
238
+ mesh.triangles = Array.from(geometry.index.array);
239
+ } else {
240
+ mesh.triangles = Array.from({ length: position.count }, (_, i) => i);
241
+ }
242
+ mesh.triangles.length -= mesh.triangles.length % 3;
243
+ mesh.groups = new Array(mesh.triangles.length / 3).fill(0);
244
+ for (const group of geometry.groups) {
245
+ const end = Math.min(mesh.groups.length, (group.start + group.count) / 3);
246
+ for (let t = group.start / 3; t < end; t++) {
247
+ mesh.groups[t] = group.materialIndex ?? 0;
248
+ }
249
+ }
250
+ }
251
+
252
+ // Normals per normal id (for shading) and per place (for brushes), both of
253
+ // unit length: the base normal, plus how far the area-weighted normal of the
254
+ // surface now has turned from that of the surface before any brush. They are
255
+ // kept until places move or triangles split.
256
+ function updateNormals(mesh) {
257
+ if (mesh.normalsFresh) {
258
+ return;
259
+ }
260
+ mesh.normalsFresh = true;
261
+ if (!mesh.baseSurfaceNormals) {
262
+ mesh.baseSurfaceNormals = surfaceNormals(mesh, mesh.basePositions);
263
+ }
264
+ const now = surfaceNormals(mesh, mesh.positions);
265
+ const before = mesh.baseSurfaceNormals;
266
+ const shading = mesh.baseNormals.map((value, i) => value + now[i] - before[i]);
267
+ normalizeAll(shading);
268
+ for (let id = 0; id < mesh.normalCount; id++) {
269
+ const replaced = mesh.replaced[mesh.normalPlace[id]];
270
+ for (let axis = 0; replaced > 0 && axis < 3; axis++) {
271
+ shading[id * 3 + axis] += (now[id * 3 + axis] - shading[id * 3 + axis]) * replaced;
272
+ }
273
+ }
274
+ normalizeAll(shading);
275
+ const places = new Float64Array(mesh.positions.length);
276
+ mesh.cornerPlace.forEach((place, corner) => {
277
+ const id = mesh.cornerNormal[corner] * 3;
278
+ places[place * 3] += shading[id];
279
+ places[place * 3 + 1] += shading[id + 1];
280
+ places[place * 3 + 2] += shading[id + 2];
281
+ });
282
+ normalizeAll(places);
283
+ mesh.placeNormals = places;
284
+ mesh.shadingNormals = shading;
285
+ }
286
+
287
+ // The area-weighted normal of the surface at each normal id, with places at
288
+ // `positions`.
289
+ function surfaceNormals(mesh, positions) {
290
+ const { triangles, cornerPlace, cornerNormal } = mesh;
291
+ const normals = new Float64Array(mesh.normalCount * 3);
292
+ for (let t = 0; t < triangles.length; t += 3) {
293
+ const a = cornerPlace[triangles[t]] * 3;
294
+ const b = cornerPlace[triangles[t + 1]] * 3;
295
+ const c = cornerPlace[triangles[t + 2]] * 3;
296
+ const ux = positions[b] - positions[a];
297
+ const uy = positions[b + 1] - positions[a + 1];
298
+ const uz = positions[b + 2] - positions[a + 2];
299
+ const vx = positions[c] - positions[a];
300
+ const vy = positions[c + 1] - positions[a + 1];
301
+ const vz = positions[c + 2] - positions[a + 2];
302
+ const nx = uy * vz - uz * vy;
303
+ const ny = uz * vx - ux * vz;
304
+ const nz = ux * vy - uy * vx;
305
+ for (let k = 0; k < 3; k++) {
306
+ const id = cornerNormal[triangles[t + k]] * 3;
307
+ normals[id] += nx;
308
+ normals[id + 1] += ny;
309
+ normals[id + 2] += nz;
310
+ }
311
+ }
312
+ normalizeAll(normals);
313
+ return normals;
314
+ }
315
+
316
+ function normalizeAll(values) {
317
+ for (let i = 0; i < values.length; i += 3) {
318
+ const length =
319
+ Math.sqrt(
320
+ values[i] * values[i] + values[i + 1] * values[i + 1] + values[i + 2] * values[i + 2]
321
+ ) || 1;
322
+ values[i] /= length;
323
+ values[i + 1] /= length;
324
+ values[i + 2] /= length;
325
+ }
326
+ }
327
+
328
+ // Each place's neighbours along triangle edges. An edge inside the surface
329
+ // lists its ends twice, once per triangle. They are kept until triangles
330
+ // split.
331
+ function placeNeighbours(mesh) {
332
+ if (mesh.neighbours) {
333
+ return mesh.neighbours;
334
+ }
335
+ const neighbours = Array.from({ length: mesh.positions.length / 3 }, () => []);
336
+ const { triangles, cornerPlace } = mesh;
337
+ for (let t = 0; t < triangles.length; t += 3) {
338
+ for (let k = 0; k < 3; k++) {
339
+ const a = cornerPlace[triangles[t + k]];
340
+ const b = cornerPlace[triangles[t + ((k + 1) % 3)]];
341
+ neighbours[a].push(b);
342
+ neighbours[b].push(a);
343
+ }
344
+ }
345
+ mesh.neighbours = neighbours;
346
+ return neighbours;
347
+ }
348
+
349
+ //
350
+ // Refinement
351
+ //
352
+
353
+ // Splits every edge longer than `target` whose middle is inside a brush,
354
+ // pass after pass, until none is left or the next pass would go over the
355
+ // triangle limit. Both triangles on an edge split it by the same test, so
356
+ // they share its new middle place.
357
+ function refine(mesh, brushes, target) {
358
+ let check = null;
359
+ for (let pass = 0; pass < 8; pass++) {
360
+ const splits = markSplits(mesh, brushes, target, check);
361
+ if (splits.length === 0 || mesh.groups.length + splits.added > MAX_TRIANGLES) {
362
+ return;
363
+ }
364
+ check = splitTriangles(mesh, splits);
365
+ }
366
+ }
367
+
368
+ // The triangles to split, each as [triangle, bits] with a bit for each edge
369
+ // to split (edge k runs from corner k to corner k + 1), and how many
370
+ // triangles splitting them adds. Only the triangles in `check` are looked at
371
+ // when it is given: after the first pass, a triangle that was not split has
372
+ // no edge left to split.
373
+ function markSplits(mesh, brushes, target, check) {
374
+ const { positions, triangles, cornerPlace } = mesh;
375
+ const splits = [];
376
+ splits.added = 0;
377
+ const count = check ? check.length : triangles.length / 3;
378
+ for (let n = 0; n < count; n++) {
379
+ const t = check ? check[n] : n;
380
+ let bits = 0;
381
+ for (let k = 0; k < 3; k++) {
382
+ const a = cornerPlace[triangles[t * 3 + k]] * 3;
383
+ const b = cornerPlace[triangles[t * 3 + ((k + 1) % 3)]] * 3;
384
+ const dx = positions[b] - positions[a];
385
+ const dy = positions[b + 1] - positions[a + 1];
386
+ const dz = positions[b + 2] - positions[a + 2];
387
+ const length = Math.sqrt(dx * dx + dy * dy + dz * dz);
388
+ if (length <= target) {
389
+ continue;
390
+ }
391
+ const x = positions[a] + dx / 2;
392
+ const y = positions[a + 1] + dy / 2;
393
+ const z = positions[a + 2] + dz / 2;
394
+ for (const brush of brushes) {
395
+ if (brush.distance(x, y, z) < brush.radius + length / 2) {
396
+ bits |= 1 << k;
397
+ splits.added++;
398
+ break;
399
+ }
400
+ }
401
+ }
402
+ if (bits) {
403
+ splits.push([t, bits]);
404
+ }
405
+ }
406
+ return splits;
407
+ }
408
+
409
+ // One pass of splits: a triangle with one split edge becomes two, with two
410
+ // becomes three, with three becomes four. The first new triangle takes the
411
+ // old one's slot and the rest go on the end. Returns the new triangles.
412
+ function splitTriangles(mesh, splits) {
413
+ const middles = { places: new Map(), corners: new Map(), normals: new Map() };
414
+ const { triangles, groups } = mesh;
415
+ const made = [];
416
+ mesh.normalsFresh = false;
417
+ mesh.baseSurfaceNormals = null;
418
+ mesh.neighbours = null;
419
+ mesh.placeTriangles = null;
420
+ for (const [t, bits] of splits) {
421
+ const corners = [triangles[t * 3], triangles[t * 3 + 1], triangles[t * 3 + 2]];
422
+ const split = [0, 1, 2].map((k) => (bits >> k) & 1);
423
+ const count = split[0] + split[1] + split[2];
424
+ const group = groups[t];
425
+ let slot = t;
426
+ const emit = (a, b, c) => {
427
+ if (slot < 0) {
428
+ slot = groups.length;
429
+ triangles.push(0, 0, 0);
430
+ groups.push(group);
431
+ }
432
+ triangles[slot * 3] = a;
433
+ triangles[slot * 3 + 1] = b;
434
+ triangles[slot * 3 + 2] = c;
435
+ made.push(slot);
436
+ slot = -1;
437
+ };
438
+
439
+ // Turn the corners so the pattern starts at corner 0: for one split,
440
+ // edge 0-1 is split; for two, edge 2-0 is the one left whole.
441
+ let turn = 0;
442
+ if (count === 1) {
443
+ turn = split.indexOf(1);
444
+ } else if (count === 2) {
445
+ turn = (split.indexOf(0) + 1) % 3;
446
+ }
447
+ const [a, b, c] = [0, 1, 2].map((k) => corners[(k + turn) % 3]);
448
+ const ab = middleCorner(mesh, middles, a, b);
449
+ if (count === 1) {
450
+ emit(a, ab, c);
451
+ emit(ab, b, c);
452
+ continue;
453
+ }
454
+ const bc = middleCorner(mesh, middles, b, c);
455
+ if (count === 2) {
456
+ emit(ab, b, bc);
457
+ emit(a, ab, bc);
458
+ emit(a, bc, c);
459
+ continue;
460
+ }
461
+ const ca = middleCorner(mesh, middles, c, a);
462
+ emit(a, ab, ca);
463
+ emit(ab, b, bc);
464
+ emit(ca, bc, c);
465
+ emit(ab, bc, ca);
466
+ }
467
+ return made;
468
+ }
469
+
470
+ function pairKey(a, b) {
471
+ return a < b ? a * KEY + b : b * KEY + a;
472
+ }
473
+
474
+ // The corner halfway between corners a and b, made once per pair. Its
475
+ // attributes are the average of theirs.
476
+ function middleCorner(mesh, middles, a, b) {
477
+ const key = pairKey(a, b);
478
+ const known = middles.corners.get(key);
479
+ if (known !== undefined) {
480
+ return known;
481
+ }
482
+ const corner = mesh.cornerPlace.length;
483
+ mesh.cornerPlace.push(middlePlace(mesh, middles, a, b));
484
+ const normalKey = pairKey(mesh.cornerNormal[a], mesh.cornerNormal[b]);
485
+ let normal = middles.normals.get(normalKey);
486
+ if (normal === undefined) {
487
+ normal = mesh.cornerNormal[a];
488
+ if (mesh.cornerNormal[b] !== normal) {
489
+ normal = mesh.normalCount++;
490
+ mesh.normalPlace.push(mesh.cornerPlace[corner]);
491
+ addMiddleNormal(mesh.baseNormals, mesh.cornerNormal[a], mesh.cornerNormal[b]);
492
+ }
493
+ middles.normals.set(normalKey, normal);
494
+ }
495
+ mesh.cornerNormal.push(normal);
496
+ for (const { itemSize, values } of Object.values(mesh.attributes)) {
497
+ for (let k = 0; k < itemSize; k++) {
498
+ values.push((values[a * itemSize + k] + values[b * itemSize + k]) / 2);
499
+ }
500
+ }
501
+ middles.corners.set(key, corner);
502
+ return corner;
503
+ }
504
+
505
+ function addMiddleNormal(normals, a, b) {
506
+ const n = [0, 1, 2].map((axis) => normals[a * 3 + axis] + normals[b * 3 + axis]);
507
+ const length = Math.sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) || 1;
508
+ normals.push(n[0] / length, n[1] / length, n[2] / length);
509
+ }
510
+
511
+ // The place halfway between the places of corners a and b, now and before
512
+ // any brush.
513
+ function middlePlace(mesh, middles, a, b) {
514
+ const p = mesh.cornerPlace[a];
515
+ const q = mesh.cornerPlace[b];
516
+ const key = pairKey(p, q);
517
+ const known = middles.places.get(key);
518
+ if (known !== undefined) {
519
+ return known;
520
+ }
521
+ const { positions, basePositions } = mesh;
522
+ const place = positions.length / 3;
523
+ for (let axis = 0; axis < 3; axis++) {
524
+ positions.push((positions[p * 3 + axis] + positions[q * 3 + axis]) / 2);
525
+ basePositions.push((basePositions[p * 3 + axis] + basePositions[q * 3 + axis]) / 2);
526
+ }
527
+ mesh.replaced.push((mesh.replaced[p] + mesh.replaced[q]) / 2);
528
+ middles.places.set(key, place);
529
+ return place;
530
+ }
531
+
532
+ //
533
+ // Applying a step
534
+ //
535
+
536
+ // A brush's shape on the surface: a ball around `center`, or for a crease a
537
+ // tube around a line through `points`. `distance(x, y, z)` measures a point
538
+ // from it.
539
+ function ballShape(center, radius) {
540
+ const [cx, cy, cz] = center;
541
+ return {
542
+ center,
543
+ radius,
544
+ distance: (x, y, z) =>
545
+ Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy) + (z - cz) * (z - cz)),
546
+ };
547
+ }
548
+
549
+ function lineShape(points, radius) {
550
+ const nearest = (point) => {
551
+ let best = points[0];
552
+ let bestDistance = Infinity;
553
+ for (let i = 0; i + 1 < points.length; i++) {
554
+ const candidate = nearestOnLine(point, points[i], points[i + 1]);
555
+ const d = distanceBetween(point, candidate);
556
+ if (d < bestDistance) {
557
+ bestDistance = d;
558
+ best = candidate;
559
+ }
560
+ }
561
+ return best;
562
+ };
563
+ return {
564
+ center: points[0],
565
+ radius,
566
+ nearest,
567
+ distance: (x, y, z) => distanceBetween([x, y, z], nearest([x, y, z])),
568
+ };
569
+ }
570
+
571
+ function distanceBetween(a, b) {
572
+ const dx = a[0] - b[0];
573
+ const dy = a[1] - b[1];
574
+ const dz = a[2] - b[2];
575
+ return Math.sqrt(dx * dx + dy * dy + dz * dz);
576
+ }
577
+
578
+ function nearestOnLine(point, from, to) {
579
+ const d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
580
+ const lengthSquared = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
581
+ let t = 0;
582
+ if (lengthSquared > 0) {
583
+ t =
584
+ ((point[0] - from[0]) * d[0] + (point[1] - from[1]) * d[1] + (point[2] - from[2]) * d[2]) /
585
+ lengthSquared;
586
+ t = Math.max(0, Math.min(1, t));
587
+ }
588
+ return [from[0] + d[0] * t, from[1] + d[1] * t, from[2] + d[2] * t];
589
+ }
590
+
591
+ // The point of the surface nearest `point`, and how far it is. A triangle
592
+ // whose corners are all further than the best distance found plus its
593
+ // longest edge cannot hold a nearer point, and is skipped.
594
+ function nearestOnSurface(mesh, point) {
595
+ const { positions, triangles, cornerPlace } = mesh;
596
+ const triangle = new THREE.Triangle();
597
+ const target = new THREE.Vector3(...point);
598
+ const found = new THREE.Vector3();
599
+ const best = new THREE.Vector3();
600
+ let bestDistance = Infinity;
601
+ const [px, py, pz] = point;
602
+ for (let t = 0; t < triangles.length; t += 3) {
603
+ const a = cornerPlace[triangles[t]] * 3;
604
+ const b = cornerPlace[triangles[t + 1]] * 3;
605
+ const c = cornerPlace[triangles[t + 2]] * 3;
606
+ const dx = positions[a] - px;
607
+ const dy = positions[a + 1] - py;
608
+ const dz = positions[a + 2] - pz;
609
+ const toCorner = Math.sqrt(dx * dx + dy * dy + dz * dz);
610
+ const ex = positions[b] - positions[a];
611
+ const ey = positions[b + 1] - positions[a + 1];
612
+ const ez = positions[b + 2] - positions[a + 2];
613
+ const fx = positions[c] - positions[a];
614
+ const fy = positions[c + 1] - positions[a + 1];
615
+ const fz = positions[c + 2] - positions[a + 2];
616
+ const reach = Math.sqrt(Math.max(ex * ex + ey * ey + ez * ez, fx * fx + fy * fy + fz * fz));
617
+ if (toCorner - reach > bestDistance) {
618
+ continue;
619
+ }
620
+ triangle.a.set(positions[a], positions[a + 1], positions[a + 2]);
621
+ triangle.b.set(positions[b], positions[b + 1], positions[b + 2]);
622
+ triangle.c.set(positions[c], positions[c + 1], positions[c + 2]);
623
+ triangle.closestPointToPoint(target, found);
624
+ const d = found.distanceTo(target);
625
+ if (d < bestDistance) {
626
+ bestDistance = d;
627
+ best.copy(found);
628
+ }
629
+ }
630
+ return { point: best.toArray(), distance: bestDistance };
631
+ }
632
+
633
+ // The stroke's shape, with `at` (and a crease's end) moved onto the surface,
634
+ // or null when `at` is further than the radius from it.
635
+ function strokeShape(mesh, stroke) {
636
+ const start = nearestOnSurface(mesh, stroke.at);
637
+ if (start.distance > stroke.radius) {
638
+ return null;
639
+ }
640
+ if (stroke.brush !== 'crease') {
641
+ return ballShape(start.point, stroke.radius);
642
+ }
643
+
644
+ // A straight line would sink inside a curved surface, so the crease runs
645
+ // through points along it, each moved onto the surface.
646
+ const points = [nearestOnSurface(mesh, stroke.line[0]).point];
647
+ for (let n = 0; n + 1 < stroke.line.length; n++) {
648
+ const [from, to] = [stroke.line[n], stroke.line[n + 1]];
649
+ const length = Math.hypot(to[0] - from[0], to[1] - from[1], to[2] - from[2]);
650
+ const count = Math.max(1, Math.min(32, Math.ceil(length / (stroke.radius / 2))));
651
+ for (let i = 1; i <= count; i++) {
652
+ const along = from.map((value, axis) => value + ((to[axis] - value) * i) / count);
653
+ points.push(nearestOnSurface(mesh, along).point);
654
+ }
655
+ }
656
+ return lineShape(points, stroke.radius);
657
+ }
658
+
659
+ // Refines the surface under every stroke of the step, then applies them in
660
+ // turn. A grab stretches the surface it moves, so the stretched part is
661
+ // refined again.
662
+ function applyStep(mesh, step, shortest) {
663
+ const smallest = Math.min(...step.map((stroke) => stroke.radius));
664
+ const target = Math.max(smallest * EDGE_PER_RADIUS, shortest);
665
+ const strokes = step
666
+ .map((stroke) => ({ stroke, shape: strokeShape(mesh, stroke) }))
667
+ .filter(({ shape }) => shape);
668
+ if (strokes.length === 0) {
669
+ return;
670
+ }
671
+ refine(
672
+ mesh,
673
+ strokes.map(({ shape }) => shape),
674
+ target
675
+ );
676
+ const neighbours = placeNeighbours(mesh);
677
+ const moved = [];
678
+ for (const { stroke, shape } of strokes) {
679
+ shape.edge = target;
680
+ if (stroke.brush !== 'grab') {
681
+ updateNormals(mesh);
682
+ }
683
+ const weights = brushWeights(mesh, neighbours, shape);
684
+ BRUSH_ACTIONS[stroke.brush](mesh, weights, stroke, shape, neighbours);
685
+ if (stroke.brush === 'grab') {
686
+ const end = shape.center.map((value, axis) => value + stroke.by[axis] * stroke.strength);
687
+ moved.push(lineShape([shape.center, end], stroke.radius));
688
+ }
689
+ }
690
+ if (moved.length > 0) {
691
+ refine(mesh, moved, target);
692
+ }
693
+ }
694
+
695
+ // How much each place under the brush is moved, from 1 at the middle to 0 at
696
+ // the radius: a smoothstep of the distance, the usual "smooth" brush falloff.
697
+ // Only places joined to the place nearest the middle through other places
698
+ // under the brush are counted, so a brush does not reach through to another
699
+ // piece.
700
+ function brushWeights(mesh, neighbours, shape) {
701
+ const { positions } = mesh;
702
+ const [cx, cy, cz] = shape.center;
703
+ let start = -1;
704
+ let nearest = Infinity;
705
+ for (let i = 0; i < positions.length; i += 3) {
706
+ const dx = positions[i] - cx;
707
+ const dy = positions[i + 1] - cy;
708
+ const dz = positions[i + 2] - cz;
709
+ const d = dx * dx + dy * dy + dz * dz;
710
+ if (d < nearest) {
711
+ nearest = d;
712
+ start = i / 3;
713
+ }
714
+ }
715
+ const weights = new Map();
716
+ const seen = new Set([start]);
717
+ const queue = [start];
718
+ while (queue.length > 0) {
719
+ const place = queue.pop();
720
+ const d = shape.distance(
721
+ positions[place * 3],
722
+ positions[place * 3 + 1],
723
+ positions[place * 3 + 2]
724
+ );
725
+ if (d >= shape.radius) {
726
+ continue;
727
+ }
728
+ const t = 1 - d / shape.radius;
729
+ weights.set(place, t * t * (3 - 2 * t));
730
+ for (const next of neighbours[place]) {
731
+ if (!seen.has(next)) {
732
+ seen.add(next);
733
+ queue.push(next);
734
+ }
735
+ }
736
+ }
737
+ return weights;
738
+ }
739
+
740
+ //
741
+ // Moving places
742
+ //
743
+
744
+ // Makes the moves. A move can turn a triangle over where the surface is
745
+ // tightly curved, as at the bottom of a groove; the moves of that triangle's
746
+ // places are then halved, up to three times, and after that taken back.
747
+ // Taking a move back can turn over a neighbour, so this repeats until no
748
+ // triangle is turned; with every move taken back, none is.
749
+ //
750
+ // A triangle also counts as turned when it faces away from the surface at its
751
+ // corners, as the triangles around them now face: a crumple. With `small`, the
752
+ // moves are small next to the surface's shape (all brushes but grab), and it
753
+ // counts as turned when it faces away from its corners' normals from before
754
+ // the moves: an overhang in a groove.
755
+ function moveAll(mesh, moves, small = true) {
756
+ const facing = small ? mesh.placeNormals : null;
757
+ mesh.normalsFresh = false;
758
+ const around = placeTriangles(mesh);
759
+ const before = normalsAround(mesh, moves, around);
760
+
761
+ // How much of each move is made.
762
+ const share = new Map();
763
+ for (const [place, move] of moves) {
764
+ share.set(place, 0);
765
+ shareMove(mesh, place, move, share, 1);
766
+ }
767
+ for (let attempt = 0; ; attempt++) {
768
+ let changed = false;
769
+ for (const place of turnedPlaces(mesh, before, around, facing)) {
770
+ const move = moves.get(place);
771
+ if (move && share.get(place) > 0) {
772
+ shareMove(mesh, place, move, share, attempt < 3 ? share.get(place) / 2 : 0);
773
+ changed = true;
774
+ }
775
+ }
776
+ if (!changed) {
777
+ return;
778
+ }
779
+ }
780
+ }
781
+
782
+ // The normal of every triangle with a corner at a moving place.
783
+ function normalsAround(mesh, moves, around) {
784
+ const before = new Map();
785
+ for (const place of moves.keys()) {
786
+ for (const triangle of around[place]) {
787
+ if (!before.has(triangle)) {
788
+ before.set(triangle, triangleNormal(mesh, triangle));
789
+ }
790
+ }
791
+ }
792
+ return before;
793
+ }
794
+
795
+ // Sets the place to `next` of its move from where it started.
796
+ function shareMove(mesh, place, move, share, next) {
797
+ for (let axis = 0; axis < 3; axis++) {
798
+ mesh.positions[place * 3 + axis] += move[axis] * (next - share.get(place));
799
+ }
800
+ share.set(place, next);
801
+ }
802
+
803
+ // The corners of the triangles, of those in `before`, that are now turned.
804
+ function turnedPlaces(mesh, before, around, facing) {
805
+ const turned = new Set();
806
+ const surface = surfaceAround(mesh, around);
807
+ const facingBefore = (place) => placeVector(facing, place);
808
+ for (const [triangle, a] of before) {
809
+ const b = triangleNormal(mesh, triangle);
810
+ if (
811
+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2] < 0 ||
812
+ facesAway(mesh, triangle, b, surface) ||
813
+ (facing && facesAway(mesh, triangle, b, facingBefore))
814
+ ) {
815
+ for (let k = 0; k < 3; k++) {
816
+ turned.add(mesh.cornerPlace[mesh.triangles[triangle * 3 + k]]);
817
+ }
818
+ }
819
+ }
820
+ return turned;
821
+ }
822
+
823
+ // Whether a triangle's `normal` points against the sum of `normalAt` its
824
+ // three corners' places.
825
+ function facesAway(mesh, triangle, normal, normalAt) {
826
+ let dot = 0;
827
+ for (let k = 0; k < 3; k++) {
828
+ const n = normalAt(mesh.cornerPlace[mesh.triangles[triangle * 3 + k]]);
829
+ dot += normal[0] * n[0] + normal[1] * n[1] + normal[2] * n[2];
830
+ }
831
+ return dot < 0;
832
+ }
833
+
834
+ function placeVector(values, place) {
835
+ return [values[place * 3], values[place * 3 + 1], values[place * 3 + 2]];
836
+ }
837
+
838
+ // The unit normal at a place from the triangles around it as they are now,
839
+ // worked out when first asked for.
840
+ function surfaceAround(mesh, around) {
841
+ const known = new Map();
842
+ return (place) => {
843
+ let n = known.get(place);
844
+ if (!n) {
845
+ n = [0, 0, 0];
846
+ for (const triangle of around[place]) {
847
+ const face = triangleNormal(mesh, triangle);
848
+ n[0] += face[0];
849
+ n[1] += face[1];
850
+ n[2] += face[2];
851
+ }
852
+ const length = Math.hypot(...n) || 1;
853
+ n = n.map((value) => value / length);
854
+ known.set(place, n);
855
+ }
856
+ return n;
857
+ };
858
+ }
859
+
860
+ // The triangles each place is a corner of. They are kept until triangles
861
+ // split.
862
+ function placeTriangles(mesh) {
863
+ if (mesh.placeTriangles) {
864
+ return mesh.placeTriangles;
865
+ }
866
+ const around = Array.from({ length: mesh.positions.length / 3 }, () => []);
867
+ for (let t = 0; t < mesh.triangles.length; t++) {
868
+ around[mesh.cornerPlace[mesh.triangles[t]]].push(Math.floor(t / 3));
869
+ }
870
+ mesh.placeTriangles = around;
871
+ return around;
872
+ }
873
+
874
+ // A triangle's normal, as long as twice its area.
875
+ function triangleNormal(mesh, triangle) {
876
+ const { positions, triangles, cornerPlace } = mesh;
877
+ const a = cornerPlace[triangles[triangle * 3]] * 3;
878
+ const b = cornerPlace[triangles[triangle * 3 + 1]] * 3;
879
+ const c = cornerPlace[triangles[triangle * 3 + 2]] * 3;
880
+ const ux = positions[b] - positions[a];
881
+ const uy = positions[b + 1] - positions[a + 1];
882
+ const uz = positions[b + 2] - positions[a + 2];
883
+ const vx = positions[c] - positions[a];
884
+ const vy = positions[c + 1] - positions[a + 1];
885
+ const vz = positions[c + 2] - positions[a + 2];
886
+ return [uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx];
887
+ }
888
+
889
+ function normalAt(mesh, place) {
890
+ return placeVector(mesh.placeNormals, place);
891
+ }
892
+
893
+ function positionAt(mesh, place) {
894
+ return placeVector(mesh.positions, place);
895
+ }
896
+
897
+ //
898
+ // Brushes
899
+ //
900
+
901
+ // Each brush works out every move from the surface as it was before the
902
+ // stroke, then makes them.
903
+ const BRUSH_ACTIONS = { grab, inflate, smooth, flatten, pinch, crease };
904
+
905
+ // Moves the surface by `by`.
906
+ function grab(mesh, weights, stroke) {
907
+ const moves = new Map();
908
+ for (const [place, weight] of weights) {
909
+ moves.set(
910
+ place,
911
+ stroke.by.map((value) => value * stroke.strength * weight)
912
+ );
913
+ }
914
+ moveAll(mesh, moves, false);
915
+ }
916
+
917
+ // Pushes the surface out along its normals by `strength` meters.
918
+ function inflate(mesh, weights, stroke) {
919
+ const moves = new Map();
920
+ for (const [place, weight] of weights) {
921
+ moves.set(
922
+ place,
923
+ normalAt(mesh, place).map((value) => value * stroke.strength * weight)
924
+ );
925
+ }
926
+ moveAll(mesh, moves);
927
+ }
928
+
929
+ // Moves each place toward the average of the surface around it, a few times
930
+ // over. The places under the brush are sorted into cubes the size of the
931
+ // edges the brush refined to, and a place moves toward the middles of the
932
+ // cubes around it, weighted by distance, so the result does not depend on how
933
+ // the triangles happen to be laid out. Cubes facing away (the other side of a
934
+ // thin piece) are left out. Only the move along the place's normal is made:
935
+ // it flattens bumps and rounds ridges, where a move along the surface would
936
+ // only slide places about. At full strength a step goes 0.8 of the way.
937
+ function smooth(mesh, weights, stroke, shape) {
938
+ const size = shape.edge;
939
+ const reach = size * 2;
940
+ const { positions, placeNormals } = mesh;
941
+ for (let step = 0; step < SMOOTH_STEPS; step++) {
942
+ const cells = cubeSums(mesh, weights, size);
943
+ const moves = new Map();
944
+ for (const [place, weight] of weights) {
945
+ const here = placeVector(positions, place);
946
+ const n = placeVector(placeNormals, place);
947
+ const [i, j, k] = here.map((value) => Math.floor(value / size));
948
+ const sum = [0, 0, 0];
949
+ let total = 0;
950
+ for (let di = -1; di <= 1; di++) {
951
+ for (let dj = -1; dj <= 1; dj++) {
952
+ for (let dk = -1; dk <= 1; dk++) {
953
+ const cell = cells.get(cubeKey(i + di, j + dj, k + dk));
954
+ const w = cell ? cubeWeight(cell, here, n, reach) : 0;
955
+ for (let axis = 0; w > 0 && axis < 3; axis++) {
956
+ sum[axis] += (cell[axis] / cell[3]) * w;
957
+ }
958
+ total += w;
959
+ }
960
+ }
961
+ }
962
+ if (total === 0) {
963
+ continue;
964
+ }
965
+ const toward = sum.map((value, axis) => value / total - here[axis]);
966
+ const out =
967
+ (toward[0] * n[0] + toward[1] * n[1] + toward[2] * n[2]) * 0.8 * stroke.strength * weight;
968
+ moves.set(place, [n[0] * out, n[1] * out, n[2] * out]);
969
+ }
970
+ moveAll(mesh, moves);
971
+ }
972
+ markReplaced(mesh, weights);
973
+ }
974
+
975
+ // How much a cube counts toward the average at `here`: nothing when it faces
976
+ // away or its middle is out of reach, and less the further its middle is.
977
+ function cubeWeight(cell, here, n, reach) {
978
+ if (cell[4] * n[0] + cell[5] * n[1] + cell[6] * n[2] <= 0) {
979
+ return 0;
980
+ }
981
+ const d = Math.hypot(...[0, 1, 2].map((axis) => cell[axis] / cell[3] - here[axis]));
982
+ return d < reach ? (1 - (d / reach) ** 2) ** 2 : 0;
983
+ }
984
+
985
+ // Per cube: the sums of its places' positions, their count, and the sum of
986
+ // their normals.
987
+ function cubeSums(mesh, weights, size) {
988
+ const { positions, placeNormals } = mesh;
989
+ const cells = new Map();
990
+ for (const place of weights.keys()) {
991
+ const at = place * 3;
992
+ const key = cubeKey(
993
+ Math.floor(positions[at] / size),
994
+ Math.floor(positions[at + 1] / size),
995
+ Math.floor(positions[at + 2] / size)
996
+ );
997
+ let cell = cells.get(key);
998
+ if (!cell) {
999
+ cell = [0, 0, 0, 0, 0, 0, 0];
1000
+ cells.set(key, cell);
1001
+ }
1002
+ for (let axis = 0; axis < 3; axis++) {
1003
+ cell[axis] += positions[at + axis];
1004
+ cell[4 + axis] += placeNormals[at + axis];
1005
+ }
1006
+ cell[3] += 1;
1007
+ }
1008
+ return cells;
1009
+ }
1010
+
1011
+ // A cube's three whole-number coordinates as one number.
1012
+ function cubeKey(i, j, k) {
1013
+ return ((i + 2048) * 4096 + (j + 2048)) * 4096 + (k + 2048);
1014
+ }
1015
+
1016
+ function markReplaced(mesh, weights) {
1017
+ for (const [place, weight] of weights) {
1018
+ mesh.replaced[place] = Math.max(mesh.replaced[place], weight);
1019
+ }
1020
+ }
1021
+
1022
+ // Pulls the surface toward the plane through the weighted middle of the
1023
+ // places under the brush, facing their weighted average normal.
1024
+ function flatten(mesh, weights, stroke) {
1025
+ const middle = [0, 0, 0];
1026
+ const facing = [0, 0, 0];
1027
+ let total = 0;
1028
+ for (const [place, weight] of weights) {
1029
+ const p = positionAt(mesh, place);
1030
+ const n = normalAt(mesh, place);
1031
+ for (let axis = 0; axis < 3; axis++) {
1032
+ middle[axis] += p[axis] * weight;
1033
+ facing[axis] += n[axis] * weight;
1034
+ }
1035
+ total += weight;
1036
+ }
1037
+ const length = Math.hypot(...facing);
1038
+ if (total === 0 || length === 0) {
1039
+ return;
1040
+ }
1041
+ const plane = middle.map((value) => value / total);
1042
+ const n = facing.map((value) => value / length);
1043
+ const moves = new Map();
1044
+ for (const [place, weight] of weights) {
1045
+ const p = positionAt(mesh, place);
1046
+ const height = (p[0] - plane[0]) * n[0] + (p[1] - plane[1]) * n[1] + (p[2] - plane[2]) * n[2];
1047
+ moves.set(
1048
+ place,
1049
+ n.map((value) => -value * height * stroke.strength * weight)
1050
+ );
1051
+ }
1052
+ moveAll(mesh, moves);
1053
+ markReplaced(mesh, weights);
1054
+ }
1055
+
1056
+ // The part of a move that runs along the surface at a place.
1057
+ function alongSurface(mesh, place, move) {
1058
+ const n = normalAt(mesh, place);
1059
+ const out = move[0] * n[0] + move[1] * n[1] + move[2] * n[2];
1060
+ return move.map((value, axis) => value - out * n[axis]);
1061
+ }
1062
+
1063
+ // Pulls the surface toward the stroke's middle, along the surface.
1064
+ function pinch(mesh, weights, stroke, shape) {
1065
+ const moves = new Map();
1066
+ for (const [place, weight] of weights) {
1067
+ const p = positionAt(mesh, place);
1068
+ const toward = shape.center.map((value, axis) => value - p[axis]);
1069
+ moves.set(
1070
+ place,
1071
+ alongSurface(mesh, place, toward).map((value) => value * stroke.strength * weight)
1072
+ );
1073
+ }
1074
+ moveAll(mesh, moves);
1075
+ }
1076
+
1077
+ // Cuts a groove along the line from `at` to `at + by`: the surface is pushed
1078
+ // in by `strength` meters on the line, less away from it, and drawn toward
1079
+ // the line so the groove's bottom is sharp. A negative strength raises a
1080
+ // ridge.
1081
+ function crease(mesh, weights, stroke, shape) {
1082
+ const moves = new Map();
1083
+ for (const [place, weight] of weights) {
1084
+ const p = positionAt(mesh, place);
1085
+ const t = 1 - shape.distance(...p) / shape.radius;
1086
+ const depth = stroke.strength * t * t;
1087
+ const n = normalAt(mesh, place);
1088
+ const line = shape.nearest(p);
1089
+ const toward = alongSurface(
1090
+ mesh,
1091
+ place,
1092
+ line.map((value, axis) => value - p[axis])
1093
+ );
1094
+ moves.set(
1095
+ place,
1096
+ n.map((value, axis) => -value * depth + toward[axis] * 0.25 * weight)
1097
+ );
1098
+ }
1099
+ moveAll(mesh, moves);
1100
+ }
1101
+
1102
+ //
1103
+ // Back to a geometry
1104
+ //
1105
+
1106
+ // An indexed geometry with every attribute of the original, normals from the
1107
+ // sculpted surface, and the original's material groups and userData.
1108
+ function putTogether(mesh, original) {
1109
+ updateNormals(mesh);
1110
+ const { cornerPlace, cornerNormal, positions, shadingNormals } = mesh;
1111
+ const count = cornerPlace.length;
1112
+ const position = new Float32Array(count * 3);
1113
+ const normal = new Float32Array(count * 3);
1114
+ for (let corner = 0; corner < count; corner++) {
1115
+ for (let axis = 0; axis < 3; axis++) {
1116
+ position[corner * 3 + axis] = positions[cornerPlace[corner] * 3 + axis];
1117
+ normal[corner * 3 + axis] = shadingNormals[cornerNormal[corner] * 3 + axis];
1118
+ }
1119
+ }
1120
+ const geometry = new THREE.BufferGeometry();
1121
+ geometry.setAttribute('position', new THREE.BufferAttribute(position, 3));
1122
+ geometry.setAttribute('normal', new THREE.BufferAttribute(normal, 3));
1123
+ for (const [name, { itemSize, values }] of Object.entries(mesh.attributes)) {
1124
+ geometry.setAttribute(name, new THREE.Float32BufferAttribute(values, itemSize));
1125
+ }
1126
+
1127
+ // Triangles are sorted by material so each group is one run.
1128
+ const order = mesh.groups.map((_, t) => t);
1129
+ if (original.groups.length > 0) {
1130
+ order.sort((a, b) => mesh.groups[a] - mesh.groups[b]);
1131
+ }
1132
+ const index = [];
1133
+ for (const t of order) {
1134
+ index.push(mesh.triangles[t * 3], mesh.triangles[t * 3 + 1], mesh.triangles[t * 3 + 2]);
1135
+ }
1136
+ geometry.setIndex(index);
1137
+ if (original.groups.length > 0) {
1138
+ let start = 0;
1139
+ for (let n = 1; n <= order.length; n++) {
1140
+ if (n === order.length || mesh.groups[order[n]] !== mesh.groups[order[start]]) {
1141
+ geometry.addGroup(start * 3, (n - start) * 3, mesh.groups[order[start]]);
1142
+ start = n;
1143
+ }
1144
+ }
1145
+ }
1146
+ geometry.userData = { ...original.userData };
1147
+ return geometry;
1148
+ }