incanto 0.79.0 → 0.79.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/debug.d.ts +9 -0
- package/dist/debug.js +48 -7
- package/dist/index.js +1 -1
- package/dist/{src-rS7AyeKD.js → src-3rJ6QSfX.js} +1 -1
- package/dist/vite.js +1 -1
- package/editor/assets/{agent8-WXuvhs5H.js → agent8-q_2WV8pw.js} +1 -1
- package/editor/assets/debug-DepFCl1d.js +3 -0
- package/editor/assets/{index-DJryzpvb.js → index-QEwr2eXD.js} +2 -2
- package/editor/index.html +1 -1
- package/package.json +1 -1
- package/templates-app/beacon-isle-3d/package.json +1 -1
- package/templates-app/molehill-2d/package.json +1 -1
- package/templates-app/platformer-2d/package.json +1 -1
- package/templates-app/star-survivor/package.json +1 -1
- package/templates-app/tps-3d/package.json +1 -1
- package/templates-app/village-quest-3d/package.json +1 -1
- package/editor/assets/debug-xpJQqbx1.js +0 -3
|
@@ -6226,7 +6226,7 @@ void main() {
|
|
|
6226
6226
|
if (any(greaterThan(abs(vCutLocal), uHalf))) discard;
|
|
6227
6227
|
gl_FragColor = vec4(0.0);
|
|
6228
6228
|
}
|
|
6229
|
-
`,colorWrite:!1,depthWrite:!0,depthTest:!1,side:2}),_S=9.81,vS=6,yS=.15,bS=class extends Tt{static props={water:{default:``,nodePath:!0},draft:{default:.35},stiffness:{default:3},damping:{default:3.5},drift:{default:.6},drag:{default:.9},samples:{default:4},size:{default:[1,1]}};static signals=[`submerged`,`surfaced`];water=``;draft=.35;stiffness=3;damping=3.5;drift=.6;drag=.9;samples=4;size=[1,1];surface=null;wet=!1;reportedNoImpulse=!1;reportedNoWater=!1;update(e){if(e<=0)return;let t=this.resolveWater();if(!t){this.reportedNoWater||(this.reportedNoWater=!0,z(this.node.tree?.engine??null,`warn`,`[incanto] ${this.node.getPath()}: Buoyancy found no Water3D in the tree, so this body is not floating. It keeps looking, so a water added later is fine — otherwise add one, or name it with "water".`));return}let n=this.node;if(!n.applyImpulse){this.reportedNoImpulse||(this.reportedNoImpulse=!0,z(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: Buoyancy needs a body it can push — this node has no applyImpulse, so it will never float. Put it on a RigidBody3D.`));return}let[r,i,a]=(()=>{let e=B(n);return[e[0]??0,e[1]??0,e[2]??0]})(),o=[(this.size[0]??1)/2,(this.size[1]??1)/2],s=this.samplePoints(r,a,o[0],o[1]),c=n.mass??1,l=n.linearVelocity??[0,0,0],u=0,d=0,f=0,p=0,m=0;for(let[e,n]of s){let r=t.heightAt(e,n)-(i-this.draft);if(r<=0)continue;p++,m=Math.max(m,r),u+=_S*(1+this.stiffness*(r/Math.max(this.draft,yS)));let a=.6;d+=t.heightAt(e+a,n)-t.heightAt(e-a,n),f+=t.heightAt(e,n+a)-t.heightAt(e,n-a)}let h=p>0;if(h!==this.wet&&(this.wet=h,this.emit(h?`submerged`:`surfaced`,this.node)),!h)return;let g=p/s.length,_=Math.min(u/s.length-this.damping*(l[1]??0),vS*_S),v=l[1]??0,y=Math.sqrt(2*_S*m),b=Math.min(_*e,y-v+_S*e)*c,x=(-d*this.drift*12-(l[0]??0)*this.drag)*g*e*c,S=(-f*this.drift*12-(l[2]??0)*this.drag)*g*e*c;n.applyImpulse([x,b,S])}samplePoints(e,t,n,r){let i=Math.max(1,Math.round(this.samples));if(i===1)return[[e,t]];let a=[];for(let o=0;o<i;o++){let s=o/i*Math.PI*2+Math.PI/4;a.push([e+Math.cos(s)*n,t+Math.sin(s)*r])}return a}resolveWater(){if(this.surface)return this.surface;if(this.water!==``){let e=this.node.getNodeOrNull(this.water);if(!(e instanceof Lx))throw new L(`NODE_NOT_FOUND`,`Buoyancy on '${this.node.getPath()}': water '${this.water}' is not a Water3D in the tree.`,{prop:`water`});return this.surface=e,e}return this.surface=xS(this.node.getRoot()),this.surface}};function xS(e){if(e instanceof Lx)return e;for(let t of e.children){let e=xS(t);if(e)return e}return null}function SS(e,t,n,r){if(t===``)return r;try{return n()}catch(n){if(e.authored&&!e.reported.has(t)){e.reported.add(t);let r=n instanceof Error?n.message:String(n);z(e.engine??null,`error`,`[incanto] ${e.who}: ${r} ${e.consequence}`)}return r}}var CS=Math.PI/180,wS=12,TS=class extends Tt{static props={action:{default:`grab`},throwAction:{default:`throw`},range:{default:2.2},group:{default:`carryable`},maxMass:{default:30},holdDistance:{default:1.2},holdHeight:{default:.5},throwSpeed:{default:9},gain:{default:14},inheritMotion:{default:1,range:{min:0,max:1}},facePath:{default:`../Skin`,nodePath:!0}};static signals=[`grabbed`,`dropped`,`thrown`];action=`grab`;throwAction=`throw`;range=2.2;group=`carryable`;maxMass=30;holdDistance=1.2;holdHeight=.5;throwSpeed=9;gain=14;inheritMotion=1;facePath=`../Skin`;held=null;reported=new Set;get body(){let e=this.node;return e instanceof Ib?e:e.parent??e}forward(){let e=((this.facePath===``?this.body:this.node.getNodeOrNull(this.facePath))?.rotation?.[1]??0)*CS;return[Math.sin(e),0,Math.cos(e)]}handPoint(){let e=B(this.body),t=this.forward();return[(e[0]??0)+t[0]*this.holdDistance,(e[1]??0)+this.holdHeight,(e[2]??0)+t[2]*this.holdDistance]}update(){let e=this.node.tree?.engine?.input;if(!e)return;let t=this.node.tree?.engine,n=(n,r)=>SS({engine:t,who:this.node.getPath(),reported:this.reported,consequence:`Nothing can be picked up.`,authored:r},n,()=>e.justPressed(n),!1),r=n(this.action,this.action!==`grab`),i=this.throwAction!==``&&n(this.throwAction,this.throwAction!==`throw`);r&&(this.held?this.drop():this.grab()),this.held&&i&&this.throw()}fixedUpdate(){let e=this.held;if(!e)return;if(e.tree===null){this.held=null;return}let t=this.handPoint(),n=B(e),r=(t[0]??0)-(n[0]??0),i=(t[1]??0)-(n[1]??0),a=(t[2]??0)-(n[2]??0);if(Math.hypot(r,i,a)>Math.max(3,this.range*1.5)){let n=e,r=e.parent?B(e.parent):[0,0,0];n.position=[(t[0]??0)-(r[0]??0),(t[1]??0)-(r[1]??0),(t[2]??0)-(r[2]??0)],n.linearVelocity=[0,0,0];return}let o=r*this.gain,s=i*this.gain,c=a*this.gain,l=Math.hypot(o,s,c);l>wS&&(o*=wS/l,s*=wS/l,c*=wS/l);let u=e;u.linearVelocity=[o,s,c],u.angularVelocity=[0,0,0]}grab(){if(this.held)return this.held;let e=this.handPoint(),t=this.node.tree;if(!t)return null;let n=null,r=1/0;for(let i of t.getNodesInGroup(this.group)){if(!(i instanceof zb)||i.tree===null||i===this.body||i.mass>this.maxMass)continue;let t=B(i),a=Math.hypot((t[0]??0)-e[0],(t[1]??0)-e[1],(t[2]??0)-e[2]);a<=this.range&&a<r&&(n=i,r=a)}return n?(this.held=n,n.gravityScale=0,this.emit(`grabbed`,n),n):null}drop(){let e=this.held;e&&(this.held=null,e.tree!==null&&(e.gravityScale=1),this.emit(`dropped`,e))}throw(){let e=this.held;if(!e)return;let t=this.forward();if(this.drop(),e.tree===null)return;let n=e,r=this.body.linearVelocity??[],i=Math.min(1,Math.max(0,this.inheritMotion));n.linearVelocity=[t[0]*this.throwSpeed+(r[0]??0)*i,this.throwSpeed*.35+Math.max(0,r[1]??0)*i,t[2]*this.throwSpeed+(r[2]??0)*i],this.emit(`thrown`,e)}onReady(){this.facePath!==``&&!this.node.getNodeOrNull(this.facePath)&&z(this.node.tree?.engine??null,`warn`,`[incanto] ${this.node.getPath()}: Carry faces along '${this.facePath}', which is not in the tree — "ahead" is the body's own rotation until it is. Set facePath to the skin the controller turns, or ''.`)}},ES=180/Math.PI;function DS(e,t,n,r){let i=e,a=i.rotation,o=Array.isArray(a),[s,c]=o?[t[0]??0,t[2]??0]:[t[0]??0,t[1]??0];if(Math.hypot(s,c)<1e-6)return;let l=(o?Math.atan2(s,c):Math.atan2(c,s))*ES,u=o?a[1]??0:a??0,d=(l-u+540)%360-180,f=r*n*ES;Math.abs(d)>f&&(d=Math.sign(d)*f);let p=u+d;o?i.rotation=[a[0]??0,p,a[2]??0]:i.rotation=p}var OS={facePath:{default:``,nodePath:!0},turnSpeed:{default:100}},kS=class extends Tt{static props={target:{default:``,nodePath:!0},targetGroup:{default:``},retargetEvery:{default:.25,range:{min:0}},speed:{default:60},stopRange:{default:0},loseRange:{default:0},moveParent:{default:!1},requireSight:{default:!1},ground:{default:null,kinds:[`null`,`boolean`]},...OS};static signals=[`reachedTarget`,`lostTarget`];target=``;targetGroup=``;retargetEvery=.25;speed=60;picked=null;get chasing(){return this.current}current=null;sincePick=1/0;stopRange=0;loseRange=0;moveParent=!1;requireSight=!1;ground=null;facePath=``;fall=0;turnSpeed=100;inRange=!1;lost=!1;onReady(){if(this.target===``&&this.targetGroup===``)throw new L(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "target" (a node path) or "targetGroup" (a group name) is required.`,{prop:`target`});if(this.moveParent){let e=this.node.parent;if(!e||!Cv(e))throw new L(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else wv(this)}fallStep(e,t){if(e.isOnFloor?.()??!0)return this.fall=0,0;let n=this.node.tree?.engine?.scene?.physics?.gravity?.[1]??(e.position.length===2?980:-9.81);return this.fall+=n*t,this.fall*t}dropIfAirborne(e,t){let n=this.fallStep(e,t);if(n!==0){let r=[...e.position];r[1]=(r[1]??0)+n,ey(e,r,t)}}nearestOfGroup(e,t){if(this.sincePick+=t,this.picked&&this.picked.tree!==null&&this.sincePick<this.retargetEvery)return this.picked;this.sincePick=0;let n=B(e),r=null,i=1/0;for(let t of this.node.tree?.getNodesInGroup(this.targetGroup)??[]){if(t===e||t===this.node||!Cv(t))continue;let a=Tv(n,B(t));a<i&&(!this.requireSight||this.canSee(e,t))&&(r=t,i=a)}return this.picked=r,r}canSee(e,t){let n=this.physics;if(!n)return!0;let r=B(e),i=B(t),a=r.length>=3,o=a?[r[0]??0,(r[1]??0)+.5,r[2]??0]:[r[0]??0,r[1]??0],s=(a?[i[0]??0,(i[1]??0)+.5,i[2]??0]:[i[0]??0,i[1]??0]).map((e,t)=>e-(o[t]??0)),c=Math.hypot(...s);return c<.001?!0:n.castRay(o,s,c,e,{staticOnly:!0})==null}walksTheGround(e){if(this.ground!==null)return this.ground;let t=e;return e.position.length===3&&typeof t.slopeLimitDeg==`number`}update(e){let t=this.moveParent?this.node.parent:this.node;if(!t||!Cv(t))return;let n=this.targetGroup===``?this.node.getNodeOrNull(this.target):this.nearestOfGroup(t,e);if(n&&Cv(n)&&this.requireSight&&!this.canSee(t,n)&&(n=null),this.current=n&&Cv(n)?n:null,!n||!Cv(n))return;let r=Ba(t,B(n)),i=this.walksTheGround(t);i&&(r[1]=t.position[1]??0);let a=Tv(t.position,r);if(this.loseRange>0&&a>this.loseRange){this.lost||(this.lost=!0,this.inRange=!1,this.emit(`lostTarget`)),i&&this.dropIfAirborne(t,e);return}if(this.lost=!1,this.stopRange>0&&a<=this.stopRange){this.inRange||(this.inRange=!0,this.emit(`reachedTarget`)),i&&this.dropIfAirborne(t,e);return}this.inRange=!1;let o=Math.min(this.speed*e,this.stopRange>0?a-this.stopRange:a),s=[...t.position],{position:c}=kv(t.position,r,Math.max(0,o));if(i&&(c[1]=(c[1]??0)+this.fallStep(t,e)),ey(t,c,e),this.facePath!==``){let t=this.node.getNodeOrNull(this.facePath);t&&DS(t,c.map((e,t)=>e-(s[t]??0)),e,this.turnSpeed)}}},AS=Math.PI/180,jS=class extends Tt{static props={target:{default:``,nodePath:!0,required:!0},back:{default:8},up:{default:3},smoothing:{default:.85,range:{min:0,max:1}}};static signals=[];target=``;back=8;up=3;smoothing=.85;heading=null;onReady(){wv(this)}update(e){let t=this.node,n=t.getNodeOrNull(this.target);if(!Cv(t)||!n||!Cv(n))return;let r=MS(n);this.heading===null&&(this.heading=r);let i=r-this.heading;for(;i>Math.PI;)i-=Math.PI*2;for(;i<-Math.PI;)i+=Math.PI*2;let a=this.smoothing**(e*60);this.heading+=i*(1-a);let o=B(n),s=this.heading,c=o.length>=3?[(o[0]??0)-Math.sin(s)*this.back,(o[1]??0)+this.up,(o[2]??0)-Math.cos(s)*this.back]:[(o[0]??0)-Math.cos(s)*this.back,(o[1]??0)-Math.sin(s)*this.back],l=B(t),u=this.placed?c.map((e,t)=>(l[t]??e)+(e-(l[t]??e))*(1-a)):c;this.placed=!0,t.position=Ba(t,u)}placed=!1;snap(){this.placed=!1,this.heading=null}};function MS(e){let t=e.rotation;if(Array.isArray(t)){let e=(t[0]??0)*AS,n=(t[1]??0)*AS;return Math.atan2(Math.sin(n),Math.cos(e)*Math.cos(n))}return(t??0)*AS}var NS=class e extends Tt{static props={respawn:{default:``,nodePath:!0,required:!0},group:{default:`player`},once:{default:!0},dropBelow:{default:0}};static signals=[`activated`];respawn=``;group=`player`;once=!0;dropBelow=0;lit=!1;sentTo=[];litAt=0;onReady(){this.node.on(`triggerEnter`,e=>{let t=e;if(this.group!==``&&!t.isInGroup(this.group)||this.once&&this.lit)return;let n=this.node.getNodeOrNull(this.respawn);if(!n||!Array.isArray(n.to))return;let r=[...B(this.node)];r.length>=2&&(r[1]=(r[1]??0)-this.dropBelow),n.to=r,this.lit=!0,this.sentTo=[...r],this.litAt=this.node.tree?.engine?.unscaledTime??this.litAt+1,this.emit(`activated`,t)})}serialize(){return{lit:this.lit,sentTo:[...this.sentTo],litAt:this.litAt}}deserialize(e){let t=e;typeof t.lit==`boolean`&&(this.lit=t.lit),Array.isArray(t.sentTo)&&t.sentTo.every(e=>typeof e==`number`)&&(this.sentTo=[...t.sentTo]),typeof t.litAt==`number`&&Number.isFinite(t.litAt)&&(this.litAt=t.litAt)}announce(){if(!this.lit||this.sentTo.length===0)return;let e=this.node.getNodeOrNull(this.respawn);!e||!Array.isArray(e.to)||this.laterSiblingLit(e)||(e.to=[...this.sentTo])}laterSiblingLit(t){let n=this.node.getRoot(),r=!1,i=n=>{if(r)return;let a=n.behavior;a instanceof e&&a!==this&&a.lit&&a.sentTo.length>0&&n.getNodeOrNull(a.respawn)===t&&a.litAt>this.litAt&&(r=!0);for(let e of n.children)i(e)};return i(n),r}},PS=120,FS=class extends Tt{static props={button:{default:0},maxDistance:{default:0,range:{min:0}}};static signals=[`clicked`,`hovered`,`unhovered`];button=0;maxDistance=0;hovering=!1;pressedHere=!1;silentFrames=0;update(){let e=this.node.tree?.engine;if(!e)return;let t=e.picker,n=e.input.pointerPosition();if(!t||!n){t&&(this.silentFrames+=1,this.silentFrames===PS&&z(e,`error`,`[incanto] Clickable on '${this.node.getPath()}' has had no pointer for ${PS} frames, so it can never fire. Nothing is feeding the cursor: pass \`pointer: true\` to createGame2D/3D, or call \`engine.input.attachPointer(canvas)\` on a manual boot.`)),this.hovering&&this.setHover(!1);return}this.silentFrames=0;let r=e.pickAt(n.x,n.y),i=r!==null&&this.isSelfOrDescendant(r)&&this.withinRange();i!==this.hovering&&this.setHover(i),e.input.mouseJustPressed(this.button)&&(this.pressedHere=i),e.input.mouseJustReleased(this.button)&&(this.pressedHere&&i&&this.emit(`clicked`,this.node),this.pressedHere=!1)}setHover(e){this.hovering=e,this.emit(e?`hovered`:`unhovered`,this.node)}isSelfOrDescendant(e){for(let t=e;t;t=t.parent)if(t===this.node)return!0;return!1}withinRange(){if(this.maxDistance<=0)return!0;let e=this.currentCamera();if(!e)return this.warnedNoCamera||(this.warnedNoCamera=!0,z(this.node.tree?.engine??null,`error`,`[incanto] Clickable on '${this.node.getPath()}' has maxDistance ${this.maxDistance}, which is a range FROM THE CAMERA — and this scene has no camera to measure from, so every click is accepted. Add one, or drop the prop.`)),!0;let t=B(e),n=B(this.node);if(t.length===0||n.length===0)return!0;let r=0;for(let e=0;e<Math.max(t.length,n.length);e++){let i=(t[e]??0)-(n[e]??0);r+=i*i}return Math.sqrt(r)<=this.maxDistance}warnedNoCamera=!1;camera=null;currentCamera(){if(this.camera?.tree&&this.camera.current===!0)return this.camera;let e=this.node.tree?.root;if(!e)return null;let t=null,n=e=>{let r=e.constructor.typeName??``;if(r===`Camera2D`||r===`Camera3D`){if(e.current===!0)return e;t??=e}for(let t of e.children){let e=n(t);if(e)return e}return null};return this.camera=n(e)??t,this.camera}},IS=class extends Tt{static props={group:{default:`player`}};static signals=[`totalChanged`];group=`player`;total=0;onReady(){this.node.addToGroup(this.group)}collect(e){this.total+=e,this.emit(`totalChanged`,this.total)}serialize(){return{total:this.total}}deserialize(e){let t=e;typeof t.total==`number`&&(this.total=t.total)}announce(){this.emit(`totalChanged`,this.total)}},LS=class extends Tt{static props={amount:{default:0},max:{default:0}};static signals=[`changed`,`earned`,`spent`,`refused`];amount=0;max=0;canAfford(e){return e<=0?!0:e<=this.amount}spend(e){return an(e,this.node,`Currency.spend`)<=0?(this.refuseNonsense(`spend`,e),!0):this.canAfford(e)?(this.amount-=e,this.emit(`spent`,e),this.emit(`changed`,this.amount),!0):(this.emit(`refused`,e),!1)}earn(e){if(an(e,this.node,`Currency.earn`)<=0){this.refuseNonsense(`earn`,e);return}let t=this.max>0?Math.max(0,this.max-this.amount):e,n=Math.min(e,t);n>0&&(this.amount+=n,this.emit(`earned`,n),this.emit(`changed`,this.amount)),n<e&&this.emit(`refused`,e-n)}get room(){return this.max>0?Math.max(0,this.max-this.amount):1/0}complained=new Set;refuseNonsense(e,t){t===0||this.complained.has(e)||(this.complained.add(e),z(this.node.tree?.engine??null,`error`,`[incanto] Currency.${e}(${t}) on '${this.node.getPath()}' — a negative amount is a sign flip in the caller, never an offer. Ignored: ${e===`spend`?`spending a negative used to PAY you`:`earning a negative used to TAKE from you`}.`))}setAmount(e){let t=an(e,this.node,`Currency.setAmount`);this.amount=this.max>0?Math.min(this.max,t):t,this.emit(`changed`,this.amount)}serialize(){return{amount:this.amount}}deserialize(e){let t=e;typeof t.amount==`number`&&(this.amount=t.amount)}announce(){this.emit(`changed`,this.amount)}};function RS(e,t){let n=e.node;if(!n.declaredSignalNames().includes(`triggerEnter`)){let t=e.constructor.name;throw new L(`UNKNOWN_SIGNAL`,`${t} on '${n.getPath()}' needs a node that emits 'triggerEnter' — attach it to an Area2D/Area3D (or another body that declares the collision signals). '${n.name}' declares: [${n.declaredSignalNames().join(`, `)}].`,{signal:`triggerEnter`,path:n.getPath()})}n.on(`triggerEnter`,e=>t(e))}var zS=class extends Tt{static props={amount:{default:10},targetGroup:{default:``},oncePerTarget:{default:!0},repeatEvery:{default:0},destroySelf:{default:!1},...$v};static signals=[`dealtDamage`];amount=10;targetGroup=``;oncePerTarget=!0;repeatEvery=0;destroySelf=!1;freeParent=!1;hit=new WeakSet;inside=new Map;onReady(){RS(this,e=>{this.inside.set(e,this.repeatEvery),this.tryDamage(e)}),this.node.on(`triggerExit`,e=>{this.inside.delete(e),this.hit.delete(e)})}update(e){if(!(this.repeatEvery<=0||this.inside.size===0))for(let[t,n]of this.inside){if(!t.tree){this.inside.delete(t);continue}let r=n-e;r>0?this.inside.set(t,r):(this.inside.set(t,this.repeatEvery),this.tryDamage(t,{repeat:!0}))}}tryDamage(e,t){if(!t?.repeat&&this.oncePerTarget&&this.hit.has(e))return;let n=ny(e);n&&(this.targetGroup!==``&&!n.owner.isInGroup(this.targetGroup)&&!e.isInGroup(this.targetGroup)||(this.oncePerTarget&&this.hit.add(e),n.health.damage(this.amount,B(this.node)),this.emit(`dealtDamage`,this.amount,n.owner),this.destroySelf&&Qv(this,this.freeParent,`DamageOnContact`)))}},BS=class extends Tt{static signals=[`dayPhaseChanged`];static props={daySeconds:{default:240},startHour:{default:10},maxSunElevationDeg:{default:55},nightDarkness:{default:.75},paused:{default:!1}};daySeconds=240;startHour=10;maxSunElevationDeg=55;nightDarkness=.75;paused=!1;hour=0;phase=``;applyClock=0;baseAmbient=.3;baseExposure=1;captured=!1;reportedNoSky=!1;serialize(){return{hour:this.hour,paused:this.paused}}deserialize(e){let t=e??{};typeof t.hour==`number`&&Number.isFinite(t.hour)&&(this.hour=(t.hour%24+24)%24),typeof t.paused==`boolean`&&(this.paused=t.paused)}onReady(){this.hour=this.startHour}update(e){this.paused||(this.hour=(this.hour+e/this.daySeconds*24)%24);let t=VS(this.hour);t!==this.phase&&(this.phase=t,this.emit(`dayPhaseChanged`,t)),this.applyClock-=e,!(this.applyClock>0)&&(this.applyClock=.2,this.applyHour())}applyHour(){let e=this.node.tree?.engine,t=e?.scene?.environment;if(!e||!t?.sky){e&&!this.reportedNoSky&&(this.reportedNoSky=!0,z(e,`warn`,`[incanto] ${this.node.getPath()}: DayNight drives environment.sky, and this scene has no \`sky\` — the clock runs and nothing on screen changes. It keeps looking, so a sky added later is fine; otherwise add \`"sky": { "type": "atmosphere" }\` to the scene environment.`));return}this.captured||(this.captured=!0,this.baseAmbient=t.ambient?.intensity??.3,this.baseExposure=t.exposure??1);let n=(this.hour-6)/12*Math.PI,r=Math.sin(n);t.sky.elevationDeg=r*this.maxSunElevationDeg+(r<0?r*10:0),t.sky.azimuthDeg=this.hour/24*360+90;let i=Math.max(0,r),a=this.nightDarkness;t.ambient={...t.ambient??{},intensity:this.baseAmbient*(1-a+a*i)},t.exposure=this.baseExposure*(1-a*.55*(1-i))}};function VS(e){return e<5||e>=20?`night`:e<7.5?`dawn`:e<17.5?`day`:`dusk`}var HS=class extends Tt{static props={targetGroup:{default:``,required:!0},range:{default:0},facePath:{default:``,nodePath:!0},turnSpeed:{default:6},aimTolerance:{default:6}};static signals=[`acquired`,`lostTarget`,`aimed`,`lostAim`];targetGroup=``;range=0;facePath=``;turnSpeed=6;aimTolerance=6;target=null;onTarget=!1;onReady(){if(this.targetGroup===``)throw new L(`PROP_TYPE_MISMATCH`,`FaceTarget on '${this.node.getPath()}': "targetGroup" is required — it is the group this turret acquires from.`,{prop:`targetGroup`})}update(e){let t=this.node;if(!Cv(t))return;let n=this.nearest();if(n!==this.target&&(this.target=n,this.emit(n?`acquired`:`lostTarget`,n),n||this.setAim(!1)),!n)return;let r=this.facePath===``?t:this.node.getNodeOrNull(this.facePath);if(!r)return;let i=n.position.map((e,n)=>e-(t.position[n]??0));DS(r,i,e,this.turnSpeed),this.setAim(this.pointedAt(r,i))}nearest(){let e=this.node,t=null,n=1/0;for(let r of this.node.tree?.getNodesInGroup(this.targetGroup)??[]){if(!Cv(r))continue;let i=Math.hypot(...r.position.map((t,n)=>t-(e.position[n]??0)));this.range>0&&i>this.range||i<n&&(n=i,t=r)}return t}pointedAt(e,t){let n=e.rotation,r=Array.isArray(n),[i,a]=r?[t[0]??0,t[2]??0]:[t[0]??0,t[1]??0],o=Math.hypot(i,a);if(o<1e-6)return!0;let s=(r?n[1]??0:n??0)*Math.PI/180,c=r?Math.sin(s):Math.cos(s),l=r?Math.cos(s):Math.sin(s);return(c*i+l*a)/o>=Math.cos(this.aimTolerance*Math.PI/180)}setAim(e){e!==this.onTarget&&(this.onTarget=e,this.emit(e?`aimed`:`lostAim`,this.target))}},US=class extends Tt{static props={rise:{default:1},seconds:{default:.7},hold:{default:.3},drift:{default:0},freeOnEnd:{default:!0}};rise=1;seconds=.7;hold=.3;drift=0;freeOnEnd=!0;elapsed=0;start=[];done=!1;onReady(){let e=this.node;this.start=[...e.position??[]],e.opacity===void 0&&z(this.node.tree?.engine,`warn`,`[incanto] FloatAway on '${this.node.getPath()}' will not fade — ${this.node.constructor.name} has no "opacity" prop, so it pops out at full brightness instead. Use a node that has one (Label, Label3D, Sprite2D, Sprite3D).`)}update(e){if(this.done)return;let t=this.node;if(!t.position)return;this.elapsed+=e;let n=Math.max(.001,this.seconds),r=Math.min(1,this.elapsed/n),i=[...this.start],a=1-(1-r)*(1-r),o=this.start.length===2?-1:1;if(i[1]=(this.start[1]??0)+o*this.rise*a,this.drift!==0&&(i[0]=(this.start[0]??0)+this.drift*a),t.position=i,t.opacity!==void 0){let e=Math.min(.99,Math.max(0,this.hold));t.opacity=r<=e?1:1-(r-e)/(1-e)}r>=1&&(this.done=!0,this.freeOnEnd&&this.node.queueFree())}};function WS(e,t=0){let n=e.tree?.engine,r=e.getPath(),i=(n?.seed??4660)>>>0;for(let e=0;e<r.length;e++)i^=r.charCodeAt(e),i=Math.imul(i,16777619)>>>0;return new Ee((i^Math.imul(t+1,2654435769))>>>0)}var GS=class extends Tt{static props={target:{default:``,nodePath:!0,required:!0},offset:{default:[]},smoothing:{default:0,range:{min:0,max:1}},deadzone:{default:0,range:{min:0}}};static signals=[];target=``;offset=[];smoothing=0;deadzone=0;shakeRng=null;onReady(){if(this.target===``)throw new L(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.deadzone<0)throw new L(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "deadzone" must be >= 0, got ${this.deadzone}.`,{prop:`deadzone`});wv(this)}shakeMag=0;shakeT=0;shakeFalloff=.28;shake(e,t=.28){this.shakeMag=Math.max(this.shakeMag,e),this.shakeT=t,this.shakeFalloff=t}update(e){let t=this.node;if(!Cv(t))return;let n=t.getNodeOrNull(this.target);if(!n||!Cv(n))return;let r=B(t),i=Ev(B(n),this.offset);if(!(this.deadzone>0&&Tv(r,i)<=this.deadzone)){let n=Av(this.smoothing,e);n>=1?t.position=Ba(t,i):t.position=Ba(t,r.map((e,t)=>e+((i[t]??e)-e)*n))}if(this.shakeT>0){this.shakeT-=this.engine?.unscaledDelta||e;let n=this.shakeMag*Math.max(0,this.shakeT)/this.shakeFalloff;this.shakeT<=0&&(this.shakeMag=0);let r=t.position.slice();this.shakeRng??=WS(this.node);for(let e=0;e<r.length;e++){let t=r.length>=3&&e===1?.5:1;r[e]=(r[e]??0)+(this.shakeRng.next()*2-1)*n*t}t.position=r}}};function KS(e,t){return si(ot(t),{engine:e,...e.resolveScene?{resolveScene:e.resolveScene}:{}})}function qS(e){let t=e.scene?.source;t&&(e.setScene(KS(e,t)),e.ensurePhysics())}var JS=new WeakSet;function YS(e,t,n){if(JS.has(e))return;let r=n?.fadeSeconds??.4,i=()=>{e.setScene(KS(e,t)),e.ensurePhysics()};if(typeof document>`u`||r<=0){i();return}JS.add(e);let a=e.timeScale;e.timeScale=0;let o=()=>{JS.delete(e),a!==0&&(e.timeScale=a)},s=`incanto-scene-fade`,c=document.getElementById(s);c||(c=document.createElement(`div`),c.id=s,c.style.cssText=`position:fixed;inset:0;z-index:10001;background:#000;opacity:0;pointer-events:none;`,document.body.appendChild(c)),c.style.transition=`opacity ${r/2}s`,c.style.opacity=`1`,setTimeout(()=>{try{i()}catch(t){z(e,`error`,`[incanto] goToScene: the destination scene did not load — staying in '${e.scene?.name??`?`}'.`,t)}finally{o();let e=document.getElementById(s);e&&(e.style.opacity=`0`,setTimeout(()=>e.remove(),r*500+60))}},r*500+30)}var XS=class e extends Tt{static signals=[`flowChanged`];static props={restartAction:{default:`restart`},pauseAction:{default:`pause`},freezeOnEnd:{default:!0},bannerPath:{default:`%Banner`,nodePath:!0},pausePanelPath:{default:`%PauseMenu`,nodePath:!0},titlePanelPath:{default:``,nodePath:!0},saveSlots:{default:``}};restartAction=`restart`;freezeOnEnd=!0;bannerPath=`%Banner`;pauseAction=`pause`;reportedActions=new Set;readAction(t,n){let r=this[t],i=e.props[t];return SS({engine:this.engine,who:this.node.getPath(),reported:this.reportedActions,consequence:n,authored:r!==(typeof i?.default==`string`?i.default:``)},r,()=>this.engine.input.justPressed(r),!1)}pausePanelPath=`%PauseMenu`;titlePanelPath=``;saveSlots=``;slots=null;store(){return this.saveSlots===``?null:(this.slots??=new ua(this.saveSlots),this.slots)}save(e=`1`){let t=typeof e==`string`&&e!==``?e:`1`,n=this.store(),r=this.node.tree?.engine??null;return!n||!r?(z(r,`error`,`[incanto] ${this.node.getPath()}: save('${t}') did nothing — this GameFlow has no \`saveSlots\`, so there is nowhere to keep it. Name a namespace and the slot is written; leave it empty and this game does not save.`),!1):(n.write(t,{scene:r.scene?.name??``,state:r.captureState(),savedAt:Date.now()}),this.node.emit(`flowChanged`,this.state),!0)}hasSave(e=`1`){let t=typeof e==`string`&&e!==``?e:`1`;return(this.store()?.read(t)??null)!==null}continueFrom(e=`1`){let t=typeof e==`string`&&e!==``?e:`1`,n=this.store(),r=this.node.tree?.engine??null;if(!n||!r)return!1;let i=n.read(t);if(!i)return!1;let a=r.scene?.name??``;if(i.scene!==``&&i.scene!==a)return z(r,`error`,`[incanto] ${this.node.getPath()}: continueFrom('${t}') holds scene '${i.scene}' and this is '${a}' — load that scene first, then restore. Routing between scenes is the game's: the engine has no map of your levels.`),!1;this.thaw(),qS(r);let o=r.restoreState(i.state);return o.missing.length>0&&z(r,`warn`,`[incanto] ${this.node.getPath()}: continueFrom('${t}') — ${o.missing.length} uid(s) in the save are not in this build; everything else was restored.`),!0}screens=[];everShown=new Set;onTitle=!1;screen(e){if(!(typeof e!=`string`||e===``)){if(this.node.getNodeOrNull(e)===null){z(this.engine,`error`,`[incanto] ${this.node.getPath()}: screen('${e}') found no such node — nothing opened.`);return}this.screens.push(e),this.everShown.add(e),this.freeze(),this.syncPausePanel()}}back(){if(this.screens.length===0){if(this.state===`paused`&&!this.onTitle)return;this.resume();return}this.screens.pop(),this.screens.length===0&&this.state!==`paused`&&this.thaw(),this.syncPausePanel()}state=`playing`;frozeScale=!1;unwatchScene=null;onExitTree(){this.unwatchScene?.(),this.unwatchScene=null}onReady(){this.titlePanelPath!==``&&this.state===`playing`&&(this.onTitle=!0,this.pause()),this.syncPausePanel();let e=this.node.tree?.engine??null;e&&(this.unwatchScene?.(),this.unwatchScene=e.sceneChanged.connect(e=>{!e||e.root!==this.node.getRoot()||this.state!==`playing`&&(this.frozeScale=!1,this.freeze())}))}syncPausePanel(){let e=this.state===`paused`?this.onTitle?this.titlePanelPath:this.pausePanelPath:``,t=this.screens[this.screens.length-1]??e,n=new Set([this.titlePanelPath,this.pausePanelPath,...this.everShown]);n.delete(``);let r=null;for(let e of n){let n=this.node.getNodeOrNull(e);if(!n||!(`visible`in n))continue;let i=e===t;n.visible=i,i&&(r=n)}let i=r??this.node.getNodeOrNull(this.pausePanelPath),a=i?ZS(i):null;a&&(r?(this.navigationWas===null&&(this.navigationWas=a.focusNavigation),a.focusNavigation=!0,a.focus(QS(a))):this.navigationWas!==null&&(a.focusNavigation&&=this.navigationWas,this.navigationWas=null))}navigationWas=null;gameOver(e=`GAME OVER`,t=`#ef4444`){this.transition(`gameover`,e,t)}win(e=`YOU WIN`,t=`#4ade80`){this.transition(`won`,e,t)}pause(){this.state===`playing`&&(this.state=`paused`,this.freeze(),this.syncPausePanel(),this.node.emit(`flowChanged`,this.state))}resume(){this.state===`paused`&&(this.state=`playing`,this.screens.length=0,this.onTitle=!1,this.thaw(),this.syncPausePanel(),this.node.emit(`flowChanged`,this.state))}restart(){this.thaw(),qS(this.engine)}goToScene(e,t=void 0){this.thaw(),YS(this.engine,e,t)}transition(e,t,n){this.state===`gameover`||this.state===`won`||(this.state=e,this.freezeOnEnd&&this.freeze(),this.bannerPath!==``&&this.node.getNodeOrNull(this.bannerPath)?.show(t,{color:n,seconds:0}),this.node.emit(`flowChanged`,e))}freeze(){if(this.frozeScale)return;this.frozeScale=!0;let e=this.node.tree?.engine??null;e&&(e.timeScale=0)}thaw(){if(!this.frozeScale)return;this.frozeScale=!1;let e=this.node.tree?.engine??null;e&&(e.timeScale=1)}update(){let e=this.readAction(`pauseAction`,`The pause key will do nothing.`),t=this.readAction(`restartAction`,`The restart key will do nothing.`);if(this.state===`playing`||this.state===`paused`){e&&(this.state===`playing`?this.pause():this.resume());return}this.state!==`gameover`&&this.state!==`won`||t&&this.restart()}};function ZS(e){for(let t=e;t;t=t.parent)if(t instanceof mn)return t;return null}function QS(e){return e.focusables()[0]??null}var $S=class extends Tt{static props={targets:{default:`player`},offset:{default:[0,12,14]},minZoom:{default:1,range:{min:.1}},maxZoom:{default:2.5,range:{min:.1}},padding:{default:.25,range:{min:0,max:.9}},smoothing:{default:.15,range:{min:0,max:1}},lookAtGroup:{default:!0}};static signals=[];targets=`player`;offset=[0,12,14];minZoom=1;maxZoom=2.5;padding=.25;smoothing=.15;lookAtGroup=!0;zoom=1;centre=[0,0,0];onReady(){if(this.minZoom>this.maxZoom)throw new L(`PROP_TYPE_MISMATCH`,`GroupCamera on '${this.node.getPath()}': "minZoom" (${this.minZoom}) is greater than "maxZoom" (${this.maxZoom}) — there is no zoom that satisfies both.`,{prop:`minZoom`,path:this.node.getPath()})}members(){let e=this.node.tree;return e?[...e.getNodesInGroup(this.targets)].filter(e=>Cv(e)):[]}update(e){let t=this.members();if(t.length===0)return;let n=t.map(e=>B(e)),r=[0,0,0];for(let e of n)r[0]+=e[0]??0,r[1]+=e[1]??0,r[2]+=e[2]??0;r[0]/=n.length,r[1]/=n.length,r[2]/=n.length;let i=0;for(let e=0;e<n.length;e++)for(let t=e+1;t<n.length;t++){let r=n[e],a=n[t];i=Math.max(i,Math.hypot((r[0]??0)-(a[0]??0),(r[2]??0)-(a[2]??0)))}let a=Math.hypot(this.offset[0]??0,this.offset[1]??0,this.offset[2]??0)||1,o=(this.node.fov??60)*(Math.PI/180),s=Math.tan(o/2)*(1-this.padding),c=s>.001?i/2/s/a:this.minZoom,l=Math.min(this.maxZoom,Math.max(this.minZoom,c)),u=this.smoothing>0?1-Math.exp(-e/this.smoothing):1;this.zoom+=(l-this.zoom)*u,this.centre[0]=this.centre[0]+(r[0]-this.centre[0])*u,this.centre[1]=this.centre[1]+(r[1]-this.centre[1])*u,this.centre[2]=this.centre[2]+(r[2]-this.centre[2])*u;let d=this.node;if(d.position=[this.centre[0]+(this.offset[0]??0)*this.zoom,this.centre[1]+(this.offset[1]??0)*this.zoom,this.centre[2]+(this.offset[2]??0)*this.zoom],!this.lookAtGroup)return;let f=this.centre[0]-(d.position[0]??0),p=this.centre[1]-(d.position[1]??0),m=this.centre[2]-(d.position[2]??0),h=Math.atan2(-f,-m)*180/Math.PI;d.rotation=[Math.atan2(p,Math.hypot(f,m))*180/Math.PI,h,0]}snap(){this.centre=[0,0,0],this.zoom=this.minZoom;let e=this.members();if(e.length===0)return;let t=e.map(e=>B(e));for(let e of t)this.centre[0]=this.centre[0]+(e[0]??0)/t.length,this.centre[1]=this.centre[1]+(e[1]??0)/t.length,this.centre[2]=this.centre[2]+(e[2]??0)/t.length}};function eC(e){return Array.isArray(e.position)}function tC(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}var nC=class extends Tt{static props={action:{default:`interact`},range:{default:2},actorGroup:{default:`player`},prompt:{default:``},focus:{default:`any`,options:[`any`,`nearest`,`facing`]},coneDeg:{default:40,range:{min:1,max:360}}};static signals=[`interacted`,`focused`,`unfocused`];action=`interact`;range=2;actorGroup=`player`;prompt=``;focus=`any`;coneDeg=40;focusedBy=null;reportedActions=new Set;onReady(){wv(this)}update(){let e=this.node.tree?.engine;if(!e?.scene)return;let t=SS({engine:e,who:this.node.getPath(),reported:this.reportedActions,consequence:`nothing here can be interacted with`,authored:this.action!==`interact`},this.action,()=>e.input.justPressed(this.action),!1);if(!eC(this.node))return;let n=B(this.node),r=null,i=1/0,a=this.node.tree?.getNodesInGroup(this.actorGroup)??aC(this.node.getRoot(),this.actorGroup);for(let e of a){if(!eC(e))continue;let t=tC(n,B(e));t<=this.range&&t<i&&(r=e,i=t)}let o=r;if(o&&this.focus!==`any`&&!this.claims(o,n)&&(o=null),o!==this.focusedBy){let e=this.focusedBy;this.focusedBy=o,e&&this.emit(`unfocused`,e),o&&this.emit(`focused`,o)}!t||!o||this.emit(`interacted`,o)}claims(e,t){let n=this.focus===`facing`?iC(this.node.getRoot()):null,r=n?n.at:B(e),i=e=>{if(!n)return 1;let t=(e[0]??0)-(r[0]??0),i=(e[1]??0)-(r[1]??0),a=(e[2]??0)-(r[2]??0),o=Math.hypot(t,i,a);return o<1e-6?1:t/o*n.fx+i/o*n.fy+a/o*n.fz},a=Math.cos(this.coneDeg/2*(Math.PI/180)),o=i(t);if(o<a)return!1;let s=n?-o:tC(r,t);for(let t of rC(this.node.getRoot())){if(t===this||t.focus===`any`||t.actorGroup!==this.actorGroup||!eC(t.node))continue;let o=B(t.node);if(tC(B(e),o)>t.range)continue;let c=i(o);if(!(n&&c<a)&&(n?-c:tC(r,o))<s)return!1}return!0}};function rC(e){let t=[],n=e=>{e.behavior instanceof nC&&t.push(e.behavior);for(let t of e.children)n(t)};return n(e),t}function iC(e){let t=null,n=null,r=e=>{e.constructor.typeName===`Camera3D`&&(t??=e,e.current&&(n??=e));for(let t of e.children)r(t)};r(e);let i=n??t;if(!i)return null;let a=i.rotation??[0,0,0],o=(a[0]??0)*Math.PI/180,s=(a[1]??0)*Math.PI/180,c=-Math.sin(s),l=Math.sin(o)*Math.cos(s),u=-Math.cos(o)*Math.cos(s);return{at:B(i),fx:c,fy:l,fz:u}}function aC(e,t){let n=[],r=e=>{e.isInGroup(t)&&n.push(e);for(let t of e.children)r(t)};return r(e),n}var oC=.28;function sC(e,t,n,r,i,a){e?.effects.record({kind:t,name:n,from:r,amount:i,at:e.time,wiredAs:a})}var cC=class extends Tt{static props={falloff:{default:oC}};falloff=oC;magnitude=0;t=0;prev=[];shakeRng=null;shake(e,t=this.falloff){this.engine?.settings.get(`reduceMotion`)!==!0&&(this.magnitude=Math.max(this.magnitude,e),this.t=t,sC(this.engine,`shake`,``,this.node?.getPath()??`engine`,e,this.node?.wiringPath()))}update(e){let t=wv(this),n=t.position;for(let e=0;e<this.prev.length;e++)n[e]=(n[e]??0)-(this.prev[e]??0);if(this.t<=0){this.prev.length>0&&(t.position=n.slice(),this.prev.length=0);return}this.t-=this.engine?.unscaledDelta||e;let r=this.magnitude*Math.max(0,this.t)/this.falloff;this.t<=0&&(this.magnitude=0);let i=n.slice();this.prev.length!==i.length&&(this.prev=Array(i.length).fill(0));for(let e=0;e<i.length;e++){let t=i.length>=3&&e===1?.5:1;this.shakeRng??=WS(this.node),this.prev[e]=(this.shakeRng.next()*2-1)*r*t,i[e]=(i[e]??0)+this.prev[e]}t.position=i}},lC=class extends Tt{static props={seconds:{default:1},startOnSignal:{default:!1},...$v};static signals=[`expired`];seconds=1;startOnSignal=!1;freeParent=!1;elapsed=0;running=!1;fired=!1;onReady(){if(!(this.seconds>0))throw new L(`PROP_TYPE_MISMATCH`,`Lifetime on '${this.node.getPath()}': "seconds" must be > 0, got ${this.seconds}.`,{prop:`seconds`});this.running=!this.startOnSignal}startTimer(){this.elapsed=0,this.fired=!1,this.running=!0}update(e){!this.running||this.fired||(this.elapsed+=e,this.elapsed>=this.seconds&&(this.fired=!0,this.running=!1,this.emit(`expired`),Qv(this,this.freeParent,`Lifetime`)))}},uC=Math.PI/180,dC=class extends Tt{static props={rider:{default:``,nodePath:!0,required:!0},steed:{default:`..`,nodePath:!0},drive:{default:``,nodePath:!0},walk:{default:``,nodePath:!0},skin:{default:`Skin`},saddle:{default:``,nodePath:!0},skinOnSaddle:{default:[0,0,0]},skinOnRider:{default:[0,0,0]},dismountAt:{default:[1.8,.3,0]}};static signals=[`mounted`,`dismounted`];rider=``;steed=`..`;drive=``;walk=``;skin=`Skin`;saddle=``;skinOnSaddle=[0,0,0];skinOnRider=[0,0,0];dismountAt=[1.8,.3,0];mounted=!1;mounts=0;parked=null;onReady(){this.riderNode(),this.steedNode()}riderNode(){let e=this.node.getNodeOrNull(this.rider);if(!e||!Cv(e))throw new L(`NODE_NOT_FOUND`,`Mount on '${this.node.getPath()}': "rider" '${this.rider}' is not a spatial node.`,{prop:`rider`,path:this.node.getPath()});return e}steedNode(){let e=this.node.getNodeOrNull(this.steed);if(!e||!Cv(e))throw new L(`NODE_NOT_FOUND`,`Mount on '${this.node.getPath()}': "steed" '${this.steed}' is not a spatial node.`,{prop:`steed`,path:this.node.getPath()});return e}switchOf(e,t,n){if(t!==``){let e=this.node.getNodeOrNull(t);if(!e)throw new L(`NODE_NOT_FOUND`,`Mount on '${this.node.getPath()}': "${n}" '${t}' resolves to no node.`,{prop:n,path:this.node.getPath()});return e}for(let t of e.children){let e=t;if(typeof e.enabled==`boolean`&&(typeof e.yaw==`number`||typeof e.throttle==`number`))return t}return null}skinNode(e){return this.skin===``?null:e.getNodeOrNull(this.skin)??null}saddleNode(){return this.saddle===``?this.steedNode():this.node.getNode(this.saddle)}mount(){if(this.mounted)return!1;let e=this.riderNode(),t=this.steedNode(),n=this.switchOf(e,this.walk,`walk`),r=this.switchOf(t,this.drive,`drive`);n&&(n.enabled=!1),this.parked={gravityScale:e.gravityScale??1,visible:e.visible??!0,enabled:e.enabled??!0},`enabled`in e&&(e.enabled=!1),`visible`in e&&(e.visible=!1),`gravityScale`in e&&(e.gravityScale=0),e.linearVelocity&&=e.linearVelocity.map(()=>0);let i=this.skinNode(e);return i&&(i.reparent(this.saddleNode()),i.position=[...this.skinOnSaddle],Array.isArray(i.rotation)?i.rotation=[0,0,0]:typeof i.rotation==`number`&&(i.rotation=0)),r&&n&&typeof n.yaw==`number`&&typeof r.yaw==`number`&&(r.yaw=n.yaw,typeof n.pitch==`number`&&(r.pitch=n.pitch)),r&&(r.enabled=!0),this.mounted=!0,this.mounts+=1,this.emit(`mounted`,t),!0}dismount(){if(!this.mounted)return!1;let e=this.riderNode(),t=this.steedNode(),n=this.switchOf(e,this.walk,`walk`),r=this.switchOf(t,this.drive,`drive`),i=B(t),a=this.dismountAt,o;if(i.length>=3){let e=Array.isArray(t.rotation)?t.rotation:[0,0,0],n=Math.atan2(Math.sin((e[1]??0)*uC),Math.cos((e[0]??0)*uC)*Math.cos((e[1]??0)*uC));o=[(i[0]??0)+Math.cos(n)*(a[0]??0)+Math.sin(n)*(a[2]??0),(i[1]??0)+(a[1]??0),(i[2]??0)-Math.sin(n)*(a[0]??0)+Math.cos(n)*(a[2]??0)]}else{let e=(typeof t.rotation==`number`?t.rotation:0)*uC;o=[(i[0]??0)+Math.cos(e)*(a[0]??0)-Math.sin(e)*(a[1]??0),(i[1]??0)+Math.sin(e)*(a[0]??0)+Math.cos(e)*(a[1]??0)]}e.position=Ba(e,o),e.linearVelocity&&=e.linearVelocity.map(()=>0),this.parked&&(`gravityScale`in e&&(e.gravityScale=this.parked.gravityScale),`enabled`in e&&(e.enabled=this.parked.enabled),`visible`in e&&(e.visible=this.parked.visible));let s=this.skinNode(this.saddleNode());return s&&(s.reparent(e),s.position=[...this.skinOnRider]),r&&n&&typeof n.yaw==`number`&&typeof r.yaw==`number`&&(n.yaw=r.yaw,typeof r.pitch==`number`&&(n.pitch=r.pitch)),r&&(r.enabled=!1),t.linearVelocity&&=t.linearVelocity.map(()=>0),n&&(n.enabled=!0),this.mounted=!1,this.emit(`dismounted`,t),!0}toggle(){this.mounted?this.dismount():this.mount()}update(){if(!this.mounted)return;let e=this.riderNode();e.position=Ba(e,B(this.steedNode()))}},fC=[`linear`,`easeIn`,`easeOut`,`easeInOut`];function pC(e,t){let n=t<0?0:t>1?1:t;switch(e){case`linear`:return n;case`easeIn`:return n*n;case`easeOut`:return 1-(1-n)*(1-n);case`easeInOut`:return n<.5?2*n*n:1-(-2*n+2)**2/2}}var mC=class extends Tt{static props={to:{default:[],required:!0},duration:{default:1},ease:{default:`easeInOut`,options:[...fC]},startOnSignal:{default:!1}};static signals=[`arrived`];to=[];duration=1;ease=`easeInOut`;startOnSignal=!1;from=[];elapsed=0;running=!1;arrivedFired=!1;onReady(){if(!(this.duration>0))throw new L(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "duration" must be > 0, got ${this.duration}.`,{prop:`duration`});if(!fC.includes(this.ease))throw new L(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "ease" must be one of [${fC.join(`, `)}], got '${this.ease}'.`,{prop:`ease`});let e=wv(this);this.from=[...e.position],this.startOnSignal||(this.running=!0)}start(){let e=this.node;this.from=[...e.position],this.elapsed=0,this.arrivedFired=!1,this.running=!0}finish(){let e=this.node;e.position=e.position.map((e,t)=>this.to[t]??e),this.running=!1,this.elapsed=this.duration,this.arrivedFired||(this.arrivedFired=!0,this.emit(`arrived`))}update(e){if(!this.running)return;let t=this.node;this.elapsed+=e;let n=Math.min(1,this.elapsed/this.duration),r=pC(this.ease,n);t.position=this.from.map((e,t)=>e+((this.to[t]??e)-e)*r),n>=1&&!this.arrivedFired&&(this.arrivedFired=!0,this.running=!1,this.emit(`arrived`))}},hC=[`x`,`y`,`z`],gC=[`position`,`rotation`,`scale`],_C={x:0,y:1,z:2},vC=class extends Tt{static props={axis:{default:`y`,options:[...hC]},amplitude:{default:1},frequency:{default:1},mode:{default:`position`,options:[...gC]}};static signals=[];axis=`y`;amplitude=1;frequency=1;mode=`position`;base=0;time=0;onReady(){if(!hC.includes(this.axis))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "axis" must be one of [${hC.join(`, `)}], got '${this.axis}'.`,{prop:`axis`});if(!gC.includes(this.mode))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "mode" must be one of [${gC.join(`, `)}], got '${this.mode}'.`,{prop:`mode`});this.base=this.readChannel()}update(e){this.time+=e;let t=this.amplitude*Math.sin(2*Math.PI*this.frequency*this.time);this.writeChannel(this.base+t)}isScalarRotation(){return this.mode===`rotation`&&typeof this.node.rotation==`number`}readChannel(){if(this.isScalarRotation())return this.node.rotation;let e=this.node[this.mode];if(!Array.isArray(e))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': node has no '${this.mode}' array to oscillate.`,{prop:`mode`});return e[_C[this.axis]]??0}writeChannel(e){if(this.isScalarRotation()){this.node.rotation=e;return}let t=[...this.node[this.mode]];t[_C[this.axis]]=e,this.node[this.mode]=t}},yC=class extends Tt{static signals=[`waypointReached`,`arrived`];static props={speed:{default:120},loop:{default:!1},moveParent:{default:!1},path:{default:``,nodePath:!0},autoStart:{default:!0},...OS};speed=120;loop=!1;moveParent=!1;path=``;autoStart=!0;declared=[];facePath=``;turnSpeed=100;waypoints=[];index=0;get moving(){return this.index<this.waypoints.length}setPath(e){this.waypoints=e.map(e=>[...e]),this.index=0}onReady(){if(this.path===``)return;let e=this.node.getNodeOrNull(this.path);if(!e)throw new L(`NODE_NOT_FOUND`,`PathFollow on '${this.node.getPath()}': "path" '${this.path}' resolves to no node — it names the parent whose children are the waypoints.`,{prop:`path`,path:this.node.getPath()});if(this.declared=e.children.filter(Cv).map(e=>B(e)),this.declared.length===0)throw new L(`PROP_TYPE_MISMATCH`,`PathFollow on '${this.node.getPath()}': "path" '${this.path}' has no spatial children to walk.`,{prop:`path`,path:this.node.getPath()});this.autoStart&&this.setPath(this.declared)}start(){this.declared.length!==0&&this.setPath(this.declared)}stop(){this.waypoints=[],this.index=0}update(e){if(!this.moving)return;let t=this.mover(),n=this.speed*e,r=[...t.position],i=[...t.position];for(;n>0&&this.index<this.waypoints.length;){let a=this.waypoints[this.index],o=kv(i,a,n),s=bC(i,o.position);if(i=o.position,n-=s,o.reached){if(this.node.emit(`waypointReached`,this.index),this.index+=1,this.index>=this.waypoints.length)if(this.loop&&this.waypoints.length>1)this.index=0;else{ey(t,i,e),this.face(t,r,i,e),this.node.emit(`arrived`);return}}else break}ey(t,i,e),this.face(t,r,i,e)}face(e,t,n,r){if(this.facePath===``)return;let i=this.node.getNodeOrNull(this.facePath);i&&DS(i,n.map((e,n)=>e-(t[n]??0)),r,this.turnSpeed)}mover(){if(!this.moveParent)return wv(this);let e=this.node.parent;if(!e||!Cv(e))throw new L(`PROP_TYPE_MISMATCH`,`PathFollow on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move.`,{prop:`moveParent`,path:this.node.getPath()});return e}};function bC(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(t[i]??0)-(e[i]??0);n+=r*r}return Math.sqrt(n)}var xC=class extends Tt{static props={points:{default:[],required:!0},speed:{default:60},loop:{default:!0},mode:{default:`loop`,options:[`loop`,`pingpong`]},pauseAt:{default:0},moveParent:{default:!1},...OS};static signals=[`reachedPoint`];points=[];speed=60;loop=!0;mode=`loop`;pauseAt=0;moveParent=!1;facePath=``;turnSpeed=100;index=0;direction=1;pauseTimer=0;onReady(){if(!Array.isArray(this.points)||this.points.length===0)throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "points" must be a non-empty array of position arrays or node paths.`,{prop:`points`});if(this.mode!==`loop`&&this.mode!==`pingpong`)throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "mode" must be 'loop' or 'pingpong', got '${this.mode}'.`,{prop:`mode`});if(this.moveParent){let e=this.node.parent;if(!e||!Cv(e))throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else wv(this)}update(e){if(this.pauseTimer>0){this.pauseTimer=Math.max(0,this.pauseTimer-e);return}let t=this.moveParent?this.node.parent:this.node;if(!t||!Cv(t))return;let n=t,r=this.pointAt(this.index);if(!r){this.reportDeadWaypoint(this.index);return}let i=[...n.position],{position:a,reached:o}=kv(n.position,r,this.speed*e);ey(n,a,e),this.face(i,a,e),o&&(this.emit(`reachedPoint`,this.index),this.advance(),this.pauseAt>0&&(this.pauseTimer=this.pauseAt))}face(e,t,n){if(this.facePath===``)return;let r=this.node.getNodeOrNull(this.facePath);r&&DS(r,t.map((t,n)=>t-(e[n]??0)),n,this.turnSpeed)}reportedDead=new Set;reportDeadWaypoint(e){if(this.reportedDead.has(e))return;this.reportedDead.add(e);let t=this.points[e];z(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: waypoint ${e} (${JSON.stringify(t)}) resolves to nothing — the patrol stops here and never moves again.`)}pointAt(e){let t=this.points[e];if(Array.isArray(t))return t;if(typeof t==`string`){let e=this.node.getNodeOrNull(t);if(!e||!Cv(e))return null;let n=this.moveParent?this.node.parent:this.node;return!n||!Cv(n)?null:Ba(n,B(e))}return null}advance(){let e=this.points.length-1;if(this.mode===`pingpong`){this.index>=e?this.direction=-1:this.index<=0&&(this.direction=1),this.index=Math.min(e,Math.max(0,this.index+this.direction));return}this.index<e?this.index+=1:this.loop&&(this.index=0)}},SC=5,CC=class extends Tt{static props={at:{default:[]},health:{default:``,nodePath:!0}};static signals=[`phaseChanged`,`phase2`,`phase3`,`phase4`,`phase5`];at=[];health=``;phase=1;watched=null;onReady(){let e=this.health===``?this.node:this.node.getNodeOrNull(this.health)??this.node;if(this.watched=ny(e)?.health??null,!this.watched){z(this.node.tree?.engine??null,`error`,`[incanto] Phases on '${this.node.getPath()}' found no Health to watch, so the fight has one phase forever. Put it under the node that carries the Health, or name one with \`health\`.`);return}this.watched.on(`healthChanged`,(e,t)=>this.read(e,t))}read(e,t){if(!(t>0))return;let n=e/t,r=1;for(let[e,t]of this.at.entries())n<=t&&(r=e+2);for(;this.phase<r;)this.phase+=1,this.phase<=SC&&this.emit(`phase${this.phase}`),this.emit(`phaseChanged`,this.phase)}serialize(){return{phase:this.phase}}deserialize(e){let t=e;typeof t.phase==`number`&&t.phase>=1&&(this.phase=t.phase)}announce(){this.emit(`phaseChanged`,this.phase)}},wC=class extends Tt{static props={value:{default:1},kind:{default:`coin`},collectorGroup:{default:`player`}};static signals=[`collected`];value=1;kind=`coin`;collectorGroup=`player`;collectedAlready=!1;onReady(){RS(this,e=>this.tryCollect(e))}tryCollect(e){if(this.collectedAlready)return;let t=TC(e,this.collectorGroup);t&&(this.collectedAlready=!0,this.node.queueFree(),this.emit(`collected`,this.value,t))}};function TC(e,t){let n=[e];for(;n.length>0;){let e=n.shift();if(e.isInGroup(t))return e;n.push(...e.children)}for(let n=e.parent;n;n=n.parent)if(n.isInGroup(t))return n;return null}var EC=class extends Tt{static props={prefabs:{default:``}};static signals=[];prefabs=``;held=new Map;onEnterTree(){this.claim()}onReady(){this.claim()}claim(){let e=this.prefabs.split(`,`).map(e=>e.trim()).filter(e=>e!==``),t=e.length>0?e:[...this.node.children].map(e=>e.name);for(let e of t){if(this.held.has(e))continue;let t=this.node.children.find(t=>t.name===e);if(!t)throw new L(`NODE_NOT_FOUND`,`PrefabShelf on '${this.node.getPath()}': "prefabs" names '${e}', which is not a child of this node. It holds: ${this.childNames()||`(nothing)`}.`,{prop:`prefabs`,path:this.node.getPath()});$i(t),this.node.removeChild(t),this.held.set(e,t)}}names(){return[...this.held.keys()]}template(e){return this.held.get(e)??null}make(e){let t=this.held.get(e);if(!t)throw new L(`NODE_NOT_FOUND`,`PrefabShelf on '${this.node.getPath()}': no template named '${e}'. This shelf holds: ${this.childNames()||`(nothing)`}.`,{path:this.node.getPath()});let n=Ji(t,Yi(this.node));return typeof n.visible==`boolean`&&(n.visible=!0),n}childNames(){return this.names().join(`, `)}},DC=class extends Tt{static props={speed:{default:300},direction:{default:null,kinds:[`null`,`array`,`string`]},gravity:{default:0}};static signals=[];_speed=300;_direction=null;gravity=0;velocity=[];fall=0;get speed(){return this._speed}set speed(e){this._speed=e,this.armed&&this.aim()}get direction(){return this._direction}set direction(e){this._direction=e,this.armed?this.aim():this.node&&this.resolveDirection()}get armed(){return this.velocity.length>0}aim(e=void 0,t=void 0){e!==void 0&&(this._direction=e),t!==void 0&&(this.carry=[...t]);let n=wv(this),r=this.resolveDirection();for(this.velocity=r.map((e,t)=>e*this._speed+(this.carry[t]??0));this.velocity.length<n.position.length;)this.velocity.push(this.carry[this.velocity.length]??0)}carry=[];onReady(){if(this.speed===0&&this.gravity===0)throw new L(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': a projectile with "speed" 0 and "gravity" 0 never moves — set one of them.`,{prop:`speed`});wv(this),this.resolveDirection()}update(e){this.armed||this.aim();let t=this.node;this.gravity!==0&&(this.fall+=this.gravity*e*(t.position.length===3?-1:1));let n=t.position,r=Math.max(n.length,this.velocity.length),i=Array(r);for(let t=0;t<r;t++){let r=(this.velocity[t]??0)+(t===1?this.fall:0);i[t]=(n[t]??0)+r*e}t.position=i}resolveDirection(){if(Array.isArray(this._direction))return Ov(this._direction);if(this._direction===null||this._direction===`forward`)return this.forwardFromRotation();throw new L(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': "direction" must be a vector or 'forward', got ${JSON.stringify(this._direction)}.`,{prop:`direction`})}forwardFromRotation(){let e=this.node.rotation;if(typeof e==`number`){let t=e*Math.PI/180;return[Math.cos(t),Math.sin(t)]}if(Array.isArray(e)){let t=(e[1]??0)*Math.PI/180,n=(e[0]??0)*Math.PI/180;return Ov([Math.sin(t),-Math.sin(n)*Math.cos(t),Math.cos(n)*Math.cos(t)])}return[1,0]}},OC=class extends Tt{static props={game:{default:`game`},slot:{default:`1`},label:{default:``},scene:{default:``},restoreOnReady:{default:!1},probeOnReady:{default:!1},keep:{default:[],nodePath:!0}};static signals=[`saved`,`saveFailed`,`restored`,`noSave`,`hasSave`];game=`game`;slot=`1`;label=``;scene=``;restoreOnReady=!1;probeOnReady=!1;keep=[];keptPoses={};elapsed=0;slots=null;store(){return this.slots??=new ua(this.game),this.slots}warnedVolatile=!1;pendingRestore=!1;pendingProbe=!1;onReady(){this.pendingRestore=this.restoreOnReady,this.pendingProbe=this.probeOnReady}update(e){this.pendingProbe&&(this.pendingProbe=!1,this.probe()),this.pendingRestore&&(this.pendingRestore=!1,this.restore()),this.elapsed+=e}probe(){let e=this.store().read(this.slot);if(!e){this.emit(`noSave`);return}this.emit(`hasSave`,e.label||e.scene,e.playtime,e.scene)}get playtime(){return Math.round(this.elapsed)}slotScene(){return this.store().read(this.slot)?.scene??null}save(){let e=this.engine;this.keptPoses=this.readPoses();let t=e.captureState(),n=e.lastCaptureFailures;if(n.length>0){e.log.error(`[incanto] SavePoint '${this.slot}' REFUSED to write: ${n.length} behavior(s) threw out of serialize(), so this save is missing their run and would overwrite the slot that is not. First: ${n[0]}`),this.emit(`saveFailed`,this.slot);return}this.store().write(this.slot,{scene:this.scene||(e.scene?.source.name??``),state:t,label:this.label,savedAt:Date.now(),playtime:Math.round(this.elapsed)}),!this.store().persistent&&!this.warnedVolatile&&(this.warnedVolatile=!0,e.log.warn(`SavePoint wrote slot '${this.slot}' to memory, not to disk — this browser refused localStorage (private window, storage disabled, or quota exhausted), so the run is lost when the page closes. \`SaveSlots.persistent\` is how a game asks before promising the player anything.`)),this.emit(`saved`,this.slot)}restore(){let e=this.store().read(this.slot);if(!e){this.emit(`noSave`);return}let t=this.engine.restoreState(e.state),n=this.scene||this.engine?.scene?.source.name;n&&e.scene&&e.scene!==n?z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': this slot was saved in scene '${e.scene}' and you are in '${n}'. Load that scene first — a save is restored INTO the scene it came from (incanto-save-slots.md).`):t.expected>0&&t.restored===0&&z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': restored 0 of ${t.expected} saveable behaviour(s)`+(t.missing.length>0?` — ${t.missing.length} uid(s) in the save are not in this scene, starting with '${t.missing[0]}'. That save is from an older build, or from another scene.`:`. Nothing in the save matched a node here.`)),this.emit(`restored`,t.restored)}clear(){this.store().remove(this.slot)}serialize(){return{playtime:Math.round(this.elapsed),poses:{...this.keptPoses}}}deserialize(e){let t=e;if(typeof t.playtime==`number`&&t.playtime>=0&&(this.elapsed=t.playtime),this.keptPoses={},t.poses&&typeof t.poses==`object`&&!Array.isArray(t.poses))for(let[e,n]of Object.entries(t.poses))Array.isArray(n)&&n.length===6&&n.every(e=>typeof e==`number`)&&(this.keptPoses[e]=[...n])}announce(){let e=this.node.getRoot();for(let[t,n]of Object.entries(this.keptPoses)){let r=e.getNodeByUid(t);r&&(Array.isArray(r.position)&&(r.position=n.slice(0,3)),Array.isArray(r.rotation)&&(r.rotation=n.slice(3,6)))}}readPoses(){let e={};for(let t of this.keep){let n=this.node.getNodeOrNull(t);if(!n){z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': keep names '${t}', which is not in this scene — that node's position is NOT in the save and a continue will put it back where the scene file says.`);continue}if(!n.uid){z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': keep names '${t}', which has no uid — a save is keyed by uid, so there is nothing to file its position under. Give the node a uid (\`newUid()\`, or open the scene in the editor once).`);continue}let r=n;if(!Array.isArray(r.position)){z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': keep names '${t}', a ${n.constructor.name} with no position — only a 2D/3D node has a pose to keep.`);continue}let i=r.position.map(e=>e),a=Array.isArray(r.rotation)?r.rotation:[];e[n.uid]=[i[0]??0,i[1]??0,i[2]??0,a[0]??0,a[1]??0,a[2]??0]}return e}},kC=class extends Tt{static props={score:{default:0},lives:{default:0},scoreToWin:{default:0}};static signals=[`scoreChanged`,`won`,`lost`,`lifeLost`,`livesChanged`];score=0;lives=0;scoreToWin=0;hasWon=!1;hasLost=!1;get won(){return this.hasWon}get lost(){return this.hasLost}onReady(){if(this.lives<0)throw new L(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "lives" must be >= 0, got ${this.lives}.`,{prop:`lives`});if(this.scoreToWin<0)throw new L(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "scoreToWin" must be >= 0, got ${this.scoreToWin}.`,{prop:`scoreToWin`})}addScore(e){this.setScore(this.score+an(e,this.node,`ScoreKeeper.addScore`))}setScore(e){this.score=an(e,this.node,`ScoreKeeper.setScore`),this.emit(`scoreChanged`,this.score),this.scoreToWin>0&&!this.hasWon&&this.score>=this.scoreToWin&&(this.hasWon=!0,this.emit(`won`))}loseLife(){this.lives<=0||this.hasLost||(--this.lives,this.emit(`lifeLost`,this.lives),this.emit(`livesChanged`,this.lives),this.lives<=0&&(this.hasLost=!0,this.emit(`lost`)))}serialize(){return{score:this.score,lives:this.lives,hasWon:this.hasWon,hasLost:this.hasLost}}deserialize(e){let t=e;typeof t.score==`number`&&(this.score=t.score),typeof t.lives==`number`&&(this.lives=t.lives),typeof t.hasWon==`boolean`&&(this.hasWon=t.hasWon),typeof t.hasLost==`boolean`&&(this.hasLost=t.hasLost)}announce(){this.emit(`scoreChanged`,this.score),this.emit(`livesChanged`,this.lives)}},AC=[`shape`,`size`,`radius`,`height`,`offset`,`oneWay`];function jC(e,t){let n=e.shape;for(let n of Object.keys(e))if(!AC.includes(n))throw new L(`BAD_FORMAT`,`Collider on '${t}' has an unknown key "${n}".`+rt(n,AC)+` A collider is [${AC.join(`, `)}] — friction, restitution and mass are props of the BODY, not of its collider.`,{prop:n,validOptions:[...AC]});if(n!==void 0){if(e.oneWay!==void 0&&typeof e.oneWay!=`boolean`)throw new L(`BAD_FORMAT`,`Collider on '${t}': "oneWay" must be a boolean (platforms you jump up through), got ${JSON.stringify(e.oneWay)}.`);if(n===`rect`){let n=e.size;if(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${t}': rect needs "size": [width, height].`);return}if(n===`circle`){if(typeof e.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': circle needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}throw new L(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(n)}.`)}}var MC=class extends Ht{static typeName=`Node2D`;static props={position:{default:[0,0]},rotation:{default:0},static:{default:!1},scale:{default:[1,1]},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},visible:{default:!0}};static propAliases={zIndex:`renderOrder`};position=[0,0];rotation=0;static=!1;scale=[1,1];renderOrder=0;orderGroup=`default`;get effectiveRenderOrder(){return Jn(this.orderGroup,this.renderOrder,this.tree?.engine?.orderGroups)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new ru}_staticReady(e){return!0}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-cl.degToRad(this.rotation),t.scale.set(this.scale[0]??1,this.scale[1]??1,1),t.visible=this.visible}free(){super.free(),this._object2D?.removeFromParent(),this._object2D=null}},NC=class extends MC{static props={collider:{default:{},variants:{tag:`shape`,byTag:{rect:{shape:`rect`,size:[32,32]},circle:{shape:`circle`,radius:16},capsule:{shape:`capsule`,radius:12,height:32}}}},enabled:{default:!0}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;_enabled=!0;_enabledChanged=!1;get collider(){return this._collider}set collider(e){if(typeof e!=`object`||!e||Array.isArray(e)){z(this.tree?.engine??null,`error`,`[incanto] ${this.getPath()}: collider must be an object, got ${e===null?`null`:Array.isArray(e)?`an array`:typeof e} — to switch this body off set \`enabled = false\` instead. Keeping the collider it had.`);return}this._collider=e,this._colliderChanged=!0}get enabled(){return this._enabled}set enabled(e){e!==this._enabled&&(this._enabled=e,this._enabledChanged=!0)}static validateJson(e){jC(e.collider,e.name)}_physics=null},PC=class extends NC{static typeName=`StaticBody2D`;static props={friction:{default:.5},restitution:{default:0}};friction=.5;restitution=0},FC=class extends NC{static typeName=`Area2D`;overlapping(e=void 0){let t=this._physics?.overlapping(this)??[];return e===void 0?t:t.filter(t=>t.isInGroup(e))}},IC=class extends NC{static typeName=`RigidBody2D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0]},angularVelocity:{default:0},linearDamping:{default:0,range:{min:0}},angularDamping:{default:0,range:{min:0}}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearDamping=0;angularDamping=0;linearVelocity=[0,0];angularVelocity=0;get velocity(){return this.linearVelocity}set velocity(e){this.linearVelocity=e}applyImpulse(e){this._physics?.applyImpulse(this,e)}},LC=class extends NC{static typeName=`CharacterBody2D`;static props={velocity:{default:[0,0]},stickToGround:{default:!0},slopeLimitDeg:{default:45},stepHeight:{default:35,range:{min:0}},collideWithCharacters:{default:!0},pushes:{default:0,range:{min:0}}};pushes=0;static propAliases={snapToGround:`stickToGround`};velocity=[0,0];stickToGround=!0;slopeLimitDeg=45;stepHeight=35;collideWithCharacters=!0;_grounded=!1;moveAndSlide(){if(!this._physics)throw new L(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody2D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody2D '${this.name}' has no physics world — await enablePhysics2D(engine) first.`);this._physics.moveAndSlide(this)}_onWall=0;_onCeiling=!1;isOnWall(){return this._onWall!==0}wallSide(){return this._onWall}isOnCeiling(){return this._onCeiling}isOnFloor(){return this._grounded}},RC=100,zC=Math.PI/180,BC=.9,VC=class extends Tt{static props={pieces:{default:8,range:{min:1}},impulse:{default:4},spin:{default:6},lifetime:{default:2.5,range:{min:0}},when:{default:`died`},mesh:{default:``,nodePath:!0},free:{default:!0}};static signals=[`shattered`];pieces=8;impulse=4;spin=6;lifetime=2.5;when=`died`;mesh=``;free=!0;broken=!1;get breakable(){let e=this.node;return e instanceof Ib||e instanceof NC?e:e.parent??e}onReady(){if(this.when===``)return;let e=this.breakable;try{e.on(this.when,()=>this.break(),{owner:this.node})}catch(t){z(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: Shatter listens for '${this.when}' on '${e.getPath()}', which declares no such signal — give it a Health (it emits 'died'), name another signal in "when", or set "when": "" and call break() yourself. (${t instanceof Error?t.message:String(t)})`)}}break(){if(this.broken)return;this.broken=!0;let e=this.breakable,t=e.getRoot(),n=this.node.tree?.engine?.rng,r=()=>n?n.next():Math.random(),i=!(e instanceof NC)&&(e instanceof Ib||B(e).length===3),a=B(e),o=Math.max(1,Math.round(this.pieces)),s=[];if(i){let t=this.findMesh(e,`MeshInstance3D`),n=e.collider,i=t?.size??n?.size??[1,1,1],c=t?.material??{},l=t?.castShadow??!1,u=(e.mass??1)/o,d=(e.rotation?.[1]??0)*zC,f=Math.max(1,Math.ceil(Math.cbrt(o))),p=[(i[0]??1)/f,(i[1]??1)/f,(i[2]??1)/f],m=p.map(e=>e*BC),h=0;for(let t=0;t<f&&h<o;t++)for(let n=0;n<f&&h<o;n++)for(let i=0;i<f&&h<o;i++,h++){let o=(i-(f-1)/2)*(p[0]??1),g=(t-(f-1)/2)*(p[1]??1),_=(n-(f-1)/2)*(p[2]??1),v=o*Math.cos(d)+_*Math.sin(d),y=-o*Math.sin(d)+_*Math.cos(d),b=Math.hypot(v,g,y),x=b>1e-6?[v/b,g/b,y/b]:[r()-.5,r(),r()-.5].map(e=>e*2),S=this.impulse*(.6+r()*.6),C={name:`${e.name}Piece${h}`,type:`RigidBody3D`,props:{position:[(a[0]??0)+v,(a[1]??0)+g,(a[2]??0)+y],rotation:[0,d/zC,0],mass:u,friction:.7,collider:{shape:`box`,size:m},linearVelocity:[(x[0]??0)*S,(x[1]??0)*S+this.impulse*.5,(x[2]??0)*S],angularVelocity:[(r()-.5)*2*this.spin,(r()-.5)*2*this.spin,(r()-.5)*2*this.spin]},children:[{name:`Mesh`,type:`MeshInstance3D`,props:{mesh:`box`,size:m,material:{...c},castShadow:l}}]};this.lifetime>0&&(C.script={name:`Lifetime`,props:{seconds:this.lifetime}}),s.push(xi(C,Yi(this.node)))}}else{let t=this.findMesh(e,`ColorRect2D`),n=t?null:this.findMesh(e,`Sprite2D`),i=e.collider,c=t?.size??i?.size??[i?.radius?i.radius*2:40,i?.radius?i.radius*2:40],l=t?.color??n?.tint??`#ffffff`,u=(e.mass??1)/o,d=(e.rotation??0)*zC,f=Math.max(1,Math.ceil(Math.sqrt(o))),p=[(c[0]??40)/f,(c[1]??40)/f],m=p.map(e=>e*BC),h=this.impulse*RC,g=0;for(let t=0;t<f&&g<o;t++)for(let n=0;n<f&&g<o;n++,g++){let i=(n-(f-1)/2)*(p[0]??1),o=(t-(f-1)/2)*(p[1]??1),c=i*Math.cos(d)-o*Math.sin(d),_=i*Math.sin(d)+o*Math.cos(d),v=Math.hypot(c,_),y=v>1e-6?[c/v,_/v]:[(r()-.5)*2,-r()],b=h*(.6+r()*.6),x={name:`${e.name}Piece${g}`,type:`RigidBody2D`,props:{position:[(a[0]??0)+c,(a[1]??0)+_],rotation:d/zC,mass:u,friction:.7,collider:{shape:`rect`,size:m},linearVelocity:[(y[0]??0)*b,(y[1]??0)*b-h*.5],angularVelocity:(r()-.5)*2*this.spin},children:[{name:`Rect`,type:`ColorRect2D`,props:{size:m,color:l}}]};this.lifetime>0&&(x.script={name:`Lifetime`,props:{seconds:this.lifetime}}),s.push(xi(x,Yi(this.node)))}}this.free&&(e.enabled=!1,e.queueFree());for(let e of s)t.addChild(e);this.emit(`shattered`,e)}findMesh(e,t){if(this.mesh!==``)return this.node.getNodeOrNull(this.mesh);let n=e=>{if(e.constructor.typeName===t)return e;for(let t of e.children){let e=n(t);if(e)return e}return null};return n(e)}},HC=Math.PI/180,UC=class extends Tt{static props={range:{default:12,range:{min:0}},coneDeg:{default:70,range:{min:0,max:360}},targetGroup:{default:`player`},facingPath:{default:`../Skin`,nodePath:!0},eyeHeight:{default:.6},chestHeight:{default:.3},fillSeconds:{default:0,range:{min:0}},los:{default:!0}};static signals=[`spotted`,`lost`];range=12;coneDeg=70;targetGroup=`player`;facingPath=`../Skin`;eyeHeight=.6;chestHeight=.3;fillSeconds=0;los=!0;suspicion=0;target=null;seenNow=new Set;alarmed=!1;lastTarget=null;sees(e){return this.seenNow.has(e)}seen(){return[...this.seenNow].sort((e,t)=>this.distanceTo(e)-this.distanceTo(t))}update(e){let t=this.node.parent;if(!t)return;let n=B(t),r=n.length<3,[i,a]=this.facing(t,r),o=Math.cos(Math.min(360,Math.max(0,this.coneDeg))*.5*HC),s=this.node.tree?.getNodesInGroup(this.targetGroup)??[],c=new Set,l=null,u=1/0;for(let e of s){if(e===t||e===this.node||e.tree===null)continue;let s=B(e);if(!Array.isArray(s)||s.length<2)continue;let d=(s[0]??0)-(n[0]??0),f=r?(s[1]??0)-(n[1]??0):(s[2]??0)-(n[2]??0),p=Math.hypot(d,f);if(!(p>this.range)&&!(p>.001&&this.coneDeg<360&&(i*d+a*f)/p<o)){if(this.los){let e=r?[n[0]??0,n[1]??0]:[n[0]??0,(n[1]??0)+this.eyeHeight,n[2]??0],i=(r?[s[0]??0,s[1]??0]:[s[0]??0,(s[1]??0)+this.chestHeight,s[2]??0]).map((t,n)=>t-(e[n]??0)),a=Math.hypot(...i);if(a>.001&&this.physics?.castRay(e,i,a,t,{staticOnly:!0}))continue}c.add(e),p<u&&(u=p,l=e)}}if(this.seenNow=c,this.target=l,l&&(this.lastTarget=l),this.fillSeconds<=0)this.suspicion=+!!l;else{let t=e/this.fillSeconds;this.suspicion=Math.min(1,Math.max(0,this.suspicion+(l?t:-t)))}!this.alarmed&&this.suspicion>=1?(this.alarmed=!0,this.emit(`spotted`,l??this.lastTarget)):this.alarmed&&this.suspicion<=0&&(this.alarmed=!1,this.emit(`lost`,this.lastTarget))}facing(e,t){let n=((this.facingPath===``?null:this.node.getNodeOrNull(this.facingPath))??e).rotation;if(t){let e=(typeof n==`number`?n:0)*HC;return[Math.cos(e),Math.sin(e)]}let r=(Array.isArray(n)?n[1]??0:0)*HC;return[Math.sin(r),Math.cos(r)]}distanceTo(e){let t=this.node.parent;if(!t)return 1/0;let n=B(t),r=B(e);return n.length<3?Math.hypot((n[0]??0)-(r[0]??0),(n[1]??0)-(r[1]??0)):Math.hypot((n[0]??0)-(r[0]??0),(n[2]??0)-(r[2]??0))}},WC=class{behavior;detached=new Map;constructor(e){this.behavior=e}resolveTemplate(e){let t=this.detached.get(e);if(t)return t;let n=this.behavior.node,r=GC(n,e),i=r?n.tree?._templates.get(r)??null:null;if(i)return this.detached.set(e,i),i;let a=e===``?null:n.getNodeOrNull(e);if(!a){let t=this.behavior.constructor.name;throw new L(`NODE_NOT_FOUND`,`${t} on '${n.getPath()}': "prefab" '${e}' does not resolve to a template node. Point it at a (usually hidden) child node to clone.`,{prop:`prefab`,path:n.getPath()})}return r&&n.tree?._templates.set(r,a),$i(a),a.parent&&a.parent.removeChild(a),this.detached.set(e,a),a}spawn(e,t=void 0){let n=Ji(e,Yi(this.behavior.node)),r=t?.at??[],i=t?.parent??this.behavior.node;if(Cv(n)&&(r.length>0||i!==this.behavior.node)){let e=i===this.behavior.node||!Cv(this.behavior.node)?[]:KC(B(this.behavior.node),B(i));n.position=Ev(e,r.length>0?r:qC(e.length||n.position.length))}return typeof n.visible==`boolean`&&(n.visible=!0),(t?.parent??this.behavior.node).addChild(n),n}};function GC(e,t){if(t===``||t.startsWith(`%`))return null;if(t.startsWith(`/`))return t;let n=e.getPath().split(`/`);for(let e of t.split(`/`))if(!(e===``||e===`.`)){if(e===`..`){if(n.length<=1)return null;n.pop();continue}n.push(e)}return n.join(`/`)}function KC(e,t){let n=Math.max(e.length,t.length),r=[];for(let i=0;i<n;i++)r.push((e[i]??0)-(t[i]??0));return r}function qC(e){return Array.from({length:e},()=>0)}var JC=class extends Tt{static props={prefab:{default:``,nodePath:!0,required:!0},interval:{default:1},max:{default:0},at:{default:[]},autoStart:{default:!0},total:{default:0},into:{default:``,nodePath:!0}};static signals=[`spawned`,`finished`];prefab=``;interval=1;max=0;at=[];autoStart=!0;total=0;into=``;source=new WC(this);template;live=new Set;timer=0;running=!1;spawnedCount=0;done=!1;get liveCount(){return this.prune(),this.live.size}_templateForTest(){return this.template}onEnterTree(){this.template=this.source.resolveTemplate(this.prefab)}onReady(){if(!(this.interval>0)&&this.max<=0&&this.total<=0)throw new L(`PROP_TYPE_MISMATCH`,`Spawner on '${this.node.getPath()}': "interval" ${this.interval} spawns a clone every FRAME and neither "max" (live cap) nor "total" (lifetime cap) is set, so the scene grows without bound. Give it an interval, or a cap.`,{prop:`interval`});this.template=this.source.resolveTemplate(this.prefab),this.into!==``&&this.node.getNode(this.into),this.running=this.autoStart,this.timer=this.interval}start(){this.done||(this.running=!0)}stop(){this.running=!1}spawn(){if(this.prune(),this.done||this.max>0&&this.live.size>=this.max)return null;let e=this.into===``?void 0:this.node.getNode(this.into),t=this.source.spawn(this.template,this.at.length>0||e?{at:this.at,parent:e}:void 0);return this.live.add(t),this.spawnedCount+=1,this.emit(`spawned`,t),this.total>0&&this.spawnedCount>=this.total&&(this.done=!0,this.running=!1,this.emit(`finished`)),t}update(e){this.running&&(this.timer-=e,!(this.timer>0)&&(this.timer+=this.interval,this.spawn()))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}};function YC(e,t,n,r,i=`low`){if(!(n>0)||!(r>0))return null;let a=e.length>=3&&t.length>=3,o=(t[0]??0)-(e[0]??0),s=a?(t[2]??0)-(e[2]??0):0,c=a?Math.hypot(o,s):Math.abs(o);if(c<1e-6)return null;let l=a?(t[1]??0)-(e[1]??0):-((t[1]??0)-(e[1]??0)),u=n*n,d=u*u-r*(r*c*c+2*l*u);if(d<0)return null;let f=Math.sqrt(d),p=(u+(i===`high`?f:-f))/(r*c),m=Math.atan(p),h=Math.cos(m),g=Math.sin(m);return a?[o/c*h,g,s/c*h]:[Math.sign(o)*h,-g]}function XC(e,t){let n=e.length>=3&&t.length>=3,r=(t[0]??0)-(e[0]??0),i=n?(t[2]??0)-(e[2]??0):0,a=n?Math.hypot(r,i):Math.abs(r);if(a<1e-6)return null;let o=Math.SQRT1_2;return n?[r/a*o,o,i/a*o]:[Math.sign(r)*o,-o]}var ZC={CameraShake:cC,DayNight:BS,GameFlow:XS,PathFollow:yC,Health:ty,Lifetime:lC,Checkpoint:NS,Turret:class extends Tt{static props={targetGroup:{default:`enemy`},requireSight:{default:!1},range:{default:6,range:{min:0}},damage:{default:10},cooldown:{default:.6,range:{min:0}},shelf:{default:``,nodePath:!0},prefab:{default:``},muzzle:{default:[]},arc:{default:`flat`,options:[`flat`,`low`,`high`]},into:{default:``,nodePath:!0},...OS};static signals=[`acquired`,`fired`,`lost`];targetGroup=`enemy`;requireSight=!1;range=6;damage=10;cooldown=.6;shelf=``;prefab=``;muzzle=[];into=``;arc=`flat`;facePath=``;turnSpeed=100;target=null;shots=0;wait=0;onReady(){if(this.shelf===``!=(this.prefab===``))throw new L(`PROP_TYPE_MISMATCH`,`Turret on '${this.node.getPath()}': "shelf" and "prefab" go together — name both for a projectile, neither for hitscan.`,{prop:this.shelf===``?`shelf`:`prefab`,path:this.node.getPath()})}canSee(e,t){let n=this.physics;if(!n)return!0;let r=t.map((t,n)=>t-(e[n]??0)),i=Math.hypot(...r);return i<.001?!0:n.castRay(e,r,i,this.node,{staticOnly:!0})==null}update(e){if(this.wait=Math.max(0,this.wait-e),!Cv(this.node))return;let t=B(this.node),n=null,r=this.range;for(let e of this.node.tree?.getNodesInGroup(this.targetGroup)??[]){if(e===this.node||!Cv(e)||ny(e)?.health.isDead)continue;let i=Tv(t,B(e));i<=r&&(!this.requireSight||this.canSee(t,B(e)))&&(n=e,r=i)}if(n!==this.target){let e=this.target;this.target=n,n?this.emit(`acquired`,n):e&&this.emit(`lost`)}if(!n)return;let i=B(n),a=this.facePath===``?null:this.node.getNodeOrNull(this.facePath),o=this.aimAt(t,i,a);if(a&&(DS(a,o,e,this.turnSpeed),this.arc!==`flat`)){let e=a.rotation;if(Array.isArray(e)){let t=Math.hypot(o[0]??0,o[2]??0);a.rotation=[-(Math.atan2(o[1]??0,t)*180/Math.PI),e[1]??0,e[2]??0]}}this.wait>0||(this.wait=this.cooldown,this.shots+=1,this.shelf===``?ny(n)?.health.damage(this.damage,t):this.launch(n,t,o,a),this.emit(`fired`,n))}muzzleAt(e,t){if(this.muzzle.length===0)return[...e];let n=t?za(t,this.muzzle):this.muzzle;return e.map((e,t)=>e+(n[t]??0))}aimAt(e,t,n){if(this.arc===`flat`)return t.map((t,n)=>t-(e[n]??0));let r=this.muzzleAt(e,n),i=this.shellBallistics();return i?YC(r,t,i.speed,i.gravity,this.arc)??XC(r,t)??t.map((e,t)=>e-(r[t]??0)):t.map((e,t)=>e-(r[t]??0))}shellBallistics(){if(this.shelf===``||this.prefab===``)return null;let e=this.node.getNodeOrNull(this.shelf)?.behavior;if(!e||typeof e.template!=`function`)return null;let t=e.template(this.prefab)?.behavior;if(!t||typeof t.speed!=`number`||typeof t.gravity!=`number`)return null;if(!(t.gravity>0))throw new L(`PROP_TYPE_MISMATCH`,`Turret on '${this.node.getPath()}': "arc" is '${this.arc}', but '${this.prefab}' has no gravity to arc against — give its Projectile a "gravity", or leave the turret flat.`,{prop:`arc`,path:this.node.getPath()});return{speed:t.speed,gravity:t.gravity}}launch(e,t,n,r){let i=this.node.getNodeOrNull(this.shelf)?.behavior;if(!i||typeof i.make!=`function`)throw new L(`NODE_NOT_FOUND`,`Turret on '${this.node.getPath()}': "shelf" '${this.shelf}' is not a PrefabShelf.`,{prop:`shelf`,path:this.node.getPath()});let a=i.make(this.prefab);if(!Cv(a))return;let o=this.into===``?this.node.parent:this.node.getNodeOrNull(this.into);if(!o)return;let s=Math.hypot(...n)||1,c=n.map(e=>e/s),l=Cv(o)?B(o):t.map(()=>0);a.position=this.muzzleAt(t,r).map((e,t)=>e-(l[t]??0));let u=a.behavior;u&&`direction`in u&&(u.direction=c),o.addChild(a)}},ScoreKeeper:kC,Currency:LS,Pickup:wC,Collector:IS,DamageOnContact:zS,Interactable:nC,Clickable:FS,Phases:CC,SavePoint:OC,FollowCamera:GS,ChaseCamera:jS,GroupCamera:$S,Patrol:xC,Chase:kS,FaceTarget:HS,Wander:class extends Tt{static props={speed:{default:40},radius:{default:50},changeEvery:{default:2}};static signals=[];speed=40;radius=50;changeEvery=2;origin=[];goal=[];timer=0;onReady(){if(!(this.radius>0))throw new L(`PROP_TYPE_MISMATCH`,`Wander on '${this.node.getPath()}': "radius" must be > 0, got ${this.radius}.`,{prop:`radius`});let e=wv(this);this.origin=[...e.position],this.goal=[...e.position],this.pickGoal()}update(e){let t=this.node;this.timer-=e;let{position:n,reached:r}=kv(t.position,this.goal,this.speed*e);ry(t)||(t.position=n,(r||this.timer<=0)&&this.pickGoal())}pickGoal(){this.timer=this.changeEvery;let e=this.origin.length,t=e===3?1:-1,n=Array(e);for(let r=0;r<8;r++){for(let r=0;r<e;r++)n[r]=r===t?this.origin[r]??0:(this.origin[r]??0)+this.rng.range(-this.radius,this.radius);if(Tv(n,this.origin)<=this.radius){this.goal=n;return}}this.goal=n.map((e,t)=>{let r=this.origin[t]??0,i=Tv(n,this.origin)||1;return r+(e-r)/i*this.radius})}},ZombieAI:class extends Tt{static props={aggroTarget:{default:``,nodePath:!0},aggroRange:{default:12},deAggroRange:{default:0},chaseSpeed:{default:4},wanderSpeed:{default:1.4},wanderRadius:{default:8},wanderChangeEvery:{default:3},goalTarget:{default:``,nodePath:!0},stopRange:{default:1.2},moveParent:{default:!1}};static signals=[`enteredAggro`,`exitedAggro`,`movementStateChanged`];aggroTarget=``;aggroRange=12;deAggroRange=0;chaseSpeed=4;wanderSpeed=1.4;wanderRadius=8;wanderChangeEvery=3;goalTarget=``;stopRange=1.2;moveParent=!1;aggro=!1;started=!1;home=[];goal=[];timer=0;lastState=``;mover(){let e=this.moveParent?this.node.parent:this.node;return e&&Cv(e)?e:null}effectiveDeAggro(){return this.deAggroRange>0?this.deAggroRange:this.aggroRange*1.5}onReady(){if(this.moveParent){let e=this.node.parent;if(!e||!Cv(e))throw new L(`PROP_TYPE_MISMATCH`,`ZombieAI on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else wv(this)}update(e){let t=this.mover();if(!t)return;this.started||(this.started=!0,this.home=[...t.position],this.pickGoal());let n=this.aggroTarget?this.node.getNodeOrNull(this.aggroTarget):null,r=n&&Cv(n)?Ba(t,B(n)):null,i=r?this.groundDistance(t.position,r):1/0;if(!this.aggro&&i<=this.aggroRange?(this.aggro=!0,this.emit(`enteredAggro`)):this.aggro&&i>=this.effectiveDeAggro()&&(this.aggro=!1,this.emit(`exitedAggro`),this.pickGoal()),this.aggro&&r){let n=this.approach(t,r,this.chaseSpeed,e);this.setState(n?`idle`:`run`);return}this.timer-=e;let a=this.approach(t,this.goal,this.wanderSpeed,e);this.setState(a?`idle`:`walk`),(a||this.timer<=0)&&this.pickGoal()}approach(e,t,n,r){let i=e.position;if(this.groundDistance(i,t)<=this.stopRange)return!0;let a=i.length>=3?1:-1,o=[...t];a>=0&&(o[a]=i[a]??0);let s=this.groundDistance(i,o),{position:c}=kv(i,o,Math.min(n*r,Math.max(0,s-this.stopRange)));return ry(e)||(e.position=c),!1}groundDistance(e,t){if(e.length>=3){let n=(e[0]??0)-(t[0]??0),r=(e[2]??0)-(t[2]??0);return Math.hypot(n,r)}return Tv(e,t)}setState(e){e!==this.lastState&&(this.lastState=e,this.emit(`movementStateChanged`,e))}pickGoal(){this.timer=this.wanderChangeEvery;let e=this.mover(),t=e?e.position:this.home,n=t.length>=3?1:-1,r=this.home,i=this.goalTarget?this.node.getNodeOrNull(this.goalTarget):null;if(i&&Cv(i)){let e=i.position;r=t.map((t,n)=>t+((e[n]??0)-t)*.4)}let a=[...r];for(let e=0;e<a.length;e++)e!==n&&(a[e]=(r[e]??0)+this.rng.range(-this.wanderRadius,this.wanderRadius));n>=0&&(a[n]=t[n]??0),this.goal=a}},Mount:dC,MoveTo:mC,Oscillate:vC,Spawner:JC,WaveSpawner:class extends Tt{static props={waves:{default:[],required:!0},autoStart:{default:!0}};static signals=[`spawned`,`waveStarted`,`waveCleared`,`allCleared`];waves=[];autoStart=!0;source=new WC(this);parsed=[];live=new Set;waveIndex=-1;get wave(){return this.waveIndex<0?0:Math.min(this.parsed.length,this.waveIndex+1)}get waveCount(){return this.parsed.length}phase=`idle`;timer=0;spawnedThisWave=0;announced=!1;onEnterTree(){if(!(!Array.isArray(this.waves)||this.waves.length===0))for(let e of this.waves){let t=e.prefab;typeof t==`string`&&t!==``&&this.source.resolveTemplate(t)}}onReady(){if(!Array.isArray(this.waves)||this.waves.length===0)throw new L(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': "waves" must be a non-empty array of { prefab, count, interval, delayBefore }.`,{prop:`waves`});this.parsed=this.waves.map((e,t)=>this.parseWave(e,t));for(let e of this.parsed)this.source.resolveTemplate(e.prefab);this.autoStart&&this.beginWave(0)}start(){this.beginWave(0)}serialize(){return{wave:this.waveIndex,done:this.phase===`done`}}deserialize(e){let t=e??{};if(t.done===!0){this.phase=`done`,this.waveIndex=this.parsed.length-1;return}if(typeof t.wave!=`number`||!Number.isInteger(t.wave))return;let n=Math.max(0,Math.min(t.wave,this.parsed.length-1));this.beginWave(n)}update(e){if(this.phase===`idle`||this.phase===`done`)return;let t=this.parsed[this.waveIndex];if(t){if(this.announced||(this.announced=!0,this.emit(`waveStarted`,this.waveIndex)),this.phase===`delay`){this.timer-=e,this.timer<=0&&(this.phase=`spawning`,this.timer=0);return}if(this.phase===`spawning`){for(this.timer-=e;this.timer<=0&&this.spawnedThisWave<t.count;){let e=this.source.spawn(this.source.resolveTemplate(t.prefab));this.live.add(e),this.spawnedThisWave+=1,this.emit(`spawned`,e),this.timer+=t.interval}this.spawnedThisWave>=t.count&&(this.phase=`clearing`);return}if(this.phase===`clearing`&&(this.prune(),this.live.size===0)){this.emit(`waveCleared`,this.waveIndex);let e=this.waveIndex+1;e<this.parsed.length?this.beginWave(e):(this.phase=`done`,this.emit(`allCleared`))}}}beginWave(e){this.waveIndex=e,this.spawnedThisWave=0,this.announced=!1,this.live.clear();let t=this.parsed[e];t&&(t.delayBefore>0?(this.phase=`delay`,this.timer=t.delayBefore):(this.phase=`spawning`,this.timer=0))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}parseWave(e,t){let n=e,r=typeof n?.prefab==`string`?n.prefab:``;if(r===``)throw new L(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': wave ${t} needs a "prefab" template path.`,{prop:`waves`});return{prefab:r,count:typeof n?.count==`number`?n.count:1,interval:typeof n?.interval==`number`?n.interval:.5,delayBefore:typeof n?.delayBefore==`number`?n.delayBefore:0}}},Projectile:DC,Buoyancy:bS,FloatAway:US,Shatter:VC,Blast:ay,Carry:TS,Sight:UC,PrefabShelf:EC};function QC(e){let t=e?.replace??!0;for(let[e,n]of Object.entries(ZC))kt(e,n,{replace:t})}var $C=new Set;function ew(e){return $C.add(e),()=>$C.delete(e)}function tw(e,t){return[...$C].filter(n=>n.dimension===e&&(t===void 0||n.engine===t))}function nw(e,t){return t===null?e===`rope`||e===`spring`:t}var rw=`using deprecated parameters for the initialization function`;async function iw(e,t=console){let n=t.warn;t.warn=(...e)=>{typeof e[0]==`string`&&e[0].includes(rw)||n.apply(t,e)};try{await e()}finally{t.warn=n}}var aw=class extends MC{static typeName=`Joint2D`;static props={type:{default:`revolute`,options:[`fixed`,`revolute`,`prismatic`,`rope`,`spring`]},target:{default:``,nodePath:!0,required:!0},anchor:{default:[0,0]},targetAnchor:{default:[0,0]},axis:{default:[0,1]},limits:{default:[]},motorSpeed:{default:0},motorStrength:{default:20,range:{min:0}},length:{default:0},stiffness:{default:50},damping:{default:5},collide:{default:null,kinds:[`null`,`boolean`]}};type=`revolute`;target=``;anchor=[0,0];targetAnchor=[0,0];limits=[];motorSpeed=0;motorStrength=20;angle=0;axis=[0,1];travel=0;length=0;stiffness=50;damping=5;collide=null;onEnterTree(){if(!(this.parent instanceof NC))throw new L(`TREE_VIOLATION`,`Joint2D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new L(`BAD_FORMAT`,`Joint2D '${this.name}' needs a "target" node path to the body it links to.`);if(this.type===`prismatic`&&!(Math.hypot(this.axis[0]??0,this.axis[1]??0)>1e-6))throw new L(`BAD_FORMAT`,`Joint2D '${this.name}': a prismatic joint needs a non-zero "axis" (got ${JSON.stringify(this.axis)}).`);if((this.type===`revolute`||this.type===`prismatic`)&&this.limits.length!==0&&this.limits.length!==2)throw new L(`BAD_FORMAT`,`Joint2D '${this.name}': "limits" is [minDeg, maxDeg] or [] (got ${JSON.stringify(this.limits)}).`)}_resolveBodies(){let e=this.parent,t=this.getNodeOrNull(this.target);if(!(t instanceof NC))throw new L(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);if(e===t)throw new L(`BAD_FORMAT`,`Joint2D '${this.name}': target '${this.target}' is the SAME body this joint hangs off, so it constrains nothing. A joint is a child of ONE body pointing at the OTHER — name the other body (e.g. "%Crate").`,{prop:`target`,path:this.getPath()});return{a:e,b:t}}},Z=100,ow=Math.PI/180;async function sw(e,t){let n=await Iv(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await iw(()=>n.init()),new cw(n,e,t)}var cw=class{R;engine;debugDraw=!1;debugScope=null;dimension=`2d`;unregisterDebug;warnedNoCollider=new WeakSet;entries=new Map;byColliderHandle=new Map;world;events;kcc;disconnectScene;disconnect;lastDt=1/60;optsGravity;lastScene=null;constructor(e,t,n){this.R=e,this.engine=t,this.optsGravity=n?.gravity,this.simulate=n?.simulate??!0,this.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,980];this.world=new e.World({x:(i[0]??0)/Z,y:(i[1]??0)/Z}),this.kcc=this.world.createCharacterController(.01),this.kcc.setUp({x:0,y:-1}),this.events=new e.EventQueue(!0),this.unregisterDebug=ew(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.disconnectScene=t.sceneChanged.connect(()=>{this.pruneOverlaps(),t.scene&&this.syncBodies()}),t.physics=this,this.syncBodies()}simulate;step(e){if(this.lastDt=e,!this.simulate){this.syncBodies(),this.poseFromTree();return}if(this.engine.scene!==this.lastScene&&(this.lastScene=this.engine.scene,!this.optsGravity)){let e=this.engine.scene?.physics?.gravity??[0,980];this.world.gravity={x:(e[0]??0)/Z,y:(e[1]??0)/Z}}this.syncBodies(),this.world.timestep=e,this.world.step(this.events);for(let[e,t]of this.entries){let n=t.body.translation();if(!t.body.isFixed()&&!(e instanceof FC)){let[t,r,i]=vw(e),a=n.x*Z-t,o=n.y*Z-r;if(i!==0){let t=-i*ow;e.position=[a*Math.cos(t)-o*Math.sin(t),a*Math.sin(t)+o*Math.cos(t)]}else e.position=[a,o]}if(e instanceof IC){e.fixedRotation||(e.rotation=t.body.rotation()/ow-vw(e)[2],t.lastRot=t.body.rotation()/ow);let n=t.body.linvel();e.linearVelocity=[n.x*Z,n.y*Z],e.angularVelocity=t.body.angvel(),t.lastVX=e.linearVelocity[0]??0,t.lastVY=e.linearVelocity[1]??0,t.lastAV=e.angularVelocity}let r=t.body.translation();t.lastX=r.x*Z,t.lastY=r.y*Z}this.events.drainCollisionEvents((e,t,n)=>{let r=this.byColliderHandle.get(e),i=this.byColliderHandle.get(t);if(!r||!i||!r.enabled||!i.enabled)return;let a=n?`triggerEnter`:`triggerExit`;if(n!==(this.overlaps.get(r)?.has(i)??!1)){this.trackOverlap(r,i,n),this.trackOverlap(i,r,n);try{r.emit(a,i),i.emit(a,r)}catch(e){z(this.engine,`error`,`incanto: error in a '${a}' handler (${r.name} ↔ ${i.name}):`,e)}}})}canCarry(e,t){if(this.jointed.get(e)?.has(t))return!1;let n=t;for(let t=0;t<8&&n;t++){if(n===e)return!1;n=this.entries.get(n)?.ground??null}return!0}moveAndSlide(e){let t=this.ensureEntry(e),n=e.velocity[1]??0;e.stickToGround&&n>=0?this.kcc.enableSnapToGround(.05):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*ow),e.stepHeight>0?this.kcc.enableAutostep(e.stepHeight/Z,e.stepHeight/Z/2,!1):this.kcc.disableAutostep();let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=_w(t.ground);r=e-(t.groundX??e),i=n-(t.groundY??n);let a=this.entries.get(t.ground);if(a&&t.groundRot!==void 0&&t.riderX!==void 0&&t.riderY!==void 0){let o=a.body.rotation()-t.groundRot,s=t.riderX-(t.groundX??e),c=t.riderY-(t.groundY??n);r+=s*Math.cos(o)-c*Math.sin(o)-s,i+=s*Math.sin(o)+c*Math.cos(o)-c}}else t.ground=null;let a=i<-.1&&e.isOnFloor?.()===!0&&n>0?0:n*this.lastDt,o={x:((e.velocity[0]??0)*this.lastDt+r)/Z*1,y:(a+i)/Z*1},s=t.body.translation().y*Z+fw(e),c=t=>{let r=this.byColliderHandle.get(t.handle);return!(r&&r!==e&&r.collider.oneWay===!0&&(n<0||s>pw(r)+dw))},l=this.jointed.get(e);this.kcc.setApplyImpulsesToDynamicBodies(e.pushes>0),e.pushes>0&&this.kcc.setCharacterMass(e.pushes),this.kcc.computeColliderMovement(t.collider,o,this.R.QueryFilterFlags.EXCLUDE_SENSORS,void 0,t=>{let n=this.byColliderHandle.get(t.handle);return!e.collideWithCharacters&&n instanceof LC||n&&l?.get(n)===!1?!1:c(t)});let u=this.kcc.computedMovement(),d=t.body.translation();t.body.setNextKinematicTranslation({x:d.x+u.x,y:d.y+u.y}),e._grounded=this.kcc.computedGrounded(),e._onWall=0,e._onCeiling=!1;let f=this.kcc.numComputedCollisions();for(let t=0;t<f;t++){let n=this.kcc.computedCollision(t)?.normal1;n&&(n.y>.7?e._grounded||(e._onCeiling=!0):Math.abs(n.x)>.7&&(e._onWall=n.x>0?-1:1))}if(e._grounded){let n=(d.x+u.x)*Z,r=(d.y+u.y)*Z+fw(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&this.canCarry(e,i.node)){t.ground=i.node;let[r,a]=_w(i.node);t.groundX=r,t.groundY=a,t.groundRot=this.entries.get(i.node)?.body.rotation(),t.riderX=n,t.riderY=(d.y+u.y)*Z+fw(e)}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope?this.scopedLines(this.debugScope):this.world.debugRender().vertices,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]*Z;return t}scopedLines(e){let t=[],n=[],r=e=>{let t=this.entries.get(e);t&&n.push(t.body);for(let t of e.children)r(t)};r(e);for(let t=e.parent;t&&n.length===0;t=t.parent){let e=this.entries.get(t);e&&n.push(e.body)}for(let e of n)for(let n=0;n<e.numColliders();n++){let r=e.collider(n);if(!r)continue;let i=r.translation(),a=r.rotation(),o=Math.cos(a),s=Math.sin(a),c=(e,n)=>{t.push(i.x+e*o-n*s,i.y+e*s+n*o)},l=(e,t,n,r)=>{c(e,t),c(n,r)},u=r.shape;if(u.halfExtents){let{x:e,y:t}=u.halfExtents;l(-e,-t,e,-t),l(e,-t,e,t),l(e,t,-e,t),l(-e,t,-e,-t)}else if(u.radius!==void 0){let e=u.radius,t=u.halfHeight??0;for(let n=0;n<24;n++){let r=n/24*Math.PI*2,i=(n+1)/24*Math.PI*2,a=e=>e>=0?t:-t;l(Math.cos(r)*e,Math.sin(r)*e+a(Math.sin(r)),Math.cos(i)*e,Math.sin(i)*e+a(Math.sin(i)))}t>0&&(l(-e,-t,-e,t),l(e,-t,e,t))}}return new Float32Array(t)}syncJoints(e){let t=this.R;if(e){for(let[e,t]of this.joints)if(!this.jointSet.has(e)){this.world.removeImpulseJoint(t,!0),this.joints.delete(e);let n=this.jointBodies.get(e);n&&this.unlinkJointed(n[0],n[1]),this.jointBodies.delete(e),this.hingeState.delete(e),this.tetherState.delete(e)}}for(let e of this.jointSet){if(this.joints.has(e)||this.refusedJoints.has(e))continue;let{a:n,b:r}=e._resolveBodies(),i=this.entries.get(n),a=this.entries.get(r);if(!i||!a)continue;if(e.type===`prismatic`){let t=Math.abs(i.body.rotation()-a.body.rotation())/ow;if(t=Math.abs((t+180)%360-180),t>.5){this.refusedJoints.add(e),z(this.engine,`error`,`[incanto] Joint2D '${e.getPath()}': its two bodies disagree about the slide axis by ${t.toFixed(1)}° — '${n.name}' and '${r.name}' are authored with different rotations, and Rapier reads the axis in BOTH bodies' local frames. Give both bodies the same rotation. The joint was not made.`);continue}}let o={x:(e.anchor[0]??0)/Z,y:(e.anchor[1]??0)/Z},s={x:(e.targetAnchor[0]??0)/Z,y:(e.targetAnchor[1]??0)/Z},c=e.length/Z;if(e.length===0&&(e.type===`rope`||e.type===`spring`)){let e=i.body.translation(),t=a.body.translation();c=Math.hypot(t.x-e.x,t.y-e.y)}let l;if(e.type===`fixed`)l=t.JointData.fixed(o,0,s,0);else if(e.type===`rope`)l=t.JointData.rope(c,o,s);else if(e.type===`spring`)l=t.JointData.spring(c,e.stiffness,e.damping,o,s);else if(e.type===`prismatic`){let n=e.axis[0]??0,r=e.axis[1]??0,i=Math.hypot(n,r)||1;l=t.JointData.prismatic(o,s,{x:n/i,y:r/i})}else l=t.JointData.revolute(o,s);let u=this.world.createImpulseJoint(l,i.body,a.body,!0);(e.type===`revolute`||e.type===`prismatic`)&&this.applyHinge(e,u,!0);let d=nw(e.type,e.collide);u.setContactsEnabled(d),this.joints.set(e,u),this.jointBodies.set(e,[n,r]),this.linkJointed(n,r,d),(e.type===`rope`||e.type===`spring`)&&this.tetherState.set(e,this.tetherKey(e))}for(let[e,t]of this.joints){if(e.type!==`rope`&&e.type!==`spring`)continue;let n=this.tetherKey(e);if(this.tetherState.get(e)===n)continue;this.world.removeImpulseJoint(t,!0),this.joints.delete(e);let r=this.jointBodies.get(e);r&&this.unlinkJointed(r[0],r[1]),this.jointBodies.delete(e),this.tetherState.delete(e)}for(let[e,t]of this.joints){if(e.type!==`revolute`&&e.type!==`prismatic`)continue;this.applyHinge(e,t,!1);let n=this.jointBodies.get(e),r=n&&this.entries.get(n[0]),i=n&&this.entries.get(n[1]);if(!(!r||!i))if(e.type===`revolute`){let t=(r.body.rotation()-i.body.rotation())/ow;t=((t+180)%360+360)%360-180,e.angle=t}else{let t=r.body.rotation(),n=i.body.rotation(),a=r.body.translation(),o=i.body.translation(),[s,c]=[e.anchor[0]??0,e.anchor[1]??0],[l,u]=[e.targetAnchor[0]??0,e.targetAnchor[1]??0],d=a.x*Z+s*Math.cos(t)-c*Math.sin(t),f=a.y*Z+s*Math.sin(t)+c*Math.cos(t),p=o.x*Z+l*Math.cos(n)-u*Math.sin(n),m=o.y*Z+l*Math.sin(n)+u*Math.cos(n),[h,g]=[e.axis[0]??0,e.axis[1]??0],_=Math.hypot(h,g)||1,v=(h*Math.cos(t)-g*Math.sin(t))/_,y=(h*Math.sin(t)+g*Math.cos(t))/_;e.travel=(d-p)*v+(f-m)*y}}}overlaps=new Map;trackOverlap(e,t,n){let r=this.overlaps.get(e);n?(r||(r=new Set,this.overlaps.set(e,r)),r.add(t)):r&&(r.delete(t),r.size===0&&this.overlaps.delete(e))}forgetOverlaps(e){this.overlaps.delete(e);for(let[t,n]of this.overlaps)n.delete(e),n.size===0&&this.overlaps.delete(t)}releaseOverlaps(e){let t=this.overlaps.get(e);if(!(!t||t.size===0))for(let n of[...t]){this.trackOverlap(e,n,!1),this.trackOverlap(n,e,!1);try{e.emit(`triggerExit`,n),n.emit(`triggerExit`,e)}catch(t){z(this.engine,`error`,`incanto: error in a 'triggerExit' handler (${e.name} ↔ ${n.name}):`,t)}}}armOverlaps(e,t){let n=[],r=t.translation();this.world.intersectionsWithShape({x:r.x,y:r.y},t.rotation(),t.shape,t=>{let r=this.byColliderHandle.get(t.handle);return r&&r!==e&&t.isEnabled()&&n.push(r),!0},void 0,void 0,t);for(let t of n)if(!this.overlaps.get(e)?.has(t)){this.trackOverlap(e,t,!0),this.trackOverlap(t,e,!0);try{e.emit(`triggerEnter`,t),t.emit(`triggerEnter`,e)}catch(n){z(this.engine,`error`,`incanto: error in a 'triggerEnter' handler (${e.name} ↔ ${t.name}):`,n)}}}pruneOverlaps(){for(let[e,t]of this.overlaps){if(e.tree===null){this.overlaps.delete(e);continue}for(let e of t)e.tree===null&&t.delete(e);t.size===0&&this.overlaps.delete(e)}}overlapping(e){let t=this.overlaps.get(e);if(!t)return[];for(let e of t)e.tree===null&&t.delete(e);return[...t]}massOf(e){return this.entries.get(e)?.body.mass()??1}rotationOf(e){let t=this.entries.get(e);return t?t.body.rotation()/ow:0}velocityOf(e){let t=this.entries.get(e)?.body.linvel();return t?[t.x*Z,t.y*Z]:[0,0]}applyImpulse(e,t){let n=this.entries.get(e);if(n){if(e instanceof IC){let t=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(t!==n.lastVX||r!==n.lastVY)&&n.body.setLinvel({x:t/Z,y:r/Z},!0)}if(n.body.applyImpulse({x:t[0]/Z,y:t[1]/Z},!0),e instanceof IC){let t=n.body.linvel();e.linearVelocity=[t.x*Z,t.y*Z],n.lastVX=e.linearVelocity[0]??0,n.lastVY=e.linearVelocity[1]??0}}}castRay(e,t,n,r,i){let a=Math.hypot(t[0],t[1]);if(!(a>0))return null;let o=new this.R.Ray({x:e[0]/Z,y:e[1]/Z},{x:t[0]/a,y:t[1]/a}),s=r?this.entries.get(r)?.collider:void 0,c=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castRayAndGetNormal(o,n/Z,!0,c,void 0,s,void 0,e=>!e.isSensor());if(!l)return null;let u=l.timeOfImpact*Z;return{distance:u,normal:[l.normal.x,l.normal.y],node:this.byColliderHandle.get(l.collider.handle)??null,point:[e[0]+t[0]/a*u,e[1]+t[1]/a*u]}}castSphere(e,t,n,r,i,a){let o=this.R,s=Math.hypot(t[0],t[1]);if(!(s>0))return null;let c=i?this.entries.get(i):void 0,l=a?.staticOnly?o.QueryFilterFlags.EXCLUDE_DYNAMIC|o.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,u=this.world.castShape({x:e[0]/Z,y:e[1]/Z},0,{x:t[0]/s,y:t[1]/s},new o.Ball(n/Z),0,r/Z,!0,l,void 0,c?.collider,c?.body,e=>!e.isSensor());return u?{distance:u.time_of_impact*Z,node:this.byColliderHandle.get(u.collider.handle)??null}:null}dispose(){this.disconnect(),this.disconnectScene(),this.unregisterDebug(),this.engine.physics===this&&(this.engine.physics=null),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;jointBodies=new Map;hingeState=new Map;refusedJoints=new Set;tetherState=new Map;tetherKey(e){return`${e.length}/${e.stiffness}/${e.damping}`}jointed=new Map;linkJointed(e,t,n){for(let[r,i]of[[e,t],[t,e]]){let e=this.jointed.get(r);e||(e=new Map,this.jointed.set(r,e)),e.set(i,n)}}unlinkJointed(e,t){this.jointed.get(e)?.delete(t),this.jointed.get(t)?.delete(e)}applyHinge(e,t,n){let r=JSON.stringify(e.limits),i=`${e.motorSpeed}/${e.motorStrength}`,a=this.hingeState.get(e),o=t,s=e.type===`revolute`?ow:1/Z;if(n||a?.limits!==r)if(e.limits.length===2){let t=(e.limits[0]??0)*s,n=(e.limits[1]??0)*s;o.setLimits(-Math.max(t,n),-Math.min(t,n))}else n||o.setLimits(-1e9,1e9);if((n||a?.motor!==i)&&(e.motorSpeed===0?n||o.configureMotorVelocity(0,0):o.configureMotorVelocity(-e.motorSpeed*s,e.motorStrength)),this.hingeState.set(e,{limits:r,motor:i}),e.motorSpeed!==0){let t=this.jointBodies.get(e);for(let e of t??[]){let t=this.entries.get(e);t&&!t.body.isFixed()&&t.body.isSleeping()&&t.body.wakeUp()}}}bodySet=new Set;poseFromTree(){for(let[e,t]of this.entries){let[n,r,i]=gw(e);t.body.setTranslation({x:n/Z,y:r/Z},!1),t.body.setRotation(i*ow,!1)}this.world.propagateModifiedBodyPositionsToColliders()}syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=e.root===this.lastRoot,r=t!==this.lastStructure||!n;if(r){let r=n?e.tree._structureSince(this.lastStructure):null;if(this.lastStructure=t,this.lastRoot=e.root,r){let t=!1;for(let{node:e,added:n}of r)e instanceof NC&&(n?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof aw&&(t=!0);t&&(this.jointSet.clear(),lw(e.root,this.jointSet))}else this.bodySet.clear(),uw(e.root,this.bodySet),this.jointSet.clear(),lw(e.root,this.jointSet)}let i=this.bodySet;for(let e of i){if(e.collider.shape===void 0){let t=this.entries.get(e);t&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.warnedNoCollider.has(e)||(this.warnedNoCollider.add(e),z(this.engine,`warn`,`[incanto] '${e.name}' has no collider — physics skips it.`));continue}let t=this.entries.get(e);t&&e._colliderChanged&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.ensureEntry(e)}if(this.syncJoints(r),r)for(let[e,t]of this.entries)i.has(e)||(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),this.forgetOverlaps(e),e._physics=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let[r,i,a]=gw(e),o=r/Z,s=i/Z,c,l=e instanceof IC;c=l?n.RigidBodyDesc.dynamic():e instanceof LC||e instanceof FC?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),c.setTranslation(o,s).setRotation(a*ow),e instanceof IC&&(c.setGravityScale(e.gravityScale),c.setLinearDamping(e.linearDamping).setAngularDamping(e.angularDamping),c.setLinvel((e.linearVelocity[0]??0)/Z,(e.linearVelocity[1]??0)/Z),c.setAngvel(e.fixedRotation?0:e.angularVelocity),e.fixedRotation&&c.lockRotations());let u=this.world.createRigidBody(c),d=yw(n,e.collider,e.name);d.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),d.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof FC&&d.setSensor(!0),e instanceof IC&&d.setMass(e.mass),(e instanceof IC||e instanceof PC)&&xw(n,d,e);let f=this.world.createCollider(d,u);return t={body:u,collider:f,lastX:r,lastY:i,lastRot:a,lastVX:0,lastVY:0,lastAV:l?e.angularVelocity:0,lastMass:l?e.mass:1,lastFriction:e.friction??.5,lastRestitution:e.restitution??0,lastGravityScale:l?e.gravityScale:1,lastLinDamp:l?e.linearDamping:0,lastAngDamp:l?e.angularDamping:0},this.entries.set(e,t),this.byColliderHandle.set(f.handle,e),e.enabled||(f.setEnabled(!1),u.setEnabled(!1)),e._colliderChanged=!1,e._enabledChanged=!1,e._physics=this,t}e._enabledChanged&&(e.enabled||this.releaseOverlaps(e),t.collider.setEnabled(e.enabled),t.body.setEnabled(e.enabled),e._enabledChanged=!1,e.enabled&&this.armOverlaps(e,t.collider));let[r,i,a]=gw(e);if((r!==t.lastX||i!==t.lastY)&&(t.body.setTranslation({x:r/Z,y:i/Z},!0),t.lastX=r,t.lastY=i),a!==t.lastRot&&(t.body.setRotation(a*ow,!0),t.lastRot=a),e instanceof IC){let n=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(n!==t.lastVX||r!==t.lastVY)&&(t.body.setLinvel({x:n/Z,y:r/Z},!0),t.lastVX=n,t.lastVY=r),e.angularVelocity!==t.lastAV&&(t.body.setAngvel(e.angularVelocity,!0),t.lastAV=e.angularVelocity),e.gravityScale!==t.lastGravityScale&&(t.body.setGravityScale(e.gravityScale,!0),t.lastGravityScale=e.gravityScale),e.mass!==t.lastMass&&(t.collider.setMass(e.mass),t.lastMass=e.mass),(e.friction!==t.lastFriction||e.restitution!==t.lastRestitution)&&(xw(this.R,t.collider,e),t.lastFriction=e.friction,t.lastRestitution=e.restitution),e.linearDamping!==t.lastLinDamp&&(t.body.setLinearDamping(e.linearDamping),t.lastLinDamp=e.linearDamping),e.angularDamping!==t.lastAngDamp&&(t.body.setAngularDamping(e.angularDamping),t.lastAngDamp=e.angularDamping)}else e instanceof PC&&(e.friction!==t.lastFriction||e.restitution!==t.lastRestitution)&&(xw(this.R,t.collider,e),t.lastFriction=e.friction,t.lastRestitution=e.restitution);return t}};function lw(e,t){e instanceof aw&&t.add(e);for(let n of e.children)lw(n,t)}function uw(e,t){e instanceof NC&&t.add(e);for(let n of e.children)uw(n,t)}var dw=4;function fw(e){let t=e.collider;return t.shape===`rect`?(t.size?.[1]??32)/2:t.shape===`capsule`?(t.height??32)/2+(t.radius??8):t.radius??16}function pw(e){let[,t]=_w(e),n=e.collider;return t-(n.shape===`rect`?(n.size?.[1]??32)/2:n.shape===`capsule`?(n.height??32)/2+(n.radius??8):n.radius??16)}var mw=[],hw=[0,0,0];function gw(e){mw.length=0;for(let t=e;t;t=t.parent)t instanceof MC&&mw.push(t);let t=0,n=0,r=0;for(let e=mw.length-1;e>=0;e--){let i=mw[e],a=i.position[0]??0,o=i.position[1]??0;if(r!==0){let e=r*ow,i=Math.cos(e),s=Math.sin(e);t+=a*i-o*s,n+=a*s+o*i}else t+=a,n+=o;r+=i.rotation}return hw[0]=t,hw[1]=n,hw[2]=r,hw}function _w(e){let t=gw(e);return[t[0],t[1]]}function vw(e){let t=null;for(let n=e.parent;n;n=n.parent)if(n instanceof MC){t=n;break}let n=gw(t);return[n[0],n[1],n[2]]}function yw(e,t,n){jC(t,n);let r=bw(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Z,(i[1]??0)/Z),r}function bw(e,t,n){let r=t.shape;if(r===`rect`){let r=t.size;if(!Array.isArray(r)||r.length!==2||r.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${n}': rect needs "size": [width, height].`);return e.ColliderDesc.cuboid(r[0]/2/Z,r[1]/2/Z)}if(r===`circle`){if(typeof t.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': circle needs "radius".`);return e.ColliderDesc.ball(t.radius/Z)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2/Z,t.radius/Z)}throw new L(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(r)}.`)}function xw(e,t,n){let r=e.CoefficientCombineRule;t.setFriction(n.friction),t.setFrictionCombineRule(n.friction===.5?r.Average:n.friction<.5?r.Min:r.Max),t.setRestitution(n.restitution),t.setRestitutionCombineRule(n.restitution>0?r.Max:r.Average)}function Sw(e){let t=[];for(let n=2;n<=32;n++)e%n===0&&t.push(e/n);return t.sort((e,t)=>t-e).slice(0,6)}function Cw(e,t,n,r,i,a,o=`frame`){if(!r||!i||!t||!n)return null;if(r%t!==0||i%n!==0){let a=[];if(r%t!==0){let e=Sw(r);a.push(`${r} px wide is not a whole number of ${t} px frames`+(e.length>0?` (${e.join(`, `)} would divide it)`:``))}if(i%n!==0){let e=Sw(i);a.push(`${i} px tall is not a whole number of ${n} px frames`+(e.length>0?` (${e.join(`, `)} would divide it)`:``))}return`[incanto] spritesheet '${e}' does not fit its frame size: ${a.join(`; `)}. Every row after the first is cut off centre.`}if(a!==void 0){let s=r/t*(i/n);if(a>=s){let t=o===`tile`?`tile atlas`:`spritesheet`,n=o===`tile`?`a cell asks for tile`:`an animation asks for frame`;return`[incanto] ${t} '${e}' has ${s} ${o}s (0–${s-1}), and ${n} ${a}. Those ${o}s draw whatever is at the wrong end of the sheet.`}}return null}var ww=new Zf(1,1),Tw=class extends MC{static typeName=`Sprite2D`;static props={texture:{default:``,asset:{kind:`texture`,refOnly:!0}},anchor:{default:[.5,.5]},flipX:{default:!1},flipY:{default:!1},tint:{default:`#ffffff`},opacity:{default:1,range:{min:0,max:1}}};texture=``;anchor=[.5,.5];flipX=!1;flipY=!1;tint=`#ffffff`;opacity=1;quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Ld(ww,new Td({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_createObject2D(){return super._createObject2D()}resolveTexture(e){if(!this.texture||!e)return null;let t=e.getTexture(this.texture),n=t.image;return!n?.width||!n.height?null:{texture:t,width:n.width,height:n.height}}_staticReady(e){return this.texture===``||this.resolveTexture(e)!==null}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=t.material,r=this.resolveTexture(e);if(!r){t.visible=!1;return}t.visible=!0,n.map!==r.texture&&(n.map=r.texture,n.needsUpdate=!0);let i=r.width,a=r.height;t.scale.set(this.flipX?-i:i,this.flipY?-a:a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??.5;t.position.set((.5-o)*i,(s-.5)*a,0),t.renderOrder=this.effectiveRenderOrder,n.color.set(this.tint),n.opacity=this.opacity}free(){(this.quadMesh?.material)?.dispose(),this.quadMesh=null,super.free()}},Ew=class extends Tw{static typeName=`AnimatedSprite2D`;static signals=[`animationFinished`];static props={sheet:{default:``,asset:{kind:`spritesheet`,refOnly:!0}},animations:{default:{}},autoplay:{default:``}};sheet=``;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;currentDef=null;ownTexture=null;loadedSheetRef=``;play(e){let{name:t,def:n}=Fo(this.animations,e,this.name);this.currentAnimation=t,this.currentDef=n,this.frameList=Ro(n.frames,t),this.frameIndex=0,this.currentFrame=this.frameList[0]??0,this.frameTime=0,this.playing=!0}stop(){this.playing=!1}onReady(){Lo(this.animations,this.name),this.autoplay&&this.play(this.autoplay)}update(e){if(!this.playing||this.currentAnimation===``)return;let t=this.currentDef;if(!t||!Number.isFinite(t.fps)||t.fps<=0)return;let n=1/t.fps;for(this.frameTime+=e;this.frameTime>=n;)if(this.frameTime-=n,this.frameIndex+=1,this.frameIndex>=this.frameList.length)if(t.loop)this.frameIndex=0;else{this.frameIndex=this.frameList.length-1,this.playing=!1,this.emit(`animationFinished`,this.currentAnimation);break}this.currentFrame=this.frameList[this.frameIndex]??0}gridChecked=``;checkGrid(e,t,n,r,i){if(this.gridChecked===e)return;this.gridChecked=e;let a=0;for(let[e,t]of Object.entries(this.animations))if(typeof t!=`string`)try{for(let n of Ro(t.frames,e))n>a&&(a=n)}catch{return}let o=Cw(e,t,n,r,i,a);o&&z(this.tree?.engine??null,`error`,o)}resolveTexture(e){if(!this.sheet||!e)return null;let t=e.getSheet(this.sheet);this.loadedSheetRef!==this.sheet&&(this.ownTexture=t.texture.clone(),this.ownTexture.needsUpdate=!0,this.loadedSheetRef=this.sheet);let n=this.ownTexture,r=t.texture.image;if(!r?.width||!r.height)return null;this.checkGrid(this.sheet,t.frameWidth,t.frameHeight,r.width,r.height);let i=Math.max(1,Math.floor(r.width/t.frameWidth)),a=this.currentFrame%i,o=Math.floor(this.currentFrame/i);return n.repeat.set(t.frameWidth/r.width,t.frameHeight/r.height),n.offset.set(a*t.frameWidth/r.width,1-(o+1)*t.frameHeight/r.height),{texture:n,width:t.frameWidth,height:t.frameHeight}}},Dw=class e extends MC{static typeName=`Camera2D`;static props={follow:{default:``,nodePath:!0},smoothing:{default:0},zoom:{default:1},limits:{default:[]},current:{default:!1},blendSeconds:{default:0,range:{min:0}}};follow=``;smoothing=0;zoom=1;limits=[];current=!1;makeCurrent(t=void 0){let n=this.tree?.root??this.getRoot(),r=t=>{t instanceof e&&(t.current=t===this);for(let e of t.children)r(e)};r(n),this.current=!0,this._blendRequest=t}blendSeconds=0;_blendRequest=void 0;get effectiveZoom(){return Math.max(.01,this.zoom)}warnedFollow=``;update(e){if(!this.follow)return;let t=this.getNodeOrNull(this.follow);if(!(t instanceof MC)){if(this.warnedFollow!==this.follow){this.warnedFollow=this.follow;let e=t?`a ${t.constructor.typeName??`Node`}`:`nothing`;z(this.tree?.engine??null,`warn`,`[incanto] ${this.getPath()}: follow '${this.follow}' is ${e}, which has no position for the camera to track — the view will not move. Point it at a Node2D.`)}return}let[n=0,r=0]=B(t),[i=0,a=0]=B(this),o=Math.min(Math.max(this.smoothing,0),.99),s=o<=0?1:1-o**(e*60),[c=0,l=0]=Ba(this,[i+(n-i)*s,a+(r-a)*s]);this.position=[c,l]}clampedCenter(e,t){let n=B(this),r=n[0]??0,i=n[1]??0;if(this.limits.length!==0&&this.limits.length!==4)throw new L(`BAD_FORMAT`,`Camera2D '${this.name}' limits must be [] or [minX,minY,maxX,maxY], got length ${this.limits.length}.`);if(this.limits.length===4){let[n,a,o,s]=this.limits,c=e/(2*this.effectiveZoom),l=t/(2*this.effectiveZoom);r=Ow(r,n+c,o-c),i=Ow(i,a+l,s-l)}return{x:r,y:i}}};function Ow(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var kw={moveAction:`move`,jumpAction:`jump`,dashAction:`dash`,crouchAction:`crouch`},Aw=class extends Ht{static typeName=`CharacterController2D`;static props={mode:{default:`platformer`,options:[`platformer`,`topDown`]},maxSpeed:{default:220},jumpHeight:{default:64},moveAction:{default:`move`},jumpAction:{default:`jump`},coyoteSeconds:{default:0},jumpBufferSeconds:{default:0},jumpCutMultiplier:{default:1},maxJumps:{default:1},dashSpeed:{default:0},dashSeconds:{default:.15},dashAction:{default:`dash`},wallSlideSpeed:{default:0},wallJumpImpulse:{default:[0,0]},crouchHeight:{default:0,range:{min:0}},crouchSpeedMultiplier:{default:.5,range:{min:0}},crouchAction:{default:`crouch`}};static signals=[`movementStateChanged`];mode=`platformer`;maxSpeed=220;jumpHeight=64;moveAction=`move`;jumpAction=`jump`;coyoteSeconds=0;jumpBufferSeconds=0;jumpCutMultiplier=1;maxJumps=1;dashSpeed=0;dashSeconds=.15;dashAction=`dash`;crouchHeight=0;crouchSpeedMultiplier=.5;crouchAction=`crouch`;crouching=!1;standingHeight=0;wallSlideSpeed=0;wallJumpImpulse=[0,0];state=`idle`;coyoteLeft=0;bufferLeft=0;jumpsUsed=0;dashLeft=0;dashDir=1;rising=!1;onReady(){if(!(this.parent instanceof LC))throw new L(`TREE_VIOLATION`,`CharacterController2D '${this.name}' must be a child of a CharacterBody2D (parent is '${this.parent?.name??`none`}').`);if(this.mode!==`platformer`&&this.mode!==`topDown`)throw new L(`PROP_TYPE_MISMATCH`,`CharacterController2D.mode must be 'platformer' or 'topDown', got '${this.mode}'.`)}fixedUpdate(e){let t=this.tree?.engine;if(!t?.scene)return;let n=this.parent;if(!(n instanceof LC))return;let r=t.input,i=this.readAction(`moveAction`,()=>r.getVector(this.moveAction),{x:0,y:0},`the character will not move`),a=ny(n)?.health??null;(a?.staggered??!1)&&(i.x=0,i.y=0);let o=a?.knocked?a.kickVelocity:[],s=a?.knocked?a.takeLift():0;if(this.mode===`topDown`){n.velocity=o.length>0?[o[0]??0,o[1]??0]:[i.x*this.maxSpeed,i.y*this.maxSpeed],n.moveAndSlide();return}let c=t.scene.physics?.gravity?.[1]??980,l=n.isOnFloor()&&!(this.rising&&(n.velocity[1]??0)<0),u=-Math.sqrt(2*c*this.jumpHeight);if(this.dashLeft>0){this.dashLeft-=e,n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}if(this.dashSpeed>0&&this.readAction(`dashAction`,()=>r.justPressed(this.dashAction),!1,`the character will never dash`)){this.dashLeft=this.dashSeconds,this.dashDir=i.x===0?this.dashDir:Math.sign(i.x),n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}n.velocity[0]=o.length>0?o[0]??0:i.x*this.maxSpeed;let d=this.crouchHeight>0&&this.readAction(`crouchAction`,()=>r.isPressed(this.crouchAction),!1,`the character will never crouch`);if(!this.crouching){let e=jw(n.collider);d&&l&&this.crouchHeight<e&&(this.standingHeight=e,this.crouching=!0,Nw(n,this.crouchHeight,e))}else if(!d){let e=this.standingHeight-this.crouchHeight,t=(n.position[1]??0)-Mw(n.collider)+1;n._physics?.castRay([n.position[0]??0,t],[0,-1],e+2,n)||(this.crouching=!1,Nw(n,this.standingHeight,this.crouchHeight))}this.crouching&&(n.velocity[0]=(n.velocity[0]??0)*this.crouchSpeedMultiplier),l?(this.coyoteLeft=this.coyoteSeconds,this.jumpsUsed=0):(this.coyoteLeft=Math.max(0,this.coyoteLeft-e),this.coyoteLeft<=0&&this.jumpsUsed===0&&(this.jumpsUsed=1));let f=this.readAction(`jumpAction`,()=>r.justPressed(this.jumpAction),!1,`the character will never jump`);f?this.bufferLeft=Math.max(this.jumpBufferSeconds,0):this.bufferLeft=Math.max(0,this.bufferLeft-e);let p=this.bufferLeft>0||f;this.crouching&&(p=!1,this.bufferLeft=0);let m=this.wallSlideSpeed>0||this.wallJumpImpulse.some(e=>e!==0)?n.isOnWall():!1;if(p&&m&&!l&&this.wallJumpImpulse.some(e=>e!==0)){let e=-n.wallSide();n.velocity[0]=e*(this.wallJumpImpulse[0]??0),n.velocity[1]=-(this.wallJumpImpulse[1]??0),this.bufferLeft=0,this.rising=!0,this.jumpsUsed=1}else if(p&&(l||this.coyoteLeft>0||this.jumpsUsed<this.maxJumps))n.velocity[1]=u,this.bufferLeft=0,this.coyoteLeft=0,this.rising=!0,this.jumpsUsed=l?1:this.jumpsUsed+1;else if(l)n.velocity[1]=20,this.rising=!1;else{n.velocity[1]=(n.velocity[1]??0)+c*e;let t=this.readAction(`jumpAction`,()=>r.isPressed(this.jumpAction),!1,`the character will never jump`);this.rising&&this.jumpCutMultiplier<1&&!t&&(n.velocity[1]=(n.velocity[1]??0)*this.jumpCutMultiplier,this.rising=!1),(n.velocity[1]??0)>=0&&(this.rising=!1),this.wallSlideSpeed>0&&m&&(n.velocity[1]??0)>this.wallSlideSpeed&&(n.velocity[1]=this.wallSlideSpeed)}s!==0&&(n.velocity[1]=s,s<0&&(this.rising=!0)),n.isOnCeiling()&&(n.velocity[1]??0)<0&&(n.velocity[1]=0,this.rising=!1),n.moveAndSlide();let h=n.velocity[1]??0;if(this.wallSlideSpeed>0&&!n.isOnFloor()&&n.isOnWall()&&h>0)this.setState(`wallSlide`);else if(n.isOnFloor()){let e=Math.abs(i.x)>.01;this.setState(this.crouching?e?`sneak`:`crouch`:e?`run`:`idle`)}else this.setState(h<0?`jump`:`fall`)}setState(e){e!==this.state&&(this.state=e,this.emit(`movementStateChanged`,e))}reportedActions=new Set;readAction(e,t,n,r){let i=this[e];return SS({engine:this.tree?.engine,who:this.getPath(),reported:this.reportedActions,consequence:r,authored:i!==kw[e]},i,t,n)}};function jw(e){return e.shape===`rect`?e.size?.[1]??0:e.shape===`capsule`?e.height??0:0}function Mw(e){return e.shape===`rect`?(e.size?.[1]??0)/2:e.shape===`capsule`?(e.height??0)/2+(e.radius??0):e.radius??0}function Nw(e,t,n){let r=e.collider;if(r.shape===`rect`){let i=r.size??[32,n];e.collider={...r,size:[i[0]??32,t]}}else if(r.shape===`capsule`)e.collider={...r,height:t};else return;let i=(n-t)/2,a=e.position;e.position=[a[0]??0,(a[1]??0)+i]}var Pw=new Zf(1,1),Fw=class extends MC{static typeName=`ColorRect2D`;static props={size:{default:[100,100]},color:{default:`#ffffff`},opacity:{default:1,range:{min:0,max:1}},anchor:{default:[.5,.5]}};size=[100,100];color=`#ffffff`;opacity=1;anchor=[.5,.5];quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Ld(Pw,new Td({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=this.size[0]??0,r=this.size[1]??0;t.visible=n>0&&r>0&&this.opacity>0,t.scale.set(n,r,1);let i=this.anchor[0]??.5,a=this.anchor[1]??.5;t.position.set((.5-i)*n,(a-.5)*r,0),t.renderOrder=this.effectiveRenderOrder;let o=t.material;o.color.set(this.color),o.opacity=this.opacity}free(){(this.quadMesh?.material)?.dispose(),this.quadMesh=null,super.free()}},Iw=new Zf(1,1),Lw=class extends MC{static typeName=`Label`;static props={text:{default:``},fontSize:{default:16},color:{default:`#ffffff`},font:{default:`monospace`},align:{default:`left`},opacity:{default:1,range:{min:0,max:1}}};text=``;fontSize=16;color=`#ffffff`;font=`monospace`;align=`left`;opacity=1;quadMesh=null;canvas=null;lastKey=``;_quad(){return this.quadMesh||(this.quadMesh=new Ld(Iw,new Td({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=et(this,this.text);if(typeof document>`u`||n===``){t.visible=!1;return}let r=`${n}\0${this.fontSize}\0${this.color}\0${this.font}\0${this.align}`;r!==this.lastKey&&(this.lastKey=r,this.rasterize()),t.visible=this.opacity>0,t.material.opacity=this.opacity,t.renderOrder=this.effectiveRenderOrder}rasterize(){let e=et(this,this.text),t=Math.min(globalThis.devicePixelRatio??1,2);this.canvas??=document.createElement(`canvas`);let n=this.canvas.getContext(`2d`);if(!n)return;let r=`${this.fontSize*t}px ${this.font}`;n.font=r;let i=n.measureText(e),a=Math.max(1,Math.ceil(i.width)),o=Math.ceil(this.fontSize*t*1.4);this.canvas.width=a,this.canvas.height=o,n.font=r,n.fillStyle=this.color,n.textBaseline=`middle`,n.fillText(e,0,o/2);let s=this._quad(),c=s.material;c.map?.dispose();let l=new Vf(this.canvas);l.colorSpace=hc,c.map=l,c.needsUpdate=!0;let u=a/t,d=o/t;s.scale.set(u,d,1);let f=this.align===`center`?.5:+(this.align===`right`);s.position.set((.5-f)*u,0,0)}free(){let e=this.quadMesh;if(e){let t=e.material;t.map?.dispose(),t.dispose(),e.removeFromParent(),this.quadMesh=null}this.canvas=null,super.free()}},Rw=new Zf(1,1),zw=class e extends MC{orderGroup=`effects`;static typeName=`Particles2D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...ko]},emitting:{default:!0},worldSpace:{default:!1},rate:{default:40},burst:{default:0},lifetime:{default:[.6,1.2]},speed:{default:[40,120]},directionDeg:{default:-90},spreadDeg:{default:30},gravity:{default:[0,0]},drag:{default:0},sizeStart:{default:8},sizeEnd:{default:2},colorStart:{default:`#ffffff`},colorEnd:{default:`#ffffff`},paletteColors:{default:[]},alphaStart:{default:1,range:{min:0,max:1}},alphaEnd:{default:0,range:{min:0,max:1}},shimmer:{default:0},blend:{default:`add`,options:[`add`,`normal`]},maxParticles:{default:256},emitBox:{default:[0,0]},drift:{default:[0,0]}};preset=`custom`;emitting=!0;worldSpace=!1;rate=40;burst=0;lifetime=[.6,1.2];speed=[40,120];directionDeg=-90;spreadDeg=30;gravity=[0,0];drag=0;sizeStart=8;sizeEnd=2;colorStart=`#ffffff`;colorEnd=`#ffffff`;paletteColors=[];alphaStart=1;alphaEnd=0;shimmer=0;blend=`add`;maxParticles=256;emitBox=[0,0];drift=[0,0];static validateJson(e){let t=e;if(t.preset!==`custom`&&!ko.includes(t.preset))throw new L(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${ko.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:ko});if(t.blend!==`add`&&t.blend!==`normal`)throw new L(`BAD_FORMAT`,`Particles2D '${e.name}' blend must be 'add' or 'normal', got '${t.blend}'.`,{prop:`blend`,validOptions:[`add`,`normal`]})}sim=null;bursted=!1;finishedEmitted=!1;_ensureSim(){if(!this.sim){Ao(this,this.preset,ht(e.typeName));let t=WS(this);this.sim=new Mo({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[this.speed[0]??0,this.speed[1]??0],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[this.gravity[0]??0,this.gravity[1]??0,0],drag:this.drag,maxParticles:this.maxParticles,emitBox:[this.emitBox[0]??0,this.emitBox[1]??0,0],drift:[this.drift[0]??0,this.drift[1]??0,0]},t)}return this.sim}get aliveCount(){return this.sim?.count??0}particles(){let e=[];return this.sim?.forEach(t=>{e.push({...t})}),e}lastWorld=null;wasEmitting=!1;update(e){let t=this._ensureSim();this.holdWorldSpace(t),t.setRate(this.emitting?this.rate:0),this.burst>0&&!this.bursted&&(this.emitting||this.armedByReplay)&&(this.bursted=!0,this.armedByReplay=!1,t.burst(this.burst),this.report(`burst`,this.burst));let n=this.emitting&&this.rate>0;n!==this.wasEmitting&&(this.wasEmitting=n,n&&this.report(`emit`,this.rate)),t.update(e),(!this.emitting||this.rate===0)&&this.bursted&&t.done&&!this.finishedEmitted&&(this.finishedEmitted=!0,this.emit(`finished`))}holdWorldSpace(e){if(!this.worldSpace){this.lastWorld=null;return}let t=0,n=0;for(let e=this;e;e=e.parent)e instanceof MC&&(t+=e.position[0]??0,n+=e.position[1]??0);let r=this.lastWorld;r&&e.translateAll(r[0]-t,r[1]-n,r[2]-0),this.lastWorld=[t,n,0]}meshKey=``;free(){this.mesh&&=(this.mesh.removeFromParent(),Bw(this.mesh),null),super.free()}report(e,t){let n=this.tree?.engine;n?.effects.record({kind:e,name:this.preset,from:this.getPath(),wiredAs:this.wiringPath(),amount:t,at:n.time})}replay(){this.bursted=!1,this.finishedEmitted=!1,this.armedByReplay=!0}armedByReplay=!1;mesh=null;paletteCache=[];paletteCacheKey=``;refreshPalette(){let e=this.paletteColors;if(e.length===0)return null;let t=e.join(`|`);if(t!==this.paletteCacheKey){this.paletteCacheKey=t;for(let t=0;t<e.length;t++){let n=this.paletteCache[t];n||(n=new J,this.paletteCache[t]=n),n.set(e[t])}this.paletteCache.length=e.length}return this.paletteCache}_syncObject2D(e){super._syncObject2D(e);let t=this._ensureSim(),n=`${this.maxParticles}|${this.blend}`;if(!this.mesh||this.meshKey!==n){this.mesh&&(this.mesh.removeFromParent(),Bw(this.mesh)),this.meshKey=n;let e=new Td({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new uf(Rw,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(xc),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let r=this.mesh,i=this.refreshPalette(),a=i?null:Hw.set(this.colorStart),o=Uw.set(this.colorEnd),s=this.shimmer,c=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;Vw.makeScale(t,t,1),Vw.setPosition(e.x,-e.y,0),r.setMatrixAt(c,Vw);let n=i?i[Math.floor(e.seed*i.length)]:a,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);s>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*s+e.seed))),Ww.copy(n).lerp(o,e.t).multiplyScalar(l),r.setColorAt(c,Ww),c+=1}),r.count=c,r.instanceMatrix.needsUpdate=!0,r.instanceColor&&(r.instanceColor.needsUpdate=!0),r.renderOrder=this.effectiveRenderOrder}};function Bw(e){e.dispose();let t=e.material;for(let e of Array.isArray(t)?t:[t])e.dispose()}var Vw=new q,Hw=new J,Uw=new J,Ww=new J;function Gw(e,t){if(typeof t==`number`&&Number.isInteger(t)&&t>=-1)return t;throw new L(`PROP_TYPE_MISMATCH`,`TileMap2D: legend entry '${e}' must be a tile INDEX (a whole number, -1 for empty), got ${Kw(t)}. Solidity is the separate "solid" prop — a list of tile indices: "legend": { "${e}": 0 }, "solid": [0].`,{prop:`legend`})}function Kw(e){return e===null?`null`:Array.isArray(e)?`an array of ${e.length}`:typeof e==`object`?`an object (keys: ${Object.keys(e).join(`, `)})`:typeof e==`number`?`${e}`:`a ${typeof e}`}function qw(e,t){let n=[],r=0;for(let i of e){let e=[];if(typeof i==`string`)for(let n of i){let r=t[n];if(r!==void 0)e.push(Gw(n,r));else if(n===`.`||n===` `)e.push(-1);else if(n>=`0`&&n<=`9`)e.push(n.charCodeAt(0)-48);else throw new L(`BAD_FORMAT`,`TileMap2D: unknown tile char '${n}' — add it to "legend" (char → tile index), or use '.'/' ' for empty and digits 0-9.`)}else for(let t of i)e.push(t);r=Math.max(r,e.length),n.push(e)}for(let e of n)for(;e.length<r;)e.push(-1);return n}function Jw(e,t){let n=e.length,r=n>0?e[0].length:0,i=e.map(e=>e.map(()=>!1)),a=(n,r)=>t.has(e[r][n]),o=[];for(let e=0;e<n;e++)for(let t=0;t<r;t++){if(!a(t,e)||i[e][t])continue;let s=1;for(;t+s<r&&a(t+s,e)&&!i[e][t+s];)s++;let c=1;grow:for(;e+c<n;){for(let n=0;n<s;n++)if(!a(t+n,e+c)||i[e+c][t+n])break grow;c++}for(let n=0;n<c;n++)for(let r=0;r<s;r++)i[e+n][t+r]=!0;o.push({x:t,y:e,w:s,h:c})}return o}var Yw=1e6,Xw=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,Zw=class extends MC{static typeName=`TileMap2D`;static props={texture:{default:``,asset:{kind:`texture`,refOnly:!0}},tileSize:{default:32},columns:{default:0},cells:{default:[]},legend:{default:{}},colors:{default:{}},solid:{default:[]},opacity:{default:1,range:{min:0,max:1}}};texture=``;tileSize=32;columns=0;_cells=[];_legend={};_solid=[];geometryDirty=!0;gridChecked=``;collidersDirty=!0;builtScale=[1,1];get cells(){return this._cells}set cells(e){this._cells=e,this.geometryDirty=!0,this.collidersDirty=!0}get legend(){return this._legend}set legend(e){this._legend=e,this.geometryDirty=!0,this.collidersDirty=!0}_colors={};get colors(){return this._colors}set colors(e){this._colors=e,this.geometryDirty=!0,this.collidersDirty=!0}palette(){return Object.values(this._colors)}allChars(){let e={...this._legend};return Object.keys(this._colors).forEach((t,n)=>{e[t]=Yw+n}),e}solidIndices(){let e=this.allChars(),t=[];for(let n of this._solid)typeof n==`number`?t.push(n):e[n]===void 0?n.length===1&&n>=`0`&&n<=`9`&&t.push(n.charCodeAt(0)-48):t.push(e[n]);return t}get solid(){return this._solid}set solid(e){this._solid=e,this.collidersDirty=!0}opacity=1;tileMesh=null;builtColumns=0;builtRows=0;static validateJson(e){let t=e;for(let[n,r]of Object.entries(t._colors))if(!(typeof r==`string`&&Xw.test(r)))throw new L(`PROP_TYPE_MISMATCH`,`TileMap2D '${e.name}': "colors" ['${n}'] is ${JSON.stringify(r)} — a colour here is \`#rgb\` or \`#rrggbb\`, the same as every other colour prop.`,{prop:`colors`});if(t.texture!==``&&Object.keys(t._colors).length>0)throw new L(`PROP_TYPE_MISMATCH`,`TileMap2D '${e.name}': "colors" and "texture" are exclusive — colours are for a level authored before the art arrives. Drop one of them.`,{prop:`colors`});qw(t._cells,t.allChars())}grid(){return qw(this._cells,this.allChars())}cellAt(e,t){let n=B(this),[r,i]=this.scaledTile();if(!(r>0)||!(i>0))return null;let a=Math.floor((e-(n[0]??0))/r),o=Math.floor((t-(n[1]??0))/i),s=this.grid()[o];return!s||a<0||a>=s.length?null:[a,o]}scaledTile(){let[e=1,t=1]=this.scale;return[this.tileSize*Math.abs(e),this.tileSize*Math.abs(t)]}tileAt(e,t){return this.grid()[t]?.[e]??-1}worldAt(e,t){let n=B(this),[r,i]=this.scaledTile();return[(n[0]??0)+e*r+r/2,(n[1]??0)+t*i+i/2]}setTile(e,t,n){let r=this._cells[t];if(typeof r!=`string`||e<0||e>=r.length||n.length!==1)return!1;let i=this._cells.slice();return i[t]=`${r.slice(0,e)}${n}${r.slice(e+1)}`,this.cells=i,!0}onReady(){this.rebuildColliders()}update(e){let[t=1,n=1]=this.scale;(t!==this.builtScale[0]||n!==this.builtScale[1])&&(this.collidersDirty=!0),this.collidersDirty&&this.rebuildColliders()}rebuildColliders(){this.collidersDirty=!1;for(let e of[...this.children])e.name.startsWith(`__tileSolid`)&&e.free();if(this.builtScale=[this.scale[0]??1,this.scale[1]??1],this._solid.length===0)return;let e=this.tileSize,[t,n]=this.builtScale;Jw(this.grid(),new Set(this.solidIndices())).forEach((r,i)=>{let a=new PC(`__tileSolid${i}`);a.position=[(r.x+r.w/2)*e*t,(r.y+r.h/2)*e*n],a.collider={shape:`rect`,size:[r.w*e*t,r.h*e*n]},this.addChild(a)})}_mesh(){return this.tileMesh||(this.tileMesh=new Ld(new dd,new Td({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.tileMesh)),this.tileMesh}_staticReady(e){return this.texture===``||!e?this.texture===``:!!e.getTexture(this.texture).image?.width}_syncObject2D(e){super._syncObject2D(e);let t=this._mesh(),n=t.material;if(Object.keys(this._colors).length>0){if(t.visible=this.opacity>0,t.renderOrder=this.effectiveRenderOrder,n.opacity=this.opacity,(n.map!==null||!n.vertexColors)&&(n.map=null,n.vertexColors=!0,n.needsUpdate=!0,this.geometryDirty=!0),!this.geometryDirty)return;this.geometryDirty=!1,this.builtColumns=1,this.builtRows=1,this.buildGeometry(t.geometry,1,1);return}if(!this.texture||!e){t.visible=!1;return}let r=e.getTexture(this.texture),i=r.image;if(!i?.width||!i.height){t.visible=!1;return}t.visible=this.opacity>0,t.renderOrder=this.effectiveRenderOrder,n.opacity=this.opacity,n.map!==r&&(r.magFilter=Wo,n.map=r,n.needsUpdate=!0,this.geometryDirty=!0);let a=-1;for(let e of this.grid())for(let t of e)t>a&&(a=t);let o=`${this.texture}|${a}`;if(this.gridChecked!==o){this.gridChecked=o;let e=Cw(this.texture,this.tileSize,this.tileSize,i.width,i.height,a>=0?a:void 0,`tile`);e&&z(this.tree?.engine??null,`error`,e)}let s=this.columns>0?this.columns:Math.max(1,Math.floor(i.width/this.tileSize)),c=Math.max(1,Math.floor(i.height/this.tileSize));(s!==this.builtColumns||c!==this.builtRows)&&(this.geometryDirty=!0),this.geometryDirty&&(this.geometryDirty=!1,this.builtColumns=s,this.builtRows=c,this.buildGeometry(t.geometry,s,c))}buildGeometry(e,t,n){let r=this.grid(),i=this.tileSize,a=[],o=[],s=[],c=this.palette().map(e=>new J(e)),l=[];for(let e=0;e<r.length;e++){let u=r[e];for(let r=0;r<u.length;r++){let d=u[r];if(d<0)continue;let f=r*i,p=f+i,m=-(e*i),h=-((e+1)*i),g=a.length/3;a.push(f,m,0,p,m,0,p,h,0,f,h,0);let _=d>=Yw?0:d%t,v=d>=Yw?0:Math.floor(d/t),y=_/t,b=(_+1)/t,x=1-v/n,S=1-(v+1)/n;o.push(y,x,b,x,b,S,y,S);let C=d>=Yw?c[d-Yw]:void 0,w=C?.r??1,T=C?.g??1,E=C?.b??1;for(let e=0;e<4;e++)l.push(w,T,E);s.push(g,g+2,g+1,g,g+3,g+2)}}e.setAttribute(`position`,new Y(new Float32Array(a),3)),e.setAttribute(`uv`,new Y(new Float32Array(o),2)),e.setAttribute(`color`,new Y(new Float32Array(l),3)),e.setIndex(s),e.computeBoundingSphere()}get renderedTileCount(){let e=this.tileMesh?.geometry.getAttribute(`position`);return e?e.count/4:0}free(){this.tileMesh?.geometry.dispose(),super.free()}},Qw=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],$w=class extends Ht{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:Qw}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new iu,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!Qw.includes(t))throw new L(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${Qw.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:Qw})}_anchorOrigin(e,t){let n=this.anchor;return{x:n.includes(`right`)?e:n===`top`||n===`center`||n===`bottom`?e/2:0,y:n.includes(`bottom`)?t:n===`left`||n===`center`||n===`right`?t/2:0}}};function eT(){No(),R(MC),R(Tw),R(Fw),R(zw),R(Ew),R(Dw),R(Lw),R($w),R(PC),R(IC),R(FC),R(LC),R(Aw),R(aw),R(Zw)}function tT(e){for(let t=e;t;t=t.parent)if(!t.visible)return!1;return!0}function nT(e,t={}){let n=null;for(let r of e){if(!tT(r.object))continue;let e=r.object;for(;e&&!e.userData?.incantoNode;)e=e.parent;let i=e?.userData?.incantoNode;if(i===void 0)continue;if(!t.byRenderOrder)return i;let a=r.object.renderOrder??0;(!n||a>=n.order)&&(n={node:i,order:a})}return n?.node??null}function rT(e){let t=new Float32Array(e.length/2*3);for(let n=0,r=0;n<e.length;n+=2,r+=3)t[r]=e[n],t[r+1]=-e[n+1],t[r+2]=0;return t}function iT(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function aT(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}function oT(e,t,n){return{x:e.offsetX+t/e.uiW*e.contentW,y:e.offsetY+n/e.uiH*e.contentH}}function sT(e,t,n){return{x:(t-e.offsetX)/e.contentW*e.uiW,y:(n-e.offsetY)/e.contentH*e.uiH}}var cT=new Ou,lT=new G,uT=12,dT=new Float32Array(16);function fT(e){if(!(e instanceof MC))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),cT.setFromObject(t),cT.getSize(lT);let n,r,i,a;if(!Number.isFinite(lT.x)||lT.x===0&&lT.y===0){let e=new G().setFromMatrixPosition(t.matrixWorld);n=e.x-uT,i=e.x+uT,r=e.y-uT,a=e.y+uT}else n=cT.min.x-2,i=cT.max.x+2,r=cT.min.y-2,a=cT.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return dT.set(o),dT}function pT(){return{visited:new Set,cameras:[],emitters:[]}}function mT(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function hT(e,t,n,r,i,a,o){let s=a??pT();s.visited.clear(),s.cameras.length=0,s.emitters.length=0,bT(e,t,n,!1,s.visited,s.cameras,s.emitters,r,i,o?.ignoreStatic===!0),xT(t,s.visited),xT(n,s.visited);let c=null;for(let e=0;e<s.cameras.length;e++){let t=s.cameras[e];if(t.current){c=t;break}}return c||=s.cameras[0]??null,yT(s.emitters,c),{activeCamera:c}}var gT=new G,_T=new G,vT=new G;function yT(e,t){if(e.length===0||!t)return;let n=t._ensureObject2D();n.updateWorldMatrix(!0,!1),n.getWorldPosition(_T),vT.set(0,1,0).applyQuaternion(n.quaternion);let r={position:[_T.x,_T.y,0],forward:[0,0,-1],up:[vT.x,vT.y,vT.z]};for(let{node:t,parent:n}of e)n.updateWorldMatrix(!0,!1),n.getWorldPosition(gT),t._setSpatialPose({position:[gT.x,gT.y,0],listener:r})}function bT(e,t,n,r,i,a,o,s,c,l){let u=t,d=r;if(e instanceof MC&&!(e instanceof $w)){let t=e._ensureObject2D();if(e.static&&!l&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof $w){let t=e._ensureGroup();t.parent!==n&&n.add(t);let r=c?e._anchorOrigin(c.width,c.height):{x:0,y:0};t.position.set(r.x,-r.y,0),i.add(t),d=!0,u=t}else if(e instanceof MC){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(s),i.add(n),e instanceof Dw&&!r&&a.push(e),u=n}else mT(e)&&o.push({node:e,parent:u});for(let t of e.children)bT(t,u,n,d,i,a,o,s,c,l);if(e instanceof MC&&!(e instanceof $w)){let t=e._ensureObject2D();e.static&&!l&&e._staticReady(s)?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}function xT(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&xT(i,t)}}function ST(){return{lastNode:null,lastCx:0,lastCy:0,lastZoom:1,active:!1,t:0,seconds:0,fromCx:0,fromCy:0,fromZoom:1}}function CT(e,t,n,r,i,a){if(!t)return e.lastNode=null,e.active=!1,{cx:n,cy:r,zoom:i};let o=t._blendRequest;if(t._blendRequest=void 0,e.lastNode!==t){let n=o??t.blendSeconds;e.lastNode&&n>0?(e.fromCx=e.lastCx,e.fromCy=e.lastCy,e.fromZoom=e.lastZoom,e.t=0,e.seconds=n,e.active=!0):e.active=!1}let s={cx:n,cy:r,zoom:i};if(e.active){e.t+=a;let t=Math.min(1,e.t/e.seconds),o=t<.5?2*t*t:1-(-2*t+2)**2/2;s={cx:e.fromCx+(n-e.fromCx)*o,cy:e.fromCy+(r-e.fromCy)*o,zoom:e.fromZoom+(i-e.fromZoom)*o},t>=1&&(e.active=!1)}return e.lastCx=s.cx,e.lastCy=s.cy,e.lastZoom=s.zoom,e.lastNode=t,s}var wT=120,TT=class{viewOverride=null;viewBlend=ST();webgl;captureFrame(){return new Promise((e,t)=>{this.pendingCaptures.push({resolve:e,reject:t}),setTimeout(()=>{if(this.pendingCaptures.length>0)try{this.render()}catch(e){let t=e instanceof Error?e:Error(String(e));for(let e of this.pendingCaptures.splice(0))e.reject(t)}},wT)})}pendingCaptures=[];drainFrameCapture(){if(this.pendingCaptures.length===0)return;let e=this.pendingCaptures;this.pendingCaptures=[];try{let t=this.webgl.getContext(),n=this.webgl.domElement.width,r=this.webgl.domElement.height,i=new Uint8Array(n*r*4);this.webgl.setRenderTarget(null),t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,i);for(let e=0;e<Math.floor(r/2);e++){let t=e*n*4,a=(r-1-e)*n*4;for(let e=0;e<n*4;e++){let n=i[t+e];i[t+e]=i[a+e],i[a+e]=n}}for(let t of e)t.resolve({pixels:i,width:n,height:r})}catch(t){let n=t instanceof Error?t:Error(String(t));for(let t of e)t.reject(n)}}basePixelRatio=1;setRenderScale(e){let t=Number.isFinite(e)&&e>0?Math.min(2,Math.max(.25,e)):1;this.webgl.setPixelRatio(this.basePixelRatio*t)}worldScene=new pu;syncScratch=pT();ignoreStatic=!1;uiScene=new pu;worldCam=new cm(-1,1,1,-1,-1e3,1e3);uiCam=new cm(-1,1,1,-1,-1e3,1e3);engine;assets;ownsAssets;loadedAssetScenes=new WeakSet;disconnect;canvas;constructor(e){this.canvas=e.canvas,this.engine=e.engine;let t=e.canvas.clientWidth||e.canvas.width||1,n=e.canvas.clientHeight||e.canvas.height||1;this.lastView={cx:t/2,cy:n/2,zoom:1,w:t,h:n},this.assets=e.assets??new sv(void 0,this.engine),this.ownsAssets=!e.assets;let r=Po(e.engine.scene?.environment,{antialias:!0,pixelRatio:1,preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,e),i=ba(e.engine.settings.get(`quality`));r.antialias=r.antialias&&i.antialias,r.pixelRatio=Math.min(r.pixelRatio,i.pixelRatio),this.webgl=zo(()=>new ov({canvas:e.canvas,antialias:r.antialias,preserveDrawingBuffer:r.preserveDrawingBuffer})),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.engine.toWorld=(e,t)=>{if(!this.hasRendered)return null;let n=this.worldFromScreen(e,t);return[n.x,n.y]},this.engine.toScreen=e=>{if(!this.hasRendered)return null;let t=this.screenFromWorld(e[0]??0,e[1]??0);return{x:t.x,y:t.y,behind:!1}},this.basePixelRatio=r.pixelRatio,this.webgl.setPixelRatio(r.pixelRatio),this.webgl.info.autoReset=!1,this.debugLines=new jf(new dd,new yf({color:`#00ff6e`,transparent:!0,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.worldScene.add(this.debugLines),this.selectionLines=new jf(new dd,new yf({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.worldScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>{let e=performance.now();this.render(),this.engine.noteRenderMs(performance.now()-e)})}debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?fT(t):null;if(this.selectionLines.visible=n!==null,!n)return;let r=new Float32Array(n.length/2*3);for(let e=0,t=0;e<n.length;e+=2,t+=3)r[t]=n[e],r[t+1]=n[e+1],r[t+2]=0;this.selectionLines.geometry.setAttribute(`position`,new Y(r,3)),this.selectionLines.geometry.getAttribute(`position`).needsUpdate=!0}syncDebugLines(){let e=null;for(let t of tw(`2d`,this.engine))if(e=t.debugLines(),e)break;if(this.debugLines.visible=e!==null,!e)return;let t=rT(e);this.debugLines.geometry.setAttribute(`position`,new Y(t,3))}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e));let t=e.environment?.background;this.worldScene.background=typeof t==`string`?new J(t):null;let n=this.canvas.clientWidth||this.canvas.width,r=this.canvas.clientHeight||this.canvas.height,i=this.webgl.getSize(DT);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:sr(e.viewport),o=a?cr(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r;this.lastUi={w:s,h:c};let{activeCamera:l}=hT(e.root,this.worldScene,this.uiScene,this.assets,{width:s,height:c},this.syncScratch,{ignoreStatic:this.ignoreStatic}),u=a?{x:a.design[0]/2,y:a.design[1]/2}:{x:n/2,y:r/2},d=1;if(this.viewOverride?(u={x:this.viewOverride.cx,y:this.viewOverride.cy},d=this.viewOverride.zoom):l&&(u=l.clampedCenter(s,c),d=l.effectiveZoom),!this.viewOverride){let e=CT(this.viewBlend,l??null,u.x,u.y,d,this.engine.unscaledDelta);u={x:e.cx,y:e.cy},d=e.zoom}let f=o?.scale??1;this.lastView={cx:u.x,cy:u.y,zoom:d*f,w:n,h:r},this.lastViewport=o,this.hasRendered=!0,o&&(o.offsetX>.5||o.offsetY>.5)?(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r),this.webgl.clear(),this.webgl.setViewport(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissor(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissorTest(!0)):(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r)),ET(this.worldCam,u.x,u.y,s/d,c/d),ET(this.uiCam,s/2,c/2,s,c),this.webgl.info.reset(),this.webgl.autoClear=!0,this.webgl.render(this.worldScene,this.worldCam),this.webgl.autoClear=!1,this.webgl.render(this.uiScene,this.uiCam),this.webgl.autoClear=!0,this.drainFrameCapture()}lastUi={w:1,h:1};lastViewport=null;lastView;hasRendered=!1;view(){return{...this.lastView}}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}worldFromScreen(e,t){return aT(this.lastView,e,t)}screenFromWorld(e,t){return iT(this.lastView,e,t)}pick(e,t){if(!this.hasRendered)return null;let{w:n,h:r}=this.lastView,i=this.lastViewport?.offsetX??0,a=this.lastViewport?.offsetY??0,o=this.lastViewport?.contentW??n,s=this.lastViewport?.contentH??r;return e<i||e>i+o||t<a||t>a+s?null:(kT.set((e-i)/o*2-1,-((t-a)/s*2-1)),this.hit(this.uiScene,this.uiCam)||this.hit(this.worldScene,this.worldCam))}hit(e,t){return AT.setFromCamera(kT,t),nT(AT.intersectObjects(e.children,!0),{byRenderOrder:!0})}isUiNode(e){let t=e._object2D??e._group??null;for(;t;){if(t===this.uiScene)return!0;t=t.parent}return!1}screenFromUi(e,t){return oT(this.uiView(),e,t)}uiFromScreen(e,t){return sT(this.uiView(),e,t)}uiView(){return{offsetX:this.lastViewport?.offsetX??0,offsetY:this.lastViewport?.offsetY??0,contentW:this.lastViewport?.contentW??this.lastView.w,contentH:this.lastViewport?.contentH??this.lastView.h,uiW:this.lastUi.w,uiH:this.lastUi.h}}boundsOf(e){let t=e._object2D;if(!t||(jT.makeEmpty(),jT.expandByObject(t),jT.isEmpty())||(jT.getSize(OT),OT.x===0&&OT.y===0))return null;let n=this.isUiNode(e)?(e,t)=>this.screenFromUi(e,t):(e,t)=>this.screenFromWorld(e,t),r=n(jT.min.x,-jT.max.y),i=n(jT.max.x,-jT.min.y);return{x:r.x,y:r.y,w:i.x-r.x,h:i.y-r.y}}dispose(){this.engine.picker&&(this.engine.picker=null),this.engine.toWorld&&(this.engine.toWorld=null),this.engine.toScreen&&(this.engine.toScreen=null),this.disconnect();for(let e of[this.worldScene,this.uiScene])e.traverse(e=>{let t=e;if(!t.isMesh)return;let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)e?.dispose()});this.ownsAssets&&this.assets.dispose(),this.webgl.dispose()}};function ET(e,t,n,r,i){e.position.set(t,-n,10),e.left=-r/2,e.right=r/2,e.top=i/2,e.bottom=-i/2,e.updateProjectionMatrix()}var DT=new U,OT=new G,kT=new U,AT=new Rm,jT=new Ou;async function MT(e){eT(),(e.gameplay??!0)&&QC();for(let[t,n]of Object.entries(e.behaviors??{}))kt(t,n,{replace:!0});let t=new wa({seed:e.seed,fixedHz:e.fixedHz,...e.settings?{settings:e.settings}:{},...e._scheduler?{scheduler:e._scheduler}:{}}),n=NT(e.scene);if(Tn(n)===`3d`)throw new L(`WRONG_DIMENSION`,`createGame2D was given a 3D scene ('${String(n.name??`scene`)}'). Its nodes are never drawn by the 2D renderer and never simulated by 2D physics — you get a blank canvas. Boot it with createGame3D instead.`);let r=si(NT(n),{resolveScene:e.resolveScene,engine:t});t.setScene(r);let i=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&PT(r.root))&&(i=await sw(t)),e.physics!==!1&&(t.physicsProvider=async e=>{t.physics||!PT(e)||(i=await sw(t))});let a=[],o=e.keyboard??(typeof window<`u`?window:!1);o&&t.input.attachKeyboard(o);let s=!1,c=()=>{if(s||e.pointer===!1)return;let n=t.scene?.root;if(!n||e.pointer===void 0&&!IT(n))return;s=!0;let r=typeof e.pointer==`object`?e.pointer.lockOnClick??!1:!1;t.input.attachPointer(e.canvas,{lockOnClick:r})};c(),a.push(t.sceneChanged.connect(()=>c())),a.push(FT(t,r.root,e.canvas)),a.push(t.settings.bindAudio(t.audio)),a.push(Yv(t)),a.push(t.settings.bindLocale(t.locale)),e.pageGestures||lv(e.canvas);let l=e.touch??`auto`;if(l!==!1){let n=e.touchContainer??e.canvas.parentElement??null;if(n){let r={force:l===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=Zt(t,n,r),o=t.sceneChanged.connect(()=>{i?.dispose(),i=Zt(t,n,r)});a.push(()=>{o(),i?.dispose()})}}let u=e._rendererFactory?e._rendererFactory(t,e.canvas):new TT({canvas:e.canvas,engine:t,...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.preserveDrawingBuffer===void 0?{}:{preserveDrawingBuffer:e.preserveDrawingBuffer},...e.antialias===void 0?{}:{antialias:e.antialias}});a.push(t.settings.bindFrameCap(e=>{t.maxFps=e})),a.push(t.settings.bindRenderScale(e=>{u.setRenderScale?.(e)})),a.push(...Sv({engine:t,applyDrive:async e=>{let n=0,r=!0,i=()=>{r&&(n+=1,requestAnimationFrame(i))};typeof requestAnimationFrame==`function`&&requestAnimationFrame(i);let a={engine:t,project:(e,t)=>{let n=u.screenFromWorld;return n?n.call(u,e,t):null},wait:e=>new Promise(t=>setTimeout(t,e))};for(let t of e)await Mv(a,t);return r=!1,n},captureFramePixels:()=>{let e=u.captureFrame;return e?e.call(u):Promise.reject(new L(`TREE_VIOLATION`,`this renderer cannot capture frames`))},rendererStats:()=>u.stats?.(),assetErrors:()=>[...u.assets?.errors()??[],...cv(t.scene?.tree.root)]}));let d=e.debug??!1,f=e.editor??d,p=f===!0?{}:f||null,m={label:`✎ edit this scene`,run:async()=>{if(!p)return;let r=p.open??Kv,i=async t=>{let n=await MT({...e,scene:t});p?.onReboot?.(n)};await qv(async()=>{g();try{await r({scene:n,play:i,exit:e=>i(e??n),...p.save?{save:p.save}:{},...p.library?{library:p.library===!0?Bv():p.library}:{}})}catch(e){z(t,`error`,`[incanto] could not open the editor:`,e),await i(n)}},`opening the editor…`)}};if(d){let n=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(n){let{attachDebugOverlay:r}=await Iv(async()=>{let{attachDebugOverlay:e}=await import(`./debug-xpJQqbx1.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(t,{container:n,statsSource:()=>u.stats?.()??{},...p?{actions:[m]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&a.push(()=>i.dispose())}}e.autoStart!==!1&&t.start();let h=!1;function g(){h||(h=!0,Xv([[`physics`,()=>i?.dispose()],[`app cleanups`,()=>{for(let e of a)e()}],[`engine`,()=>t.dispose()],[`renderer`,()=>u.dispose()]]))}return{engine:t,get scene(){let e=t.scene;if(!e)throw new L(`TREE_VIOLATION`,`game.scene: the engine has no scene.`);return e},sourceJson:n,renderer:u,physics:i,pick(e,n){return t.picker?.(e,n)??null},async frame(e){let t=u.captureFrame;if(!t)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);let n=await t.call(u);return _v(n.pixels,n.width,n.height,e)},assetErrors(){return[...u.assets?.errors()??[],...cv(t.scene?.tree.root)]},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...t.stats(),...u.stats?.()}},openEditor:p?async()=>{h||await m.run()}:null,dispose:g}}function NT(e){try{return structuredClone(e)}catch{throw new L(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function PT(e){if(e instanceof NC)return!0;for(let t of e.children)if(PT(t))return!0;return!1}function FT(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`){let e=window;r.push({target:e,type:`keydown`}),r.push({target:e,type:`pointerdown`})}if(r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Ua&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}function IT(e){if(e.behavior?.constructor.name===`Clickable`)return!0;for(let t of e.children)if(IT(t))return!0;return!1}var LT=[[`run`,[`run`,`move`,`walk`]],[`jump`,[`jump`,`idle`]],[`fall`,[`fall`,`jump`,`idle`]],[`wallSlide`,[`wallSlide`,`idle`]],[`dash`,[`dash`,`run`,`move`,`idle`]]];function RT(e){let t=new Set(Object.keys(e));if(t.has(`idle`))for(let[n,r]of LT){if(t.has(n))continue;let i=r.find(e=>e!==n&&t.has(e));i&&(e[n]=i)}}function zT(e,t){let n=e;if(typeof n?.frame?.width!=`number`||typeof n.frame.height!=`number`||!n.animations||Object.keys(n.animations).length===0)throw new L(`BAD_FORMAT`,`Library sprite metadata needs {frame: {width, height}, animations: {<name>: {start, end, frameRate, repeat}}} — got ${JSON.stringify(e).slice(0,120)}.`);let r={},i=null,a=null;for(let[e,t]of Object.entries(n.animations)){if(typeof t.start!=`number`||typeof t.end!=`number`||typeof t.frameRate!=`number`)throw new L(`BAD_FORMAT`,`Library animation '${e}' needs numeric start/end/frameRate, got ${JSON.stringify(t)}.`);let n=t.repeat===-1;r[e]={frames:[t.start,t.end],fps:t.frameRate,loop:n},i??=e,n&&a===null&&(a=e)}RT(r);let o=t.autoplay??a??i;return{asset:{type:`spritesheet`,url:t.url,frameWidth:n.frame.width,frameHeight:n.frame.height},props:{sheet:`$${t.assetKey}`,autoplay:o,animations:r}}}var BT=e({createGame2D:()=>MT,enablePhysics2D:()=>sw}),VT=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),HT=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),UT=class extends ru{constructor(e){super(),this.weight=0,this.isBinary=!1,this.overrideBlink=`none`,this.overrideLookAt=`none`,this.overrideMouth=`none`,this._binds=[],this.name=`VRMExpression_${e}`,this.expressionName=e,this.type=`VRMExpression`,this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink===`block`?+(0<this.outputWeight):this.overrideBlink===`blend`?this.outputWeight:0}get overrideLookAtAmount(){return this.overrideLookAt===`block`?+(0<this.outputWeight):this.overrideLookAt===`blend`?this.outputWeight:0}get overrideMouthAmount(){return this.overrideMouth===`block`?+(0<this.outputWeight):this.overrideMouth===`blend`?this.outputWeight:0}get outputWeight(){return this.isBinary?+(this.weight>.5):this.weight}addBind(e){this._binds.push(e)}deleteBind(e){let t=this._binds.indexOf(e);t>=0&&this._binds.splice(t,1)}applyWeight(e){let t=this.outputWeight;t*=e?.multiplier??1,this.isBinary&&t<1&&(t=0),this._binds.forEach(e=>e.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(e=>e.clearAppliedWeight())}};function WT(e,t,n){let r=e.parser.json,i=r.nodes?.[t];if(i==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${t}] of glTF but the node doesn't exist`),null;let a=i.mesh;if(a==null)return null;let o=r.meshes?.[a];if(o==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${a}] of glTF but the mesh doesn't exist`),null;let s=o.primitives.length,c=[];return n.traverse(e=>{c.length<s&&e.isMesh&&c.push(e)}),c}function GT(e,t){return HT(this,null,function*(){return WT(e,t,yield e.parser.getDependency(`node`,t))})}function KT(e){return HT(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=WT(e,r,t);i!=null&&n.set(r,i)}),n})}var qT={Aa:`aa`,Ih:`ih`,Ou:`ou`,Ee:`ee`,Oh:`oh`,Blink:`blink`,Happy:`happy`,Angry:`angry`,Sad:`sad`,Relaxed:`relaxed`,LookUp:`lookUp`,Surprised:`surprised`,LookDown:`lookDown`,LookLeft:`lookLeft`,LookRight:`lookRight`,BlinkLeft:`blinkLeft`,BlinkRight:`blinkRight`,Neutral:`neutral`};function JT(e){return Math.max(Math.min(e,1),0)}var YT=class e{constructor(){this.blinkExpressionNames=[`blink`,`blinkLeft`,`blinkRight`],this.lookAtExpressionNames=[`lookLeft`,`lookRight`,`lookUp`,`lookDown`],this.mouthExpressionNames=[`aa`,`ee`,`ih`,`oh`,`ou`],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},t=new Set(Object.values(qT));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(qT));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)||(e[n]=r)}),e}copy(e){return this._expressions.concat().forEach(e=>{this.unregisterExpression(e)}),e._expressions.forEach(e=>{this.registerExpression(e)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new e().copy(this)}getExpression(e){return this._expressionMap[e]??null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){let t=this._expressions.indexOf(e);t===-1&&console.warn(`VRMExpressionManager: The specified expressions is not registered`),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){return this.getExpression(e)?.weight??null}setValue(e,t){let n=this.getExpression(e);n&&(n.weight=JT(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){let t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(e=>{e.clearAppliedWeight()}),this._expressions.forEach(t=>{let n=1,r=t.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(n*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(n*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(n*=e.mouth),t.applyWeight({multiplier:n})})}_calculateWeightMultipliers(){let e=1,t=1,n=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,t-=r.overrideLookAtAmount,n-=r.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),n=Math.max(0,n),{blink:e,lookAt:t,mouth:n}}},XT={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},ZT={_Color:XT.Color,_EmissionColor:XT.EmissionColor,_ShadeColor:XT.ShadeColor,_RimColor:XT.RimColor,_OutlineColor:XT.OutlineColor},QT=new J,$T=class e{constructor({material:e,type:t,targetValue:n,targetAlpha:r}){this.material=e,this.type=t,this.targetValue=n,this.targetAlpha=r??1;let i=this._initColorBindState(),a=this._initAlphaBindState();this._state={color:i,alpha:a}}applyWeight(e){let{color:t,alpha:n}=this._state;if(t!=null){let{propertyName:n,deltaValue:r}=t;this.material[n]?.add(QT.copy(r).multiplyScalar(e))}if(n!=null){let{propertyName:t,deltaValue:r}=n;this.material[t]!=null&&(this.material[t]+=r*e)}}clearAppliedWeight(){let{color:e,alpha:t}=this._state;if(e!=null){let{propertyName:t,initialValue:n}=e;this.material[t]?.copy(n)}if(t!=null){let{propertyName:e,initialValue:n}=t;this.material[e]!=null&&(this.material[e]=n)}}_initColorBindState(){let{material:e,type:t,targetValue:n}=this,r=this._getPropertyNameMap()?.[t]?.[0]??null;if(r==null)return console.warn(`Tried to add a material color bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type is not supported.`),null;let i=e[r].clone();return{propertyName:r,initialValue:i,deltaValue:new J(n.r-i.r,n.g-i.g,n.b-i.b)}}_initAlphaBindState(){let{material:e,type:t,targetAlpha:n}=this,r=this._getPropertyNameMap()?.[t]?.[1]??null;if(r==null&&n!==1)return console.warn(`Tried to add a material alpha bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type does not support alpha.`),null;if(r==null)return null;let i=e[r];return{propertyName:r,initialValue:i,deltaValue:n-i}}_getPropertyNameMap(){return Object.entries(e._propertyNameMapMap).find(([e])=>this.material[e]===!0)?.[1]??null}};$T._propertyNameMapMap={isMeshStandardMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null]},isMeshBasicMaterial:{color:[`color`,`opacity`]},isMToonMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null],outlineColor:[`outlineColorFactor`,null],matcapColor:[`matcapFactor`,null],rimColor:[`parametricRimColorFactor`,null],shadeColor:[`shadeColorFactor`,null]}};var eE=$T,tE=class{constructor({primitives:e,index:t,weight:n}){this.primitives=e,this.index=t,this.weight=n}applyWeight(e){this.primitives.forEach(t=>{t.morphTargetInfluences?.[this.index]!=null&&(t.morphTargetInfluences[this.index]+=this.weight*e)})}clearAppliedWeight(){this.primitives.forEach(e=>{e.morphTargetInfluences?.[this.index]!=null&&(e.morphTargetInfluences[this.index]=0)})}},nE=new U,rE=class e{constructor({material:t,scale:n,offset:r}){this.material=t,this.scale=n,this.offset=r;let i=Object.entries(e._propertyNamesMap).find(([e])=>t[e]===!0)?.[1];i==null?(console.warn(`Tried to add a texture transform bind to the material ${t.name??`(no name)`} but the material is not supported.`),this._properties=[]):(this._properties=[],i.forEach(e=>{let i=t[e]?.clone();if(!i)return null;t[e]=i;let a=i.offset.clone(),o=i.repeat.clone(),s=r.clone().sub(a),c=n.clone().sub(o);this._properties.push({name:e,initialOffset:a,deltaOffset:s,initialScale:o,deltaScale:c})}))}applyWeight(e){this._properties.forEach(t=>{let n=this.material[t.name];n!==void 0&&(n.offset.add(nE.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(nE.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};rE._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var iE=rE,aE=new Set([`1.0`,`1.0-beta`]),oE=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return HT(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return HT(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return HT(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!aE.has(r))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.expressions;if(!i)return null;let a=new Set(Object.values(qT)),o=new Map;i.preset!=null&&Object.entries(i.preset).forEach(([e,t])=>{if(t!=null){if(!a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`);return}o.set(e,t)}}),i.custom!=null&&Object.entries(i.custom).forEach(([e,t])=>{if(a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`);return}o.set(e,t)});let s=new YT;return yield Promise.all(Array.from(o.entries()).map(t=>HT(this,[t],function*([t,n]){var r,i,a;let o=new UT(t);if(e.scene.add(o),o.isBinary=n.isBinary??!1,o.overrideBlink=n.overrideBlink??`none`,o.overrideLookAt=n.overrideLookAt??`none`,o.overrideMouth=n.overrideMouth??`none`,(r=n.morphTargetBinds)==null||r.forEach(t=>HT(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield GT(e,t.node),i=t.index;if(!r.every(e=>Array.isArray(e.morphTargetInfluences)&&i<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${n.name} attempts to index morph #${i} but not found.`);return}o.addBind(new tE({primitives:r,index:i,weight:t.weight??1}))})),n.materialColorBinds||n.textureTransformBinds){let t=[];e.scene.traverse(e=>{let n=e.material;n&&(Array.isArray(n)?t.push(...n):t.push(n))}),(i=n.materialColorBinds)==null||i.forEach(e=>HT(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new eE({material:t,type:e.type,targetValue:new J().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>HT(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new iE({material:t,offset:new U().fromArray(e.offset??[0,0]),scale:new U().fromArray(e.scale??[1,1])}))})}))}s.registerExpression(o)}))),s})}_v0Import(t){return HT(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.blendShapeMaster;if(!i)return null;let a=new YT,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>HT(this,null,function*(){let i=r.presetName,o=(i!=null&&e.v0v1PresetNameMap[i]||null)??r.name;if(o==null){console.warn(`VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression`);return}if(s.has(o)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${i} has duplicated entries. Ignoring the expression`);return}s.add(o);let c=new UT(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>HT(this,null,function*(){var i;if(e.mesh===void 0||e.index===void 0)return;let a=[];(i=n.nodes)==null||i.forEach((t,n)=>{t.mesh===e.mesh&&a.push(n)});let o=e.index;yield Promise.all(a.map(n=>HT(this,null,function*(){let i=yield GT(t,n);if(!i.every(e=>Array.isArray(e.morphTargetInfluences)&&o<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${r.name} attempts to index ${o}th morph but not found.`);return}c.addBind(new tE({primitives:i,index:o,weight:.01*(e.weight??100)}))})))}));let l=r.materialValues;l&&l.length!==0&&l.forEach(e=>{if(e.materialName===void 0||e.propertyName===void 0||e.targetValue===void 0)return;let n=[];t.scene.traverse(t=>{if(t.material){let r=t.material;Array.isArray(r)?n.push(...r.filter(t=>(t.name===e.materialName||t.name===e.materialName+` (Outline)`)&&n.indexOf(t)===-1)):r.name===e.materialName&&n.indexOf(r)===-1&&n.push(r)}});let r=e.propertyName;n.forEach(t=>{if(r===`_MainTex_ST`){let n=new U(e.targetValue[0],e.targetValue[1]),r=new U(e.targetValue[2],e.targetValue[3]);r.y=1-r.y-n.y,c.addBind(new iE({material:t,scale:n,offset:r}));return}let n=ZT[r];if(n){c.addBind(new eE({material:t,type:n,targetValue:new J().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}));return}console.warn(r+` is not supported`)})}),a.registerExpression(c)}))),a})}};oE.v0v1PresetNameMap={a:`aa`,e:`ee`,i:`ih`,o:`oh`,u:`ou`,blink:`blink`,joy:`happy`,angry:`angry`,sorrow:`sad`,fun:`relaxed`,lookup:`lookUp`,lookdown:`lookDown`,lookleft:`lookLeft`,lookright:`lookRight`,blink_l:`blinkLeft`,blink_r:`blinkRight`,neutral:`neutral`};var sE=oE,cE=class e{constructor(t,n){this._firstPersonOnlyLayer=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=e.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=t,this.meshAnnotations=n}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMFirstPerson: humanoid must be same in order to copy`);return this.meshAnnotations=e.meshAnnotations.map(e=>({meshes:e.meshes.concat(),type:e.type})),this}clone(){return new e(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:t=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:n=e.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||=(this._firstPersonOnlyLayer=t,this._thirdPersonOnlyLayer=n,this.meshAnnotations.forEach(e=>{e.meshes.forEach(t=>{e.type===`firstPersonOnly`?(t.layers.set(this._firstPersonOnlyLayer),t.traverse(e=>e.layers.set(this._firstPersonOnlyLayer))):e.type===`thirdPersonOnly`?(t.layers.set(this._thirdPersonOnlyLayer),t.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer))):e.type===`auto`&&this._createHeadlessModel(t)})}),!0)}_excludeTriangles(e,t,n,r){let i=0;if(t!=null&&t.length>0)for(let a=0;a<e.length;a+=3){let o=e[a],s=e[a+1],c=e[a+2],l=t[o],u=n[o];if(l[0]>0&&r.includes(u[0])||l[1]>0&&r.includes(u[1])||l[2]>0&&r.includes(u[2])||l[3]>0&&r.includes(u[3]))continue;let d=t[s],f=n[s];if(d[0]>0&&r.includes(f[0])||d[1]>0&&r.includes(f[1])||d[2]>0&&r.includes(f[2])||d[3]>0&&r.includes(f[3]))continue;let p=t[c],m=n[c];p[0]>0&&r.includes(m[0])||p[1]>0&&r.includes(m[1])||p[2]>0&&r.includes(m[2])||p[3]>0&&r.includes(m[3])||(e[i++]=o,e[i++]=s,e[i++]=c)}return i}_createErasedMesh(e,t){let n=new Yd(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);let r=n.geometry,i=r.getAttribute(`skinIndex`),a=i instanceof Im?[]:i.array,o=[];for(let e=0;e<a.length;e+=4)o.push([a[e],a[e+1],a[e+2],a[e+3]]);let s=r.getAttribute(`skinWeight`),c=s instanceof Im?[]:s.array,l=[];for(let e=0;e<c.length;e+=4)l.push([c[e],c[e+1],c[e+2],c[e+3]]);let u=r.getIndex();if(!u)throw Error(`The geometry doesn't have an index buffer`);let d=Array.from(u.array),f=this._excludeTriangles(d,l,o,t),p=[];for(let e=0;e<f;e++)p[e]=d[e];return r.setIndex(p),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new ef(e.skeleton.bones,e.skeleton.boneInverses),new q),n}_createHeadlessModelForSkinnedMesh(e,t){let n=[];if(t.skeleton.bones.forEach((e,t)=>{this._isEraseTarget(e)&&n.push(t)}),!n.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(t,n);e.add(r)}_createHeadlessModel(e){if(e.type===`Group`)if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer));else{let t=new iu;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(e=>e.type===`SkinnedMesh`).forEach(e=>{let n=e;this._createHeadlessModelForSkinnedMesh(t,n)})}else if(e.type===`SkinnedMesh`){let t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode(`head`)?!0:e.parent?this._isEraseTarget(e.parent):!1}};cE.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,cE.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var lE=cE,uE=new Set([`1.0`,`1.0-beta`]),dE=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return HT(this,null,function*(){let t=e.userData.vrmHumanoid;if(t!==null){if(t===void 0)throw Error(`VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);e.userData.vrmFirstPerson=yield this._import(e,t)}})}_import(e,t){return HT(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return HT(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=n.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!uE.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield KT(e);return Array.from(s.entries()).forEach(([e,t])=>{let n=(a?.meshAnnotations)?.find(t=>t.node===e);o.push({meshes:t,type:n?.type??`auto`})}),new lE(t,o)})}_v0Import(e,t){return HT(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.firstPerson;if(!i)return null;let a=[],o=yield KT(e);return Array.from(o.entries()).forEach(([e,t])=>{let r=n.nodes[e],o=i.meshAnnotations?i.meshAnnotations.find(e=>e.mesh===r.mesh):void 0;a.push({meshes:t,type:this._convertV0FlagToV1Type(o?.firstPersonFlag)})}),new lE(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},fE=new G,pE=new G,mE=new W,hE=class extends iu{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new Vm(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(e=>{e.geometry.dispose(),e.material.dispose()})}updateMatrixWorld(e){Array.from(this._boneAxesMap.entries()).forEach(([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(fE,mE,pE);let n=fE.set(.1,.1,.1).divide(pE);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},gE=`hips.spine.chest.upperChest.neck.head.leftEye.rightEye.jaw.leftUpperLeg.leftLowerLeg.leftFoot.leftToes.rightUpperLeg.rightLowerLeg.rightFoot.rightToes.leftShoulder.leftUpperArm.leftLowerArm.leftHand.rightShoulder.rightUpperArm.rightLowerArm.rightHand.leftThumbMetacarpal.leftThumbProximal.leftThumbDistal.leftIndexProximal.leftIndexIntermediate.leftIndexDistal.leftMiddleProximal.leftMiddleIntermediate.leftMiddleDistal.leftRingProximal.leftRingIntermediate.leftRingDistal.leftLittleProximal.leftLittleIntermediate.leftLittleDistal.rightThumbMetacarpal.rightThumbProximal.rightThumbDistal.rightIndexProximal.rightIndexIntermediate.rightIndexDistal.rightMiddleProximal.rightMiddleIntermediate.rightMiddleDistal.rightRingProximal.rightRingIntermediate.rightRingDistal.rightLittleProximal.rightLittleIntermediate.rightLittleDistal`.split(`.`),_E={hips:null,spine:`hips`,chest:`spine`,upperChest:`chest`,neck:`upperChest`,head:`neck`,leftEye:`head`,rightEye:`head`,jaw:`head`,leftUpperLeg:`hips`,leftLowerLeg:`leftUpperLeg`,leftFoot:`leftLowerLeg`,leftToes:`leftFoot`,rightUpperLeg:`hips`,rightLowerLeg:`rightUpperLeg`,rightFoot:`rightLowerLeg`,rightToes:`rightFoot`,leftShoulder:`upperChest`,leftUpperArm:`leftShoulder`,leftLowerArm:`leftUpperArm`,leftHand:`leftLowerArm`,rightShoulder:`upperChest`,rightUpperArm:`rightShoulder`,rightLowerArm:`rightUpperArm`,rightHand:`rightLowerArm`,leftThumbMetacarpal:`leftHand`,leftThumbProximal:`leftThumbMetacarpal`,leftThumbDistal:`leftThumbProximal`,leftIndexProximal:`leftHand`,leftIndexIntermediate:`leftIndexProximal`,leftIndexDistal:`leftIndexIntermediate`,leftMiddleProximal:`leftHand`,leftMiddleIntermediate:`leftMiddleProximal`,leftMiddleDistal:`leftMiddleIntermediate`,leftRingProximal:`leftHand`,leftRingIntermediate:`leftRingProximal`,leftRingDistal:`leftRingIntermediate`,leftLittleProximal:`leftHand`,leftLittleIntermediate:`leftLittleProximal`,leftLittleDistal:`leftLittleIntermediate`,rightThumbMetacarpal:`rightHand`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbDistal:`rightThumbProximal`,rightIndexProximal:`rightHand`,rightIndexIntermediate:`rightIndexProximal`,rightIndexDistal:`rightIndexIntermediate`,rightMiddleProximal:`rightHand`,rightMiddleIntermediate:`rightMiddleProximal`,rightMiddleDistal:`rightMiddleIntermediate`,rightRingProximal:`rightHand`,rightRingIntermediate:`rightRingProximal`,rightRingDistal:`rightRingIntermediate`,rightLittleProximal:`rightHand`,rightLittleIntermediate:`rightLittleProximal`,rightLittleDistal:`rightLittleIntermediate`};function vE(e){return e.invert?e.invert():e.inverse(),e}var yE=new G,bE=new W,xE=class{constructor(e){this.humanBones=e,this.restPose=this.getAbsolutePose()}getAbsolutePose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);r&&(yE.copy(r.position),bE.copy(r.quaternion),e[n]={position:yE.toArray(),rotation:bE.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;yE.set(0,0,0),bE.identity();let i=this.restPose[n];i?.position&&yE.fromArray(i.position).negate(),i?.rotation&&vE(bE.fromArray(i.rotation)),yE.add(r.position),bE.premultiply(r.quaternion),e[n]={position:yE.toArray(),rotation:bE.toArray()}}),e}setPose(e){Object.entries(e).forEach(([e,t])=>{let n=e,r=this.getBoneNode(n);if(!r)return;let i=this.restPose[n];i&&(t?.position&&(r.position.fromArray(t.position),i.position&&r.position.add(yE.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(bE.fromArray(i.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([e,t])=>{let n=this.getBoneNode(e);n&&(t?.position&&n.position.fromArray(t.position),t?.rotation&&n.quaternion.fromArray(t.rotation))})}getBone(e){return this.humanBones[e]??void 0}getBoneNode(e){return this.humanBones[e]?.node??null}},SE=new G,CE=new W,wE=new G,TE=class e extends xE{static _setupTransforms(e){let t=new ru;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};gE.forEach(t=>{var o;let s=e.getBoneNode(t);if(s){let e=new G,c=new W;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(e,c,SE),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new W;(o=s.parent)==null||o.matrixWorld.decompose(SE,l,SE),a[t]=l}});let o={};return gE.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=_E[a],a!=null);)s=n[a];let c=new ru;c.name=`Normalized_`+i.name,(a?o[a]?.node:t).add(c),c.position.copy(e),s&&c.position.sub(s),o[r]={node:c}}}),{rigBones:o,root:t,parentWorldRotations:a,boneRotations:i}}constructor(t){let{rigBones:n,root:r,parentWorldRotations:i,boneRotations:a}=e._setupTransforms(t);super(n),this.original=t,this.root=r,this._parentWorldRotations=i,this._boneRotations=a}update(){gE.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=CE.copy(r).invert(),a=this._boneRotations[e];if(t.quaternion.copy(n.quaternion).multiply(r).premultiply(i).multiply(a),e===`hips`){let e=n.getWorldPosition(wE);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},EE=class e{get restPose(){return console.warn(`VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead.`),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,t){this.autoUpdateHumanBones=t?.autoUpdateHumanBones??!0,this._rawHumanBones=new xE(e),this._normalizedHumanBones=new TE(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new xE(e.humanBones),this._normalizedHumanBones=new TE(this._rawHumanBones),this}clone(){return new e(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn(`VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead.`),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn(`VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead.`),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn(`VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead.`),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn(`VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead.`),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn(`VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead.`),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn(`VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead.`),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},DE={Hips:`hips`,Spine:`spine`,Head:`head`,LeftUpperLeg:`leftUpperLeg`,LeftLowerLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,RightUpperLeg:`rightUpperLeg`,RightLowerLeg:`rightLowerLeg`,RightFoot:`rightFoot`,LeftUpperArm:`leftUpperArm`,LeftLowerArm:`leftLowerArm`,LeftHand:`leftHand`,RightUpperArm:`rightUpperArm`,RightLowerArm:`rightLowerArm`,RightHand:`rightHand`},OE=new Set([`1.0`,`1.0-beta`]),kE={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},AE=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return HT(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return HT(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return HT(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!OE.has(r))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.humanoid;if(!i)return null;let a=i.humanBones.leftThumbIntermediate!=null||i.humanBones.rightThumbIntermediate!=null,o={};i.humanBones!=null&&(yield Promise.all(Object.entries(i.humanBones).map(e=>HT(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=kE[n];e!=null&&(n=e)}let i=yield this.parser.getDependency(`node`,r);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${n} (index = ${r}) does not exist`);return}o[n]={node:i}}))));let s=new EE(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new hE(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return HT(this,null,function*(){let t=this.parser.json.extensions?.VRM;if(!t)return null;let n=t.humanoid;if(!n)return null;let r={};n.humanBones!=null&&(yield Promise.all(n.humanBones.map(e=>HT(this,null,function*(){let t=e.bone,n=e.node;if(t==null||n==null)return;let i=yield this.parser.getDependency(`node`,n);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${t} (index = ${n}) does not exist`);return}let a=kE[t]??t;if(r[a]!=null){console.warn(`Multiple bone entries for ${a} detected (index = ${n}), ignoring duplicated entries.`);return}r[a]={node:i}}))));let i=new EE(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new hE(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(DE).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},jE=class extends dd{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new Y(new Float32Array(195),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new Y(new Uint16Array(189),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,e=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let e=0;e<64;e++){let t=e/63*this._currentTheta;this._attrPos.setXYZ(e+1,this._currentRadius*Math.sin(t),0,this._currentRadius*Math.cos(t))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<63;e++)this._attrIndex.setXYZ(e*3,0,e+1,e+2);this._attrIndex.needsUpdate=!0}},ME=class extends dd{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new G,this._currentTail=new G,this._attrPos=new Y(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new Y(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},NE=new W,PE=new W,FE=new G,IE=new G,LE=Math.sqrt(2)/2,RE=new W(0,0,-LE,LE),zE=new G(0,1,0),BE=class extends iu{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new jE;e.radius=.5;let t=new Td({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new Ld(e,t),this.add(this._meshPitch)}{let e=new jE;e.radius=.5;let t=new Td({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new Ld(e,t),this.add(this._meshYaw)}{let e=new ME;e.radius=.1;let t=new yf({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new jf(e,t),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(e){let t=cl.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=cl.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(FE),this.vrmLookAt.getLookAtWorldQuaternion(NE),NE.multiply(this.vrmLookAt.getFaceFrontQuaternion(PE)),this._meshYaw.position.copy(FE),this._meshYaw.quaternion.copy(NE),this._meshPitch.position.copy(FE),this._meshPitch.quaternion.copy(NE),this._meshPitch.quaternion.multiply(PE.setFromAxisAngle(zE,t)),this._meshPitch.quaternion.multiply(RE);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(IE).sub(FE),this._lineTarget.geometry.tail.copy(IE),this._lineTarget.geometry.update(),this._lineTarget.position.copy(FE)),super.updateMatrixWorld(e)}},VE=new G,HE=new G;function UE(e,t){return e.matrixWorld.decompose(VE,t,HE),t}function WE(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function GE(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var KE=new G(0,0,1),qE=new G,JE=new G,YE=new G,XE=new W,ZE=new W,QE=new W,$E=new W,eD=new Bl,tD=class e{constructor(e,t){this.offsetFromHeadBone=new G,this.autoUpdate=!0,this.faceFront=new G(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new W)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn(`VRMLookAt: euler is deprecated. use getEuler() instead.`),this.getEuler(new Bl)}getEuler(e){return e.set(cl.DEG2RAD*this._pitch,cl.DEG2RAD*this._yaw,0,`YXZ`)}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMLookAt: humanoid must be same in order to copy`);return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new e(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let t=this.humanoid.getRawBoneNode(`head`);return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){return UE(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(KE)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=WE(this.faceFront);return eD.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(eD).premultiply($E.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(ZE),this.getFaceFrontQuaternion(QE),e.copy(KE).applyQuaternion(ZE).applyQuaternion(QE).applyEuler(this.getEuler(eD))}lookAt(e){let t=XE.copy(this._restHeadWorldQuaternion).multiply(vE(this.getLookAtWorldQuaternion(ZE))),n=this.getLookAtWorldPosition(JE),r=YE.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=WE(this.faceFront),[o,s]=WE(r),c=GE(o-i),l=GE(a-s);this._yaw=cl.RAD2DEG*c,this._pitch=cl.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(qE)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};tD.EULER_ORDER=`YXZ`;var nD=tD,rD=new G(0,0,1),iD=new W,aD=new W,oD=new Bl(0,0,0,`YXZ`),sD=class{constructor(e,t,n,r,i){this.humanoid=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i,this.faceFront=new G(0,0,1),this._restQuatLeftEye=new W,this._restQuatRightEye=new W,this._restLeftEyeParentWorldQuat=new W,this._restRightEyeParentWorldQuat=new W;let a=this.humanoid.getRawBoneNode(`leftEye`),o=this.humanoid.getRawBoneNode(`rightEye`);a&&(this._restQuatLeftEye.copy(a.quaternion),UE(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),UE(o.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(e,t){let n=this.humanoid.getRawBoneNode(`leftEye`),r=this.humanoid.getRawBoneNode(`rightEye`),i=this.humanoid.getNormalizedBoneNode(`leftEye`),a=this.humanoid.getNormalizedBoneNode(`rightEye`);n&&(t<0?oD.x=-cl.DEG2RAD*this.rangeMapVerticalDown.map(-t):oD.x=cl.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?oD.y=-cl.DEG2RAD*this.rangeMapHorizontalInner.map(-e):oD.y=cl.DEG2RAD*this.rangeMapHorizontalOuter.map(e),iD.setFromEuler(oD),this._getWorldFaceFrontQuat(aD),i.quaternion.copy(aD).multiply(iD).multiply(aD.invert()),iD.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(iD).premultiply(iD.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?oD.x=-cl.DEG2RAD*this.rangeMapVerticalDown.map(-t):oD.x=cl.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?oD.y=-cl.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):oD.y=cl.DEG2RAD*this.rangeMapHorizontalInner.map(e),iD.setFromEuler(oD),this._getWorldFaceFrontQuat(aD),a.quaternion.copy(aD).multiply(iD).multiply(aD.invert()),iD.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(iD).premultiply(iD.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=cl.RAD2DEG*e.y,n=cl.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(rD)<.01)return e.identity();let[t,n]=WE(this.faceFront);return oD.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(oD)}};sD.type=`bone`;var cD=class{constructor(e,t,n,r,i){this.expressions=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i}applyYawPitch(e,t){t<0?(this.expressions.setValue(`lookDown`,0),this.expressions.setValue(`lookUp`,this.rangeMapVerticalUp.map(-t))):(this.expressions.setValue(`lookUp`,0),this.expressions.setValue(`lookDown`,this.rangeMapVerticalDown.map(t))),e<0?(this.expressions.setValue(`lookLeft`,0),this.expressions.setValue(`lookRight`,this.rangeMapHorizontalOuter.map(-e))):(this.expressions.setValue(`lookRight`,0),this.expressions.setValue(`lookLeft`,this.rangeMapHorizontalOuter.map(e)))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=cl.RAD2DEG*e.y,n=cl.RAD2DEG*e.x;this.applyYawPitch(t,n)}};cD.type=`expression`;var lD=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*JT(e/this.inputMaxValue)}},uD=new Set([`1.0`,`1.0-beta`]),dD=.01,fD=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return HT(this,null,function*(){let t=e.userData.vrmHumanoid;if(t===null)return;if(t===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);let n=e.userData.vrmExpressionManager;if(n!==null){if(n===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first`);e.userData.vrmLookAt=yield this._import(e,t,n)}})}_import(e,t,n){return HT(this,null,function*(){return t==null||n==null?null:(yield this._v1Import(e,t,n))||(yield this._v0Import(e,t,n))||null})}_v1Import(e,t,n){return HT(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=e.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!uD.has(i))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.lookAt;if(!a)return null;let o=a.type===`expression`?1:10,s=this._v1ImportRangeMap(a.rangeMapHorizontalInner,o),c=this._v1ImportRangeMap(a.rangeMapHorizontalOuter,o),l=this._v1ImportRangeMap(a.rangeMapVerticalDown,o),u=this._v1ImportRangeMap(a.rangeMapVerticalUp,o),d;d=a.type===`expression`?new cD(n,s,c,l,u):new sD(t,s,c,l,u);let f=this._importLookAt(t,d);return f.offsetFromHeadBone.fromArray(a.offsetFromHeadBone??[0,.06,0]),f})}_v1ImportRangeMap(e,t){let n=e?.inputMaxValue??90,r=e?.outputScale??t;return n<dD&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=dD),new lD(n,r)}_v0Import(e,t,n){return HT(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let r=e.firstPerson;if(!r)return null;let i=r.lookAtTypeName===`BlendShape`?1:10,a=this._v0ImportDegreeMap(r.lookAtHorizontalInner,i),o=this._v0ImportDegreeMap(r.lookAtHorizontalOuter,i),s=this._v0ImportDegreeMap(r.lookAtVerticalDown,i),c=this._v0ImportDegreeMap(r.lookAtVerticalUp,i),l;l=r.lookAtTypeName===`BlendShape`?new cD(n,a,o,s,c):new sD(t,a,o,s,c);let u=this._importLookAt(t,l);return r.firstPersonBoneOffset?u.offsetFromHeadBone.set(r.firstPersonBoneOffset.x??0,r.firstPersonBoneOffset.y??.06,-(r.firstPersonBoneOffset.z??0)):u.offsetFromHeadBone.set(0,.06,0),u.faceFront.set(0,0,-1),l instanceof sD&&l.faceFront.set(0,0,-1),u})}_v0ImportDegreeMap(e,t){let n=e?.curve;JSON.stringify(n)!==`[0,0,0,1,1,1,1,0]`&&console.warn(`Curves of LookAtDegreeMap defined in VRM 0.0 are not supported`);let r=e?.xRange??90,i=e?.yRange??t;return r<dD&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=dD),new lD(r,i)}_importLookAt(e,t){let n=new nD(e,t);if(this.helperRoot){let e=new BE(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function pD(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}var mD=new Set([`1.0`,`1.0-beta`]),hD=class{get name(){return`VRMMetaLoaderPlugin`}constructor(e,t){this.parser=e,this.needThumbnailImage=t?.needThumbnailImage??!1,this.acceptLicenseUrls=t?.acceptLicenseUrls??[`https://vrm.dev/licenses/1.0/`],this.acceptV0Meta=t?.acceptV0Meta??!0}afterRoot(e){return HT(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return HT(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return HT(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let t=e.extensions?.VRMC_vrm;if(t==null)return null;let n=t.specVersion;if(!mD.has(n))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${n}"`),null;let r=t.meta;if(!r)return null;let i=r.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(i))throw Error(`VRMMetaLoaderPlugin: The license url "${i}" is not accepted`);let a;return this.needThumbnailImage&&r.thumbnailImage!=null&&(a=(yield this._extractGLTFImage(r.thumbnailImage))??void 0),{metaVersion:`1`,name:r.name,version:r.version,authors:r.authors,copyrightInformation:r.copyrightInformation,contactInformation:r.contactInformation,references:r.references,thirdPartyLicenses:r.thirdPartyLicenses,thumbnailImage:a,licenseUrl:r.licenseUrl,avatarPermission:r.avatarPermission,allowExcessivelyViolentUsage:r.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:r.allowExcessivelySexualUsage,commercialUsage:r.commercialUsage,allowPoliticalOrReligiousUsage:r.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:r.allowAntisocialOrHateUsage,creditNotation:r.creditNotation,allowRedistribution:r.allowRedistribution,modification:r.modification,otherLicenseUrl:r.otherLicenseUrl}})}_v0Import(e){return HT(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let t=e.meta;if(!t)return null;if(!this.acceptV0Meta)throw Error(`VRMMetaLoaderPlugin: Attempted to load VRM0.0 meta but acceptV0Meta is false`);let n;return this.needThumbnailImage&&t.texture!=null&&t.texture!==-1&&(n=yield this.parser.getDependency(`texture`,t.texture)),{metaVersion:`0`,allowedUserName:t.allowedUserName,author:t.author,commercialUssageName:t.commercialUssageName,contactInformation:t.contactInformation,licenseName:t.licenseName,otherLicenseUrl:t.otherLicenseUrl,otherPermissionUrl:t.otherPermissionUrl,reference:t.reference,sexualUssageName:t.sexualUssageName,texture:n??void 0,title:t.title,version:t.version,violentUssageName:t.violentUssageName}})}_extractGLTFImage(e){return HT(this,null,function*(){let t=this.parser.json.images?.[e];if(t==null)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image doesn't exist`),null;let n=t.uri;if(t.bufferView!=null){let e=yield this.parser.getDependency(`bufferView`,t.bufferView),r=new Blob([e],{type:t.mimeType});n=URL.createObjectURL(r)}return n==null?(console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image couldn't load properly`),null):yield new Hp().loadAsync(pD(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},gD=class{constructor(e){this.scene=e.scene,this.meta=e.meta,this.humanoid=e.humanoid,this.expressionManager=e.expressionManager,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt}update(e){this.humanoid.update(),this.lookAt&&this.lookAt.update(e),this.expressionManager&&this.expressionManager.update()}},_D=class extends gD{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach(t=>{t.update&&t.update(e)})}},vD=Object.defineProperty,yD=Object.getOwnPropertySymbols,bD=Object.prototype.hasOwnProperty,xD=Object.prototype.propertyIsEnumerable,SD=(e,t,n)=>t in e?vD(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,CD=(e,t)=>{for(var n in t||={})bD.call(t,n)&&SD(e,n,t[n]);if(yD)for(var n of yD(t))xD.call(t,n)&&SD(e,n,t[n]);return e},wD=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});function TD(e,t){e.colorSpace=t}var ED=class{get pending(){return Promise.all(this._pendings)}constructor(e,t){this._parser=e,this._materialParams=t,this._pendings=[]}assignPrimitive(e,t){t!=null&&(this._materialParams[e]=t)}assignColor(e,t,n){if(t!=null){let r=new J().fromArray(t);n&&r.convertSRGBToLinear(),this._materialParams[e]=r}}assignTexture(e,t,n){return wD(this,null,function*(){let r=wD(this,null,function*(){if(t!=null){let r=yield this._parser.assignTexture(this._materialParams,e,t);if(r==null){console.warn(`GLTFMToonMaterialParamsAssignHelper: Failed to load texture. The rendering result may be wrong`);return}n&&TD(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return wD(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},DD=`// #define PHONG
|
|
6229
|
+
`,colorWrite:!1,depthWrite:!0,depthTest:!1,side:2}),_S=9.81,vS=6,yS=.15,bS=class extends Tt{static props={water:{default:``,nodePath:!0},draft:{default:.35},stiffness:{default:3},damping:{default:3.5},drift:{default:.6},drag:{default:.9},samples:{default:4},size:{default:[1,1]}};static signals=[`submerged`,`surfaced`];water=``;draft=.35;stiffness=3;damping=3.5;drift=.6;drag=.9;samples=4;size=[1,1];surface=null;wet=!1;reportedNoImpulse=!1;reportedNoWater=!1;update(e){if(e<=0)return;let t=this.resolveWater();if(!t){this.reportedNoWater||(this.reportedNoWater=!0,z(this.node.tree?.engine??null,`warn`,`[incanto] ${this.node.getPath()}: Buoyancy found no Water3D in the tree, so this body is not floating. It keeps looking, so a water added later is fine — otherwise add one, or name it with "water".`));return}let n=this.node;if(!n.applyImpulse){this.reportedNoImpulse||(this.reportedNoImpulse=!0,z(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: Buoyancy needs a body it can push — this node has no applyImpulse, so it will never float. Put it on a RigidBody3D.`));return}let[r,i,a]=(()=>{let e=B(n);return[e[0]??0,e[1]??0,e[2]??0]})(),o=[(this.size[0]??1)/2,(this.size[1]??1)/2],s=this.samplePoints(r,a,o[0],o[1]),c=n.mass??1,l=n.linearVelocity??[0,0,0],u=0,d=0,f=0,p=0,m=0;for(let[e,n]of s){let r=t.heightAt(e,n)-(i-this.draft);if(r<=0)continue;p++,m=Math.max(m,r),u+=_S*(1+this.stiffness*(r/Math.max(this.draft,yS)));let a=.6;d+=t.heightAt(e+a,n)-t.heightAt(e-a,n),f+=t.heightAt(e,n+a)-t.heightAt(e,n-a)}let h=p>0;if(h!==this.wet&&(this.wet=h,this.emit(h?`submerged`:`surfaced`,this.node)),!h)return;let g=p/s.length,_=Math.min(u/s.length-this.damping*(l[1]??0),vS*_S),v=l[1]??0,y=Math.sqrt(2*_S*m),b=Math.min(_*e,y-v+_S*e)*c,x=(-d*this.drift*12-(l[0]??0)*this.drag)*g*e*c,S=(-f*this.drift*12-(l[2]??0)*this.drag)*g*e*c;n.applyImpulse([x,b,S])}samplePoints(e,t,n,r){let i=Math.max(1,Math.round(this.samples));if(i===1)return[[e,t]];let a=[];for(let o=0;o<i;o++){let s=o/i*Math.PI*2+Math.PI/4;a.push([e+Math.cos(s)*n,t+Math.sin(s)*r])}return a}resolveWater(){if(this.surface)return this.surface;if(this.water!==``){let e=this.node.getNodeOrNull(this.water);if(!(e instanceof Lx))throw new L(`NODE_NOT_FOUND`,`Buoyancy on '${this.node.getPath()}': water '${this.water}' is not a Water3D in the tree.`,{prop:`water`});return this.surface=e,e}return this.surface=xS(this.node.getRoot()),this.surface}};function xS(e){if(e instanceof Lx)return e;for(let t of e.children){let e=xS(t);if(e)return e}return null}function SS(e,t,n,r){if(t===``)return r;try{return n()}catch(n){if(e.authored&&!e.reported.has(t)){e.reported.add(t);let r=n instanceof Error?n.message:String(n);z(e.engine??null,`error`,`[incanto] ${e.who}: ${r} ${e.consequence}`)}return r}}var CS=Math.PI/180,wS=12,TS=class extends Tt{static props={action:{default:`grab`},throwAction:{default:`throw`},range:{default:2.2},group:{default:`carryable`},maxMass:{default:30},holdDistance:{default:1.2},holdHeight:{default:.5},throwSpeed:{default:9},gain:{default:14},inheritMotion:{default:1,range:{min:0,max:1}},facePath:{default:`../Skin`,nodePath:!0}};static signals=[`grabbed`,`dropped`,`thrown`];action=`grab`;throwAction=`throw`;range=2.2;group=`carryable`;maxMass=30;holdDistance=1.2;holdHeight=.5;throwSpeed=9;gain=14;inheritMotion=1;facePath=`../Skin`;held=null;reported=new Set;get body(){let e=this.node;return e instanceof Ib?e:e.parent??e}forward(){let e=((this.facePath===``?this.body:this.node.getNodeOrNull(this.facePath))?.rotation?.[1]??0)*CS;return[Math.sin(e),0,Math.cos(e)]}handPoint(){let e=B(this.body),t=this.forward();return[(e[0]??0)+t[0]*this.holdDistance,(e[1]??0)+this.holdHeight,(e[2]??0)+t[2]*this.holdDistance]}update(){let e=this.node.tree?.engine?.input;if(!e)return;let t=this.node.tree?.engine,n=(n,r)=>SS({engine:t,who:this.node.getPath(),reported:this.reported,consequence:`Nothing can be picked up.`,authored:r},n,()=>e.justPressed(n),!1),r=n(this.action,this.action!==`grab`),i=this.throwAction!==``&&n(this.throwAction,this.throwAction!==`throw`);r&&(this.held?this.drop():this.grab()),this.held&&i&&this.throw()}fixedUpdate(){let e=this.held;if(!e)return;if(e.tree===null){this.held=null;return}let t=this.handPoint(),n=B(e),r=(t[0]??0)-(n[0]??0),i=(t[1]??0)-(n[1]??0),a=(t[2]??0)-(n[2]??0);if(Math.hypot(r,i,a)>Math.max(3,this.range*1.5)){let n=e,r=e.parent?B(e.parent):[0,0,0];n.position=[(t[0]??0)-(r[0]??0),(t[1]??0)-(r[1]??0),(t[2]??0)-(r[2]??0)],n.linearVelocity=[0,0,0];return}let o=r*this.gain,s=i*this.gain,c=a*this.gain,l=Math.hypot(o,s,c);l>wS&&(o*=wS/l,s*=wS/l,c*=wS/l);let u=e;u.linearVelocity=[o,s,c],u.angularVelocity=[0,0,0]}grab(){if(this.held)return this.held;let e=this.handPoint(),t=this.node.tree;if(!t)return null;let n=null,r=1/0;for(let i of t.getNodesInGroup(this.group)){if(!(i instanceof zb)||i.tree===null||i===this.body||i.mass>this.maxMass)continue;let t=B(i),a=Math.hypot((t[0]??0)-e[0],(t[1]??0)-e[1],(t[2]??0)-e[2]);a<=this.range&&a<r&&(n=i,r=a)}return n?(this.held=n,n.gravityScale=0,this.emit(`grabbed`,n),n):null}drop(){let e=this.held;e&&(this.held=null,e.tree!==null&&(e.gravityScale=1),this.emit(`dropped`,e))}throw(){let e=this.held;if(!e)return;let t=this.forward();if(this.drop(),e.tree===null)return;let n=e,r=this.body.linearVelocity??[],i=Math.min(1,Math.max(0,this.inheritMotion));n.linearVelocity=[t[0]*this.throwSpeed+(r[0]??0)*i,this.throwSpeed*.35+Math.max(0,r[1]??0)*i,t[2]*this.throwSpeed+(r[2]??0)*i],this.emit(`thrown`,e)}onReady(){this.facePath!==``&&!this.node.getNodeOrNull(this.facePath)&&z(this.node.tree?.engine??null,`warn`,`[incanto] ${this.node.getPath()}: Carry faces along '${this.facePath}', which is not in the tree — "ahead" is the body's own rotation until it is. Set facePath to the skin the controller turns, or ''.`)}},ES=180/Math.PI;function DS(e,t,n,r){let i=e,a=i.rotation,o=Array.isArray(a),[s,c]=o?[t[0]??0,t[2]??0]:[t[0]??0,t[1]??0];if(Math.hypot(s,c)<1e-6)return;let l=(o?Math.atan2(s,c):Math.atan2(c,s))*ES,u=o?a[1]??0:a??0,d=(l-u+540)%360-180,f=r*n*ES;Math.abs(d)>f&&(d=Math.sign(d)*f);let p=u+d;o?i.rotation=[a[0]??0,p,a[2]??0]:i.rotation=p}var OS={facePath:{default:``,nodePath:!0},turnSpeed:{default:100}},kS=class extends Tt{static props={target:{default:``,nodePath:!0},targetGroup:{default:``},retargetEvery:{default:.25,range:{min:0}},speed:{default:60},stopRange:{default:0},loseRange:{default:0},moveParent:{default:!1},requireSight:{default:!1},ground:{default:null,kinds:[`null`,`boolean`]},...OS};static signals=[`reachedTarget`,`lostTarget`];target=``;targetGroup=``;retargetEvery=.25;speed=60;picked=null;get chasing(){return this.current}current=null;sincePick=1/0;stopRange=0;loseRange=0;moveParent=!1;requireSight=!1;ground=null;facePath=``;fall=0;turnSpeed=100;inRange=!1;lost=!1;onReady(){if(this.target===``&&this.targetGroup===``)throw new L(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "target" (a node path) or "targetGroup" (a group name) is required.`,{prop:`target`});if(this.moveParent){let e=this.node.parent;if(!e||!Cv(e))throw new L(`PROP_TYPE_MISMATCH`,`Chase on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else wv(this)}fallStep(e,t){if(e.isOnFloor?.()??!0)return this.fall=0,0;let n=this.node.tree?.engine?.scene?.physics?.gravity?.[1]??(e.position.length===2?980:-9.81);return this.fall+=n*t,this.fall*t}dropIfAirborne(e,t){let n=this.fallStep(e,t);if(n!==0){let r=[...e.position];r[1]=(r[1]??0)+n,ey(e,r,t)}}nearestOfGroup(e,t){if(this.sincePick+=t,this.picked&&this.picked.tree!==null&&this.sincePick<this.retargetEvery)return this.picked;this.sincePick=0;let n=B(e),r=null,i=1/0;for(let t of this.node.tree?.getNodesInGroup(this.targetGroup)??[]){if(t===e||t===this.node||!Cv(t))continue;let a=Tv(n,B(t));a<i&&(!this.requireSight||this.canSee(e,t))&&(r=t,i=a)}return this.picked=r,r}canSee(e,t){let n=this.physics;if(!n)return!0;let r=B(e),i=B(t),a=r.length>=3,o=a?[r[0]??0,(r[1]??0)+.5,r[2]??0]:[r[0]??0,r[1]??0],s=(a?[i[0]??0,(i[1]??0)+.5,i[2]??0]:[i[0]??0,i[1]??0]).map((e,t)=>e-(o[t]??0)),c=Math.hypot(...s);return c<.001?!0:n.castRay(o,s,c,e,{staticOnly:!0})==null}walksTheGround(e){if(this.ground!==null)return this.ground;let t=e;return e.position.length===3&&typeof t.slopeLimitDeg==`number`}update(e){let t=this.moveParent?this.node.parent:this.node;if(!t||!Cv(t))return;let n=this.targetGroup===``?this.node.getNodeOrNull(this.target):this.nearestOfGroup(t,e);if(n&&Cv(n)&&this.requireSight&&!this.canSee(t,n)&&(n=null),this.current=n&&Cv(n)?n:null,!n||!Cv(n))return;let r=Ba(t,B(n)),i=this.walksTheGround(t);i&&(r[1]=t.position[1]??0);let a=Tv(t.position,r);if(this.loseRange>0&&a>this.loseRange){this.lost||(this.lost=!0,this.inRange=!1,this.emit(`lostTarget`)),i&&this.dropIfAirborne(t,e);return}if(this.lost=!1,this.stopRange>0&&a<=this.stopRange){this.inRange||(this.inRange=!0,this.emit(`reachedTarget`)),i&&this.dropIfAirborne(t,e);return}this.inRange=!1;let o=Math.min(this.speed*e,this.stopRange>0?a-this.stopRange:a),s=[...t.position],{position:c}=kv(t.position,r,Math.max(0,o));if(i&&(c[1]=(c[1]??0)+this.fallStep(t,e)),ey(t,c,e),this.facePath!==``){let t=this.node.getNodeOrNull(this.facePath);t&&DS(t,c.map((e,t)=>e-(s[t]??0)),e,this.turnSpeed)}}},AS=Math.PI/180,jS=class extends Tt{static props={target:{default:``,nodePath:!0,required:!0},back:{default:8},up:{default:3},smoothing:{default:.85,range:{min:0,max:1}}};static signals=[];target=``;back=8;up=3;smoothing=.85;heading=null;onReady(){wv(this)}update(e){let t=this.node,n=t.getNodeOrNull(this.target);if(!Cv(t)||!n||!Cv(n))return;let r=MS(n);this.heading===null&&(this.heading=r);let i=r-this.heading;for(;i>Math.PI;)i-=Math.PI*2;for(;i<-Math.PI;)i+=Math.PI*2;let a=this.smoothing**(e*60);this.heading+=i*(1-a);let o=B(n),s=this.heading,c=o.length>=3?[(o[0]??0)-Math.sin(s)*this.back,(o[1]??0)+this.up,(o[2]??0)-Math.cos(s)*this.back]:[(o[0]??0)-Math.cos(s)*this.back,(o[1]??0)-Math.sin(s)*this.back],l=B(t),u=this.placed?c.map((e,t)=>(l[t]??e)+(e-(l[t]??e))*(1-a)):c;this.placed=!0,t.position=Ba(t,u)}placed=!1;snap(){this.placed=!1,this.heading=null}};function MS(e){let t=e.rotation;if(Array.isArray(t)){let e=(t[0]??0)*AS,n=(t[1]??0)*AS;return Math.atan2(Math.sin(n),Math.cos(e)*Math.cos(n))}return(t??0)*AS}var NS=class e extends Tt{static props={respawn:{default:``,nodePath:!0,required:!0},group:{default:`player`},once:{default:!0},dropBelow:{default:0}};static signals=[`activated`];respawn=``;group=`player`;once=!0;dropBelow=0;lit=!1;sentTo=[];litAt=0;onReady(){this.node.on(`triggerEnter`,e=>{let t=e;if(this.group!==``&&!t.isInGroup(this.group)||this.once&&this.lit)return;let n=this.node.getNodeOrNull(this.respawn);if(!n||!Array.isArray(n.to))return;let r=[...B(this.node)];r.length>=2&&(r[1]=(r[1]??0)-this.dropBelow),n.to=r,this.lit=!0,this.sentTo=[...r],this.litAt=this.node.tree?.engine?.unscaledTime??this.litAt+1,this.emit(`activated`,t)})}serialize(){return{lit:this.lit,sentTo:[...this.sentTo],litAt:this.litAt}}deserialize(e){let t=e;typeof t.lit==`boolean`&&(this.lit=t.lit),Array.isArray(t.sentTo)&&t.sentTo.every(e=>typeof e==`number`)&&(this.sentTo=[...t.sentTo]),typeof t.litAt==`number`&&Number.isFinite(t.litAt)&&(this.litAt=t.litAt)}announce(){if(!this.lit||this.sentTo.length===0)return;let e=this.node.getNodeOrNull(this.respawn);!e||!Array.isArray(e.to)||this.laterSiblingLit(e)||(e.to=[...this.sentTo])}laterSiblingLit(t){let n=this.node.getRoot(),r=!1,i=n=>{if(r)return;let a=n.behavior;a instanceof e&&a!==this&&a.lit&&a.sentTo.length>0&&n.getNodeOrNull(a.respawn)===t&&a.litAt>this.litAt&&(r=!0);for(let e of n.children)i(e)};return i(n),r}},PS=120,FS=class extends Tt{static props={button:{default:0},maxDistance:{default:0,range:{min:0}}};static signals=[`clicked`,`hovered`,`unhovered`];button=0;maxDistance=0;hovering=!1;pressedHere=!1;silentFrames=0;update(){let e=this.node.tree?.engine;if(!e)return;let t=e.picker,n=e.input.pointerPosition();if(!t||!n){t&&(this.silentFrames+=1,this.silentFrames===PS&&z(e,`error`,`[incanto] Clickable on '${this.node.getPath()}' has had no pointer for ${PS} frames, so it can never fire. Nothing is feeding the cursor: pass \`pointer: true\` to createGame2D/3D, or call \`engine.input.attachPointer(canvas)\` on a manual boot.`)),this.hovering&&this.setHover(!1);return}this.silentFrames=0;let r=e.pickAt(n.x,n.y),i=r!==null&&this.isSelfOrDescendant(r)&&this.withinRange();i!==this.hovering&&this.setHover(i),e.input.mouseJustPressed(this.button)&&(this.pressedHere=i),e.input.mouseJustReleased(this.button)&&(this.pressedHere&&i&&this.emit(`clicked`,this.node),this.pressedHere=!1)}setHover(e){this.hovering=e,this.emit(e?`hovered`:`unhovered`,this.node)}isSelfOrDescendant(e){for(let t=e;t;t=t.parent)if(t===this.node)return!0;return!1}withinRange(){if(this.maxDistance<=0)return!0;let e=this.currentCamera();if(!e)return this.warnedNoCamera||(this.warnedNoCamera=!0,z(this.node.tree?.engine??null,`error`,`[incanto] Clickable on '${this.node.getPath()}' has maxDistance ${this.maxDistance}, which is a range FROM THE CAMERA — and this scene has no camera to measure from, so every click is accepted. Add one, or drop the prop.`)),!0;let t=B(e),n=B(this.node);if(t.length===0||n.length===0)return!0;let r=0;for(let e=0;e<Math.max(t.length,n.length);e++){let i=(t[e]??0)-(n[e]??0);r+=i*i}return Math.sqrt(r)<=this.maxDistance}warnedNoCamera=!1;camera=null;currentCamera(){if(this.camera?.tree&&this.camera.current===!0)return this.camera;let e=this.node.tree?.root;if(!e)return null;let t=null,n=e=>{let r=e.constructor.typeName??``;if(r===`Camera2D`||r===`Camera3D`){if(e.current===!0)return e;t??=e}for(let t of e.children){let e=n(t);if(e)return e}return null};return this.camera=n(e)??t,this.camera}},IS=class extends Tt{static props={group:{default:`player`}};static signals=[`totalChanged`];group=`player`;total=0;onReady(){this.node.addToGroup(this.group)}collect(e){this.total+=e,this.emit(`totalChanged`,this.total)}serialize(){return{total:this.total}}deserialize(e){let t=e;typeof t.total==`number`&&(this.total=t.total)}announce(){this.emit(`totalChanged`,this.total)}},LS=class extends Tt{static props={amount:{default:0},max:{default:0}};static signals=[`changed`,`earned`,`spent`,`refused`];amount=0;max=0;canAfford(e){return e<=0?!0:e<=this.amount}spend(e){return an(e,this.node,`Currency.spend`)<=0?(this.refuseNonsense(`spend`,e),!0):this.canAfford(e)?(this.amount-=e,this.emit(`spent`,e),this.emit(`changed`,this.amount),!0):(this.emit(`refused`,e),!1)}earn(e){if(an(e,this.node,`Currency.earn`)<=0){this.refuseNonsense(`earn`,e);return}let t=this.max>0?Math.max(0,this.max-this.amount):e,n=Math.min(e,t);n>0&&(this.amount+=n,this.emit(`earned`,n),this.emit(`changed`,this.amount)),n<e&&this.emit(`refused`,e-n)}get room(){return this.max>0?Math.max(0,this.max-this.amount):1/0}complained=new Set;refuseNonsense(e,t){t===0||this.complained.has(e)||(this.complained.add(e),z(this.node.tree?.engine??null,`error`,`[incanto] Currency.${e}(${t}) on '${this.node.getPath()}' — a negative amount is a sign flip in the caller, never an offer. Ignored: ${e===`spend`?`spending a negative used to PAY you`:`earning a negative used to TAKE from you`}.`))}setAmount(e){let t=an(e,this.node,`Currency.setAmount`);this.amount=this.max>0?Math.min(this.max,t):t,this.emit(`changed`,this.amount)}serialize(){return{amount:this.amount}}deserialize(e){let t=e;typeof t.amount==`number`&&(this.amount=t.amount)}announce(){this.emit(`changed`,this.amount)}};function RS(e,t){let n=e.node;if(!n.declaredSignalNames().includes(`triggerEnter`)){let t=e.constructor.name;throw new L(`UNKNOWN_SIGNAL`,`${t} on '${n.getPath()}' needs a node that emits 'triggerEnter' — attach it to an Area2D/Area3D (or another body that declares the collision signals). '${n.name}' declares: [${n.declaredSignalNames().join(`, `)}].`,{signal:`triggerEnter`,path:n.getPath()})}n.on(`triggerEnter`,e=>t(e))}var zS=class extends Tt{static props={amount:{default:10},targetGroup:{default:``},oncePerTarget:{default:!0},repeatEvery:{default:0},destroySelf:{default:!1},...$v};static signals=[`dealtDamage`];amount=10;targetGroup=``;oncePerTarget=!0;repeatEvery=0;destroySelf=!1;freeParent=!1;hit=new WeakSet;inside=new Map;onReady(){RS(this,e=>{this.inside.set(e,this.repeatEvery),this.tryDamage(e)}),this.node.on(`triggerExit`,e=>{this.inside.delete(e),this.hit.delete(e)})}update(e){if(!(this.repeatEvery<=0||this.inside.size===0))for(let[t,n]of this.inside){if(!t.tree){this.inside.delete(t);continue}let r=n-e;r>0?this.inside.set(t,r):(this.inside.set(t,this.repeatEvery),this.tryDamage(t,{repeat:!0}))}}tryDamage(e,t){if(!t?.repeat&&this.oncePerTarget&&this.hit.has(e))return;let n=ny(e);n&&(this.targetGroup!==``&&!n.owner.isInGroup(this.targetGroup)&&!e.isInGroup(this.targetGroup)||(this.oncePerTarget&&this.hit.add(e),n.health.damage(this.amount,B(this.node)),this.emit(`dealtDamage`,this.amount,n.owner),this.destroySelf&&Qv(this,this.freeParent,`DamageOnContact`)))}},BS=class extends Tt{static signals=[`dayPhaseChanged`];static props={daySeconds:{default:240},startHour:{default:10},maxSunElevationDeg:{default:55},nightDarkness:{default:.75},paused:{default:!1}};daySeconds=240;startHour=10;maxSunElevationDeg=55;nightDarkness=.75;paused=!1;hour=0;phase=``;applyClock=0;baseAmbient=.3;baseExposure=1;captured=!1;reportedNoSky=!1;serialize(){return{hour:this.hour,paused:this.paused}}deserialize(e){let t=e??{};typeof t.hour==`number`&&Number.isFinite(t.hour)&&(this.hour=(t.hour%24+24)%24),typeof t.paused==`boolean`&&(this.paused=t.paused)}onReady(){this.hour=this.startHour}update(e){this.paused||(this.hour=(this.hour+e/this.daySeconds*24)%24);let t=VS(this.hour);t!==this.phase&&(this.phase=t,this.emit(`dayPhaseChanged`,t)),this.applyClock-=e,!(this.applyClock>0)&&(this.applyClock=.2,this.applyHour())}applyHour(){let e=this.node.tree?.engine,t=e?.scene?.environment;if(!e||!t?.sky){e&&!this.reportedNoSky&&(this.reportedNoSky=!0,z(e,`warn`,`[incanto] ${this.node.getPath()}: DayNight drives environment.sky, and this scene has no \`sky\` — the clock runs and nothing on screen changes. It keeps looking, so a sky added later is fine; otherwise add \`"sky": { "type": "atmosphere" }\` to the scene environment.`));return}this.captured||(this.captured=!0,this.baseAmbient=t.ambient?.intensity??.3,this.baseExposure=t.exposure??1);let n=(this.hour-6)/12*Math.PI,r=Math.sin(n);t.sky.elevationDeg=r*this.maxSunElevationDeg+(r<0?r*10:0),t.sky.azimuthDeg=this.hour/24*360+90;let i=Math.max(0,r),a=this.nightDarkness;t.ambient={...t.ambient??{},intensity:this.baseAmbient*(1-a+a*i)},t.exposure=this.baseExposure*(1-a*.55*(1-i))}};function VS(e){return e<5||e>=20?`night`:e<7.5?`dawn`:e<17.5?`day`:`dusk`}var HS=class extends Tt{static props={targetGroup:{default:``,required:!0},range:{default:0},facePath:{default:``,nodePath:!0},turnSpeed:{default:6},aimTolerance:{default:6}};static signals=[`acquired`,`lostTarget`,`aimed`,`lostAim`];targetGroup=``;range=0;facePath=``;turnSpeed=6;aimTolerance=6;target=null;onTarget=!1;onReady(){if(this.targetGroup===``)throw new L(`PROP_TYPE_MISMATCH`,`FaceTarget on '${this.node.getPath()}': "targetGroup" is required — it is the group this turret acquires from.`,{prop:`targetGroup`})}update(e){let t=this.node;if(!Cv(t))return;let n=this.nearest();if(n!==this.target&&(this.target=n,this.emit(n?`acquired`:`lostTarget`,n),n||this.setAim(!1)),!n)return;let r=this.facePath===``?t:this.node.getNodeOrNull(this.facePath);if(!r)return;let i=n.position.map((e,n)=>e-(t.position[n]??0));DS(r,i,e,this.turnSpeed),this.setAim(this.pointedAt(r,i))}nearest(){let e=this.node,t=null,n=1/0;for(let r of this.node.tree?.getNodesInGroup(this.targetGroup)??[]){if(!Cv(r))continue;let i=Math.hypot(...r.position.map((t,n)=>t-(e.position[n]??0)));this.range>0&&i>this.range||i<n&&(n=i,t=r)}return t}pointedAt(e,t){let n=e.rotation,r=Array.isArray(n),[i,a]=r?[t[0]??0,t[2]??0]:[t[0]??0,t[1]??0],o=Math.hypot(i,a);if(o<1e-6)return!0;let s=(r?n[1]??0:n??0)*Math.PI/180,c=r?Math.sin(s):Math.cos(s),l=r?Math.cos(s):Math.sin(s);return(c*i+l*a)/o>=Math.cos(this.aimTolerance*Math.PI/180)}setAim(e){e!==this.onTarget&&(this.onTarget=e,this.emit(e?`aimed`:`lostAim`,this.target))}},US=class extends Tt{static props={rise:{default:1},seconds:{default:.7},hold:{default:.3},drift:{default:0},freeOnEnd:{default:!0}};rise=1;seconds=.7;hold=.3;drift=0;freeOnEnd=!0;elapsed=0;start=[];done=!1;onReady(){let e=this.node;this.start=[...e.position??[]],e.opacity===void 0&&z(this.node.tree?.engine,`warn`,`[incanto] FloatAway on '${this.node.getPath()}' will not fade — ${this.node.constructor.name} has no "opacity" prop, so it pops out at full brightness instead. Use a node that has one (Label, Label3D, Sprite2D, Sprite3D).`)}update(e){if(this.done)return;let t=this.node;if(!t.position)return;this.elapsed+=e;let n=Math.max(.001,this.seconds),r=Math.min(1,this.elapsed/n),i=[...this.start],a=1-(1-r)*(1-r),o=this.start.length===2?-1:1;if(i[1]=(this.start[1]??0)+o*this.rise*a,this.drift!==0&&(i[0]=(this.start[0]??0)+this.drift*a),t.position=i,t.opacity!==void 0){let e=Math.min(.99,Math.max(0,this.hold));t.opacity=r<=e?1:1-(r-e)/(1-e)}r>=1&&(this.done=!0,this.freeOnEnd&&this.node.queueFree())}};function WS(e,t=0){let n=e.tree?.engine,r=e.getPath(),i=(n?.seed??4660)>>>0;for(let e=0;e<r.length;e++)i^=r.charCodeAt(e),i=Math.imul(i,16777619)>>>0;return new Ee((i^Math.imul(t+1,2654435769))>>>0)}var GS=class extends Tt{static props={target:{default:``,nodePath:!0,required:!0},offset:{default:[]},smoothing:{default:0,range:{min:0,max:1}},deadzone:{default:0,range:{min:0}}};static signals=[];target=``;offset=[];smoothing=0;deadzone=0;shakeRng=null;onReady(){if(this.target===``)throw new L(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "target" (a node path) is required.`,{prop:`target`});if(this.deadzone<0)throw new L(`PROP_TYPE_MISMATCH`,`FollowCamera on '${this.node.getPath()}': "deadzone" must be >= 0, got ${this.deadzone}.`,{prop:`deadzone`});wv(this)}shakeMag=0;shakeT=0;shakeFalloff=.28;shake(e,t=.28){this.shakeMag=Math.max(this.shakeMag,e),this.shakeT=t,this.shakeFalloff=t}update(e){let t=this.node;if(!Cv(t))return;let n=t.getNodeOrNull(this.target);if(!n||!Cv(n))return;let r=B(t),i=Ev(B(n),this.offset);if(!(this.deadzone>0&&Tv(r,i)<=this.deadzone)){let n=Av(this.smoothing,e);n>=1?t.position=Ba(t,i):t.position=Ba(t,r.map((e,t)=>e+((i[t]??e)-e)*n))}if(this.shakeT>0){this.shakeT-=this.engine?.unscaledDelta||e;let n=this.shakeMag*Math.max(0,this.shakeT)/this.shakeFalloff;this.shakeT<=0&&(this.shakeMag=0);let r=t.position.slice();this.shakeRng??=WS(this.node);for(let e=0;e<r.length;e++){let t=r.length>=3&&e===1?.5:1;r[e]=(r[e]??0)+(this.shakeRng.next()*2-1)*n*t}t.position=r}}};function KS(e,t){return si(ot(t),{engine:e,...e.resolveScene?{resolveScene:e.resolveScene}:{}})}function qS(e){let t=e.scene?.source;t&&(e.setScene(KS(e,t)),e.ensurePhysics())}var JS=new WeakSet;function YS(e,t,n){if(JS.has(e))return;let r=n?.fadeSeconds??.4,i=()=>{e.setScene(KS(e,t)),e.ensurePhysics()};if(typeof document>`u`||r<=0){i();return}JS.add(e);let a=e.timeScale;e.timeScale=0;let o=()=>{JS.delete(e),a!==0&&(e.timeScale=a)},s=`incanto-scene-fade`,c=document.getElementById(s);c||(c=document.createElement(`div`),c.id=s,c.style.cssText=`position:fixed;inset:0;z-index:10001;background:#000;opacity:0;pointer-events:none;`,document.body.appendChild(c)),c.style.transition=`opacity ${r/2}s`,c.style.opacity=`1`,setTimeout(()=>{try{i()}catch(t){z(e,`error`,`[incanto] goToScene: the destination scene did not load — staying in '${e.scene?.name??`?`}'.`,t)}finally{o();let e=document.getElementById(s);e&&(e.style.opacity=`0`,setTimeout(()=>e.remove(),r*500+60))}},r*500+30)}var XS=class e extends Tt{static signals=[`flowChanged`];static props={restartAction:{default:`restart`},pauseAction:{default:`pause`},freezeOnEnd:{default:!0},bannerPath:{default:`%Banner`,nodePath:!0},pausePanelPath:{default:`%PauseMenu`,nodePath:!0},titlePanelPath:{default:``,nodePath:!0},saveSlots:{default:``}};restartAction=`restart`;freezeOnEnd=!0;bannerPath=`%Banner`;pauseAction=`pause`;reportedActions=new Set;readAction(t,n){let r=this[t],i=e.props[t];return SS({engine:this.engine,who:this.node.getPath(),reported:this.reportedActions,consequence:n,authored:r!==(typeof i?.default==`string`?i.default:``)},r,()=>this.engine.input.justPressed(r),!1)}pausePanelPath=`%PauseMenu`;titlePanelPath=``;saveSlots=``;slots=null;store(){return this.saveSlots===``?null:(this.slots??=new ua(this.saveSlots),this.slots)}save(e=`1`){let t=typeof e==`string`&&e!==``?e:`1`,n=this.store(),r=this.node.tree?.engine??null;return!n||!r?(z(r,`error`,`[incanto] ${this.node.getPath()}: save('${t}') did nothing — this GameFlow has no \`saveSlots\`, so there is nowhere to keep it. Name a namespace and the slot is written; leave it empty and this game does not save.`),!1):(n.write(t,{scene:r.scene?.name??``,state:r.captureState(),savedAt:Date.now()}),this.node.emit(`flowChanged`,this.state),!0)}hasSave(e=`1`){let t=typeof e==`string`&&e!==``?e:`1`;return(this.store()?.read(t)??null)!==null}continueFrom(e=`1`){let t=typeof e==`string`&&e!==``?e:`1`,n=this.store(),r=this.node.tree?.engine??null;if(!n||!r)return!1;let i=n.read(t);if(!i)return!1;let a=r.scene?.name??``;if(i.scene!==``&&i.scene!==a)return z(r,`error`,`[incanto] ${this.node.getPath()}: continueFrom('${t}') holds scene '${i.scene}' and this is '${a}' — load that scene first, then restore. Routing between scenes is the game's: the engine has no map of your levels.`),!1;this.thaw(),qS(r);let o=r.restoreState(i.state);return o.missing.length>0&&z(r,`warn`,`[incanto] ${this.node.getPath()}: continueFrom('${t}') — ${o.missing.length} uid(s) in the save are not in this build; everything else was restored.`),!0}screens=[];everShown=new Set;onTitle=!1;screen(e){if(!(typeof e!=`string`||e===``)){if(this.node.getNodeOrNull(e)===null){z(this.engine,`error`,`[incanto] ${this.node.getPath()}: screen('${e}') found no such node — nothing opened.`);return}this.screens.push(e),this.everShown.add(e),this.freeze(),this.syncPausePanel()}}back(){if(this.screens.length===0){if(this.state===`paused`&&!this.onTitle)return;this.resume();return}this.screens.pop(),this.screens.length===0&&this.state!==`paused`&&this.thaw(),this.syncPausePanel()}state=`playing`;frozeScale=!1;unwatchScene=null;onExitTree(){this.unwatchScene?.(),this.unwatchScene=null}onReady(){this.titlePanelPath!==``&&this.state===`playing`&&(this.onTitle=!0,this.pause()),this.syncPausePanel();let e=this.node.tree?.engine??null;e&&(this.unwatchScene?.(),this.unwatchScene=e.sceneChanged.connect(e=>{!e||e.root!==this.node.getRoot()||this.state!==`playing`&&(this.frozeScale=!1,this.freeze())}))}syncPausePanel(){let e=this.state===`paused`?this.onTitle?this.titlePanelPath:this.pausePanelPath:``,t=this.screens[this.screens.length-1]??e,n=new Set([this.titlePanelPath,this.pausePanelPath,...this.everShown]);n.delete(``);let r=null;for(let e of n){let n=this.node.getNodeOrNull(e);if(!n||!(`visible`in n))continue;let i=e===t;n.visible=i,i&&(r=n)}let i=r??this.node.getNodeOrNull(this.pausePanelPath),a=i?ZS(i):null;a&&(r?(this.navigationWas===null&&(this.navigationWas=a.focusNavigation),a.focusNavigation=!0,a.focus(QS(a))):this.navigationWas!==null&&(a.focusNavigation&&=this.navigationWas,this.navigationWas=null))}navigationWas=null;gameOver(e=`GAME OVER`,t=`#ef4444`){this.transition(`gameover`,e,t)}win(e=`YOU WIN`,t=`#4ade80`){this.transition(`won`,e,t)}pause(){this.state===`playing`&&(this.state=`paused`,this.freeze(),this.syncPausePanel(),this.node.emit(`flowChanged`,this.state))}resume(){this.state===`paused`&&(this.state=`playing`,this.screens.length=0,this.onTitle=!1,this.thaw(),this.syncPausePanel(),this.node.emit(`flowChanged`,this.state))}restart(){this.thaw(),qS(this.engine)}goToScene(e,t=void 0){this.thaw(),YS(this.engine,e,t)}transition(e,t,n){this.state===`gameover`||this.state===`won`||(this.state=e,this.freezeOnEnd&&this.freeze(),this.bannerPath!==``&&this.node.getNodeOrNull(this.bannerPath)?.show(t,{color:n,seconds:0}),this.node.emit(`flowChanged`,e))}freeze(){if(this.frozeScale)return;this.frozeScale=!0;let e=this.node.tree?.engine??null;e&&(e.timeScale=0)}thaw(){if(!this.frozeScale)return;this.frozeScale=!1;let e=this.node.tree?.engine??null;e&&(e.timeScale=1)}update(){let e=this.readAction(`pauseAction`,`The pause key will do nothing.`),t=this.readAction(`restartAction`,`The restart key will do nothing.`);if(this.state===`playing`||this.state===`paused`){e&&(this.state===`playing`?this.pause():this.resume());return}this.state!==`gameover`&&this.state!==`won`||t&&this.restart()}};function ZS(e){for(let t=e;t;t=t.parent)if(t instanceof mn)return t;return null}function QS(e){return e.focusables()[0]??null}var $S=class extends Tt{static props={targets:{default:`player`},offset:{default:[0,12,14]},minZoom:{default:1,range:{min:.1}},maxZoom:{default:2.5,range:{min:.1}},padding:{default:.25,range:{min:0,max:.9}},smoothing:{default:.15,range:{min:0,max:1}},lookAtGroup:{default:!0}};static signals=[];targets=`player`;offset=[0,12,14];minZoom=1;maxZoom=2.5;padding=.25;smoothing=.15;lookAtGroup=!0;zoom=1;centre=[0,0,0];onReady(){if(this.minZoom>this.maxZoom)throw new L(`PROP_TYPE_MISMATCH`,`GroupCamera on '${this.node.getPath()}': "minZoom" (${this.minZoom}) is greater than "maxZoom" (${this.maxZoom}) — there is no zoom that satisfies both.`,{prop:`minZoom`,path:this.node.getPath()})}members(){let e=this.node.tree;return e?[...e.getNodesInGroup(this.targets)].filter(e=>Cv(e)):[]}update(e){let t=this.members();if(t.length===0)return;let n=t.map(e=>B(e)),r=[0,0,0];for(let e of n)r[0]+=e[0]??0,r[1]+=e[1]??0,r[2]+=e[2]??0;r[0]/=n.length,r[1]/=n.length,r[2]/=n.length;let i=0;for(let e=0;e<n.length;e++)for(let t=e+1;t<n.length;t++){let r=n[e],a=n[t];i=Math.max(i,Math.hypot((r[0]??0)-(a[0]??0),(r[2]??0)-(a[2]??0)))}let a=Math.hypot(this.offset[0]??0,this.offset[1]??0,this.offset[2]??0)||1,o=(this.node.fov??60)*(Math.PI/180),s=Math.tan(o/2)*(1-this.padding),c=s>.001?i/2/s/a:this.minZoom,l=Math.min(this.maxZoom,Math.max(this.minZoom,c)),u=this.smoothing>0?1-Math.exp(-e/this.smoothing):1;this.zoom+=(l-this.zoom)*u,this.centre[0]=this.centre[0]+(r[0]-this.centre[0])*u,this.centre[1]=this.centre[1]+(r[1]-this.centre[1])*u,this.centre[2]=this.centre[2]+(r[2]-this.centre[2])*u;let d=this.node;if(d.position=[this.centre[0]+(this.offset[0]??0)*this.zoom,this.centre[1]+(this.offset[1]??0)*this.zoom,this.centre[2]+(this.offset[2]??0)*this.zoom],!this.lookAtGroup)return;let f=this.centre[0]-(d.position[0]??0),p=this.centre[1]-(d.position[1]??0),m=this.centre[2]-(d.position[2]??0),h=Math.atan2(-f,-m)*180/Math.PI;d.rotation=[Math.atan2(p,Math.hypot(f,m))*180/Math.PI,h,0]}snap(){this.centre=[0,0,0],this.zoom=this.minZoom;let e=this.members();if(e.length===0)return;let t=e.map(e=>B(e));for(let e of t)this.centre[0]=this.centre[0]+(e[0]??0)/t.length,this.centre[1]=this.centre[1]+(e[1]??0)/t.length,this.centre[2]=this.centre[2]+(e[2]??0)/t.length}};function eC(e){return Array.isArray(e.position)}function tC(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(e[i]??0)-(t[i]??0);n+=r*r}return Math.sqrt(n)}var nC=class extends Tt{static props={action:{default:`interact`},range:{default:2},actorGroup:{default:`player`},prompt:{default:``},focus:{default:`any`,options:[`any`,`nearest`,`facing`]},coneDeg:{default:40,range:{min:1,max:360}}};static signals=[`interacted`,`focused`,`unfocused`];action=`interact`;range=2;actorGroup=`player`;prompt=``;focus=`any`;coneDeg=40;focusedBy=null;reportedActions=new Set;onReady(){wv(this)}update(){let e=this.node.tree?.engine;if(!e?.scene)return;let t=SS({engine:e,who:this.node.getPath(),reported:this.reportedActions,consequence:`nothing here can be interacted with`,authored:this.action!==`interact`},this.action,()=>e.input.justPressed(this.action),!1);if(!eC(this.node))return;let n=B(this.node),r=null,i=1/0,a=this.node.tree?.getNodesInGroup(this.actorGroup)??aC(this.node.getRoot(),this.actorGroup);for(let e of a){if(!eC(e))continue;let t=tC(n,B(e));t<=this.range&&t<i&&(r=e,i=t)}let o=r;if(o&&this.focus!==`any`&&!this.claims(o,n)&&(o=null),o!==this.focusedBy){let e=this.focusedBy;this.focusedBy=o,e&&this.emit(`unfocused`,e),o&&this.emit(`focused`,o)}!t||!o||this.emit(`interacted`,o)}claims(e,t){let n=this.focus===`facing`?iC(this.node.getRoot()):null,r=n?n.at:B(e),i=e=>{if(!n)return 1;let t=(e[0]??0)-(r[0]??0),i=(e[1]??0)-(r[1]??0),a=(e[2]??0)-(r[2]??0),o=Math.hypot(t,i,a);return o<1e-6?1:t/o*n.fx+i/o*n.fy+a/o*n.fz},a=Math.cos(this.coneDeg/2*(Math.PI/180)),o=i(t);if(o<a)return!1;let s=n?-o:tC(r,t);for(let t of rC(this.node.getRoot())){if(t===this||t.focus===`any`||t.actorGroup!==this.actorGroup||!eC(t.node))continue;let o=B(t.node);if(tC(B(e),o)>t.range)continue;let c=i(o);if(!(n&&c<a)&&(n?-c:tC(r,o))<s)return!1}return!0}};function rC(e){let t=[],n=e=>{e.behavior instanceof nC&&t.push(e.behavior);for(let t of e.children)n(t)};return n(e),t}function iC(e){let t=null,n=null,r=e=>{e.constructor.typeName===`Camera3D`&&(t??=e,e.current&&(n??=e));for(let t of e.children)r(t)};r(e);let i=n??t;if(!i)return null;let a=i.rotation??[0,0,0],o=(a[0]??0)*Math.PI/180,s=(a[1]??0)*Math.PI/180,c=-Math.sin(s),l=Math.sin(o)*Math.cos(s),u=-Math.cos(o)*Math.cos(s);return{at:B(i),fx:c,fy:l,fz:u}}function aC(e,t){let n=[],r=e=>{e.isInGroup(t)&&n.push(e);for(let t of e.children)r(t)};return r(e),n}var oC=.28;function sC(e,t,n,r,i,a){e?.effects.record({kind:t,name:n,from:r,amount:i,at:e.time,wiredAs:a})}var cC=class extends Tt{static props={falloff:{default:oC}};falloff=oC;magnitude=0;t=0;prev=[];shakeRng=null;shake(e,t=this.falloff){this.engine?.settings.get(`reduceMotion`)!==!0&&(this.magnitude=Math.max(this.magnitude,e),this.t=t,sC(this.engine,`shake`,``,this.node?.getPath()??`engine`,e,this.node?.wiringPath()))}update(e){let t=wv(this),n=t.position;for(let e=0;e<this.prev.length;e++)n[e]=(n[e]??0)-(this.prev[e]??0);if(this.t<=0){this.prev.length>0&&(t.position=n.slice(),this.prev.length=0);return}this.t-=this.engine?.unscaledDelta||e;let r=this.magnitude*Math.max(0,this.t)/this.falloff;this.t<=0&&(this.magnitude=0);let i=n.slice();this.prev.length!==i.length&&(this.prev=Array(i.length).fill(0));for(let e=0;e<i.length;e++){let t=i.length>=3&&e===1?.5:1;this.shakeRng??=WS(this.node),this.prev[e]=(this.shakeRng.next()*2-1)*r*t,i[e]=(i[e]??0)+this.prev[e]}t.position=i}},lC=class extends Tt{static props={seconds:{default:1},startOnSignal:{default:!1},...$v};static signals=[`expired`];seconds=1;startOnSignal=!1;freeParent=!1;elapsed=0;running=!1;fired=!1;onReady(){if(!(this.seconds>0))throw new L(`PROP_TYPE_MISMATCH`,`Lifetime on '${this.node.getPath()}': "seconds" must be > 0, got ${this.seconds}.`,{prop:`seconds`});this.running=!this.startOnSignal}startTimer(){this.elapsed=0,this.fired=!1,this.running=!0}update(e){!this.running||this.fired||(this.elapsed+=e,this.elapsed>=this.seconds&&(this.fired=!0,this.running=!1,this.emit(`expired`),Qv(this,this.freeParent,`Lifetime`)))}},uC=Math.PI/180,dC=class extends Tt{static props={rider:{default:``,nodePath:!0,required:!0},steed:{default:`..`,nodePath:!0},drive:{default:``,nodePath:!0},walk:{default:``,nodePath:!0},skin:{default:`Skin`},saddle:{default:``,nodePath:!0},skinOnSaddle:{default:[0,0,0]},skinOnRider:{default:[0,0,0]},dismountAt:{default:[1.8,.3,0]}};static signals=[`mounted`,`dismounted`];rider=``;steed=`..`;drive=``;walk=``;skin=`Skin`;saddle=``;skinOnSaddle=[0,0,0];skinOnRider=[0,0,0];dismountAt=[1.8,.3,0];mounted=!1;mounts=0;parked=null;onReady(){this.riderNode(),this.steedNode()}riderNode(){let e=this.node.getNodeOrNull(this.rider);if(!e||!Cv(e))throw new L(`NODE_NOT_FOUND`,`Mount on '${this.node.getPath()}': "rider" '${this.rider}' is not a spatial node.`,{prop:`rider`,path:this.node.getPath()});return e}steedNode(){let e=this.node.getNodeOrNull(this.steed);if(!e||!Cv(e))throw new L(`NODE_NOT_FOUND`,`Mount on '${this.node.getPath()}': "steed" '${this.steed}' is not a spatial node.`,{prop:`steed`,path:this.node.getPath()});return e}switchOf(e,t,n){if(t!==``){let e=this.node.getNodeOrNull(t);if(!e)throw new L(`NODE_NOT_FOUND`,`Mount on '${this.node.getPath()}': "${n}" '${t}' resolves to no node.`,{prop:n,path:this.node.getPath()});return e}for(let t of e.children){let e=t;if(typeof e.enabled==`boolean`&&(typeof e.yaw==`number`||typeof e.throttle==`number`))return t}return null}skinNode(e){return this.skin===``?null:e.getNodeOrNull(this.skin)??null}saddleNode(){return this.saddle===``?this.steedNode():this.node.getNode(this.saddle)}mount(){if(this.mounted)return!1;let e=this.riderNode(),t=this.steedNode(),n=this.switchOf(e,this.walk,`walk`),r=this.switchOf(t,this.drive,`drive`);n&&(n.enabled=!1),this.parked={gravityScale:e.gravityScale??1,visible:e.visible??!0,enabled:e.enabled??!0},`enabled`in e&&(e.enabled=!1),`visible`in e&&(e.visible=!1),`gravityScale`in e&&(e.gravityScale=0),e.linearVelocity&&=e.linearVelocity.map(()=>0);let i=this.skinNode(e);return i&&(i.reparent(this.saddleNode()),i.position=[...this.skinOnSaddle],Array.isArray(i.rotation)?i.rotation=[0,0,0]:typeof i.rotation==`number`&&(i.rotation=0)),r&&n&&typeof n.yaw==`number`&&typeof r.yaw==`number`&&(r.yaw=n.yaw,typeof n.pitch==`number`&&(r.pitch=n.pitch)),r&&(r.enabled=!0),this.mounted=!0,this.mounts+=1,this.emit(`mounted`,t),!0}dismount(){if(!this.mounted)return!1;let e=this.riderNode(),t=this.steedNode(),n=this.switchOf(e,this.walk,`walk`),r=this.switchOf(t,this.drive,`drive`),i=B(t),a=this.dismountAt,o;if(i.length>=3){let e=Array.isArray(t.rotation)?t.rotation:[0,0,0],n=Math.atan2(Math.sin((e[1]??0)*uC),Math.cos((e[0]??0)*uC)*Math.cos((e[1]??0)*uC));o=[(i[0]??0)+Math.cos(n)*(a[0]??0)+Math.sin(n)*(a[2]??0),(i[1]??0)+(a[1]??0),(i[2]??0)-Math.sin(n)*(a[0]??0)+Math.cos(n)*(a[2]??0)]}else{let e=(typeof t.rotation==`number`?t.rotation:0)*uC;o=[(i[0]??0)+Math.cos(e)*(a[0]??0)-Math.sin(e)*(a[1]??0),(i[1]??0)+Math.sin(e)*(a[0]??0)+Math.cos(e)*(a[1]??0)]}e.position=Ba(e,o),e.linearVelocity&&=e.linearVelocity.map(()=>0),this.parked&&(`gravityScale`in e&&(e.gravityScale=this.parked.gravityScale),`enabled`in e&&(e.enabled=this.parked.enabled),`visible`in e&&(e.visible=this.parked.visible));let s=this.skinNode(this.saddleNode());return s&&(s.reparent(e),s.position=[...this.skinOnRider]),r&&n&&typeof n.yaw==`number`&&typeof r.yaw==`number`&&(n.yaw=r.yaw,typeof r.pitch==`number`&&(n.pitch=r.pitch)),r&&(r.enabled=!1),t.linearVelocity&&=t.linearVelocity.map(()=>0),n&&(n.enabled=!0),this.mounted=!1,this.emit(`dismounted`,t),!0}toggle(){this.mounted?this.dismount():this.mount()}update(){if(!this.mounted)return;let e=this.riderNode();e.position=Ba(e,B(this.steedNode()))}},fC=[`linear`,`easeIn`,`easeOut`,`easeInOut`];function pC(e,t){let n=t<0?0:t>1?1:t;switch(e){case`linear`:return n;case`easeIn`:return n*n;case`easeOut`:return 1-(1-n)*(1-n);case`easeInOut`:return n<.5?2*n*n:1-(-2*n+2)**2/2}}var mC=class extends Tt{static props={to:{default:[],required:!0},duration:{default:1},ease:{default:`easeInOut`,options:[...fC]},startOnSignal:{default:!1}};static signals=[`arrived`];to=[];duration=1;ease=`easeInOut`;startOnSignal=!1;from=[];elapsed=0;running=!1;arrivedFired=!1;onReady(){if(!(this.duration>0))throw new L(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "duration" must be > 0, got ${this.duration}.`,{prop:`duration`});if(!fC.includes(this.ease))throw new L(`PROP_TYPE_MISMATCH`,`MoveTo on '${this.node.getPath()}': "ease" must be one of [${fC.join(`, `)}], got '${this.ease}'.`,{prop:`ease`});let e=wv(this);this.from=[...e.position],this.startOnSignal||(this.running=!0)}start(){let e=this.node;this.from=[...e.position],this.elapsed=0,this.arrivedFired=!1,this.running=!0}finish(){let e=this.node;e.position=e.position.map((e,t)=>this.to[t]??e),this.running=!1,this.elapsed=this.duration,this.arrivedFired||(this.arrivedFired=!0,this.emit(`arrived`))}update(e){if(!this.running)return;let t=this.node;this.elapsed+=e;let n=Math.min(1,this.elapsed/this.duration),r=pC(this.ease,n);t.position=this.from.map((e,t)=>e+((this.to[t]??e)-e)*r),n>=1&&!this.arrivedFired&&(this.arrivedFired=!0,this.running=!1,this.emit(`arrived`))}},hC=[`x`,`y`,`z`],gC=[`position`,`rotation`,`scale`],_C={x:0,y:1,z:2},vC=class extends Tt{static props={axis:{default:`y`,options:[...hC]},amplitude:{default:1},frequency:{default:1},mode:{default:`position`,options:[...gC]}};static signals=[];axis=`y`;amplitude=1;frequency=1;mode=`position`;base=0;time=0;onReady(){if(!hC.includes(this.axis))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "axis" must be one of [${hC.join(`, `)}], got '${this.axis}'.`,{prop:`axis`});if(!gC.includes(this.mode))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': "mode" must be one of [${gC.join(`, `)}], got '${this.mode}'.`,{prop:`mode`});this.base=this.readChannel()}update(e){this.time+=e;let t=this.amplitude*Math.sin(2*Math.PI*this.frequency*this.time);this.writeChannel(this.base+t)}isScalarRotation(){return this.mode===`rotation`&&typeof this.node.rotation==`number`}readChannel(){if(this.isScalarRotation())return this.node.rotation;let e=this.node[this.mode];if(!Array.isArray(e))throw new L(`PROP_TYPE_MISMATCH`,`Oscillate on '${this.node.getPath()}': node has no '${this.mode}' array to oscillate.`,{prop:`mode`});return e[_C[this.axis]]??0}writeChannel(e){if(this.isScalarRotation()){this.node.rotation=e;return}let t=[...this.node[this.mode]];t[_C[this.axis]]=e,this.node[this.mode]=t}},yC=class extends Tt{static signals=[`waypointReached`,`arrived`];static props={speed:{default:120},loop:{default:!1},moveParent:{default:!1},path:{default:``,nodePath:!0},autoStart:{default:!0},...OS};speed=120;loop=!1;moveParent=!1;path=``;autoStart=!0;declared=[];facePath=``;turnSpeed=100;waypoints=[];index=0;get moving(){return this.index<this.waypoints.length}setPath(e){this.waypoints=e.map(e=>[...e]),this.index=0}onReady(){if(this.path===``)return;let e=this.node.getNodeOrNull(this.path);if(!e)throw new L(`NODE_NOT_FOUND`,`PathFollow on '${this.node.getPath()}': "path" '${this.path}' resolves to no node — it names the parent whose children are the waypoints.`,{prop:`path`,path:this.node.getPath()});if(this.declared=e.children.filter(Cv).map(e=>B(e)),this.declared.length===0)throw new L(`PROP_TYPE_MISMATCH`,`PathFollow on '${this.node.getPath()}': "path" '${this.path}' has no spatial children to walk.`,{prop:`path`,path:this.node.getPath()});this.autoStart&&this.setPath(this.declared)}start(){this.declared.length!==0&&this.setPath(this.declared)}stop(){this.waypoints=[],this.index=0}update(e){if(!this.moving)return;let t=this.mover(),n=this.speed*e,r=[...t.position],i=[...t.position];for(;n>0&&this.index<this.waypoints.length;){let a=this.waypoints[this.index],o=kv(i,a,n),s=bC(i,o.position);if(i=o.position,n-=s,o.reached){if(this.node.emit(`waypointReached`,this.index),this.index+=1,this.index>=this.waypoints.length)if(this.loop&&this.waypoints.length>1)this.index=0;else{ey(t,i,e),this.face(t,r,i,e),this.node.emit(`arrived`);return}}else break}ey(t,i,e),this.face(t,r,i,e)}face(e,t,n,r){if(this.facePath===``)return;let i=this.node.getNodeOrNull(this.facePath);i&&DS(i,n.map((e,n)=>e-(t[n]??0)),r,this.turnSpeed)}mover(){if(!this.moveParent)return wv(this);let e=this.node.parent;if(!e||!Cv(e))throw new L(`PROP_TYPE_MISMATCH`,`PathFollow on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move.`,{prop:`moveParent`,path:this.node.getPath()});return e}};function bC(e,t){let n=0,r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=(t[i]??0)-(e[i]??0);n+=r*r}return Math.sqrt(n)}var xC=class extends Tt{static props={points:{default:[],required:!0},speed:{default:60},loop:{default:!0},mode:{default:`loop`,options:[`loop`,`pingpong`]},pauseAt:{default:0},moveParent:{default:!1},...OS};static signals=[`reachedPoint`];points=[];speed=60;loop=!0;mode=`loop`;pauseAt=0;moveParent=!1;facePath=``;turnSpeed=100;index=0;direction=1;pauseTimer=0;onReady(){if(!Array.isArray(this.points)||this.points.length===0)throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "points" must be a non-empty array of position arrays or node paths.`,{prop:`points`});if(this.mode!==`loop`&&this.mode!==`pingpong`)throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "mode" must be 'loop' or 'pingpong', got '${this.mode}'.`,{prop:`mode`});if(this.moveParent){let e=this.node.parent;if(!e||!Cv(e))throw new L(`PROP_TYPE_MISMATCH`,`Patrol on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else wv(this)}update(e){if(this.pauseTimer>0){this.pauseTimer=Math.max(0,this.pauseTimer-e);return}let t=this.moveParent?this.node.parent:this.node;if(!t||!Cv(t))return;let n=t,r=this.pointAt(this.index);if(!r){this.reportDeadWaypoint(this.index);return}let i=[...n.position],{position:a,reached:o}=kv(n.position,r,this.speed*e);ey(n,a,e),this.face(i,a,e),o&&(this.emit(`reachedPoint`,this.index),this.advance(),this.pauseAt>0&&(this.pauseTimer=this.pauseAt))}face(e,t,n){if(this.facePath===``)return;let r=this.node.getNodeOrNull(this.facePath);r&&DS(r,t.map((t,n)=>t-(e[n]??0)),n,this.turnSpeed)}reportedDead=new Set;reportDeadWaypoint(e){if(this.reportedDead.has(e))return;this.reportedDead.add(e);let t=this.points[e];z(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: waypoint ${e} (${JSON.stringify(t)}) resolves to nothing — the patrol stops here and never moves again.`)}pointAt(e){let t=this.points[e];if(Array.isArray(t))return t;if(typeof t==`string`){let e=this.node.getNodeOrNull(t);if(!e||!Cv(e))return null;let n=this.moveParent?this.node.parent:this.node;return!n||!Cv(n)?null:Ba(n,B(e))}return null}advance(){let e=this.points.length-1;if(this.mode===`pingpong`){this.index>=e?this.direction=-1:this.index<=0&&(this.direction=1),this.index=Math.min(e,Math.max(0,this.index+this.direction));return}this.index<e?this.index+=1:this.loop&&(this.index=0)}},SC=5,CC=class extends Tt{static props={at:{default:[]},health:{default:``,nodePath:!0}};static signals=[`phaseChanged`,`phase2`,`phase3`,`phase4`,`phase5`];at=[];health=``;phase=1;watched=null;onReady(){let e=this.health===``?this.node:this.node.getNodeOrNull(this.health)??this.node;if(this.watched=ny(e)?.health??null,!this.watched){z(this.node.tree?.engine??null,`error`,`[incanto] Phases on '${this.node.getPath()}' found no Health to watch, so the fight has one phase forever. Put it under the node that carries the Health, or name one with \`health\`.`);return}this.watched.on(`healthChanged`,(e,t)=>this.read(e,t))}read(e,t){if(!(t>0))return;let n=e/t,r=1;for(let[e,t]of this.at.entries())n<=t&&(r=e+2);for(;this.phase<r;)this.phase+=1,this.phase<=SC&&this.emit(`phase${this.phase}`),this.emit(`phaseChanged`,this.phase)}serialize(){return{phase:this.phase}}deserialize(e){let t=e;typeof t.phase==`number`&&t.phase>=1&&(this.phase=t.phase)}announce(){this.emit(`phaseChanged`,this.phase)}},wC=class extends Tt{static props={value:{default:1},kind:{default:`coin`},collectorGroup:{default:`player`}};static signals=[`collected`];value=1;kind=`coin`;collectorGroup=`player`;collectedAlready=!1;onReady(){RS(this,e=>this.tryCollect(e))}tryCollect(e){if(this.collectedAlready)return;let t=TC(e,this.collectorGroup);t&&(this.collectedAlready=!0,this.node.queueFree(),this.emit(`collected`,this.value,t))}};function TC(e,t){let n=[e];for(;n.length>0;){let e=n.shift();if(e.isInGroup(t))return e;n.push(...e.children)}for(let n=e.parent;n;n=n.parent)if(n.isInGroup(t))return n;return null}var EC=class extends Tt{static props={prefabs:{default:``}};static signals=[];prefabs=``;held=new Map;onEnterTree(){this.claim()}onReady(){this.claim()}claim(){let e=this.prefabs.split(`,`).map(e=>e.trim()).filter(e=>e!==``),t=e.length>0?e:[...this.node.children].map(e=>e.name);for(let e of t){if(this.held.has(e))continue;let t=this.node.children.find(t=>t.name===e);if(!t)throw new L(`NODE_NOT_FOUND`,`PrefabShelf on '${this.node.getPath()}': "prefabs" names '${e}', which is not a child of this node. It holds: ${this.childNames()||`(nothing)`}.`,{prop:`prefabs`,path:this.node.getPath()});$i(t),this.node.removeChild(t),this.held.set(e,t)}}names(){return[...this.held.keys()]}template(e){return this.held.get(e)??null}make(e){let t=this.held.get(e);if(!t)throw new L(`NODE_NOT_FOUND`,`PrefabShelf on '${this.node.getPath()}': no template named '${e}'. This shelf holds: ${this.childNames()||`(nothing)`}.`,{path:this.node.getPath()});let n=Ji(t,Yi(this.node));return typeof n.visible==`boolean`&&(n.visible=!0),n}childNames(){return this.names().join(`, `)}},DC=class extends Tt{static props={speed:{default:300},direction:{default:null,kinds:[`null`,`array`,`string`]},gravity:{default:0}};static signals=[];_speed=300;_direction=null;gravity=0;velocity=[];fall=0;get speed(){return this._speed}set speed(e){this._speed=e,this.armed&&this.aim()}get direction(){return this._direction}set direction(e){this._direction=e,this.armed?this.aim():this.node&&this.resolveDirection()}get armed(){return this.velocity.length>0}aim(e=void 0,t=void 0){e!==void 0&&(this._direction=e),t!==void 0&&(this.carry=[...t]);let n=wv(this),r=this.resolveDirection();for(this.velocity=r.map((e,t)=>e*this._speed+(this.carry[t]??0));this.velocity.length<n.position.length;)this.velocity.push(this.carry[this.velocity.length]??0)}carry=[];onReady(){if(this.speed===0&&this.gravity===0)throw new L(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': a projectile with "speed" 0 and "gravity" 0 never moves — set one of them.`,{prop:`speed`});wv(this),this.resolveDirection()}update(e){this.armed||this.aim();let t=this.node;this.gravity!==0&&(this.fall+=this.gravity*e*(t.position.length===3?-1:1));let n=t.position,r=Math.max(n.length,this.velocity.length),i=Array(r);for(let t=0;t<r;t++){let r=(this.velocity[t]??0)+(t===1?this.fall:0);i[t]=(n[t]??0)+r*e}t.position=i}resolveDirection(){if(Array.isArray(this._direction))return Ov(this._direction);if(this._direction===null||this._direction===`forward`)return this.forwardFromRotation();throw new L(`PROP_TYPE_MISMATCH`,`Projectile on '${this.node.getPath()}': "direction" must be a vector or 'forward', got ${JSON.stringify(this._direction)}.`,{prop:`direction`})}forwardFromRotation(){let e=this.node.rotation;if(typeof e==`number`){let t=e*Math.PI/180;return[Math.cos(t),Math.sin(t)]}if(Array.isArray(e)){let t=(e[1]??0)*Math.PI/180,n=(e[0]??0)*Math.PI/180;return Ov([Math.sin(t),-Math.sin(n)*Math.cos(t),Math.cos(n)*Math.cos(t)])}return[1,0]}},OC=class extends Tt{static props={game:{default:`game`},slot:{default:`1`},label:{default:``},scene:{default:``},restoreOnReady:{default:!1},probeOnReady:{default:!1},keep:{default:[],nodePath:!0}};static signals=[`saved`,`saveFailed`,`restored`,`noSave`,`hasSave`];game=`game`;slot=`1`;label=``;scene=``;restoreOnReady=!1;probeOnReady=!1;keep=[];keptPoses={};elapsed=0;slots=null;store(){return this.slots??=new ua(this.game),this.slots}warnedVolatile=!1;pendingRestore=!1;pendingProbe=!1;onReady(){this.pendingRestore=this.restoreOnReady,this.pendingProbe=this.probeOnReady}update(e){this.pendingProbe&&(this.pendingProbe=!1,this.probe()),this.pendingRestore&&(this.pendingRestore=!1,this.restore()),this.elapsed+=e}probe(){let e=this.store().read(this.slot);if(!e){this.emit(`noSave`);return}this.emit(`hasSave`,e.label||e.scene,e.playtime,e.scene)}get playtime(){return Math.round(this.elapsed)}slotScene(){return this.store().read(this.slot)?.scene??null}save(){let e=this.engine;this.keptPoses=this.readPoses();let t=e.captureState(),n=e.lastCaptureFailures;if(n.length>0){e.log.error(`[incanto] SavePoint '${this.slot}' REFUSED to write: ${n.length} behavior(s) threw out of serialize(), so this save is missing their run and would overwrite the slot that is not. First: ${n[0]}`),this.emit(`saveFailed`,this.slot);return}this.store().write(this.slot,{scene:this.scene||(e.scene?.source.name??``),state:t,label:this.label,savedAt:Date.now(),playtime:Math.round(this.elapsed)}),!this.store().persistent&&!this.warnedVolatile&&(this.warnedVolatile=!0,e.log.warn(`SavePoint wrote slot '${this.slot}' to memory, not to disk — this browser refused localStorage (private window, storage disabled, or quota exhausted), so the run is lost when the page closes. \`SaveSlots.persistent\` is how a game asks before promising the player anything.`)),this.emit(`saved`,this.slot)}restore(){let e=this.store().read(this.slot);if(!e){this.emit(`noSave`);return}let t=this.engine.restoreState(e.state),n=this.scene||this.engine?.scene?.source.name;n&&e.scene&&e.scene!==n?z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': this slot was saved in scene '${e.scene}' and you are in '${n}'. Load that scene first — a save is restored INTO the scene it came from (incanto-save-slots.md).`):t.expected>0&&t.restored===0&&z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': restored 0 of ${t.expected} saveable behaviour(s)`+(t.missing.length>0?` — ${t.missing.length} uid(s) in the save are not in this scene, starting with '${t.missing[0]}'. That save is from an older build, or from another scene.`:`. Nothing in the save matched a node here.`)),this.emit(`restored`,t.restored)}clear(){this.store().remove(this.slot)}serialize(){return{playtime:Math.round(this.elapsed),poses:{...this.keptPoses}}}deserialize(e){let t=e;if(typeof t.playtime==`number`&&t.playtime>=0&&(this.elapsed=t.playtime),this.keptPoses={},t.poses&&typeof t.poses==`object`&&!Array.isArray(t.poses))for(let[e,n]of Object.entries(t.poses))Array.isArray(n)&&n.length===6&&n.every(e=>typeof e==`number`)&&(this.keptPoses[e]=[...n])}announce(){let e=this.node.getRoot();for(let[t,n]of Object.entries(this.keptPoses)){let r=e.getNodeByUid(t);r&&(Array.isArray(r.position)&&(r.position=n.slice(0,3)),Array.isArray(r.rotation)&&(r.rotation=n.slice(3,6)))}}readPoses(){let e={};for(let t of this.keep){let n=this.node.getNodeOrNull(t);if(!n){z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': keep names '${t}', which is not in this scene — that node's position is NOT in the save and a continue will put it back where the scene file says.`);continue}if(!n.uid){z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': keep names '${t}', which has no uid — a save is keyed by uid, so there is nothing to file its position under. Give the node a uid (\`newUid()\`, or open the scene in the editor once).`);continue}let r=n;if(!Array.isArray(r.position)){z(this.engine,`error`,`[incanto] SavePoint '${this.slot}': keep names '${t}', a ${n.constructor.name} with no position — only a 2D/3D node has a pose to keep.`);continue}let i=r.position.map(e=>e),a=Array.isArray(r.rotation)?r.rotation:[];e[n.uid]=[i[0]??0,i[1]??0,i[2]??0,a[0]??0,a[1]??0,a[2]??0]}return e}},kC=class extends Tt{static props={score:{default:0},lives:{default:0},scoreToWin:{default:0}};static signals=[`scoreChanged`,`won`,`lost`,`lifeLost`,`livesChanged`];score=0;lives=0;scoreToWin=0;hasWon=!1;hasLost=!1;get won(){return this.hasWon}get lost(){return this.hasLost}onReady(){if(this.lives<0)throw new L(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "lives" must be >= 0, got ${this.lives}.`,{prop:`lives`});if(this.scoreToWin<0)throw new L(`PROP_TYPE_MISMATCH`,`ScoreKeeper on '${this.node.getPath()}': "scoreToWin" must be >= 0, got ${this.scoreToWin}.`,{prop:`scoreToWin`})}addScore(e){this.setScore(this.score+an(e,this.node,`ScoreKeeper.addScore`))}setScore(e){this.score=an(e,this.node,`ScoreKeeper.setScore`),this.emit(`scoreChanged`,this.score),this.scoreToWin>0&&!this.hasWon&&this.score>=this.scoreToWin&&(this.hasWon=!0,this.emit(`won`))}loseLife(){this.lives<=0||this.hasLost||(--this.lives,this.emit(`lifeLost`,this.lives),this.emit(`livesChanged`,this.lives),this.lives<=0&&(this.hasLost=!0,this.emit(`lost`)))}serialize(){return{score:this.score,lives:this.lives,hasWon:this.hasWon,hasLost:this.hasLost}}deserialize(e){let t=e;typeof t.score==`number`&&(this.score=t.score),typeof t.lives==`number`&&(this.lives=t.lives),typeof t.hasWon==`boolean`&&(this.hasWon=t.hasWon),typeof t.hasLost==`boolean`&&(this.hasLost=t.hasLost)}announce(){this.emit(`scoreChanged`,this.score),this.emit(`livesChanged`,this.lives)}},AC=[`shape`,`size`,`radius`,`height`,`offset`,`oneWay`];function jC(e,t){let n=e.shape;for(let n of Object.keys(e))if(!AC.includes(n))throw new L(`BAD_FORMAT`,`Collider on '${t}' has an unknown key "${n}".`+rt(n,AC)+` A collider is [${AC.join(`, `)}] — friction, restitution and mass are props of the BODY, not of its collider.`,{prop:n,validOptions:[...AC]});if(n!==void 0){if(e.oneWay!==void 0&&typeof e.oneWay!=`boolean`)throw new L(`BAD_FORMAT`,`Collider on '${t}': "oneWay" must be a boolean (platforms you jump up through), got ${JSON.stringify(e.oneWay)}.`);if(n===`rect`){let n=e.size;if(!Array.isArray(n)||n.length!==2||n.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${t}': rect needs "size": [width, height].`);return}if(n===`circle`){if(typeof e.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': circle needs "radius".`);return}if(n===`capsule`){if(typeof e.radius!=`number`||typeof e.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${t}': capsule needs "radius" and "height".`);return}throw new L(`BAD_FORMAT`,`Collider on '${t}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(n)}.`)}}var MC=class extends Ht{static typeName=`Node2D`;static props={position:{default:[0,0]},rotation:{default:0},static:{default:!1},scale:{default:[1,1]},renderOrder:{default:0},orderGroup:{default:`default`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},visible:{default:!0}};static propAliases={zIndex:`renderOrder`};position=[0,0];rotation=0;static=!1;scale=[1,1];renderOrder=0;orderGroup=`default`;get effectiveRenderOrder(){return Jn(this.orderGroup,this.renderOrder,this.tree?.engine?.orderGroups)}visible=!0;_object2D=null;_ensureObject2D(){return this._object2D||(this._object2D=this._createObject2D(),this._object2D.userData.incantoNode=this),this._object2D}_createObject2D(){return new ru}_staticReady(e){return!0}_syncObject2D(e){let t=this._ensureObject2D();t.position.set(this.position[0]??0,-(this.position[1]??0),0),t.rotation.z=-cl.degToRad(this.rotation),t.scale.set(this.scale[0]??1,this.scale[1]??1,1),t.visible=this.visible}free(){super.free(),this._object2D?.removeFromParent(),this._object2D=null}},NC=class extends MC{static props={collider:{default:{},variants:{tag:`shape`,byTag:{rect:{shape:`rect`,size:[32,32]},circle:{shape:`circle`,radius:16},capsule:{shape:`capsule`,radius:12,height:32}}}},enabled:{default:!0}};static signals=[`triggerEnter`,`triggerExit`];_collider={};_colliderChanged=!1;_enabled=!0;_enabledChanged=!1;get collider(){return this._collider}set collider(e){if(typeof e!=`object`||!e||Array.isArray(e)){z(this.tree?.engine??null,`error`,`[incanto] ${this.getPath()}: collider must be an object, got ${e===null?`null`:Array.isArray(e)?`an array`:typeof e} — to switch this body off set \`enabled = false\` instead. Keeping the collider it had.`);return}this._collider=e,this._colliderChanged=!0}get enabled(){return this._enabled}set enabled(e){e!==this._enabled&&(this._enabled=e,this._enabledChanged=!0)}static validateJson(e){jC(e.collider,e.name)}_physics=null},PC=class extends NC{static typeName=`StaticBody2D`;static props={friction:{default:.5},restitution:{default:0}};friction=.5;restitution=0},FC=class extends NC{static typeName=`Area2D`;overlapping(e=void 0){let t=this._physics?.overlapping(this)??[];return e===void 0?t:t.filter(t=>t.isInGroup(e))}},IC=class extends NC{static typeName=`RigidBody2D`;static props={mass:{default:1},gravityScale:{default:1},fixedRotation:{default:!1},friction:{default:.5},restitution:{default:0},linearVelocity:{default:[0,0]},angularVelocity:{default:0},linearDamping:{default:0,range:{min:0}},angularDamping:{default:0,range:{min:0}}};mass=1;gravityScale=1;fixedRotation=!1;friction=.5;restitution=0;linearDamping=0;angularDamping=0;linearVelocity=[0,0];angularVelocity=0;get velocity(){return this.linearVelocity}set velocity(e){this.linearVelocity=e}applyImpulse(e){this._physics?.applyImpulse(this,e)}},LC=class extends NC{static typeName=`CharacterBody2D`;static props={velocity:{default:[0,0]},stickToGround:{default:!0},slopeLimitDeg:{default:45},stepHeight:{default:35,range:{min:0}},collideWithCharacters:{default:!0},pushes:{default:0,range:{min:0}}};pushes=0;static propAliases={snapToGround:`stickToGround`};velocity=[0,0];stickToGround=!0;slopeLimitDeg=45;stepHeight=35;collideWithCharacters=!0;_grounded=!1;moveAndSlide(){if(!this._physics)throw new L(`TREE_VIOLATION`,this.collider.shape===void 0?`CharacterBody2D '${this.name}' has no collider — set a collider prop (physics skips collider-less bodies).`:`CharacterBody2D '${this.name}' has no physics world — await enablePhysics2D(engine) first.`);this._physics.moveAndSlide(this)}_onWall=0;_onCeiling=!1;isOnWall(){return this._onWall!==0}wallSide(){return this._onWall}isOnCeiling(){return this._onCeiling}isOnFloor(){return this._grounded}},RC=100,zC=Math.PI/180,BC=.9,VC=class extends Tt{static props={pieces:{default:8,range:{min:1}},impulse:{default:4},spin:{default:6},lifetime:{default:2.5,range:{min:0}},when:{default:`died`},mesh:{default:``,nodePath:!0},free:{default:!0}};static signals=[`shattered`];pieces=8;impulse=4;spin=6;lifetime=2.5;when=`died`;mesh=``;free=!0;broken=!1;get breakable(){let e=this.node;return e instanceof Ib||e instanceof NC?e:e.parent??e}onReady(){if(this.when===``)return;let e=this.breakable;try{e.on(this.when,()=>this.break(),{owner:this.node})}catch(t){z(this.node.tree?.engine??null,`error`,`[incanto] ${this.node.getPath()}: Shatter listens for '${this.when}' on '${e.getPath()}', which declares no such signal — give it a Health (it emits 'died'), name another signal in "when", or set "when": "" and call break() yourself. (${t instanceof Error?t.message:String(t)})`)}}break(){if(this.broken)return;this.broken=!0;let e=this.breakable,t=e.getRoot(),n=this.node.tree?.engine?.rng,r=()=>n?n.next():Math.random(),i=!(e instanceof NC)&&(e instanceof Ib||B(e).length===3),a=B(e),o=Math.max(1,Math.round(this.pieces)),s=[];if(i){let t=this.findMesh(e,`MeshInstance3D`),n=e.collider,i=t?.size??n?.size??[1,1,1],c=t?.material??{},l=t?.castShadow??!1,u=(e.mass??1)/o,d=(e.rotation?.[1]??0)*zC,f=Math.max(1,Math.ceil(Math.cbrt(o))),p=[(i[0]??1)/f,(i[1]??1)/f,(i[2]??1)/f],m=p.map(e=>e*BC),h=0;for(let t=0;t<f&&h<o;t++)for(let n=0;n<f&&h<o;n++)for(let i=0;i<f&&h<o;i++,h++){let o=(i-(f-1)/2)*(p[0]??1),g=(t-(f-1)/2)*(p[1]??1),_=(n-(f-1)/2)*(p[2]??1),v=o*Math.cos(d)+_*Math.sin(d),y=-o*Math.sin(d)+_*Math.cos(d),b=Math.hypot(v,g,y),x=b>1e-6?[v/b,g/b,y/b]:[r()-.5,r(),r()-.5].map(e=>e*2),S=this.impulse*(.6+r()*.6),C={name:`${e.name}Piece${h}`,type:`RigidBody3D`,props:{position:[(a[0]??0)+v,(a[1]??0)+g,(a[2]??0)+y],rotation:[0,d/zC,0],mass:u,friction:.7,collider:{shape:`box`,size:m},linearVelocity:[(x[0]??0)*S,(x[1]??0)*S+this.impulse*.5,(x[2]??0)*S],angularVelocity:[(r()-.5)*2*this.spin,(r()-.5)*2*this.spin,(r()-.5)*2*this.spin]},children:[{name:`Mesh`,type:`MeshInstance3D`,props:{mesh:`box`,size:m,material:{...c},castShadow:l}}]};this.lifetime>0&&(C.script={name:`Lifetime`,props:{seconds:this.lifetime}}),s.push(xi(C,Yi(this.node)))}}else{let t=this.findMesh(e,`ColorRect2D`),n=t?null:this.findMesh(e,`Sprite2D`),i=e.collider,c=t?.size??i?.size??[i?.radius?i.radius*2:40,i?.radius?i.radius*2:40],l=t?.color??n?.tint??`#ffffff`,u=(e.mass??1)/o,d=(e.rotation??0)*zC,f=Math.max(1,Math.ceil(Math.sqrt(o))),p=[(c[0]??40)/f,(c[1]??40)/f],m=p.map(e=>e*BC),h=this.impulse*RC,g=0;for(let t=0;t<f&&g<o;t++)for(let n=0;n<f&&g<o;n++,g++){let i=(n-(f-1)/2)*(p[0]??1),o=(t-(f-1)/2)*(p[1]??1),c=i*Math.cos(d)-o*Math.sin(d),_=i*Math.sin(d)+o*Math.cos(d),v=Math.hypot(c,_),y=v>1e-6?[c/v,_/v]:[(r()-.5)*2,-r()],b=h*(.6+r()*.6),x={name:`${e.name}Piece${g}`,type:`RigidBody2D`,props:{position:[(a[0]??0)+c,(a[1]??0)+_],rotation:d/zC,mass:u,friction:.7,collider:{shape:`rect`,size:m},linearVelocity:[(y[0]??0)*b,(y[1]??0)*b-h*.5],angularVelocity:(r()-.5)*2*this.spin},children:[{name:`Rect`,type:`ColorRect2D`,props:{size:m,color:l}}]};this.lifetime>0&&(x.script={name:`Lifetime`,props:{seconds:this.lifetime}}),s.push(xi(x,Yi(this.node)))}}this.free&&(e.enabled=!1,e.queueFree());for(let e of s)t.addChild(e);this.emit(`shattered`,e)}findMesh(e,t){if(this.mesh!==``)return this.node.getNodeOrNull(this.mesh);let n=e=>{if(e.constructor.typeName===t)return e;for(let t of e.children){let e=n(t);if(e)return e}return null};return n(e)}},HC=Math.PI/180,UC=class extends Tt{static props={range:{default:12,range:{min:0}},coneDeg:{default:70,range:{min:0,max:360}},targetGroup:{default:`player`},facingPath:{default:`../Skin`,nodePath:!0},eyeHeight:{default:.6},chestHeight:{default:.3},fillSeconds:{default:0,range:{min:0}},los:{default:!0}};static signals=[`spotted`,`lost`];range=12;coneDeg=70;targetGroup=`player`;facingPath=`../Skin`;eyeHeight=.6;chestHeight=.3;fillSeconds=0;los=!0;suspicion=0;target=null;seenNow=new Set;alarmed=!1;lastTarget=null;sees(e){return this.seenNow.has(e)}seen(){return[...this.seenNow].sort((e,t)=>this.distanceTo(e)-this.distanceTo(t))}update(e){let t=this.node.parent;if(!t)return;let n=B(t),r=n.length<3,[i,a]=this.facing(t,r),o=Math.cos(Math.min(360,Math.max(0,this.coneDeg))*.5*HC),s=this.node.tree?.getNodesInGroup(this.targetGroup)??[],c=new Set,l=null,u=1/0;for(let e of s){if(e===t||e===this.node||e.tree===null)continue;let s=B(e);if(!Array.isArray(s)||s.length<2)continue;let d=(s[0]??0)-(n[0]??0),f=r?(s[1]??0)-(n[1]??0):(s[2]??0)-(n[2]??0),p=Math.hypot(d,f);if(!(p>this.range)&&!(p>.001&&this.coneDeg<360&&(i*d+a*f)/p<o)){if(this.los){let e=r?[n[0]??0,n[1]??0]:[n[0]??0,(n[1]??0)+this.eyeHeight,n[2]??0],i=(r?[s[0]??0,s[1]??0]:[s[0]??0,(s[1]??0)+this.chestHeight,s[2]??0]).map((t,n)=>t-(e[n]??0)),a=Math.hypot(...i);if(a>.001&&this.physics?.castRay(e,i,a,t,{staticOnly:!0}))continue}c.add(e),p<u&&(u=p,l=e)}}if(this.seenNow=c,this.target=l,l&&(this.lastTarget=l),this.fillSeconds<=0)this.suspicion=+!!l;else{let t=e/this.fillSeconds;this.suspicion=Math.min(1,Math.max(0,this.suspicion+(l?t:-t)))}!this.alarmed&&this.suspicion>=1?(this.alarmed=!0,this.emit(`spotted`,l??this.lastTarget)):this.alarmed&&this.suspicion<=0&&(this.alarmed=!1,this.emit(`lost`,this.lastTarget))}facing(e,t){let n=((this.facingPath===``?null:this.node.getNodeOrNull(this.facingPath))??e).rotation;if(t){let e=(typeof n==`number`?n:0)*HC;return[Math.cos(e),Math.sin(e)]}let r=(Array.isArray(n)?n[1]??0:0)*HC;return[Math.sin(r),Math.cos(r)]}distanceTo(e){let t=this.node.parent;if(!t)return 1/0;let n=B(t),r=B(e);return n.length<3?Math.hypot((n[0]??0)-(r[0]??0),(n[1]??0)-(r[1]??0)):Math.hypot((n[0]??0)-(r[0]??0),(n[2]??0)-(r[2]??0))}},WC=class{behavior;detached=new Map;constructor(e){this.behavior=e}resolveTemplate(e){let t=this.detached.get(e);if(t)return t;let n=this.behavior.node,r=GC(n,e),i=r?n.tree?._templates.get(r)??null:null;if(i)return this.detached.set(e,i),i;let a=e===``?null:n.getNodeOrNull(e);if(!a){let t=this.behavior.constructor.name;throw new L(`NODE_NOT_FOUND`,`${t} on '${n.getPath()}': "prefab" '${e}' does not resolve to a template node. Point it at a (usually hidden) child node to clone.`,{prop:`prefab`,path:n.getPath()})}return r&&n.tree?._templates.set(r,a),$i(a),a.parent&&a.parent.removeChild(a),this.detached.set(e,a),a}spawn(e,t=void 0){let n=Ji(e,Yi(this.behavior.node)),r=t?.at??[],i=t?.parent??this.behavior.node;if(Cv(n)&&(r.length>0||i!==this.behavior.node)){let e=i===this.behavior.node||!Cv(this.behavior.node)?[]:KC(B(this.behavior.node),B(i));n.position=Ev(e,r.length>0?r:qC(e.length||n.position.length))}return typeof n.visible==`boolean`&&(n.visible=!0),(t?.parent??this.behavior.node).addChild(n),n}};function GC(e,t){if(t===``||t.startsWith(`%`))return null;if(t.startsWith(`/`))return t;let n=e.getPath().split(`/`);for(let e of t.split(`/`))if(!(e===``||e===`.`)){if(e===`..`){if(n.length<=1)return null;n.pop();continue}n.push(e)}return n.join(`/`)}function KC(e,t){let n=Math.max(e.length,t.length),r=[];for(let i=0;i<n;i++)r.push((e[i]??0)-(t[i]??0));return r}function qC(e){return Array.from({length:e},()=>0)}var JC=class extends Tt{static props={prefab:{default:``,nodePath:!0,required:!0},interval:{default:1},max:{default:0},at:{default:[]},autoStart:{default:!0},total:{default:0},into:{default:``,nodePath:!0}};static signals=[`spawned`,`finished`];prefab=``;interval=1;max=0;at=[];autoStart=!0;total=0;into=``;source=new WC(this);template;live=new Set;timer=0;running=!1;spawnedCount=0;done=!1;get liveCount(){return this.prune(),this.live.size}_templateForTest(){return this.template}onEnterTree(){this.template=this.source.resolveTemplate(this.prefab)}onReady(){if(!(this.interval>0)&&this.max<=0&&this.total<=0)throw new L(`PROP_TYPE_MISMATCH`,`Spawner on '${this.node.getPath()}': "interval" ${this.interval} spawns a clone every FRAME and neither "max" (live cap) nor "total" (lifetime cap) is set, so the scene grows without bound. Give it an interval, or a cap.`,{prop:`interval`});this.template=this.source.resolveTemplate(this.prefab),this.into!==``&&this.node.getNode(this.into),this.running=this.autoStart,this.timer=this.interval}start(){this.done||(this.running=!0)}stop(){this.running=!1}spawn(){if(this.prune(),this.done||this.max>0&&this.live.size>=this.max)return null;let e=this.into===``?void 0:this.node.getNode(this.into),t=this.source.spawn(this.template,this.at.length>0||e?{at:this.at,parent:e}:void 0);return this.live.add(t),this.spawnedCount+=1,this.emit(`spawned`,t),this.total>0&&this.spawnedCount>=this.total&&(this.done=!0,this.running=!1,this.emit(`finished`)),t}update(e){this.running&&(this.timer-=e,!(this.timer>0)&&(this.timer+=this.interval,this.spawn()))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}};function YC(e,t,n,r,i=`low`){if(!(n>0)||!(r>0))return null;let a=e.length>=3&&t.length>=3,o=(t[0]??0)-(e[0]??0),s=a?(t[2]??0)-(e[2]??0):0,c=a?Math.hypot(o,s):Math.abs(o);if(c<1e-6)return null;let l=a?(t[1]??0)-(e[1]??0):-((t[1]??0)-(e[1]??0)),u=n*n,d=u*u-r*(r*c*c+2*l*u);if(d<0)return null;let f=Math.sqrt(d),p=(u+(i===`high`?f:-f))/(r*c),m=Math.atan(p),h=Math.cos(m),g=Math.sin(m);return a?[o/c*h,g,s/c*h]:[Math.sign(o)*h,-g]}function XC(e,t){let n=e.length>=3&&t.length>=3,r=(t[0]??0)-(e[0]??0),i=n?(t[2]??0)-(e[2]??0):0,a=n?Math.hypot(r,i):Math.abs(r);if(a<1e-6)return null;let o=Math.SQRT1_2;return n?[r/a*o,o,i/a*o]:[Math.sign(r)*o,-o]}var ZC={CameraShake:cC,DayNight:BS,GameFlow:XS,PathFollow:yC,Health:ty,Lifetime:lC,Checkpoint:NS,Turret:class extends Tt{static props={targetGroup:{default:`enemy`},requireSight:{default:!1},range:{default:6,range:{min:0}},damage:{default:10},cooldown:{default:.6,range:{min:0}},shelf:{default:``,nodePath:!0},prefab:{default:``},muzzle:{default:[]},arc:{default:`flat`,options:[`flat`,`low`,`high`]},into:{default:``,nodePath:!0},...OS};static signals=[`acquired`,`fired`,`lost`];targetGroup=`enemy`;requireSight=!1;range=6;damage=10;cooldown=.6;shelf=``;prefab=``;muzzle=[];into=``;arc=`flat`;facePath=``;turnSpeed=100;target=null;shots=0;wait=0;onReady(){if(this.shelf===``!=(this.prefab===``))throw new L(`PROP_TYPE_MISMATCH`,`Turret on '${this.node.getPath()}': "shelf" and "prefab" go together — name both for a projectile, neither for hitscan.`,{prop:this.shelf===``?`shelf`:`prefab`,path:this.node.getPath()})}canSee(e,t){let n=this.physics;if(!n)return!0;let r=t.map((t,n)=>t-(e[n]??0)),i=Math.hypot(...r);return i<.001?!0:n.castRay(e,r,i,this.node,{staticOnly:!0})==null}update(e){if(this.wait=Math.max(0,this.wait-e),!Cv(this.node))return;let t=B(this.node),n=null,r=this.range;for(let e of this.node.tree?.getNodesInGroup(this.targetGroup)??[]){if(e===this.node||!Cv(e)||ny(e)?.health.isDead)continue;let i=Tv(t,B(e));i<=r&&(!this.requireSight||this.canSee(t,B(e)))&&(n=e,r=i)}if(n!==this.target){let e=this.target;this.target=n,n?this.emit(`acquired`,n):e&&this.emit(`lost`)}if(!n)return;let i=B(n),a=this.facePath===``?null:this.node.getNodeOrNull(this.facePath),o=this.aimAt(t,i,a);if(a&&(DS(a,o,e,this.turnSpeed),this.arc!==`flat`)){let e=a.rotation;if(Array.isArray(e)){let t=Math.hypot(o[0]??0,o[2]??0);a.rotation=[-(Math.atan2(o[1]??0,t)*180/Math.PI),e[1]??0,e[2]??0]}}this.wait>0||(this.wait=this.cooldown,this.shots+=1,this.shelf===``?ny(n)?.health.damage(this.damage,t):this.launch(n,t,o,a),this.emit(`fired`,n))}muzzleAt(e,t){if(this.muzzle.length===0)return[...e];let n=t?za(t,this.muzzle):this.muzzle;return e.map((e,t)=>e+(n[t]??0))}aimAt(e,t,n){if(this.arc===`flat`)return t.map((t,n)=>t-(e[n]??0));let r=this.muzzleAt(e,n),i=this.shellBallistics();return i?YC(r,t,i.speed,i.gravity,this.arc)??XC(r,t)??t.map((e,t)=>e-(r[t]??0)):t.map((e,t)=>e-(r[t]??0))}shellBallistics(){if(this.shelf===``||this.prefab===``)return null;let e=this.node.getNodeOrNull(this.shelf)?.behavior;if(!e||typeof e.template!=`function`)return null;let t=e.template(this.prefab)?.behavior;if(!t||typeof t.speed!=`number`||typeof t.gravity!=`number`)return null;if(!(t.gravity>0))throw new L(`PROP_TYPE_MISMATCH`,`Turret on '${this.node.getPath()}': "arc" is '${this.arc}', but '${this.prefab}' has no gravity to arc against — give its Projectile a "gravity", or leave the turret flat.`,{prop:`arc`,path:this.node.getPath()});return{speed:t.speed,gravity:t.gravity}}launch(e,t,n,r){let i=this.node.getNodeOrNull(this.shelf)?.behavior;if(!i||typeof i.make!=`function`)throw new L(`NODE_NOT_FOUND`,`Turret on '${this.node.getPath()}': "shelf" '${this.shelf}' is not a PrefabShelf.`,{prop:`shelf`,path:this.node.getPath()});let a=i.make(this.prefab);if(!Cv(a))return;let o=this.into===``?this.node.parent:this.node.getNodeOrNull(this.into);if(!o)return;let s=Math.hypot(...n)||1,c=n.map(e=>e/s),l=Cv(o)?B(o):t.map(()=>0);a.position=this.muzzleAt(t,r).map((e,t)=>e-(l[t]??0));let u=a.behavior;u&&`direction`in u&&(u.direction=c),o.addChild(a)}},ScoreKeeper:kC,Currency:LS,Pickup:wC,Collector:IS,DamageOnContact:zS,Interactable:nC,Clickable:FS,Phases:CC,SavePoint:OC,FollowCamera:GS,ChaseCamera:jS,GroupCamera:$S,Patrol:xC,Chase:kS,FaceTarget:HS,Wander:class extends Tt{static props={speed:{default:40},radius:{default:50},changeEvery:{default:2}};static signals=[];speed=40;radius=50;changeEvery=2;origin=[];goal=[];timer=0;onReady(){if(!(this.radius>0))throw new L(`PROP_TYPE_MISMATCH`,`Wander on '${this.node.getPath()}': "radius" must be > 0, got ${this.radius}.`,{prop:`radius`});let e=wv(this);this.origin=[...e.position],this.goal=[...e.position],this.pickGoal()}update(e){let t=this.node;this.timer-=e;let{position:n,reached:r}=kv(t.position,this.goal,this.speed*e);ry(t)||(t.position=n,(r||this.timer<=0)&&this.pickGoal())}pickGoal(){this.timer=this.changeEvery;let e=this.origin.length,t=e===3?1:-1,n=Array(e);for(let r=0;r<8;r++){for(let r=0;r<e;r++)n[r]=r===t?this.origin[r]??0:(this.origin[r]??0)+this.rng.range(-this.radius,this.radius);if(Tv(n,this.origin)<=this.radius){this.goal=n;return}}this.goal=n.map((e,t)=>{let r=this.origin[t]??0,i=Tv(n,this.origin)||1;return r+(e-r)/i*this.radius})}},ZombieAI:class extends Tt{static props={aggroTarget:{default:``,nodePath:!0},aggroRange:{default:12},deAggroRange:{default:0},chaseSpeed:{default:4},wanderSpeed:{default:1.4},wanderRadius:{default:8},wanderChangeEvery:{default:3},goalTarget:{default:``,nodePath:!0},stopRange:{default:1.2},moveParent:{default:!1}};static signals=[`enteredAggro`,`exitedAggro`,`movementStateChanged`];aggroTarget=``;aggroRange=12;deAggroRange=0;chaseSpeed=4;wanderSpeed=1.4;wanderRadius=8;wanderChangeEvery=3;goalTarget=``;stopRange=1.2;moveParent=!1;aggro=!1;started=!1;home=[];goal=[];timer=0;lastState=``;mover(){let e=this.moveParent?this.node.parent:this.node;return e&&Cv(e)?e:null}effectiveDeAggro(){return this.deAggroRange>0?this.deAggroRange:this.aggroRange*1.5}onReady(){if(this.moveParent){let e=this.node.parent;if(!e||!Cv(e))throw new L(`PROP_TYPE_MISMATCH`,`ZombieAI on '${this.node.getPath()}': "moveParent" needs a spatial parent (a Node2D/Node3D) to move. '${this.node.name}' has none.`,{prop:`moveParent`,path:this.node.getPath()})}else wv(this)}update(e){let t=this.mover();if(!t)return;this.started||(this.started=!0,this.home=[...t.position],this.pickGoal());let n=this.aggroTarget?this.node.getNodeOrNull(this.aggroTarget):null,r=n&&Cv(n)?Ba(t,B(n)):null,i=r?this.groundDistance(t.position,r):1/0;if(!this.aggro&&i<=this.aggroRange?(this.aggro=!0,this.emit(`enteredAggro`)):this.aggro&&i>=this.effectiveDeAggro()&&(this.aggro=!1,this.emit(`exitedAggro`),this.pickGoal()),this.aggro&&r){let n=this.approach(t,r,this.chaseSpeed,e);this.setState(n?`idle`:`run`);return}this.timer-=e;let a=this.approach(t,this.goal,this.wanderSpeed,e);this.setState(a?`idle`:`walk`),(a||this.timer<=0)&&this.pickGoal()}approach(e,t,n,r){let i=e.position;if(this.groundDistance(i,t)<=this.stopRange)return!0;let a=i.length>=3?1:-1,o=[...t];a>=0&&(o[a]=i[a]??0);let s=this.groundDistance(i,o),{position:c}=kv(i,o,Math.min(n*r,Math.max(0,s-this.stopRange)));return ry(e)||(e.position=c),!1}groundDistance(e,t){if(e.length>=3){let n=(e[0]??0)-(t[0]??0),r=(e[2]??0)-(t[2]??0);return Math.hypot(n,r)}return Tv(e,t)}setState(e){e!==this.lastState&&(this.lastState=e,this.emit(`movementStateChanged`,e))}pickGoal(){this.timer=this.wanderChangeEvery;let e=this.mover(),t=e?e.position:this.home,n=t.length>=3?1:-1,r=this.home,i=this.goalTarget?this.node.getNodeOrNull(this.goalTarget):null;if(i&&Cv(i)){let e=i.position;r=t.map((t,n)=>t+((e[n]??0)-t)*.4)}let a=[...r];for(let e=0;e<a.length;e++)e!==n&&(a[e]=(r[e]??0)+this.rng.range(-this.wanderRadius,this.wanderRadius));n>=0&&(a[n]=t[n]??0),this.goal=a}},Mount:dC,MoveTo:mC,Oscillate:vC,Spawner:JC,WaveSpawner:class extends Tt{static props={waves:{default:[],required:!0},autoStart:{default:!0}};static signals=[`spawned`,`waveStarted`,`waveCleared`,`allCleared`];waves=[];autoStart=!0;source=new WC(this);parsed=[];live=new Set;waveIndex=-1;get wave(){return this.waveIndex<0?0:Math.min(this.parsed.length,this.waveIndex+1)}get waveCount(){return this.parsed.length}phase=`idle`;timer=0;spawnedThisWave=0;announced=!1;onEnterTree(){if(!(!Array.isArray(this.waves)||this.waves.length===0))for(let e of this.waves){let t=e.prefab;typeof t==`string`&&t!==``&&this.source.resolveTemplate(t)}}onReady(){if(!Array.isArray(this.waves)||this.waves.length===0)throw new L(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': "waves" must be a non-empty array of { prefab, count, interval, delayBefore }.`,{prop:`waves`});this.parsed=this.waves.map((e,t)=>this.parseWave(e,t));for(let e of this.parsed)this.source.resolveTemplate(e.prefab);this.autoStart&&this.beginWave(0)}start(){this.beginWave(0)}serialize(){return{wave:this.waveIndex,done:this.phase===`done`}}deserialize(e){let t=e??{};if(t.done===!0){this.phase=`done`,this.waveIndex=this.parsed.length-1;return}if(typeof t.wave!=`number`||!Number.isInteger(t.wave))return;let n=Math.max(0,Math.min(t.wave,this.parsed.length-1));this.beginWave(n)}update(e){if(this.phase===`idle`||this.phase===`done`)return;let t=this.parsed[this.waveIndex];if(t){if(this.announced||(this.announced=!0,this.emit(`waveStarted`,this.waveIndex)),this.phase===`delay`){this.timer-=e,this.timer<=0&&(this.phase=`spawning`,this.timer=0);return}if(this.phase===`spawning`){for(this.timer-=e;this.timer<=0&&this.spawnedThisWave<t.count;){let e=this.source.spawn(this.source.resolveTemplate(t.prefab));this.live.add(e),this.spawnedThisWave+=1,this.emit(`spawned`,e),this.timer+=t.interval}this.spawnedThisWave>=t.count&&(this.phase=`clearing`);return}if(this.phase===`clearing`&&(this.prune(),this.live.size===0)){this.emit(`waveCleared`,this.waveIndex);let e=this.waveIndex+1;e<this.parsed.length?this.beginWave(e):(this.phase=`done`,this.emit(`allCleared`))}}}beginWave(e){this.waveIndex=e,this.spawnedThisWave=0,this.announced=!1,this.live.clear();let t=this.parsed[e];t&&(t.delayBefore>0?(this.phase=`delay`,this.timer=t.delayBefore):(this.phase=`spawning`,this.timer=0))}prune(){for(let e of this.live)e.parent===null&&this.live.delete(e)}parseWave(e,t){let n=e,r=typeof n?.prefab==`string`?n.prefab:``;if(r===``)throw new L(`PROP_TYPE_MISMATCH`,`WaveSpawner on '${this.node.getPath()}': wave ${t} needs a "prefab" template path.`,{prop:`waves`});return{prefab:r,count:typeof n?.count==`number`?n.count:1,interval:typeof n?.interval==`number`?n.interval:.5,delayBefore:typeof n?.delayBefore==`number`?n.delayBefore:0}}},Projectile:DC,Buoyancy:bS,FloatAway:US,Shatter:VC,Blast:ay,Carry:TS,Sight:UC,PrefabShelf:EC};function QC(e){let t=e?.replace??!0;for(let[e,n]of Object.entries(ZC))kt(e,n,{replace:t})}var $C=new Set;function ew(e){return $C.add(e),()=>$C.delete(e)}function tw(e,t){return[...$C].filter(n=>n.dimension===e&&(t===void 0||n.engine===t))}function nw(e,t){return t===null?e===`rope`||e===`spring`:t}var rw=`using deprecated parameters for the initialization function`;async function iw(e,t=console){let n=t.warn;t.warn=(...e)=>{typeof e[0]==`string`&&e[0].includes(rw)||n.apply(t,e)};try{await e()}finally{t.warn=n}}var aw=class extends MC{static typeName=`Joint2D`;static props={type:{default:`revolute`,options:[`fixed`,`revolute`,`prismatic`,`rope`,`spring`]},target:{default:``,nodePath:!0,required:!0},anchor:{default:[0,0]},targetAnchor:{default:[0,0]},axis:{default:[0,1]},limits:{default:[]},motorSpeed:{default:0},motorStrength:{default:20,range:{min:0}},length:{default:0},stiffness:{default:50},damping:{default:5},collide:{default:null,kinds:[`null`,`boolean`]}};type=`revolute`;target=``;anchor=[0,0];targetAnchor=[0,0];limits=[];motorSpeed=0;motorStrength=20;angle=0;axis=[0,1];travel=0;length=0;stiffness=50;damping=5;collide=null;onEnterTree(){if(!(this.parent instanceof NC))throw new L(`TREE_VIOLATION`,`Joint2D '${this.name}' must be a child of a physics body (its body A); parent is '${this.parent?.name??`none`}'.`);if(this.target===``)throw new L(`BAD_FORMAT`,`Joint2D '${this.name}' needs a "target" node path to the body it links to.`);if(this.type===`prismatic`&&!(Math.hypot(this.axis[0]??0,this.axis[1]??0)>1e-6))throw new L(`BAD_FORMAT`,`Joint2D '${this.name}': a prismatic joint needs a non-zero "axis" (got ${JSON.stringify(this.axis)}).`);if((this.type===`revolute`||this.type===`prismatic`)&&this.limits.length!==0&&this.limits.length!==2)throw new L(`BAD_FORMAT`,`Joint2D '${this.name}': "limits" is [minDeg, maxDeg] or [] (got ${JSON.stringify(this.limits)}).`)}_resolveBodies(){let e=this.parent,t=this.getNodeOrNull(this.target);if(!(t instanceof NC))throw new L(`NODE_NOT_FOUND`,`Joint2D '${this.name}': target '${this.target}' is not a physics body.`);if(e===t)throw new L(`BAD_FORMAT`,`Joint2D '${this.name}': target '${this.target}' is the SAME body this joint hangs off, so it constrains nothing. A joint is a child of ONE body pointing at the OTHER — name the other body (e.g. "%Crate").`,{prop:`target`,path:this.getPath()});return{a:e,b:t}}},Z=100,ow=Math.PI/180;async function sw(e,t){let n=await Iv(()=>import(`./rapier-CEuLKeCu.js`),[],import.meta.url);return await iw(()=>n.init()),new cw(n,e,t)}var cw=class{R;engine;debugDraw=!1;debugScope=null;dimension=`2d`;unregisterDebug;warnedNoCollider=new WeakSet;entries=new Map;byColliderHandle=new Map;world;events;kcc;disconnectScene;disconnect;lastDt=1/60;optsGravity;lastScene=null;constructor(e,t,n){this.R=e,this.engine=t,this.optsGravity=n?.gravity,this.simulate=n?.simulate??!0,this.lastScene=t.scene;let r=t.scene?.physics?.gravity,i=n?.gravity??r??[0,980];this.world=new e.World({x:(i[0]??0)/Z,y:(i[1]??0)/Z}),this.kcc=this.world.createCharacterController(.01),this.kcc.setUp({x:0,y:-1}),this.events=new e.EventQueue(!0),this.unregisterDebug=ew(this),this.disconnect=t.fixedUpdated.connect(e=>this.step(e)),this.disconnectScene=t.sceneChanged.connect(()=>{this.pruneOverlaps(),t.scene&&this.syncBodies()}),t.physics=this,this.syncBodies()}simulate;step(e){if(this.lastDt=e,!this.simulate){this.syncBodies(),this.poseFromTree();return}if(this.engine.scene!==this.lastScene&&(this.lastScene=this.engine.scene,!this.optsGravity)){let e=this.engine.scene?.physics?.gravity??[0,980];this.world.gravity={x:(e[0]??0)/Z,y:(e[1]??0)/Z}}this.syncBodies(),this.world.timestep=e,this.world.step(this.events);for(let[e,t]of this.entries){let n=t.body.translation();if(!t.body.isFixed()&&!(e instanceof FC)){let[t,r,i]=vw(e),a=n.x*Z-t,o=n.y*Z-r;if(i!==0){let t=-i*ow;e.position=[a*Math.cos(t)-o*Math.sin(t),a*Math.sin(t)+o*Math.cos(t)]}else e.position=[a,o]}if(e instanceof IC){e.fixedRotation||(e.rotation=t.body.rotation()/ow-vw(e)[2],t.lastRot=t.body.rotation()/ow);let n=t.body.linvel();e.linearVelocity=[n.x*Z,n.y*Z],e.angularVelocity=t.body.angvel(),t.lastVX=e.linearVelocity[0]??0,t.lastVY=e.linearVelocity[1]??0,t.lastAV=e.angularVelocity}let r=t.body.translation();t.lastX=r.x*Z,t.lastY=r.y*Z}this.events.drainCollisionEvents((e,t,n)=>{let r=this.byColliderHandle.get(e),i=this.byColliderHandle.get(t);if(!r||!i||!r.enabled||!i.enabled)return;let a=n?`triggerEnter`:`triggerExit`;if(n!==(this.overlaps.get(r)?.has(i)??!1)){this.trackOverlap(r,i,n),this.trackOverlap(i,r,n);try{r.emit(a,i),i.emit(a,r)}catch(e){z(this.engine,`error`,`incanto: error in a '${a}' handler (${r.name} ↔ ${i.name}):`,e)}}})}canCarry(e,t){if(this.jointed.get(e)?.has(t))return!1;let n=t;for(let t=0;t<8&&n;t++){if(n===e)return!1;n=this.entries.get(n)?.ground??null}return!0}moveAndSlide(e){let t=this.ensureEntry(e),n=e.velocity[1]??0;e.stickToGround&&n>=0?this.kcc.enableSnapToGround(.05):this.kcc.disableSnapToGround(),this.kcc.setMaxSlopeClimbAngle(e.slopeLimitDeg*ow),e.stepHeight>0?this.kcc.enableAutostep(e.stepHeight/Z,e.stepHeight/Z/2,!1):this.kcc.disableAutostep();let r=0,i=0;if(t.ground&&t.ground._physics===this){let[e,n]=_w(t.ground);r=e-(t.groundX??e),i=n-(t.groundY??n);let a=this.entries.get(t.ground);if(a&&t.groundRot!==void 0&&t.riderX!==void 0&&t.riderY!==void 0){let o=a.body.rotation()-t.groundRot,s=t.riderX-(t.groundX??e),c=t.riderY-(t.groundY??n);r+=s*Math.cos(o)-c*Math.sin(o)-s,i+=s*Math.sin(o)+c*Math.cos(o)-c}}else t.ground=null;let a=i<-.1&&e.isOnFloor?.()===!0&&n>0?0:n*this.lastDt,o={x:((e.velocity[0]??0)*this.lastDt+r)/Z*1,y:(a+i)/Z*1},s=t.body.translation().y*Z+fw(e),c=t=>{let r=this.byColliderHandle.get(t.handle);return!(r&&r!==e&&r.collider.oneWay===!0&&(n<0||s>pw(r)+dw))},l=this.jointed.get(e);this.kcc.setApplyImpulsesToDynamicBodies(e.pushes>0),e.pushes>0&&this.kcc.setCharacterMass(e.pushes),this.kcc.computeColliderMovement(t.collider,o,this.R.QueryFilterFlags.EXCLUDE_SENSORS,void 0,t=>{let n=this.byColliderHandle.get(t.handle);return!e.collideWithCharacters&&n instanceof LC||n&&l?.get(n)===!1?!1:c(t)});let u=this.kcc.computedMovement(),d=t.body.translation();t.body.setNextKinematicTranslation({x:d.x+u.x,y:d.y+u.y}),e._grounded=this.kcc.computedGrounded(),e._onWall=0,e._onCeiling=!1;let f=this.kcc.numComputedCollisions();for(let t=0;t<f;t++){let n=this.kcc.computedCollision(t)?.normal1;n&&(n.y>.7?e._grounded||(e._onCeiling=!0):Math.abs(n.x)>.7&&(e._onWall=n.x>0?-1:1))}if(e._grounded){let n=(d.x+u.x)*Z,r=(d.y+u.y)*Z+fw(e)-2,i=this.castRay([n,r],[0,1],8,e);if(i?.node&&this.canCarry(e,i.node)){t.ground=i.node;let[r,a]=_w(i.node);t.groundX=r,t.groundY=a,t.groundRot=this.entries.get(i.node)?.body.rotation(),t.riderX=n,t.riderY=(d.y+u.y)*Z+fw(e)}else t.ground=null}else t.ground=null}debugLines(){if(!this.debugDraw)return null;let e=this.debugScope?this.scopedLines(this.debugScope):this.world.debugRender().vertices,t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]*Z;return t}scopedLines(e){let t=[],n=[],r=e=>{let t=this.entries.get(e);t&&n.push(t.body);for(let t of e.children)r(t)};r(e);for(let t=e.parent;t&&n.length===0;t=t.parent){let e=this.entries.get(t);e&&n.push(e.body)}for(let e of n)for(let n=0;n<e.numColliders();n++){let r=e.collider(n);if(!r)continue;let i=r.translation(),a=r.rotation(),o=Math.cos(a),s=Math.sin(a),c=(e,n)=>{t.push(i.x+e*o-n*s,i.y+e*s+n*o)},l=(e,t,n,r)=>{c(e,t),c(n,r)},u=r.shape;if(u.halfExtents){let{x:e,y:t}=u.halfExtents;l(-e,-t,e,-t),l(e,-t,e,t),l(e,t,-e,t),l(-e,t,-e,-t)}else if(u.radius!==void 0){let e=u.radius,t=u.halfHeight??0;for(let n=0;n<24;n++){let r=n/24*Math.PI*2,i=(n+1)/24*Math.PI*2,a=e=>e>=0?t:-t;l(Math.cos(r)*e,Math.sin(r)*e+a(Math.sin(r)),Math.cos(i)*e,Math.sin(i)*e+a(Math.sin(i)))}t>0&&(l(-e,-t,-e,t),l(e,-t,e,t))}}return new Float32Array(t)}syncJoints(e){let t=this.R;if(e){for(let[e,t]of this.joints)if(!this.jointSet.has(e)){this.world.removeImpulseJoint(t,!0),this.joints.delete(e);let n=this.jointBodies.get(e);n&&this.unlinkJointed(n[0],n[1]),this.jointBodies.delete(e),this.hingeState.delete(e),this.tetherState.delete(e)}}for(let e of this.jointSet){if(this.joints.has(e)||this.refusedJoints.has(e))continue;let{a:n,b:r}=e._resolveBodies(),i=this.entries.get(n),a=this.entries.get(r);if(!i||!a)continue;if(e.type===`prismatic`){let t=Math.abs(i.body.rotation()-a.body.rotation())/ow;if(t=Math.abs((t+180)%360-180),t>.5){this.refusedJoints.add(e),z(this.engine,`error`,`[incanto] Joint2D '${e.getPath()}': its two bodies disagree about the slide axis by ${t.toFixed(1)}° — '${n.name}' and '${r.name}' are authored with different rotations, and Rapier reads the axis in BOTH bodies' local frames. Give both bodies the same rotation. The joint was not made.`);continue}}let o={x:(e.anchor[0]??0)/Z,y:(e.anchor[1]??0)/Z},s={x:(e.targetAnchor[0]??0)/Z,y:(e.targetAnchor[1]??0)/Z},c=e.length/Z;if(e.length===0&&(e.type===`rope`||e.type===`spring`)){let e=i.body.translation(),t=a.body.translation();c=Math.hypot(t.x-e.x,t.y-e.y)}let l;if(e.type===`fixed`)l=t.JointData.fixed(o,0,s,0);else if(e.type===`rope`)l=t.JointData.rope(c,o,s);else if(e.type===`spring`)l=t.JointData.spring(c,e.stiffness,e.damping,o,s);else if(e.type===`prismatic`){let n=e.axis[0]??0,r=e.axis[1]??0,i=Math.hypot(n,r)||1;l=t.JointData.prismatic(o,s,{x:n/i,y:r/i})}else l=t.JointData.revolute(o,s);let u=this.world.createImpulseJoint(l,i.body,a.body,!0);(e.type===`revolute`||e.type===`prismatic`)&&this.applyHinge(e,u,!0);let d=nw(e.type,e.collide);u.setContactsEnabled(d),this.joints.set(e,u),this.jointBodies.set(e,[n,r]),this.linkJointed(n,r,d),(e.type===`rope`||e.type===`spring`)&&this.tetherState.set(e,this.tetherKey(e))}for(let[e,t]of this.joints){if(e.type!==`rope`&&e.type!==`spring`)continue;let n=this.tetherKey(e);if(this.tetherState.get(e)===n)continue;this.world.removeImpulseJoint(t,!0),this.joints.delete(e);let r=this.jointBodies.get(e);r&&this.unlinkJointed(r[0],r[1]),this.jointBodies.delete(e),this.tetherState.delete(e)}for(let[e,t]of this.joints){if(e.type!==`revolute`&&e.type!==`prismatic`)continue;this.applyHinge(e,t,!1);let n=this.jointBodies.get(e),r=n&&this.entries.get(n[0]),i=n&&this.entries.get(n[1]);if(!(!r||!i))if(e.type===`revolute`){let t=(r.body.rotation()-i.body.rotation())/ow;t=((t+180)%360+360)%360-180,e.angle=t}else{let t=r.body.rotation(),n=i.body.rotation(),a=r.body.translation(),o=i.body.translation(),[s,c]=[e.anchor[0]??0,e.anchor[1]??0],[l,u]=[e.targetAnchor[0]??0,e.targetAnchor[1]??0],d=a.x*Z+s*Math.cos(t)-c*Math.sin(t),f=a.y*Z+s*Math.sin(t)+c*Math.cos(t),p=o.x*Z+l*Math.cos(n)-u*Math.sin(n),m=o.y*Z+l*Math.sin(n)+u*Math.cos(n),[h,g]=[e.axis[0]??0,e.axis[1]??0],_=Math.hypot(h,g)||1,v=(h*Math.cos(t)-g*Math.sin(t))/_,y=(h*Math.sin(t)+g*Math.cos(t))/_;e.travel=(d-p)*v+(f-m)*y}}}overlaps=new Map;trackOverlap(e,t,n){let r=this.overlaps.get(e);n?(r||(r=new Set,this.overlaps.set(e,r)),r.add(t)):r&&(r.delete(t),r.size===0&&this.overlaps.delete(e))}forgetOverlaps(e){this.overlaps.delete(e);for(let[t,n]of this.overlaps)n.delete(e),n.size===0&&this.overlaps.delete(t)}releaseOverlaps(e){let t=this.overlaps.get(e);if(!(!t||t.size===0))for(let n of[...t]){this.trackOverlap(e,n,!1),this.trackOverlap(n,e,!1);try{e.emit(`triggerExit`,n),n.emit(`triggerExit`,e)}catch(t){z(this.engine,`error`,`incanto: error in a 'triggerExit' handler (${e.name} ↔ ${n.name}):`,t)}}}armOverlaps(e,t){let n=[],r=t.translation();this.world.intersectionsWithShape({x:r.x,y:r.y},t.rotation(),t.shape,t=>{let r=this.byColliderHandle.get(t.handle);return r&&r!==e&&t.isEnabled()&&n.push(r),!0},void 0,void 0,t);for(let t of n)if(!this.overlaps.get(e)?.has(t)){this.trackOverlap(e,t,!0),this.trackOverlap(t,e,!0);try{e.emit(`triggerEnter`,t),t.emit(`triggerEnter`,e)}catch(n){z(this.engine,`error`,`incanto: error in a 'triggerEnter' handler (${e.name} ↔ ${t.name}):`,n)}}}pruneOverlaps(){for(let[e,t]of this.overlaps){if(e.tree===null){this.overlaps.delete(e);continue}for(let e of t)e.tree===null&&t.delete(e);t.size===0&&this.overlaps.delete(e)}}overlapping(e){let t=this.overlaps.get(e);if(!t)return[];for(let e of t)e.tree===null&&t.delete(e);return[...t]}massOf(e){return this.entries.get(e)?.body.mass()??1}rotationOf(e){let t=this.entries.get(e);return t?t.body.rotation()/ow:0}velocityOf(e){let t=this.entries.get(e)?.body.linvel();return t?[t.x*Z,t.y*Z]:[0,0]}applyImpulse(e,t){let n=this.entries.get(e);if(n){if(e instanceof IC){let t=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(t!==n.lastVX||r!==n.lastVY)&&n.body.setLinvel({x:t/Z,y:r/Z},!0)}if(n.body.applyImpulse({x:t[0]/Z,y:t[1]/Z},!0),e instanceof IC){let t=n.body.linvel();e.linearVelocity=[t.x*Z,t.y*Z],n.lastVX=e.linearVelocity[0]??0,n.lastVY=e.linearVelocity[1]??0}}}castRay(e,t,n,r,i){let a=Math.hypot(t[0],t[1]);if(!(a>0))return null;let o=new this.R.Ray({x:e[0]/Z,y:e[1]/Z},{x:t[0]/a,y:t[1]/a}),s=r?this.entries.get(r)?.collider:void 0,c=i?.staticOnly?this.R.QueryFilterFlags.EXCLUDE_DYNAMIC|this.R.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,l=this.world.castRayAndGetNormal(o,n/Z,!0,c,void 0,s,void 0,e=>!e.isSensor());if(!l)return null;let u=l.timeOfImpact*Z;return{distance:u,normal:[l.normal.x,l.normal.y],node:this.byColliderHandle.get(l.collider.handle)??null,point:[e[0]+t[0]/a*u,e[1]+t[1]/a*u]}}castSphere(e,t,n,r,i,a){let o=this.R,s=Math.hypot(t[0],t[1]);if(!(s>0))return null;let c=i?this.entries.get(i):void 0,l=a?.staticOnly?o.QueryFilterFlags.EXCLUDE_DYNAMIC|o.QueryFilterFlags.EXCLUDE_KINEMATIC:void 0,u=this.world.castShape({x:e[0]/Z,y:e[1]/Z},0,{x:t[0]/s,y:t[1]/s},new o.Ball(n/Z),0,r/Z,!0,l,void 0,c?.collider,c?.body,e=>!e.isSensor());return u?{distance:u.time_of_impact*Z,node:this.byColliderHandle.get(u.collider.handle)??null}:null}dispose(){this.disconnect(),this.disconnectScene(),this.unregisterDebug(),this.engine.physics===this&&(this.engine.physics=null),this.world.free()}lastStructure=-1;lastRoot=null;jointSet=new Set;joints=new Map;jointBodies=new Map;hingeState=new Map;refusedJoints=new Set;tetherState=new Map;tetherKey(e){return`${e.length}/${e.stiffness}/${e.damping}`}jointed=new Map;linkJointed(e,t,n){for(let[r,i]of[[e,t],[t,e]]){let e=this.jointed.get(r);e||(e=new Map,this.jointed.set(r,e)),e.set(i,n)}}unlinkJointed(e,t){this.jointed.get(e)?.delete(t),this.jointed.get(t)?.delete(e)}applyHinge(e,t,n){let r=JSON.stringify(e.limits),i=`${e.motorSpeed}/${e.motorStrength}`,a=this.hingeState.get(e),o=t,s=e.type===`revolute`?ow:1/Z;if(n||a?.limits!==r)if(e.limits.length===2){let t=(e.limits[0]??0)*s,n=(e.limits[1]??0)*s;o.setLimits(-Math.max(t,n),-Math.min(t,n))}else n||o.setLimits(-1e9,1e9);if((n||a?.motor!==i)&&(e.motorSpeed===0?n||o.configureMotorVelocity(0,0):o.configureMotorVelocity(-e.motorSpeed*s,e.motorStrength)),this.hingeState.set(e,{limits:r,motor:i}),e.motorSpeed!==0){let t=this.jointBodies.get(e);for(let e of t??[]){let t=this.entries.get(e);t&&!t.body.isFixed()&&t.body.isSleeping()&&t.body.wakeUp()}}}bodySet=new Set;poseFromTree(){for(let[e,t]of this.entries){let[n,r,i]=gw(e);t.body.setTranslation({x:n/Z,y:r/Z},!1),t.body.setRotation(i*ow,!1)}this.world.propagateModifiedBodyPositionsToColliders()}syncBodies(){let e=this.engine.scene;if(!e)return;let t=e.tree._structureVersion,n=e.root===this.lastRoot,r=t!==this.lastStructure||!n;if(r){let r=n?e.tree._structureSince(this.lastStructure):null;if(this.lastStructure=t,this.lastRoot=e.root,r){let t=!1;for(let{node:e,added:n}of r)e instanceof NC&&(n?this.bodySet.add(e):this.bodySet.delete(e)),e instanceof aw&&(t=!0);t&&(this.jointSet.clear(),lw(e.root,this.jointSet))}else this.bodySet.clear(),uw(e.root,this.bodySet),this.jointSet.clear(),lw(e.root,this.jointSet)}let i=this.bodySet;for(let e of i){if(e.collider.shape===void 0){let t=this.entries.get(e);t&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.warnedNoCollider.has(e)||(this.warnedNoCollider.add(e),z(this.engine,`warn`,`[incanto] '${e.name}' has no collider — physics skips it.`));continue}let t=this.entries.get(e);t&&e._colliderChanged&&(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),e._physics=null),this.ensureEntry(e)}if(this.syncJoints(r),r)for(let[e,t]of this.entries)i.has(e)||(this.byColliderHandle.delete(t.collider.handle),this.world.removeRigidBody(t.body),this.entries.delete(e),this.forgetOverlaps(e),e._physics=null)}ensureEntry(e){let t=this.entries.get(e),n=this.R;if(!t){let[r,i,a]=gw(e),o=r/Z,s=i/Z,c,l=e instanceof IC;c=l?n.RigidBodyDesc.dynamic():e instanceof LC||e instanceof FC?n.RigidBodyDesc.kinematicPositionBased():n.RigidBodyDesc.fixed(),c.setTranslation(o,s).setRotation(a*ow),e instanceof IC&&(c.setGravityScale(e.gravityScale),c.setLinearDamping(e.linearDamping).setAngularDamping(e.angularDamping),c.setLinvel((e.linearVelocity[0]??0)/Z,(e.linearVelocity[1]??0)/Z),c.setAngvel(e.fixedRotation?0:e.angularVelocity),e.fixedRotation&&c.lockRotations());let u=this.world.createRigidBody(c),d=yw(n,e.collider,e.name);d.setActiveEvents(n.ActiveEvents.COLLISION_EVENTS),d.setActiveCollisionTypes(n.ActiveCollisionTypes.ALL),e instanceof FC&&d.setSensor(!0),e instanceof IC&&d.setMass(e.mass),(e instanceof IC||e instanceof PC)&&xw(n,d,e);let f=this.world.createCollider(d,u);return t={body:u,collider:f,lastX:r,lastY:i,lastRot:a,lastVX:0,lastVY:0,lastAV:l?e.angularVelocity:0,lastMass:l?e.mass:1,lastFriction:e.friction??.5,lastRestitution:e.restitution??0,lastGravityScale:l?e.gravityScale:1,lastLinDamp:l?e.linearDamping:0,lastAngDamp:l?e.angularDamping:0},this.entries.set(e,t),this.byColliderHandle.set(f.handle,e),e.enabled||(f.setEnabled(!1),u.setEnabled(!1)),e._colliderChanged=!1,e._enabledChanged=!1,e._physics=this,t}e._enabledChanged&&(e.enabled||this.releaseOverlaps(e),t.collider.setEnabled(e.enabled),t.body.setEnabled(e.enabled),e._enabledChanged=!1,e.enabled&&this.armOverlaps(e,t.collider));let[r,i,a]=gw(e);if((r!==t.lastX||i!==t.lastY)&&(t.body.setTranslation({x:r/Z,y:i/Z},!0),t.lastX=r,t.lastY=i),a!==t.lastRot&&(t.body.setRotation(a*ow,!0),t.lastRot=a),e instanceof IC){let n=e.linearVelocity[0]??0,r=e.linearVelocity[1]??0;(n!==t.lastVX||r!==t.lastVY)&&(t.body.setLinvel({x:n/Z,y:r/Z},!0),t.lastVX=n,t.lastVY=r),e.angularVelocity!==t.lastAV&&(t.body.setAngvel(e.angularVelocity,!0),t.lastAV=e.angularVelocity),e.gravityScale!==t.lastGravityScale&&(t.body.setGravityScale(e.gravityScale,!0),t.lastGravityScale=e.gravityScale),e.mass!==t.lastMass&&(t.collider.setMass(e.mass),t.lastMass=e.mass),(e.friction!==t.lastFriction||e.restitution!==t.lastRestitution)&&(xw(this.R,t.collider,e),t.lastFriction=e.friction,t.lastRestitution=e.restitution),e.linearDamping!==t.lastLinDamp&&(t.body.setLinearDamping(e.linearDamping),t.lastLinDamp=e.linearDamping),e.angularDamping!==t.lastAngDamp&&(t.body.setAngularDamping(e.angularDamping),t.lastAngDamp=e.angularDamping)}else e instanceof PC&&(e.friction!==t.lastFriction||e.restitution!==t.lastRestitution)&&(xw(this.R,t.collider,e),t.lastFriction=e.friction,t.lastRestitution=e.restitution);return t}};function lw(e,t){e instanceof aw&&t.add(e);for(let n of e.children)lw(n,t)}function uw(e,t){e instanceof NC&&t.add(e);for(let n of e.children)uw(n,t)}var dw=4;function fw(e){let t=e.collider;return t.shape===`rect`?(t.size?.[1]??32)/2:t.shape===`capsule`?(t.height??32)/2+(t.radius??8):t.radius??16}function pw(e){let[,t]=_w(e),n=e.collider;return t-(n.shape===`rect`?(n.size?.[1]??32)/2:n.shape===`capsule`?(n.height??32)/2+(n.radius??8):n.radius??16)}var mw=[],hw=[0,0,0];function gw(e){mw.length=0;for(let t=e;t;t=t.parent)t instanceof MC&&mw.push(t);let t=0,n=0,r=0;for(let e=mw.length-1;e>=0;e--){let i=mw[e],a=i.position[0]??0,o=i.position[1]??0;if(r!==0){let e=r*ow,i=Math.cos(e),s=Math.sin(e);t+=a*i-o*s,n+=a*s+o*i}else t+=a,n+=o;r+=i.rotation}return hw[0]=t,hw[1]=n,hw[2]=r,hw}function _w(e){let t=gw(e);return[t[0],t[1]]}function vw(e){let t=null;for(let n=e.parent;n;n=n.parent)if(n instanceof MC){t=n;break}let n=gw(t);return[n[0],n[1],n[2]]}function yw(e,t,n){jC(t,n);let r=bw(e,t,n),i=t.offset;return Array.isArray(i)&&r.setTranslation((i[0]??0)/Z,(i[1]??0)/Z),r}function bw(e,t,n){let r=t.shape;if(r===`rect`){let r=t.size;if(!Array.isArray(r)||r.length!==2||r.some(e=>typeof e!=`number`))throw new L(`BAD_FORMAT`,`Collider on '${n}': rect needs "size": [width, height].`);return e.ColliderDesc.cuboid(r[0]/2/Z,r[1]/2/Z)}if(r===`circle`){if(typeof t.radius!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': circle needs "radius".`);return e.ColliderDesc.ball(t.radius/Z)}if(r===`capsule`){if(typeof t.radius!=`number`||typeof t.height!=`number`)throw new L(`BAD_FORMAT`,`Collider on '${n}': capsule needs "radius" and "height".`);return e.ColliderDesc.capsule(t.height/2/Z,t.radius/Z)}throw new L(`BAD_FORMAT`,`Collider on '${n}': "shape" must be 'rect', 'circle', or 'capsule', got ${JSON.stringify(r)}.`)}function xw(e,t,n){let r=e.CoefficientCombineRule;t.setFriction(n.friction),t.setFrictionCombineRule(n.friction===.5?r.Average:n.friction<.5?r.Min:r.Max),t.setRestitution(n.restitution),t.setRestitutionCombineRule(n.restitution>0?r.Max:r.Average)}function Sw(e){let t=[];for(let n=2;n<=32;n++)e%n===0&&t.push(e/n);return t.sort((e,t)=>t-e).slice(0,6)}function Cw(e,t,n,r,i,a,o=`frame`){if(!r||!i||!t||!n)return null;if(r%t!==0||i%n!==0){let a=[];if(r%t!==0){let e=Sw(r);a.push(`${r} px wide is not a whole number of ${t} px frames`+(e.length>0?` (${e.join(`, `)} would divide it)`:``))}if(i%n!==0){let e=Sw(i);a.push(`${i} px tall is not a whole number of ${n} px frames`+(e.length>0?` (${e.join(`, `)} would divide it)`:``))}return`[incanto] spritesheet '${e}' does not fit its frame size: ${a.join(`; `)}. Every row after the first is cut off centre.`}if(a!==void 0){let s=r/t*(i/n);if(a>=s){let t=o===`tile`?`tile atlas`:`spritesheet`,n=o===`tile`?`a cell asks for tile`:`an animation asks for frame`;return`[incanto] ${t} '${e}' has ${s} ${o}s (0–${s-1}), and ${n} ${a}. Those ${o}s draw whatever is at the wrong end of the sheet.`}}return null}var ww=new Zf(1,1),Tw=class extends MC{static typeName=`Sprite2D`;static props={texture:{default:``,asset:{kind:`texture`,refOnly:!0}},anchor:{default:[.5,.5]},flipX:{default:!1},flipY:{default:!1},tint:{default:`#ffffff`},opacity:{default:1,range:{min:0,max:1}}};texture=``;anchor=[.5,.5];flipX=!1;flipY=!1;tint=`#ffffff`;opacity=1;quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Ld(ww,new Td({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_createObject2D(){return super._createObject2D()}resolveTexture(e){if(!this.texture||!e)return null;let t=e.getTexture(this.texture),n=t.image;return!n?.width||!n.height?null:{texture:t,width:n.width,height:n.height}}_staticReady(e){return this.texture===``||this.resolveTexture(e)!==null}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=t.material,r=this.resolveTexture(e);if(!r){t.visible=!1;return}t.visible=!0,n.map!==r.texture&&(n.map=r.texture,n.needsUpdate=!0);let i=r.width,a=r.height;t.scale.set(this.flipX?-i:i,this.flipY?-a:a,1);let o=this.anchor[0]??.5,s=this.anchor[1]??.5;t.position.set((.5-o)*i,(s-.5)*a,0),t.renderOrder=this.effectiveRenderOrder,n.color.set(this.tint),n.opacity=this.opacity}free(){(this.quadMesh?.material)?.dispose(),this.quadMesh=null,super.free()}},Ew=class extends Tw{static typeName=`AnimatedSprite2D`;static signals=[`animationFinished`];static props={sheet:{default:``,asset:{kind:`spritesheet`,refOnly:!0}},animations:{default:{}},autoplay:{default:``}};sheet=``;animations={};autoplay=``;playing=!1;currentFrame=0;currentAnimation=``;frameList=[];frameIndex=0;frameTime=0;currentDef=null;ownTexture=null;loadedSheetRef=``;play(e){let{name:t,def:n}=Fo(this.animations,e,this.name);this.currentAnimation=t,this.currentDef=n,this.frameList=Ro(n.frames,t),this.frameIndex=0,this.currentFrame=this.frameList[0]??0,this.frameTime=0,this.playing=!0}stop(){this.playing=!1}onReady(){Lo(this.animations,this.name),this.autoplay&&this.play(this.autoplay)}update(e){if(!this.playing||this.currentAnimation===``)return;let t=this.currentDef;if(!t||!Number.isFinite(t.fps)||t.fps<=0)return;let n=1/t.fps;for(this.frameTime+=e;this.frameTime>=n;)if(this.frameTime-=n,this.frameIndex+=1,this.frameIndex>=this.frameList.length)if(t.loop)this.frameIndex=0;else{this.frameIndex=this.frameList.length-1,this.playing=!1,this.emit(`animationFinished`,this.currentAnimation);break}this.currentFrame=this.frameList[this.frameIndex]??0}gridChecked=``;checkGrid(e,t,n,r,i){if(this.gridChecked===e)return;this.gridChecked=e;let a=0;for(let[e,t]of Object.entries(this.animations))if(typeof t!=`string`)try{for(let n of Ro(t.frames,e))n>a&&(a=n)}catch{return}let o=Cw(e,t,n,r,i,a);o&&z(this.tree?.engine??null,`error`,o)}resolveTexture(e){if(!this.sheet||!e)return null;let t=e.getSheet(this.sheet);this.loadedSheetRef!==this.sheet&&(this.ownTexture=t.texture.clone(),this.ownTexture.needsUpdate=!0,this.loadedSheetRef=this.sheet);let n=this.ownTexture,r=t.texture.image;if(!r?.width||!r.height)return null;this.checkGrid(this.sheet,t.frameWidth,t.frameHeight,r.width,r.height);let i=Math.max(1,Math.floor(r.width/t.frameWidth)),a=this.currentFrame%i,o=Math.floor(this.currentFrame/i);return n.repeat.set(t.frameWidth/r.width,t.frameHeight/r.height),n.offset.set(a*t.frameWidth/r.width,1-(o+1)*t.frameHeight/r.height),{texture:n,width:t.frameWidth,height:t.frameHeight}}},Dw=class e extends MC{static typeName=`Camera2D`;static props={follow:{default:``,nodePath:!0},smoothing:{default:0},zoom:{default:1},limits:{default:[]},current:{default:!1},blendSeconds:{default:0,range:{min:0}}};follow=``;smoothing=0;zoom=1;limits=[];current=!1;makeCurrent(t=void 0){let n=this.tree?.root??this.getRoot(),r=t=>{t instanceof e&&(t.current=t===this);for(let e of t.children)r(e)};r(n),this.current=!0,this._blendRequest=t}blendSeconds=0;_blendRequest=void 0;get effectiveZoom(){return Math.max(.01,this.zoom)}warnedFollow=``;update(e){if(!this.follow)return;let t=this.getNodeOrNull(this.follow);if(!(t instanceof MC)){if(this.warnedFollow!==this.follow){this.warnedFollow=this.follow;let e=t?`a ${t.constructor.typeName??`Node`}`:`nothing`;z(this.tree?.engine??null,`warn`,`[incanto] ${this.getPath()}: follow '${this.follow}' is ${e}, which has no position for the camera to track — the view will not move. Point it at a Node2D.`)}return}let[n=0,r=0]=B(t),[i=0,a=0]=B(this),o=Math.min(Math.max(this.smoothing,0),.99),s=o<=0?1:1-o**(e*60),[c=0,l=0]=Ba(this,[i+(n-i)*s,a+(r-a)*s]);this.position=[c,l]}clampedCenter(e,t){let n=B(this),r=n[0]??0,i=n[1]??0;if(this.limits.length!==0&&this.limits.length!==4)throw new L(`BAD_FORMAT`,`Camera2D '${this.name}' limits must be [] or [minX,minY,maxX,maxY], got length ${this.limits.length}.`);if(this.limits.length===4){let[n,a,o,s]=this.limits,c=e/(2*this.effectiveZoom),l=t/(2*this.effectiveZoom);r=Ow(r,n+c,o-c),i=Ow(i,a+l,s-l)}return{x:r,y:i}}};function Ow(e,t,n){return t>n?(t+n)/2:Math.min(n,Math.max(t,e))}var kw={moveAction:`move`,jumpAction:`jump`,dashAction:`dash`,crouchAction:`crouch`},Aw=class extends Ht{static typeName=`CharacterController2D`;static props={mode:{default:`platformer`,options:[`platformer`,`topDown`]},maxSpeed:{default:220},jumpHeight:{default:64},moveAction:{default:`move`},jumpAction:{default:`jump`},coyoteSeconds:{default:0},jumpBufferSeconds:{default:0},jumpCutMultiplier:{default:1},maxJumps:{default:1},dashSpeed:{default:0},dashSeconds:{default:.15},dashAction:{default:`dash`},wallSlideSpeed:{default:0},wallJumpImpulse:{default:[0,0]},crouchHeight:{default:0,range:{min:0}},crouchSpeedMultiplier:{default:.5,range:{min:0}},crouchAction:{default:`crouch`}};static signals=[`movementStateChanged`];mode=`platformer`;maxSpeed=220;jumpHeight=64;moveAction=`move`;jumpAction=`jump`;coyoteSeconds=0;jumpBufferSeconds=0;jumpCutMultiplier=1;maxJumps=1;dashSpeed=0;dashSeconds=.15;dashAction=`dash`;crouchHeight=0;crouchSpeedMultiplier=.5;crouchAction=`crouch`;crouching=!1;standingHeight=0;wallSlideSpeed=0;wallJumpImpulse=[0,0];state=`idle`;coyoteLeft=0;bufferLeft=0;jumpsUsed=0;dashLeft=0;dashDir=1;rising=!1;onReady(){if(!(this.parent instanceof LC))throw new L(`TREE_VIOLATION`,`CharacterController2D '${this.name}' must be a child of a CharacterBody2D (parent is '${this.parent?.name??`none`}').`);if(this.mode!==`platformer`&&this.mode!==`topDown`)throw new L(`PROP_TYPE_MISMATCH`,`CharacterController2D.mode must be 'platformer' or 'topDown', got '${this.mode}'.`)}fixedUpdate(e){let t=this.tree?.engine;if(!t?.scene)return;let n=this.parent;if(!(n instanceof LC))return;let r=t.input,i=this.readAction(`moveAction`,()=>r.getVector(this.moveAction),{x:0,y:0},`the character will not move`),a=ny(n)?.health??null;(a?.staggered??!1)&&(i.x=0,i.y=0);let o=a?.knocked?a.kickVelocity:[],s=a?.knocked?a.takeLift():0;if(this.mode===`topDown`){n.velocity=o.length>0?[o[0]??0,o[1]??0]:[i.x*this.maxSpeed,i.y*this.maxSpeed],n.moveAndSlide();return}let c=t.scene.physics?.gravity?.[1]??980,l=n.isOnFloor()&&!(this.rising&&(n.velocity[1]??0)<0),u=-Math.sqrt(2*c*this.jumpHeight);if(this.dashLeft>0){this.dashLeft-=e,n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}if(this.dashSpeed>0&&this.readAction(`dashAction`,()=>r.justPressed(this.dashAction),!1,`the character will never dash`)){this.dashLeft=this.dashSeconds,this.dashDir=i.x===0?this.dashDir:Math.sign(i.x),n.velocity[0]=this.dashDir*this.dashSpeed,n.velocity[1]=0,n.moveAndSlide(),this.setState(`dash`);return}n.velocity[0]=o.length>0?o[0]??0:i.x*this.maxSpeed;let d=this.crouchHeight>0&&this.readAction(`crouchAction`,()=>r.isPressed(this.crouchAction),!1,`the character will never crouch`);if(!this.crouching){let e=jw(n.collider);d&&l&&this.crouchHeight<e&&(this.standingHeight=e,this.crouching=!0,Nw(n,this.crouchHeight,e))}else if(!d){let e=this.standingHeight-this.crouchHeight,t=(n.position[1]??0)-Mw(n.collider)+1;n._physics?.castRay([n.position[0]??0,t],[0,-1],e+2,n)||(this.crouching=!1,Nw(n,this.standingHeight,this.crouchHeight))}this.crouching&&(n.velocity[0]=(n.velocity[0]??0)*this.crouchSpeedMultiplier),l?(this.coyoteLeft=this.coyoteSeconds,this.jumpsUsed=0):(this.coyoteLeft=Math.max(0,this.coyoteLeft-e),this.coyoteLeft<=0&&this.jumpsUsed===0&&(this.jumpsUsed=1));let f=this.readAction(`jumpAction`,()=>r.justPressed(this.jumpAction),!1,`the character will never jump`);f?this.bufferLeft=Math.max(this.jumpBufferSeconds,0):this.bufferLeft=Math.max(0,this.bufferLeft-e);let p=this.bufferLeft>0||f;this.crouching&&(p=!1,this.bufferLeft=0);let m=this.wallSlideSpeed>0||this.wallJumpImpulse.some(e=>e!==0)?n.isOnWall():!1;if(p&&m&&!l&&this.wallJumpImpulse.some(e=>e!==0)){let e=-n.wallSide();n.velocity[0]=e*(this.wallJumpImpulse[0]??0),n.velocity[1]=-(this.wallJumpImpulse[1]??0),this.bufferLeft=0,this.rising=!0,this.jumpsUsed=1}else if(p&&(l||this.coyoteLeft>0||this.jumpsUsed<this.maxJumps))n.velocity[1]=u,this.bufferLeft=0,this.coyoteLeft=0,this.rising=!0,this.jumpsUsed=l?1:this.jumpsUsed+1;else if(l)n.velocity[1]=20,this.rising=!1;else{n.velocity[1]=(n.velocity[1]??0)+c*e;let t=this.readAction(`jumpAction`,()=>r.isPressed(this.jumpAction),!1,`the character will never jump`);this.rising&&this.jumpCutMultiplier<1&&!t&&(n.velocity[1]=(n.velocity[1]??0)*this.jumpCutMultiplier,this.rising=!1),(n.velocity[1]??0)>=0&&(this.rising=!1),this.wallSlideSpeed>0&&m&&(n.velocity[1]??0)>this.wallSlideSpeed&&(n.velocity[1]=this.wallSlideSpeed)}s!==0&&(n.velocity[1]=s,s<0&&(this.rising=!0)),n.isOnCeiling()&&(n.velocity[1]??0)<0&&(n.velocity[1]=0,this.rising=!1),n.moveAndSlide();let h=n.velocity[1]??0;if(this.wallSlideSpeed>0&&!n.isOnFloor()&&n.isOnWall()&&h>0)this.setState(`wallSlide`);else if(n.isOnFloor()){let e=Math.abs(i.x)>.01;this.setState(this.crouching?e?`sneak`:`crouch`:e?`run`:`idle`)}else this.setState(h<0?`jump`:`fall`)}setState(e){e!==this.state&&(this.state=e,this.emit(`movementStateChanged`,e))}reportedActions=new Set;readAction(e,t,n,r){let i=this[e];return SS({engine:this.tree?.engine,who:this.getPath(),reported:this.reportedActions,consequence:r,authored:i!==kw[e]},i,t,n)}};function jw(e){return e.shape===`rect`?e.size?.[1]??0:e.shape===`capsule`?e.height??0:0}function Mw(e){return e.shape===`rect`?(e.size?.[1]??0)/2:e.shape===`capsule`?(e.height??0)/2+(e.radius??0):e.radius??0}function Nw(e,t,n){let r=e.collider;if(r.shape===`rect`){let i=r.size??[32,n];e.collider={...r,size:[i[0]??32,t]}}else if(r.shape===`capsule`)e.collider={...r,height:t};else return;let i=(n-t)/2,a=e.position;e.position=[a[0]??0,(a[1]??0)+i]}var Pw=new Zf(1,1),Fw=class extends MC{static typeName=`ColorRect2D`;static props={size:{default:[100,100]},color:{default:`#ffffff`},opacity:{default:1,range:{min:0,max:1}},anchor:{default:[.5,.5]}};size=[100,100];color=`#ffffff`;opacity=1;anchor=[.5,.5];quadMesh=null;_quad(){return this.quadMesh||(this.quadMesh=new Ld(Pw,new Td({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=this.size[0]??0,r=this.size[1]??0;t.visible=n>0&&r>0&&this.opacity>0,t.scale.set(n,r,1);let i=this.anchor[0]??.5,a=this.anchor[1]??.5;t.position.set((.5-i)*n,(a-.5)*r,0),t.renderOrder=this.effectiveRenderOrder;let o=t.material;o.color.set(this.color),o.opacity=this.opacity}free(){(this.quadMesh?.material)?.dispose(),this.quadMesh=null,super.free()}},Iw=new Zf(1,1),Lw=class extends MC{static typeName=`Label`;static props={text:{default:``},fontSize:{default:16},color:{default:`#ffffff`},font:{default:`monospace`},align:{default:`left`},opacity:{default:1,range:{min:0,max:1}}};text=``;fontSize=16;color=`#ffffff`;font=`monospace`;align=`left`;opacity=1;quadMesh=null;canvas=null;lastKey=``;_quad(){return this.quadMesh||(this.quadMesh=new Ld(Iw,new Td({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.quadMesh)),this.quadMesh}_syncObject2D(e){super._syncObject2D(e);let t=this._quad(),n=et(this,this.text);if(typeof document>`u`||n===``){t.visible=!1;return}let r=`${n}\0${this.fontSize}\0${this.color}\0${this.font}\0${this.align}`;r!==this.lastKey&&(this.lastKey=r,this.rasterize()),t.visible=this.opacity>0,t.material.opacity=this.opacity,t.renderOrder=this.effectiveRenderOrder}rasterize(){let e=et(this,this.text),t=Math.min(globalThis.devicePixelRatio??1,2);this.canvas??=document.createElement(`canvas`);let n=this.canvas.getContext(`2d`);if(!n)return;let r=`${this.fontSize*t}px ${this.font}`;n.font=r;let i=n.measureText(e),a=Math.max(1,Math.ceil(i.width)),o=Math.ceil(this.fontSize*t*1.4);this.canvas.width=a,this.canvas.height=o,n.font=r,n.fillStyle=this.color,n.textBaseline=`middle`,n.fillText(e,0,o/2);let s=this._quad(),c=s.material;c.map?.dispose();let l=new Vf(this.canvas);l.colorSpace=hc,c.map=l,c.needsUpdate=!0;let u=a/t,d=o/t;s.scale.set(u,d,1);let f=this.align===`center`?.5:+(this.align===`right`);s.position.set((.5-f)*u,0,0)}free(){let e=this.quadMesh;if(e){let t=e.material;t.map?.dispose(),t.dispose(),e.removeFromParent(),this.quadMesh=null}this.canvas=null,super.free()}},Rw=new Zf(1,1),zw=class e extends MC{orderGroup=`effects`;static typeName=`Particles2D`;static signals=[`finished`];static props={orderGroup:{default:`effects`,options:[`background`,`terrain`,`default`,`characters`,`effects`,`overlay`]},preset:{default:`custom`,options:[`custom`,...ko]},emitting:{default:!0},worldSpace:{default:!1},rate:{default:40},burst:{default:0},lifetime:{default:[.6,1.2]},speed:{default:[40,120]},directionDeg:{default:-90},spreadDeg:{default:30},gravity:{default:[0,0]},drag:{default:0},sizeStart:{default:8},sizeEnd:{default:2},colorStart:{default:`#ffffff`},colorEnd:{default:`#ffffff`},paletteColors:{default:[]},alphaStart:{default:1,range:{min:0,max:1}},alphaEnd:{default:0,range:{min:0,max:1}},shimmer:{default:0},blend:{default:`add`,options:[`add`,`normal`]},maxParticles:{default:256},emitBox:{default:[0,0]},drift:{default:[0,0]}};preset=`custom`;emitting=!0;worldSpace=!1;rate=40;burst=0;lifetime=[.6,1.2];speed=[40,120];directionDeg=-90;spreadDeg=30;gravity=[0,0];drag=0;sizeStart=8;sizeEnd=2;colorStart=`#ffffff`;colorEnd=`#ffffff`;paletteColors=[];alphaStart=1;alphaEnd=0;shimmer=0;blend=`add`;maxParticles=256;emitBox=[0,0];drift=[0,0];static validateJson(e){let t=e;if(t.preset!==`custom`&&!ko.includes(t.preset))throw new L(`BAD_FORMAT`,`Particles2D '${e.name}' preset must be 'custom' or one of [${ko.join(`, `)}], got '${t.preset}'.`,{prop:`preset`,validOptions:ko});if(t.blend!==`add`&&t.blend!==`normal`)throw new L(`BAD_FORMAT`,`Particles2D '${e.name}' blend must be 'add' or 'normal', got '${t.blend}'.`,{prop:`blend`,validOptions:[`add`,`normal`]})}sim=null;bursted=!1;finishedEmitted=!1;_ensureSim(){if(!this.sim){Ao(this,this.preset,ht(e.typeName));let t=WS(this);this.sim=new Mo({rate:this.emitting?this.rate:0,lifetime:[this.lifetime[0]??1,this.lifetime[1]??1],speed:[this.speed[0]??0,this.speed[1]??0],directionDeg:this.directionDeg,spreadDeg:this.spreadDeg,gravity:[this.gravity[0]??0,this.gravity[1]??0,0],drag:this.drag,maxParticles:this.maxParticles,emitBox:[this.emitBox[0]??0,this.emitBox[1]??0,0],drift:[this.drift[0]??0,this.drift[1]??0,0]},t)}return this.sim}get aliveCount(){return this.sim?.count??0}particles(){let e=[];return this.sim?.forEach(t=>{e.push({...t})}),e}lastWorld=null;wasEmitting=!1;update(e){let t=this._ensureSim();this.holdWorldSpace(t),t.setRate(this.emitting?this.rate:0),this.burst>0&&!this.bursted&&(this.emitting||this.armedByReplay)&&(this.bursted=!0,this.armedByReplay=!1,t.burst(this.burst),this.report(`burst`,this.burst));let n=this.emitting&&this.rate>0;n!==this.wasEmitting&&(this.wasEmitting=n,n&&this.report(`emit`,this.rate)),t.update(e),(!this.emitting||this.rate===0)&&this.bursted&&t.done&&!this.finishedEmitted&&(this.finishedEmitted=!0,this.emit(`finished`))}holdWorldSpace(e){if(!this.worldSpace){this.lastWorld=null;return}let t=0,n=0;for(let e=this;e;e=e.parent)e instanceof MC&&(t+=e.position[0]??0,n+=e.position[1]??0);let r=this.lastWorld;r&&e.translateAll(r[0]-t,r[1]-n,r[2]-0),this.lastWorld=[t,n,0]}meshKey=``;free(){this.mesh&&=(this.mesh.removeFromParent(),Bw(this.mesh),null),super.free()}report(e,t){let n=this.tree?.engine;n?.effects.record({kind:e,name:this.preset,from:this.getPath(),wiredAs:this.wiringPath(),amount:t,at:n.time})}replay(){this.bursted=!1,this.finishedEmitted=!1,this.armedByReplay=!0}armedByReplay=!1;mesh=null;paletteCache=[];paletteCacheKey=``;refreshPalette(){let e=this.paletteColors;if(e.length===0)return null;let t=e.join(`|`);if(t!==this.paletteCacheKey){this.paletteCacheKey=t;for(let t=0;t<e.length;t++){let n=this.paletteCache[t];n||(n=new J,this.paletteCache[t]=n),n.set(e[t])}this.paletteCache.length=e.length}return this.paletteCache}_syncObject2D(e){super._syncObject2D(e);let t=this._ensureSim(),n=`${this.maxParticles}|${this.blend}`;if(!this.mesh||this.meshKey!==n){this.mesh&&(this.mesh.removeFromParent(),Bw(this.mesh)),this.meshKey=n;let e=new Td({transparent:!0,depthWrite:!1,blending:this.blend===`add`?2:1});this.mesh=new uf(Rw,e,this.maxParticles),this.mesh.instanceMatrix.setUsage(xc),this.mesh.frustumCulled=!1,this._ensureObject2D().add(this.mesh)}let r=this.mesh,i=this.refreshPalette(),a=i?null:Hw.set(this.colorStart),o=Uw.set(this.colorEnd),s=this.shimmer,c=0;t.forEach(e=>{let t=this.sizeStart+(this.sizeEnd-this.sizeStart)*e.t;Vw.makeScale(t,t,1),Vw.setPosition(e.x,-e.y,0),r.setMatrixAt(c,Vw);let n=i?i[Math.floor(e.seed*i.length)]:a,l=Math.max(0,this.alphaStart+(this.alphaEnd-this.alphaStart)*e.t);s>0&&(l*=.5+.5*Math.sin(2*Math.PI*(e.age*s+e.seed))),Ww.copy(n).lerp(o,e.t).multiplyScalar(l),r.setColorAt(c,Ww),c+=1}),r.count=c,r.instanceMatrix.needsUpdate=!0,r.instanceColor&&(r.instanceColor.needsUpdate=!0),r.renderOrder=this.effectiveRenderOrder}};function Bw(e){e.dispose();let t=e.material;for(let e of Array.isArray(t)?t:[t])e.dispose()}var Vw=new q,Hw=new J,Uw=new J,Ww=new J;function Gw(e,t){if(typeof t==`number`&&Number.isInteger(t)&&t>=-1)return t;throw new L(`PROP_TYPE_MISMATCH`,`TileMap2D: legend entry '${e}' must be a tile INDEX (a whole number, -1 for empty), got ${Kw(t)}. Solidity is the separate "solid" prop — a list of tile indices: "legend": { "${e}": 0 }, "solid": [0].`,{prop:`legend`})}function Kw(e){return e===null?`null`:Array.isArray(e)?`an array of ${e.length}`:typeof e==`object`?`an object (keys: ${Object.keys(e).join(`, `)})`:typeof e==`number`?`${e}`:`a ${typeof e}`}function qw(e,t){let n=[],r=0;for(let i of e){let e=[];if(typeof i==`string`)for(let n of i){let r=t[n];if(r!==void 0)e.push(Gw(n,r));else if(n===`.`||n===` `)e.push(-1);else if(n>=`0`&&n<=`9`)e.push(n.charCodeAt(0)-48);else throw new L(`BAD_FORMAT`,`TileMap2D: unknown tile char '${n}' — add it to "legend" (char → tile index), or use '.'/' ' for empty and digits 0-9.`)}else for(let t of i)e.push(t);r=Math.max(r,e.length),n.push(e)}for(let e of n)for(;e.length<r;)e.push(-1);return n}function Jw(e,t){let n=e.length,r=n>0?e[0].length:0,i=e.map(e=>e.map(()=>!1)),a=(n,r)=>t.has(e[r][n]),o=[];for(let e=0;e<n;e++)for(let t=0;t<r;t++){if(!a(t,e)||i[e][t])continue;let s=1;for(;t+s<r&&a(t+s,e)&&!i[e][t+s];)s++;let c=1;grow:for(;e+c<n;){for(let n=0;n<s;n++)if(!a(t+n,e+c)||i[e+c][t+n])break grow;c++}for(let n=0;n<c;n++)for(let r=0;r<s;r++)i[e+n][t+r]=!0;o.push({x:t,y:e,w:s,h:c})}return o}var Yw=1e6,Xw=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,Zw=class extends MC{static typeName=`TileMap2D`;static props={texture:{default:``,asset:{kind:`texture`,refOnly:!0}},tileSize:{default:32},columns:{default:0},cells:{default:[]},legend:{default:{}},colors:{default:{}},solid:{default:[]},opacity:{default:1,range:{min:0,max:1}}};texture=``;tileSize=32;columns=0;_cells=[];_legend={};_solid=[];geometryDirty=!0;gridChecked=``;collidersDirty=!0;builtScale=[1,1];get cells(){return this._cells}set cells(e){this._cells=e,this.geometryDirty=!0,this.collidersDirty=!0}get legend(){return this._legend}set legend(e){this._legend=e,this.geometryDirty=!0,this.collidersDirty=!0}_colors={};get colors(){return this._colors}set colors(e){this._colors=e,this.geometryDirty=!0,this.collidersDirty=!0}palette(){return Object.values(this._colors)}allChars(){let e={...this._legend};return Object.keys(this._colors).forEach((t,n)=>{e[t]=Yw+n}),e}solidIndices(){let e=this.allChars(),t=[];for(let n of this._solid)typeof n==`number`?t.push(n):e[n]===void 0?n.length===1&&n>=`0`&&n<=`9`&&t.push(n.charCodeAt(0)-48):t.push(e[n]);return t}get solid(){return this._solid}set solid(e){this._solid=e,this.collidersDirty=!0}opacity=1;tileMesh=null;builtColumns=0;builtRows=0;static validateJson(e){let t=e;for(let[n,r]of Object.entries(t._colors))if(!(typeof r==`string`&&Xw.test(r)))throw new L(`PROP_TYPE_MISMATCH`,`TileMap2D '${e.name}': "colors" ['${n}'] is ${JSON.stringify(r)} — a colour here is \`#rgb\` or \`#rrggbb\`, the same as every other colour prop.`,{prop:`colors`});if(t.texture!==``&&Object.keys(t._colors).length>0)throw new L(`PROP_TYPE_MISMATCH`,`TileMap2D '${e.name}': "colors" and "texture" are exclusive — colours are for a level authored before the art arrives. Drop one of them.`,{prop:`colors`});qw(t._cells,t.allChars())}grid(){return qw(this._cells,this.allChars())}cellAt(e,t){let n=B(this),[r,i]=this.scaledTile();if(!(r>0)||!(i>0))return null;let a=Math.floor((e-(n[0]??0))/r),o=Math.floor((t-(n[1]??0))/i),s=this.grid()[o];return!s||a<0||a>=s.length?null:[a,o]}scaledTile(){let[e=1,t=1]=this.scale;return[this.tileSize*Math.abs(e),this.tileSize*Math.abs(t)]}tileAt(e,t){return this.grid()[t]?.[e]??-1}worldAt(e,t){let n=B(this),[r,i]=this.scaledTile();return[(n[0]??0)+e*r+r/2,(n[1]??0)+t*i+i/2]}setTile(e,t,n){let r=this._cells[t];if(typeof r!=`string`||e<0||e>=r.length||n.length!==1)return!1;let i=this._cells.slice();return i[t]=`${r.slice(0,e)}${n}${r.slice(e+1)}`,this.cells=i,!0}onReady(){this.rebuildColliders()}update(e){let[t=1,n=1]=this.scale;(t!==this.builtScale[0]||n!==this.builtScale[1])&&(this.collidersDirty=!0),this.collidersDirty&&this.rebuildColliders()}rebuildColliders(){this.collidersDirty=!1;for(let e of[...this.children])e.name.startsWith(`__tileSolid`)&&e.free();if(this.builtScale=[this.scale[0]??1,this.scale[1]??1],this._solid.length===0)return;let e=this.tileSize,[t,n]=this.builtScale;Jw(this.grid(),new Set(this.solidIndices())).forEach((r,i)=>{let a=new PC(`__tileSolid${i}`);a.position=[(r.x+r.w/2)*e*t,(r.y+r.h/2)*e*n],a.collider={shape:`rect`,size:[r.w*e*t,r.h*e*n]},this.addChild(a)})}_mesh(){return this.tileMesh||(this.tileMesh=new Ld(new dd,new Td({transparent:!0,depthWrite:!1})),this._ensureObject2D().add(this.tileMesh)),this.tileMesh}_staticReady(e){return this.texture===``||!e?this.texture===``:!!e.getTexture(this.texture).image?.width}_syncObject2D(e){super._syncObject2D(e);let t=this._mesh(),n=t.material;if(Object.keys(this._colors).length>0){if(t.visible=this.opacity>0,t.renderOrder=this.effectiveRenderOrder,n.opacity=this.opacity,(n.map!==null||!n.vertexColors)&&(n.map=null,n.vertexColors=!0,n.needsUpdate=!0,this.geometryDirty=!0),!this.geometryDirty)return;this.geometryDirty=!1,this.builtColumns=1,this.builtRows=1,this.buildGeometry(t.geometry,1,1);return}if(!this.texture||!e){t.visible=!1;return}let r=e.getTexture(this.texture),i=r.image;if(!i?.width||!i.height){t.visible=!1;return}t.visible=this.opacity>0,t.renderOrder=this.effectiveRenderOrder,n.opacity=this.opacity,n.map!==r&&(r.magFilter=Wo,n.map=r,n.needsUpdate=!0,this.geometryDirty=!0);let a=-1;for(let e of this.grid())for(let t of e)t>a&&(a=t);let o=`${this.texture}|${a}`;if(this.gridChecked!==o){this.gridChecked=o;let e=Cw(this.texture,this.tileSize,this.tileSize,i.width,i.height,a>=0?a:void 0,`tile`);e&&z(this.tree?.engine??null,`error`,e)}let s=this.columns>0?this.columns:Math.max(1,Math.floor(i.width/this.tileSize)),c=Math.max(1,Math.floor(i.height/this.tileSize));(s!==this.builtColumns||c!==this.builtRows)&&(this.geometryDirty=!0),this.geometryDirty&&(this.geometryDirty=!1,this.builtColumns=s,this.builtRows=c,this.buildGeometry(t.geometry,s,c))}buildGeometry(e,t,n){let r=this.grid(),i=this.tileSize,a=[],o=[],s=[],c=this.palette().map(e=>new J(e)),l=[];for(let e=0;e<r.length;e++){let u=r[e];for(let r=0;r<u.length;r++){let d=u[r];if(d<0)continue;let f=r*i,p=f+i,m=-(e*i),h=-((e+1)*i),g=a.length/3;a.push(f,m,0,p,m,0,p,h,0,f,h,0);let _=d>=Yw?0:d%t,v=d>=Yw?0:Math.floor(d/t),y=_/t,b=(_+1)/t,x=1-v/n,S=1-(v+1)/n;o.push(y,x,b,x,b,S,y,S);let C=d>=Yw?c[d-Yw]:void 0,w=C?.r??1,T=C?.g??1,E=C?.b??1;for(let e=0;e<4;e++)l.push(w,T,E);s.push(g,g+2,g+1,g,g+3,g+2)}}e.setAttribute(`position`,new Y(new Float32Array(a),3)),e.setAttribute(`uv`,new Y(new Float32Array(o),2)),e.setAttribute(`color`,new Y(new Float32Array(l),3)),e.setIndex(s),e.computeBoundingSphere()}get renderedTileCount(){let e=this.tileMesh?.geometry.getAttribute(`position`);return e?e.count/4:0}free(){this.tileMesh?.geometry.dispose(),super.free()}},Qw=[`top-left`,`top`,`top-right`,`left`,`center`,`right`,`bottom-left`,`bottom`,`bottom-right`],$w=class extends Ht{static typeName=`UILayer`;static props={anchor:{default:`top-left`,options:Qw}};anchor=`top-left`;group=null;_ensureGroup(){return this.group||(this.group=new iu,this.group.userData.incantoNode=this),this.group}static validateJson(e){let t=e.anchor;if(!Qw.includes(t))throw new L(`BAD_FORMAT`,`UILayer '${e.name}' anchor must be one of [${Qw.join(`, `)}], got '${t}'.`,{prop:`anchor`,validOptions:Qw})}_anchorOrigin(e,t){let n=this.anchor;return{x:n.includes(`right`)?e:n===`top`||n===`center`||n===`bottom`?e/2:0,y:n.includes(`bottom`)?t:n===`left`||n===`center`||n===`right`?t/2:0}}};function eT(){No(),R(MC),R(Tw),R(Fw),R(zw),R(Ew),R(Dw),R(Lw),R($w),R(PC),R(IC),R(FC),R(LC),R(Aw),R(aw),R(Zw)}function tT(e){for(let t=e;t;t=t.parent)if(!t.visible)return!1;return!0}function nT(e,t={}){let n=null;for(let r of e){if(!tT(r.object))continue;let e=r.object;for(;e&&!e.userData?.incantoNode;)e=e.parent;let i=e?.userData?.incantoNode;if(i===void 0)continue;if(!t.byRenderOrder)return i;let a=r.object.renderOrder??0;(!n||a>=n.order)&&(n={node:i,order:a})}return n?.node??null}function rT(e){let t=new Float32Array(e.length/2*3);for(let n=0,r=0;n<e.length;n+=2,r+=3)t[r]=e[n],t[r+1]=-e[n+1],t[r+2]=0;return t}function iT(e,t,n){return{x:(t-e.cx)*e.zoom+e.w/2,y:(n-e.cy)*e.zoom+e.h/2}}function aT(e,t,n){return{x:(t-e.w/2)/e.zoom+e.cx,y:(n-e.h/2)/e.zoom+e.cy}}function oT(e,t,n){return{x:e.offsetX+t/e.uiW*e.contentW,y:e.offsetY+n/e.uiH*e.contentH}}function sT(e,t,n){return{x:(t-e.offsetX)/e.contentW*e.uiW,y:(n-e.offsetY)/e.contentH*e.uiH}}var cT=new Ou,lT=new G,uT=12,dT=new Float32Array(16);function fT(e){if(!(e instanceof MC))return null;let t=e._ensureObject2D();t.updateWorldMatrix(!0,!0),cT.setFromObject(t),cT.getSize(lT);let n,r,i,a;if(!Number.isFinite(lT.x)||lT.x===0&&lT.y===0){let e=new G().setFromMatrixPosition(t.matrixWorld);n=e.x-uT,i=e.x+uT,r=e.y-uT,a=e.y+uT}else n=cT.min.x-2,i=cT.max.x+2,r=cT.min.y-2,a=cT.max.y+2;let o=[n,r,i,r,i,r,i,a,i,a,n,a,n,a,n,r];return dT.set(o),dT}function pT(){return{visited:new Set,cameras:[],emitters:[]}}function mT(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function hT(e,t,n,r,i,a,o){let s=a??pT();s.visited.clear(),s.cameras.length=0,s.emitters.length=0,bT(e,t,n,!1,s.visited,s.cameras,s.emitters,r,i,o?.ignoreStatic===!0),xT(t,s.visited),xT(n,s.visited);let c=null;for(let e=0;e<s.cameras.length;e++){let t=s.cameras[e];if(t.current){c=t;break}}return c||=s.cameras[0]??null,yT(s.emitters,c),{activeCamera:c}}var gT=new G,_T=new G,vT=new G;function yT(e,t){if(e.length===0||!t)return;let n=t._ensureObject2D();n.updateWorldMatrix(!0,!1),n.getWorldPosition(_T),vT.set(0,1,0).applyQuaternion(n.quaternion);let r={position:[_T.x,_T.y,0],forward:[0,0,-1],up:[vT.x,vT.y,vT.z]};for(let{node:t,parent:n}of e)n.updateWorldMatrix(!0,!1),n.getWorldPosition(gT),t._setSpatialPose({position:[gT.x,gT.y,0],listener:r})}function bT(e,t,n,r,i,a,o,s,c,l){let u=t,d=r;if(e instanceof MC&&!(e instanceof $w)){let t=e._ensureObject2D();if(e.static&&!l&&t.userData.incantoStaticSynced===!0){t.userData.incantoStatic=!0,i.add(t);return}}if(e instanceof $w){let t=e._ensureGroup();t.parent!==n&&n.add(t);let r=c?e._anchorOrigin(c.width,c.height):{x:0,y:0};t.position.set(r.x,-r.y,0),i.add(t),d=!0,u=t}else if(e instanceof MC){let n=e._ensureObject2D();n.parent!==t&&t.add(n),e._syncObject2D(s),i.add(n),e instanceof Dw&&!r&&a.push(e),u=n}else mT(e)&&o.push({node:e,parent:u});for(let t of e.children)bT(t,u,n,d,i,a,o,s,c,l);if(e instanceof MC&&!(e instanceof $w)){let t=e._ensureObject2D();e.static&&!l&&e._staticReady(s)?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}function xT(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&xT(i,t)}}function ST(){return{lastNode:null,lastCx:0,lastCy:0,lastZoom:1,active:!1,t:0,seconds:0,fromCx:0,fromCy:0,fromZoom:1}}function CT(e,t,n,r,i,a){if(!t)return e.lastNode=null,e.active=!1,{cx:n,cy:r,zoom:i};let o=t._blendRequest;if(t._blendRequest=void 0,e.lastNode!==t){let n=o??t.blendSeconds;e.lastNode&&n>0?(e.fromCx=e.lastCx,e.fromCy=e.lastCy,e.fromZoom=e.lastZoom,e.t=0,e.seconds=n,e.active=!0):e.active=!1}let s={cx:n,cy:r,zoom:i};if(e.active){e.t+=a;let t=Math.min(1,e.t/e.seconds),o=t<.5?2*t*t:1-(-2*t+2)**2/2;s={cx:e.fromCx+(n-e.fromCx)*o,cy:e.fromCy+(r-e.fromCy)*o,zoom:e.fromZoom+(i-e.fromZoom)*o},t>=1&&(e.active=!1)}return e.lastCx=s.cx,e.lastCy=s.cy,e.lastZoom=s.zoom,e.lastNode=t,s}var wT=120,TT=class{viewOverride=null;viewBlend=ST();webgl;captureFrame(){return new Promise((e,t)=>{this.pendingCaptures.push({resolve:e,reject:t}),setTimeout(()=>{if(this.pendingCaptures.length>0)try{this.render()}catch(e){let t=e instanceof Error?e:Error(String(e));for(let e of this.pendingCaptures.splice(0))e.reject(t)}},wT)})}pendingCaptures=[];drainFrameCapture(){if(this.pendingCaptures.length===0)return;let e=this.pendingCaptures;this.pendingCaptures=[];try{let t=this.webgl.getContext(),n=this.webgl.domElement.width,r=this.webgl.domElement.height,i=new Uint8Array(n*r*4);this.webgl.setRenderTarget(null),t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,i);for(let e=0;e<Math.floor(r/2);e++){let t=e*n*4,a=(r-1-e)*n*4;for(let e=0;e<n*4;e++){let n=i[t+e];i[t+e]=i[a+e],i[a+e]=n}}for(let t of e)t.resolve({pixels:i,width:n,height:r})}catch(t){let n=t instanceof Error?t:Error(String(t));for(let t of e)t.reject(n)}}basePixelRatio=1;setRenderScale(e){let t=Number.isFinite(e)&&e>0?Math.min(2,Math.max(.25,e)):1;this.webgl.setPixelRatio(this.basePixelRatio*t)}worldScene=new pu;syncScratch=pT();ignoreStatic=!1;uiScene=new pu;worldCam=new cm(-1,1,1,-1,-1e3,1e3);uiCam=new cm(-1,1,1,-1,-1e3,1e3);engine;assets;ownsAssets;loadedAssetScenes=new WeakSet;disconnect;canvas;constructor(e){this.canvas=e.canvas,this.engine=e.engine;let t=e.canvas.clientWidth||e.canvas.width||1,n=e.canvas.clientHeight||e.canvas.height||1;this.lastView={cx:t/2,cy:n/2,zoom:1,w:t,h:n},this.assets=e.assets??new sv(void 0,this.engine),this.ownsAssets=!e.assets;let r=Po(e.engine.scene?.environment,{antialias:!0,pixelRatio:1,preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,e),i=ba(e.engine.settings.get(`quality`));r.antialias=r.antialias&&i.antialias,r.pixelRatio=Math.min(r.pixelRatio,i.pixelRatio),this.webgl=zo(()=>new ov({canvas:e.canvas,antialias:r.antialias,preserveDrawingBuffer:r.preserveDrawingBuffer})),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.engine.toWorld=(e,t)=>{if(!this.hasRendered)return null;let n=this.worldFromScreen(e,t);return[n.x,n.y]},this.engine.toScreen=e=>{if(!this.hasRendered)return null;let t=this.screenFromWorld(e[0]??0,e[1]??0);return{x:t.x,y:t.y,behind:!1}},this.basePixelRatio=r.pixelRatio,this.webgl.setPixelRatio(r.pixelRatio),this.webgl.info.autoReset=!1,this.debugLines=new jf(new dd,new yf({color:`#00ff6e`,transparent:!0,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.worldScene.add(this.debugLines),this.selectionLines=new jf(new dd,new yf({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.worldScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>{let e=performance.now();this.render(),this.engine.noteRenderMs(performance.now()-e)})}debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?fT(t):null;if(this.selectionLines.visible=n!==null,!n)return;let r=new Float32Array(n.length/2*3);for(let e=0,t=0;e<n.length;e+=2,t+=3)r[t]=n[e],r[t+1]=n[e+1],r[t+2]=0;this.selectionLines.geometry.setAttribute(`position`,new Y(r,3)),this.selectionLines.geometry.getAttribute(`position`).needsUpdate=!0}syncDebugLines(){let e=null;for(let t of tw(`2d`,this.engine))if(e=t.debugLines(),e)break;if(this.debugLines.visible=e!==null,!e)return;let t=rT(e);this.debugLines.geometry.setAttribute(`position`,new Y(t,3))}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e));let t=e.environment?.background;this.worldScene.background=typeof t==`string`?new J(t):null;let n=this.canvas.clientWidth||this.canvas.width,r=this.canvas.clientHeight||this.canvas.height,i=this.webgl.getSize(DT);(i.x!==n||i.y!==r)&&this.webgl.setSize(n,r,!1);let a=this.viewOverride?null:sr(e.viewport),o=a?cr(n,r,a):null,s=o?o.viewW:n,c=o?o.viewH:r;this.lastUi={w:s,h:c};let{activeCamera:l}=hT(e.root,this.worldScene,this.uiScene,this.assets,{width:s,height:c},this.syncScratch,{ignoreStatic:this.ignoreStatic}),u=a?{x:a.design[0]/2,y:a.design[1]/2}:{x:n/2,y:r/2},d=1;if(this.viewOverride?(u={x:this.viewOverride.cx,y:this.viewOverride.cy},d=this.viewOverride.zoom):l&&(u=l.clampedCenter(s,c),d=l.effectiveZoom),!this.viewOverride){let e=CT(this.viewBlend,l??null,u.x,u.y,d,this.engine.unscaledDelta);u={x:e.cx,y:e.cy},d=e.zoom}let f=o?.scale??1;this.lastView={cx:u.x,cy:u.y,zoom:d*f,w:n,h:r},this.lastViewport=o,this.hasRendered=!0,o&&(o.offsetX>.5||o.offsetY>.5)?(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r),this.webgl.clear(),this.webgl.setViewport(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissor(o.offsetX,o.offsetY,o.contentW,o.contentH),this.webgl.setScissorTest(!0)):(this.webgl.setScissorTest(!1),this.webgl.setViewport(0,0,n,r)),ET(this.worldCam,u.x,u.y,s/d,c/d),ET(this.uiCam,s/2,c/2,s,c),this.webgl.info.reset(),this.webgl.autoClear=!0,this.webgl.render(this.worldScene,this.worldCam),this.webgl.autoClear=!1,this.webgl.render(this.uiScene,this.uiCam),this.webgl.autoClear=!0,this.drainFrameCapture()}lastUi={w:1,h:1};lastViewport=null;lastView;hasRendered=!1;view(){return{...this.lastView}}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}worldFromScreen(e,t){return aT(this.lastView,e,t)}screenFromWorld(e,t){return iT(this.lastView,e,t)}pick(e,t){if(!this.hasRendered)return null;let{w:n,h:r}=this.lastView,i=this.lastViewport?.offsetX??0,a=this.lastViewport?.offsetY??0,o=this.lastViewport?.contentW??n,s=this.lastViewport?.contentH??r;return e<i||e>i+o||t<a||t>a+s?null:(kT.set((e-i)/o*2-1,-((t-a)/s*2-1)),this.hit(this.uiScene,this.uiCam)||this.hit(this.worldScene,this.worldCam))}hit(e,t){return AT.setFromCamera(kT,t),nT(AT.intersectObjects(e.children,!0),{byRenderOrder:!0})}isUiNode(e){let t=e._object2D??e._group??null;for(;t;){if(t===this.uiScene)return!0;t=t.parent}return!1}screenFromUi(e,t){return oT(this.uiView(),e,t)}uiFromScreen(e,t){return sT(this.uiView(),e,t)}uiView(){return{offsetX:this.lastViewport?.offsetX??0,offsetY:this.lastViewport?.offsetY??0,contentW:this.lastViewport?.contentW??this.lastView.w,contentH:this.lastViewport?.contentH??this.lastView.h,uiW:this.lastUi.w,uiH:this.lastUi.h}}boundsOf(e){let t=e._object2D;if(!t||(jT.makeEmpty(),jT.expandByObject(t),jT.isEmpty())||(jT.getSize(OT),OT.x===0&&OT.y===0))return null;let n=this.isUiNode(e)?(e,t)=>this.screenFromUi(e,t):(e,t)=>this.screenFromWorld(e,t),r=n(jT.min.x,-jT.max.y),i=n(jT.max.x,-jT.min.y);return{x:r.x,y:r.y,w:i.x-r.x,h:i.y-r.y}}dispose(){this.engine.picker&&(this.engine.picker=null),this.engine.toWorld&&(this.engine.toWorld=null),this.engine.toScreen&&(this.engine.toScreen=null),this.disconnect();for(let e of[this.worldScene,this.uiScene])e.traverse(e=>{let t=e;if(!t.isMesh)return;let n=Array.isArray(t.material)?t.material:[t.material];for(let e of n)e?.dispose()});this.ownsAssets&&this.assets.dispose(),this.webgl.dispose()}};function ET(e,t,n,r,i){e.position.set(t,-n,10),e.left=-r/2,e.right=r/2,e.top=i/2,e.bottom=-i/2,e.updateProjectionMatrix()}var DT=new U,OT=new G,kT=new U,AT=new Rm,jT=new Ou;async function MT(e){eT(),(e.gameplay??!0)&&QC();for(let[t,n]of Object.entries(e.behaviors??{}))kt(t,n,{replace:!0});let t=new wa({seed:e.seed,fixedHz:e.fixedHz,...e.settings?{settings:e.settings}:{},...e._scheduler?{scheduler:e._scheduler}:{}}),n=NT(e.scene);if(Tn(n)===`3d`)throw new L(`WRONG_DIMENSION`,`createGame2D was given a 3D scene ('${String(n.name??`scene`)}'). Its nodes are never drawn by the 2D renderer and never simulated by 2D physics — you get a blank canvas. Boot it with createGame3D instead.`);let r=si(NT(n),{resolveScene:e.resolveScene,engine:t});t.setScene(r);let i=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&PT(r.root))&&(i=await sw(t)),e.physics!==!1&&(t.physicsProvider=async e=>{t.physics||!PT(e)||(i=await sw(t))});let a=[],o=e.keyboard??(typeof window<`u`?window:!1);o&&t.input.attachKeyboard(o);let s=!1,c=()=>{if(s||e.pointer===!1)return;let n=t.scene?.root;if(!n||e.pointer===void 0&&!IT(n))return;s=!0;let r=typeof e.pointer==`object`?e.pointer.lockOnClick??!1:!1;t.input.attachPointer(e.canvas,{lockOnClick:r})};c(),a.push(t.sceneChanged.connect(()=>c())),a.push(FT(t,r.root,e.canvas)),a.push(t.settings.bindAudio(t.audio)),a.push(Yv(t)),a.push(t.settings.bindLocale(t.locale)),e.pageGestures||lv(e.canvas);let l=e.touch??`auto`;if(l!==!1){let n=e.touchContainer??e.canvas.parentElement??null;if(n){let r={force:l===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=Zt(t,n,r),o=t.sceneChanged.connect(()=>{i?.dispose(),i=Zt(t,n,r)});a.push(()=>{o(),i?.dispose()})}}let u=e._rendererFactory?e._rendererFactory(t,e.canvas):new TT({canvas:e.canvas,engine:t,...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.preserveDrawingBuffer===void 0?{}:{preserveDrawingBuffer:e.preserveDrawingBuffer},...e.antialias===void 0?{}:{antialias:e.antialias}});a.push(t.settings.bindFrameCap(e=>{t.maxFps=e})),a.push(t.settings.bindRenderScale(e=>{u.setRenderScale?.(e)})),a.push(...Sv({engine:t,applyDrive:async e=>{let n=0,r=!0,i=()=>{r&&(n+=1,requestAnimationFrame(i))};typeof requestAnimationFrame==`function`&&requestAnimationFrame(i);let a={engine:t,project:(e,t)=>{let n=u.screenFromWorld;return n?n.call(u,e,t):null},wait:e=>new Promise(t=>setTimeout(t,e))};for(let t of e)await Mv(a,t);return r=!1,n},captureFramePixels:()=>{let e=u.captureFrame;return e?e.call(u):Promise.reject(new L(`TREE_VIOLATION`,`this renderer cannot capture frames`))},rendererStats:()=>u.stats?.(),assetErrors:()=>[...u.assets?.errors()??[],...cv(t.scene?.tree.root)]}));let d=e.debug??!1,f=e.editor??d,p=f===!0?{}:f||null,m={label:`✎ edit this scene`,run:async()=>{if(!p)return;let r=p.open??Kv,i=async t=>{let n=await MT({...e,scene:t});p?.onReboot?.(n)};await qv(async()=>{g();try{await r({scene:n,play:i,exit:e=>i(e??n),...p.save?{save:p.save}:{},...p.library?{library:p.library===!0?Bv():p.library}:{}})}catch(e){z(t,`error`,`[incanto] could not open the editor:`,e),await i(n)}},`opening the editor…`)}};if(d){let n=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(n){let{attachDebugOverlay:r}=await Iv(async()=>{let{attachDebugOverlay:e}=await import(`./debug-DepFCl1d.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(t,{container:n,statsSource:()=>u.stats?.()??{},...p?{actions:[m]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&a.push(()=>i.dispose())}}e.autoStart!==!1&&t.start();let h=!1;function g(){h||(h=!0,Xv([[`physics`,()=>i?.dispose()],[`app cleanups`,()=>{for(let e of a)e()}],[`engine`,()=>t.dispose()],[`renderer`,()=>u.dispose()]]))}return{engine:t,get scene(){let e=t.scene;if(!e)throw new L(`TREE_VIOLATION`,`game.scene: the engine has no scene.`);return e},sourceJson:n,renderer:u,physics:i,pick(e,n){return t.picker?.(e,n)??null},async frame(e){let t=u.captureFrame;if(!t)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);let n=await t.call(u);return _v(n.pixels,n.width,n.height,e)},assetErrors(){return[...u.assets?.errors()??[],...cv(t.scene?.tree.root)]},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...t.stats(),...u.stats?.()}},openEditor:p?async()=>{h||await m.run()}:null,dispose:g}}function NT(e){try{return structuredClone(e)}catch{throw new L(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function PT(e){if(e instanceof NC)return!0;for(let t of e.children)if(PT(t))return!0;return!1}function FT(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`){let e=window;r.push({target:e,type:`keydown`}),r.push({target:e,type:`pointerdown`})}if(r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Ua&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}function IT(e){if(e.behavior?.constructor.name===`Clickable`)return!0;for(let t of e.children)if(IT(t))return!0;return!1}var LT=[[`run`,[`run`,`move`,`walk`]],[`jump`,[`jump`,`idle`]],[`fall`,[`fall`,`jump`,`idle`]],[`wallSlide`,[`wallSlide`,`idle`]],[`dash`,[`dash`,`run`,`move`,`idle`]]];function RT(e){let t=new Set(Object.keys(e));if(t.has(`idle`))for(let[n,r]of LT){if(t.has(n))continue;let i=r.find(e=>e!==n&&t.has(e));i&&(e[n]=i)}}function zT(e,t){let n=e;if(typeof n?.frame?.width!=`number`||typeof n.frame.height!=`number`||!n.animations||Object.keys(n.animations).length===0)throw new L(`BAD_FORMAT`,`Library sprite metadata needs {frame: {width, height}, animations: {<name>: {start, end, frameRate, repeat}}} — got ${JSON.stringify(e).slice(0,120)}.`);let r={},i=null,a=null;for(let[e,t]of Object.entries(n.animations)){if(typeof t.start!=`number`||typeof t.end!=`number`||typeof t.frameRate!=`number`)throw new L(`BAD_FORMAT`,`Library animation '${e}' needs numeric start/end/frameRate, got ${JSON.stringify(t)}.`);let n=t.repeat===-1;r[e]={frames:[t.start,t.end],fps:t.frameRate,loop:n},i??=e,n&&a===null&&(a=e)}RT(r);let o=t.autoplay??a??i;return{asset:{type:`spritesheet`,url:t.url,frameWidth:n.frame.width,frameHeight:n.frame.height},props:{sheet:`$${t.assetKey}`,autoplay:o,animations:r}}}var BT=e({createGame2D:()=>MT,enablePhysics2D:()=>sw}),VT=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),HT=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),UT=class extends ru{constructor(e){super(),this.weight=0,this.isBinary=!1,this.overrideBlink=`none`,this.overrideLookAt=`none`,this.overrideMouth=`none`,this._binds=[],this.name=`VRMExpression_${e}`,this.expressionName=e,this.type=`VRMExpression`,this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink===`block`?+(0<this.outputWeight):this.overrideBlink===`blend`?this.outputWeight:0}get overrideLookAtAmount(){return this.overrideLookAt===`block`?+(0<this.outputWeight):this.overrideLookAt===`blend`?this.outputWeight:0}get overrideMouthAmount(){return this.overrideMouth===`block`?+(0<this.outputWeight):this.overrideMouth===`blend`?this.outputWeight:0}get outputWeight(){return this.isBinary?+(this.weight>.5):this.weight}addBind(e){this._binds.push(e)}deleteBind(e){let t=this._binds.indexOf(e);t>=0&&this._binds.splice(t,1)}applyWeight(e){let t=this.outputWeight;t*=e?.multiplier??1,this.isBinary&&t<1&&(t=0),this._binds.forEach(e=>e.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(e=>e.clearAppliedWeight())}};function WT(e,t,n){let r=e.parser.json,i=r.nodes?.[t];if(i==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${t}] of glTF but the node doesn't exist`),null;let a=i.mesh;if(a==null)return null;let o=r.meshes?.[a];if(o==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${a}] of glTF but the mesh doesn't exist`),null;let s=o.primitives.length,c=[];return n.traverse(e=>{c.length<s&&e.isMesh&&c.push(e)}),c}function GT(e,t){return HT(this,null,function*(){return WT(e,t,yield e.parser.getDependency(`node`,t))})}function KT(e){return HT(this,null,function*(){let t=yield e.parser.getDependencies(`node`),n=new Map;return t.forEach((t,r)=>{let i=WT(e,r,t);i!=null&&n.set(r,i)}),n})}var qT={Aa:`aa`,Ih:`ih`,Ou:`ou`,Ee:`ee`,Oh:`oh`,Blink:`blink`,Happy:`happy`,Angry:`angry`,Sad:`sad`,Relaxed:`relaxed`,LookUp:`lookUp`,Surprised:`surprised`,LookDown:`lookDown`,LookLeft:`lookLeft`,LookRight:`lookRight`,BlinkLeft:`blinkLeft`,BlinkRight:`blinkRight`,Neutral:`neutral`};function JT(e){return Math.max(Math.min(e,1),0)}var YT=class e{constructor(){this.blinkExpressionNames=[`blink`,`blinkLeft`,`blinkRight`],this.lookAtExpressionNames=[`lookLeft`,`lookRight`,`lookUp`,`lookDown`],this.mouthExpressionNames=[`aa`,`ee`,`ih`,`oh`,`ou`],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},t=new Set(Object.values(qT));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(qT));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)||(e[n]=r)}),e}copy(e){return this._expressions.concat().forEach(e=>{this.unregisterExpression(e)}),e._expressions.forEach(e=>{this.registerExpression(e)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new e().copy(this)}getExpression(e){return this._expressionMap[e]??null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){let t=this._expressions.indexOf(e);t===-1&&console.warn(`VRMExpressionManager: The specified expressions is not registered`),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){return this.getExpression(e)?.weight??null}setValue(e,t){let n=this.getExpression(e);n&&(n.weight=JT(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){let t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(e=>{e.clearAppliedWeight()}),this._expressions.forEach(t=>{let n=1,r=t.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(n*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(n*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(n*=e.mouth),t.applyWeight({multiplier:n})})}_calculateWeightMultipliers(){let e=1,t=1,n=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,t-=r.overrideLookAtAmount,n-=r.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),n=Math.max(0,n),{blink:e,lookAt:t,mouth:n}}},XT={Color:`color`,EmissionColor:`emissionColor`,ShadeColor:`shadeColor`,MatcapColor:`matcapColor`,RimColor:`rimColor`,OutlineColor:`outlineColor`},ZT={_Color:XT.Color,_EmissionColor:XT.EmissionColor,_ShadeColor:XT.ShadeColor,_RimColor:XT.RimColor,_OutlineColor:XT.OutlineColor},QT=new J,$T=class e{constructor({material:e,type:t,targetValue:n,targetAlpha:r}){this.material=e,this.type=t,this.targetValue=n,this.targetAlpha=r??1;let i=this._initColorBindState(),a=this._initAlphaBindState();this._state={color:i,alpha:a}}applyWeight(e){let{color:t,alpha:n}=this._state;if(t!=null){let{propertyName:n,deltaValue:r}=t;this.material[n]?.add(QT.copy(r).multiplyScalar(e))}if(n!=null){let{propertyName:t,deltaValue:r}=n;this.material[t]!=null&&(this.material[t]+=r*e)}}clearAppliedWeight(){let{color:e,alpha:t}=this._state;if(e!=null){let{propertyName:t,initialValue:n}=e;this.material[t]?.copy(n)}if(t!=null){let{propertyName:e,initialValue:n}=t;this.material[e]!=null&&(this.material[e]=n)}}_initColorBindState(){let{material:e,type:t,targetValue:n}=this,r=this._getPropertyNameMap()?.[t]?.[0]??null;if(r==null)return console.warn(`Tried to add a material color bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type is not supported.`),null;let i=e[r].clone();return{propertyName:r,initialValue:i,deltaValue:new J(n.r-i.r,n.g-i.g,n.b-i.b)}}_initAlphaBindState(){let{material:e,type:t,targetAlpha:n}=this,r=this._getPropertyNameMap()?.[t]?.[1]??null;if(r==null&&n!==1)return console.warn(`Tried to add a material alpha bind to the material ${e.name??`(no name)`}, the type ${t} but the material or the type does not support alpha.`),null;if(r==null)return null;let i=e[r];return{propertyName:r,initialValue:i,deltaValue:n-i}}_getPropertyNameMap(){return Object.entries(e._propertyNameMapMap).find(([e])=>this.material[e]===!0)?.[1]??null}};$T._propertyNameMapMap={isMeshStandardMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null]},isMeshBasicMaterial:{color:[`color`,`opacity`]},isMToonMaterial:{color:[`color`,`opacity`],emissionColor:[`emissive`,null],outlineColor:[`outlineColorFactor`,null],matcapColor:[`matcapFactor`,null],rimColor:[`parametricRimColorFactor`,null],shadeColor:[`shadeColorFactor`,null]}};var eE=$T,tE=class{constructor({primitives:e,index:t,weight:n}){this.primitives=e,this.index=t,this.weight=n}applyWeight(e){this.primitives.forEach(t=>{t.morphTargetInfluences?.[this.index]!=null&&(t.morphTargetInfluences[this.index]+=this.weight*e)})}clearAppliedWeight(){this.primitives.forEach(e=>{e.morphTargetInfluences?.[this.index]!=null&&(e.morphTargetInfluences[this.index]=0)})}},nE=new U,rE=class e{constructor({material:t,scale:n,offset:r}){this.material=t,this.scale=n,this.offset=r;let i=Object.entries(e._propertyNamesMap).find(([e])=>t[e]===!0)?.[1];i==null?(console.warn(`Tried to add a texture transform bind to the material ${t.name??`(no name)`} but the material is not supported.`),this._properties=[]):(this._properties=[],i.forEach(e=>{let i=t[e]?.clone();if(!i)return null;t[e]=i;let a=i.offset.clone(),o=i.repeat.clone(),s=r.clone().sub(a),c=n.clone().sub(o);this._properties.push({name:e,initialOffset:a,deltaOffset:s,initialScale:o,deltaScale:c})}))}applyWeight(e){this._properties.forEach(t=>{let n=this.material[t.name];n!==void 0&&(n.offset.add(nE.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(nE.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};rE._propertyNamesMap={isMeshStandardMaterial:[`map`,`emissiveMap`,`bumpMap`,`normalMap`,`displacementMap`,`roughnessMap`,`metalnessMap`,`alphaMap`],isMeshBasicMaterial:[`map`,`specularMap`,`alphaMap`],isMToonMaterial:[`map`,`normalMap`,`emissiveMap`,`shadeMultiplyTexture`,`rimMultiplyTexture`,`outlineWidthMultiplyTexture`,`uvAnimationMaskTexture`]};var iE=rE,aE=new Set([`1.0`,`1.0-beta`]),oE=class e{get name(){return`VRMExpressionLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return HT(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return HT(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return HT(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!aE.has(r))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.expressions;if(!i)return null;let a=new Set(Object.values(qT)),o=new Map;i.preset!=null&&Object.entries(i.preset).forEach(([e,t])=>{if(t!=null){if(!a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`);return}o.set(e,t)}}),i.custom!=null&&Object.entries(i.custom).forEach(([e,t])=>{if(a.has(e)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`);return}o.set(e,t)});let s=new YT;return yield Promise.all(Array.from(o.entries()).map(t=>HT(this,[t],function*([t,n]){var r,i,a;let o=new UT(t);if(e.scene.add(o),o.isBinary=n.isBinary??!1,o.overrideBlink=n.overrideBlink??`none`,o.overrideLookAt=n.overrideLookAt??`none`,o.overrideMouth=n.overrideMouth??`none`,(r=n.morphTargetBinds)==null||r.forEach(t=>HT(this,null,function*(){if(t.node===void 0||t.index===void 0)return;let r=yield GT(e,t.node),i=t.index;if(!r.every(e=>Array.isArray(e.morphTargetInfluences)&&i<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${n.name} attempts to index morph #${i} but not found.`);return}o.addBind(new tE({primitives:r,index:i,weight:t.weight??1}))})),n.materialColorBinds||n.textureTransformBinds){let t=[];e.scene.traverse(e=>{let n=e.material;n&&(Array.isArray(n)?t.push(...n):t.push(n))}),(i=n.materialColorBinds)==null||i.forEach(e=>HT(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new eE({material:t,type:e.type,targetValue:new J().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}))})})),(a=n.textureTransformBinds)==null||a.forEach(e=>HT(this,null,function*(){t.filter(t=>{let n=this.parser.associations.get(t)?.materials;return e.material===n}).forEach(t=>{o.addBind(new iE({material:t,offset:new U().fromArray(e.offset??[0,0]),scale:new U().fromArray(e.scale??[1,1])}))})}))}s.registerExpression(o)}))),s})}_v0Import(t){return HT(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.blendShapeMaster;if(!i)return null;let a=new YT,o=i.blendShapeGroups;if(!o)return a;let s=new Set;return yield Promise.all(o.map(r=>HT(this,null,function*(){let i=r.presetName,o=(i!=null&&e.v0v1PresetNameMap[i]||null)??r.name;if(o==null){console.warn(`VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression`);return}if(s.has(o)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${i} has duplicated entries. Ignoring the expression`);return}s.add(o);let c=new UT(o);t.scene.add(c),c.isBinary=r.isBinary??!1,r.binds&&r.binds.forEach(e=>HT(this,null,function*(){var i;if(e.mesh===void 0||e.index===void 0)return;let a=[];(i=n.nodes)==null||i.forEach((t,n)=>{t.mesh===e.mesh&&a.push(n)});let o=e.index;yield Promise.all(a.map(n=>HT(this,null,function*(){let i=yield GT(t,n);if(!i.every(e=>Array.isArray(e.morphTargetInfluences)&&o<e.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${r.name} attempts to index ${o}th morph but not found.`);return}c.addBind(new tE({primitives:i,index:o,weight:.01*(e.weight??100)}))})))}));let l=r.materialValues;l&&l.length!==0&&l.forEach(e=>{if(e.materialName===void 0||e.propertyName===void 0||e.targetValue===void 0)return;let n=[];t.scene.traverse(t=>{if(t.material){let r=t.material;Array.isArray(r)?n.push(...r.filter(t=>(t.name===e.materialName||t.name===e.materialName+` (Outline)`)&&n.indexOf(t)===-1)):r.name===e.materialName&&n.indexOf(r)===-1&&n.push(r)}});let r=e.propertyName;n.forEach(t=>{if(r===`_MainTex_ST`){let n=new U(e.targetValue[0],e.targetValue[1]),r=new U(e.targetValue[2],e.targetValue[3]);r.y=1-r.y-n.y,c.addBind(new iE({material:t,scale:n,offset:r}));return}let n=ZT[r];if(n){c.addBind(new eE({material:t,type:n,targetValue:new J().fromArray(e.targetValue),targetAlpha:e.targetValue[3]}));return}console.warn(r+` is not supported`)})}),a.registerExpression(c)}))),a})}};oE.v0v1PresetNameMap={a:`aa`,e:`ee`,i:`ih`,o:`oh`,u:`ou`,blink:`blink`,joy:`happy`,angry:`angry`,sorrow:`sad`,fun:`relaxed`,lookup:`lookUp`,lookdown:`lookDown`,lookleft:`lookLeft`,lookright:`lookRight`,blink_l:`blinkLeft`,blink_r:`blinkRight`,neutral:`neutral`};var sE=oE,cE=class e{constructor(t,n){this._firstPersonOnlyLayer=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=e.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=t,this.meshAnnotations=n}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMFirstPerson: humanoid must be same in order to copy`);return this.meshAnnotations=e.meshAnnotations.map(e=>({meshes:e.meshes.concat(),type:e.type})),this}clone(){return new e(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:t=e.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:n=e.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||=(this._firstPersonOnlyLayer=t,this._thirdPersonOnlyLayer=n,this.meshAnnotations.forEach(e=>{e.meshes.forEach(t=>{e.type===`firstPersonOnly`?(t.layers.set(this._firstPersonOnlyLayer),t.traverse(e=>e.layers.set(this._firstPersonOnlyLayer))):e.type===`thirdPersonOnly`?(t.layers.set(this._thirdPersonOnlyLayer),t.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer))):e.type===`auto`&&this._createHeadlessModel(t)})}),!0)}_excludeTriangles(e,t,n,r){let i=0;if(t!=null&&t.length>0)for(let a=0;a<e.length;a+=3){let o=e[a],s=e[a+1],c=e[a+2],l=t[o],u=n[o];if(l[0]>0&&r.includes(u[0])||l[1]>0&&r.includes(u[1])||l[2]>0&&r.includes(u[2])||l[3]>0&&r.includes(u[3]))continue;let d=t[s],f=n[s];if(d[0]>0&&r.includes(f[0])||d[1]>0&&r.includes(f[1])||d[2]>0&&r.includes(f[2])||d[3]>0&&r.includes(f[3]))continue;let p=t[c],m=n[c];p[0]>0&&r.includes(m[0])||p[1]>0&&r.includes(m[1])||p[2]>0&&r.includes(m[2])||p[3]>0&&r.includes(m[3])||(e[i++]=o,e[i++]=s,e[i++]=c)}return i}_createErasedMesh(e,t){let n=new Yd(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);let r=n.geometry,i=r.getAttribute(`skinIndex`),a=i instanceof Im?[]:i.array,o=[];for(let e=0;e<a.length;e+=4)o.push([a[e],a[e+1],a[e+2],a[e+3]]);let s=r.getAttribute(`skinWeight`),c=s instanceof Im?[]:s.array,l=[];for(let e=0;e<c.length;e+=4)l.push([c[e],c[e+1],c[e+2],c[e+3]]);let u=r.getIndex();if(!u)throw Error(`The geometry doesn't have an index buffer`);let d=Array.from(u.array),f=this._excludeTriangles(d,l,o,t),p=[];for(let e=0;e<f;e++)p[e]=d[e];return r.setIndex(p),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new ef(e.skeleton.bones,e.skeleton.boneInverses),new q),n}_createHeadlessModelForSkinnedMesh(e,t){let n=[];if(t.skeleton.bones.forEach((e,t)=>{this._isEraseTarget(e)&&n.push(t)}),!n.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(t,n);e.add(r)}_createHeadlessModel(e){if(e.type===`Group`)if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer));else{let t=new iu;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(e=>e.type===`SkinnedMesh`).forEach(e=>{let n=e;this._createHeadlessModelForSkinnedMesh(t,n)})}else if(e.type===`SkinnedMesh`){let t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(e=>e.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode(`head`)?!0:e.parent?this._isEraseTarget(e.parent):!1}};cE.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,cE.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var lE=cE,uE=new Set([`1.0`,`1.0-beta`]),dE=class{get name(){return`VRMFirstPersonLoaderPlugin`}constructor(e){this.parser=e}afterRoot(e){return HT(this,null,function*(){let t=e.userData.vrmHumanoid;if(t!==null){if(t===void 0)throw Error(`VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);e.userData.vrmFirstPerson=yield this._import(e,t)}})}_import(e,t){return HT(this,null,function*(){return t==null?null:(yield this._v1Import(e,t))||(yield this._v0Import(e,t))||null})}_v1Import(e,t){return HT(this,null,function*(){let n=this.parser.json;if(n.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=n.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!uE.has(i))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.firstPerson,o=[],s=yield KT(e);return Array.from(s.entries()).forEach(([e,t])=>{let n=(a?.meshAnnotations)?.find(t=>t.node===e);o.push({meshes:t,type:n?.type??`auto`})}),new lE(t,o)})}_v0Import(e,t){return HT(this,null,function*(){let n=this.parser.json,r=n.extensions?.VRM;if(!r)return null;let i=r.firstPerson;if(!i)return null;let a=[],o=yield KT(e);return Array.from(o.entries()).forEach(([e,t])=>{let r=n.nodes[e],o=i.meshAnnotations?i.meshAnnotations.find(e=>e.mesh===r.mesh):void 0;a.push({meshes:t,type:this._convertV0FlagToV1Type(o?.firstPersonFlag)})}),new lE(t,a)})}_convertV0FlagToV1Type(e){return e===`FirstPersonOnly`?`firstPersonOnly`:e===`ThirdPersonOnly`?`thirdPersonOnly`:e===`Both`?`both`:`auto`}},fE=new G,pE=new G,mE=new W,hE=class extends iu{constructor(e){super(),this.vrmHumanoid=e,this._boneAxesMap=new Map,Object.values(e.humanBones).forEach(e=>{let t=new Vm(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(e=>{e.geometry.dispose(),e.material.dispose()})}updateMatrixWorld(e){Array.from(this._boneAxesMap.entries()).forEach(([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(fE,mE,pE);let n=fE.set(.1,.1,.1).divide(pE);t.matrix.copy(e.node.matrixWorld).scale(n)}),super.updateMatrixWorld(e)}},gE=`hips.spine.chest.upperChest.neck.head.leftEye.rightEye.jaw.leftUpperLeg.leftLowerLeg.leftFoot.leftToes.rightUpperLeg.rightLowerLeg.rightFoot.rightToes.leftShoulder.leftUpperArm.leftLowerArm.leftHand.rightShoulder.rightUpperArm.rightLowerArm.rightHand.leftThumbMetacarpal.leftThumbProximal.leftThumbDistal.leftIndexProximal.leftIndexIntermediate.leftIndexDistal.leftMiddleProximal.leftMiddleIntermediate.leftMiddleDistal.leftRingProximal.leftRingIntermediate.leftRingDistal.leftLittleProximal.leftLittleIntermediate.leftLittleDistal.rightThumbMetacarpal.rightThumbProximal.rightThumbDistal.rightIndexProximal.rightIndexIntermediate.rightIndexDistal.rightMiddleProximal.rightMiddleIntermediate.rightMiddleDistal.rightRingProximal.rightRingIntermediate.rightRingDistal.rightLittleProximal.rightLittleIntermediate.rightLittleDistal`.split(`.`),_E={hips:null,spine:`hips`,chest:`spine`,upperChest:`chest`,neck:`upperChest`,head:`neck`,leftEye:`head`,rightEye:`head`,jaw:`head`,leftUpperLeg:`hips`,leftLowerLeg:`leftUpperLeg`,leftFoot:`leftLowerLeg`,leftToes:`leftFoot`,rightUpperLeg:`hips`,rightLowerLeg:`rightUpperLeg`,rightFoot:`rightLowerLeg`,rightToes:`rightFoot`,leftShoulder:`upperChest`,leftUpperArm:`leftShoulder`,leftLowerArm:`leftUpperArm`,leftHand:`leftLowerArm`,rightShoulder:`upperChest`,rightUpperArm:`rightShoulder`,rightLowerArm:`rightUpperArm`,rightHand:`rightLowerArm`,leftThumbMetacarpal:`leftHand`,leftThumbProximal:`leftThumbMetacarpal`,leftThumbDistal:`leftThumbProximal`,leftIndexProximal:`leftHand`,leftIndexIntermediate:`leftIndexProximal`,leftIndexDistal:`leftIndexIntermediate`,leftMiddleProximal:`leftHand`,leftMiddleIntermediate:`leftMiddleProximal`,leftMiddleDistal:`leftMiddleIntermediate`,leftRingProximal:`leftHand`,leftRingIntermediate:`leftRingProximal`,leftRingDistal:`leftRingIntermediate`,leftLittleProximal:`leftHand`,leftLittleIntermediate:`leftLittleProximal`,leftLittleDistal:`leftLittleIntermediate`,rightThumbMetacarpal:`rightHand`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbDistal:`rightThumbProximal`,rightIndexProximal:`rightHand`,rightIndexIntermediate:`rightIndexProximal`,rightIndexDistal:`rightIndexIntermediate`,rightMiddleProximal:`rightHand`,rightMiddleIntermediate:`rightMiddleProximal`,rightMiddleDistal:`rightMiddleIntermediate`,rightRingProximal:`rightHand`,rightRingIntermediate:`rightRingProximal`,rightRingDistal:`rightRingIntermediate`,rightLittleProximal:`rightHand`,rightLittleIntermediate:`rightLittleProximal`,rightLittleDistal:`rightLittleIntermediate`};function vE(e){return e.invert?e.invert():e.inverse(),e}var yE=new G,bE=new W,xE=class{constructor(e){this.humanBones=e,this.restPose=this.getAbsolutePose()}getAbsolutePose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);r&&(yE.copy(r.position),bE.copy(r.quaternion),e[n]={position:yE.toArray(),rotation:bE.toArray()})}),e}getPose(){let e={};return Object.keys(this.humanBones).forEach(t=>{let n=t,r=this.getBoneNode(n);if(!r)return;yE.set(0,0,0),bE.identity();let i=this.restPose[n];i?.position&&yE.fromArray(i.position).negate(),i?.rotation&&vE(bE.fromArray(i.rotation)),yE.add(r.position),bE.premultiply(r.quaternion),e[n]={position:yE.toArray(),rotation:bE.toArray()}}),e}setPose(e){Object.entries(e).forEach(([e,t])=>{let n=e,r=this.getBoneNode(n);if(!r)return;let i=this.restPose[n];i&&(t?.position&&(r.position.fromArray(t.position),i.position&&r.position.add(yE.fromArray(i.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),i.rotation&&r.quaternion.multiply(bE.fromArray(i.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([e,t])=>{let n=this.getBoneNode(e);n&&(t?.position&&n.position.fromArray(t.position),t?.rotation&&n.quaternion.fromArray(t.rotation))})}getBone(e){return this.humanBones[e]??void 0}getBoneNode(e){return this.humanBones[e]?.node??null}},SE=new G,CE=new W,wE=new G,TE=class e extends xE{static _setupTransforms(e){let t=new ru;t.name=`VRMHumanoidRig`;let n={},r={},i={},a={};gE.forEach(t=>{var o;let s=e.getBoneNode(t);if(s){let e=new G,c=new W;s.updateWorldMatrix(!0,!1),s.matrixWorld.decompose(e,c,SE),n[t]=e,r[t]=c,i[t]=s.quaternion.clone();let l=new W;(o=s.parent)==null||o.matrixWorld.decompose(SE,l,SE),a[t]=l}});let o={};return gE.forEach(r=>{let i=e.getBoneNode(r);if(i){let e=n[r],a=r,s;for(;s==null&&(a=_E[a],a!=null);)s=n[a];let c=new ru;c.name=`Normalized_`+i.name,(a?o[a]?.node:t).add(c),c.position.copy(e),s&&c.position.sub(s),o[r]={node:c}}}),{rigBones:o,root:t,parentWorldRotations:a,boneRotations:i}}constructor(t){let{rigBones:n,root:r,parentWorldRotations:i,boneRotations:a}=e._setupTransforms(t);super(n),this.original=t,this.root=r,this._parentWorldRotations=i,this._boneRotations=a}update(){gE.forEach(e=>{let t=this.original.getBoneNode(e);if(t!=null){let n=this.getBoneNode(e),r=this._parentWorldRotations[e],i=CE.copy(r).invert(),a=this._boneRotations[e];if(t.quaternion.copy(n.quaternion).multiply(r).premultiply(i).multiply(a),e===`hips`){let e=n.getWorldPosition(wE);t.parent.updateWorldMatrix(!0,!1);let r=t.parent.matrixWorld,i=e.applyMatrix4(r.invert());t.position.copy(i)}}})}},EE=class e{get restPose(){return console.warn(`VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead.`),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,t){this.autoUpdateHumanBones=t?.autoUpdateHumanBones??!0,this._rawHumanBones=new xE(e),this._normalizedHumanBones=new TE(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new xE(e.humanBones),this._normalizedHumanBones=new TE(this._rawHumanBones),this}clone(){return new e(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn(`VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead.`),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn(`VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead.`),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn(`VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead.`),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn(`VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead.`),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn(`VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead.`),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn(`VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead.`),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},DE={Hips:`hips`,Spine:`spine`,Head:`head`,LeftUpperLeg:`leftUpperLeg`,LeftLowerLeg:`leftLowerLeg`,LeftFoot:`leftFoot`,RightUpperLeg:`rightUpperLeg`,RightLowerLeg:`rightLowerLeg`,RightFoot:`rightFoot`,LeftUpperArm:`leftUpperArm`,LeftLowerArm:`leftLowerArm`,LeftHand:`leftHand`,RightUpperArm:`rightUpperArm`,RightLowerArm:`rightLowerArm`,RightHand:`rightHand`},OE=new Set([`1.0`,`1.0-beta`]),kE={leftThumbProximal:`leftThumbMetacarpal`,leftThumbIntermediate:`leftThumbProximal`,rightThumbProximal:`rightThumbMetacarpal`,rightThumbIntermediate:`rightThumbProximal`},AE=class{get name(){return`VRMHumanoidLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot,this.autoUpdateHumanBones=t?.autoUpdateHumanBones}afterRoot(e){return HT(this,null,function*(){e.userData.vrmHumanoid=yield this._import(e)})}_import(e){return HT(this,null,function*(){return(yield this._v1Import(e))||(yield this._v0Import(e))||null})}_v1Import(e){return HT(this,null,function*(){let t=this.parser.json;if(t.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let n=t.extensions?.VRMC_vrm;if(!n)return null;let r=n.specVersion;if(!OE.has(r))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${r}"`),null;let i=n.humanoid;if(!i)return null;let a=i.humanBones.leftThumbIntermediate!=null||i.humanBones.rightThumbIntermediate!=null,o={};i.humanBones!=null&&(yield Promise.all(Object.entries(i.humanBones).map(e=>HT(this,[e],function*([e,t]){let n=e,r=t.node;if(a){let e=kE[n];e!=null&&(n=e)}let i=yield this.parser.getDependency(`node`,r);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${n} (index = ${r}) does not exist`);return}o[n]={node:i}}))));let s=new EE(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let e=new hE(s);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return s})}_v0Import(e){return HT(this,null,function*(){let t=this.parser.json.extensions?.VRM;if(!t)return null;let n=t.humanoid;if(!n)return null;let r={};n.humanBones!=null&&(yield Promise.all(n.humanBones.map(e=>HT(this,null,function*(){let t=e.bone,n=e.node;if(t==null||n==null)return;let i=yield this.parser.getDependency(`node`,n);if(i==null){console.warn(`A glTF node bound to the humanoid bone ${t} (index = ${n}) does not exist`);return}let a=kE[t]??t;if(r[a]!=null){console.warn(`Multiple bone entries for ${a} detected (index = ${n}), ignoring duplicated entries.`);return}r[a]={node:i}}))));let i=new EE(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(i.normalizedHumanBonesRoot),this.helperRoot){let e=new hE(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i})}_ensureRequiredBonesExist(e){let t=Object.values(DE).filter(t=>e[t]==null);if(t.length>0)throw Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(`, `)}`);return e}},jE=class extends dd{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new Y(new Float32Array(195),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new Y(new Uint16Array(189),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,e=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let e=0;e<64;e++){let t=e/63*this._currentTheta;this._attrPos.setXYZ(e+1,this._currentRadius*Math.sin(t),0,this._currentRadius*Math.cos(t))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<63;e++)this._attrIndex.setXYZ(e*3,0,e+1,e+2);this._attrIndex.needsUpdate=!0}},ME=class extends dd{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new G,this._currentTail=new G,this._attrPos=new Y(new Float32Array(294),3),this.setAttribute(`position`,this._attrPos),this._attrIndex=new Y(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){let t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){let t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},NE=new W,PE=new W,FE=new G,IE=new G,LE=Math.sqrt(2)/2,RE=new W(0,0,-LE,LE),zE=new G(0,1,0),BE=class extends iu{constructor(e){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=e;{let e=new jE;e.radius=.5;let t=new Td({color:65280,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshPitch=new Ld(e,t),this.add(this._meshPitch)}{let e=new jE;e.radius=.5;let t=new Td({color:16711680,transparent:!0,opacity:.5,side:2,depthTest:!1,depthWrite:!1});this._meshYaw=new Ld(e,t),this.add(this._meshYaw)}{let e=new ME;e.radius=.1;let t=new yf({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new jf(e,t),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(e){let t=cl.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=t,this._meshYaw.geometry.update();let n=cl.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(FE),this.vrmLookAt.getLookAtWorldQuaternion(NE),NE.multiply(this.vrmLookAt.getFaceFrontQuaternion(PE)),this._meshYaw.position.copy(FE),this._meshYaw.quaternion.copy(NE),this._meshPitch.position.copy(FE),this._meshPitch.quaternion.copy(NE),this._meshPitch.quaternion.multiply(PE.setFromAxisAngle(zE,t)),this._meshPitch.quaternion.multiply(RE);let{target:r,autoUpdate:i}=this.vrmLookAt;r!=null&&i&&(r.getWorldPosition(IE).sub(FE),this._lineTarget.geometry.tail.copy(IE),this._lineTarget.geometry.update(),this._lineTarget.position.copy(FE)),super.updateMatrixWorld(e)}},VE=new G,HE=new G;function UE(e,t){return e.matrixWorld.decompose(VE,t,HE),t}function WE(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function GE(e){let t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}var KE=new G(0,0,1),qE=new G,JE=new G,YE=new G,XE=new W,ZE=new W,QE=new W,$E=new W,eD=new Bl,tD=class e{constructor(e,t){this.offsetFromHeadBone=new G,this.autoUpdate=!0,this.faceFront=new G(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new W)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn(`VRMLookAt: euler is deprecated. use getEuler() instead.`),this.getEuler(new Bl)}getEuler(e){return e.set(cl.DEG2RAD*this._pitch,cl.DEG2RAD*this._yaw,0,`YXZ`)}copy(e){if(this.humanoid!==e.humanoid)throw Error(`VRMLookAt: humanoid must be same in order to copy`);return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new e(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let t=this.humanoid.getRawBoneNode(`head`);return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){return UE(this.humanoid.getRawBoneNode(`head`),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(KE)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=WE(this.faceFront);return eD.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(eD).premultiply($E.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(ZE),this.getFaceFrontQuaternion(QE),e.copy(KE).applyQuaternion(ZE).applyQuaternion(QE).applyEuler(this.getEuler(eD))}lookAt(e){let t=XE.copy(this._restHeadWorldQuaternion).multiply(vE(this.getLookAtWorldQuaternion(ZE))),n=this.getLookAtWorldPosition(JE),r=YE.copy(e).sub(n).applyQuaternion(t).normalize(),[i,a]=WE(this.faceFront),[o,s]=WE(r),c=GE(o-i),l=GE(a-s);this._yaw=cl.RAD2DEG*c,this._pitch=cl.RAD2DEG*l,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(qE)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};tD.EULER_ORDER=`YXZ`;var nD=tD,rD=new G(0,0,1),iD=new W,aD=new W,oD=new Bl(0,0,0,`YXZ`),sD=class{constructor(e,t,n,r,i){this.humanoid=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i,this.faceFront=new G(0,0,1),this._restQuatLeftEye=new W,this._restQuatRightEye=new W,this._restLeftEyeParentWorldQuat=new W,this._restRightEyeParentWorldQuat=new W;let a=this.humanoid.getRawBoneNode(`leftEye`),o=this.humanoid.getRawBoneNode(`rightEye`);a&&(this._restQuatLeftEye.copy(a.quaternion),UE(a.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),UE(o.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(e,t){let n=this.humanoid.getRawBoneNode(`leftEye`),r=this.humanoid.getRawBoneNode(`rightEye`),i=this.humanoid.getNormalizedBoneNode(`leftEye`),a=this.humanoid.getNormalizedBoneNode(`rightEye`);n&&(t<0?oD.x=-cl.DEG2RAD*this.rangeMapVerticalDown.map(-t):oD.x=cl.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?oD.y=-cl.DEG2RAD*this.rangeMapHorizontalInner.map(-e):oD.y=cl.DEG2RAD*this.rangeMapHorizontalOuter.map(e),iD.setFromEuler(oD),this._getWorldFaceFrontQuat(aD),i.quaternion.copy(aD).multiply(iD).multiply(aD.invert()),iD.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(iD).premultiply(iD.invert()).multiply(this._restQuatLeftEye)),r&&(t<0?oD.x=-cl.DEG2RAD*this.rangeMapVerticalDown.map(-t):oD.x=cl.DEG2RAD*this.rangeMapVerticalUp.map(t),e<0?oD.y=-cl.DEG2RAD*this.rangeMapHorizontalOuter.map(-e):oD.y=cl.DEG2RAD*this.rangeMapHorizontalInner.map(e),iD.setFromEuler(oD),this._getWorldFaceFrontQuat(aD),a.quaternion.copy(aD).multiply(iD).multiply(aD.invert()),iD.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(a.quaternion).multiply(iD).premultiply(iD.invert()).multiply(this._restQuatRightEye))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=cl.RAD2DEG*e.y,n=cl.RAD2DEG*e.x;this.applyYawPitch(t,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(rD)<.01)return e.identity();let[t,n]=WE(this.faceFront);return oD.set(0,.5*Math.PI+t,n,`YZX`),e.setFromEuler(oD)}};sD.type=`bone`;var cD=class{constructor(e,t,n,r,i){this.expressions=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=i}applyYawPitch(e,t){t<0?(this.expressions.setValue(`lookDown`,0),this.expressions.setValue(`lookUp`,this.rangeMapVerticalUp.map(-t))):(this.expressions.setValue(`lookUp`,0),this.expressions.setValue(`lookDown`,this.rangeMapVerticalDown.map(t))),e<0?(this.expressions.setValue(`lookLeft`,0),this.expressions.setValue(`lookRight`,this.rangeMapHorizontalOuter.map(-e))):(this.expressions.setValue(`lookRight`,0),this.expressions.setValue(`lookLeft`,this.rangeMapHorizontalOuter.map(e)))}lookAt(e){console.warn(`VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.`);let t=cl.RAD2DEG*e.y,n=cl.RAD2DEG*e.x;this.applyYawPitch(t,n)}};cD.type=`expression`;var lD=class{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*JT(e/this.inputMaxValue)}},uD=new Set([`1.0`,`1.0-beta`]),dD=.01,fD=class{get name(){return`VRMLookAtLoaderPlugin`}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return HT(this,null,function*(){let t=e.userData.vrmHumanoid;if(t===null)return;if(t===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first`);let n=e.userData.vrmExpressionManager;if(n!==null){if(n===void 0)throw Error(`VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first`);e.userData.vrmLookAt=yield this._import(e,t,n)}})}_import(e,t,n){return HT(this,null,function*(){return t==null||n==null?null:(yield this._v1Import(e,t,n))||(yield this._v0Import(e,t,n))||null})}_v1Import(e,t,n){return HT(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let r=e.extensions?.VRMC_vrm;if(!r)return null;let i=r.specVersion;if(!uD.has(i))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${i}"`),null;let a=r.lookAt;if(!a)return null;let o=a.type===`expression`?1:10,s=this._v1ImportRangeMap(a.rangeMapHorizontalInner,o),c=this._v1ImportRangeMap(a.rangeMapHorizontalOuter,o),l=this._v1ImportRangeMap(a.rangeMapVerticalDown,o),u=this._v1ImportRangeMap(a.rangeMapVerticalUp,o),d;d=a.type===`expression`?new cD(n,s,c,l,u):new sD(t,s,c,l,u);let f=this._importLookAt(t,d);return f.offsetFromHeadBone.fromArray(a.offsetFromHeadBone??[0,.06,0]),f})}_v1ImportRangeMap(e,t){let n=e?.inputMaxValue??90,r=e?.outputScale??t;return n<dD&&(console.warn(`VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!`),n=dD),new lD(n,r)}_v0Import(e,t,n){return HT(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let r=e.firstPerson;if(!r)return null;let i=r.lookAtTypeName===`BlendShape`?1:10,a=this._v0ImportDegreeMap(r.lookAtHorizontalInner,i),o=this._v0ImportDegreeMap(r.lookAtHorizontalOuter,i),s=this._v0ImportDegreeMap(r.lookAtVerticalDown,i),c=this._v0ImportDegreeMap(r.lookAtVerticalUp,i),l;l=r.lookAtTypeName===`BlendShape`?new cD(n,a,o,s,c):new sD(t,a,o,s,c);let u=this._importLookAt(t,l);return r.firstPersonBoneOffset?u.offsetFromHeadBone.set(r.firstPersonBoneOffset.x??0,r.firstPersonBoneOffset.y??.06,-(r.firstPersonBoneOffset.z??0)):u.offsetFromHeadBone.set(0,.06,0),u.faceFront.set(0,0,-1),l instanceof sD&&l.faceFront.set(0,0,-1),u})}_v0ImportDegreeMap(e,t){let n=e?.curve;JSON.stringify(n)!==`[0,0,0,1,1,1,1,0]`&&console.warn(`Curves of LookAtDegreeMap defined in VRM 0.0 are not supported`);let r=e?.xRange??90,i=e?.yRange??t;return r<dD&&(console.warn(`VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!`),r=dD),new lD(r,i)}_importLookAt(e,t){let n=new nD(e,t);if(this.helperRoot){let e=new BE(n);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return n}};function pD(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}var mD=new Set([`1.0`,`1.0-beta`]),hD=class{get name(){return`VRMMetaLoaderPlugin`}constructor(e,t){this.parser=e,this.needThumbnailImage=t?.needThumbnailImage??!1,this.acceptLicenseUrls=t?.acceptLicenseUrls??[`https://vrm.dev/licenses/1.0/`],this.acceptV0Meta=t?.acceptV0Meta??!0}afterRoot(e){return HT(this,null,function*(){e.userData.vrmMeta=yield this._import(e)})}_import(e){return HT(this,null,function*(){return(yield this._v1Import(e))??(yield this._v0Import(e))??null})}_v1Import(e){return HT(this,null,function*(){let e=this.parser.json;if(e.extensionsUsed?.indexOf(`VRMC_vrm`)===-1)return null;let t=e.extensions?.VRMC_vrm;if(t==null)return null;let n=t.specVersion;if(!mD.has(n))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${n}"`),null;let r=t.meta;if(!r)return null;let i=r.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(i))throw Error(`VRMMetaLoaderPlugin: The license url "${i}" is not accepted`);let a;return this.needThumbnailImage&&r.thumbnailImage!=null&&(a=(yield this._extractGLTFImage(r.thumbnailImage))??void 0),{metaVersion:`1`,name:r.name,version:r.version,authors:r.authors,copyrightInformation:r.copyrightInformation,contactInformation:r.contactInformation,references:r.references,thirdPartyLicenses:r.thirdPartyLicenses,thumbnailImage:a,licenseUrl:r.licenseUrl,avatarPermission:r.avatarPermission,allowExcessivelyViolentUsage:r.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:r.allowExcessivelySexualUsage,commercialUsage:r.commercialUsage,allowPoliticalOrReligiousUsage:r.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:r.allowAntisocialOrHateUsage,creditNotation:r.creditNotation,allowRedistribution:r.allowRedistribution,modification:r.modification,otherLicenseUrl:r.otherLicenseUrl}})}_v0Import(e){return HT(this,null,function*(){let e=this.parser.json.extensions?.VRM;if(!e)return null;let t=e.meta;if(!t)return null;if(!this.acceptV0Meta)throw Error(`VRMMetaLoaderPlugin: Attempted to load VRM0.0 meta but acceptV0Meta is false`);let n;return this.needThumbnailImage&&t.texture!=null&&t.texture!==-1&&(n=yield this.parser.getDependency(`texture`,t.texture)),{metaVersion:`0`,allowedUserName:t.allowedUserName,author:t.author,commercialUssageName:t.commercialUssageName,contactInformation:t.contactInformation,licenseName:t.licenseName,otherLicenseUrl:t.otherLicenseUrl,otherPermissionUrl:t.otherPermissionUrl,reference:t.reference,sexualUssageName:t.sexualUssageName,texture:n??void 0,title:t.title,version:t.version,violentUssageName:t.violentUssageName}})}_extractGLTFImage(e){return HT(this,null,function*(){let t=this.parser.json.images?.[e];if(t==null)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image doesn't exist`),null;let n=t.uri;if(t.bufferView!=null){let e=yield this.parser.getDependency(`bufferView`,t.bufferView),r=new Blob([e],{type:t.mimeType});n=URL.createObjectURL(r)}return n==null?(console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${e}] of glTF as a thumbnail but the image couldn't load properly`),null):yield new Hp().loadAsync(pD(n,this.parser.options.path)).catch(e=>(console.error(e),console.warn(`VRMMetaLoaderPlugin: Failed to load a thumbnail image`),null))})}},gD=class{constructor(e){this.scene=e.scene,this.meta=e.meta,this.humanoid=e.humanoid,this.expressionManager=e.expressionManager,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt}update(e){this.humanoid.update(),this.lookAt&&this.lookAt.update(e),this.expressionManager&&this.expressionManager.update()}},_D=class extends gD{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach(t=>{t.update&&t.update(e)})}},vD=Object.defineProperty,yD=Object.getOwnPropertySymbols,bD=Object.prototype.hasOwnProperty,xD=Object.prototype.propertyIsEnumerable,SD=(e,t,n)=>t in e?vD(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,CD=(e,t)=>{for(var n in t||={})bD.call(t,n)&&SD(e,n,t[n]);if(yD)for(var n of yD(t))xD.call(t,n)&&SD(e,n,t[n]);return e},wD=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});function TD(e,t){e.colorSpace=t}var ED=class{get pending(){return Promise.all(this._pendings)}constructor(e,t){this._parser=e,this._materialParams=t,this._pendings=[]}assignPrimitive(e,t){t!=null&&(this._materialParams[e]=t)}assignColor(e,t,n){if(t!=null){let r=new J().fromArray(t);n&&r.convertSRGBToLinear(),this._materialParams[e]=r}}assignTexture(e,t,n){return wD(this,null,function*(){let r=wD(this,null,function*(){if(t!=null){let r=yield this._parser.assignTexture(this._materialParams,e,t);if(r==null){console.warn(`GLTFMToonMaterialParamsAssignHelper: Failed to load texture. The rendering result may be wrong`);return}n&&TD(r,`srgb`)}});return this._pendings.push(r),r})}assignTextureByIndex(e,t,n){return wD(this,null,function*(){return this.assignTexture(e,t==null?void 0:{index:t},n)})}},DD=`// #define PHONG
|
|
6230
6230
|
|
|
6231
6231
|
varying vec3 vViewPosition;
|
|
6232
6232
|
|
|
@@ -8959,7 +8959,7 @@ void main() {
|
|
|
8959
8959
|
#include <tonemapping_fragment>
|
|
8960
8960
|
#include <colorspace_fragment>
|
|
8961
8961
|
|
|
8962
|
-
}`};var zV=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,BV={apartment:`lebombo_1k.hdr`,city:`potsdamer_platz_1k.hdr`,dawn:`kiara_1_dawn_1k.hdr`,forest:`forest_slope_1k.hdr`,lobby:`st_fagans_interior_1k.hdr`,night:`dikhololo_night_1k.hdr`,park:`rooitou_park_1k.hdr`,studio:`studio_small_03_1k.hdr`,sunset:`venice_sunset_1k.hdr`,warehouse:`empty_warehouse_01_1k.hdr`};function VV(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=BV[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(BV).join(`, `)}.`);return`${zV}/${t}`}return null}var HV=75,UV=class{scene;ambient=new dm(`#ffffff`,0);envKey=null;config=kr(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new fu(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new J;onHdriError=null;assets=null;backdropUrl=null;backdropTexture=null;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?Nr(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get post(){return this.config.post}get sceneFog(){return this.scene.fog instanceof fu?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=kr(e));let r=this.config,i=e?.ambient;if(this.ambient.color.set(i?.color??`#ffffff`),this.ambient.intensity=i?.intensity??0,t&&(t.toneMappingExposure=r.exposure,t.shadowMap.enabled=r.shadows!==!1,r.shadows!==!1&&r.shadows!==null&&r.shadows.static?t.shadowMap.autoUpdate&&(t.shadowMap.autoUpdate=!1,t.shadowMap.needsUpdate=!0):t.shadowMap.autoUpdate||(t.shadowMap.autoUpdate=!0)),this.applyHdri(e),this.applySky(r.sky,t),this.applyBackdrop(r.skybox),this._sky&&(this._sky.visible=this.backdropTexture===null),this.applyFog(r),this.scene.environment=this.hdriTexture??this.skyEnvTarget?.texture??null,this.scene.environmentIntensity=(this.scene.environment===this.skyEnvTarget?.texture&&this.skyEnvTarget?.55:1)*WV(e?.iblIntensity),this.backdropTexture)this.scene.background=this.backdropTexture;else if(r.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new J(t):null}}applySunLight(e,t=null){if(!e)return;let n=this.sunDirection;if(t){let r=e.position.length()||100,i,a,o;if(n)[i,a,o]=n;else{i=e.position.x-e.target.position.x,a=e.position.y-e.target.position.y,o=e.position.z-e.target.position.z;let t=Math.hypot(i,a,o)||1;i/=t,a/=t,o/=t}e.target.position.set(t.x,t.y,t.z),e.target.updateMatrixWorld(),e.position.set(t.x+i*r,t.y+a*r,t.z+o*r)}else if(n){let t=e.position.length()||100;e.position.set(n[0],n[1],n[2]).multiplyScalar(t)}let r=this.config.shadows;if(r&&typeof r==`object`){if(!e.castShadow){let t=e.shadow.camera;`left`in t&&t.left===-5&&(t.left=-75,t.right=HV,t.top=HV,t.bottom=-75,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.castShadow=!0}e.shadow.mapSize.x!==r.mapSize&&(e.shadow.mapSize.set(r.mapSize,r.mapSize),e.shadow.map?.dispose(),e.shadow.map=null),e.shadow.radius=r.radius}}applyUnderwater(e){e&&(this.underwaterFog||=new fu(`#000000`,.5,e.visibility),this.underwaterFog.color.set(e.color),this.underwaterFog.near=.5,this.underwaterFog.far=e.visibility,this.scene.fog=this.underwaterFog,this.scene.background=this.underwaterBg.set(e.color),this._sky&&(this._sky.visible=!1))}applyHdri(e){let t=VV(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new LV().load(t,e=>{if(this.hdriUrl!==t){e.dispose();return}e.mapping=303,this.hdriTexture=e},void 0,e=>{this.onHdriError?.(t,e)}))}applyBackdrop(e){let t=typeof e==`string`?e:null;if(t===this.backdropUrl||(this.backdropUrl=t,this.backdropTexture?.dispose(),this.backdropTexture=null,!t))return;if(/\.hdr(\?|#|$)/i.test(t)){if(typeof document>`u`)return;new LV().load(t,e=>{if(this.backdropUrl!==t){e.dispose();return}e.mapping=303,this.backdropTexture=e},void 0,e=>{this.onHdriError?.(t,e)});return}let n=this.assets?.textures.acquireOwn(t,{colorSpace:`srgb`})??null;n&&(n.mapping=303,n.colorSpace=hc,this.backdropTexture=n)}applySky(e,t){let n=e?JSON.stringify(e):``;if(n!==this.skyKey&&(this.skyKey=n,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null),e)){this._sky=new RV,this._sky.scale.setScalar(45e4);let t=this._sky.material.uniforms;(t.sunPosition?.value).set(...e.sunPosition),t.turbidity&&(t.turbidity.value=e.turbidity),t.rayleigh&&(t.rayleigh.value=e.rayleigh),this.scene.add(this._sky)}if(e&&t&&this._sky&&this.skyEnvKey!==n){this.skyEnvKey=n,this.skyEnvTarget?.dispose();let e=new ph(t),r=new pu;r.add(this._sky),this.skyEnvTarget=e.fromScene(r),e.dispose(),this.scene.add(this._sky)}!e&&this.skyEnvTarget&&(this.skyEnvTarget.dispose(),this.skyEnvTarget=null,this.skyEnvKey=``)}applyFog(e){if(!e.fog){this.scene.fog=null;return}let t=e.fog.color||(e.sky?Pr(e.sky):`#cfd8e0`);this.fog.color.set(t),this.fog.near=e.fog.near,this.fog.far=e.fog.far,this.scene.fog=this.fog}dispose(){this.hdriTexture?.dispose(),this.hdriTexture=null,this.backdropTexture?.dispose(),this.backdropTexture=null,this.backdropUrl=null,this.skyEnvTarget?.dispose(),this.skyEnvTarget=null,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null)}};function WV(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new L(`BAD_FORMAT`,`environment.iblIntensity must be a finite number >= 0 (multiplies the image-based ambience: sky-derived base 0.55, HDRI base 1; default 1), got ${JSON.stringify(e)}.`,{prop:`iblIntensity`});return e}var GV=new Ou,KV=new Ou,qV=new q,JV=new q,YV=new G,XV=Array.from({length:8},()=>new G),ZV=.4,QV=new Float32Array(72),$V=[[0,0,0],[1,0,0],[1,0,1],[0,0,1],[0,1,0],[1,1,0],[1,1,1],[0,1,1]],eH=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];function tH(e,t){t.makeEmpty(),qV.copy(e.matrixWorld).invert(),e.traverse(e=>{let n=e,r;n.isInstancedMesh?(n.boundingBox||n.computeBoundingBox?.(),r=n.boundingBox):n.geometry&&(n.geometry.boundingBox||n.geometry.computeBoundingBox(),r=n.geometry.boundingBox),r&&(KV.copy(r).applyMatrix4(JV.multiplyMatrices(qV,e.matrixWorld)),t.union(KV))})}function nH(e){if(!(e instanceof Fb))return null;let t=e._ensureObject3D();t.updateWorldMatrix(!0,!0),tH(t,GV);let n=!0;GV.isEmpty()?(n=!1,YV.setFromMatrixPosition(t.matrixWorld),GV.min.set(YV.x-ZV,YV.y-ZV,YV.z-ZV),GV.max.set(YV.x+ZV,YV.y+ZV,YV.z+ZV)):GV.expandByScalar(.02);let{min:r,max:i}=GV;for(let e=0;e<8;e++){let[a,o,s]=$V[e],c=XV[e].set(a?i.x:r.x,o?i.y:r.y,s?i.z:r.z);n&&c.applyMatrix4(t.matrixWorld)}let a=0;for(let[e,t]of eH){let n=XV[e],r=XV[t];QV[a++]=n.x,QV[a++]=n.y,QV[a++]=n.z,QV[a++]=r.x,QV[a++]=r.y,QV[a++]=r.z}return QV}function rH(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function iH(){let e=new Set,t=[],n=[],r=[];return{visited:e,cameras:t,renderHooks:n,emitters:r,state:{visited:e,cameras:t,renderHooks:n,emitters:r,assets:void 0,sunDirection:null,sunLight:null,alpha:1,ignoreStatic:!1,quality:null},blend:{cam:new rm,active:!1,t:0,seconds:0,fromPos:new G,fromQuat:new W,fromFov:60,lastNode:null,lastPos:new G,lastQuat:new W,lastFov:60}}}var aH=new G,oH=new W;function sH(e,t,n,r,i){let a=i??iH();a.visited.clear(),a.cameras.length=0,a.renderHooks.length=0,a.emitters.length=0;let o=a.state;o.assets=n,o.sunDirection=r?.sunDirection??null,o.ignoreStatic=r?.ignoreStatic===!0,o.sunLight=null,o.alpha=r?.alpha??1,o.quality=r?.quality??null,mH(e,t,o),_H(t,a.visited);let s=null;for(let e=0;e<a.cameras.length;e++){let t=a.cameras[e];if(t.current){s=t;break}}s||=a.cameras[0]??null;let c=s?s._ensureObject3D():null;return s&&c&&(c=cH(a.blend,s,c,r?.dt??0)),pH(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}function cH(e,t,n,r){let i=t._blendRequest;if(t._blendRequest=void 0,e.lastNode!==t){let n=i??t.blendSeconds;e.lastNode&&n>0?(e.fromPos.copy(e.lastPos),e.fromQuat.copy(e.lastQuat),e.fromFov=e.lastFov,e.t=0,e.seconds=n,e.active=!0):e.active=!1}let a=n;if(e.active){e.t+=r;let t=Math.min(1,e.t/e.seconds),i=t<.5?2*t*t:1-(-2*t+2)**2/2;n.updateWorldMatrix(!0,!1),n.getWorldPosition(aH),n.getWorldQuaternion(oH),e.cam.position.copy(e.fromPos).lerp(aH,i),e.cam.quaternion.copy(e.fromQuat).slerp(oH,i),e.cam.fov=e.fromFov+(n.fov-e.fromFov)*i,e.cam.near=n.near,e.cam.far=n.far,e.cam.aspect=n.aspect,e.cam.updateProjectionMatrix(),e.cam.updateMatrixWorld(!0),t>=1?e.active=!1:a=e.cam}return a.updateWorldMatrix(!0,!1),a.getWorldPosition(e.lastPos),a.getWorldQuaternion(e.lastQuat),e.lastFov=a.fov,e.lastNode=t,a}var lH=new G,uH=new G,dH=new G,fH=new G;function pH(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(uH),t.getWorldDirection(dH),fH.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[uH.x,uH.y,uH.z],forward:[dH.x,dH.y,dH.z],up:[fH.x,fH.y,fH.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(lH),t._setSpatialPose({position:[lH.x,lH.y,lH.z],listener:n})}function mH(e,t,n){let r=t;if(e instanceof Fb){let i=e._ensureObject3D();if(e.static&&!n.ignoreStatic&&i.userData.incantoStaticSynced===!0){i.userData.incantoStatic=!0,n.visited.add(i);return}if(i.parent!==t&&t.add(i),n.quality){let t=e._applyQualityCaps;typeof t==`function`&&t.call(e,n.quality)}if(e._syncObject3D(n.alpha,n.assets??null),n.assets&&e instanceof WL&&e._syncModel(n.assets),typeof e._onRender3D==`function`&&n.renderHooks.push(e),n.sunDirection){let t=e._applySunDirection;typeof t==`function`&&t.call(e,n.sunDirection)}e instanceof SL&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof dP&&n.cameras.push(e),r=i}else rH(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)mH(t,r,n);if(e instanceof Fb){let t=e._ensureObject3D();e.static&&!n.ignoreStatic&&e._staticReady(n.assets??null)?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,gH(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var hH=new WeakSet;function gH(e){if(hH.has(e))return;hH.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof dP)&&t.push(`${e.name} (${e.constructor.typeName??`?`})`);for(let t of e.children)n(t)};n(e),t.length>0&&z(e.tree?.engine??null,`warn`,`[incanto] static subtree '${e.name}' freezes animated/per-frame nodes: ${t.join(`, `)} — they will stop updating. Unmark static or move them out.`)}function _H(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&_H(i,t)}}var vH=120,yH=class{viewOverride=null;overrideCam=new rm(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new pu;environment=(()=>{let e=new UV(this.threeScene);return e.onHdriError=(e,t)=>{this.assets.textures.noteError(e,t),z(this.engine,`error`,`[incanto] the scene's lighting (${e}) could not be loaded — nothing else lights it.`)},e})();engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;warmCamera=null;deferCompile=!1;syncScratch=iH();ignoreStatic=!1;renderCtx=null;causticsTarget=null;causticsScene=null;causticsUniforms=null;cloudsTarget=null;cloudsHalfTarget=null;cloudsBlurTarget=null;cloudsScene=null;cloudsUniforms=null;cloudsBlurScene=null;cloudsBlurUniforms=null;cloudsCompositeScene=null;cloudsCompositeUniforms=null;bloomTarget=null;bloomBrightTarget=null;bloomBlurTarget=null;bloomBrightScene=null;bloomBrightUniforms=null;bloomBlurScene=null;bloomBlurUniforms=null;bloomCompositeScene=null;bloomCompositeUniforms=null;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.ownsAssets=!e.assets,this.assets=e.assets??new QA(this.engine),this.environment.assets=this.assets;let t=Po(e.engine.scene?.environment,{antialias:e.qualityDefaults?.antialias??!0,pixelRatio:e.qualityDefaults?.pixelRatio??Math.min(globalThis.devicePixelRatio??1,2),preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio,preserveDrawingBuffer:e.preserveDrawingBuffer});this.webgl=zo(()=>new ov({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer})),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.engine.toWorld=(e,t)=>{let n=this.worldFromScreen(e,t);return n?[n.x,n.y,n.z]:null},this.engine.toScreen=e=>this.screenFromWorld(e[0]??0,e[1]??0,e[2]??0),this.engine.screenRay=(e,t)=>this.rayFromScreen(e,t),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.adaptive=e.adaptiveResolution===!1?null:new bV,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new jf(new dd,new yf({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new jf(new dd,new yf({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.threeScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>{let e=performance.now();this.render(),this.engine.noteRenderMs(performance.now()-e)})}basePixelRatio;adaptive;renderScale=1;adaptiveScale=1;lastFrameAt=0;debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?nH(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new Y(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of tw(`3d`,this.engine))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new Y(e,3))}governResolution(){let e=this.adaptive;if(!e)return;let t=globalThis.performance?.now?.()??0,n=this.lastFrameAt;if(this.lastFrameAt=t,n===0)return;let r=t-n;if(r>500){e.reset();return}let i=e.push(r);i!==null&&(this.adaptiveScale=i,this.applyPixelRatio())}setRenderScale(e){let t=Math.min(2,Math.max(.25,e>0?e:1));t!==this.renderScale&&(this.renderScale=t,this.applyPixelRatio())}setFrameTarget(e){this.adaptive?.setTarget(e)}applyPixelRatio(){this.webgl.setPixelRatio(this.basePixelRatio*this.renderScale*this.adaptiveScale);let e=this.lastSize;e.w>0&&e.h>0&&this.webgl.setSize(e.w,e.h,!1)}deferFirstCompile(){this.deferCompile=!0}async warmUp(e){this.deferCompile=!1;let t=this.warmCamera;if(!t)return;let n=[];this.threeScene.traverse(e=>{(e.isMesh||e.isPoints)&&n.push(e)});let r=n.filter(e=>e.visible);if(r.length===0){this.webgl.compile(this.threeScene,t),e?.(1);return}for(let e of r)e.visible=!1;let i=Math.min(bH,r.length),a=Math.ceil(r.length/i);try{for(let n=0;n<i;n++){for(let e=n*a;e<Math.min((n+1)*a,r.length);e++)r[e].visible=!0;this.webgl.compile(this.threeScene,t),e?.((n+1)/i),await cj()}}finally{for(let e of r)e.visible=!0}}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.governResolution(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e)),this.environment.apply(e.environment,this.webgl);let{activeCamera:t,renderHooks:n,sunLight:r}=sH(e.root,this.threeScene,this.assets,{sunDirection:this.environment.sunDirection,alpha:this.engine.interpolationAlpha,dt:this.engine.unscaledDelta,ignoreStatic:this.ignoreStatic,quality:ya(this.engine.settings.get(`quality`))},this.syncScratch),i=t;if(this.viewOverride){let[e,t,n]=this.viewOverride.position,[r,a,o]=this.viewOverride.target;this.overrideCam.position.set(e,t,n),this.overrideCam.lookAt(SH.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(OH),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&!this.deferCompile&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i)),this.warmCamera=i;let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(xH);(u.x!==c||u.y!==l)&&this.webgl.setSize(c,l,!1),this.lastSize={w:c,h:l};let d=l===0?1:c/l;i.aspect!==d&&(i.aspect=d,i.updateProjectionMatrix()),this.renderCtx||={gl:this.webgl,scene:this.threeScene,camera:i};let f=this.renderCtx;f.camera=i,o?(o.updateWorldMatrix(!0,!1),o.target.updateWorldMatrix(!0,!1),f.sunDir=wH.setFromMatrixPosition(o.matrixWorld).sub(TH.setFromMatrixPosition(o.target.matrixWorld)).normalize()):f.sunDir=null;for(let e=0;e<n.length;e++)n[e]?._onRender3D(f);let p=null;for(let e=0;e<n.length;e++){let t=n[e].underwaterAt?.(a.x,a.y,a.z);if(t){p=t;break}}this.environment.applyUnderwater(p);let m=this.environment.clouds,h=this.environment.bloom,g=this.environment.post;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):(h||g)&&!p?this.renderWithBloom(i,h,g):this.webgl.render(this.threeScene,i),this.drainFrameCapture()}captureFrame(){return new Promise((e,t)=>{this.pendingCaptures.push({resolve:e,reject:t}),setTimeout(()=>{if(this.pendingCaptures.length>0)try{this.render()}catch(e){let t=e instanceof Error?e:Error(String(e));for(let e of this.pendingCaptures.splice(0))e.reject(t)}},vH)})}pendingCaptures=[];drainFrameCapture(){if(this.pendingCaptures.length===0)return;let e=this.pendingCaptures;this.pendingCaptures=[];try{let t=this.webgl.getContext(),n=this.webgl.domElement.width,r=this.webgl.domElement.height,i=new Uint8Array(n*r*4);this.webgl.setRenderTarget(null),t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,i),jH(i,n,r);for(let t of e)t.resolve({pixels:i,width:n,height:r})}catch(t){let n=t instanceof Error?t:Error(String(t));for(let t of e)t.reject(n)}}renderWithBloom(e,t,n=null){let r=this.webgl.getDrawingBufferSize(xH),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/2)),s=Math.max(1,Math.ceil(a/2));if(this.bloomTarget&&(this.bloomTarget.width!==i||this.bloomTarget.height!==a)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new Ol(i,a,{type:rs,samples:4}),this.bloomBrightTarget=new Ol(o,s,{type:rs}),this.bloomBlurTarget=new Ol(o,s,{type:rs})),!this.bloomBrightScene){let e=EV();this.bloomBrightScene=new pu,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=DV();this.bloomBlurScene=new pu,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=OV();this.bloomCompositeScene=new pu,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let c=this.bloomBrightTarget,l=this.bloomBlurTarget;if(this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e),t){let n=this.bloomBrightUniforms;n.tScene.value=this.bloomTarget.texture,n.uThreshold.value=t.threshold,this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBrightScene,e);let r=this.bloomBlurUniforms;r.tTex.value=c.texture,r.uDir.value.set(1/o,0),this.webgl.setRenderTarget(l),this.webgl.render(this.bloomBlurScene,e),r.tTex.value=l.texture,r.uDir.value.set(0,1/s),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e)}let u=this.bloomCompositeUniforms;u.tScene.value=this.bloomTarget.texture,u.tBloom.value=t?c.texture:this.bloomTarget.texture,u.uStrength.value=t?t.strength:0,u.uVignette.value=n?.vignette??0,u.uSaturation.value=n?.saturation??1,u.uContrast.value=n?.contrast??1,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(xH),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/3)),s=Math.max(1,Math.ceil(a/3));if(this.cloudsTarget&&(this.cloudsTarget.width!==i||this.cloudsTarget.height!==a)&&(this.cloudsTarget.depthTexture?.dispose(),this.cloudsTarget.dispose(),this.cloudsTarget=null,this.cloudsHalfTarget?.dispose(),this.cloudsHalfTarget=null,this.cloudsBlurTarget?.dispose(),this.cloudsBlurTarget=null),!this.cloudsTarget){let e=new Hf(i,a);e.type=ns,this.cloudsTarget=new Ol(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Ol(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Ol(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=PV();this.cloudsScene=new pu,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=NV();this.cloudsBlurScene=new pu,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=FV();this.cloudsCompositeScene=new pu,this.cloudsCompositeScene.add(e),this.cloudsCompositeUniforms=t}this.webgl.setRenderTarget(this.cloudsTarget),this.webgl.render(this.threeScene,e);let c=this.cloudsUniforms;c.tDepth.value=this.cloudsTarget.depthTexture,c.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(c.uCameraPos.value),c.uTime.value=(globalThis.performance?.now()??0)*.001*t.speed;let l=this.environment.sunDirection??[.4,.8,.3];c.uSunDir.value.set(l[0],l[1],l[2]).normalize(),n&&c.uSunColor.value.copy(n.color),c.uCloudColor.value.set(t.color),c.uShadeColor.value.set(t.shadeColor);let u=this.environment.sceneFog;u?(c.uHorizonColor.value.copy(u.color),c.uFarFade.value=u.far):(c.uHorizonColor.value.set(`#cdd9e6`),c.uFarFade.value=6e3),c.uBase.value=t.base,c.uTop.value=t.top,c.uCoverage.value=t.coverage,c.uDensity.value=t.density,c.uScale.value=t.scale,c.uWind.value.set(1,.35),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(this.cloudsScene,e);let d=this.cloudsBlurUniforms,f=this.cloudsBlurScene;d.tTex.value=this.cloudsHalfTarget.texture,d.uDir.value.set(1/o,0),this.webgl.setRenderTarget(this.cloudsBlurTarget),this.webgl.render(f,e),d.tTex.value=this.cloudsBlurTarget.texture,d.uDir.value.set(0,1/s),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(f,e),this.webgl.setRenderTarget(null);let p=this.cloudsCompositeUniforms;p.tScene.value=this.cloudsTarget.texture,p.tClouds.value=this.cloudsHalfTarget.texture,this.webgl.render(this.cloudsCompositeScene,e)}renderWithCaustics(e,t){let n=this.webgl.getDrawingBufferSize(xH),r=Math.max(1,n.x),i=Math.max(1,n.y);if(this.causticsTarget&&(this.causticsTarget.width!==r||this.causticsTarget.height!==i)&&(this.causticsTarget.depthTexture?.dispose(),this.causticsTarget.dispose(),this.causticsTarget=null),!this.causticsTarget){let e=new Hf(r,i);e.type=ns,this.causticsTarget=new Ol(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=$y();this.causticsScene=new pu,this.causticsScene.add(e),this.causticsUniforms=t}this.webgl.setRenderTarget(this.causticsTarget),this.webgl.render(this.threeScene,e),this.webgl.setRenderTarget(null);let a=this.causticsUniforms;a.tColor.value=this.causticsTarget.texture,a.tDepth.value=this.causticsTarget.depthTexture,a.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(a.uCameraPos.value),a.uWaterLevel.value=t.surfaceY,a.uTime.value=(globalThis.performance?.now()??0)*.001*t.caustics.speed,a.uCausticColor.value.set(t.caustics.color),a.uCausticIntensity.value=t.caustics.intensity,a.uCausticScale.value=t.caustics.scale,a.uMaxDist.value=t.visibility;let o=this.environment.sunDirection;o&&a.uSunDirection.value.set(o[0],o[1],o[2]),a.uRayStrength.value=t.rays.enabled?t.rays.strength:0,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(CH.set(e,t,n).project(r),{x:(CH.x+1)/2*this.lastSize.w,y:(1-CH.y)/2*this.lastSize.h,behind:CH.z>1}):{x:0,y:0,behind:!0}}worldFromScreen(e,t,n=0){let r=this.rayFromScreen(e,t);if(!r)return null;let i=r.dir[1];if(Math.abs(i)<1e-6)return null;let a=(n-r.origin[1])/i;return a<0?null:{x:r.origin[0]+r.dir[0]*a,y:n,z:r.origin[2]+r.dir[2]*a}}rayFromScreen(e,t){let n=this.lastCamera;if(!n||e<0||e>this.lastSize.w||t<0||t>this.lastSize.h)return null;AH.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),kH.setFromCamera(AH,n);let r=kH.ray.origin,i=kH.ray.direction;return{origin:[r.x,r.y,r.z],dir:[i.x,i.y,i.z]}}pick(e,t){let n=this.lastCamera;return n?(AH.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),kH.setFromCamera(AH,n),nT(kH.intersectObjects(this.threeScene.children,!0))):null}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}lastCameraPosition(){let e=this.lastCamera;return e?(e.getWorldPosition(DH),{x:DH.x,y:DH.y,z:DH.z}):null}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(EH):EH.identity();return{right:new G(1,0,0).applyQuaternion(t),up:new G(0,1,0).applyQuaternion(t),forward:new G(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){this.engine.picker&&(this.engine.picker=null),this.engine.toWorld&&(this.engine.toWorld=null),this.engine.toScreen&&(this.engine.toScreen=null),this.engine.screenRay&&(this.engine.screenRay=null),this.disconnect(),this.threeScene.traverse(e=>{let t=e;if(!(!t.isMesh||t.userData?.incantoModelShared))if(t.geometry?.dispose(),Array.isArray(t.material))for(let e of t.material)e.dispose();else t.material?.dispose()}),this.causticsTarget?.depthTexture?.dispose(),this.causticsTarget?.dispose();let e=this.causticsScene?.children[0];e?.geometry?.dispose(),e?.material?.dispose(),this.cloudsTarget?.depthTexture?.dispose(),this.cloudsTarget?.dispose(),this.cloudsHalfTarget?.dispose(),this.cloudsBlurTarget?.dispose(),this.bloomTarget?.dispose(),this.bloomBrightTarget?.dispose(),this.bloomBlurTarget?.dispose();for(let e of[this.cloudsScene,this.cloudsBlurScene,this.cloudsCompositeScene,this.bloomBrightScene,this.bloomBlurScene,this.bloomCompositeScene]){let t=e?.children[0];t?.geometry?.dispose(),t?.material?.dispose()}this.ownsAssets&&this.assets.dispose(),this.environment.dispose(),this.webgl.dispose()}},bH=12,xH=new U,SH=new G,CH=new G,wH=new G,TH=new G,EH=new W,DH=new G,OH=new G,kH=new Rm,AH=new U;function jH(e,t,n){let r=t*4,i=new Uint8Array(r);for(let t=0;t<Math.floor(n/2);t++){let a=t*r,o=(n-1-t)*r;i.set(e.subarray(a,a+r)),e.copyWithin(a,o,o+r),e.set(i,o)}}async function MH(e){let t=async(t,n)=>{e.onProgress&&(e.onProgress(t,n),await cj())};vV(),(e.gameplay??!0)&&QC();for(let[t,n]of Object.entries(e.behaviors??{}))kt(t,n,{replace:!0});let n=new wa({seed:e.seed,fixedHz:e.fixedHz,...e.settings?{settings:e.settings}:{},...e._scheduler?{scheduler:e._scheduler}:{}}),r=NH(e.scene);if(Tn(r)===`2d`)throw new L(`WRONG_DIMENSION`,`createGame3D was given a 2D scene ('${String(r.name??`scene`)}'). Its nodes are never drawn by the 3D renderer and never simulated by 3D physics — you get a blank canvas. Boot it with createGame2D instead.`);let i=si(NH(r),{resolveScene:e.resolveScene,engine:n});n.setScene(i),await t(.06,`scene`);let a=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&PH(i.root))&&(a=await CM(n)),e.physics!==!1&&(n.physicsProvider=async e=>{n.physics||!PH(e)||(a=await CM(n))}),await t(.1,`physics`);let o=[],s=e.keyboard??(typeof window<`u`?window:!1);s&&n.input.attachKeyboard(s);let c=!1,l=()=>{if(c||e.pointer===!1)return;let t=n.scene?.root;if(!t||e.pointer===void 0&&!IH(t))return;c=!0;let r=typeof e.pointer==`object`?e.pointer.lockOnClick??!0:!0;n.input.attachPointer(e.canvas,{lockOnClick:r})};l(),o.push(n.sceneChanged.connect(()=>l())),o.push(FH(n,i.root,e.canvas)),e.pageGestures||lv(e.canvas);let u=e.touch??`auto`;if(u!==!1){let t=e.touchContainer??e.canvas.parentElement??null;if(t){let r={force:u===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=Zt(n,t,r),a=n.sceneChanged.connect(()=>{i?.dispose(),i=Zt(n,t,r)});o.push(()=>{a(),i?.dispose()})}}let d=ba(n.settings.autoQuality()),f=e._rendererFactory?e._rendererFactory(n,e.canvas):new yH({canvas:e.canvas,engine:n,qualityDefaults:{antialias:d.antialias,pixelRatio:d.pixelRatio},...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.adaptiveResolution===void 0?{}:{adaptiveResolution:e.adaptiveResolution},...e.preserveDrawingBuffer===void 0?{}:{preserveDrawingBuffer:e.preserveDrawingBuffer}});await t(.14,`renderer`);let p=e.debug??!1,m=e.editor??p,h=m===!0?{}:m||null,g={label:`✎ edit this scene`,run:async()=>{if(!h)return;let t=Jv(f),i=h.open??Kv,a=async t=>{let n=await MH({...e,scene:t});h?.onReboot?.(n)};await qv(async()=>{x();try{await i({scene:r,...t?{camera:t}:{},play:a,exit:e=>a(e??r),...h.save?{save:h.save}:{},...h.library?{library:h.library===!0?Bv():h.library}:{}})}catch(e){z(n,`error`,`[incanto] could not open the editor:`,e),await a(r)}},`opening the editor…`)}};if(p){let t=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(t){let{attachDebugOverlay:r}=await Iv(async()=>{let{attachDebugOverlay:e}=await import(`./debug-xpJQqbx1.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(n,{container:t,statsSource:()=>f.stats?.()??{},...f.captureFrame?{frameSource:()=>y()}:{},...h?{actions:[g]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&o.push(()=>i.dispose())}}let _=e.autoStart!==!1;_&&n.start(),await t(.16,`shaders`);try{f.deferFirstCompile?.();let t=globalThis.performance?.now?.()??0;_&&(n.tick(t),n.tick(t+16)),await f.warmUp?.(t=>{e.onProgress?.(.16+t*.82,`shaders`)})}catch{}o.push(n.settings.bindAudio(n.audio)),o.push(n.settings.bindLocale(n.locale));let v=e=>{dj(n,e)};o.push(n.settings.bindQuality(v)),o.push(n.sceneChanged.connect(()=>{v(_a(n.settings.get(`quality`)))})),o.push(n.settings.bindFrameCap(e=>{n.maxFps=e,f.setFrameTarget?.(e||60)})),o.push(n.settings.bindRenderScale(e=>{f.setRenderScale?.(e)}));let y=()=>{let e=f.captureFrame;if(!e)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);return e.call(f)};o.push(...Sv({engine:n,applyDrive:async e=>{let t=0,r=!0,i=()=>{r&&(t+=1,requestAnimationFrame(i))};requestAnimationFrame(i);let a={engine:n,project:(e,t,n)=>{let r=f.screenFromWorld;return r?r.call(f,e,t,n):null},wait:e=>new Promise(t=>setTimeout(t,e))};for(let t of e)await Mv(a,t);return r=!1,t},captureFramePixels:y,rendererStats:()=>f.stats?.(),assetErrors:()=>f.assets?.errors()??[]})),o.push(Yv(n)),await t(1,`ready`);let b=!1;function x(){b||(b=!0,Xv([[`physics`,()=>a?.dispose()],[`app cleanups`,()=>{for(let e of o)e()}],[`engine`,()=>n.dispose()],[`renderer`,()=>f.dispose()]]))}return{engine:n,get scene(){let e=n.scene;if(!e)throw new L(`TREE_VIOLATION`,`game.scene: the engine has no scene.`);return e},sourceJson:r,renderer:f,physics:a,assetErrors(){return[...f.assets?.errors()??[],...cv(n.scene?.tree.root)]},async frame(e){let t=f.captureFrame;if(!t)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);let n=await t.call(f);return _v(n.pixels,n.width,n.height,e)},pick(e,t){return n.picker?.(e,t)??null},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...n.stats(),...f.stats?.()}},openEditor:h?async()=>{b||await g.run()}:null,dispose:x}}function NH(e){try{return structuredClone(e)}catch{throw new L(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function PH(e){if(e instanceof Ib)return!0;for(let t of e.children)if(PH(t))return!0;return!1}function FH(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`){let e=window;r.push({target:e,type:`keydown`}),r.push({target:e,type:`pointerdown`})}if(r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Ua&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}function IH(e){if(e.behavior?.constructor.name===`Clickable`)return!0;for(let t of e.children)if(IH(t))return!0;return!1}var LH=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>Kj,WATER_CUTOUT_MAX:()=>4,WATER_MAX_RIPPLES:()=>8,createGame3D:()=>MH,enablePhysics3D:()=>CM}),RH=500,zH=2e3,BH=new WeakMap,VH=class e{account;roomId;roomState=new N;allUserStates=new N;userJoined=new N;userLeft=new N;globalState=new N;globalMyState=new N;asset=new N;latestUserStates={};latestRoomState={};latestGlobalState={};latestGlobalMyState={};latestAsset={};server;engine;throttleMs;keyframeMs;subs=[];messageSignals=new Map;collectionSignals=new Map;latestCollections=new Map;globalMessageSignals=new Map;globalCollectionSignals=new Map;latestGlobalCollections=new Map;scenes=new Map;lastSent=new Map;reportedDeadKeys=new Set;reportDeadSyncKey(e,t){this.reportedDeadKeys.has(t)||this.aliveMs<RH||(this.reportedDeadKeys.add(t),z(e.tree?.engine??null,`error`,`[incanto] ${e.getPath()}: sync key '${t}' reads as undefined — it is never sent, so remote players never see it change. Check the prop name and the node path.`))}sendAccumulator=0;keyframeAccumulator=0;aliveMs=0;detachReplication=null;lastOwner=null;boundScene=null;declaredRoom=null;reportedUnbound=!1;static get(e){return BH.get(e)??null}static async create(t,n={}){await BH.get(t)?.dispose();let r=n.transport??await KH(n.config,t);if(await r.connect()===!1)throw new L(`NETWORK_UNAVAILABLE`,"The multiplayer transport refused to connect, so this game cannot join a room. Check the server is running and reachable; pass `transport` to use a LocalGameServer or LoopbackTransport instead.");let i=n.room??t.scene?.multiplayer?.room??`auto`,a=new e(t,r,await r.remoteFunction(`joinRoom`,[i===`auto`?void 0:i],{needResponse:!0}),n.throttleMs??50,n.keyframeMs??zH);return BH.set(t,a),a}constructor(e,t,n,r,i){this.engine=e,this.server=t,this.roomId=n,this.account=t.account,this.throttleMs=Math.max(30,r),this.keyframeMs=Math.max(0,i),this.boundScene=e.scene,this.declaredRoom=e.scene?.multiplayer?.room,this.subs.push(t.subscribeRoomState(n,e=>{this.latestRoomState=e,this.roomState.emit(e)}),t.subscribeRoomAllUserStates(n,e=>{this.latestUserStates=e,this.allUserStates.emit(e)}),t.onRoomUserJoin(n,e=>this.userJoined.emit(e)),t.onRoomUserLeave(n,e=>this.userLeft.emit(e))),t.subscribeGlobalState&&this.subs.push(t.subscribeGlobalState(e=>{this.latestGlobalState=e,this.globalState.emit(e)})),t.subscribeGlobalMyState&&this.subs.push(t.subscribeGlobalMyState(e=>{this.latestGlobalMyState=e,this.globalMyState.emit(e)})),t.subscribeAsset&&this.subs.push(t.subscribeAsset(this.account,e=>{this.latestAsset=e,this.asset.emit(e)})),this.detachReplication=e.fixedUpdated.connect(e=>this.replicate(e))}message(e){let t=this.messageSignals.get(e);return t||(t=new N,this.messageSignals.set(e,t),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>t?.emit(e)))),t}collection(e){let t=this.collectionSignals.get(e);return t||(t=new N,this.collectionSignals.set(e,t),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,n=>{this.latestCollections.set(e,n),t?.emit(n)}))),t}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let t=this.globalMessageSignals.get(e);if(!t){t=new N,this.globalMessageSignals.set(e,t);let n=this.server.onGlobalMessage?.(e,e=>t?.emit(e));n&&this.subs.push(n)}return t}globalCollection(e){let t=this.globalCollectionSignals.get(e);if(!t){t=new N,this.globalCollectionSignals.set(e,t);let n=this.server.subscribeGlobalCollection?.(e,n=>{this.latestGlobalCollections.set(e,n),t?.emit(n)});n&&this.subs.push(n)}return t}latestGlobalCollection(e){return this.globalCollection(e),this.latestGlobalCollections.get(e)??{}}setMyState(e){return this.server.remoteFunction(`setMyState`,[this.roomId,e],{throttle:this.throttleMs,throttleKey:`incanto:myState`})}patchRoomState(e){return this.server.remoteFunction(`patchRoomState`,[this.roomId,e])}addEntity(e,t){return this.server.remoteFunction(`addEntity`,[this.roomId,e,t])}updateEntity(e,t,n){return this.server.remoteFunction(`updateEntity`,[this.roomId,e,t,n])}removeEntity(e,t){return this.server.remoteFunction(`removeEntity`,[this.roomId,e,t])}sendEvent(e,t){return this.server.remoteFunction(`sendEvent`,[this.roomId,e,t])}call(e,...t){return this.server.remoteFunction(e,[this.roomId,...t],{needResponse:!0})}registerScene(e,t){this.scenes.set(e,t)}resolveScene(e){let t=this.scenes.get(e);if(!t)throw new L(`UNRESOLVED_INSTANCE`,`No scene registered for '${e}'. Registered: [${[...this.scenes.keys()].join(`, `)}]. Call manager.registerScene('${e}', sceneJson).`);return t}async dispose(){this.detachReplication?.();for(let e of this.subs)e();await this.server.remoteFunction(`leaveRoom`,[this.roomId]),BH.get(this.engine)===this&&BH.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t)return;if(t!==this.boundScene){let e=t.multiplayer?.room;if(e===this.declaredRoom)this.boundScene=t,this.lastOwner=null,this.lastSent.clear();else{this.reportedUnbound||(this.reportedUnbound=!0,z(this.engine,`error`,`[incanto] multiplayer: this client stopped broadcasting — the scene changed to '${t.name}', which declares room ${JSON.stringify(e??null)} and this manager is bound to ${JSON.stringify(this.declaredRoom??null)}. Create a new NetworkManager for the new room (incanto-multiplayer.md).`));return}}this.sendAccumulator+=e*1e3,this.aliveMs+=e*1e3;let n=HH(t.root,!0);if(!n)return;n!==this.lastOwner&&(this.lastOwner=n,this.lastSent.clear());let r=n.network,i=Math.max(30,typeof r.throttleMs==`number`?r.throttleMs:this.throttleMs),a=Array.isArray(r.sync)?r.sync:[],o={},s=!1;for(let e of a){let t=WH(n,e);if(t===void 0){this.reportDeadSyncKey(n,e);continue}o[e]=ot(t),at(this.lastSent.get(e)??null,t)||(s=!0)}this.keyframeAccumulator+=e*1e3;let c=this.keyframeMs>0&&this.keyframeAccumulator>=this.keyframeMs;if(!(this.sendAccumulator<i)&&!(!s&&!c)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,ot(t));this.keyframeAccumulator=0,this.sendAccumulator=0,this.setMyState({sync:o}).catch(e=>{this.engine._asyncFailed(`${n.getPath()}: replication to room '${this.roomId}' failed — this client is no longer visible to the others`,e)})}}};function HH(e,t=!1){let n=[];if(UH(e,n),t&&n.length>1)throw new L(`BAD_FORMAT`,`Multiple network owner nodes found (${n.map(e=>e.getPath()).join(`, `)}). Exactly ONE node per player may declare network.mode 'owner' — replicate spawned entities through collections instead.`);return n[0]??null}function UH(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)UH(n,t)}function WH(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:e.getNodeOrNull(t.slice(0,n))??void 0,i=n===-1?t:t.slice(n+1);if(!r)return;let a=r[i];return a instanceof Set?[...a]:a}function GH(e,t,n,r){for(let[i,a]of Object.entries(t)){let t=i.lastIndexOf(`.`),o=t===-1?e:e.getNodeOrNull(i.slice(0,t)),s=t===-1?i:i.slice(t+1);o?n(o,s,a):r?.(i)}}async function KH(e,t){let{createAgent8Server:n}=await Iv(async()=>{let{createAgent8Server:e}=await import(`./agent8-WXuvhs5H.js`);return{createAgent8Server:e}},[],import.meta.url);return n(e,t)}var qH=new Set([`__id`,`__roomId`,`__updated`,`__leaved`,`account`,`roomId`]),JH=class extends Ht{static typeName=`NetworkSpawner`;static signals=[`spawned`,`despawned`];static props={source:{default:`users`},scene:{default:``,required:!0},interpolate:{default:!0}};source=`users`;scene=``;interpolate=!0;spawned=new Map;positionTargets=new Map;failedKeys=new Set;reported=new Set;waited=0;update(e){let t=this.tree?.engine;if(!t)return;let n=VH.get(t);if(!n){this.waited+=e,this.waited>2&&this.report(`there is no multiplayer in this game`);return}let r=this.currentEntries(n);for(let[e,t]of Object.entries(r)){let r=this.spawned.get(e),i=this.patchOf(t);if(!r){if(this.failedKeys.has(e)||!i)continue;try{let e=n.resolveScene(this.scene);r=Si({...e,root:qi(e.root)},Yi(this)),Xi(r),Zi(r)}catch(t){throw this.failedKeys.add(e),t}r.name=YH(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}i&&GH(r,i,(e,t,n)=>this.setProp(e,t,n),e=>this.report(`'${e}' names a node this scene does not have`))}for(let[e,t]of[...this.spawned.entries()])e in r||(this.spawned.delete(e),this.positionTargets.delete(t),this.emit(`despawned`,t,e),t.free());this.interpolate&&this.stepInterpolation(e)}currentEntries(e){if(this.source===`users`){let t={};for(let[n,r]of Object.entries(e.latestUserStates))n!==e.account&&(t[n]=r);return t}return this.source.startsWith(`collection:`)?e.latestCollection(this.source.slice(11)):{}}patchOf(e){if(e.sync!==void 0)return e.sync;if(this.source===`users`)return;let t={};for(let[n,r]of Object.entries(e))qH.has(n)||n.startsWith(`$`)||(t[n]=r);return Object.keys(t).length>0?t:void 0}report(e){this.reported.has(e)||(this.reported.add(e),z(this.tree?.engine??null,`error`,`[incanto] NetworkSpawner '${this.name}': ${e} — that value replicates to nothing.`))}setProp(e,t,n){if(this.interpolate&&t===`position`&&Array.isArray(n)){this.positionTargets.has(e)||(e.position=[...n]),this.positionTargets.set(e,n);return}if(t===`position`&&Array.isArray(e.position)){this.report(`'position' arrived as ${JSON.stringify(n)} — a node position is a number array`);return}if(t===`groups`){if(Array.isArray(n))for(let t of n)typeof t==`string`&&e.addToGroup(t);return}try{e[t]=n}catch(n){this.reported.has(`prop:${t}`)||(this.reported.add(`prop:${t}`),z(this.tree?.engine,`error`,`[incanto] NetworkSpawner on '${this.getPath()}': replicated key '${t}' cannot be written onto a '${e.constructor.typeName??`Node`}' — it is a readonly accessor, not a prop. Sync a real prop, or a plain data key of your own.`,n))}}replicatedPosition(e){return this.positionTargets.get(e)}stepInterpolation(e){let t=this.tree?.engine?.unscaledDelta||e,n=Math.min(1,t*8);for(let[e,t]of this.positionTargets){let r=e.position;if(!Array.isArray(r)){e.position=[...t];continue}e.position=r.map((e,r)=>e+((t[r]??e)-e)*n)}}};function YH(e){return e.replace(/[/%]/g,`_`)||`remote`}function XH(){No(),R(JH)}function ZH(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}var QH=ZH()?.getItem(`incanto-editor-lang`)??`en`,$H=new Set;function eU(){return QH}function tU(e){QH=e,ZH()?.setItem(`incanto-editor-lang`,e);for(let e of $H)e()}function nU(e){$H.add(e)}function rU(e){return e[QH]}var iU={node:{paths:[`M5 5h14v14H5z`]},move:{paths:[`M12 3v18M3 12h18`,`M8 7l4-4 4 4M8 17l4 4 4-4M7 8l-4 4 4 4M17 8l4 4-4 4`]},image:{paths:[`M4 5h16v14H4z`,`M4 15l5-5 4 4 3-3 4 4`],circles:[[9,9,1.6]]},film:{paths:[`M4 4h16v16H4z`,`M4 9h16M4 15h16`,`M9 4v16M15 4v16`]},video:{paths:[`M3 7h12v10H3z`,`M15 10l6-3v10l-6-3`]},text:{paths:[`M5 7V5h14v2`,`M12 5v14`,`M9 19h6`]},layers:{paths:[`M12 3 3 8l9 5 9-5-9-5z`,`M3 12l9 5 9-5`,`M3 16l9 5 9-5`]},square:{paths:[`M5 5h14v14H5z`,`M5 12h14`]},ball:{paths:[`M12 8v0`],circles:[[12,12,8],[12,12,1.4]]},person:{paths:[`M5 21v-1a7 7 0 0 1 14 0v1`],circles:[[12,7,4]]},area:{paths:[`M5 5h14v14H5z`],dashed:!0},gamepad:{paths:[`M7 9h-0M6 12h4M8 10v4`,`M4 8h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2z`],circles:[[16,11,1],[18.5,13.5,1]]},clock:{paths:[`M12 7v5l3 2`],circles:[[12,12,9]]},cube:{paths:[`M21 16V8l-9-5-9 5v8l9 5 9-5z`,`M3.3 7.5 12 12.5l8.7-5`,`M12 22V12.5`]},sun:{paths:[`M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9 17 7M7 17l-2.1 2.1`],circles:[[12,12,4]]},bulb:{paths:[`M9 18h6M10 21h4`,`M8 13a6 6 0 1 1 8 0c-1 1-1.5 2-1.5 3h-5c0-1-.5-2-1.5-3z`]},spot:{paths:[`M10 3h4l1 4H9z`,`M9 7L4 20h16L15 7`,`M8 15h8`]},globe:{paths:[`M2 12h20`,`M12 2a15 15 0 0 1 0 20a15 15 0 0 1 0-20z`],circles:[[12,12,10]]},link:{paths:[`M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1`,`M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1`]},speaker:{paths:[`M11 5 6 9H3v6h3l5 4V5z`,`M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13`]},swatch:{paths:[`M4 4h16v16H4z`,`M4 4l16 16`]},sparkles:{paths:[`M12 4v5M12 15v5M5 12h5M14 12h5`],circles:[[6,5,1],[18,19,1]]},waves:{paths:[`M2 8c3-3 5 3 8 0s5 3 8 0`,`M2 14c3-3 5 3 8 0s5 3 8 0`,`M2 20c3-3 5 3 8 0s5 3 8 0`]},plant:{paths:[`M12 21v-8`,`M12 13c0-4-3-6-7-6 0 4 3 6 7 6z`,`M12 11c0-4 3-6 7-6 0 4-3 6-7 6z`]},flower:{paths:[`M12 21v-7`],circles:[[12,9,2],[12,4.5,2.2],[16.3,7.5,2.2],[14.7,12.6,2.2],[9.3,12.6,2.2],[7.7,7.5,2.2]]},voxels:{paths:[`M4 14h8v8H4z`,`M12 14h8v8h-8z`,`M8 6h8v8H8z`]}},aU={Node:`node`,Timer:`clock`,AudioPlayer:`speaker`,ColorRect2D:`swatch`,Particles2D:`sparkles`,Particles3D:`sparkles`,Weather3D:`sparkles`,Flock3D:`sparkles`,Water3D:`waves`,UiMinimap:`globe`,UiWaypoint:`move`,Foliage3D:`plant`,Flowers3D:`flower`,VoxelGrid3D:`voxels`,ModelInstance3D:`person`,CharacterController3D:`gamepad`,Ragdoll3D:`person`,Vehicle3D:`move`,Node2D:`move`,Sprite2D:`image`,AnimatedSprite2D:`film`,Camera2D:`video`,Label:`text`,UILayer:`layers`,StaticBody2D:`square`,RigidBody2D:`ball`,CharacterBody2D:`person`,Area2D:`area`,CharacterController2D:`gamepad`,Node3D:`move`,Billboard3D:`layers`,MeshInstance3D:`cube`,LoftMesh3D:`cube`,Camera3D:`video`,DirectionalLight3D:`sun`,OmniLight3D:`bulb`,SpotLight3D:`spot`,StaticBody3D:`square`,RigidBody3D:`ball`,CharacterBody3D:`person`,Area3D:`area`,NetworkSpawner:`globe`};function oU(e){let t=iU[aU[e??``]??(e?`node`:`link`)],n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`width`,`13`),n.setAttribute(`height`,`13`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),t.dashed&&n.setAttribute(`stroke-dasharray`,`3 2.4`);for(let e of t.paths){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,e),n.appendChild(t)}for(let[e,r,i]of t.circles??[]){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);t.setAttribute(`cx`,String(e)),t.setAttribute(`cy`,String(r)),t.setAttribute(`r`,String(i)),n.appendChild(t)}return n}function sU(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`width`,`12`),e.setAttribute(`height`,`12`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2.4`),e.setAttribute(`aria-hidden`,`true`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`d`,`m6 9 6 6 6-6`),e.appendChild(t),e}var cU=[{type:`texture`,label:`image (texture)`,metaHints:[`filter`]},{type:`spritesheet`,label:`spritesheet`,metaHints:[`filter`,`frameWidth`,`frameHeight`]},{type:`model`,label:`3D model (GLB/VRM)`,metaHints:[]},{type:`animation`,label:`animation (GLB clips)`,metaHints:[`clip`]}],lU=new Set,uU=null,dU=null;function fU(e,t,n){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e;let i=()=>{let i=r.value.trim().replace(/\//g,``);i&&i!==e?t(i):n()};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`/`&&e.preventDefault(),e.key===`Enter`&&i(),e.key===`Escape`&&n()});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());return r.addEventListener(`blur`,i),queueMicrotask(()=>{r.focus(),r.select()}),r}function pU(e,t){let n={path:``,name:``,folders:new Map,assets:[]},r=e=>{let t=n;if(e===``)return t;for(let n of e.split(`/`)){let e=t.folders.get(n);e||(e={path:t.path?`${t.path}/${n}`:n,name:n,folders:new Map,assets:[]},t.folders.set(n,e)),t=e}return t};for(let t of e){let e=t.lastIndexOf(`/`);r(e===-1?``:t.slice(0,e)).assets.push(t)}for(let e of t)r(e);return n}function mU(e){let t=e.assets.length;for(let n of e.folders.values())t+=mU(n);return t}function hU(e,t){e.textContent=``;let n=t.working.assets??{},r=Object.keys(n);if(r.length===0&&t.pendingGroups.size===0&&!t.addingAsset&&!t.addingGroup){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no assets yet — + adds textures, models, animations`,e.appendChild(t);return}let i=(e,n)=>{e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.add(`drop-target`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-target`)),e.addEventListener(`drop`,r=>{r.preventDefault(),r.stopPropagation(),e.classList.remove(`drop-target`);let i=r.dataTransfer?.getData(`text/incanto-asset`);i&&t.moveAsset(i,n);let a=r.dataTransfer?.getData(`text/incanto-group`);a&&t.moveGroup(a,n)})};i(e,``);let a=(e,r)=>{let i=n[e],a=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,o=t.assetErrors.get(e),s=document.createElement(`div`);s.className=`tree-row asset-row${t.selectedAsset===e?` selected`:``}${o===void 0?``:` asset-failed`}`,o!==void 0&&(s.title=`failed to load: ${o}`),s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.dataTransfer?.setData(`text/incanto-asset`,e)});let c=document.createElement(`span`);if(c.className=`tree-icon`,c.appendChild(jU(i.type??``)),c.addEventListener(`click`,e=>{e.stopPropagation(),MU(c,i.type??``)}),uU===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;s.appendChild(fU(a,r=>{uU=null,t.renameAssetKey(e,n+r)},()=>{uU=null,t.selectAsset(t.selectedAsset)})),s.draggable=!1,s.insertBefore(c,s.firstChild),r.appendChild(s);return}let l=document.createElement(`span`);l.className=`tree-name asset-key`,l.textContent=`$${a}`,l.title=o===void 0?`$${e}`:`$${e} — failed to load: ${o}`,l.addEventListener(`dblclick`,n=>{n.stopPropagation(),uU=e,t.selectAsset(e)}),s.append(c,l),s.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(s)},o=(e,n)=>{let r=lU.has(e.path),s=document.createElement(`div`);s.className=`asset-folder${r?` collapsed`:``}${t.selectedGroup===e.path?` selected`:``}`,s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.stopPropagation(),t.dataTransfer?.setData(`text/incanto-group`,e.path)});let c=document.createElement(`span`);c.className=`chev`,c.appendChild(sU());let l=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);l.setAttribute(`viewBox`,`0 0 24 24`),l.setAttribute(`width`,`12`),l.setAttribute(`height`,`12`),l.setAttribute(`fill`,`none`),l.setAttribute(`stroke`,`currentColor`),l.setAttribute(`stroke-width`,`1.8`),l.setAttribute(`aria-hidden`,`true`);let u=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);if(u.setAttribute(`d`,`M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`),l.appendChild(u),dU===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,fU(e.name,n=>{dU=null,t.renameGroup(e.path,i+n)},()=>{dU=null,t.selectGroup(t.selectedGroup)})),s.draggable=!1,n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}return}let d=document.createElement(`span`);d.textContent=e.name,d.addEventListener(`dblclick`,n=>{n.stopPropagation(),dU=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${mU(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{lU.has(e.path)?lU.delete(e.path):lU.add(e.path),t.selectGroup(e.path)}),i(s,e.path),n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}},s=pU(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function gU(e,t,n,r){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(IU(t.newGroupParent?`NEW GROUP IN ${t.newGroupParent}/`:`NEW GROUP`));let n=document.createElement(`input`);n.placeholder=t.newGroupParent?`heroes`:`characters (or a/b to nest)`,n.className=`mono`,e.appendChild(EU(`name`,n));let r=document.createElement(`button`);r.type=`button`,r.className=`primary`,r.textContent=`add`;let i=()=>{let e=n.value.trim().replace(/^\/+|\/+$/g,``);e&&(t.cancelAddForms(),t.addGroup(t.newGroupParent?`${t.newGroupParent}/${e}`:e))};r.addEventListener(`click`,i),n.addEventListener(`keydown`,e=>{e.key===`Enter`&&i()});let a=document.createElement(`div`);return a.className=`pop-actions`,a.appendChild(r),e.appendChild(a),setTimeout(()=>n.focus(),0),!0}if(t.addingAsset)return bU(e,t,r);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(IU(`GROUP (${i} asset${i===1?``:`s`})`));let a=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)+1):``,o=r.includes(`/`)?r.slice(r.lastIndexOf(`/`)+1):r;e.appendChild(DU(`name`,o,e=>{let n=e.trim().replace(/\/+/g,``);n&&n!==o&&t.renameGroup(r,a+n)}));let s=document.createElement(`button`);return s.type=`button`,s.className=`ghost danger`,s.textContent=`delete group`,s.addEventListener(`click`,()=>{if(i===0){t.deleteGroup(r);return}n(`'${r}/' contains ${i} asset${i===1?``:`s`} — deleting the group deletes them too.`,`delete group & assets`,()=>t.deleteGroup(r))}),e.appendChild(s),!0}let i=t.selectedAsset;if(i===null)return!1;let a=t.working.assets??{};if(!(i in a))return!1;e.appendChild(IU(`ASSET — ${String(a[i].type??`?`)}`)),e.appendChild(NU(i)),e.appendChild(PU(t,i)),e.appendChild(_U(t,a,i,r));let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost danger`,o.textContent=`delete asset`,o.addEventListener(`click`,()=>{t.selectAsset(null),t.mutate(()=>{delete a[i],Object.keys(a).length===0&&delete t.working.assets})}),e.appendChild(o),!0}function _U(e,t,n,r){let i=t[n],a=document.createElement(`div`);a.className=`asset-editor`;let o=n.includes(`/`)?n.slice(n.lastIndexOf(`/`)+1):n,s=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)+1):``,c=DU(`name`,o,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==o&&e.renameAssetKey(n,s+r)});FU(c.querySelector(`input`)),a.appendChild(c);let l=DU(`url`,String(i.url??``),t=>{e.mutate(()=>{i.url=t.trim()})}),u=l.querySelector(`input`);if(r&&u){let t=SU(String(i.type??``));l.classList.add(`has-lib`),l.appendChild(TU(()=>t,`asset url`,r,t=>{u.value=t,e.mutate(()=>{i.url=t})},()=>wU(t,e,String(i.type??``)),()=>String(i.type??``)||void 0))}a.appendChild(l);let d=e.assetErrors.get(n);if(d!==void 0){let e=document.createElement(`div`);e.className=`conn-warn`,e.textContent=`failed to load — every node using $${n} draws nothing. Check the url: ${d}`,a.appendChild(e)}let f=document.createElement(`div`);f.className=`muted-note`,f.textContent=`meta (key · value)`,a.appendChild(f);for(let[t,n]of Object.entries(i))t===`type`||t===`url`||a.appendChild(vU(e,i,t,n));return a.appendChild(yU(e,i)),a}function vU(e,t,n,r){let i=document.createElement(`div`);i.className=`meta-row`;let a=document.createElement(`input`);a.value=n,a.className=`mono`;let o=document.createElement(`input`);o.value=typeof r==`string`?r:JSON.stringify(r),o.className=`mono`;let s=()=>{let r=a.value.trim();e.mutate(()=>{delete t[n],r&&(t[r]=OU(o.value))})};a.addEventListener(`change`,s),o.addEventListener(`change`,s);let c=document.createElement(`button`);return c.type=`button`,c.className=`linklike danger-link`,c.textContent=`✕`,c.addEventListener(`click`,()=>{e.mutate(()=>{delete t[n]})}),i.append(a,o,c),i}function yU(e,t){let n=document.createElement(`div`);n.className=`meta-row`;let r=document.createElement(`input`);r.placeholder=`filter…`,r.className=`mono`;let i=document.createElement(`input`);i.placeholder=`nearest`,i.className=`mono`;let a=()=>{let n=r.value.trim();!n||i.value.trim()===``||e.mutate(()=>{t[n]=OU(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function bU(e,t,n){return e.appendChild(IU(`NEW ASSET`)),e.appendChild(xU(t,n)),!0}function xU(e,t){let n=document.createElement(`div`);n.className=`asset-editor`;let r=document.createElement(`select`);for(let e of cU){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,r.appendChild(t)}n.appendChild(EU(`type`,r));let i=document.createElement(`input`);i.placeholder=`(optional) characters`,i.className=`mono`,i.value=e.newAssetGroup;let a=`asset-groups-list`;i.setAttribute(`list`,a);let o=document.createElement(`datalist`);o.id=a;let s=new Set;for(let t of Object.keys(e.working.assets??{})){let e=t.lastIndexOf(`/`);e!==-1&&s.add(t.slice(0,e))}for(let t of e.pendingGroups)s.add(t);for(let e of s){let t=document.createElement(`option`);t.value=e,o.appendChild(t)}n.appendChild(EU(`group`,i)),n.appendChild(o);let c=document.createElement(`input`);c.placeholder=`coin`,c.className=`mono`,FU(c),n.appendChild(EU(`key`,c));let l=document.createElement(`input`);l.placeholder=`/textures/coin.png · https://… · data:…`,l.className=`mono`;let u=EU(`url`,l);t&&(u.classList.add(`has-lib`),u.appendChild(TU(()=>SU(r.value),`new asset`,t,e=>{l.value=e,c.value.trim()||(c.value=CU(e))},()=>wU(SU(r.value),e,r.value),()=>r.value||void 0))),n.appendChild(u);let d=document.createElement(`textarea`);d.rows=2,d.placeholder=`or paste a JSON object: { "type": "model", "url": "/m.glb" }`,n.appendChild(d);let f=document.createElement(`button`);f.type=`button`,f.className=`primary`,f.textContent=`add`,f.addEventListener(`click`,()=>{let t=c.value.trim().replace(/^\$/,``);if(!t)return;let n=i.value.trim().replace(/\/+$/,``),a=n?`${n}/${t}`:t,o=null,s=d.value.trim();if(s)try{o=JSON.parse(s)}catch{d.classList.add(`invalid`);return}else l.value.trim()&&(o={type:r.value,url:l.value.trim()});o&&(e.cancelAddForms(),e.selectedAsset=a,e.mutate(()=>{e.working.assets||(e.working.assets={});let t=e.working.assets;t[a]=o}))});let p=document.createElement(`div`);return p.className=`pop-actions`,p.appendChild(f),n.appendChild(p),n}function SU(e){return e===`model`||e===`animation`?`model`:e===`audio`?`audio`:e===`texture`||e===`spritesheet`?`image`:`any`}function CU(e){return((e.split(/[?#]/)[0]??``).split(`/`).pop()??``).replace(/\.[^.]+$/,``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function wU(e,t,n){if(n===`animation`)return[`3d`,`animations`];let r=(t.working.dimension??`2d`)===`3d`;if(e===`image`)return r?[`3d`,`textures`]:[`2d`,`sprite_characters`];if(e===`model`)return[`3d`,`characters`]}function TU(e,t,n,r,i,a){let o=document.createElement(`button`);return o.type=`button`,o.className=`asset-lib`,o.textContent=`📚 library`,o.title=`Browse the agent8 asset library`,o.addEventListener(`click`,o=>{o.preventDefault();let s=i?.(),c=a?.();n({kind:e(),target:t,...s?{shelf:s}:{},...c?{assetType:c}:{}}).then(e=>{e&&r(e)})}),o}function EU(e,t){let n=document.createElement(`label`);n.className=`field`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n}function DU(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),EU(e,r)}function OU(e){let t=e.trim();if(t===`true`)return!0;if(t===`false`)return!1;if(t!==``&&Number.isFinite(Number(t)))return Number(t);if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.parse(t)}catch{return e}return e}var kU={texture:`M3 5h18v14H3z M3 15l5-5 4 4 3-3 6 6 M8.5 9.5h.01`,spritesheet:`M3 4h18v16H3z M9 4v16 M15 4v16 M3 12h18`,model:`M12 2l9 5v10l-9 5-9-5V7z M12 12l9-5 M12 12L3 7 M12 12v10`,animation:`M12 2a10 10 0 1 0 10 10 M22 12l-3-3m3 3l3-3 M12 7v5l3 3`},AU={texture:{en:`image (texture) — Sprite2D.texture references it as "$key".`,ko:`이미지(텍스처) — Sprite2D.texture에서 "$키"로 참조합니다.`},spritesheet:{en:`spritesheet — AnimatedSprite2D slices it into named frame animations.`,ko:`스프라이트시트 — AnimatedSprite2D가 이름 붙은 프레임 애니메이션으로 자릅니다.`},model:{en:`3D model (GLB/glTF/VRM) — ModelInstance3D.model references it as "$key".`,ko:`3D 모델(GLB/glTF/VRM) — ModelInstance3D.model에서 "$키"로 참조합니다.`},animation:{en:`animation clips (GLB, in memory — drawn nowhere) — any model can play them; mixamo retargets onto VRM.`,ko:`애니메이션 클립(GLB, 메모리 전용 — 그려지지 않음) — 어떤 모델이든 재생 가능, mixamo는 VRM에 자동 리타게팅.`}};function jU(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`width`,`13`),t.setAttribute(`height`,`13`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.8`),t.setAttribute(`aria-hidden`,`true`);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return n.setAttribute(`d`,kU[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function MU(e,t){document.querySelector(`.balloon`)?.remove();let n=AU[t];if(!n)return;let r=document.createElement(`div`);r.className=`balloon floating`;let i=document.createElement(`div`);i.className=`balloon-title`,i.textContent=t;let a=document.createElement(`span`);a.textContent=rU(n),r.append(i,a),document.body.appendChild(r);let o=e.getBoundingClientRect();r.style.left=`${o.right+8}px`,r.style.top=`${Math.max(8,o.top-8)}px`;let s=()=>{r.remove(),document.removeEventListener(`pointerdown`,s,!0)};setTimeout(()=>document.addEventListener(`pointerdown`,s,!0),0)}function NU(e){let t=document.createElement(`div`);t.className=`field uid-line`;let n=document.createElement(`span`);n.textContent=`key`;let r=document.createElement(`div`);r.className=`uid-value`;let i=document.createElement(`code`);i.textContent=`$${e}`;let a=document.createElement(`button`);return a.type=`button`,a.className=`uid-copy`,a.title=`Copy key`,a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,a.addEventListener(`click`,()=>{navigator.clipboard?.writeText(`$${e}`),a.classList.add(`copied`),setTimeout(()=>a.classList.remove(`copied`),600)}),r.append(i,a),t.append(n,r),t}function PU(e,t){let n=t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``,r=document.createElement(`select`),i=new Set([``]);for(let t of Object.keys(e.working.assets??{})){let e=t.split(`/`);for(let t=1;t<e.length;t++)i.add(e.slice(0,t).join(`/`))}for(let t of e.pendingGroups)i.add(t);for(let e of[...i].sort()){let t=document.createElement(`option`);t.value=e,t.textContent=e===``?`(root)`:`${e}/`,e===n&&(t.selected=!0),r.appendChild(t)}r.addEventListener(`change`,()=>{e.moveAsset(t,r.value)});let a=document.createElement(`label`);a.className=`field`;let o=document.createElement(`span`);return o.textContent=`group`,a.append(o,r),a}function FU(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function IU(e){let t=document.createElement(`div`);t.className=`section-title`,t.textContent=e;let n=document.createElement(`span`);return n.className=`rule`,t.appendChild(n),t}function LU(e,t){if(e.mode===`project`&&e.hasScene)return{open:`in-hand`};let n=t.filter(e=>e.scene);return n.length===1?{open:`only`,entry:n[0]}:{open:`picker`}}var RU=window.parent!==window,zU=new URLSearchParams(window.location.search).get(`parentOrigin`),BU=!1;function VU(e){if(RU){if(!zU){BU||(BU=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,zU)}}var HU={ready(e,t,n){VU({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){VU({type:`incanto-editor:open`,input:e,output:t})},change(e){VU({type:`incanto-editor:change`,dirty:e})},save(e,t,n){VU({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){VU({type:`incanto-editor:error`,message:e})}},UU=[[`Core`,e=>!e.endsWith(`2D`)&&!e.endsWith(`3D`)&&e!==`Label`&&e!==`UILayer`&&e!==`NetworkSpawner`],[`2D`,e=>e.endsWith(`2D`)&&!/Body|Area|Controller/.test(e)||e===`Label`||e===`UILayer`],[`2D Physics`,e=>e.endsWith(`2D`)&&/Body|Area|Controller/.test(e)],[`3D`,e=>e.endsWith(`3D`)&&!/Body|Area|Controller/.test(e)],[`3D Physics`,e=>e.endsWith(`3D`)&&/Body|Area|Controller/.test(e)],[`Network`,e=>e===`NetworkSpawner`]],WU=[...UU,[`Other`,e=>UU.every(([,t])=>!t(e))]],GU={title:{en:`How Incanto scenes work`,ko:`Incanto 씬은 어떻게 동작하나`},sections:[{heading:{en:`Everything is a node in a tree`,ko:`모든 것은 트리 위의 노드`},text:{en:`A scene is ONE tree of typed nodes (Godot-style). Each node has a name (unique among its siblings), a type that defines its props and behavior, optional children, and an optional scene-wide-unique uid. The whole structure lives in a *.scene.json file — there is no hidden state: what you see in this editor IS the file.`,ko:`씬은 타입을 가진 노드들의 단일 트리입니다(Godot 방식). 각 노드는 이름(형제 간 유일), props와 동작을 결정하는 타입, 선택적 자식들, 그리고 선택적인 씬 전역 유일 uid를 가집니다. 전체 구조가 *.scene.json 파일 하나에 들어있고 숨겨진 상태는 없습니다 — 이 에디터에서 보는 것이 곧 파일 그 자체입니다.`}},{heading:{en:`Props are delta-only`,ko:`Props는 변경분만 기록`},text:{en:`Every prop has a default defined by the engine. The JSON only stores values that DIFFER from the default — so files stay small and diffs stay meaningful. This editor follows the same rule: set a value back to its default and it disappears from the file.`,ko:`모든 prop에는 엔진이 정의한 기본값이 있습니다. JSON에는 기본값과 다른 값만 기록되어 파일이 작고 diff가 의미를 가집니다. 이 에디터도 같은 규칙을 따릅니다 — 값을 기본값으로 되돌리면 파일에서 사라집니다.`}},{heading:{en:`Addressing: paths, names, uid, groups`,ko:`노드 찾기: 경로·이름·uid·그룹`},text:{en:`Code reaches nodes four ways: a path like "Player/Skin" (relative) or "%Unique" (marked-unique name), getNodesByName("Enemy") which returns a LIST (names repeat across the tree), getNodeByUid("n_x1y2") which returns exactly one node and survives moves/renames, and groups — free tags for queries like "every coin".`,ko:`코드는 네 가지 방법으로 노드에 접근합니다: "Player/Skin" 같은 경로(상대) 또는 "%Unique"(유일 표시 이름), 트리 전체에서 같은 이름을 모두 찾는 getNodesByName("Enemy") — 이름은 중복될 수 있어 리스트가 돌아옵니다 —, 정확히 한 노드를 돌려주고 이동/개명에도 살아남는 getNodeByUid("n_x1y2"), 그리고 "모든 코인"처럼 묶어 조회하는 자유 태그 groups.`}},{heading:{en:`Signals connect, behaviors act`,ko:`시그널로 잇고 비헤이비어로 움직인다`},text:{en:`Nodes emit signals (an Area2D fires triggerEnter, a Timer fires timeout). The scene's "connections" wire a signal to a handler — declaratively, in JSON. Game logic itself is a Behavior: a TypeScript class in YOUR game, attached by name via "script". The inspector's CONNECTIONS section shows and edits these links on the selected node — what it emits, what reaches it, and any end that no longer resolves. The handler code itself lives in your game.`,ko:`노드는 시그널을 발산합니다(Area2D의 triggerEnter, Timer의 timeout). 씬의 "connections"가 시그널을 핸들러에 선언적으로(JSON으로) 연결합니다. 게임 로직 자체는 Behavior — 게임 쪽 TypeScript 클래스이며 "script"에 이름으로 연결됩니다. 인스펙터의 CONNECTIONS 섹션이 선택한 노드의 연결을 보여주고 편집합니다 — 나가는 것, 들어오는 것, 그리고 더 이상 찾을 수 없는 끝. 핸들러 코드 자체는 게임에 있습니다.`}},{heading:{en:`Assets are declared, then referenced`,ko:`에셋은 선언하고 $키로 참조`},text:{en:`The scene header declares assets (textures, spritesheets, 3D models, animation clips) under a key; nodes reference them as "$key". Animations are data too: an {type:"animation"} asset loads GLB clips into memory and any ModelInstance3D can play them — Mixamo clips retarget onto VRM avatars automatically.`,ko:`씬 헤더에서 에셋(텍스처·스프라이트시트·3D 모델·애니메이션 클립)을 키로 선언하고, 노드는 "$key"로 참조합니다. 애니메이션도 데이터입니다 — {type:"animation"} 에셋이 GLB 클립을 메모리에 올리고 어떤 ModelInstance3D든 재생할 수 있으며, Mixamo 클립은 VRM 아바타에 자동 리타게팅됩니다.`}}]},Q=(e,t,...n)=>({type:e,summary:t,body:n}),KU=[{id:`core`,label:{en:`Core`,ko:`Core`},intro:{en:`Dimension-free building blocks: plain containers and the game clock. They render nothing themselves.`,ko:`차원과 무관한 기본 블록 — 순수 컨테이너와 게임 시계입니다. 스스로는 아무것도 그리지 않습니다.`},nodes:[Q(`Node`,{en:`A plain container with no transform.`,ko:`변환 없이 자식을 묶는 순수 컨테이너.`},{en:`Use it to group related nodes (all coins, all UI) without affecting their positions. Lifecycle, signals, groups, script — everything works; it just has no visual or spatial meaning of its own.`,ko:`위치에 영향을 주지 않으면서 관련 노드(코인 전부, UI 전부)를 묶을 때 씁니다. 라이프사이클·시그널·그룹·스크립트가 모두 동작하며, 시각적·공간적 의미만 없습니다.`}),Q(`Timer`,{en:"A serializable countdown that emits `timeout`.",ko:"`timeout` 시그널을 쏘는 직렬화 가능한 카운트다운."},{en:`Set waitTime (seconds), optionally autostart or oneShot, and connect its timeout signal to any handler. Because it is a node, the whole timing setup lives in the scene file — agents can read and tune it.`,ko:`waitTime(초)을 정하고 autostart·oneShot을 선택한 뒤 timeout 시그널을 핸들러에 연결하세요. 노드이기 때문에 타이밍 설정 전체가 씬 파일에 남아 에이전트가 읽고 조정할 수 있습니다.`}),Q(`Respawn`,{en:`Catches whatever it hangs off when it leaves the world, and puts it back.`,ko:`부모가 월드 밖으로 떨어지면 붙잡아 원래 자리로 되돌립니다.`},{en:`Make it a child of the player. With no props it catches its parent 50 m under the spawn (1000 px in 2D — the same line incanto-playtest calls "fell"), returns it to where it started and zeroes the velocity the fall built up. below names the line, to names the landing, target picks a different node. It emits respawned, and deliberately does not decide what falling COSTS — wire that to a ScoreKeeper or a Health if it should hurt.`,ko:`플레이어의 자식으로 두세요. 프롭 없이도 스폰 50 m 아래(2D는 1000 px — incanto-playtest가 "fell"로 부르는 그 선)에서 부모를 붙잡아 처음 위치로 되돌리고, 낙하로 쌓인 속도를 0으로 만듭니다. below는 그 선, to는 착지 지점, target은 다른 노드를 지정합니다. respawned 시그널을 쏘며, 추락의 "대가"는 일부러 정하지 않습니다 — 피해를 주려면 ScoreKeeper나 Health에 연결하세요.`}),Q(`HudLayer`,{en:`Screen-space HUD overlay above the canvas — parent for UiText/UiBar/UiBanner.`,ko:`캔버스 위 화면 고정 HUD 오버레이 — UiText/UiBar/UiBanner의 부모.`},{en:`A DOM overlay (position:fixed) that never blocks pointer input. Put UI widgets as children; each picks one of 9 anchors (topLeft…bottomRight). Works identically over 2D and 3D renderers; in headless/tests it is a silent no-op. zIndex lifts it above the canvas.`,ko:`포인터 입력을 가로막지 않는 DOM 오버레이(position:fixed)입니다. UI 위젯을 자식으로 두면 각자 9개 앵커(topLeft…bottomRight) 중 하나에 붙습니다. 2D·3D 렌더러 어디서나 동일하게 동작하고, 헤드리스/테스트에서는 조용히 no-op입니다. zIndex로 캔버스 위에 올립니다.`}),Q(`UiText`,{en:`A HUD text line — score, timers, hints.`,ko:`HUD 텍스트 한 줄 — 점수, 타이머, 힌트.`},{en:`Child of HudLayer. Set text/size/color in JSON; update from behaviors: (getNode('%Score') as UiText).text = String(score). shadow adds a soft outline for readability over any scene.`,ko:`HudLayer의 자식. text/size/color를 JSON으로 정하고, 비헤이비어에서 (getNode('%Score') as UiText).text = String(score) 로 갱신하세요. shadow는 어떤 화면 위에서도 읽히도록 부드러운 그림자를 더합니다.`}),Q(`UiBar`,{en:`A labeled progress bar — health, stamina, reload, boss HP.`,ko:`라벨 달린 진행 바 — 체력, 스태미나, 재장전, 보스 HP.`},{en:`Child of HudLayer. Drive value/max from behaviors; the fill animates and turns lowColor under lowThreshold (default 30%). width/height/color/background style it; label prefixes a small caption.`,ko:`HudLayer의 자식. 비헤이비어에서 value/max를 갱신하면 채움이 애니메이션되고 lowThreshold(기본 30%) 아래로 떨어지면 lowColor로 바뀝니다. width/height/color/background로 스타일, label로 작은 캡션을 붙입니다.`}),Q(`UiBanner`,{en:`Center-screen announcements with fade and a queue — "WAVE 2", "YOU DIED".`,ko:`페이드·큐가 있는 중앙 공지 — "WAVE 2", "YOU DIED".`},{en:`Child of HudLayer. Call show('WAVE 2', { color, seconds }) from behaviors; messages queue and fade in/out. seconds 0 = sticky until the next show(). clear() drops everything. Emits bannerShown(text).`,ko:`HudLayer의 자식. 비헤이비어에서 show('WAVE 2', { color, seconds })를 호출하면 메시지가 큐에 쌓여 페이드 인/아웃됩니다. seconds 0이면 다음 show()까지 고정, clear()로 전부 제거. bannerShown(text) 시그널을 냅니다.`}),Q(`UiButton`,{en:`A clickable HUD button — menus, START screens, dialog choices.`,ko:`클릭 가능한 HUD 버튼 — 메뉴, 시작 화면, 대화 선택지.`},{en:`Child of HudLayer. Set text/size/color/background; disabled greys it out. Emits the 'pressed' signal (behaviors: node.on('pressed', ...)); press() triggers it programmatically (gamepad menus, tests).`,ko:`HudLayer의 자식. text/size/color/background를 설정하고 disabled로 비활성화합니다. 'pressed' 시그널을 내며(비헤이비어에서 node.on('pressed', ...)), press()로 코드에서도 누를 수 있습니다(게임패드 메뉴, 테스트).`}),Q(`UiPanel`,{en:`A box that holds other widgets — the thing a menu, options screen or inventory actually is.`,ko:`다른 위젯을 담는 상자 — 메뉴·설정 화면·인벤토리가 실제로 이것입니다.`},{en:`Child of HudLayer. Widgets under it mount INSIDE it, so tree structure becomes screen structure; panels nest. layout column|row|grid with columns (an inventory is a grid panel, one child per slot), plus gap/padding/background/radius/width/height/border. width or height 0 = size to the contents.`,ko:`HudLayer의 자식. 그 아래 위젯들이 이 안에 마운트되어 트리 구조가 화면 구조가 됩니다(중첩 가능). layout은 column|row|grid이고 columns와 함께 씁니다(인벤토리 = grid 패널, 슬롯당 자식 하나). gap/padding/background/radius/width/height/border 지원. width·height가 0이면 내용에 맞춰집니다.`}),Q(`UiImage`,{en:`A picture in the HUD — item icons, portraits, a logo.`,ko:`HUD 안의 그림 — 아이템 아이콘, 초상화, 로고.`},{en:`src takes a url or a $assetKey (declare the icon once like any other asset). fit contain|cover|fill; tint multiplies through the picture, which is how an unaffordable item greys out in one prop; opacity for disabled states.`,ko:`src는 url 또는 $assetKey(아이콘도 다른 에셋처럼 한 번만 선언). fit은 contain|cover|fill, tint는 그림에 곱해져서 살 수 없는 아이템을 프롭 하나로 회색 처리합니다. opacity로 비활성 표현.`}),Q(`UiSlider`,{en:`A value the player sets — volume, sensitivity, difficulty.`,ko:`플레이어가 조절하는 값 — 볼륨, 감도, 난이도.`},{en:`Emits changed(value). label/value/min/max/step/width/color. Setting .value from a behavior updates the control WITHOUT re-emitting, so restoring a saved setting does not fire the handler that saved it.`,ko:`changed(value) 시그널. label/value/min/max/step/width/color. 비헤이비어에서 .value를 설정하면 컨트롤만 갱신되고 changed는 다시 발생하지 않습니다 — 저장된 설정을 복원할 때 저장 핸들러가 다시 도는 것을 막습니다.`}),Q(`UiToggle`,{en:`An on/off switch — mute, invert-Y, fullscreen.`,ko:`켜기/끄기 스위치 — 음소거, Y축 반전, 전체화면.`},{en:`Emits changed(boolean). label/value. Same no-re-emit rule as UiSlider when set from code.`,ko:`changed(boolean) 시그널. label/value. 코드에서 설정할 때 재발생하지 않는 규칙은 UiSlider와 같습니다.`}),Q(`UiMinimap`,{en:`A minimap — the world around one node, as dots.`,ko:`미니맵 — 한 노드 주변 세계를 점으로.`},{en:`Draws a circle (or square: shape) of radius world units around the node at follow, with a dot per member of every group named in dots (a color each), turned by the node at heading so up is forward, and self as the player's own mark. size in px, dotSize, background. markers() answers headless, so a test can ask what is on the map.`,ko:`follow 노드를 중심으로 radius(월드 단위) 안을 원(또는 shape: square)으로 그리고, dots에 이름 붙인 그룹마다 점(그룹별 색)을 찍으며, heading 노드의 방향으로 지도를 돌려 위쪽이 앞이 되게 하고, self가 플레이어 자신의 표시입니다. size는 px, dotSize, background. markers()는 헤드리스에서도 답하므로 테스트가 지도 위에 무엇이 있는지 물을 수 있습니다.`}),Q(`UiWaypoint`,{en:`An objective marker — a diamond over the target, an arrow at the edge when it is off screen.`,ko:`목표 마커 — 대상 위의 다이아몬드, 화면 밖이면 가장자리의 화살표.`},{en:"Floats over target through the renderer projection (anchor means nothing here). Off screen it slides to the margin rectangle along the line from the centre and turns its arrow that way; behind the camera it is mirrored first, so it points the way to turn. distance shows the metres from `from` (the first player-group node by default); hideWithin hides it when you are that close; arrived fires once when from comes within arriveWithin, and again after leaving and coming back. label, color, size. screen() answers headless from whatever toScreen a test installs.",ko:`target 위에 렌더러 투영으로 떠 있습니다(anchor는 의미 없음). 화면 밖이면 중심에서 잇는 선을 따라 margin 사각형까지 밀려가 화살표가 그쪽을 가리키고, 카메라 뒤에 있으면 먼저 중심 대칭으로 뒤집혀 돌아설 방향을 가리킵니다. distance는 from(기본은 player 그룹의 첫 노드)에서의 미터를 보여주고, hideWithin은 그만큼 가까우면 숨기며, arrived는 from이 arriveWithin 안에 들어올 때 한 번(떠났다 돌아오면 다시) 발생합니다. label, color, size. screen()은 헤드리스에서도 테스트가 설치한 toScreen으로 답합니다.`}),Q(`UiLanguageSelect`,{en:`The language picker, already wired.`,ko:`이미 연결된 언어 선택기.`},{en:`Options are the locales the scene declares in "strings", each labeled with its own endonym. Picking one switches the game live and persists it. English is the base: any key a locale omits falls back to it, on purpose.`,ko:`옵션은 씬의 "strings"가 선언한 로케일이며, 각 언어의 자기 이름으로 표시됩니다. 선택하면 즉시 바뀌고 저장됩니다. 영어가 기준이라 로케일이 빠뜨린 키는 의도적으로 영어로 표시됩니다.`}),Q(`Label3D`,{en:`Text standing in the world — a nameplate, a sign, a damage number.`,ko:`월드에 서 있는 텍스트 — 이름표, 표지판, 데미지 숫자.`},{en:`height is the cap height in METRES and the quad follows what the text measures, so a sign is as wide as its words. Faces the camera by default (a damage number read from behind is a bug) and carries a dark outline so it stays readable over anything. Everything else a sprite knows — anchor, tint, opacity, renderOrder — it inherits. For a damage number: set text, then float it up and fade opacity to 0 and queueFree().`,ko:`height는 글자 높이(미터)이고 가로 폭은 텍스트 실측을 따라갑니다. 기본으로 카메라를 향하며(뒤에서 읽히는 데미지 숫자는 버그니까요) 어두운 외곽선이 있어 어떤 배경에서도 읽힙니다. 앵커·틴트·투명도·renderOrder 등 스프라이트의 나머지 기능은 그대로 상속합니다. 데미지 숫자는 text를 넣고 위로 띄우며 opacity를 0으로 보낸 뒤 queueFree() 하면 됩니다.`}),Q(`UiVolumeSlider`,{en:`A volume slider, already wired to a bus.`,ko:`볼륨 슬라이더 — 버스에 이미 연결되어 있습니다.`},{en:`bus picks which one it owns: master (everything), sfx or music. It writes engine.audio, which persists itself, so nothing needs saving. Left unlabelled it names its own bus. Two of them (music + sfx) is the audio menu most games ship.`,ko:`bus로 어느 볼륨을 맡을지 고릅니다 — master(전체), sfx, music. engine.audio에 쓰면 자동 저장되므로 따로 저장할 게 없습니다. label을 비워두면 버스 이름이 표시됩니다. 대부분의 게임은 music + sfx 두 개면 충분합니다.`}),Q(`UiMuteToggle`,{en:`The mute switch — checked means silent.`,ko:`음소거 스위치 — 체크하면 소리가 꺼집니다.`},{en:`Writes engine.audio.muted and persists with the volumes. Follows a mute made anywhere else, so two menus can never disagree.`,ko:`engine.audio.muted에 쓰고 볼륨과 함께 저장됩니다. 다른 곳에서 음소거해도 따라가므로 두 메뉴가 어긋나지 않습니다.`}),Q(`UiQualitySelect`,{en:`Graphics quality — Low, Medium, High. Already wired.`,ko:`그래픽 품질 — Low, Medium, High. 이미 연결되어 있습니다.`},{en:`Low turns off shadows, bloom, post and clouds; Medium keeps shadows but makes them static and drops post; High is everything. Applies live and persists. Antialiasing follows the tier on the NEXT launch — it is a WebGL context attribute and cannot change while a context exists. Picking records a human choice, so device detection never overrides it later.`,ko:`Low는 그림자·블룸·포스트·구름을 끄고, Medium은 그림자를 정적으로 유지하며 포스트를 끄고, High는 전부 켭니다. 즉시 적용되고 저장됩니다. 안티에일리어싱만 다음 실행부터 반영됩니다(WebGL 컨텍스트 속성이라 생성 후에는 못 바꿉니다). 사람이 고른 값으로 기록되어 이후 자동 감지가 덮어쓰지 않습니다.`}),Q(`UiFrameCapSelect`,{en:`Frame rate cap — 30, 60, 120 or Unlimited.`,ko:`프레임 제한 — 30, 60, 120 또는 무제한.`},{en:`Gates the whole frame, not just the render, so it saves CPU as well as GPU — a cooler phone and a longer battery. Unlimited (0) is the default. Restrict the list with options, e.g. "60,120,0".`,ko:`렌더뿐 아니라 프레임 전체를 제한하므로 GPU와 CPU를 함께 아낍니다 — 발열과 배터리에 유리합니다. 기본값은 무제한(0). options로 목록을 줄일 수 있습니다(예: "60,120,0").`}),Q(`UiRenderScaleSelect`,{en:`Resolution scale — 50%, 75%, 100%.`,ko:`해상도 배율 — 50%, 75%, 100%.`},{en:`The cheapest frames on a weak GPU: at 75% the fragment shaders run over 56% of the pixels for a slightly softer image and nothing else, where dropping a quality tier costs the shadows outright. Multiplies with the engine's automatic resolution governor rather than fighting it.`,ko:`저사양 GPU에서 가장 값싼 프레임: 75%면 픽셀의 약 56%만 셰이딩하므로 이미지가 약간 부드러워질 뿐이지만, 품질 단계를 낮추면 그림자가 통째로 사라집니다. 엔진의 자동 해상도 조절과 충돌하지 않고 곱해집니다.`}),Q(`UiSelect`,{en:`One of several — quality, resolution, language.`,ko:`여러 개 중 하나 — 품질, 해상도, 언어.`},{en:`options is a comma-separated list ("low,medium,high"); value is the current one. Emits changed(value).`,ko:`options는 쉼표로 구분된 목록("low,medium,high"), value가 현재 선택입니다. changed(value) 시그널.`}),Q(`UiDialogue`,{en:`A typewriter dialogue box with a queue and choice buttons — the RPG conversation layer.`,ko:`타자기 효과·큐·선택지 버튼을 갖춘 대화창 — RPG 대화 레이어.`},{en:`Child of HudLayer (anchor bottom by default). say(speaker, text, choices?) queues lines; clicking (or advance()) reveals then advances; choice lines wait for choose(i). Signals: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0 = instant. Check .active to pause player input during conversations.`,ko:`HudLayer의 자식(기본 anchor bottom). say(화자, 텍스트, 선택지?)로 줄을 큐에 넣고, 클릭(또는 advance())이 전체 공개→다음 줄로 진행하며, 선택지 줄은 choose(i)를 기다립니다. 시그널: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0이면 즉시 표시. 대화 중 플레이어 입력을 멈추려면 .active를 확인하세요.`}),Q(`AudioPlayer`,{en:`Plays a sound: zero-asset procedural SFX, BGM loops, or one-shot effects.`,ko:`소리 재생 — 무에셋 절차적 효과음, 배경음 루프, 단발 효과음.`},{en:`Set preset (coin/jump/hurt/explosion/…) for an instant zero-asset SFX (pitch/seed vary it), or leave it "custom" and set src (URL or "$assetKey"). volume 0..1; bus routes through engine.audio (sfx|music) for global volume/mute; loop for music; autoplay starts on ready (browsers may hold it until the first user gesture). Call play()/stop() from game code. Dimension-free — 2D and 3D alike.`,ko:`preset(coin/jump/hurt/explosion/…)을 설정하면 즉시 무에셋 효과음이 납니다(pitch·seed로 변형). 아니면 "custom"으로 두고 src(URL 또는 "$에셋키")를 쓰세요. volume은 0..1, bus는 engine.audio(sfx|music)를 통해 전역 볼륨/음소거에 연결, 음악은 loop, autoplay는 준비되면 재생합니다(브라우저가 첫 입력까지 보류 가능). 게임 코드에서 play()/stop()을 부르세요. 2D·3D 어디서나 동작합니다.`})]},{id:`2d`,label:{en:`2D`,ko:`2D`},intro:{en:`The 2D world is y-down pixels: 1 unit = 1 px, (0,0) top-left, rotation in clockwise degrees. Rendering needs a current Camera2D.`,ko:`2D 세계는 y-아래 픽셀 좌표입니다: 1유닛=1px, (0,0)은 좌상단, 회전은 시계방향 도(degree). 렌더링에는 current 카메라(Camera2D)가 필요합니다.`},nodes:[Q(`Node2D`,{en:`The 2D transform container (position/rotation/scale).`,ko:`2D 변환 컨테이너(position/rotation/scale).`},{en:`Children inherit its transform — move the parent, everything follows. renderOrder orders drawing; visible hides the subtree.`,ko:`자식은 변환을 상속합니다 — 부모를 움직이면 전부 따라옵니다. renderOrder로 그리기 순서를, visible로 서브트리 표시를 제어합니다.`}),Q(`Sprite2D`,{en:`A textured quad.`,ko:`텍스처 사각형(스프라이트).`},{en:`texture is "$assetKey" from the scene assets. anchor [0.5,0.5] centers; flipX/flipY mirror; tint multiplies color; opacity fades. Size comes from the texture × scale.`,ko:`texture는 씬 에셋의 "$키"입니다. anchor [0.5,0.5]면 중앙 기준, flipX/flipY로 반전, tint로 색 곱, opacity로 투명도. 크기는 텍스처 × scale로 정해집니다.`}),Q(`ColorRect2D`,{en:`A flat colored rectangle — no texture needed.`,ko:`단색 사각형 — 텍스처 불필요.`},{en:`size [w,h] px, color, opacity, anchor. Backgrounds, platforms, walls, UI panels, generated-level tiles (maze2d/dungeon2d emit these) — blocky art without any asset.`,ko:`size [w,h] px, color, opacity, anchor. 배경·플랫폼·벽·UI 패널·생성 레벨 타일(maze2d/dungeon2d가 이걸 만듭니다) — 에셋 없이 만드는 블록 그래픽입니다.`}),Q(`TileMap2D`,{en:`A whole tile level as ONE node — grid render + merged static colliders.`,ko:`타일 레벨 전체를 노드 하나로 — 그리드 렌더 + 병합된 정적 콜라이더.`},{en:`Author cells as rows of characters: "." / space = empty, digits 0-9 = atlas tile index, other chars map through legend ({"G": 12}) or colors ({"#": "#3a4356"}), which paints a flat colour and needs no atlas at all — use it to block out a level before the art arrives (exclusive with texture). texture is a "$atlas" asset read left-to-right top-to-bottom in tileSize squares (columns: 0 derives from the texture width). solid becomes static colliders, greedy-merged into a few rectangles, and takes the CHAR you painted as well as a tile index. Cell (0,0) hangs its top-left on the node origin.`,ko:`cells를 문자 행으로 작성합니다: "."/공백 = 빈 칸, 숫자 0-9 = 아틀라스 타일 번호, 그 외 문자는 legend({"G": 12}) 또는 colors({"#": "#3a4356"})로 매핑합니다. colors는 아틀라스 없이 단색 칸을 그려서 아트가 오기 전에 레벨을 잡을 때 씁니다(texture와 동시 사용 불가). texture는 tileSize 정사각형을 좌→우, 상→하로 읽는 "$아틀라스" 에셋입니다(columns: 0이면 텍스처 폭에서 유도). solid는 정적 콜라이더가 되며(타일 번호뿐 아니라 칠한 문자도 받습니다) 소수의 직사각형으로 탐욕 병합됩니다. (0,0) 칸의 좌상단이 노드 원점에 걸립니다.`}),Q(`AnimatedSprite2D`,{en:`Spritesheet animation player.`,ko:`스프라이트시트 애니메이션 플레이어.`},{en:`Point sheet at a "$sheet" asset, define animations as named frame ranges with fps/loop in JSON, set autoplay. Emits animationFinished(name) for one-shot chains.`,ko:`sheet에 "$시트" 에셋을 연결하고, JSON에 fps/loop를 가진 이름별 프레임 구간으로 animations를 정의한 뒤 autoplay를 지정하세요. 단발 애니메이션 연결을 위해 animationFinished(name)를 발산합니다.`}),Q(`Camera2D`,{en:`The 2D view: follow, zoom, limits.`,ko:`2D 시점 — 추적·줌·경계.`},{en:`position is the view CENTER. follow tracks a node path with smoothing (0..1, higher = snappier). limits [minX,minY,maxX,maxY] clamps the view inside a world region. current: true makes it THE camera.`,ko:`position은 화면의 중심입니다. follow가 노드 경로를 smoothing(0..1, 높을수록 빠릿)으로 추적합니다. limits [minX,minY,maxX,maxY]가 시점을 월드 영역 안에 가둡니다. current: true인 카메라가 실제 시점이 됩니다.`}),Q(`Particles2D`,{en:`A 2D particle emitter (fire, sparks, smoke…).`,ko:`2D 파티클 이미터(불·스파크·연기…).`},{en:`Start from a preset (fire/smoke/sparks/…) then override any prop: rate, lifetime/speed ranges, direction + spread, gravity, size/color/alpha start→end, additive blend. burst > 0 with emitting: false makes a one-shot that emits finished. Animates LIVE in this editor.`,ko:`preset(fire/smoke/sparks/…)에서 시작해 어떤 prop이든 덮어쓰세요: rate, lifetime/speed 구간, direction+spread, gravity, size/color/alpha 시작→끝, additive blend. emitting: false에 burst > 0이면 단발 발사 후 finished를 발산합니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Label`,{en:`Text rendered to a quad.`,ko:`텍스트를 그리는 노드.`},{en:`text/fontSize/color/font/align — rendered via CanvasTexture, so any system font string works. Inside a UILayer it pins to the screen (HUD).`,ko:`text/fontSize/color/font/align — CanvasTexture로 그려져 시스템 폰트 문자열을 그대로 쓸 수 있습니다. UILayer 아래에 두면 화면에 고정됩니다(HUD).`}),Q(`UILayer`,{en:`A screen-space subtree (HUD).`,ko:`화면 고정 서브트리(HUD).`},{en:`Everything under it ignores the camera: positions are screen pixels from the top-left. Score counters, prompts, menus go here.`,ko:`이 아래의 모든 것은 카메라를 무시합니다 — 좌상단 기준 화면 픽셀 좌표입니다. 점수, 안내 문구, 메뉴를 여기에 둡니다.`})]},{id:`2d-physics`,label:{en:`2D Physics`,ko:`2D 물리`},intro:{en:`Rapier-backed. Colliders are PROPS ({shape, …}) — the green dashed wireframes in this editor. Physics runs when the game calls enablePhysics2D (and in play mode). Gravity lives on the scene row.`,ko:`Rapier 기반입니다. 콜라이더는 prop({shape, …})이며 에디터의 초록 점선이 그것입니다. 물리는 게임이 enablePhysics2D를 부를 때(그리고 플레이 모드에서) 돌고, 중력은 씬 행에 있습니다.`},nodes:[Q(`StaticBody2D`,{en:`Immovable collision: ground, walls, platforms.`,ko:`움직이지 않는 충돌체 — 바닥·벽·플랫폼.`},{en:`Other bodies collide with it; it never moves. Cheapest body type — use it for all level geometry.`,ko:`다른 바디가 부딪히지만 자신은 절대 움직이지 않습니다. 가장 저렴한 바디 — 레벨 지형 전부에 쓰세요.`}),Q(`RigidBody2D`,{en:`Fully simulated: falls, bounces, pushes.`,ko:`완전 시뮬레이션 — 떨어지고 튕기고 밀립니다.`},{en:`Gravity and collisions drive it. Set linearVelocity to launch. For player characters prefer CharacterBody2D (direct control).`,ko:`중력과 충돌이 움직임을 결정합니다. linearVelocity로 발사하세요. 플레이어 캐릭터에는 직접 제어가 가능한 CharacterBody2D를 권합니다.`}),Q(`CharacterBody2D`,{en:`Kinematic character: you set velocity, it slides.`,ko:`키네마틱 캐릭터 — 속도를 주면 미끄러지듯 이동.`},{en:`moveAndSlide() resolves collisions without physics pushing back; isOnFloor() gates jumps. Sensors (Area2D) do not block it but still fire triggers.`,ko:`moveAndSlide()가 밀려나지 않으면서 충돌을 처리하고 isOnFloor()로 점프를 판정합니다. 센서(Area2D)는 길을 막지 않으면서 트리거를 발사합니다.`}),Q(`Area2D`,{en:`A sensor: overlap triggers, no collision response.`,ko:`센서 — 겹침 감지만, 충돌 반응 없음.`},{en:`Fires triggerEnter(other)/triggerExit(other). Coins, checkpoints, damage zones. Filter with other.isInGroup("player").`,ko:`triggerEnter(other)/triggerExit(other)를 발산합니다. 코인·체크포인트·데미지 존에 쓰고, other.isInGroup("player")로 거릅니다.`}),Q(`CharacterController2D`,{en:`Zero-code platformer/top-down movement.`,ko:`코드 없는 플랫포머/탑다운 이동.`},{en:`Put it UNDER a CharacterBody2D. mode "platformer" (gravity + jump via jumpAction) or "topDown" (free 2-axis). Reads the scene input map actions (moveAction/jumpAction). maxSpeed/jumpHeight are intent-level numbers.`,ko:`CharacterBody2D의 자식으로 두세요. mode는 "platformer"(중력+jumpAction 점프) 또는 "topDown"(자유 2축)이며 씬 입력 맵의 액션(moveAction/jumpAction)을 읽습니다. maxSpeed/jumpHeight는 의도 그대로의 숫자입니다.`}),Q(`Joint2D`,{en:`A physics joint linking its parent body to a target body — weld, hinge, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 힌지, 로프, 스프링.`},{en:`Child of body A (a physics body); "target" is a node path to body B. type: fixed (rigid weld) / revolute (pin at the anchors) / rope (caps anchor distance at length px; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL px offsets.`,ko:`바디 A(물리 바디)의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / revolute(앵커 핀 힌지) / rope(앵커 간 거리를 length px로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 px 오프셋.`})]},{id:`3d`,label:{en:`3D`,ko:`3D`},intro:{en:`Meters, y-up, rotations in degrees. Standard materials need LIGHT — add a DirectionalLight3D or scene ambient, or you get silhouettes.`,ko:`미터 단위, y-위, 회전은 도(degree)입니다. 표준 머티리얼은 빛이 필요합니다 — DirectionalLight3D나 씬 ambient가 없으면 실루엣만 보입니다.`},nodes:[Q(`Node3D`,{en:`The 3D transform container.`,ko:`3D 변환 컨테이너.`},{en:`position [x,y,z] in meters, rotation [x,y,z] in degrees, scale per axis. Children inherit.`,ko:`position [x,y,z] 미터, rotation [x,y,z] 도, scale은 축별. 자식이 상속합니다.`}),Q(`MeshInstance3D`,{en:`A primitive mesh + material.`,ko:`프리미티브 메시 + 머티리얼.`},{en:`mesh: box/sphere/plane/cylinder…, size per primitive, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat} (this editor gives it swatches, sliders, texture-URL fields, and a repeat [u,v] tiling vector). map/normalMap are texture URLs; repeat only takes effect with a map. castShadow/receiveShadow per node.`,ko:`mesh: box/sphere/plane/cylinder…, 프리미티브별 size, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat}(에디터가 스와치·슬라이더·텍스처 URL 입력·repeat [u,v] 타일링 벡터 제공). map/normalMap은 텍스처 URL, repeat는 map이 있을 때만 적용. 그림자는 castShadow/receiveShadow.`}),Q(`LoftMesh3D`,{en:`A smooth swept hull (loft).`,ko:`부드러운 스윕 선체(로프트).`},{en:`sections: ≥2 cross-section stations {z, width, height, y, corner 0..1} interpolated into ONE smooth curved surface — vehicle bodies, glass canopies, boat hulls. slices/smooth control tessellation. Same material as MeshInstance3D minus textures (no UVs); pair clearcoat paint or high-envMapIntensity glass with the smooth normals for the automotive look.`,ko:`sections: 단면 스테이션 {z, width, height, y, corner 0..1} 2개 이상을 보간해 하나의 매끈한 곡면을 만듭니다 — 차체, 유리 캐노피, 선체. slices/smooth로 테셀레이션 조절. material은 MeshInstance3D와 동일하되 텍스처 제외(UV 없음). clearcoat 도장이나 높은 envMapIntensity 유리를 곡면 법선과 조합하면 자동차 룩이 납니다.`}),Q(`ModelInstance3D`,{en:`A GLB/glTF/VRM model file.`,ko:`GLB/glTF/VRM 모델 파일.`},{en:'model: "$assetKey" or URL. targetHeight scales the model to stand N units tall (run `npx incanto-model file.glb` to read its real size first). animation plays an embedded clip name OR an "$animation" asset — Mixamo clips retarget onto VRM humanoids automatically. One node per VRM asset (the avatar runtime mounts live). To make it SOLID, park it under a body with collider {shape:"auto"}: the collider is built from the model\'s own triangles — a triangle mesh on a static body (keeps its holes, so you walk through an archway) and a convex hull on a moving one.',ko:'model은 "$에셋키" 또는 URL입니다. targetHeight가 모델을 N유닛 높이로 맞춥니다(먼저 `npx incanto-model 파일.glb`로 실제 크기를 확인하세요). animation은 내장 클립 이름 또는 "$애니메이션" 에셋을 재생하며, Mixamo 클립은 VRM 휴머노이드에 자동 리타게팅됩니다. VRM 에셋은 노드 하나만 쓸 수 있습니다(아바타 런타임이 라이브로 마운트됨). 단단하게 만들려면 collider {shape:"auto"}인 바디 아래에 두세요 — 모델 자신의 삼각형에서 콜라이더가 만들어집니다(정적 바디는 트라이메시라 아치 구멍도 그대로, 움직이는 바디는 볼록 껍질).'}),Q(`Sprite3D`,{en:`A 2D image as a camera-facing billboard (the 2.5D look).`,ko:`카메라를 향하는 2D 빌보드 스프라이트(2.5D 룩).`},{en:`A textured quad that turns to face the camera inside the 3D world (Octopath / Don't Starve / MapleStory-in-3D). texture is an image URL; size is [w,h] in METERS. billboard: "y" stays upright with a screen-aligned yaw — off-center sprites never roll (characters/props), "full" faces it completely (items/FX), "none" is fixed to the node rotation. anchor [0.5,0] plants the feet on the ground. pixelArt nearest-filters for crisp pixels; alphaTest is a hard cutout that depth-sorts against 3D geometry (a tree occludes it); flipX mirrors left/right; tint/opacity recolor.`,ko:`3D 월드 안에서 카메라를 향해 도는 텍스처 쿼드(Octopath/Don't Starve, 3D 속 메이플스토리 룩). texture는 이미지 URL, size는 [너비,높이] 미터. billboard: "y"는 세로로 선 채 카메라 방향과 정렬된 yaw — 화면 가장자리에서도 기울지 않음(캐릭터/사물), "full"은 완전히 향함(아이템/FX), "none"은 노드 회전에 고정. anchor [0.5,0]은 발을 바닥에 둡니다. pixelArt는 nearest 필터로 픽셀을 또렷하게, alphaTest는 3D 지형과 깊이정렬되는 하드 컷아웃(나무가 가림), flipX는 좌우 반전, tint/opacity로 색·투명도.`}),Q(`AnimatedSprite3D`,{en:`A billboard sprite that plays spritesheet animations.`,ko:`스프라이트시트 애니를 재생하는 빌보드 스프라이트.`},{en:`Everything Sprite3D does, plus frame animation. sheet is a spritesheet image URL whose cells are frameWidth×frameHeight; animations maps a name to {frames, fps, loop} where frames is an inclusive [start,end] range or an explicit list; autoplay starts one on load. Game code calls play("walk") / stop(); a non-looping clip clamps on its last frame and emits animationFinished(name) — chain attack→idle from it.`,ko:`Sprite3D의 모든 기능 + 프레임 애니. sheet는 frameWidth×frameHeight 칸을 가진 스프라이트시트 URL, animations는 이름→{frames, fps, loop}(frames는 포함 [시작,끝] 범위 또는 명시 목록), autoplay는 로드 시 하나를 시작. 게임 코드에서 play("walk")/stop() 호출, 비반복 클립은 마지막 프레임에 머물며 animationFinished(name)를 emit(attack→idle 연결).`}),Q(`Billboard3D`,{en:`A group that turns toward the camera — children follow.`,ko:`카메라를 향해 도는 그룹 — 자식들이 함께 회전.`},{en:`A transform container that orients itself toward the camera every frame; children inherit the rotation, so hang world-space UI under it — HP bars, markers, floating icons (text is a canvas-rendered texture on a child Sprite3D). mode: "screen" (default) copies the camera orientation so a child rectangle stays an upright rectangle anywhere on screen (a yaw-only look-at visibly tilts off-center shapes under a pitched camera); "y" stays upright with a screen-aligned yaw (no off-center roll); "none" turns billboarding off. While billboarding, the node's own rotation prop (and the rotate gizmo) is overwritten every frame — switch to "none" to pose children, then switch back. Unlike Sprite3D (a textured quad that spins only its own image), Billboard3D rotates the whole group.`,ko:`매 프레임 카메라를 향해 자신을 회전시키는 변환 컨테이너로, 자식이 회전을 상속합니다 — HP바·마커·아이콘 같은 월드 UI를 자식으로 붙이세요(텍스트는 캔버스로 그린 텍스처를 자식 Sprite3D에). mode: "screen"(기본)은 카메라 자세를 그대로 복사해 자식 직사각형이 화면 어디서든 똑바른 직사각형으로 보입니다(yaw만 도는 look-at은 기울어진 카메라에서 중앙 밖 도형이 눈에 띄게 비스듬해짐); "y"는 세로로 선 채 카메라로 yaw만; "none"은 빌보드 끔. 빌보드 중에는 노드 자신의 rotation(회전 기즈모 포함)이 매 프레임 덮어써집니다 — 자식을 배치할 땐 "none"으로 바꿨다가 되돌리세요. 자기 그림만 도는 Sprite3D(텍스처 쿼드)와 달리 그룹 전체가 회전합니다.`}),Q(`Camera3D`,{en:`The 3D view.`,ko:`3D 시점.`},{en:`Perspective camera; fov in degrees; current: true selects it. Use the editor's "game cam" (0) to preview exactly what it renders.`,ko:`원근 카메라이며 fov는 도 단위, current: true가 실제 시점이 됩니다. 에디터의 "game cam"(0)으로 정확한 렌더 결과를 미리 보세요.`}),Q(`DirectionalLight3D`,{en:`Sun-like light from a direction.`,ko:`태양광 — 방향에서 평행하게.`},{en:`Position sets the direction toward the origin. intensity/color; pair with scene ambient for soft fill.`,ko:`위치가 원점을 향한 방향을 정합니다. intensity/color를 조절하고 부드러운 채움광은 씬 ambient와 함께 쓰세요.`}),Q(`OmniLight3D`,{en:`A point light radiating everywhere.`,ko:`점광 — 사방으로 퍼지는 빛.`},{en:`Lamps, torches, glows. range limits reach; intensity/color shape the falloff.`,ko:`램프·횃불·발광체. range로 도달 거리를, intensity/color로 감쇠를 만듭니다.`}),Q(`SpotLight3D`,{en:`A cone of light that aims.`,ko:`원뿔광 — 방향을 가진 빛.`},{en:`Flashlights, searchlights, headlights, stage spots. Aims down its −Z like a camera (rotation [-90,0,0] = at the floor). coneDeg is the FULL cone angle, penumbra softens the edge, range limits reach; castShadow makes it a shadow caster (one extra render per frame). lookAt aims it at a node every frame — a searchlight that tracks the player. To sweep, yaw a parent pivot: a yaw on the pitched light itself swings the cone sideways (Euler XYZ).`,ko:`손전등·서치라이트·헤드라이트·무대 조명. 카메라처럼 자신의 −Z를 향합니다(rotation [-90,0,0] = 바닥). coneDeg는 원뿔 전체 각, penumbra는 가장자리 부드러움, range는 도달 거리. castShadow를 켜면 그림자를 드리웁니다(프레임당 렌더 1회 추가). lookAt은 매 프레임 지정한 노드를 겨냥합니다 — 플레이어를 쫓는 서치라이트. 훑으려면 부모 피벗을 yaw 회전하세요: 기울인 조명 자체를 yaw하면 원뿔이 옆으로 돌아갑니다(Euler XYZ).`}),Q(`Particles3D`,{en:`A 3D particle emitter (fire, magic, weather…).`,ko:`3D 파티클 이미터(불·마법·날씨…).`},{en:`The same preset + override model as Particles2D, in meters with [x,y,z] gravity. Camera-facing billboard quads, instanced — hundreds are cheap. Animates LIVE in this editor.`,ko:`Particles2D와 같은 preset+덮어쓰기 모델을 미터 단위와 [x,y,z] 중력으로. 카메라를 향하는 빌보드 쿼드를 인스턴싱해 수백 개도 가볍습니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Weather3D`,{en:`Rain or snow that follows the camera.`,ko:`카메라를 따라다니는 비 또는 눈.`},{en:`A Particles3D preset that stays around the current Camera3D: kind rain|snow, intensity (live — fade a storm in), radius and height of the box it falls in, wind as an [x, z] drift, follow to pin it to a node instead. One instanced emitter, nothing per drop; pair it with a dark sky and fog. Headless it still counts as particles for the framing check.`,ko:`현재 Camera3D 주위에 머무는 Particles3D 프리셋: kind rain|snow, intensity(실시간 — 폭풍을 서서히 키우기), 내리는 상자의 radius와 height, wind는 [x, z] 흐름, follow로 대신 특정 노드에 고정. 인스턴싱된 이미터 하나 값이며 빗방울마다 비용은 없습니다. 어두운 하늘과 안개를 곁들이세요. 헤드리스에서도 프레이밍 검사에는 파티클로 잡힙니다.`}),Q(`Flock3D`,{en:`A flock — gulls, fish, bats — as one instanced mesh that flies itself.`,ko:`떼 — 갈매기·물고기·박쥐 — 스스로 나는 인스턴싱 메시 하나.`},{en:`Boids: each instance steers away from neighbours closer than separation, toward the heading (alignment) and centre (cohesion) of those within sight, turns back inside an ellipsoid radius wide and height tall around this node — or around the node at follow, offset by this position — never faster than turn, always at speed, +z forward. count is live. One draw call, no bodies; seeded from engine.rng; boids() answers headless. Takes no collider.`,ko:`보이드: 각 인스턴스는 separation보다 가까운 이웃에서 멀어지고, sight 안 이웃의 방향(alignment)과 중심(cohesion)으로 향하며, 이 노드(또는 follow 노드에 이 position만큼 오프셋한 곳) 주위 radius 너비·height 높이의 타원체 안으로 되돌아오고, turn보다 빨리 돌지 않으며 항상 speed로 +z 앞을 향해 납니다. count는 실시간. 드로우 콜 하나, 물리 바디 없음, engine.rng로 시드; boids()는 헤드리스에서도 답합니다. collider는 받지 않습니다.`}),Q(`Terrain3D`,{en:`Procedural heightfield terrain with biome texture splatting.`,ko:`바이옴 텍스처 스플래팅이 적용된 절차적 하이트필드 지형.`},{en:`Seeded simplex hills displaced once on the CPU; theme (island/alpine/plains/desert/custom) picks the 4 blended biome textures by height and slope. heightAt(x,z) answers the surface height anywhere. For physics, parent it under a StaticBody3D with collider {shape:'heightfield'}.`,ko:`시드 기반 심플렉스 언덕을 CPU에서 한 번 변위합니다. theme(island/alpine/plains/desert/custom)이 높이·경사로 블렌딩되는 바이옴 텍스처 4장을 고릅니다. heightAt(x,z)로 어디서든 지표 높이를 얻고, 물리는 StaticBody3D 아래에 두고 collider {shape:'heightfield'}를 쓰세요.`}),Q(`Water3D`,{en:`A shader-water surface with splash signals.`,ko:`스플래시 신호를 내는 셰이더 물 표면.`},{en:`size [w,d] meters on XZ. quality 'fancy' (default) = FBM wave shader with a trough/surface/peak ramp (colors), CubeCamera reflections (reflection/reflectionInterval) and opt-in shoreline foam; 'simple' = the cheap sine material (color). Bodies crossing the surface emit entered/exited(body) and raise ripples (interaction). Volumetric gameplay still wants an Area3D. Waves animate LIVE in this editor.`,ko:`XZ 평면에 size [w,d] 미터. quality 'fancy'(기본)는 FBM 파도 셰이더 — trough/surface/peak 램프(colors), CubeCamera 반사(reflection/reflectionInterval), 옵트인 해안 거품(foam). 'simple'은 저사양용 사인파 머티리얼(color). 바디가 수면을 지나면 entered/exited(body) 신호와 물결이 일어납니다(interaction). 부피 기반 게임플레이엔 여전히 Area3D를 쓰세요. 이 에디터에서 파도가 라이브로 움직입니다.`}),Q(`River3D`,{en:`Running water derived from a path and the ground under it.`,ko:`경로와 그 아래 지형에서 유도되는 흐르는 물.`},{en:`Author a centerline path [[x,z],…] plus width/widths (a profile source→mouth) and depth; the node samples the Terrain3D underneath and derives the rest. It CARVES ITS OWN BED by default (carve): a trench per reach that heightAt, the collider, the splat and draped vegetation all see, with a floor that only ever falls, so a path over a rise digs through instead of burying the water. Its surface is then FITTED to that ground — never higher than the lowest rim holding it, ending where the ground comes up to meet it (asymmetric on a sloping reach), lying down as a film where a bank has fallen away, so a river can never hang in the air. Plus a current that speeds up where the channel pinches or tips (flowSpeed is the mean) and whitewater from grade, bank shear and thinning column. Boulders in the channel are answered without wiring: the node finds MeshInstance3D/InstancedMesh3D footprints standing in the water column and the current piles a white cushion on the upstream face, tears a wake downstream and bends its sheen around them. A trench thinner than a terrain cell cannot survive the grid: a 2.4 m creek on a 260 m map wants Terrain3D resolution 256. flowForce drags bodies downstream (drag, never thrust) and sampleAt(x,z) answers where a world point sits in the channel. No extra render passes — a map can carry a dozen.`,ko:`중심선 path [[x,z],…]와 width/widths(상류→하류 프로파일), depth만 주면 나머지는 아래 Terrain3D를 샘플링해 유도합니다. 기본적으로 강이 자기 바닥을 직접 팝니다(carve) — 구간마다 하나씩 도랑을 내고, heightAt·콜라이더·스플랫·식생 드레이프가 모두 그 지형을 봅니다. 파낸 바닥은 계속 내려가기만 하므로 경로가 언덕을 넘어도 물이 묻히지 않고 뚫고 흐릅니다. 그리고 수면은 그 지형에 맞춰집니다 — 자기를 담는 가장 낮은 둑보다 높아질 수 없고, 지면이 올라오는 지점에서 끝나며(비스듬한 구간에서는 좌우 폭이 다릅니다), 둑이 아예 없는 쪽에서는 경사면에 얇은 막처럼 누워버립니다. 그래서 강이 공중에 뜨는 일이 없습니다. 여기에 폭이 좁아지거나 경사가 급해지면 빨라지는 유속(flowSpeed는 평균)과 경사·둑 전단·얕아지는 수심에서 나오는 흰 물살이 더해집니다. 수로에 놓인 바위도 배선 없이 반응합니다 — MeshInstance3D/InstancedMesh3D 중 실제로 물기둥과 겹치는 것을 찾아, 상류면에 흰 물이 쌓이고 하류로 후류가 찢어지며 수면 광택이 바위를 돌아 휩니다. 지형 셀보다 얇은 도랑은 그리드에서 살아남지 못합니다 — 260 m 맵의 2.4 m 개울이라면 Terrain3D resolution 256이 필요합니다. flowForce가 바디를 하류로 끌고(밀지 않고 끌어당김), sampleAt(x,z)로 월드 좌표가 수로 어디에 있는지 알 수 있습니다. 추가 렌더 패스가 없어 한 맵에 여러 개를 둘 수 있습니다.`}),Q(`WaterCutout3D`,{en:`Marks its parent as something that holds the water back — a dry hull, a diving bell, a well.`,ko:`부모 오브젝트가 물을 막는다고 표시 — 마른 선실, 잠수종, 우물.`},{en:`Water is ONE surface and knows nothing about interiors, so an open hull floating on it fills with sea every time a crest clears its floor — freeboard alone can never promise otherwise. This node names the geometry that keeps the water out: it MUST be a CHILD of that thing (a hull, a bell, a dock's well, a cave mouth), and the water re-draws the part of it inside the box into its depth pre-pass, then hides behind it exactly as it hides behind any solid object. Nothing is ever cut OUT of the water, so a hole in open sea is impossible: overshoot the box and more of that hull holds water back, undershoot and water stands in the bow. size is the box extent in meters; enabled toggles it live (a scuttled hull starts letting the sea in). Four per water surface; needs quality fancy.`,ko:`물은 하나의 표면이라 '안쪽'이라는 개념이 없습니다. 그래서 뚜껑 없는 배를 띄우면 파도 마루가 바닥을 넘을 때마다 배 안에 바다가 차 보이고, 건현(freeboard)만으로는 절대 막을 수 없습니다. 이 노드는 '물을 막는 지오메트리'를 지정합니다. 반드시 그 물체(선체·잠수종·부두 우물·동굴 입구)의 자식이어야 하며, 물이 상자 안쪽의 그 지오메트리를 자기 깊이 프리패스에 다시 그린 뒤 평범한 불투명 물체 뒤에 숨듯 그 뒤로 숨습니다. 물에서 무언가를 '도려내지' 않으므로 열린 바다에 구멍이 나는 일은 원리적으로 불가능합니다 — 상자가 크면 그 배가 물을 더 많이 막을 뿐이고, 작으면 뱃머리에 물이 남습니다. size는 미터 단위 상자 크기, enabled는 런타임 토글(침수 시작 연출). 수면 하나당 4개, quality fancy 필요.`}),Q(`Foliage3D`,{en:`An instanced grass/flower carpet that sways.`,ko:`바람에 흔들리는 인스턴스 풀밭/꽃밭. `},{en:`kind grass/flowers/reeds scattered over area [w,d] at density (capped by maxInstances — instanced, tens of thousands of blades cheap). Grass defaults to style 'mesh': every instance is a REAL tapered blade curved by a bezier vertex shader — Voronoi-clump hue/lean, groundColor soil roots (match the terrain), sunDirection tip sheen, 2-octave rolling wind, fadeStart/fadeEnd camera LOD, and (interaction) blade-bending around moving bodies. style 'blades' keeps the 8-SDF-blades-per-quad ported shader, 'simple' the legacy quads. colorA/colorB tint bottom→top, sway sets the wind, seed makes the scatter reproducible. avoidWater (on by default) keeps blades OUT of standing and running water — a creek cutting its bed through the field gets banks, not blades waving in the current; turn it off for reeds and paddy fields.`,ko:`kind grass/flowers/reeds를 area [w,d]에 density로 흩뿌립니다(maxInstances 상한 — 인스턴싱이라 수만 가닥도 가벼움). grass는 기본 style 'mesh': 인스턴스 하나하나가 베지어 버텍스 셰이더로 휘어지는 진짜 잎 메시 — 보로노이 클럼프 색/기울기, groundColor 흙빛 뿌리(지형 색에 맞추세요), sunDirection 잎끝 광택, 2옥타브 굽이치는 바람, fadeStart/fadeEnd 카메라 LOD, (interaction) 움직이는 바디 주변 풀 눕힘까지. style 'blades'는 쿼드당 8가닥 SDF 셰이더, 'simple'은 기존 쿼드 룩. colorA/colorB가 아래→위 색, sway가 바람 세기, seed가 배치를 재현 가능하게 합니다. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 잎을 심지 않습니다 — 개울이 들판을 가르고 지나가면 물살 속에 풀이 서 있는 대신 둑이 생깁니다. 갈대·논은 꺼서 쓰세요.`}),Q(`Flowers3D`,{en:`Instanced flower PLANTS — stems, leaves, multi-petal heads.`,ko:`인스턴스 꽃밭 — 줄기·잎·여러 장 꽃잎의 진짜 꽃 식물.`},{en:`Real procedural flower plants (curved stem, 2-3 leaves, a 5-8 petal head around a contrasting center disc, 1-3 blooms per plant) scattered over area [w,d]. density is the vibe dial: 'lush' / 'sparse' (default) / 'none', or a number in plants/m². varieties picks a subset of daisy/cosmos/bellflower ([] = all three); palette sets the head colors ([] = white/yellow/violet). clustering 0-1 gathers plants into Voronoi patches that bloom one species + color together; sway bobs the heads in a gentle wind; seed makes the field reproducible. ≤3 varieties → ≤6 draw calls. avoidWater (on by default) keeps plants out of standing and running water — a meadow a stream runs through has a bank of flowers, not flowers in the current.`,ko:`진짜 프로시저럴 꽃 식물(휘어진 줄기, 잎 2-3장, 대비되는 중심 원반을 두른 꽃잎 5-8장 머리, 포기당 꽃 1-3송이)을 area [w,d]에 흩뿌립니다. density가 바이브 다이얼: 'lush'(풍성하게) / 'sparse'(듬성듬성, 기본) / 'none'(없게) 또는 m²당 개수. varieties는 daisy/cosmos/bellflower 부분집합([] = 셋 다), palette는 꽃 색([] = 흰/노랑/보라). clustering 0-1이 보로노이 패치로 모아 한 패치가 같은 종·같은 색으로 피고, sway가 바람에 머리를 끄덕이며, seed로 배치가 재현됩니다. 품종 ≤3 → 드로우 콜 ≤6. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 꽃을 심지 않습니다 — 시내가 지나는 들판에는 물살 속 꽃이 아니라 꽃이 핀 둑이 생깁니다.`}),Q(`Tree3D`,{en:`Procedural tree groves — real branching trunks, textured leaves, one node per forest.`,ko:`프로시저럴 나무 숲 — 진짜 가지가 뻗은 줄기와 텍스처 잎, 숲 하나가 노드 하나.`},{en:`type conifer/broadleaf/dead picks the recipe family; tier is the cost dial: simple = primitive low-poly, medium = light forest presets (≤3k tris/tree), high = full ez-tree presets (8–20k, hero trees). count > 1 scatters a forest patch over area [w,d] — up to 3 seed variants, each branches + leaves InstancedMesh (≤6 draw calls); count × tris/tree is budget-checked at load. seed makes every branch and leaf reproducible; height jitters ±20% per instance; leaves sway in a simplex wind.`,ko:`type conifer/broadleaf/dead가 수종을, tier가 비용을 정합니다: simple = 기존 로우폴리, medium = 가벼운 forest 프리셋(나무당 ≤3k tris), high = 풀 ez-tree 프리셋(8–20k, 주인공 나무). count > 1이면 area [w,d]에 숲 패치를 흩뿌립니다 — 시드 변형 최대 3종, 변형마다 가지+잎 InstancedMesh(드로우 콜 ≤6), count × tris는 로드 시 예산 검사. seed로 가지와 잎이 전부 재현되고 height는 인스턴스마다 ±20% 지터링, 잎은 심플렉스 바람에 흔들립니다.`}),Q(`VoxelGrid3D`,{en:`A Minecraft-style block grid in ONE node.`,ko:`마인크래프트식 블록 그리드 — 노드 하나로.`},{en:`voxels is a list of [x,y,z,palette] integer cells (terrain/island generators emit these). Greedy-meshed and instanced — large worlds stay one draw batch. Game code edits blocks via setBlock/getBlock; emits blocksChanged.`,ko:`voxels는 [x,y,z,팔레트] 정수 셀 목록입니다(terrain/island 생성기가 만들어 냅니다). 그리디 메싱+인스턴싱으로 큰 월드도 드로우 배치 하나를 유지합니다. 게임 코드는 setBlock/getBlock으로 수정하고 blocksChanged가 발산됩니다.`})]},{id:`3d-physics`,label:{en:`3D Physics`,ko:`3D 물리`},intro:{en:`Same model as 2D, in meters with y-up gravity ([0,-9.81,0] default). Colliders: box {size}, sphere {radius}, capsule {radius,height}.`,ko:`2D와 같은 모델을 미터·y-위 중력([0,-9.81,0] 기본)으로. 콜라이더는 box {size}, sphere {radius}, capsule {radius,height}.`},nodes:[Q(`StaticBody3D`,{en:`Immovable 3D collision.`,ko:`움직이지 않는 3D 충돌체.`},{en:`Floors, walls, level geometry. collider {shape:"auto"} takes the shape from the MeshInstance3D or ModelInstance3D the body carries as a child, so the blocker can never be bigger or smaller than what the player sees — the fix for hand-typed extents that leave you stopping in mid-air. A GLB becomes a triangle mesh here, holes and all.`,ko:`바닥·벽·레벨 지형. collider {shape:"auto"}는 바디가 자식으로 들고 있는 MeshInstance3D 또는 ModelInstance3D의 생김새를 그대로 씁니다 — 보이는 것보다 크거나 작은 콜라이더가 생길 수 없습니다. 손으로 적은 크기 때문에 허공에서 막히는 문제의 해법입니다. GLB는 여기서 구멍까지 살아있는 트라이메시가 됩니다.`}),Q(`RigidBody3D`,{en:`Simulated 3D body.`,ko:`시뮬레이션되는 3D 바디.`},{en:`Crates, balls, debris — gravity and impacts drive it.`,ko:`상자·공·파편 — 중력과 충격이 움직입니다.`}),Q(`CharacterBody3D`,{en:`Kinematic 3D character.`,ko:`키네마틱 3D 캐릭터.`},{en:`moveAndSlide with up = +y; isOnFloor for jumps.`,ko:`+y를 위로 moveAndSlide, 점프 판정은 isOnFloor.`}),Q(`Area3D`,{en:`3D overlap sensor.`,ko:`3D 겹침 센서.`},{en:`triggerEnter/Exit — pickups, zones, goals.`,ko:`triggerEnter/Exit — 아이템·존·골인 지점.`}),Q(`CharacterController3D`,{en:`Zero-code 3D movement + camera rig.`,ko:`코드 없는 3D 이동 + 카메라 리그.`},{en:`Put it UNDER a CharacterBody3D. view: thirdPerson (orbit + zoom), firstPerson (eyeHeight, mouseLook), sideView or flightView. Reads moveAction/jumpAction/sprintAction from the scene input map; skinPath turns the visual child to face travel. Intent-level numbers: maxSpeed, jumpVelocity, camDistance.`,ko:`CharacterBody3D의 자식으로 두세요. view는 thirdPerson(궤도+줌), firstPerson(eyeHeight, mouseLook), sideView, flightView 중 하나입니다. 씬 입력 맵의 moveAction/jumpAction/sprintAction을 읽고 skinPath의 비주얼 자식을 진행 방향으로 돌립니다. maxSpeed·jumpVelocity·camDistance 같은 의도 수준의 숫자만 만집니다.`}),Q(`Ragdoll3D`,{en:`A ragdoll for a skinned model — the death that falls.`,ko:`스킨 모델의 래그돌 — 쓰러지는 죽음.`},{en:`Idle it is nothing. activate() reads the skeleton at target (Mixamo names, forgiving lookup), builds a capsule RigidBody3D per limb where the bones are — torso, head, upper arms, forearms, thighs, shins — joins each to its parent with a spherical Joint3D, gives them the velocity of the body they fell out of, and drives the bones from the limbs every frame after. Wire it from Health.died; turn the body collider and controller off beside it (and leave freeOnDeath off — the ragdoll drives that model). mass is shared out by limb, damping calms the flailing, lifetime frees it and hands the skeleton back; reset() does that now. Headless, activate(pose) takes bone positions.`,ko:`가만히 있을 땐 아무것도 아닙니다. activate()가 target의 스켈레톤(Mixamo 이름, 관대한 조회)을 읽어 뼈가 있는 자리에 팔다리마다 캡슐 RigidBody3D를 세우고 — 몸통, 머리, 위팔, 아래팔, 허벅지, 정강이 — 각각을 부모에 구형 Joint3D로 잇고, 떨어져 나온 바디의 속도를 물려준 뒤, 매 프레임 팔다리에서 뼈를 움직입니다. Health.died에서 연결하고, 옆에서 바디 콜라이더와 컨트롤러를 끄세요(freeOnDeath는 끄기 — 래그돌이 그 모델을 움직입니다). mass는 팔다리에 나뉘고, damping이 버둥거림을 잦아들게 하며, lifetime이 스스로 해제하고 스켈레톤을 돌려줍니다. reset()은 지금 당장. 헤드리스에선 activate(pose)가 뼈 위치를 받습니다.`}),Q(`BoneLookAt3D`,{en:`Look-at IK for one bone — the head turns toward a target on top of the animation.`,ko:`본 하나의 룩앳 IK — 애니메이션 위에서 머리가 대상을 향해 돌아갑니다.`},{en:`"target" = ModelInstance3D path, "bone" = bone name (default Head), "lookAt" = the node to watch (e.g. "%Player"). Blends in/out smoothly and DISENGAGES beyond maxAngleDeg (no owl necks); weight sets how far it commits. forwardAxis names the bone's facing axis (mixamo heads: +z). Purely visual — headless no-op.`,ko:`"target"에 ModelInstance3D 경로, "bone"에 본 이름(기본 Head), "lookAt"에 바라볼 노드(예: "%Player")를 줍니다. 부드럽게 페이드 인/아웃하고 maxAngleDeg 밖에서는 해제됩니다(목이 돌아가지 않음). weight로 몰입도를 조절하고 forwardAxis는 본의 정면 축입니다(mixamo 머리: +z). 순수 시각 기능 — 헤드리스에서는 no-op.`}),Q(`InstancedMesh3D`,{en:`Hundreds of copies of one mesh in ONE draw call — rocks, posts, crates.`,ko:`메시 하나의 수백 개 복사본을 드로우콜 1개로 — 바위, 말뚝, 상자.`},{en:`Same mesh/size/material surface as MeshInstance3D; "transforms" places the copies — each row [x, y, z, yawDeg?, scale?]. Replace the whole array to update (mutations are not watched). The scattering workhorse for open worlds. collider: {} makes the whole field solid — every row gets its own collider SHAPED LIKE THE MESH (a faceted gem stone collides as that stone's hull, not as a ball tucked inside it), all hanging off one fixed body. A boulder field the player walks straight through is the tell that a world is scenery rather than a place.`,ko:`MeshInstance3D와 같은 mesh/size/material 표면에 "transforms"로 복사본을 배치합니다 — 각 행은 [x, y, z, yawDeg?, scale?]. 갱신은 배열 전체 교체로 하세요(내부 변경은 감지되지 않음). 오픈월드 스캐터링의 주력입니다. collider: {}를 주면 필드 전체가 단단해집니다 — 행마다 메시 생김새 그대로의 콜라이더가 생기고(각진 gem 바위는 안에 박힌 구가 아니라 그 바위 자신의 볼록 껍질로 부딪힙니다), 전부 하나의 고정 바디에 붙습니다. 플레이어가 통과해버리는 바위밭은 그 세계가 배경 그림이라는 신호입니다.`}),Q(`BoneAttachment3D`,{en:`Rides a skeleton bone of an animated model — swords in hands, hats on heads.`,ko:`애니메이션 모델의 스켈레톤 본을 따라다님 — 손에 쥔 검, 머리 위 모자.`},{en:`"target" is a node path to the ModelInstance3D, "bone" the bone name ("RightHand" also matches the Mixamo spellings). Children inherit the live animated transform; this node's own position/rotation become a bone-space offset. Purely visual — headless it stays where its props put it, so keep gameplay checks range-based.`,ko:`"target"에 ModelInstance3D 노드 경로, "bone"에 본 이름을 줍니다("RightHand"는 Mixamo 표기도 자동 매칭). 자식들이 살아있는 애니메이션 트랜스폼을 물려받고, 이 노드의 position/rotation은 본 기준 오프셋이 됩니다. 순수 시각 기능 — 헤드리스에서는 prop 위치에 머무니 게임 판정은 거리 기반으로 유지하세요.`}),Q(`Trail3D`,{en:`A fading world-space ribbon behind the parent — wingtip trails, sword arcs, tyre streaks.`,ko:`부모 뒤로 남는 페이드아웃 월드 리본 — 날개끝 궤적, 검격 궤적, 타이어 자국.`},{en:"Child of the moving node. Records the world position over `seconds` and renders a camera-facing strip that tapers and fades to the tail. width (m), color, opacity, additive for glowing energy trails, minDistance filters jitter. emitting: false stops laying new ribbon while the old tail fades out.",ko:`움직이는 노드의 자식으로 두세요. seconds 동안의 월드 위치를 기록해 꼬리로 갈수록 가늘어지고 투명해지는 카메라 지향 스트립을 그립니다. width(m), color, opacity, 빛나는 에너지 궤적에는 additive, minDistance로 떨림을 걸러냅니다. emitting: false면 새 리본만 멈추고 기존 꼬리는 자연스럽게 사라집니다.`}),Q(`Joint3D`,{en:`A physics joint linking its parent body to a target body — weld, ball joint, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 볼 조인트, 로프, 스프링.`},{en:`Child of body A; "target" is a node path to body B. type: fixed (rigid weld) / spherical (ball joint at the anchors) / revolute (a HINGE about axis — a door, a wheel, a lever — with limits [minDeg, maxDeg] and a motorSpeed in deg/s; angle reads it back) / prismatic (a SLIDE along axis — a portcullis, an elevator — with limits in metres and a motorSpeed in m/s; travel reads it back) / rope (caps anchor distance at length m; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL meter offsets.`,ko:`바디 A의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / spherical(앵커 볼 조인트) / revolute(axis를 축으로 도는 경첩 — 문, 바퀴, 레버; limits [minDeg, maxDeg]와 motorSpeed deg/s, angle로 읽음) / prismatic(axis를 따라 미끄러지는 슬라이드 — 내리닫이문, 엘리베이터; limits 미터, motorSpeed m/s, travel로 읽음) / rope(앵커 간 거리를 length m로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 미터 오프셋.`}),Q(`Vehicle3D`,{en:`A car in one node — wheels on springs, throttle, steering, brake.`,ko:`노드 하나로 자동차 — 스프링 위 바퀴, 가속, 조향, 브레이크.`},{en:`Goes UNDER a dynamic RigidBody3D chassis (a hard error anywhere else). wheels lists each wheel: position in the chassis frame, radius, rest (spring length), steer and drive flags. Reads moveAction (y = throttle, x = steer) and brakeAction every step; engineForce, brakeForce, maxSteerDeg, the suspension stiffness/compression/relaxation, maxTravel, friction and sideFriction are the feel. Forward is +z, like a character. Children named Wheel0…N and their Hub are posed for you (steer and roll), so a tyre mesh under a Hub just works; speed and wheel(i) read back. Zones (Area3D) are driven through, never onto.`,ko:`동적 RigidBody3D 차체 아래에 둡니다(다른 곳이면 하드 에러). wheels에 바퀴마다 차체 기준 position, radius, rest(스프링 길이), steer·drive 플래그를 적습니다. 매 스텝 moveAction(y = 가속, x = 조향)과 brakeAction을 읽고, engineForce·brakeForce·maxSteerDeg·서스펜션 stiffness/compression/relaxation·maxTravel·friction·sideFriction이 감각을 정합니다. 앞은 캐릭터처럼 +z. Wheel0…N 자식과 그 Hub는 자동으로 자세가 잡히므로(조향·회전) Hub 아래 타이어 메시가 그대로 돕니다. speed와 wheel(i)로 읽어옵니다. 구역(Area3D)은 위로 올라타지 않고 통과합니다.`})]},{id:`network`,label:{en:`Network`,ko:`네트워크`},intro:{en:`Multiplayer is transport-agnostic: the engine speaks one NetworkTransport interface (built-in offline Loopback + an @agent8/gameserver adapter). The scene declares replication; one owner node per player broadcasts its sync keys.`,ko:`멀티플레이어는 트랜스포트 불가지론입니다 — 엔진은 NetworkTransport 인터페이스 하나만 사용합니다(내장 오프라인 Loopback + @agent8/gameserver 어댑터). 복제는 씬이 선언하며, 플레이어당 하나의 owner 노드가 sync 키를 송출합니다.`},nodes:[Q(`NetworkSpawner`,{en:`Spawns a registered scene per remote player/entity.`,ko:`원격 플레이어/엔티티마다 등록된 씬을 생성.`},{en:`source "users" mirrors every OTHER account in the room (self skipped); "collection:<id>" mirrors a room collection. Replicated sync patches apply to each instance; position interpolates. Emits spawned/despawned.`,ko:`source "users"는 방의 다른 모든 계정을 미러링하고(자신 제외) "collection:<id>"는 방 컬렉션을 미러링합니다. 복제 sync 패치가 인스턴스에 적용되고 position은 보간됩니다. spawned/despawned를 발산합니다.`})]}],qU=`overview`,JU=null;function YU(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),QU()}function XU(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function ZU(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&XU()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,XU))}function QU(){let e=document.querySelector(`#docs-tabs`),t=document.querySelector(`#docs-body`);if(!e||!t)return;e.textContent=``;let n=(t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`docs-tab${qU===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{qU=t,JU=null,QU()}),e.appendChild(r)};n(`overview`,rU({en:`Overview`,ko:`개요`}));for(let e of KU)n(e.id,rU(e.label));if(t.textContent=``,qU===`overview`){$U(t);return}let r=KU.find(e=>e.id===qU);r&&eW(t,r)}function $U(e){let t=document.createElement(`h2`);t.textContent=rU(GU.title),e.appendChild(t);for(let t of GU.sections){let n=document.createElement(`h3`);n.textContent=rU(t.heading);let r=document.createElement(`p`);r.textContent=rU(t.text),e.append(n,r)}}function eW(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=rU(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${JU===n.type?` open`:``}`;let r=document.createElement(`button`);r.type=`button`,r.className=`docs-node-head`;let i=document.createElement(`span`);i.className=`tree-icon`,i.appendChild(oU(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=rU(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{JU=JU===n.type?null:n.type,QU()}),t.appendChild(r),JU===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=rU(t),e.appendChild(n)}e.appendChild(tW(n.type)),t.appendChild(e)}e.appendChild(t)}}function tW(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[rU({en:`prop`,ko:`prop`}),rU({en:`default`,ko:`기본값`})]){let t=document.createElement(`th`);t.textContent=e,n.appendChild(t)}t.appendChild(n);try{let n=ht(e);for(let[e,r]of Object.entries(n)){let n=document.createElement(`tr`),i=document.createElement(`td`);i.className=`mono`,i.textContent=e;let a=document.createElement(`td`);a.className=`mono`,a.textContent=JSON.stringify(r.default),n.append(i,a),t.appendChild(n)}}catch{}return t}function $(e){return Math.round(e*100)/100}function nW(e,t,n,r,i){return{name:e,type:`StaticBody3D`,props:{collider:{shape:`box`,size:t},position:n,...i?{rotation:i}:{}},children:[{name:`Skin`,type:`MeshInstance3D`,props:{mesh:`box`,size:t,...r}}]}}function rW(e,t,n,r,i,a){let o=$(r.range(i[0],i[1])),s=$(r.range(.5,.7));return{name:`Rock${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[t,$(o*s*.6),n],snapToGround:!1,rotation:[0,r.int(0,359),0],scale:[o,$(o*s),$(o*r.range(.8,1.1))],material:{color:a??iW(r),roughness:1},castShadow:!0}}}function iW(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function aW(e){return[{name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(e*.8),$(e*1.5),$(e*.6)],intensity:1,castShadow:!0,shadowArea:$(e*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-e*.8),$(e*.8),$(-e*.6)],intensity:.4,color:`#b9d4ff`}}]}function oW(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function sW(e,t,n){return Math.min(Math.max(e,t),n)}var cW=[`boxes`,`ruins`,`garden`],lW=.5,uW=.1,dW=2,fW={boxes:{floor:`#3f3f3f`,wall:`#55504a`,obstacles:[`#b0413e`,`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#878787`]},ruins:{floor:`#7d766b`,wall:`#8a8378`,obstacles:[`#8a8378`,`#979085`,`#a39a8d`,`#7b746a`]},garden:{floor:`#4d7c3a`,wall:`#2f6b2f`,obstacles:[`#2f6b2f`,`#3a7a38`,`#356e33`]}};function pW(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!cW.includes(o))throw new L(`BAD_FORMAT`,`generateArena theme must be one of [${cW.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...cW]});let s=fW[o],c=new Ee(t),l=[nW(`Floor`,[n,uW,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+lW*2,i,lW],f=[lW,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(nW(`Wall1`,d,[0,u,-(r+lW)/2],p),nW(`Wall2`,d,[0,u,(r+lW)/2],p),nW(`Wall3`,f,[-(n+lW)/2,u,0],p),nW(`Wall4`,f,[(n+lW)/2,u,0],p)),o===`ruins`?l.push(...hW(c,s,n,r,i,a)):l.push(...mW(c,s,n,r,i,a,o)),o===`garden`&&l.push(...gW(c,n,r));let m=Math.max(n,r);return l.push({name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(m*.8),$(m*1.5),$(m*.6)],intensity:1,castShadow:!0,shadowArea:$(m*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-m*.8),$(m*.8),$(-m*.6)],intensity:.4,color:`#b9d4ff`}},{name:`Lamp`,type:`OmniLight3D`,props:{position:[0,$(i+2),0],intensity:.5,color:`#fff3d6`,range:$(m)}}),{name:`Arena`,type:`Node3D`,children:l}}function mW(e,t,n,r,i,a,o){let s=[],c=o===`garden`?Math.min(n,r)*.16:0;for(let o=1;o<=a;o++){let a=[$(e.range(.8,2.6)),$(e.range(.8,Math.max(1.2,i*.8))),$(e.range(.8,2.6))],l=$(e.range(-(n/2-dW),n/2-dW)),u=$(e.range(-(r/2-dW),r/2-dW));if(c>0&&Math.hypot(l,u)<c+1.5){let t=Math.max(Math.hypot(l,u),.001);l=$(l/t*(c+1.5+e.range(0,2))),u=$(u/t*(c+1.5+e.range(0,2)))}let d=e.int(0,359);s.push(nW(`Obstacle${o}`,a,[l,$(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function hW(e,t,n,r,i,a){let o=[];if(a<=0)return o;let s=Math.max(1,Math.round(Math.sqrt(a/2))),c=Math.ceil(a/s),l=n-dW*2,u=r-dW*2,d=0;for(let n=0;n<s&&d<a;n++){let r=$(s===1?0:-u/2+n/(s-1)*u);for(let n=0;n<c&&d<a;n++){d++;let a=$((c===1?0:-l/2+n/(c-1)*l)+e.range(-.4,.4)),s=$(e.next()>.35?e.range(i*.7,i*1.2):e.range(.4,.9)),u=$(e.range(.8,1.2));o.push(nW(`Obstacle${d}`,[u,s,u],[a,$(s/2),$(r+e.range(-.4,.4))],{material:{color:e.pick(t.obstacles),roughness:.95},castShadow:!0},[0,e.int(-8,8),0]))}}return o}function gW(e,t,n){let r=[],i=Math.min(t,n)*.16,a=r=>{let a=Math.min(t,n)/2-r/2-1,o=$(e.range(-a,a)),s=$(e.range(-a,a)),c=Math.max(Math.hypot(o,s),.001);return c<i+r/2&&(o=$(o/c*(i+r/2+.5)),s=$(s/c*(i+r/2+.5))),[o,s]};for(let i=1;i<=3;i++){let o=$(Math.min(t,n)*e.range(.18,.26)),[s,c]=a(o);r.push({name:`Grass${i}`,type:`Foliage3D`,props:{kind:`grass`,area:[o,o],density:10,seed:e.int(1,1e9),position:[s,0,c]}})}for(let i=1;i<=2;i++){let o=$(Math.min(t,n)*e.range(.12,.18)),[s,c]=a(o);r.push({name:`FlowerBed${i}`,type:`Flowers3D`,props:{density:`lush`,clustering:.3,area:[o,o],seed:e.int(1,1e9),position:[s,0,c]}})}return r.push({name:`Pool`,type:`Water3D`,props:{size:[$(i*2),$(i*2)],position:[0,.3,0],waveHeight:.04}}),r}var _W=32,vW=[4,8],yW=`#332f3a`,bW=`#6b6357`;function xW(e){let{seed:t,rooms:n=5}=e,[r,i]=oW(e.size,[960,720]),a=Math.max(8,Math.floor(r/_W)),o=Math.max(8,Math.floor(i/_W)),s=new Ee(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(vW[0],vW[1]),t=s.int(vW[0],vW[1]),n={x:s.int(1,Math.max(1,a-e-1)),y:s.int(1,Math.max(1,o-t-1)),w:e,h:t};c.some(e=>SW(e,n,1))||c.push(n)}let l=new Set,u=e=>{for(let t=e.y;t<e.y+e.h;t++)for(let n=e.x;n<e.x+e.w;n++)l.add(`${n},${t}`)};for(let e of c)u(e);let d=[];for(let e=1;e<c.length;e++){let[t,n]=CW(c[e-1]),[r,i]=CW(c[e]),a={x:Math.min(t,r),y:n,w:Math.abs(t-r)+1,h:1},o={x:r,y:Math.min(n,i),w:1,h:Math.abs(n-i)+1};for(let[t,n]of[[`H`,a],[`V`,o]])u(n),(n.w>1||n.h>1)&&d.push({name:`Corridor${e}${t}`,rect:n})}let f=new Set;for(let e of l){let[t,n]=e.split(`,`).map(Number);for(let e=-1;e<=1;e++)for(let r=-1;r<=1;r++){let i=`${t+r},${n+e}`;l.has(i)||f.add(i)}}let p=-(a*_W)/2,m=-(o*_W)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*_W,m+(t.y+t.h/2)*_W],size:[t.w*_W,t.h*_W],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,yW));for(let e of d)g.push(h(e.name,e.rect,yW));let _=0;for(let e=-1;e<=o;e++){let t=-1;for(;t<=a;){if(!f.has(`${t},${e}`)){t++;continue}let n=1;for(;t+n<=a&&f.has(`${t+n},${e}`);)n++;_++;let r=[n*_W,_W];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*_W,m+(e+.5)*_W],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:bW}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function SW(e,t,n){return e.x-n<t.x+t.w&&e.x+e.w+n>t.x&&e.y-n<t.y+t.h&&e.y+e.h+n>t.y}function CW(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var wW=[[0,-1],[1,0],[0,1],[-1,0]];function TW(e,t,n){let r=2*t+1,i=2*n+1,a=Array.from({length:i},()=>Array(r).fill(!1)),o=(e,t)=>{a[t][e]=!0};o(1,1);let s=new Set([`0,0`]),c=[[0,0]];for(;c.length>0;){let[r,i]=c[c.length-1],a=[];for(let[e,o]of wW){let c=r+e,l=i+o;c>=0&&c<t&&l>=0&&l<n&&!s.has(`${c},${l}`)&&a.push([c,l])}if(a.length===0){c.pop();continue}let[l,u]=e.pick(a);s.add(`${l},${u}`),o(2*l+1,2*u+1),o(r+l+1,i+u+1),c.push([l,u])}return o(0,1),o(2*t,2*n-1),{cols:t,rows:n,cells:a}}var EW=[`stone`,`hedge`,`canyon`],DW=.1,OW=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,kW=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,AW={stone:{wall:{color:`#e8e2d8`,map:`${OW}/blocks.png`,normalMap:`${OW}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${kW}/stone.png`,normalMap:`${kW}/stone_normal.png`,tile:3,roughness:1},cap:`#6b5848`,pillar:`#cfc8bb`,path:`#665f55`,sun:{color:`#c9d6ea`,intensity:.75,height:.5},fill:`#9fb4cc`,mood:{sky:{elevationDeg:10,azimuthDeg:150,turbidity:16,rayleigh:3.2},fog:{near:.5,far:3.5,color:`#86909c`},exposure:.82,ambient:{color:`#c9d4e2`,intensity:.12}}},hedge:{wall:{color:`#55a83e`,map:`${kW}/grass.png`,normalMap:`${kW}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${kW}/grass.png`,normalMap:`${kW}/grass_normal.png`,tile:3,roughness:1},pillar:`#3d7531`,path:`#7d6845`,sun:{color:`#e9eee6`,intensity:.7,height:1},fill:`#b9c8b4`,mood:{sky:{elevationDeg:35,azimuthDeg:150,turbidity:18,rayleigh:4.2},fog:{near:.8,far:5,color:`#aab8a6`},exposure:.88,ambient:{color:`#dde5d8`,intensity:.15}}},canyon:{wall:{color:`#f0b070`,map:`${kW}/stone.png`,normalMap:`${kW}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${kW}/sand.png`,normalMap:`${kW}/sand_normal.png`,tile:3.5,roughness:1},pillar:`#d8a868`,path:`#a98a58`,sun:{color:`#ffb572`,intensity:1.15,height:.35},fill:`#caa37e`,mood:{sky:{elevationDeg:9,azimuthDeg:230,turbidity:9,rayleigh:3.5},fog:{near:.7,far:4.5,color:`#c79c6e`},exposure:.92,ambient:{color:`#ffdcb6`,intensity:.13}}}};function jW(e,t,n){return{color:e.color,roughness:e.roughness,map:e.map,...e.normalMap?{normalMap:e.normalMap}:{},repeat:[$(t/e.tile),$(n/e.tile)]}}var MW=10;function NW(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!EW.includes(o))throw new L(`BAD_FORMAT`,`generateMaze theme must be one of [${EW.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...EW]});let s=AW[o],c=new Ee(t),l=TW(c,n,r),u=2*n+1,d=2*r+1,f=$(u*i),p=$(d*i),m=(e,t)=>[$((e+.5)*i-f/2),$((t+.5)*i-p/2)],h=[nW(`Floor`,[f,DW,p],[0,-.1/2,0],{material:jW(s.floor,f,p),receiveShadow:!0})],g=[],_=0;for(let e=0;e<d;e++){let t=0;for(;t<u;){if(l.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<u&&!l.cells[e]?.[t+n];)n++;g.push({gx:t,gz:e,run:n}),_++;let r=$(n*i);h.push(nW(`Wall${_}`,[r,a,i],[$((t+n/2)*i-f/2),$(a/2),$((e+.5)*i-p/2)],{material:jW(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...PW(g,i,a,f,p,s.cap)),h.push(...FW(c,l,i,a,m,s)),o===`hedge`?(h.push(...zW(c,g,i,a,m)),h.push(...BW(c,l,i,m,n,r))):o===`canyon`&&h.push(...VW(c,g,i,a,m)),h.push(...LW(l,i,a,m,s)),h.push(...aW(Math.max(f,p)).map((e,t)=>{if(t!==0)return{...e,props:{...e.props,color:s.fill}};let n=e.props?.position;return{...e,props:{...e.props,color:s.sun.color,intensity:s.sun.intensity,position:[n[0]??0,$((n[1]??0)*s.sun.height),n[2]??0]}}})),{name:`Maze`,type:`Node3D`,children:h}}function PW(e,t,n,r,i,a){return e.map((e,o)=>({name:`Cap${o+1}`,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(e.run*t+.16),.12,$(t+.16)],position:[$((e.gx+e.run/2)*t-r/2),$(n+.06),$((e.gz+.5)*t-i/2)],material:{color:a,roughness:1},castShadow:!0,receiveShadow:!0}}))}function FW(e,t,n,r,i,a){let o=[],s=(e,n)=>t.cells[n]?.[e]===!1;for(let e=2;e<t.cells.length-1;e+=2)for(let n=2;n<(t.cells[e]?.length??0)-1;n+=2)s(n,e)&&Number(s(n-1,e))+Number(s(n+1,e))+Number(s(n,e-1))+Number(s(n,e+1))>=3&&o.push([n,e]);let c=Math.min(MW,o.length),l=[],u=new Set,d=$(n*1.2),f=$(r*1.12);for(let t=1;t<=c;t++){let n=e.int(0,o.length-1);for(;u.has(n);)n=(n+1)%o.length;u.add(n);let[r,s]=o[n],[c,p]=i(r,s);l.push(IW(`Pillar${t}`,c,p,d,f,a))}return l}function IW(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,$(i/2),n],material:{...jW(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function LW(e,t,n,r,i){let a=2*e.cols,o=2*e.rows-1,s=$(t*1.1),c=$(n*1.25),l=[[0,0],[0,2],[a,o-1],[a,o+1]].map(([e,t],n)=>{let[a,o]=r(e,t);return IW(`Gate${n+1}`,a,o,s,c,i)});for(let[e,n,s]of[[`EntrancePath`,0,1],[`ExitPath`,a,o]]){let[a,o]=r(n,s);l.push({name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(t*.96),.04,$(t*.96)],position:[a,.02,o],material:{...jW(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var RW=10;function zW(e,t,n,r,i){return[...t].filter(e=>e.run>=2).sort((e,t)=>t.run-e.run||e.gz-t.gz||e.gx-t.gx).slice(0,RW).map((t,a)=>{let[,o]=i(t.gx,t.gz),[s]=i(t.gx,t.gz),[c]=i(t.gx+t.run-1,t.gz);return{name:`HedgeTop${a+1}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[$(t.run*n*.92),$(n*.7)],density:14,height:.35,sway:.4,colorA:`#2f5e26`,colorB:`#5d8a3c`,seed:e.int(1,1e9),position:[$((s+c)/2),r,o]}}})}function BW(e,t,n,r,i,a){let o=[];for(let e=0;e<t.cells.length;e++)for(let n=0;n<(t.cells[e]?.length??0);n++)t.cells[e]?.[n]&&o.push([n,e]);let s=Math.min(o.length,Math.max(3,Math.floor(i*a/12))),c=[],l=new Set;for(let t=1;t<=s&&l.size<o.length;t++){let i=e.int(0,o.length-1);for(;l.has(i);)i=(i+1)%o.length;l.add(i);let[a,s]=o[i],[u,d]=r(a,s),f=$(n*.8);c.push({name:`Grass${t}`,type:`Foliage3D`,props:{kind:`grass`,area:[f,f],density:8,seed:e.int(1,1e9),position:[u,0,d]}})}return c}function VW(e,t,n,r,i){let a=[];if(t.length===0)return a;let o=Math.min(8,t.length);for(let s=1;s<=o;s++){let o=e.pick(t),[c,l]=i(o.gx+e.int(0,o.run-1),o.gz),u=rW(s,c,l,e,[.3,$(n*.35)],`#8f7355`),d=u.props?.position;d[1]=$(d[1]+r),a.push(u)}return a}var HW=`#23222b`,UW=`#5f6672`;function WW(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=TW(new Ee(t),n,r),o=2*n+1,s=2*r+1,c=$(o*i),l=$(s*i),u=[{name:`Floor`,type:`ColorRect2D`,props:{size:[c,l],color:HW}}],d=0;for(let e=0;e<s;e++){let t=0;for(;t<o;){if(a.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<o&&!a.cells[e]?.[t+n];)n++;d++;let r=[$(n*i),i];u.push({name:`Wall${d}`,type:`StaticBody2D`,props:{position:[$((t+n/2)*i-c/2),$((e+.5)*i-l/2)],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:UW}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var GW=16,KW=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function qW(e){let{seed:t,count:n=10,width:r=[80,160],gapX:i=[40,120],stepY:a=[-80,40],start:o=[0,300]}=e,s=new Ee(t),c=[],l=$(s.range(r[0],r[1])),u=o[0],d=o[1];for(let e=1;e<=n&&(c.push(JW(e,u,d,l,s.pick(KW))),e!==n);e++){let e=$(s.range(r[0],r[1])),t=$(s.range(i[0],i[1]));u=$(u+l/2+t+e/2),d=$(d+s.range(a[0],a[1])),l=e}return{name:`Platforms`,type:`Node2D`,children:c}}function JW(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,GW]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,GW],color:i}}]}}var YW=[3,5],XW=3,ZW={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function QW(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=oW(e.area,[60,60]),o=new Ee(t),s=[];for(let e=1;e<=n;e++){let t=o.int(YW[0],YW[1]),n=[];for(let e=1;e<=t;e++){let r=$(o.range(1,2.2));n.push({name:`Puff${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[$((e-(t+1)/2)*o.range(1,1.6)),$(o.range(-.3,.3)),$(o.range(-.6,.6))],scale:[$(r*o.range(1.1,1.6)),$(r*.55),r],material:ZW}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[$(o.range(-i/2,i/2)),$(r+o.range(-3,XW)),$(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,props:{snapToGround:!1},children:s}}var $W=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],eG=128,tG=20,nG=.8,rG=.12,iG={island:{splat:`island`,maxHeight:4.5,sun:`#fff4d6`,fill:`#b9d4ff`,sky:{elevationDeg:38,azimuthDeg:145,turbidity:2.6,rayleigh:1.1},fog:{near:1,far:4},iblIntensity:.72},alpine:{splat:`alpine`,maxHeight:8,roughness:.65,detail:5,sun:`#f4f7ff`,fill:`#c9d8f2`,sky:{elevationDeg:45,azimuthDeg:35,turbidity:1.4,rayleigh:1.3},fog:{near:1.8,far:6.5},sunIntensity:1.1,exposure:.92,iblIntensity:.72},plains:{splat:`plains`,maxHeight:4,sun:`#fff2cf`,fill:`#bcd3ef`,sky:{elevationDeg:36,azimuthDeg:140,turbidity:2.4,rayleigh:1},fog:{near:.9,far:4},iblIntensity:.58},desert:{splat:`desert`,maxHeight:5,sun:`#ffe3b3`,fill:`#e8c9a6`,sky:{elevationDeg:42,azimuthDeg:160,turbidity:7,rayleigh:.6},fog:{near:.8,far:3.2,color:`#e8d3ae`},sunIntensity:1.35,iblIntensity:.75},meadow:{splat:`grassland`,maxHeight:1.2,sun:`#fff8e2`,fill:`#bfe0c9`,sky:{elevationDeg:55,azimuthDeg:125,turbidity:2.4,rayleigh:.95},fog:{near:1,far:4.4},sunIntensity:2.6,exposure:1.12,iblIntensity:.62},forest:{splat:`forest`,maxHeight:2.5,sun:`#ffdca8`,fill:`#a9c8b4`,sky:{elevationDeg:29,azimuthDeg:120,turbidity:5.5,rayleigh:1},fog:{near:.22,far:1.8,color:`#9fb494`},sunIntensity:2.6,ambient:.26,iblIntensity:.55},savanna:{splat:`savanna`,maxHeight:3,sun:`#ffdca0`,fill:`#e6d2a4`,sky:{elevationDeg:34,azimuthDeg:150,turbidity:5,rayleigh:.7},fog:{near:1,far:4.2,color:`#e3cf9f`},sunIntensity:2,exposure:1.05,iblIntensity:.6},snow:{splat:`snow`,maxHeight:2.2,sun:`#dfe9ff`,fill:`#c2d2f0`,sky:{elevationDeg:22,azimuthDeg:35,turbidity:1.6,rayleigh:1.6},fog:{near:1.2,far:5,color:`#dbe6f5`},sunIntensity:1,exposure:.9,iblIntensity:.72},wetland:{splat:`wetland`,maxHeight:1.4,sun:`#d6ddc8`,fill:`#9fb29a`,sky:{elevationDeg:24,azimuthDeg:115,turbidity:9,rayleigh:1.1},fog:{near:.5,far:2,color:`#92a288`},sunIntensity:1.5,exposure:.94,ambient:.24,iblIntensity:.66},volcanic:{splat:`volcanic`,maxHeight:4,roughness:.7,sun:`#ff8a4a`,fill:`#7a4a3a`,sky:{elevationDeg:14,azimuthDeg:135,turbidity:10,rayleigh:.3},fog:{near:.18,far:1.4,color:`#2a211c`},sunIntensity:1.7,exposure:.86,ambient:.22,iblIntensity:.5}};function aG(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=iG[n];if(!a)throw new L(`BAD_FORMAT`,`generateTerrain theme must be one of [${$W.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...$W]});let o=Math.max(2,Math.round(e.resolution??eG)),s=e.maxHeight||a.maxHeight,c=new Ee(t),l=n===`island`,u=e=>Mj({width:r,depth:r,segsX:o,segsZ:o,maxHeight:e,seed:t,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},islandEdge:l}),d=u(s);if(l)for(let e=0;e<3;e++){let e=sG(d)-tG,t=d.maxHeight-d.minHeight,n=d.minHeight+rG*t;if(e+nG<=n)break;let r=tG-nG,i=sG(d)-d.minHeight-rG*t;s=$(s*Math.min(r/i*.95,.9)),d=u(s)}let f=[{name:`Ground`,type:`StaticBody3D`,props:{collider:{shape:`heightfield`}},children:[{name:`Surface`,type:`Terrain3D`,props:{size:[r,r],maxHeight:s,seed:t,theme:a.splat,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},...o===eG?{}:{resolution:o}}}]}],p=n===`wetland`;if(l)f.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,oG(d),0],opacity:1}});else if(p){let e=d.maxHeight-d.minHeight||1,t=$(d.minHeight+.22*e);f.push({name:`Swamp`,type:`Water3D`,props:{size:[r,r],position:[0,t,0],waveHeight:.02,quality:`simple`,color:`#3a4a30`,opacity:.95}})}else if(i){let e=$(d.minHeight+.1*(d.maxHeight-d.minHeight));f.push({name:`Lake`,type:`Water3D`,props:{size:[r,r],position:[0,e,0],waveHeight:.04}})}return f.push(...CG(n,c,d,r)),l&&f.push(QW({seed:c.int(1,1e9),count:6,area:r,altitude:Math.round(d.maxHeight+12)})),f.push(...aW(r).map((e,t)=>wG(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:f}}function oG(e){let t=sG(e)-tG,n=e.minHeight+rG*(e.maxHeight-e.minHeight);return $(Math.max(Math.min(t+nG,n),t+.55))}function sG(e){let t=-1/0,n=e.width/2,r=e.depth/2,i=e.segsX;for(let a=0;a<=i;a++){let o=-n+a/i*e.width,s=-r+a/i*e.depth;t=Math.max(t,e.baseHeight(o,-r),e.baseHeight(o,r),e.baseHeight(-n,s),e.baseHeight(n,s))}return t}function cG(e,t,n){let r=Math.min(t.width/2-n.margin,n.within??1/0),i=t.maxHeight-t.minHeight||1,a=[];for(let o=0;o<n.count*30&&a.length<n.count;o++){let o=$(e.range(-r,r)),s=$(e.range(-r,r));if(n.clearing&&Math.hypot(o,s)<n.clearing||n.within&&Math.hypot(o,s)>n.within)continue;let c=t.heightAt(o,s),l=(c-t.minHeight)/i;l<n.band[0]||l>n.band[1]||t.slopeAt(o,s)>n.maxSlope||a.push({x:o,z:s,y:c})}return a}var lG=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],uG=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],dG={canopy:`#9aa052`,trunk:`#8a6a44`},fG={canopy:`#39513f`,trunk:`#5a5650`};function pG(e,t){return e===`conifer`?t.pick(lG):e===`broadleaf`?t.pick(uG):null}function mG(e,t,n,r,i){let a=i?.height??[4.5,7],o=i?.sink??(i?.count===void 0?.05:.3),s={};i?.tier!==void 0&&(s.tier=i.tier),i?.count!==void 0&&i.area!==void 0&&(s.count=i.count,s.area=[i.area,i.area]);let c=pG(r,n),l=i?.palette??c;return l&&(s.canopyColor=l.canopy,s.trunkColor=l.trunk),{name:e,type:`Tree3D`,props:{type:r,seed:n.int(1,1e9),height:$(n.range(a[0],a[1])),position:[t.x,$(t.y-o),t.z],...s}}}function hG(e,t,n,r,i,a=0,o){return{name:e,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[r,r],density:i,height:o?.height??.3,...o?.colors?{colorA:o.colors[0],colorB:o.colors[1]}:{},seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z],...a>0?{flowers:a}:{}}}}function gG(e,t,n,r,i){return{name:e,type:`Foliage3D`,props:{kind:`reeds`,style:`simple`,area:[r,r],density:i,height:.9,colorA:`#2f4a26`,colorB:`#5a6f33`,seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function _G(e,t,n,r,i){return{name:e,type:`Flowers3D`,props:{density:i,area:[r,r],seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function vG(e,t,n,r){return e.map((e,i)=>{let a=rW(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=$(o[1]+e.y),a})}function yG(e){let t=Math.round(e.range(104,128)),n=Math.round(t-e.range(10,18)),r=Math.round(t-e.range(20,30)),i=e=>e.toString(16).padStart(2,`0`);return`#${i(n)}${i(t)}${i(r)}`}function bG(e){let t=Math.round(e.range(196,224)),n=Math.min(255,t+Math.round(e.range(4,12))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(t)}${r(t)}${r(n)}`}function xG(e){let t=Math.round(e.range(34,56)),n=Math.min(255,t+Math.round(e.range(2,8))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(n)}${r(t)}${r(t)}`}var SG=[`#6f5b41`,`#7a644a`,`#665439`];function CG(e,t,n,r){let i=[];switch(e){case`island`:{let e=cG(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=cG(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`conifer`)));let r=cG(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...vG(r,t,[.6,1.8]));break}case`plains`:{let e=cG(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`broadleaf`)));let r=cG(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...vG(r,t,[.4,1.2]));break}case`desert`:{let e=cG(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`dead`)));let r=cG(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...vG(r,t,[.5,1.6]));break}case`meadow`:{let e=$(r*.09),a=cG(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>hG(`Carpet${r+1}`,n,t,e,30)));let o=$(r*.07),s=cG(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>_G(`Flowers${n+1}`,e,t,o,`sparse`)));let c=cG(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>mG(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=cG(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...vG(l,t,[.3,.9]));break}case`forest`:{let e=$(r*.12),a=r/2-8,o=Do(t.int(1,1e9)),s=(e,t,n)=>{let r=o(e/70,t/70);return r>.12?`conifer`:r<-.12?`broadleaf`:n%2==0?`conifer`:`broadleaf`},c=cG(t,n,{count:40,band:[0,1],maxSlope:.18,margin:8,clearing:e+6}),l=c.map((e,t)=>s(e.x,e.z,t));i.push(...c.map((e,n)=>mG(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(mG(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=cG(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>mG(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=cG(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>mG(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=cG(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>mG(`Bush${n+1}`,e,t,`bush`,{count:4,area:10,height:[2.1,3.1],sink:.12})));let p=0;c.forEach((e,r)=>{if(r%3==2)return;let o=t.range(0,Math.PI*2),s=t.range(2,4.5),c=t.int(1,1e9),l=$(sW(e.x+Math.cos(o)*s,-a,a)),u=$(sW(e.z+Math.sin(o)*s,-a,a));n.slopeAt(l,u)>.09||(p++,i.push({name:`Fern${p}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,tuftStyle:`fern`,area:[8,8],density:9,height:.4,colorA:`#4a6b34`,colorB:`#82a258`,seed:c,position:[l,$(n.heightAt(l,u)+.02),u]}}))});let m=$(r*.08),h=cG(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>hG(`Grass${n+1}`,e,t,m,20,0,{height:.24,colors:[`#4f7034`,`#85a154`]})));let g=u.length>0?t.int(3,5):0;for(let e=0;e<g;e++){let r=u[e%u.length],o=t.range(0,Math.PI*2),s=t.range(2.5,4.5),c=$(sW(r.x+Math.cos(o)*s,-a,a)),l=$(sW(r.z+Math.sin(o)*s,-a,a));i.push({name:`Log${e+1}`,type:`Tree3D`,props:{type:`dead`,seed:t.int(1,1e9),height:$(t.range(4.2,5.6)),trunkColor:`#4a4236`,position:[c,$(n.heightAt(c,l)+.12),l],rotation:[0,t.int(0,359),$(t.range(81,97))]}})}cG(t,n,{count:5,band:[0,1],maxSlope:.25,margin:9,clearing:e}).forEach((e,n)=>{let r=$(t.range(.16,.28)),a=$(t.range(.3,.55));i.push({name:`Stump${n+1}`,type:`MeshInstance3D`,props:{mesh:`cylinder`,size:[r,a,r],position:[e.x,$(e.y+a/2-.06),e.z],rotation:[0,t.int(0,359),0],material:{color:t.pick(SG),roughness:1},castShadow:!0}})});let _=cG(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...vG(_,t,[.3,1],yG));let v=$(e*.75),y=cG(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-$(v/Math.SQRT2)});i.push(...y.map((e,n)=>hG(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=$(e*.45),x=cG(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-$(b/Math.SQRT2)});i.push(...x.map((e,n)=>_G(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=cG(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:dG})));let a=$(r*.09),o=cG(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>hG(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=cG(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...vG(s,t,[.4,1.4]));let c=cG(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>mG(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=cG(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:fG})));let r=cG(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...vG(r,t,[.5,1.8],bG));break}case`wetland`:{let e=$(r*.08),a=cG(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>gG(`Reeds${r+1}`,n,t,e,4)));let o=$(r*.08),s=cG(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>hG(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=cG(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>mG(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=cG(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>mG(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=cG(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...vG(u,t,[.3,1],yG));break}case`volcanic`:{let e=cG(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=cG(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...vG(r,t,[.4,1.8],xG)),cG(t,n,{count:3,band:[0,.6],maxSlope:.18,margin:12}).forEach((e,n)=>{t.int(1,1e9),i.push({name:`Smoke${n+1}`,type:`Particles3D`,props:{preset:`smoke`,position:[e.x,$(e.y+.2),e.z],rate:8,maxParticles:64,colorStart:`#5a5048`,colorEnd:`#2a2422`,sizeStart:18,sizeEnd:44}}),i.push({name:`Embers${n+1}`,type:`Particles3D`,props:{position:[e.x,$(e.y+.1),e.z],rate:10,maxParticles:48,lifetime:[.8,1.8],speed:[12,34],directionDeg:-90,spreadDeg:40,gravity:[0,-18],sizeStart:4,sizeEnd:1,colorStart:`#ffce6a`,colorEnd:`#d83a14`,blend:`add`}})});break}}return i}function wG(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var TG={arena:{description:`FPS stage: floor, 4 perimeter walls, obstacles, lights — themes: boxes (crates), ruins (broken stone rows), garden (hedges, grass, pool)`,dimension:`3d`,params:{theme:{type:`string`,default:`boxes`,options:[...cW]},width:{type:`number`,default:30,min:4},depth:{type:`number`,default:30,min:4},wallHeight:{type:`number`,default:3,min:.5},obstacles:{type:`number`,default:8,min:0}}},terrain:{description:`Heightfield world: StaticBody3D{heightfield} + Terrain3D + theme dressing (trees, rocks, grass, sea/clouds on island, broad swamp water on wetland, smoke/ember emitters on volcanic; maxHeight 0 = theme default; water adds a lake to non-island themes)`,dimension:`3d`,params:{theme:{type:`string`,default:`island`,options:[...$W]},size:{type:`number`,default:200,min:40,max:400},maxHeight:{type:`number`,default:0,min:0},water:{type:`boolean`,default:!1}}},maze:{description:`Recursive-backtracker 3D maze, west→east — themes: stone, hedge (green + grass), canyon (sandstone + rim rocks)`,dimension:`3d`,params:{theme:{type:`string`,default:`stone`,options:[...EW]},width:{type:`number`,default:8,min:2,max:40},depth:{type:`number`,default:8,min:2,max:40},cellSize:{type:`number`,default:2,min:.5},wallHeight:{type:`number`,default:2.5,min:.5}}},maze2d:{description:`The same maze algorithm as 2D ColorRect2D + StaticBody2D tiles`,dimension:`2d`,params:{cols:{type:`number`,default:10,min:2,max:40},rows:{type:`number`,default:8,min:2,max:40},cellPx:{type:`number`,default:64,min:8}}},dungeon2d:{description:`Roguelike rooms + L-corridors: floor rects, wall bodies (32px tiles)`,dimension:`2d`,params:{rooms:{type:`number`,default:5,min:1,max:20},size:{type:`number`,default:960,min:256}}},platforms2d:{description:`Left-to-right 2D platform course (tune ranges via the library)`,dimension:`2d`,params:{count:{type:`number`,default:10,min:1}}}},EG={arena:pW,terrain:aG,maze:NW,maze2d:WW,dungeon2d:xW,platforms2d:qW};function DG(e,t){let n=EG[e];if(!n){let t=Object.keys(EG);throw new L(`BAD_FORMAT`,`Unknown generator '${e}'. Valid: [${t.join(`, `)}] — the old meadow/forest/island/rocks/clouds generators became themes (e.g. terrain theme: 'meadow', arena theme: 'garden'); scatter is library-only (needs item templates).`,{validOptions:t})}return n(t)}function OG(e){return Object.entries(TG).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function kG(e,t){if(e.type===`boolean`)return t===!0||t===`true`;if(e.type===`number`){let n=typeof t==`boolean`?NaN:Number(t);return(t===``||!Number.isFinite(n))&&(n=e.default),e.min!==void 0&&(n=Math.max(e.min,n)),e.max!==void 0&&(n=Math.min(e.max,n)),n}let n=String(t);return e.options&&!e.options.includes(n)?e.default:n}function AG(){return Math.floor(Math.random()*1e6)}var jG=[],MG=new Map,NG=null;function PG(e){let t=document.querySelector(`#generate`);t&&(LG(e),t.removeAttribute(`hidden`))}function FG(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function IG(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&FG()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,FG),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,FG),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>RG(e)))}function LG(e){let t=document.querySelector(`#generate-body`),n=document.querySelector(`#generate-status`);if(!t)return;n&&(n.textContent=``),t.textContent=``;let r=e.working.dimension??`2d`;jG=OG(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=rU({en:`Deterministic ${r.toUpperCase()} environment generators — the subtree inserts under the selected node (the root when nothing is selected). The same seed always generates the same level.`,ko:`결정적 ${r.toUpperCase()} 환경 생성기 — 생성된 서브트리는 선택한 노드 아래에(선택이 없으면 루트에) 들어갑니다. 같은 시드는 항상 같은 레벨을 만듭니다.`}),t.appendChild(i);let a=zG(rU({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of jG){let t=document.createElement(`option`);t.value=e,t.textContent=e,o.appendChild(t)}a.appendChild(o),t.appendChild(a);let s=document.createElement(`p`);s.className=`gen-desc`,t.appendChild(s);let c=document.createElement(`div`);c.id=`generate-params`,t.appendChild(c);let l=zG(`seed`);NG=document.createElement(`input`),NG.type=`number`,NG.step=`1`,NG.value=String(AG());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=rU({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{NG&&(NG.value=String(AG()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(NG,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=jG.find(e=>e.name===o.value)??jG[0];if(e){s.textContent=e.meta.description,c.textContent=``,MG=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=zG(t),r;if(n.type===`boolean`)r=document.createElement(`input`),r.type=`checkbox`,r.checked=n.default===!0;else if(n.type===`string`&&n.options){r=document.createElement(`select`);for(let e of n.options){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}r.value=String(n.default)}else r=document.createElement(`input`),r.type=n.type===`number`?`number`:`text`,n.type===`number`&&(r.step=`any`,n.min!==void 0&&(r.min=String(n.min)),n.max!==void 0&&(r.max=String(n.max))),r.value=String(n.default),(n.min!==void 0||n.max!==void 0)&&(r.title=`${n.min??``}–${n.max??``}`);MG.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function RG(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=jG.find(e=>e.name===n?.value);if(!r||!NG)return;let i={seed:kG({type:`number`,default:AG(),min:0},NG.value)};for(let[e,t]of MG){let n=r.meta.params[e];n&&(i[e]=kG(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=DG(r.name,i)}catch(e){t&&(t.textContent=e instanceof Error?e.message:String(e));return}let o=e.insertNode(a,e.selection??[]);if(o===null){t&&(t.textContent=rU({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),NG&&(NG.value=String(AG())),FG()}function zG(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var BG={connections:{title:{en:`connections — wire a signal to a handler`,ko:`connections — 시그널을 핸들러에 연결`},body:{en:'A connection says "when THIS node emits THIS signal, call THIS method on THAT node" — declaratively, in the scene JSON, with no TypeScript. emits = leaving this node; receives = arriving at it. Paths resolve from the scene ROOT (`Player/Sword`, `.` for the root itself). A red target does not resolve and the game will refuse to load the scene. Handlers on a scripted node are free text: they live in your behavior, which the editor never loads.',ko:'연결은 "이 노드가 이 시그널을 보내면, 저 노드의 이 메서드를 호출한다"를 씬 JSON에 선언합니다 — TypeScript 없이. emits는 이 노드에서 나가는 것, receives는 들어오는 것입니다. 경로는 씬 루트 기준입니다(`Player/Sword`, 루트 자신은 `.`). 빨간 대상은 찾을 수 없다는 뜻이고, 게임은 그 씬을 열지 못합니다. 스크립트가 있는 노드의 핸들러는 자유 입력입니다 — 에디터가 읽지 않는 게임 코드에 있기 때문입니다.'}},groups:{title:{en:`groups — tag nodes for queries`,ko:`groups — 조회용 태그`},body:{en:'A LIST of names. Game code finds nodes with tree-wide queries like getNodesInGroup("coins"), and triggers can filter by group (e.g. only react to "player"). Type a name and press Enter. For key-values a node carries (what KIND of thing it is, what it is worth) use `tags`, below.',ko:`자유 형식 태그입니다. 게임 코드가 getNodesInGroup("coins")처럼 트리 전체에서 노드를 찾고, 트리거는 그룹으로 거릅니다(예: "player"에만 반응). 이름을 입력하고 Enter를 누르세요.`},example:`triggerEnter → if (other.isInGroup("player")) collect()`},tags:{title:{en:`tags — free-form identity JSON`,ko:`tags — 자유 형식 식별 JSON`},body:{en:'Not groups. `groups` is a LIST of names you query the tree by; `tags` is an OBJECT of key-values the node carries for your game logic — what kind of thing it is and what it is worth. Connections filter on them (`filter: {tag: {kind: "ITEM"}}`), and a behavior reads `node.tags`. Anything JSON: numbers, strings, nested objects. A rhythm chart lives here — one note node per beat, `{"beat": 4, "lane": 0}`.',ko:'groups와 다릅니다. `groups`는 트리를 조회하는 이름 목록이고, `tags`는 노드가 지니는 키-값 객체입니다 — 무엇이며 얼마나 값어치가 있는지. 연결이 이것으로 거르고(`filter: {tag: {kind: "ITEM"}}`), 비헤이비어는 `node.tags`로 읽습니다. JSON이면 무엇이든 됩니다 — 숫자, 문자열, 중첩 객체.'},example:`{"kind": "ITEM", "value": 10}`},script:{title:{en:`script — attach YOUR game logic`,ko:`script — 게임 로직 연결`},body:{en:`A Behavior is a TypeScript class living in YOUR game code, linked by name. The editor stores the link; the class itself must be registered in the game before loadScene. Props here are passed to the behavior instance.`,ko:`Behavior는 게임 코드에 있는 TypeScript 클래스이며 이름으로 연결됩니다. 에디터는 연결만 저장하고, 클래스 자체는 loadScene 전에 게임에서 등록되어야 합니다. 여기의 props가 비헤이비어 인스턴스로 전달됩니다.`},example:`registerBehavior('CoinCounter', CoinCounter) // in your main.ts`,copy:{label:`copy behavior boilerplate`,text:`import { Behavior, registerBehavior } from 'incanto';
|
|
8962
|
+
}`};var zV=`https://agent8-games.verse8.io/assets/3D/default/textures/hdri`,BV={apartment:`lebombo_1k.hdr`,city:`potsdamer_platz_1k.hdr`,dawn:`kiara_1_dawn_1k.hdr`,forest:`forest_slope_1k.hdr`,lobby:`st_fagans_interior_1k.hdr`,night:`dikhololo_night_1k.hdr`,park:`rooitou_park_1k.hdr`,studio:`studio_small_03_1k.hdr`,sunset:`venice_sunset_1k.hdr`,warehouse:`empty_warehouse_01_1k.hdr`};function VV(e){if(typeof e.hdri==`string`&&e.hdri!==``)return e.hdri;if(typeof e.preset==`string`){let t=BV[e.preset];if(!t)throw Error(`Unknown environment preset '${e.preset}'. Available: ${Object.keys(BV).join(`, `)}.`);return`${zV}/${t}`}return null}var HV=75,UV=class{scene;ambient=new dm(`#ffffff`,0);envKey=null;config=kr(void 0);hdriUrl=null;hdriTexture=null;_sky=null;skyKey=``;skyEnvKey=``;skyEnvTarget=null;fog=new fu(`#ffffff`,1,1e3);underwaterFog=null;underwaterBg=new J;onHdriError=null;assets=null;backdropUrl=null;backdropTexture=null;constructor(e){this.scene=e,this.scene.add(this.ambient)}get sunDirection(){return this.config.sky?Nr(this.config.sky):null}get clouds(){return this.config.clouds}get bloom(){return this.config.bloom}get post(){return this.config.post}get sceneFog(){return this.scene.fog instanceof fu?this.scene.fog:null}apply(e,t){let n=e===void 0?``:JSON.stringify(e);n!==this.envKey&&(this.envKey=n,this.config=kr(e));let r=this.config,i=e?.ambient;if(this.ambient.color.set(i?.color??`#ffffff`),this.ambient.intensity=i?.intensity??0,t&&(t.toneMappingExposure=r.exposure,t.shadowMap.enabled=r.shadows!==!1,r.shadows!==!1&&r.shadows!==null&&r.shadows.static?t.shadowMap.autoUpdate&&(t.shadowMap.autoUpdate=!1,t.shadowMap.needsUpdate=!0):t.shadowMap.autoUpdate||(t.shadowMap.autoUpdate=!0)),this.applyHdri(e),this.applySky(r.sky,t),this.applyBackdrop(r.skybox),this._sky&&(this._sky.visible=this.backdropTexture===null),this.applyFog(r),this.scene.environment=this.hdriTexture??this.skyEnvTarget?.texture??null,this.scene.environmentIntensity=(this.scene.environment===this.skyEnvTarget?.texture&&this.skyEnvTarget?.55:1)*WV(e?.iblIntensity),this.backdropTexture)this.scene.background=this.backdropTexture;else if(r.skybox===!0&&this.hdriTexture)this.scene.background=this.hdriTexture;else{let t=e?.background;this.scene.background=typeof t==`string`?new J(t):null}}applySunLight(e,t=null){if(!e)return;let n=this.sunDirection;if(t){let r=e.position.length()||100,i,a,o;if(n)[i,a,o]=n;else{i=e.position.x-e.target.position.x,a=e.position.y-e.target.position.y,o=e.position.z-e.target.position.z;let t=Math.hypot(i,a,o)||1;i/=t,a/=t,o/=t}e.target.position.set(t.x,t.y,t.z),e.target.updateMatrixWorld(),e.position.set(t.x+i*r,t.y+a*r,t.z+o*r)}else if(n){let t=e.position.length()||100;e.position.set(n[0],n[1],n[2]).multiplyScalar(t)}let r=this.config.shadows;if(r&&typeof r==`object`){if(!e.castShadow){let t=e.shadow.camera;`left`in t&&t.left===-5&&(t.left=-75,t.right=HV,t.top=HV,t.bottom=-75,t.near=.5,t.far=500,t.updateProjectionMatrix()),e.castShadow=!0}e.shadow.mapSize.x!==r.mapSize&&(e.shadow.mapSize.set(r.mapSize,r.mapSize),e.shadow.map?.dispose(),e.shadow.map=null),e.shadow.radius=r.radius}}applyUnderwater(e){e&&(this.underwaterFog||=new fu(`#000000`,.5,e.visibility),this.underwaterFog.color.set(e.color),this.underwaterFog.near=.5,this.underwaterFog.far=e.visibility,this.scene.fog=this.underwaterFog,this.scene.background=this.underwaterBg.set(e.color),this._sky&&(this._sky.visible=!1))}applyHdri(e){let t=VV(e??{});t!==this.hdriUrl&&(this.hdriUrl=t,this.hdriTexture?.dispose(),this.hdriTexture=null,t&&new LV().load(t,e=>{if(this.hdriUrl!==t){e.dispose();return}e.mapping=303,this.hdriTexture=e},void 0,e=>{this.onHdriError?.(t,e)}))}applyBackdrop(e){let t=typeof e==`string`?e:null;if(t===this.backdropUrl||(this.backdropUrl=t,this.backdropTexture?.dispose(),this.backdropTexture=null,!t))return;if(/\.hdr(\?|#|$)/i.test(t)){if(typeof document>`u`)return;new LV().load(t,e=>{if(this.backdropUrl!==t){e.dispose();return}e.mapping=303,this.backdropTexture=e},void 0,e=>{this.onHdriError?.(t,e)});return}let n=this.assets?.textures.acquireOwn(t,{colorSpace:`srgb`})??null;n&&(n.mapping=303,n.colorSpace=hc,this.backdropTexture=n)}applySky(e,t){let n=e?JSON.stringify(e):``;if(n!==this.skyKey&&(this.skyKey=n,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null),e)){this._sky=new RV,this._sky.scale.setScalar(45e4);let t=this._sky.material.uniforms;(t.sunPosition?.value).set(...e.sunPosition),t.turbidity&&(t.turbidity.value=e.turbidity),t.rayleigh&&(t.rayleigh.value=e.rayleigh),this.scene.add(this._sky)}if(e&&t&&this._sky&&this.skyEnvKey!==n){this.skyEnvKey=n,this.skyEnvTarget?.dispose();let e=new ph(t),r=new pu;r.add(this._sky),this.skyEnvTarget=e.fromScene(r),e.dispose(),this.scene.add(this._sky)}!e&&this.skyEnvTarget&&(this.skyEnvTarget.dispose(),this.skyEnvTarget=null,this.skyEnvKey=``)}applyFog(e){if(!e.fog){this.scene.fog=null;return}let t=e.fog.color||(e.sky?Pr(e.sky):`#cfd8e0`);this.fog.color.set(t),this.fog.near=e.fog.near,this.fog.far=e.fog.far,this.scene.fog=this.fog}dispose(){this.hdriTexture?.dispose(),this.hdriTexture=null,this.backdropTexture?.dispose(),this.backdropTexture=null,this.backdropUrl=null,this.skyEnvTarget?.dispose(),this.skyEnvTarget=null,this._sky&&=(this.scene.remove(this._sky),this._sky.material.dispose(),this._sky.geometry.dispose(),null)}};function WV(e){if(e===void 0)return 1;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new L(`BAD_FORMAT`,`environment.iblIntensity must be a finite number >= 0 (multiplies the image-based ambience: sky-derived base 0.55, HDRI base 1; default 1), got ${JSON.stringify(e)}.`,{prop:`iblIntensity`});return e}var GV=new Ou,KV=new Ou,qV=new q,JV=new q,YV=new G,XV=Array.from({length:8},()=>new G),ZV=.4,QV=new Float32Array(72),$V=[[0,0,0],[1,0,0],[1,0,1],[0,0,1],[0,1,0],[1,1,0],[1,1,1],[0,1,1]],eH=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];function tH(e,t){t.makeEmpty(),qV.copy(e.matrixWorld).invert(),e.traverse(e=>{let n=e,r;n.isInstancedMesh?(n.boundingBox||n.computeBoundingBox?.(),r=n.boundingBox):n.geometry&&(n.geometry.boundingBox||n.geometry.computeBoundingBox(),r=n.geometry.boundingBox),r&&(KV.copy(r).applyMatrix4(JV.multiplyMatrices(qV,e.matrixWorld)),t.union(KV))})}function nH(e){if(!(e instanceof Fb))return null;let t=e._ensureObject3D();t.updateWorldMatrix(!0,!0),tH(t,GV);let n=!0;GV.isEmpty()?(n=!1,YV.setFromMatrixPosition(t.matrixWorld),GV.min.set(YV.x-ZV,YV.y-ZV,YV.z-ZV),GV.max.set(YV.x+ZV,YV.y+ZV,YV.z+ZV)):GV.expandByScalar(.02);let{min:r,max:i}=GV;for(let e=0;e<8;e++){let[a,o,s]=$V[e],c=XV[e].set(a?i.x:r.x,o?i.y:r.y,s?i.z:r.z);n&&c.applyMatrix4(t.matrixWorld)}let a=0;for(let[e,t]of eH){let n=XV[e],r=XV[t];QV[a++]=n.x,QV[a++]=n.y,QV[a++]=n.z,QV[a++]=r.x,QV[a++]=r.y,QV[a++]=r.z}return QV}function rH(e){return e.spatial===!0&&typeof e._setSpatialPose==`function`}function iH(){let e=new Set,t=[],n=[],r=[];return{visited:e,cameras:t,renderHooks:n,emitters:r,state:{visited:e,cameras:t,renderHooks:n,emitters:r,assets:void 0,sunDirection:null,sunLight:null,alpha:1,ignoreStatic:!1,quality:null},blend:{cam:new rm,active:!1,t:0,seconds:0,fromPos:new G,fromQuat:new W,fromFov:60,lastNode:null,lastPos:new G,lastQuat:new W,lastFov:60}}}var aH=new G,oH=new W;function sH(e,t,n,r,i){let a=i??iH();a.visited.clear(),a.cameras.length=0,a.renderHooks.length=0,a.emitters.length=0;let o=a.state;o.assets=n,o.sunDirection=r?.sunDirection??null,o.ignoreStatic=r?.ignoreStatic===!0,o.sunLight=null,o.alpha=r?.alpha??1,o.quality=r?.quality??null,mH(e,t,o),_H(t,a.visited);let s=null;for(let e=0;e<a.cameras.length;e++){let t=a.cameras[e];if(t.current){s=t;break}}s||=a.cameras[0]??null;let c=s?s._ensureObject3D():null;return s&&c&&(c=cH(a.blend,s,c,r?.dt??0)),pH(a.emitters,c),{activeCamera:c,renderHooks:a.renderHooks,sunLight:o.sunLight}}function cH(e,t,n,r){let i=t._blendRequest;if(t._blendRequest=void 0,e.lastNode!==t){let n=i??t.blendSeconds;e.lastNode&&n>0?(e.fromPos.copy(e.lastPos),e.fromQuat.copy(e.lastQuat),e.fromFov=e.lastFov,e.t=0,e.seconds=n,e.active=!0):e.active=!1}let a=n;if(e.active){e.t+=r;let t=Math.min(1,e.t/e.seconds),i=t<.5?2*t*t:1-(-2*t+2)**2/2;n.updateWorldMatrix(!0,!1),n.getWorldPosition(aH),n.getWorldQuaternion(oH),e.cam.position.copy(e.fromPos).lerp(aH,i),e.cam.quaternion.copy(e.fromQuat).slerp(oH,i),e.cam.fov=e.fromFov+(n.fov-e.fromFov)*i,e.cam.near=n.near,e.cam.far=n.far,e.cam.aspect=n.aspect,e.cam.updateProjectionMatrix(),e.cam.updateMatrixWorld(!0),t>=1?e.active=!1:a=e.cam}return a.updateWorldMatrix(!0,!1),a.getWorldPosition(e.lastPos),a.getWorldQuaternion(e.lastQuat),e.lastFov=a.fov,e.lastNode=t,a}var lH=new G,uH=new G,dH=new G,fH=new G;function pH(e,t){if(e.length===0||!t)return;t.updateWorldMatrix(!0,!1),t.getWorldPosition(uH),t.getWorldDirection(dH),fH.set(0,1,0).applyQuaternion(t.quaternion);let n={position:[uH.x,uH.y,uH.z],forward:[dH.x,dH.y,dH.z],up:[fH.x,fH.y,fH.z]};for(let{node:t,parent:r}of e)r.updateWorldMatrix(!0,!1),r.getWorldPosition(lH),t._setSpatialPose({position:[lH.x,lH.y,lH.z],listener:n})}function mH(e,t,n){let r=t;if(e instanceof Fb){let i=e._ensureObject3D();if(e.static&&!n.ignoreStatic&&i.userData.incantoStaticSynced===!0){i.userData.incantoStatic=!0,n.visited.add(i);return}if(i.parent!==t&&t.add(i),n.quality){let t=e._applyQualityCaps;typeof t==`function`&&t.call(e,n.quality)}if(e._syncObject3D(n.alpha,n.assets??null),n.assets&&e instanceof WL&&e._syncModel(n.assets),typeof e._onRender3D==`function`&&n.renderHooks.push(e),n.sunDirection){let t=e._applySunDirection;typeof t==`function`&&t.call(e,n.sunDirection)}e instanceof SL&&(!n.sunLight||e.intensity>n.sunLight.intensity)&&(n.sunLight=e),n.visited.add(i),e instanceof dP&&n.cameras.push(e),r=i}else rH(e)&&n.emitters.push({node:e,parent:r});for(let t of e.children)mH(t,r,n);if(e instanceof Fb){let t=e._ensureObject3D();e.static&&!n.ignoreStatic&&e._staticReady(n.assets??null)?(t.userData.incantoStaticSynced=!0,t.userData.incantoStatic=!0,gH(e)):t.userData.incantoStaticSynced===!0&&(t.userData.incantoStaticSynced=!1,t.userData.incantoStatic=!1)}}var hH=new WeakSet;function gH(e){if(hH.has(e))return;hH.add(e);let t=[],n=e=>{(typeof e._onRender3D==`function`||e instanceof dP)&&t.push(`${e.name} (${e.constructor.typeName??`?`})`);for(let t of e.children)n(t)};n(e),t.length>0&&z(e.tree?.engine??null,`warn`,`[incanto] static subtree '${e.name}' freezes animated/per-frame nodes: ${t.join(`, `)} — they will stop updating. Unmark static or move them out.`)}function _H(e,t){let n=e.children;for(let r=n.length-1;r>=0;r--){let i=n[r];i.userData.incantoNode&&!t.has(i)?e.remove(i):i.userData.incantoStatic!==!0&&_H(i,t)}}var vH=120,yH=class{viewOverride=null;overrideCam=new rm(60,1,.05,5e3);lastCamera=null;lastSize={w:1,h:1};webgl;threeScene=new pu;environment=(()=>{let e=new UV(this.threeScene);return e.onHdriError=(e,t)=>{this.assets.textures.noteError(e,t),z(this.engine,`error`,`[incanto] the scene's lighting (${e}) could not be loaded — nothing else lights it.`)},e})();engine;disconnect;canvas;assets;ownsAssets;loadedAssetScenes=new WeakSet;compiledScene=null;warmCamera=null;deferCompile=!1;syncScratch=iH();ignoreStatic=!1;renderCtx=null;causticsTarget=null;causticsScene=null;causticsUniforms=null;cloudsTarget=null;cloudsHalfTarget=null;cloudsBlurTarget=null;cloudsScene=null;cloudsUniforms=null;cloudsBlurScene=null;cloudsBlurUniforms=null;cloudsCompositeScene=null;cloudsCompositeUniforms=null;bloomTarget=null;bloomBrightTarget=null;bloomBlurTarget=null;bloomBrightScene=null;bloomBrightUniforms=null;bloomBlurScene=null;bloomBlurUniforms=null;bloomCompositeScene=null;bloomCompositeUniforms=null;constructor(e){this.canvas=e.canvas,this.engine=e.engine,this.ownsAssets=!e.assets,this.assets=e.assets??new QA(this.engine),this.environment.assets=this.assets;let t=Po(e.engine.scene?.environment,{antialias:e.qualityDefaults?.antialias??!0,pixelRatio:e.qualityDefaults?.pixelRatio??Math.min(globalThis.devicePixelRatio??1,2),preserveDrawingBuffer:!1},globalThis.devicePixelRatio??1,{pixelRatio:e.pixelRatio,preserveDrawingBuffer:e.preserveDrawingBuffer});this.webgl=zo(()=>new ov({canvas:e.canvas,antialias:t.antialias,preserveDrawingBuffer:t.preserveDrawingBuffer})),this.webgl.info.autoReset=!1,this.engine.picker=(e,t)=>this.pick(e,t),this.engine.toWorld=(e,t)=>{let n=this.worldFromScreen(e,t);return n?[n.x,n.y,n.z]:null},this.engine.toScreen=e=>this.screenFromWorld(e[0]??0,e[1]??0,e[2]??0),this.engine.screenRay=(e,t)=>this.rayFromScreen(e,t),this.basePixelRatio=t.pixelRatio,this.webgl.setPixelRatio(t.pixelRatio),this.adaptive=e.adaptiveResolution===!1?null:new bV,this.webgl.shadowMap.enabled=!0,this.webgl.shadowMap.type=1,this.webgl.toneMapping=4,this.webgl.toneMappingExposure=1,this.debugLines=new jf(new dd,new yf({color:`#00ff6e`,depthTest:!1})),this.debugLines.frustumCulled=!1,this.debugLines.renderOrder=9999,this.debugLines.visible=!1,this.threeScene.add(this.debugLines),this.selectionLines=new jf(new dd,new yf({color:`#ffb020`,transparent:!0,depthTest:!1})),this.selectionLines.frustumCulled=!1,this.selectionLines.renderOrder=1e4,this.selectionLines.visible=!1,this.threeScene.add(this.selectionLines),this.disconnect=this.engine.updated.connect(()=>{let e=performance.now();this.render(),this.engine.noteRenderMs(performance.now()-e)})}basePixelRatio;adaptive;renderScale=1;adaptiveScale=1;lastFrameAt=0;debugLines;selectionLines;syncSelectionOutline(){let e=this.engine.debugSelection;e&&e.tree!==this.engine.scene?.tree&&(this.engine.debugSelection=null);let t=this.engine.debugSelection,n=t?nH(t):null;if(this.selectionLines.visible=n!==null,n){this.selectionLines.geometry.setAttribute(`position`,new Y(n,3));let e=this.selectionLines.geometry.getAttribute(`position`);e.needsUpdate=!0}}syncDebugLines(){let e=null;for(let t of tw(`3d`,this.engine))if(e=t.debugLines(),e)break;this.debugLines.visible=e!==null,e&&this.debugLines.geometry.setAttribute(`position`,new Y(e,3))}governResolution(){let e=this.adaptive;if(!e)return;let t=globalThis.performance?.now?.()??0,n=this.lastFrameAt;if(this.lastFrameAt=t,n===0)return;let r=t-n;if(r>500){e.reset();return}let i=e.push(r);i!==null&&(this.adaptiveScale=i,this.applyPixelRatio())}setRenderScale(e){let t=Math.min(2,Math.max(.25,e>0?e:1));t!==this.renderScale&&(this.renderScale=t,this.applyPixelRatio())}setFrameTarget(e){this.adaptive?.setTarget(e)}applyPixelRatio(){this.webgl.setPixelRatio(this.basePixelRatio*this.renderScale*this.adaptiveScale);let e=this.lastSize;e.w>0&&e.h>0&&this.webgl.setSize(e.w,e.h,!1)}deferFirstCompile(){this.deferCompile=!0}async warmUp(e){this.deferCompile=!1;let t=this.warmCamera;if(!t)return;let n=[];this.threeScene.traverse(e=>{(e.isMesh||e.isPoints)&&n.push(e)});let r=n.filter(e=>e.visible);if(r.length===0){this.webgl.compile(this.threeScene,t),e?.(1);return}for(let e of r)e.visible=!1;let i=Math.min(bH,r.length),a=Math.ceil(r.length/i);try{for(let n=0;n<i;n++){for(let e=n*a;e<Math.min((n+1)*a,r.length);e++)r[e].visible=!0;this.webgl.compile(this.threeScene,t),e?.((n+1)/i),await cj()}}finally{for(let e of r)e.visible=!0}}render(){let e=this.engine.scene;if(!e)return;this.webgl.info.reset(),this.governResolution(),this.syncDebugLines(),this.syncSelectionOutline(),e.assets&&!this.loadedAssetScenes.has(e)&&(this.assets.load(e.assets),this.loadedAssetScenes.add(e)),this.environment.apply(e.environment,this.webgl);let{activeCamera:t,renderHooks:n,sunLight:r}=sH(e.root,this.threeScene,this.assets,{sunDirection:this.environment.sunDirection,alpha:this.engine.interpolationAlpha,dt:this.engine.unscaledDelta,ignoreStatic:this.ignoreStatic,quality:ya(this.engine.settings.get(`quality`))},this.syncScratch),i=t;if(this.viewOverride){let[e,t,n]=this.viewOverride.position,[r,a,o]=this.viewOverride.target;this.overrideCam.position.set(e,t,n),this.overrideCam.lookAt(SH.set(r,a,o)),i=this.overrideCam}if(!i)return;this.lastCamera=i,i.updateWorldMatrix(!0,!1);let a=i.getWorldPosition(OH),o=r?r._ensureObject3D():null,s=!!o&&r.shadowFollowsCamera===!0;this.environment.applySunLight(o,s?a:null),this.compiledScene!==e&&!this.deferCompile&&(this.compiledScene=e,this.webgl.compile(this.threeScene,i)),this.warmCamera=i;let c=this.canvas.clientWidth||this.canvas.width,l=this.canvas.clientHeight||this.canvas.height,u=this.webgl.getSize(xH);(u.x!==c||u.y!==l)&&this.webgl.setSize(c,l,!1),this.lastSize={w:c,h:l};let d=l===0?1:c/l;i.aspect!==d&&(i.aspect=d,i.updateProjectionMatrix()),this.renderCtx||={gl:this.webgl,scene:this.threeScene,camera:i};let f=this.renderCtx;f.camera=i,o?(o.updateWorldMatrix(!0,!1),o.target.updateWorldMatrix(!0,!1),f.sunDir=wH.setFromMatrixPosition(o.matrixWorld).sub(TH.setFromMatrixPosition(o.target.matrixWorld)).normalize()):f.sunDir=null;for(let e=0;e<n.length;e++)n[e]?._onRender3D(f);let p=null;for(let e=0;e<n.length;e++){let t=n[e].underwaterAt?.(a.x,a.y,a.z);if(t){p=t;break}}this.environment.applyUnderwater(p);let m=this.environment.clouds,h=this.environment.bloom,g=this.environment.post;p?.caustics.enabled?this.renderWithCaustics(i,p):m&&!p?this.renderWithClouds(i,m,o):(h||g)&&!p?this.renderWithBloom(i,h,g):this.webgl.render(this.threeScene,i),this.drainFrameCapture()}captureFrame(){return new Promise((e,t)=>{this.pendingCaptures.push({resolve:e,reject:t}),setTimeout(()=>{if(this.pendingCaptures.length>0)try{this.render()}catch(e){let t=e instanceof Error?e:Error(String(e));for(let e of this.pendingCaptures.splice(0))e.reject(t)}},vH)})}pendingCaptures=[];drainFrameCapture(){if(this.pendingCaptures.length===0)return;let e=this.pendingCaptures;this.pendingCaptures=[];try{let t=this.webgl.getContext(),n=this.webgl.domElement.width,r=this.webgl.domElement.height,i=new Uint8Array(n*r*4);this.webgl.setRenderTarget(null),t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,i),jH(i,n,r);for(let t of e)t.resolve({pixels:i,width:n,height:r})}catch(t){let n=t instanceof Error?t:Error(String(t));for(let t of e)t.reject(n)}}renderWithBloom(e,t,n=null){let r=this.webgl.getDrawingBufferSize(xH),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/2)),s=Math.max(1,Math.ceil(a/2));if(this.bloomTarget&&(this.bloomTarget.width!==i||this.bloomTarget.height!==a)&&(this.bloomTarget.dispose(),this.bloomTarget=null,this.bloomBrightTarget?.dispose(),this.bloomBrightTarget=null,this.bloomBlurTarget?.dispose(),this.bloomBlurTarget=null),this.bloomTarget||(this.bloomTarget=new Ol(i,a,{type:rs,samples:4}),this.bloomBrightTarget=new Ol(o,s,{type:rs}),this.bloomBlurTarget=new Ol(o,s,{type:rs})),!this.bloomBrightScene){let e=EV();this.bloomBrightScene=new pu,this.bloomBrightScene.add(e.mesh),this.bloomBrightUniforms=e.uniforms;let t=DV();this.bloomBlurScene=new pu,this.bloomBlurScene.add(t.mesh),this.bloomBlurUniforms=t.uniforms;let n=OV();this.bloomCompositeScene=new pu,this.bloomCompositeScene.add(n.mesh),this.bloomCompositeUniforms=n.uniforms}let c=this.bloomBrightTarget,l=this.bloomBlurTarget;if(this.webgl.setRenderTarget(this.bloomTarget),this.webgl.render(this.threeScene,e),t){let n=this.bloomBrightUniforms;n.tScene.value=this.bloomTarget.texture,n.uThreshold.value=t.threshold,this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBrightScene,e);let r=this.bloomBlurUniforms;r.tTex.value=c.texture,r.uDir.value.set(1/o,0),this.webgl.setRenderTarget(l),this.webgl.render(this.bloomBlurScene,e),r.tTex.value=l.texture,r.uDir.value.set(0,1/s),this.webgl.setRenderTarget(c),this.webgl.render(this.bloomBlurScene,e)}let u=this.bloomCompositeUniforms;u.tScene.value=this.bloomTarget.texture,u.tBloom.value=t?c.texture:this.bloomTarget.texture,u.uStrength.value=t?t.strength:0,u.uVignette.value=n?.vignette??0,u.uSaturation.value=n?.saturation??1,u.uContrast.value=n?.contrast??1,this.webgl.setRenderTarget(null),this.webgl.render(this.bloomCompositeScene,e)}renderWithClouds(e,t,n){let r=this.webgl.getDrawingBufferSize(xH),i=Math.max(1,r.x),a=Math.max(1,r.y),o=Math.max(1,Math.ceil(i/3)),s=Math.max(1,Math.ceil(a/3));if(this.cloudsTarget&&(this.cloudsTarget.width!==i||this.cloudsTarget.height!==a)&&(this.cloudsTarget.depthTexture?.dispose(),this.cloudsTarget.dispose(),this.cloudsTarget=null,this.cloudsHalfTarget?.dispose(),this.cloudsHalfTarget=null,this.cloudsBlurTarget?.dispose(),this.cloudsBlurTarget=null),!this.cloudsTarget){let e=new Hf(i,a);e.type=ns,this.cloudsTarget=new Ol(i,a,{depthTexture:e,depthBuffer:!0})}if(this.cloudsHalfTarget||(this.cloudsHalfTarget=new Ol(o,s,{depthBuffer:!1}),this.cloudsBlurTarget=new Ol(o,s,{depthBuffer:!1})),!this.cloudsScene){let{mesh:e,uniforms:t}=PV();this.cloudsScene=new pu,this.cloudsScene.add(e),this.cloudsUniforms=t}if(!this.cloudsBlurScene){let{mesh:e,uniforms:t}=NV();this.cloudsBlurScene=new pu,this.cloudsBlurScene.add(e),this.cloudsBlurUniforms=t}if(!this.cloudsCompositeScene){let{mesh:e,uniforms:t}=FV();this.cloudsCompositeScene=new pu,this.cloudsCompositeScene.add(e),this.cloudsCompositeUniforms=t}this.webgl.setRenderTarget(this.cloudsTarget),this.webgl.render(this.threeScene,e);let c=this.cloudsUniforms;c.tDepth.value=this.cloudsTarget.depthTexture,c.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(c.uCameraPos.value),c.uTime.value=(globalThis.performance?.now()??0)*.001*t.speed;let l=this.environment.sunDirection??[.4,.8,.3];c.uSunDir.value.set(l[0],l[1],l[2]).normalize(),n&&c.uSunColor.value.copy(n.color),c.uCloudColor.value.set(t.color),c.uShadeColor.value.set(t.shadeColor);let u=this.environment.sceneFog;u?(c.uHorizonColor.value.copy(u.color),c.uFarFade.value=u.far):(c.uHorizonColor.value.set(`#cdd9e6`),c.uFarFade.value=6e3),c.uBase.value=t.base,c.uTop.value=t.top,c.uCoverage.value=t.coverage,c.uDensity.value=t.density,c.uScale.value=t.scale,c.uWind.value.set(1,.35),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(this.cloudsScene,e);let d=this.cloudsBlurUniforms,f=this.cloudsBlurScene;d.tTex.value=this.cloudsHalfTarget.texture,d.uDir.value.set(1/o,0),this.webgl.setRenderTarget(this.cloudsBlurTarget),this.webgl.render(f,e),d.tTex.value=this.cloudsBlurTarget.texture,d.uDir.value.set(0,1/s),this.webgl.setRenderTarget(this.cloudsHalfTarget),this.webgl.render(f,e),this.webgl.setRenderTarget(null);let p=this.cloudsCompositeUniforms;p.tScene.value=this.cloudsTarget.texture,p.tClouds.value=this.cloudsHalfTarget.texture,this.webgl.render(this.cloudsCompositeScene,e)}renderWithCaustics(e,t){let n=this.webgl.getDrawingBufferSize(xH),r=Math.max(1,n.x),i=Math.max(1,n.y);if(this.causticsTarget&&(this.causticsTarget.width!==r||this.causticsTarget.height!==i)&&(this.causticsTarget.depthTexture?.dispose(),this.causticsTarget.dispose(),this.causticsTarget=null),!this.causticsTarget){let e=new Hf(r,i);e.type=ns,this.causticsTarget=new Ol(r,i,{depthTexture:e,depthBuffer:!0})}if(!this.causticsScene){let{mesh:e,uniforms:t}=$y();this.causticsScene=new pu,this.causticsScene.add(e),this.causticsUniforms=t}this.webgl.setRenderTarget(this.causticsTarget),this.webgl.render(this.threeScene,e),this.webgl.setRenderTarget(null);let a=this.causticsUniforms;a.tColor.value=this.causticsTarget.texture,a.tDepth.value=this.causticsTarget.depthTexture,a.uInvViewProj.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).invert(),e.getWorldPosition(a.uCameraPos.value),a.uWaterLevel.value=t.surfaceY,a.uTime.value=(globalThis.performance?.now()??0)*.001*t.caustics.speed,a.uCausticColor.value.set(t.caustics.color),a.uCausticIntensity.value=t.caustics.intensity,a.uCausticScale.value=t.caustics.scale,a.uMaxDist.value=t.visibility;let o=this.environment.sunDirection;o&&a.uSunDirection.value.set(o[0],o[1],o[2]),a.uRayStrength.value=t.rays.enabled?t.rays.strength:0,this.webgl.render(this.causticsScene,e)}screenFromWorld(e,t,n){let r=this.lastCamera;return r?(CH.set(e,t,n).project(r),{x:(CH.x+1)/2*this.lastSize.w,y:(1-CH.y)/2*this.lastSize.h,behind:CH.z>1}):{x:0,y:0,behind:!0}}worldFromScreen(e,t,n=0){let r=this.rayFromScreen(e,t);if(!r)return null;let i=r.dir[1];if(Math.abs(i)<1e-6)return null;let a=(n-r.origin[1])/i;return a<0?null:{x:r.origin[0]+r.dir[0]*a,y:n,z:r.origin[2]+r.dir[2]*a}}rayFromScreen(e,t){let n=this.lastCamera;if(!n||e<0||e>this.lastSize.w||t<0||t>this.lastSize.h)return null;AH.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),kH.setFromCamera(AH,n);let r=kH.ray.origin,i=kH.ray.direction;return{origin:[r.x,r.y,r.z],dir:[i.x,i.y,i.z]}}pick(e,t){let n=this.lastCamera;return n?(AH.set(e/this.lastSize.w*2-1,-(t/this.lastSize.h*2-1)),kH.setFromCamera(AH,n),nT(kH.intersectObjects(this.threeScene.children,!0))):null}stats(){let e=this.webgl.info;return{triangles:e.render.triangles,drawCalls:e.render.calls,geometries:e.memory.geometries,textures:e.memory.textures}}lastCameraPosition(){let e=this.lastCamera;return e?(e.getWorldPosition(DH),{x:DH.x,y:DH.y,z:DH.z}):null}cameraBasis(){let e=this.lastCamera,t=e?e.getWorldQuaternion(EH):EH.identity();return{right:new G(1,0,0).applyQuaternion(t),up:new G(0,1,0).applyQuaternion(t),forward:new G(0,0,-1).applyQuaternion(t)}}refreshShadows(){this.webgl.shadowMap.needsUpdate=!0}dispose(){this.engine.picker&&(this.engine.picker=null),this.engine.toWorld&&(this.engine.toWorld=null),this.engine.toScreen&&(this.engine.toScreen=null),this.engine.screenRay&&(this.engine.screenRay=null),this.disconnect(),this.threeScene.traverse(e=>{let t=e;if(!(!t.isMesh||t.userData?.incantoModelShared))if(t.geometry?.dispose(),Array.isArray(t.material))for(let e of t.material)e.dispose();else t.material?.dispose()}),this.causticsTarget?.depthTexture?.dispose(),this.causticsTarget?.dispose();let e=this.causticsScene?.children[0];e?.geometry?.dispose(),e?.material?.dispose(),this.cloudsTarget?.depthTexture?.dispose(),this.cloudsTarget?.dispose(),this.cloudsHalfTarget?.dispose(),this.cloudsBlurTarget?.dispose(),this.bloomTarget?.dispose(),this.bloomBrightTarget?.dispose(),this.bloomBlurTarget?.dispose();for(let e of[this.cloudsScene,this.cloudsBlurScene,this.cloudsCompositeScene,this.bloomBrightScene,this.bloomBlurScene,this.bloomCompositeScene]){let t=e?.children[0];t?.geometry?.dispose(),t?.material?.dispose()}this.ownsAssets&&this.assets.dispose(),this.environment.dispose(),this.webgl.dispose()}},bH=12,xH=new U,SH=new G,CH=new G,wH=new G,TH=new G,EH=new W,DH=new G,OH=new G,kH=new Rm,AH=new U;function jH(e,t,n){let r=t*4,i=new Uint8Array(r);for(let t=0;t<Math.floor(n/2);t++){let a=t*r,o=(n-1-t)*r;i.set(e.subarray(a,a+r)),e.copyWithin(a,o,o+r),e.set(i,o)}}async function MH(e){let t=async(t,n)=>{e.onProgress&&(e.onProgress(t,n),await cj())};vV(),(e.gameplay??!0)&&QC();for(let[t,n]of Object.entries(e.behaviors??{}))kt(t,n,{replace:!0});let n=new wa({seed:e.seed,fixedHz:e.fixedHz,...e.settings?{settings:e.settings}:{},...e._scheduler?{scheduler:e._scheduler}:{}}),r=NH(e.scene);if(Tn(r)===`2d`)throw new L(`WRONG_DIMENSION`,`createGame3D was given a 2D scene ('${String(r.name??`scene`)}'). Its nodes are never drawn by the 3D renderer and never simulated by 3D physics — you get a blank canvas. Boot it with createGame2D instead.`);let i=si(NH(r),{resolveScene:e.resolveScene,engine:n});n.setScene(i),await t(.06,`scene`);let a=null;(e.physics===!0||(e.physics??`auto`)===`auto`&&PH(i.root))&&(a=await CM(n)),e.physics!==!1&&(n.physicsProvider=async e=>{n.physics||!PH(e)||(a=await CM(n))}),await t(.1,`physics`);let o=[],s=e.keyboard??(typeof window<`u`?window:!1);s&&n.input.attachKeyboard(s);let c=!1,l=()=>{if(c||e.pointer===!1)return;let t=n.scene?.root;if(!t||e.pointer===void 0&&!IH(t))return;c=!0;let r=typeof e.pointer==`object`?e.pointer.lockOnClick??!0:!0;n.input.attachPointer(e.canvas,{lockOnClick:r})};l(),o.push(n.sceneChanged.connect(()=>l())),o.push(FH(n,i.root,e.canvas)),e.pageGestures||lv(e.canvas);let u=e.touch??`auto`;if(u!==!1){let t=e.touchContainer??e.canvas.parentElement??null;if(t){let r={force:u===!0,...e._touchDoc?{doc:e._touchDoc}:{}},i=Zt(n,t,r),a=n.sceneChanged.connect(()=>{i?.dispose(),i=Zt(n,t,r)});o.push(()=>{a(),i?.dispose()})}}let d=ba(n.settings.autoQuality()),f=e._rendererFactory?e._rendererFactory(n,e.canvas):new yH({canvas:e.canvas,engine:n,qualityDefaults:{antialias:d.antialias,pixelRatio:d.pixelRatio},...e.pixelRatio===void 0?{}:{pixelRatio:e.pixelRatio},...e.adaptiveResolution===void 0?{}:{adaptiveResolution:e.adaptiveResolution},...e.preserveDrawingBuffer===void 0?{}:{preserveDrawingBuffer:e.preserveDrawingBuffer}});await t(.14,`renderer`);let p=e.debug??!1,m=e.editor??p,h=m===!0?{}:m||null,g={label:`✎ edit this scene`,run:async()=>{if(!h)return;let t=Jv(f),i=h.open??Kv,a=async t=>{let n=await MH({...e,scene:t});h?.onReboot?.(n)};await qv(async()=>{x();try{await i({scene:r,...t?{camera:t}:{},play:a,exit:e=>a(e??r),...h.save?{save:h.save}:{},...h.library?{library:h.library===!0?Bv():h.library}:{}})}catch(e){z(n,`error`,`[incanto] could not open the editor:`,e),await a(r)}},`opening the editor…`)}};if(p){let t=e.touchContainer??e.canvas.parentElement??(typeof document<`u`?document.body:null);if(t){let{attachDebugOverlay:r}=await Iv(async()=>{let{attachDebugOverlay:e}=await import(`./debug-DepFCl1d.js`);return{attachDebugOverlay:e}},[],import.meta.url),i=r(n,{container:t,statsSource:()=>f.stats?.()??{},...f.captureFrame?{frameSource:()=>y()}:{},...h?{actions:[g]}:{},...e._debugDoc?{doc:e._debugDoc}:{}});i&&o.push(()=>i.dispose())}}let _=e.autoStart!==!1;_&&n.start(),await t(.16,`shaders`);try{f.deferFirstCompile?.();let t=globalThis.performance?.now?.()??0;_&&(n.tick(t),n.tick(t+16)),await f.warmUp?.(t=>{e.onProgress?.(.16+t*.82,`shaders`)})}catch{}o.push(n.settings.bindAudio(n.audio)),o.push(n.settings.bindLocale(n.locale));let v=e=>{dj(n,e)};o.push(n.settings.bindQuality(v)),o.push(n.sceneChanged.connect(()=>{v(_a(n.settings.get(`quality`)))})),o.push(n.settings.bindFrameCap(e=>{n.maxFps=e,f.setFrameTarget?.(e||60)})),o.push(n.settings.bindRenderScale(e=>{f.setRenderScale?.(e)}));let y=()=>{let e=f.captureFrame;if(!e)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);return e.call(f)};o.push(...Sv({engine:n,applyDrive:async e=>{let t=0,r=!0,i=()=>{r&&(t+=1,requestAnimationFrame(i))};requestAnimationFrame(i);let a={engine:n,project:(e,t,n)=>{let r=f.screenFromWorld;return r?r.call(f,e,t,n):null},wait:e=>new Promise(t=>setTimeout(t,e))};for(let t of e)await Mv(a,t);return r=!1,t},captureFramePixels:y,rendererStats:()=>f.stats?.(),assetErrors:()=>f.assets?.errors()??[]})),o.push(Yv(n)),await t(1,`ready`);let b=!1;function x(){b||(b=!0,Xv([[`physics`,()=>a?.dispose()],[`app cleanups`,()=>{for(let e of o)e()}],[`engine`,()=>n.dispose()],[`renderer`,()=>f.dispose()]]))}return{engine:n,get scene(){let e=n.scene;if(!e)throw new L(`TREE_VIOLATION`,`game.scene: the engine has no scene.`);return e},sourceJson:r,renderer:f,physics:a,assetErrors(){return[...f.assets?.errors()??[],...cv(n.scene?.tree.root)]},async frame(e){let t=f.captureFrame;if(!t)throw new L(`TREE_VIOLATION`,`this renderer cannot capture frames`);let n=await t.call(f);return _v(n.pixels,n.width,n.height,e)},pick(e,t){return n.picker?.(e,t)??null},stats(){return{triangles:0,drawCalls:0,geometries:0,textures:0,...n.stats(),...f.stats?.()}},openEditor:h?async()=>{b||await g.run()}:null,dispose:x}}function NH(e){try{return structuredClone(e)}catch{throw new L(`BAD_FORMAT`,`createGame "scene" must be plain scene JSON (the imported *.scene.json object) — got something unclonable (a loaded Scene, class instances, or functions).`)}}function PH(e){if(e instanceof Ib)return!0;for(let t of e.children)if(PH(t))return!0;return!1}function FH(e,t,n){let r=[],i=n;if(i.addEventListener&&r.push({target:i,type:`pointerdown`}),typeof window<`u`){let e=window;r.push({target:e,type:`keydown`}),r.push({target:e,type:`pointerdown`})}if(r.length===0)return()=>{};function a(){for(let e of r)e.target.removeEventListener?.(e.type,o)}function o(){e.sfx.unlock(),e.music.unlock();let n=!1,r=e=>{e instanceof Ua&&(e.retryPending(),e.pendingGesture&&(n=!0));for(let t of e.children)r(t)};r(t),n||a()}for(let e of r)e.target.addEventListener?.(e.type,o,{passive:!0});return a}function IH(e){if(e.behavior?.constructor.name===`Clickable`)return!0;for(let t of e.children)if(IH(t))return!0;return!1}var LH=e({DEFAULT_TERRAIN_TEXTURE_BASE:()=>Kj,WATER_CUTOUT_MAX:()=>4,WATER_MAX_RIPPLES:()=>8,createGame3D:()=>MH,enablePhysics3D:()=>CM}),RH=500,zH=2e3,BH=new WeakMap,VH=class e{account;roomId;roomState=new N;allUserStates=new N;userJoined=new N;userLeft=new N;globalState=new N;globalMyState=new N;asset=new N;latestUserStates={};latestRoomState={};latestGlobalState={};latestGlobalMyState={};latestAsset={};server;engine;throttleMs;keyframeMs;subs=[];messageSignals=new Map;collectionSignals=new Map;latestCollections=new Map;globalMessageSignals=new Map;globalCollectionSignals=new Map;latestGlobalCollections=new Map;scenes=new Map;lastSent=new Map;reportedDeadKeys=new Set;reportDeadSyncKey(e,t){this.reportedDeadKeys.has(t)||this.aliveMs<RH||(this.reportedDeadKeys.add(t),z(e.tree?.engine??null,`error`,`[incanto] ${e.getPath()}: sync key '${t}' reads as undefined — it is never sent, so remote players never see it change. Check the prop name and the node path.`))}sendAccumulator=0;keyframeAccumulator=0;aliveMs=0;detachReplication=null;lastOwner=null;boundScene=null;declaredRoom=null;reportedUnbound=!1;static get(e){return BH.get(e)??null}static async create(t,n={}){await BH.get(t)?.dispose();let r=n.transport??await KH(n.config,t);if(await r.connect()===!1)throw new L(`NETWORK_UNAVAILABLE`,"The multiplayer transport refused to connect, so this game cannot join a room. Check the server is running and reachable; pass `transport` to use a LocalGameServer or LoopbackTransport instead.");let i=n.room??t.scene?.multiplayer?.room??`auto`,a=new e(t,r,await r.remoteFunction(`joinRoom`,[i===`auto`?void 0:i],{needResponse:!0}),n.throttleMs??50,n.keyframeMs??zH);return BH.set(t,a),a}constructor(e,t,n,r,i){this.engine=e,this.server=t,this.roomId=n,this.account=t.account,this.throttleMs=Math.max(30,r),this.keyframeMs=Math.max(0,i),this.boundScene=e.scene,this.declaredRoom=e.scene?.multiplayer?.room,this.subs.push(t.subscribeRoomState(n,e=>{this.latestRoomState=e,this.roomState.emit(e)}),t.subscribeRoomAllUserStates(n,e=>{this.latestUserStates=e,this.allUserStates.emit(e)}),t.onRoomUserJoin(n,e=>this.userJoined.emit(e)),t.onRoomUserLeave(n,e=>this.userLeft.emit(e))),t.subscribeGlobalState&&this.subs.push(t.subscribeGlobalState(e=>{this.latestGlobalState=e,this.globalState.emit(e)})),t.subscribeGlobalMyState&&this.subs.push(t.subscribeGlobalMyState(e=>{this.latestGlobalMyState=e,this.globalMyState.emit(e)})),t.subscribeAsset&&this.subs.push(t.subscribeAsset(this.account,e=>{this.latestAsset=e,this.asset.emit(e)})),this.detachReplication=e.fixedUpdated.connect(e=>this.replicate(e))}message(e){let t=this.messageSignals.get(e);return t||(t=new N,this.messageSignals.set(e,t),this.subs.push(this.server.onRoomMessage(this.roomId,e,e=>t?.emit(e)))),t}collection(e){let t=this.collectionSignals.get(e);return t||(t=new N,this.collectionSignals.set(e,t),this.subs.push(this.server.subscribeRoomCollection(this.roomId,e,n=>{this.latestCollections.set(e,n),t?.emit(n)}))),t}latestCollection(e){return this.collection(e),this.latestCollections.get(e)??{}}globalMessage(e){let t=this.globalMessageSignals.get(e);if(!t){t=new N,this.globalMessageSignals.set(e,t);let n=this.server.onGlobalMessage?.(e,e=>t?.emit(e));n&&this.subs.push(n)}return t}globalCollection(e){let t=this.globalCollectionSignals.get(e);if(!t){t=new N,this.globalCollectionSignals.set(e,t);let n=this.server.subscribeGlobalCollection?.(e,n=>{this.latestGlobalCollections.set(e,n),t?.emit(n)});n&&this.subs.push(n)}return t}latestGlobalCollection(e){return this.globalCollection(e),this.latestGlobalCollections.get(e)??{}}setMyState(e){return this.server.remoteFunction(`setMyState`,[this.roomId,e],{throttle:this.throttleMs,throttleKey:`incanto:myState`})}patchRoomState(e){return this.server.remoteFunction(`patchRoomState`,[this.roomId,e])}addEntity(e,t){return this.server.remoteFunction(`addEntity`,[this.roomId,e,t])}updateEntity(e,t,n){return this.server.remoteFunction(`updateEntity`,[this.roomId,e,t,n])}removeEntity(e,t){return this.server.remoteFunction(`removeEntity`,[this.roomId,e,t])}sendEvent(e,t){return this.server.remoteFunction(`sendEvent`,[this.roomId,e,t])}call(e,...t){return this.server.remoteFunction(e,[this.roomId,...t],{needResponse:!0})}registerScene(e,t){this.scenes.set(e,t)}resolveScene(e){let t=this.scenes.get(e);if(!t)throw new L(`UNRESOLVED_INSTANCE`,`No scene registered for '${e}'. Registered: [${[...this.scenes.keys()].join(`, `)}]. Call manager.registerScene('${e}', sceneJson).`);return t}async dispose(){this.detachReplication?.();for(let e of this.subs)e();await this.server.remoteFunction(`leaveRoom`,[this.roomId]),BH.get(this.engine)===this&&BH.delete(this.engine)}replicate(e){let t=this.engine.scene;if(!t)return;if(t!==this.boundScene){let e=t.multiplayer?.room;if(e===this.declaredRoom)this.boundScene=t,this.lastOwner=null,this.lastSent.clear();else{this.reportedUnbound||(this.reportedUnbound=!0,z(this.engine,`error`,`[incanto] multiplayer: this client stopped broadcasting — the scene changed to '${t.name}', which declares room ${JSON.stringify(e??null)} and this manager is bound to ${JSON.stringify(this.declaredRoom??null)}. Create a new NetworkManager for the new room (incanto-multiplayer.md).`));return}}this.sendAccumulator+=e*1e3,this.aliveMs+=e*1e3;let n=HH(t.root,!0);if(!n)return;n!==this.lastOwner&&(this.lastOwner=n,this.lastSent.clear());let r=n.network,i=Math.max(30,typeof r.throttleMs==`number`?r.throttleMs:this.throttleMs),a=Array.isArray(r.sync)?r.sync:[],o={},s=!1;for(let e of a){let t=WH(n,e);if(t===void 0){this.reportDeadSyncKey(n,e);continue}o[e]=ot(t),at(this.lastSent.get(e)??null,t)||(s=!0)}this.keyframeAccumulator+=e*1e3;let c=this.keyframeMs>0&&this.keyframeAccumulator>=this.keyframeMs;if(!(this.sendAccumulator<i)&&!(!s&&!c)&&Object.keys(o).length!==0){for(let[e,t]of Object.entries(o))this.lastSent.set(e,ot(t));this.keyframeAccumulator=0,this.sendAccumulator=0,this.setMyState({sync:o}).catch(e=>{this.engine._asyncFailed(`${n.getPath()}: replication to room '${this.roomId}' failed — this client is no longer visible to the others`,e)})}}};function HH(e,t=!1){let n=[];if(UH(e,n),t&&n.length>1)throw new L(`BAD_FORMAT`,`Multiple network owner nodes found (${n.map(e=>e.getPath()).join(`, `)}). Exactly ONE node per player may declare network.mode 'owner' — replicate spawned entities through collections instead.`);return n[0]??null}function UH(e,t){e.network?.mode===`owner`&&t.push(e);for(let n of e.children)UH(n,t)}function WH(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:e.getNodeOrNull(t.slice(0,n))??void 0,i=n===-1?t:t.slice(n+1);if(!r)return;let a=r[i];return a instanceof Set?[...a]:a}function GH(e,t,n,r){for(let[i,a]of Object.entries(t)){let t=i.lastIndexOf(`.`),o=t===-1?e:e.getNodeOrNull(i.slice(0,t)),s=t===-1?i:i.slice(t+1);o?n(o,s,a):r?.(i)}}async function KH(e,t){let{createAgent8Server:n}=await Iv(async()=>{let{createAgent8Server:e}=await import(`./agent8-q_2WV8pw.js`);return{createAgent8Server:e}},[],import.meta.url);return n(e,t)}var qH=new Set([`__id`,`__roomId`,`__updated`,`__leaved`,`account`,`roomId`]),JH=class extends Ht{static typeName=`NetworkSpawner`;static signals=[`spawned`,`despawned`];static props={source:{default:`users`},scene:{default:``,required:!0},interpolate:{default:!0}};source=`users`;scene=``;interpolate=!0;spawned=new Map;positionTargets=new Map;failedKeys=new Set;reported=new Set;waited=0;update(e){let t=this.tree?.engine;if(!t)return;let n=VH.get(t);if(!n){this.waited+=e,this.waited>2&&this.report(`there is no multiplayer in this game`);return}let r=this.currentEntries(n);for(let[e,t]of Object.entries(r)){let r=this.spawned.get(e),i=this.patchOf(t);if(!r){if(this.failedKeys.has(e)||!i)continue;try{let e=n.resolveScene(this.scene);r=Si({...e,root:qi(e.root)},Yi(this)),Xi(r),Zi(r)}catch(t){throw this.failedKeys.add(e),t}r.name=YH(e),this.addChild(r),this.spawned.set(e,r),this.emit(`spawned`,r,e)}i&&GH(r,i,(e,t,n)=>this.setProp(e,t,n),e=>this.report(`'${e}' names a node this scene does not have`))}for(let[e,t]of[...this.spawned.entries()])e in r||(this.spawned.delete(e),this.positionTargets.delete(t),this.emit(`despawned`,t,e),t.free());this.interpolate&&this.stepInterpolation(e)}currentEntries(e){if(this.source===`users`){let t={};for(let[n,r]of Object.entries(e.latestUserStates))n!==e.account&&(t[n]=r);return t}return this.source.startsWith(`collection:`)?e.latestCollection(this.source.slice(11)):{}}patchOf(e){if(e.sync!==void 0)return e.sync;if(this.source===`users`)return;let t={};for(let[n,r]of Object.entries(e))qH.has(n)||n.startsWith(`$`)||(t[n]=r);return Object.keys(t).length>0?t:void 0}report(e){this.reported.has(e)||(this.reported.add(e),z(this.tree?.engine??null,`error`,`[incanto] NetworkSpawner '${this.name}': ${e} — that value replicates to nothing.`))}setProp(e,t,n){if(this.interpolate&&t===`position`&&Array.isArray(n)){this.positionTargets.has(e)||(e.position=[...n]),this.positionTargets.set(e,n);return}if(t===`position`&&Array.isArray(e.position)){this.report(`'position' arrived as ${JSON.stringify(n)} — a node position is a number array`);return}if(t===`groups`){if(Array.isArray(n))for(let t of n)typeof t==`string`&&e.addToGroup(t);return}try{e[t]=n}catch(n){this.reported.has(`prop:${t}`)||(this.reported.add(`prop:${t}`),z(this.tree?.engine,`error`,`[incanto] NetworkSpawner on '${this.getPath()}': replicated key '${t}' cannot be written onto a '${e.constructor.typeName??`Node`}' — it is a readonly accessor, not a prop. Sync a real prop, or a plain data key of your own.`,n))}}replicatedPosition(e){return this.positionTargets.get(e)}stepInterpolation(e){let t=this.tree?.engine?.unscaledDelta||e,n=Math.min(1,t*8);for(let[e,t]of this.positionTargets){let r=e.position;if(!Array.isArray(r)){e.position=[...t];continue}e.position=r.map((e,r)=>e+((t[r]??e)-e)*n)}}};function YH(e){return e.replace(/[/%]/g,`_`)||`remote`}function XH(){No(),R(JH)}function ZH(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}var QH=ZH()?.getItem(`incanto-editor-lang`)??`en`,$H=new Set;function eU(){return QH}function tU(e){QH=e,ZH()?.setItem(`incanto-editor-lang`,e);for(let e of $H)e()}function nU(e){$H.add(e)}function rU(e){return e[QH]}var iU={node:{paths:[`M5 5h14v14H5z`]},move:{paths:[`M12 3v18M3 12h18`,`M8 7l4-4 4 4M8 17l4 4 4-4M7 8l-4 4 4 4M17 8l4 4-4 4`]},image:{paths:[`M4 5h16v14H4z`,`M4 15l5-5 4 4 3-3 4 4`],circles:[[9,9,1.6]]},film:{paths:[`M4 4h16v16H4z`,`M4 9h16M4 15h16`,`M9 4v16M15 4v16`]},video:{paths:[`M3 7h12v10H3z`,`M15 10l6-3v10l-6-3`]},text:{paths:[`M5 7V5h14v2`,`M12 5v14`,`M9 19h6`]},layers:{paths:[`M12 3 3 8l9 5 9-5-9-5z`,`M3 12l9 5 9-5`,`M3 16l9 5 9-5`]},square:{paths:[`M5 5h14v14H5z`,`M5 12h14`]},ball:{paths:[`M12 8v0`],circles:[[12,12,8],[12,12,1.4]]},person:{paths:[`M5 21v-1a7 7 0 0 1 14 0v1`],circles:[[12,7,4]]},area:{paths:[`M5 5h14v14H5z`],dashed:!0},gamepad:{paths:[`M7 9h-0M6 12h4M8 10v4`,`M4 8h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2z`],circles:[[16,11,1],[18.5,13.5,1]]},clock:{paths:[`M12 7v5l3 2`],circles:[[12,12,9]]},cube:{paths:[`M21 16V8l-9-5-9 5v8l9 5 9-5z`,`M3.3 7.5 12 12.5l8.7-5`,`M12 22V12.5`]},sun:{paths:[`M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9 17 7M7 17l-2.1 2.1`],circles:[[12,12,4]]},bulb:{paths:[`M9 18h6M10 21h4`,`M8 13a6 6 0 1 1 8 0c-1 1-1.5 2-1.5 3h-5c0-1-.5-2-1.5-3z`]},spot:{paths:[`M10 3h4l1 4H9z`,`M9 7L4 20h16L15 7`,`M8 15h8`]},globe:{paths:[`M2 12h20`,`M12 2a15 15 0 0 1 0 20a15 15 0 0 1 0-20z`],circles:[[12,12,10]]},link:{paths:[`M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1`,`M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1`]},speaker:{paths:[`M11 5 6 9H3v6h3l5 4V5z`,`M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13`]},swatch:{paths:[`M4 4h16v16H4z`,`M4 4l16 16`]},sparkles:{paths:[`M12 4v5M12 15v5M5 12h5M14 12h5`],circles:[[6,5,1],[18,19,1]]},waves:{paths:[`M2 8c3-3 5 3 8 0s5 3 8 0`,`M2 14c3-3 5 3 8 0s5 3 8 0`,`M2 20c3-3 5 3 8 0s5 3 8 0`]},plant:{paths:[`M12 21v-8`,`M12 13c0-4-3-6-7-6 0 4 3 6 7 6z`,`M12 11c0-4 3-6 7-6 0 4-3 6-7 6z`]},flower:{paths:[`M12 21v-7`],circles:[[12,9,2],[12,4.5,2.2],[16.3,7.5,2.2],[14.7,12.6,2.2],[9.3,12.6,2.2],[7.7,7.5,2.2]]},voxels:{paths:[`M4 14h8v8H4z`,`M12 14h8v8h-8z`,`M8 6h8v8H8z`]}},aU={Node:`node`,Timer:`clock`,AudioPlayer:`speaker`,ColorRect2D:`swatch`,Particles2D:`sparkles`,Particles3D:`sparkles`,Weather3D:`sparkles`,Flock3D:`sparkles`,Water3D:`waves`,UiMinimap:`globe`,UiWaypoint:`move`,Foliage3D:`plant`,Flowers3D:`flower`,VoxelGrid3D:`voxels`,ModelInstance3D:`person`,CharacterController3D:`gamepad`,Ragdoll3D:`person`,Vehicle3D:`move`,Node2D:`move`,Sprite2D:`image`,AnimatedSprite2D:`film`,Camera2D:`video`,Label:`text`,UILayer:`layers`,StaticBody2D:`square`,RigidBody2D:`ball`,CharacterBody2D:`person`,Area2D:`area`,CharacterController2D:`gamepad`,Node3D:`move`,Billboard3D:`layers`,MeshInstance3D:`cube`,LoftMesh3D:`cube`,Camera3D:`video`,DirectionalLight3D:`sun`,OmniLight3D:`bulb`,SpotLight3D:`spot`,StaticBody3D:`square`,RigidBody3D:`ball`,CharacterBody3D:`person`,Area3D:`area`,NetworkSpawner:`globe`};function oU(e){let t=iU[aU[e??``]??(e?`node`:`link`)],n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`width`,`13`),n.setAttribute(`height`,`13`),n.setAttribute(`fill`,`none`),n.setAttribute(`stroke`,`currentColor`),n.setAttribute(`stroke-width`,`2`),n.setAttribute(`stroke-linecap`,`round`),n.setAttribute(`stroke-linejoin`,`round`),t.dashed&&n.setAttribute(`stroke-dasharray`,`3 2.4`);for(let e of t.paths){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`d`,e),n.appendChild(t)}for(let[e,r,i]of t.circles??[]){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);t.setAttribute(`cx`,String(e)),t.setAttribute(`cy`,String(r)),t.setAttribute(`r`,String(i)),n.appendChild(t)}return n}function sU(){let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);e.setAttribute(`viewBox`,`0 0 24 24`),e.setAttribute(`width`,`12`),e.setAttribute(`height`,`12`),e.setAttribute(`fill`,`none`),e.setAttribute(`stroke`,`currentColor`),e.setAttribute(`stroke-width`,`2.4`),e.setAttribute(`aria-hidden`,`true`);let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`d`,`m6 9 6 6 6-6`),e.appendChild(t),e}var cU=[{type:`texture`,label:`image (texture)`,metaHints:[`filter`]},{type:`spritesheet`,label:`spritesheet`,metaHints:[`filter`,`frameWidth`,`frameHeight`]},{type:`model`,label:`3D model (GLB/VRM)`,metaHints:[]},{type:`animation`,label:`animation (GLB clips)`,metaHints:[`clip`]}],lU=new Set,uU=null,dU=null;function fU(e,t,n){let r=document.createElement(`input`);r.className=`rename-input`,r.value=e;let i=()=>{let i=r.value.trim().replace(/\//g,``);i&&i!==e?t(i):n()};r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`/`&&e.preventDefault(),e.key===`Enter`&&i(),e.key===`Escape`&&n()});for(let e of[`click`,`pointerdown`,`dblclick`,`mousedown`])r.addEventListener(e,e=>e.stopPropagation());return r.addEventListener(`blur`,i),queueMicrotask(()=>{r.focus(),r.select()}),r}function pU(e,t){let n={path:``,name:``,folders:new Map,assets:[]},r=e=>{let t=n;if(e===``)return t;for(let n of e.split(`/`)){let e=t.folders.get(n);e||(e={path:t.path?`${t.path}/${n}`:n,name:n,folders:new Map,assets:[]},t.folders.set(n,e)),t=e}return t};for(let t of e){let e=t.lastIndexOf(`/`);r(e===-1?``:t.slice(0,e)).assets.push(t)}for(let e of t)r(e);return n}function mU(e){let t=e.assets.length;for(let n of e.folders.values())t+=mU(n);return t}function hU(e,t){e.textContent=``;let n=t.working.assets??{},r=Object.keys(n);if(r.length===0&&t.pendingGroups.size===0&&!t.addingAsset&&!t.addingGroup){let t=document.createElement(`div`);t.className=`muted-note explorer-empty`,t.textContent=`no assets yet — + adds textures, models, animations`,e.appendChild(t);return}let i=(e,n)=>{e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.add(`drop-target`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-target`)),e.addEventListener(`drop`,r=>{r.preventDefault(),r.stopPropagation(),e.classList.remove(`drop-target`);let i=r.dataTransfer?.getData(`text/incanto-asset`);i&&t.moveAsset(i,n);let a=r.dataTransfer?.getData(`text/incanto-group`);a&&t.moveGroup(a,n)})};i(e,``);let a=(e,r)=>{let i=n[e],a=e.includes(`/`)?e.slice(e.lastIndexOf(`/`)+1):e,o=t.assetErrors.get(e),s=document.createElement(`div`);s.className=`tree-row asset-row${t.selectedAsset===e?` selected`:``}${o===void 0?``:` asset-failed`}`,o!==void 0&&(s.title=`failed to load: ${o}`),s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.dataTransfer?.setData(`text/incanto-asset`,e)});let c=document.createElement(`span`);if(c.className=`tree-icon`,c.appendChild(jU(i.type??``)),c.addEventListener(`click`,e=>{e.stopPropagation(),MU(c,i.type??``)}),uU===e){let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)+1):``;s.appendChild(fU(a,r=>{uU=null,t.renameAssetKey(e,n+r)},()=>{uU=null,t.selectAsset(t.selectedAsset)})),s.draggable=!1,s.insertBefore(c,s.firstChild),r.appendChild(s);return}let l=document.createElement(`span`);l.className=`tree-name asset-key`,l.textContent=`$${a}`,l.title=o===void 0?`$${e}`:`$${e} — failed to load: ${o}`,l.addEventListener(`dblclick`,n=>{n.stopPropagation(),uU=e,t.selectAsset(e)}),s.append(c,l),s.addEventListener(`click`,()=>t.selectAsset(e)),r.appendChild(s)},o=(e,n)=>{let r=lU.has(e.path),s=document.createElement(`div`);s.className=`asset-folder${r?` collapsed`:``}${t.selectedGroup===e.path?` selected`:``}`,s.draggable=!0,s.addEventListener(`dragstart`,t=>{t.stopPropagation(),t.dataTransfer?.setData(`text/incanto-group`,e.path)});let c=document.createElement(`span`);c.className=`chev`,c.appendChild(sU());let l=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);l.setAttribute(`viewBox`,`0 0 24 24`),l.setAttribute(`width`,`12`),l.setAttribute(`height`,`12`),l.setAttribute(`fill`,`none`),l.setAttribute(`stroke`,`currentColor`),l.setAttribute(`stroke-width`,`1.8`),l.setAttribute(`aria-hidden`,`true`);let u=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);if(u.setAttribute(`d`,`M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`),l.appendChild(u),dU===e.path){let i=e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)+1):``;if(s.append(c,l,fU(e.name,n=>{dU=null,t.renameGroup(e.path,i+n)},()=>{dU=null,t.selectGroup(t.selectedGroup)})),s.draggable=!1,n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}return}let d=document.createElement(`span`);d.textContent=e.name,d.addEventListener(`dblclick`,n=>{n.stopPropagation(),dU=e.path,t.selectGroup(e.path)});let f=document.createElement(`span`);if(f.className=`count`,f.textContent=`(${mU(e)})`,s.append(c,l,d,f),s.addEventListener(`click`,()=>{lU.has(e.path)?lU.delete(e.path):lU.add(e.path),t.selectGroup(e.path)}),i(s,e.path),n.appendChild(s),!r){let t=document.createElement(`div`);t.className=`tree-children`;for(let n of e.folders.values())o(n,t);for(let n of e.assets)a(n,t);t.children.length>0&&n.appendChild(t)}},s=pU(r,t.pendingGroups);for(let t of s.assets)a(t,e);for(let t of s.folders.values())o(t,e)}function gU(e,t,n,r){if(t.selection!==null)return!1;if(t.addingGroup){e.appendChild(IU(t.newGroupParent?`NEW GROUP IN ${t.newGroupParent}/`:`NEW GROUP`));let n=document.createElement(`input`);n.placeholder=t.newGroupParent?`heroes`:`characters (or a/b to nest)`,n.className=`mono`,e.appendChild(EU(`name`,n));let r=document.createElement(`button`);r.type=`button`,r.className=`primary`,r.textContent=`add`;let i=()=>{let e=n.value.trim().replace(/^\/+|\/+$/g,``);e&&(t.cancelAddForms(),t.addGroup(t.newGroupParent?`${t.newGroupParent}/${e}`:e))};r.addEventListener(`click`,i),n.addEventListener(`keydown`,e=>{e.key===`Enter`&&i()});let a=document.createElement(`div`);return a.className=`pop-actions`,a.appendChild(r),e.appendChild(a),setTimeout(()=>n.focus(),0),!0}if(t.addingAsset)return bU(e,t,r);if(t.selectedGroup!==null){let r=t.selectedGroup,i=t.groupCount(r);e.appendChild(IU(`GROUP (${i} asset${i===1?``:`s`})`));let a=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)+1):``,o=r.includes(`/`)?r.slice(r.lastIndexOf(`/`)+1):r;e.appendChild(DU(`name`,o,e=>{let n=e.trim().replace(/\/+/g,``);n&&n!==o&&t.renameGroup(r,a+n)}));let s=document.createElement(`button`);return s.type=`button`,s.className=`ghost danger`,s.textContent=`delete group`,s.addEventListener(`click`,()=>{if(i===0){t.deleteGroup(r);return}n(`'${r}/' contains ${i} asset${i===1?``:`s`} — deleting the group deletes them too.`,`delete group & assets`,()=>t.deleteGroup(r))}),e.appendChild(s),!0}let i=t.selectedAsset;if(i===null)return!1;let a=t.working.assets??{};if(!(i in a))return!1;e.appendChild(IU(`ASSET — ${String(a[i].type??`?`)}`)),e.appendChild(NU(i)),e.appendChild(PU(t,i)),e.appendChild(_U(t,a,i,r));let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost danger`,o.textContent=`delete asset`,o.addEventListener(`click`,()=>{t.selectAsset(null),t.mutate(()=>{delete a[i],Object.keys(a).length===0&&delete t.working.assets})}),e.appendChild(o),!0}function _U(e,t,n,r){let i=t[n],a=document.createElement(`div`);a.className=`asset-editor`;let o=n.includes(`/`)?n.slice(n.lastIndexOf(`/`)+1):n,s=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)+1):``,c=DU(`name`,o,t=>{let r=t.trim().replace(/^\$/,``).replace(/\//g,``);r&&r!==o&&e.renameAssetKey(n,s+r)});FU(c.querySelector(`input`)),a.appendChild(c);let l=DU(`url`,String(i.url??``),t=>{e.mutate(()=>{i.url=t.trim()})}),u=l.querySelector(`input`);if(r&&u){let t=SU(String(i.type??``));l.classList.add(`has-lib`),l.appendChild(TU(()=>t,`asset url`,r,t=>{u.value=t,e.mutate(()=>{i.url=t})},()=>wU(t,e,String(i.type??``)),()=>String(i.type??``)||void 0))}a.appendChild(l);let d=e.assetErrors.get(n);if(d!==void 0){let e=document.createElement(`div`);e.className=`conn-warn`,e.textContent=`failed to load — every node using $${n} draws nothing. Check the url: ${d}`,a.appendChild(e)}let f=document.createElement(`div`);f.className=`muted-note`,f.textContent=`meta (key · value)`,a.appendChild(f);for(let[t,n]of Object.entries(i))t===`type`||t===`url`||a.appendChild(vU(e,i,t,n));return a.appendChild(yU(e,i)),a}function vU(e,t,n,r){let i=document.createElement(`div`);i.className=`meta-row`;let a=document.createElement(`input`);a.value=n,a.className=`mono`;let o=document.createElement(`input`);o.value=typeof r==`string`?r:JSON.stringify(r),o.className=`mono`;let s=()=>{let r=a.value.trim();e.mutate(()=>{delete t[n],r&&(t[r]=OU(o.value))})};a.addEventListener(`change`,s),o.addEventListener(`change`,s);let c=document.createElement(`button`);return c.type=`button`,c.className=`linklike danger-link`,c.textContent=`✕`,c.addEventListener(`click`,()=>{e.mutate(()=>{delete t[n]})}),i.append(a,o,c),i}function yU(e,t){let n=document.createElement(`div`);n.className=`meta-row`;let r=document.createElement(`input`);r.placeholder=`filter…`,r.className=`mono`;let i=document.createElement(`input`);i.placeholder=`nearest`,i.className=`mono`;let a=()=>{let n=r.value.trim();!n||i.value.trim()===``||e.mutate(()=>{t[n]=OU(i.value)})};return r.addEventListener(`change`,a),i.addEventListener(`change`,a),n.append(r,i,document.createElement(`span`)),n}function bU(e,t,n){return e.appendChild(IU(`NEW ASSET`)),e.appendChild(xU(t,n)),!0}function xU(e,t){let n=document.createElement(`div`);n.className=`asset-editor`;let r=document.createElement(`select`);for(let e of cU){let t=document.createElement(`option`);t.value=e.type,t.textContent=e.label,r.appendChild(t)}n.appendChild(EU(`type`,r));let i=document.createElement(`input`);i.placeholder=`(optional) characters`,i.className=`mono`,i.value=e.newAssetGroup;let a=`asset-groups-list`;i.setAttribute(`list`,a);let o=document.createElement(`datalist`);o.id=a;let s=new Set;for(let t of Object.keys(e.working.assets??{})){let e=t.lastIndexOf(`/`);e!==-1&&s.add(t.slice(0,e))}for(let t of e.pendingGroups)s.add(t);for(let e of s){let t=document.createElement(`option`);t.value=e,o.appendChild(t)}n.appendChild(EU(`group`,i)),n.appendChild(o);let c=document.createElement(`input`);c.placeholder=`coin`,c.className=`mono`,FU(c),n.appendChild(EU(`key`,c));let l=document.createElement(`input`);l.placeholder=`/textures/coin.png · https://… · data:…`,l.className=`mono`;let u=EU(`url`,l);t&&(u.classList.add(`has-lib`),u.appendChild(TU(()=>SU(r.value),`new asset`,t,e=>{l.value=e,c.value.trim()||(c.value=CU(e))},()=>wU(SU(r.value),e,r.value),()=>r.value||void 0))),n.appendChild(u);let d=document.createElement(`textarea`);d.rows=2,d.placeholder=`or paste a JSON object: { "type": "model", "url": "/m.glb" }`,n.appendChild(d);let f=document.createElement(`button`);f.type=`button`,f.className=`primary`,f.textContent=`add`,f.addEventListener(`click`,()=>{let t=c.value.trim().replace(/^\$/,``);if(!t)return;let n=i.value.trim().replace(/\/+$/,``),a=n?`${n}/${t}`:t,o=null,s=d.value.trim();if(s)try{o=JSON.parse(s)}catch{d.classList.add(`invalid`);return}else l.value.trim()&&(o={type:r.value,url:l.value.trim()});o&&(e.cancelAddForms(),e.selectedAsset=a,e.mutate(()=>{e.working.assets||(e.working.assets={});let t=e.working.assets;t[a]=o}))});let p=document.createElement(`div`);return p.className=`pop-actions`,p.appendChild(f),n.appendChild(p),n}function SU(e){return e===`model`||e===`animation`?`model`:e===`audio`?`audio`:e===`texture`||e===`spritesheet`?`image`:`any`}function CU(e){return((e.split(/[?#]/)[0]??``).split(`/`).pop()??``).replace(/\.[^.]+$/,``).replace(/[^a-zA-Z0-9_-]+/g,`_`).replace(/_{2,}/g,`_`).replace(/^_+|_+$/g,``).toLowerCase()||`asset`}function wU(e,t,n){if(n===`animation`)return[`3d`,`animations`];let r=(t.working.dimension??`2d`)===`3d`;if(e===`image`)return r?[`3d`,`textures`]:[`2d`,`sprite_characters`];if(e===`model`)return[`3d`,`characters`]}function TU(e,t,n,r,i,a){let o=document.createElement(`button`);return o.type=`button`,o.className=`asset-lib`,o.textContent=`📚 library`,o.title=`Browse the agent8 asset library`,o.addEventListener(`click`,o=>{o.preventDefault();let s=i?.(),c=a?.();n({kind:e(),target:t,...s?{shelf:s}:{},...c?{assetType:c}:{}}).then(e=>{e&&r(e)})}),o}function EU(e,t){let n=document.createElement(`label`);n.className=`field`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n}function DU(e,t,n){let r=document.createElement(`input`);return r.value=t,r.className=`mono`,r.addEventListener(`change`,()=>n(r.value)),EU(e,r)}function OU(e){let t=e.trim();if(t===`true`)return!0;if(t===`false`)return!1;if(t!==``&&Number.isFinite(Number(t)))return Number(t);if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.parse(t)}catch{return e}return e}var kU={texture:`M3 5h18v14H3z M3 15l5-5 4 4 3-3 6 6 M8.5 9.5h.01`,spritesheet:`M3 4h18v16H3z M9 4v16 M15 4v16 M3 12h18`,model:`M12 2l9 5v10l-9 5-9-5V7z M12 12l9-5 M12 12L3 7 M12 12v10`,animation:`M12 2a10 10 0 1 0 10 10 M22 12l-3-3m3 3l3-3 M12 7v5l3 3`},AU={texture:{en:`image (texture) — Sprite2D.texture references it as "$key".`,ko:`이미지(텍스처) — Sprite2D.texture에서 "$키"로 참조합니다.`},spritesheet:{en:`spritesheet — AnimatedSprite2D slices it into named frame animations.`,ko:`스프라이트시트 — AnimatedSprite2D가 이름 붙은 프레임 애니메이션으로 자릅니다.`},model:{en:`3D model (GLB/glTF/VRM) — ModelInstance3D.model references it as "$key".`,ko:`3D 모델(GLB/glTF/VRM) — ModelInstance3D.model에서 "$키"로 참조합니다.`},animation:{en:`animation clips (GLB, in memory — drawn nowhere) — any model can play them; mixamo retargets onto VRM.`,ko:`애니메이션 클립(GLB, 메모리 전용 — 그려지지 않음) — 어떤 모델이든 재생 가능, mixamo는 VRM에 자동 리타게팅.`}};function jU(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);t.setAttribute(`viewBox`,`0 0 24 24`),t.setAttribute(`width`,`13`),t.setAttribute(`height`,`13`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke`,`currentColor`),t.setAttribute(`stroke-width`,`1.8`),t.setAttribute(`aria-hidden`,`true`);let n=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return n.setAttribute(`d`,kU[e]??`M4 4h16v16H4z`),t.appendChild(n),t.classList.add(`asset-icon-${e}`),t}function MU(e,t){document.querySelector(`.balloon`)?.remove();let n=AU[t];if(!n)return;let r=document.createElement(`div`);r.className=`balloon floating`;let i=document.createElement(`div`);i.className=`balloon-title`,i.textContent=t;let a=document.createElement(`span`);a.textContent=rU(n),r.append(i,a),document.body.appendChild(r);let o=e.getBoundingClientRect();r.style.left=`${o.right+8}px`,r.style.top=`${Math.max(8,o.top-8)}px`;let s=()=>{r.remove(),document.removeEventListener(`pointerdown`,s,!0)};setTimeout(()=>document.addEventListener(`pointerdown`,s,!0),0)}function NU(e){let t=document.createElement(`div`);t.className=`field uid-line`;let n=document.createElement(`span`);n.textContent=`key`;let r=document.createElement(`div`);r.className=`uid-value`;let i=document.createElement(`code`);i.textContent=`$${e}`;let a=document.createElement(`button`);return a.type=`button`,a.className=`uid-copy`,a.title=`Copy key`,a.innerHTML=`<svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,a.addEventListener(`click`,()=>{navigator.clipboard?.writeText(`$${e}`),a.classList.add(`copied`),setTimeout(()=>a.classList.remove(`copied`),600)}),r.append(i,a),t.append(n,r),t}function PU(e,t){let n=t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``,r=document.createElement(`select`),i=new Set([``]);for(let t of Object.keys(e.working.assets??{})){let e=t.split(`/`);for(let t=1;t<e.length;t++)i.add(e.slice(0,t).join(`/`))}for(let t of e.pendingGroups)i.add(t);for(let e of[...i].sort()){let t=document.createElement(`option`);t.value=e,t.textContent=e===``?`(root)`:`${e}/`,e===n&&(t.selected=!0),r.appendChild(t)}r.addEventListener(`change`,()=>{e.moveAsset(t,r.value)});let a=document.createElement(`label`);a.className=`field`;let o=document.createElement(`span`);return o.textContent=`group`,a.append(o,r),a}function FU(e){e&&(e.addEventListener(`keydown`,e=>{e.key===`/`&&e.preventDefault()}),e.addEventListener(`input`,()=>{e.value.includes(`/`)&&(e.value=e.value.replace(/\//g,``))}))}function IU(e){let t=document.createElement(`div`);t.className=`section-title`,t.textContent=e;let n=document.createElement(`span`);return n.className=`rule`,t.appendChild(n),t}function LU(e,t){if(e.mode===`project`&&e.hasScene)return{open:`in-hand`};let n=t.filter(e=>e.scene);return n.length===1?{open:`only`,entry:n[0]}:{open:`picker`}}var RU=window.parent!==window,zU=new URLSearchParams(window.location.search).get(`parentOrigin`),BU=!1;function VU(e){if(RU){if(!zU){BU||(BU=!0,console.warn(`incanto-editor: embedded without ?parentOrigin=<origin> — postMessage disabled`));return}window.parent.postMessage(e,zU)}}var HU={ready(e,t,n){VU({type:`incanto-editor:ready`,input:e,output:t,version:n})},open(e,t){VU({type:`incanto-editor:open`,input:e,output:t})},change(e){VU({type:`incanto-editor:change`,dirty:e})},save(e,t,n){VU({type:`incanto-editor:save`,input:e,output:t,data:n})},error(e){VU({type:`incanto-editor:error`,message:e})}},UU=[[`Core`,e=>!e.endsWith(`2D`)&&!e.endsWith(`3D`)&&e!==`Label`&&e!==`UILayer`&&e!==`NetworkSpawner`],[`2D`,e=>e.endsWith(`2D`)&&!/Body|Area|Controller/.test(e)||e===`Label`||e===`UILayer`],[`2D Physics`,e=>e.endsWith(`2D`)&&/Body|Area|Controller/.test(e)],[`3D`,e=>e.endsWith(`3D`)&&!/Body|Area|Controller/.test(e)],[`3D Physics`,e=>e.endsWith(`3D`)&&/Body|Area|Controller/.test(e)],[`Network`,e=>e===`NetworkSpawner`]],WU=[...UU,[`Other`,e=>UU.every(([,t])=>!t(e))]],GU={title:{en:`How Incanto scenes work`,ko:`Incanto 씬은 어떻게 동작하나`},sections:[{heading:{en:`Everything is a node in a tree`,ko:`모든 것은 트리 위의 노드`},text:{en:`A scene is ONE tree of typed nodes (Godot-style). Each node has a name (unique among its siblings), a type that defines its props and behavior, optional children, and an optional scene-wide-unique uid. The whole structure lives in a *.scene.json file — there is no hidden state: what you see in this editor IS the file.`,ko:`씬은 타입을 가진 노드들의 단일 트리입니다(Godot 방식). 각 노드는 이름(형제 간 유일), props와 동작을 결정하는 타입, 선택적 자식들, 그리고 선택적인 씬 전역 유일 uid를 가집니다. 전체 구조가 *.scene.json 파일 하나에 들어있고 숨겨진 상태는 없습니다 — 이 에디터에서 보는 것이 곧 파일 그 자체입니다.`}},{heading:{en:`Props are delta-only`,ko:`Props는 변경분만 기록`},text:{en:`Every prop has a default defined by the engine. The JSON only stores values that DIFFER from the default — so files stay small and diffs stay meaningful. This editor follows the same rule: set a value back to its default and it disappears from the file.`,ko:`모든 prop에는 엔진이 정의한 기본값이 있습니다. JSON에는 기본값과 다른 값만 기록되어 파일이 작고 diff가 의미를 가집니다. 이 에디터도 같은 규칙을 따릅니다 — 값을 기본값으로 되돌리면 파일에서 사라집니다.`}},{heading:{en:`Addressing: paths, names, uid, groups`,ko:`노드 찾기: 경로·이름·uid·그룹`},text:{en:`Code reaches nodes four ways: a path like "Player/Skin" (relative) or "%Unique" (marked-unique name), getNodesByName("Enemy") which returns a LIST (names repeat across the tree), getNodeByUid("n_x1y2") which returns exactly one node and survives moves/renames, and groups — free tags for queries like "every coin".`,ko:`코드는 네 가지 방법으로 노드에 접근합니다: "Player/Skin" 같은 경로(상대) 또는 "%Unique"(유일 표시 이름), 트리 전체에서 같은 이름을 모두 찾는 getNodesByName("Enemy") — 이름은 중복될 수 있어 리스트가 돌아옵니다 —, 정확히 한 노드를 돌려주고 이동/개명에도 살아남는 getNodeByUid("n_x1y2"), 그리고 "모든 코인"처럼 묶어 조회하는 자유 태그 groups.`}},{heading:{en:`Signals connect, behaviors act`,ko:`시그널로 잇고 비헤이비어로 움직인다`},text:{en:`Nodes emit signals (an Area2D fires triggerEnter, a Timer fires timeout). The scene's "connections" wire a signal to a handler — declaratively, in JSON. Game logic itself is a Behavior: a TypeScript class in YOUR game, attached by name via "script". The inspector's CONNECTIONS section shows and edits these links on the selected node — what it emits, what reaches it, and any end that no longer resolves. The handler code itself lives in your game.`,ko:`노드는 시그널을 발산합니다(Area2D의 triggerEnter, Timer의 timeout). 씬의 "connections"가 시그널을 핸들러에 선언적으로(JSON으로) 연결합니다. 게임 로직 자체는 Behavior — 게임 쪽 TypeScript 클래스이며 "script"에 이름으로 연결됩니다. 인스펙터의 CONNECTIONS 섹션이 선택한 노드의 연결을 보여주고 편집합니다 — 나가는 것, 들어오는 것, 그리고 더 이상 찾을 수 없는 끝. 핸들러 코드 자체는 게임에 있습니다.`}},{heading:{en:`Assets are declared, then referenced`,ko:`에셋은 선언하고 $키로 참조`},text:{en:`The scene header declares assets (textures, spritesheets, 3D models, animation clips) under a key; nodes reference them as "$key". Animations are data too: an {type:"animation"} asset loads GLB clips into memory and any ModelInstance3D can play them — Mixamo clips retarget onto VRM avatars automatically.`,ko:`씬 헤더에서 에셋(텍스처·스프라이트시트·3D 모델·애니메이션 클립)을 키로 선언하고, 노드는 "$key"로 참조합니다. 애니메이션도 데이터입니다 — {type:"animation"} 에셋이 GLB 클립을 메모리에 올리고 어떤 ModelInstance3D든 재생할 수 있으며, Mixamo 클립은 VRM 아바타에 자동 리타게팅됩니다.`}}]},Q=(e,t,...n)=>({type:e,summary:t,body:n}),KU=[{id:`core`,label:{en:`Core`,ko:`Core`},intro:{en:`Dimension-free building blocks: plain containers and the game clock. They render nothing themselves.`,ko:`차원과 무관한 기본 블록 — 순수 컨테이너와 게임 시계입니다. 스스로는 아무것도 그리지 않습니다.`},nodes:[Q(`Node`,{en:`A plain container with no transform.`,ko:`변환 없이 자식을 묶는 순수 컨테이너.`},{en:`Use it to group related nodes (all coins, all UI) without affecting their positions. Lifecycle, signals, groups, script — everything works; it just has no visual or spatial meaning of its own.`,ko:`위치에 영향을 주지 않으면서 관련 노드(코인 전부, UI 전부)를 묶을 때 씁니다. 라이프사이클·시그널·그룹·스크립트가 모두 동작하며, 시각적·공간적 의미만 없습니다.`}),Q(`Timer`,{en:"A serializable countdown that emits `timeout`.",ko:"`timeout` 시그널을 쏘는 직렬화 가능한 카운트다운."},{en:`Set waitTime (seconds), optionally autostart or oneShot, and connect its timeout signal to any handler. Because it is a node, the whole timing setup lives in the scene file — agents can read and tune it.`,ko:`waitTime(초)을 정하고 autostart·oneShot을 선택한 뒤 timeout 시그널을 핸들러에 연결하세요. 노드이기 때문에 타이밍 설정 전체가 씬 파일에 남아 에이전트가 읽고 조정할 수 있습니다.`}),Q(`Respawn`,{en:`Catches whatever it hangs off when it leaves the world, and puts it back.`,ko:`부모가 월드 밖으로 떨어지면 붙잡아 원래 자리로 되돌립니다.`},{en:`Make it a child of the player. With no props it catches its parent 50 m under the spawn (1000 px in 2D — the same line incanto-playtest calls "fell"), returns it to where it started and zeroes the velocity the fall built up. below names the line, to names the landing, target picks a different node. It emits respawned, and deliberately does not decide what falling COSTS — wire that to a ScoreKeeper or a Health if it should hurt.`,ko:`플레이어의 자식으로 두세요. 프롭 없이도 스폰 50 m 아래(2D는 1000 px — incanto-playtest가 "fell"로 부르는 그 선)에서 부모를 붙잡아 처음 위치로 되돌리고, 낙하로 쌓인 속도를 0으로 만듭니다. below는 그 선, to는 착지 지점, target은 다른 노드를 지정합니다. respawned 시그널을 쏘며, 추락의 "대가"는 일부러 정하지 않습니다 — 피해를 주려면 ScoreKeeper나 Health에 연결하세요.`}),Q(`HudLayer`,{en:`Screen-space HUD overlay above the canvas — parent for UiText/UiBar/UiBanner.`,ko:`캔버스 위 화면 고정 HUD 오버레이 — UiText/UiBar/UiBanner의 부모.`},{en:`A DOM overlay (position:fixed) that never blocks pointer input. Put UI widgets as children; each picks one of 9 anchors (topLeft…bottomRight). Works identically over 2D and 3D renderers; in headless/tests it is a silent no-op. zIndex lifts it above the canvas.`,ko:`포인터 입력을 가로막지 않는 DOM 오버레이(position:fixed)입니다. UI 위젯을 자식으로 두면 각자 9개 앵커(topLeft…bottomRight) 중 하나에 붙습니다. 2D·3D 렌더러 어디서나 동일하게 동작하고, 헤드리스/테스트에서는 조용히 no-op입니다. zIndex로 캔버스 위에 올립니다.`}),Q(`UiText`,{en:`A HUD text line — score, timers, hints.`,ko:`HUD 텍스트 한 줄 — 점수, 타이머, 힌트.`},{en:`Child of HudLayer. Set text/size/color in JSON; update from behaviors: (getNode('%Score') as UiText).text = String(score). shadow adds a soft outline for readability over any scene.`,ko:`HudLayer의 자식. text/size/color를 JSON으로 정하고, 비헤이비어에서 (getNode('%Score') as UiText).text = String(score) 로 갱신하세요. shadow는 어떤 화면 위에서도 읽히도록 부드러운 그림자를 더합니다.`}),Q(`UiBar`,{en:`A labeled progress bar — health, stamina, reload, boss HP.`,ko:`라벨 달린 진행 바 — 체력, 스태미나, 재장전, 보스 HP.`},{en:`Child of HudLayer. Drive value/max from behaviors; the fill animates and turns lowColor under lowThreshold (default 30%). width/height/color/background style it; label prefixes a small caption.`,ko:`HudLayer의 자식. 비헤이비어에서 value/max를 갱신하면 채움이 애니메이션되고 lowThreshold(기본 30%) 아래로 떨어지면 lowColor로 바뀝니다. width/height/color/background로 스타일, label로 작은 캡션을 붙입니다.`}),Q(`UiBanner`,{en:`Center-screen announcements with fade and a queue — "WAVE 2", "YOU DIED".`,ko:`페이드·큐가 있는 중앙 공지 — "WAVE 2", "YOU DIED".`},{en:`Child of HudLayer. Call show('WAVE 2', { color, seconds }) from behaviors; messages queue and fade in/out. seconds 0 = sticky until the next show(). clear() drops everything. Emits bannerShown(text).`,ko:`HudLayer의 자식. 비헤이비어에서 show('WAVE 2', { color, seconds })를 호출하면 메시지가 큐에 쌓여 페이드 인/아웃됩니다. seconds 0이면 다음 show()까지 고정, clear()로 전부 제거. bannerShown(text) 시그널을 냅니다.`}),Q(`UiButton`,{en:`A clickable HUD button — menus, START screens, dialog choices.`,ko:`클릭 가능한 HUD 버튼 — 메뉴, 시작 화면, 대화 선택지.`},{en:`Child of HudLayer. Set text/size/color/background; disabled greys it out. Emits the 'pressed' signal (behaviors: node.on('pressed', ...)); press() triggers it programmatically (gamepad menus, tests).`,ko:`HudLayer의 자식. text/size/color/background를 설정하고 disabled로 비활성화합니다. 'pressed' 시그널을 내며(비헤이비어에서 node.on('pressed', ...)), press()로 코드에서도 누를 수 있습니다(게임패드 메뉴, 테스트).`}),Q(`UiPanel`,{en:`A box that holds other widgets — the thing a menu, options screen or inventory actually is.`,ko:`다른 위젯을 담는 상자 — 메뉴·설정 화면·인벤토리가 실제로 이것입니다.`},{en:`Child of HudLayer. Widgets under it mount INSIDE it, so tree structure becomes screen structure; panels nest. layout column|row|grid with columns (an inventory is a grid panel, one child per slot), plus gap/padding/background/radius/width/height/border. width or height 0 = size to the contents.`,ko:`HudLayer의 자식. 그 아래 위젯들이 이 안에 마운트되어 트리 구조가 화면 구조가 됩니다(중첩 가능). layout은 column|row|grid이고 columns와 함께 씁니다(인벤토리 = grid 패널, 슬롯당 자식 하나). gap/padding/background/radius/width/height/border 지원. width·height가 0이면 내용에 맞춰집니다.`}),Q(`UiImage`,{en:`A picture in the HUD — item icons, portraits, a logo.`,ko:`HUD 안의 그림 — 아이템 아이콘, 초상화, 로고.`},{en:`src takes a url or a $assetKey (declare the icon once like any other asset). fit contain|cover|fill; tint multiplies through the picture, which is how an unaffordable item greys out in one prop; opacity for disabled states.`,ko:`src는 url 또는 $assetKey(아이콘도 다른 에셋처럼 한 번만 선언). fit은 contain|cover|fill, tint는 그림에 곱해져서 살 수 없는 아이템을 프롭 하나로 회색 처리합니다. opacity로 비활성 표현.`}),Q(`UiSlider`,{en:`A value the player sets — volume, sensitivity, difficulty.`,ko:`플레이어가 조절하는 값 — 볼륨, 감도, 난이도.`},{en:`Emits changed(value). label/value/min/max/step/width/color. Setting .value from a behavior updates the control WITHOUT re-emitting, so restoring a saved setting does not fire the handler that saved it.`,ko:`changed(value) 시그널. label/value/min/max/step/width/color. 비헤이비어에서 .value를 설정하면 컨트롤만 갱신되고 changed는 다시 발생하지 않습니다 — 저장된 설정을 복원할 때 저장 핸들러가 다시 도는 것을 막습니다.`}),Q(`UiToggle`,{en:`An on/off switch — mute, invert-Y, fullscreen.`,ko:`켜기/끄기 스위치 — 음소거, Y축 반전, 전체화면.`},{en:`Emits changed(boolean). label/value. Same no-re-emit rule as UiSlider when set from code.`,ko:`changed(boolean) 시그널. label/value. 코드에서 설정할 때 재발생하지 않는 규칙은 UiSlider와 같습니다.`}),Q(`UiMinimap`,{en:`A minimap — the world around one node, as dots.`,ko:`미니맵 — 한 노드 주변 세계를 점으로.`},{en:`Draws a circle (or square: shape) of radius world units around the node at follow, with a dot per member of every group named in dots (a color each), turned by the node at heading so up is forward, and self as the player's own mark. size in px, dotSize, background. markers() answers headless, so a test can ask what is on the map.`,ko:`follow 노드를 중심으로 radius(월드 단위) 안을 원(또는 shape: square)으로 그리고, dots에 이름 붙인 그룹마다 점(그룹별 색)을 찍으며, heading 노드의 방향으로 지도를 돌려 위쪽이 앞이 되게 하고, self가 플레이어 자신의 표시입니다. size는 px, dotSize, background. markers()는 헤드리스에서도 답하므로 테스트가 지도 위에 무엇이 있는지 물을 수 있습니다.`}),Q(`UiWaypoint`,{en:`An objective marker — a diamond over the target, an arrow at the edge when it is off screen.`,ko:`목표 마커 — 대상 위의 다이아몬드, 화면 밖이면 가장자리의 화살표.`},{en:"Floats over target through the renderer projection (anchor means nothing here). Off screen it slides to the margin rectangle along the line from the centre and turns its arrow that way; behind the camera it is mirrored first, so it points the way to turn. distance shows the metres from `from` (the first player-group node by default); hideWithin hides it when you are that close; arrived fires once when from comes within arriveWithin, and again after leaving and coming back. label, color, size. screen() answers headless from whatever toScreen a test installs.",ko:`target 위에 렌더러 투영으로 떠 있습니다(anchor는 의미 없음). 화면 밖이면 중심에서 잇는 선을 따라 margin 사각형까지 밀려가 화살표가 그쪽을 가리키고, 카메라 뒤에 있으면 먼저 중심 대칭으로 뒤집혀 돌아설 방향을 가리킵니다. distance는 from(기본은 player 그룹의 첫 노드)에서의 미터를 보여주고, hideWithin은 그만큼 가까우면 숨기며, arrived는 from이 arriveWithin 안에 들어올 때 한 번(떠났다 돌아오면 다시) 발생합니다. label, color, size. screen()은 헤드리스에서도 테스트가 설치한 toScreen으로 답합니다.`}),Q(`UiLanguageSelect`,{en:`The language picker, already wired.`,ko:`이미 연결된 언어 선택기.`},{en:`Options are the locales the scene declares in "strings", each labeled with its own endonym. Picking one switches the game live and persists it. English is the base: any key a locale omits falls back to it, on purpose.`,ko:`옵션은 씬의 "strings"가 선언한 로케일이며, 각 언어의 자기 이름으로 표시됩니다. 선택하면 즉시 바뀌고 저장됩니다. 영어가 기준이라 로케일이 빠뜨린 키는 의도적으로 영어로 표시됩니다.`}),Q(`Label3D`,{en:`Text standing in the world — a nameplate, a sign, a damage number.`,ko:`월드에 서 있는 텍스트 — 이름표, 표지판, 데미지 숫자.`},{en:`height is the cap height in METRES and the quad follows what the text measures, so a sign is as wide as its words. Faces the camera by default (a damage number read from behind is a bug) and carries a dark outline so it stays readable over anything. Everything else a sprite knows — anchor, tint, opacity, renderOrder — it inherits. For a damage number: set text, then float it up and fade opacity to 0 and queueFree().`,ko:`height는 글자 높이(미터)이고 가로 폭은 텍스트 실측을 따라갑니다. 기본으로 카메라를 향하며(뒤에서 읽히는 데미지 숫자는 버그니까요) 어두운 외곽선이 있어 어떤 배경에서도 읽힙니다. 앵커·틴트·투명도·renderOrder 등 스프라이트의 나머지 기능은 그대로 상속합니다. 데미지 숫자는 text를 넣고 위로 띄우며 opacity를 0으로 보낸 뒤 queueFree() 하면 됩니다.`}),Q(`UiVolumeSlider`,{en:`A volume slider, already wired to a bus.`,ko:`볼륨 슬라이더 — 버스에 이미 연결되어 있습니다.`},{en:`bus picks which one it owns: master (everything), sfx or music. It writes engine.audio, which persists itself, so nothing needs saving. Left unlabelled it names its own bus. Two of them (music + sfx) is the audio menu most games ship.`,ko:`bus로 어느 볼륨을 맡을지 고릅니다 — master(전체), sfx, music. engine.audio에 쓰면 자동 저장되므로 따로 저장할 게 없습니다. label을 비워두면 버스 이름이 표시됩니다. 대부분의 게임은 music + sfx 두 개면 충분합니다.`}),Q(`UiMuteToggle`,{en:`The mute switch — checked means silent.`,ko:`음소거 스위치 — 체크하면 소리가 꺼집니다.`},{en:`Writes engine.audio.muted and persists with the volumes. Follows a mute made anywhere else, so two menus can never disagree.`,ko:`engine.audio.muted에 쓰고 볼륨과 함께 저장됩니다. 다른 곳에서 음소거해도 따라가므로 두 메뉴가 어긋나지 않습니다.`}),Q(`UiQualitySelect`,{en:`Graphics quality — Low, Medium, High. Already wired.`,ko:`그래픽 품질 — Low, Medium, High. 이미 연결되어 있습니다.`},{en:`Low turns off shadows, bloom, post and clouds; Medium keeps shadows but makes them static and drops post; High is everything. Applies live and persists. Antialiasing follows the tier on the NEXT launch — it is a WebGL context attribute and cannot change while a context exists. Picking records a human choice, so device detection never overrides it later.`,ko:`Low는 그림자·블룸·포스트·구름을 끄고, Medium은 그림자를 정적으로 유지하며 포스트를 끄고, High는 전부 켭니다. 즉시 적용되고 저장됩니다. 안티에일리어싱만 다음 실행부터 반영됩니다(WebGL 컨텍스트 속성이라 생성 후에는 못 바꿉니다). 사람이 고른 값으로 기록되어 이후 자동 감지가 덮어쓰지 않습니다.`}),Q(`UiFrameCapSelect`,{en:`Frame rate cap — 30, 60, 120 or Unlimited.`,ko:`프레임 제한 — 30, 60, 120 또는 무제한.`},{en:`Gates the whole frame, not just the render, so it saves CPU as well as GPU — a cooler phone and a longer battery. Unlimited (0) is the default. Restrict the list with options, e.g. "60,120,0".`,ko:`렌더뿐 아니라 프레임 전체를 제한하므로 GPU와 CPU를 함께 아낍니다 — 발열과 배터리에 유리합니다. 기본값은 무제한(0). options로 목록을 줄일 수 있습니다(예: "60,120,0").`}),Q(`UiRenderScaleSelect`,{en:`Resolution scale — 50%, 75%, 100%.`,ko:`해상도 배율 — 50%, 75%, 100%.`},{en:`The cheapest frames on a weak GPU: at 75% the fragment shaders run over 56% of the pixels for a slightly softer image and nothing else, where dropping a quality tier costs the shadows outright. Multiplies with the engine's automatic resolution governor rather than fighting it.`,ko:`저사양 GPU에서 가장 값싼 프레임: 75%면 픽셀의 약 56%만 셰이딩하므로 이미지가 약간 부드러워질 뿐이지만, 품질 단계를 낮추면 그림자가 통째로 사라집니다. 엔진의 자동 해상도 조절과 충돌하지 않고 곱해집니다.`}),Q(`UiSelect`,{en:`One of several — quality, resolution, language.`,ko:`여러 개 중 하나 — 품질, 해상도, 언어.`},{en:`options is a comma-separated list ("low,medium,high"); value is the current one. Emits changed(value).`,ko:`options는 쉼표로 구분된 목록("low,medium,high"), value가 현재 선택입니다. changed(value) 시그널.`}),Q(`UiDialogue`,{en:`A typewriter dialogue box with a queue and choice buttons — the RPG conversation layer.`,ko:`타자기 효과·큐·선택지 버튼을 갖춘 대화창 — RPG 대화 레이어.`},{en:`Child of HudLayer (anchor bottom by default). say(speaker, text, choices?) queues lines; clicking (or advance()) reveals then advances; choice lines wait for choose(i). Signals: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0 = instant. Check .active to pause player input during conversations.`,ko:`HudLayer의 자식(기본 anchor bottom). say(화자, 텍스트, 선택지?)로 줄을 큐에 넣고, 클릭(또는 advance())이 전체 공개→다음 줄로 진행하며, 선택지 줄은 choose(i)를 기다립니다. 시그널: lineShown(text), choiceMade(index), dialogueFinished. charsPerSecond 0이면 즉시 표시. 대화 중 플레이어 입력을 멈추려면 .active를 확인하세요.`}),Q(`AudioPlayer`,{en:`Plays a sound: zero-asset procedural SFX, BGM loops, or one-shot effects.`,ko:`소리 재생 — 무에셋 절차적 효과음, 배경음 루프, 단발 효과음.`},{en:`Set preset (coin/jump/hurt/explosion/…) for an instant zero-asset SFX (pitch/seed vary it), or leave it "custom" and set src (URL or "$assetKey"). volume 0..1; bus routes through engine.audio (sfx|music) for global volume/mute; loop for music; autoplay starts on ready (browsers may hold it until the first user gesture). Call play()/stop() from game code. Dimension-free — 2D and 3D alike.`,ko:`preset(coin/jump/hurt/explosion/…)을 설정하면 즉시 무에셋 효과음이 납니다(pitch·seed로 변형). 아니면 "custom"으로 두고 src(URL 또는 "$에셋키")를 쓰세요. volume은 0..1, bus는 engine.audio(sfx|music)를 통해 전역 볼륨/음소거에 연결, 음악은 loop, autoplay는 준비되면 재생합니다(브라우저가 첫 입력까지 보류 가능). 게임 코드에서 play()/stop()을 부르세요. 2D·3D 어디서나 동작합니다.`})]},{id:`2d`,label:{en:`2D`,ko:`2D`},intro:{en:`The 2D world is y-down pixels: 1 unit = 1 px, (0,0) top-left, rotation in clockwise degrees. Rendering needs a current Camera2D.`,ko:`2D 세계는 y-아래 픽셀 좌표입니다: 1유닛=1px, (0,0)은 좌상단, 회전은 시계방향 도(degree). 렌더링에는 current 카메라(Camera2D)가 필요합니다.`},nodes:[Q(`Node2D`,{en:`The 2D transform container (position/rotation/scale).`,ko:`2D 변환 컨테이너(position/rotation/scale).`},{en:`Children inherit its transform — move the parent, everything follows. renderOrder orders drawing; visible hides the subtree.`,ko:`자식은 변환을 상속합니다 — 부모를 움직이면 전부 따라옵니다. renderOrder로 그리기 순서를, visible로 서브트리 표시를 제어합니다.`}),Q(`Sprite2D`,{en:`A textured quad.`,ko:`텍스처 사각형(스프라이트).`},{en:`texture is "$assetKey" from the scene assets. anchor [0.5,0.5] centers; flipX/flipY mirror; tint multiplies color; opacity fades. Size comes from the texture × scale.`,ko:`texture는 씬 에셋의 "$키"입니다. anchor [0.5,0.5]면 중앙 기준, flipX/flipY로 반전, tint로 색 곱, opacity로 투명도. 크기는 텍스처 × scale로 정해집니다.`}),Q(`ColorRect2D`,{en:`A flat colored rectangle — no texture needed.`,ko:`단색 사각형 — 텍스처 불필요.`},{en:`size [w,h] px, color, opacity, anchor. Backgrounds, platforms, walls, UI panels, generated-level tiles (maze2d/dungeon2d emit these) — blocky art without any asset.`,ko:`size [w,h] px, color, opacity, anchor. 배경·플랫폼·벽·UI 패널·생성 레벨 타일(maze2d/dungeon2d가 이걸 만듭니다) — 에셋 없이 만드는 블록 그래픽입니다.`}),Q(`TileMap2D`,{en:`A whole tile level as ONE node — grid render + merged static colliders.`,ko:`타일 레벨 전체를 노드 하나로 — 그리드 렌더 + 병합된 정적 콜라이더.`},{en:`Author cells as rows of characters: "." / space = empty, digits 0-9 = atlas tile index, other chars map through legend ({"G": 12}) or colors ({"#": "#3a4356"}), which paints a flat colour and needs no atlas at all — use it to block out a level before the art arrives (exclusive with texture). texture is a "$atlas" asset read left-to-right top-to-bottom in tileSize squares (columns: 0 derives from the texture width). solid becomes static colliders, greedy-merged into a few rectangles, and takes the CHAR you painted as well as a tile index. Cell (0,0) hangs its top-left on the node origin.`,ko:`cells를 문자 행으로 작성합니다: "."/공백 = 빈 칸, 숫자 0-9 = 아틀라스 타일 번호, 그 외 문자는 legend({"G": 12}) 또는 colors({"#": "#3a4356"})로 매핑합니다. colors는 아틀라스 없이 단색 칸을 그려서 아트가 오기 전에 레벨을 잡을 때 씁니다(texture와 동시 사용 불가). texture는 tileSize 정사각형을 좌→우, 상→하로 읽는 "$아틀라스" 에셋입니다(columns: 0이면 텍스처 폭에서 유도). solid는 정적 콜라이더가 되며(타일 번호뿐 아니라 칠한 문자도 받습니다) 소수의 직사각형으로 탐욕 병합됩니다. (0,0) 칸의 좌상단이 노드 원점에 걸립니다.`}),Q(`AnimatedSprite2D`,{en:`Spritesheet animation player.`,ko:`스프라이트시트 애니메이션 플레이어.`},{en:`Point sheet at a "$sheet" asset, define animations as named frame ranges with fps/loop in JSON, set autoplay. Emits animationFinished(name) for one-shot chains.`,ko:`sheet에 "$시트" 에셋을 연결하고, JSON에 fps/loop를 가진 이름별 프레임 구간으로 animations를 정의한 뒤 autoplay를 지정하세요. 단발 애니메이션 연결을 위해 animationFinished(name)를 발산합니다.`}),Q(`Camera2D`,{en:`The 2D view: follow, zoom, limits.`,ko:`2D 시점 — 추적·줌·경계.`},{en:`position is the view CENTER. follow tracks a node path with smoothing (0..1, higher = snappier). limits [minX,minY,maxX,maxY] clamps the view inside a world region. current: true makes it THE camera.`,ko:`position은 화면의 중심입니다. follow가 노드 경로를 smoothing(0..1, 높을수록 빠릿)으로 추적합니다. limits [minX,minY,maxX,maxY]가 시점을 월드 영역 안에 가둡니다. current: true인 카메라가 실제 시점이 됩니다.`}),Q(`Particles2D`,{en:`A 2D particle emitter (fire, sparks, smoke…).`,ko:`2D 파티클 이미터(불·스파크·연기…).`},{en:`Start from a preset (fire/smoke/sparks/…) then override any prop: rate, lifetime/speed ranges, direction + spread, gravity, size/color/alpha start→end, additive blend. burst > 0 with emitting: false makes a one-shot that emits finished. Animates LIVE in this editor.`,ko:`preset(fire/smoke/sparks/…)에서 시작해 어떤 prop이든 덮어쓰세요: rate, lifetime/speed 구간, direction+spread, gravity, size/color/alpha 시작→끝, additive blend. emitting: false에 burst > 0이면 단발 발사 후 finished를 발산합니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Label`,{en:`Text rendered to a quad.`,ko:`텍스트를 그리는 노드.`},{en:`text/fontSize/color/font/align — rendered via CanvasTexture, so any system font string works. Inside a UILayer it pins to the screen (HUD).`,ko:`text/fontSize/color/font/align — CanvasTexture로 그려져 시스템 폰트 문자열을 그대로 쓸 수 있습니다. UILayer 아래에 두면 화면에 고정됩니다(HUD).`}),Q(`UILayer`,{en:`A screen-space subtree (HUD).`,ko:`화면 고정 서브트리(HUD).`},{en:`Everything under it ignores the camera: positions are screen pixels from the top-left. Score counters, prompts, menus go here.`,ko:`이 아래의 모든 것은 카메라를 무시합니다 — 좌상단 기준 화면 픽셀 좌표입니다. 점수, 안내 문구, 메뉴를 여기에 둡니다.`})]},{id:`2d-physics`,label:{en:`2D Physics`,ko:`2D 물리`},intro:{en:`Rapier-backed. Colliders are PROPS ({shape, …}) — the green dashed wireframes in this editor. Physics runs when the game calls enablePhysics2D (and in play mode). Gravity lives on the scene row.`,ko:`Rapier 기반입니다. 콜라이더는 prop({shape, …})이며 에디터의 초록 점선이 그것입니다. 물리는 게임이 enablePhysics2D를 부를 때(그리고 플레이 모드에서) 돌고, 중력은 씬 행에 있습니다.`},nodes:[Q(`StaticBody2D`,{en:`Immovable collision: ground, walls, platforms.`,ko:`움직이지 않는 충돌체 — 바닥·벽·플랫폼.`},{en:`Other bodies collide with it; it never moves. Cheapest body type — use it for all level geometry.`,ko:`다른 바디가 부딪히지만 자신은 절대 움직이지 않습니다. 가장 저렴한 바디 — 레벨 지형 전부에 쓰세요.`}),Q(`RigidBody2D`,{en:`Fully simulated: falls, bounces, pushes.`,ko:`완전 시뮬레이션 — 떨어지고 튕기고 밀립니다.`},{en:`Gravity and collisions drive it. Set linearVelocity to launch. For player characters prefer CharacterBody2D (direct control).`,ko:`중력과 충돌이 움직임을 결정합니다. linearVelocity로 발사하세요. 플레이어 캐릭터에는 직접 제어가 가능한 CharacterBody2D를 권합니다.`}),Q(`CharacterBody2D`,{en:`Kinematic character: you set velocity, it slides.`,ko:`키네마틱 캐릭터 — 속도를 주면 미끄러지듯 이동.`},{en:`moveAndSlide() resolves collisions without physics pushing back; isOnFloor() gates jumps. Sensors (Area2D) do not block it but still fire triggers.`,ko:`moveAndSlide()가 밀려나지 않으면서 충돌을 처리하고 isOnFloor()로 점프를 판정합니다. 센서(Area2D)는 길을 막지 않으면서 트리거를 발사합니다.`}),Q(`Area2D`,{en:`A sensor: overlap triggers, no collision response.`,ko:`센서 — 겹침 감지만, 충돌 반응 없음.`},{en:`Fires triggerEnter(other)/triggerExit(other). Coins, checkpoints, damage zones. Filter with other.isInGroup("player").`,ko:`triggerEnter(other)/triggerExit(other)를 발산합니다. 코인·체크포인트·데미지 존에 쓰고, other.isInGroup("player")로 거릅니다.`}),Q(`CharacterController2D`,{en:`Zero-code platformer/top-down movement.`,ko:`코드 없는 플랫포머/탑다운 이동.`},{en:`Put it UNDER a CharacterBody2D. mode "platformer" (gravity + jump via jumpAction) or "topDown" (free 2-axis). Reads the scene input map actions (moveAction/jumpAction). maxSpeed/jumpHeight are intent-level numbers.`,ko:`CharacterBody2D의 자식으로 두세요. mode는 "platformer"(중력+jumpAction 점프) 또는 "topDown"(자유 2축)이며 씬 입력 맵의 액션(moveAction/jumpAction)을 읽습니다. maxSpeed/jumpHeight는 의도 그대로의 숫자입니다.`}),Q(`Joint2D`,{en:`A physics joint linking its parent body to a target body — weld, hinge, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 힌지, 로프, 스프링.`},{en:`Child of body A (a physics body); "target" is a node path to body B. type: fixed (rigid weld) / revolute (pin at the anchors) / rope (caps anchor distance at length px; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL px offsets.`,ko:`바디 A(물리 바디)의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / revolute(앵커 핀 힌지) / rope(앵커 간 거리를 length px로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 px 오프셋.`})]},{id:`3d`,label:{en:`3D`,ko:`3D`},intro:{en:`Meters, y-up, rotations in degrees. Standard materials need LIGHT — add a DirectionalLight3D or scene ambient, or you get silhouettes.`,ko:`미터 단위, y-위, 회전은 도(degree)입니다. 표준 머티리얼은 빛이 필요합니다 — DirectionalLight3D나 씬 ambient가 없으면 실루엣만 보입니다.`},nodes:[Q(`Node3D`,{en:`The 3D transform container.`,ko:`3D 변환 컨테이너.`},{en:`position [x,y,z] in meters, rotation [x,y,z] in degrees, scale per axis. Children inherit.`,ko:`position [x,y,z] 미터, rotation [x,y,z] 도, scale은 축별. 자식이 상속합니다.`}),Q(`MeshInstance3D`,{en:`A primitive mesh + material.`,ko:`프리미티브 메시 + 머티리얼.`},{en:`mesh: box/sphere/plane/cylinder…, size per primitive, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat} (this editor gives it swatches, sliders, texture-URL fields, and a repeat [u,v] tiling vector). map/normalMap are texture URLs; repeat only takes effect with a map. castShadow/receiveShadow per node.`,ko:`mesh: box/sphere/plane/cylinder…, 프리미티브별 size, material {color, roughness, metalness, emissive, emissiveIntensity, wireframe, map, normalMap, repeat}(에디터가 스와치·슬라이더·텍스처 URL 입력·repeat [u,v] 타일링 벡터 제공). map/normalMap은 텍스처 URL, repeat는 map이 있을 때만 적용. 그림자는 castShadow/receiveShadow.`}),Q(`LoftMesh3D`,{en:`A smooth swept hull (loft).`,ko:`부드러운 스윕 선체(로프트).`},{en:`sections: ≥2 cross-section stations {z, width, height, y, corner 0..1} interpolated into ONE smooth curved surface — vehicle bodies, glass canopies, boat hulls. slices/smooth control tessellation. Same material as MeshInstance3D minus textures (no UVs); pair clearcoat paint or high-envMapIntensity glass with the smooth normals for the automotive look.`,ko:`sections: 단면 스테이션 {z, width, height, y, corner 0..1} 2개 이상을 보간해 하나의 매끈한 곡면을 만듭니다 — 차체, 유리 캐노피, 선체. slices/smooth로 테셀레이션 조절. material은 MeshInstance3D와 동일하되 텍스처 제외(UV 없음). clearcoat 도장이나 높은 envMapIntensity 유리를 곡면 법선과 조합하면 자동차 룩이 납니다.`}),Q(`ModelInstance3D`,{en:`A GLB/glTF/VRM model file.`,ko:`GLB/glTF/VRM 모델 파일.`},{en:'model: "$assetKey" or URL. targetHeight scales the model to stand N units tall (run `npx incanto-model file.glb` to read its real size first). animation plays an embedded clip name OR an "$animation" asset — Mixamo clips retarget onto VRM humanoids automatically. One node per VRM asset (the avatar runtime mounts live). To make it SOLID, park it under a body with collider {shape:"auto"}: the collider is built from the model\'s own triangles — a triangle mesh on a static body (keeps its holes, so you walk through an archway) and a convex hull on a moving one.',ko:'model은 "$에셋키" 또는 URL입니다. targetHeight가 모델을 N유닛 높이로 맞춥니다(먼저 `npx incanto-model 파일.glb`로 실제 크기를 확인하세요). animation은 내장 클립 이름 또는 "$애니메이션" 에셋을 재생하며, Mixamo 클립은 VRM 휴머노이드에 자동 리타게팅됩니다. VRM 에셋은 노드 하나만 쓸 수 있습니다(아바타 런타임이 라이브로 마운트됨). 단단하게 만들려면 collider {shape:"auto"}인 바디 아래에 두세요 — 모델 자신의 삼각형에서 콜라이더가 만들어집니다(정적 바디는 트라이메시라 아치 구멍도 그대로, 움직이는 바디는 볼록 껍질).'}),Q(`Sprite3D`,{en:`A 2D image as a camera-facing billboard (the 2.5D look).`,ko:`카메라를 향하는 2D 빌보드 스프라이트(2.5D 룩).`},{en:`A textured quad that turns to face the camera inside the 3D world (Octopath / Don't Starve / MapleStory-in-3D). texture is an image URL; size is [w,h] in METERS. billboard: "y" stays upright with a screen-aligned yaw — off-center sprites never roll (characters/props), "full" faces it completely (items/FX), "none" is fixed to the node rotation. anchor [0.5,0] plants the feet on the ground. pixelArt nearest-filters for crisp pixels; alphaTest is a hard cutout that depth-sorts against 3D geometry (a tree occludes it); flipX mirrors left/right; tint/opacity recolor.`,ko:`3D 월드 안에서 카메라를 향해 도는 텍스처 쿼드(Octopath/Don't Starve, 3D 속 메이플스토리 룩). texture는 이미지 URL, size는 [너비,높이] 미터. billboard: "y"는 세로로 선 채 카메라 방향과 정렬된 yaw — 화면 가장자리에서도 기울지 않음(캐릭터/사물), "full"은 완전히 향함(아이템/FX), "none"은 노드 회전에 고정. anchor [0.5,0]은 발을 바닥에 둡니다. pixelArt는 nearest 필터로 픽셀을 또렷하게, alphaTest는 3D 지형과 깊이정렬되는 하드 컷아웃(나무가 가림), flipX는 좌우 반전, tint/opacity로 색·투명도.`}),Q(`AnimatedSprite3D`,{en:`A billboard sprite that plays spritesheet animations.`,ko:`스프라이트시트 애니를 재생하는 빌보드 스프라이트.`},{en:`Everything Sprite3D does, plus frame animation. sheet is a spritesheet image URL whose cells are frameWidth×frameHeight; animations maps a name to {frames, fps, loop} where frames is an inclusive [start,end] range or an explicit list; autoplay starts one on load. Game code calls play("walk") / stop(); a non-looping clip clamps on its last frame and emits animationFinished(name) — chain attack→idle from it.`,ko:`Sprite3D의 모든 기능 + 프레임 애니. sheet는 frameWidth×frameHeight 칸을 가진 스프라이트시트 URL, animations는 이름→{frames, fps, loop}(frames는 포함 [시작,끝] 범위 또는 명시 목록), autoplay는 로드 시 하나를 시작. 게임 코드에서 play("walk")/stop() 호출, 비반복 클립은 마지막 프레임에 머물며 animationFinished(name)를 emit(attack→idle 연결).`}),Q(`Billboard3D`,{en:`A group that turns toward the camera — children follow.`,ko:`카메라를 향해 도는 그룹 — 자식들이 함께 회전.`},{en:`A transform container that orients itself toward the camera every frame; children inherit the rotation, so hang world-space UI under it — HP bars, markers, floating icons (text is a canvas-rendered texture on a child Sprite3D). mode: "screen" (default) copies the camera orientation so a child rectangle stays an upright rectangle anywhere on screen (a yaw-only look-at visibly tilts off-center shapes under a pitched camera); "y" stays upright with a screen-aligned yaw (no off-center roll); "none" turns billboarding off. While billboarding, the node's own rotation prop (and the rotate gizmo) is overwritten every frame — switch to "none" to pose children, then switch back. Unlike Sprite3D (a textured quad that spins only its own image), Billboard3D rotates the whole group.`,ko:`매 프레임 카메라를 향해 자신을 회전시키는 변환 컨테이너로, 자식이 회전을 상속합니다 — HP바·마커·아이콘 같은 월드 UI를 자식으로 붙이세요(텍스트는 캔버스로 그린 텍스처를 자식 Sprite3D에). mode: "screen"(기본)은 카메라 자세를 그대로 복사해 자식 직사각형이 화면 어디서든 똑바른 직사각형으로 보입니다(yaw만 도는 look-at은 기울어진 카메라에서 중앙 밖 도형이 눈에 띄게 비스듬해짐); "y"는 세로로 선 채 카메라로 yaw만; "none"은 빌보드 끔. 빌보드 중에는 노드 자신의 rotation(회전 기즈모 포함)이 매 프레임 덮어써집니다 — 자식을 배치할 땐 "none"으로 바꿨다가 되돌리세요. 자기 그림만 도는 Sprite3D(텍스처 쿼드)와 달리 그룹 전체가 회전합니다.`}),Q(`Camera3D`,{en:`The 3D view.`,ko:`3D 시점.`},{en:`Perspective camera; fov in degrees; current: true selects it. Use the editor's "game cam" (0) to preview exactly what it renders.`,ko:`원근 카메라이며 fov는 도 단위, current: true가 실제 시점이 됩니다. 에디터의 "game cam"(0)으로 정확한 렌더 결과를 미리 보세요.`}),Q(`DirectionalLight3D`,{en:`Sun-like light from a direction.`,ko:`태양광 — 방향에서 평행하게.`},{en:`Position sets the direction toward the origin. intensity/color; pair with scene ambient for soft fill.`,ko:`위치가 원점을 향한 방향을 정합니다. intensity/color를 조절하고 부드러운 채움광은 씬 ambient와 함께 쓰세요.`}),Q(`OmniLight3D`,{en:`A point light radiating everywhere.`,ko:`점광 — 사방으로 퍼지는 빛.`},{en:`Lamps, torches, glows. range limits reach; intensity/color shape the falloff.`,ko:`램프·횃불·발광체. range로 도달 거리를, intensity/color로 감쇠를 만듭니다.`}),Q(`SpotLight3D`,{en:`A cone of light that aims.`,ko:`원뿔광 — 방향을 가진 빛.`},{en:`Flashlights, searchlights, headlights, stage spots. Aims down its −Z like a camera (rotation [-90,0,0] = at the floor). coneDeg is the FULL cone angle, penumbra softens the edge, range limits reach; castShadow makes it a shadow caster (one extra render per frame). lookAt aims it at a node every frame — a searchlight that tracks the player. To sweep, yaw a parent pivot: a yaw on the pitched light itself swings the cone sideways (Euler XYZ).`,ko:`손전등·서치라이트·헤드라이트·무대 조명. 카메라처럼 자신의 −Z를 향합니다(rotation [-90,0,0] = 바닥). coneDeg는 원뿔 전체 각, penumbra는 가장자리 부드러움, range는 도달 거리. castShadow를 켜면 그림자를 드리웁니다(프레임당 렌더 1회 추가). lookAt은 매 프레임 지정한 노드를 겨냥합니다 — 플레이어를 쫓는 서치라이트. 훑으려면 부모 피벗을 yaw 회전하세요: 기울인 조명 자체를 yaw하면 원뿔이 옆으로 돌아갑니다(Euler XYZ).`}),Q(`Particles3D`,{en:`A 3D particle emitter (fire, magic, weather…).`,ko:`3D 파티클 이미터(불·마법·날씨…).`},{en:`The same preset + override model as Particles2D, in meters with [x,y,z] gravity. Camera-facing billboard quads, instanced — hundreds are cheap. Animates LIVE in this editor.`,ko:`Particles2D와 같은 preset+덮어쓰기 모델을 미터 단위와 [x,y,z] 중력으로. 카메라를 향하는 빌보드 쿼드를 인스턴싱해 수백 개도 가볍습니다. 이 에디터에서 라이브로 움직입니다.`}),Q(`Weather3D`,{en:`Rain or snow that follows the camera.`,ko:`카메라를 따라다니는 비 또는 눈.`},{en:`A Particles3D preset that stays around the current Camera3D: kind rain|snow, intensity (live — fade a storm in), radius and height of the box it falls in, wind as an [x, z] drift, follow to pin it to a node instead. One instanced emitter, nothing per drop; pair it with a dark sky and fog. Headless it still counts as particles for the framing check.`,ko:`현재 Camera3D 주위에 머무는 Particles3D 프리셋: kind rain|snow, intensity(실시간 — 폭풍을 서서히 키우기), 내리는 상자의 radius와 height, wind는 [x, z] 흐름, follow로 대신 특정 노드에 고정. 인스턴싱된 이미터 하나 값이며 빗방울마다 비용은 없습니다. 어두운 하늘과 안개를 곁들이세요. 헤드리스에서도 프레이밍 검사에는 파티클로 잡힙니다.`}),Q(`Flock3D`,{en:`A flock — gulls, fish, bats — as one instanced mesh that flies itself.`,ko:`떼 — 갈매기·물고기·박쥐 — 스스로 나는 인스턴싱 메시 하나.`},{en:`Boids: each instance steers away from neighbours closer than separation, toward the heading (alignment) and centre (cohesion) of those within sight, turns back inside an ellipsoid radius wide and height tall around this node — or around the node at follow, offset by this position — never faster than turn, always at speed, +z forward. count is live. One draw call, no bodies; seeded from engine.rng; boids() answers headless. Takes no collider.`,ko:`보이드: 각 인스턴스는 separation보다 가까운 이웃에서 멀어지고, sight 안 이웃의 방향(alignment)과 중심(cohesion)으로 향하며, 이 노드(또는 follow 노드에 이 position만큼 오프셋한 곳) 주위 radius 너비·height 높이의 타원체 안으로 되돌아오고, turn보다 빨리 돌지 않으며 항상 speed로 +z 앞을 향해 납니다. count는 실시간. 드로우 콜 하나, 물리 바디 없음, engine.rng로 시드; boids()는 헤드리스에서도 답합니다. collider는 받지 않습니다.`}),Q(`Terrain3D`,{en:`Procedural heightfield terrain with biome texture splatting.`,ko:`바이옴 텍스처 스플래팅이 적용된 절차적 하이트필드 지형.`},{en:`Seeded simplex hills displaced once on the CPU; theme (island/alpine/plains/desert/custom) picks the 4 blended biome textures by height and slope. heightAt(x,z) answers the surface height anywhere. For physics, parent it under a StaticBody3D with collider {shape:'heightfield'}.`,ko:`시드 기반 심플렉스 언덕을 CPU에서 한 번 변위합니다. theme(island/alpine/plains/desert/custom)이 높이·경사로 블렌딩되는 바이옴 텍스처 4장을 고릅니다. heightAt(x,z)로 어디서든 지표 높이를 얻고, 물리는 StaticBody3D 아래에 두고 collider {shape:'heightfield'}를 쓰세요.`}),Q(`Water3D`,{en:`A shader-water surface with splash signals.`,ko:`스플래시 신호를 내는 셰이더 물 표면.`},{en:`size [w,d] meters on XZ. quality 'fancy' (default) = FBM wave shader with a trough/surface/peak ramp (colors), CubeCamera reflections (reflection/reflectionInterval) and opt-in shoreline foam; 'simple' = the cheap sine material (color). Bodies crossing the surface emit entered/exited(body) and raise ripples (interaction). Volumetric gameplay still wants an Area3D. Waves animate LIVE in this editor.`,ko:`XZ 평면에 size [w,d] 미터. quality 'fancy'(기본)는 FBM 파도 셰이더 — trough/surface/peak 램프(colors), CubeCamera 반사(reflection/reflectionInterval), 옵트인 해안 거품(foam). 'simple'은 저사양용 사인파 머티리얼(color). 바디가 수면을 지나면 entered/exited(body) 신호와 물결이 일어납니다(interaction). 부피 기반 게임플레이엔 여전히 Area3D를 쓰세요. 이 에디터에서 파도가 라이브로 움직입니다.`}),Q(`River3D`,{en:`Running water derived from a path and the ground under it.`,ko:`경로와 그 아래 지형에서 유도되는 흐르는 물.`},{en:`Author a centerline path [[x,z],…] plus width/widths (a profile source→mouth) and depth; the node samples the Terrain3D underneath and derives the rest. It CARVES ITS OWN BED by default (carve): a trench per reach that heightAt, the collider, the splat and draped vegetation all see, with a floor that only ever falls, so a path over a rise digs through instead of burying the water. Its surface is then FITTED to that ground — never higher than the lowest rim holding it, ending where the ground comes up to meet it (asymmetric on a sloping reach), lying down as a film where a bank has fallen away, so a river can never hang in the air. Plus a current that speeds up where the channel pinches or tips (flowSpeed is the mean) and whitewater from grade, bank shear and thinning column. Boulders in the channel are answered without wiring: the node finds MeshInstance3D/InstancedMesh3D footprints standing in the water column and the current piles a white cushion on the upstream face, tears a wake downstream and bends its sheen around them. A trench thinner than a terrain cell cannot survive the grid: a 2.4 m creek on a 260 m map wants Terrain3D resolution 256. flowForce drags bodies downstream (drag, never thrust) and sampleAt(x,z) answers where a world point sits in the channel. No extra render passes — a map can carry a dozen.`,ko:`중심선 path [[x,z],…]와 width/widths(상류→하류 프로파일), depth만 주면 나머지는 아래 Terrain3D를 샘플링해 유도합니다. 기본적으로 강이 자기 바닥을 직접 팝니다(carve) — 구간마다 하나씩 도랑을 내고, heightAt·콜라이더·스플랫·식생 드레이프가 모두 그 지형을 봅니다. 파낸 바닥은 계속 내려가기만 하므로 경로가 언덕을 넘어도 물이 묻히지 않고 뚫고 흐릅니다. 그리고 수면은 그 지형에 맞춰집니다 — 자기를 담는 가장 낮은 둑보다 높아질 수 없고, 지면이 올라오는 지점에서 끝나며(비스듬한 구간에서는 좌우 폭이 다릅니다), 둑이 아예 없는 쪽에서는 경사면에 얇은 막처럼 누워버립니다. 그래서 강이 공중에 뜨는 일이 없습니다. 여기에 폭이 좁아지거나 경사가 급해지면 빨라지는 유속(flowSpeed는 평균)과 경사·둑 전단·얕아지는 수심에서 나오는 흰 물살이 더해집니다. 수로에 놓인 바위도 배선 없이 반응합니다 — MeshInstance3D/InstancedMesh3D 중 실제로 물기둥과 겹치는 것을 찾아, 상류면에 흰 물이 쌓이고 하류로 후류가 찢어지며 수면 광택이 바위를 돌아 휩니다. 지형 셀보다 얇은 도랑은 그리드에서 살아남지 못합니다 — 260 m 맵의 2.4 m 개울이라면 Terrain3D resolution 256이 필요합니다. flowForce가 바디를 하류로 끌고(밀지 않고 끌어당김), sampleAt(x,z)로 월드 좌표가 수로 어디에 있는지 알 수 있습니다. 추가 렌더 패스가 없어 한 맵에 여러 개를 둘 수 있습니다.`}),Q(`WaterCutout3D`,{en:`Marks its parent as something that holds the water back — a dry hull, a diving bell, a well.`,ko:`부모 오브젝트가 물을 막는다고 표시 — 마른 선실, 잠수종, 우물.`},{en:`Water is ONE surface and knows nothing about interiors, so an open hull floating on it fills with sea every time a crest clears its floor — freeboard alone can never promise otherwise. This node names the geometry that keeps the water out: it MUST be a CHILD of that thing (a hull, a bell, a dock's well, a cave mouth), and the water re-draws the part of it inside the box into its depth pre-pass, then hides behind it exactly as it hides behind any solid object. Nothing is ever cut OUT of the water, so a hole in open sea is impossible: overshoot the box and more of that hull holds water back, undershoot and water stands in the bow. size is the box extent in meters; enabled toggles it live (a scuttled hull starts letting the sea in). Four per water surface; needs quality fancy.`,ko:`물은 하나의 표면이라 '안쪽'이라는 개념이 없습니다. 그래서 뚜껑 없는 배를 띄우면 파도 마루가 바닥을 넘을 때마다 배 안에 바다가 차 보이고, 건현(freeboard)만으로는 절대 막을 수 없습니다. 이 노드는 '물을 막는 지오메트리'를 지정합니다. 반드시 그 물체(선체·잠수종·부두 우물·동굴 입구)의 자식이어야 하며, 물이 상자 안쪽의 그 지오메트리를 자기 깊이 프리패스에 다시 그린 뒤 평범한 불투명 물체 뒤에 숨듯 그 뒤로 숨습니다. 물에서 무언가를 '도려내지' 않으므로 열린 바다에 구멍이 나는 일은 원리적으로 불가능합니다 — 상자가 크면 그 배가 물을 더 많이 막을 뿐이고, 작으면 뱃머리에 물이 남습니다. size는 미터 단위 상자 크기, enabled는 런타임 토글(침수 시작 연출). 수면 하나당 4개, quality fancy 필요.`}),Q(`Foliage3D`,{en:`An instanced grass/flower carpet that sways.`,ko:`바람에 흔들리는 인스턴스 풀밭/꽃밭. `},{en:`kind grass/flowers/reeds scattered over area [w,d] at density (capped by maxInstances — instanced, tens of thousands of blades cheap). Grass defaults to style 'mesh': every instance is a REAL tapered blade curved by a bezier vertex shader — Voronoi-clump hue/lean, groundColor soil roots (match the terrain), sunDirection tip sheen, 2-octave rolling wind, fadeStart/fadeEnd camera LOD, and (interaction) blade-bending around moving bodies. style 'blades' keeps the 8-SDF-blades-per-quad ported shader, 'simple' the legacy quads. colorA/colorB tint bottom→top, sway sets the wind, seed makes the scatter reproducible. avoidWater (on by default) keeps blades OUT of standing and running water — a creek cutting its bed through the field gets banks, not blades waving in the current; turn it off for reeds and paddy fields.`,ko:`kind grass/flowers/reeds를 area [w,d]에 density로 흩뿌립니다(maxInstances 상한 — 인스턴싱이라 수만 가닥도 가벼움). grass는 기본 style 'mesh': 인스턴스 하나하나가 베지어 버텍스 셰이더로 휘어지는 진짜 잎 메시 — 보로노이 클럼프 색/기울기, groundColor 흙빛 뿌리(지형 색에 맞추세요), sunDirection 잎끝 광택, 2옥타브 굽이치는 바람, fadeStart/fadeEnd 카메라 LOD, (interaction) 움직이는 바디 주변 풀 눕힘까지. style 'blades'는 쿼드당 8가닥 SDF 셰이더, 'simple'은 기존 쿼드 룩. colorA/colorB가 아래→위 색, sway가 바람 세기, seed가 배치를 재현 가능하게 합니다. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 잎을 심지 않습니다 — 개울이 들판을 가르고 지나가면 물살 속에 풀이 서 있는 대신 둑이 생깁니다. 갈대·논은 꺼서 쓰세요.`}),Q(`Flowers3D`,{en:`Instanced flower PLANTS — stems, leaves, multi-petal heads.`,ko:`인스턴스 꽃밭 — 줄기·잎·여러 장 꽃잎의 진짜 꽃 식물.`},{en:`Real procedural flower plants (curved stem, 2-3 leaves, a 5-8 petal head around a contrasting center disc, 1-3 blooms per plant) scattered over area [w,d]. density is the vibe dial: 'lush' / 'sparse' (default) / 'none', or a number in plants/m². varieties picks a subset of daisy/cosmos/bellflower ([] = all three); palette sets the head colors ([] = white/yellow/violet). clustering 0-1 gathers plants into Voronoi patches that bloom one species + color together; sway bobs the heads in a gentle wind; seed makes the field reproducible. ≤3 varieties → ≤6 draw calls. avoidWater (on by default) keeps plants out of standing and running water — a meadow a stream runs through has a bank of flowers, not flowers in the current.`,ko:`진짜 프로시저럴 꽃 식물(휘어진 줄기, 잎 2-3장, 대비되는 중심 원반을 두른 꽃잎 5-8장 머리, 포기당 꽃 1-3송이)을 area [w,d]에 흩뿌립니다. density가 바이브 다이얼: 'lush'(풍성하게) / 'sparse'(듬성듬성, 기본) / 'none'(없게) 또는 m²당 개수. varieties는 daisy/cosmos/bellflower 부분집합([] = 셋 다), palette는 꽃 색([] = 흰/노랑/보라). clustering 0-1이 보로노이 패치로 모아 한 패치가 같은 종·같은 색으로 피고, sway가 바람에 머리를 끄덕이며, seed로 배치가 재현됩니다. 품종 ≤3 → 드로우 콜 ≤6. avoidWater(기본 켜짐)는 고인 물·흐르는 물 안에 꽃을 심지 않습니다 — 시내가 지나는 들판에는 물살 속 꽃이 아니라 꽃이 핀 둑이 생깁니다.`}),Q(`Tree3D`,{en:`Procedural tree groves — real branching trunks, textured leaves, one node per forest.`,ko:`프로시저럴 나무 숲 — 진짜 가지가 뻗은 줄기와 텍스처 잎, 숲 하나가 노드 하나.`},{en:`type conifer/broadleaf/dead picks the recipe family; tier is the cost dial: simple = primitive low-poly, medium = light forest presets (≤3k tris/tree), high = full ez-tree presets (8–20k, hero trees). count > 1 scatters a forest patch over area [w,d] — up to 3 seed variants, each branches + leaves InstancedMesh (≤6 draw calls); count × tris/tree is budget-checked at load. seed makes every branch and leaf reproducible; height jitters ±20% per instance; leaves sway in a simplex wind.`,ko:`type conifer/broadleaf/dead가 수종을, tier가 비용을 정합니다: simple = 기존 로우폴리, medium = 가벼운 forest 프리셋(나무당 ≤3k tris), high = 풀 ez-tree 프리셋(8–20k, 주인공 나무). count > 1이면 area [w,d]에 숲 패치를 흩뿌립니다 — 시드 변형 최대 3종, 변형마다 가지+잎 InstancedMesh(드로우 콜 ≤6), count × tris는 로드 시 예산 검사. seed로 가지와 잎이 전부 재현되고 height는 인스턴스마다 ±20% 지터링, 잎은 심플렉스 바람에 흔들립니다.`}),Q(`VoxelGrid3D`,{en:`A Minecraft-style block grid in ONE node.`,ko:`마인크래프트식 블록 그리드 — 노드 하나로.`},{en:`voxels is a list of [x,y,z,palette] integer cells (terrain/island generators emit these). Greedy-meshed and instanced — large worlds stay one draw batch. Game code edits blocks via setBlock/getBlock; emits blocksChanged.`,ko:`voxels는 [x,y,z,팔레트] 정수 셀 목록입니다(terrain/island 생성기가 만들어 냅니다). 그리디 메싱+인스턴싱으로 큰 월드도 드로우 배치 하나를 유지합니다. 게임 코드는 setBlock/getBlock으로 수정하고 blocksChanged가 발산됩니다.`})]},{id:`3d-physics`,label:{en:`3D Physics`,ko:`3D 물리`},intro:{en:`Same model as 2D, in meters with y-up gravity ([0,-9.81,0] default). Colliders: box {size}, sphere {radius}, capsule {radius,height}.`,ko:`2D와 같은 모델을 미터·y-위 중력([0,-9.81,0] 기본)으로. 콜라이더는 box {size}, sphere {radius}, capsule {radius,height}.`},nodes:[Q(`StaticBody3D`,{en:`Immovable 3D collision.`,ko:`움직이지 않는 3D 충돌체.`},{en:`Floors, walls, level geometry. collider {shape:"auto"} takes the shape from the MeshInstance3D or ModelInstance3D the body carries as a child, so the blocker can never be bigger or smaller than what the player sees — the fix for hand-typed extents that leave you stopping in mid-air. A GLB becomes a triangle mesh here, holes and all.`,ko:`바닥·벽·레벨 지형. collider {shape:"auto"}는 바디가 자식으로 들고 있는 MeshInstance3D 또는 ModelInstance3D의 생김새를 그대로 씁니다 — 보이는 것보다 크거나 작은 콜라이더가 생길 수 없습니다. 손으로 적은 크기 때문에 허공에서 막히는 문제의 해법입니다. GLB는 여기서 구멍까지 살아있는 트라이메시가 됩니다.`}),Q(`RigidBody3D`,{en:`Simulated 3D body.`,ko:`시뮬레이션되는 3D 바디.`},{en:`Crates, balls, debris — gravity and impacts drive it.`,ko:`상자·공·파편 — 중력과 충격이 움직입니다.`}),Q(`CharacterBody3D`,{en:`Kinematic 3D character.`,ko:`키네마틱 3D 캐릭터.`},{en:`moveAndSlide with up = +y; isOnFloor for jumps.`,ko:`+y를 위로 moveAndSlide, 점프 판정은 isOnFloor.`}),Q(`Area3D`,{en:`3D overlap sensor.`,ko:`3D 겹침 센서.`},{en:`triggerEnter/Exit — pickups, zones, goals.`,ko:`triggerEnter/Exit — 아이템·존·골인 지점.`}),Q(`CharacterController3D`,{en:`Zero-code 3D movement + camera rig.`,ko:`코드 없는 3D 이동 + 카메라 리그.`},{en:`Put it UNDER a CharacterBody3D. view: thirdPerson (orbit + zoom), firstPerson (eyeHeight, mouseLook), sideView or flightView. Reads moveAction/jumpAction/sprintAction from the scene input map; skinPath turns the visual child to face travel. Intent-level numbers: maxSpeed, jumpVelocity, camDistance.`,ko:`CharacterBody3D의 자식으로 두세요. view는 thirdPerson(궤도+줌), firstPerson(eyeHeight, mouseLook), sideView, flightView 중 하나입니다. 씬 입력 맵의 moveAction/jumpAction/sprintAction을 읽고 skinPath의 비주얼 자식을 진행 방향으로 돌립니다. maxSpeed·jumpVelocity·camDistance 같은 의도 수준의 숫자만 만집니다.`}),Q(`Ragdoll3D`,{en:`A ragdoll for a skinned model — the death that falls.`,ko:`스킨 모델의 래그돌 — 쓰러지는 죽음.`},{en:`Idle it is nothing. activate() reads the skeleton at target (Mixamo names, forgiving lookup), builds a capsule RigidBody3D per limb where the bones are — torso, head, upper arms, forearms, thighs, shins — joins each to its parent with a spherical Joint3D, gives them the velocity of the body they fell out of, and drives the bones from the limbs every frame after. Wire it from Health.died; turn the body collider and controller off beside it (and leave freeOnDeath off — the ragdoll drives that model). mass is shared out by limb, damping calms the flailing, lifetime frees it and hands the skeleton back; reset() does that now. Headless, activate(pose) takes bone positions.`,ko:`가만히 있을 땐 아무것도 아닙니다. activate()가 target의 스켈레톤(Mixamo 이름, 관대한 조회)을 읽어 뼈가 있는 자리에 팔다리마다 캡슐 RigidBody3D를 세우고 — 몸통, 머리, 위팔, 아래팔, 허벅지, 정강이 — 각각을 부모에 구형 Joint3D로 잇고, 떨어져 나온 바디의 속도를 물려준 뒤, 매 프레임 팔다리에서 뼈를 움직입니다. Health.died에서 연결하고, 옆에서 바디 콜라이더와 컨트롤러를 끄세요(freeOnDeath는 끄기 — 래그돌이 그 모델을 움직입니다). mass는 팔다리에 나뉘고, damping이 버둥거림을 잦아들게 하며, lifetime이 스스로 해제하고 스켈레톤을 돌려줍니다. reset()은 지금 당장. 헤드리스에선 activate(pose)가 뼈 위치를 받습니다.`}),Q(`BoneLookAt3D`,{en:`Look-at IK for one bone — the head turns toward a target on top of the animation.`,ko:`본 하나의 룩앳 IK — 애니메이션 위에서 머리가 대상을 향해 돌아갑니다.`},{en:`"target" = ModelInstance3D path, "bone" = bone name (default Head), "lookAt" = the node to watch (e.g. "%Player"). Blends in/out smoothly and DISENGAGES beyond maxAngleDeg (no owl necks); weight sets how far it commits. forwardAxis names the bone's facing axis (mixamo heads: +z). Purely visual — headless no-op.`,ko:`"target"에 ModelInstance3D 경로, "bone"에 본 이름(기본 Head), "lookAt"에 바라볼 노드(예: "%Player")를 줍니다. 부드럽게 페이드 인/아웃하고 maxAngleDeg 밖에서는 해제됩니다(목이 돌아가지 않음). weight로 몰입도를 조절하고 forwardAxis는 본의 정면 축입니다(mixamo 머리: +z). 순수 시각 기능 — 헤드리스에서는 no-op.`}),Q(`InstancedMesh3D`,{en:`Hundreds of copies of one mesh in ONE draw call — rocks, posts, crates.`,ko:`메시 하나의 수백 개 복사본을 드로우콜 1개로 — 바위, 말뚝, 상자.`},{en:`Same mesh/size/material surface as MeshInstance3D; "transforms" places the copies — each row [x, y, z, yawDeg?, scale?]. Replace the whole array to update (mutations are not watched). The scattering workhorse for open worlds. collider: {} makes the whole field solid — every row gets its own collider SHAPED LIKE THE MESH (a faceted gem stone collides as that stone's hull, not as a ball tucked inside it), all hanging off one fixed body. A boulder field the player walks straight through is the tell that a world is scenery rather than a place.`,ko:`MeshInstance3D와 같은 mesh/size/material 표면에 "transforms"로 복사본을 배치합니다 — 각 행은 [x, y, z, yawDeg?, scale?]. 갱신은 배열 전체 교체로 하세요(내부 변경은 감지되지 않음). 오픈월드 스캐터링의 주력입니다. collider: {}를 주면 필드 전체가 단단해집니다 — 행마다 메시 생김새 그대로의 콜라이더가 생기고(각진 gem 바위는 안에 박힌 구가 아니라 그 바위 자신의 볼록 껍질로 부딪힙니다), 전부 하나의 고정 바디에 붙습니다. 플레이어가 통과해버리는 바위밭은 그 세계가 배경 그림이라는 신호입니다.`}),Q(`BoneAttachment3D`,{en:`Rides a skeleton bone of an animated model — swords in hands, hats on heads.`,ko:`애니메이션 모델의 스켈레톤 본을 따라다님 — 손에 쥔 검, 머리 위 모자.`},{en:`"target" is a node path to the ModelInstance3D, "bone" the bone name ("RightHand" also matches the Mixamo spellings). Children inherit the live animated transform; this node's own position/rotation become a bone-space offset. Purely visual — headless it stays where its props put it, so keep gameplay checks range-based.`,ko:`"target"에 ModelInstance3D 노드 경로, "bone"에 본 이름을 줍니다("RightHand"는 Mixamo 표기도 자동 매칭). 자식들이 살아있는 애니메이션 트랜스폼을 물려받고, 이 노드의 position/rotation은 본 기준 오프셋이 됩니다. 순수 시각 기능 — 헤드리스에서는 prop 위치에 머무니 게임 판정은 거리 기반으로 유지하세요.`}),Q(`Trail3D`,{en:`A fading world-space ribbon behind the parent — wingtip trails, sword arcs, tyre streaks.`,ko:`부모 뒤로 남는 페이드아웃 월드 리본 — 날개끝 궤적, 검격 궤적, 타이어 자국.`},{en:"Child of the moving node. Records the world position over `seconds` and renders a camera-facing strip that tapers and fades to the tail. width (m), color, opacity, additive for glowing energy trails, minDistance filters jitter. emitting: false stops laying new ribbon while the old tail fades out.",ko:`움직이는 노드의 자식으로 두세요. seconds 동안의 월드 위치를 기록해 꼬리로 갈수록 가늘어지고 투명해지는 카메라 지향 스트립을 그립니다. width(m), color, opacity, 빛나는 에너지 궤적에는 additive, minDistance로 떨림을 걸러냅니다. emitting: false면 새 리본만 멈추고 기존 꼬리는 자연스럽게 사라집니다.`}),Q(`Joint3D`,{en:`A physics joint linking its parent body to a target body — weld, ball joint, rope, spring.`,ko:`부모 바디와 대상 바디를 잇는 물리 조인트 — 용접, 볼 조인트, 로프, 스프링.`},{en:`Child of body A; "target" is a node path to body B. type: fixed (rigid weld) / spherical (ball joint at the anchors) / revolute (a HINGE about axis — a door, a wheel, a lever — with limits [minDeg, maxDeg] and a motorSpeed in deg/s; angle reads it back) / prismatic (a SLIDE along axis — a portcullis, an elevator — with limits in metres and a motorSpeed in m/s; travel reads it back) / rope (caps anchor distance at length m; 0 = measured at creation) / spring (pulls toward length with stiffness/damping). anchor/targetAnchor are LOCAL meter offsets.`,ko:`바디 A의 자식으로 두고 "target"에 바디 B의 노드 경로를 줍니다. type: fixed(강체 용접) / spherical(앵커 볼 조인트) / revolute(axis를 축으로 도는 경첩 — 문, 바퀴, 레버; limits [minDeg, maxDeg]와 motorSpeed deg/s, angle로 읽음) / prismatic(axis를 따라 미끄러지는 슬라이드 — 내리닫이문, 엘리베이터; limits 미터, motorSpeed m/s, travel로 읽음) / rope(앵커 간 거리를 length m로 제한, 0이면 생성 시 실측) / spring(stiffness/damping으로 length를 향해 당김). anchor/targetAnchor는 로컬 미터 오프셋.`}),Q(`Vehicle3D`,{en:`A car in one node — wheels on springs, throttle, steering, brake.`,ko:`노드 하나로 자동차 — 스프링 위 바퀴, 가속, 조향, 브레이크.`},{en:`Goes UNDER a dynamic RigidBody3D chassis (a hard error anywhere else). wheels lists each wheel: position in the chassis frame, radius, rest (spring length), steer and drive flags. Reads moveAction (y = throttle, x = steer) and brakeAction every step; engineForce, brakeForce, maxSteerDeg, the suspension stiffness/compression/relaxation, maxTravel, friction and sideFriction are the feel. Forward is +z, like a character. Children named Wheel0…N and their Hub are posed for you (steer and roll), so a tyre mesh under a Hub just works; speed and wheel(i) read back. Zones (Area3D) are driven through, never onto.`,ko:`동적 RigidBody3D 차체 아래에 둡니다(다른 곳이면 하드 에러). wheels에 바퀴마다 차체 기준 position, radius, rest(스프링 길이), steer·drive 플래그를 적습니다. 매 스텝 moveAction(y = 가속, x = 조향)과 brakeAction을 읽고, engineForce·brakeForce·maxSteerDeg·서스펜션 stiffness/compression/relaxation·maxTravel·friction·sideFriction이 감각을 정합니다. 앞은 캐릭터처럼 +z. Wheel0…N 자식과 그 Hub는 자동으로 자세가 잡히므로(조향·회전) Hub 아래 타이어 메시가 그대로 돕니다. speed와 wheel(i)로 읽어옵니다. 구역(Area3D)은 위로 올라타지 않고 통과합니다.`})]},{id:`network`,label:{en:`Network`,ko:`네트워크`},intro:{en:`Multiplayer is transport-agnostic: the engine speaks one NetworkTransport interface (built-in offline Loopback + an @agent8/gameserver adapter). The scene declares replication; one owner node per player broadcasts its sync keys.`,ko:`멀티플레이어는 트랜스포트 불가지론입니다 — 엔진은 NetworkTransport 인터페이스 하나만 사용합니다(내장 오프라인 Loopback + @agent8/gameserver 어댑터). 복제는 씬이 선언하며, 플레이어당 하나의 owner 노드가 sync 키를 송출합니다.`},nodes:[Q(`NetworkSpawner`,{en:`Spawns a registered scene per remote player/entity.`,ko:`원격 플레이어/엔티티마다 등록된 씬을 생성.`},{en:`source "users" mirrors every OTHER account in the room (self skipped); "collection:<id>" mirrors a room collection. Replicated sync patches apply to each instance; position interpolates. Emits spawned/despawned.`,ko:`source "users"는 방의 다른 모든 계정을 미러링하고(자신 제외) "collection:<id>"는 방 컬렉션을 미러링합니다. 복제 sync 패치가 인스턴스에 적용되고 position은 보간됩니다. spawned/despawned를 발산합니다.`})]}],qU=`overview`,JU=null;function YU(){document.querySelector(`#docs`)?.removeAttribute(`hidden`),QU()}function XU(){document.querySelector(`#docs`)?.setAttribute(`hidden`,``)}function ZU(){let e=document.querySelector(`#docs`);e&&(e.addEventListener(`pointerdown`,t=>{t.target===e&&XU()}),document.querySelector(`#docs-close`)?.addEventListener(`click`,XU))}function QU(){let e=document.querySelector(`#docs-tabs`),t=document.querySelector(`#docs-body`);if(!e||!t)return;e.textContent=``;let n=(t,n)=>{let r=document.createElement(`button`);r.type=`button`,r.className=`docs-tab${qU===t?` active`:``}`,r.textContent=n,r.addEventListener(`click`,()=>{qU=t,JU=null,QU()}),e.appendChild(r)};n(`overview`,rU({en:`Overview`,ko:`개요`}));for(let e of KU)n(e.id,rU(e.label));if(t.textContent=``,qU===`overview`){$U(t);return}let r=KU.find(e=>e.id===qU);r&&eW(t,r)}function $U(e){let t=document.createElement(`h2`);t.textContent=rU(GU.title),e.appendChild(t);for(let t of GU.sections){let n=document.createElement(`h3`);n.textContent=rU(t.heading);let r=document.createElement(`p`);r.textContent=rU(t.text),e.append(n,r)}}function eW(e,t){let n=document.createElement(`p`);n.className=`docs-intro`,n.textContent=rU(t.intro),e.appendChild(n);for(let n of t.nodes){let t=document.createElement(`div`);t.className=`docs-node${JU===n.type?` open`:``}`;let r=document.createElement(`button`);r.type=`button`,r.className=`docs-node-head`;let i=document.createElement(`span`);i.className=`tree-icon`,i.appendChild(oU(n.type));let a=document.createElement(`strong`);a.textContent=n.type;let o=document.createElement(`span`);if(o.className=`docs-summary`,o.textContent=rU(n.summary),r.append(i,a,o),r.addEventListener(`click`,()=>{JU=JU===n.type?null:n.type,QU()}),t.appendChild(r),JU===n.type){let e=document.createElement(`div`);e.className=`docs-detail`;for(let t of n.body){let n=document.createElement(`p`);n.textContent=rU(t),e.appendChild(n)}e.appendChild(tW(n.type)),t.appendChild(e)}e.appendChild(t)}}function tW(e){let t=document.createElement(`table`);t.className=`docs-props`;let n=document.createElement(`tr`);for(let e of[rU({en:`prop`,ko:`prop`}),rU({en:`default`,ko:`기본값`})]){let t=document.createElement(`th`);t.textContent=e,n.appendChild(t)}t.appendChild(n);try{let n=ht(e);for(let[e,r]of Object.entries(n)){let n=document.createElement(`tr`),i=document.createElement(`td`);i.className=`mono`,i.textContent=e;let a=document.createElement(`td`);a.className=`mono`,a.textContent=JSON.stringify(r.default),n.append(i,a),t.appendChild(n)}}catch{}return t}function $(e){return Math.round(e*100)/100}function nW(e,t,n,r,i){return{name:e,type:`StaticBody3D`,props:{collider:{shape:`box`,size:t},position:n,...i?{rotation:i}:{}},children:[{name:`Skin`,type:`MeshInstance3D`,props:{mesh:`box`,size:t,...r}}]}}function rW(e,t,n,r,i,a){let o=$(r.range(i[0],i[1])),s=$(r.range(.5,.7));return{name:`Rock${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[t,$(o*s*.6),n],snapToGround:!1,rotation:[0,r.int(0,359),0],scale:[o,$(o*s),$(o*r.range(.8,1.1))],material:{color:a??iW(r),roughness:1},castShadow:!0}}}function iW(e){let t=Math.round(e.range(110,160)).toString(16).padStart(2,`0`);return`#${t}${t}${t}`}function aW(e){return[{name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(e*.8),$(e*1.5),$(e*.6)],intensity:1,castShadow:!0,shadowArea:$(e*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-e*.8),$(e*.8),$(-e*.6)],intensity:.4,color:`#b9d4ff`}}]}function oW(e,t){return e===void 0?t:typeof e==`number`?[e,e]:e}function sW(e,t,n){return Math.min(Math.max(e,t),n)}var cW=[`boxes`,`ruins`,`garden`],lW=.5,uW=.1,dW=2,fW={boxes:{floor:`#3f3f3f`,wall:`#55504a`,obstacles:[`#b0413e`,`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#878787`]},ruins:{floor:`#7d766b`,wall:`#8a8378`,obstacles:[`#8a8378`,`#979085`,`#a39a8d`,`#7b746a`]},garden:{floor:`#4d7c3a`,wall:`#2f6b2f`,obstacles:[`#2f6b2f`,`#3a7a38`,`#356e33`]}};function pW(e){let{seed:t,width:n=30,depth:r=30,wallHeight:i=3,obstacles:a=8,theme:o=`boxes`}=e;if(!cW.includes(o))throw new L(`BAD_FORMAT`,`generateArena theme must be one of [${cW.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...cW]});let s=fW[o],c=new Ee(t),l=[nW(`Floor`,[n,uW,r],[0,-.1/2,0],{material:{color:s.floor,roughness:1},receiveShadow:!0})],u=i/2,d=[n+lW*2,i,lW],f=[lW,i,r],p={material:{color:s.wall,roughness:.9},receiveShadow:!0};l.push(nW(`Wall1`,d,[0,u,-(r+lW)/2],p),nW(`Wall2`,d,[0,u,(r+lW)/2],p),nW(`Wall3`,f,[-(n+lW)/2,u,0],p),nW(`Wall4`,f,[(n+lW)/2,u,0],p)),o===`ruins`?l.push(...hW(c,s,n,r,i,a)):l.push(...mW(c,s,n,r,i,a,o)),o===`garden`&&l.push(...gW(c,n,r));let m=Math.max(n,r);return l.push({name:`Sun`,type:`DirectionalLight3D`,props:{position:[$(m*.8),$(m*1.5),$(m*.6)],intensity:1,castShadow:!0,shadowArea:$(m*1.2)}},{name:`FillLight`,type:`DirectionalLight3D`,props:{position:[$(-m*.8),$(m*.8),$(-m*.6)],intensity:.4,color:`#b9d4ff`}},{name:`Lamp`,type:`OmniLight3D`,props:{position:[0,$(i+2),0],intensity:.5,color:`#fff3d6`,range:$(m)}}),{name:`Arena`,type:`Node3D`,children:l}}function mW(e,t,n,r,i,a,o){let s=[],c=o===`garden`?Math.min(n,r)*.16:0;for(let o=1;o<=a;o++){let a=[$(e.range(.8,2.6)),$(e.range(.8,Math.max(1.2,i*.8))),$(e.range(.8,2.6))],l=$(e.range(-(n/2-dW),n/2-dW)),u=$(e.range(-(r/2-dW),r/2-dW));if(c>0&&Math.hypot(l,u)<c+1.5){let t=Math.max(Math.hypot(l,u),.001);l=$(l/t*(c+1.5+e.range(0,2))),u=$(u/t*(c+1.5+e.range(0,2)))}let d=e.int(0,359);s.push(nW(`Obstacle${o}`,a,[l,$(a[1]/2),u],{material:{color:e.pick(t.obstacles),roughness:.8},castShadow:!0},[0,d,0]))}return s}function hW(e,t,n,r,i,a){let o=[];if(a<=0)return o;let s=Math.max(1,Math.round(Math.sqrt(a/2))),c=Math.ceil(a/s),l=n-dW*2,u=r-dW*2,d=0;for(let n=0;n<s&&d<a;n++){let r=$(s===1?0:-u/2+n/(s-1)*u);for(let n=0;n<c&&d<a;n++){d++;let a=$((c===1?0:-l/2+n/(c-1)*l)+e.range(-.4,.4)),s=$(e.next()>.35?e.range(i*.7,i*1.2):e.range(.4,.9)),u=$(e.range(.8,1.2));o.push(nW(`Obstacle${d}`,[u,s,u],[a,$(s/2),$(r+e.range(-.4,.4))],{material:{color:e.pick(t.obstacles),roughness:.95},castShadow:!0},[0,e.int(-8,8),0]))}}return o}function gW(e,t,n){let r=[],i=Math.min(t,n)*.16,a=r=>{let a=Math.min(t,n)/2-r/2-1,o=$(e.range(-a,a)),s=$(e.range(-a,a)),c=Math.max(Math.hypot(o,s),.001);return c<i+r/2&&(o=$(o/c*(i+r/2+.5)),s=$(s/c*(i+r/2+.5))),[o,s]};for(let i=1;i<=3;i++){let o=$(Math.min(t,n)*e.range(.18,.26)),[s,c]=a(o);r.push({name:`Grass${i}`,type:`Foliage3D`,props:{kind:`grass`,area:[o,o],density:10,seed:e.int(1,1e9),position:[s,0,c]}})}for(let i=1;i<=2;i++){let o=$(Math.min(t,n)*e.range(.12,.18)),[s,c]=a(o);r.push({name:`FlowerBed${i}`,type:`Flowers3D`,props:{density:`lush`,clustering:.3,area:[o,o],seed:e.int(1,1e9),position:[s,0,c]}})}return r.push({name:`Pool`,type:`Water3D`,props:{size:[$(i*2),$(i*2)],position:[0,.3,0],waveHeight:.04}}),r}var _W=32,vW=[4,8],yW=`#332f3a`,bW=`#6b6357`;function xW(e){let{seed:t,rooms:n=5}=e,[r,i]=oW(e.size,[960,720]),a=Math.max(8,Math.floor(r/_W)),o=Math.max(8,Math.floor(i/_W)),s=new Ee(t),c=[];for(let e=0;e<n*12&&c.length<n;e++){let e=s.int(vW[0],vW[1]),t=s.int(vW[0],vW[1]),n={x:s.int(1,Math.max(1,a-e-1)),y:s.int(1,Math.max(1,o-t-1)),w:e,h:t};c.some(e=>SW(e,n,1))||c.push(n)}let l=new Set,u=e=>{for(let t=e.y;t<e.y+e.h;t++)for(let n=e.x;n<e.x+e.w;n++)l.add(`${n},${t}`)};for(let e of c)u(e);let d=[];for(let e=1;e<c.length;e++){let[t,n]=CW(c[e-1]),[r,i]=CW(c[e]),a={x:Math.min(t,r),y:n,w:Math.abs(t-r)+1,h:1},o={x:r,y:Math.min(n,i),w:1,h:Math.abs(n-i)+1};for(let[t,n]of[[`H`,a],[`V`,o]])u(n),(n.w>1||n.h>1)&&d.push({name:`Corridor${e}${t}`,rect:n})}let f=new Set;for(let e of l){let[t,n]=e.split(`,`).map(Number);for(let e=-1;e<=1;e++)for(let r=-1;r<=1;r++){let i=`${t+r},${n+e}`;l.has(i)||f.add(i)}}let p=-(a*_W)/2,m=-(o*_W)/2,h=(e,t,n)=>({name:e,type:`ColorRect2D`,props:{position:[p+(t.x+t.w/2)*_W,m+(t.y+t.h/2)*_W],size:[t.w*_W,t.h*_W],color:n}}),g=c.map((e,t)=>h(`Room${t+1}`,e,yW));for(let e of d)g.push(h(e.name,e.rect,yW));let _=0;for(let e=-1;e<=o;e++){let t=-1;for(;t<=a;){if(!f.has(`${t},${e}`)){t++;continue}let n=1;for(;t+n<=a&&f.has(`${t+n},${e}`);)n++;_++;let r=[n*_W,_W];g.push({name:`Wall${_}`,type:`StaticBody2D`,props:{position:[p+(t+n/2)*_W,m+(e+.5)*_W],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:bW}}]}),t+=n}}return{name:`Dungeon`,type:`Node2D`,children:g}}function SW(e,t,n){return e.x-n<t.x+t.w&&e.x+e.w+n>t.x&&e.y-n<t.y+t.h&&e.y+e.h+n>t.y}function CW(e){return[Math.floor(e.x+e.w/2),Math.floor(e.y+e.h/2)]}var wW=[[0,-1],[1,0],[0,1],[-1,0]];function TW(e,t,n){let r=2*t+1,i=2*n+1,a=Array.from({length:i},()=>Array(r).fill(!1)),o=(e,t)=>{a[t][e]=!0};o(1,1);let s=new Set([`0,0`]),c=[[0,0]];for(;c.length>0;){let[r,i]=c[c.length-1],a=[];for(let[e,o]of wW){let c=r+e,l=i+o;c>=0&&c<t&&l>=0&&l<n&&!s.has(`${c},${l}`)&&a.push([c,l])}if(a.length===0){c.pop();continue}let[l,u]=e.pick(a);s.add(`${l},${u}`),o(2*l+1,2*u+1),o(r+l+1,i+u+1),c.push([l,u])}return o(0,1),o(2*t,2*n-1),{cols:t,rows:n,cells:a}}var EW=[`stone`,`hedge`,`canyon`],DW=.1,OW=`https://agent8-games.verse8.io/assets/3D/default/textures/wall`,kW=`https://agent8-games.verse8.io/assets/3D/default/textures/terrain`,AW={stone:{wall:{color:`#e8e2d8`,map:`${OW}/blocks.png`,normalMap:`${OW}/blocks_normal.png`,tile:2,roughness:.95},floor:{color:`#99938a`,map:`${kW}/stone.png`,normalMap:`${kW}/stone_normal.png`,tile:3,roughness:1},cap:`#6b5848`,pillar:`#cfc8bb`,path:`#665f55`,sun:{color:`#c9d6ea`,intensity:.75,height:.5},fill:`#9fb4cc`,mood:{sky:{elevationDeg:10,azimuthDeg:150,turbidity:16,rayleigh:3.2},fog:{near:.5,far:3.5,color:`#86909c`},exposure:.82,ambient:{color:`#c9d4e2`,intensity:.12}}},hedge:{wall:{color:`#55a83e`,map:`${kW}/grass.png`,normalMap:`${kW}/grass_normal.png`,tile:1.4,roughness:1},floor:{color:`#86b06d`,map:`${kW}/grass.png`,normalMap:`${kW}/grass_normal.png`,tile:3,roughness:1},pillar:`#3d7531`,path:`#7d6845`,sun:{color:`#e9eee6`,intensity:.7,height:1},fill:`#b9c8b4`,mood:{sky:{elevationDeg:35,azimuthDeg:150,turbidity:18,rayleigh:4.2},fog:{near:.8,far:5,color:`#aab8a6`},exposure:.88,ambient:{color:`#dde5d8`,intensity:.15}}},canyon:{wall:{color:`#f0b070`,map:`${kW}/stone.png`,normalMap:`${kW}/stone_normal.png`,tile:2.4,roughness:1},floor:{color:`#e3c193`,map:`${kW}/sand.png`,normalMap:`${kW}/sand_normal.png`,tile:3.5,roughness:1},pillar:`#d8a868`,path:`#a98a58`,sun:{color:`#ffb572`,intensity:1.15,height:.35},fill:`#caa37e`,mood:{sky:{elevationDeg:9,azimuthDeg:230,turbidity:9,rayleigh:3.5},fog:{near:.7,far:4.5,color:`#c79c6e`},exposure:.92,ambient:{color:`#ffdcb6`,intensity:.13}}}};function jW(e,t,n){return{color:e.color,roughness:e.roughness,map:e.map,...e.normalMap?{normalMap:e.normalMap}:{},repeat:[$(t/e.tile),$(n/e.tile)]}}var MW=10;function NW(e){let{seed:t,width:n=8,depth:r=8,cellSize:i=2,wallHeight:a=2.5,theme:o=`stone`}=e;if(!EW.includes(o))throw new L(`BAD_FORMAT`,`generateMaze theme must be one of [${EW.join(`, `)}], got '${o}'.`,{prop:`theme`,validOptions:[...EW]});let s=AW[o],c=new Ee(t),l=TW(c,n,r),u=2*n+1,d=2*r+1,f=$(u*i),p=$(d*i),m=(e,t)=>[$((e+.5)*i-f/2),$((t+.5)*i-p/2)],h=[nW(`Floor`,[f,DW,p],[0,-.1/2,0],{material:jW(s.floor,f,p),receiveShadow:!0})],g=[],_=0;for(let e=0;e<d;e++){let t=0;for(;t<u;){if(l.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<u&&!l.cells[e]?.[t+n];)n++;g.push({gx:t,gz:e,run:n}),_++;let r=$(n*i);h.push(nW(`Wall${_}`,[r,a,i],[$((t+n/2)*i-f/2),$(a/2),$((e+.5)*i-p/2)],{material:jW(s.wall,r,a),castShadow:!0,receiveShadow:!0})),t+=n}}return s.cap&&h.push(...PW(g,i,a,f,p,s.cap)),h.push(...FW(c,l,i,a,m,s)),o===`hedge`?(h.push(...zW(c,g,i,a,m)),h.push(...BW(c,l,i,m,n,r))):o===`canyon`&&h.push(...VW(c,g,i,a,m)),h.push(...LW(l,i,a,m,s)),h.push(...aW(Math.max(f,p)).map((e,t)=>{if(t!==0)return{...e,props:{...e.props,color:s.fill}};let n=e.props?.position;return{...e,props:{...e.props,color:s.sun.color,intensity:s.sun.intensity,position:[n[0]??0,$((n[1]??0)*s.sun.height),n[2]??0]}}})),{name:`Maze`,type:`Node3D`,children:h}}function PW(e,t,n,r,i,a){return e.map((e,o)=>({name:`Cap${o+1}`,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(e.run*t+.16),.12,$(t+.16)],position:[$((e.gx+e.run/2)*t-r/2),$(n+.06),$((e.gz+.5)*t-i/2)],material:{color:a,roughness:1},castShadow:!0,receiveShadow:!0}}))}function FW(e,t,n,r,i,a){let o=[],s=(e,n)=>t.cells[n]?.[e]===!1;for(let e=2;e<t.cells.length-1;e+=2)for(let n=2;n<(t.cells[e]?.length??0)-1;n+=2)s(n,e)&&Number(s(n-1,e))+Number(s(n+1,e))+Number(s(n,e-1))+Number(s(n,e+1))>=3&&o.push([n,e]);let c=Math.min(MW,o.length),l=[],u=new Set,d=$(n*1.2),f=$(r*1.12);for(let t=1;t<=c;t++){let n=e.int(0,o.length-1);for(;u.has(n);)n=(n+1)%o.length;u.add(n);let[r,s]=o[n],[c,p]=i(r,s);l.push(IW(`Pillar${t}`,c,p,d,f,a))}return l}function IW(e,t,n,r,i,a){return{name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[r,i,r],position:[t,$(i/2),n],material:{...jW(a.wall,r,i),color:a.pillar},castShadow:!0,receiveShadow:!0}}}function LW(e,t,n,r,i){let a=2*e.cols,o=2*e.rows-1,s=$(t*1.1),c=$(n*1.25),l=[[0,0],[0,2],[a,o-1],[a,o+1]].map(([e,t],n)=>{let[a,o]=r(e,t);return IW(`Gate${n+1}`,a,o,s,c,i)});for(let[e,n,s]of[[`EntrancePath`,0,1],[`ExitPath`,a,o]]){let[a,o]=r(n,s);l.push({name:e,type:`MeshInstance3D`,props:{mesh:`box`,size:[$(t*.96),.04,$(t*.96)],position:[a,.02,o],material:{...jW(i.floor,t,t),color:i.path},receiveShadow:!0}})}return l}var RW=10;function zW(e,t,n,r,i){return[...t].filter(e=>e.run>=2).sort((e,t)=>t.run-e.run||e.gz-t.gz||e.gx-t.gx).slice(0,RW).map((t,a)=>{let[,o]=i(t.gx,t.gz),[s]=i(t.gx,t.gz),[c]=i(t.gx+t.run-1,t.gz);return{name:`HedgeTop${a+1}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[$(t.run*n*.92),$(n*.7)],density:14,height:.35,sway:.4,colorA:`#2f5e26`,colorB:`#5d8a3c`,seed:e.int(1,1e9),position:[$((s+c)/2),r,o]}}})}function BW(e,t,n,r,i,a){let o=[];for(let e=0;e<t.cells.length;e++)for(let n=0;n<(t.cells[e]?.length??0);n++)t.cells[e]?.[n]&&o.push([n,e]);let s=Math.min(o.length,Math.max(3,Math.floor(i*a/12))),c=[],l=new Set;for(let t=1;t<=s&&l.size<o.length;t++){let i=e.int(0,o.length-1);for(;l.has(i);)i=(i+1)%o.length;l.add(i);let[a,s]=o[i],[u,d]=r(a,s),f=$(n*.8);c.push({name:`Grass${t}`,type:`Foliage3D`,props:{kind:`grass`,area:[f,f],density:8,seed:e.int(1,1e9),position:[u,0,d]}})}return c}function VW(e,t,n,r,i){let a=[];if(t.length===0)return a;let o=Math.min(8,t.length);for(let s=1;s<=o;s++){let o=e.pick(t),[c,l]=i(o.gx+e.int(0,o.run-1),o.gz),u=rW(s,c,l,e,[.3,$(n*.35)],`#8f7355`),d=u.props?.position;d[1]=$(d[1]+r),a.push(u)}return a}var HW=`#23222b`,UW=`#5f6672`;function WW(e){let{seed:t,cols:n=10,rows:r=8,cellPx:i=64}=e,a=TW(new Ee(t),n,r),o=2*n+1,s=2*r+1,c=$(o*i),l=$(s*i),u=[{name:`Floor`,type:`ColorRect2D`,props:{size:[c,l],color:HW}}],d=0;for(let e=0;e<s;e++){let t=0;for(;t<o;){if(a.cells[e]?.[t]){t++;continue}let n=1;for(;t+n<o&&!a.cells[e]?.[t+n];)n++;d++;let r=[$(n*i),i];u.push({name:`Wall${d}`,type:`StaticBody2D`,props:{position:[$((t+n/2)*i-c/2),$((e+.5)*i-l/2)],collider:{shape:`rect`,size:r}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:r,color:UW}}]}),t+=n}}return{name:`Maze2D`,type:`Node2D`,children:u}}var GW=16,KW=[`#5b8266`,`#3e6990`,`#a26b38`,`#6d5a96`,`#b0413e`];function qW(e){let{seed:t,count:n=10,width:r=[80,160],gapX:i=[40,120],stepY:a=[-80,40],start:o=[0,300]}=e,s=new Ee(t),c=[],l=$(s.range(r[0],r[1])),u=o[0],d=o[1];for(let e=1;e<=n&&(c.push(JW(e,u,d,l,s.pick(KW))),e!==n);e++){let e=$(s.range(r[0],r[1])),t=$(s.range(i[0],i[1]));u=$(u+l/2+t+e/2),d=$(d+s.range(a[0],a[1])),l=e}return{name:`Platforms`,type:`Node2D`,children:c}}function JW(e,t,n,r,i){return{name:`Platform${e}`,type:`StaticBody2D`,props:{position:[t,n],collider:{shape:`rect`,size:[r,GW]}},children:[{name:`Skin`,type:`ColorRect2D`,props:{size:[r,GW],color:i}}]}}var YW=[3,5],XW=3,ZW={color:`#ffffff`,roughness:1,emissive:`#ffffff`,emissiveIntensity:.25};function QW(e){let{seed:t,count:n=8,altitude:r=18}=e,[i,a]=oW(e.area,[60,60]),o=new Ee(t),s=[];for(let e=1;e<=n;e++){let t=o.int(YW[0],YW[1]),n=[];for(let e=1;e<=t;e++){let r=$(o.range(1,2.2));n.push({name:`Puff${e}`,type:`MeshInstance3D`,props:{mesh:`sphere`,size:[1,1,1],position:[$((e-(t+1)/2)*o.range(1,1.6)),$(o.range(-.3,.3)),$(o.range(-.6,.6))],scale:[$(r*o.range(1.1,1.6)),$(r*.55),r],material:ZW}})}s.push({name:`Cloud${e}`,type:`Node3D`,props:{position:[$(o.range(-i/2,i/2)),$(r+o.range(-3,XW)),$(o.range(-a/2,a/2))]},children:n})}return{name:`Clouds`,type:`Node3D`,props:{snapToGround:!1},children:s}}var $W=[`island`,`alpine`,`plains`,`desert`,`meadow`,`forest`,`savanna`,`snow`,`wetland`,`volcanic`],eG=128,tG=20,nG=.8,rG=.12,iG={island:{splat:`island`,maxHeight:4.5,sun:`#fff4d6`,fill:`#b9d4ff`,sky:{elevationDeg:38,azimuthDeg:145,turbidity:2.6,rayleigh:1.1},fog:{near:1,far:4},iblIntensity:.72},alpine:{splat:`alpine`,maxHeight:8,roughness:.65,detail:5,sun:`#f4f7ff`,fill:`#c9d8f2`,sky:{elevationDeg:45,azimuthDeg:35,turbidity:1.4,rayleigh:1.3},fog:{near:1.8,far:6.5},sunIntensity:1.1,exposure:.92,iblIntensity:.72},plains:{splat:`plains`,maxHeight:4,sun:`#fff2cf`,fill:`#bcd3ef`,sky:{elevationDeg:36,azimuthDeg:140,turbidity:2.4,rayleigh:1},fog:{near:.9,far:4},iblIntensity:.58},desert:{splat:`desert`,maxHeight:5,sun:`#ffe3b3`,fill:`#e8c9a6`,sky:{elevationDeg:42,azimuthDeg:160,turbidity:7,rayleigh:.6},fog:{near:.8,far:3.2,color:`#e8d3ae`},sunIntensity:1.35,iblIntensity:.75},meadow:{splat:`grassland`,maxHeight:1.2,sun:`#fff8e2`,fill:`#bfe0c9`,sky:{elevationDeg:55,azimuthDeg:125,turbidity:2.4,rayleigh:.95},fog:{near:1,far:4.4},sunIntensity:2.6,exposure:1.12,iblIntensity:.62},forest:{splat:`forest`,maxHeight:2.5,sun:`#ffdca8`,fill:`#a9c8b4`,sky:{elevationDeg:29,azimuthDeg:120,turbidity:5.5,rayleigh:1},fog:{near:.22,far:1.8,color:`#9fb494`},sunIntensity:2.6,ambient:.26,iblIntensity:.55},savanna:{splat:`savanna`,maxHeight:3,sun:`#ffdca0`,fill:`#e6d2a4`,sky:{elevationDeg:34,azimuthDeg:150,turbidity:5,rayleigh:.7},fog:{near:1,far:4.2,color:`#e3cf9f`},sunIntensity:2,exposure:1.05,iblIntensity:.6},snow:{splat:`snow`,maxHeight:2.2,sun:`#dfe9ff`,fill:`#c2d2f0`,sky:{elevationDeg:22,azimuthDeg:35,turbidity:1.6,rayleigh:1.6},fog:{near:1.2,far:5,color:`#dbe6f5`},sunIntensity:1,exposure:.9,iblIntensity:.72},wetland:{splat:`wetland`,maxHeight:1.4,sun:`#d6ddc8`,fill:`#9fb29a`,sky:{elevationDeg:24,azimuthDeg:115,turbidity:9,rayleigh:1.1},fog:{near:.5,far:2,color:`#92a288`},sunIntensity:1.5,exposure:.94,ambient:.24,iblIntensity:.66},volcanic:{splat:`volcanic`,maxHeight:4,roughness:.7,sun:`#ff8a4a`,fill:`#7a4a3a`,sky:{elevationDeg:14,azimuthDeg:135,turbidity:10,rayleigh:.3},fog:{near:.18,far:1.4,color:`#2a211c`},sunIntensity:1.7,exposure:.86,ambient:.22,iblIntensity:.5}};function aG(e){let{seed:t,theme:n=`island`,size:r=200,water:i=!1}=e,a=iG[n];if(!a)throw new L(`BAD_FORMAT`,`generateTerrain theme must be one of [${$W.join(`, `)}], got '${n}'.`,{prop:`theme`,validOptions:[...$W]});let o=Math.max(2,Math.round(e.resolution??eG)),s=e.maxHeight||a.maxHeight,c=new Ee(t),l=n===`island`,u=e=>Mj({width:r,depth:r,segsX:o,segsZ:o,maxHeight:e,seed:t,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},islandEdge:l}),d=u(s);if(l)for(let e=0;e<3;e++){let e=sG(d)-tG,t=d.maxHeight-d.minHeight,n=d.minHeight+rG*t;if(e+nG<=n)break;let r=tG-nG,i=sG(d)-d.minHeight-rG*t;s=$(s*Math.min(r/i*.95,.9)),d=u(s)}let f=[{name:`Ground`,type:`StaticBody3D`,props:{collider:{shape:`heightfield`}},children:[{name:`Surface`,type:`Terrain3D`,props:{size:[r,r],maxHeight:s,seed:t,theme:a.splat,...a.roughness===void 0?{}:{roughness:a.roughness},...a.detail===void 0?{}:{detail:a.detail},...o===eG?{}:{resolution:o}}}]}],p=n===`wetland`;if(l)f.push({name:`Sea`,type:`Water3D`,props:{size:[r*8,r*8],position:[0,oG(d),0],opacity:1}});else if(p){let e=d.maxHeight-d.minHeight||1,t=$(d.minHeight+.22*e);f.push({name:`Swamp`,type:`Water3D`,props:{size:[r,r],position:[0,t,0],waveHeight:.02,quality:`simple`,color:`#3a4a30`,opacity:.95}})}else if(i){let e=$(d.minHeight+.1*(d.maxHeight-d.minHeight));f.push({name:`Lake`,type:`Water3D`,props:{size:[r,r],position:[0,e,0],waveHeight:.04}})}return f.push(...CG(n,c,d,r)),l&&f.push(QW({seed:c.int(1,1e9),count:6,area:r,altitude:Math.round(d.maxHeight+12)})),f.push(...aW(r).map((e,t)=>wG(e,t===0?a.sun:a.fill,t===0?a.sunIntensity??1.7:void 0))),{name:`Terrain`,type:`Node3D`,children:f}}function oG(e){let t=sG(e)-tG,n=e.minHeight+rG*(e.maxHeight-e.minHeight);return $(Math.max(Math.min(t+nG,n),t+.55))}function sG(e){let t=-1/0,n=e.width/2,r=e.depth/2,i=e.segsX;for(let a=0;a<=i;a++){let o=-n+a/i*e.width,s=-r+a/i*e.depth;t=Math.max(t,e.baseHeight(o,-r),e.baseHeight(o,r),e.baseHeight(-n,s),e.baseHeight(n,s))}return t}function cG(e,t,n){let r=Math.min(t.width/2-n.margin,n.within??1/0),i=t.maxHeight-t.minHeight||1,a=[];for(let o=0;o<n.count*30&&a.length<n.count;o++){let o=$(e.range(-r,r)),s=$(e.range(-r,r));if(n.clearing&&Math.hypot(o,s)<n.clearing||n.within&&Math.hypot(o,s)>n.within)continue;let c=t.heightAt(o,s),l=(c-t.minHeight)/i;l<n.band[0]||l>n.band[1]||t.slopeAt(o,s)>n.maxSlope||a.push({x:o,z:s,y:c})}return a}var lG=[{canopy:`#2f5d44`,trunk:`#6e4a32`},{canopy:`#356a4c`,trunk:`#71503a`},{canopy:`#2c5740`,trunk:`#5f4530`},{canopy:`#3a6b4a`,trunk:`#6a4c34`}],uG=[{canopy:`#4a7c3f`,trunk:`#7a5a3a`},{canopy:`#56883c`,trunk:`#806044`},{canopy:`#7a9d3e`,trunk:`#9a9488`},{canopy:`#86a346`,trunk:`#a39c8e`},{canopy:`#b8862f`,trunk:`#7e5e38`},{canopy:`#a8702c`,trunk:`#74552f`}],dG={canopy:`#9aa052`,trunk:`#8a6a44`},fG={canopy:`#39513f`,trunk:`#5a5650`};function pG(e,t){return e===`conifer`?t.pick(lG):e===`broadleaf`?t.pick(uG):null}function mG(e,t,n,r,i){let a=i?.height??[4.5,7],o=i?.sink??(i?.count===void 0?.05:.3),s={};i?.tier!==void 0&&(s.tier=i.tier),i?.count!==void 0&&i.area!==void 0&&(s.count=i.count,s.area=[i.area,i.area]);let c=pG(r,n),l=i?.palette??c;return l&&(s.canopyColor=l.canopy,s.trunkColor=l.trunk),{name:e,type:`Tree3D`,props:{type:r,seed:n.int(1,1e9),height:$(n.range(a[0],a[1])),position:[t.x,$(t.y-o),t.z],...s}}}function hG(e,t,n,r,i,a=0,o){return{name:e,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,area:[r,r],density:i,height:o?.height??.3,...o?.colors?{colorA:o.colors[0],colorB:o.colors[1]}:{},seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z],...a>0?{flowers:a}:{}}}}function gG(e,t,n,r,i){return{name:e,type:`Foliage3D`,props:{kind:`reeds`,style:`simple`,area:[r,r],density:i,height:.9,colorA:`#2f4a26`,colorB:`#5a6f33`,seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function _G(e,t,n,r,i){return{name:e,type:`Flowers3D`,props:{density:i,area:[r,r],seed:n.int(1,1e9),position:[t.x,$(t.y+.02),t.z]}}}function vG(e,t,n,r){return e.map((e,i)=>{let a=rW(i+1,e.x,e.z,t,n,r?.(t)),o=a.props?.position;return o[1]=$(o[1]+e.y),a})}function yG(e){let t=Math.round(e.range(104,128)),n=Math.round(t-e.range(10,18)),r=Math.round(t-e.range(20,30)),i=e=>e.toString(16).padStart(2,`0`);return`#${i(n)}${i(t)}${i(r)}`}function bG(e){let t=Math.round(e.range(196,224)),n=Math.min(255,t+Math.round(e.range(4,12))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(t)}${r(t)}${r(n)}`}function xG(e){let t=Math.round(e.range(34,56)),n=Math.min(255,t+Math.round(e.range(2,8))),r=e=>e.toString(16).padStart(2,`0`);return`#${r(n)}${r(t)}${r(t)}`}var SG=[`#6f5b41`,`#7a644a`,`#665439`];function CG(e,t,n,r){let i=[];switch(e){case`island`:{let e=cG(t,n,{count:7,band:[.18,.6],maxSlope:.5,margin:26});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`conifer`)));break}case`alpine`:{let e=cG(t,n,{count:10,band:[.2,.5],maxSlope:.55,margin:6});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`conifer`)));let r=cG(t,n,{count:8,band:[.55,1],maxSlope:.9,margin:6});i.push(...vG(r,t,[.6,1.8]));break}case`plains`:{let e=cG(t,n,{count:8,band:[0,1],maxSlope:.4,margin:6});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`broadleaf`)));let r=cG(t,n,{count:6,band:[0,1],maxSlope:.5,margin:6});i.push(...vG(r,t,[.4,1.2]));break}case`desert`:{let e=cG(t,n,{count:6,band:[0,1],maxSlope:.45,margin:6});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`dead`)));let r=cG(t,n,{count:8,band:[0,1],maxSlope:.6,margin:6});i.push(...vG(r,t,[.5,1.6]));break}case`meadow`:{let e=$(r*.09),a=cG(t,n,{count:7,band:[0,1],maxSlope:.05,margin:e/2+8});i.push(...a.map((n,r)=>hG(`Carpet${r+1}`,n,t,e,30)));let o=$(r*.07),s=cG(t,n,{count:3,band:[0,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>_G(`Flowers${n+1}`,e,t,o,`sparse`)));let c=cG(t,n,{count:4,band:[0,1],maxSlope:.1,margin:12});i.push(...c.map((e,n)=>mG(`Grove${n+1}`,e,t,`broadleaf`,{count:3,area:6})));let l=cG(t,n,{count:6,band:[0,1],maxSlope:.2,margin:8});i.push(...vG(l,t,[.3,.9]));break}case`forest`:{let e=$(r*.12),a=r/2-8,o=Do(t.int(1,1e9)),s=(e,t,n)=>{let r=o(e/70,t/70);return r>.12?`conifer`:r<-.12?`broadleaf`:n%2==0?`conifer`:`broadleaf`},c=cG(t,n,{count:40,band:[0,1],maxSlope:.18,margin:8,clearing:e+6}),l=c.map((e,t)=>s(e.x,e.z,t));i.push(...c.map((e,n)=>mG(`Grove${n+1}`,e,t,l[n],{count:12,area:13,height:[5.5,8]}))),c.forEach((e,n)=>{n%3==0&&i.push(mG(`Sapling${n+1}`,e,t,l[n],{count:4,area:19,height:[2.5,3.4],sink:.12}))});let u=cG(t,n,{count:6,band:[0,1],maxSlope:.2,margin:12,clearing:e+4});i.push(...u.map((e,n)=>mG(`Elder${n+1}`,e,t,s(e.x,e.z,n),{tier:`high`,height:[8.4,9.8]})));let d=cG(t,n,{count:3,band:[0,1],maxSlope:.18,margin:10,clearing:e+6});i.push(...d.map((e,n)=>mG(`Accent${n+1}`,e,t,`broadleaf`,{tier:`high`,count:3,area:7,height:[5.6,6.8]})));let f=cG(t,n,{count:10,band:[0,1],maxSlope:.14,margin:9,clearing:e+2});i.push(...f.map((e,n)=>mG(`Bush${n+1}`,e,t,`bush`,{count:4,area:10,height:[2.1,3.1],sink:.12})));let p=0;c.forEach((e,r)=>{if(r%3==2)return;let o=t.range(0,Math.PI*2),s=t.range(2,4.5),c=t.int(1,1e9),l=$(sW(e.x+Math.cos(o)*s,-a,a)),u=$(sW(e.z+Math.sin(o)*s,-a,a));n.slopeAt(l,u)>.09||(p++,i.push({name:`Fern${p}`,type:`Foliage3D`,props:{kind:`grass`,style:`tufts`,tuftStyle:`fern`,area:[8,8],density:9,height:.4,colorA:`#4a6b34`,colorB:`#82a258`,seed:c,position:[l,$(n.heightAt(l,u)+.02),u]}}))});let m=$(r*.08),h=cG(t,n,{count:5,band:[0,1],maxSlope:.06,margin:m/2+8});i.push(...h.map((e,n)=>hG(`Grass${n+1}`,e,t,m,20,0,{height:.24,colors:[`#4f7034`,`#85a154`]})));let g=u.length>0?t.int(3,5):0;for(let e=0;e<g;e++){let r=u[e%u.length],o=t.range(0,Math.PI*2),s=t.range(2.5,4.5),c=$(sW(r.x+Math.cos(o)*s,-a,a)),l=$(sW(r.z+Math.sin(o)*s,-a,a));i.push({name:`Log${e+1}`,type:`Tree3D`,props:{type:`dead`,seed:t.int(1,1e9),height:$(t.range(4.2,5.6)),trunkColor:`#4a4236`,position:[c,$(n.heightAt(c,l)+.12),l],rotation:[0,t.int(0,359),$(t.range(81,97))]}})}cG(t,n,{count:5,band:[0,1],maxSlope:.25,margin:9,clearing:e}).forEach((e,n)=>{let r=$(t.range(.16,.28)),a=$(t.range(.3,.55));i.push({name:`Stump${n+1}`,type:`MeshInstance3D`,props:{mesh:`cylinder`,size:[r,a,r],position:[e.x,$(e.y+a/2-.06),e.z],rotation:[0,t.int(0,359),0],material:{color:t.pick(SG),roughness:1},castShadow:!0}})});let _=cG(t,n,{count:8,band:[0,1],maxSlope:.2,margin:8});i.push(...vG(_,t,[.3,1],yG));let v=$(e*.75),y=cG(t,n,{count:3,band:[0,1],maxSlope:.06,margin:8,within:e-$(v/Math.SQRT2)});i.push(...y.map((e,n)=>hG(`Clearing${n+1}`,e,t,v,30,0,{colors:[`#5d8438`,`#a8bc60`]})));let b=$(e*.45),x=cG(t,n,{count:2,band:[0,1],maxSlope:.06,margin:8,within:e-$(b/Math.SQRT2)});i.push(...x.map((e,n)=>_G(`Flowers${n+1}`,e,t,b,`sparse`)));break}case`savanna`:{let e=cG(t,n,{count:7,band:[0,.85],maxSlope:.35,margin:8});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`broadleaf`,{height:[3.5,5],palette:dG})));let a=$(r*.09),o=cG(t,n,{count:6,band:[0,1],maxSlope:.05,margin:a/2+8});i.push(...o.map((e,n)=>hG(`Carpet${n+1}`,e,t,a,26,0,{height:.34,colors:[`#9a8f43`,`#c9bd6a`]})));let s=cG(t,n,{count:7,band:[0,1],maxSlope:.5,margin:8});i.push(...vG(s,t,[.4,1.4]));let c=cG(t,n,{count:4,band:[0,1],maxSlope:.2,margin:9});i.push(...c.map((e,n)=>mG(`Scrub${n+1}`,e,t,`bush`,{count:3,area:8,height:[1.4,2.2]})));break}case`snow`:{let e=cG(t,n,{count:8,band:[0,.9],maxSlope:.4,margin:8});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`conifer`,{height:[4,6.5],palette:fG})));let r=cG(t,n,{count:10,band:[0,1],maxSlope:.7,margin:8});i.push(...vG(r,t,[.5,1.8],bG));break}case`wetland`:{let e=$(r*.08),a=cG(t,n,{count:6,band:[0,.5],maxSlope:.06,margin:e/2+8});i.push(...a.map((n,r)=>gG(`Reeds${r+1}`,n,t,e,4)));let o=$(r*.08),s=cG(t,n,{count:4,band:[.2,1],maxSlope:.05,margin:o/2+8});i.push(...s.map((e,n)=>hG(`Moss${n+1}`,e,t,o,22,0,{height:.22,colors:[`#3a5a2c`,`#6f8a48`]})));let c=cG(t,n,{count:6,band:[.25,1],maxSlope:.35,margin:9});i.push(...c.map((e,n)=>mG(`Snag${n+1}`,e,t,`dead`,{height:[4,6]})));let l=cG(t,n,{count:6,band:[.2,1],maxSlope:.2,margin:9});i.push(...l.map((e,n)=>mG(`Bush${n+1}`,e,t,`bush`,{count:3,area:7,height:[1.6,2.6]})));let u=cG(t,n,{count:5,band:[.2,1],maxSlope:.3,margin:8});i.push(...vG(u,t,[.3,1],yG));break}case`volcanic`:{let e=cG(t,n,{count:7,band:[0,1],maxSlope:.45,margin:8});i.push(...e.map((e,n)=>mG(`Tree${n+1}`,e,t,`dead`,{height:[4,6.5]})));let r=cG(t,n,{count:12,band:[0,1],maxSlope:.7,margin:8});i.push(...vG(r,t,[.4,1.8],xG)),cG(t,n,{count:3,band:[0,.6],maxSlope:.18,margin:12}).forEach((e,n)=>{t.int(1,1e9),i.push({name:`Smoke${n+1}`,type:`Particles3D`,props:{preset:`smoke`,position:[e.x,$(e.y+.2),e.z],rate:8,maxParticles:64,colorStart:`#5a5048`,colorEnd:`#2a2422`,sizeStart:18,sizeEnd:44}}),i.push({name:`Embers${n+1}`,type:`Particles3D`,props:{position:[e.x,$(e.y+.1),e.z],rate:10,maxParticles:48,lifetime:[.8,1.8],speed:[12,34],directionDeg:-90,spreadDeg:40,gravity:[0,-18],sizeStart:4,sizeEnd:1,colorStart:`#ffce6a`,colorEnd:`#d83a14`,blend:`add`}})});break}}return i}function wG(e,t,n){return{...e,props:{...e.props,color:t,...n===void 0?{}:{intensity:n}}}}var TG={arena:{description:`FPS stage: floor, 4 perimeter walls, obstacles, lights — themes: boxes (crates), ruins (broken stone rows), garden (hedges, grass, pool)`,dimension:`3d`,params:{theme:{type:`string`,default:`boxes`,options:[...cW]},width:{type:`number`,default:30,min:4},depth:{type:`number`,default:30,min:4},wallHeight:{type:`number`,default:3,min:.5},obstacles:{type:`number`,default:8,min:0}}},terrain:{description:`Heightfield world: StaticBody3D{heightfield} + Terrain3D + theme dressing (trees, rocks, grass, sea/clouds on island, broad swamp water on wetland, smoke/ember emitters on volcanic; maxHeight 0 = theme default; water adds a lake to non-island themes)`,dimension:`3d`,params:{theme:{type:`string`,default:`island`,options:[...$W]},size:{type:`number`,default:200,min:40,max:400},maxHeight:{type:`number`,default:0,min:0},water:{type:`boolean`,default:!1}}},maze:{description:`Recursive-backtracker 3D maze, west→east — themes: stone, hedge (green + grass), canyon (sandstone + rim rocks)`,dimension:`3d`,params:{theme:{type:`string`,default:`stone`,options:[...EW]},width:{type:`number`,default:8,min:2,max:40},depth:{type:`number`,default:8,min:2,max:40},cellSize:{type:`number`,default:2,min:.5},wallHeight:{type:`number`,default:2.5,min:.5}}},maze2d:{description:`The same maze algorithm as 2D ColorRect2D + StaticBody2D tiles`,dimension:`2d`,params:{cols:{type:`number`,default:10,min:2,max:40},rows:{type:`number`,default:8,min:2,max:40},cellPx:{type:`number`,default:64,min:8}}},dungeon2d:{description:`Roguelike rooms + L-corridors: floor rects, wall bodies (32px tiles)`,dimension:`2d`,params:{rooms:{type:`number`,default:5,min:1,max:20},size:{type:`number`,default:960,min:256}}},platforms2d:{description:`Left-to-right 2D platform course (tune ranges via the library)`,dimension:`2d`,params:{count:{type:`number`,default:10,min:1}}}},EG={arena:pW,terrain:aG,maze:NW,maze2d:WW,dungeon2d:xW,platforms2d:qW};function DG(e,t){let n=EG[e];if(!n){let t=Object.keys(EG);throw new L(`BAD_FORMAT`,`Unknown generator '${e}'. Valid: [${t.join(`, `)}] — the old meadow/forest/island/rocks/clouds generators became themes (e.g. terrain theme: 'meadow', arena theme: 'garden'); scatter is library-only (needs item templates).`,{validOptions:t})}return n(t)}function OG(e){return Object.entries(TG).filter(([,t])=>t.dimension===e).map(([e,t])=>({name:e,meta:t}))}function kG(e,t){if(e.type===`boolean`)return t===!0||t===`true`;if(e.type===`number`){let n=typeof t==`boolean`?NaN:Number(t);return(t===``||!Number.isFinite(n))&&(n=e.default),e.min!==void 0&&(n=Math.max(e.min,n)),e.max!==void 0&&(n=Math.min(e.max,n)),n}let n=String(t);return e.options&&!e.options.includes(n)?e.default:n}function AG(){return Math.floor(Math.random()*1e6)}var jG=[],MG=new Map,NG=null;function PG(e){let t=document.querySelector(`#generate`);t&&(LG(e),t.removeAttribute(`hidden`))}function FG(){document.querySelector(`#generate`)?.setAttribute(`hidden`,``)}function IG(e){let t=document.querySelector(`#generate`);t&&(t.addEventListener(`pointerdown`,e=>{e.target===t&&FG()}),document.querySelector(`#generate-close`)?.addEventListener(`click`,FG),document.querySelector(`#generate-cancel`)?.addEventListener(`click`,FG),document.querySelector(`#generate-insert`)?.addEventListener(`click`,()=>RG(e)))}function LG(e){let t=document.querySelector(`#generate-body`),n=document.querySelector(`#generate-status`);if(!t)return;n&&(n.textContent=``),t.textContent=``;let r=e.working.dimension??`2d`;jG=OG(r);let i=document.createElement(`p`);i.className=`gen-hint`,i.textContent=rU({en:`Deterministic ${r.toUpperCase()} environment generators — the subtree inserts under the selected node (the root when nothing is selected). The same seed always generates the same level.`,ko:`결정적 ${r.toUpperCase()} 환경 생성기 — 생성된 서브트리는 선택한 노드 아래에(선택이 없으면 루트에) 들어갑니다. 같은 시드는 항상 같은 레벨을 만듭니다.`}),t.appendChild(i);let a=zG(rU({en:`generator`,ko:`생성기`})),o=document.createElement(`select`);o.id=`generate-name`;for(let{name:e}of jG){let t=document.createElement(`option`);t.value=e,t.textContent=e,o.appendChild(t)}a.appendChild(o),t.appendChild(a);let s=document.createElement(`p`);s.className=`gen-desc`,t.appendChild(s);let c=document.createElement(`div`);c.id=`generate-params`,t.appendChild(c);let l=zG(`seed`);NG=document.createElement(`input`),NG.type=`number`,NG.step=`1`,NG.value=String(AG());let u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=`↻`,u.title=rU({en:`New random seed`,ko:`새 랜덤 시드`}),u.addEventListener(`click`,()=>{NG&&(NG.value=String(AG()))});let d=document.createElement(`div`);d.className=`gen-seed-row`,d.append(NG,u),l.appendChild(d),t.appendChild(l);let f=()=>{let e=jG.find(e=>e.name===o.value)??jG[0];if(e){s.textContent=e.meta.description,c.textContent=``,MG=new Map;for(let[t,n]of Object.entries(e.meta.params)){let e=zG(t),r;if(n.type===`boolean`)r=document.createElement(`input`),r.type=`checkbox`,r.checked=n.default===!0;else if(n.type===`string`&&n.options){r=document.createElement(`select`);for(let e of n.options){let t=document.createElement(`option`);t.value=e,t.textContent=e,r.appendChild(t)}r.value=String(n.default)}else r=document.createElement(`input`),r.type=n.type===`number`?`number`:`text`,n.type===`number`&&(r.step=`any`,n.min!==void 0&&(r.min=String(n.min)),n.max!==void 0&&(r.max=String(n.max))),r.value=String(n.default),(n.min!==void 0||n.max!==void 0)&&(r.title=`${n.min??``}–${n.max??``}`);MG.set(t,r),e.appendChild(r),c.appendChild(e)}}};o.addEventListener(`change`,f),f()}function RG(e){let t=document.querySelector(`#generate-status`),n=document.querySelector(`#generate-name`),r=jG.find(e=>e.name===n?.value);if(!r||!NG)return;let i={seed:kG({type:`number`,default:AG(),min:0},NG.value)};for(let[e,t]of MG){let n=r.meta.params[e];n&&(i[e]=kG(n,t.type===`checkbox`?t.checked:t.value))}let a;try{a=DG(r.name,i)}catch(e){t&&(t.textContent=e instanceof Error?e.message:String(e));return}let o=e.insertNode(a,e.selection??[]);if(o===null){t&&(t.textContent=rU({en:`Insert failed — see the error banner.`,ko:`삽입 실패 — 에러 배너를 확인하세요.`}));return}e.select(o),NG&&(NG.value=String(AG())),FG()}function zG(e){let t=document.createElement(`label`);t.className=`field`;let n=document.createElement(`span`);return n.textContent=e,t.appendChild(n),t}var BG={connections:{title:{en:`connections — wire a signal to a handler`,ko:`connections — 시그널을 핸들러에 연결`},body:{en:'A connection says "when THIS node emits THIS signal, call THIS method on THAT node" — declaratively, in the scene JSON, with no TypeScript. emits = leaving this node; receives = arriving at it. Paths resolve from the scene ROOT (`Player/Sword`, `.` for the root itself). A red target does not resolve and the game will refuse to load the scene. Handlers on a scripted node are free text: they live in your behavior, which the editor never loads.',ko:'연결은 "이 노드가 이 시그널을 보내면, 저 노드의 이 메서드를 호출한다"를 씬 JSON에 선언합니다 — TypeScript 없이. emits는 이 노드에서 나가는 것, receives는 들어오는 것입니다. 경로는 씬 루트 기준입니다(`Player/Sword`, 루트 자신은 `.`). 빨간 대상은 찾을 수 없다는 뜻이고, 게임은 그 씬을 열지 못합니다. 스크립트가 있는 노드의 핸들러는 자유 입력입니다 — 에디터가 읽지 않는 게임 코드에 있기 때문입니다.'}},groups:{title:{en:`groups — tag nodes for queries`,ko:`groups — 조회용 태그`},body:{en:'A LIST of names. Game code finds nodes with tree-wide queries like getNodesInGroup("coins"), and triggers can filter by group (e.g. only react to "player"). Type a name and press Enter. For key-values a node carries (what KIND of thing it is, what it is worth) use `tags`, below.',ko:`자유 형식 태그입니다. 게임 코드가 getNodesInGroup("coins")처럼 트리 전체에서 노드를 찾고, 트리거는 그룹으로 거릅니다(예: "player"에만 반응). 이름을 입력하고 Enter를 누르세요.`},example:`triggerEnter → if (other.isInGroup("player")) collect()`},tags:{title:{en:`tags — free-form identity JSON`,ko:`tags — 자유 형식 식별 JSON`},body:{en:'Not groups. `groups` is a LIST of names you query the tree by; `tags` is an OBJECT of key-values the node carries for your game logic — what kind of thing it is and what it is worth. Connections filter on them (`filter: {tag: {kind: "ITEM"}}`), and a behavior reads `node.tags`. Anything JSON: numbers, strings, nested objects. A rhythm chart lives here — one note node per beat, `{"beat": 4, "lane": 0}`.',ko:'groups와 다릅니다. `groups`는 트리를 조회하는 이름 목록이고, `tags`는 노드가 지니는 키-값 객체입니다 — 무엇이며 얼마나 값어치가 있는지. 연결이 이것으로 거르고(`filter: {tag: {kind: "ITEM"}}`), 비헤이비어는 `node.tags`로 읽습니다. JSON이면 무엇이든 됩니다 — 숫자, 문자열, 중첩 객체.'},example:`{"kind": "ITEM", "value": 10}`},script:{title:{en:`script — attach YOUR game logic`,ko:`script — 게임 로직 연결`},body:{en:`A Behavior is a TypeScript class living in YOUR game code, linked by name. The editor stores the link; the class itself must be registered in the game before loadScene. Props here are passed to the behavior instance.`,ko:`Behavior는 게임 코드에 있는 TypeScript 클래스이며 이름으로 연결됩니다. 에디터는 연결만 저장하고, 클래스 자체는 loadScene 전에 게임에서 등록되어야 합니다. 여기의 props가 비헤이비어 인스턴스로 전달됩니다.`},example:`registerBehavior('CoinCounter', CoinCounter) // in your main.ts`,copy:{label:`copy behavior boilerplate`,text:`import { Behavior, registerBehavior } from 'incanto';
|
|
8963
8963
|
|
|
8964
8964
|
export class MyBehavior extends Behavior {
|
|
8965
8965
|
static props = { speed: { default: 100 } };
|