Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

12.3 KB
Raw Blame
import test from 'node:test';import assert from 'node:assert/strict';import * as THREE from 'three/webgpu';
import {batchRigidAssemblies,resolveAssemblyHit} from '../src/game/assembly-batching.mjs';
function fixture(key='windowAssembly'){
 const parent=new THREE.Group(),wood=new THREE.MeshStandardMaterial({roughness:.83}),iron=new THREE.MeshStandardMaterial({metalness:.65}),g=new THREE.BoxGeometry(.05,.17,.42),root=new THREE.Group();root.name='Scene_A';root.userData.interaction={kind:key==='windowAssembly'?'window':'door',id:'A'};
 const part=(group,name,x,y,z,material=wood)=>{const m=new THREE.Mesh(g,material);m.name=name;m.position.set(x,y,z);group.add(m);return m;};
 const frame=new THREE.Group();frame.name='Frame';root.add(frame);part(frame,'FrameA',0,1.3,-.35);part(frame,'FrameB',0,1.3,.35);
 if(key==='windowAssembly')for(let i=1;i<=3;i++){const board=new THREE.Group();board.name='Board_'+i;board.position.set(.12,.2+i*.26,0);root.add(board);part(board,'TimberA',0,0,-.21);part(board,'TimberB',0,0,.21);part(board,'Nail',.04,0,.37,iron);}else{const hinge=new THREE.Group();hinge.name='Door_Hinge';hinge.position.set(.02,0,-.5);root.add(hinge);part(hinge,'LeafA',0,.6,.3);part(hinge,'LeafB',0,.6,.72);part(hinge,'Latch',.04,.6,.92,iron);}
 const socket=new THREE.Object3D();socket.name='Mount';socket.position.set(.1,.6,0);root.add(socket);const clone=root.clone(true);clone.name='Scene_B';clone.position.z=3;clone.userData.interaction={kind:key==='windowAssembly'?'window':'door',id:'B'};clone.traverse(n=>{if(n.isMesh)n.material=n.material.clone();});parent.add(root,clone);parent.updateMatrixWorld(true);
 const instances=[root,clone].map(r=>({root:r,assetKey:key,entry:{key,sha256:'fixture-pin'},animations:key==='windowAssembly'?[]:[new THREE.AnimationClip('Open',1,[new THREE.NumberKeyframeTrack('Door_Hinge.rotation[y]',[0,1],[0,-1.2])])]}));return{parent,instances,g};
}
test('explicit static furnishing families share repeated templates and preserve original hit ancestry',()=>{
 const f=fixture();for(const instance of f.instances){instance.assetKey='bench';instance.animations=[];instance.root.userData.interaction={kind:'storage',id:instance.root.name};}
 const before=coverage([f.parent]),h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent,staticFamilies:['bench']});
 assert.equal(h.stats.acceptedInstances,2);assert.equal(h.meshes.length,2);parity(before,coverage([f.parent]));
 const source=f.instances[1].root.getObjectByName('TimberA'),hit=resolveAssemblyHit(rayAt(source).intersectObjects(h.group.children,true)[0]);assert.equal(hit.assemblyRoot,f.instances[1].root);
 h.dispose();parity(before,coverage([f.parent]));
});
test('static furnishing opt-in never silently freezes animation or controlled subparts',()=>{
 for(const kind of ['animation','control']){const f=fixture();for(const i of f.instances){i.assetKey='bench';if(kind==='animation')i.animations=[new THREE.AnimationClip('Move',1,[])];else i.root.getObjectByName('Board_1').userData.dynamic=true;}
 const h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent,staticFamilies:['bench']});assert.equal(h.stats.acceptedInstances,0);assert.equal(h.meshes.length,0);h.dispose();}
});
function coverage(roots,ignoreLayers=false){const triangles=[],p=new THREE.Vector3(),n=new THREE.Vector3(),mat=new THREE.Matrix4(),im=new THREE.Matrix4();for(const root of roots){root.updateWorldMatrix(true,true);root.traverseVisible(mesh=>{if(!mesh.isMesh||!ignoreLayers&&!mesh.layers.mask)return;const g=mesh.geometry,position=g.attributes.position,normal=g.attributes.normal,uv=g.attributes.uv,total=g.index?.count??position.count;for(let instance=0;instance<(mesh.isInstancedMesh?mesh.count:1);instance++){if(mesh.isInstancedMesh){mesh.getMatrixAt(instance,im);mat.multiplyMatrices(mesh.matrixWorld,im);}else mat.copy(mesh.matrixWorld);const nm=new THREE.Matrix3().getNormalMatrix(mat);for(let i=0;i<total;i+=3){const row=[];for(let k=0;k<3;k++){const v=g.index?g.index.getX(i+k):i+k;p.fromBufferAttribute(position,v).applyMatrix4(mat);n.fromBufferAttribute(normal,v).applyNormalMatrix(nm);row.push(p.x,p.y,p.z,n.x,n.y,n.z,uv.getX(v),uv.getY(v));}triangles.push(row);}}});}return triangles.sort((a,b)=>a.map(v=>v.toFixed(4)).join(',').localeCompare(b.map(v=>v.toFixed(4)).join(',')));}
function parity(a,b){assert.equal(a.length,b.length,'triangle count');for(let i=0;i<a.length;i++)for(let k=0;k<a[i].length;k++)assert(Math.abs(a[i][k]-b[i][k])<5e-6,`world position/normal/UV at${i}:${k}`);}
function rayAt(node){node.updateWorldMatrix(true,false);const target=new THREE.Vector3(0,.026,.075).applyMatrix4(node.matrixWorld),direction=new THREE.Vector3(1,0,0).transformDirection(node.matrixWorld);return new THREE.Raycaster(target.clone().addScaledVector(direction,3),direction.negate(),0,10);}
test('opt-in assembly templates retain source graph/material/geometry and exact world coverage',()=>{const f=fixture();f.parent.position.set(7,2,-5);f.parent.rotation.y=.43;f.parent.scale.setScalar(1.25);f.instances[1].root.rotation.y=.7;f.instances[1].root.scale.setScalar(.8);const before=coverage([f.parent]),socket=f.instances[0].root.getObjectByName('Mount');socket.updateWorldMatrix(true,false);const socketMatrix=socket.matrixWorld.clone(),vertices=f.g.attributes.position.array.slice(),h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent});assert(h.meshes.length>0);assert(h.stats.after<h.stats.before);parity(before,coverage([f.parent]));assert.deepEqual(f.g.attributes.position.array,vertices);assert(socket.matrixWorld.equals(socketMatrix));for(const m of h.meshes)assert.equal(m.userData.assetKey,'windowAssembly');h.dispose();parity(before,coverage([f.parent]));assert(h.meshes.every(n=>n.parent===null));});
test('hinge transforms update independently and unchanged sync never writes GPU buffers',()=>{const f=fixture('door'),h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent}),versions=h.meshes.map(n=>n.instanceMatrix.version);assert.equal(h.sync().changedBatches,0);assert.deepEqual(h.meshes.map(n=>n.instanceMatrix.version),versions);f.instances[1].root.getObjectByName('Door_Hinge').rotation.y=-1.2;assert(h.sync().changedBatches>0);parity(coverage(f.instances.map(i=>i.root),true),coverage([f.parent]));const versions2=h.meshes.map(n=>n.instanceMatrix.version);h.sync();assert.deepEqual(h.meshes.map(n=>n.instanceMatrix.version),versions2);h.dispose();});
test('board and ancestor visibility compact active matrices with fresh bounds and no duplicate sources',()=>{const f=fixture(),h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent});f.instances[0].root.getObjectByName('Board_2').visible=false;f.instances[1].root.visible=false;h.sync();parity(coverage(f.instances.map(i=>i.root),true),coverage([f.parent]));for(const n of h.meshes){assert(n.boundingBox);assert(n.boundingSphere);assert.equal(n.visible,n.count>0);}f.instances[1].root.visible=true;f.instances[0].root.getObjectByName('Board_2').visible=true;h.sync();parity(coverage(f.instances.map(i=>i.root),true),coverage([f.parent]));h.dispose();});
test('native ray hits resolve to exact original source/semantic root and reject stale compacted hits',()=>{const f=fixture(),source=f.instances[1].root.getObjectByName('TimberA'),ray=rayAt(source),before=ray.intersectObjects(f.parent.children,true)[0],h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent}),hit=ray.intersectObjects(f.parent.children,true)[0],resolved=resolveAssemblyHit(hit);assert(resolved.object===before.object,"Original source mesh identity");assert(resolved.assemblyRoot===f.instances[1].root,"Original semantic root identity");assert(Math.abs(resolved.distance-before.distance)<5e-6);assert(resolved.point.distanceTo(before.point)<5e-6);f.instances[1].root.visible=false;h.sync();assert.equal(resolveAssemblyHit(hit),null);assert.equal(resolveAssemblyHit(before),before);h.dispose();});
test('changed local part or cloned material falls back to original without contaminating other instances',()=>{const f=fixture(),h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent});f.instances[0].root.getObjectByName('TimberA').position.z+=.05;f.instances[1].root.getObjectByName('FrameA').material.color.set('#ff0000');h.sync();parity(coverage(f.instances.map(i=>i.root),true),coverage([f.parent]));assert(h.stats.fallbackEntries>0);for(const n of h.meshes)assert.notEqual(n.material.color.getHex(),0xff0000);h.dispose();});
test('unsupported deformation/state/paths reject complete instances and preserve source layers',()=>{for(const mutation of ['blend','callback','shader','morph','mirror','nonuniform','shear','badTrack','badPath']){const f=fixture('door');for(const i of f.instances){const node=i.root.getObjectByName('LeafA');if(mutation==='blend')node.material.transparent=true;if(mutation==='callback')node.onBeforeRender=()=>{};if(mutation==='shader')node.material.onBeforeCompile=()=>{};if(mutation==='morph')node.geometry.morphAttributes.position=[node.geometry.attributes.position.clone()];if(mutation==='mirror')i.root.scale.x=-1;if(mutation==='nonuniform')i.root.scale.y=2;if(mutation==='shear'){i.root.matrixAutoUpdate=false;i.root.matrix.makeShear(.3,0,0,0,0,0);}if(mutation==='badTrack')i.animations.push(new THREE.AnimationClip('Bad',1,[new THREE.NumberKeyframeTrack('LeafA.material.opacity',[0,1],[1,.5])]));}const h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent,...(mutation==='badPath'?{controlledNodes:{door:['Missing/Hinge']}}:{})});assert.equal(h.meshes.length,0,mutation);for(const i of f.instances)i.root.traverse(n=>{if(n.isMesh)assert.equal(n.layers.mask,1,mutation);});h.dispose();}});
test('initial partial local visibility keeps remaining source parts instead of hiding the whole merged entry',()=>{const f=fixture();f.instances[0].root.getObjectByName('FrameA').visible=false;const before=coverage([f.parent]),h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent});parity(before,coverage([f.parent]));h.dispose();});
test('resolved indexed source face indices match original ray hit',()=>{const f=fixture(),ray=rayAt(f.instances[1].root.getObjectByName('TimberA')),before=ray.intersectObjects(f.parent.children,true)[0],h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent}),after=resolveAssemblyHit(ray.intersectObjects(f.parent.children,true)[0]);assert.deepEqual([after.face.a,after.face.b,after.face.c],[before.face.a,before.face.b,before.face.c]);assert(after.normal.distanceTo(before.normal)<5e-6);h.dispose();});
test('sync makes raycast matrices current without a render traversal, including nonzero cells',()=>{const f=fixture();f.instances[1].root.position.z=20;const h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent});f.parent.position.set(4,2,8);f.instances[1].root.getObjectByName('Board_1').rotation.y=.4;h.sync();const source=f.instances[1].root.getObjectByName('TimberA'),ray=rayAt(source),before=ray.intersectObjects(f.instances.map(i=>i.root),true);const rawRay=new THREE.Raycaster(ray.ray.origin,ray.ray.direction,0,10);rawRay.layers.enableAll();const rawHits=[];for(const i of f.instances)i.root.traverseVisible(n=>{if(n.isMesh)n.raycast(rawRay,rawHits);});const raw=rawHits.sort((a,b)=>a.distance-b.distance)[0],after=resolveAssemblyHit(ray.intersectObjects(h.group.children,true)[0]);assert(after&&raw,'Current batch and source hits');assert(after.object===raw.object,'Current source ray identity');assert(Math.abs(after.distance-raw.distance)<5e-6);h.dispose();});
test('resolved curved-surface ray normal preserves native interpolation magnitude',()=>{const f=fixture(),g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute([0,-1,-1,0,1,-1,0,0,1],3));g.setAttribute('normal',new THREE.Float32BufferAttribute([1,0,0,.8,.6,0,.8,0,.6],3));g.setAttribute('uv',new THREE.Float32BufferAttribute([0,0,1,0,.5,1],2));for(const i of f.instances)i.root.getObjectByName('TimberA').geometry=g;f.parent.updateMatrixWorld(true);const source=f.instances[1].root.getObjectByName('TimberA'),target=source.getWorldPosition(new THREE.Vector3()).add(new THREE.Vector3(0,.01,-.65)),ray=new THREE.Raycaster(target.clone().add(new THREE.Vector3(3,0,0)),new THREE.Vector3(-1,0,0),0,5),before=ray.intersectObjects(f.parent.children,true)[0];assert(before.object===source);assert(before.normal.length()<.99);const h=batchRigidAssemblies(f.instances,{enabled:true,parent:f.parent}),after=resolveAssemblyHit(ray.intersectObjects(f.parent.children,true)[0]);assert(after.object===source);assert(after.normal.distanceTo(before.normal)<5e-6,'Preserve native interpolated normal magnitude');h.dispose();});