@pascal-app/geometry-script 0.0.0-stage → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,783 @@
1
+ import { union } from '@pascal-app/core/polygon-boolean';
2
+ import { GEOMETRY_MANIFEST_MAX_BYTES, GEOMETRY_SCRIPT_MAX_BYTES } from '@pascal-app/core/schema';
3
+ import * as THREE from 'three';
4
+ import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js';
5
+ import { ConvexGeometry } from 'three/examples/jsm/geometries/ConvexGeometry.js';
6
+ import { LoftGeometry } from 'three/examples/jsm/geometries/LoftGeometry.js';
7
+ import * as ParametricFunctions from 'three/examples/jsm/geometries/ParametricFunctions.js';
8
+ import { ParametricGeometry } from 'three/examples/jsm/geometries/ParametricGeometry.js';
9
+ import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
10
+ import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';
11
+ import { ADDITION, Brush, DIFFERENCE, Evaluator, INTERSECTION, SUBTRACTION } from 'three-bvh-csg';
12
+ import { transformModule } from './transform.js';
13
+ export const GEOMETRY_SCRIPT_LIMITS = {
14
+ triangles: 300_000,
15
+ materials: 32,
16
+ extent: 60,
17
+ };
18
+ const csg = { ADDITION, Brush, DIFFERENCE, Evaluator, INTERSECTION, SUBTRACTION };
19
+ const MODULES = {
20
+ three: THREE,
21
+ 'three-bvh-csg': csg,
22
+ BufferGeometryUtils: BufferGeometryUtils,
23
+ ConvexGeometry: { ConvexGeometry },
24
+ LoftGeometry: { LoftGeometry },
25
+ ParametricGeometry: { ParametricGeometry },
26
+ ParametricFunctions: ParametricFunctions,
27
+ RoundedBoxGeometry: { RoundedBoxGeometry },
28
+ };
29
+ const LIB = {
30
+ BufferGeometryUtils,
31
+ ConvexGeometry,
32
+ LoftGeometry,
33
+ ParametricGeometry,
34
+ ParametricFunctions,
35
+ RoundedBoxGeometry,
36
+ csg,
37
+ };
38
+ export const MOUNTS = new Set(['floor', 'wall', 'wall-side', 'ceiling']);
39
+ export function readParamSpecs(raw) {
40
+ if (raw == null)
41
+ return [];
42
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
43
+ throw new Error('`params` must be an object of { id: default | { default, min, max, step } }');
44
+ }
45
+ return Object.entries(raw).map(([id, spec]) => {
46
+ const described = spec !== null && typeof spec === 'object' && !Array.isArray(spec);
47
+ const value = described ? (spec.default ?? spec.value) : spec;
48
+ if (typeof value !== 'number' && typeof value !== 'boolean' && typeof value !== 'string') {
49
+ throw new Error(`Param "${id}" needs a number, boolean or string default`);
50
+ }
51
+ if (typeof value === 'number' && !Number.isFinite(value)) {
52
+ throw new Error(`Param "${id}" default is not finite`);
53
+ }
54
+ const kind = typeof value;
55
+ return described
56
+ ? {
57
+ id,
58
+ kind,
59
+ default: value,
60
+ label: spec.label,
61
+ min: spec.min,
62
+ max: spec.max,
63
+ step: spec.step,
64
+ unit: spec.unit,
65
+ options: spec.options,
66
+ }
67
+ : { id, kind, default: value };
68
+ });
69
+ }
70
+ export function resolveParams(specs, overrides) {
71
+ const values = {};
72
+ for (const spec of specs) {
73
+ const override = overrides[spec.id];
74
+ let value = typeof override === typeof spec.default ? override : spec.default;
75
+ if (typeof value === 'string' && spec.options && !spec.options.includes(value))
76
+ value = spec.default;
77
+ if (typeof value === 'number') {
78
+ if (spec.min !== undefined)
79
+ value = Math.max(spec.min, value);
80
+ if (spec.max !== undefined)
81
+ value = Math.min(spec.max, value);
82
+ }
83
+ values[spec.id] = value;
84
+ }
85
+ return values;
86
+ }
87
+ const conventionId = (name, prefix) => {
88
+ if (!name.startsWith(prefix))
89
+ return null;
90
+ const id = name.slice(prefix.length).trim();
91
+ return id.length > 0 ? id : null;
92
+ };
93
+ const slugify = (value) => value
94
+ .toLowerCase()
95
+ .replace(/[^a-z0-9]+/g, '_')
96
+ .replace(/^_+|_+$/g, '');
97
+ const isCutter = (name) => /^(cutout|cut:(wall|ceiling|slab))$/.test(name);
98
+ const isHelper = (object) => isCutter(object.name) || object.name === 'collider';
99
+ function triangleCount(geometry) {
100
+ const index = geometry.getIndex();
101
+ return Math.floor((index ? index.count : (geometry.getAttribute('position')?.count ?? 0)) / 3);
102
+ }
103
+ function assertFinite(geometry, label) {
104
+ const position = geometry.getAttribute('position');
105
+ if (!position)
106
+ throw new Error(`${label} has no position attribute`);
107
+ const array = position.array;
108
+ for (let i = 0; i < array.length; i++) {
109
+ if (!Number.isFinite(array[i]))
110
+ throw new Error(`${label} has non-finite vertex positions`);
111
+ }
112
+ }
113
+ /** Bounds of the visible geometry: helpers (cutout, collider) and lights do not count. */
114
+ function visibleBounds(root) {
115
+ const box = new THREE.Box3();
116
+ const meshBox = new THREE.Box3();
117
+ root.updateWorldMatrix(true, true);
118
+ root.traverse((object) => {
119
+ const mesh = object;
120
+ if (!mesh.isMesh || isHelper(mesh))
121
+ return;
122
+ let hidden = false;
123
+ for (let p = mesh; p; p = p.parent)
124
+ if (isHelper(p))
125
+ hidden = true;
126
+ if (hidden)
127
+ return;
128
+ mesh.geometry.computeBoundingBox();
129
+ meshBox.copy(mesh.geometry.boundingBox).applyMatrix4(mesh.matrixWorld);
130
+ box.union(meshBox);
131
+ });
132
+ return box;
133
+ }
134
+ function originFor(box, mount) {
135
+ const center = box.getCenter(new THREE.Vector3());
136
+ if (mount === 'wall-side')
137
+ return new THREE.Vector3(center.x, box.min.y, box.min.z);
138
+ return new THREE.Vector3(center.x, box.min.y, center.z);
139
+ }
140
+ const round = (v) => Math.round(v * 1e6) / 1e6;
141
+ const vec = (v) => [round(v.x), round(v.y), round(v.z)];
142
+ /**
143
+ * Reads the naming conventions into the manifest and rewrites the output so
144
+ * they survive glTF: GLTFLoader strips ':' from node names, so convention ids
145
+ * move to `userData.pascal`, materials get `slot_<id>` names, and lights
146
+ * become manifest entries the item light system drives.
147
+ */
148
+ function readConventions(root) {
149
+ const parts = [];
150
+ const anchors = [];
151
+ const lights = [];
152
+ const slots = new Map();
153
+ const materialSlot = new Map();
154
+ const toRemove = [];
155
+ let cutout = false;
156
+ let collider = false;
157
+ let triangles = 0;
158
+ const world = new THREE.Vector3();
159
+ root.updateWorldMatrix(true, true);
160
+ root.traverse((object) => {
161
+ const userData = object.userData;
162
+ const partId = conventionId(object.name, 'part:');
163
+ if (partId) {
164
+ if (parts.some((p) => p.id === partId))
165
+ throw new Error(`Duplicate part id "${partId}"`);
166
+ parts.push({
167
+ id: partId,
168
+ label: typeof userData.label === 'string' ? userData.label : undefined,
169
+ type: typeof userData.type === 'string' ? slugify(userData.type) || undefined : undefined,
170
+ });
171
+ userData.pascal = { ...userData.pascal, part: partId };
172
+ object.name = `part_${partId}`;
173
+ }
174
+ const anchorId = conventionId(object.name, 'anchor:');
175
+ if (anchorId) {
176
+ const normal = Array.isArray(userData.normal) ? userData.normal : undefined;
177
+ anchors.push({
178
+ id: anchorId,
179
+ position: vec(object.getWorldPosition(world)),
180
+ normal: normal?.length === 3 ? normal : undefined,
181
+ });
182
+ toRemove.push(object);
183
+ return;
184
+ }
185
+ const light = object;
186
+ const lightId = conventionId(object.name, 'light:') ?? (light.isLight ? `light_${lights.length + 1}` : null);
187
+ if (lightId) {
188
+ const color = typeof userData.color === 'string'
189
+ ? userData.color
190
+ : light.isLight
191
+ ? `#${light.color.getHexString()}`
192
+ : '#fff4e0';
193
+ const intensity = typeof userData.intensity === 'number'
194
+ ? userData.intensity
195
+ : light.isLight
196
+ ? light.intensity
197
+ : 1;
198
+ const distance = typeof userData.distance === 'number'
199
+ ? userData.distance
200
+ : light.isLight && light.distance > 0
201
+ ? light.distance
202
+ : undefined;
203
+ lights.push({
204
+ id: lightId,
205
+ position: vec(object.getWorldPosition(world)),
206
+ color,
207
+ intensity,
208
+ distance,
209
+ });
210
+ toRemove.push(object);
211
+ return;
212
+ }
213
+ if (isCutter(object.name))
214
+ cutout = true;
215
+ if (object.name === 'collider')
216
+ collider = true;
217
+ const mesh = object;
218
+ if (!mesh.isMesh)
219
+ return;
220
+ assertFinite(mesh.geometry, mesh.name || 'A mesh');
221
+ if (isHelper(mesh))
222
+ return;
223
+ triangles += triangleCount(mesh.geometry);
224
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
225
+ for (const material of materials) {
226
+ if (materialSlot.has(material))
227
+ continue;
228
+ const authored = material.name ?? '';
229
+ const slotId = slugify(conventionId(authored, 'slot_') ?? authored) || `material_${slots.size + 1}`;
230
+ material.name = `slot_${slotId}`;
231
+ materialSlot.set(material, slotId);
232
+ const surface = material;
233
+ const hints = {
234
+ color: surface.color?.isColor ? `#${surface.color.getHexString()}` : undefined,
235
+ roughness: surface.roughness,
236
+ metalness: surface.metalness,
237
+ // Faintly translucent shades and alpha-cut leaves are not glass; the viewer's glass cut-off.
238
+ transparent: (surface.transmission ?? 0) > 0 || (material.transparent && material.opacity < 0.6),
239
+ emissive: (surface.emissiveIntensity ?? 0) > 0 &&
240
+ (surface.emissive?.r > 0 || surface.emissive?.g > 0 || surface.emissive?.b > 0),
241
+ };
242
+ const previous = slots.get(slotId);
243
+ if (previous) {
244
+ // A shared slot with conflicting materials has no single authored tone to match.
245
+ for (const key of ['color', 'roughness', 'metalness', 'transparent']) {
246
+ if (previous[key] !== hints[key])
247
+ delete previous[key];
248
+ }
249
+ previous.emissive ||= hints.emissive;
250
+ }
251
+ else {
252
+ slots.set(slotId, {
253
+ id: slotId,
254
+ label: (conventionId(authored, 'slot_') ?? authored) || undefined,
255
+ ...hints,
256
+ });
257
+ }
258
+ }
259
+ });
260
+ for (const object of toRemove)
261
+ object.parent?.remove(object);
262
+ return {
263
+ parts,
264
+ anchors,
265
+ lights,
266
+ slots: [...slots.values()],
267
+ cutout,
268
+ collider,
269
+ triangles,
270
+ materialCount: materialSlot.size,
271
+ };
272
+ }
273
+ const SURFACE_MIN_NORMAL_Y = 0.95;
274
+ /** Faces pointing at least this far down hang ceiling items (a vault plane up to ~70°). */
275
+ const UNDERSIDE_MAX_NORMAL_Y = -0.35;
276
+ const SURFACE_MIN_AREA = 0.04;
277
+ const SURFACE_MAX_COUNT = 32;
278
+ function partOf(object) {
279
+ for (let p = object; p; p = p.parent) {
280
+ const part = p.userData.pascal?.part;
281
+ if (part)
282
+ return part;
283
+ }
284
+ return undefined;
285
+ }
286
+ function convexHull(points) {
287
+ const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
288
+ if (sorted.length < 3)
289
+ return sorted;
290
+ const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
291
+ const lower = [];
292
+ for (const point of sorted) {
293
+ while (lower.length >= 2 && cross(lower.at(-2), lower.at(-1), point) <= 0)
294
+ lower.pop();
295
+ lower.push(point);
296
+ }
297
+ const upper = [];
298
+ for (const point of sorted.reverse()) {
299
+ while (upper.length >= 2 && cross(upper.at(-2), upper.at(-1), point) <= 0)
300
+ upper.pop();
301
+ upper.push(point);
302
+ }
303
+ return [...lower.slice(0, -1), ...upper.slice(0, -1)];
304
+ }
305
+ function readCutters(root, mount) {
306
+ const cutters = [];
307
+ root.traverse((object) => {
308
+ const mesh = object;
309
+ if (!mesh.isMesh || !isCutter(mesh.name))
310
+ return;
311
+ if (mesh.name === 'cut:wall' ||
312
+ (mesh.name === 'cutout' && (mount === 'wall' || mount === 'wall-side')))
313
+ return;
314
+ const positions = mesh.geometry.getAttribute('position');
315
+ const index = mesh.geometry.getIndex();
316
+ const points = Array.from({ length: positions.count }, (_, i) => new THREE.Vector3().fromBufferAttribute(positions, i).applyMatrix4(mesh.matrixWorld));
317
+ const triangles = [];
318
+ for (let i = 0; i < (index?.count ?? positions.count); i += 3) {
319
+ const triangle = [0, 1, 2].map((j) => points[index ? index.getX(i + j) : i + j]);
320
+ const [a, b, c] = triangle;
321
+ if (Math.abs((b.x - a.x) * (c.z - a.z) - (b.z - a.z) * (c.x - a.x)) < 1e-10)
322
+ continue;
323
+ triangles.push(triangle.map((p) => [p.x, p.z]));
324
+ }
325
+ const host = (mesh.name === 'cutout' ? 'mounted' : mesh.name.slice(4));
326
+ const minY = points.reduce((y, p) => Math.min(y, p.y), Infinity);
327
+ const maxY = points.reduce((y, p) => Math.max(y, p.y), -Infinity);
328
+ for (const region of union(triangles))
329
+ cutters.push({ host, polygon: region.outer, minY, maxY });
330
+ });
331
+ return cutters;
332
+ }
333
+ /**
334
+ * Per-part bounds and the upward-facing flat areas things can rest on (a
335
+ * landing, a seat, a step), so a placement tool can drop an object onto real
336
+ * geometry without a raycast. Outlines are convex hulls per mesh and height.
337
+ */
338
+ function analyseGeometry(root, parts) {
339
+ const partBounds = new Map();
340
+ const surfaces = new Map();
341
+ const undersides = new Map();
342
+ const a = new THREE.Vector3();
343
+ const b = new THREE.Vector3();
344
+ const c = new THREE.Vector3();
345
+ const ab = new THREE.Vector3();
346
+ const ac = new THREE.Vector3();
347
+ const box = new THREE.Box3();
348
+ root.updateWorldMatrix(true, true);
349
+ root.traverse((object) => {
350
+ const mesh = object;
351
+ if (!mesh.isMesh || isHelper(mesh))
352
+ return;
353
+ const part = partOf(mesh);
354
+ mesh.geometry.computeBoundingBox();
355
+ box.copy(mesh.geometry.boundingBox).applyMatrix4(mesh.matrixWorld);
356
+ if (part)
357
+ partBounds.set(part, (partBounds.get(part) ?? new THREE.Box3()).union(box));
358
+ const position = mesh.geometry.getAttribute('position');
359
+ const index = mesh.geometry.getIndex();
360
+ const count = index ? index.count : position.count;
361
+ for (let i = 0; i + 2 < count; i += 3) {
362
+ const ia = index ? index.getX(i) : i;
363
+ const ib = index ? index.getX(i + 1) : i + 1;
364
+ const ic = index ? index.getX(i + 2) : i + 2;
365
+ a.fromBufferAttribute(position, ia).applyMatrix4(mesh.matrixWorld);
366
+ b.fromBufferAttribute(position, ib).applyMatrix4(mesh.matrixWorld);
367
+ c.fromBufferAttribute(position, ic).applyMatrix4(mesh.matrixWorld);
368
+ const normal = ab.subVectors(b, a).cross(ac.subVectors(c, a));
369
+ const area = normal.length() / 2;
370
+ if (area === 0)
371
+ continue;
372
+ const ny = normal.y / (2 * area);
373
+ if (ny <= UNDERSIDE_MAX_NORMAL_Y) {
374
+ const unit = normal.clone().normalize();
375
+ const key = `${mesh.uuid}|${unit
376
+ .toArray()
377
+ .map((v) => v.toFixed(2))
378
+ .join(',')}`;
379
+ const entry = undersides.get(key) ?? {
380
+ part,
381
+ normal: unit,
382
+ d: -unit.dot(a),
383
+ area: 0,
384
+ points: [],
385
+ };
386
+ entry.area += area;
387
+ entry.points.push([a.x, a.z], [b.x, b.z], [c.x, c.z]);
388
+ undersides.set(key, entry);
389
+ continue;
390
+ }
391
+ if (ny < SURFACE_MIN_NORMAL_Y)
392
+ continue;
393
+ const y = Math.round(((a.y + b.y + c.y) / 3) * 100) / 100;
394
+ // One outline per mesh and height: a hull across meshes would merge a beam
395
+ // and its returns into one surface covering the whole object.
396
+ const key = `${mesh.uuid}|${y}`;
397
+ const entry = surfaces.get(key) ?? { part, y, area: 0, points: [] };
398
+ entry.area += area;
399
+ entry.points.push([a.x, a.z], [b.x, b.z], [c.x, c.z]);
400
+ surfaces.set(key, entry);
401
+ }
402
+ });
403
+ for (const part of parts) {
404
+ const bounds = partBounds.get(part.id);
405
+ if (bounds && !bounds.isEmpty())
406
+ part.bounds = { min: vec(bounds.min), max: vec(bounds.max) };
407
+ }
408
+ const hull = (points) => convexHull(points).map(([x, z]) => [Math.round(x * 1000) / 1000, Math.round(z * 1000) / 1000]);
409
+ return {
410
+ surfaces: [...surfaces.values()]
411
+ .filter((surface) => surface.area >= SURFACE_MIN_AREA)
412
+ .sort((x, y) => y.area - x.area)
413
+ .slice(0, SURFACE_MAX_COUNT)
414
+ .map((surface) => ({ part: surface.part, y: surface.y, polygon: hull(surface.points) })),
415
+ undersides: [...undersides.values()]
416
+ .filter((underside) => underside.area >= SURFACE_MIN_AREA)
417
+ .sort((x, y) => y.area - x.area)
418
+ .slice(0, SURFACE_MAX_COUNT)
419
+ .map((underside) => ({
420
+ part: underside.part,
421
+ polygon: hull(underside.points),
422
+ plane: [
423
+ ...underside.normal.toArray().map((v) => Math.round(v * 1e5) / 1e5),
424
+ Math.round(underside.d * 1e5) / 1e5,
425
+ ],
426
+ })),
427
+ };
428
+ }
429
+ /**
430
+ * Merges each part's meshes by material, so a porch draws as a few dozen
431
+ * meshes instead of hundreds (draw calls, not triangles, are the cost). Part
432
+ * groups keep their names and extras; helpers (cutout, collider) and
433
+ * multi-material meshes stay as authored.
434
+ */
435
+ function mergeByPartAndMaterial(root, animated) {
436
+ const owner = (mesh) => {
437
+ for (let p = mesh.parent; p; p = p.parent) {
438
+ if (p.userData.pascal?.part || p === root)
439
+ return p;
440
+ }
441
+ return root;
442
+ };
443
+ root.updateWorldMatrix(true, true);
444
+ const buckets = new Map();
445
+ root.traverse((object) => {
446
+ const mesh = object;
447
+ if (!mesh.isMesh || isHelper(mesh) || Array.isArray(mesh.material))
448
+ return;
449
+ const group = owner(mesh);
450
+ // A mesh that moves on its own (or under a moving group) keeps its node.
451
+ for (let p = mesh; p && p !== group; p = p.parent) {
452
+ if (animated.has(p))
453
+ return;
454
+ }
455
+ const attributes = Object.keys(mesh.geometry.attributes).sort().join(',');
456
+ const key = `${group.uuid}|${mesh.material.uuid}|${attributes}`;
457
+ const bucket = buckets.get(key) ?? { owner: group, material: mesh.material, meshes: [] };
458
+ bucket.meshes.push(mesh);
459
+ buckets.set(key, bucket);
460
+ });
461
+ const inverse = new THREE.Matrix4();
462
+ for (const { owner: group, material, meshes } of buckets.values()) {
463
+ if (meshes.length < 2)
464
+ continue;
465
+ inverse.copy(group.matrixWorld).invert();
466
+ const geometries = meshes.map((mesh) => {
467
+ const geometry = mesh.geometry.index ? mesh.geometry.toNonIndexed() : mesh.geometry.clone();
468
+ return geometry.applyMatrix4(new THREE.Matrix4().multiplyMatrices(inverse, mesh.matrixWorld));
469
+ });
470
+ const merged = BufferGeometryUtils.mergeGeometries(geometries);
471
+ if (!merged)
472
+ continue;
473
+ for (const mesh of meshes)
474
+ mesh.parent?.remove(mesh);
475
+ const combined = new THREE.Mesh(merged, material);
476
+ combined.name = `${group.name || 'object'}_${material.name}`;
477
+ group.add(combined);
478
+ }
479
+ }
480
+ const ANIMATION_LIMITS = { clips: 32, duration: 120, values: 200_000 };
481
+ /**
482
+ * The module's clips (`group.animations`, as in any three.js project), with
483
+ * every track rebound to its target's uuid: names like `part:door.quaternion`
484
+ * do not survive three's track-name parser, and part objects are renamed for
485
+ * glTF. Returns the clips and the objects they animate.
486
+ */
487
+ function readAnimations(built, root) {
488
+ const clips = (built.animations ?? []).filter(Boolean);
489
+ if (clips.length > ANIMATION_LIMITS.clips) {
490
+ throw new Error(`${clips.length} animation clips exceeds the ${ANIMATION_LIMITS.clips} limit`);
491
+ }
492
+ const objects = [];
493
+ root.traverse((object) => objects.push(object));
494
+ const byLongestName = objects
495
+ .filter((object) => object.name)
496
+ .sort((a, b) => b.name.length - a.name.length);
497
+ const animated = new Set();
498
+ const names = new Set();
499
+ let values = 0;
500
+ for (const clip of clips) {
501
+ if (!(clip instanceof THREE.AnimationClip)) {
502
+ throw new Error('group.animations must hold THREE.AnimationClip instances');
503
+ }
504
+ if (names.has(clip.name))
505
+ throw new Error(`Two animation clips are named "${clip.name}"`);
506
+ names.add(clip.name);
507
+ if (!(clip.duration > 0 && clip.duration <= ANIMATION_LIMITS.duration)) {
508
+ throw new Error(`Clip "${clip.name}" lasts ${clip.duration} s; clips run 0–${ANIMATION_LIMITS.duration} s`);
509
+ }
510
+ for (const track of clip.tracks) {
511
+ const target = objects.find((object) => track.name.startsWith(`${object.uuid}.`)) ??
512
+ byLongestName.find((object) => track.name.startsWith(`${object.name}.`));
513
+ if (!target) {
514
+ throw new Error(`Track "${track.name}" in clip "${clip.name}" targets no object: name the target <objectName>.<property> or <object.uuid>.<property>`);
515
+ }
516
+ const property = track.name.slice((track.name.startsWith(`${target.uuid}.`) ? target.uuid : target.name).length + 1);
517
+ track.name = `${target.uuid}.${property}`;
518
+ animated.add(target);
519
+ values += track.values.length;
520
+ for (const value of track.values) {
521
+ if (!Number.isFinite(value))
522
+ throw new Error(`Clip "${clip.name}" has non-finite keyframes`);
523
+ }
524
+ }
525
+ }
526
+ if (values > ANIMATION_LIMITS.values) {
527
+ throw new Error(`Animations hold ${values} keyframe values; the limit is ${ANIMATION_LIMITS.values}`);
528
+ }
529
+ return { clips, animated };
530
+ }
531
+ const SAMPLE_FPS = 30;
532
+ const MAX_SAMPLES = 900;
533
+ /**
534
+ * glTF stores only position, quaternion and scale tracks, and the exporter
535
+ * silently drops the rest (an Euler `rotation[y]` track, a `position[x]`
536
+ * one). So each clip is played once in a mixer and the transforms it
537
+ * produces are sampled back as position / quaternion / scale tracks: any
538
+ * track that moves objects survives, however the module wrote it.
539
+ */
540
+ function sampleTransformClips(root, clips) {
541
+ const mixer = new THREE.AnimationMixer(root);
542
+ const sampled = [];
543
+ for (const clip of clips) {
544
+ const targets = [
545
+ ...new Set(clip.tracks
546
+ .map((track) => root.getObjectByProperty('uuid', track.name.split('.')[0]))
547
+ .filter((object) => Boolean(object))),
548
+ ];
549
+ const rest = targets.map((object) => ({
550
+ position: object.position.clone(),
551
+ quaternion: object.quaternion.clone(),
552
+ scale: object.scale.clone(),
553
+ }));
554
+ const count = Math.min(MAX_SAMPLES, Math.ceil(clip.duration * SAMPLE_FPS) + 1);
555
+ const times = Array.from({ length: count }, (_, i) => (clip.duration * i) / (count - 1));
556
+ const values = targets.map(() => ({
557
+ position: [],
558
+ quaternion: [],
559
+ scale: [],
560
+ }));
561
+ const action = mixer.clipAction(clip);
562
+ // Played once and held: a looping action wraps to its first frame at the
563
+ // clip's end, so `open` would be stored ending closed.
564
+ action.setLoop(THREE.LoopOnce, 1);
565
+ action.clampWhenFinished = true;
566
+ action.play();
567
+ for (const time of times) {
568
+ mixer.setTime(time);
569
+ targets.forEach((object, k) => {
570
+ values[k].position.push(...object.position.toArray());
571
+ values[k].quaternion.push(...object.quaternion.toArray());
572
+ values[k].scale.push(...object.scale.toArray());
573
+ });
574
+ }
575
+ action.stop();
576
+ mixer.uncacheClip(clip);
577
+ const tracks = [];
578
+ targets.forEach((object, k) => {
579
+ const { position, quaternion, scale } = rest[k];
580
+ object.position.copy(position);
581
+ object.quaternion.copy(quaternion);
582
+ object.scale.copy(scale);
583
+ const moves = (series, base) => series.some((value, i) => Math.abs(value - base[i % base.length]) > 1e-6);
584
+ const v = values[k];
585
+ if (moves(v.position, position.toArray()))
586
+ tracks.push(new THREE.VectorKeyframeTrack(`${object.uuid}.position`, times, v.position));
587
+ if (moves(v.quaternion, quaternion.toArray()))
588
+ tracks.push(new THREE.QuaternionKeyframeTrack(`${object.uuid}.quaternion`, times, v.quaternion));
589
+ if (moves(v.scale, scale.toArray()))
590
+ tracks.push(new THREE.VectorKeyframeTrack(`${object.uuid}.scale`, times, v.scale));
591
+ });
592
+ if (tracks.length === 0) {
593
+ throw new Error(`Clip "${clip.name}" moves nothing: only position, rotation and scale animate (material or visibility tracks do not)`);
594
+ }
595
+ sampled.push(new THREE.AnimationClip(clip.name, clip.duration, tracks));
596
+ }
597
+ root.updateWorldMatrix(true, true);
598
+ return sampled;
599
+ }
600
+ // GLTFExporter writes binaries through FileReader, which Bun and Node lack.
601
+ function ensureFileReader() {
602
+ const g = globalThis;
603
+ if (g.FileReader)
604
+ return;
605
+ g.FileReader = class {
606
+ result = null;
607
+ onloadend = null;
608
+ readAsArrayBuffer(blob) {
609
+ void blob.arrayBuffer().then((buffer) => {
610
+ this.result = buffer;
611
+ this.onloadend?.();
612
+ });
613
+ }
614
+ readAsDataURL(blob) {
615
+ void blob.arrayBuffer().then((buffer) => {
616
+ this.result = `data:${blob.type};base64,${Buffer.from(buffer).toString('base64')}`;
617
+ this.onloadend?.();
618
+ });
619
+ }
620
+ };
621
+ }
622
+ async function exportGlb(root, animations) {
623
+ ensureFileReader();
624
+ const exporter = new GLTFExporter();
625
+ const result = await exporter.parseAsync(root, { binary: true, onlyVisible: false, animations });
626
+ if (!(result instanceof ArrayBuffer))
627
+ throw new Error('GLB export returned JSON instead of binary');
628
+ return result;
629
+ }
630
+ /** Outlines keep at most this many corners; a 64-sided circle reads the same with 16. */
631
+ const MAX_OUTLINE_POINTS = 16;
632
+ function thin(points) {
633
+ if (points.length <= MAX_OUTLINE_POINTS)
634
+ return points;
635
+ const step = points.length / MAX_OUTLINE_POINTS;
636
+ return Array.from({ length: MAX_OUTLINE_POINTS }, (_, i) => points[Math.floor(i * step)]);
637
+ }
638
+ function outlineArea(polygon) {
639
+ let area = 0;
640
+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
641
+ area += polygon[j][0] * polygon[i][1] - polygon[i][0] * polygon[j][1];
642
+ }
643
+ return Math.abs(area) / 2;
644
+ }
645
+ const manifestBytes = (manifest) => new TextEncoder().encode(JSON.stringify(manifest)).byteLength;
646
+ /**
647
+ * The manifest rides inline in the node, so it stays under
648
+ * GEOMETRY_MANIFEST_MAX_BYTES: outlines are thinned (cutter footprints only
649
+ * when still over, since a coarser footprint changes the hole), then the smallest
650
+ * surfaces and undersides go first (placement falls back to the bounds there),
651
+ * then trailing part entries. The build itself never fails over its size.
652
+ */
653
+ function compactManifest(manifest) {
654
+ const next = {
655
+ ...manifest,
656
+ surfaces: manifest.surfaces.map((surface) => ({ ...surface, polygon: thin(surface.polygon) })),
657
+ undersides: manifest.undersides.map((underside) => ({
658
+ ...underside,
659
+ polygon: thin(underside.polygon),
660
+ })),
661
+ };
662
+ const bySize = (a, b) => outlineArea(b.polygon) - outlineArea(a.polygon);
663
+ next.surfaces.sort(bySize);
664
+ next.undersides.sort(bySize);
665
+ if (manifestBytes(next) > GEOMETRY_MANIFEST_MAX_BYTES) {
666
+ next.cutters = next.cutters?.map((cutter) => ({ ...cutter, polygon: thin(cutter.polygon) }));
667
+ }
668
+ while (manifestBytes(next) > GEOMETRY_MANIFEST_MAX_BYTES) {
669
+ const last = (list) => list.length ? outlineArea(list[list.length - 1].polygon) : Number.POSITIVE_INFINITY;
670
+ if (next.surfaces.length || next.undersides.length) {
671
+ if (last(next.surfaces) <= last(next.undersides))
672
+ next.surfaces.pop();
673
+ else
674
+ next.undersides.pop();
675
+ }
676
+ else if (next.parts.length)
677
+ next.parts.pop();
678
+ else
679
+ break;
680
+ }
681
+ return next;
682
+ }
683
+ async function digest(bytes) {
684
+ // An opaque-origin sandbox has no WebCrypto; its host hashes what it receives.
685
+ if (!globalThis.crypto?.subtle)
686
+ return '';
687
+ const hash = await crypto.subtle.digest('SHA-256', bytes);
688
+ return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
689
+ }
690
+ /**
691
+ * Everything after a module has built its object, whatever the language:
692
+ * re-origins it for its mount, reads the conventions into the manifest, samples
693
+ * its clips and exports the GLB. `built.animations` holds its clips.
694
+ */
695
+ export async function finishBuild({ built, mount, specs, params, code, language, }) {
696
+ const root = new THREE.Group();
697
+ root.name = 'pascal_script_root';
698
+ root.add(built);
699
+ const box = visibleBounds(root);
700
+ if (box.isEmpty())
701
+ throw new Error('build() returned no visible meshes');
702
+ const size = box.getSize(new THREE.Vector3());
703
+ if (Math.max(size.x, size.y, size.z) > GEOMETRY_SCRIPT_LIMITS.extent) {
704
+ throw new Error(`The object is ${vec(size).join(' × ')} m; the limit is ${GEOMETRY_SCRIPT_LIMITS.extent} m per side. Units are metres.`);
705
+ }
706
+ built.position.sub(originFor(box, mount));
707
+ root.updateWorldMatrix(true, true);
708
+ const read = readAnimations(built, root);
709
+ const clips = sampleTransformClips(root, read.clips);
710
+ const animated = read.animated;
711
+ const conventions = readConventions(root);
712
+ if (conventions.triangles > GEOMETRY_SCRIPT_LIMITS.triangles) {
713
+ throw new Error(`${conventions.triangles} triangles exceeds the ${GEOMETRY_SCRIPT_LIMITS.triangles} limit`);
714
+ }
715
+ if (conventions.materialCount > GEOMETRY_SCRIPT_LIMITS.materials) {
716
+ throw new Error(`${conventions.materialCount} materials exceeds the ${GEOMETRY_SCRIPT_LIMITS.materials} limit`);
717
+ }
718
+ const { surfaces, undersides } = analyseGeometry(root, conventions.parts);
719
+ mergeByPartAndMaterial(root, animated);
720
+ const bounds = visibleBounds(root);
721
+ const glb = await exportGlb(root, clips);
722
+ return {
723
+ glb,
724
+ sha256: await digest(glb),
725
+ script: await digest(new TextEncoder().encode(code)),
726
+ language,
727
+ mount,
728
+ params,
729
+ manifest: compactManifest({
730
+ bounds: { min: vec(bounds.min), max: vec(bounds.max) },
731
+ params: specs,
732
+ parts: conventions.parts,
733
+ surfaces,
734
+ undersides,
735
+ slots: conventions.slots,
736
+ anchors: conventions.anchors,
737
+ lights: conventions.lights,
738
+ animations: clips.map((clip) => ({
739
+ name: clip.name,
740
+ duration: Math.round(clip.duration * 1000) / 1000,
741
+ })),
742
+ cutters: readCutters(root, mount),
743
+ cutout: conventions.cutout,
744
+ collider: conventions.collider,
745
+ triangles: conventions.triangles,
746
+ }),
747
+ };
748
+ }
749
+ // A deterrent, not the isolation boundary: hosts run this in a locked-down worker or process.
750
+ const SOURCE_GUARD = /\bimport\s*\(|\beval\s*\(|\bFunction\s*\(|\.constructor\s*\(|\bprocess\b|\brequire\s*\(/;
751
+ export function assertScriptSize(code) {
752
+ if (new TextEncoder().encode(code).byteLength > GEOMETRY_SCRIPT_MAX_BYTES) {
753
+ throw new Error(`The script is longer than ${GEOMETRY_SCRIPT_MAX_BYTES / 1024} KiB`);
754
+ }
755
+ }
756
+ export async function compileGeometryScript(input) {
757
+ assertScriptSize(input.code);
758
+ if (SOURCE_GUARD.test(input.code)) {
759
+ throw new Error('Geometry scripts cannot use dynamic import, eval, Function constructors, process or require');
760
+ }
761
+ const body = transformModule(input.code, MODULES);
762
+ // Evaluating the model's module is the compiler's job; callers run it in a locked-down worker.
763
+ const factory = new Function('__modules', 'THREE', 'lib', body);
764
+ const exported = factory(MODULES, THREE, LIB);
765
+ if (typeof exported.build !== 'function') {
766
+ throw new Error('The script must `export default function build({ params, THREE, lib })`');
767
+ }
768
+ const mount = (exported.mount ?? 'floor');
769
+ if (!MOUNTS.has(mount))
770
+ throw new Error(`\`mount\` must be one of ${[...MOUNTS].join(', ')}`);
771
+ const specs = readParamSpecs(exported.params);
772
+ const params = resolveParams(specs, input.params ?? {});
773
+ const built = await exported.build({
774
+ params,
775
+ inputs: {},
776
+ THREE,
777
+ lib: LIB,
778
+ });
779
+ if (!(built instanceof THREE.Object3D)) {
780
+ throw new Error('build() must return a THREE.Object3D (usually a THREE.Group)');
781
+ }
782
+ return finishBuild({ built, mount, specs, params, code: input.code, language: 'three' });
783
+ }