gaesup-world 1.0.19 → 1.0.21
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/blueprints-editor.cjs +1 -1
- package/dist/blueprints-editor.js +2 -2
- package/dist/core/interactions/components/Clicker/index.d.ts +4 -1
- package/dist/core/motions/entities/refs/types.d.ts +2 -0
- package/dist/editor.cjs +1 -1
- package/dist/editor.js +3 -3
- package/dist/{index-CauGUCKK.js → index-BUQXtHf3.js} +5 -6
- package/dist/{index-eON1JSxy.js → index-C5agFfBe.js} +47 -45
- package/dist/index-CHoKlv0U.cjs +1 -0
- package/dist/{index-BOdJzeGD.cjs → index-CJj-Z7Jr.cjs} +1 -1
- package/dist/{index-CfiJq_gE.js → index-D0Rz5_-J.js} +5 -6
- package/dist/index-D1hpjfAw.cjs +1 -0
- package/dist/{index-CHw7l-nB.cjs → index-DHZJyO9k.cjs} +1 -1
- package/dist/{index-BxrA12Fe.js → index-DShLht0Q.js} +1 -1
- package/dist/{index-Dw6Hncw5.js → index-Drmv86ws.js} +2 -2
- package/dist/index-HxpKt5rO.js +320 -0
- package/dist/index-co-QAQz9.cjs +1 -0
- package/dist/{index-B0m-VWUU.cjs → index-syAx2qzT.cjs} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +13 -13
- package/dist/network.cjs +1 -1
- package/dist/network.js +3 -3
- package/dist/{plugin-Dntrv2mX.js → plugin-BEJHB06f.js} +35 -36
- package/dist/{plugin-Dnl88bC4.cjs → plugin-CS2nMv9n.cjs} +1 -1
- package/dist/runtime.cjs +1 -1
- package/dist/runtime.js +7 -7
- package/package.json +1 -1
- package/dist/index-B414uKZc.cjs +0 -1
- package/dist/index-BXluyPfP.js +0 -318
- package/dist/index-CeK0uKiq.cjs +0 -1
- package/dist/index-D0d_tDEf.cjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const P=require("react/jsx-runtime"),g=require("react"),he=require("@react-three/drei"),We=require("@react-three/fiber"),Me=require("@react-three/rapier"),an=require("three"),vt=require("three-stdlib"),p=require("./gaesupStore-2zKBYTYo.cjs");require("reflect-metadata");const ln=require("./EventBus-DjA75MWC.cjs"),cn=require("immer"),un=require("zustand"),dn=require("zustand/middleware/immer");function hn(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:()=>t[e]})}}return n.default=t,Object.freeze(n)}const I=hn(an);class fn{engines;snapshots;eventListeners;eventHandlers;middlewares;constructor(){this.engines=new Map,this.snapshots=new Map,this.eventListeners=new Set,this.eventHandlers=new Map,this.middlewares=[]}use(n){this.middlewares.push(n)}emit(n){const e=this.eventHandlers.get(n.type);e&&e.forEach(i=>i(n));let r=0;const o=()=>{if(r<this.middlewares.length){const i=this.middlewares[r++];i?.(n,o)}};o()}on(n,e){return this.eventHandlers.has(n)||this.eventHandlers.set(n,new Set),this.eventHandlers.get(n).add(e),()=>{this.eventHandlers.get(n)?.delete(e)}}register(n,...e){const r=this.buildEngine(n,...e);if(!r)return;const o=this.engines.get(n);o!==r&&(o&&(o.dispose(),this.snapshots.delete(n)),this.engines.set(n,r),this.emit({type:"register",id:n,timestamp:Date.now(),data:{engine:r}}))}unregister(n){const e=this.engines.get(n);e&&(e.dispose(),this.engines.delete(n),this.snapshots.delete(n),this.emit({type:"unregister",id:n,timestamp:Date.now(),data:{engine:e}}))}getEngine(n){return this.engines.get(n)}execute(n,e){const r=this.getEngine(n);r&&(this.emit({type:"execute",id:n,timestamp:Date.now(),data:{command:e}}),this.executeCommand(r,e,n),this.notifyListeners(n))}snapshot(n){const e=this.getEngine(n);if(!e)return null;const r=this.createSnapshot(e,n);return r&&this.emit({type:"snapshot",id:n,timestamp:Date.now(),data:{snapshot:r}}),r}getCachedSnapshot(n){return this.snapshots.get(n)}cacheSnapshot(n,e){this.snapshots.set(n,e)}subscribe(n){return this.eventListeners.add(n),()=>this.eventListeners.delete(n)}notifyListeners(n){if(this.eventListeners.size===0)return;const e=this.snapshot(n);e&&(this.cacheSnapshot(n,e),this.eventListeners.forEach(r=>r(e,n)))}getAllSnapshots(){const n=new Map;return this.engines.forEach((e,r)=>{const o=this.snapshot(r);o&&n.set(r,o)}),n}dispose(){this.engines.forEach(n=>n.dispose()),this.engines.clear(),this.snapshots.clear(),this.eventListeners.clear(),this.eventHandlers.clear(),this.middlewares=[]}}class Le extends fn{constructor(){super(),this.processMetrics(),this.processEventLog()}processMetrics(){const n=Object.getPrototypeOf(this);Reflect.getMetadata("enableMetrics",n)}processEventLog(){const n=Object.getPrototypeOf(this);Reflect.getMetadata("enableEventLog",n)}}function Mt(){return function(...t){if(t.length===1){const r=t[0];Reflect.defineMetadata("enableEventLog",!0,r.prototype);return}const[n,e]=t;Reflect.defineMetadata("enableEventLog",!0,n,e)}}function me(){return function(t,n,e){const r=e.value;return e.value=function(...o){const i=performance.now(),s=r.apply(this,o),a=performance.now();return p.logger.log(`[${this.constructor.name}] ${n} snapshot processed in ${(a-i).toFixed(2)}ms`),s},e}}function Fe(){return function(t,n,e){const r=e.value;return e.value=function(o,i,...s){if(!i||typeof i!="object"){p.logger.warn(`[${this.constructor.name}] Invalid command passed to ${n}`);return}return r.apply(this,[o,i,...s])},e}}function ye(){return function(t,n,e){const r=e.value;return e.value=function(...o){const[i]=o;return i?this.getEngine?((typeof i=="string"||typeof i=="number"||typeof i=="symbol"?this.getEngine(i):null)||p.logger.warn(`[${this.constructor.name}] No engine found for id: ${String(i)} in ${n}`),r.apply(this,o)):r.apply(this,o):(p.logger.warn(`[${this.constructor.name}] No id provided for ${n}`),r.apply(this,o))},e}}function be(t=16){const n=new Map;return function(e,r,o){const i=o.value;return o.value=function(...s){const a=s[0],c=typeof a=="object"&&a!==null&&"id"in a?String(a.id):String(a??"default"),l=`${this.constructor.name}_${r}_${c}`,h=Date.now(),u=n.get(l);if(u&&h-u.timestamp<t)return u.value;const d=i.apply(this,s);return n.set(l,{value:d,timestamp:h}),d},o}}function Ct(){return function(t){Reflect.defineMetadata("enableMetrics",!0,t.prototype)}}function Be(t){return function(n){Reflect.defineMetadata("domain",t,n),p.BridgeRegistry.register(t,n),p.DIContainer.getInstance().registerService(n)}}function gn(t){return function(n,e){const r=Reflect.getMetadata("commands",n)||[];r.push({name:t,method:e}),Reflect.defineMetadata("commands",r,n)}}var pn=Object.getOwnPropertyDescriptor,mn=(t,n,e,r)=>{for(var o=r>1?void 0:r?pn(n,e):n,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(o)||o);return o};let ke=class extends p.AbstractSystem{callbacks;systemType;constructor(t="default"){const n={currentAnimation:"idle",animationMixer:null,actions:new Map,isPlaying:!1,currentWeight:1,blendDuration:.3,lastUpdate:Date.now()},e={activeAnimations:0,totalActions:0,currentWeight:1,mixerTime:0,lastUpdate:0,blendProgress:0,frameTime:0};super(n,e),this.callbacks=new Set,this.systemType=t}getSystemType(){return this.systemType}subscribe(t){return this.callbacks.add(t),()=>this.callbacks.delete(t)}notifyCallbacks(){this.callbacks.forEach(t=>t(this.getMetrics()))}initializeMixer(t){this.state.animationMixer=new I.AnimationMixer(t)}addAnimation(t,n){if(!this.state.animationMixer)return;const e=this.state.animationMixer.clipAction(n);this.state.actions.set(t,e),this.updateMetrics(0),this.notifyCallbacks()}registerAction(t,n){this.state.actions.set(t,n),this.updateMetrics(0),this.notifyCallbacks()}playAnimation(t,n=this.state.blendDuration){const e=this.state.actions.get(t);if(!e)return;const r=this.state.actions.get(this.state.currentAnimation);r&&r!==e&&r.fadeOut(n),e.reset().fadeIn(n).play(),this.state.currentAnimation=t,this.state.isPlaying=!0,this.updateMetrics(0),this.notifyCallbacks()}stopAnimation(){const t=this.state.actions.get(this.state.currentAnimation);t&&t.stop(),this.state.isPlaying=!1,this.state.currentAnimation="idle",this.updateMetrics(0),this.notifyCallbacks()}setWeight(t){const n=this.state.actions.get(this.state.currentAnimation);n&&(n.weight=t,this.state.currentWeight=t,this.updateMetrics(0),this.notifyCallbacks())}setTimeScale(t){const n=this.state.actions.get(this.state.currentAnimation);n&&(n.timeScale=t,this.notifyCallbacks())}performUpdate(t){this.state.animationMixer&&(this.state.animationMixer.update(t.deltaTime/1e3),this.metrics.mixerTime+=t.deltaTime/1e3)}createUpdateArgs(t){return t}updateAnimation(t){const n={deltaTime:t*1e3,totalTime:0,frameCount:0};super.update(n),this.callbacks.size>0&&this.notifyCallbacks()}getCurrentAnimation(){return this.state.currentAnimation}getAnimationList(){return Array.from(this.state.actions.keys())}getMetrics(){return this.metrics}getState(){return this.state}updateMetrics(t){this.metrics.frameTime=t;let n=0;for(const e of this.state.actions.values())e.isRunning()&&n++;this.metrics.activeAnimations=n,this.metrics.totalActions=this.state.actions.size,this.metrics.currentWeight=this.state.currentWeight,this.metrics.lastUpdate=Date.now()}clearActions(){this.state.actions.forEach(t=>{t.isRunning()&&t.stop()}),this.state.actions.clear(),this.state.currentAnimation="idle",this.state.isPlaying=!1,this.updateMetrics(0),this.notifyCallbacks()}onDispose(){this.state.animationMixer&&(this.state.animationMixer.stopAllAction(),this.state.animationMixer=null),this.state.actions.clear(),this.callbacks.clear()}};ke=mn([p.ManageRuntime({autoStart:!1})],ke);var yn=Object.defineProperty,bn=Object.getOwnPropertyDescriptor,Z=(t,n,e,r)=>{for(var o=r>1?void 0:r?bn(n,e):n,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=(r?s(n,e,o):s(o))||o);return r&&o&&yn(n,e,o),o};function lt(t){return t.replace(/[\x00-\x1F\x7F]/g,"").trim()}let K=class extends Le{constructor(){super(),["character","vehicle","airplane"].forEach(n=>{this.register(n)}),this.setupEngineSubscriptions()}setupEngineSubscriptions(){this.engines.forEach((t,n)=>{t.subscribe(()=>{this.notifyListeners(n)})})}buildEngine(t){return new ke(t)}registerAnimationAction(t,n,e){const r=this.getEngine(t);if(r){const o=lt(n),i=o.length>0?o:n;r.registerAction(i,e)}}registerAnimations(t,n){const e=this.getEngine(t);e&&Object.entries(n).forEach(([r,o])=>{if(o){const i=lt(r),s=i.length>0?i:r;e.registerAction(s,o)}})}unregisterAnimations(t){const n=this.getEngine(t);n&&n.clearActions()}executeCommand(t,n){switch(n.type){case"play":n.animation&&t.playAnimation(n.animation,n.duration);break;case"stop":t.stopAnimation();break;case"setWeight":n.weight!==void 0&&t.setWeight(n.weight);break;case"setSpeed":n.speed!==void 0&&t.setTimeScale(n.speed);break}}createSnapshot(t){const n=t.getState(),e=t.getMetrics();return{currentAnimation:n.currentAnimation,isPlaying:n.isPlaying,weight:n.currentWeight,speed:1,availableAnimations:t.getAnimationList(),metrics:{activeAnimations:e.activeAnimations,totalActions:e.totalActions,mixerTime:e.mixerTime,lastUpdate:e.lastUpdate}}}getMetrics(t){const n=this.getEngine(t);return n?n.getMetrics():null}update(t,n){const e=this.getEngine(t);e&&e.updateAnimation(n)}execute(t,n){super.execute(t,n)}snapshot(t){const n=super.snapshot(t);return n||{currentAnimation:"idle",isPlaying:!1,weight:0,speed:1,availableAnimations:[],metrics:{activeAnimations:0,totalActions:0,mixerTime:0,lastUpdate:0}}}};Z([ye()],K.prototype,"registerAnimationAction",1);Z([ye()],K.prototype,"unregisterAnimations",1);Z([gn("play"),Fe()],K.prototype,"executeCommand",1);Z([me(),be(16)],K.prototype,"createSnapshot",1);Z([ye()],K.prototype,"getMetrics",1);Z([ye()],K.prototype,"update",1);Z([me(),be(16)],K.prototype,"snapshot",1);K=Z([Be("animation"),Ct()],K);let ct=null;function Ke(){const t=p.BridgeFactory.getOrCreate("animation");return t||(ct??=new K,ct)}function Tt(){const t=g.useRef(null),n=p.useGaesupStore(h=>h.mode),e=p.useGaesupStore(h=>h.animationState),r=p.useGaesupStore(h=>h.setAnimation),o=Ke();t.current=o,g.useEffect(()=>{t.current=o;const h=o.subscribe((u,d)=>{if(!u)return;const f=d,m=p.useGaesupStore.getState().animationState?.[f]?.current;u.currentAnimation!==m&&r(f,u.currentAnimation)});return()=>{h()}},[r,o]);const i=g.useCallback((h,u)=>{t.current&&t.current.execute(h,u)},[]),s=g.useCallback((h,u)=>{i(h,{type:"play",animation:u})},[i]),a=g.useCallback(h=>{i(h,{type:"stop"})},[i]),c=g.useCallback((h,u)=>{t.current&&t.current.registerAnimations(h,u)},[]),l=n?.type||"character";return{bridge:o,playAnimation:s,stopAnimation:a,executeCommand:i,registerAnimations:c,currentType:l,currentAnimation:e?.[l]?.current||"idle"}}var wn=Object.defineProperty,Sn=Object.getOwnPropertyDescriptor,In=(t,n,e,r)=>{for(var o=Sn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&wn(n,e,o),o};class xt{animationBridge=Ke();lastAnimation="idle";update(n){const{isMoving:e,isRunning:r,isJumping:o,isFalling:i,isRiding:s}=n;let a="idle";s?a="ride":o?a="jump":i?a="fall":r?a="run":e&&(a="walk"),a!==this.lastAnimation&&(this.animationBridge.execute("character",{type:"play",animation:a}),this.lastAnimation=a)}}In([p.HandleError(),p.Profile()],xt.prototype,"update");var vn=Object.defineProperty,Mn=Object.getOwnPropertyDescriptor,we=(t,n,e,r)=>{for(var o=Mn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&vn(n,e,o),o};class se{config;constructor(n){this.config=n}applyGravity(n,e){if(!n.current)return;const{modeType:r}=e;switch(r){case"character":this.applyCharacterGravity(n,e);break;case"airplane":this.applyAirplaneGravity(n);break;case"vehicle":this.applyVehicleGravity(n);break;default:this.applyCharacterGravity(n,e)}}applyCharacterGravity(n,e){const{gameStates:{isJumping:r,isFalling:o}}=e,{jumpGravityScale:i=1.5,normalGravityScale:s=1}=this.config;r||o?n.current.setGravityScale(i,!1):n.current.setGravityScale(s,!1)}applyAirplaneGravity(n){const{gravityScale:e=.3}=this.config;n.current.setGravityScale(e,!1)}applyVehicleGravity(n){const{normalGravityScale:e=1}=this.config;n.current.setGravityScale(e,!1)}}we([p.Profile()],se.prototype,"applyGravity");we([p.Profile()],se.prototype,"applyCharacterGravity");we([p.Profile()],se.prototype,"applyAirplaneGravity");we([p.Profile()],se.prototype,"applyVehicleGravity");var Cn=Object.defineProperty,Tn=Object.getOwnPropertyDescriptor,je=(t,n,e,r)=>{for(var o=Tn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&Cn(n,e,o),o};const xn=100,ze=1e3,Ce=10;function En(){const t=new Map,n=Array.from({length:Ce},()=>new I.Vector3);return{getTempVector:e=>{const r=n[e%Ce];return r?r.set(0,0,0):new I.Vector3},getCached:(e,r)=>{if(!t.has(e)){if(t.size>=xn){const o=t.keys().next().value;o!==void 0&&t.delete(o)}t.set(e,r())}return t.get(e)},clear:()=>t.clear(),getStats:()=>({cacheSize:t.size,tempVectorCount:Ce})}}const U=new Map,ut=t=>{const n=Math.round(t*100)/100;if(!U.has(n)){if(U.size>=ze){const e=U.keys().next().value;e!==void 0&&U.delete(e)}U.set(n,{sin:Math.sin(t),cos:Math.cos(t)})}return U.get(n)},Gn=()=>U.clear(),An=()=>({size:U.size,maxSize:ze,coverage:`${(U.size/ze*100).toFixed(1)}%`}),dt=(t,n,e=.01)=>Math.abs(t-n)>=e,Se=class Et{static instance;vectorCaches=new Map;static getInstance(){return this.instance??=new Et}getVectorCache(n){return this.vectorCaches.get(n)??(this.vectorCaches.set(n,En()),this.vectorCaches.get(n))}clearAll(){this.vectorCaches.forEach(n=>n.clear()),Gn()}getStats(){return{vectorCaches:Array.from(this.vectorCaches.entries()).map(([n,e])=>({id:n,...e.getStats()})),trigCache:An()}}};je([p.Profile()],Se.prototype,"getVectorCache");je([p.HandleError()],Se.prototype,"clearAll");je([p.MonitorMemory(10)],Se.prototype,"getStats");let Rn=Se;const k={requestId:0,waypoints:[],threshold:1,shouldRun:!1,listeners:new Set};function He(){k.listeners.forEach(t=>t())}function ht(){return k.requestId+=1,k.requestId}function kn(t){return k.requestId===t}function Te(t,n,e){k.waypoints=t,k.threshold=n,k.shouldRun=e,He()}function xe(){k.waypoints.length!==0&&(k.waypoints=[],He())}function zn(t){return k.listeners.add(t),()=>k.listeners.delete(t)}function Gt(){return k.waypoints}function _n(){return{threshold:k.threshold,shouldRun:k.shouldRun}}function Pn(t){const n=k.waypoints[0];return n?t.distanceTo(n)>k.threshold?n:(k.waypoints.shift(),He(),k.waypoints[0]??null):null}var Dn=Object.defineProperty,Nn=Object.getOwnPropertyDescriptor,ae=(t,n,e,r)=>{for(var o=Nn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&Dn(n,e,o),o};class ne{memoManager=Rn.getInstance();vectorCache=this.memoManager.getVectorCache("direction");lastEulerY={character:0,vehicle:0,airplane:0};lastDirectionLength=0;lastKeyboardState={forward:!1,backward:!1,leftward:!1,rightward:!1};timers=new Set;inputBackend;config;tempEuler=new I.Euler;tempQuaternion=new I.Quaternion;targetQuaternion=new I.Quaternion;cameraForward=new I.Vector3;cameraRight=new I.Vector3;desiredMovement=new I.Vector3;upAxis=new I.Vector3(0,1,0);constructor(n={},e=p.createInteractionInputAdapter()){this.inputBackend=e,this.config=n}updateDirection(n,e,r,o){const{modeType:i}=n;switch(i){case"character":this.updateCharacterDirection(n,e,r);break;case"vehicle":this.updateVehicleDirection(n,e,r);break;case"airplane":this.updateAirplaneDirection(n,o,e,r);break;default:this.updateCharacterDirection(n,e,r)}}updateCharacterDirection(n,e,r){const{activeState:o}=n,i=this.getKeyboard(r),s=this.getMouse(r),a=this.lastKeyboardState.forward!==i.forward||this.lastKeyboardState.backward!==i.backward||this.lastKeyboardState.leftward!==i.leftward||this.lastKeyboardState.rightward!==i.rightward,c=i.forward||i.backward||i.leftward||i.rightward;s.isActive?this.handleMouseDirection(o,s,this.config,r):c&&this.handleKeyboardDirection(o,i,this.config,e,r),(a||c)&&(this.lastKeyboardState={forward:i.forward,backward:i.backward,leftward:i.leftward,rightward:i.rightward}),this.emitRotationUpdate(o,"character")}updateVehicleDirection(n,e,r){const{activeState:o}=n,i=this.getKeyboard(r),{forward:s,backward:a,leftward:c,rightward:l}=i,h=Number(l)-Number(c),u=Number(s)-Number(a);o.euler.y-=h*(Math.PI/64);const{sin:d,cos:f}=ut(o.euler.y);o.direction.set(d*u,0,f*u),o.dir.copy(o.direction),this.emitRotationUpdate(o,"vehicle")}updateAirplaneDirection(n,e,r,o){const{activeState:i}=n,s=this.getKeyboard(o),{forward:a,backward:c,leftward:l,rightward:h,shift:u,space:d}=s,{angleDelta:f={x:.02,y:.02,z:.02},maxAngle:m={x:Math.PI/6,y:Math.PI,z:Math.PI/6},accelRatio:b=1.5}=this.config||{};if(!e?.current)return;let y=1;u&&(y*=b),d&&(y*=1.5);const M=Number(c)-Number(a),v=Number(l)-Number(h);r==="chase"?i.euler.y+=v*f.y*.5:i.euler.y+=v*f.y,this.applyAirplaneRotation(e.current,M,v,m,i),i.direction.set(Math.sin(i.euler.y)*y,-M*y,Math.cos(i.euler.y)*y),i.dir.copy(i.direction).normalize(),this.emitRotationUpdate(i,"airplane")}getKeyboard(n){return n?.inputRef?.current?.keyboard??this.inputBackend.getKeyboard()}getMouse(n){return n?.inputRef?.current?.mouse??this.inputBackend.getMouse()}applyAirplaneRotation(n,e,r,o,i){const s=o.x*e,a=-o.z*r,c=n.rotation.x,l=n.rotation.z,h=o.x,u=o.z;let d=c+s,f=l+a;d<-h?d=-h:d>h&&(d=h),f<-u?f=-u:f>u&&(f=u),i.euler.x=d,i.euler.z=f,this.tempEuler.set(d,0,f),this.tempQuaternion.setFromEuler(n.rotation),this.targetQuaternion.setFromEuler(this.tempEuler),this.tempQuaternion.slerp(this.targetQuaternion,.2),n.setRotationFromQuaternion(this.tempQuaternion)}handleMouseDirection(n,e,r,o){this.syncClickNavigationTarget(e,o);const{automation:i}=o?.worldContext||{};if(i?.settings.trackProgress&&i.queue.actions&&i.queue.actions.length>0){const s=i.queue.actions.shift();if(s&&s.target){const a=this.vectorCache.getTempVector(2),c=o?.rigidBodyRef?.current;if(c){const u=c.translation();a.set(u.x,u.y,u.z)}else a.set(0,0,0);const l=s.target,h=this.vectorCache.getTempVector(1);h.subVectors(l,a).normalize(),o?.memo&&(o.memo.direction||(o.memo.direction=new I.Vector3),o.memo.directionTarget||(o.memo.directionTarget=new I.Vector3),o.memo.direction.copy(h),o.memo.directionTarget.copy(l)),i.queue.loop&&s&&i.queue.actions&&i.queue.actions.push(s)}}else{if(o?.rigidBodyRef.current){const s=o.rigidBodyRef.current.translation(),a=this.vectorCache.getTempVector(0);if(a.set(s.x,s.y,s.z),p.calcNorm(a,e.target)<1){this.handleClicker(o,s);return}}this.applyMouseRotation(n,e,r)}}syncClickNavigationTarget(n,e){if(Gt().length===0)return;const r=this.vectorCache.getTempVector(3),o=e?.rigidBodyRef?.current;if(o){const c=o.translation();r.set(c.x,c.y,c.z)}else r.copy(e?.inputRef.current.mouse.target??n.target);const i=Pn(r),{shouldRun:s}=_n();if(!i){e?.setMouseInput?.({isActive:!1,shouldRun:!1}),n.isActive=!1,n.shouldRun=!1;return}const a=Math.atan2(i.z-r.z,i.x-r.x);e?.setMouseInput?.({target:i,angle:a,position:new I.Vector2(i.x,i.z),isActive:!0,shouldRun:s}),n.target=i,n.angle=a,n.isActive=!0,n.shouldRun=s}handleClicker(n,e){const{automation:r}=n.worldContext||{};if(r?.settings.trackProgress&&r.queue.actions&&r.queue.actions.length>0){const o=r.queue.actions.shift();if(o&&o.target){const i=Math.atan2(o.target.z-e.z,o.target.x-e.x);n.setMouseInput?.({target:o.target,angle:i,isActive:!0})}else if(o&&o.type==="wait"){const i=o.duration||1e3;if(n.state){n.state.clock.stop();const s=setTimeout(()=>{n.state&&n.state.clock.start(),this.timers.delete(s)},i);this.timers.add(s)}}r.queue.loop&&o&&r.queue.actions&&r.queue.actions.push(o)}else n.setMouseInput?.({isActive:!1,shouldRun:!1})}applyMouseRotation(n,e,r){n.euler.y=Math.PI/2-e.angle;const{sin:o,cos:i}=ut(n.euler.y);n.dir.set(-o,0,-i),n.direction.copy(n.dir)}handleKeyboardDirection(n,e,r,o,i){const s=this.resolveKeyboardMovementDirection(e,i);s&&(n.dir.copy(s).multiplyScalar(-1),n.euler.y=Math.atan2(s.x,s.z),n.direction.copy(n.dir))}resolveKeyboardMovementDirection(n,e){const r=Number(n.forward)-Number(n.backward),o=Number(n.rightward)-Number(n.leftward);if(r===0&&o===0)return null;const i=this.desiredMovement.set(0,0,0),s=e?.state?.camera;return s&&(s.getWorldDirection(this.cameraForward),this.cameraForward.y=0,this.cameraForward.lengthSq()>1e-6&&(this.cameraForward.normalize(),this.cameraRight.crossVectors(this.cameraForward,this.upAxis).normalize(),i.addScaledVector(this.cameraForward,r),i.addScaledVector(this.cameraRight,o))),i.lengthSq()<=1e-6&&i.set(o,0,-r),i.normalize()}emitRotationUpdate(n,e){const r=n.dir.length(),o=dt(n.euler.y,this.lastEulerY[e],.001),i=dt(r,this.lastDirectionLength,.01);(o||i)&&(this.lastDirectionLength=r),this.lastEulerY[e]=n.euler.y}dispose(){this.timers.forEach(n=>clearTimeout(n)),this.timers.clear()}}ae([p.Profile()],ne.prototype,"updateDirection");ae([p.Profile()],ne.prototype,"updateCharacterDirection");ae([p.Profile()],ne.prototype,"updateVehicleDirection");ae([p.Profile()],ne.prototype,"updateAirplaneDirection");ae([p.HandleError()],ne.prototype,"dispose");let le=null;function On(t){return t.endsWith("/")?t:`${t}/`}function Wn(){try{const t=globalThis.__GAESUP_WASM_BASE_URL__;if(t)return new URL("wasm/gaesup_core.wasm",On(t)).toString();if(typeof document<"u"&&typeof document.baseURI=="string"&&document.baseURI.length>0)return new URL("wasm/gaesup_core.wasm",document.baseURI).toString()}catch{}return"/wasm/gaesup_core.wasm"}async function At(){return typeof WebAssembly>"u"?null:le||(le=(async()=>{try{const t=Wn(),n=await fetch(t);if(!n.ok)return null;const e=await n.arrayBuffer(),{instance:r}=await WebAssembly.instantiate(e,{}),o=r.exports;return!o||!(o.memory instanceof WebAssembly.Memory)||typeof o.alloc_f32!="function"||typeof o.dealloc_f32!="function"?null:o}catch{return null}})(),le)}const Ln={cellSize:2,worldMinX:-200,worldMinZ:-200,worldMaxX:200,worldMaxZ:200,maxStepHeight:1.1},Fn=[[1,0,10],[-1,0,10],[0,1,10],[0,-1,10],[1,1,14],[1,-1,14],[-1,1,14],[-1,-1,14]],te=1e-6;function Bn(t){return!!(t&&typeof t.alloc_u8=="function"&&typeof t.dealloc_u8=="function"&&typeof t.alloc_u32=="function"&&typeof t.dealloc_u32=="function"&&typeof t.astar_find_path=="function")}class B{static instance=null;config;gridWidth;gridHeight;grid;costGrid;heightGrid;hasHeightData=!1;hasBlockedData=!1;wasm=null;ready=!1;gridPtr=0;outPathPtr=0;outCapacity=512;constructor(n={}){this.config={...Ln,...n};const{cellSize:e,worldMinX:r,worldMinZ:o,worldMaxX:i,worldMaxZ:s}=this.config;this.gridWidth=Math.ceil((i-r)/e),this.gridHeight=Math.ceil((s-o)/e);const a=this.gridWidth*this.gridHeight;this.grid=new Uint8Array(a).fill(1),this.costGrid=new Uint8Array(a).fill(1),this.heightGrid=new Float32Array(a)}static getInstance(n){return B.instance||(B.instance=new B(n)),B.instance}async init(){if(this.ready)return!0;const n=await At();if(Bn(n)){this.wasm=n;const e=this.gridWidth*this.gridHeight;this.gridPtr=this.wasm.alloc_u8(e),this.outPathPtr=this.wasm.alloc_u32(this.outCapacity*2),this.syncGridToWasm()}else this.wasm=null;return this.ready=!0,!0}syncGridToWasm(){this.syncToWasm(this.grid)}syncToWasm(n){this.wasm&&new Uint8Array(this.wasm.memory.buffer,this.gridPtr,this.gridWidth*this.gridHeight).set(n)}cellIndex(n,e){return e*this.gridWidth+n}isGridCell(n,e){return n>=0&&n<this.gridWidth&&e>=0&&e<this.gridHeight}setCell(n,e,r){if(!this.isGridCell(n,e))return;const o=this.cellIndex(n,e);this.grid[o]=r,this.costGrid[o]=r,r===0&&(this.hasBlockedData=!0)}worldToGrid(n,e){const{cellSize:r,worldMinX:o,worldMinZ:i}=this.config,s=Math.floor((n-o)/r),a=Math.floor((e-i)/r);return[Math.max(0,Math.min(s,this.gridWidth-1)),Math.max(0,Math.min(a,this.gridHeight-1))]}gridToWorld(n,e,r){const{cellSize:o,worldMinX:i,worldMinZ:s}=this.config;return[i+(n+.5)*o,r??this.heightGrid[this.cellIndex(n,e)]??0,s+(e+.5)*o]}resolveAgentFootprint(n={}){const e=Math.max(0,n.clearance??0),r=Math.max(0,n.agentRadius??0)+e,o=Math.max(r,Math.max(0,n.agentWidth??0)*.5+e),i=Math.max(r,Math.max(0,n.agentDepth??0)*.5+e);return{halfWidth:o,halfDepth:i,hasClearance:o>te||i>te}}getCellBounds(n,e){const{cellSize:r,worldMinX:o,worldMinZ:i}=this.config,s=o+n*r,a=i+e*r;return{minX:s,maxX:s+r,minZ:a,maxZ:a+r}}footprintOverlapsBlockedCell(n,e,r){const[o,,i]=this.gridToWorld(n,e,0),s=o-r.halfWidth,a=o+r.halfWidth,c=i-r.halfDepth,l=i+r.halfDepth,h=Math.ceil(r.halfWidth/this.config.cellSize),u=Math.ceil(r.halfDepth/this.config.cellSize);for(let d=e-u;d<=e+u;d+=1)for(let f=n-h;f<=n+h;f+=1){if(!this.isGridCell(f,d))continue;const m=this.cellIndex(f,d);if(this.grid[m]!==0)continue;const b=this.getCellBounds(f,d),y=a>b.minX+te&&s<b.maxX-te,M=l>b.minZ+te&&c<b.maxZ-te;if(y&&M)return!0}return!1}canOccupyCell(n,e,r){if(!this.isGridCell(n,e))return!1;const o=this.cellIndex(n,e);return this.grid[o]===0?!1:r.hasClearance?!this.footprintOverlapsBlockedCell(n,e,r):!0}createTraversalGrid(n){if(!n.hasClearance)return this.grid;const e=new Uint8Array(this.grid.length);for(let r=0;r<this.gridHeight;r+=1)for(let o=0;o<this.gridWidth;o+=1){const i=this.cellIndex(o,r);e[i]=this.canOccupyCell(o,r,n)?1:0}return e}createTraversalCostGrid(n){if(n===this.grid)return this.costGrid;const e=new Uint8Array(this.costGrid.length);for(let r=0;r<e.length;r+=1)e[r]=n[r]===0?0:this.costGrid[r]??1;return e}setBlocked(n,e,r,o){this.setRegion(n,e,r,o,0)}setWalkable(n,e,r,o){this.setRegion(n,e,r,o,1)}reset(n=1){const e=Math.max(0,Math.min(255,Math.round(n)));this.grid.fill(e===0?0:1),this.costGrid.fill(e),this.heightGrid.fill(0),this.hasHeightData=!1,this.hasBlockedData=e===0}setRegion(n,e,r,o,i){const{cellSize:s,worldMinX:a,worldMinZ:c}=this.config,l=r/2,h=o/2,u=Math.floor((n-l-a)/s),d=Math.floor((e-h-c)/s),f=Math.ceil((n+l-a)/s),m=Math.ceil((e+h-c)/s);for(let b=d;b<m;b++)for(let y=u;y<f;y++)this.setCell(y,b,i)}setCost(n,e,r){const[o,i]=this.worldToGrid(n,e),s=this.cellIndex(o,i),a=Math.max(0,Math.min(255,Math.round(r)));this.costGrid[s]=a,a===0&&(this.grid[s]=0,this.hasBlockedData=!0)}setHeight(n,e,r){const[o,i]=this.worldToGrid(n,e);this.heightGrid[this.cellIndex(o,i)]=r,r!==0&&(this.hasHeightData=!0)}setHeightRegion(n,e,r,o,i){this.setHeightSampler(n,e,r,o,()=>i)}setHeightSampler(n,e,r,o,i){const{cellSize:s,worldMinX:a,worldMinZ:c}=this.config,l=r/2,h=o/2,u=Math.floor((n-l-a)/s),d=Math.floor((e-h-c)/s),f=Math.ceil((n+l-a)/s),m=Math.ceil((e+h-c)/s);for(let b=d;b<m;b++)for(let y=u;y<f;y++){if(!this.isGridCell(y,b))continue;const[M,,v]=this.gridToWorld(y,b,0),R=i(M,v);this.heightGrid[this.cellIndex(y,b)]=R,R!==0&&(this.hasHeightData=!0)}}sampleHeight(n,e){const[r,o]=this.worldToGrid(n,e);return this.heightGrid[this.cellIndex(r,o)]??0}hasNavigationConstraints(){return this.hasBlockedData||this.hasHeightData}setBlockedFromBox(n){const e=new I.Vector3,r=new I.Vector3;n.getCenter(e),n.getSize(r),this.setBlocked(e.x,e.z,r.x,r.z)}findPath(n,e,r,o,i,s=!1){if(!this.ready)return[];const a=typeof i=="object"&&i!==null?i:{...i!==void 0?{y:i}:{},weighted:s},c=this.resolveAgentFootprint(a),l=a.y,h=a.weighted??s,[u,d]=this.worldToGrid(n,e),[f,m]=this.worldToGrid(r,o),b=this.createTraversalGrid(c),y=h?this.createTraversalCostGrid(b):this.costGrid;return this.wasm&&!this.hasHeightData?this.findPathWasm(u,d,f,m,l,h,b,y):this.findPathJS(u,d,f,m,l,h,b,y)}findPathWasm(n,e,r,o,i,s,a,c){const l=this.wasm;if(s&&typeof l.astar_find_path_weighted!="function")return this.findPathJS(n,e,r,o,i,!0,a,c);s?this.syncToWasm(c):this.syncToWasm(a);const u=(s?l.astar_find_path_weighted:l.astar_find_path)(this.gridPtr,this.gridWidth,this.gridHeight,n,e,r,o,this.outPathPtr,this.outCapacity);if(u===0)return[];const d=new Uint32Array(l.memory.buffer,this.outPathPtr,u*2),f=[];for(let m=0;m<u;m++){const b=d[m*2],y=d[m*2+1];b===void 0||y===void 0||f.push(this.gridToWorld(b,y,i))}return f}findPathJS(n,e,r,o,i,s,a=this.grid,c=this.costGrid){const l=this.gridWidth,h=this.gridHeight,u=a,d=l*h,f=this.cellIndex(n,e),m=this.cellIndex(r,o);if(u[f]===0||u[m]===0)return[];if(f===m)return[this.gridToWorld(r,o,i)];const b=new Uint32Array(d).fill(4294967295),y=new Uint32Array(d).fill(4294967295),M=new Uint8Array(d);b[f]=0;const v=[{f:this.octileH(n,e,r,o),idx:f}];for(;v.length>0;){let G=0;for(let C=1;C<v.length;C++){const $=v[C],N=v[G];$&&N&&$.f<N.f&&(G=C)}const W=v[G],S=v[v.length-1];if(!W||!S)break;v[G]=S,v.pop();const w=W.idx;if(w===m)break;if(M[w])continue;M[w]=1;const T=w%l,A=w/l|0,x=b[w];if(x!==void 0)for(const[C,$,N]of Fn){const j=T+C,H=A+$;if(j<0||H<0||j>=l||H>=h)continue;const O=this.cellIndex(j,H);if(M[O]||u[O]===0||!this.canStepBetween(w,O)||C!==0&&$!==0&&(u[A*l+j]===0||u[H*l+T]===0||!this.canStepBetween(w,this.cellIndex(j,A))||!this.canStepBetween(w,this.cellIndex(T,H))))continue;const sn=s?Math.max(1,c[O]??1):1,ve=x+N*sn,at=b[O];at!==void 0&&ve<at&&(b[O]=ve,y[O]=w,v.push({f:ve+this.octileH(j,H,r,o),idx:O}))}}if(b[m]===4294967295)return[];const R=[];let _=m;for(;_!==f;){R.push(this.gridToWorld(_%l,_/l|0,i));const G=y[_];if(G===void 0)return[];if(_=G,_===4294967295)return[]}return R.push(this.gridToWorld(n,e,i)),R.reverse(),R}octileH(n,e,r,o){const i=Math.abs(n-r),s=Math.abs(e-o);return Math.max(i,s)*10+Math.min(i,s)*4}canStepBetween(n,e){return this.hasHeightData?Math.abs((this.heightGrid[e]??0)-(this.heightGrid[n]??0))<=this.config.maxStepHeight:!0}hasLineOfSight(n,e,r,o,i={}){return this.canTraverseSegment(n,e,r,o,i)}canTraverseSegment(n,e,r,o,i={}){const s=r-n,a=o-e,c=Math.sqrt(s*s+a*a),l=Math.max(1,Math.ceil(c/(this.config.cellSize*.5))),h=this.resolveAgentFootprint(i);let u=-1,d=-1;for(let f=0;f<=l;f++){const m=f/l,[b,y]=this.worldToGrid(n+s*m,e+a*m);if(b===u&&y===d)continue;const M=this.cellIndex(b,y);if(!(i.ignoreStart&&f===0)&&!this.canOccupyCell(b,y,h)||u!==-1&&d!==-1&&!this.canStepBetween(this.cellIndex(u,d),M))return!1;u=b,d=y}return!0}smoothPath(n,e,r,o={}){if(n.length===0)return[];const i=e??n[0],s=r??n[n.length-1];if(!i||!s)return[];const a=[i],c=e?1:0,l=r?n.length-1:n.length;for(let d=c;d<l;d++){const f=n[d];f&&a.push(f)}a.push(s);const h=[];let u=0;for(h.push(a[u]);u<a.length-1;){let d=a.length-1;const f=a[u];for(;d>u+1&&!this.hasLineOfSight(f[0],f[2],a[d][0],a[d][2],o);)d-=1;h.push(a[d]),u=d}return h}simplifyPath(n){if(n.length<=2)return n;const e=n[0];if(!e)return[];const r=[e];for(let i=1;i<n.length-1;i++){const s=r[r.length-1],a=n[i],c=n[i+1];if(!s||!a||!c)continue;const l=a[0]-s[0],h=a[2]-s[2],u=c[0]-a[0],d=c[2]-a[2];Math.abs(l*d-h*u)>.01&&r.push(a)}const o=n[n.length-1];return o&&r.push(o),r}isWalkable(n,e,r={}){const[o,i]=this.worldToGrid(n,e);return this.canOccupyCell(o,i,this.resolveAgentFootprint(r))}getGridDimensions(){return{width:this.gridWidth,height:this.gridHeight,cellSize:this.config.cellSize}}dispose(){this.wasm&&(this.gridPtr&&this.wasm.dealloc_u8(this.gridPtr,this.gridWidth*this.gridHeight),this.outPathPtr&&this.wasm.dealloc_u32(this.outPathPtr,this.outCapacity*2)),B.instance=null,this.ready=!1}}var Kn=Object.defineProperty,jn=Object.getOwnPropertyDescriptor,re=(t,n,e,r)=>{for(var o=jn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&Kn(n,e,o),o};class J{refs;constructor(){this.refs={activeState:{position:new I.Vector3,quaternion:new I.Quaternion,euler:new I.Euler,velocity:new I.Vector3,direction:new I.Vector3,dir:new I.Vector3,angular:new I.Vector3,isGround:!1},gameStates:{canRide:!1,isRiding:!1,isJumping:!1,isFalling:!1,isMoving:!1,isRunning:!1,isNotMoving:!0,isNotRunning:!0,isOnTheGround:!0,nearbyRideable:void 0,currentRideable:void 0,rideableDistance:void 0}}}getActiveState(){return this.refs.activeState}getGameStates(){return this.refs.gameStates}getState(){return this.refs}updateActiveState(n){Object.assign(this.refs.activeState,n)}updateGameStates(n){Object.assign(this.refs.gameStates,n)}resetActiveState(){this.refs.activeState.position.set(0,0,0),this.refs.activeState.quaternion.identity(),this.refs.activeState.euler.set(0,0,0),this.refs.activeState.velocity.set(0,0,0),this.refs.activeState.direction.set(0,0,0),this.refs.activeState.dir.set(0,0,0),this.refs.activeState.angular.set(0,0,0),this.refs.activeState.isGround=!1}resetGameStates(){this.refs.gameStates.canRide=!1,this.refs.gameStates.isRiding=!1,this.refs.gameStates.isJumping=!1,this.refs.gameStates.isFalling=!1,this.refs.gameStates.isMoving=!1,this.refs.gameStates.isRunning=!1,this.refs.gameStates.isNotMoving=!0,this.refs.gameStates.isNotRunning=!0,this.refs.gameStates.isOnTheGround=!0,this.refs.gameStates.nearbyRideable=void 0,this.refs.gameStates.currentRideable=void 0,this.refs.gameStates.rideableDistance=void 0}reset(){this.resetActiveState(),this.resetGameStates()}dispose(){this.reset()}}re([p.Profile()],J.prototype,"updateActiveState");re([p.Profile()],J.prototype,"updateGameStates");re([p.HandleError()],J.prototype,"resetActiveState");re([p.HandleError()],J.prototype,"resetGameStates");re([p.HandleError()],J.prototype,"reset");re([p.HandleError()],J.prototype,"dispose");var Hn=Object.defineProperty,Un=Object.getOwnPropertyDescriptor,Rt=(t,n,e,r)=>{for(var o=Un(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&Hn(n,e,o),o};class Ue{stateManager;inputBackend;config;scratchImpulse={x:0,y:0,z:0};scratchLinvel={x:0,y:0,z:0};navigation=B.getInstance();constructor(n,e,r=p.createInteractionInputAdapter()){this.stateManager=e??new J,this.inputBackend=r,this.config=n}applyImpulse(n,e,r){if(!n.current)return;const{modeType:o}=e;switch(o){case"character":this.applyCharacterImpulse(n,e,r);break;case"vehicle":this.applyVehicleImpulse(n,e,r);break;case"airplane":this.applyAirplaneImpulse(n,e);break;default:this.applyCharacterImpulse(n,e,r)}}applyCharacterImpulse(n,e,r){const{gameStates:{isMoving:o,isRunning:i,isOnTheGround:s,isJumping:a},activeState:c}=e,{walkSpeed:l=10,runSpeed:h=20,jumpSpeed:u=15}=this.config;if(a&&s){const d=n.current.linvel();this.scratchLinvel.x=d.x,this.scratchLinvel.y=u,this.scratchLinvel.z=d.z,n.current.setLinvel(this.scratchLinvel,!0),this.stateManager.updateGameStates({isOnTheGround:!1})}if(o){const d=i?h:l,f=c.dir,m=c.velocity,b=n.current.mass(),y=-f.x*d,M=-f.z*d;if(!this.canMoveForward(n.current,y,M,r)){this.scratchLinvel.x=0,this.scratchLinvel.y=n.current.linvel().y,this.scratchLinvel.z=0,n.current.setLinvel(this.scratchLinvel,!0);return}const v=y-m.x,R=M-m.z;this.scratchImpulse.x=v*b,this.scratchImpulse.y=0,this.scratchImpulse.z=R*b,n.current.applyImpulse(this.scratchImpulse,!0)}}canMoveForward(n,e,r,o){if(!this.navigation.hasNavigationConstraints())return!0;const i=Math.sqrt(e*e+r*r);if(i<=1e-4||typeof n.translation!="function")return!0;const s=n.translation(),{cellSize:a}=this.navigation.getGridDimensions(),c=Math.max(.45,Math.min(a*.75,i*.08)),l=e/i,h=r/i,u=s.x+l*c,d=s.z+h*c,f=Math.max(0,o?.colliderSize?.radius??this.config.navigationAgentRadius??.35);return this.navigation.canTraverseSegment(s.x,s.z,u,d,{agentRadius:f,ignoreStart:!0})}applyVehicleImpulse(n,e,r){const{activeState:o}=e,i=this.getKeyboard(r),{maxSpeed:s=10,accelRatio:a=2}=this.config,c=i.shift&&!e.mouse.isLookAround,l=n.current.linvel(),h=Math.max(0,s);if(l.x*l.x+l.z*l.z<h*h){const d=n.current.mass(),f=c?a:1;this.scratchImpulse.x=o.dir.x*d*f,this.scratchImpulse.y=0,this.scratchImpulse.z=o.dir.z*d*f,n.current.applyImpulse(this.scratchImpulse,!0)}}applyAirplaneImpulse(n,e){const{activeState:r}=e,{maxSpeed:o=20}=this.config,i=n.current.linvel(),s=Math.max(0,o);if(i.x*i.x+i.y*i.y+i.z*i.z<s*s){const c=n.current.mass();this.scratchImpulse.x=r.direction.x*c,this.scratchImpulse.y=r.direction.y*c,this.scratchImpulse.z=r.direction.z*c,n.current.applyImpulse(this.scratchImpulse,!0)}}getKeyboard(n){return n?.inputRef?.current?.keyboard??this.inputBackend.getKeyboard()}}Rt([p.Profile()],Ue.prototype,"applyImpulse");Rt([p.Profile()],Ue.prototype,"applyCharacterImpulse");var $n=Object.defineProperty,Vn=Object.getOwnPropertyDescriptor,D=(t,n,e,r)=>{for(var o=r>1?void 0:r?Vn(n,e):n,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=(r?s(n,e,o):s(o))||o);return r&&o&&$n(n,e,o),o};const qn={isJumping:!1,isMoving:!1,isRunning:!1,lastUpdate:0},Zn={forcesApplied:0,dampingChanges:0,frameTime:0},ft=.75,gt=.25,Jn=.025,Yn=3,Xn=1.2,Qn=.35,er=-.25;function tr(t){const n=t;return n.calcProp!==void 0&&n.physicsState!==void 0}let z=class extends p.AbstractSystem{directionComponent;impulseComponent;gravityComponent;animationController=new xt;forceComponents=[];keyStateCache=new Map;isCurrentlyJumping=!1;lastJumpPressed=!1;lastMovingState=!1;lastRunningState=!1;lastPositionY=0;groundStableCount=0;lastGroundedY=null;tempQuaternion=new I.Quaternion;tempEuler=new I.Euler;tempVector=new I.Vector3;jumpScratch=new I.Vector3;config;constructor(t,n={},e){super(qn,Zn,n),this.config=t,this.directionComponent=new ne(this.config),this.impulseComponent=new Ue(this.config,e),this.gravityComponent=new se(this.config)}updateConfig(t){this.config={...this.config,...t}}performUpdate(t){this.calculate(t.calcProp,t.physicsState)}createUpdateArgs(t){if(tr(t))return t;throw new Error("PhysicsSystem requires updateWithArgs().")}updateMetrics(t){this.state.isJumping=this.isCurrentlyJumping,this.state.isMoving=this.lastMovingState,this.state.isRunning=this.lastRunningState}updateWithArgs(t){this.performUpdateWithArgs(t)}calculate(t,n){if(!n||!t.rigidBodyRef.current)return;if(t.worldContext?.cameraOption?.focus===!0){this.freezeInput(n),this.checkGround(t,n),this.animationController.update(n.gameStates);return}const r=t.rigidBodyRef.current.linvel();n.activeState.velocity.set(r.x,r.y,r.z),this.checkAllStates(t,n),this.animationController.update(n.gameStates);const{modeType:i="character"}=n;switch(i){case"character":this.calculateCharacter(t,n);break;case"vehicle":this.calculateVehicle(t,n);break;case"airplane":this.calculateAirplane(t,n);break}}checkAllStates(t,n){const e=t.rigidBodyRef.current?.handle??-1;this.checkGround(t,n),this.checkMoving(n),this.checkRiding(e,n)}checkGround(t,n){const{rigidBodyRef:e}=t,r=n.gameStates,o=n.activeState;if(!e.current){r.isOnTheGround=!1,r.isFalling=!0;return}const i=e.current.linvel(),s=e.current.translation(),a=Math.abs(i.y),c=Math.abs(s.y-this.lastPositionY),l=i.y>.02,h=s.y<=ft,u=this.lastGroundedY!==null&&Math.abs(s.y-this.lastGroundedY)<=ft,d=h||u,f=r.isJumping||n.keyboard.space,m=u&&!f&&a<Xn&&c<Qn;!l&&d&&a<gt&&c<Jn?this.groundStableCount=Math.min(this.groundStableCount+1,5):this.groundStableCount=0,this.lastPositionY=s.y;const y=d&&!l&&a<gt||m||this.groundStableCount>=Yn,M=!y&&i.y<er;y&&(this.lastGroundedY=s.y,this.resetJumpState(n)),r.isOnTheGround=y,r.isFalling=M,this.copyVector3(o.position,s),this.copyVector3(o.velocity,i)}checkMoving(t){const n=t.gameStates,e=t.keyboard,r=t.mouse,{shift:o,space:i,forward:s,backward:a,leftward:c,rightward:l}=e,h=s||a||c||l,u=h||r.isActive,d=h&&o&&!r.isLookAround||r.isActive&&r.shouldRun;t.modeType==="character"&&i&&!this.lastJumpPressed&&n.isOnTheGround&&!this.isCurrentlyJumping&&(this.isCurrentlyJumping=!0,n.isJumping=!0),this.lastJumpPressed=i,this.updateStateIfChanged("isMoving",u,()=>{this.lastMovingState=u,n.isMoving=u,n.isNotMoving=!u}),this.updateStateIfChanged("isRunning",d,()=>{this.lastRunningState=d,n.isRunning=d,n.isNotRunning=!d})}checkRiding(t=-1,n){const e=n.keyboard;this.keyStateCache.has(t)||this.keyStateCache.set(t,{lastKeyE:!1,lastKeyR:!1});const r=this.keyStateCache.get(t),o=e.keyE,i=n.gameStates;o&&!r.lastKeyE&&(i.canRide&&!i.isRiding||i.isRiding),r.lastKeyE=o,r.lastKeyR=!1}freezeInput(t){const n=t.gameStates;n.isMoving=!1,n.isNotMoving=!0,n.isRunning=!1,n.isNotRunning=!0,n.isJumping=!1,this.isCurrentlyJumping=!1,this.lastJumpPressed=t.keyboard.space,this.lastMovingState=!1,this.lastRunningState=!1}resetJumpState(t){this.isCurrentlyJumping=!1,t.gameStates.isJumping=!1}calculateCharacter(t,n){const{rigidBodyRef:e,innerGroupRef:r}=t;if(this.directionComponent.updateDirection(n,"normal",t),this.impulseComponent.applyImpulse(e,n,t),this.gravityComponent.applyGravity(e,n),this.updateForces(e,n.delta??0),e?.current){const o=n.gameStates,i=n.activeState,{isJumping:s,isFalling:a,isNotMoving:c}=o,{linearDamping:l=.9,airDamping:h=.2,stopDamping:u=1}=this.config;e.current.setLinearDamping(s||a?h:c?l*u:l),e.current.setEnabledRotations(!1,!1,!1,!1),r?.current&&r.current.quaternion.setFromEuler(i.euler)}}calculateVehicle(t,n){const{rigidBodyRef:e,innerGroupRef:r}=t;if(this.directionComponent.updateDirection(n,"normal",t),this.impulseComponent.applyImpulse(e,n,t),this.applyDamping(e,n),this.updateForces(e,n.delta??0),e?.current){const o=n.activeState;e.current.setEnabledRotations(!1,!0,!1,!1),this.tempEuler.set(0,o.euler.y,0),this.tempQuaternion.setFromEuler(this.tempEuler),e.current.setRotation(this.tempQuaternion,!0),r?.current&&(r.current.rotation.y=0)}}calculateAirplane(t,n){const{rigidBodyRef:e,innerGroupRef:r}=t;if(this.directionComponent.updateDirection(n,"normal",t,r),this.impulseComponent.applyImpulse(e,n,t),this.gravityComponent.applyGravity(e,n),this.applyDamping(e,n),this.updateForces(e,n.delta??0),e?.current){e.current.setEnabledRotations(!1,!1,!1,!1);const o=n.activeState;this.tempEuler.set(0,o.euler.y,0),this.tempQuaternion.setFromEuler(this.tempEuler),e.current.setRotation(this.tempQuaternion,!0)}}applyDamping(t,n){if(!t?.current||!n)return;const{modeType:e,keyboard:r}=n,{space:o}=r;if(e==="vehicle"){const{linearDamping:i=.9,brakeRatio:s=i}=this.config,a=o?s:i;t.current.setLinearDamping(a)}else if(e==="airplane"){const{linearDamping:i=.2}=this.config;t.current.setLinearDamping(i)}}addForceComponent(t){this.forceComponents.push(t)}applyForce(t,n){if(!n)return;const e=n.linvel();this.tempVector.set(e.x+t.x,e.y+t.y,e.z+t.z),n.setLinvel(this.tempVector,!0)}calculateMovement(t,n,e,r,o){const i=(o??new I.Vector3).set(0,0,0),s=t.shift&&!t.isLookAround,a=s?2:1,c=(n.maxSpeed??10)*a;return t.forward&&(i.z+=1),t.backward&&(i.z-=1),t.leftward&&(i.x+=1),t.rightward&&(i.x-=1),i.length()>0&&(i.normalize().multiplyScalar(c*r),e.isRunning=s,e.isNotRunning=!s),i}calculateJump(t,n,e){return e?(n.isJumping=!0,this.jumpScratch.set(0,t.jumpSpeed??0,0)):this.jumpScratch.set(0,0,0)}updateForces(t,n){if(!t.current||this.forceComponents.length===0)return;const e=t.current;for(let r=0,o=this.forceComponents.length;r<o;r++){const i=this.forceComponents[r];i&&i.update(e,n)}}copyVector3(t,n){t.set(n.x,n.y,n.z)}onDispose(){this.directionComponent.dispose(),this.forceComponents=[],this.keyStateCache.clear(),this.groundStableCount=0,this.lastGroundedY=null,this.lastJumpPressed=!1}updateStateIfChanged(t,n,e){return this.state[t]!==n?(this.state[t]=n,e?.(),!0):!1}};D([p.HandleError()],z.prototype,"updateConfig",1);D([p.Profile()],z.prototype,"performUpdate",1);D([p.Profile()],z.prototype,"updateMetrics",1);D([p.HandleError(),p.Profile()],z.prototype,"calculate",1);D([p.Profile()],z.prototype,"checkAllStates",1);D([p.Profile()],z.prototype,"checkGround",1);D([p.Profile()],z.prototype,"checkMoving",1);D([p.HandleError(),p.Profile()],z.prototype,"calculateCharacter",1);D([p.HandleError(),p.Profile()],z.prototype,"calculateVehicle",1);D([p.HandleError(),p.Profile()],z.prototype,"calculateAirplane",1);D([p.Profile()],z.prototype,"applyDamping",1);D([p.HandleError()],z.prototype,"applyForce",1);D([p.HandleError(),p.Profile()],z.prototype,"calculateMovement",1);D([p.HandleError()],z.prototype,"calculateJump",1);D([p.Profile()],z.prototype,"updateForces",1);z=D([p.ManageRuntime({autoStart:!1})],z);var nr=Object.defineProperty,rr=Object.getOwnPropertyDescriptor,$e=(t,n,e,r)=>{for(var o=r>1?void 0:r?rr(n,e):n,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=(r?s(n,e,o):s(o))||o);return r&&o&&nr(n,e,o),o};let ee=class extends Le{buildEngine(t,n,e){const r=new z(n,{},e);return{system:r,dispose:()=>r.dispose()}}executeCommand(t,n,e){switch(n.type){case"updateConfig":t.system.updateConfig(n.data);break}}createSnapshot(t){return{...t.system.getState(),metrics:{...t.system.getMetrics()}}}updateEntity(t,n){const e=this.getEngine(t);e&&(e.system.updateWithArgs(n),this.notifyListeners(t))}};$e([Fe()],ee.prototype,"executeCommand",1);$e([me(),be(16)],ee.prototype,"createSnapshot",1);ee=$e([Be("physics"),Mt()],ee);const Ve=g.createContext({runtime:null,revision:0});function or({runtime:t=null,revision:n=0,children:e}){return P.jsx(Ve.Provider,{value:{runtime:t,revision:n},children:e})}function qe(){return g.useContext(Ve).runtime}function Ze(){return g.useContext(Ve).revision}let Ee=null;const _e=new Set;function kt(){return Ee||(Ee=new J),Ee}const pt=t=>(_e.add(t),()=>{_e.delete(t)}),ce=()=>{_e.forEach(t=>t())};function Je(){const t=g.useRef(null);t.current||(t.current=kt());const n=g.useSyncExternalStore(pt,()=>t.current.getActiveState(),()=>t.current.getActiveState()),e=g.useSyncExternalStore(pt,()=>t.current.getGameStates(),()=>t.current.getGameStates()),r=g.useCallback(a=>{t.current?.updateActiveState(a),ce()},[]),o=g.useCallback(a=>{t.current?.updateGameStates(a),ce()},[]),i=g.useCallback(()=>{t.current?.resetActiveState(),ce()},[]),s=g.useCallback(()=>{t.current?.resetGameStates(),ce()},[]);return g.useEffect(()=>()=>{t.current=null},[]),{activeState:n,gameStates:e,updateActiveState:r,updateGameStates:o,resetActiveState:i,resetGameStates:s}}const ir=[{type:"none",labelEn:"None",labelKo:"없음"},{type:"snow",labelEn:"Snow",labelKo:"눈"},{type:"rain",labelEn:"Rain",labelKo:"비"},{type:"storm",labelEn:"Storm",labelKo:"폭풍"},{type:"wind",labelEn:"Wind",labelKo:"바람"}],sr=[{type:"solid",labelEn:"Solid",labelKo:"일반벽"},{type:"window",labelEn:"Window",labelKo:"창문벽"},{type:"door",labelEn:"Door",labelKo:"문벽"},{type:"arch",labelEn:"Arch",labelKo:"아치"},{type:"half",labelEn:"Half Wall",labelKo:"반벽"},{type:"railing",labelEn:"Railing",labelKo:"난간"},{type:"glass",labelEn:"Glass Wall",labelKo:"유리벽"}],fe={flag:{label:"Flag",defaultWidth:1.5,defaultHeight:1,windStrength:1,poleType:"side"},banner:{label:"Banner",defaultWidth:1.2,defaultHeight:3,windStrength:.3,poleType:"top"},panel:{label:"Panel",defaultWidth:2,defaultHeight:1.5,windStrength:0,poleType:"frame"},placard:{label:"Placard",defaultWidth:4,defaultHeight:1,windStrength:.5,poleType:"both"}},Pe=[{id:"brick-house",categoryId:"exterior-walls",categoryName:"Exterior Walls",labelEn:"Brick House",labelKo:"벽돌집",exteriorColor:"#8b4a34",interiorColor:"#eadfce",sideColor:"#6f3b2c",defaultKind:"solid",roughness:.82},{id:"plaster-house",categoryId:"interior-walls",categoryName:"Interior Walls",labelEn:"Plaster Room",labelKo:"석고 내벽",exteriorColor:"#d7d0bf",interiorColor:"#f2eadc",sideColor:"#b6ac9a",defaultKind:"solid",roughness:.86},{id:"wood-cabin",categoryId:"exterior-walls",categoryName:"Exterior Walls",labelEn:"Wood Cabin",labelKo:"나무집",exteriorColor:"#8a5a36",interiorColor:"#c8a174",sideColor:"#6f4529",defaultKind:"solid",roughness:.74},{id:"stone-cottage",categoryId:"exterior-walls",categoryName:"Exterior Walls",labelEn:"Stone Cottage",labelKo:"돌집",exteriorColor:"#79766d",interiorColor:"#d5ceb9",sideColor:"#56544e",defaultKind:"solid",roughness:.9},{id:"modern-concrete",categoryId:"exterior-walls",categoryName:"Exterior Walls",labelEn:"Modern Concrete",labelKo:"모던 콘크리트",exteriorColor:"#858a8c",interiorColor:"#e8e8e3",sideColor:"#64686a",defaultKind:"solid",roughness:.8},{id:"shopfront",categoryId:"special-walls",categoryName:"Special Walls",labelEn:"Shopfront",labelKo:"상점 전면",exteriorColor:"#4b5563",interiorColor:"#e5dcc9",sideColor:"#374151",defaultKind:"window",roughness:.48,metalness:.08},{id:"glass-office",categoryId:"special-walls",categoryName:"Special Walls",labelEn:"Glass Office",labelKo:"유리 오피스",exteriorColor:"#8ecae6",interiorColor:"#d8f2ff",sideColor:"#4b6470",defaultKind:"glass",roughness:.16,metalness:.03},{id:"garden-fence",categoryId:"special-walls",categoryName:"Special Walls",labelEn:"Garden Fence",labelKo:"정원 울타리",exteriorColor:"#7a5a3a",interiorColor:"#9b7653",sideColor:"#5d422c",defaultKind:"railing",roughness:.78}],De=[{id:"oak-planks",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Oak Planks",labelKo:"오크 판자",color:"#8b5a2b",roughness:.58},{id:"pine-planks",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Pine Planks",labelKo:"소나무 판자",color:"#b88952",roughness:.62},{id:"walnut-planks",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Walnut Planks",labelKo:"월넛 판자",color:"#4b2f22",roughness:.64},{id:"bamboo-floor",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Bamboo Floor",labelKo:"대나무 바닥",color:"#c2a15b",roughness:.55},{id:"herringbone-wood",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Herringbone",labelKo:"헤링본 목재",color:"#9a6a3a",roughness:.5},{id:"white-marble",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"White Marble",labelKo:"화이트 대리석",color:"#f0f0ec",roughness:.22,metalness:.05},{id:"black-marble",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Black Marble",labelKo:"블랙 대리석",color:"#25252a",roughness:.2,metalness:.08},{id:"granite",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Granite",labelKo:"화강암",color:"#77746f",roughness:.42,metalness:.03},{id:"slate",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Slate",labelKo:"슬레이트",color:"#3f4a4d",roughness:.62},{id:"basalt",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Basalt",labelKo:"현무암",color:"#2c2f31",roughness:.72},{id:"limestone",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Limestone",labelKo:"석회암",color:"#c8bea8",roughness:.66},{id:"cobblestone",categoryId:"masonry-floors",categoryName:"Masonry Floors",labelEn:"Cobblestone",labelKo:"자갈석",color:"#6f6b60",roughness:.82},{id:"brick-pavers",categoryId:"masonry-floors",categoryName:"Masonry Floors",labelEn:"Brick Pavers",labelKo:"벽돌 포장",color:"#9a4f37",roughness:.78},{id:"terracotta",categoryId:"masonry-floors",categoryName:"Masonry Floors",labelEn:"Terracotta",labelKo:"테라코타",color:"#b85f3c",roughness:.76},{id:"concrete",categoryId:"urban-floors",categoryName:"Urban Floors",labelEn:"Concrete",labelKo:"콘크리트",color:"#8b8d8c",roughness:.86},{id:"asphalt",categoryId:"urban-floors",categoryName:"Urban Floors",labelEn:"Asphalt",labelKo:"아스팔트",color:"#242629",roughness:.9},{id:"ceramic-white",categoryId:"decor-floors",categoryName:"Decor Floors",labelEn:"White Ceramic",labelKo:"화이트 세라믹",color:"#f7f7f2",roughness:.28},{id:"checker-tile",categoryId:"decor-floors",categoryName:"Decor Floors",labelEn:"Checker Tile",labelKo:"체커 타일",color:"#d9d9d2",roughness:.32},{id:"mosaic-blue",categoryId:"decor-floors",categoryName:"Decor Floors",labelEn:"Blue Mosaic",labelKo:"블루 모자이크",color:"#3b78a0",roughness:.34},{id:"metal-grate",categoryId:"special-floors",categoryName:"Special Floors",labelEn:"Metal Grate",labelKo:"금속 그레이팅",color:"#5c6268",material:"METAL",roughness:.38,metalness:.75},{id:"glass-tile",categoryId:"special-floors",categoryName:"Special Floors",labelEn:"Glass Tile",labelKo:"유리 타일",color:"#9ed8ff",material:"GLASS",roughness:.08,opacity:.42,transparent:!0},{id:"sandstone",categoryId:"natural-floors",categoryName:"Natural Floors",labelEn:"Sandstone",labelKo:"사암",color:"#c9ab75",roughness:.88},{id:"snow-ice",categoryId:"natural-floors",categoryName:"Natural Floors",labelEn:"Snow Ice",labelKo:"눈 얼음",color:"#eef5ff",roughness:.5,metalness:.02},{id:"moss-stone",categoryId:"natural-floors",categoryName:"Natural Floors",labelEn:"Moss Stone",labelKo:"이끼 낀 돌",color:"#60704a",roughness:.84}],ar=[{type:"sakura",labelEn:"Sakura",labelKo:"벚꽃나무"},{type:"oak",labelEn:"Oak",labelKo:"참나무"},{type:"pine",labelEn:"Pine",labelKo:"소나무"},{type:"maple",labelEn:"Maple",labelKo:"단풍나무"},{type:"birch",labelEn:"Birch",labelKo:"자작나무"},{type:"willow",labelEn:"Willow",labelKo:"버드나무"},{type:"cypress",labelEn:"Cypress",labelKo:"사이프러스"},{type:"dead",labelEn:"Dead Tree",labelKo:"고목"}],zt={sakura:{primaryColor:"#f7bfd2",secondaryColor:"#5e3d30"},oak:{primaryColor:"#4f8f3a",secondaryColor:"#6b4a2a"},pine:{primaryColor:"#2f6f45",secondaryColor:"#5b3b24"},maple:{primaryColor:"#d05a2d",secondaryColor:"#654126"},birch:{primaryColor:"#87b95a",secondaryColor:"#e8e1cf"},willow:{primaryColor:"#7fae55",secondaryColor:"#6a5635"},cypress:{primaryColor:"#315f3a",secondaryColor:"#59402d"},dead:{primaryColor:"#8b7a61",secondaryColor:"#4b392c"}},lr=[{type:"none",labelEn:"None",labelKo:"없음"},{type:"water",labelEn:"Water",labelKo:"물"},{type:"grass",labelEn:"Grass",labelKo:"잔디"},{type:"sand",labelEn:"Sand",labelKo:"모래"},{type:"snowfield",labelEn:"Snowfield",labelKo:"눈밭"}],cr=[{type:"box",labelEn:"Box",labelKo:"박스"},{type:"stairs",labelEn:"Stairs",labelKo:"계단"},{type:"round",labelEn:"Round",labelKo:"원형"},{type:"ramp",labelEn:"Ramp",labelKo:"경사"}],_t=[{type:"tree",labelEn:"Tree",labelKo:"나무"},{type:"flag",labelEn:"Flag",labelKo:"깃발"},{type:"fire",labelEn:"Fire",labelKo:"불"},{type:"billboard",labelEn:"Billboard",labelKo:"간판"}],ur=[{type:"none",labelEn:"None",labelKo:"없음"},..._t,{type:"model",labelEn:"Model",labelKo:"기본 기물"}],dr=Object.keys(fe).map(t=>({style:t,meta:fe[t]}));function hr(t,n,e){const r=g.useRef(!1);g.useEffect(()=>{if(!t||!e||r.current)return;const o=Ke();return o.registerAnimations(n,t),r.current=!0,()=>{r.current&&(o.unregisterAnimations(n),r.current=!1)}},[t,n,e])}function fr(t,n,e,r){const o=g.useRef(!1),i=g.useRef(null);return i.current||(i.current=p.BridgeFactory.getOrCreate("motion")),g.useEffect(()=>{if(!(!n.current||o.current||!i.current))return i.current.register(t,e==="vehicle"||e==="airplane"?e:"character",n.current),o.current=!0,()=>{i.current?.unregister(t),o.current=!1}},[n,e,t]),{executeMotionCommand:c=>{o.current&&r&&i.current&&i.current.execute(t,c)},getMotionSnapshot:()=>o.current&&r&&i.current?i.current.snapshot(t):null}}const gr=(t,n)=>{["forward","backward","leftward","rightward","shift","space","keyE","keyR"].forEach(r=>{t.keyboard[r]!==n.keyboard[r]&&(t.keyboard[r]=n.keyboard[r])}),t.mouse.target.equals(n.mouse.target)||t.mouse.target.copy(n.mouse.target),t.mouse.angle!==n.mouse.angle&&(t.mouse.angle=n.mouse.angle),t.mouse.isActive!==n.mouse.isActive&&(t.mouse.isActive=n.mouse.isActive),t.mouse.shouldRun!==n.mouse.shouldRun&&(t.mouse.shouldRun=n.mouse.shouldRun)},pr="gaesup.motions",Ye="physics.bridge",Xe=p.DEFAULT_INTERACTION_INPUT_EXTENSION_ID,Qe="motions.runtime",et="motions:teleport";function Pt(t,n={}){const e=n.physicsExtensionId??Ye,r=n.inputExtensionId??Xe,o=t.systems.require(e),i=t.input.require(r);return{physicsBridge:o.createBridge(),inputAdapter:i.createAdapter(),events:t.events,extensionIds:{physics:e,input:r}}}function mr(t,n){t.events.emit(et,n)}function Dt(t={}){const n=t.id??pr,e=t.physicsExtensionId??Ye,r=t.inputExtensionId??Xe,o=t.runtimeServiceId??Qe,i=t.createPhysicsBridge??(()=>new ee),s=t.createInputAdapter??p.createInteractionInputAdapter;return{id:n,name:"GaeSup Motions",version:"0.1.0",runtime:"client",capabilities:["motions","physics","input"],setup(a){a.systems.register(e,{Bridge:ee,createBridge:i},n),a.input.register(r,{createAdapter:s},n),a.services.register(o,{create:c=>Pt(a,{physicsExtensionId:e,inputExtensionId:r,...c})},n),a.events.emit("motions:ready",{pluginId:n,physicsExtensionId:e,inputExtensionId:r,runtimeServiceId:o})},dispose(a){a.systems.remove(e),a.input.remove(r),a.services.remove(o)}}}const yr=Dt();function br(t,n,e,r,o){const i=t.mode?.type||"character",s=n.getActiveState(),a=n.getGameStates(),c=t.automation;return{activeState:s,gameStates:a,keyboard:{...e.keyboard},mouse:{target:o.copy(e.mouse.target),angle:e.mouse.angle,isActive:e.mouse.isActive,shouldRun:e.mouse.shouldRun,...e.mouse.isLookAround!==void 0?{isLookAround:e.mouse.isLookAround}:{}},automationOption:c,modeType:i,delta:r}}function wr(t){if(!t||typeof t!="object")return!1;const e=t.position;return!!e&&typeof e.x=="number"&&typeof e.y=="number"&&typeof e.z=="number"}function Sr(t){if(!("detail"in t))return null;const n=t.detail;return wr(n)?n:null}function Ir(t){if(typeof window>"u"||typeof document>"u")return()=>{};const n=e=>{const r=Sr(e);r&&t(r)};return window.addEventListener("gaesup:teleport",n),document.addEventListener("teleport-request",n),()=>{window.removeEventListener("gaesup:teleport",n),document.removeEventListener("teleport-request",n)}}let mt=null;function vr(){return{physicsBridge:new ee,inputAdapter:p.createInteractionInputAdapter(),events:new ln.InMemoryEventBus,extensionIds:{physics:"fallback.physics.bridge",input:"fallback.interaction.input"}}}function Mr(){return mt??=vr(),mt}function Cr(t){const{enabled:n=!0,allowLegacyFallback:e=!0}=t,r=qe(),o=Ze(),i=g.useMemo(()=>t.motionsRuntime||!r?null:r.getService(Qe)?.create()??null,[r,o,t.motionsRuntime]),s=g.useMemo(()=>t.motionsRuntime||i||!e?null:Mr(),[e,i,t.motionsRuntime]),a=t.motionsRuntime??i??s,c=g.useRef(null),l=g.useRef(new I.Vector3),h=g.useRef(null),u=g.useRef(null),d=g.useRef(!1),f=p.useGaesupStore(w=>w.physics),m=g.useRef(f),b=g.useRef(null);b.current??=p.createInteractionInputAdapter();const y=a?.inputAdapter??b.current,M=g.useRef(y);M.current=y;const v=n&&!!a,R=g.useRef({keyboard:y.getKeyboard(),mouse:y.getMouse()}),_=g.useRef(null),G=g.useRef(w=>{M.current.updateKeyboard(w)}),W=g.useRef(w=>{M.current.updateMouse(w)});g.useEffect(()=>{d.current||(m.current=f)},[f]),g.useEffect(()=>{if(h.current=kt(),!n){d.current&&(u.current?.unregister("global-physics"),d.current=!1),u.current=null,c.current=null;return}const w=a?.physicsBridge;if(!w){d.current&&(u.current?.unregister("global-physics"),d.current=!1),u.current=null,c.current=null;return}return u.current=w,d.current||(u.current.register("global-physics",m.current,h.current),d.current=!0),()=>{d.current&&u.current&&(u.current.unregister("global-physics"),d.current=!1),c.current=null}},[n,a?.physicsBridge]),g.useEffect(()=>{n&&d.current&&u.current&&u.current.execute("global-physics",{type:"updateConfig",data:f})},[n,f]),g.useEffect(()=>{const w=C=>{t.rigidBodyRef?.current&&C&&(t.rigidBodyRef.current.setTranslation({x:C.x,y:C.y,z:C.z},!0),t.rigidBodyRef.current.setLinvel({x:0,y:0,z:0},!0),t.rigidBodyRef.current.setAngvel({x:0,y:0,z:0},!0))},T=C=>{w(C.position)},A=a?.events.on(et,T),x=a===s?Ir(T):void 0;return()=>{A?.(),x?.()}},[s,a,a?.events,t.rigidBodyRef]);const S=g.useCallback((w,T)=>{if(!n||!u.current||!h.current)return;const A=R.current;A.keyboard=y.getKeyboard(),A.mouse=y.getMouse();let x=c.current;if(x)gr(x,A),x.activeState=h.current.getActiveState(),x.gameStates=h.current.getGameStates(),x.delta=T;else{const $=p.useGaesupStore.getState();if(x=br($,h.current,A,T,l.current),c.current=x,x.activeState){const{activeState:N}=x;t.rigidBodyRef.current.lockRotations(!1,!0),N.euler.set(0,0,0),t.rigidBodyRef.current.setTranslation({x:N.position.x,y:N.position.y+5,z:N.position.z},!0)}}let C=_.current;C?(C.rigidBodyRef=t.rigidBodyRef,C.state=w,C.delta=T,C.worldContext=p.useGaesupStore.getState(),t.colliderSize?C.colliderSize=t.colliderSize:delete C.colliderSize,t.innerGroupRef&&(C.innerGroupRef=t.innerGroupRef)):(C={rigidBodyRef:t.rigidBodyRef,state:w,delta:T,worldContext:p.useGaesupStore.getState(),dispatch:()=>{},inputRef:R,setKeyboardInput:G.current,setMouseInput:W.current,...t.colliderSize?{colliderSize:t.colliderSize}:{},...t.innerGroupRef?{innerGroupRef:t.innerGroupRef}:{}},_.current=C),u.current.updateEntity("global-physics",{deltaTime:T,calcProp:C,physicsState:x})},[n,y,t]);return We.useFrame((w,T)=>{v&&S(w,T)}),{isReady:v,bridge:u.current}}function Nt(t){return t?t.plugins.context.input.get(p.DEFAULT_INTERACTION_INPUT_EXTENSION_ID)?.createAdapter()??null:null}function tt(){const t=qe(),n=Ze(),e=g.useRef(null);return e.current??=p.createInteractionInputAdapter(),g.useMemo(()=>Nt(t)??e.current,[t,n])}function Ot(){const t=tt(),[n,e]=g.useState(()=>({keyboard:t.getKeyboard(),mouse:t.getMouse()}));g.useEffect(()=>(e({keyboard:t.getKeyboard(),mouse:t.getMouse()}),t.subscribe?.(s=>{e({keyboard:s.keyboard,mouse:s.mouse})})),[t]);const r=g.useCallback(s=>{t.updateKeyboard(s),t.subscribe||e({keyboard:t.getKeyboard(),mouse:t.getMouse()})},[t]),o=g.useCallback(s=>{t.updateMouse(s),t.subscribe||e({keyboard:t.getKeyboard(),mouse:t.getMouse()})},[t]),i=g.useCallback(s=>{o(s)},[o]);return{keyboard:n.keyboard,mouse:n.mouse,updateKeyboard:r,updateMouse:o,dispatchInput:i}}function Wt(t){const{playAnimation:n,currentType:e,currentAnimation:r}=Tt(),{keyboard:o,mouse:i}=Ot(),s=p.useGaesupStore(u=>u.automation),{gameStates:a}=Je(),c=g.useMemo(()=>{const u=o?.forward||o?.backward||o?.leftward||o?.rightward,d=i?.isActive||!1;return{isMoving:u||d,isRunning:!!o?.shift&&!i?.isLookAround&&u||i?.shouldRun&&d&&s?.queue.isRunning}},[o.forward,o.backward,o.leftward,o.rightward,o.shift,i.isActive,i.shouldRun,i.isLookAround,s]),l=g.useMemo(()=>a?.isJumping?"jump":a?.isFalling?"fall":a?.isRiding?"ride":c.isRunning?"run":c.isMoving?"walk":"idle",[a.isJumping,a.isFalling,a.isRiding,c.isRunning,c.isMoving]),h=g.useMemo(()=>["idle","walk","run","jump","fall","ride","land"],[]);g.useEffect(()=>{if(!t)return;l!=="idle"?l!==r&&n(e,l):h.includes(r)&&r!=="idle"&&n(e,"idle")},[t,l,r,n,e,h])}function Tr(t){const{onIntersectionEnter:n,onIntersectionExit:e,onCollisionEnter:r,userData:o}=t,i=(l,...h)=>{if(typeof l=="function")try{l(...h)}catch{}},s=g.useCallback(l=>{i(n,l),i(o?.onNear,l,o)},[n,o]),a=g.useCallback(l=>{i(e,l),i(o?.onFar,l,o),i(o?.onLeave,l,o)},[e,o]),c=g.useCallback(l=>{i(r,l),i(o?.onNear,l,o)},[r,o]);return{handleIntersectionEnter:s,handleIntersectionExit:a,handleCollisionEnter:c}}function xr(t){const{onReady:n,onFrame:e,onAnimate:r,onDestroy:o,actions:i}=t;g.useEffect(()=>(n&&n(),o),[o,n]),g.useEffect(()=>{let s;const a=()=>{e&&e(),r&&i&&r(),s=requestAnimationFrame(a)};if(!(!e&&!(r&&i)))return s=requestAnimationFrame(a),()=>{cancelAnimationFrame(s)}},[e,r,i])}function Er(t){const{id:n,rigidBodyRef:e,isActive:r,actions:o,outerGroupRef:i,innerGroupRef:s,colliderRef:a,groundRay:c,colliderSize:l}=t,h=g.useRef(n||`entity-${Date.now()}-${Math.random()}`).current,u=p.useGaesupStore(v=>v.mode),d=u?.type??"character",f=r===!0;hr(o,d,f),Wt(f&&d==="character");const{executeMotionCommand:m,getMotionSnapshot:b}=fr(h,e,d,f),y={rigidBodyRef:e,enabled:f,...i?{outerGroupRef:i}:{},...s?{innerGroupRef:s}:{},...a?{colliderRef:a}:{},...c?{groundRay:c}:{},...l?{colliderSize:l}:{}};Cr(y);const M=Tr(t);return xr(t),{executeMotionCommand:m,getMotionSnapshot:b,mode:u,...M}}function Lt({nodes:t,color:n,skeleton:e,url:r,excludeNodeNames:o}){const{processedNodes:i,ownedMaterials:s}=g.useMemo(()=>{const a=[],c=o&&o.length>0?new Set(o):null,l=d=>{const f=d.clone();return a.push(f),n&&"color"in f&&f.color instanceof I.Color&&f.color.set(n),f},h=d=>n?Array.isArray(d)?d.map(f=>l(f)):l(d):d;return{processedNodes:Object.keys(t).map((d,f)=>{if(c&&c.has(d))return null;const m=t[d];return m instanceof I.SkinnedMesh?{type:"skinnedMesh",material:h(m.material),geometry:m.geometry,skeleton:e||m.skeleton,key:`${r}-${d}-${f}`}:m instanceof I.Mesh?{type:"mesh",material:h(m.material),geometry:m.geometry,key:`${r}-${d}-${f}`}:null}).filter(d=>d!==null),ownedMaterials:a}},[t,n,e,r,o]);return g.useEffect(()=>()=>{for(const a of s)a.dispose()},[s]),P.jsx(P.Fragment,{children:i.map(a=>a?a.type==="skinnedMesh"?P.jsx("skinnedMesh",{castShadow:!0,receiveShadow:!0,material:a.material,geometry:a.geometry,skeleton:a.skeleton,frustumCulled:!1,dispose:null},a.key):P.jsx("mesh",{castShadow:!0,receiveShadow:!0,material:a.material,geometry:a.geometry,dispose:null},a.key):null)})}function Gr({url:t,isActive:n,color:e,skeleton:r}){const{scene:o}=he.useGLTF(t),i=g.useMemo(()=>vt.SkeletonUtils.clone(o),[o]),{nodes:s}=We.useGraph(i);return Wt(n),P.jsx("group",{children:P.jsx(Lt,{nodes:s,url:t,...e?{color:e}:{},...r?{skeleton:r}:{}})})}const Ft=g.forwardRef((t,n)=>{const e=typeof t.modelYawOffset=="number"?t.modelYawOffset:t.componentType==="character"?Math.PI:0,r=t.baseColor??t.parts?.[0]?.color;return P.jsx("group",{receiveShadow:!0,castShadow:!0,ref:n,userData:{intangible:!0},children:P.jsxs("group",{"rotation-y":e,children:[t.children,t.objectNode&&t.animationRef&&P.jsx("primitive",{object:t.objectNode,visible:!1,receiveShadow:!0,castShadow:!0,ref:t.animationRef}),P.jsx(Lt,{nodes:t.nodes,skeleton:t.skeleton,url:t.url||"",...r?{color:r}:{},...t.excludeBaseNodes&&t.excludeBaseNodes.length>0?{excludeNodeNames:t.excludeBaseNodes}:{}})]})})});Ft.displayName="InnerGroupRef";const ge=new Map;function Ar(t){const n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=Math.round((r+1)/t*255);const e=new I.DataTexture(n,t,1,I.RedFormat);return e.minFilter=I.NearestFilter,e.magFilter=I.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e}function nt(t=3){const n=Math.max(2,Math.min(8,Math.floor(t))),e=ge.get(n);if(e)return e;const r=Ar(n);return ge.set(n,r),r}function Rr(t={}){return new I.MeshToonMaterial({color:t.color??"#ffffff",vertexColors:t.vertexColors??!1,transparent:t.transparent??!1,opacity:t.opacity??1,map:t.map??null,alphaMap:t.alphaMap??null,emissive:t.emissive??"#000000",emissiveIntensity:t.emissiveIntensity??0,gradientMap:nt(t.steps??3),side:t.side??I.FrontSide,depthWrite:t.depthWrite??!0})}let Bt=!1;function kr(t){Bt=t}function Kt(){return Bt}function zr(){for(const t of ge.values())t.dispose();ge.clear()}const yt=new WeakSet;function jt(t,n=4){if(!t||yt.has(t))return;yt.add(t);const e=nt(n);t.traverse(r=>{const o=r;if(!o.isMesh)return;const s=(Array.isArray(o.material)?o.material:[o.material]).map(a=>{if(!a||a.isMeshToonMaterial)return a;const l=a;return new I.MeshToonMaterial({color:l.color&&l.color.clone()||new I.Color("#ffffff"),map:l.map??null,normalMap:l.normalMap??null,alphaMap:l.alphaMap??null,transparent:a.transparent,opacity:a.opacity,side:a.side,emissive:l.emissive&&l.emissive.clone()||new I.Color(0),emissiveMap:l.emissiveMap??null,emissiveIntensity:l.emissiveIntensity??1,gradientMap:e})});o.material=Array.isArray(o.material)?s:s[0]})}const pe=new Map,de=new I.Vector3(1,1,1),_r=new I.Box3,Pr=t=>{const n=pe.get(t);n&&--n.refCount<=0&&pe.delete(t)},Dr=t=>{try{return _r.setFromObject(t).getSize(p.getPooledVector())}catch{return de.clone()}},Nr=({url:t})=>{const n=p.useGaesupStore(u=>u.sizes),e=p.useGaesupStore(u=>u.setSizes),r=t??"data:application/json,{}",o=!!t?.trim(),i=he.useGLTF(r),s=g.useRef(!1),a=g.useCallback(()=>o&&i.scene?Dr(i.scene):de.clone(),[i.scene,o]);g.useEffect(()=>{if(!t||!o)return;const u=pe.get(t);return u?u.refCount++:pe.set(t,{gltf:i,refCount:1,size:a()}),i.scene&&Kt()&&jt(i.scene),()=>Pr(t)},[t,o,i,a]),g.useEffect(()=>{if(s.current||!o||!t||!i.scene||n[t])return;s.current=!0;const u=a();e(d=>({...d,[t]:u}))},[t,i.scene,n,e,a,o]);const c=g.useMemo(()=>o&&t?n[t]??de:de,[n,t,o]),l=g.useCallback((u,d)=>{if(!o)return;const f=d??t;f&&Promise.resolve().then(()=>e(m=>({...m,[f]:u})))},[t,e,o]),h=g.useCallback(u=>{if(!o)return null;const d=u??t;return d?n[d]??null:null},[t,n,o]);return{gltf:i,size:c,setSize:l,getSize:h}},Or=()=>{const t=p.useGaesupStore(r=>r.sizes),n=g.useCallback(r=>{if(!r)return{};const o={};return Object.entries(r).forEach(([i,s])=>{typeof s=="string"?o[i]=t[s]??null:o[i]=null}),o},[t]),e=g.useCallback(r=>{},[]);return{getSizesByUrls:n,preloadSizes:e}},Wr="data:application/json,"+encodeURIComponent(JSON.stringify({asset:{version:"2.0"},scenes:[{nodes:[]}],nodes:[]}));function Lr(t,n){if(t[n])return n;const e=Object.keys(t),r=n.toLowerCase();return e.find(o=>o.toLowerCase()===r)??e.find(o=>o.toLowerCase().includes(r))??(e.length===1?e[0]:void 0)}const Ht=g.forwardRef((t,n)=>{const e=g.useRef(null);g.useImperativeHandle(n,()=>e.current);const{size:r}=Nr({url:t.url||""}),o=t.url?.trim()?t.url:Wr,{scene:i,animations:s}=he.useGLTF(o),{actions:a,ref:c}=he.useAnimations(s),l=g.useRef(void 0),{handleIntersectionEnter:h,handleIntersectionExit:u,handleCollisionEnter:d}=Er({rigidBodyRef:e,...t.name?{id:t.name}:{},...t.userData?{userData:t.userData}:{},...t.onIntersectionEnter?{onIntersectionEnter:t.onIntersectionEnter}:{},...t.onIntersectionExit?{onIntersectionExit:t.onIntersectionExit}:{},...t.onCollisionEnter?{onCollisionEnter:t.onCollisionEnter}:{},...t.onReady?{onReady:t.onReady}:{},...t.onFrame?{onFrame:t.onFrame}:{},...t.onAnimate?{onAnimate:t.onAnimate}:{},...t.onDestroy||t.onDestory?{onDestroy:t.onDestroy??t.onDestory}:{},actions:a,isActive:t.isActive,...t.outerGroupRef?{outerGroupRef:t.outerGroupRef}:{},...t.innerGroupRef?{innerGroupRef:t.innerGroupRef}:{},...t.colliderRef?{colliderRef:t.colliderRef}:{},...t.groundRay?{groundRay:t.groundRay}:{},...t.colliderSize?{colliderSize:t.colliderSize}:{}}),f=g.useMemo(()=>vt.SkeletonUtils.clone(i),[i]),m=g.useMemo(()=>{let S=null;return f.traverse(w=>{w instanceof I.SkinnedMesh&&(S=w.skeleton)}),S},[f]),b=g.useMemo(()=>!t.parts||t.parts.length===0?null:t.parts.map(({url:S,color:w},T)=>S?g.createElement(Gr,{url:S,isActive:!0,componentType:t.componentType,...t.currentAnimation?{currentAnimation:t.currentAnimation}:{},...w?{color:w}:{},key:`${t.componentType}-${S}-${w||"default"}-${T}`,...m?{skeleton:m}:{}}):null).filter(Boolean),[t.parts,t.componentType,t.currentAnimation,m]),{nodes:y}=We.useGraph(f),M=Object.values(y).find(S=>S.type==="Object3D"),v=t.rotation instanceof I.Euler?t.rotation.y:0,R=t.outerGroupRef?{ref:t.outerGroupRef}:{},_=t.innerGroupRef?{ref:t.innerGroupRef}:{},G=t.isActive?{canSleep:!1,ccd:!0}:{canSleep:!0,ccd:!1},W=g.useMemo(()=>{if(t.colliderSize){const x=Math.max(.05,t.colliderSize.radius),C=Math.max(.05,t.colliderSize.height*.5-x);return{halfHeight:C,radius:x,y:C+x}}const S=Math.max(r.x,.1),w=Math.max(r.z,.1),T=t.componentType==="character"?Math.max(.18,Math.min(S,w)*.35):Math.max(.2,S*1.2),A=Math.max(.05,r.y*.5-T);return{halfHeight:A,radius:T,y:A+T}},[t.colliderSize,t.componentType,r.x,r.y,r.z]);return g.useEffect(()=>{if(!t.currentAnimation)return;const S=Lr(a,t.currentAnimation);if(!S||l.current===S)return;const w=l.current?a[l.current]:void 0,T=a[S];w?.fadeOut(.2),T?.reset().fadeIn(.2).play(),l.current=S},[a,t.currentAnimation]),P.jsx("group",{...R,userData:{intangible:!0},children:P.jsxs(Me.RigidBody,{...G,colliders:!1,ref:e,...t.name?{name:t.name}:{},position:t.position,rotation:Me.euler().set(0,v,0),userData:t.userData,type:t.rigidbodyType||(t.isActive?"dynamic":"fixed"),...t.sensor!==void 0?{sensor:t.sensor}:{},onIntersectionEnter:h,onIntersectionExit:u,onCollisionEnter:d,...t.rigidBodyProps,children:[!t.isNotColliding&&P.jsx(Me.CapsuleCollider,{ref:t.colliderRef,args:[W.halfHeight,W.radius],position:[0,W.y,0]}),P.jsx("group",{...t.scale!==void 0?{scale:t.scale}:{},children:P.jsxs(Ft,{animationRef:c,nodes:y,..._,isActive:t.isActive,componentType:t.componentType,...M?{objectNode:M}:{},...t.modelYawOffset!==void 0?{modelYawOffset:t.modelYawOffset}:{},...t.isRiderOn!==void 0?{isRiderOn:t.isRiderOn}:{},...t.enableRiding!==void 0?{enableRiding:t.enableRiding}:{},...t.ridingUrl?{ridingUrl:t.ridingUrl}:{},...t.offset?{offset:t.offset}:{},...t.baseColor?{baseColor:t.baseColor}:{},...t.excludeBaseNodes?{excludeBaseNodes:t.excludeBaseNodes}:{},...t.parts?{parts:t.parts}:{},children:[t.children,b]})})]})})});Ht.displayName="PhysicsEntity";const Fr=Object.freeze({cellSize:4,heightStep:1,origin:"center"});class Br{id;spec;constructor(n={}){this.id=n.id??"square",this.spec={...Fr,...n.spec}}toWorld(n){const e=this.spec.origin==="center"?0:this.spec.cellSize/2;return{x:n.x*this.spec.cellSize+e,y:n.level*this.spec.heightStep,z:n.z*this.spec.cellSize+e}}fromWorld(n){const e=this.spec.origin==="center"?0:this.spec.cellSize/2;return{x:Math.round((n.x-e)/this.spec.cellSize),z:Math.round((n.z-e)/this.spec.cellSize),level:Math.round(n.y/this.spec.heightStep)}}getNeighbors(n){return[{x:n.x,z:n.z-1,level:n.level},{x:n.x+1,z:n.z,level:n.level},{x:n.x,z:n.z+1,level:n.level},{x:n.x-1,z:n.z,level:n.level}]}equals(n,e){return n.x===e.x&&n.z===e.z&&n.level===e.level}key(n){return`${n.x}:${n.z}:${n.level}`}edgeToWorld(n){const e=this.toWorld(n),r=this.spec.cellSize/2;switch(n.side){case"north":return{...e,z:e.z-r};case"east":return{...e,x:e.x+r};case"south":return{...e,z:e.z+r};case"west":return{...e,x:e.x-r}}}edgeKey(n){return`${n.x}:${n.z}:${n.level}:${n.side}`}cornerToWorld(n){const e=this.toWorld(n),r=this.spec.cellSize/2;return{x:e.x-r,y:e.y,z:e.z-r}}cornerKey(n){return`${n.x}:${n.z}:${n.level}`}}const Ut=()=>({ok:!0}),Kr=(t,n)=>{const e={ok:!1,reason:t};return e.ruleId=n,e};function jr(){return{id:"no-overlap",test(t){const n=t.request.footprint?.coords??[t.request.coord];for(const e of n)if(t.getOccupants(e).filter(o=>o.id!==t.request.subject.id).length>0)return Kr("Target coordinate is already occupied.","no-overlap");return Ut()}}}class bt extends Error{result;constructor(n){super(n.reason??"Placement request was rejected."),this.name="PlacementRejectedError",this.result=n}}class wt extends Error{constructor(n){super(`Placement entry "${n}" does not exist.`),this.name="MissingPlacementEntryError"}}class Hr{adapter;rules;entries=new Map;occupied=new Map;constructor(n){this.adapter=n.adapter,this.rules=[...n.rules??[]]}use(n){this.rules.push(n)}canPlace(n){const e={request:n,entries:this.entries,adapter:this.adapter,getOccupants:r=>this.getOccupants(r)};for(const r of this.rules){const o=r.test(e);if(!o.ok)return o.ruleId===void 0?{...o,ruleId:r.id}:o}return Ut()}place(n){const e=this.canPlace(n);if(!e.ok)throw new bt(e);const r=this.toEntry(n),o=this.entries.get(r.id);o&&this.unindex(o),this.entries.set(r.id,r),this.index(r);const i={type:"place",after:r};return o&&(i.before=o),i}remove(n){const e=this.entries.get(n);if(!e)throw new wt(n);return this.unindex(e),this.entries.delete(n),{type:"remove",before:e}}move(n,e,r){const o=this.requireEntry(n),i={subject:o.subject,coord:e,footprint:r??this.moveFootprint(o,e)};o.rotation!==void 0&&(i.rotation=o.rotation);const s=this.canPlace(i);if(!s.ok)throw new bt(s);const a=this.toEntry(i);return this.unindex(o),this.entries.set(n,a),this.index(a),{type:"move",before:o,after:a}}rotate(n,e){const r=this.requireEntry(n),o={...r,rotation:e};return this.entries.set(n,o),{type:"rotate",before:r,after:o}}get(n){return this.entries.get(n)}list(){return Array.from(this.entries.values())}getOccupants(n){const e=this.occupied.get(this.adapter.key(n));return e?Array.from(e).map(r=>this.entries.get(r)).filter(r=>r!==void 0):[]}clear(){this.entries.clear(),this.occupied.clear()}toEntry(n){const e={id:n.subject.id,subject:n.subject,coord:n.coord,footprint:n.footprint??{kind:"cell",coords:[n.coord]}};return n.rotation!==void 0&&(e.rotation=n.rotation),e}requireEntry(n){const e=this.entries.get(n);if(!e)throw new wt(n);return e}index(n){for(const e of this.getFootprintCoords(n)){const r=this.adapter.key(e),o=this.occupied.get(r)??new Set;o.add(n.id),this.occupied.set(r,o)}}unindex(n){for(const e of this.getFootprintCoords(n)){const r=this.adapter.key(e),o=this.occupied.get(r);o&&(o.delete(n.id),o.size===0&&this.occupied.delete(r))}}getFootprintCoords(n){return n.footprint.coords??[n.coord]}moveFootprint(n,e){const r=n.footprint.coords;return r!==void 0&&r.length===1&&r[0]!==void 0&&this.adapter.equals(r[0],n.coord)?{...n.footprint,coords:[e]}:n.footprint}}function Ur(t){return new Hr(t)}const E=Object.freeze({GRID_CELL_SIZE:4,SNAP_GRID_SIZE:4,HEIGHT_STEP:1,TILE_MULTIPLIERS:Object.freeze({SMALL:1,MEDIUM:2,LARGE:3,HUGE:4}),WALL_SIZES:Object.freeze({WIDTH:4,HEIGHT:4,THICKNESS:.5,MIN_LENGTH:.5,MAX_LENGTH:10}),GRID_DIVISIONS:25,DEFAULT_GRID_SIZE:100}),L=new Br({id:"building-square",spec:{cellSize:E.GRID_CELL_SIZE,heightStep:E.HEIGHT_STEP,origin:"center"}}),Ne=t=>t>=0?t*2:-t*2-1,rt=(t,n)=>{const e=Ne(t),r=Ne(n),o=e+r;return o*(o+1)/2+r},$t=t=>({...t,x:Math.round(t.x/E.SNAP_GRID_SIZE)*E.SNAP_GRID_SIZE,z:Math.round(t.z/E.SNAP_GRID_SIZE)*E.SNAP_GRID_SIZE}),Vt=t=>L.fromWorld(t),qt=t=>L.toWorld(t),Zt=t=>{const n=Math.PI/2;return(Math.round(t/n)%4+4)%4*n},Jt=t=>{switch(t){case"north":case"south":return Math.PI/2;case"east":case"west":return 0}},$r=t=>{const n=L.edgeToWorld(t),e=Jt(t.side),r=E.WALL_SIZES.WIDTH/2,o={x:Math.sin(e),z:Math.cos(e)};return{position:{x:V(n.x-o.x*r),y:n.y,z:V(n.z-o.z*r)},rotationY:e}},ie=(t,n)=>{const e=Zt(n),r=E.WALL_SIZES.WIDTH/2,o=E.GRID_CELL_SIZE,i={x:t.x+Math.sin(e)*r,y:t.y,z:t.z+Math.cos(e)*r};if(e===0||e===Math.PI){const s=Math.trunc(i.x/o),a=i.x-s*o;return{x:V(s),z:V(Math.round(i.z/o)),level:V(Math.round(i.y/E.HEIGHT_STEP)),side:a>=0?"east":"west"}}return{x:V(Math.round(i.x/o)),z:V(Math.trunc(i.z/o)),level:V(Math.round(i.y/E.HEIGHT_STEP)),side:i.z-Math.trunc(i.z/o)*o>=0?"south":"north"}},Vr=t=>L.edgeKey(t),V=t=>Object.is(t,-0)||Math.abs(t)<1e-10?0:Number(t.toFixed(10)),F=t=>Vt(t),qr=t=>qt(t),X=(t,n=1)=>{const e=Math.max(1,Math.round(n)),r=-Math.floor(e/2),o=[];for(let i=0;i<e;i++)for(let s=0;s<e;s++)o.push({x:t.x+r+i,z:t.z+r+s,level:t.level});return o},Zr=t=>t.map(n=>L.key(n)),Yt=(t,n={})=>{const e=Math.max(1,Math.round(n.x??1)),r=Math.max(1,Math.round(n.y??1)),o=Math.max(1,Math.round(n.z??1)),i=[];for(let s=0;s<e;s++)for(let a=0;a<r;a++)for(let c=0;c<o;c++)i.push({x:t.x+s,z:t.z+c,level:t.level+a});return i},Xt={id:"building-placement",toWorld(t){return t.kind==="cell"?L.toWorld(t.cell):L.edgeToWorld(t.edge)},fromWorld(t){return{kind:"cell",cell:L.fromWorld(t)}},getNeighbors(t){return t.kind==="edge"?[t]:L.getNeighbors(t.cell).map(n=>({kind:"cell",cell:n}))},equals(t,n){return this.key(t)===this.key(n)},key(t){return t.kind==="cell"?`cell:${L.key(t.cell)}`:`edge:${L.edgeKey(t.edge)}`}},ot=t=>{const n=t.cell??F(t.position),e=t.footprint??X(n,t.size||1),r={id:t.id,subject:{id:t.id,type:"tile",tags:["building","tile",`shape:${t.shape??"box"}`,...t.objectType&&t.objectType!=="none"?[`terrain:${t.objectType}`]:[]]},coord:{kind:"cell",cell:n},footprint:{kind:"cell",coords:e.map(o=>({kind:"cell",cell:o}))}};return t.rotation!==void 0&&(r.rotation=t.rotation),r},Qt=t=>{const n=t.edge??ie(t.position,t.rotation.y);return{id:t.id,subject:{id:t.id,type:"wall",tags:["building","wall",`side:${n.side}`]},coord:{kind:"edge",edge:n},footprint:{kind:"edge",coords:[{kind:"edge",edge:n}]},rotation:t.rotation.y}},it=t=>{const n=t.cell??F(t.position),e=Yt(n,t.size);return{id:t.id,subject:{id:t.id,type:"block",tags:["building","block",...t.materialId?[`material:${t.materialId}`]:[],...t.tags??[]]},coord:{kind:"cell",cell:n},footprint:{kind:"volume",coords:e.map(r=>({kind:"cell",cell:r}))}}},en=t=>t.tiles.map(ot),tn=t=>t.walls.map(Qt),nn=(t,n,e=[])=>[...Array.from(t).flatMap(en),...Array.from(n).flatMap(tn),...Array.from(e).map(it)],Oe=(t=[],n=[],e={})=>{const r=[...e.includeNoOverlapRule===!1?[]:[jr()],...e.rules??[]],o=Ur({adapter:Xt,rules:[]});for(const i of nn(t,n,e.blocks??[])){const s={subject:i.subject,coord:i.coord,footprint:i.footprint};o.place(i.rotation===void 0?s:{...s,rotation:i.rotation})}for(const i of r)o.use(i);return o},Y=(t,n,e)=>{const r=n.get(e);if(r){for(const o of r){const i=t.get(o);i&&(i.delete(e),i.size===0&&t.delete(o))}n.delete(e)}},q=(t,n,e,r,o,i,s,a)=>{const c=Math.floor(r/a),l=Math.floor(o/a),h=Math.floor(i/a),u=Math.floor(s/a),d=[];for(let f=c;f<=l;f++)for(let m=h;m<=u;m++){const b=rt(f,m);let y=t.get(b);y||(y=new Set,t.set(b,y)),y.add(e),d.push(b)}n.set(e,d)},Ie=(t,n,e,r,o,i)=>{const s=Math.floor(n/i),a=Math.floor(e/i),c=Math.floor(r/i),l=Math.floor(o/i),h=new Set;for(let u=s;u<=a;u++)for(let d=c;d<=l;d++){const f=t.get(rt(u,d));if(f)for(const m of f)h.add(m)}return h},Q=t=>E.GRID_CELL_SIZE*t/2,st=(t,n)=>Math.abs(t.x-n.x)<t.halfSize+n.halfSize-.1&&Math.abs(t.z-n.z)<t.halfSize+n.halfSize-.1,Jr=(t,n,e,r)=>{const o=E.GRID_CELL_SIZE,i=Q(r),s=E.HEIGHT_STEP*.5,a=Ie(t,e.x-i,e.x+i,e.z-i,e.z+i,o);for(const c of a){const l=n.get(c);if(l&&st({x:e.x,z:e.z,halfSize:i},l)&&Math.abs((l.y??0)-e.y)<s)return!0}return!1},rn=(t,n,e,r)=>{const o=E.GRID_CELL_SIZE,i=Q(r),s=Ie(t,e.x-i,e.x+i,e.z-i,e.z+i,o);let a=0;for(const c of s){const l=n.get(c);if(!l||!st({x:e.x,z:e.z,halfSize:i},l))continue;const h=(l.y??0)+E.HEIGHT_STEP;h>a&&(a=h)}return a},on=(t,n,e,r)=>{const i=Ie(t,e.x-.5,e.x+.5,e.z-.5,e.z+.5,1);for(const s of i){const a=n.get(s);if(a&&Math.abs(a.x-e.x)<.5&&Math.abs(a.z-e.z)<.5&&Math.abs(a.rotY-r)<.1)return!0}return!1};function Yr(t){return{version:1,meshes:Array.from(t.meshes.values(),oe),wallGroups:Array.from(t.wallGroups.values(),oe),tileGroups:Array.from(t.tileGroups.values(),oe),blocks:t.blocks.map(oe),objects:t.objects.map(oe),showSnow:t.showSnow,showFog:t.showFog,fogColor:t.fogColor,weatherEffect:t.weatherEffect}}function oe(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}function Xr(t,n){if(n){t.meshes.clear(),t.wallGroups.clear(),t.tileGroups.clear(),t.tileIndex.clear(),t.tileCells.clear(),t.tileMeta.clear(),t.wallIndex.clear(),t.wallCells.clear(),t.wallMeta.clear();for(const e of n.meshes??[])t.meshes.set(e.id,{...e});Qr(t,n.tileGroups??[]),eo(t,n.wallGroups??[]),t.blocks=(n.blocks??[]).map(e=>({...e,cell:e.cell??F(e.position)})),t.objects=(n.objects??[]).map(e=>({...e})),t.showSnow=n.showSnow??!1,t.showFog=n.showFog??!1,t.fogColor=n.fogColor??"#cfd8e3",t.weatherEffect=n.weatherEffect??(t.showSnow?"snow":"none"),t.initialized=!0}}function Qr(t,n){const e=E.GRID_CELL_SIZE;for(const r of n){const o=r.tiles.map(i=>{const s=i.cell??F(i.position),a={...i,cell:s,footprint:i.footprint??X(s,i.size||1)},c=Q(a.size||1);return t.tileMeta.set(a.id,{x:a.position.x,z:a.position.z,y:a.position.y,halfSize:c}),q(t.tileIndex,t.tileCells,a.id,a.position.x-c,a.position.x+c,a.position.z-c,a.position.z+c,e),a});t.tileGroups.set(r.id,{...r,tiles:o})}}function eo(t,n){for(const e of n){const r=e.walls.map(o=>{const i={...o,edge:o.edge??ie(o.position,o.rotation.y)},s=.5;return t.wallMeta.set(i.id,{x:i.position.x,z:i.position.z,rotY:i.rotation.y}),q(t.wallIndex,t.wallCells,i.id,i.position.x-s,i.position.x+s,i.position.z-s,i.position.z+s,1),i});t.wallGroups.set(e.id,{...e,walls:r})}}cn.enableMapSet();const Ge="custom-tiles";function to(t){return t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Ae(t,n,e,r){t.tileCategories.has(n)||t.tileCategories.set(n,{id:n,name:e,description:r,tileGroupIds:[]})}function Re(t,n,e){const r=t.tileCategories.get(n);!r||r.tileGroupIds.includes(e)||t.tileCategories.set(n,{...r,tileGroupIds:[...r.tileGroupIds,e]})}function St(t,n,e,r){t.wallCategories.has(n)||t.wallCategories.set(n,{id:n,name:e,description:r,wallGroupIds:[]})}function It(t,n,e){const r=t.wallCategories.get(n);!r||r.wallGroupIds.includes(e)||t.wallCategories.set(n,{...r,wallGroupIds:[...r.wallGroupIds,e]})}const no=un.create()(dn.immer((t,n)=>({initialized:!1,tileIndex:new Map,tileCells:new Map,tileMeta:new Map,wallIndex:new Map,wallCells:new Map,wallMeta:new Map,meshes:new Map,wallGroups:new Map,tileGroups:new Map,blocks:[],wallCategories:new Map,tileCategories:new Map,editMode:"none",showGrid:!0,gridSize:100,snapToGrid:!0,hoverPosition:null,currentTileMultiplier:1,currentTileHeight:0,currentTileShape:"box",currentTileRotation:0,currentTileMaterialId:null,currentCustomTileName:"Custom Tile",currentCustomTileColor:"#8f8f8f",currentCustomTileTextureUrl:"",currentWallRotation:0,currentWallMaterialId:null,currentWallKind:"solid",objects:[],selectedTileObjectType:"none",currentTerrainColor:"#5a7a35",currentTerrainAccentColor:"#8fbc5a",selectedPlacedObjectType:"none",selectedModelObjectId:"door-basic",currentModelUrl:"",currentModelScale:1,currentModelColor:"#9b7653",selectedWallId:null,selectedTileId:null,selectedBlockId:null,currentFlagWidth:1.5,currentFlagHeight:1,currentFlagImageUrl:"",currentFlagStyle:"flag",currentFireIntensity:1.5,currentFireWidth:1,currentFireHeight:1.5,currentFireColor:"#ff6622",currentObjectRotation:0,currentObjectPrimaryColor:"#f7bfd2",currentObjectSecondaryColor:"#5e3d30",currentTreeKind:"sakura",currentBillboardText:"HELLO",currentBillboardImageUrl:"",currentBillboardColor:"#00ff88",currentBillboardWidth:0,currentBillboardHeight:1.5,currentBillboardScale:1,currentBillboardOffsetY:0,currentBillboardElevation:1,currentBillboardIntensity:2,showSnow:!1,showFog:!1,fogColor:"#cfd8e3",weatherEffect:"none",initializeDefaults:()=>t(e=>{if(e.initialized)return;e.meshes.set("brick-wall",{id:"brick-wall",color:"#8B4513",material:"STANDARD",roughness:.8}),e.meshes.set("glass-wall",{id:"glass-wall",material:"GLASS",opacity:.3,transparent:!0}),e.meshes.set("concrete-wall",{id:"concrete-wall",color:"#808080",material:"STANDARD",roughness:.9}),e.meshes.set("wood-floor",{id:"wood-floor",color:"#654321",material:"STANDARD",roughness:.6}),e.meshes.set("marble-floor",{id:"marble-floor",color:"#f0f0f0",material:"STANDARD",roughness:.2,metalness:.1}),e.meshes.set("sand-floor",{id:"sand-floor",color:"#c9ab75",material:"STANDARD",roughness:.96,metalness:.02}),e.meshes.set("snow-floor",{id:"snow-floor",color:"#eef5ff",material:"STANDARD",roughness:.9,metalness:0}),e.wallCategories.set("interior-walls",{id:"interior-walls",name:"Interior Walls",description:"Walls for interior spaces",wallGroupIds:["plaster-walls","painted-walls"]}),e.wallCategories.set("exterior-walls",{id:"exterior-walls",name:"Exterior Walls",description:"Walls for building exteriors",wallGroupIds:["brick-walls","concrete-walls"]}),e.wallCategories.set("special-walls",{id:"special-walls",name:"Special Walls",description:"Glass and special material walls",wallGroupIds:["glass-walls"]}),e.tileCategories.set("wood-floors",{id:"wood-floors",name:"Wood Floors",description:"Various wood flooring options",tileGroupIds:["oak-floor","pine-floor"]}),e.tileCategories.set("stone-floors",{id:"stone-floors",name:"Stone Floors",description:"Marble and stone flooring",tileGroupIds:["marble-floor","granite-floor"]}),e.tileCategories.set("natural-floors",{id:"natural-floors",name:"Natural Floors",description:"Sand and snow terrain flooring",tileGroupIds:["sand-floor","snow-floor"]}),e.wallGroups.set("brick-walls",{id:"brick-walls",name:"Brick Walls",frontMeshId:"brick-wall",backMeshId:"brick-wall",sideMeshId:"brick-wall",walls:[]}),e.wallGroups.set("glass-walls",{id:"glass-walls",name:"Glass Walls",frontMeshId:"glass-wall",backMeshId:"glass-wall",sideMeshId:"glass-wall",walls:[]}),e.wallGroups.set("concrete-walls",{id:"concrete-walls",name:"Concrete Walls",frontMeshId:"concrete-wall",backMeshId:"concrete-wall",sideMeshId:"concrete-wall",walls:[]}),e.wallGroups.set("plaster-walls",{id:"plaster-walls",name:"Plaster Walls",frontMeshId:"brick-wall",backMeshId:"brick-wall",sideMeshId:"brick-wall",walls:[]}),e.wallGroups.set("painted-walls",{id:"painted-walls",name:"Painted Walls",frontMeshId:"brick-wall",backMeshId:"brick-wall",sideMeshId:"brick-wall",walls:[]});for(const l of Pe){const h=`wall-${l.id}-exterior`,u=`wall-${l.id}-interior`,d=`wall-${l.id}-side`,f=`${l.id}-walls`;St(e,l.categoryId,l.categoryName,`${l.categoryName} wall presets`),It(e,l.categoryId,f),e.meshes.set(h,{id:h,color:l.exteriorColor,material:"STANDARD",roughness:l.roughness??.78,metalness:l.metalness??.02}),e.meshes.set(u,{id:u,color:l.interiorColor,material:"STANDARD",roughness:l.roughness??.78,metalness:l.metalness??.02}),e.meshes.set(d,{id:d,color:l.sideColor,material:"STANDARD",roughness:l.roughness??.82,metalness:l.metalness??.02}),e.wallGroups.has(f)||e.wallGroups.set(f,{id:f,name:l.labelEn,frontMeshId:h,backMeshId:u,sideMeshId:d,defaultWallKind:l.defaultKind,walls:[]})}e.tileGroups.set("oak-floor",{id:"oak-floor",name:"Oak Wood Floor",floorMeshId:"wood-floor",tiles:[]}),e.tileGroups.set("pine-floor",{id:"pine-floor",name:"Pine Wood Floor",floorMeshId:"wood-floor",tiles:[]}),e.tileGroups.set("marble-floor",{id:"marble-floor",name:"Marble Floor",floorMeshId:"marble-floor",tiles:[]}),e.tileGroups.set("granite-floor",{id:"granite-floor",name:"Granite Floor",floorMeshId:"marble-floor",tiles:[]}),e.tileGroups.set("sand-floor",{id:"sand-floor",name:"Sand Floor",floorMeshId:"sand-floor",tiles:[]}),e.tileGroups.set("snow-floor",{id:"snow-floor",name:"Snow Floor",floorMeshId:"snow-floor",tiles:[]});for(const l of De){const h=`tile-${l.id}`,u=`${l.id}-floor`;Ae(e,l.categoryId,l.categoryName,`${l.categoryName} tile presets`),Re(e,l.categoryId,u),e.meshes.has(h)||e.meshes.set(h,{id:h,color:l.color,material:l.material??"STANDARD",roughness:l.roughness??.65,metalness:l.metalness??.02,...l.opacity!==void 0?{opacity:l.opacity}:{},...l.transparent!==void 0?{transparent:l.transparent}:{},...l.mapTextureUrl?{mapTextureUrl:l.mapTextureUrl,textureUrl:l.mapTextureUrl}:{}}),e.tileGroups.has(u)||e.tileGroups.set(u,{id:u,name:l.labelEn,floorMeshId:h,tiles:[]})}e.selectedWallCategoryId="exterior-walls",e.selectedWallGroupId="brick-walls",e.selectedTileCategoryId="wood-floors",e.selectedTileGroupId="oak-floor";const r=e.tileGroups.get("oak-floor"),o=e.tileGroups.get("marble-floor"),i=e.tileGroups.get("sand-floor"),s=e.tileGroups.get("snow-floor"),a=E.GRID_CELL_SIZE,c=(l,h)=>{const u=h.cell??F(h.position),d={...h,cell:u,footprint:h.footprint??X(u,h.size||1)};l.tiles.push(d);const f=Q(h.size||1);e.tileMeta.set(d.id,{x:d.position.x,z:d.position.z,y:d.position.y,halfSize:f}),q(e.tileIndex,e.tileCells,d.id,d.position.x-f,d.position.x+f,d.position.z-f,d.position.z+f,a)};if(r&&o){for(let l=-3;l<=3;l++)for(let h=-3;h<=3;h++){const u=l*a,d=h*a,f=Math.abs(l)<=1&&Math.abs(h)<=1,m=l>=2&&h===-2,b=l>=2&&h===-3,y=l<=-2&&h>=2,M=l===3&&h===2,v=l===-3&&h===2,R=l===-2&&h===2,_=l===2&&h===-3,G=(y?i:void 0)??(b?s:void 0)??(f?o:void 0)??r,W=b?2:m||y||M?1:f?l===0&&h===0?2:1:0,S={id:`demo-${l+3}-${h+3}`,position:{x:u,y:W*E.HEIGHT_STEP,z:d},tileGroupId:G.id,size:1,shape:v?"round":R?"ramp":_?"stairs":"box"};m?c(G,{...S,objectType:"grass",objectConfig:{grassDensity:90}}):b?c(G,{...S,objectType:"snowfield"}):y?c(G,{...S,objectType:"sand"}):c(G,S)}e.objects.push({id:"demo-sakura-1",type:"sakura",position:{x:3*a,y:0,z:0},config:{size:a}},{id:"demo-flag-1",type:"flag",position:{x:0,y:0,z:-3*a},config:{flagWidth:1.5,flagHeight:1,flagStyle:"flag"}},{id:"demo-fire-1",type:"fire",position:{x:3*a,y:E.HEIGHT_STEP,z:2*a},config:{fireIntensity:1.5}})}e.initialized=!0}),addMesh:e=>t(r=>{r.meshes.set(e.id,e)}),updateMesh:(e,r)=>t(o=>{const i=o.meshes.get(e);i&&o.meshes.set(e,{...i,...r})}),removeMesh:e=>t(r=>{r.meshes.delete(e)}),addWallGroup:e=>t(r=>{r.wallGroups.set(e.id,e)}),updateWallGroup:(e,r)=>t(o=>{const i=o.wallGroups.get(e);i&&o.wallGroups.set(e,{...i,...r})}),removeWallGroup:e=>t(r=>{const o=r.wallGroups.get(e);if(o)for(const i of o.walls)Y(r.wallIndex,r.wallCells,i.id),r.wallMeta.delete(i.id);r.wallGroups.delete(e)}),addWall:(e,r)=>t(o=>{const i=o.wallGroups.get(e);if(i){const s=r.materialId??o.currentWallMaterialId,a=r.wallKind??o.currentWallKind??i.defaultWallKind??"solid",c={...r,...s?{materialId:s}:{},wallKind:a,edge:r.edge??ie(r.position,r.rotation.y)};i.walls.push(c);const l=.5;o.wallMeta.set(c.id,{x:c.position.x,z:c.position.z,rotY:c.rotation.y}),q(o.wallIndex,o.wallCells,c.id,c.position.x-l,c.position.x+l,c.position.z-l,c.position.z+l,1)}}),updateWall:(e,r,o)=>t(i=>{const s=i.wallGroups.get(e);if(s){const a=s.walls.findIndex(c=>c.id===r);if(a!==-1){const c=s.walls[a];if(c){const l=o.position!==void 0||o.rotation!==void 0;l&&(Y(i.wallIndex,i.wallCells,r),i.wallMeta.delete(r)),Object.assign(c,o),(o.position!==void 0||o.rotation!==void 0)&&(c.edge=o.edge??ie(c.position,c.rotation.y)),l&&(i.wallMeta.set(c.id,{x:c.position.x,z:c.position.z,rotY:c.rotation.y}),q(i.wallIndex,i.wallCells,c.id,c.position.x-.5,c.position.x+.5,c.position.z-.5,c.position.z+.5,1))}}}}),moveWallToGroup:(e,r)=>t(o=>{const i=o.wallGroups.get(r);if(!i)return;let s,a=-1;for(const u of o.wallGroups.values())if(a=u.walls.findIndex(d=>d.id===e),a!==-1){s=u;break}if(!s||a===-1||s.id===r){o.selectedWallGroupId=r;return}const c=s.walls[a];if(!c)return;const{materialId:l,...h}=c;s.walls.splice(a,1),i.walls.push({...h,wallGroupId:r}),o.selectedWallGroupId=r}),removeWall:(e,r)=>t(o=>{const i=o.wallGroups.get(e);i&&(Y(o.wallIndex,o.wallCells,r),o.wallMeta.delete(r),i.walls=i.walls.filter(s=>s.id!==r),o.selectedWallId===r&&(o.selectedWallId=null))}),addTileGroup:e=>t(r=>{r.tileGroups.set(e.id,e)}),updateTileGroup:(e,r)=>t(o=>{const i=o.tileGroups.get(e);i&&o.tileGroups.set(e,{...i,...r})}),removeTileGroup:e=>t(r=>{const o=r.tileGroups.get(e);if(o)for(const i of o.tiles)Y(r.tileIndex,r.tileCells,i.id),r.tileMeta.delete(i.id);r.tileGroups.delete(e)}),addTile:(e,r)=>t(o=>{const i=o.tileGroups.get(e);if(i){const s=o.selectedTileObjectType==="grass"?{grassDensity:90,terrainColor:o.currentTerrainColor,terrainAccentColor:o.currentTerrainAccentColor}:o.selectedTileObjectType==="sand"||o.selectedTileObjectType==="snowfield"?{terrainColor:o.currentTerrainColor,terrainAccentColor:o.currentTerrainAccentColor}:void 0,a=r.cell??F(r.position),c=r.materialId??o.currentTileMaterialId,l={...r,cell:a,footprint:r.footprint??X(a,r.size||1),...c?{materialId:c}:{},objectType:o.selectedTileObjectType,...s?{objectConfig:s}:{}};i.tiles.push(l);const h=E.GRID_CELL_SIZE,u=Q(l.size||1);o.tileMeta.set(l.id,{x:l.position.x,z:l.position.z,y:l.position.y,halfSize:u}),q(o.tileIndex,o.tileCells,l.id,l.position.x-u,l.position.x+u,l.position.z-u,l.position.z+u,h)}}),updateTile:(e,r,o)=>t(i=>{const s=i.tileGroups.get(e);if(s){const a=s.tiles.findIndex(c=>c.id===r);if(a!==-1){const c=s.tiles[a];if(c){const l=o.position!==void 0||o.size!==void 0;if(l&&(Y(i.tileIndex,i.tileCells,r),i.tileMeta.delete(r)),Object.assign(c,o),o.position!==void 0||o.size!==void 0||o.cell!==void 0){const h=o.cell??F(c.position);c.cell=h,c.footprint=o.footprint??X(h,c.size||1)}if(l){const h=E.GRID_CELL_SIZE,u=Q(c.size||1);i.tileMeta.set(c.id,{x:c.position.x,z:c.position.z,y:c.position.y,halfSize:u}),q(i.tileIndex,i.tileCells,c.id,c.position.x-u,c.position.x+u,c.position.z-u,c.position.z+u,h)}}}}}),removeTile:(e,r)=>t(o=>{const i=o.tileGroups.get(e);i&&(Y(o.tileIndex,o.tileCells,r),o.tileMeta.delete(r),i.tiles=i.tiles.filter(s=>s.id!==r),o.selectedTileId===r&&(o.selectedTileId=null))}),addBlock:e=>t(r=>{const o=e.cell??F(e.position);r.blocks.push({...e,cell:o})}),updateBlock:(e,r)=>t(o=>{const i=o.blocks.findIndex(a=>a.id===e);if(i===-1)return;const s=o.blocks[i];s&&(Object.assign(s,r),(r.position!==void 0||r.cell!==void 0)&&(s.cell=r.cell??F(s.position)))}),removeBlock:e=>t(r=>{r.blocks=r.blocks.filter(o=>o.id!==e),r.selectedBlockId===e&&(r.selectedBlockId=null)}),setEditMode:e=>t(r=>{r.editMode=e,e!=="none"&&(r.showGrid=!0)}),setShowGrid:e=>t(r=>{r.showGrid=e}),setGridSize:e=>t(r=>{r.gridSize=e}),setSnapToGrid:e=>t(r=>{r.snapToGrid=e}),setHoverPosition:e=>t(r=>{r.hoverPosition=e}),setTileMultiplier:e=>t(r=>{r.currentTileMultiplier=e}),setTileHeight:e=>t(r=>{const o=Math.max(0,Math.min(6,Math.round(e)));r.currentTileHeight=r.currentTileShape==="stairs"||r.currentTileShape==="ramp"?Math.max(1,o):o}),setTileShape:e=>t(r=>{r.currentTileShape=e,(e==="stairs"||e==="ramp")&&r.currentTileHeight===0&&(r.currentTileHeight=1)}),setTileRotation:e=>t(r=>{r.currentTileRotation=e}),setCurrentTileMaterialId:e=>t(r=>{r.currentTileMaterialId=e}),setCustomTileDraft:e=>t(r=>{e.name!==void 0&&(r.currentCustomTileName=e.name),e.color!==void 0&&(r.currentCustomTileColor=e.color),e.textureUrl!==void 0&&(r.currentCustomTileTextureUrl=e.textureUrl)}),applyTilePreset:e=>t(r=>{const o=De.find(a=>a.id===e);if(!o)return;const i=`tile-${o.id}`,s=`${o.id}-floor`;Ae(r,o.categoryId,o.categoryName,`${o.categoryName} tile presets`),Re(r,o.categoryId,s),r.meshes.set(i,{id:i,color:o.color,material:o.material??"STANDARD",roughness:o.roughness??.65,metalness:o.metalness??.02,...o.opacity!==void 0?{opacity:o.opacity}:{},...o.transparent!==void 0?{transparent:o.transparent}:{},...o.mapTextureUrl?{mapTextureUrl:o.mapTextureUrl,textureUrl:o.mapTextureUrl}:{}}),r.tileGroups.has(s)||r.tileGroups.set(s,{id:s,name:o.labelEn,floorMeshId:i,tiles:[]}),r.selectedTileCategoryId=o.categoryId,r.selectedTileGroupId=s,r.currentTileMaterialId=null}),applyCustomTile:()=>t(e=>{const r=e.currentCustomTileName.trim()||"Custom Tile",o=e.currentCustomTileColor||"#8f8f8f",i=e.currentCustomTileTextureUrl.trim(),s=to(`${r}-${o}-${i||"color"}`)||"custom-tile",a=`custom-tile-${s}`,c=`custom-tile-group-${s}`;Ae(e,Ge,"Custom Tiles","User-created tile maps"),Re(e,Ge,c),e.meshes.set(a,{id:a,color:o,material:"STANDARD",roughness:.62,metalness:.02,...i?{mapTextureUrl:i,textureUrl:i}:{}}),e.tileGroups.has(c)||e.tileGroups.set(c,{id:c,name:r,floorMeshId:a,tiles:[]}),e.selectedTileCategoryId=Ge,e.selectedTileGroupId=c,e.currentTileMaterialId=null}),setWallRotation:e=>t(r=>{r.currentWallRotation=e}),setCurrentWallMaterialId:e=>t(r=>{r.currentWallMaterialId=e}),setWallKind:e=>t(r=>{if(r.currentWallKind=e,!!r.selectedWallId)for(const o of r.wallGroups.values()){const i=o.walls.find(s=>s.id===r.selectedWallId);if(i){i.wallKind=e;return}}}),applyWallPreset:e=>t(r=>{const o=Pe.find(l=>l.id===e);if(!o)return;const i=`wall-${o.id}-exterior`,s=`wall-${o.id}-interior`,a=`wall-${o.id}-side`,c=`${o.id}-walls`;St(r,o.categoryId,o.categoryName,`${o.categoryName} wall presets`),It(r,o.categoryId,c),r.meshes.set(i,{id:i,color:o.exteriorColor,material:"STANDARD",roughness:o.roughness??.78,metalness:o.metalness??.02}),r.meshes.set(s,{id:s,color:o.interiorColor,material:"STANDARD",roughness:o.roughness??.78,metalness:o.metalness??.02}),r.meshes.set(a,{id:a,color:o.sideColor,material:"STANDARD",roughness:o.roughness??.82,metalness:o.metalness??.02}),r.wallGroups.has(c)||r.wallGroups.set(c,{id:c,name:o.labelEn,frontMeshId:i,backMeshId:s,sideMeshId:a,defaultWallKind:o.defaultKind,walls:[]}),r.selectedWallCategoryId=o.categoryId,r.selectedWallGroupId=c,r.currentWallKind=o.defaultKind,r.currentWallMaterialId=null}),snapPosition:e=>{const{snapToGrid:r}=n();return r?$t(e):e},checkTilePosition:e=>{const{currentTileMultiplier:r,currentTileRotation:o,currentTileShape:i,selectedTileGroupId:s,selectedTileObjectType:a,blocks:c,tileGroups:l,wallGroups:h}=n(),u=F(e),d=ot({id:"__candidate_tile__",position:e,size:r,shape:i,rotation:o,objectType:a,cell:u,footprint:X(u,r)}),f=Oe(l.values(),h.values(),{blocks:c}),m={subject:d.subject,coord:d.coord,footprint:d.footprint};return!f.canPlace(d.rotation===void 0?m:{...m,rotation:d.rotation}).ok},checkBlockPosition:e=>{const{blocks:r,tileGroups:o,wallGroups:i}=n(),s=it({id:"__candidate_block__",position:e.position,...e.cell?{cell:e.cell}:{},...e.size?{size:e.size}:{}});return!Oe(o.values(),i.values(),{blocks:r}).canPlace({subject:s.subject,coord:s.coord,footprint:s.footprint}).ok},getSupportHeightAt:e=>{const{tileIndex:r,tileMeta:o,currentTileMultiplier:i}=n();return rn(r,o,e,i)},checkWallPosition:(e,r)=>{const{wallIndex:o,wallMeta:i}=n();return on(o,i,e,r)},isInEditMode:()=>{const{editMode:e}=n();return e!=="none"},serialize:()=>Yr(n()),hydrate:e=>t(r=>{Xr(r,e)}),addWallCategory:e=>t(r=>{r.wallCategories.set(e.id,e)}),updateWallCategory:(e,r)=>t(o=>{const i=o.wallCategories.get(e);i&&o.wallCategories.set(e,{...i,...r})}),removeWallCategory:e=>t(r=>{r.wallCategories.delete(e)}),setSelectedWallCategory:e=>t(r=>{r.selectedWallCategoryId=e;const o=r.wallCategories.get(e);if(o&&o.wallGroupIds.length>0){const i=o.wallGroupIds[0];i&&(r.selectedWallGroupId=i)}}),addTileCategory:e=>t(r=>{r.tileCategories.set(e.id,e)}),updateTileCategory:(e,r)=>t(o=>{const i=o.tileCategories.get(e);i&&o.tileCategories.set(e,{...i,...r})}),removeTileCategory:e=>t(r=>{r.tileCategories.delete(e)}),setSelectedTileCategory:e=>t(r=>{r.selectedTileCategoryId=e;const o=r.tileCategories.get(e);if(o&&o.tileGroupIds.length>0){const i=o.tileGroupIds[0];i&&(r.selectedTileGroupId=i)}}),setSelectedTileObjectType:e=>t(r=>{r.selectedTileObjectType=e,e==="grass"?(r.currentTerrainColor="#5a7a35",r.currentTerrainAccentColor="#8fbc5a"):e==="water"?(r.currentTerrainColor="#2f8dbd",r.currentTerrainAccentColor="#9ed6c8"):e==="sand"?(r.currentTerrainColor="#b89b66",r.currentTerrainAccentColor="#e0c27a"):e==="snowfield"&&(r.currentTerrainColor="#dcecff",r.currentTerrainAccentColor="#ffffff")}),setTerrainColors:(e,r)=>t(o=>{o.currentTerrainColor=e,r!==void 0&&(o.currentTerrainAccentColor=r)}),setSelectedPlacedObjectType:e=>t(r=>{r.selectedPlacedObjectType=e}),setSelectedModelObjectId:e=>t(r=>{r.selectedModelObjectId=e}),setModelUrl:e=>t(r=>{r.currentModelUrl=e}),setModelScale:e=>t(r=>{r.currentModelScale=Math.max(.1,Math.min(10,e))}),setModelColor:e=>t(r=>{r.currentModelColor=e}),setSelectedWallId:e=>t(r=>{r.selectedWallId=e,e&&(r.selectedTileId=null,r.selectedBlockId=null)}),setSelectedTileId:e=>t(r=>{r.selectedTileId=e,e&&(r.selectedWallId=null,r.selectedBlockId=null)}),setSelectedBlockId:e=>t(r=>{r.selectedBlockId=e,e&&(r.selectedWallId=null,r.selectedTileId=null)}),addObject:e=>t(r=>{r.objects.push(e)}),removeObject:e=>t(r=>{r.objects=r.objects.filter(o=>o.id!==e)}),updateObject:(e,r)=>t(o=>{const i=o.objects.findIndex(s=>s.id===e);if(i!==-1){const s=o.objects[i];s&&Object.assign(s,r)}}),setFlagWidth:e=>t(r=>{r.currentFlagWidth=e}),setFlagHeight:e=>t(r=>{r.currentFlagHeight=e}),setFlagImageUrl:e=>t(r=>{r.currentFlagImageUrl=e}),setFlagStyle:e=>t(r=>{r.currentFlagStyle=e;const o=fe[e];r.currentFlagWidth=o.defaultWidth,r.currentFlagHeight=o.defaultHeight}),setFireIntensity:e=>t(r=>{r.currentFireIntensity=e}),setFireWidth:e=>t(r=>{r.currentFireWidth=e}),setFireHeight:e=>t(r=>{r.currentFireHeight=e}),setFireColor:e=>t(r=>{r.currentFireColor=e}),setObjectRotation:e=>t(r=>{r.currentObjectRotation=e}),setObjectPrimaryColor:e=>t(r=>{r.currentObjectPrimaryColor=e}),setObjectSecondaryColor:e=>t(r=>{r.currentObjectSecondaryColor=e}),setTreeKind:e=>t(r=>{const o=zt[e];r.currentTreeKind=e,r.currentObjectPrimaryColor=o.primaryColor,r.currentObjectSecondaryColor=o.secondaryColor}),setBillboardText:e=>t(r=>{r.currentBillboardText=e}),setBillboardImageUrl:e=>t(r=>{r.currentBillboardImageUrl=e}),setBillboardColor:e=>t(r=>{r.currentBillboardColor=e}),setBillboardWidth:e=>t(r=>{r.currentBillboardWidth=e}),setBillboardHeight:e=>t(r=>{r.currentBillboardHeight=e}),setBillboardScale:e=>t(r=>{r.currentBillboardScale=e}),setBillboardOffsetY:e=>t(r=>{r.currentBillboardOffsetY=e}),setBillboardElevation:e=>t(r=>{r.currentBillboardElevation=e}),setBillboardIntensity:e=>t(r=>{r.currentBillboardIntensity=e}),setShowSnow:e=>t(r=>{r.showSnow=e,r.weatherEffect=e?"snow":"none"}),setShowFog:e=>t(r=>{r.showFog=e}),setFogColor:e=>t(r=>{r.fogColor=e}),setWeatherEffect:e=>t(r=>{r.weatherEffect=e,r.showSnow=e==="snow"})})));function ue(t,n,e,r){const o=Math.atan2(n.z-e.z,n.x-e.x);t.updateMouse({target:n,angle:o,position:new I.Vector2(n.x,n.z),isActive:!0,shouldRun:r})}function ro(t={}){const{minHeight:n=.5,offsetY:e=.5,useNavigation:r=!0,simplifyPath:o=!0,waypointThreshold:i=1,fallbackToDirectOnFail:s=!0,agentRadius:a=.35,agentWidth:c,agentDepth:l,clearance:h}=t,{activeState:u}=Je(),d=tt(),f=!!u?.position,m=(M,v,R)=>{if(R!=="ground"||!u?.position)return!1;try{const _=u.position,G=p.V3(M.point.x,M.point.y,M.point.z),W=Math.max(G.y+e,n),S=p.V3(G.x,W,G.z),w=_.clone(),T=ht();return r?(B.getInstance().init().then(()=>{if(!kn(T))return;const A=B.getInstance(),x={agentRadius:a,...c!==void 0?{agentWidth:c}:{},...l!==void 0?{agentDepth:l}:{},...h!==void 0?{clearance:h}:{}};if(S.y=Math.max(A.sampleHeight(S.x,S.z)+e,n),A.hasLineOfSight(w.x,w.z,S.x,S.z,x)){Te([S],i,v),ue(d,S,w,v);return}const C=A.findPath(w.x,w.z,S.x,S.z,{weighted:!0,...x});if(C.length===0){xe(),s&&!A.hasNavigationConstraints()&&A.isWalkable(S.x,S.z,x)&&(Te([S],i,v),ue(d,S,w,v));return}const N=(o?A.smoothPath(C,[w.x,w.y,w.z],[S.x,S.y,S.z],x):C).map(O=>new I.Vector3(O[0],O[1],O[2])).filter(O=>O.distanceTo(w)>i),j=N[N.length-1];(!j||j.distanceTo(S)>i)&&N.push(S);const H=N.length>0?N:[S];Te(H,i,v),ue(d,H[0]??S,w,v)}),!0):(xe(),ue(d,S,w,v),!0)}catch(_){return console.error("moveClicker error:",_),!1}};return{moveClicker:m,stopClicker:()=>{try{if(!f)return;ht(),xe(),d.updateMouse({isActive:!1,shouldRun:!1})}catch{}},onClick:M=>{m(M,!1,"ground")},isReady:f}}exports.BUILDING_BASIC_OBJECT_OPTIONS=_t;exports.BUILDING_FLAG_STYLE_OPTIONS=dr;exports.BUILDING_PLACED_OBJECT_OPTIONS=ur;exports.BUILDING_TILE_OBJECT_OPTIONS=lr;exports.BUILDING_TILE_PRESETS=De;exports.BUILDING_TILE_SHAPE_OPTIONS=cr;exports.BUILDING_TREE_COLOR_PRESETS=zt;exports.BUILDING_TREE_OPTIONS=ar;exports.BUILDING_WALL_KIND_OPTIONS=sr;exports.BUILDING_WALL_PRESETS=Pe;exports.BUILDING_WEATHER_EFFECT_OPTIONS=ir;exports.CacheSnapshot=be;exports.CoreBridge=Le;exports.DEFAULT_MOTIONS_INPUT_EXTENSION_ID=Xe;exports.DEFAULT_MOTIONS_PHYSICS_EXTENSION_ID=Ye;exports.DEFAULT_MOTIONS_RUNTIME_SERVICE_ID=Qe;exports.DomainBridge=Be;exports.EnableEventLog=Mt;exports.EnableMetrics=Ct;exports.FLAG_STYLE_META=fe;exports.GaesupRuntimeProvider=or;exports.LogSnapshot=me;exports.MOTIONS_TELEPORT_EVENT=et;exports.NavigationSystem=B;exports.PhysicsEntity=Ht;exports.TILE_CONSTANTS=E;exports.ValidateCommand=Fe;exports.applyToonToScene=jt;exports.blockToPlacementEntry=it;exports.buildingCellToWorld=qt;exports.buildingGridAdapter=L;exports.buildingGroupsToPlacementEntries=nn;exports.buildingPlacementAdapter=Xt;exports.cellToTilePosition=qr;exports.createBlockFootprint=Yt;exports.createBuildingPlacementEngine=Oe;exports.createMotionsPlugin=Dt;exports.createMotionsRuntime=Pt;exports.createTileFootprint=X;exports.createToonMaterial=Rr;exports.disposeToonGradients=zr;exports.edgeKey=Vr;exports.edgeSideToWallRotation=Jt;exports.edgeToWallTransform=$r;exports.getClickNavigationRoute=Gt;exports.getDefaultToonMode=Kt;exports.getTileSupportHeight=rn;exports.getToonGradient=nt;exports.hasTileCollision=Jr;exports.hasWallCollision=on;exports.indexAabb=q;exports.loadCoreWasm=At;exports.motionsPlugin=yr;exports.normalizeQuarterTurnRotation=Zt;exports.pair=rt;exports.queryAabbIds=Ie;exports.requestMotionsTeleport=mr;exports.resolveRuntimeInputBackend=Nt;exports.setDefaultToonMode=kr;exports.snapBuildingPosition=$t;exports.subscribeClickNavigationRoute=zn;exports.tileFootprintKeys=Zr;exports.tileGroupToPlacementEntries=en;exports.tileHalfSize=Q;exports.tileOverlaps=st;exports.tilePositionToCell=F;exports.tileToPlacementEntry=ot;exports.unindexId=Y;exports.useAnimationBridge=Tt;exports.useBuildingStore=no;exports.useClicker=ro;exports.useGaesupGltf=Or;exports.useGaesupRuntime=qe;exports.useGaesupRuntimeRevision=Ze;exports.useInputBackend=tt;exports.useInteractionSystem=Ot;exports.useStateSystem=Je;exports.wallGroupToPlacementEntries=tn;exports.wallToPlacementEntry=Qt;exports.wallTransformToEdge=ie;exports.worldToBuildingCell=Vt;exports.zigZag=Ne;
|
|
1
|
+
"use strict";const N=require("react/jsx-runtime"),g=require("react"),he=require("@react-three/drei"),We=require("@react-three/fiber"),Me=require("@react-three/rapier"),an=require("three"),vt=require("three-stdlib"),p=require("./gaesupStore-2zKBYTYo.cjs");require("reflect-metadata");const ln=require("./EventBus-DjA75MWC.cjs"),cn=require("immer"),un=require("zustand"),dn=require("zustand/middleware/immer");function hn(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,r.get?r:{enumerable:!0,get:()=>t[e]})}}return n.default=t,Object.freeze(n)}const I=hn(an);class fn{engines;snapshots;eventListeners;eventHandlers;middlewares;constructor(){this.engines=new Map,this.snapshots=new Map,this.eventListeners=new Set,this.eventHandlers=new Map,this.middlewares=[]}use(n){this.middlewares.push(n)}emit(n){const e=this.eventHandlers.get(n.type);e&&e.forEach(i=>i(n));let r=0;const o=()=>{if(r<this.middlewares.length){const i=this.middlewares[r++];i?.(n,o)}};o()}on(n,e){return this.eventHandlers.has(n)||this.eventHandlers.set(n,new Set),this.eventHandlers.get(n).add(e),()=>{this.eventHandlers.get(n)?.delete(e)}}register(n,...e){const r=this.buildEngine(n,...e);if(!r)return;const o=this.engines.get(n);o!==r&&(o&&(o.dispose(),this.snapshots.delete(n)),this.engines.set(n,r),this.emit({type:"register",id:n,timestamp:Date.now(),data:{engine:r}}))}unregister(n){const e=this.engines.get(n);e&&(e.dispose(),this.engines.delete(n),this.snapshots.delete(n),this.emit({type:"unregister",id:n,timestamp:Date.now(),data:{engine:e}}))}getEngine(n){return this.engines.get(n)}execute(n,e){const r=this.getEngine(n);r&&(this.emit({type:"execute",id:n,timestamp:Date.now(),data:{command:e}}),this.executeCommand(r,e,n),this.notifyListeners(n))}snapshot(n){const e=this.getEngine(n);if(!e)return null;const r=this.createSnapshot(e,n);return r&&this.emit({type:"snapshot",id:n,timestamp:Date.now(),data:{snapshot:r}}),r}getCachedSnapshot(n){return this.snapshots.get(n)}cacheSnapshot(n,e){this.snapshots.set(n,e)}subscribe(n){return this.eventListeners.add(n),()=>this.eventListeners.delete(n)}notifyListeners(n){if(this.eventListeners.size===0)return;const e=this.snapshot(n);e&&(this.cacheSnapshot(n,e),this.eventListeners.forEach(r=>r(e,n)))}getAllSnapshots(){const n=new Map;return this.engines.forEach((e,r)=>{const o=this.snapshot(r);o&&n.set(r,o)}),n}dispose(){this.engines.forEach(n=>n.dispose()),this.engines.clear(),this.snapshots.clear(),this.eventListeners.clear(),this.eventHandlers.clear(),this.middlewares=[]}}class Le extends fn{constructor(){super(),this.processMetrics(),this.processEventLog()}processMetrics(){const n=Object.getPrototypeOf(this);Reflect.getMetadata("enableMetrics",n)}processEventLog(){const n=Object.getPrototypeOf(this);Reflect.getMetadata("enableEventLog",n)}}function Mt(){return function(...t){if(t.length===1){const r=t[0];Reflect.defineMetadata("enableEventLog",!0,r.prototype);return}const[n,e]=t;Reflect.defineMetadata("enableEventLog",!0,n,e)}}function me(){return function(t,n,e){const r=e.value;return e.value=function(...o){const i=performance.now(),s=r.apply(this,o),a=performance.now();return p.logger.log(`[${this.constructor.name}] ${n} snapshot processed in ${(a-i).toFixed(2)}ms`),s},e}}function Fe(){return function(t,n,e){const r=e.value;return e.value=function(o,i,...s){if(!i||typeof i!="object"){p.logger.warn(`[${this.constructor.name}] Invalid command passed to ${n}`);return}return r.apply(this,[o,i,...s])},e}}function ye(){return function(t,n,e){const r=e.value;return e.value=function(...o){const[i]=o;return i?this.getEngine?((typeof i=="string"||typeof i=="number"||typeof i=="symbol"?this.getEngine(i):null)||p.logger.warn(`[${this.constructor.name}] No engine found for id: ${String(i)} in ${n}`),r.apply(this,o)):r.apply(this,o):(p.logger.warn(`[${this.constructor.name}] No id provided for ${n}`),r.apply(this,o))},e}}function be(t=16){const n=new Map;return function(e,r,o){const i=o.value;return o.value=function(...s){const a=s[0],c=typeof a=="object"&&a!==null&&"id"in a?String(a.id):String(a??"default"),l=`${this.constructor.name}_${r}_${c}`,h=Date.now(),u=n.get(l);if(u&&h-u.timestamp<t)return u.value;const d=i.apply(this,s);return n.set(l,{value:d,timestamp:h}),d},o}}function Ct(){return function(t){Reflect.defineMetadata("enableMetrics",!0,t.prototype)}}function Be(t){return function(n){Reflect.defineMetadata("domain",t,n),p.BridgeRegistry.register(t,n),p.DIContainer.getInstance().registerService(n)}}function gn(t){return function(n,e){const r=Reflect.getMetadata("commands",n)||[];r.push({name:t,method:e}),Reflect.defineMetadata("commands",r,n)}}var pn=Object.getOwnPropertyDescriptor,mn=(t,n,e,r)=>{for(var o=r>1?void 0:r?pn(n,e):n,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(o)||o);return o};let ke=class extends p.AbstractSystem{callbacks;systemType;constructor(t="default"){const n={currentAnimation:"idle",animationMixer:null,actions:new Map,isPlaying:!1,currentWeight:1,blendDuration:.3,lastUpdate:Date.now()},e={activeAnimations:0,totalActions:0,currentWeight:1,mixerTime:0,lastUpdate:0,blendProgress:0,frameTime:0};super(n,e),this.callbacks=new Set,this.systemType=t}getSystemType(){return this.systemType}subscribe(t){return this.callbacks.add(t),()=>this.callbacks.delete(t)}notifyCallbacks(){this.callbacks.forEach(t=>t(this.getMetrics()))}initializeMixer(t){this.state.animationMixer=new I.AnimationMixer(t)}addAnimation(t,n){if(!this.state.animationMixer)return;const e=this.state.animationMixer.clipAction(n);this.state.actions.set(t,e),this.updateMetrics(0),this.notifyCallbacks()}registerAction(t,n){this.state.actions.set(t,n),this.updateMetrics(0),this.notifyCallbacks()}playAnimation(t,n=this.state.blendDuration){const e=this.state.actions.get(t);if(!e)return;const r=this.state.actions.get(this.state.currentAnimation);r&&r!==e&&r.fadeOut(n),e.reset().fadeIn(n).play(),this.state.currentAnimation=t,this.state.isPlaying=!0,this.updateMetrics(0),this.notifyCallbacks()}stopAnimation(){const t=this.state.actions.get(this.state.currentAnimation);t&&t.stop(),this.state.isPlaying=!1,this.state.currentAnimation="idle",this.updateMetrics(0),this.notifyCallbacks()}setWeight(t){const n=this.state.actions.get(this.state.currentAnimation);n&&(n.weight=t,this.state.currentWeight=t,this.updateMetrics(0),this.notifyCallbacks())}setTimeScale(t){const n=this.state.actions.get(this.state.currentAnimation);n&&(n.timeScale=t,this.notifyCallbacks())}performUpdate(t){this.state.animationMixer&&(this.state.animationMixer.update(t.deltaTime/1e3),this.metrics.mixerTime+=t.deltaTime/1e3)}createUpdateArgs(t){return t}updateAnimation(t){const n={deltaTime:t*1e3,totalTime:0,frameCount:0};super.update(n),this.callbacks.size>0&&this.notifyCallbacks()}getCurrentAnimation(){return this.state.currentAnimation}getAnimationList(){return Array.from(this.state.actions.keys())}getMetrics(){return this.metrics}getState(){return this.state}updateMetrics(t){this.metrics.frameTime=t;let n=0;for(const e of this.state.actions.values())e.isRunning()&&n++;this.metrics.activeAnimations=n,this.metrics.totalActions=this.state.actions.size,this.metrics.currentWeight=this.state.currentWeight,this.metrics.lastUpdate=Date.now()}clearActions(){this.state.actions.forEach(t=>{t.isRunning()&&t.stop()}),this.state.actions.clear(),this.state.currentAnimation="idle",this.state.isPlaying=!1,this.updateMetrics(0),this.notifyCallbacks()}onDispose(){this.state.animationMixer&&(this.state.animationMixer.stopAllAction(),this.state.animationMixer=null),this.state.actions.clear(),this.callbacks.clear()}};ke=mn([p.ManageRuntime({autoStart:!1})],ke);var yn=Object.defineProperty,bn=Object.getOwnPropertyDescriptor,Z=(t,n,e,r)=>{for(var o=r>1?void 0:r?bn(n,e):n,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=(r?s(n,e,o):s(o))||o);return r&&o&&yn(n,e,o),o};function lt(t){return t.replace(/[\x00-\x1F\x7F]/g,"").trim()}let K=class extends Le{constructor(){super(),["character","vehicle","airplane"].forEach(n=>{this.register(n)}),this.setupEngineSubscriptions()}setupEngineSubscriptions(){this.engines.forEach((t,n)=>{t.subscribe(()=>{this.notifyListeners(n)})})}buildEngine(t){return new ke(t)}registerAnimationAction(t,n,e){const r=this.getEngine(t);if(r){const o=lt(n),i=o.length>0?o:n;r.registerAction(i,e)}}registerAnimations(t,n){const e=this.getEngine(t);e&&Object.entries(n).forEach(([r,o])=>{if(o){const i=lt(r),s=i.length>0?i:r;e.registerAction(s,o)}})}unregisterAnimations(t){const n=this.getEngine(t);n&&n.clearActions()}executeCommand(t,n){switch(n.type){case"play":n.animation&&t.playAnimation(n.animation,n.duration);break;case"stop":t.stopAnimation();break;case"setWeight":n.weight!==void 0&&t.setWeight(n.weight);break;case"setSpeed":n.speed!==void 0&&t.setTimeScale(n.speed);break}}createSnapshot(t){const n=t.getState(),e=t.getMetrics();return{currentAnimation:n.currentAnimation,isPlaying:n.isPlaying,weight:n.currentWeight,speed:1,availableAnimations:t.getAnimationList(),metrics:{activeAnimations:e.activeAnimations,totalActions:e.totalActions,mixerTime:e.mixerTime,lastUpdate:e.lastUpdate}}}getMetrics(t){const n=this.getEngine(t);return n?n.getMetrics():null}update(t,n){const e=this.getEngine(t);e&&e.updateAnimation(n)}execute(t,n){super.execute(t,n)}snapshot(t){const n=super.snapshot(t);return n||{currentAnimation:"idle",isPlaying:!1,weight:0,speed:1,availableAnimations:[],metrics:{activeAnimations:0,totalActions:0,mixerTime:0,lastUpdate:0}}}};Z([ye()],K.prototype,"registerAnimationAction",1);Z([ye()],K.prototype,"unregisterAnimations",1);Z([gn("play"),Fe()],K.prototype,"executeCommand",1);Z([me(),be(16)],K.prototype,"createSnapshot",1);Z([ye()],K.prototype,"getMetrics",1);Z([ye()],K.prototype,"update",1);Z([me(),be(16)],K.prototype,"snapshot",1);K=Z([Be("animation"),Ct()],K);let ct=null;function Ke(){const t=p.BridgeFactory.getOrCreate("animation");return t||(ct??=new K,ct)}function Tt(){const t=g.useRef(null),n=p.useGaesupStore(h=>h.mode),e=p.useGaesupStore(h=>h.animationState),r=p.useGaesupStore(h=>h.setAnimation),o=Ke();t.current=o,g.useEffect(()=>{t.current=o;const h=o.subscribe((u,d)=>{if(!u)return;const f=d,m=p.useGaesupStore.getState().animationState?.[f]?.current;u.currentAnimation!==m&&r(f,u.currentAnimation)});return()=>{h()}},[r,o]);const i=g.useCallback((h,u)=>{t.current&&t.current.execute(h,u)},[]),s=g.useCallback((h,u)=>{i(h,{type:"play",animation:u})},[i]),a=g.useCallback(h=>{i(h,{type:"stop"})},[i]),c=g.useCallback((h,u)=>{t.current&&t.current.registerAnimations(h,u)},[]),l=n?.type||"character";return{bridge:o,playAnimation:s,stopAnimation:a,executeCommand:i,registerAnimations:c,currentType:l,currentAnimation:e?.[l]?.current||"idle"}}var wn=Object.defineProperty,Sn=Object.getOwnPropertyDescriptor,In=(t,n,e,r)=>{for(var o=Sn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&wn(n,e,o),o};class xt{animationBridge=Ke();lastAnimation="idle";update(n){const{isMoving:e,isRunning:r,isJumping:o,isFalling:i,isRiding:s}=n;let a="idle";s?a="ride":o?a="jump":i?a="fall":r?a="run":e&&(a="walk"),a!==this.lastAnimation&&(this.animationBridge.execute("character",{type:"play",animation:a}),this.lastAnimation=a)}}In([p.HandleError(),p.Profile()],xt.prototype,"update");var vn=Object.defineProperty,Mn=Object.getOwnPropertyDescriptor,we=(t,n,e,r)=>{for(var o=Mn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&vn(n,e,o),o};class se{config;constructor(n){this.config=n}applyGravity(n,e){if(!n.current)return;const{modeType:r}=e;switch(r){case"character":this.applyCharacterGravity(n,e);break;case"airplane":this.applyAirplaneGravity(n);break;case"vehicle":this.applyVehicleGravity(n);break;default:this.applyCharacterGravity(n,e)}}applyCharacterGravity(n,e){const{gameStates:{isJumping:r,isFalling:o}}=e,{jumpGravityScale:i=1.5,normalGravityScale:s=1}=this.config;r||o?n.current.setGravityScale(i,!1):n.current.setGravityScale(s,!1)}applyAirplaneGravity(n){const{gravityScale:e=.3}=this.config;n.current.setGravityScale(e,!1)}applyVehicleGravity(n){const{normalGravityScale:e=1}=this.config;n.current.setGravityScale(e,!1)}}we([p.Profile()],se.prototype,"applyGravity");we([p.Profile()],se.prototype,"applyCharacterGravity");we([p.Profile()],se.prototype,"applyAirplaneGravity");we([p.Profile()],se.prototype,"applyVehicleGravity");var Cn=Object.defineProperty,Tn=Object.getOwnPropertyDescriptor,je=(t,n,e,r)=>{for(var o=Tn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&Cn(n,e,o),o};const xn=100,ze=1e3,Ce=10;function En(){const t=new Map,n=Array.from({length:Ce},()=>new I.Vector3);return{getTempVector:e=>{const r=n[e%Ce];return r?r.set(0,0,0):new I.Vector3},getCached:(e,r)=>{if(!t.has(e)){if(t.size>=xn){const o=t.keys().next().value;o!==void 0&&t.delete(o)}t.set(e,r())}return t.get(e)},clear:()=>t.clear(),getStats:()=>({cacheSize:t.size,tempVectorCount:Ce})}}const U=new Map,ut=t=>{const n=Math.round(t*100)/100;if(!U.has(n)){if(U.size>=ze){const e=U.keys().next().value;e!==void 0&&U.delete(e)}U.set(n,{sin:Math.sin(t),cos:Math.cos(t)})}return U.get(n)},Gn=()=>U.clear(),An=()=>({size:U.size,maxSize:ze,coverage:`${(U.size/ze*100).toFixed(1)}%`}),dt=(t,n,e=.01)=>Math.abs(t-n)>=e,Se=class Et{static instance;vectorCaches=new Map;static getInstance(){return this.instance??=new Et}getVectorCache(n){return this.vectorCaches.get(n)??(this.vectorCaches.set(n,En()),this.vectorCaches.get(n))}clearAll(){this.vectorCaches.forEach(n=>n.clear()),Gn()}getStats(){return{vectorCaches:Array.from(this.vectorCaches.entries()).map(([n,e])=>({id:n,...e.getStats()})),trigCache:An()}}};je([p.Profile()],Se.prototype,"getVectorCache");je([p.HandleError()],Se.prototype,"clearAll");je([p.MonitorMemory(10)],Se.prototype,"getStats");let Rn=Se;const k={requestId:0,waypoints:[],threshold:1,shouldRun:!1,listeners:new Set};function He(){k.listeners.forEach(t=>t())}function ht(){return k.requestId+=1,k.requestId}function kn(t){return k.requestId===t}function Te(t,n,e){k.waypoints=t,k.threshold=n,k.shouldRun=e,He()}function xe(){k.waypoints.length!==0&&(k.waypoints=[],He())}function zn(t){return k.listeners.add(t),()=>k.listeners.delete(t)}function Gt(){return k.waypoints}function _n(){return{threshold:k.threshold,shouldRun:k.shouldRun}}function Pn(t){const n=k.waypoints[0];return n?t.distanceTo(n)>k.threshold?n:(k.waypoints.shift(),He(),k.waypoints[0]??null):null}var Dn=Object.defineProperty,Nn=Object.getOwnPropertyDescriptor,ae=(t,n,e,r)=>{for(var o=Nn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&Dn(n,e,o),o};class ne{memoManager=Rn.getInstance();vectorCache=this.memoManager.getVectorCache("direction");lastEulerY={character:0,vehicle:0,airplane:0};lastDirectionLength=0;lastKeyboardState={forward:!1,backward:!1,leftward:!1,rightward:!1};timers=new Set;inputBackend;config;tempEuler=new I.Euler;tempQuaternion=new I.Quaternion;targetQuaternion=new I.Quaternion;cameraForward=new I.Vector3;cameraRight=new I.Vector3;desiredMovement=new I.Vector3;upAxis=new I.Vector3(0,1,0);constructor(n={},e=p.createInteractionInputAdapter()){this.inputBackend=e,this.config=n}updateDirection(n,e,r,o){const{modeType:i}=n;switch(i){case"character":this.updateCharacterDirection(n,e,r);break;case"vehicle":this.updateVehicleDirection(n,e,r);break;case"airplane":this.updateAirplaneDirection(n,o,e,r);break;default:this.updateCharacterDirection(n,e,r)}}updateCharacterDirection(n,e,r){const{activeState:o}=n,i=this.getKeyboard(r),s=this.getMouse(r),a=this.lastKeyboardState.forward!==i.forward||this.lastKeyboardState.backward!==i.backward||this.lastKeyboardState.leftward!==i.leftward||this.lastKeyboardState.rightward!==i.rightward,c=i.forward||i.backward||i.leftward||i.rightward;s.isActive?this.handleMouseDirection(o,s,this.config,r):c&&this.handleKeyboardDirection(o,i,this.config,e,r),(a||c)&&(this.lastKeyboardState={forward:i.forward,backward:i.backward,leftward:i.leftward,rightward:i.rightward}),this.emitRotationUpdate(o,"character")}updateVehicleDirection(n,e,r){const{activeState:o}=n,i=this.getKeyboard(r),{forward:s,backward:a,leftward:c,rightward:l}=i,h=Number(l)-Number(c),u=Number(s)-Number(a);o.euler.y-=h*(Math.PI/64);const{sin:d,cos:f}=ut(o.euler.y);o.direction.set(d*u,0,f*u),o.dir.copy(o.direction),this.emitRotationUpdate(o,"vehicle")}updateAirplaneDirection(n,e,r,o){const{activeState:i}=n,s=this.getKeyboard(o),{forward:a,backward:c,leftward:l,rightward:h,shift:u,space:d}=s,{angleDelta:f={x:.02,y:.02,z:.02},maxAngle:m={x:Math.PI/6,y:Math.PI,z:Math.PI/6},accelRatio:b=1.5}=this.config||{};if(!e?.current)return;let y=1;u&&(y*=b),d&&(y*=1.5);const M=Number(c)-Number(a),v=Number(l)-Number(h);r==="chase"?i.euler.y+=v*f.y*.5:i.euler.y+=v*f.y,this.applyAirplaneRotation(e.current,M,v,m,i),i.direction.set(Math.sin(i.euler.y)*y,-M*y,Math.cos(i.euler.y)*y),i.dir.copy(i.direction).normalize(),this.emitRotationUpdate(i,"airplane")}getKeyboard(n){return n?.inputRef?.current?.keyboard??this.inputBackend.getKeyboard()}getMouse(n){return n?.inputRef?.current?.mouse??this.inputBackend.getMouse()}applyAirplaneRotation(n,e,r,o,i){const s=o.x*e,a=-o.z*r,c=n.rotation.x,l=n.rotation.z,h=o.x,u=o.z;let d=c+s,f=l+a;d<-h?d=-h:d>h&&(d=h),f<-u?f=-u:f>u&&(f=u),i.euler.x=d,i.euler.z=f,this.tempEuler.set(d,0,f),this.tempQuaternion.setFromEuler(n.rotation),this.targetQuaternion.setFromEuler(this.tempEuler),this.tempQuaternion.slerp(this.targetQuaternion,.2),n.setRotationFromQuaternion(this.tempQuaternion)}handleMouseDirection(n,e,r,o){this.syncClickNavigationTarget(e,o);const{automation:i}=o?.worldContext||{};if(i?.settings.trackProgress&&i.queue.actions&&i.queue.actions.length>0){const s=i.queue.actions.shift();if(s&&s.target){const a=this.vectorCache.getTempVector(2),c=o?.rigidBodyRef?.current;if(c){const u=c.translation();a.set(u.x,u.y,u.z)}else a.set(0,0,0);const l=s.target,h=this.vectorCache.getTempVector(1);h.subVectors(l,a).normalize(),o?.memo&&(o.memo.direction||(o.memo.direction=new I.Vector3),o.memo.directionTarget||(o.memo.directionTarget=new I.Vector3),o.memo.direction.copy(h),o.memo.directionTarget.copy(l)),i.queue.loop&&s&&i.queue.actions&&i.queue.actions.push(s)}}else{if(o?.rigidBodyRef.current){const s=o.rigidBodyRef.current.translation(),a=this.vectorCache.getTempVector(0);if(a.set(s.x,s.y,s.z),p.calcNorm(a,e.target)<1){this.handleClicker(o,s);return}}this.applyMouseRotation(n,e,r)}}syncClickNavigationTarget(n,e){if(Gt().length===0)return;const r=this.vectorCache.getTempVector(3),o=e?.rigidBodyRef?.current;if(o){const c=o.translation();r.set(c.x,c.y,c.z)}else r.copy(e?.inputRef.current.mouse.target??n.target);const i=Pn(r),{shouldRun:s}=_n();if(!i){e?.setMouseInput?.({isActive:!1,shouldRun:!1}),n.isActive=!1,n.shouldRun=!1;return}const a=Math.atan2(i.z-r.z,i.x-r.x);e?.setMouseInput?.({target:i,angle:a,position:new I.Vector2(i.x,i.z),isActive:!0,shouldRun:s}),n.target=i,n.angle=a,n.isActive=!0,n.shouldRun=s}handleClicker(n,e){const{automation:r}=n.worldContext||{};if(r?.settings.trackProgress&&r.queue.actions&&r.queue.actions.length>0){const o=r.queue.actions.shift();if(o&&o.target){const i=Math.atan2(o.target.z-e.z,o.target.x-e.x);n.setMouseInput?.({target:o.target,angle:i,isActive:!0})}else if(o&&o.type==="wait"){const i=o.duration||1e3;if(n.state){n.state.clock.stop();const s=setTimeout(()=>{n.state&&n.state.clock.start(),this.timers.delete(s)},i);this.timers.add(s)}}r.queue.loop&&o&&r.queue.actions&&r.queue.actions.push(o)}else n.setMouseInput?.({isActive:!1,shouldRun:!1})}applyMouseRotation(n,e,r){n.euler.y=Math.PI/2-e.angle;const{sin:o,cos:i}=ut(n.euler.y);n.dir.set(-o,0,-i),n.direction.copy(n.dir)}handleKeyboardDirection(n,e,r,o,i){const s=this.resolveKeyboardMovementDirection(e,i);s&&(n.dir.copy(s).multiplyScalar(-1),n.euler.y=Math.atan2(s.x,s.z),n.direction.copy(n.dir))}resolveKeyboardMovementDirection(n,e){const r=Number(n.forward)-Number(n.backward),o=Number(n.rightward)-Number(n.leftward);if(r===0&&o===0)return null;const i=this.desiredMovement.set(0,0,0),s=e?.state?.camera;return s&&(s.getWorldDirection(this.cameraForward),this.cameraForward.y=0,this.cameraForward.lengthSq()>1e-6&&(this.cameraForward.normalize(),this.cameraRight.crossVectors(this.cameraForward,this.upAxis).normalize(),i.addScaledVector(this.cameraForward,r),i.addScaledVector(this.cameraRight,o))),i.lengthSq()<=1e-6&&i.set(o,0,-r),i.normalize()}emitRotationUpdate(n,e){const r=n.dir.length(),o=dt(n.euler.y,this.lastEulerY[e],.001),i=dt(r,this.lastDirectionLength,.01);(o||i)&&(this.lastDirectionLength=r),this.lastEulerY[e]=n.euler.y}dispose(){this.timers.forEach(n=>clearTimeout(n)),this.timers.clear()}}ae([p.Profile()],ne.prototype,"updateDirection");ae([p.Profile()],ne.prototype,"updateCharacterDirection");ae([p.Profile()],ne.prototype,"updateVehicleDirection");ae([p.Profile()],ne.prototype,"updateAirplaneDirection");ae([p.HandleError()],ne.prototype,"dispose");let le=null;function On(t){return t.endsWith("/")?t:`${t}/`}function Wn(){try{const t=globalThis.__GAESUP_WASM_BASE_URL__;if(t)return new URL("wasm/gaesup_core.wasm",On(t)).toString();if(typeof document<"u"&&typeof document.baseURI=="string"&&document.baseURI.length>0)return new URL("wasm/gaesup_core.wasm",document.baseURI).toString()}catch{}return"/wasm/gaesup_core.wasm"}async function At(){return typeof WebAssembly>"u"?null:le||(le=(async()=>{try{const t=Wn(),n=await fetch(t);if(!n.ok)return null;const e=await n.arrayBuffer(),{instance:r}=await WebAssembly.instantiate(e,{}),o=r.exports;return!o||!(o.memory instanceof WebAssembly.Memory)||typeof o.alloc_f32!="function"||typeof o.dealloc_f32!="function"?null:o}catch{return null}})(),le)}const Ln={cellSize:2,worldMinX:-200,worldMinZ:-200,worldMaxX:200,worldMaxZ:200,maxStepHeight:1.1},Fn=[[1,0,10],[-1,0,10],[0,1,10],[0,-1,10],[1,1,14],[1,-1,14],[-1,1,14],[-1,-1,14]],te=1e-6;function Bn(t){return!!(t&&typeof t.alloc_u8=="function"&&typeof t.dealloc_u8=="function"&&typeof t.alloc_u32=="function"&&typeof t.dealloc_u32=="function"&&typeof t.astar_find_path=="function")}class B{static instance=null;config;gridWidth;gridHeight;grid;costGrid;heightGrid;hasHeightData=!1;hasBlockedData=!1;wasm=null;ready=!1;gridPtr=0;outPathPtr=0;outCapacity=512;constructor(n={}){this.config={...Ln,...n};const{cellSize:e,worldMinX:r,worldMinZ:o,worldMaxX:i,worldMaxZ:s}=this.config;this.gridWidth=Math.ceil((i-r)/e),this.gridHeight=Math.ceil((s-o)/e);const a=this.gridWidth*this.gridHeight;this.grid=new Uint8Array(a).fill(1),this.costGrid=new Uint8Array(a).fill(1),this.heightGrid=new Float32Array(a)}static getInstance(n){return B.instance||(B.instance=new B(n)),B.instance}async init(){if(this.ready)return!0;const n=await At();if(Bn(n)){this.wasm=n;const e=this.gridWidth*this.gridHeight;this.gridPtr=this.wasm.alloc_u8(e),this.outPathPtr=this.wasm.alloc_u32(this.outCapacity*2),this.syncGridToWasm()}else this.wasm=null;return this.ready=!0,!0}syncGridToWasm(){this.syncToWasm(this.grid)}syncToWasm(n){this.wasm&&new Uint8Array(this.wasm.memory.buffer,this.gridPtr,this.gridWidth*this.gridHeight).set(n)}cellIndex(n,e){return e*this.gridWidth+n}isGridCell(n,e){return n>=0&&n<this.gridWidth&&e>=0&&e<this.gridHeight}setCell(n,e,r){if(!this.isGridCell(n,e))return;const o=this.cellIndex(n,e);this.grid[o]=r,this.costGrid[o]=r,r===0&&(this.hasBlockedData=!0)}worldToGrid(n,e){const{cellSize:r,worldMinX:o,worldMinZ:i}=this.config,s=Math.floor((n-o)/r),a=Math.floor((e-i)/r);return[Math.max(0,Math.min(s,this.gridWidth-1)),Math.max(0,Math.min(a,this.gridHeight-1))]}gridToWorld(n,e,r){const{cellSize:o,worldMinX:i,worldMinZ:s}=this.config;return[i+(n+.5)*o,r??this.heightGrid[this.cellIndex(n,e)]??0,s+(e+.5)*o]}resolveAgentFootprint(n={}){const e=Math.max(0,n.clearance??0),r=Math.max(0,n.agentRadius??0)+e,o=Math.max(r,Math.max(0,n.agentWidth??0)*.5+e),i=Math.max(r,Math.max(0,n.agentDepth??0)*.5+e);return{halfWidth:o,halfDepth:i,hasClearance:o>te||i>te}}getCellBounds(n,e){const{cellSize:r,worldMinX:o,worldMinZ:i}=this.config,s=o+n*r,a=i+e*r;return{minX:s,maxX:s+r,minZ:a,maxZ:a+r}}footprintOverlapsBlockedCell(n,e,r){const[o,,i]=this.gridToWorld(n,e,0),s=o-r.halfWidth,a=o+r.halfWidth,c=i-r.halfDepth,l=i+r.halfDepth,h=Math.ceil(r.halfWidth/this.config.cellSize),u=Math.ceil(r.halfDepth/this.config.cellSize);for(let d=e-u;d<=e+u;d+=1)for(let f=n-h;f<=n+h;f+=1){if(!this.isGridCell(f,d))continue;const m=this.cellIndex(f,d);if(this.grid[m]!==0)continue;const b=this.getCellBounds(f,d),y=a>b.minX+te&&s<b.maxX-te,M=l>b.minZ+te&&c<b.maxZ-te;if(y&&M)return!0}return!1}canOccupyCell(n,e,r){if(!this.isGridCell(n,e))return!1;const o=this.cellIndex(n,e);return this.grid[o]===0?!1:r.hasClearance?!this.footprintOverlapsBlockedCell(n,e,r):!0}createTraversalGrid(n){if(!n.hasClearance)return this.grid;const e=new Uint8Array(this.grid.length);for(let r=0;r<this.gridHeight;r+=1)for(let o=0;o<this.gridWidth;o+=1){const i=this.cellIndex(o,r);e[i]=this.canOccupyCell(o,r,n)?1:0}return e}createTraversalCostGrid(n){if(n===this.grid)return this.costGrid;const e=new Uint8Array(this.costGrid.length);for(let r=0;r<e.length;r+=1)e[r]=n[r]===0?0:this.costGrid[r]??1;return e}setBlocked(n,e,r,o){this.setRegion(n,e,r,o,0)}setWalkable(n,e,r,o){this.setRegion(n,e,r,o,1)}reset(n=1){const e=Math.max(0,Math.min(255,Math.round(n)));this.grid.fill(e===0?0:1),this.costGrid.fill(e),this.heightGrid.fill(0),this.hasHeightData=!1,this.hasBlockedData=e===0}setRegion(n,e,r,o,i){const{cellSize:s,worldMinX:a,worldMinZ:c}=this.config,l=r/2,h=o/2,u=Math.floor((n-l-a)/s),d=Math.floor((e-h-c)/s),f=Math.ceil((n+l-a)/s),m=Math.ceil((e+h-c)/s);for(let b=d;b<m;b++)for(let y=u;y<f;y++)this.setCell(y,b,i)}setCost(n,e,r){const[o,i]=this.worldToGrid(n,e),s=this.cellIndex(o,i),a=Math.max(0,Math.min(255,Math.round(r)));this.costGrid[s]=a,a===0&&(this.grid[s]=0,this.hasBlockedData=!0)}setHeight(n,e,r){const[o,i]=this.worldToGrid(n,e);this.heightGrid[this.cellIndex(o,i)]=r,r!==0&&(this.hasHeightData=!0)}setHeightRegion(n,e,r,o,i){this.setHeightSampler(n,e,r,o,()=>i)}setHeightSampler(n,e,r,o,i){const{cellSize:s,worldMinX:a,worldMinZ:c}=this.config,l=r/2,h=o/2,u=Math.floor((n-l-a)/s),d=Math.floor((e-h-c)/s),f=Math.ceil((n+l-a)/s),m=Math.ceil((e+h-c)/s);for(let b=d;b<m;b++)for(let y=u;y<f;y++){if(!this.isGridCell(y,b))continue;const[M,,v]=this.gridToWorld(y,b,0),R=i(M,v);this.heightGrid[this.cellIndex(y,b)]=R,R!==0&&(this.hasHeightData=!0)}}sampleHeight(n,e){const[r,o]=this.worldToGrid(n,e);return this.heightGrid[this.cellIndex(r,o)]??0}hasNavigationConstraints(){return this.hasBlockedData||this.hasHeightData}setBlockedFromBox(n){const e=new I.Vector3,r=new I.Vector3;n.getCenter(e),n.getSize(r),this.setBlocked(e.x,e.z,r.x,r.z)}findPath(n,e,r,o,i,s=!1){if(!this.ready)return[];const a=typeof i=="object"&&i!==null?i:{...i!==void 0?{y:i}:{},weighted:s},c=this.resolveAgentFootprint(a),l=a.y,h=a.weighted??s,[u,d]=this.worldToGrid(n,e),[f,m]=this.worldToGrid(r,o),b=this.createTraversalGrid(c),y=h?this.createTraversalCostGrid(b):this.costGrid;return this.wasm&&!this.hasHeightData?this.findPathWasm(u,d,f,m,l,h,b,y):this.findPathJS(u,d,f,m,l,h,b,y)}findPathWasm(n,e,r,o,i,s,a,c){const l=this.wasm;if(s&&typeof l.astar_find_path_weighted!="function")return this.findPathJS(n,e,r,o,i,!0,a,c);s?this.syncToWasm(c):this.syncToWasm(a);const u=(s?l.astar_find_path_weighted:l.astar_find_path)(this.gridPtr,this.gridWidth,this.gridHeight,n,e,r,o,this.outPathPtr,this.outCapacity);if(u===0)return[];const d=new Uint32Array(l.memory.buffer,this.outPathPtr,u*2),f=[];for(let m=0;m<u;m++){const b=d[m*2],y=d[m*2+1];b===void 0||y===void 0||f.push(this.gridToWorld(b,y,i))}return f}findPathJS(n,e,r,o,i,s,a=this.grid,c=this.costGrid){const l=this.gridWidth,h=this.gridHeight,u=a,d=l*h,f=this.cellIndex(n,e),m=this.cellIndex(r,o);if(u[f]===0||u[m]===0)return[];if(f===m)return[this.gridToWorld(r,o,i)];const b=new Uint32Array(d).fill(4294967295),y=new Uint32Array(d).fill(4294967295),M=new Uint8Array(d);b[f]=0;const v=[{f:this.octileH(n,e,r,o),idx:f}];for(;v.length>0;){let G=0;for(let C=1;C<v.length;C++){const $=v[C],D=v[G];$&&D&&$.f<D.f&&(G=C)}const W=v[G],S=v[v.length-1];if(!W||!S)break;v[G]=S,v.pop();const w=W.idx;if(w===m)break;if(M[w])continue;M[w]=1;const T=w%l,A=w/l|0,x=b[w];if(x!==void 0)for(const[C,$,D]of Fn){const j=T+C,H=A+$;if(j<0||H<0||j>=l||H>=h)continue;const O=this.cellIndex(j,H);if(M[O]||u[O]===0||!this.canStepBetween(w,O)||C!==0&&$!==0&&(u[A*l+j]===0||u[H*l+T]===0||!this.canStepBetween(w,this.cellIndex(j,A))||!this.canStepBetween(w,this.cellIndex(T,H))))continue;const sn=s?Math.max(1,c[O]??1):1,ve=x+D*sn,at=b[O];at!==void 0&&ve<at&&(b[O]=ve,y[O]=w,v.push({f:ve+this.octileH(j,H,r,o),idx:O}))}}if(b[m]===4294967295)return[];const R=[];let _=m;for(;_!==f;){R.push(this.gridToWorld(_%l,_/l|0,i));const G=y[_];if(G===void 0)return[];if(_=G,_===4294967295)return[]}return R.push(this.gridToWorld(n,e,i)),R.reverse(),R}octileH(n,e,r,o){const i=Math.abs(n-r),s=Math.abs(e-o);return Math.max(i,s)*10+Math.min(i,s)*4}canStepBetween(n,e){return this.hasHeightData?Math.abs((this.heightGrid[e]??0)-(this.heightGrid[n]??0))<=this.config.maxStepHeight:!0}hasLineOfSight(n,e,r,o,i={}){return this.canTraverseSegment(n,e,r,o,i)}canTraverseSegment(n,e,r,o,i={}){const s=r-n,a=o-e,c=Math.sqrt(s*s+a*a),l=Math.max(1,Math.ceil(c/(this.config.cellSize*.5))),h=this.resolveAgentFootprint(i);let u=-1,d=-1;for(let f=0;f<=l;f++){const m=f/l,[b,y]=this.worldToGrid(n+s*m,e+a*m);if(b===u&&y===d)continue;const M=this.cellIndex(b,y);if(!(i.ignoreStart&&f===0)&&!this.canOccupyCell(b,y,h)||u!==-1&&d!==-1&&!this.canStepBetween(this.cellIndex(u,d),M))return!1;u=b,d=y}return!0}smoothPath(n,e,r,o={}){if(n.length===0)return[];const i=e??n[0],s=r??n[n.length-1];if(!i||!s)return[];const a=[i],c=e?1:0,l=r?n.length-1:n.length;for(let d=c;d<l;d++){const f=n[d];f&&a.push(f)}a.push(s);const h=[];let u=0;for(h.push(a[u]);u<a.length-1;){let d=a.length-1;const f=a[u];for(;d>u+1&&!this.hasLineOfSight(f[0],f[2],a[d][0],a[d][2],o);)d-=1;h.push(a[d]),u=d}return h}simplifyPath(n){if(n.length<=2)return n;const e=n[0];if(!e)return[];const r=[e];for(let i=1;i<n.length-1;i++){const s=r[r.length-1],a=n[i],c=n[i+1];if(!s||!a||!c)continue;const l=a[0]-s[0],h=a[2]-s[2],u=c[0]-a[0],d=c[2]-a[2];Math.abs(l*d-h*u)>.01&&r.push(a)}const o=n[n.length-1];return o&&r.push(o),r}isWalkable(n,e,r={}){const[o,i]=this.worldToGrid(n,e);return this.canOccupyCell(o,i,this.resolveAgentFootprint(r))}getGridDimensions(){return{width:this.gridWidth,height:this.gridHeight,cellSize:this.config.cellSize}}dispose(){this.wasm&&(this.gridPtr&&this.wasm.dealloc_u8(this.gridPtr,this.gridWidth*this.gridHeight),this.outPathPtr&&this.wasm.dealloc_u32(this.outPathPtr,this.outCapacity*2)),B.instance=null,this.ready=!1}}var Kn=Object.defineProperty,jn=Object.getOwnPropertyDescriptor,re=(t,n,e,r)=>{for(var o=jn(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&Kn(n,e,o),o};class J{refs;constructor(){this.refs={activeState:{position:new I.Vector3,quaternion:new I.Quaternion,euler:new I.Euler,velocity:new I.Vector3,direction:new I.Vector3,dir:new I.Vector3,angular:new I.Vector3,isGround:!1},gameStates:{canRide:!1,isRiding:!1,isJumping:!1,isFalling:!1,isMoving:!1,isRunning:!1,isNotMoving:!0,isNotRunning:!0,isOnTheGround:!0,nearbyRideable:void 0,currentRideable:void 0,rideableDistance:void 0}}}getActiveState(){return this.refs.activeState}getGameStates(){return this.refs.gameStates}getState(){return this.refs}updateActiveState(n){Object.assign(this.refs.activeState,n)}updateGameStates(n){Object.assign(this.refs.gameStates,n)}resetActiveState(){this.refs.activeState.position.set(0,0,0),this.refs.activeState.quaternion.identity(),this.refs.activeState.euler.set(0,0,0),this.refs.activeState.velocity.set(0,0,0),this.refs.activeState.direction.set(0,0,0),this.refs.activeState.dir.set(0,0,0),this.refs.activeState.angular.set(0,0,0),this.refs.activeState.isGround=!1}resetGameStates(){this.refs.gameStates.canRide=!1,this.refs.gameStates.isRiding=!1,this.refs.gameStates.isJumping=!1,this.refs.gameStates.isFalling=!1,this.refs.gameStates.isMoving=!1,this.refs.gameStates.isRunning=!1,this.refs.gameStates.isNotMoving=!0,this.refs.gameStates.isNotRunning=!0,this.refs.gameStates.isOnTheGround=!0,this.refs.gameStates.nearbyRideable=void 0,this.refs.gameStates.currentRideable=void 0,this.refs.gameStates.rideableDistance=void 0}reset(){this.resetActiveState(),this.resetGameStates()}dispose(){this.reset()}}re([p.Profile()],J.prototype,"updateActiveState");re([p.Profile()],J.prototype,"updateGameStates");re([p.HandleError()],J.prototype,"resetActiveState");re([p.HandleError()],J.prototype,"resetGameStates");re([p.HandleError()],J.prototype,"reset");re([p.HandleError()],J.prototype,"dispose");var Hn=Object.defineProperty,Un=Object.getOwnPropertyDescriptor,Rt=(t,n,e,r)=>{for(var o=Un(n,e),i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=s(n,e,o)||o);return o&&Hn(n,e,o),o};class Ue{stateManager;inputBackend;config;scratchImpulse={x:0,y:0,z:0};scratchLinvel={x:0,y:0,z:0};navigation=B.getInstance();constructor(n,e,r=p.createInteractionInputAdapter()){this.stateManager=e??new J,this.inputBackend=r,this.config=n}applyImpulse(n,e,r){if(!n.current)return;const{modeType:o}=e;switch(o){case"character":this.applyCharacterImpulse(n,e,r);break;case"vehicle":this.applyVehicleImpulse(n,e,r);break;case"airplane":this.applyAirplaneImpulse(n,e);break;default:this.applyCharacterImpulse(n,e,r)}}applyCharacterImpulse(n,e,r){const{gameStates:{isMoving:o,isRunning:i,isOnTheGround:s,isJumping:a},activeState:c}=e,{walkSpeed:l=10,runSpeed:h=20,jumpSpeed:u=15}=this.config;if(a&&s){const d=n.current.linvel();this.scratchLinvel.x=d.x,this.scratchLinvel.y=u,this.scratchLinvel.z=d.z,n.current.setLinvel(this.scratchLinvel,!0),this.stateManager.updateGameStates({isOnTheGround:!1})}if(o){const d=i?h:l,f=c.dir,m=c.velocity,b=n.current.mass(),y=-f.x*d,M=-f.z*d;if(!this.canMoveForward(n.current,y,M,r)){this.scratchLinvel.x=0,this.scratchLinvel.y=n.current.linvel().y,this.scratchLinvel.z=0,n.current.setLinvel(this.scratchLinvel,!0);return}const v=y-m.x,R=M-m.z;this.scratchImpulse.x=v*b,this.scratchImpulse.y=0,this.scratchImpulse.z=R*b,n.current.applyImpulse(this.scratchImpulse,!0)}}canMoveForward(n,e,r,o){if(!this.navigation.hasNavigationConstraints())return!0;const i=Math.sqrt(e*e+r*r);if(i<=1e-4||typeof n.translation!="function")return!0;const s=n.translation(),{cellSize:a}=this.navigation.getGridDimensions(),c=Math.max(.45,Math.min(a*.75,i*.08)),l=e/i,h=r/i,u=s.x+l*c,d=s.z+h*c,f=Math.max(0,o?.colliderSize?.radius??this.config.navigationAgentRadius??.35);return this.navigation.canTraverseSegment(s.x,s.z,u,d,{agentRadius:f,ignoreStart:!0})}applyVehicleImpulse(n,e,r){const{activeState:o}=e,i=this.getKeyboard(r),{maxSpeed:s=10,accelRatio:a=2}=this.config,c=i.shift&&!e.mouse.isLookAround,l=n.current.linvel(),h=Math.max(0,s);if(l.x*l.x+l.z*l.z<h*h){const d=n.current.mass(),f=c?a:1;this.scratchImpulse.x=o.dir.x*d*f,this.scratchImpulse.y=0,this.scratchImpulse.z=o.dir.z*d*f,n.current.applyImpulse(this.scratchImpulse,!0)}}applyAirplaneImpulse(n,e){const{activeState:r}=e,{maxSpeed:o=20}=this.config,i=n.current.linvel(),s=Math.max(0,o);if(i.x*i.x+i.y*i.y+i.z*i.z<s*s){const c=n.current.mass();this.scratchImpulse.x=r.direction.x*c,this.scratchImpulse.y=r.direction.y*c,this.scratchImpulse.z=r.direction.z*c,n.current.applyImpulse(this.scratchImpulse,!0)}}getKeyboard(n){return n?.inputRef?.current?.keyboard??this.inputBackend.getKeyboard()}}Rt([p.Profile()],Ue.prototype,"applyImpulse");Rt([p.Profile()],Ue.prototype,"applyCharacterImpulse");var $n=Object.defineProperty,Vn=Object.getOwnPropertyDescriptor,P=(t,n,e,r)=>{for(var o=r>1?void 0:r?Vn(n,e):n,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=(r?s(n,e,o):s(o))||o);return r&&o&&$n(n,e,o),o};const qn={isJumping:!1,isMoving:!1,isRunning:!1,lastUpdate:0},Zn={forcesApplied:0,dampingChanges:0,frameTime:0},ft=.75,gt=.25,Jn=.025,Yn=3,Xn=1.2,Qn=.35,er=-.25;function tr(t){const n=t;return n.calcProp!==void 0&&n.physicsState!==void 0}let z=class extends p.AbstractSystem{directionComponent;impulseComponent;gravityComponent;animationController=new xt;forceComponents=[];keyStateCache=new Map;isCurrentlyJumping=!1;lastJumpPressed=!1;lastMovingState=!1;lastRunningState=!1;lastPositionY=0;groundStableCount=0;lastGroundedY=null;tempQuaternion=new I.Quaternion;tempEuler=new I.Euler;tempVector=new I.Vector3;jumpScratch=new I.Vector3;config;constructor(t,n={},e){super(qn,Zn,n),this.config=t,this.directionComponent=new ne(this.config),this.impulseComponent=new Ue(this.config,e),this.gravityComponent=new se(this.config)}updateConfig(t){this.config={...this.config,...t}}performUpdate(t){this.calculate(t.calcProp,t.physicsState)}createUpdateArgs(t){if(tr(t))return t;throw new Error("PhysicsSystem requires updateWithArgs().")}updateMetrics(t){this.state.isJumping=this.isCurrentlyJumping,this.state.isMoving=this.lastMovingState,this.state.isRunning=this.lastRunningState}updateWithArgs(t){this.performUpdateWithArgs(t)}calculate(t,n){if(!n||!t.rigidBodyRef.current)return;if(t.worldContext?.cameraOption?.focus===!0){this.freezeInput(n),this.checkGround(t,n),this.animationController.update(n.gameStates);return}const r=t.rigidBodyRef.current.linvel();n.activeState.velocity.set(r.x,r.y,r.z),this.checkAllStates(t,n),this.animationController.update(n.gameStates);const{modeType:i="character"}=n;switch(i){case"character":this.calculateCharacter(t,n);break;case"vehicle":this.calculateVehicle(t,n);break;case"airplane":this.calculateAirplane(t,n);break}}checkAllStates(t,n){const e=t.rigidBodyRef.current?.handle??-1;this.checkGround(t,n),this.checkMoving(n),this.checkRiding(e,n)}checkGround(t,n){const{rigidBodyRef:e}=t,r=n.gameStates,o=n.activeState;if(!e.current){r.isOnTheGround=!1,r.isFalling=!0;return}const i=e.current.linvel(),s=e.current.translation(),a=Math.abs(i.y),c=Math.abs(s.y-this.lastPositionY),l=i.y>.02,h=s.y<=ft,u=this.lastGroundedY!==null&&Math.abs(s.y-this.lastGroundedY)<=ft,d=h||u,f=r.isJumping||n.keyboard.space,m=u&&!f&&a<Xn&&c<Qn;!l&&d&&a<gt&&c<Jn?this.groundStableCount=Math.min(this.groundStableCount+1,5):this.groundStableCount=0,this.lastPositionY=s.y;const y=d&&!l&&a<gt||m||this.groundStableCount>=Yn,M=!y&&i.y<er;y&&(this.lastGroundedY=s.y,this.resetJumpState(n)),r.isOnTheGround=y,r.isFalling=M,this.copyVector3(o.position,s),this.copyVector3(o.velocity,i)}checkMoving(t){const n=t.gameStates,e=t.keyboard,r=t.mouse,{shift:o,space:i,forward:s,backward:a,leftward:c,rightward:l}=e,h=s||a||c||l,u=h||r.isActive,d=h&&o&&!r.isLookAround||r.isActive&&r.shouldRun;t.modeType==="character"&&i&&!this.lastJumpPressed&&n.isOnTheGround&&!this.isCurrentlyJumping&&(this.isCurrentlyJumping=!0,n.isJumping=!0),this.lastJumpPressed=i,this.updateStateIfChanged("isMoving",u,()=>{this.lastMovingState=u,n.isMoving=u,n.isNotMoving=!u}),this.updateStateIfChanged("isRunning",d,()=>{this.lastRunningState=d,n.isRunning=d,n.isNotRunning=!d})}checkRiding(t=-1,n){const e=n.keyboard;this.keyStateCache.has(t)||this.keyStateCache.set(t,{lastKeyE:!1,lastKeyR:!1});const r=this.keyStateCache.get(t),o=e.keyE,i=n.gameStates;o&&!r.lastKeyE&&(i.canRide&&!i.isRiding||i.isRiding),r.lastKeyE=o,r.lastKeyR=!1}freezeInput(t){const n=t.gameStates;n.isMoving=!1,n.isNotMoving=!0,n.isRunning=!1,n.isNotRunning=!0,n.isJumping=!1,this.isCurrentlyJumping=!1,this.lastJumpPressed=t.keyboard.space,this.lastMovingState=!1,this.lastRunningState=!1}resetJumpState(t){this.isCurrentlyJumping=!1,t.gameStates.isJumping=!1}calculateCharacter(t,n){const{rigidBodyRef:e,innerGroupRef:r}=t;if(this.directionComponent.updateDirection(n,"normal",t),this.impulseComponent.applyImpulse(e,n,t),this.gravityComponent.applyGravity(e,n),this.updateForces(e,n.delta??0),e?.current){const o=n.gameStates,i=n.activeState,{isJumping:s,isFalling:a,isNotMoving:c}=o,{linearDamping:l=.9,airDamping:h=.2,stopDamping:u=1}=this.config;e.current.setLinearDamping(s||a?h:c?l*u:l),e.current.setEnabledRotations(!1,!1,!1,!1),r?.current&&r.current.quaternion.setFromEuler(i.euler)}}calculateVehicle(t,n){const{rigidBodyRef:e,innerGroupRef:r}=t;if(this.directionComponent.updateDirection(n,"normal",t),this.impulseComponent.applyImpulse(e,n,t),this.applyDamping(e,n),this.updateForces(e,n.delta??0),e?.current){const o=n.activeState;e.current.setEnabledRotations(!1,!0,!1,!1),this.tempEuler.set(0,o.euler.y,0),this.tempQuaternion.setFromEuler(this.tempEuler),e.current.setRotation(this.tempQuaternion,!0),r?.current&&(r.current.rotation.y=0)}}calculateAirplane(t,n){const{rigidBodyRef:e,innerGroupRef:r}=t;if(this.directionComponent.updateDirection(n,"normal",t,r),this.impulseComponent.applyImpulse(e,n,t),this.gravityComponent.applyGravity(e,n),this.applyDamping(e,n),this.updateForces(e,n.delta??0),e?.current){e.current.setEnabledRotations(!1,!1,!1,!1);const o=n.activeState;this.tempEuler.set(0,o.euler.y,0),this.tempQuaternion.setFromEuler(this.tempEuler),e.current.setRotation(this.tempQuaternion,!0)}}applyDamping(t,n){if(!t?.current||!n)return;const{modeType:e,keyboard:r}=n,{space:o}=r;if(e==="vehicle"){const{linearDamping:i=.9,brakeRatio:s=i}=this.config,a=o?s:i;t.current.setLinearDamping(a)}else if(e==="airplane"){const{linearDamping:i=.2}=this.config;t.current.setLinearDamping(i)}}addForceComponent(t){this.forceComponents.push(t)}applyForce(t,n){if(!n)return;const e=n.linvel();this.tempVector.set(e.x+t.x,e.y+t.y,e.z+t.z),n.setLinvel(this.tempVector,!0)}calculateMovement(t,n,e,r,o){const i=(o??new I.Vector3).set(0,0,0),s=t.shift&&!t.isLookAround,a=s?2:1,c=(n.maxSpeed??10)*a;return t.forward&&(i.z+=1),t.backward&&(i.z-=1),t.leftward&&(i.x+=1),t.rightward&&(i.x-=1),i.length()>0&&(i.normalize().multiplyScalar(c*r),e.isRunning=s,e.isNotRunning=!s),i}calculateJump(t,n,e){return e?(n.isJumping=!0,this.jumpScratch.set(0,t.jumpSpeed??0,0)):this.jumpScratch.set(0,0,0)}updateForces(t,n){if(!t.current||this.forceComponents.length===0)return;const e=t.current;for(let r=0,o=this.forceComponents.length;r<o;r++){const i=this.forceComponents[r];i&&i.update(e,n)}}copyVector3(t,n){t.set(n.x,n.y,n.z)}onDispose(){this.directionComponent.dispose(),this.forceComponents=[],this.keyStateCache.clear(),this.groundStableCount=0,this.lastGroundedY=null,this.lastJumpPressed=!1}updateStateIfChanged(t,n,e){return this.state[t]!==n?(this.state[t]=n,e?.(),!0):!1}};P([p.HandleError()],z.prototype,"updateConfig",1);P([p.Profile()],z.prototype,"performUpdate",1);P([p.Profile()],z.prototype,"updateMetrics",1);P([p.HandleError(),p.Profile()],z.prototype,"calculate",1);P([p.Profile()],z.prototype,"checkAllStates",1);P([p.Profile()],z.prototype,"checkGround",1);P([p.Profile()],z.prototype,"checkMoving",1);P([p.HandleError(),p.Profile()],z.prototype,"calculateCharacter",1);P([p.HandleError(),p.Profile()],z.prototype,"calculateVehicle",1);P([p.HandleError(),p.Profile()],z.prototype,"calculateAirplane",1);P([p.Profile()],z.prototype,"applyDamping",1);P([p.HandleError()],z.prototype,"applyForce",1);P([p.HandleError(),p.Profile()],z.prototype,"calculateMovement",1);P([p.HandleError()],z.prototype,"calculateJump",1);P([p.Profile()],z.prototype,"updateForces",1);z=P([p.ManageRuntime({autoStart:!1})],z);var nr=Object.defineProperty,rr=Object.getOwnPropertyDescriptor,$e=(t,n,e,r)=>{for(var o=r>1?void 0:r?rr(n,e):n,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=(r?s(n,e,o):s(o))||o);return r&&o&&nr(n,e,o),o};let ee=class extends Le{buildEngine(t,n,e){const r=new z(n,{},e);return{system:r,dispose:()=>r.dispose()}}executeCommand(t,n,e){switch(n.type){case"updateConfig":t.system.updateConfig(n.data);break}}createSnapshot(t){return{...t.system.getState(),metrics:{...t.system.getMetrics()}}}updateEntity(t,n){const e=this.getEngine(t);e&&(e.system.updateWithArgs(n),this.notifyListeners(t))}};$e([Fe()],ee.prototype,"executeCommand",1);$e([me(),be(16)],ee.prototype,"createSnapshot",1);ee=$e([Be("physics"),Mt()],ee);const Ve=g.createContext({runtime:null,revision:0});function or({runtime:t=null,revision:n=0,children:e}){return N.jsx(Ve.Provider,{value:{runtime:t,revision:n},children:e})}function qe(){return g.useContext(Ve).runtime}function Ze(){return g.useContext(Ve).revision}let Ee=null;const _e=new Set;function kt(){return Ee||(Ee=new J),Ee}const pt=t=>(_e.add(t),()=>{_e.delete(t)}),ce=()=>{_e.forEach(t=>t())};function Je(){const t=g.useRef(null);t.current||(t.current=kt());const n=g.useSyncExternalStore(pt,()=>t.current.getActiveState(),()=>t.current.getActiveState()),e=g.useSyncExternalStore(pt,()=>t.current.getGameStates(),()=>t.current.getGameStates()),r=g.useCallback(a=>{t.current?.updateActiveState(a),ce()},[]),o=g.useCallback(a=>{t.current?.updateGameStates(a),ce()},[]),i=g.useCallback(()=>{t.current?.resetActiveState(),ce()},[]),s=g.useCallback(()=>{t.current?.resetGameStates(),ce()},[]);return g.useEffect(()=>()=>{t.current=null},[]),{activeState:n,gameStates:e,updateActiveState:r,updateGameStates:o,resetActiveState:i,resetGameStates:s}}const ir=[{type:"none",labelEn:"None",labelKo:"없음"},{type:"snow",labelEn:"Snow",labelKo:"눈"},{type:"rain",labelEn:"Rain",labelKo:"비"},{type:"storm",labelEn:"Storm",labelKo:"폭풍"},{type:"wind",labelEn:"Wind",labelKo:"바람"}],sr=[{type:"solid",labelEn:"Solid",labelKo:"일반벽"},{type:"window",labelEn:"Window",labelKo:"창문벽"},{type:"door",labelEn:"Door",labelKo:"문벽"},{type:"arch",labelEn:"Arch",labelKo:"아치"},{type:"half",labelEn:"Half Wall",labelKo:"반벽"},{type:"railing",labelEn:"Railing",labelKo:"난간"},{type:"glass",labelEn:"Glass Wall",labelKo:"유리벽"}],fe={flag:{label:"Flag",defaultWidth:1.5,defaultHeight:1,windStrength:1,poleType:"side"},banner:{label:"Banner",defaultWidth:1.2,defaultHeight:3,windStrength:.3,poleType:"top"},panel:{label:"Panel",defaultWidth:2,defaultHeight:1.5,windStrength:0,poleType:"frame"},placard:{label:"Placard",defaultWidth:4,defaultHeight:1,windStrength:.5,poleType:"both"}},Pe=[{id:"brick-house",categoryId:"exterior-walls",categoryName:"Exterior Walls",labelEn:"Brick House",labelKo:"벽돌집",exteriorColor:"#8b4a34",interiorColor:"#eadfce",sideColor:"#6f3b2c",defaultKind:"solid",roughness:.82},{id:"plaster-house",categoryId:"interior-walls",categoryName:"Interior Walls",labelEn:"Plaster Room",labelKo:"석고 내벽",exteriorColor:"#d7d0bf",interiorColor:"#f2eadc",sideColor:"#b6ac9a",defaultKind:"solid",roughness:.86},{id:"wood-cabin",categoryId:"exterior-walls",categoryName:"Exterior Walls",labelEn:"Wood Cabin",labelKo:"나무집",exteriorColor:"#8a5a36",interiorColor:"#c8a174",sideColor:"#6f4529",defaultKind:"solid",roughness:.74},{id:"stone-cottage",categoryId:"exterior-walls",categoryName:"Exterior Walls",labelEn:"Stone Cottage",labelKo:"돌집",exteriorColor:"#79766d",interiorColor:"#d5ceb9",sideColor:"#56544e",defaultKind:"solid",roughness:.9},{id:"modern-concrete",categoryId:"exterior-walls",categoryName:"Exterior Walls",labelEn:"Modern Concrete",labelKo:"모던 콘크리트",exteriorColor:"#858a8c",interiorColor:"#e8e8e3",sideColor:"#64686a",defaultKind:"solid",roughness:.8},{id:"shopfront",categoryId:"special-walls",categoryName:"Special Walls",labelEn:"Shopfront",labelKo:"상점 전면",exteriorColor:"#4b5563",interiorColor:"#e5dcc9",sideColor:"#374151",defaultKind:"window",roughness:.48,metalness:.08},{id:"glass-office",categoryId:"special-walls",categoryName:"Special Walls",labelEn:"Glass Office",labelKo:"유리 오피스",exteriorColor:"#8ecae6",interiorColor:"#d8f2ff",sideColor:"#4b6470",defaultKind:"glass",roughness:.16,metalness:.03},{id:"garden-fence",categoryId:"special-walls",categoryName:"Special Walls",labelEn:"Garden Fence",labelKo:"정원 울타리",exteriorColor:"#7a5a3a",interiorColor:"#9b7653",sideColor:"#5d422c",defaultKind:"railing",roughness:.78}],De=[{id:"oak-planks",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Oak Planks",labelKo:"오크 판자",color:"#8b5a2b",roughness:.58},{id:"pine-planks",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Pine Planks",labelKo:"소나무 판자",color:"#b88952",roughness:.62},{id:"walnut-planks",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Walnut Planks",labelKo:"월넛 판자",color:"#4b2f22",roughness:.64},{id:"bamboo-floor",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Bamboo Floor",labelKo:"대나무 바닥",color:"#c2a15b",roughness:.55},{id:"herringbone-wood",categoryId:"wood-floors",categoryName:"Wood Floors",labelEn:"Herringbone",labelKo:"헤링본 목재",color:"#9a6a3a",roughness:.5},{id:"white-marble",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"White Marble",labelKo:"화이트 대리석",color:"#f0f0ec",roughness:.22,metalness:.05},{id:"black-marble",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Black Marble",labelKo:"블랙 대리석",color:"#25252a",roughness:.2,metalness:.08},{id:"granite",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Granite",labelKo:"화강암",color:"#77746f",roughness:.42,metalness:.03},{id:"slate",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Slate",labelKo:"슬레이트",color:"#3f4a4d",roughness:.62},{id:"basalt",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Basalt",labelKo:"현무암",color:"#2c2f31",roughness:.72},{id:"limestone",categoryId:"stone-floors",categoryName:"Stone Floors",labelEn:"Limestone",labelKo:"석회암",color:"#c8bea8",roughness:.66},{id:"cobblestone",categoryId:"masonry-floors",categoryName:"Masonry Floors",labelEn:"Cobblestone",labelKo:"자갈석",color:"#6f6b60",roughness:.82},{id:"brick-pavers",categoryId:"masonry-floors",categoryName:"Masonry Floors",labelEn:"Brick Pavers",labelKo:"벽돌 포장",color:"#9a4f37",roughness:.78},{id:"terracotta",categoryId:"masonry-floors",categoryName:"Masonry Floors",labelEn:"Terracotta",labelKo:"테라코타",color:"#b85f3c",roughness:.76},{id:"concrete",categoryId:"urban-floors",categoryName:"Urban Floors",labelEn:"Concrete",labelKo:"콘크리트",color:"#8b8d8c",roughness:.86},{id:"asphalt",categoryId:"urban-floors",categoryName:"Urban Floors",labelEn:"Asphalt",labelKo:"아스팔트",color:"#242629",roughness:.9},{id:"ceramic-white",categoryId:"decor-floors",categoryName:"Decor Floors",labelEn:"White Ceramic",labelKo:"화이트 세라믹",color:"#f7f7f2",roughness:.28},{id:"checker-tile",categoryId:"decor-floors",categoryName:"Decor Floors",labelEn:"Checker Tile",labelKo:"체커 타일",color:"#d9d9d2",roughness:.32},{id:"mosaic-blue",categoryId:"decor-floors",categoryName:"Decor Floors",labelEn:"Blue Mosaic",labelKo:"블루 모자이크",color:"#3b78a0",roughness:.34},{id:"metal-grate",categoryId:"special-floors",categoryName:"Special Floors",labelEn:"Metal Grate",labelKo:"금속 그레이팅",color:"#5c6268",material:"METAL",roughness:.38,metalness:.75},{id:"glass-tile",categoryId:"special-floors",categoryName:"Special Floors",labelEn:"Glass Tile",labelKo:"유리 타일",color:"#9ed8ff",material:"GLASS",roughness:.08,opacity:.42,transparent:!0},{id:"sandstone",categoryId:"natural-floors",categoryName:"Natural Floors",labelEn:"Sandstone",labelKo:"사암",color:"#c9ab75",roughness:.88},{id:"snow-ice",categoryId:"natural-floors",categoryName:"Natural Floors",labelEn:"Snow Ice",labelKo:"눈 얼음",color:"#eef5ff",roughness:.5,metalness:.02},{id:"moss-stone",categoryId:"natural-floors",categoryName:"Natural Floors",labelEn:"Moss Stone",labelKo:"이끼 낀 돌",color:"#60704a",roughness:.84}],ar=[{type:"sakura",labelEn:"Sakura",labelKo:"벚꽃나무"},{type:"oak",labelEn:"Oak",labelKo:"참나무"},{type:"pine",labelEn:"Pine",labelKo:"소나무"},{type:"maple",labelEn:"Maple",labelKo:"단풍나무"},{type:"birch",labelEn:"Birch",labelKo:"자작나무"},{type:"willow",labelEn:"Willow",labelKo:"버드나무"},{type:"cypress",labelEn:"Cypress",labelKo:"사이프러스"},{type:"dead",labelEn:"Dead Tree",labelKo:"고목"}],zt={sakura:{primaryColor:"#f7bfd2",secondaryColor:"#5e3d30"},oak:{primaryColor:"#4f8f3a",secondaryColor:"#6b4a2a"},pine:{primaryColor:"#2f6f45",secondaryColor:"#5b3b24"},maple:{primaryColor:"#d05a2d",secondaryColor:"#654126"},birch:{primaryColor:"#87b95a",secondaryColor:"#e8e1cf"},willow:{primaryColor:"#7fae55",secondaryColor:"#6a5635"},cypress:{primaryColor:"#315f3a",secondaryColor:"#59402d"},dead:{primaryColor:"#8b7a61",secondaryColor:"#4b392c"}},lr=[{type:"none",labelEn:"None",labelKo:"없음"},{type:"water",labelEn:"Water",labelKo:"물"},{type:"grass",labelEn:"Grass",labelKo:"잔디"},{type:"sand",labelEn:"Sand",labelKo:"모래"},{type:"snowfield",labelEn:"Snowfield",labelKo:"눈밭"}],cr=[{type:"box",labelEn:"Box",labelKo:"박스"},{type:"stairs",labelEn:"Stairs",labelKo:"계단"},{type:"round",labelEn:"Round",labelKo:"원형"},{type:"ramp",labelEn:"Ramp",labelKo:"경사"}],_t=[{type:"tree",labelEn:"Tree",labelKo:"나무"},{type:"flag",labelEn:"Flag",labelKo:"깃발"},{type:"fire",labelEn:"Fire",labelKo:"불"},{type:"billboard",labelEn:"Billboard",labelKo:"간판"}],ur=[{type:"none",labelEn:"None",labelKo:"없음"},..._t,{type:"model",labelEn:"Model",labelKo:"기본 기물"}],dr=Object.keys(fe).map(t=>({style:t,meta:fe[t]}));function hr(t,n,e){const r=g.useRef(!1);g.useEffect(()=>{if(!t||!e||r.current)return;const o=Ke();return o.registerAnimations(n,t),r.current=!0,()=>{r.current&&(o.unregisterAnimations(n),r.current=!1)}},[t,n,e])}function fr(t,n,e,r){const o=g.useRef(!1),i=g.useRef(null);return i.current||(i.current=p.BridgeFactory.getOrCreate("motion")),g.useEffect(()=>{if(!(!n.current||o.current||!i.current))return i.current.register(t,e==="vehicle"||e==="airplane"?e:"character",n.current),o.current=!0,()=>{i.current?.unregister(t),o.current=!1}},[n,e,t]),{executeMotionCommand:c=>{o.current&&r&&i.current&&i.current.execute(t,c)},getMotionSnapshot:()=>o.current&&r&&i.current?i.current.snapshot(t):null}}const gr=(t,n)=>{["forward","backward","leftward","rightward","shift","space","keyE","keyR"].forEach(r=>{t.keyboard[r]!==n.keyboard[r]&&(t.keyboard[r]=n.keyboard[r])}),t.mouse.target.equals(n.mouse.target)||t.mouse.target.copy(n.mouse.target),t.mouse.angle!==n.mouse.angle&&(t.mouse.angle=n.mouse.angle),t.mouse.isActive!==n.mouse.isActive&&(t.mouse.isActive=n.mouse.isActive),t.mouse.shouldRun!==n.mouse.shouldRun&&(t.mouse.shouldRun=n.mouse.shouldRun)},pr="gaesup.motions",Ye="physics.bridge",Xe=p.DEFAULT_INTERACTION_INPUT_EXTENSION_ID,Qe="motions.runtime",et="motions:teleport";function Pt(t,n={}){const e=n.physicsExtensionId??Ye,r=n.inputExtensionId??Xe,o=t.systems.require(e),i=t.input.require(r);return{physicsBridge:o.createBridge(),inputAdapter:i.createAdapter(),events:t.events,extensionIds:{physics:e,input:r}}}function mr(t,n){t.events.emit(et,n)}function Dt(t={}){const n=t.id??pr,e=t.physicsExtensionId??Ye,r=t.inputExtensionId??Xe,o=t.runtimeServiceId??Qe,i=t.createPhysicsBridge??(()=>new ee),s=t.createInputAdapter??p.createInteractionInputAdapter;return{id:n,name:"GaeSup Motions",version:"0.1.0",runtime:"client",capabilities:["motions","physics","input"],setup(a){a.systems.register(e,{Bridge:ee,createBridge:i},n),a.input.register(r,{createAdapter:s},n),a.services.register(o,{create:c=>Pt(a,{physicsExtensionId:e,inputExtensionId:r,...c})},n),a.events.emit("motions:ready",{pluginId:n,physicsExtensionId:e,inputExtensionId:r,runtimeServiceId:o})},dispose(a){a.systems.remove(e),a.input.remove(r),a.services.remove(o)}}}const yr=Dt();function br(t,n,e,r,o){const i=t.mode?.type||"character",s=n.getActiveState(),a=n.getGameStates(),c=t.automation;return{activeState:s,gameStates:a,keyboard:{...e.keyboard},mouse:{target:o.copy(e.mouse.target),angle:e.mouse.angle,isActive:e.mouse.isActive,shouldRun:e.mouse.shouldRun,...e.mouse.isLookAround!==void 0?{isLookAround:e.mouse.isLookAround}:{}},automationOption:c,modeType:i,delta:r}}function wr(t){if(!t||typeof t!="object")return!1;const e=t.position;return!!e&&typeof e.x=="number"&&typeof e.y=="number"&&typeof e.z=="number"}function Sr(t){if(!("detail"in t))return null;const n=t.detail;return wr(n)?n:null}function Ir(t){if(typeof window>"u"||typeof document>"u")return()=>{};const n=e=>{const r=Sr(e);r&&t(r)};return window.addEventListener("gaesup:teleport",n),document.addEventListener("teleport-request",n),()=>{window.removeEventListener("gaesup:teleport",n),document.removeEventListener("teleport-request",n)}}let mt=null;function vr(){return{physicsBridge:new ee,inputAdapter:p.createInteractionInputAdapter(),events:new ln.InMemoryEventBus,extensionIds:{physics:"fallback.physics.bridge",input:"fallback.interaction.input"}}}function Mr(){return mt??=vr(),mt}function Cr(t){const{enabled:n=!0,allowLegacyFallback:e=!0}=t,r=qe(),o=Ze(),i=g.useMemo(()=>t.motionsRuntime||!r?null:r.getService(Qe)?.create()??null,[r,o,t.motionsRuntime]),s=g.useMemo(()=>t.motionsRuntime||i||!e?null:Mr(),[e,i,t.motionsRuntime]),a=t.motionsRuntime??i??s,c=g.useRef(null),l=g.useRef(new I.Vector3),h=g.useRef(null),u=g.useRef(null),d=g.useRef(!1),f=p.useGaesupStore(w=>w.physics),m=g.useRef(f),b=g.useRef(null);b.current??=p.createInteractionInputAdapter();const y=a?.inputAdapter??b.current,M=g.useRef(y);M.current=y;const v=n&&!!a,R=g.useRef({keyboard:y.getKeyboard(),mouse:y.getMouse()}),_=g.useRef(null),G=g.useRef(w=>{M.current.updateKeyboard(w)}),W=g.useRef(w=>{M.current.updateMouse(w)});g.useEffect(()=>{d.current||(m.current=f)},[f]),g.useEffect(()=>{if(h.current=kt(),!n){d.current&&(u.current?.unregister("global-physics"),d.current=!1),u.current=null,c.current=null;return}const w=a?.physicsBridge;if(!w){d.current&&(u.current?.unregister("global-physics"),d.current=!1),u.current=null,c.current=null;return}return u.current=w,d.current||(u.current.register("global-physics",m.current,h.current),d.current=!0),()=>{d.current&&u.current&&(u.current.unregister("global-physics"),d.current=!1),c.current=null}},[n,a?.physicsBridge]),g.useEffect(()=>{n&&d.current&&u.current&&u.current.execute("global-physics",{type:"updateConfig",data:f})},[n,f]),g.useEffect(()=>{const w=C=>{t.rigidBodyRef?.current&&C&&(t.rigidBodyRef.current.setTranslation({x:C.x,y:C.y,z:C.z},!0),t.rigidBodyRef.current.setLinvel({x:0,y:0,z:0},!0),t.rigidBodyRef.current.setAngvel({x:0,y:0,z:0},!0))},T=C=>{w(C.position)},A=a?.events.on(et,T),x=a===s?Ir(T):void 0;return()=>{A?.(),x?.()}},[s,a,a?.events,t.rigidBodyRef]);const S=g.useCallback((w,T)=>{if(!n||!u.current||!h.current)return;const A=R.current;A.keyboard=y.getKeyboard(),A.mouse=y.getMouse();let x=c.current;if(x)gr(x,A),x.activeState=h.current.getActiveState(),x.gameStates=h.current.getGameStates(),x.delta=T;else{const $=p.useGaesupStore.getState();if(x=br($,h.current,A,T,l.current),c.current=x,x.activeState){const{activeState:D}=x;t.rigidBodyRef.current.lockRotations(!1,!0),D.euler.set(0,0,0),t.rigidBodyRef.current.setTranslation({x:D.position.x,y:D.position.y+5,z:D.position.z},!0)}}let C=_.current;C?(C.rigidBodyRef=t.rigidBodyRef,C.state=w,C.delta=T,C.worldContext=p.useGaesupStore.getState(),t.colliderSize?C.colliderSize=t.colliderSize:delete C.colliderSize,t.innerGroupRef&&(C.innerGroupRef=t.innerGroupRef)):(C={rigidBodyRef:t.rigidBodyRef,state:w,delta:T,worldContext:p.useGaesupStore.getState(),dispatch:()=>{},inputRef:R,setKeyboardInput:G.current,setMouseInput:W.current,...t.colliderSize?{colliderSize:t.colliderSize}:{},...t.innerGroupRef?{innerGroupRef:t.innerGroupRef}:{}},_.current=C),u.current.updateEntity("global-physics",{deltaTime:T,calcProp:C,physicsState:x})},[n,y,t]);return We.useFrame((w,T)=>{v&&S(w,T)}),{isReady:v,bridge:u.current}}function Nt(t){return t?t.plugins.context.input.get(p.DEFAULT_INTERACTION_INPUT_EXTENSION_ID)?.createAdapter()??null:null}function tt(){const t=qe(),n=Ze(),e=g.useRef(null);return e.current??=p.createInteractionInputAdapter(),g.useMemo(()=>Nt(t)??e.current,[t,n])}function Ot(){const t=tt(),[n,e]=g.useState(()=>({keyboard:t.getKeyboard(),mouse:t.getMouse()}));g.useEffect(()=>(e({keyboard:t.getKeyboard(),mouse:t.getMouse()}),t.subscribe?.(s=>{e({keyboard:s.keyboard,mouse:s.mouse})})),[t]);const r=g.useCallback(s=>{t.updateKeyboard(s),t.subscribe||e({keyboard:t.getKeyboard(),mouse:t.getMouse()})},[t]),o=g.useCallback(s=>{t.updateMouse(s),t.subscribe||e({keyboard:t.getKeyboard(),mouse:t.getMouse()})},[t]),i=g.useCallback(s=>{o(s)},[o]);return{keyboard:n.keyboard,mouse:n.mouse,updateKeyboard:r,updateMouse:o,dispatchInput:i}}function Wt(t){const{playAnimation:n,currentType:e,currentAnimation:r}=Tt(),{keyboard:o,mouse:i}=Ot(),s=p.useGaesupStore(u=>u.automation),{gameStates:a}=Je(),c=g.useMemo(()=>{const u=o?.forward||o?.backward||o?.leftward||o?.rightward,d=i?.isActive||!1;return{isMoving:u||d,isRunning:!!o?.shift&&!i?.isLookAround&&u||i?.shouldRun&&d&&s?.queue.isRunning}},[o.forward,o.backward,o.leftward,o.rightward,o.shift,i.isActive,i.shouldRun,i.isLookAround,s]),l=g.useMemo(()=>a?.isJumping?"jump":a?.isFalling?"fall":a?.isRiding?"ride":c.isRunning?"run":c.isMoving?"walk":"idle",[a.isJumping,a.isFalling,a.isRiding,c.isRunning,c.isMoving]),h=g.useMemo(()=>["idle","walk","run","jump","fall","ride","land"],[]);g.useEffect(()=>{if(!t)return;l!=="idle"?l!==r&&n(e,l):h.includes(r)&&r!=="idle"&&n(e,"idle")},[t,l,r,n,e,h])}function Tr(t){const{onIntersectionEnter:n,onIntersectionExit:e,onCollisionEnter:r,userData:o}=t,i=(l,...h)=>{if(typeof l=="function")try{l(...h)}catch{}},s=g.useCallback(l=>{i(n,l),i(o?.onNear,l,o)},[n,o]),a=g.useCallback(l=>{i(e,l),i(o?.onFar,l,o),i(o?.onLeave,l,o)},[e,o]),c=g.useCallback(l=>{i(r,l),i(o?.onNear,l,o)},[r,o]);return{handleIntersectionEnter:s,handleIntersectionExit:a,handleCollisionEnter:c}}function xr(t){const{onReady:n,onFrame:e,onAnimate:r,onDestroy:o,actions:i}=t;g.useEffect(()=>(n&&n(),o),[o,n]),g.useEffect(()=>{let s;const a=()=>{e&&e(),r&&i&&r(),s=requestAnimationFrame(a)};if(!(!e&&!(r&&i)))return s=requestAnimationFrame(a),()=>{cancelAnimationFrame(s)}},[e,r,i])}function Er(t){const{id:n,rigidBodyRef:e,isActive:r,actions:o,outerGroupRef:i,innerGroupRef:s,colliderRef:a,groundRay:c,colliderSize:l}=t,h=g.useRef(n||`entity-${Date.now()}-${Math.random()}`).current,u=p.useGaesupStore(v=>v.mode),d=u?.type??"character",f=r===!0;hr(o,d,f),Wt(f&&d==="character");const{executeMotionCommand:m,getMotionSnapshot:b}=fr(h,e,d,f),y={rigidBodyRef:e,enabled:f,...i?{outerGroupRef:i}:{},...s?{innerGroupRef:s}:{},...a?{colliderRef:a}:{},...c?{groundRay:c}:{},...l?{colliderSize:l}:{}};Cr(y);const M=Tr(t);return xr(t),{executeMotionCommand:m,getMotionSnapshot:b,mode:u,...M}}function Lt({nodes:t,color:n,skeleton:e,url:r,excludeNodeNames:o}){const{processedNodes:i,ownedMaterials:s}=g.useMemo(()=>{const a=[],c=o&&o.length>0?new Set(o):null,l=d=>{const f=d.clone();return a.push(f),n&&"color"in f&&f.color instanceof I.Color&&f.color.set(n),f},h=d=>n?Array.isArray(d)?d.map(f=>l(f)):l(d):d;return{processedNodes:Object.keys(t).map((d,f)=>{if(c&&c.has(d))return null;const m=t[d];return m instanceof I.SkinnedMesh?{type:"skinnedMesh",material:h(m.material),geometry:m.geometry,skeleton:e||m.skeleton,key:`${r}-${d}-${f}`}:m instanceof I.Mesh?{type:"mesh",material:h(m.material),geometry:m.geometry,key:`${r}-${d}-${f}`}:null}).filter(d=>d!==null),ownedMaterials:a}},[t,n,e,r,o]);return g.useEffect(()=>()=>{for(const a of s)a.dispose()},[s]),N.jsx(N.Fragment,{children:i.map(a=>a?a.type==="skinnedMesh"?N.jsx("skinnedMesh",{castShadow:!0,receiveShadow:!0,material:a.material,geometry:a.geometry,skeleton:a.skeleton,frustumCulled:!1,dispose:null},a.key):N.jsx("mesh",{castShadow:!0,receiveShadow:!0,material:a.material,geometry:a.geometry,dispose:null},a.key):null)})}function Gr({url:t,isActive:n,color:e,skeleton:r}){const{scene:o}=he.useGLTF(t),i=g.useMemo(()=>vt.SkeletonUtils.clone(o),[o]),{nodes:s}=We.useGraph(i);return Wt(n),N.jsx("group",{children:N.jsx(Lt,{nodes:s,url:t,...e?{color:e}:{},...r?{skeleton:r}:{}})})}const Ft=g.forwardRef((t,n)=>{const e=typeof t.modelYawOffset=="number"?t.modelYawOffset:t.componentType==="character"?Math.PI:0,r=t.baseColor??t.parts?.[0]?.color;return N.jsxs("group",{receiveShadow:!0,castShadow:!0,ref:n,userData:{intangible:!0},children:[t.children,N.jsxs("group",{"rotation-y":e,...t.modelScale!==void 0?{scale:t.modelScale}:{},children:[t.objectNode&&t.animationRef&&N.jsx("primitive",{object:t.objectNode,visible:!1,receiveShadow:!0,castShadow:!0,ref:t.animationRef}),N.jsx(Lt,{nodes:t.nodes,skeleton:t.skeleton,url:t.url||"",...r?{color:r}:{},...t.excludeBaseNodes&&t.excludeBaseNodes.length>0?{excludeNodeNames:t.excludeBaseNodes}:{}}),t.modelChildren]})]})});Ft.displayName="InnerGroupRef";const ge=new Map;function Ar(t){const n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=Math.round((r+1)/t*255);const e=new I.DataTexture(n,t,1,I.RedFormat);return e.minFilter=I.NearestFilter,e.magFilter=I.NearestFilter,e.generateMipmaps=!1,e.needsUpdate=!0,e}function nt(t=3){const n=Math.max(2,Math.min(8,Math.floor(t))),e=ge.get(n);if(e)return e;const r=Ar(n);return ge.set(n,r),r}function Rr(t={}){return new I.MeshToonMaterial({color:t.color??"#ffffff",vertexColors:t.vertexColors??!1,transparent:t.transparent??!1,opacity:t.opacity??1,map:t.map??null,alphaMap:t.alphaMap??null,emissive:t.emissive??"#000000",emissiveIntensity:t.emissiveIntensity??0,gradientMap:nt(t.steps??3),side:t.side??I.FrontSide,depthWrite:t.depthWrite??!0})}let Bt=!1;function kr(t){Bt=t}function Kt(){return Bt}function zr(){for(const t of ge.values())t.dispose();ge.clear()}const yt=new WeakSet;function jt(t,n=4){if(!t||yt.has(t))return;yt.add(t);const e=nt(n);t.traverse(r=>{const o=r;if(!o.isMesh)return;const s=(Array.isArray(o.material)?o.material:[o.material]).map(a=>{if(!a||a.isMeshToonMaterial)return a;const l=a;return new I.MeshToonMaterial({color:l.color&&l.color.clone()||new I.Color("#ffffff"),map:l.map??null,normalMap:l.normalMap??null,alphaMap:l.alphaMap??null,transparent:a.transparent,opacity:a.opacity,side:a.side,emissive:l.emissive&&l.emissive.clone()||new I.Color(0),emissiveMap:l.emissiveMap??null,emissiveIntensity:l.emissiveIntensity??1,gradientMap:e})});o.material=Array.isArray(o.material)?s:s[0]})}const pe=new Map,de=new I.Vector3(1,1,1),_r=new I.Box3,Pr=t=>{const n=pe.get(t);n&&--n.refCount<=0&&pe.delete(t)},Dr=t=>{try{return _r.setFromObject(t).getSize(p.getPooledVector())}catch{return de.clone()}},Nr=({url:t})=>{const n=p.useGaesupStore(u=>u.sizes),e=p.useGaesupStore(u=>u.setSizes),r=t??"data:application/json,{}",o=!!t?.trim(),i=he.useGLTF(r),s=g.useRef(!1),a=g.useCallback(()=>o&&i.scene?Dr(i.scene):de.clone(),[i.scene,o]);g.useEffect(()=>{if(!t||!o)return;const u=pe.get(t);return u?u.refCount++:pe.set(t,{gltf:i,refCount:1,size:a()}),i.scene&&Kt()&&jt(i.scene),()=>Pr(t)},[t,o,i,a]),g.useEffect(()=>{if(s.current||!o||!t||!i.scene||n[t])return;s.current=!0;const u=a();e(d=>({...d,[t]:u}))},[t,i.scene,n,e,a,o]);const c=g.useMemo(()=>o&&t?n[t]??de:de,[n,t,o]),l=g.useCallback((u,d)=>{if(!o)return;const f=d??t;f&&Promise.resolve().then(()=>e(m=>({...m,[f]:u})))},[t,e,o]),h=g.useCallback(u=>{if(!o)return null;const d=u??t;return d?n[d]??null:null},[t,n,o]);return{gltf:i,size:c,setSize:l,getSize:h}},Or=()=>{const t=p.useGaesupStore(r=>r.sizes),n=g.useCallback(r=>{if(!r)return{};const o={};return Object.entries(r).forEach(([i,s])=>{typeof s=="string"?o[i]=t[s]??null:o[i]=null}),o},[t]),e=g.useCallback(r=>{},[]);return{getSizesByUrls:n,preloadSizes:e}},Wr="data:application/json,"+encodeURIComponent(JSON.stringify({asset:{version:"2.0"},scenes:[{nodes:[]}],nodes:[]}));function Lr(t,n){if(t[n])return n;const e=Object.keys(t),r=n.toLowerCase();return e.find(o=>o.toLowerCase()===r)??e.find(o=>o.toLowerCase().includes(r))??(e.length===1?e[0]:void 0)}const Ht=g.forwardRef((t,n)=>{const e=g.useRef(null);g.useImperativeHandle(n,()=>e.current);const{size:r}=Nr({url:t.url||""}),o=t.url?.trim()?t.url:Wr,{scene:i,animations:s}=he.useGLTF(o),{actions:a,ref:c}=he.useAnimations(s),l=g.useRef(void 0),{handleIntersectionEnter:h,handleIntersectionExit:u,handleCollisionEnter:d}=Er({rigidBodyRef:e,...t.name?{id:t.name}:{},...t.userData?{userData:t.userData}:{},...t.onIntersectionEnter?{onIntersectionEnter:t.onIntersectionEnter}:{},...t.onIntersectionExit?{onIntersectionExit:t.onIntersectionExit}:{},...t.onCollisionEnter?{onCollisionEnter:t.onCollisionEnter}:{},...t.onReady?{onReady:t.onReady}:{},...t.onFrame?{onFrame:t.onFrame}:{},...t.onAnimate?{onAnimate:t.onAnimate}:{},...t.onDestroy||t.onDestory?{onDestroy:t.onDestroy??t.onDestory}:{},actions:a,isActive:t.isActive,...t.outerGroupRef?{outerGroupRef:t.outerGroupRef}:{},...t.innerGroupRef?{innerGroupRef:t.innerGroupRef}:{},...t.colliderRef?{colliderRef:t.colliderRef}:{},...t.groundRay?{groundRay:t.groundRay}:{},...t.colliderSize?{colliderSize:t.colliderSize}:{}}),f=g.useMemo(()=>vt.SkeletonUtils.clone(i),[i]),m=g.useMemo(()=>{let S=null;return f.traverse(w=>{w instanceof I.SkinnedMesh&&(S=w.skeleton)}),S},[f]),b=g.useMemo(()=>!t.parts||t.parts.length===0?null:t.parts.map(({url:S,color:w},T)=>S?g.createElement(Gr,{url:S,isActive:!0,componentType:t.componentType,...t.currentAnimation?{currentAnimation:t.currentAnimation}:{},...w?{color:w}:{},key:`${t.componentType}-${S}-${w||"default"}-${T}`,...m?{skeleton:m}:{}}):null).filter(Boolean),[t.parts,t.componentType,t.currentAnimation,m]),{nodes:y}=We.useGraph(f),M=Object.values(y).find(S=>S.type==="Object3D"),v=t.rotation instanceof I.Euler?t.rotation.y:0,R=t.outerGroupRef?{ref:t.outerGroupRef}:{},_=t.innerGroupRef?{ref:t.innerGroupRef}:{},G=t.isActive?{canSleep:!1,ccd:!0}:{canSleep:!0,ccd:!1},W=g.useMemo(()=>{if(t.colliderSize){const x=Math.max(.05,t.colliderSize.radius),C=Math.max(.05,t.colliderSize.height*.5-x);return{halfHeight:C,radius:x,y:C+x}}const S=Math.max(r.x,.1),w=Math.max(r.z,.1),T=t.componentType==="character"?Math.max(.18,Math.min(S,w)*.35):Math.max(.2,S*1.2),A=Math.max(.05,r.y*.5-T);return{halfHeight:A,radius:T,y:A+T}},[t.colliderSize,t.componentType,r.x,r.y,r.z]);return g.useEffect(()=>{if(!t.currentAnimation)return;const S=Lr(a,t.currentAnimation);if(!S||l.current===S)return;const w=l.current?a[l.current]:void 0,T=a[S];w?.fadeOut(.2),T?.reset().fadeIn(.2).play(),l.current=S},[a,t.currentAnimation]),N.jsx("group",{...R,userData:{intangible:!0},children:N.jsxs(Me.RigidBody,{...G,colliders:!1,ref:e,...t.name?{name:t.name}:{},position:t.position,rotation:Me.euler().set(0,v,0),userData:t.userData,type:t.rigidbodyType||(t.isActive?"dynamic":"fixed"),...t.sensor!==void 0?{sensor:t.sensor}:{},onIntersectionEnter:h,onIntersectionExit:u,onCollisionEnter:d,...t.rigidBodyProps,children:[!t.isNotColliding&&N.jsx(Me.CapsuleCollider,{ref:t.colliderRef,args:[W.halfHeight,W.radius],position:[0,W.y,0]}),N.jsx(Ft,{animationRef:c,nodes:y,..._,isActive:t.isActive,componentType:t.componentType,...M?{objectNode:M}:{},...t.modelYawOffset!==void 0?{modelYawOffset:t.modelYawOffset}:{},...t.scale!==void 0?{modelScale:t.scale}:{},...t.isRiderOn!==void 0?{isRiderOn:t.isRiderOn}:{},...t.enableRiding!==void 0?{enableRiding:t.enableRiding}:{},...t.ridingUrl?{ridingUrl:t.ridingUrl}:{},...t.offset?{offset:t.offset}:{},...t.baseColor?{baseColor:t.baseColor}:{},...t.excludeBaseNodes?{excludeBaseNodes:t.excludeBaseNodes}:{},...t.parts?{parts:t.parts}:{},...b?{modelChildren:b}:{},children:t.children})]})})});Ht.displayName="PhysicsEntity";const Fr=Object.freeze({cellSize:4,heightStep:1,origin:"center"});class Br{id;spec;constructor(n={}){this.id=n.id??"square",this.spec={...Fr,...n.spec}}toWorld(n){const e=this.spec.origin==="center"?0:this.spec.cellSize/2;return{x:n.x*this.spec.cellSize+e,y:n.level*this.spec.heightStep,z:n.z*this.spec.cellSize+e}}fromWorld(n){const e=this.spec.origin==="center"?0:this.spec.cellSize/2;return{x:Math.round((n.x-e)/this.spec.cellSize),z:Math.round((n.z-e)/this.spec.cellSize),level:Math.round(n.y/this.spec.heightStep)}}getNeighbors(n){return[{x:n.x,z:n.z-1,level:n.level},{x:n.x+1,z:n.z,level:n.level},{x:n.x,z:n.z+1,level:n.level},{x:n.x-1,z:n.z,level:n.level}]}equals(n,e){return n.x===e.x&&n.z===e.z&&n.level===e.level}key(n){return`${n.x}:${n.z}:${n.level}`}edgeToWorld(n){const e=this.toWorld(n),r=this.spec.cellSize/2;switch(n.side){case"north":return{...e,z:e.z-r};case"east":return{...e,x:e.x+r};case"south":return{...e,z:e.z+r};case"west":return{...e,x:e.x-r}}}edgeKey(n){return`${n.x}:${n.z}:${n.level}:${n.side}`}cornerToWorld(n){const e=this.toWorld(n),r=this.spec.cellSize/2;return{x:e.x-r,y:e.y,z:e.z-r}}cornerKey(n){return`${n.x}:${n.z}:${n.level}`}}const Ut=()=>({ok:!0}),Kr=(t,n)=>{const e={ok:!1,reason:t};return e.ruleId=n,e};function jr(){return{id:"no-overlap",test(t){const n=t.request.footprint?.coords??[t.request.coord];for(const e of n)if(t.getOccupants(e).filter(o=>o.id!==t.request.subject.id).length>0)return Kr("Target coordinate is already occupied.","no-overlap");return Ut()}}}class bt extends Error{result;constructor(n){super(n.reason??"Placement request was rejected."),this.name="PlacementRejectedError",this.result=n}}class wt extends Error{constructor(n){super(`Placement entry "${n}" does not exist.`),this.name="MissingPlacementEntryError"}}class Hr{adapter;rules;entries=new Map;occupied=new Map;constructor(n){this.adapter=n.adapter,this.rules=[...n.rules??[]]}use(n){this.rules.push(n)}canPlace(n){const e={request:n,entries:this.entries,adapter:this.adapter,getOccupants:r=>this.getOccupants(r)};for(const r of this.rules){const o=r.test(e);if(!o.ok)return o.ruleId===void 0?{...o,ruleId:r.id}:o}return Ut()}place(n){const e=this.canPlace(n);if(!e.ok)throw new bt(e);const r=this.toEntry(n),o=this.entries.get(r.id);o&&this.unindex(o),this.entries.set(r.id,r),this.index(r);const i={type:"place",after:r};return o&&(i.before=o),i}remove(n){const e=this.entries.get(n);if(!e)throw new wt(n);return this.unindex(e),this.entries.delete(n),{type:"remove",before:e}}move(n,e,r){const o=this.requireEntry(n),i={subject:o.subject,coord:e,footprint:r??this.moveFootprint(o,e)};o.rotation!==void 0&&(i.rotation=o.rotation);const s=this.canPlace(i);if(!s.ok)throw new bt(s);const a=this.toEntry(i);return this.unindex(o),this.entries.set(n,a),this.index(a),{type:"move",before:o,after:a}}rotate(n,e){const r=this.requireEntry(n),o={...r,rotation:e};return this.entries.set(n,o),{type:"rotate",before:r,after:o}}get(n){return this.entries.get(n)}list(){return Array.from(this.entries.values())}getOccupants(n){const e=this.occupied.get(this.adapter.key(n));return e?Array.from(e).map(r=>this.entries.get(r)).filter(r=>r!==void 0):[]}clear(){this.entries.clear(),this.occupied.clear()}toEntry(n){const e={id:n.subject.id,subject:n.subject,coord:n.coord,footprint:n.footprint??{kind:"cell",coords:[n.coord]}};return n.rotation!==void 0&&(e.rotation=n.rotation),e}requireEntry(n){const e=this.entries.get(n);if(!e)throw new wt(n);return e}index(n){for(const e of this.getFootprintCoords(n)){const r=this.adapter.key(e),o=this.occupied.get(r)??new Set;o.add(n.id),this.occupied.set(r,o)}}unindex(n){for(const e of this.getFootprintCoords(n)){const r=this.adapter.key(e),o=this.occupied.get(r);o&&(o.delete(n.id),o.size===0&&this.occupied.delete(r))}}getFootprintCoords(n){return n.footprint.coords??[n.coord]}moveFootprint(n,e){const r=n.footprint.coords;return r!==void 0&&r.length===1&&r[0]!==void 0&&this.adapter.equals(r[0],n.coord)?{...n.footprint,coords:[e]}:n.footprint}}function Ur(t){return new Hr(t)}const E=Object.freeze({GRID_CELL_SIZE:4,SNAP_GRID_SIZE:4,HEIGHT_STEP:1,TILE_MULTIPLIERS:Object.freeze({SMALL:1,MEDIUM:2,LARGE:3,HUGE:4}),WALL_SIZES:Object.freeze({WIDTH:4,HEIGHT:4,THICKNESS:.5,MIN_LENGTH:.5,MAX_LENGTH:10}),GRID_DIVISIONS:25,DEFAULT_GRID_SIZE:100}),L=new Br({id:"building-square",spec:{cellSize:E.GRID_CELL_SIZE,heightStep:E.HEIGHT_STEP,origin:"center"}}),Ne=t=>t>=0?t*2:-t*2-1,rt=(t,n)=>{const e=Ne(t),r=Ne(n),o=e+r;return o*(o+1)/2+r},$t=t=>({...t,x:Math.round(t.x/E.SNAP_GRID_SIZE)*E.SNAP_GRID_SIZE,z:Math.round(t.z/E.SNAP_GRID_SIZE)*E.SNAP_GRID_SIZE}),Vt=t=>L.fromWorld(t),qt=t=>L.toWorld(t),Zt=t=>{const n=Math.PI/2;return(Math.round(t/n)%4+4)%4*n},Jt=t=>{switch(t){case"north":case"south":return Math.PI/2;case"east":case"west":return 0}},$r=t=>{const n=L.edgeToWorld(t),e=Jt(t.side),r=E.WALL_SIZES.WIDTH/2,o={x:Math.sin(e),z:Math.cos(e)};return{position:{x:V(n.x-o.x*r),y:n.y,z:V(n.z-o.z*r)},rotationY:e}},ie=(t,n)=>{const e=Zt(n),r=E.WALL_SIZES.WIDTH/2,o=E.GRID_CELL_SIZE,i={x:t.x+Math.sin(e)*r,y:t.y,z:t.z+Math.cos(e)*r};if(e===0||e===Math.PI){const s=Math.trunc(i.x/o),a=i.x-s*o;return{x:V(s),z:V(Math.round(i.z/o)),level:V(Math.round(i.y/E.HEIGHT_STEP)),side:a>=0?"east":"west"}}return{x:V(Math.round(i.x/o)),z:V(Math.trunc(i.z/o)),level:V(Math.round(i.y/E.HEIGHT_STEP)),side:i.z-Math.trunc(i.z/o)*o>=0?"south":"north"}},Vr=t=>L.edgeKey(t),V=t=>Object.is(t,-0)||Math.abs(t)<1e-10?0:Number(t.toFixed(10)),F=t=>Vt(t),qr=t=>qt(t),X=(t,n=1)=>{const e=Math.max(1,Math.round(n)),r=-Math.floor(e/2),o=[];for(let i=0;i<e;i++)for(let s=0;s<e;s++)o.push({x:t.x+r+i,z:t.z+r+s,level:t.level});return o},Zr=t=>t.map(n=>L.key(n)),Yt=(t,n={})=>{const e=Math.max(1,Math.round(n.x??1)),r=Math.max(1,Math.round(n.y??1)),o=Math.max(1,Math.round(n.z??1)),i=[];for(let s=0;s<e;s++)for(let a=0;a<r;a++)for(let c=0;c<o;c++)i.push({x:t.x+s,z:t.z+c,level:t.level+a});return i},Xt={id:"building-placement",toWorld(t){return t.kind==="cell"?L.toWorld(t.cell):L.edgeToWorld(t.edge)},fromWorld(t){return{kind:"cell",cell:L.fromWorld(t)}},getNeighbors(t){return t.kind==="edge"?[t]:L.getNeighbors(t.cell).map(n=>({kind:"cell",cell:n}))},equals(t,n){return this.key(t)===this.key(n)},key(t){return t.kind==="cell"?`cell:${L.key(t.cell)}`:`edge:${L.edgeKey(t.edge)}`}},ot=t=>{const n=t.cell??F(t.position),e=t.footprint??X(n,t.size||1),r={id:t.id,subject:{id:t.id,type:"tile",tags:["building","tile",`shape:${t.shape??"box"}`,...t.objectType&&t.objectType!=="none"?[`terrain:${t.objectType}`]:[]]},coord:{kind:"cell",cell:n},footprint:{kind:"cell",coords:e.map(o=>({kind:"cell",cell:o}))}};return t.rotation!==void 0&&(r.rotation=t.rotation),r},Qt=t=>{const n=t.edge??ie(t.position,t.rotation.y);return{id:t.id,subject:{id:t.id,type:"wall",tags:["building","wall",`side:${n.side}`]},coord:{kind:"edge",edge:n},footprint:{kind:"edge",coords:[{kind:"edge",edge:n}]},rotation:t.rotation.y}},it=t=>{const n=t.cell??F(t.position),e=Yt(n,t.size);return{id:t.id,subject:{id:t.id,type:"block",tags:["building","block",...t.materialId?[`material:${t.materialId}`]:[],...t.tags??[]]},coord:{kind:"cell",cell:n},footprint:{kind:"volume",coords:e.map(r=>({kind:"cell",cell:r}))}}},en=t=>t.tiles.map(ot),tn=t=>t.walls.map(Qt),nn=(t,n,e=[])=>[...Array.from(t).flatMap(en),...Array.from(n).flatMap(tn),...Array.from(e).map(it)],Oe=(t=[],n=[],e={})=>{const r=[...e.includeNoOverlapRule===!1?[]:[jr()],...e.rules??[]],o=Ur({adapter:Xt,rules:[]});for(const i of nn(t,n,e.blocks??[])){const s={subject:i.subject,coord:i.coord,footprint:i.footprint};o.place(i.rotation===void 0?s:{...s,rotation:i.rotation})}for(const i of r)o.use(i);return o},Y=(t,n,e)=>{const r=n.get(e);if(r){for(const o of r){const i=t.get(o);i&&(i.delete(e),i.size===0&&t.delete(o))}n.delete(e)}},q=(t,n,e,r,o,i,s,a)=>{const c=Math.floor(r/a),l=Math.floor(o/a),h=Math.floor(i/a),u=Math.floor(s/a),d=[];for(let f=c;f<=l;f++)for(let m=h;m<=u;m++){const b=rt(f,m);let y=t.get(b);y||(y=new Set,t.set(b,y)),y.add(e),d.push(b)}n.set(e,d)},Ie=(t,n,e,r,o,i)=>{const s=Math.floor(n/i),a=Math.floor(e/i),c=Math.floor(r/i),l=Math.floor(o/i),h=new Set;for(let u=s;u<=a;u++)for(let d=c;d<=l;d++){const f=t.get(rt(u,d));if(f)for(const m of f)h.add(m)}return h},Q=t=>E.GRID_CELL_SIZE*t/2,st=(t,n)=>Math.abs(t.x-n.x)<t.halfSize+n.halfSize-.1&&Math.abs(t.z-n.z)<t.halfSize+n.halfSize-.1,Jr=(t,n,e,r)=>{const o=E.GRID_CELL_SIZE,i=Q(r),s=E.HEIGHT_STEP*.5,a=Ie(t,e.x-i,e.x+i,e.z-i,e.z+i,o);for(const c of a){const l=n.get(c);if(l&&st({x:e.x,z:e.z,halfSize:i},l)&&Math.abs((l.y??0)-e.y)<s)return!0}return!1},rn=(t,n,e,r)=>{const o=E.GRID_CELL_SIZE,i=Q(r),s=Ie(t,e.x-i,e.x+i,e.z-i,e.z+i,o);let a=0;for(const c of s){const l=n.get(c);if(!l||!st({x:e.x,z:e.z,halfSize:i},l))continue;const h=(l.y??0)+E.HEIGHT_STEP;h>a&&(a=h)}return a},on=(t,n,e,r)=>{const i=Ie(t,e.x-.5,e.x+.5,e.z-.5,e.z+.5,1);for(const s of i){const a=n.get(s);if(a&&Math.abs(a.x-e.x)<.5&&Math.abs(a.z-e.z)<.5&&Math.abs(a.rotY-r)<.1)return!0}return!1};function Yr(t){return{version:1,meshes:Array.from(t.meshes.values(),oe),wallGroups:Array.from(t.wallGroups.values(),oe),tileGroups:Array.from(t.tileGroups.values(),oe),blocks:t.blocks.map(oe),objects:t.objects.map(oe),showSnow:t.showSnow,showFog:t.showFog,fogColor:t.fogColor,weatherEffect:t.weatherEffect}}function oe(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}function Xr(t,n){if(n){t.meshes.clear(),t.wallGroups.clear(),t.tileGroups.clear(),t.tileIndex.clear(),t.tileCells.clear(),t.tileMeta.clear(),t.wallIndex.clear(),t.wallCells.clear(),t.wallMeta.clear();for(const e of n.meshes??[])t.meshes.set(e.id,{...e});Qr(t,n.tileGroups??[]),eo(t,n.wallGroups??[]),t.blocks=(n.blocks??[]).map(e=>({...e,cell:e.cell??F(e.position)})),t.objects=(n.objects??[]).map(e=>({...e})),t.showSnow=n.showSnow??!1,t.showFog=n.showFog??!1,t.fogColor=n.fogColor??"#cfd8e3",t.weatherEffect=n.weatherEffect??(t.showSnow?"snow":"none"),t.initialized=!0}}function Qr(t,n){const e=E.GRID_CELL_SIZE;for(const r of n){const o=r.tiles.map(i=>{const s=i.cell??F(i.position),a={...i,cell:s,footprint:i.footprint??X(s,i.size||1)},c=Q(a.size||1);return t.tileMeta.set(a.id,{x:a.position.x,z:a.position.z,y:a.position.y,halfSize:c}),q(t.tileIndex,t.tileCells,a.id,a.position.x-c,a.position.x+c,a.position.z-c,a.position.z+c,e),a});t.tileGroups.set(r.id,{...r,tiles:o})}}function eo(t,n){for(const e of n){const r=e.walls.map(o=>{const i={...o,edge:o.edge??ie(o.position,o.rotation.y)},s=.5;return t.wallMeta.set(i.id,{x:i.position.x,z:i.position.z,rotY:i.rotation.y}),q(t.wallIndex,t.wallCells,i.id,i.position.x-s,i.position.x+s,i.position.z-s,i.position.z+s,1),i});t.wallGroups.set(e.id,{...e,walls:r})}}cn.enableMapSet();const Ge="custom-tiles";function to(t){return t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Ae(t,n,e,r){t.tileCategories.has(n)||t.tileCategories.set(n,{id:n,name:e,description:r,tileGroupIds:[]})}function Re(t,n,e){const r=t.tileCategories.get(n);!r||r.tileGroupIds.includes(e)||t.tileCategories.set(n,{...r,tileGroupIds:[...r.tileGroupIds,e]})}function St(t,n,e,r){t.wallCategories.has(n)||t.wallCategories.set(n,{id:n,name:e,description:r,wallGroupIds:[]})}function It(t,n,e){const r=t.wallCategories.get(n);!r||r.wallGroupIds.includes(e)||t.wallCategories.set(n,{...r,wallGroupIds:[...r.wallGroupIds,e]})}const no=un.create()(dn.immer((t,n)=>({initialized:!1,tileIndex:new Map,tileCells:new Map,tileMeta:new Map,wallIndex:new Map,wallCells:new Map,wallMeta:new Map,meshes:new Map,wallGroups:new Map,tileGroups:new Map,blocks:[],wallCategories:new Map,tileCategories:new Map,editMode:"none",showGrid:!0,gridSize:100,snapToGrid:!0,hoverPosition:null,currentTileMultiplier:1,currentTileHeight:0,currentTileShape:"box",currentTileRotation:0,currentTileMaterialId:null,currentCustomTileName:"Custom Tile",currentCustomTileColor:"#8f8f8f",currentCustomTileTextureUrl:"",currentWallRotation:0,currentWallMaterialId:null,currentWallKind:"solid",objects:[],selectedTileObjectType:"none",currentTerrainColor:"#5a7a35",currentTerrainAccentColor:"#8fbc5a",selectedPlacedObjectType:"none",selectedModelObjectId:"door-basic",currentModelUrl:"",currentModelScale:1,currentModelColor:"#9b7653",selectedWallId:null,selectedTileId:null,selectedBlockId:null,currentFlagWidth:1.5,currentFlagHeight:1,currentFlagImageUrl:"",currentFlagStyle:"flag",currentFireIntensity:1.5,currentFireWidth:1,currentFireHeight:1.5,currentFireColor:"#ff6622",currentObjectRotation:0,currentObjectPrimaryColor:"#f7bfd2",currentObjectSecondaryColor:"#5e3d30",currentTreeKind:"sakura",currentBillboardText:"HELLO",currentBillboardImageUrl:"",currentBillboardColor:"#00ff88",currentBillboardWidth:0,currentBillboardHeight:1.5,currentBillboardScale:1,currentBillboardOffsetY:0,currentBillboardElevation:1,currentBillboardIntensity:2,showSnow:!1,showFog:!1,fogColor:"#cfd8e3",weatherEffect:"none",initializeDefaults:()=>t(e=>{if(e.initialized)return;e.meshes.set("brick-wall",{id:"brick-wall",color:"#8B4513",material:"STANDARD",roughness:.8}),e.meshes.set("glass-wall",{id:"glass-wall",material:"GLASS",opacity:.3,transparent:!0}),e.meshes.set("concrete-wall",{id:"concrete-wall",color:"#808080",material:"STANDARD",roughness:.9}),e.meshes.set("wood-floor",{id:"wood-floor",color:"#654321",material:"STANDARD",roughness:.6}),e.meshes.set("marble-floor",{id:"marble-floor",color:"#f0f0f0",material:"STANDARD",roughness:.2,metalness:.1}),e.meshes.set("sand-floor",{id:"sand-floor",color:"#c9ab75",material:"STANDARD",roughness:.96,metalness:.02}),e.meshes.set("snow-floor",{id:"snow-floor",color:"#eef5ff",material:"STANDARD",roughness:.9,metalness:0}),e.wallCategories.set("interior-walls",{id:"interior-walls",name:"Interior Walls",description:"Walls for interior spaces",wallGroupIds:["plaster-walls","painted-walls"]}),e.wallCategories.set("exterior-walls",{id:"exterior-walls",name:"Exterior Walls",description:"Walls for building exteriors",wallGroupIds:["brick-walls","concrete-walls"]}),e.wallCategories.set("special-walls",{id:"special-walls",name:"Special Walls",description:"Glass and special material walls",wallGroupIds:["glass-walls"]}),e.tileCategories.set("wood-floors",{id:"wood-floors",name:"Wood Floors",description:"Various wood flooring options",tileGroupIds:["oak-floor","pine-floor"]}),e.tileCategories.set("stone-floors",{id:"stone-floors",name:"Stone Floors",description:"Marble and stone flooring",tileGroupIds:["marble-floor","granite-floor"]}),e.tileCategories.set("natural-floors",{id:"natural-floors",name:"Natural Floors",description:"Sand and snow terrain flooring",tileGroupIds:["sand-floor","snow-floor"]}),e.wallGroups.set("brick-walls",{id:"brick-walls",name:"Brick Walls",frontMeshId:"brick-wall",backMeshId:"brick-wall",sideMeshId:"brick-wall",walls:[]}),e.wallGroups.set("glass-walls",{id:"glass-walls",name:"Glass Walls",frontMeshId:"glass-wall",backMeshId:"glass-wall",sideMeshId:"glass-wall",walls:[]}),e.wallGroups.set("concrete-walls",{id:"concrete-walls",name:"Concrete Walls",frontMeshId:"concrete-wall",backMeshId:"concrete-wall",sideMeshId:"concrete-wall",walls:[]}),e.wallGroups.set("plaster-walls",{id:"plaster-walls",name:"Plaster Walls",frontMeshId:"brick-wall",backMeshId:"brick-wall",sideMeshId:"brick-wall",walls:[]}),e.wallGroups.set("painted-walls",{id:"painted-walls",name:"Painted Walls",frontMeshId:"brick-wall",backMeshId:"brick-wall",sideMeshId:"brick-wall",walls:[]});for(const l of Pe){const h=`wall-${l.id}-exterior`,u=`wall-${l.id}-interior`,d=`wall-${l.id}-side`,f=`${l.id}-walls`;St(e,l.categoryId,l.categoryName,`${l.categoryName} wall presets`),It(e,l.categoryId,f),e.meshes.set(h,{id:h,color:l.exteriorColor,material:"STANDARD",roughness:l.roughness??.78,metalness:l.metalness??.02}),e.meshes.set(u,{id:u,color:l.interiorColor,material:"STANDARD",roughness:l.roughness??.78,metalness:l.metalness??.02}),e.meshes.set(d,{id:d,color:l.sideColor,material:"STANDARD",roughness:l.roughness??.82,metalness:l.metalness??.02}),e.wallGroups.has(f)||e.wallGroups.set(f,{id:f,name:l.labelEn,frontMeshId:h,backMeshId:u,sideMeshId:d,defaultWallKind:l.defaultKind,walls:[]})}e.tileGroups.set("oak-floor",{id:"oak-floor",name:"Oak Wood Floor",floorMeshId:"wood-floor",tiles:[]}),e.tileGroups.set("pine-floor",{id:"pine-floor",name:"Pine Wood Floor",floorMeshId:"wood-floor",tiles:[]}),e.tileGroups.set("marble-floor",{id:"marble-floor",name:"Marble Floor",floorMeshId:"marble-floor",tiles:[]}),e.tileGroups.set("granite-floor",{id:"granite-floor",name:"Granite Floor",floorMeshId:"marble-floor",tiles:[]}),e.tileGroups.set("sand-floor",{id:"sand-floor",name:"Sand Floor",floorMeshId:"sand-floor",tiles:[]}),e.tileGroups.set("snow-floor",{id:"snow-floor",name:"Snow Floor",floorMeshId:"snow-floor",tiles:[]});for(const l of De){const h=`tile-${l.id}`,u=`${l.id}-floor`;Ae(e,l.categoryId,l.categoryName,`${l.categoryName} tile presets`),Re(e,l.categoryId,u),e.meshes.has(h)||e.meshes.set(h,{id:h,color:l.color,material:l.material??"STANDARD",roughness:l.roughness??.65,metalness:l.metalness??.02,...l.opacity!==void 0?{opacity:l.opacity}:{},...l.transparent!==void 0?{transparent:l.transparent}:{},...l.mapTextureUrl?{mapTextureUrl:l.mapTextureUrl,textureUrl:l.mapTextureUrl}:{}}),e.tileGroups.has(u)||e.tileGroups.set(u,{id:u,name:l.labelEn,floorMeshId:h,tiles:[]})}e.selectedWallCategoryId="exterior-walls",e.selectedWallGroupId="brick-walls",e.selectedTileCategoryId="wood-floors",e.selectedTileGroupId="oak-floor";const r=e.tileGroups.get("oak-floor"),o=e.tileGroups.get("marble-floor"),i=e.tileGroups.get("sand-floor"),s=e.tileGroups.get("snow-floor"),a=E.GRID_CELL_SIZE,c=(l,h)=>{const u=h.cell??F(h.position),d={...h,cell:u,footprint:h.footprint??X(u,h.size||1)};l.tiles.push(d);const f=Q(h.size||1);e.tileMeta.set(d.id,{x:d.position.x,z:d.position.z,y:d.position.y,halfSize:f}),q(e.tileIndex,e.tileCells,d.id,d.position.x-f,d.position.x+f,d.position.z-f,d.position.z+f,a)};if(r&&o){for(let l=-3;l<=3;l++)for(let h=-3;h<=3;h++){const u=l*a,d=h*a,f=Math.abs(l)<=1&&Math.abs(h)<=1,m=l>=2&&h===-2,b=l>=2&&h===-3,y=l<=-2&&h>=2,M=l===3&&h===2,v=l===-3&&h===2,R=l===-2&&h===2,_=l===2&&h===-3,G=(y?i:void 0)??(b?s:void 0)??(f?o:void 0)??r,W=b?2:m||y||M?1:f?l===0&&h===0?2:1:0,S={id:`demo-${l+3}-${h+3}`,position:{x:u,y:W*E.HEIGHT_STEP,z:d},tileGroupId:G.id,size:1,shape:v?"round":R?"ramp":_?"stairs":"box"};m?c(G,{...S,objectType:"grass",objectConfig:{grassDensity:90}}):b?c(G,{...S,objectType:"snowfield"}):y?c(G,{...S,objectType:"sand"}):c(G,S)}e.objects.push({id:"demo-sakura-1",type:"sakura",position:{x:3*a,y:0,z:0},config:{size:a}},{id:"demo-flag-1",type:"flag",position:{x:0,y:0,z:-3*a},config:{flagWidth:1.5,flagHeight:1,flagStyle:"flag"}},{id:"demo-fire-1",type:"fire",position:{x:3*a,y:E.HEIGHT_STEP,z:2*a},config:{fireIntensity:1.5}})}e.initialized=!0}),addMesh:e=>t(r=>{r.meshes.set(e.id,e)}),updateMesh:(e,r)=>t(o=>{const i=o.meshes.get(e);i&&o.meshes.set(e,{...i,...r})}),removeMesh:e=>t(r=>{r.meshes.delete(e)}),addWallGroup:e=>t(r=>{r.wallGroups.set(e.id,e)}),updateWallGroup:(e,r)=>t(o=>{const i=o.wallGroups.get(e);i&&o.wallGroups.set(e,{...i,...r})}),removeWallGroup:e=>t(r=>{const o=r.wallGroups.get(e);if(o)for(const i of o.walls)Y(r.wallIndex,r.wallCells,i.id),r.wallMeta.delete(i.id);r.wallGroups.delete(e)}),addWall:(e,r)=>t(o=>{const i=o.wallGroups.get(e);if(i){const s=r.materialId??o.currentWallMaterialId,a=r.wallKind??o.currentWallKind??i.defaultWallKind??"solid",c={...r,...s?{materialId:s}:{},wallKind:a,edge:r.edge??ie(r.position,r.rotation.y)};i.walls.push(c);const l=.5;o.wallMeta.set(c.id,{x:c.position.x,z:c.position.z,rotY:c.rotation.y}),q(o.wallIndex,o.wallCells,c.id,c.position.x-l,c.position.x+l,c.position.z-l,c.position.z+l,1)}}),updateWall:(e,r,o)=>t(i=>{const s=i.wallGroups.get(e);if(s){const a=s.walls.findIndex(c=>c.id===r);if(a!==-1){const c=s.walls[a];if(c){const l=o.position!==void 0||o.rotation!==void 0;l&&(Y(i.wallIndex,i.wallCells,r),i.wallMeta.delete(r)),Object.assign(c,o),(o.position!==void 0||o.rotation!==void 0)&&(c.edge=o.edge??ie(c.position,c.rotation.y)),l&&(i.wallMeta.set(c.id,{x:c.position.x,z:c.position.z,rotY:c.rotation.y}),q(i.wallIndex,i.wallCells,c.id,c.position.x-.5,c.position.x+.5,c.position.z-.5,c.position.z+.5,1))}}}}),moveWallToGroup:(e,r)=>t(o=>{const i=o.wallGroups.get(r);if(!i)return;let s,a=-1;for(const u of o.wallGroups.values())if(a=u.walls.findIndex(d=>d.id===e),a!==-1){s=u;break}if(!s||a===-1||s.id===r){o.selectedWallGroupId=r;return}const c=s.walls[a];if(!c)return;const{materialId:l,...h}=c;s.walls.splice(a,1),i.walls.push({...h,wallGroupId:r}),o.selectedWallGroupId=r}),removeWall:(e,r)=>t(o=>{const i=o.wallGroups.get(e);i&&(Y(o.wallIndex,o.wallCells,r),o.wallMeta.delete(r),i.walls=i.walls.filter(s=>s.id!==r),o.selectedWallId===r&&(o.selectedWallId=null))}),addTileGroup:e=>t(r=>{r.tileGroups.set(e.id,e)}),updateTileGroup:(e,r)=>t(o=>{const i=o.tileGroups.get(e);i&&o.tileGroups.set(e,{...i,...r})}),removeTileGroup:e=>t(r=>{const o=r.tileGroups.get(e);if(o)for(const i of o.tiles)Y(r.tileIndex,r.tileCells,i.id),r.tileMeta.delete(i.id);r.tileGroups.delete(e)}),addTile:(e,r)=>t(o=>{const i=o.tileGroups.get(e);if(i){const s=o.selectedTileObjectType==="grass"?{grassDensity:90,terrainColor:o.currentTerrainColor,terrainAccentColor:o.currentTerrainAccentColor}:o.selectedTileObjectType==="sand"||o.selectedTileObjectType==="snowfield"?{terrainColor:o.currentTerrainColor,terrainAccentColor:o.currentTerrainAccentColor}:void 0,a=r.cell??F(r.position),c=r.materialId??o.currentTileMaterialId,l={...r,cell:a,footprint:r.footprint??X(a,r.size||1),...c?{materialId:c}:{},objectType:o.selectedTileObjectType,...s?{objectConfig:s}:{}};i.tiles.push(l);const h=E.GRID_CELL_SIZE,u=Q(l.size||1);o.tileMeta.set(l.id,{x:l.position.x,z:l.position.z,y:l.position.y,halfSize:u}),q(o.tileIndex,o.tileCells,l.id,l.position.x-u,l.position.x+u,l.position.z-u,l.position.z+u,h)}}),updateTile:(e,r,o)=>t(i=>{const s=i.tileGroups.get(e);if(s){const a=s.tiles.findIndex(c=>c.id===r);if(a!==-1){const c=s.tiles[a];if(c){const l=o.position!==void 0||o.size!==void 0;if(l&&(Y(i.tileIndex,i.tileCells,r),i.tileMeta.delete(r)),Object.assign(c,o),o.position!==void 0||o.size!==void 0||o.cell!==void 0){const h=o.cell??F(c.position);c.cell=h,c.footprint=o.footprint??X(h,c.size||1)}if(l){const h=E.GRID_CELL_SIZE,u=Q(c.size||1);i.tileMeta.set(c.id,{x:c.position.x,z:c.position.z,y:c.position.y,halfSize:u}),q(i.tileIndex,i.tileCells,c.id,c.position.x-u,c.position.x+u,c.position.z-u,c.position.z+u,h)}}}}}),removeTile:(e,r)=>t(o=>{const i=o.tileGroups.get(e);i&&(Y(o.tileIndex,o.tileCells,r),o.tileMeta.delete(r),i.tiles=i.tiles.filter(s=>s.id!==r),o.selectedTileId===r&&(o.selectedTileId=null))}),addBlock:e=>t(r=>{const o=e.cell??F(e.position);r.blocks.push({...e,cell:o})}),updateBlock:(e,r)=>t(o=>{const i=o.blocks.findIndex(a=>a.id===e);if(i===-1)return;const s=o.blocks[i];s&&(Object.assign(s,r),(r.position!==void 0||r.cell!==void 0)&&(s.cell=r.cell??F(s.position)))}),removeBlock:e=>t(r=>{r.blocks=r.blocks.filter(o=>o.id!==e),r.selectedBlockId===e&&(r.selectedBlockId=null)}),setEditMode:e=>t(r=>{r.editMode=e,e!=="none"&&(r.showGrid=!0)}),setShowGrid:e=>t(r=>{r.showGrid=e}),setGridSize:e=>t(r=>{r.gridSize=e}),setSnapToGrid:e=>t(r=>{r.snapToGrid=e}),setHoverPosition:e=>t(r=>{r.hoverPosition=e}),setTileMultiplier:e=>t(r=>{r.currentTileMultiplier=e}),setTileHeight:e=>t(r=>{const o=Math.max(0,Math.min(6,Math.round(e)));r.currentTileHeight=r.currentTileShape==="stairs"||r.currentTileShape==="ramp"?Math.max(1,o):o}),setTileShape:e=>t(r=>{r.currentTileShape=e,(e==="stairs"||e==="ramp")&&r.currentTileHeight===0&&(r.currentTileHeight=1)}),setTileRotation:e=>t(r=>{r.currentTileRotation=e}),setCurrentTileMaterialId:e=>t(r=>{r.currentTileMaterialId=e}),setCustomTileDraft:e=>t(r=>{e.name!==void 0&&(r.currentCustomTileName=e.name),e.color!==void 0&&(r.currentCustomTileColor=e.color),e.textureUrl!==void 0&&(r.currentCustomTileTextureUrl=e.textureUrl)}),applyTilePreset:e=>t(r=>{const o=De.find(a=>a.id===e);if(!o)return;const i=`tile-${o.id}`,s=`${o.id}-floor`;Ae(r,o.categoryId,o.categoryName,`${o.categoryName} tile presets`),Re(r,o.categoryId,s),r.meshes.set(i,{id:i,color:o.color,material:o.material??"STANDARD",roughness:o.roughness??.65,metalness:o.metalness??.02,...o.opacity!==void 0?{opacity:o.opacity}:{},...o.transparent!==void 0?{transparent:o.transparent}:{},...o.mapTextureUrl?{mapTextureUrl:o.mapTextureUrl,textureUrl:o.mapTextureUrl}:{}}),r.tileGroups.has(s)||r.tileGroups.set(s,{id:s,name:o.labelEn,floorMeshId:i,tiles:[]}),r.selectedTileCategoryId=o.categoryId,r.selectedTileGroupId=s,r.currentTileMaterialId=null}),applyCustomTile:()=>t(e=>{const r=e.currentCustomTileName.trim()||"Custom Tile",o=e.currentCustomTileColor||"#8f8f8f",i=e.currentCustomTileTextureUrl.trim(),s=to(`${r}-${o}-${i||"color"}`)||"custom-tile",a=`custom-tile-${s}`,c=`custom-tile-group-${s}`;Ae(e,Ge,"Custom Tiles","User-created tile maps"),Re(e,Ge,c),e.meshes.set(a,{id:a,color:o,material:"STANDARD",roughness:.62,metalness:.02,...i?{mapTextureUrl:i,textureUrl:i}:{}}),e.tileGroups.has(c)||e.tileGroups.set(c,{id:c,name:r,floorMeshId:a,tiles:[]}),e.selectedTileCategoryId=Ge,e.selectedTileGroupId=c,e.currentTileMaterialId=null}),setWallRotation:e=>t(r=>{r.currentWallRotation=e}),setCurrentWallMaterialId:e=>t(r=>{r.currentWallMaterialId=e}),setWallKind:e=>t(r=>{if(r.currentWallKind=e,!!r.selectedWallId)for(const o of r.wallGroups.values()){const i=o.walls.find(s=>s.id===r.selectedWallId);if(i){i.wallKind=e;return}}}),applyWallPreset:e=>t(r=>{const o=Pe.find(l=>l.id===e);if(!o)return;const i=`wall-${o.id}-exterior`,s=`wall-${o.id}-interior`,a=`wall-${o.id}-side`,c=`${o.id}-walls`;St(r,o.categoryId,o.categoryName,`${o.categoryName} wall presets`),It(r,o.categoryId,c),r.meshes.set(i,{id:i,color:o.exteriorColor,material:"STANDARD",roughness:o.roughness??.78,metalness:o.metalness??.02}),r.meshes.set(s,{id:s,color:o.interiorColor,material:"STANDARD",roughness:o.roughness??.78,metalness:o.metalness??.02}),r.meshes.set(a,{id:a,color:o.sideColor,material:"STANDARD",roughness:o.roughness??.82,metalness:o.metalness??.02}),r.wallGroups.has(c)||r.wallGroups.set(c,{id:c,name:o.labelEn,frontMeshId:i,backMeshId:s,sideMeshId:a,defaultWallKind:o.defaultKind,walls:[]}),r.selectedWallCategoryId=o.categoryId,r.selectedWallGroupId=c,r.currentWallKind=o.defaultKind,r.currentWallMaterialId=null}),snapPosition:e=>{const{snapToGrid:r}=n();return r?$t(e):e},checkTilePosition:e=>{const{currentTileMultiplier:r,currentTileRotation:o,currentTileShape:i,selectedTileGroupId:s,selectedTileObjectType:a,blocks:c,tileGroups:l,wallGroups:h}=n(),u=F(e),d=ot({id:"__candidate_tile__",position:e,size:r,shape:i,rotation:o,objectType:a,cell:u,footprint:X(u,r)}),f=Oe(l.values(),h.values(),{blocks:c}),m={subject:d.subject,coord:d.coord,footprint:d.footprint};return!f.canPlace(d.rotation===void 0?m:{...m,rotation:d.rotation}).ok},checkBlockPosition:e=>{const{blocks:r,tileGroups:o,wallGroups:i}=n(),s=it({id:"__candidate_block__",position:e.position,...e.cell?{cell:e.cell}:{},...e.size?{size:e.size}:{}});return!Oe(o.values(),i.values(),{blocks:r}).canPlace({subject:s.subject,coord:s.coord,footprint:s.footprint}).ok},getSupportHeightAt:e=>{const{tileIndex:r,tileMeta:o,currentTileMultiplier:i}=n();return rn(r,o,e,i)},checkWallPosition:(e,r)=>{const{wallIndex:o,wallMeta:i}=n();return on(o,i,e,r)},isInEditMode:()=>{const{editMode:e}=n();return e!=="none"},serialize:()=>Yr(n()),hydrate:e=>t(r=>{Xr(r,e)}),addWallCategory:e=>t(r=>{r.wallCategories.set(e.id,e)}),updateWallCategory:(e,r)=>t(o=>{const i=o.wallCategories.get(e);i&&o.wallCategories.set(e,{...i,...r})}),removeWallCategory:e=>t(r=>{r.wallCategories.delete(e)}),setSelectedWallCategory:e=>t(r=>{r.selectedWallCategoryId=e;const o=r.wallCategories.get(e);if(o&&o.wallGroupIds.length>0){const i=o.wallGroupIds[0];i&&(r.selectedWallGroupId=i)}}),addTileCategory:e=>t(r=>{r.tileCategories.set(e.id,e)}),updateTileCategory:(e,r)=>t(o=>{const i=o.tileCategories.get(e);i&&o.tileCategories.set(e,{...i,...r})}),removeTileCategory:e=>t(r=>{r.tileCategories.delete(e)}),setSelectedTileCategory:e=>t(r=>{r.selectedTileCategoryId=e;const o=r.tileCategories.get(e);if(o&&o.tileGroupIds.length>0){const i=o.tileGroupIds[0];i&&(r.selectedTileGroupId=i)}}),setSelectedTileObjectType:e=>t(r=>{r.selectedTileObjectType=e,e==="grass"?(r.currentTerrainColor="#5a7a35",r.currentTerrainAccentColor="#8fbc5a"):e==="water"?(r.currentTerrainColor="#2f8dbd",r.currentTerrainAccentColor="#9ed6c8"):e==="sand"?(r.currentTerrainColor="#b89b66",r.currentTerrainAccentColor="#e0c27a"):e==="snowfield"&&(r.currentTerrainColor="#dcecff",r.currentTerrainAccentColor="#ffffff")}),setTerrainColors:(e,r)=>t(o=>{o.currentTerrainColor=e,r!==void 0&&(o.currentTerrainAccentColor=r)}),setSelectedPlacedObjectType:e=>t(r=>{r.selectedPlacedObjectType=e}),setSelectedModelObjectId:e=>t(r=>{r.selectedModelObjectId=e}),setModelUrl:e=>t(r=>{r.currentModelUrl=e}),setModelScale:e=>t(r=>{r.currentModelScale=Math.max(.1,Math.min(10,e))}),setModelColor:e=>t(r=>{r.currentModelColor=e}),setSelectedWallId:e=>t(r=>{r.selectedWallId=e,e&&(r.selectedTileId=null,r.selectedBlockId=null)}),setSelectedTileId:e=>t(r=>{r.selectedTileId=e,e&&(r.selectedWallId=null,r.selectedBlockId=null)}),setSelectedBlockId:e=>t(r=>{r.selectedBlockId=e,e&&(r.selectedWallId=null,r.selectedTileId=null)}),addObject:e=>t(r=>{r.objects.push(e)}),removeObject:e=>t(r=>{r.objects=r.objects.filter(o=>o.id!==e)}),updateObject:(e,r)=>t(o=>{const i=o.objects.findIndex(s=>s.id===e);if(i!==-1){const s=o.objects[i];s&&Object.assign(s,r)}}),setFlagWidth:e=>t(r=>{r.currentFlagWidth=e}),setFlagHeight:e=>t(r=>{r.currentFlagHeight=e}),setFlagImageUrl:e=>t(r=>{r.currentFlagImageUrl=e}),setFlagStyle:e=>t(r=>{r.currentFlagStyle=e;const o=fe[e];r.currentFlagWidth=o.defaultWidth,r.currentFlagHeight=o.defaultHeight}),setFireIntensity:e=>t(r=>{r.currentFireIntensity=e}),setFireWidth:e=>t(r=>{r.currentFireWidth=e}),setFireHeight:e=>t(r=>{r.currentFireHeight=e}),setFireColor:e=>t(r=>{r.currentFireColor=e}),setObjectRotation:e=>t(r=>{r.currentObjectRotation=e}),setObjectPrimaryColor:e=>t(r=>{r.currentObjectPrimaryColor=e}),setObjectSecondaryColor:e=>t(r=>{r.currentObjectSecondaryColor=e}),setTreeKind:e=>t(r=>{const o=zt[e];r.currentTreeKind=e,r.currentObjectPrimaryColor=o.primaryColor,r.currentObjectSecondaryColor=o.secondaryColor}),setBillboardText:e=>t(r=>{r.currentBillboardText=e}),setBillboardImageUrl:e=>t(r=>{r.currentBillboardImageUrl=e}),setBillboardColor:e=>t(r=>{r.currentBillboardColor=e}),setBillboardWidth:e=>t(r=>{r.currentBillboardWidth=e}),setBillboardHeight:e=>t(r=>{r.currentBillboardHeight=e}),setBillboardScale:e=>t(r=>{r.currentBillboardScale=e}),setBillboardOffsetY:e=>t(r=>{r.currentBillboardOffsetY=e}),setBillboardElevation:e=>t(r=>{r.currentBillboardElevation=e}),setBillboardIntensity:e=>t(r=>{r.currentBillboardIntensity=e}),setShowSnow:e=>t(r=>{r.showSnow=e,r.weatherEffect=e?"snow":"none"}),setShowFog:e=>t(r=>{r.showFog=e}),setFogColor:e=>t(r=>{r.fogColor=e}),setWeatherEffect:e=>t(r=>{r.weatherEffect=e,r.showSnow=e==="snow"})})));function ue(t,n,e,r){const o=Math.atan2(n.z-e.z,n.x-e.x);t.updateMouse({target:n,angle:o,position:new I.Vector2(n.x,n.z),isActive:!0,shouldRun:r})}function ro(t={}){const{minHeight:n=.5,offsetY:e=.5,useNavigation:r=!0,simplifyPath:o=!0,waypointThreshold:i=1,fallbackToDirectOnFail:s=!0,agentRadius:a=.35,agentWidth:c,agentDepth:l,clearance:h}=t,{activeState:u}=Je(),d=tt(),f=!!u?.position,m=(M,v,R)=>{if(R!=="ground"||!u?.position)return!1;try{const _=u.position,G=p.V3(M.point.x,M.point.y,M.point.z),W=Math.max(G.y+e,n),S=p.V3(G.x,W,G.z),w=_.clone(),T=ht();return r?(B.getInstance().init().then(()=>{if(!kn(T))return;const A=B.getInstance(),x={agentRadius:a,...c!==void 0?{agentWidth:c}:{},...l!==void 0?{agentDepth:l}:{},...h!==void 0?{clearance:h}:{}};if(S.y=Math.max(A.sampleHeight(S.x,S.z)+e,n),A.hasLineOfSight(w.x,w.z,S.x,S.z,x)){Te([S],i,v),ue(d,S,w,v);return}const C=A.findPath(w.x,w.z,S.x,S.z,{weighted:!0,...x});if(C.length===0){xe(),s&&!A.hasNavigationConstraints()&&A.isWalkable(S.x,S.z,x)&&(Te([S],i,v),ue(d,S,w,v));return}const D=(o?A.smoothPath(C,[w.x,w.y,w.z],[S.x,S.y,S.z],x):C).map(O=>new I.Vector3(O[0],O[1],O[2])).filter(O=>O.distanceTo(w)>i),j=D[D.length-1];(!j||j.distanceTo(S)>i)&&D.push(S);const H=D.length>0?D:[S];Te(H,i,v),ue(d,H[0]??S,w,v)}),!0):(xe(),ue(d,S,w,v),!0)}catch(_){return console.error("moveClicker error:",_),!1}};return{moveClicker:m,stopClicker:()=>{try{if(!f)return;ht(),xe(),d.updateMouse({isActive:!1,shouldRun:!1})}catch{}},onClick:M=>{m(M,!1,"ground")},isReady:f}}exports.BUILDING_BASIC_OBJECT_OPTIONS=_t;exports.BUILDING_FLAG_STYLE_OPTIONS=dr;exports.BUILDING_PLACED_OBJECT_OPTIONS=ur;exports.BUILDING_TILE_OBJECT_OPTIONS=lr;exports.BUILDING_TILE_PRESETS=De;exports.BUILDING_TILE_SHAPE_OPTIONS=cr;exports.BUILDING_TREE_COLOR_PRESETS=zt;exports.BUILDING_TREE_OPTIONS=ar;exports.BUILDING_WALL_KIND_OPTIONS=sr;exports.BUILDING_WALL_PRESETS=Pe;exports.BUILDING_WEATHER_EFFECT_OPTIONS=ir;exports.CacheSnapshot=be;exports.CoreBridge=Le;exports.DEFAULT_MOTIONS_INPUT_EXTENSION_ID=Xe;exports.DEFAULT_MOTIONS_PHYSICS_EXTENSION_ID=Ye;exports.DEFAULT_MOTIONS_RUNTIME_SERVICE_ID=Qe;exports.DomainBridge=Be;exports.EnableEventLog=Mt;exports.EnableMetrics=Ct;exports.FLAG_STYLE_META=fe;exports.GaesupRuntimeProvider=or;exports.LogSnapshot=me;exports.MOTIONS_TELEPORT_EVENT=et;exports.NavigationSystem=B;exports.PhysicsEntity=Ht;exports.TILE_CONSTANTS=E;exports.ValidateCommand=Fe;exports.applyToonToScene=jt;exports.blockToPlacementEntry=it;exports.buildingCellToWorld=qt;exports.buildingGridAdapter=L;exports.buildingGroupsToPlacementEntries=nn;exports.buildingPlacementAdapter=Xt;exports.cellToTilePosition=qr;exports.createBlockFootprint=Yt;exports.createBuildingPlacementEngine=Oe;exports.createMotionsPlugin=Dt;exports.createMotionsRuntime=Pt;exports.createTileFootprint=X;exports.createToonMaterial=Rr;exports.disposeToonGradients=zr;exports.edgeKey=Vr;exports.edgeSideToWallRotation=Jt;exports.edgeToWallTransform=$r;exports.getClickNavigationRoute=Gt;exports.getDefaultToonMode=Kt;exports.getTileSupportHeight=rn;exports.getToonGradient=nt;exports.hasTileCollision=Jr;exports.hasWallCollision=on;exports.indexAabb=q;exports.loadCoreWasm=At;exports.motionsPlugin=yr;exports.normalizeQuarterTurnRotation=Zt;exports.pair=rt;exports.queryAabbIds=Ie;exports.requestMotionsTeleport=mr;exports.resolveRuntimeInputBackend=Nt;exports.setDefaultToonMode=kr;exports.snapBuildingPosition=$t;exports.subscribeClickNavigationRoute=zn;exports.tileFootprintKeys=Zr;exports.tileGroupToPlacementEntries=en;exports.tileHalfSize=Q;exports.tileOverlaps=st;exports.tilePositionToCell=F;exports.tileToPlacementEntry=ot;exports.unindexId=Y;exports.useAnimationBridge=Tt;exports.useBuildingStore=no;exports.useClicker=ro;exports.useGaesupGltf=Or;exports.useGaesupRuntime=qe;exports.useGaesupRuntimeRevision=Ze;exports.useInputBackend=tt;exports.useInteractionSystem=Ot;exports.useStateSystem=Je;exports.wallGroupToPlacementEntries=tn;exports.wallToPlacementEntry=Qt;exports.wallTransformToEdge=ie;exports.worldToBuildingCell=Vt;exports.zigZag=Ne;
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { useRef as h, useEffect as b, useCallback as A, useMemo as ut, useLayoutEffect as J } from "react";
|
|
2
2
|
import { useFrame as ct, useThree as mt } from "@react-three/fiber";
|
|
3
3
|
import * as a from "three";
|
|
4
|
-
import { V as dt, G as ht, W as gt } from "./index-
|
|
4
|
+
import { V as dt, G as ht, W as gt } from "./index-C5agFfBe.js";
|
|
5
5
|
import { H, P as G, C as pt, M as vt, u as U } from "./gaesupStore-DTu0tYBp.js";
|
|
6
|
-
import "reflect-metadata";
|
|
7
6
|
import yt from "mitt";
|
|
8
7
|
var wt = Object.defineProperty, Ct = Object.getOwnPropertyDescriptor, K = (e, o, t, i) => {
|
|
9
8
|
for (var n = Ct(o, t), r = e.length - 1, c; r >= 0; r--)
|
|
@@ -688,10 +687,10 @@ function Zt() {
|
|
|
688
687
|
system: F
|
|
689
688
|
};
|
|
690
689
|
}
|
|
691
|
-
function
|
|
690
|
+
function Kt() {
|
|
692
691
|
return Zt(), null;
|
|
693
692
|
}
|
|
694
|
-
function
|
|
693
|
+
function $t() {
|
|
695
694
|
const e = h(null), o = h(null), t = h(null), i = h(null);
|
|
696
695
|
return {
|
|
697
696
|
outerGroupRef: e,
|
|
@@ -701,7 +700,7 @@ function Jt() {
|
|
|
701
700
|
};
|
|
702
701
|
}
|
|
703
702
|
export {
|
|
704
|
-
|
|
703
|
+
Kt as C,
|
|
705
704
|
j as a,
|
|
706
|
-
|
|
705
|
+
$t as u
|
|
707
706
|
};
|