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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
import { Vector3 } from 'three/webgpu';
import type { Box3, Object3D } from 'three/webgpu';
import { DisposeRegistry } from '../lifecycle/core';
export interface Zone {id:string;bounds:Box3;neighbors:string[]}
export function visibleZones(zones:readonly Zone[],start:string,hops:number):Set<string>{const byId=new Map(zones.map(z=>[z.id,z])),found=new Set<string>([start]),queue:{id:string;depth:number}[]=[{id:start,depth:0}];for(let i=0;i<queue.length;i++){const entry=queue[i]!;if(entry.depth>=Math.max(0,Math.floor(hops)))continue;for(const id of byId.get(entry.id)?.neighbors??[])if(byId.has(id)&&!found.has(id)){found.add(id);queue.push({id,depth:entry.depth+1});}}return found;}
export function createZoneVisibility(zones:Zone[],roots:Map<string,Object3D>,viewpoint:()=>Vector3,hops:()=>number):{current():string|null;update(nowMs:number):void;dispose():void}{const originals=new Map([...roots].map(([id,o])=>[id,o.visible]));let current:string|null=null,candidate:string|null=null,since=0,last=-Infinity,disposed=false;return{current:()=>current,update(nowMs){if(disposed||nowMs-last<200)return;last=nowMs;const point=viewpoint();let next:string|null=null,distance=Infinity;for(const z of zones){const d=z.bounds.distanceToPoint(point);if(d<distance){distance=d;next=z.id;}if(d===0)break;}if(current===null){current=next;candidate=next;since=nowMs;}else if(next!==candidate){candidate=next;since=nowMs;}else if(next!==current&&nowMs-since>=300)current=next;const visible=current?visibleZones(zones,current,hops()):new Set<string>();for(const [id,root]of roots)root.visible=visible.has(id);},dispose(){if(disposed)return;disposed=true;for(const[id,root]of roots)root.visible=originals.get(id)??true;}};}
export interface CellKey {x:number;y:number;z:number}
export interface CellStreamerOptions<C>{cellSize:number;viewpoint:()=>Vector3;radius:()=>number;hysteresis:number;concurrent:number;attachBudgetMs:number;maxResident:number;graceMs:number;load(cell:CellKey,signal:AbortSignal):Promise<C>;attach(cell:CellKey,content:C,registry:DisposeRegistry):void;detach(cell:CellKey,content:C):void;onCellError?:(cell:CellKey,error:unknown)=>void}
const cellId=(c:CellKey)=>`${c.x},${c.y},${c.z}`;
export function wantedCells(point:Vector3,radius:number,cellSize:number):CellKey[]{if(!(cellSize>0)||!Number.isFinite(radius)||radius<0)throw new Error('Invalid cell size or radius');const center={x:Math.floor(point.x/cellSize),y:Math.floor(point.y/cellSize),z:Math.floor(point.z/cellSize)},reach=Math.ceil(radius/cellSize),result:{cell:CellKey;distance:number}[]=[];for(let x=center.x-reach;x<=center.x+reach;x++)for(let y=center.y-reach;y<=center.y+reach;y++)for(let z=center.z-reach;z<=center.z+reach;z++){const distance=((x+.5)*cellSize-point.x)**2+((y+.5)*cellSize-point.y)**2+((z+.5)*cellSize-point.z)**2;if(distance<=radius*radius||(x===center.x&&y===center.y&&z===center.z))result.push({cell:{x,y,z},distance});}result.sort((a,b)=>a.distance-b.distance||a.cell.x-b.cell.x||a.cell.y-b.cell.y||a.cell.z-b.cell.z);return result.map(x=>x.cell);}
type Status='loading'|'queued'|'resident'|'failed';
interface Entry<C>{key:string;cell:CellKey;status:Status;controller:AbortController;registry:DisposeRegistry;content:C|undefined;hasContent:boolean;lastWanted:number;outsideSince:number|null;retryAt:number;attempts:number;distance:number}
export interface CellStreamerCore {update(nowMs:number,radiusScale?:number):void;stats():{resident:number;loading:number;queued:number;attachedLastFrame:number;evicted:number};dispose():void}
/** Injected attach clock makes budget and back-off tests deterministic. Only the hook uses the browser clock. */
export function createCellStreamer<C>(o:CellStreamerOptions<C>,attachClock:()=>number=()=>performance.now()):CellStreamerCore{
if(!(o.cellSize>0)||!Number.isInteger(o.concurrent)||o.concurrent<1||!Number.isInteger(o.maxResident)||o.maxResident<1||o.attachBudgetMs<0||o.graceMs<0||o.hysteresis<0)throw new Error('Invalid cell streamer options');const entries=new Map<string,Entry<C>>(),allControllers=new Set<AbortController>(),attachQueue:Entry<C>[]=[];let disposed=false,lastScan=-Infinity,now=0,scale=1,evicted=0,attachedLastFrame=0,residentCount=0,pumpNeeded=true,queueDirty=false;let wanted:CellKey[]=[];
const report=(e:Entry<C>,error:unknown)=>{try{o.onCellError?.(e.cell,error);}catch{/* A dev diagnostics consumer must not make a cell failure fatal. */}};
const release=(e:Entry<C>)=>{e.controller.abort();allControllers.delete(e.controller);if(e.hasContent){try{o.detach(e.cell,e.content as C);}catch(error){report(e,error);}e.hasContent=false;e.content=undefined;}e.registry.disposeAll();};
const fail=(e:Entry<C>,error:unknown)=>{release(e);e.status='failed';e.attempts++;e.retryAt=now+Math.min(30000,1000*2**(e.attempts-1));pumpNeeded=true;report(e,error);};
const launch=(e:Entry<C>)=>{e.status='loading';e.controller=new AbortController();e.registry=new DisposeRegistry();allControllers.add(e.controller);const controller=e.controller;let promise:Promise<C>;try{promise=o.load(e.cell,controller.signal);}catch(error){fail(e,error);return;}promise.then(content=>{if(disposed||controller.signal.aborted||entries.get(e.key)!==e){try{o.detach(e.cell,content);}catch(error){report(e,error);}return;}e.content=content;e.hasContent=true;e.status='queued';attachQueue.push(e);queueDirty=true;pumpNeeded=true;},error=>{if(disposed||controller.signal.aborted)return;fail(e,error);});};
const drop=(e:Entry<C>)=>{if(e.status==='resident')residentCount--;release(e);entries.delete(e.key);evicted++;pumpNeeded=true;};
const pump=()=>{let loading=0;for(const e of entries.values())if(e.status==='loading')loading++;for(const cell of wanted){if(loading>=o.concurrent)break;const key=cellId(cell);let e=entries.get(key);if(e){if(e.status!=='failed'||now<e.retryAt)continue;}else{e={key,cell,status:'failed',controller:new AbortController(),registry:new DisposeRegistry(),content:undefined,hasContent:false,lastWanted:now,outsideSince:null,retryAt:0,attempts:0,distance:0};entries.set(key,e);}launch(e);loading++;}};
return{update(nowMs,radiusScale=1){if(disposed)return;now=nowMs;scale=Math.max(0,radiusScale);attachedLastFrame=0;const point=o.viewpoint(),radius=o.radius()*scale;if(now-lastScan>=250){lastScan=now;pumpNeeded=true;queueDirty=true;wanted=wantedCells(point,radius,o.cellSize).slice(0,o.maxResident);const keys=new Set(wanted.map(cellId));for(const e of entries.values()){const dx=(e.cell.x+.5)*o.cellSize-point.x,dy=(e.cell.y+.5)*o.cellSize-point.y,dz=(e.cell.z+.5)*o.cellSize-point.z;e.distance=Math.sqrt(dx*dx+dy*dy+dz*dz);if(keys.has(e.key)){e.lastWanted=now;e.outsideSince=null;}else if(e.distance>radius*(1+o.hysteresis)&&e.outsideSince===null)e.outsideSince=now;else if(e.distance<=radius*(1+o.hysteresis))e.outsideSince=null;}}
for(const e of entries.values())if(e.outsideSince!==null&&now-e.outsideSince>=o.graceMs)drop(e);
if(attachQueue.length){if(queueDirty){attachQueue.sort((a,b)=>a.distance-b.distance||a.lastWanted-b.lastWanted);queueDirty=false;}const start=attachClock();while(attachQueue.length&&attachClock()-start<o.attachBudgetMs){const e=attachQueue.shift()!;if(e.status!=='queued'||entries.get(e.key)!==e)continue;while(residentCount>=o.maxResident){let oldest:Entry<C>|undefined;for(const candidate of entries.values())if(candidate.status==='resident'&&(!oldest||candidate.lastWanted<oldest.lastWanted||(candidate.lastWanted===oldest.lastWanted&&candidate.distance>oldest.distance)))oldest=candidate;if(oldest)drop(oldest);else break;}try{o.attach(e.cell,e.content as C,e.registry);e.status='resident';residentCount++;attachedLastFrame++;}catch(error){fail(e,error);}}}
if(pumpNeeded){pumpNeeded=false;pump();}},stats(){let r=0,l=0,q=0;for(const e of entries.values()){if(e.status==='resident')r++;if(e.status==='loading')l++;if(e.status==='queued')q++;}return{resident:r,loading:l,queued:q,attachedLastFrame,evicted};},dispose(){if(disposed)return;disposed=true;for(const c of allControllers)c.abort();for(const e of entries.values())release(e);entries.clear();wanted=[];attachQueue.length=0;allControllers.clear();}};
}