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.

7.0 KB
Raw Blame
import { Group, InstancedMesh, InstancedBufferAttribute, DynamicDrawUsage, Mesh, Matrix4, Sphere, Vector3 } from 'three/webgpu';
import type { BufferGeometry, Material } from 'three/webgpu';
import { deriveInstancingSafeGeometry } from './core';
export interface LodLevel {geometry:BufferGeometry;material?:Material;maxDistance:number}
export interface InstanceSet {key:string;geometry:BufferGeometry;material:Material;matrices:Float32Array;colors?:Float32Array;castShadow:boolean;receiveShadow:boolean;cellSize:number;density:'vegetation'|'instance'|'none';lods?:LodLevel[];dynamic?:boolean;bounds?:Sphere}
export interface InstanceHandle {readonly capacity:number;count:number;setMatrix(i:number,m:Matrix4):void;setColor(i:number,r:number,g:number,b:number):void;flush():void}
export interface InstanceCell {key:string;indices:number[]}
export function splitInstanceCells(matrices:Float32Array,cellSize:number):InstanceCell[]{if(matrices.length%16)throw new Error('Instance matrix buffer must contain 16 floats per instance');if(cellSize<0||!Number.isFinite(cellSize))throw new Error('Invalid instance cellSize');const groups=new Map<string,InstanceCell>();for(let i=0;i<matrices.length/16;i++){const key=cellSize?`${Math.floor(matrices[i*16+12]!/cellSize)},${Math.floor(matrices[i*16+14]!/cellSize)}`:'0,0';let c=groups.get(key);if(!c){c={key,indices:[]};groups.set(key,c);}c.indices.push(i);}return [...groups.values()].sort((a,b)=>{const aa=a.key.split(',').map(Number),bb=b.key.split(',').map(Number);return aa[0]!-bb[0]!||aa[1]!-bb[1]!;});}
export function selectCellLod(distance:number,limits:readonly number[],current:number,hysteresis=.05):number{if(!limits.length)return 0;let next=Math.max(0,Math.min(current,limits.length-1));while(next<limits.length-1&&distance>limits[next]!*(1+hysteresis))next++;while(next>0&&distance<limits[next-1]!*(1-hysteresis))next--;return next;}
interface RenderCell {meshes:InstancedMesh[];bounds:Sphere;level:number;visible:boolean}
export interface BuiltInstanceSet {root:Group;meshes:InstancedMesh[];handle:InstanceHandle|null;setDensity(d:number):void;update(viewpoint:Vector3,drawDistance:number,lodBias:number,maxCellsPerFrame?:number):void;dispose():void}
export function buildInstanceSet(set:InstanceSet):BuiltInstanceSet{
 if(set.dynamic&&set.cellSize!==0)throw new Error('Dynamic instance sets require cellSize 0');if(set.dynamic&&set.lods?.length)throw new Error('Use one dynamic instance set per LOD');const capacity=set.matrices.length/16;if(!Number.isInteger(capacity))throw new Error('Invalid instance matrices');if(set.colors&&set.colors.length!==capacity*3)throw new Error('Instance colors must contain 3 floats per instance');if(set.lods?.some((l,i)=>l.maxDistance<=0||(i>0&&l.maxDistance<=set.lods![i-1]!.maxDistance)))throw new Error('LOD distances must increase');
 const root=new Group();root.name=set.key;const meshes:InstancedMesh[]=[],cells:RenderCell[]=[],derived=new Map<BufferGeometry,BufferGeometry>(),matrix=new Matrix4();let density=1,disposed=false,cursor=0;
 const definitions=set.lods?.length?set.lods:[{geometry:set.geometry,material:set.material,maxDistance:Infinity}];const limits=definitions.map(l=>l.maxDistance);
 const split=splitInstanceCells(set.matrices,set.cellSize);if(set.dynamic&&!split.length)split.push({key:'0,0',indices:[]});for(const cell of split){const render:RenderCell={meshes:[],bounds:new Sphere(),level:0,visible:true};for(let level=0;level<definitions.length;level++){const def=definitions[level]!,material=def.material??set.material,geometry=deriveInstancingSafeGeometry(new Mesh(def.geometry,material),derived),mesh=new InstancedMesh(geometry,material,cell.indices.length);mesh.name=`${set.key}/${cell.key}/lod-${level}`;mesh.castShadow=set.castShadow;mesh.receiveShadow=set.receiveShadow;mesh.frustumCulled=true;if(set.dynamic)mesh.instanceMatrix.setUsage(DynamicDrawUsage);for(let i=0;i<cell.indices.length;i++)mesh.setMatrixAt(i,matrix.fromArray(set.matrices,cell.indices[i]!*16));if(set.colors||set.dynamic){const colors=new Float32Array(cell.indices.length*3).fill(1);if(set.colors)for(let i=0;i<cell.indices.length;i++)colors.set(set.colors.subarray(cell.indices[i]!*3,cell.indices[i]!*3+3),i*3);mesh.instanceColor=new InstancedBufferAttribute(colors,3);if(set.dynamic)mesh.instanceColor.setUsage(DynamicDrawUsage);}mesh.computeBoundingSphere();if(set.bounds)mesh.boundingSphere=set.bounds.clone();if(level===0)render.bounds.copy(mesh.boundingSphere!);else render.bounds.union(mesh.boundingSphere!);mesh.visible=level===0;root.add(mesh);render.meshes.push(mesh);meshes.push(mesh);}cells.push(render);}
 let requested=capacity,matStart=Infinity,matEnd=-1,colStart=Infinity,colEnd=-1;const main=meshes[0],matrixRange={start:0,count:0},colorRange={start:0,count:0};const check=(i:number)=>{if(disposed)throw new Error('Instance set disposed');if(!Number.isInteger(i)||i<0||i>=capacity)throw new RangeError(`Instance index ${i}`);};
 const applyDensity=()=>{for(const mesh of meshes)mesh.count=Math.floor((set.dynamic?requested:mesh.instanceMatrix.count)*density);};
 const handle:InstanceHandle|null=set.dynamic?{capacity,get count(){return requested;},set count(n:number){if(disposed)throw new Error('Instance set disposed');if(!Number.isInteger(n)||n<0||n>capacity)throw new RangeError('Instance count exceeds capacity');requested=n;applyDensity();},setMatrix(i,m){check(i);m.toArray(main!.instanceMatrix.array,i*16);matStart=Math.min(matStart,i);matEnd=Math.max(matEnd,i);},setColor(i,r,g,b){check(i);main!.instanceColor!.setXYZ(i,r,g,b);colStart=Math.min(colStart,i);colEnd=Math.max(colEnd,i);},flush(){if(disposed)throw new Error('Instance set disposed');if(matEnd>=matStart){main!.instanceMatrix.clearUpdateRanges();matrixRange.start=matStart*16;matrixRange.count=(matEnd-matStart+1)*16;main!.instanceMatrix.updateRanges.push(matrixRange);main!.instanceMatrix.needsUpdate=true;if(!set.bounds){main!.computeBoundingSphere();cells[0]!.bounds.copy(main!.boundingSphere!);}matStart=Infinity;matEnd=-1;}if(colEnd>=colStart){main!.instanceColor!.clearUpdateRanges();colorRange.start=colStart*3;colorRange.count=(colEnd-colStart+1)*3;main!.instanceColor!.updateRanges.push(colorRange);main!.instanceColor!.needsUpdate=true;colStart=Infinity;colEnd=-1;}applyDensity();}}:null;
 return{root,meshes,handle,setDensity(d){if(!Number.isFinite(d))throw new Error('Invalid density');density=Math.max(0,Math.min(1,d));applyDensity();},update(viewpoint,drawDistance,lodBias,maxCellsPerFrame=32){if(disposed)return;const budget=Math.min(cells.length,Math.max(1,maxCellsPerFrame));for(let i=0;i<budget;i++){const c=cells[cursor++%cells.length]!;const distance=Math.max(0,c.bounds.center.distanceTo(viewpoint)-c.bounds.radius),far=drawDistance*lodBias;if(c.visible?distance>far*1.05:distance<far*.95)c.visible=!c.visible;c.level=selectCellLod(distance/Math.max(.001,lodBias),limits,c.level);for(let l=0;l<c.meshes.length;l++)c.meshes[l]!.visible=c.visible&&l===c.level;}},dispose(){if(disposed)return;disposed=true;root.removeFromParent();for(const mesh of meshes)mesh.dispose();root.clear();for(const g of derived.values())g.dispose();derived.clear();}};
}