castle-web-cli 0.4.204 → 0.4.206

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 (134) 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 +7 -2
  5. package/dist/agent.d.ts +3 -2
  6. package/dist/agent.js +29 -18
  7. package/dist/castle-host/host.d.ts +17 -0
  8. package/dist/castle-host/host.js +551 -4
  9. package/dist/devSessionStorage.js +65 -4
  10. package/dist/effortSupport.d.ts +7 -0
  11. package/dist/effortSupport.js +31 -0
  12. package/dist/imports.d.ts +1 -1
  13. package/dist/imports.js +59 -19
  14. package/dist/index.js +4 -3
  15. package/dist/init.d.ts +9 -1
  16. package/dist/init.js +64 -25
  17. package/dist/kitCatalog.d.ts +13 -0
  18. package/dist/kitCatalog.js +111 -0
  19. package/dist/platformDoc.js +7 -2
  20. package/dist/serve.js +35 -2
  21. package/dist/shell/assets/{index-DHzA0-Sj.js → index-hWQTC8q6.js} +5 -5
  22. package/dist/shell/index.html +1 -1
  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 +5 -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 +5 -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-2d/castle.json +1 -0
  56. package/kits/physics-3d/CLAUDE.md +65 -7
  57. package/kits/physics-3d/castle.json +4 -3
  58. package/kits/physics-3d/docs/pxmodel-format.md +916 -15
  59. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  60. package/kits/physics-3d/engine3d/artobjects.js +218 -0
  61. package/kits/physics-3d/engine3d/blob.js +1058 -0
  62. package/kits/physics-3d/engine3d/branches.js +300 -0
  63. package/kits/physics-3d/engine3d/cage.js +496 -0
  64. package/kits/physics-3d/engine3d/cageops.js +516 -0
  65. package/kits/physics-3d/engine3d/frame.js +669 -0
  66. package/kits/physics-3d/engine3d/look.js +675 -0
  67. package/kits/physics-3d/engine3d/materialpresets.js +486 -0
  68. package/kits/physics-3d/engine3d/modelEditorWorld.js +3 -2
  69. package/kits/physics-3d/engine3d/modelrefs.js +120 -0
  70. package/kits/physics-3d/engine3d/motion.js +560 -0
  71. package/kits/physics-3d/engine3d/objtext.js +37 -0
  72. package/kits/physics-3d/engine3d/optimize.js +1083 -0
  73. package/kits/physics-3d/engine3d/paint.js +674 -0
  74. package/kits/physics-3d/engine3d/partgeometry.js +467 -0
  75. package/kits/physics-3d/engine3d/paths.js +324 -0
  76. package/kits/physics-3d/engine3d/pxmodel.js +429 -26
  77. package/kits/physics-3d/engine3d/scatter.js +102 -0
  78. package/kits/physics-3d/engine3d/sculpt.js +1148 -0
  79. package/kits/physics-3d/engine3d/surfacedetail.js +267 -0
  80. package/kits/physics-3d/engine3d/sweep.js +480 -0
  81. package/kits/physics-3d/engine3d/thumbnails.js +6 -4
  82. package/kits/physics-3d/engine3d/world3d.js +119 -17
  83. package/kits/physics-3d/eslint.config.js +13 -0
  84. package/kits/physics-3d/models/parts/axe.pxmodel +40 -0
  85. package/kits/physics-3d/models/parts/backpack.pxmodel +47 -0
  86. package/kits/physics-3d/models/parts/barrel.pxmodel +22 -0
  87. package/kits/physics-3d/models/parts/bedroll.pxmodel +28 -0
  88. package/kits/physics-3d/models/parts/belt-pouch.pxmodel +22 -0
  89. package/kits/physics-3d/models/parts/bolt.pxmodel +10 -0
  90. package/kits/physics-3d/models/parts/bracer.pxmodel +26 -0
  91. package/kits/physics-3d/models/parts/chain-span.pxmodel +12 -0
  92. package/kits/physics-3d/models/parts/chimney.pxmodel +11 -0
  93. package/kits/physics-3d/models/parts/crate.pxmodel +44 -0
  94. package/kits/physics-3d/models/parts/crystal.pxmodel +22 -0
  95. package/kits/physics-3d/models/parts/door-arched.pxmodel +12 -0
  96. package/kits/physics-3d/models/parts/engine-block.pxmodel +39 -0
  97. package/kits/physics-3d/models/parts/exhaust-pipe.pxmodel +30 -0
  98. package/kits/physics-3d/models/parts/fence-span.pxmodel +10 -0
  99. package/kits/physics-3d/models/parts/fender.pxmodel +19 -0
  100. package/kits/physics-3d/models/parts/headlight.pxmodel +24 -0
  101. package/kits/physics-3d/models/parts/hood.pxmodel +17 -0
  102. package/kits/physics-3d/models/parts/horned-helmet.pxmodel +37 -0
  103. package/kits/physics-3d/models/parts/jerry-can.pxmodel +26 -0
  104. package/kits/physics-3d/models/parts/ladder.pxmodel +10 -0
  105. package/kits/physics-3d/models/parts/lamp.pxmodel +20 -0
  106. package/kits/physics-3d/models/parts/lantern.pxmodel +30 -0
  107. package/kits/physics-3d/models/parts/leaf-cluster.pxmodel +21 -0
  108. package/kits/physics-3d/models/parts/offroad-tire.pxmodel +48 -0
  109. package/kits/physics-3d/models/parts/pauldron.pxmodel +26 -0
  110. package/kits/physics-3d/models/parts/rivet.pxmodel +8 -0
  111. package/kits/physics-3d/models/parts/rock.pxmodel +21 -0
  112. package/kits/physics-3d/models/parts/roll-bar-light.pxmodel +26 -0
  113. package/kits/physics-3d/models/parts/round-shield.pxmodel +31 -0
  114. package/kits/physics-3d/models/parts/saddlebag.pxmodel +30 -0
  115. package/kits/physics-3d/models/parts/spoked-wheel.pxmodel +39 -0
  116. package/kits/physics-3d/models/parts/staff.pxmodel +33 -0
  117. package/kits/physics-3d/models/parts/stepping-stones.pxmodel +8 -0
  118. package/kits/physics-3d/models/parts/stone-base.pxmodel +10 -0
  119. package/kits/physics-3d/models/parts/sword.pxmodel +33 -0
  120. package/kits/physics-3d/models/parts/window-lit.pxmodel +13 -0
  121. package/kits/physics-3d/models/parts/wizard-hat.pxmodel +28 -0
  122. package/kits/physics-3d/models/templates/biped-stout.pxmodel +59 -0
  123. package/kits/physics-3d/models/templates/biped-tall.pxmodel +63 -0
  124. package/kits/physics-3d/models/templates/quadruped.pxmodel +52 -0
  125. package/kits/physics-3d/scripts/render/filmstrip.js +217 -0
  126. package/kits/physics-3d/scripts/render/index.html +20 -0
  127. package/kits/physics-3d/scripts/render/sheet.js +411 -0
  128. package/kits/physics-3d/scripts/render.mjs +646 -0
  129. package/kits/real-time/castle.json +2 -2
  130. package/kits/real-time/code/client/ownership.js +14 -4
  131. package/kits/real-time/code/client/smooth.js +2 -2
  132. package/kits/real-time/code/server/session.js +20 -4
  133. package/kits/turn-based/castle.json +1 -0
  134. package/package.json +2 -2
@@ -3,8 +3,20 @@
3
3
  // list of named primitive parts with hierarchy -- the 3d analog of `.pxart`,
4
4
  // built to be written by hand or by an agent.
5
5
  import * as THREE from 'three';
6
- import { makeShapeMesh, makeMaterial, artRefSignature } from './materials';
6
+ import { makeShapeMesh, makeMaterial, artRefSignature, resolveArtTexture } from './materials';
7
7
  import { buildMeshGeometry } from './meshops';
8
+ import { buildPartGeometry, needsModelGeometry, partIsDoubleSided } from './partgeometry';
9
+ import { scatterPart } from './scatter';
10
+ import { placeTips } from './branches';
11
+ import { repeatAlong } from './paths';
12
+ import { applySurfaceDetail, hasSurfaceDetail } from './surfacedetail';
13
+ import { applyPaint, hasPaint } from './paint';
14
+ import { applyMaterialPreset } from './materialpresets';
15
+ import { buildModelRef } from './modelrefs';
16
+ import { applyLook, lookIsEnabled } from './look';
17
+ import { applyArtObjects, applyMaterialExtras, partArtRefs } from './artobjects';
18
+ import { coarsenParts, detailFor, optimizeModel, referenceBudget } from './optimize';
19
+ import { airSpeed, modelAnimation } from './motion';
8
20
 
9
21
  const DEG = Math.PI / 180;
10
22
 
@@ -14,6 +26,7 @@ export const PART_DEFAULTS = {
14
26
  position: [0, 0, 0],
15
27
  rotation: [0, 0, 0],
16
28
  offset: [0, 0, 0],
29
+ scale: [1, 1, 1],
17
30
  size: [1, 1, 1],
18
31
  radius: 0.5,
19
32
  height: 1,
@@ -28,7 +41,7 @@ export const PART_DEFAULTS = {
28
41
  emissiveIntensity: 1,
29
42
  };
30
43
 
31
- const VEC3_KEYS = new Set(['position', 'rotation', 'offset', 'size']);
44
+ const VEC3_KEYS = new Set(['position', 'rotation', 'offset', 'scale', 'size']);
32
45
 
33
46
  function normalizeVec3(value, fallback) {
34
47
  if (!Array.isArray(value)) return [...fallback];
@@ -38,6 +51,11 @@ function normalizeVec3(value, fallback) {
38
51
  function normalizePart(raw, index) {
39
52
  const part = { ...PART_DEFAULTS, ...(raw ?? {}) };
40
53
  part.id = typeof part.id === 'string' && part.id ? part.id : `part-${index + 1}`;
54
+
55
+ // A single number scales evenly.
56
+ if (Number.isFinite(part.scale)) {
57
+ part.scale = [part.scale, part.scale, part.scale];
58
+ }
41
59
  for (const key of VEC3_KEYS) part[key] = normalizeVec3(part[key], PART_DEFAULTS[key]);
42
60
  if (part.kind === 'mesh') {
43
61
  part.vertices = Array.isArray(part.vertices)
@@ -86,9 +104,91 @@ export function parseModel(text) {
86
104
  current = parts.find((candidate) => candidate.id === current.parent) ?? { parent: '' };
87
105
  }
88
106
  }
89
- return { name: typeof json.name === 'string' ? json.name : 'Model', parts };
107
+ const name = typeof json.name === 'string' ? json.name : 'Model';
108
+ const height = Number.isFinite(json.height) && json.height > 0 ? json.height : undefined;
109
+ return { name, parts, look: json.look, clips: json.clips, triangles: readBudget(json.triangles), height };
90
110
  }
91
111
 
112
+ // A model's `triangles` budget (optimize.js), when it is a positive number.
113
+ function readBudget(value) {
114
+ return Number.isFinite(value) && value > 0 ? value : undefined;
115
+ }
116
+
117
+ const MODEL_ONLY_KEYS = [
118
+ 'profile',
119
+ 'outline',
120
+ 'holes',
121
+ 'smooth',
122
+ 'depth',
123
+ 'bevel',
124
+ 'path',
125
+ 'radiusEnd',
126
+ 'radii',
127
+ 'obj',
128
+ 'unit',
129
+ 'closed',
130
+ 'tube',
131
+ 'arc',
132
+ 'radiusTop',
133
+ 'round',
134
+ 'noise',
135
+ 'seed',
136
+ 'segments',
137
+ 'flat',
138
+ 'mirror',
139
+ 'repeat',
140
+ 'sections',
141
+ 'subdivide',
142
+ 'symmetric',
143
+ 'from',
144
+ 'ops',
145
+ 'crease',
146
+ 'taper',
147
+ 'twist',
148
+ 'fold',
149
+ 'bend',
150
+ 'scatter',
151
+ 'displace',
152
+ 'noiseScale',
153
+ 'paint',
154
+ 'up',
155
+ 'straight',
156
+ 'scaleEnd',
157
+ 'turn',
158
+ 'points',
159
+ 'thickness',
160
+ 'resolution',
161
+ 'length',
162
+ 'split',
163
+ 'spread',
164
+ 'shrink',
165
+ 'thin',
166
+ 'curve',
167
+ 'lift',
168
+ 'direction',
169
+ 'tips',
170
+ 'shapes',
171
+ 'blend',
172
+ 'colorBlend',
173
+ 'sculpt',
174
+ 'helix',
175
+ 'nodes',
176
+ 'edges',
177
+ 'net',
178
+ 'material',
179
+ 'materialColor',
180
+ 'keep',
181
+ 'src',
182
+ 'look',
183
+ 'artOffset',
184
+ 'artRotation',
185
+ 'brightness',
186
+ 'alphaTest',
187
+ 'doubleSided',
188
+ 'motion',
189
+ 'ripple',
190
+ ];
191
+
92
192
  const sameVec = (a, b) => a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
93
193
 
94
194
  // Serialize sparsely: only fields that differ from the defaults, so files stay
@@ -98,18 +198,28 @@ export function serializeModel(model) {
98
198
  const out = { id: part.id };
99
199
  if (part.parent) out.parent = part.parent;
100
200
  if (part.kind !== 'box') out.kind = part.kind;
101
- for (const key of ['position', 'rotation', 'offset']) {
201
+ for (const key of ['position', 'rotation', 'offset', 'scale']) {
102
202
  if (!sameVec(part[key], PART_DEFAULTS[key])) out[key] = part[key];
103
203
  }
104
204
  if (part.kind === 'mesh') {
105
- out.vertices = part.vertices;
106
- out.faces = part.faces;
205
+ if (!part.from) {
206
+ out.vertices = part.vertices;
207
+ out.faces = part.faces;
208
+ }
107
209
  } else if (part.kind === 'box') {
108
210
  if (!sameVec(part.size, PART_DEFAULTS.size)) out.size = part.size;
109
211
  } else {
110
212
  if (part.radius !== PART_DEFAULTS.radius) out.radius = part.radius;
111
213
  if (part.kind !== 'sphere' && part.height !== PART_DEFAULTS.height) out.height = part.height;
112
214
  }
215
+
216
+ // Fields of the model-only kinds and options (partgeometry.js), and the
217
+ // mirror / repeat modifiers, are kept as written.
218
+ for (const key of MODEL_ONLY_KEYS) {
219
+ if (part[key] !== undefined && part[key] !== null) {
220
+ out[key] = part[key];
221
+ }
222
+ }
113
223
  for (const key of [
114
224
  'color',
115
225
  'art',
@@ -128,7 +238,12 @@ export function serializeModel(model) {
128
238
  }
129
239
  return out;
130
240
  });
131
- return `${JSON.stringify({ format: 'pxmodel', name: model.name, parts }, null, 2)}\n`;
241
+ const look = model.look === undefined ? {} : { look: model.look };
242
+ const budget = model.triangles === undefined ? {} : { triangles: model.triangles };
243
+ const clips = model.clips === undefined ? {} : { clips: model.clips };
244
+ const height = model.height === undefined ? {} : { height: model.height };
245
+ const top = { format: 'pxmodel', name: model.name, ...height, ...budget, ...look, ...clips, parts };
246
+ return `${JSON.stringify(top, null, 2)}\n`;
132
247
  }
133
248
 
134
249
  export const STARTER_MODEL_TEXT = serializeModel({
@@ -170,51 +285,339 @@ function partAsShape(part) {
170
285
  };
171
286
  }
172
287
 
288
+ function buildPartMesh(part, sprites) {
289
+ let mesh;
290
+ if (part.kind === 'mesh' && !needsModelGeometry(part)) {
291
+ const { geometry, triFaces } = buildMeshGeometry(part);
292
+ mesh = new THREE.Mesh(geometry, makeMaterial(partAsShape(part), null));
293
+ mesh.userData.triFaces = triFaces;
294
+ } else {
295
+ const geometry = needsModelGeometry(part) ? buildPartGeometry(part) : null;
296
+ if (geometry) {
297
+ const art = typeof part.art === 'string' ? part.art : null;
298
+ mesh = new THREE.Mesh(
299
+ geometry,
300
+ makeMaterial(partAsShape(part), resolveArtTexture(art, sprites, part.artRepeat))
301
+ );
302
+ mesh.userData.branchTips = geometry.userData.branchTips;
303
+
304
+ // A blob with colored shapes carries its colors per vertex.
305
+ if (geometry.userData.vertexColors) {
306
+ mesh.material.color.set('#ffffff');
307
+ mesh.material.vertexColors = true;
308
+ }
309
+ } else {
310
+ mesh = makeShapeMesh(
311
+ partAsShape({ ...part, kind: SHAPE_FALLBACK[part.kind] ?? part.kind }),
312
+ sprites
313
+ );
314
+ }
315
+ }
316
+ applyArtObjects(mesh, part, partAsShape(part), sprites);
317
+ part = applyMaterialPreset(mesh, part);
318
+ return { mesh, part };
319
+ }
320
+
321
+ // Surface detail and paint split the surface only as finely as the model's
322
+ // `detail` allows (optimize.js), which is known once every part is built.
323
+ function finishPartMesh(mesh, part, detail) {
324
+ if (hasSurfaceDetail(part)) {
325
+ applySurfaceDetail(mesh, part, detail);
326
+ }
327
+ if (hasPaint(part)) {
328
+ applyPaint(mesh, part, detail);
329
+ }
330
+ for (const material of [mesh.material].flat()) {
331
+ if (part.flat) {
332
+ material.flatShading = true;
333
+ }
334
+ if (partIsDoubleSided(part) || mesh.geometry.userData.openCage) {
335
+ material.side = THREE.DoubleSide;
336
+ }
337
+ }
338
+ applyMaterialExtras(mesh, part);
339
+ mesh.castShadow = true;
340
+ mesh.receiveShadow = true;
341
+ }
342
+
343
+ // A model-only kind whose fields cannot make a shape still draws something.
344
+ const SHAPE_FALLBACK = {
345
+ loft: 'cylinder',
346
+ mesh: 'box',
347
+ lathe: 'cylinder',
348
+ extrude: 'box',
349
+ tube: 'cylinder',
350
+ sweep: 'cylinder',
351
+ surface: 'box',
352
+ branches: 'cylinder',
353
+ blob: 'sphere',
354
+ frame: 'box',
355
+ torus: 'cylinder',
356
+ cone: 'cylinder',
357
+ };
358
+
359
+ // `mirror` adds a copy of a part and everything under it, reflected across
360
+ // the parent's x, y or z = 0 plane. `repeat` adds `count - 1` copies, the
361
+ // n-th moved by n times `offset` and turned by n times `rotate` degrees about
362
+ // the parent's pivot, so it makes both rows and rings. `scatter` (scatter.js)
363
+ // places copies at random points and is used in place of `repeat` when both
364
+ // are set. `repeat.along` (paths.js) spaces copies along a curve instead.
365
+ // Copies are not parts:
366
+ // they have no ids and do not animate on their own. The deepest parts go
367
+ // first, so a copy of a parent includes its children's copies. `tips`
368
+ // (branches.js) come before a part's own copies, so those include the tips.
369
+ function applyModifiers(model, groups) {
370
+ const byId = new Map(model.parts.map((part) => [part.id, part]));
371
+ const depth = (part) => {
372
+ let count = 0;
373
+ let current = part;
374
+ while (current.parent && byId.has(current.parent)) {
375
+ current = byId.get(current.parent);
376
+ count++;
377
+ }
378
+ return count;
379
+ };
380
+ const modified = model.parts
381
+ .filter((part) => part.mirror || part.repeat || part.scatter || part.tips)
382
+ .sort((a, b) => depth(b) - depth(a));
383
+ for (const part of modified) {
384
+ const group = groups.get(part.id);
385
+ const parent = group.parent;
386
+ if (!parent) {
387
+ continue;
388
+ }
389
+ if (part.tips) {
390
+ placeTips(part, group, groups, copyOf);
391
+ }
392
+ if (part.scatter) {
393
+ scatterPart(part, group, groups, copyOf);
394
+ } else if (part.repeat && typeof part.repeat === 'object' && part.repeat.along) {
395
+ repeatAlong(part, group, groups, byId, copyOf, jitterCopy);
396
+ } else if (part.repeat && typeof part.repeat === 'object') {
397
+ const count = Math.max(1, Math.min(64, Math.round(part.repeat.count ?? 1)));
398
+ const offset = normalizeVec3(part.repeat.offset, [0, 0, 0]);
399
+ const rotate = normalizeVec3(part.repeat.rotate, [0, 0, 0]);
400
+ for (let n = 1; n < count; n++) {
401
+ const holder = new THREE.Group();
402
+ holder.userData.copyOf = part.id;
403
+ holder.position.set(offset[0] * n, offset[1] * n, offset[2] * n);
404
+ holder.rotation.set(rotate[0] * n * DEG, rotate[1] * n * DEG, rotate[2] * n * DEG);
405
+ const copy = copyOf(group);
406
+ if (part.repeat.jitter) {
407
+ jitterCopy(copy, part.repeat.jitter, n);
408
+ }
409
+ holder.add(copy);
410
+ parent.add(holder);
411
+ }
412
+ }
413
+ if (['x', 'y', 'z'].includes(part.mirror)) {
414
+ // A copy of the part and of the repeat copies just added beside it.
415
+ const siblings = parent.children.filter(
416
+ (child) => child === group || child.userData.copyOf === part.id
417
+ );
418
+ const holder = new THREE.Group();
419
+ holder.scale[part.mirror] = -1;
420
+ for (const sibling of siblings) {
421
+ holder.add(copyOf(sibling));
422
+ }
423
+ parent.add(holder);
424
+ }
425
+ }
426
+ }
427
+
428
+ // A small random difference per repeat copy, so a stack of logs or a row of
429
+ // stones does not look stamped out. Every field is the most a copy moves:
430
+ // `position` in meters, `rotate` in degrees, `scale` and `color` as fractions
431
+ // (color changes lightness). The same `seed` gives the same copies.
432
+ function jitterCopy(copy, jitter, n) {
433
+ let state = ((jitter.seed ?? 1) * 7919 + n * 104729) >>> 0;
434
+ const random = () => {
435
+ state = (state + 0x6d2b79f5) >>> 0;
436
+ let t = Math.imul(state ^ (state >>> 15), 1 | state);
437
+ t ^= t + Math.imul(t ^ (t >>> 7), 61 | t);
438
+ return (((t ^ (t >>> 14)) >>> 0) / 4294967296) * 2 - 1;
439
+ };
440
+ const position = normalizeVec3(jitter.position, [0, 0, 0]);
441
+ const rotate = normalizeVec3(jitter.rotate, [0, 0, 0]);
442
+ copy.position.x += position[0] * random();
443
+ copy.position.y += position[1] * random();
444
+ copy.position.z += position[2] * random();
445
+ copy.rotation.x += rotate[0] * random() * DEG;
446
+ copy.rotation.y += rotate[1] * random() * DEG;
447
+ copy.rotation.z += rotate[2] * random() * DEG;
448
+ if (Number.isFinite(jitter.scale)) {
449
+ copy.scale.multiplyScalar(1 + jitter.scale * random());
450
+ }
451
+ if (Number.isFinite(jitter.color) && jitter.color !== 0) {
452
+ const shift = jitter.color * random();
453
+
454
+ // Materials are shared between copies; a shifted color needs its own.
455
+ copy.traverse((child) => {
456
+ if (child.isMesh) {
457
+ child.material = [child.material].flat().map((material) => {
458
+ const own = material.clone();
459
+ own.color.offsetHSL(0, 0, shift);
460
+ return own;
461
+ });
462
+ if (child.material.length === 1) {
463
+ child.material = child.material[0];
464
+ }
465
+ }
466
+ });
467
+ }
468
+ }
469
+
470
+ function copyOf(node) {
471
+ const copy = node.clone(true);
472
+ copy.traverse((child) => {
473
+ if (child.userData.partId) {
474
+ child.userData = { copyOf: child.userData.partId };
475
+ }
476
+ });
477
+ if (node.userData.partId) {
478
+ copy.userData.copyOf = node.userData.partId;
479
+ }
480
+ return copy;
481
+ }
482
+
483
+ // The box around what a model shows. Parts used as patterns by `scatter` and
484
+ // `tips` are hidden, and Box3.setFromObject would count them.
485
+ export function visibleBounds(node) {
486
+ node.updateMatrixWorld(true);
487
+ const bounds = new THREE.Box3();
488
+ const visit = (object) => {
489
+ if (!object.visible) {
490
+ return;
491
+ }
492
+ if (object.isMesh) {
493
+ bounds.expandByObject(object, false);
494
+ return;
495
+ }
496
+ object.children.forEach(visit);
497
+ };
498
+ visit(node);
499
+ return bounds;
500
+ }
501
+
502
+ // A part's mesh sits in its group at `offset`, stretched by `scale`.
503
+ function placePartMesh(mesh, part, group) {
504
+ mesh.userData.partMesh = part.id;
505
+ mesh.position.set(part.offset[0], part.offset[1], part.offset[2]);
506
+ mesh.scale.set(part.scale[0], part.scale[1], part.scale[2]);
507
+ group.add(mesh);
508
+ }
509
+
173
510
  // Build the model as a THREE.Group: one group per part at its pivot (child
174
511
  // groups nested under their parent's group), the mesh offset inside. The
175
512
  // returned group's userData.modelParts maps part id -> group.
176
- export function buildModelNode(model, sprites) {
513
+ //
514
+ // `models` maps deck paths to the text of the model files that `kind: "model"`
515
+ // parts reference (the deck's file map will do), and `path` is this model's own
516
+ // deck path, which relative references resolve against (modelrefs.js). `chain`
517
+ // is the paths of the models being built above this one.
518
+ //
519
+ // With `options.optimize` the model is built for a game: parts that draw
520
+ // alike are merged, and meshes are shrunk to fit the triangle budget
521
+ // (optimize.js). Parts can then no longer be picked one by one.
522
+ export function buildModelNode(
523
+ model,
524
+ sprites,
525
+ models = null,
526
+ path = '',
527
+ chain = [path],
528
+ options = {}
529
+ ) {
177
530
  const root = new THREE.Group();
178
531
  const groups = new Map();
532
+ const built = [];
533
+ const references = [];
534
+
535
+ // A game build builds each referenced model once and copies it, and the
536
+ // references share this model's triangle budget.
537
+ if (options.optimize && !options.references) {
538
+ options = { ...options, references: new Map() };
539
+ }
540
+ const inner = options.optimize
541
+ ? { ...options, budget: referenceBudget(model, options.budget) }
542
+ : options;
179
543
  for (const part of model.parts) {
180
544
  const group = new THREE.Group();
181
545
  group.userData.partId = part.id;
182
546
  group.position.set(part.position[0], part.position[1], part.position[2]);
183
547
  group.rotation.set(part.rotation[0] * DEG, part.rotation[1] * DEG, part.rotation[2] * DEG);
184
- let mesh;
185
- if (part.kind === 'mesh') {
186
- const { geometry, triFaces } = buildMeshGeometry(part);
187
- mesh = new THREE.Mesh(geometry, makeMaterial(partAsShape(part), null));
188
- mesh.castShadow = true;
189
- mesh.receiveShadow = true;
190
- mesh.userData.triFaces = triFaces;
548
+ groups.set(part.id, group);
549
+ if (part.kind === 'model') {
550
+ const node = buildModelRef(part, sprites, models, chain, inner);
551
+ if (!node.userData.sharedReference) {
552
+ applyMaterialExtras(node, part);
553
+ }
554
+ references.push({ node, part });
555
+ placePartMesh(node, part, group);
191
556
  } else {
192
- mesh = makeShapeMesh(partAsShape(part), sprites);
557
+ built.push({ ...buildPartMesh(part, sprites), source: part, group });
193
558
  }
194
- mesh.userData.partMesh = part.id;
195
- mesh.position.set(part.offset[0], part.offset[1], part.offset[2]);
196
- group.add(mesh);
197
- groups.set(part.id, group);
559
+ }
560
+
561
+ // Parts over the budget are built again coarser before paint (optimize.js).
562
+ const rebuild = (part, coarseness) => buildPartMesh({ ...part, coarseness }, sprites);
563
+ coarsenParts(model, built, references, rebuild, options.budget);
564
+ const detail = detailFor(model, built, references, options.budget);
565
+ for (const { mesh, part, source, group } of built) {
566
+ finishPartMesh(mesh, part, detail);
567
+ placePartMesh(mesh, source, group);
198
568
  }
199
569
  for (const part of model.parts) {
200
570
  const parent = part.parent ? groups.get(part.parent) : null;
201
571
  (parent ?? root).add(groups.get(part.id));
202
572
  }
573
+ applyModifiers(model, groups);
574
+
575
+ // What moves (motion.js), which the optimizer keeps apart from merging.
576
+ root.userData.animation = modelAnimation(model);
577
+ if (options.optimize) {
578
+ optimizeModel(root, model, detail);
579
+ }
580
+ applyLook(root, model);
581
+ fitHeight(root, model);
203
582
  root.userData.modelParts = groups;
204
583
  return root;
205
584
  }
206
585
 
586
+ // `height` on the model scales the whole thing so its visible height is that
587
+ // many meters, about its base, so a model written at the wrong scale still
588
+ // comes out game-sized.
589
+ function fitHeight(root, model) {
590
+ if (!model.height) {
591
+ return;
592
+ }
593
+ const bounds = visibleBounds(root);
594
+ const current = bounds.max.y - bounds.min.y;
595
+ if (current <= 1e-6) {
596
+ return;
597
+ }
598
+
599
+ // An inner group carries the scale, so code that sets the root's own scale
600
+ // (a Model behavior's `scale`) multiplies it rather than replacing it.
601
+ const fit = new THREE.Group();
602
+ fit.scale.setScalar(model.height / current);
603
+ while (root.children.length > 0) {
604
+ fit.add(root.children[0]);
605
+ }
606
+ root.add(fit);
607
+ }
608
+
207
609
  // Every art ref a model uses, for change signatures.
208
610
  export function modelArtSignature(model, sprites) {
209
611
  if (!model) return '';
210
612
  const refs = [];
211
613
  for (const part of model.parts) {
212
- if (typeof part.art === 'string' && part.art) refs.push(part.art);
213
- else if (part.art && typeof part.art === 'object') {
214
- refs.push(...Object.values(part.art).filter((ref) => typeof ref === 'string'));
215
- }
614
+ refs.push(...partArtRefs(part));
216
615
  }
217
- return refs.map((ref) => artRefSignature(ref, sprites)).join('|');
616
+
617
+ // The look switch changes how every model is built, so it is part of the
618
+ // signature and a flip rebuilds placed models.
619
+ const look = lookIsEnabled() ? 'look' : 'plain';
620
+ return [look, ...refs.map((ref) => artRefSignature(ref, sprites))].join('|');
218
621
  }
219
622
 
220
623
  // Walk animation by part-id convention (legL/legR/armL/armR/torso), driven by
@@ -235,7 +638,7 @@ export function animateModelParts(entry, dt) {
235
638
  const p = entry.node.position;
236
639
  if (dt > 0 && anim.last) {
237
640
  const speed = Math.hypot(p.x - anim.last.x, p.z - anim.last.z) / dt;
238
- const verticalSpeed = (p.y - anim.last.y) / dt;
641
+ const verticalSpeed = airSpeed(entry.node, p, anim.last, dt);
239
642
  anim.swing += (Math.min(1, speed / 5) - anim.swing) * Math.min(1, dt * 10);
240
643
  anim.air += ((Math.abs(verticalSpeed) > 1.2 ? 1 : 0) - anim.air) * Math.min(1, dt * 8);
241
644
  anim.phase += Math.min(speed, 8) * 2.4 * dt;
@@ -0,0 +1,102 @@
1
+ // The `scatter` modifier: copies of a part placed at random points on the
2
+ // surface of another part, or inside a box. See docs/pxmodel-format.md.
3
+ //
4
+ // The part itself is hidden and serves as the pattern. Each copy sits in a
5
+ // frame at its point, whose +y is the surface normal when `align` is set, and
6
+ // the part's own position and rotation apply inside that frame. The same seed
7
+ // always gives the same placement.
8
+
9
+ import * as THREE from 'three';
10
+ import { MeshSurfaceSampler } from 'three/examples/jsm/math/MeshSurfaceSampler.js';
11
+
12
+ const MAX_COPIES = 200;
13
+ const UP = new THREE.Vector3(0, 1, 0);
14
+
15
+ // A small seeded random number generator (mulberry32) returning [0, 1).
16
+ function seededRandom(seed) {
17
+ let state = Math.round(seed * 9973) | 0;
18
+ return () => {
19
+ state = (state + 0x6d2b79f5) | 0;
20
+ let t = Math.imul(state ^ (state >>> 15), 1 | state);
21
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
22
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
23
+ };
24
+ }
25
+
26
+ // Points and normals in the parent's space: on the `on` part's mesh, area
27
+ // weighted, or inside the `within` box centered on the parent's pivot.
28
+ function scatterPoints(settings, parent, groups, count, random) {
29
+ const points = [];
30
+ const target = groups.get(settings.on);
31
+ const mesh = target?.children.find((child) => child.userData.partMesh === settings.on);
32
+ if (mesh) {
33
+ mesh.updateWorldMatrix(true, false);
34
+ parent.updateWorldMatrix(true, false);
35
+ const toParent = parent.matrixWorld.clone().invert().multiply(mesh.matrixWorld);
36
+ const normalMatrix = new THREE.Matrix3().getNormalMatrix(toParent);
37
+ const sampler = new MeshSurfaceSampler(mesh).setRandomGenerator(random).build();
38
+ for (let n = 0; n < count; n++) {
39
+ const position = new THREE.Vector3();
40
+ const normal = new THREE.Vector3();
41
+ sampler.sample(position, normal);
42
+ position.applyMatrix4(toParent);
43
+ normal.applyMatrix3(normalMatrix).normalize();
44
+ points.push({ position, normal });
45
+ }
46
+ return points;
47
+ }
48
+ const size = Array.isArray(settings.within) ? settings.within : [1, 0, 1];
49
+ for (let n = 0; n < count; n++) {
50
+ const position = new THREE.Vector3(
51
+ ...[0, 1, 2].map((i) => (Number.isFinite(size[i]) ? size[i] : 0) * (random() - 0.5))
52
+ );
53
+ points.push({ position, normal: UP.clone() });
54
+ }
55
+ return points;
56
+ }
57
+
58
+ function scaleRange(value) {
59
+ if (Array.isArray(value) && Number.isFinite(value[0]) && Number.isFinite(value[1])) {
60
+ return value;
61
+ }
62
+ if (Number.isFinite(value)) {
63
+ return [value, value];
64
+ }
65
+ return [1, 1];
66
+ }
67
+
68
+ // Adds the copies beside the part's group, under its parent. `copyOf` makes a
69
+ // copy of a group that has no part ids.
70
+ export function scatterPart(part, group, groups, copyOf) {
71
+ const settings = part.scatter;
72
+ const parent = group.parent;
73
+ if (!settings || typeof settings !== 'object' || !parent || settings.on === part.id) {
74
+ return;
75
+ }
76
+ const count = Math.max(0, Math.min(MAX_COPIES, Math.round(settings.count ?? 10)));
77
+ const random = seededRandom(Number.isFinite(settings.seed) ? settings.seed : 1);
78
+ const [low, high] = scaleRange(settings.scale);
79
+ const spin = new THREE.Quaternion();
80
+ for (const { position, normal } of scatterPoints(settings, parent, groups, count, random)) {
81
+ const holder = new THREE.Group();
82
+ holder.userData.copyOf = part.id;
83
+ holder.position.copy(position);
84
+ if (settings.align) {
85
+ holder.quaternion.setFromUnitVectors(UP, normal);
86
+ }
87
+
88
+ // The spin and scale are drawn for every copy, so turning `spin` or
89
+ // `align` on or off keeps the points where they were.
90
+ const angle = random() * Math.PI * 2;
91
+ const scale = low + (high - low) * random();
92
+ if (settings.spin) {
93
+ holder.quaternion.multiply(spin.setFromAxisAngle(UP, angle));
94
+ }
95
+ holder.scale.setScalar(scale);
96
+ const copy = copyOf(group);
97
+ copy.visible = true;
98
+ holder.add(copy);
99
+ parent.add(holder);
100
+ }
101
+ group.visible = false;
102
+ }