@tora-editor/tora 0.2.0 → 0.3.0

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 (107) hide show
  1. package/README.md +5 -6
  2. package/bin/tora.mjs +255 -29
  3. package/crates/packer/trusted/native-3d-meta.json +3 -3
  4. package/crates/packer/trusted/native-3d.js +180 -180
  5. package/crates/packer/trusted/native-meta.json +3 -3
  6. package/crates/packer/trusted/native.js +5 -5
  7. package/crates/packer/trusted/release-manifest.json +17 -17
  8. package/crates/packer/trusted/review-runtime-meta.json +3 -3
  9. package/crates/packer/trusted/review-runtime.js +182 -182
  10. package/docs/MIGRATION_0_3.md +39 -0
  11. package/docs/NATIVE_AGENT_TOOLS.md +12 -363
  12. package/docs/TORA_AGENT_SETUP.md +24 -106
  13. package/docs/TORA_CREATION_API.md +63 -365
  14. package/docs/reference/CORE_AUTHORING.md +8 -2
  15. package/docs/reference/PLAYABLE_STARTERS.md +1 -1
  16. package/docs/reference/packs/3d.md +2 -0
  17. package/package.json +6 -6
  18. package/packages/creative-project/project-v21.schema.json +108 -1
  19. package/scripts/lean/editor/entry.js +11 -6
  20. package/scripts/lean/editor/project-launcher.js +116 -0
  21. package/scripts/lean/editor/quick-edit-panel.js +479 -0
  22. package/scripts/lean/editor/review-editor.css +246 -68
  23. package/scripts/lean/editor/review-editor.js +1731 -1099
  24. package/scripts/lean/editor-state.mjs +6 -0
  25. package/scripts/lean/editor.mjs +6 -3
  26. package/scripts/lean/matrix.mjs +5 -0
  27. package/scripts/lean/native/agent-tools.mjs +35 -58
  28. package/scripts/lean/native/api.mjs +148 -134
  29. package/scripts/lean/native/audio-assets.mjs +30 -0
  30. package/scripts/lean/native/browser-pool.mjs +34 -0
  31. package/scripts/lean/native/build-cache.mjs +36 -5
  32. package/scripts/lean/native/contracts.mjs +8 -6
  33. package/scripts/lean/native/creative-qa.mjs +66 -12
  34. package/scripts/lean/native/demos.mjs +11 -20
  35. package/scripts/lean/native/document.mjs +14 -2
  36. package/scripts/lean/native/local-bundle.mjs +4 -2
  37. package/scripts/lean/native/mcp-server.mjs +16 -35
  38. package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
  39. package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
  40. package/scripts/lean/native/modules/star-salvage.mjs +3 -368
  41. package/scripts/lean/native/project-bundle.mjs +3 -2
  42. package/scripts/lean/native/project-index.mjs +0 -2
  43. package/scripts/lean/native/qa-adapters.mjs +10 -0
  44. package/scripts/lean/native/quick-edit.mjs +328 -0
  45. package/scripts/lean/native/review.mjs +203 -572
  46. package/scripts/lean/native/schema-vocabulary.mjs +10 -0
  47. package/scripts/lean/native/schema.mjs +1 -1
  48. package/scripts/lean/native/scope.mjs +45 -0
  49. package/scripts/lean/native/service.mjs +242 -70
  50. package/scripts/lean/native/starters.mjs +135 -8
  51. package/scripts/lean/native/variant-adapters.mjs +8 -0
  52. package/scripts/lean/native/variants-core.mjs +186 -0
  53. package/scripts/lean/native/variants.mjs +63 -0
  54. package/scripts/lean/native/win-cues.mjs +1 -1
  55. package/skills/tora-playables/SKILL.md +1 -1
  56. package/scripts/lean/editor/review-intake.js +0 -837
  57. package/scripts/lean/model-client.mjs +0 -119
  58. package/scripts/lean/native/author-expansion-proofs.mjs +0 -143
  59. package/scripts/lean/native/author-fps.mjs +0 -545
  60. package/scripts/lean/native/author-games.mjs +0 -160
  61. package/scripts/lean/native/author-harvest.mjs +0 -74
  62. package/scripts/lean/native/author-primitive-proofs.mjs +0 -875
  63. package/scripts/lean/native/author-salvage.mjs +0 -71
  64. package/scripts/lean/native/chat-compose.mjs +0 -287
  65. package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -190
  66. package/scripts/lean/native/check-salvage.mjs +0 -200
  67. package/scripts/lean/native/compatibility.mjs +0 -34
  68. package/scripts/lean/native/concept.mjs +0 -633
  69. package/scripts/lean/native/draw-stroke.mjs +0 -26
  70. package/scripts/lean/native/erase-mask.mjs +0 -18
  71. package/scripts/lean/native/glb-loader.mjs +0 -468
  72. package/scripts/lean/native/harvest-recipe.mjs +0 -21
  73. package/scripts/lean/native/instance-steering.mjs +0 -24
  74. package/scripts/lean/native/intake-creator-agent.mjs +0 -98
  75. package/scripts/lean/native/intake-creator-tools.mjs +0 -218
  76. package/scripts/lean/native/interaction-gestures.mjs +0 -45
  77. package/scripts/lean/native/match-board.mjs +0 -138
  78. package/scripts/lean/native/modules/index.mjs +0 -54
  79. package/scripts/lean/native/modules/tap-collect.mjs +0 -54
  80. package/scripts/lean/native/path-network.mjs +0 -132
  81. package/scripts/lean/native/physics-2d.mjs +0 -154
  82. package/scripts/lean/native/physics-3d.mjs +0 -259
  83. package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
  84. package/scripts/lean/native/prepare-fps-assets.mjs +0 -330
  85. package/scripts/lean/native/prepare-game-audio.mjs +0 -372
  86. package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
  87. package/scripts/lean/native/prepare-golf-assets.py +0 -211
  88. package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
  89. package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
  90. package/scripts/lean/native/prepare-primitive-images.py +0 -25
  91. package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
  92. package/scripts/lean/native/prepare-traffic-assets.py +0 -329
  93. package/scripts/lean/native/presentation.mjs +0 -335
  94. package/scripts/lean/native/review-agent-tools.mjs +0 -561
  95. package/scripts/lean/native/review-connection.mjs +0 -303
  96. package/scripts/lean/native/review-fields.mjs +0 -24
  97. package/scripts/lean/native/review-intake.mjs +0 -385
  98. package/scripts/lean/native/review-intents.mjs +0 -217
  99. package/scripts/lean/native/review-provider.mjs +0 -580
  100. package/scripts/lean/native/review-receipts.mjs +0 -76
  101. package/scripts/lean/native/review-resolver.mjs +0 -429
  102. package/scripts/lean/native/review-targets.mjs +0 -35
  103. package/scripts/lean/native/runtime.mjs +0 -1809
  104. package/scripts/lean/native/salvage-recipe.mjs +0 -20
  105. package/scripts/lean/native/stage-3d.mjs +0 -1121
  106. package/scripts/lean/native/verify.mjs +0 -4
  107. package/scripts/lean/scene-document.mjs +0 -48
@@ -1,1121 +0,0 @@
1
- /* global atob,document,Image */
2
- import {parseGlb, cloneModelTemplate, createModelAnimator} from './glb-loader.mjs';
3
- import {
4
- Scene, Color, PerspectiveCamera, WebGLRenderer, BufferGeometry, Float32BufferAttribute,
5
- Mesh, InstancedMesh, Matrix4, MeshLambertMaterial, MeshBasicMaterial, DirectionalLight, HemisphereLight, Group,
6
- BoxGeometry, CylinderGeometry, SphereGeometry, RingGeometry, CircleGeometry, Shape, Path,
7
- ShapeGeometry, Texture, SRGBColorSpace, Vector3, Vector2, Plane, Raycaster, PCFSoftShadowMap, DoubleSide,
8
- NoColorSpace, NoToneMapping, ACESFilmicToneMapping, NeutralToneMapping, DataTexture,
9
- EquirectangularReflectionMapping, PMREMGenerator, RepeatWrapping, Euler, Object3D,
10
- } from 'three';
11
-
12
- export function contactOrigin3d(component, object, props, bodies){
13
- const origin = new Vector3();
14
- const local = new Vector3();
15
- const rotation = new Euler();
16
- for(let mesh = component; mesh?.contract === 'native.mesh3d.v1'; mesh = object(mesh.parentId)){
17
- const p = props(mesh);
18
- const body = bodies.get(mesh.id);
19
- const dynamic = body?.mode === 'dynamic';
20
- const captured = dynamic && body.captured;
21
- const progress = captured ? Math.min(1, (body.captureElapsed ?? 0) / .55) : 0;
22
- const target = body?.captureTarget;
23
- const scale = 1 - progress * .65;
24
- local.set(p.sx * scale, p.sy * scale, p.sz * scale);
25
- rotation.set(
26
- dynamic ? -(body.spin ?? 0) : p.rx,
27
- body?.mode === 'kinematic' ? -(body.angle ?? p.ry) : p.ry,
28
- dynamic ? (body.spin ?? 0) * .22 : p.rz,
29
- );
30
- origin.multiply(local).applyEuler(rotation);
31
- local.set(
32
- (body?.x ?? p.x) + (captured && target ? (target.x - body.x) * progress : 0),
33
- (body?.y ?? p.y) - progress * .45,
34
- (body?.z ?? p.z) + (captured && target ? (target.z - body.z) * progress : 0),
35
- );
36
- origin.add(local);
37
- }
38
- return {x:origin.x,y:origin.y,z:origin.z};
39
- }
40
-
41
- function decodeToraMesh(base64) {
42
- const bin = atob(base64);
43
- const bytes = new Uint8Array(bin.length);
44
- for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
45
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
46
- const vertexCount = view.getUint32(8, true);
47
- const indexCount = view.getUint32(12, true);
48
- const positions = new Float32Array(vertexCount * 3);
49
- const normals = new Float32Array(vertexCount * 3);
50
- const uvs = new Float32Array(vertexCount * 2);
51
- let off = 16;
52
- for (let i = 0; i < vertexCount; i++) {
53
- positions[i * 3] = view.getFloat32(off, true);
54
- positions[i * 3 + 1] = view.getFloat32(off + 4, true);
55
- positions[i * 3 + 2] = view.getFloat32(off + 8, true);
56
- normals[i * 3] = view.getFloat32(off + 12, true);
57
- normals[i * 3 + 1] = view.getFloat32(off + 16, true);
58
- normals[i * 3 + 2] = view.getFloat32(off + 20, true);
59
- uvs[i * 2] = view.getFloat32(off + 24, true);
60
- uvs[i * 2 + 1] = view.getFloat32(off + 28, true);
61
- off += 32;
62
- }
63
- const indices = new Uint16Array(indexCount);
64
- for (let i = 0; i < indexCount; i++) {
65
- indices[i] = view.getUint16(off + i * 2, true);
66
- }
67
- const geo = new BufferGeometry();
68
- geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
69
- geo.setAttribute('normal', new Float32BufferAttribute(normals, 3));
70
- geo.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
71
- geo.setIndex(Array.from(indices));
72
- return geo;
73
- }
74
-
75
- function fairwayGround(ramp, x, z) {
76
- if (!ramp) return 0;
77
- if (z >= 1) return 0;
78
- if (z <= -1) return 1.1;
79
- return (1 - z) * 0.55;
80
- }
81
-
82
- function buildFairwayGroup(params, sharedTexture, openGeo) {
83
- const group = new Group();
84
- const ramp = Boolean(params.fairwayRamp);
85
- const cupX = params.cupX ?? 0;
86
- const cupZ = params.cupZ ?? -4.8;
87
- const cupR = params.cupRadius ?? 0.23;
88
- // Plinth & cream border framing (matching original scene.ts verbatim)
89
- const unitBox = new BoxGeometry(1, 1, 1);
90
- const boxMats = new Map();
91
- const addBox = (x, y, z, w, h, d, color) => {
92
- let mat = boxMats.get(color);
93
- if (!mat) { mat = new MeshLambertMaterial({color}); boxMats.set(color, mat); }
94
- const mesh = new Mesh(unitBox, mat);
95
- mesh.position.set(x, y, z);
96
- mesh.scale.set(w, h, d);
97
- group.add(mesh);
98
- };
99
- for (const x of [-3.2, 3.2]) {
100
- addBox(x, -0.65, 0, 0.2, 1.1, 14.6, '#a1b8b1');
101
- addBox(x - Math.sign(x) * 0.1, -0.18, 0, 0.2, 0.25, 14.4, '#e9cea5');
102
- }
103
- for (const z of [-7.2, 7.2]) {
104
- addBox(0, -0.65, z, 6.4, 1.1, 0.2, '#a1b8b1');
105
- addBox(0, -0.18, z - Math.sign(z) * 0.1, 6.2, 0.25, 0.2, '#e9cea5');
106
- }
107
- let grassU = 0.5, grassV = 0.5;
108
- if (openGeo) {
109
- const uvAttr = openGeo.getAttribute('uv');
110
- const nAttr = openGeo.getAttribute('normal');
111
- if (uvAttr && nAttr) {
112
- let idx = 0;
113
- while (idx < nAttr.count && nAttr.getY(idx) < 0.9) idx++;
114
- if (idx < uvAttr.count) {
115
- grassU = uvAttr.getX(idx);
116
- grassV = uvAttr.getY(idx);
117
- }
118
- }
119
- }
120
- const texReady = Boolean(sharedTexture && sharedTexture.image?.complete && sharedTexture.image?.naturalWidth > 0);
121
- const baseMat = texReady ? new MeshLambertMaterial({map: sharedTexture}) : new MeshLambertMaterial({color: '#6ec458'});
122
- const slopeMat = texReady ? new MeshLambertMaterial({map: sharedTexture, color: '#779263'}) : new MeshLambertMaterial({color: '#5a9949'});
123
- if (sharedTexture && !texReady) {
124
- baseMat.userData.pendingTex = {tex: sharedTexture, color: '#ffffff'};
125
- slopeMat.userData.pendingTex = {tex: sharedTexture, color: '#779263'};
126
- }
127
- const bands = ramp ? [[-7, -1], [-1, 1], [1, 7]] : [[-7, 7]];
128
- for (const [near, far] of bands) {
129
- const shape = new Shape();
130
- shape.moveTo(-3, near);
131
- shape.lineTo(3, near);
132
- shape.lineTo(3, far);
133
- shape.lineTo(-3, far);
134
- shape.closePath();
135
- if (cupZ > near && cupZ < far) {
136
- const hole = new Path();
137
- hole.absarc(cupX, cupZ, cupR, 0, Math.PI * 2, true);
138
- shape.holes.push(hole);
139
- }
140
- const geo = new ShapeGeometry(shape, 32);
141
- const pos = geo.getAttribute('position');
142
- let hasZero = false, hasPos = false;
143
- for (let i = 0; i < pos.count; i++) {
144
- const gx = pos.getX(i), gz = pos.getY(i);
145
- const gy = fairwayGround(ramp, gx, gz);
146
- if (gy === 0) hasZero = true;
147
- if (gy > 0) hasPos = true;
148
- pos.setXYZ(i, gx, gy, gz);
149
- }
150
- const index = geo.getIndex();
151
- if (index) {
152
- for (let i = 0; i < index.count; i += 3) {
153
- const b = index.getX(i + 1);
154
- index.setX(i + 1, index.getX(i + 2));
155
- index.setX(i + 2, b);
156
- }
157
- }
158
- geo.computeVertexNormals();
159
- const uv = geo.getAttribute('uv');
160
- for (let i = 0; i < uv.count; i++) uv.setXY(i, grassU, grassV);
161
- const surface = new Mesh(geo, ramp && hasZero && hasPos ? slopeMat : baseMat);
162
- surface.name = 'continuous-fairway';
163
- group.add(surface);
164
- }
165
- // Cedar wooden perimeter rails & top bevel
166
- const rail = '#d69260', top = '#f1bd87';
167
- for (const x of [-3.1, 3.1]) {
168
- addBox(x, 0.12, 0, 0.2, 0.3, 14.2, rail);
169
- addBox(x, 0.29, 0, 0.22, 0.04, 14.2, top);
170
- }
171
- for (const z of [-7.1, 7.1]) {
172
- addBox(0, fairwayGround(ramp, 0, z > 0 ? 6 : -6) + 0.12, z, 6.4, 0.3, 0.2, rail);
173
- }
174
- if (ramp) {
175
- for (const x of [-3.1, 3.1]) addBox(x, 0.7, -4.5, 0.2, 1.1, 5.2, rail);
176
- }
177
- return group;
178
- }
179
-
180
- function buildCupGroup(params) {
181
- const group = new Group();
182
- const r = params.cupRadius ?? 0.23;
183
- const cup = new Mesh(new CylinderGeometry(r, r * 0.89, 0.48, 24, 1, true), new MeshLambertMaterial({color: '#244640', side: DoubleSide}));
184
- cup.position.y = -0.24;
185
- group.add(cup);
186
- const bottom = new Mesh(new CircleGeometry(r * 0.91, 24), new MeshBasicMaterial({color: '#082c2b'}));
187
- bottom.rotation.x = -Math.PI / 2;
188
- bottom.position.y = -0.475;
189
- group.add(bottom);
190
- const lining = new Mesh(new CylinderGeometry(r, r * 0.978, 0.09, 24, 1, true), new MeshLambertMaterial({color: '#eee9cf', side: DoubleSide}));
191
- lining.position.y = -0.045;
192
- group.add(lining);
193
- const rim = new Mesh(new RingGeometry(r, r + 0.06, 24), new MeshLambertMaterial({color: '#fff7d1'}));
194
- rim.rotation.x = -Math.PI / 2;
195
- rim.position.y = 0.004;
196
- group.add(rim);
197
- return group;
198
- }
199
-
200
- function buildGardenGroup() {
201
- const group = new Group();
202
- const trunkGeo = new BoxGeometry(0.18, 1, 0.18);
203
- const trunkMat = new MeshLambertMaterial({color: '#b27b59'});
204
- const padGeo = new BoxGeometry(1.5, 0.2, 1.6);
205
- const padMat = new MeshLambertMaterial({color: '#82b88b'});
206
- const leafGeo0 = new SphereGeometry(0.62, 7, 5);
207
- const leafGeo1 = new SphereGeometry(0.49, 7, 5);
208
- const leafMatA = new MeshLambertMaterial({color: '#77b86b'});
209
- const leafMatB = new MeshLambertMaterial({color: '#3e9d79'});
210
- const trunks = new InstancedMesh(trunkGeo, trunkMat, 14);
211
- const pads = new InstancedMesh(padGeo, padMat, 14);
212
- const countA = 5; // i = 0, 3, 6, 9, 12
213
- const countB = 9;
214
- const leavesA0 = new InstancedMesh(leafGeo0, leafMatA, countA);
215
- const leavesA1 = new InstancedMesh(leafGeo1, leafMatA, countA);
216
- const leavesB0 = new InstancedMesh(leafGeo0, leafMatB, countB);
217
- const leavesB1 = new InstancedMesh(leafGeo1, leafMatB, countB);
218
- const mat4 = new Matrix4();
219
- let ia = 0, ib = 0;
220
- for (let i = 0; i < 14; i++) {
221
- const side = i % 2 ? -1 : 1;
222
- const x = side * (3.8 + (i % 3) * 0.35);
223
- const z = -6.5 + Math.floor(i / 2) * 2;
224
- mat4.makeTranslation(x, -0.02, z);
225
- trunks.setMatrixAt(i, mat4);
226
- mat4.makeTranslation(x, -0.48, z);
227
- pads.setMatrixAt(i, mat4);
228
- if (i % 3 === 0) {
229
- mat4.makeTranslation(x, 0.5, z);
230
- leavesA0.setMatrixAt(ia, mat4);
231
- mat4.makeTranslation(x, 1.0, z);
232
- leavesA1.setMatrixAt(ia, mat4);
233
- ia++;
234
- } else {
235
- mat4.makeTranslation(x, 0.5, z);
236
- leavesB0.setMatrixAt(ib, mat4);
237
- mat4.makeTranslation(x, 1.0, z);
238
- leavesB1.setMatrixAt(ib, mat4);
239
- ib++;
240
- }
241
- }
242
- for (const inst of [trunks, pads, leavesA0, leavesA1, leavesB0, leavesB1]) {
243
- inst.instanceMatrix.needsUpdate = true;
244
- group.add(inst);
245
- }
246
- return group;
247
- }
248
-
249
- function waveFlagGeometry(geometry, rest, time) {
250
- const p = geometry.getAttribute('position');
251
- for (let i = 0; i < p.count; i++) {
252
- const x = rest[i * 3], y = rest[i * 3 + 1], z = rest[i * 3 + 2];
253
- const weight = y > 0.7 ? Math.max(0, Math.min(1, (-x - 0.035) / 0.32)) : 0;
254
- p.setXYZ(i, x, y + Math.sin(time * 3.2 + x * 10) * 0.018 * weight, z + Math.sin(time * 3.2 + x * 10 + y * 2) * 0.07 * weight);
255
- }
256
- p.needsUpdate = true;
257
- geometry.computeVertexNormals();
258
- }
259
-
260
- function studioEnvironment(renderer) {
261
- const w = 64, h = 32, pixels = new Uint8Array(w * h * 4);
262
- for (let y = 0; y < h; y++) {
263
- const elevation = y / (h - 1);
264
- for (let x = 0; x < w; x++) {
265
- const u = x / w, i = (y * w + x) * 4;
266
- const key = Math.exp(-((u - 0.35) ** 2 / 0.012 + (elevation - 0.7) ** 2 / 0.018));
267
- const rim = Math.exp(-((u - 0.79) ** 2 / 0.004 + (elevation - 0.58) ** 2 / 0.055));
268
- pixels[i] = Math.min(255, 21 + elevation * 90 + key * 180 + rim * 125);
269
- pixels[i + 1] = Math.min(255, 22 + elevation * 105 + key * 158 + rim * 145);
270
- pixels[i + 2] = Math.min(255, 24 + elevation * 127 + key * 128 + rim * 180);
271
- pixels[i + 3] = 255;
272
- }
273
- }
274
- const texture = new DataTexture(pixels, w, h);
275
- texture.mapping = EquirectangularReflectionMapping;
276
- texture.needsUpdate = true;
277
- const generator = new PMREMGenerator(renderer);
278
- try { return generator.fromEquirectangular(texture); }
279
- finally { generator.dispose(); texture.dispose(); }
280
- }
281
-
282
- /** Manages one Three.js WebGL2 offscreen canvas per active native.stage3d.v1 component. */
283
- export function createStage3dManager(project, assetsMap, onTextureReady, overrides = new Map()) {
284
- const meshCache = new Map();
285
- const textureCache = new Map(), modelCache = new Map();
286
- const sharedGeometry = new Set(), sharedMaterials = new Set();
287
- let environment;
288
-
289
- function dirtyTextures() {
290
- for (const stage of stages.values()) stage.textureDirty = true;
291
- onTextureReady?.();
292
- }
293
-
294
- function getModel(asset) {
295
- if (!modelCache.has(asset.hash ?? asset.id)) {
296
- const bytes = Uint8Array.from(atob(asset.data), char => char.charCodeAt(0));
297
- const model = parseGlb(bytes, dirtyTextures);
298
- for (const geometry of model.geometries) sharedGeometry.add(geometry);
299
- for (const material of model.materials) sharedMaterials.add(material);
300
- modelCache.set(asset.hash ?? asset.id, model);
301
- }
302
- return modelCache.get(asset.hash ?? asset.id);
303
- }
304
-
305
- function disposeTree(root) {
306
- const geometry = new Set(), materials = new Set();
307
- root.traverse(obj => {
308
- if (obj.geometry && !sharedGeometry.has(obj.geometry)) geometry.add(obj.geometry);
309
- if (obj.material) for (const mat of Array.isArray(obj.material) ? obj.material : [obj.material]) {
310
- if (!sharedMaterials.has(mat)) materials.add(mat);
311
- }
312
- });
313
- for (const geo of geometry) geo.dispose();
314
- for (const mat of materials) mat.dispose();
315
- }
316
-
317
- const stages = new Map();
318
- let sharedGlCanvas, sharedRenderer, sharedCacheCanvas, sharedCacheCtx, sharedStageId;
319
-
320
- function ensureRenderer() {
321
- if (sharedRenderer !== undefined) return sharedRenderer;
322
- try {
323
- sharedGlCanvas = document.createElement('canvas');
324
- sharedGlCanvas.addEventListener?.('webglcontextrestored', () => {
325
- sharedStageId = undefined;
326
- for (const entry of stages.values()) {
327
- entry.compiled = false;
328
- entry.textureDirty = true;
329
- entry.lastRenderedTime = -1;
330
- entry.lastFlagStep = -1;
331
- }
332
- onTextureReady?.();
333
- });
334
- sharedCacheCanvas = document.createElement('canvas');
335
- sharedCacheCtx = sharedCacheCanvas.getContext?.('2d');
336
- sharedRenderer = new WebGLRenderer({
337
- canvas: sharedGlCanvas,
338
- antialias: true,
339
- alpha: false,
340
- preserveDrawingBuffer: false,
341
- powerPreference: 'default',
342
- });
343
- sharedRenderer.shadowMap.type = PCFSoftShadowMap;
344
- return sharedRenderer;
345
- } catch {
346
- sharedRenderer = null;
347
- return null;
348
- }
349
- }
350
-
351
- function getMeshGeometry(assetId) {
352
- if (!assetId) return undefined;
353
- if (meshCache.has(assetId)) return meshCache.get(assetId);
354
- const asset = assetsMap.get(assetId);
355
- if (!asset || asset.mime !== 'model/tora-mesh' || !asset.data) return undefined;
356
- const geo = decodeToraMesh(asset.data);
357
- meshCache.set(assetId, geo);
358
- sharedGeometry.add(geo);
359
- return geo;
360
- }
361
-
362
- function getTexture(assetId, usage) {
363
- if (!assetId) return undefined;
364
- const key = (usage ?? 'stage') + ':' + assetId;
365
- if (textureCache.has(key)) return textureCache.get(key);
366
- const asset = assetsMap.get(assetId);
367
- if (!asset || !asset.mime.startsWith('image/') || !asset.data) return undefined;
368
- const img = new Image();
369
- const tex = new Texture(img);
370
- tex.colorSpace = usage === 'normalMap' ? NoColorSpace : SRGBColorSpace;
371
- if (usage) {
372
- tex.flipY = false;
373
- tex.wrapS = tex.wrapT = RepeatWrapping;
374
- }
375
- const markLoaded = notify => {
376
- tex.needsUpdate = true;
377
- for (const entry of stages.values()) {
378
- entry.scene.traverse(obj => {
379
- const mats = obj.isMesh && obj.material ? (Array.isArray(obj.material) ? obj.material : [obj.material]) : [];
380
- for (const m of mats) {
381
- if (m.userData?.pendingTex && m.userData.pendingTex.tex === tex) {
382
- m.map = tex;
383
- m.color.set(m.userData.pendingTex.color || '#ffffff');
384
- delete m.userData.pendingTex;
385
- m.needsUpdate = true;
386
- }
387
- }
388
- });
389
- entry.textureDirty = true;
390
- }
391
- if (notify) onTextureReady?.();
392
- };
393
- textureCache.set(key, tex);
394
- img.onload = () => markLoaded(true);
395
- img.src = 'data:' + asset.mime + ';base64,' + asset.data;
396
- if (img.complete && img.naturalWidth) markLoaded(false);
397
- return tex;
398
- }
399
-
400
- function buildStage(stageComp) {
401
- const p = stageComp.parameters;
402
- const scene = new Scene();
403
- scene.background = new Color(p.skyColor || '#b8e2ed');
404
- const camera = new PerspectiveCamera(p.cameraFov ?? 39, 1, 0.1, 160);
405
- camera.position.set(p.cameraX ?? 10, p.cameraY ?? 18, p.cameraZ ?? 21);
406
- camera.lookAt(p.lookAtX ?? 0, p.lookAtY ?? 0.15, p.lookAtZ ?? 0);
407
- scene.add(camera);
408
- scene.add(new HemisphereLight(p.hemiSkyColor || '#fff9dd', p.hemiGroundColor || '#527b75', p.hemiIntensity ?? 1.8));
409
- const sun = new DirectionalLight(p.sunColor || '#fff0cf', p.sunIntensity ?? 2.1);
410
- sun.position.set(p.sunX ?? -9, p.sunY ?? 18, p.sunZ ?? 8);
411
- scene.add(sun);
412
-
413
- sun.shadow.camera.left = sun.shadow.camera.bottom = -16;
414
- sun.shadow.camera.right = sun.shadow.camera.top = 16;
415
- sun.shadow.camera.far = 100;
416
- sun.shadow.camera.updateProjectionMatrix();
417
-
418
- const sharedTex = getTexture(stageComp.assetSlots?.[0]?.assetId);
419
- const nodes = new Map();
420
- const dynamicNodes = new Map();
421
- const wavingFlags = [];
422
- const confettiSystems = [];
423
- const modelBindings = new Map();
424
-
425
- function tagSubtree(rootObj, rootId, sourceId, cameraAttached) {
426
- rootObj.traverse(node => {
427
- node.userData.toraRootId = rootId;
428
- node.userData.toraSourceId = sourceId;
429
- if (cameraAttached) node.userData.cameraAttached = true;
430
- });
431
- }
432
-
433
- function createMeshObject(comp, parentObj, rootId, sourceId, cameraAttached) {
434
- const mp = comp.parameters;
435
- let obj;
436
- const makeMat = () => {
437
- const opts = {};
438
- const texReady = Boolean(sharedTex && sharedTex.image?.complete && sharedTex.image?.naturalWidth > 0);
439
- if (mp.useTexture && sharedTex && texReady) opts.map = sharedTex;
440
- else opts.color = mp.useTexture ? (mp.waveFlag ? '#e85d56' : '#d89b6a') : (mp.color || '#ffffff');
441
- if (mp.doubleSide) opts.side = DoubleSide;
442
- if (mp.opacity < 1) { opts.transparent = true; opts.opacity = mp.opacity; opts.depthWrite = false; }
443
- const mat = mp.unlit ? new MeshBasicMaterial(opts) : new MeshLambertMaterial(opts);
444
- if (mp.useTexture && sharedTex && !texReady) mat.userData.pendingTex = {tex: sharedTex, color: '#ffffff'};
445
- return mat;
446
- };
447
- if (mp.primitive === 'model' || (mp.primitive === 'mesh' && !mp.waveFlag)) {
448
- obj = new Group();
449
- let child, cachedSlots, cachedParams;
450
- const animBehavior = (project.gameplay ?? []).find(b => b.kind === 'animate-3d' && b.componentId === (comp.prototypeId ?? comp.id));
451
- const binding = {
452
- sourceId,
453
- animator: null,
454
- modelBounds: null,
455
- startDefaultAnimation() {
456
- if (!binding.animator || !animBehavior) return;
457
- const ap = animBehavior.parameters;
458
- if (ap.autoplay !== false) {
459
- binding.animator.play(ap.clipName || '', {loop: ap.loop ?? 'repeat', speed: ap.speed ?? 1, fadeSeconds: 0, restart: true, startTime: ap.startTime ?? 0});
460
- }
461
- },
462
- update(params) {
463
- const runtime = overrides.get(comp.id)?.slots, prototype = overrides.get(comp.prototypeId)?.slots;
464
- const slot = id => runtime?.[id] ?? prototype?.[id] ?? comp.assetSlots?.find(s => s.slotId === id)?.assetId;
465
- const slots = ['source', 'texture', 'normalMap', 'emissiveMap'].map(slot);
466
- const fields = ['subNode','materialMode','overrideMaterialName','opacity','tintColor','roughnessScale',
467
- 'metalnessScale','castShadow','receiveShadow','normalizeSize','pivotMode','color','useTexture'];
468
- if (cachedSlots && slots.every((id, i) => id === cachedSlots[i]) &&
469
- fields.every(key => params[key] === cachedParams[key])) return false;
470
- const asset = assetsMap.get(slots[0]);
471
- if (child) { obj.remove(child); disposeTree(child); }
472
- binding.animator = null;
473
- binding.modelBounds = null;
474
- if (asset?.mime === 'model/gltf-binary') {
475
- const external = {};
476
- for (const [i, key] of ['texture','normalMap','emissiveMap'].entries()) {
477
- if (slots[i + 1]) external[key] = getTexture(slots[i + 1], key);
478
- }
479
- child = cloneModelTemplate(getModel(asset), params, external);
480
- binding.modelBounds = child.userData?.modelBounds ?? null;
481
- binding.animator = createModelAnimator(child);
482
- binding.startDefaultAnimation();
483
- } else {
484
- child = new Mesh(getMeshGeometry(slots[0]) ?? new BoxGeometry(1, 1, 1), makeMat());
485
- child.castShadow = !!params.castShadow;
486
- child.receiveShadow = !!params.receiveShadow;
487
- if (slots[1]) child.material.map = getTexture(slots[1]);
488
- else if (params.color && !params.useTexture) child.material.color.set(params.color);
489
- }
490
- obj.add(child);
491
- tagSubtree(child, rootId, sourceId, cameraAttached);
492
- cachedSlots = slots;
493
- cachedParams = {...params};
494
- return true;
495
- },
496
- };
497
- binding.update(mp);
498
- modelBindings.set(comp.id, binding);
499
- } else if (mp.primitive === 'group') {
500
- obj = new Group();
501
- } else if (mp.primitive === 'fairway') {
502
- obj = buildFairwayGroup(mp, sharedTex, getMeshGeometry(comp.assetSlots?.[0]?.assetId));
503
- } else if (mp.primitive === 'cup') {
504
- obj = buildCupGroup(mp);
505
- } else if (mp.primitive === 'garden') {
506
- obj = buildGardenGroup();
507
- } else if (mp.primitive === 'mesh') {
508
- const baseGeo = getMeshGeometry(comp.assetSlots?.[0]?.assetId);
509
- const geo = mp.waveFlag && baseGeo ? baseGeo.clone() : (baseGeo ?? new BoxGeometry(1, 1, 1));
510
- obj = new Mesh(geo, makeMat());
511
- if (mp.waveFlag && baseGeo) {
512
- wavingFlags.push({geo, rest: new Float32Array(geo.getAttribute('position').array)});
513
- }
514
- } else if (mp.primitive === 'sphere') {
515
- obj = new Mesh(new SphereGeometry(mp.radiusTop ?? 0.5, 16, 12), makeMat());
516
- } else if (mp.primitive === 'cylinder') {
517
- obj = new Mesh(new CylinderGeometry(mp.radiusTop ?? 0.23, mp.radiusBottom ?? 0.21, 1, 32, 1, Boolean(mp.openEnded)), makeMat());
518
- } else if (mp.primitive === 'ring') {
519
- obj = new Mesh(new RingGeometry(mp.innerRadius ?? 0, mp.radiusTop ?? 0.15, 24), makeMat());
520
- } else if (mp.primitive === 'circle') {
521
- obj = new Mesh(new CircleGeometry(mp.radiusTop ?? 0.21, 32), makeMat());
522
- } else {
523
- obj = new Mesh(new BoxGeometry(1, 1, 1), makeMat());
524
- }
525
- obj.position.set(mp.x ?? 0, mp.y ?? 0, mp.z ?? 0);
526
- obj.rotation.set(mp.rx ?? 0, mp.ry ?? 0, mp.rz ?? 0);
527
- obj.scale.set(mp.sx ?? 1, mp.sy ?? 1, mp.sz ?? 1);
528
- obj.visible = mp.visible !== false;
529
- tagSubtree(obj, rootId, sourceId, cameraAttached);
530
- parentObj.add(obj);
531
- return obj;
532
- }
533
-
534
- // Build all descendant native.mesh3d.v1 nodes in parent-first order
535
- const descendants = [];
536
- const rootByComp = new Map();
537
- const collect = (parentId, rootComp, camAttached) => {
538
- for (const comp of project.components) {
539
- if (comp.parentId === parentId && comp.contract === 'native.mesh3d.v1' && !comp.prototype) {
540
- const ownRoot = rootComp ?? comp;
541
- const attached = camAttached || Boolean(comp.parameters.attachToCamera);
542
- rootByComp.set(comp.id, {rootId: ownRoot.id, sourceId: ownRoot.id, cameraAttached: attached});
543
- descendants.push(comp);
544
- collect(comp.id, ownRoot, attached);
545
- }
546
- }
547
- };
548
- collect(stageComp.id, null, false);
549
-
550
- for (const comp of descendants) {
551
- const mp = comp.parameters;
552
- const meta = rootByComp.get(comp.id);
553
- const parentObj = mp.attachToCamera && comp.parentId === stageComp.id
554
- ? camera
555
- : (comp.parentId === stageComp.id ? scene : (nodes.get(comp.parentId) ?? scene));
556
- const obj = createMeshObject(comp, parentObj, meta.rootId, meta.sourceId, meta.cameraAttached);
557
- nodes.set(comp.id, obj);
558
-
559
- if (mp.confetti) {
560
- const cGroup = new Group();
561
- cGroup.userData.isConfetti = true;
562
- const cGeo = new BoxGeometry(0.08, 0.025, 0.12);
563
- const cMats = ['#ffda69', '#fff6c9', '#ef8774', '#7cc6bf'].map(c => new MeshBasicMaterial({color: c}));
564
- const pieces = Array.from({length: 28}, (_, i) => {
565
- const m = new Mesh(cGeo, cMats[i % 4]);
566
- m.visible = false;
567
- cGroup.add(m);
568
- return m;
569
- });
570
- scene.add(cGroup);
571
- confettiSystems.push({id: comp.id, origin: {x: mp.x ?? 0, y: mp.y ?? 0, z: mp.z ?? 0}, pieces});
572
- }
573
- }
574
-
575
- const guideGroup = new Group();
576
- scene.add(guideGroup);
577
- const guideDotGeo = new SphereGeometry(1, 8, 5);
578
- const guideDotMat = new MeshBasicMaterial({color: '#fff1a2', transparent: true, opacity: 0.85});
579
- const guidePool = Array.from({length: 24}, () => {
580
- const dot = new Mesh(guideDotGeo, guideDotMat);
581
- dot.visible = false;
582
- guideGroup.add(dot);
583
- return dot;
584
- });
585
- const raycaster = new Raycaster();
586
- const ndc = new Vector2();
587
- const projVec = new Vector3();
588
- const plane = new Plane(new Vector3(0, 1, 0), 0);
589
- const hitVec = new Vector3();
590
- let lastGuideKey = '';
591
-
592
- const nodeEntries = Array.from(nodes, ([id, obj]) => ({
593
- id,
594
- obj,
595
- comp: project.components.find(c => c.id === id),
596
- })).filter(item => item.comp);
597
-
598
- const entry = {
599
- id: stageComp.id,
600
- scene,
601
- camera,
602
- nodes,
603
- dynamicNodes,
604
- nodeEntries,
605
- createMeshObject,
606
- modelBindings,
607
- sun,
608
- wavingFlags,
609
- confettiSystems,
610
- guideGroup,
611
- guidePool,
612
- compiled: false,
613
- lastRenderMs: 0,
614
- textureDirty: true,
615
- animDirty: false,
616
- skyColor: p.skyColor || '#b8e2ed',
617
- lastWaveAt: -1,
618
- lastRenderedTime: -1,
619
- lastRenderedW: 0,
620
- lastRenderedH: 0,
621
- lastPoseSig: '',
622
- guideDirty: true,
623
- focusZ: 0,
624
- lastTime: -1,
625
- lastWidth: 0,
626
- lastHeight: 0,
627
- setGuide(points) {
628
- const count = points ? Math.min(points.length, guidePool.length) : 0;
629
- const key = count ? points.slice(0, count).map(p => `${p.x.toFixed(2)},${p.y.toFixed(2)},${p.z.toFixed(2)}`).join('|') : '';
630
- if (key === lastGuideKey) return;
631
- lastGuideKey = key;
632
- entry.guideDirty = true;
633
- for (let i = 0; i < guidePool.length; i++) {
634
- const dot = guidePool[i];
635
- if (i < count) {
636
- const pt = points[i];
637
- const r = 0.055 * (1 - (i / count) * 0.5);
638
- dot.visible = true;
639
- dot.scale.setScalar(r);
640
- dot.position.set(pt.x, pt.y + 0.03, pt.z);
641
- } else {
642
- dot.visible = false;
643
- }
644
- }
645
- },
646
- project(pos, width, height) {
647
- projVec.set(pos.x, pos.y, pos.z).project(camera);
648
- return {x: (projVec.x + 1) * width / 2, y: (1 - projVec.y) * height / 2};
649
- },
650
- unproject(x, y, width, height, elevation) {
651
- ndc.set((x / width) * 2 - 1, 1 - (y / height) * 2);
652
- raycaster.setFromCamera(ndc, camera);
653
- plane.constant = -elevation;
654
- return raycaster.ray.intersectPlane(plane, hitVec)
655
- ? {x: hitVec.x, y: hitVec.y, z: hitVec.z}
656
- : null;
657
- },
658
- raycast(ndcX, ndcY, maxDistance = 80, {isTarget = () => true, isOccluder = () => false} = {}) {
659
- scene.updateMatrixWorld(true);
660
- camera.updateMatrixWorld(true);
661
- ndc.set(ndcX, ndcY);
662
- raycaster.near = 0.05;
663
- raycaster.far = maxDistance;
664
- raycaster.setFromCamera(ndc, camera);
665
- const candidates = [];
666
- for (const obj of entry.nodes.values()) {
667
- if (!obj.visible || obj.userData?.cameraAttached) continue;
668
- const rid = obj.userData?.toraRootId, sid = obj.userData?.toraSourceId;
669
- if (rid && (isTarget(rid, sid) || isOccluder(rid, sid))) candidates.push(obj);
670
- }
671
- for (const obj of entry.dynamicNodes.values()) {
672
- if (!obj.visible || obj.userData?.cameraAttached) continue;
673
- const rid = obj.userData?.toraRootId, sid = obj.userData?.toraSourceId;
674
- if (rid && (isTarget(rid, sid) || isOccluder(rid, sid))) candidates.push(obj);
675
- }
676
- const hits = raycaster.intersectObjects(candidates.length ? candidates : scene.children, true);
677
- const seen = new Set();
678
- for (const hit of hits) {
679
- let hidden = false;
680
- for (let cur = hit.object; cur; cur = cur.parent) {
681
- if (!cur.visible || cur === guideGroup || cur.userData?.cameraAttached || cur.userData?.isConfetti) {
682
- hidden = true;
683
- break;
684
- }
685
- }
686
- if (hidden) continue;
687
- const rootId = hit.object.userData?.toraRootId;
688
- const sourceId = hit.object.userData?.toraSourceId;
689
- if (!rootId || seen.has(rootId)) continue;
690
- seen.add(rootId);
691
- if (isTarget(rootId, sourceId)) {
692
- return {
693
- id: rootId,
694
- sourceId,
695
- distance: hit.distance,
696
- point: {x: hit.point.x, y: hit.point.y, z: hit.point.z},
697
- };
698
- }
699
- if (isOccluder(rootId, sourceId)) return null;
700
- }
701
- return null;
702
- },
703
- };
704
- stages.set(stageComp.id, entry);
705
- return entry;
706
- }
707
-
708
- function getStage(stageComp) {
709
- return stages.get(stageComp.id) ?? buildStage(stageComp);
710
- }
711
-
712
- function syncContactParticles(entry, particles) {
713
- if (!particles.length && !entry.contactBatches) return false;
714
- if (!entry.contactBatches) {
715
- entry.contactBatches = [new SphereGeometry(1, 6, 4), new BoxGeometry(1, 0.2, 1.6)].map(geometry => {
716
- const mesh = new InstancedMesh(geometry, new MeshBasicMaterial({toneMapped: false}), 256);
717
- mesh.userData.isConfetti = true;
718
- mesh.frustumCulled = false;
719
- mesh.count = 0;
720
- entry.scene.add(mesh);
721
- return mesh;
722
- });
723
- entry.contactPose = new Object3D();
724
- entry.contactColor = new Color();
725
- }
726
- const prior = entry.contactBatches.some(mesh => mesh.count > 0);
727
- for (const mesh of entry.contactBatches) mesh.count = 0;
728
- const {contactBatches, contactPose, contactColor} = entry;
729
- for (const p of particles) {
730
- const mesh = contactBatches[Number(p.confetti)], age = p.age;
731
- contactPose.position.set(p.x + p.vx * age, p.y + p.vy * age - p.gravity * age * age / 2, p.z + p.vz * age);
732
- contactPose.rotation.set(p.spinX * age, p.spinZ * age / 2, p.spinZ * age);
733
- contactPose.scale.setScalar(p.size * Math.min(1, (p.life - age) * 7));
734
- contactPose.updateMatrix();
735
- mesh.setMatrixAt(mesh.count, contactPose.matrix);
736
- mesh.setColorAt(mesh.count, contactColor.set(p.color));
737
- mesh.count++;
738
- }
739
- for (const mesh of contactBatches) {
740
- mesh.instanceMatrix.needsUpdate = true;
741
- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
742
- }
743
- return prior || particles.length > 0;
744
- }
745
-
746
- function syncStage(stageComp, {time = 0, ambientTime, propsOf, bodies3d, fpsPose, instances3d = [], aimLocked = false, groundFn, worldWidth = 390, worldHeight = 700, designHeight}) {
747
- const entry = getStage(stageComp);
748
- const waveTime = ambientTime ?? time;
749
- const p = propsOf(stageComp);
750
- const nextSky = p.skyColor || '#b8e2ed';
751
- if (entry.skyColor !== nextSky) {
752
- entry.skyColor = nextSky;
753
- entry.scene.background = new Color(nextSky);
754
- }
755
-
756
- // Sync dynamically spawned mesh3d prototype instances (add missing, remove despawned)
757
- const liveIds = new Set(instances3d.map(item => item.id));
758
- for (const [dynId, dynObj] of entry.dynamicNodes) {
759
- if (!liveIds.has(dynId)) {
760
- dynObj.parent?.remove(dynObj);
761
- disposeTree(dynObj);
762
- entry.modelBindings.delete(dynId);
763
- entry.dynamicNodes.delete(dynId);
764
- }
765
- }
766
- for (const comp of instances3d) {
767
- if (entry.dynamicNodes.has(comp.id)) continue;
768
- const parentObj = comp.parentId === stageComp.id
769
- ? entry.scene
770
- : (entry.dynamicNodes.get(comp.parentId) ?? entry.nodes.get(comp.parentId) ?? entry.scene);
771
- const rootId = comp.instanceId ?? comp.id;
772
- const rootComp = instances3d.find(node => node.id === rootId) ?? comp;
773
- const sourceId = rootComp.prototypeId ?? rootComp.id;
774
- const obj = entry.createMeshObject(comp, parentObj, rootId, sourceId, Boolean(comp.parameters.attachToCamera));
775
- entry.dynamicNodes.set(comp.id, obj);
776
- }
777
-
778
- const portrait = worldHeight >= worldWidth;
779
- const dt = entry.lastTime < 0 || waveTime < entry.lastTime ? 0 : Math.min(0.05, waveTime - entry.lastTime);
780
- const heightExpand = Math.max(1, worldHeight / Math.max(1, designHeight ?? worldHeight));
781
- const expandFov = baseFov => heightExpand > 1.001
782
- ? Math.min(135, 2 * Math.atan(Math.tan((baseFov * Math.PI) / 360) * heightExpand) * (180 / Math.PI))
783
- : baseFov;
784
- const camAspect = worldWidth / Math.max(1, worldHeight);
785
- const camFov = fpsPose
786
- ? expandFov(portrait ? (p.cameraFov ?? 68) : (p.landscapeCameraFov ?? 54))
787
- : expandFov(portrait ? (p.cameraFov ?? 39) : (p.landscapeCameraFov ?? 22.6199));
788
- if (entry.recoil > 0) {
789
- entry.recoil = dt > 0 ? (entry.recoil * Math.exp(-10 * dt)) : entry.recoil;
790
- if (entry.recoil < 0.002) entry.recoil = 0;
791
- }
792
-
793
- // Sync mesh3d node transforms, visibility & colors from live parameters + 3D physics + drop shadows
794
- const allNodes = [
795
- ...entry.nodeEntries,
796
- ...instances3d.map(comp => ({id: comp.id, obj: entry.dynamicNodes.get(comp.id), comp})).filter(row => row.obj),
797
- ];
798
- let poseParts = '';
799
- for (const {id, obj, comp} of allNodes) {
800
- const mp = propsOf(comp);
801
- obj.visible = mp.visible !== false;
802
- if (entry.modelBindings.get(id)?.update(mp)) {
803
- entry.textureDirty = true;
804
- entry.compiled = false;
805
- }
806
- if (!mp.useTexture && obj.isMesh && obj.material?.color && mp.color) {
807
- obj.material.color.set(mp.color);
808
- }
809
- const body = bodies3d?.get(id);
810
- if (body && body.mode === 'dynamic') {
811
- const cap = body.captured ? Math.min(1, (body.captureElapsed ?? 0) / 0.55) : 0;
812
- const tx = body.captured && body.captureTarget ? body.x + (body.captureTarget.x - body.x) * cap : body.x;
813
- const ty = body.y - cap * 0.45;
814
- const tz = body.captured && body.captureTarget ? body.z + (body.captureTarget.z - body.z) * cap : body.z;
815
- obj.position.set(tx, ty, tz);
816
- const s = 1 - cap * 0.65;
817
- obj.scale.set((mp.sx ?? 1) * s, (mp.sy ?? 1) * s, (mp.sz ?? 1) * s);
818
- obj.rotation.set(-(body.spin ?? 0), mp.ry ?? 0, (body.spin ?? 0) * 0.22);
819
- } else if (body && body.mode === 'kinematic') {
820
- obj.position.set(body.x, body.y ?? mp.y ?? 0, body.z);
821
- obj.rotation.set(mp.rx ?? 0, -(body.angle ?? mp.ry ?? 0), mp.rz ?? 0);
822
- } else if (mp.dropShadowOf && bodies3d?.has(mp.dropShadowOf)) {
823
- const target = bodies3d.get(mp.dropShadowOf);
824
- const floor = groundFn ? (groundFn(target, target.x, target.z) ?? -1) : 0;
825
- obj.position.set(target.x, floor + 0.008, target.z);
826
- const lift = Math.max(0, target.y - floor - target.radius);
827
- if (obj.material) obj.material.opacity = 0.22 / (1 + lift * 2);
828
- const s = 1 + lift * 0.4;
829
- obj.scale.set(s, s, s);
830
- obj.visible = !target.captured && mp.visible !== false;
831
- } else if (mp.attachToCamera) {
832
- const refTan = Math.tan(((p.cameraFov ?? 68) * Math.PI) / 360), curTan = Math.tan((camFov * Math.PI) / 360);
833
- const r = curTan / Math.max(0.05, refTan), s = Math.min(1, r), sy = Math.min(1.15, r) * (camAspect > 1.3 ? 1.12 : 1);
834
- const sx = sy * Math.min(3.55, camAspect / (390 / 700)), rec = entry.recoil ?? 0;
835
- obj.position.set((mp.x ?? 0) * sx, (mp.y ?? 0) * sy + rec * 0.085 * s, (mp.z ?? 0) + rec * 0.3 * s);
836
- obj.rotation.set((mp.rx ?? 0) + rec * 0.34, (mp.ry ?? 0) + (camAspect > 1.1 ? 0.1 : 0), (mp.rz ?? 0) - rec * 0.09);
837
- obj.scale.set((mp.sx ?? 1) * s, (mp.sy ?? 1) * s, (mp.sz ?? 1) * s);
838
- } else {
839
- obj.position.set(mp.x ?? 0, mp.y ?? 0, mp.z ?? 0);
840
- obj.rotation.set(mp.rx ?? 0, mp.ry ?? 0, mp.rz ?? 0);
841
- obj.scale.set(mp.sx ?? 1, mp.sy ?? 1, mp.sz ?? 1);
842
- }
843
- if (fpsPose || entry.dynamicNodes.size > 0) {
844
- poseParts += `${id}:${+obj.visible},${obj.position.x * 1e2 | 0},${obj.position.y * 1e2 | 0},${obj.position.z * 1e2 | 0},${obj.rotation.x * 1e2 | 0},${obj.rotation.y * 1e2 | 0}|`;
845
- }
846
- }
847
-
848
- // Animate 3D confetti bursts when a dynamic ball in this stage is captured
849
- let capturedBody;
850
- if (bodies3d) {
851
- for (const body of bodies3d.values()) {
852
- if (body.stageId === stageComp.id && body.captured) { capturedBody = body; break; }
853
- }
854
- }
855
- for (const sys of entry.confettiSystems) {
856
- const active = Boolean(capturedBody);
857
- const t = capturedBody ? (capturedBody.captureElapsed ?? 0) : 0;
858
- sys.pieces.forEach((m, i) => {
859
- m.visible = active;
860
- if (!active) return;
861
- const a = i * 2.399;
862
- const ox = capturedBody.captureTarget?.x ?? sys.origin.x;
863
- const oy = capturedBody.captureTarget?.y ?? sys.origin.y;
864
- const oz = capturedBody.captureTarget?.z ?? sys.origin.z;
865
- m.position.set(
866
- ox + Math.cos(a) * t * (0.5 + (i % 4) * 0.17),
867
- oy + 0.3 + Math.sin(Math.min(1, t / 2) * Math.PI) * (1 + (i % 5) * 0.15),
868
- oz + Math.sin(a) * t * (0.5 + (i % 4) * 0.17),
869
- );
870
- m.rotation.set(t * 3 + i, t * 2 + i, Math.sin(t + i));
871
- });
872
- }
873
-
874
- // Camera pose: first-person FPS controller or smooth tracking / golf framing
875
- entry.camera.aspect = camAspect;
876
- let victorySway = false;
877
- if (fpsPose) {
878
- entry.lastTime = waveTime;
879
- entry.camera.rotation.order = 'YXZ';
880
- entry.camera.position.set(fpsPose.x, fpsPose.y + (fpsPose.bob ?? 0), fpsPose.z);
881
- entry.camera.rotation.set(fpsPose.pitch, fpsPose.yaw, 0);
882
- entry.camera.fov = camFov;
883
- poseParts += `c:${entry.camera.position.x * 1e2 | 0},${entry.camera.position.y * 1e2 | 0},${entry.camera.position.z * 1e2 | 0},${fpsPose.yaw * 1e3 | 0},${fpsPose.pitch * 1e3 | 0},${camFov * 1e2 | 0},${camAspect * 1e3 | 0},${(entry.recoil ?? 0) * 1e3 | 0}`;
884
- } else {
885
- const followBody = p.followTargetId ? bodies3d?.get(p.followTargetId) : undefined;
886
- const targetZ = followBody ? followBody.z * (p.followZFactor ?? 0.12) : (p.lookAtZ ?? 0);
887
- if (entry.lastTime < 0 || waveTime < entry.lastTime) entry.focusZ = targetZ;
888
- else if (!aimLocked) entry.focusZ += (targetZ - entry.focusZ) * (1 - Math.exp(-6 * dt));
889
- entry.lastTime = waveTime;
890
- const intro = Math.max(0, 1 - waveTime / 1.5);
891
- victorySway = !p.followTargetId && (p.introLift ?? 2) === 0;
892
- if (!aimLocked) {
893
- const swayX = victorySway ? Math.sin(waveTime * 0.42) * 1.15 : 0;
894
- const swayZ = victorySway ? (Math.cos(waveTime * 0.42) - 1) * 0.55 : 0;
895
- const baseX = (portrait ? (p.cameraX ?? 10) : (p.landscapeCameraX ?? 13)) + swayX;
896
- const baseY = portrait ? (p.cameraY ?? 18) + intro * (p.introLift ?? 2) : (p.landscapeCameraY ?? 15);
897
- const baseZ = (portrait ? (p.cameraZ ?? 21) : (p.landscapeCameraZ ?? 18)) + swayZ;
898
- const y = dt === 0 ? baseY : entry.camera.position.y + (baseY - entry.camera.position.y) * (1 - Math.exp(-6 * dt));
899
- entry.camera.position.set(baseX, y, baseZ + entry.focusZ);
900
- entry.camera.fov = camFov;
901
- entry.camera.lookAt(p.lookAtX ?? 0, p.lookAtY ?? 0.15, entry.focusZ);
902
- }
903
- poseParts += `a:${camAspect * 1e3 | 0},${camFov * 1e2 | 0}`;
904
- }
905
- entry.camera.updateProjectionMatrix();
906
- entry.camera.updateMatrixWorld(true);
907
- return {entry, waveTime, victorySway, poseParts};
908
- }
909
-
910
- function renderStage(stageComp, ctx2d, pixelWidth, pixelHeight, stageWidth, stageHeight, options) {
911
- const {entry, waveTime, victorySway, poseParts} = syncStage(stageComp, {
912
- ...options,
913
- worldWidth: options.worldWidth ?? stageWidth,
914
- worldHeight: options.worldHeight ?? stageHeight,
915
- });
916
- const {bodies3d} = options, drawX = options.drawX ?? 0, drawY = options.drawY ?? 0;
917
- const contactDirty = syncContactParticles(entry, options.contactParticles ?? []);
918
- Object.assign(entry, {lastX: drawX, lastY: drawY, lastWidth: stageWidth, lastHeight: stageHeight, lastDesignH: options.designHeight ?? stageHeight, isFullBleed: Boolean(options.fullBleed)});
919
- const renderer = pixelWidth >= 2 && pixelHeight >= 2 ? ensureRenderer() : null;
920
- if (!renderer || renderer.getContext?.()?.isContextLost?.()) {
921
- ctx2d.fillStyle = entry.skyColor;
922
- ctx2d.fillRect(drawX, drawY, stageWidth, stageHeight);
923
- return entry;
924
- }
925
- const maxDim = Math.max(pixelWidth, pixelHeight, 1);
926
- const p = options.propsOf(stageComp);
927
- const toneMapping = {none: NoToneMapping, neutral: NeutralToneMapping, aces: ACESFilmicToneMapping}[p.toneMapping] ?? NoToneMapping;
928
- renderer.toneMapping = toneMapping;
929
- const shadows = !!p.shadowsEnabled, size = Number(p.shadowMapSize ?? 512);
930
- renderer.shadowMap.enabled = shadows;
931
- entry.sun.castShadow = shadows;
932
- if (entry.sun.shadow.mapSize.x !== size) {
933
- entry.sun.shadow.mapSize.set(size, size);
934
- entry.sun.shadow.map?.dispose();
935
- entry.sun.shadow.map = null;
936
- }
937
- const intensity = p.envIntensity ?? 0.8;
938
- if (entry.textureDirty || !entry.compiled) {
939
- entry.usesPbr = false;
940
- entry.scene.traverse(o => { if (o.material?.isMeshStandardMaterial) entry.usesPbr = true; });
941
- }
942
- if (entry.usesPbr && intensity > 0) environment ??= studioEnvironment(renderer);
943
- entry.scene.environment = entry.usesPbr && intensity > 0 ? environment?.texture : null;
944
- entry.scene.environmentIntensity = intensity;
945
- const lightingKey = [toneMapping, shadows, size, intensity].join('/');
946
- if (entry.lightingKey !== lightingKey) { entry.textureDirty = true; entry.lightingKey = lightingKey; }
947
- const maxTarget = p.renderMaxDim ?? 520;
948
- const cap = maxDim > maxTarget ? maxTarget / maxDim : 1;
949
- const rw = Math.max(2, Math.round(pixelWidth * cap));
950
- const rh = Math.max(2, Math.round(pixelHeight * cap));
951
- const resized = sharedGlCanvas.width !== rw || sharedGlCanvas.height !== rh;
952
- if (resized) {
953
- renderer.setPixelRatio(1);
954
- renderer.setSize(rw, rh, false);
955
- sharedCacheCanvas.width = rw;
956
- sharedCacheCanvas.height = rh;
957
- sharedStageId = undefined;
958
- }
959
- if (!entry.compiled) {
960
- entry.compiled = true;
961
- const hiddenPrewarm = [];
962
- if (entry.guidePool[0] && !entry.guidePool[0].visible) {
963
- entry.guidePool[0].visible = true;
964
- entry.guidePool[0].position.set(0, -99, 0);
965
- hiddenPrewarm.push(entry.guidePool[0]);
966
- }
967
- for (const sys of entry.confettiSystems) {
968
- if (sys.pieces[0] && !sys.pieces[0].visible) {
969
- sys.pieces[0].visible = true;
970
- sys.pieces[0].position.set(0, -99, 0);
971
- hiddenPrewarm.push(sys.pieces[0]);
972
- }
973
- }
974
- renderer.compile(entry.scene, entry.camera);
975
- for (const m of hiddenPrewarm) m.visible = false;
976
- }
977
- let hasMovingBody = false;
978
- if (bodies3d) {
979
- for (const body of bodies3d.values()) {
980
- if (body.stageId !== stageComp.id) continue;
981
- if (body.mode === 'kinematic' || (body.mode === 'dynamic' && (!body.atRest || body.captured))) {
982
- hasMovingBody = true;
983
- break;
984
- }
985
- }
986
- }
987
- // Keep waving flag animation at an exact invariant 20Hz phase whether idle, pulling the ball, or rolling.
988
- const flagStep = Math.floor(waveTime * 20);
989
- const flagDirty = entry.wavingFlags.length > 0 && entry.lastFlagStep !== flagStep;
990
- const swayDirty = victorySway && Math.abs(waveTime - entry.lastRenderedTime) >= 0.032;
991
- const bodyDirty = hasMovingBody && entry.lastRenderedTime !== waveTime;
992
- const poseDirty = poseParts !== entry.lastPoseSig;
993
- const didRender = resized || sharedStageId !== stageComp.id || entry.guideDirty || entry.textureDirty || entry.animDirty || entry.lastRenderedTime < 0 || entry.lastRenderedW !== rw || entry.lastRenderedH !== rh || flagDirty || swayDirty || bodyDirty || poseDirty || contactDirty;
994
- if (didRender) {
995
- if (entry.wavingFlags.length > 0 && entry.lastFlagStep !== flagStep) {
996
- for (const flag of entry.wavingFlags) waveFlagGeometry(flag.geo, flag.rest, flagStep / 20);
997
- entry.lastFlagStep = flagStep;
998
- }
999
- renderer.setClearColor(entry.skyColor, 1);
1000
- renderer.render(entry.scene, entry.camera);
1001
- if (sharedGlCanvas.width > 0 && sharedGlCanvas.height > 0) {
1002
- sharedCacheCtx.drawImage(sharedGlCanvas, 0, 0, rw, rh);
1003
- sharedStageId = stageComp.id;
1004
- }
1005
- entry.lastRenderedTime = waveTime;
1006
- entry.lastRenderedW = rw;
1007
- entry.lastRenderedH = rh;
1008
- entry.lastPoseSig = poseParts;
1009
- entry.guideDirty = false;
1010
- entry.textureDirty = false;
1011
- entry.animDirty = false;
1012
- }
1013
- if (sharedCacheCanvas.width > 0 && sharedCacheCanvas.height > 0) {
1014
- ctx2d.drawImage(sharedCacheCanvas, drawX, drawY, stageWidth, stageHeight);
1015
- }
1016
- return entry;
1017
- }
1018
-
1019
- function reset() {
1020
- for (const entry of stages.values()) {
1021
- for (const [id, dynObj] of entry.dynamicNodes) {
1022
- dynObj.parent?.remove(dynObj);
1023
- disposeTree(dynObj);
1024
- entry.modelBindings.delete(id);
1025
- }
1026
- entry.dynamicNodes.clear();
1027
- for (const binding of entry.modelBindings.values()) {
1028
- binding.animator?.reset();
1029
- binding.startDefaultAnimation();
1030
- }
1031
- entry.animDirty = true;
1032
- entry.focusZ = 0;
1033
- entry.lastTime = -1;
1034
- entry.lastRenderedTime = -1;
1035
- entry.lastFlagStep = -1;
1036
- entry.lastPoseSig = '';
1037
- entry.guideDirty = true;
1038
- entry.setGuide([]);
1039
- }
1040
- }
1041
-
1042
- function dispose() {
1043
- for (const entry of stages.values()) {
1044
- for (const mesh of entry.contactBatches ?? []) mesh.dispose();
1045
- disposeTree(entry.scene);
1046
- entry.sun.shadow.dispose();
1047
- }
1048
- for (const geo of sharedGeometry) geo.dispose();
1049
- for (const mat of sharedMaterials) mat.dispose();
1050
- for (const tex of textureCache.values()) tex.dispose();
1051
- for (const model of modelCache.values()) for (const tex of model.textures.values()) tex.dispose();
1052
- sharedMaterials.clear();
1053
- sharedGeometry.clear();
1054
- modelCache.clear();
1055
- environment?.dispose();
1056
- environment = undefined;
1057
- stages.clear();
1058
- meshCache.clear();
1059
- textureCache.clear();
1060
- sharedRenderer?.forceContextLoss?.();
1061
- sharedRenderer?.dispose();
1062
- sharedRenderer = undefined;
1063
- sharedGlCanvas = undefined;
1064
- sharedCacheCanvas = undefined;
1065
- sharedCacheCtx = undefined;
1066
- sharedStageId = undefined;
1067
- }
1068
-
1069
- function stepAnimations(dt, onAnimEnd) {
1070
- for (const entry of stages.values()) {
1071
- for (const [id, binding] of entry.modelBindings) {
1072
- if (!binding.animator) continue;
1073
- if (binding.animator.step(dt, clipName => onAnimEnd?.(id, binding.sourceId ?? id, clipName))) {
1074
- entry.animDirty = true;
1075
- }
1076
- }
1077
- }
1078
- }
1079
-
1080
- function playModelAnimation(componentId, opts = {}) {
1081
- let matched = false;
1082
- for (const entry of stages.values()) {
1083
- for (const [id, binding] of entry.modelBindings) {
1084
- if (id !== componentId && binding.sourceId !== componentId) continue;
1085
- if (binding.animator?.play(opts.clipName || '', opts)) {
1086
- entry.animDirty = true;
1087
- matched = true;
1088
- }
1089
- }
1090
- }
1091
- return matched;
1092
- }
1093
-
1094
- function modelBoundsFor(componentId) {
1095
- for (const entry of stages.values()) {
1096
- const binding = entry.modelBindings.get(componentId);
1097
- if (binding?.modelBounds) return binding.modelBounds;
1098
- }
1099
- return null;
1100
- }
1101
-
1102
- function modelStatus() {
1103
- const total = {texturesPending: 0, textureErrors: 0, animations: {}};
1104
- for (const model of modelCache.values()) {
1105
- const status = model.imageStatus();
1106
- total.texturesPending += status.texturesPending;
1107
- total.textureErrors += status.textureErrors;
1108
- }
1109
- for (const entry of stages.values()) {
1110
- for (const [id, binding] of entry.modelBindings) {
1111
- if (binding.animator) total.animations[id] = binding.animator.snapshot();
1112
- }
1113
- }
1114
- return total;
1115
- }
1116
- function triggerRecoil(stageId) {
1117
- const entry = stages.get(stageId);
1118
- if (entry) entry.recoil = 1;
1119
- }
1120
- return {getStage, syncStage, renderStage, reset, dispose, stepAnimations, playModelAnimation, modelBoundsFor, modelStatus, triggerRecoil};
1121
- }