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.

14.2 KB
Raw Blame
import test from'node:test';import assert from'node:assert/strict';import*as THREE from'three/webgpu';import{optimizeStaticAsset,batchStaticVegetation}from'../src/game/scene-optimization.mjs';
const mesh=(g,m,x=0)=>{const n=new THREE.Mesh(g,m);n.position.x=x;return n;};const bbox=r=>{r.updateMatrixWorld(true);return new THREE.Box3().setFromObject(r);};
function triangles(meshes){return meshes.flatMap(n=>{n.updateWorldMatrix(true,false);const p=n.geometry.attributes.position,uv=n.geometry.attributes.uv,normal=n.geometry.attributes.normal,ix=n.geometry.index,out=[];for(let i=0;i<(ix?.count??p.count);i++){const k=ix?ix.getX(i):i;out.push({p:new THREE.Vector3().fromBufferAttribute(p,k).applyMatrix4(n.matrixWorld).toArray(),n:new THREE.Vector3().fromBufferAttribute(normal,k).applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(n.matrixWorld)).toArray(),uv:[uv.getX(k),uv.getY(k)]});}return out;}).sort((a,b)=>a.p[0]-b.p[0]||a.p[1]-b.p[1]||a.p[2]-b.p[2]||a.uv[0]-b.uv[0]||a.uv[1]-b.uv[1]||a.n[0]-b.n[0]||a.n[1]-b.n[1]||a.n[2]-b.n[2]);}
function parity(a,b){const key=v=>JSON.stringify([...v.p,...v.n,...v.uv].map(x=>Math.round(x*1e4))),compare=(x,y)=>key(x).localeCompare(key(y));a.sort(compare);b.sort(compare);assert.equal(a.length,b.length);for(let i=0;i<a.length;i++)for(const k of['p','n','uv'])for(let c=0;c<a[i][k].length;c++)assert(Math.abs(a[i][k][c]-b[i][k][c])<5e-6,`${k} differs`);}
test('static derivative is opt-in and preserves transformed triangle, normal, UV, bounds and named socket',()=>{const root=new THREE.Group();root.position.set(7,2,8);root.rotation.y=.6;const frame=new THREE.Group();frame.name='wall_frame';frame.position.set(.2,0,.2);root.add(frame);const g=new THREE.BoxGeometry(.3,.6,.4),m=new THREE.MeshStandardMaterial(),a=mesh(g,m,0),b=mesh(g,m,1);frame.add(a,b);const socket=new THREE.Object3D();socket.name='wall_mount';a.add(socket);root.updateMatrixWorld(true);const original=triangles([a,b]),bounds=bbox(root),matrix=socket.matrixWorld.clone(),off=optimizeStaticAsset(root);assert.equal(a.layers.mask,1);off.dispose();const h=optimizeStaticAsset(root,{enabled:true,cellSize:4});assert.equal(h.after,1);assert.equal(h.before,2);assert.equal(h.meshes.length,1);assert.equal(a.layers.mask,0);assert.equal(a.visible,true);assert.equal(root.getObjectByName('wall_mount'),socket);root.updateMatrixWorld(true);assert(socket.matrixWorld.equals(matrix));parity(original,triangles(h.meshes));assert(bbox(root).min.distanceTo(bounds.min)<1e-6);assert(bbox(root).max.distanceTo(bounds.max)<1e-6);h.dispose();assert.equal(a.layers.mask,1);assert.equal(h.meshes[0].parent,null);});
test('animated joint anchors and explicit dynamic mesh frames remain independent and reversible',()=>{const root=new THREE.Group(),g=new THREE.BoxGeometry(.2,.2,.2),m=new THREE.MeshStandardMaterial(),a=mesh(g,m,0),b=mesh(g,m,.5),joint=new THREE.Group();joint.name='Joint_Door';joint.position.z=1;root.add(a,b,joint);const c=mesh(g,m,0),d=mesh(g,m,.4),board=mesh(g,m,.8);board.name='Board_0';joint.add(c,d,board);const clip=new THREE.AnimationClip('Open',1,[new THREE.NumberKeyframeTrack('Joint_Door.rotation[y]',[0,1],[0,1])]);const h=optimizeStaticAsset(root,{enabled:true,animations:[clip],preserveNodes:['Board_0']});assert.equal(h.meshes.length,2);assert.equal(board.layers.mask,1);assert.equal(root.getObjectByName('Joint_Door'),joint);assert(h.meshes.some(n=>n.parent===joint));joint.rotation.y=.8;root.updateMatrixWorld(true);const derived=h.meshes.find(n=>n.parent===joint);parity(triangles([c,d]),triangles([derived]));h.setEnabled(false);assert.equal(a.layers.mask,1);assert.equal(c.layers.mask,1);assert.equal(derived.layers.mask,0);h.setEnabled(true);assert.equal(c.layers.mask,0);h.dispose();});
test('blends, skin/morph, mirror, partial ranges, semantic controls and unequal render state are skipped or split',()=>{const root=new THREE.Group(),g=new THREE.BoxGeometry(.1,.1,.1),m=new THREE.MeshStandardMaterial(),a=mesh(g,m),b=mesh(g,m,.2);root.add(a,b);b.receiveShadow=true;const t=new THREE.MeshStandardMaterial({transparent:true,opacity:.5}),blends=[mesh(g,t,.4),mesh(g,t,.6)];root.add(...blends);const mirror=mesh(g,m,.8);mirror.scale.x=-1;root.add(mirror);const skin=new THREE.SkinnedMesh(g,m);root.add(skin);const partial=mesh(g.clone(),m,1);partial.geometry.setDrawRange(0,3);root.add(partial);const semantic=mesh(g,m,1.2);semantic.userData.interaction={kind:'window'};root.add(semantic);const h=optimizeStaticAsset(root,{enabled:true});assert.equal(h.meshes.length,0);for(const n of[a,b,...blends,mirror,skin,partial,semantic])assert.equal(n.layers.mask,1);h.dispose();});
test('small spatial cells preserve local culling instead of merging distant geometry',()=>{const root=new THREE.Group(),g=new THREE.BoxGeometry(.2,.2,.2),m=new THREE.MeshStandardMaterial();for(const x of[0,.4,10,10.4])root.add(mesh(g,m,x));const h=optimizeStaticAsset(root,{enabled:true,cellSize:4});assert.equal(h.meshes.length,2);for(const n of h.meshes){assert(n.geometry.boundingBox);assert(n.geometry.boundingSphere);assert(n.geometry.boundingBox.max.x-n.geometry.boundingBox.min.x<1);}h.dispose();});
function vegetation(){const parent=new THREE.Group(),g=new THREE.BoxGeometry(.4,1,.4),m=new THREE.MeshStandardMaterial({alphaTest:.5}),instances=[];for(const x of[1,2,20]){const root=new THREE.Group();root.position.set(x,.5,0);root.name='tree'+x;root.add(mesh(g,m.clone(),-.3),mesh(g,m.clone(),.3));parent.add(root);instances.push({root,animations:[],entry:{key:'pine',sha256:'exact'}});}parent.updateMatrixWorld(true);return{parent,instances,g,m};}
test('vegetation reuses exact geometry/material state in bounded cells and live parent visibility',()=>{const{parent,instances,g}=vegetation(),bounds=bbox(parent),h=batchStaticVegetation(instances,{enabled:true,cellSize:12,parent});assert.equal(h.stats.before,6);assert.equal(h.stats.after,2);assert.equal(h.meshes.length,2);assert.equal(h.meshes.reduce((s,m)=>s+m.count,0),3);assert(bbox(parent).min.distanceTo(bounds.min)<1e-6);assert(bbox(parent).max.distanceTo(bounds.max)<1e-6);instances[0].root.visible=false;h.sync();assert.equal(h.meshes.reduce((s,m)=>s+m.count,0),2);const branch=new THREE.Group();parent.add(branch);branch.add(instances[1].root);branch.visible=false;h.sync();assert.equal(h.meshes.reduce((s,m)=>s+m.count,0),1);let disposed=0;g.addEventListener('dispose',()=>disposed++);h.dispose();assert.equal(disposed,0);for(const i of instances)for(const n of i.root.children)assert.equal(n.layers.mask,1);h.dispose();});
test('vegetation excludes harvest interactions, animation, material changes, mirrored roots and other families',()=>{const{parent,instances}=vegetation();instances[0].root.userData.interaction={kind:'tree'};instances[1].animations=[new THREE.AnimationClip('wind',1,[])];instances[2].root.scale.x=-1;const h=batchStaticVegetation(instances,{enabled:true,parent});assert.equal(h.meshes.length,0);for(const i of instances)for(const n of i.root.children)assert.equal(n.layers.mask,1);h.dispose();});
test('vegetation material equivalence retains roughness, mask sampler identity and scene state',()=>{const{parent,instances}=vegetation();instances[1].root.children[0].material.roughness=.35;const h=batchStaticVegetation(instances,{enabled:true,parent});assert(h.meshes.some(n=>n.material.roughness===.35));assert.equal(h.meshes.reduce((s,n)=>s+(n.geometry.index?.count??n.geometry.attributes.position.count)/3*n.count,0),72);h.dispose();});
function renderedTriangleCoverage(root){root.updateMatrixWorld(true);const values=[];root.traverseVisible(n=>{if(!n.isMesh||!n.layers.mask)return;if(!n.isInstancedMesh){values.push(...triangles([n]));return;}for(let i=0;i<n.count;i++){const transform=new THREE.Matrix4();n.getMatrixAt(i,transform);const p=new THREE.Mesh(n.geometry,n.material);p.matrixAutoUpdate=false;p.matrix.multiplyMatrices(n.matrixWorld,transform);p.matrixWorld.copy(p.matrix);values.push(...triangles([p]));}});return values.sort((a,b)=>a.p[0]-b.p[0]||a.p[1]-b.p[1]||a.p[2]-b.p[2]||a.uv[0]-b.uv[0]||a.uv[1]-b.uv[1]||a.n[0]-b.n[0]||a.n[1]-b.n[1]||a.n[2]-b.n[2]);}
function interleavedPosition(g){const a=g.attributes.position,values=new Float32Array(a.count*4);for(let i=0;i<a.count;i++){values.set([a.getX(i),a.getY(i),a.getZ(i),99],i*4);}g.setAttribute('position',new THREE.InterleavedBufferAttribute(new THREE.InterleavedBuffer(values,4),3,0,false));return g;}
test('equivalent default GPU types merge plain and interleaved foliage without changing triangles or source attributes',()=>{for(const mode of['static','vegetation']){const root=new THREE.Group(),material=new THREE.MeshStandardMaterial({alphaTest:.5,side:THREE.DoubleSide}),a=mesh(interleavedPosition(new THREE.PlaneGeometry(.4,.8)),material),b=mesh(new THREE.PlaneGeometry(.4,.8),material,.5);root.add(a,b);const plain=b.geometry.attributes.position,interleaved=a.geometry.attributes.position;assert.equal(plain.gpuType,THREE.FloatType);assert.equal(interleaved.gpuType,undefined);const before=renderedTriangleCoverage(root);let h;if(mode==='static')h=optimizeStaticAsset(root,{enabled:true});else{const parent=new THREE.Group();parent.add(root);h=batchStaticVegetation([{root,entry:{key:'bush',sha256:'fixture'}}],{enabled:true,parent});}assert.equal(h.meshes.length,1,mode);assert.equal(h.meshes[0].material,material);assert.equal(a.geometry.attributes.position,interleaved);assert.equal(b.geometry.attributes.position,plain);assert.equal(interleaved.gpuType,undefined);assert.equal(plain.gpuType,THREE.FloatType);parity(before,renderedTriangleCoverage(root.parent??root));h.dispose();}});
test('actual GPU type, normalization, item size and typed-array differences remain separate',()=>{for(const difference of['gpuType','normalized','itemSize','array'])for(const mode of['static','vegetation']){const root=new THREE.Group(),material=new THREE.MeshStandardMaterial({alphaTest:.5}),a=mesh(interleavedPosition(new THREE.PlaneGeometry(.4,.8)),material),b=mesh(new THREE.PlaneGeometry(.4,.8),material,.5);if(difference==='gpuType')b.geometry.attributes.position.gpuType=THREE.IntType;if(difference==='normalized')b.geometry.attributes.position.normalized=true;if(difference==='itemSize')b.geometry.setAttribute('uv',new THREE.BufferAttribute(new Float32Array(12),3));if(difference==='array')b.geometry.setAttribute('uv',new THREE.BufferAttribute(new Uint16Array(8),2));root.add(a,b);let h;if(mode==='static')h=optimizeStaticAsset(root,{enabled:true});else{const parent=new THREE.Group();parent.add(root);h=batchStaticVegetation([{root,entry:{key:'bush',sha256:'fixture'}}],{enabled:true,parent});}assert.equal(h.meshes.length,mode==='static'?0:2,`${mode}:${difference}`);h.dispose();assert.equal(a.layers.mask,1);assert.equal(b.layers.mask,1);}});
test('instanced cells preserve every rendered world triangle, normal and UV, including scaled rotated parents',()=>{const{parent,instances}=vegetation();parent.position.set(40,3,-10);parent.rotation.y=.45;instances[1].root.rotation.y=.7;instances[1].root.scale.setScalar(1.2);parent.updateMatrixWorld(true);const before=renderedTriangleCoverage(parent),h=batchStaticVegetation(instances,{enabled:true,parent});parity(before,renderedTriangleCoverage(parent));for(const n of h.meshes)assert.equal(n.userData.assetKey,'pine');for(const i of instances)i.root.visible=false;h.sync();assert(h.meshes.every(n=>n.visible===false&&n.count===0));instances[1].root.visible=true;h.sync();assert(h.meshes.some(n=>n.visible&&n.count===1));h.dispose();});
test('partial static vegetation leaves blended and custom-handler parts source-rendered exactly once',()=>{const{parent,instances,g}=vegetation(),blend=new THREE.MeshStandardMaterial({transparent:true,opacity:.5});for(const i of instances){const skipped=mesh(g,blend);skipped.name='Blend';i.root.add(skipped);const callback=mesh(g,i.root.children[0].material);callback.onBeforeRender=()=>{};callback.name='Handler';i.root.add(callback);}const before=renderedTriangleCoverage(parent),h=batchStaticVegetation(instances,{enabled:true,parent});parity(before,renderedTriangleCoverage(parent));for(const i of instances){assert.equal(i.root.getObjectByName('Blend').layers.mask,1);assert.equal(i.root.getObjectByName('Handler').layers.mask,1);}h.dispose();});

test('family batches span cells and explicitly compact only frustum-visible instances',()=>{
 const {parent,instances}=vegetation(),h=batchStaticVegetation(instances,{enabled:true,parent,strategy:'family-frustum'});
 assert.equal(h.meshes.length,1,'one material template should not split by forest cell');
 const camera=new THREE.PerspectiveCamera(45,1,.1,30);camera.position.set(1.5,1,5);camera.lookAt(1.5,.5,0);camera.updateMatrixWorld(true);
 h.cull(camera);assert.equal(h.meshes[0].count,2);assert.equal(h.stats.after,1);
 const version=h.meshes[0].instanceMatrix.version;h.cull(camera);assert.equal(h.meshes[0].instanceMatrix.version,version,'unchanged visibility must not reupload');
 camera.position.set(20,1,5);camera.lookAt(20,.5,0);h.cull(camera);assert.equal(h.meshes[0].count,1);
 const matrix=new THREE.Matrix4();h.meshes[0].getMatrixAt(0,matrix);assert.equal(matrix.elements[12],20);
 instances[2].root.visible=false;h.cull(camera);assert.equal(h.meshes[0].count,0);assert.equal(h.meshes[0].visible,false);
 instances[2].root.visible=true;h.cull(camera);assert.equal(h.meshes[0].count,1);h.dispose();
});
test('family frustum culling preserves boundary geometry and parent transforms in WebGPU coordinates',()=>{
 const {parent,instances}=vegetation();parent.position.set(34,2,-26);parent.rotation.y=.6;parent.scale.set(1.2,.9,1.1);parent.updateMatrixWorld(true);
 const h=batchStaticVegetation(instances,{enabled:true,parent,strategy:'family-frustum'}),camera=new THREE.PerspectiveCamera(70,16/9,.025,76);
 camera.coordinateSystem=THREE.WebGPUCoordinateSystem;camera.updateProjectionMatrix();
 const point=new THREE.Vector3(20,.5,0).applyMatrix4(parent.matrixWorld);camera.position.copy(point).add(new THREE.Vector3(0,2,5));camera.lookAt(point);
 h.cull(camera);assert.equal(h.meshes[0].count,1);
 const instanceMatrix=new THREE.Matrix4();h.meshes[0].getMatrixAt(0,instanceMatrix);const worldMatrix=parent.matrixWorld.clone().multiply(instanceMatrix);assert.ok(new THREE.Vector3().setFromMatrixPosition(worldMatrix).distanceTo(point)<1e-6);
 const frustum=new THREE.Frustum().setFromProjectionMatrix(new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix,camera.matrixWorldInverse),camera.coordinateSystem);
 const originalBox=new THREE.Box3().setFromObject(instances[2].root);assert.ok(frustum.intersectsBox(originalBox));
 h.dispose();
});