@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,26 +0,0 @@
1
- export function segmentsIntersect(a,b,c,d){
2
- const cross=(p,q,r)=>(q.x-p.x)*(r.y-p.y)-(q.y-p.y)*(r.x-p.x),ab1=cross(a,b,c),ab2=cross(a,b,d),cd1=cross(c,d,a),cd2=cross(c,d,b),epsilon=1e-8;
3
- if(Math.abs(ab1)<epsilon&&Math.abs(ab2)<epsilon&&Math.abs(cd1)<epsilon&&Math.abs(cd2)<epsilon)return Math.max(Math.min(a.x,b.x),Math.min(c.x,d.x))<=Math.min(Math.max(a.x,b.x),Math.max(c.x,d.x))+epsilon&&Math.max(Math.min(a.y,b.y),Math.min(c.y,d.y))<=Math.min(Math.max(a.y,b.y),Math.max(c.y,d.y))+epsilon;
4
- return (ab1>0)!==(ab2>0)&&(cd1>0)!==(cd2>0);
5
- }
6
- function pointInPolygon(point,polygon){
7
- let inside=false;
8
- for(let i=0,j=polygon.length-1;i<polygon.length;j=i++){
9
- const a=polygon[i],b=polygon[j];
10
- if((a.y>point.y)!==(b.y>point.y)&&point.x<(b.x-a.x)*(point.y-a.y)/(b.y-a.y)+a.x)inside=!inside;
11
- }
12
- return inside;
13
- }
14
- export function segmentHitsPolygon(a,b,polygon){
15
- if(polygon.length>=3&&(pointInPolygon(a,polygon)||pointInPolygon(b,polygon)))return true;
16
- for(let index=0;index<polygon.length;index++)if(segmentsIntersect(a,b,polygon[index],polygon[(index+1)%polygon.length]))return true;
17
- return false;
18
- }
19
- export function createStrokeStore(parameters){
20
- const config=parameters;let strokes=[],active=null,serial=0;
21
- const bounded=stroke=>({...stroke,points:stroke.points.map(point=>({...point}))});
22
- return {begin(point){const stroke={id:++serial,points:[{...point}],age:0,hitIds:new Set()};active=stroke;strokes.push(stroke);if(strokes.length>config.maxStrokes)strokes.shift();return stroke;},add(point){if(!active||active.points.length>=config.maxPoints)return false;const previous=active.points[active.points.length-1];if(Math.hypot(point.x-previous.x,point.y-previous.y)<config.minSegmentPx)return false;active.points.push({...point});return true;},end(){const stroke=active;active=null;return stroke?bounded(stroke):undefined;},cancel(){if(active)strokes=strokes.filter(stroke=>stroke!==active);active=null;},clear(){active=null;strokes=[];},tick(dt){for(const stroke of strokes)stroke.age+=dt;strokes=strokes.filter(stroke=>stroke===active||stroke.age<.18||config.mode!=='slice-blade');},get active(){return active;},get strokes(){return strokes;}};
23
- }
24
- export function strokeWalls(stroke,width){
25
- const walls=[];for(let index=1;index<stroke.points.length;index++){const a=stroke.points[index-1],b=stroke.points[index],length=Math.hypot(b.x-a.x,b.y-a.y);if(length<.001)continue;walls.push({id:`stroke-${stroke.id}-${index}`,strokeId:stroke.id,mode:'static',shape:'box',x:(a.x+b.x)/2,y:(a.y+b.y)/2,width:length,height:Math.max(2,width),angle:Math.atan2(b.y-a.y,b.x-a.x),restitution:.8});}return walls;
26
- }
@@ -1,18 +0,0 @@
1
- export function createEraseMask(parameters,{width,height,onProgress=()=>{},onComplete=()=>{},canvasFactory,source}={}){
2
- const config=parameters,gridSize=config.gridSize,cells=new Uint8Array(gridSize*gridSize);let covered=0,complete=false,lastPercent=-1,paintedImage=false;
3
- const safeW=Math.max(1,width),safeH=Math.max(1,height),scale=Math.min(1,512/Math.max(safeW,safeH)),canvas=canvasFactory?.()??(globalThis.document?.createElement?globalThis.document.createElement('canvas'):undefined);
4
- if(canvas){canvas.width=Math.max(1,Math.round(safeW*scale));canvas.height=Math.max(1,Math.round(safeH*scale));}
5
- const context=canvas?.getContext?.('2d'),color=config.maskColor??'#dceeff';
6
- const imageReady=()=>Boolean(source&&source.complete&&source.naturalWidth>0);
7
- const paint=()=>{if(!context)return;context.globalCompositeOperation='source-over';context.clearRect(0,0,canvas.width,canvas.height);if(config.mode==='erase'){if(imageReady()){context.drawImage(source,0,0,canvas.width,canvas.height);paintedImage=true;}else{context.fillStyle=color;context.fillRect(0,0,canvas.width,canvas.height);paintedImage=false;}}};paint();
8
- const report=()=>{if(complete)return;const percent=Math.round(covered/cells.length*100),rounded=Math.min(100,percent);if(rounded!==lastPercent){lastPercent=rounded;onProgress(rounded);}if(rounded>=config.targetPercent){complete=true;onComplete(rounded);}};
9
- const stamp=(x,y)=>{
10
- const gx=Math.max(0,Math.min(gridSize-1,Math.floor(x/safeW*gridSize))),gy=Math.max(0,Math.min(gridSize-1,Math.floor(y/safeH*gridSize))),rx=Math.max(0,Math.ceil(config.brushRadiusPx/safeW*gridSize)),ry=Math.max(0,Math.ceil(config.brushRadiusPx/safeH*gridSize));
11
- for(let yy=Math.max(0,gy-ry);yy<=Math.min(gridSize-1,gy+ry);yy++)for(let xx=Math.max(0,gx-rx);xx<=Math.min(gridSize-1,gx+rx);xx++){
12
- if(Math.hypot((xx+.5)/gridSize*safeW-x,(yy+.5)/gridSize*safeH-y)>config.brushRadiusPx)continue;const index=yy*gridSize+xx;if(!cells[index]){cells[index]=1;covered++;}
13
- }
14
- if(context){context.save();context.scale(scale,scale);context.globalCompositeOperation=config.mode==='erase'?'destination-out':'source-over';context.fillStyle=color;context.beginPath();context.arc(x,y,config.brushRadiusPx,0,Math.PI*2);context.fill();if(config.mode==='reveal'&&source){context.globalCompositeOperation='source-in';context.drawImage(source,0,0,safeW,safeH);}context.restore();}
15
- report();
16
- };
17
- return {canvas,stampSegment(a,b){const distance=Math.hypot(b.x-a.x,b.y-a.y),steps=Math.max(1,Math.ceil(distance/Math.max(1,config.brushRadiusPx*.45)));for(let index=0;index<=steps;index++)stamp(a.x+(b.x-a.x)*index/steps,a.y+(b.y-a.y)*index/steps);},reset(){cells.fill(0);covered=0;complete=false;lastPercent=-1;paint();report();},get progress(){return Math.round(covered/cells.length*100);},render(ctx){if(config.mode==='erase'&&covered===0&&!paintedImage&&imageReady())paint();if(canvas)ctx.drawImage(canvas,0,0,canvas.width,canvas.height,0,0,width,height);else if(config.mode==='erase'&&this.progress<100){ctx.save();ctx.globalAlpha=1-this.progress/100;ctx.fillStyle=color;ctx.fillRect(0,0,width,height);ctx.restore();}}};
18
- }
@@ -1,468 +0,0 @@
1
- /* global btoa,Image,TextDecoder */
2
- // Decodes the embedded, static glTF subset validated by the native packer.
3
- import {
4
- Bone, Box3, BufferAttribute, BufferGeometry, ClampToEdgeWrapping, Color, DoubleSide,
5
- FrontSide, Group, LinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter,
6
- Matrix4, Mesh, MeshBasicMaterial, MeshLambertMaterial, MeshStandardMaterial, MirroredRepeatWrapping,
7
- NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NoColorSpace,
8
- Quaternion, RepeatWrapping, Skeleton, SkinnedMesh, SRGBColorSpace, Texture, Vector2, Vector3,
9
- } from 'three';
10
-
11
- const arrays = {5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5126: Float32Array};
12
- const sizes = {SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT4: 16};
13
- const attributes = {POSITION: 'position', NORMAL: 'normal', COLOR_0: 'color', TEXCOORD_0: 'uv', JOINTS_0: 'skinIndex', WEIGHTS_0: 'skinWeight'};
14
- const wrapping = {33071: ClampToEdgeWrapping, 33648: MirroredRepeatWrapping, 10497: RepeatWrapping};
15
- const filters = {9728: NearestFilter, 9729: LinearFilter, 9984: NearestMipmapNearestFilter,
16
- 9985: LinearMipmapNearestFilter, 9986: NearestMipmapLinearFilter, 9987: LinearMipmapLinearFilter};
17
-
18
- function check(value) {
19
- if (!value) throw Error('E_MODEL_CORRUPT');
20
- }
21
-
22
- function attribute(bin, view, accessor) {
23
- const ArrayType = arrays[accessor.componentType], size = sizes[accessor.type];
24
- check(ArrayType && size && view && !accessor.sparse);
25
- const unit = ArrayType.BYTES_PER_ELEMENT, packed = size * unit;
26
- const stride = view.byteStride ?? packed, offset = accessor.byteOffset ?? 0;
27
- const start = (view.byteOffset ?? 0) + offset, count = accessor.count;
28
- check(Number.isSafeInteger(count) && count > 0 && offset >= 0 && start >= 0 &&
29
- stride >= packed && stride % unit === 0 && start % unit === 0 &&
30
- offset + (count - 1) * stride + packed <= view.byteLength &&
31
- start + (count - 1) * stride + packed <= bin.length);
32
- const scalars = new ArrayType(bin.buffer, bin.byteOffset + start, ((count - 1) * stride + packed) / unit);
33
- if (stride === packed) return new BufferAttribute(scalars, size, !!accessor.normalized);
34
- // Release padding and interleaved siblings without changing the integer GPU format.
35
- const out = new ArrayType(count * size);
36
- for (let i = 0; i < count; i++) {
37
- const at = i * stride / unit;
38
- out.set(scalars.subarray(at, at + size), i * size);
39
- }
40
- return new BufferAttribute(out, size, !!accessor.normalized);
41
- }
42
-
43
- function embeddedImage(bytes, mime, complete) {
44
- let binary = '';
45
- for (let i = 0; i < bytes.length; i += 8192) binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
46
- const image = new Image();
47
- image.onload = () => complete(true);
48
- image.onerror = () => complete(false);
49
- image.src = 'data:' + mime + ';base64,' + btoa(binary);
50
- return image;
51
- }
52
-
53
- export function parseGlb(bytes, onTextureReady) {
54
- check(bytes.byteLength >= 28 && bytes.byteLength <= 700000);
55
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
56
- const word = offset => view.getUint32(offset, true);
57
- check(word(0) === 0x46546c67 && word(4) === 2 && word(8) === bytes.byteLength && word(16) === 0x4e4f534a);
58
- const binAt = 20 + word(12);
59
- check(binAt % 4 === 0 && binAt + 8 <= bytes.byteLength && word(binAt + 4) === 0x004e4942 &&
60
- word(binAt) === bytes.byteLength - binAt - 8);
61
- const gltf = JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes.subarray(20, binAt)));
62
- check(gltf.asset?.version === '2.0' && gltf.buffers?.length === 1 && gltf.buffers[0].uri === undefined &&
63
- (gltf.skins?.length ?? 0) <= 4 && (gltf.animations?.length ?? 0) <= 16);
64
- const bin = bytes.subarray(binAt + 8);
65
- const textureCache = new Map(), images = new Map(), accessors = new Map(), nodesByName = new Map();
66
- const geometries = new Set(), materials = new Set();
67
- function accessor(id) {
68
- if (!accessors.has(id)) {
69
- const a = gltf.accessors[id];
70
- accessors.set(id, attribute(bin, gltf.bufferViews[a.bufferView], a));
71
- }
72
- return accessors.get(id);
73
- }
74
- function texture(info, colorSpace) {
75
- if (!info) return null;
76
- const transform = info.extensions?.KHR_texture_transform ?? {};
77
- check((transform.texCoord ?? info.texCoord ?? 0) === 0);
78
- const key = JSON.stringify([info.index, colorSpace, transform]);
79
- if (textureCache.has(key)) return textureCache.get(key);
80
- const def = gltf.textures[info.index], source = gltf.images[def.source], sampler = gltf.samplers?.[def.sampler] ?? {};
81
- const tex = new Texture();
82
- tex.colorSpace = colorSpace;
83
- tex.flipY = false;
84
- tex.wrapS = wrapping[sampler.wrapS ?? 10497];
85
- tex.wrapT = wrapping[sampler.wrapT ?? 10497];
86
- tex.magFilter = filters[sampler.magFilter ?? 9729];
87
- tex.minFilter = filters[sampler.minFilter ?? 9987];
88
- if (transform.offset) tex.offset.fromArray(transform.offset);
89
- if (transform.scale) tex.repeat.fromArray(transform.scale);
90
- tex.rotation = transform.rotation ?? 0;
91
- textureCache.set(key, tex);
92
- if (!images.has(def.source)) {
93
- const imageView = gltf.bufferViews[source.bufferView], start = imageView?.byteOffset ?? 0;
94
- check(imageView && !source.uri && ['image/png', 'image/jpeg'].includes(source.mimeType) &&
95
- start + imageView.byteLength <= bin.length);
96
- const entry = {textures: [], ready: false, failed: false};
97
- images.set(def.source, entry);
98
- entry.image = embeddedImage(bin.subarray(start, start + imageView.byteLength), source.mimeType, ok => {
99
- entry.ready = true;
100
- entry.failed = !ok;
101
- if (ok) for (const t of entry.textures) t.needsUpdate = true;
102
- onTextureReady?.();
103
- });
104
- }
105
- const entry = images.get(def.source);
106
- tex.image = entry.image;
107
- entry.textures.push(tex);
108
- if (entry.ready && !entry.failed) tex.needsUpdate = true;
109
- return tex;
110
- }
111
-
112
- const materialCache = new Map();
113
- function material(index, vertexColors) {
114
- const key = String(index) + '/' + vertexColors;
115
- if (materialCache.has(key)) return materialCache.get(key);
116
- const def = gltf.materials?.[index] ?? {}, pbr = def.pbrMetallicRoughness ?? {};
117
- const base = pbr.baseColorFactor ?? [1, 1, 1, 1], alpha = def.alphaMode ?? 'OPAQUE';
118
- const params = {name: def.name ?? '', color: new Color().fromArray(base), vertexColors,
119
- map: texture(pbr.baseColorTexture, SRGBColorSpace), side: def.doubleSided ? DoubleSide : FrontSide,
120
- opacity: alpha === 'OPAQUE' ? 1 : base[3], transparent: alpha === 'BLEND',
121
- depthWrite: alpha !== 'BLEND', alphaTest: alpha === 'MASK' ? (def.alphaCutoff ?? 0.5) : 0};
122
- let mat;
123
- if (def.extensions?.KHR_materials_unlit) mat = new MeshBasicMaterial(params);
124
- else {
125
- const orm = texture(pbr.metallicRoughnessTexture, NoColorSpace);
126
- mat = new MeshStandardMaterial({...params, roughness: pbr.roughnessFactor ?? 1,
127
- metalness: pbr.metallicFactor ?? 1, roughnessMap: orm, metalnessMap: orm,
128
- normalMap: texture(def.normalTexture, NoColorSpace), normalScale: new Vector2().setScalar(def.normalTexture?.scale ?? 1),
129
- aoMap: texture(def.occlusionTexture, NoColorSpace), aoMapIntensity: def.occlusionTexture?.strength ?? 1,
130
- emissive: new Color().fromArray(def.emissiveFactor ?? [0, 0, 0]),
131
- emissiveMap: texture(def.emissiveTexture, SRGBColorSpace),
132
- emissiveIntensity: def.extensions?.KHR_materials_emissive_strength?.emissiveStrength ?? 1});
133
- // Without supplied tangents, Three derives a basis in its default (+Y) texture convention.
134
- mat.normalScale.y *= -1;
135
- }
136
- materials.add(mat);
137
- materialCache.set(key, mat);
138
- return mat;
139
- }
140
-
141
- const meshes = gltf.meshes.map(mesh => mesh.primitives.map(p => {
142
- check((p.mode ?? 4) === 4 && p.attributes.POSITION !== undefined && !p.targets);
143
- const geo = new BufferGeometry();
144
- for (const [semantic, id] of Object.entries(p.attributes)) {
145
- check(Object.hasOwn(attributes, semantic));
146
- geo.setAttribute(attributes[semantic], accessor(id));
147
- }
148
- if (p.indices !== undefined) geo.setIndex(accessor(p.indices));
149
- if (!geo.attributes.normal) geo.computeVertexNormals();
150
- geometries.add(geo);
151
- return {geo, mat: material(p.material, !!geo.attributes.color)};
152
- }));
153
- const jointIndices = new Set();
154
- for (const s of gltf.skins ?? []) for (const j of s.joints ?? []) jointIndices.add(j);
155
- const root = new Group(), visited = new Set(), nodesByIndex = new Map(), skinnedMeshes = [];
156
- function node(index, parent) {
157
- check(!visited.has(index) && visited.size < 128);
158
- visited.add(index);
159
- const def = gltf.nodes[index], obj = jointIndices.has(index) ? new Bone() : new Group();
160
- obj.name = def.name ?? '';
161
- obj.userData.gltfNodeIndex = index;
162
- nodesByIndex.set(index, obj);
163
- if (obj.name && !nodesByName.has(obj.name)) nodesByName.set(obj.name, obj);
164
- if (def.matrix) obj.matrix.fromArray(def.matrix).decompose(obj.position, obj.quaternion, obj.scale);
165
- else {
166
- if (def.translation) obj.position.fromArray(def.translation);
167
- if (def.rotation) obj.quaternion.fromArray(def.rotation);
168
- if (def.scale) obj.scale.fromArray(def.scale);
169
- }
170
- parent.add(obj);
171
- if (def.mesh !== undefined) {
172
- for (const {geo, mat} of meshes[def.mesh]) {
173
- if (def.skin !== undefined) {
174
- const sm = new SkinnedMesh(geo, mat);
175
- sm.userData.gltfSkinIndex = def.skin;
176
- obj.add(sm);
177
- skinnedMeshes.push(sm);
178
- } else {
179
- obj.add(new Mesh(geo, mat));
180
- }
181
- }
182
- }
183
- for (const id of def.children ?? []) node(id, obj);
184
- }
185
- for (const index of gltf.scenes[gltf.scene ?? 0].nodes ?? []) node(index, root);
186
- root.updateMatrixWorld(true);
187
- const skins = (gltf.skins ?? []).map(skinDef => {
188
- const joints = skinDef.joints ?? [];
189
- check(joints.length > 0 && joints.length <= 64);
190
- let inverseBindMatrices;
191
- if (skinDef.inverseBindMatrices !== undefined) {
192
- const arr = accessor(skinDef.inverseBindMatrices).array;
193
- inverseBindMatrices = Array.from({length: joints.length}, (_, i) => new Matrix4().fromArray(arr, i * 16));
194
- } else {
195
- inverseBindMatrices = joints.map(() => new Matrix4());
196
- }
197
- return {joints, inverseBindMatrices};
198
- });
199
- for (const sm of skinnedMeshes) {
200
- const skin = skins[sm.userData.gltfSkinIndex];
201
- check(skin);
202
- const bones = skin.joints.map(j => nodesByIndex.get(j));
203
- check(bones.every(Boolean));
204
- sm.bind(new Skeleton(bones, skin.inverseBindMatrices.map(m => m.clone())), new Matrix4());
205
- }
206
- const animations = [], animationsByName = new Map();
207
- for (const [clipIdx, anim] of (gltf.animations ?? []).entries()) {
208
- const name = anim.name || ('clip_' + clipIdx);
209
- const tracks = [];
210
- let duration = 0;
211
- for (const ch of anim.channels ?? []) {
212
- const nodeIndex = ch.target?.node, path = ch.target?.path;
213
- if (nodeIndex === undefined || !['translation', 'rotation', 'scale'].includes(path)) continue;
214
- const sampler = anim.samplers?.[ch.sampler];
215
- check(sampler);
216
- const interp = sampler.interpolation ?? 'LINEAR';
217
- check(interp === 'LINEAR' || interp === 'STEP');
218
- const times = accessor(sampler.input).array;
219
- const values = accessor(sampler.output).array;
220
- if (times.length) duration = Math.max(duration, times[times.length - 1]);
221
- tracks.push({nodeIndex, path, interp, times, values});
222
- }
223
- const clip = {name, duration, tracks};
224
- animations.push(clip);
225
- if (!animationsByName.has(name)) animationsByName.set(name, clip);
226
- }
227
- return {root, nodesByName, skins, animations, animationsByName, geometries, materials, textures: textureCache,
228
- imageStatus() {
229
- let texturesPending = 0, textureErrors = 0;
230
- for (const image of images.values()) {
231
- if (!image.ready) texturesPending++;
232
- if (image.failed) textureErrors++;
233
- }
234
- return {texturesPending, textureErrors};
235
- }};
236
- }
237
-
238
- function customMaterial(source, opts, external) {
239
- const mode = opts.materialMode ?? 'asset';
240
- const matches = !opts.overrideMaterialName || source.name === opts.overrideMaterialName;
241
- const override = matches && Object.keys(external).length > 0;
242
- if (mode === 'asset' && !override && (opts.opacity ?? 1) === 1 &&
243
- (!opts.tintColor || opts.tintColor === '#ffffff') && (opts.roughnessScale ?? 1) === 1 &&
244
- (opts.metalnessScale ?? 1) === 1) return source;
245
- const ctor = {lambert: MeshLambertMaterial, unlit: MeshBasicMaterial, standard: MeshStandardMaterial}[mode];
246
- let mat;
247
- if (!ctor || source.constructor === ctor) mat = source.clone();
248
- else {
249
- mat = new ctor();
250
- for (const key of ['name', 'map', 'alphaTest', 'transparent', 'opacity', 'side', 'depthWrite', 'vertexColors',
251
- 'roughness', 'metalness', 'roughnessMap', 'metalnessMap', 'normalMap', 'aoMap', 'aoMapIntensity', 'emissiveMap', 'emissiveIntensity']) {
252
- if (key in mat && key in source) mat[key] = source[key];
253
- }
254
- for (const key of ['color', 'emissive', 'normalScale']) if (mat[key] && source[key]) mat[key].copy(source[key]);
255
- }
256
- if (opts.tintColor) mat.color.multiply(new Color(opts.tintColor));
257
- mat.opacity *= opts.opacity ?? 1;
258
- if (mat.opacity < 1 && (opts.opacity ?? 1) < 1) { mat.transparent = true; mat.depthWrite = false; }
259
- if (mat.isMeshStandardMaterial) {
260
- mat.roughness = Math.min(1, mat.roughness * (opts.roughnessScale ?? 1));
261
- mat.metalness = Math.min(1, mat.metalness * (opts.metalnessScale ?? 1));
262
- }
263
- if (override) {
264
- if (external.texture) mat.map = external.texture;
265
- if (external.normalMap && 'normalMap' in mat) mat.normalMap = external.normalMap;
266
- if (external.emissiveMap && 'emissiveMap' in mat) mat.emissiveMap = external.emissiveMap;
267
- }
268
- return mat;
269
- }
270
-
271
- export function cloneModelTemplate(template, opts = {}, externalTextures = {}) {
272
- const source = opts.subNode ? template.nodesByName.get(opts.subNode) : template.root;
273
- if (!source) throw Error('E_MODEL_SUBNODE ' + opts.subNode);
274
- const model = source.clone(true), root = new Group(), remapped = new Map();
275
- if (opts.subNode) {
276
- // Keep the authored orientation and inherited scale while placing the selected part at its own pivot.
277
- model.position.set(0, 0, 0);
278
- if (source.parent) {
279
- const parentBasis = source.parent.matrixWorld.clone().setPosition(0, 0, 0);
280
- model.updateMatrix();
281
- model.matrix.premultiply(parentBasis);
282
- model.matrixAutoUpdate = false;
283
- }
284
- }
285
- root.add(model);
286
- const clonedByIndex = new Map(), clonedSkinned = [];
287
- model.traverse(obj => {
288
- if (obj.userData?.gltfNodeIndex !== undefined) clonedByIndex.set(obj.userData.gltfNodeIndex, obj);
289
- if (!obj.isMesh) return;
290
- const original = obj.material;
291
- if (!remapped.has(original)) remapped.set(original, customMaterial(original, opts, externalTextures));
292
- obj.material = remapped.get(original);
293
- obj.castShadow = !!opts.castShadow;
294
- obj.receiveShadow = !!opts.receiveShadow;
295
- if (obj.isSkinnedMesh && obj.userData?.gltfSkinIndex !== undefined) clonedSkinned.push(obj);
296
- });
297
- if (clonedSkinned.length) {
298
- root.updateMatrixWorld(true);
299
- for (const sm of clonedSkinned) {
300
- const skin = template.skins?.[sm.userData.gltfSkinIndex];
301
- if (!skin) continue;
302
- const bones = skin.joints.map(j => clonedByIndex.get(j)).filter(Boolean);
303
- if (bones.length === skin.joints.length) {
304
- sm.bind(new Skeleton(bones, skin.inverseBindMatrices.map(m => m.clone())), new Matrix4());
305
- }
306
- }
307
- }
308
- root.userData.clonedByIndex = clonedByIndex;
309
- root.userData.template = template;
310
- const box = new Box3().setFromObject(root, true);
311
- if (!box.isEmpty()) {
312
- const size = box.getSize(new Vector3()), pivot = new Vector3();
313
- const maxSide = Math.max(size.x, size.y, size.z);
314
- if (opts.pivotMode === 'center' || opts.pivotMode === 'bottom-center') {
315
- box.getCenter(pivot);
316
- if (opts.pivotMode === 'bottom-center') pivot.y = box.min.y;
317
- }
318
- if (opts.normalizeSize > 0 && maxSide > 0) root.scale.setScalar(opts.normalizeSize / maxSide);
319
- root.position.copy(pivot).multiplyScalar(-root.scale.x);
320
- root.userData.modelBounds = {width: size.x * root.scale.x, height: size.y * root.scale.y, depth: size.z * root.scale.z};
321
- }
322
- return root;
323
- }
324
-
325
- const _vA = new Vector3(), _vB = new Vector3(), _qA = new Quaternion(), _qB = new Quaternion();
326
-
327
- function sampleTrack(track, t, outVec, outQuat) {
328
- const times = track.times, vals = track.values, n = times.length;
329
- const stride = track.path === 'rotation' ? 4 : 3;
330
- if (n === 0) return;
331
- let i0 = 0, i1 = 0, u = 0;
332
- if (n > 1 && t > times[0]) {
333
- if (t >= times[n - 1]) { i0 = i1 = n - 1; }
334
- else {
335
- let lo = 0, hi = n - 1;
336
- while (lo + 1 < hi) {
337
- const mid = (lo + hi) >> 1;
338
- if (times[mid] <= t) lo = mid; else hi = mid;
339
- }
340
- i0 = lo; i1 = hi;
341
- u = track.interp === 'STEP' ? 0 : (t - times[i0]) / Math.max(1e-8, times[i1] - times[i0]);
342
- }
343
- }
344
- const o0 = i0 * stride, o1 = i1 * stride;
345
- if (track.path === 'rotation') {
346
- _qA.set(vals[o0], vals[o0 + 1], vals[o0 + 2], vals[o0 + 3]);
347
- if (i0 === i1 || u === 0) { outQuat.copy(_qA); return; }
348
- _qB.set(vals[o1], vals[o1 + 1], vals[o1 + 2], vals[o1 + 3]);
349
- outQuat.copy(_qA).slerp(_qB, u);
350
- } else {
351
- _vA.set(vals[o0], vals[o0 + 1], vals[o0 + 2]);
352
- if (i0 === i1 || u === 0) { outVec.copy(_vA); return; }
353
- _vB.set(vals[o1], vals[o1 + 1], vals[o1 + 2]);
354
- outVec.copy(_vA).lerp(_vB, u);
355
- }
356
- }
357
-
358
- function foldedTime(rawTime, duration, loop) {
359
- if (duration <= 0) return 0;
360
- if (loop === 'once') return Math.min(duration, Math.max(0, rawTime));
361
- if (loop === 'pingpong') {
362
- const cycle = duration * 2;
363
- const m = ((rawTime % cycle) + cycle) % cycle;
364
- return m <= duration ? m : cycle - m;
365
- }
366
- return ((rawTime % duration) + duration) % duration;
367
- }
368
-
369
- export function createModelAnimator(modelRoot) {
370
- const template = modelRoot?.userData?.template;
371
- const nodes = modelRoot?.userData?.clonedByIndex;
372
- if (!template?.animations?.length || !nodes) return null;
373
- const restPose = new Map();
374
- for (const clip of template.animations) {
375
- for (const tr of clip.tracks) {
376
- const obj = nodes.get(tr.nodeIndex);
377
- if (obj && !restPose.has(tr.nodeIndex)) {
378
- restPose.set(tr.nodeIndex, {pos: obj.position.clone(), quat: obj.quaternion.clone(), scl: obj.scale.clone()});
379
- }
380
- }
381
- }
382
- const restoreRest = () => {
383
- for (const [idx, rest] of restPose) {
384
- const obj = nodes.get(idx);
385
- if (!obj) continue;
386
- obj.position.copy(rest.pos);
387
- obj.quaternion.copy(rest.quat);
388
- obj.scale.copy(rest.scl);
389
- }
390
- };
391
- let active = null, prev = null, fadeElapsed = 0, fadeDuration = 0;
392
- const scratchV = new Vector3(), scratchQ = new Quaternion();
393
- const applyPose = () => {
394
- restoreRest();
395
- const alpha = prev && fadeDuration > 0 ? Math.min(1, fadeElapsed / fadeDuration) : 1;
396
- if (prev && alpha < 1) {
397
- const pt = foldedTime(prev.time, prev.clip.duration, prev.loop);
398
- for (const tr of prev.clip.tracks) {
399
- const obj = nodes.get(tr.nodeIndex);
400
- if (!obj) continue;
401
- sampleTrack(tr, pt, scratchV, scratchQ);
402
- if (tr.path === 'translation') obj.position.copy(scratchV);
403
- else if (tr.path === 'rotation') obj.quaternion.copy(scratchQ);
404
- else if (tr.path === 'scale') obj.scale.copy(scratchV);
405
- }
406
- }
407
- if (active) {
408
- const ct = foldedTime(active.time, active.clip.duration, active.loop);
409
- for (const tr of active.clip.tracks) {
410
- const obj = nodes.get(tr.nodeIndex);
411
- if (!obj) continue;
412
- sampleTrack(tr, ct, scratchV, scratchQ);
413
- if (tr.path === 'translation') { if (alpha < 1) obj.position.lerp(scratchV, alpha); else obj.position.copy(scratchV); }
414
- else if (tr.path === 'rotation') { if (alpha < 1) obj.quaternion.slerp(scratchQ, alpha); else obj.quaternion.copy(scratchQ); }
415
- else if (tr.path === 'scale') { if (alpha < 1) obj.scale.lerp(scratchV, alpha); else obj.scale.copy(scratchV); }
416
- }
417
- }
418
- };
419
- return {
420
- play(clipName, {loop = 'repeat', speed = 1, fadeSeconds = 0.15, restart = false, startTime = 0} = {}) {
421
- const clip = clipName ? template.animationsByName.get(clipName) : template.animations[0];
422
- if (!clip) return false;
423
- if (active?.clip === clip && !restart && active.playing) {
424
- active.loop = loop;
425
- active.speed = speed;
426
- return true;
427
- }
428
- prev = active && fadeSeconds > 0 ? {...active} : null;
429
- fadeDuration = prev ? fadeSeconds : 0;
430
- fadeElapsed = 0;
431
- active = {clip, loop, speed, time: startTime, playing: true, ended: false};
432
- applyPose();
433
- return true;
434
- },
435
- step(dt, onEnd) {
436
- if (!active || !active.playing) return false;
437
- const stepDt = Math.max(0, dt);
438
- if (prev && fadeDuration > 0) {
439
- prev.time += stepDt * prev.speed;
440
- fadeElapsed += stepDt;
441
- if (fadeElapsed >= fadeDuration) { prev = null; fadeDuration = 0; }
442
- }
443
- active.time += stepDt * active.speed;
444
- let finishedClip = null;
445
- if (active.loop === 'once' && active.clip.duration > 0 && active.time >= active.clip.duration) {
446
- active.time = active.clip.duration;
447
- active.playing = false;
448
- if (!active.ended) { active.ended = true; finishedClip = active.clip.name; }
449
- }
450
- applyPose();
451
- if (finishedClip) onEnd?.(finishedClip);
452
- return true;
453
- },
454
- reset() {
455
- active = null; prev = null; fadeElapsed = 0; fadeDuration = 0;
456
- restoreRest();
457
- },
458
- snapshot() {
459
- return {
460
- clip: active?.clip?.name ?? null,
461
- time: active ? Number(active.time.toFixed(4)) : 0,
462
- playing: Boolean(active?.playing),
463
- loop: active?.loop ?? 'repeat',
464
- clips: template.animations.map(c => c.name),
465
- };
466
- },
467
- };
468
- }
@@ -1,21 +0,0 @@
1
- const treatments = Object.freeze({
2
- crisp: Object.freeze({ revealFrom: .85, revealSeconds: .5, easing: 'back-out', particles: 64, speed: 180, lifetime: 1.2, gain: .38 }),
3
- bloom: Object.freeze({ revealFrom: .72, revealSeconds: .72, easing: 'ease-out', particles: 48, speed: 140, lifetime: 1.4, gain: .34 }),
4
- });
5
- const variants = Object.freeze(Object.keys(treatments).sort());
6
-
7
- export const harvestRecipeId = 'harvest-reward-1';
8
- export const harvestRecipeVariants = Object.freeze([...variants, 'seeded']);
9
-
10
- export function harvestRecipe(plan) {
11
- const requested = plan.rewardRecipe?.variant;
12
- const variant = requested === 'seeded' ? variants[plan.seed % variants.length] : requested ?? 'crisp';
13
- return {
14
- treatment: treatments[variant],
15
- ...(requested ? { receipt: {
16
- id: harvestRecipeId, variant, seed: plan.seed,
17
- reviewStatus: 'pending', audioRoles: { ...plan.audio },
18
- scenarios: ['opening', 'first-harvest', 'invalid-swap', 'timeout', 'third-harvest', 'replay'],
19
- } } : {}),
20
- };
21
- }
@@ -1,24 +0,0 @@
1
- export function seedFromText(text){
2
- let hash=2166136261;for(const char of String(text)){hash^=char.codePointAt(0);hash=Math.imul(hash,16777619);}return hash>>>0||1;
3
- }
4
- export function createRng(seed){
5
- const initial=seed>>>0||1;let state=initial;
6
- return {next(){state=(Math.imul(state,1664525)+1013904223)>>>0;return state/4294967296;},between(min,max,integer=false){if(integer){const lo=Math.ceil(min),hi=Math.floor(max);return hi<lo?lo:Math.min(hi,lo+Math.floor((hi-lo+1)*this.next()));}return min+(max-min)*this.next();},reset(){state=initial;}};
7
- }
8
- export function findNearestByTeam(origin,nodes,team,maxRangePx=0,excludeId){
9
- let best=null,bestDistance=Infinity;
10
- for(const node of nodes){
11
- if(node.id===excludeId||node.team!==team)continue;
12
- const distance=Math.hypot(node.x-origin.x,node.y-origin.y);if(maxRangePx>0&&distance>maxRangePx)continue;
13
- if(distance<bestDistance||(distance===bestDistance&&node.id<best?.id)){best=node;bestDistance=distance;}
14
- }
15
- return best;
16
- }
17
- export function turnToward(current,target,maxDelta){
18
- let delta=((target-current+Math.PI)%(Math.PI*2)+Math.PI*2)%(Math.PI*2)-Math.PI;
19
- return current+Math.max(-maxDelta,Math.min(maxDelta,delta));
20
- }
21
- export function createInstanceSteering(seed){
22
- let rng=createRng(seed);const states=new Map(),headings=new Map();
23
- return {rng,states,headings,reset(){rng.reset();states.clear();headings.clear();},initialize(id,parameters){if(!states.has(id))states.set(id,{hp:parameters.hp,maxHp:parameters.maxHp,value:parameters.value,tag:parameters.tag??'',team:parameters.team});return states.get(id);},remove(id){states.delete(id);headings.delete(id);},snapshot(id){const state=states.get(id);return state?{...state}:undefined;}};
24
- }