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.

15.0 KB
Raw Blame
import * as THREE from 'three/webgpu';
import {mergeGeometries} from 'three/addons/utils/BufferGeometryUtils.js';
const hits=new WeakMap(),ids=new WeakMap();let nextId=0;
const id=value=>{if(!ids.has(value))ids.set(value,++nextId);return ids.get(value);};
function refreshParent(parent){const chain=[];for(let n=parent;n;n=n.parent)chain.push(n);for(const n of chain.reverse())n.updateWorldMatrix(false,false,true);}
const families=new Set(['windowAssembly','door','interiorDoor']);
const defaults={windowAssembly:['Board_1','Board_2','Board_3'],door:['Door_Hinge'],interiorDoor:['Door_Hinge']};
const visible=node=>{for(let p=node;p;p=p.parent)if(!p.visible)return false;return true;};
function uniform(matrix){const e=matrix.elements;if(e.some(v=>!Number.isFinite(v))||Math.abs(e[3])+Math.abs(e[7])+Math.abs(e[11])+Math.abs(e[15]-1)>1e-8||matrix.determinant()<=0)return false;const a=new THREE.Vector3(e[0],e[1],e[2]),b=new THREE.Vector3(e[4],e[5],e[6]),c=new THREE.Vector3(e[8],e[9],e[10]),s=a.lengthSq();return s>1e-16&&Math.abs(b.lengthSq()-s)<s*1e-6&&Math.abs(c.lengthSq()-s)<s*1e-6&&Math.abs(a.dot(b))+Math.abs(a.dot(c))+Math.abs(b.dot(c))<s*1e-6;}
function state(node,mask=node.layers.mask){return [mask,node.renderOrder,node.castShadow,node.receiveShadow,node.frustumCulled].join('/');}
function materialKey(material){const visited=new WeakSet();function key(v){if(v===null||typeof v!=='object')return typeof v==='function'?'ref:'+id(v):v;if(v.isTexture||v.isNode)return'ref:'+id(v);if(v.toArray)return[v.constructor.name,...v.toArray()];if(visited.has(v))return'ref:'+id(v);visited.add(v);if(Array.isArray(v))return v.map(key);if(Object.getPrototypeOf(v)!==Object.prototype)return'ref:'+id(v);return Object.fromEntries(Object.keys(v).sort().map(k=>[k,key(v[k])]));}return JSON.stringify(Object.fromEntries(Object.keys(material).sort().filter(k=>!['uuid','id','version','_listeners'].includes(k)).map(k=>[k,key(material[k])])));}
function layout(g){return Object.keys(g.attributes).sort().map(k=>{const a=g.attributes[k];return[k,a.itemSize,a.normalized,a.isInterleavedBufferAttribute?a.data.array.constructor.name:a.array.constructor.name,a.gpuType??THREE.FloatType].join('/');}).join('|');}
function geometryVersion(g){return[g.uuid,g.index?.version,...Object.keys(g.attributes).sort().map(k=>[k,g.attributes[k].version,g.attributes[k].data?.version])].flat().join('/');}
function supported(node){const g=node.geometry,m=node.material;if(!node.isMesh||node.isSkinnedMesh||node.isInstancedMesh||node.isBatchedMesh||Array.isArray(m)||!m?.isMeshStandardMaterial||m.isNodeMaterial||m.transparent||m.transmission>0||m.displacementMap||node.customDepthMaterial||node.customDistanceMaterial)return false;if(node.onBeforeRender!==THREE.Object3D.prototype.onBeforeRender||node.onAfterRender!==THREE.Object3D.prototype.onAfterRender||m.onBeforeCompile!==THREE.Material.prototype.onBeforeCompile||node.raycast!==THREE.Mesh.prototype.raycast)return false;return !!g?.attributes.position&&!!g.attributes.normal&&!!g.attributes.uv&&g.attributes.position.itemSize===3&&g.attributes.normal.itemSize===3&&g.attributes.uv.itemSize===2&&!Object.keys(g.morphAttributes??{}).length&&g.drawRange.start===0&&g.drawRange.count===Infinity&&!Object.values(g.attributes).some(a=>a.isInstancedBufferAttribute)&&!node.userData.sceneOptimization&&uniform(node.matrixWorld);}
function localMatrix(node,anchor){const chain=[];for(let n=node;n!==anchor;n=n.parent){if(!n)throw Error('Assembly anchor is not an ancestor');chain.push(n);}const m=new THREE.Matrix4();for(const n of chain.reverse())m.multiply(n.matrix);return m;}
function partVisibility(node,anchor){for(let n=node;n&&n!==anchor;n=n.parent)if(!n.visible)return false;return true;}
function resolveControl(root,value){if(typeof value!=='string'||!value||/[\/.\[\]]/.test(value))return null;const candidates=[];root.traverse(n=>{if(n.name===value||n.name==='Mesh_'+value||n.userData.role===value)candidates.push(n);});return candidates.length===1?candidates[0]:null;}
function collect(instance,controlNames,parent){const root=instance.root,nodes=[],anchors=new Set([root]);let reason=null;for(const name of controlNames){const n=resolveControl(root,name);if(!n)return{reason:'Missing/ambiguous control path '+name};anchors.add(n);}for(const clip of instance.animations??[])for(const track of clip.tracks){let p;try{p=THREE.PropertyBinding.parseTrackName(track.name);}catch{return{reason:'Unsupported animation path'};}if(p.objectName||p.objectIndex!==undefined||!['position','quaternion','rotation','visible'].includes(p.propertyName))return{reason:'Nonrigid/unsupported animation path '+track.name};const n=p.nodeName===root.name||!p.nodeName?root:resolveControl(root,p.nodeName);if(!n)return{reason:'Missing animation target '+track.name};anchors.add(n);}let ancestor=root;while(ancestor&&ancestor!==parent)ancestor=ancestor.parent;if(!ancestor)return{reason:'Assembly is outside batch parent'};root.traverse(n=>{if(n.matrixWorldAutoUpdate===false||n.isBone||n.isLOD||n.isLine||n.isPoints||n.isSprite)reason='Unsupported assembly graph';if(n.isMesh){if(!supported(n)||!n.layers.mask)reason='Unsupported mesh/render state';nodes.push(n);}});if(reason||!nodes.length)return{reason:reason??'Empty assembly'};const buckets=new Map();for(const node of nodes){let anchor=node;while(anchor&&!anchors.has(anchor))anchor=anchor.parent;anchor??=root;const relative=localMatrix(node,anchor);if(!uniform(relative))return{reason:'Nonrigid local part'};const mk=materialKey(node.material),lk=layout(node.geometry),key=[id(anchor),mk,state(node),lk].join(':');let b=buckets.get(key);if(!b){b={anchor,material:node.material,materialKey:mk,state:state(node),layout:lk,parts:[],instance};buckets.set(key,b);}b.parts.push({node,relative,mask:node.layers.mask,geometry:node.geometry,version:geometryVersion(node.geometry),visible:partVisibility(node,anchor),materialKey:mk,state:state(node)});}return{buckets:[...buckets.values()]};}
function prepare(parts){const geometries=[],ranges=[];let triangles=0;try{for(const p of parts){const g=p.geometry.index?p.geometry.toNonIndexed():p.geometry.clone();g.applyMatrix4(p.relative);for(const a of Object.values(g.attributes))a.gpuType??=THREE.FloatType;const count=g.attributes.position.count/3;ranges.push({start:triangles,count,part:p});triangles+=count;geometries.push(g);}const geometry=mergeGeometries(geometries,false);if(!geometry)throw Error('Assembly geometry layout mismatch');geometry.computeBoundingBox();geometry.computeBoundingSphere();return{geometry,ranges};}finally{for(const g of geometries)g.dispose();}}
/** Opt-in render derivative, BEFORE per-instance merges. Rigid OPAQUE/MASK
 * assemblies only. Control anchors are dynamic; child-local geometry is immutable.
 * Incompatible per-entry changes fall back to source. Source roots/sockets, controllers
 * and colliders stay in place; only source render layers are owned while enabled.
 * Caller contract: canonical source geometry/part transforms/materials are immutable.
 * Call sync after changed hinge/board/root visibility or world placement/parent pose;
 * no steady-state scan is needed. Door animation frames need sync until settled.
 * sync validates those assembly matrices/states, but uploads/rebounds only changed
 * batches. Unexpected part/material changes fail back to source when sync is called. */
export function batchRigidAssemblies(instances,options={}){
 const stats={before:0,after:0,acceptedInstances:0,skippedInstances:0,fallbackEntries:0,rejections:[]},meshes=[],group=new THREE.Group();group.name='SceneAssemblyBatches';const entries=[],batches=[],templates=new Map();let enabled=false,disposed=false;
 const noop={group,meshes,stats,sync:()=>({changedBatches:0}),setEnabled(){},dispose(){}};if(options.enabled!==true)return noop;
 const staticFamilies=new Set(options.staticFamilies??[]);for(const key of staticFamilies)if(typeof key!=='string'||!key||families.has(key))throw new TypeError('Explicit static family required');const parent=options.parent??instances[0]?.root.parent,cellSize=options.cellSize??12;if(!parent||!Number.isFinite(cellSize)||cellSize<=0)throw new TypeError('Assembly parent and positive cellSize required');if(options.controlledNodes)for(const key of Object.keys(options.controlledNodes))if(!families.has(key)||!Array.isArray(options.controlledNodes[key]))throw new TypeError('Unknown assembly controls '+key);
 refreshParent(parent);if(!uniform(parent.matrixWorld))return{...noop,stats:{...stats,skippedInstances:instances.length,rejections:['Nonrigid batch parent']}};
 const inverse=parent.matrixWorld.clone().invert(),byKey=new Map();
 try{for(const instance of instances){const key=instance.assetKey??instance.root?.userData.assetKey??instance.entry?.key;if(!families.has(key)&&!staticFamilies.has(key)){stats.skippedInstances++;continue;}if(staticFamilies.has(key)){let controlled=!!instance.animations?.length;instance.root.traverse(n=>{if(n!==instance.root&&(n.userData.dynamic||n.userData.interaction||n.userData.visibilityBoundary))controlled=true;});if(controlled){stats.skippedInstances++;stats.rejections.push({assetKey:key,root:instance.root.name,reason:'Controlled static furnishing'});continue;}}instance.root.updateWorldMatrix(false,true,true);const gathered=collect(instance,options.controlledNodes?.[key]??defaults[key]??[],parent);if(gathered.reason){stats.skippedInstances++;stats.rejections.push({assetKey:key,root:instance.root.name,reason:gathered.reason});continue;}stats.acceptedInstances++;const rootLocal=inverse.clone().multiply(instance.root.matrixWorld),pos=new THREE.Vector3().setFromMatrixPosition(rootLocal),cell=[Math.floor((pos.x+cellSize/2)/cellSize),Math.floor((pos.z+cellSize/2)/cellSize)],origin=new THREE.Vector3(cell[0]*cellSize,0,cell[1]*cellSize);
 for(const b of gathered.buckets){const signature=JSON.stringify([key,instance.entry?.assetId??null,instance.entry?.revisionId??null,instance.entry?.sha256??null,b.materialKey,b.state,b.layout,b.parts.map(p=>[id(p.geometry),p.relative.elements])]);let template=templates.get(signature);if(!template){template={...prepare(b.parts),material:b.material.clone()};templates.set(signature,template);}const batchKey=signature+':'+cell.join('/');let batch=byKey.get(batchKey);if(!batch){batch={template,key,origin,entries:[],active:[],mesh:null,generation:0,disposed:false};byKey.set(batchKey,batch);batches.push(batch);}const e={...b,key,cell,template,batch,fallback:false};entries.push(e);batch.entries.push(e);stats.before+=b.parts.length;}}
 for(const b of batches){const n=new THREE.InstancedMesh(b.template.geometry,b.template.material,b.entries.length),first=b.entries[0].parts[0].node;n.name='SceneAssembly_'+meshes.length;n.position.copy(b.origin);n.layers.mask=first.layers.mask;n.renderOrder=first.renderOrder;n.castShadow=first.castShadow;n.receiveShadow=first.receiveShadow;n.frustumCulled=first.frustumCulled;n.userData.assetKey=b.key;n.userData.sceneOptimization={kind:'rigid-assembly',cellSize,memberRootCount:new Set(b.entries.map(e=>e.instance.root)).size,roots:[...new Set(b.entries.map(e=>e.instance.root.name))],anchors:b.entries.map(e=>e.anchor.name)};const raycast=n.raycast;n.raycast=function(ray,intersections){const start=intersections.length;raycast.call(this,ray,intersections);for(let i=start;i<intersections.length;i++)intersections[i].assemblyGeneration=b.generation;};b.mesh=n;meshes.push(n);group.add(n);hits.set(n,b);}parent.add(group);
 }catch(error){for(const t of templates.values()){t.geometry.dispose();t.material.dispose();}for(const n of meshes)n.dispose();throw error;}
 function sync(){if(disposed||!enabled)return{changedBatches:0};refreshParent(parent);const inv=parent.matrixWorld.clone().invert();for(const i of new Set(entries.map(e=>e.instance)))i.root.updateWorldMatrix(false,true,true);const parentValid=uniform(parent.matrixWorld);stats.fallbackEntries=0;
 for(const e of entries){const rootLocal=inv.clone().multiply(e.instance.root.matrixWorld),pos=new THREE.Vector3().setFromMatrixPosition(rootLocal);e.fallback=!e.parts.every(p=>p.visible)||!parentValid||!uniform(e.anchor.matrixWorld)||Math.floor((pos.x+cellSize/2)/cellSize)!==e.cell[0]||Math.floor((pos.z+cellSize/2)/cellSize)!==e.cell[1]||e.parts.some(p=>!supported(p.node)||p.node.geometry!==p.geometry||geometryVersion(p.geometry)!==p.version||!localMatrix(p.node,e.anchor).equals(p.relative)||partVisibility(p.node,e.anchor)!==p.visible||materialKey(p.node.material)!==p.materialKey||state(p.node,p.mask)!==p.state);if(e.fallback)stats.fallbackEntries++;for(const p of e.parts)p.node.layers.mask=e.fallback?p.mask:0;e.currentVisible=!e.fallback&&visible(e.anchor)&&e.parts.every(p=>p.visible&&p.node.material.visible);e.currentMatrix=new THREE.Matrix4().makeTranslation(-e.batch.origin.x,0,-e.batch.origin.z).multiply(inv).multiply(e.anchor.matrixWorld);}
 let changedBatches=0;for(const b of batches){const active=b.entries.filter(e=>e.currentVisible),signature=active.map(e=>[entries.indexOf(e),e.currentMatrix.elements]),changed=JSON.stringify(signature)!==b.lastSignature;if(changed){b.lastSignature=JSON.stringify(signature);b.active=active;b.mesh.count=active.length;b.mesh.visible=active.length>0;for(let i=0;i<active.length;i++)b.mesh.setMatrixAt(i,active[i].currentMatrix);b.mesh.instanceMatrix.needsUpdate=true;b.mesh.computeBoundingBox();b.mesh.computeBoundingSphere();b.generation++;changedBatches++;}}group.updateWorldMatrix(false,true,true);stats.after=meshes.filter(n=>n.visible&&n.count>0).length;return{changedBatches};
 }
 function setEnabled(value){if(disposed)return;enabled=!!value;group.visible=enabled;for(const e of entries)for(const p of e.parts)p.node.layers.mask=p.mask;if(enabled)sync();else for(const b of batches)b.generation++;}
 setEnabled(true);return{group,meshes,stats,sync,setEnabled,get enabled(){return enabled;},dispose(){if(disposed)return;setEnabled(false);disposed=true;group.removeFromParent();for(const b of batches){b.disposed=true;b.active=[];b.mesh.removeFromParent();b.mesh.dispose();}for(const t of templates.values()){t.geometry.dispose();t.material.dispose();}}};
}
/** Native batch ray hits preserve original mesh material and interaction ancestry.
 * Unknown ordinary hits pass through; stale/out-of-range assembly hits return null. */
export function resolveAssemblyHit(hit){const b=hits.get(hit?.object);if(!b)return hit;if(b.disposed||hit.assemblyGeneration!==b.generation||!Number.isInteger(hit.instanceId)||hit.instanceId<0||hit.instanceId>=b.active.length)return null;const entry=b.active[hit.instanceId],range=b.template.ranges.find(r=>hit.faceIndex>=r.start&&hit.faceIndex<r.start+r.count);if(!range)return null;const part=entry.parts[b.template.ranges.indexOf(range)],faceIndex=hit.faceIndex-range.start,index=part.geometry.index,vertices=[0,1,2].map(k=>index?index.getX(faceIndex*3+k):faceIndex*3+k),matrix=new THREE.Matrix3().getNormalMatrix(part.relative.clone().invert());return{...hit,batchObject:hit.object,batchInstanceId:hit.instanceId,assemblyRoot:entry.instance.root,object:part.node,faceIndex,face:hit.face?{...hit.face,a:vertices[0],b:vertices[1],c:vertices[2],normal:hit.face.normal.clone().applyNormalMatrix(matrix),materialIndex:0}:hit.face,normal:hit.normal?.clone().applyMatrix3(matrix).multiplyScalar(1/Math.hypot(part.relative.elements[0],part.relative.elements[1],part.relative.elements[2]))};}