gaesup-world 1.0.2 → 1.0.3
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/GrassDriver-BOvF1wSA.cjs +731 -0
- package/dist/GrassDriver-BYgHaICM.js +20086 -0
- package/dist/assets.d.cts +1 -0
- package/dist/blueprints/components/BlueprintEditor/index.d.ts +0 -1
- package/dist/blueprints/components/panels/BlueprintPanel/index.d.ts +6 -2
- package/dist/blueprints/components/panels/BlueprintPanel/types.d.ts +2 -0
- package/dist/blueprints/components/panels/BlueprintPanel/utils.d.ts +0 -6
- package/dist/blueprints/editor.d.cts +0 -3
- package/dist/blueprints/editor.d.ts +0 -3
- package/dist/blueprints/types.d.ts +0 -18
- package/dist/blueprints-editor.cjs +1 -1
- package/dist/blueprints-editor.js +402 -1125
- package/dist/blueprints.cjs +1 -1
- package/dist/blueprints.js +2 -2
- package/dist/core/boilerplate/hooks/useEntityLifecycle.d.ts +1 -0
- package/dist/core/building/components/BuildingUI/index.d.ts +2 -1
- package/dist/core/building/components/mesh/billboard/index.d.ts +7 -0
- package/dist/core/building/components/mesh/grass/assets.d.ts +2 -2
- package/dist/core/building/components/mesh/sakura.d.ts +2 -0
- package/dist/core/building/components/mesh/snow/index.d.ts +6 -1
- package/dist/core/building/components/mesh/water/index.d.ts +4 -2
- package/dist/core/building/id.d.ts +1 -0
- package/dist/core/building/index.d.ts +1 -0
- package/dist/core/building/stores/buildingStore.d.ts +34 -1
- package/dist/core/building/stores/persistence.d.ts +5 -1
- package/dist/core/building/types/index.d.ts +73 -3
- package/dist/core/camera/stores/slices/cameraOption/types.d.ts +1 -0
- package/dist/core/content/exporter.d.ts +3 -0
- package/dist/core/content/types.d.ts +3 -0
- package/dist/core/editor/components/EditorLayout/types.d.ts +18 -8
- package/dist/core/editor/components/fields/index.d.ts +17 -0
- package/dist/core/editor/components/index.d.ts +1 -0
- package/dist/core/editor/components/panels/AnimationPanel.d.ts +2 -1
- package/dist/core/editor/components/panels/BlockPanel.d.ts +3 -0
- package/dist/core/editor/components/panels/BuildingPanel/NPCPanel.d.ts +30 -0
- package/dist/core/editor/components/panels/BuildingPanel/flow.d.ts +12 -0
- package/dist/core/editor/components/panels/BuildingPanel/helpers.d.ts +18 -0
- package/dist/core/editor/components/panels/BuildingPanel/index.d.ts +16 -5
- package/dist/core/editor/components/panels/BuildingPanel/sections.d.ts +173 -0
- package/dist/core/editor/components/panels/BuildingPanel/state.d.ts +134 -0
- package/dist/core/editor/components/panels/CameraPanel.d.ts +2 -1
- package/dist/core/editor/components/panels/CharacterAssetPanel/index.d.ts +2 -1
- package/dist/core/editor/components/panels/GameplayEventPanel/index.d.ts +4 -4
- package/dist/core/editor/components/panels/MotionPanel.d.ts +2 -1
- package/dist/core/editor/components/panels/NPCPanel.d.ts +3 -0
- package/dist/core/editor/components/panels/ObjectPanel.d.ts +3 -0
- package/dist/core/editor/components/panels/PerformancePanel.d.ts +2 -1
- package/dist/core/editor/components/panels/StudioPanel/index.d.ts +24 -2
- package/dist/core/editor/components/panels/TilePanel.d.ts +3 -0
- package/dist/core/editor/components/panels/VehiclePanel/index.d.ts +2 -1
- package/dist/core/editor/components/panels/WallPanel.d.ts +3 -0
- package/dist/core/editor/components/panels/WorldPanel.d.ts +3 -0
- package/dist/core/editor/components/panels/index.d.ts +6 -0
- package/dist/core/editor/components/panels/types.d.ts +6 -0
- package/dist/core/editor/index.d.ts +1 -1
- package/dist/core/editor/shell.d.ts +11 -1
- package/dist/core/gameplay/events/index.d.ts +2 -0
- package/dist/core/gameplay/events/templates.d.ts +23 -0
- package/dist/core/motions/core/forces/BuoyancyComponent.d.ts +9 -1
- package/dist/core/motions/core/forces/WindComponent.d.ts +11 -1
- package/dist/core/motions/entities/types.d.ts +6 -0
- package/dist/core/networks/core/PlayerNetworkManager.d.ts +9 -3
- package/dist/core/networks/types/index.d.ts +10 -0
- package/dist/core/npc/components/NPCInstance/types.d.ts +1 -0
- package/dist/core/npc/core/blueprint.d.ts +23 -0
- package/dist/core/npc/core/brain.d.ts +9 -0
- package/dist/core/npc/core/reinforcement.d.ts +11 -0
- package/dist/core/npc/index.d.ts +5 -0
- package/dist/core/npc/stores/npcStore.d.ts +12 -1
- package/dist/core/npc/stores/types.d.ts +12 -1
- package/dist/core/npc/types/index.d.ts +194 -0
- package/dist/core/weather/components/WeatherEffect/index.d.ts +5 -1
- package/dist/core/weather/index.d.ts +1 -1
- package/dist/defaultConfig-D-a1mbtz.cjs +1 -0
- package/dist/{defaultConfig-CJNbZAKY.js → defaultConfig-r47lN-AC.js} +831 -728
- package/dist/editor.cjs +1 -1
- package/dist/editor.d.cts +5 -0
- package/dist/editor.js +128 -115
- package/dist/eventsStore-5J9sZm-v.cjs +1 -0
- package/dist/eventsStore-Br8PKcCj.js +83 -0
- package/dist/gaesupStore-CE-oe63F.cjs +1 -0
- package/dist/{gaesupStore-BKIA2dFc.js → gaesupStore-dfWoSPPs.js} +258 -255
- package/dist/{index-BmOFYbvk.js → index-BEG0aFwg.js} +2 -2
- package/dist/{index-BsAUS0-8.js → index-BMOiJMPn.js} +17 -16
- package/dist/index-BbzAvMs-.js +331 -0
- package/dist/index-CRKFvjZ0.cjs +1 -0
- package/dist/index-CRmbe-O5.js +4169 -0
- package/dist/index-CaUZvDBz.cjs +1 -0
- package/dist/{index-BnACo_cG.js → index-Cgqkv_Dw.js} +2 -2
- package/dist/index-CzYoZOU-.cjs +1 -0
- package/dist/index-D6pLUicy.cjs +1 -0
- package/dist/{index-BjrBeKEM.js → index-FhO0e3y-.js} +2 -2
- package/dist/index-GgTn_F27.cjs +1 -0
- package/dist/{index-BUONBdvH.cjs → index-maKBe62H.cjs} +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.css +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1622 -1355
- package/dist/network.cjs +1 -1
- package/dist/network.d.cts +1 -0
- package/dist/network.js +33 -33
- package/dist/questStore-Css-uoyW.js +370 -0
- package/dist/questStore-D4HDyJkV.cjs +1 -0
- package/dist/{registerComponents-BfIcN9qa.js → registerComponents-BrKmE56h.js} +2 -2
- package/dist/{registerComponents-D3FUm9GA.cjs → registerComponents-DGEaT7bV.cjs} +1 -1
- package/dist/runtime.cjs +1 -1
- package/dist/runtime.d.cts +6 -0
- package/dist/runtime.js +42 -43
- package/dist/server-contracts.cjs +1 -1
- package/dist/server-contracts.d.cts +5 -0
- package/dist/server-contracts.js +33 -25
- package/dist/sfe-RrB92jNe.cjs +1 -0
- package/dist/sfe-uIb6H2wc.js +824 -0
- package/dist/templates-CmBSPiF_.js +572 -0
- package/dist/templates-eL763zpL.cjs +1 -0
- package/dist/toastStore-Dho0lQiS.cjs +1 -0
- package/dist/toastStore-z4vFobr9.js +164 -0
- package/dist/{useSpawnFromBlueprint-fzl4TuHG.js → useSpawnFromBlueprint-BxXAW00x.js} +1 -1
- package/dist/{useSpawnFromBlueprint-1gMiylSa.cjs → useSpawnFromBlueprint-CVdzF396.cjs} +1 -1
- package/package.json +296 -298
- package/dist/GrassDriver-0VzddMiy.cjs +0 -725
- package/dist/GrassDriver-CgXNOTL2.js +0 -9871
- package/dist/PhysicsEntity-BpoArh5L.cjs +0 -1
- package/dist/PhysicsEntity-Cy3K_czk.js +0 -3845
- package/dist/blueprints/components/editor/CameraNode/index.d.ts +0 -9
- package/dist/blueprints/components/editor/EditableNode/index.d.ts +0 -5
- package/dist/blueprints/components/editor/EditableNode/types.d.ts +0 -8
- package/dist/blueprints/components/editor/InputNode/index.d.ts +0 -9
- package/dist/defaultConfig-BR_x-243.cjs +0 -1
- package/dist/eventsStore-Cipkf938.cjs +0 -1
- package/dist/eventsStore-DqmXNVEb.js +0 -244
- package/dist/gaesupStore-BoN_06sX.cjs +0 -1
- package/dist/index-B9921cuX.cjs +0 -1
- package/dist/index-BOmJcTCV.cjs +0 -1
- package/dist/index-BlKxYuUK.js +0 -328
- package/dist/index-CwttQ-l-.cjs +0 -1
- package/dist/index-SFK6DuIo.cjs +0 -1
- package/dist/seedEvents-Dmms48tb.cjs +0 -1
- package/dist/seedEvents-v6aCLQE7.js +0 -723
- package/dist/sfe-CRsG1dTW.js +0 -10
- package/dist/sfe-CpgzdMyB.cjs +0 -1
- package/dist/snapshot-DRqZrbCu.cjs +0 -1
- package/dist/snapshot-OExk53wq.js +0 -75
|
@@ -0,0 +1,731 @@
|
|
|
1
|
+
"use strict";const i=require("react/jsx-runtime"),m=require("react"),ge=require("./gaesupStore-CE-oe63F.cjs"),R=require("./index-GgTn_F27.cjs"),kc=require("zustand/traditional"),Se=require("zustand/shallow");require("react-dom");const be=require("@react-three/fiber"),ct=require("@react-three/rapier"),se=require("./sfe-RrB92jNe.cjs"),bn=require("./assetStore-BuE4mh1C.cjs"),mi=require("./index-DCa_lUwq.cjs"),Bi=require("zustand"),ls=require("zustand/react/shallow"),We=require("./templates-eL763zpL.cjs"),Jn=require("./index-D6pLUicy.cjs"),pt=require("@react-three/drei"),_p=require("three"),ua=require("three-stdlib");require("reflect-metadata");const da=require("./weatherStore-1unmwIen.cjs"),fa=require("simplex-noise"),jp=require("./authStore-CrDnYNnL.cjs");function Mp(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const k=Mp(_p);function Oe({label:e,min:t,max:n,step:o,value:s,suffix:r,onChange:a}){return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:"#fff"},children:[i.jsx("span",{style:{width:60,flexShrink:0,color:"rgba(255,255,255,0.7)"},children:e}),i.jsx("input",{type:"range",min:t,max:n,step:o,value:s,onChange:l=>a(Number(l.target.value)),style:{flex:1,accentColor:"#0078d4"}}),i.jsxs("span",{style:{width:44,textAlign:"right",fontFamily:"monospace",fontSize:11},children:[typeof o=="number"&&o<1?s.toFixed(2):s,r??""]})]})}function tr({label:e,checked:t,onChange:n}){return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"#fff"},children:[i.jsx("input",{type:"checkbox",checked:t,onChange:o=>n(o.target.checked),style:{accentColor:"#0078d4"}}),i.jsx("span",{children:e})]})}function Di({title:e,children:t}){return i.jsxs("div",{style:{background:"rgba(0,0,0,0.2)",borderRadius:6,padding:"8px 10px",border:"1px solid rgba(255,255,255,0.08)",display:"flex",flexDirection:"column",gap:6},children:[i.jsx("div",{style:{fontSize:10,fontWeight:600,color:"rgba(255,255,255,0.5)",textTransform:"uppercase",letterSpacing:.5},children:e}),t]})}function Cp(){const e=ge.useGaesupStore(a=>a.cameraOption),t=ge.useGaesupStore(a=>a.setCameraOption),n=ge.useGaesupStore(a=>a.mode),o=m.useCallback((a,l)=>{t({[a]:l})},[t]),s=m.useCallback((a,l)=>{t({smoothing:{...e.smoothing,[a]:l}})},[t,e.smoothing]),r=a=>e[a]??0;return i.jsxs("div",{style:{padding:10,display:"flex",flexDirection:"column",gap:10},children:[i.jsxs("div",{style:{fontSize:11,color:"rgba(255,255,255,0.5)",marginBottom:-4},children:["Mode: ",n.control??"thirdPerson"]}),i.jsxs(Di,{title:"Distance",children:[i.jsx(Oe,{label:"X",min:-50,max:50,step:1,value:r("xDistance"),onChange:a=>o("xDistance",a)}),i.jsx(Oe,{label:"Y",min:0,max:50,step:1,value:r("yDistance"),onChange:a=>o("yDistance",a)}),i.jsx(Oe,{label:"Z",min:-50,max:50,step:1,value:r("zDistance"),onChange:a=>o("zDistance",a)})]}),i.jsxs(Di,{title:"FOV / Smoothing",children:[i.jsx(Oe,{label:"FOV",min:30,max:120,step:5,value:e.fov??75,suffix:"deg",onChange:a=>o("fov",a)}),i.jsx(Oe,{label:"Pos",min:.01,max:1,step:.01,value:e.smoothing?.position??.1,onChange:a=>s("position",a)}),i.jsx(Oe,{label:"Rot",min:.01,max:1,step:.01,value:e.smoothing?.rotation??.1,onChange:a=>s("rotation",a)}),i.jsx(Oe,{label:"FOV Sm",min:.01,max:1,step:.01,value:e.smoothing?.fov??.2,onChange:a=>s("fov",a)})]}),i.jsxs(Di,{title:"Zoom",children:[i.jsx(tr,{label:"Enable Zoom",checked:e.enableZoom??!1,onChange:a=>o("enableZoom",a)}),i.jsx(Oe,{label:"Speed",min:1e-4,max:.01,step:1e-4,value:e.zoomSpeed??.001,onChange:a=>o("zoomSpeed",a)}),i.jsx(Oe,{label:"Min",min:.1,max:2,step:.1,value:e.minZoom??.5,onChange:a=>o("minZoom",a)}),i.jsx(Oe,{label:"Max",min:1,max:5,step:.1,value:e.maxZoom??2,onChange:a=>o("maxZoom",a)})]}),i.jsxs(Di,{title:"Options",children:[i.jsx(tr,{label:"Collision",checked:e.enableCollision??!1,onChange:a=>o("enableCollision",a)}),i.jsx(tr,{label:"Focus Mode",checked:e.enableFocus??!1,onChange:a=>o("enableFocus",a)}),i.jsx(Oe,{label:"Focus Dist",min:1,max:50,step:1,value:e.focusDistance??15,onChange:a=>o("focusDistance",a)}),i.jsx(Oe,{label:"Max Dist",min:5,max:100,step:1,value:e.maxDistance??50,onChange:a=>o("maxDistance",a)})]}),i.jsxs(Di,{title:"Bounds",children:[i.jsx(Oe,{label:"Min Y",min:-10,max:50,step:1,value:e.bounds?.minY??2,onChange:a=>t({bounds:{...e.bounds,minY:a}})}),i.jsx(Oe,{label:"Max Y",min:5,max:100,step:1,value:e.bounds?.maxY??50,onChange:a=>t({bounds:{...e.bounds,maxY:a}})})]})]})}const Np=[{value:"thirdPerson",label:"Third Person"},{value:"firstPerson",label:"First Person"},{value:"chase",label:"Chase"},{value:"topDown",label:"Top Down"},{value:"isometric",label:"Isometric"},{value:"sideScroll",label:"Side-Scroller"},{value:"fixed",label:"Fixed"}];function Tp(){const{mode:e,setMode:t}=ge.useGaesupStore(ls.useShallow(o=>({mode:o.mode,setMode:o.setMode}))),n=e?.control||"thirdPerson";return i.jsx("div",{className:"cc-panel",children:i.jsx("div",{className:"cc-list",children:Np.map(o=>i.jsx("button",{className:`cc-button ${n===o.value?"active":""}`,onClick:()=>t({control:o.value}),children:o.label},o.value))})})}const Ip=[{key:"mode",label:"Mode",enabled:!0,format:"text"},{key:"position",label:"Position",enabled:!0,format:"vector3",precision:2},{key:"distance",label:"Distance",enabled:!0,format:"vector3",precision:2},{key:"fov",label:"FOV",enabled:!0,format:"angle",precision:1},{key:"velocity",label:"Velocity",enabled:!1,format:"vector3",precision:2},{key:"rotation",label:"Rotation",enabled:!1,format:"vector3",precision:2},{key:"zoom",label:"Zoom",enabled:!1,format:"number",precision:2},{key:"activeController",label:"Controller",enabled:!0,format:"text"}];function nr(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.x=="number"&&typeof t.y=="number"&&typeof t.z=="number"}function Bc(){const e={frameCount:0,averageFrameTime:0,lastUpdateTime:Date.now(),mode:"unknown",activeController:"unknown",distance:null,fov:0,position:null,targetPosition:null,velocity:null,rotation:null},[t,n]=m.useState(e),o=ge.useGaesupStore(d=>d.mode),s=ge.useGaesupStore(d=>d.cameraOption),{activeState:r}=R.useStateSystem(),a=m.useRef(e),l=m.useCallback((d,p)=>d===p?!1:nr(d)?nr(p)?d.x!==p.x||d.y!==p.y||d.z!==p.z:!0:typeof d!="object"||d===null?!0:JSON.stringify(d)!==JSON.stringify(p),[]),c=m.useCallback(d=>nr(d)?{x:d.x,y:d.y,z:d.z}:null,[]),u=m.useCallback(()=>{const d=s?.xDistance!==void 0&&s?.yDistance!==void 0&&s?.zDistance!==void 0?{x:s.xDistance,y:s.yDistance,z:s.zDistance}:null,p={...a.current,mode:o?.control??"unknown",activeController:s?.mode??o?.control??"unknown",distance:d,fov:s?.fov??0,position:c(r?.position),targetPosition:c(s?.target),velocity:c(r?.velocity),rotation:c(r?.euler),lastUpdateTime:Date.now(),...s?.zoom!==void 0?{zoom:s.zoom}:{}};Object.keys(p).some(v=>l(p[v],a.current[v]))&&(a.current=p,n(p))},[o,s,r,l,c]);m.useEffect(()=>{u();const d=setInterval(u,100);return()=>{clearInterval(d)}},[u]);const f=m.useCallback((d,p=2)=>d==null?"N/A":typeof d=="object"&&d.x!==void 0?`X:${d.x.toFixed(p)} Y:${d.y.toFixed(p)} Z:${d.z.toFixed(p)}`:typeof d=="number"?d.toFixed(p):d.toString(),[]);return i.jsx("div",{className:"cd-panel",children:i.jsx("div",{className:"cd-grid",children:Ip.map(d=>i.jsxs("div",{className:"cd-item",children:[i.jsx("span",{className:"cd-label",children:d.label}),i.jsx("span",{className:"cd-value",children:f(t[d.key])})]},d.key))})})}const Ep=[{id:"classic",name:"Classic",description:"A traditional third-person view.",icon:"camera",config:{mode:"thirdPerson",distance:{x:0,y:8,z:10},fov:75,smoothing:{position:.1,rotation:.1,fov:.1}}},{id:"cinematic",name:"Cinematic",description:"Smooth, movie-like camera work.",icon:"camera",config:{mode:"chase",distance:{x:2,y:7,z:8},fov:60,smoothing:{position:.05,rotation:.05,fov:.05}}},{id:"action",name:"Action",description:"Responsive camera for fast gameplay.",icon:"camera",config:{mode:"thirdPerson",distance:{x:0,y:6,z:6},fov:85,smoothing:{position:.2,rotation:.2,fov:.2}}},{id:"strategy",name:"Strategy",description:"Top-down view for an overview.",icon:"camera",config:{mode:"topDown",distance:{x:0,y:20,z:0},fov:45,smoothing:{position:.1,rotation:.1,fov:.1}}},{id:"retro",name:"Retro",description:"Classic side-scroller style.",icon:"camera",config:{mode:"sideScroll",distance:{x:15,y:0,z:0},fov:75,smoothing:{position:.15,rotation:.15,fov:.15}}}];function Ap(e,t){return!e||!t?!1:e.x===t.x&&e.y===t.y&&e.z===t.z}function kp(e){const t=e?.xDistance,n=e?.yDistance,o=e?.zDistance;if(!(t===void 0||n===void 0||o===void 0))return{x:t,y:n,z:o}}function Pc(){const[e]=m.useState(Ep),t=ge.useGaesupStore(c=>c.setMode),n=ge.useGaesupStore(c=>c.setCameraOption),o=ge.useGaesupStore(c=>c.mode),s=ge.useGaesupStore(c=>c.cameraOption),[r,a]=m.useState(null),l=m.useCallback(c=>{t({control:c.config.mode}),n({xDistance:c.config.distance.x,yDistance:c.config.distance.y,zDistance:c.config.distance.z,fov:c.config.fov,smoothing:c.config.smoothing||{position:.1,rotation:.1,fov:.1}})},[t,n,s]);return m.useEffect(()=>{const c=e.find(u=>u.config.mode===o?.control&&Ap(u.config.distance,kp(s)));a(c?c.id:null)},[o,s,e]),i.jsx("div",{className:"cp-panel",children:i.jsx("div",{className:"cp-grid",children:e.map(c=>i.jsxs("button",{className:`cp-item ${r===c.id?"active":""}`,onClick:()=>l(c),children:[i.jsx("div",{className:"cp-name",children:c.name}),i.jsx("div",{className:"cp-description",children:c.description})]},c.id))})})}function Rc({className:e="",style:t,children:n}={}){const[o,s]=m.useState("Settings"),r=()=>{switch(o){case"Settings":return i.jsx(Cp,{});case"Controller":return i.jsx(Tp,{});case"Presets":return i.jsx(Pc,{});case"Debug":return i.jsx(Bc,{});default:return null}};return i.jsxs("div",{className:`tabbed-panel ${e}`,style:t,children:[i.jsxs("div",{className:"panel-tabs",children:[i.jsx("button",{className:`panel-tab ${o==="Settings"?"active":""}`,onClick:()=>s("Settings"),children:"Settings"}),i.jsx("button",{className:`panel-tab ${o==="Controller"?"active":""}`,onClick:()=>s("Controller"),children:"Controller"}),i.jsx("button",{className:`panel-tab ${o==="Presets"?"active":""}`,onClick:()=>s("Presets"),children:"Presets"}),i.jsx("button",{className:`panel-tab ${o==="Debug"?"active":""}`,onClick:()=>s("Debug"),children:"Debug"})]}),i.jsxs("div",{className:"panel-tab-content",children:[r(),n]})]})}const Bp=[{value:"idle",label:"Idle"},{value:"walk",label:"Walk"},{value:"run",label:"Run"},{value:"jump",label:"Jump"},{value:"fall",label:"Fall"},{value:"dance",label:"Dance"},{value:"wave",label:"Wave"}];function Pp(){const{playAnimation:e,currentType:t,currentAnimation:n}=R.useAnimationBridge(),o=s=>{e(t,s)};return i.jsx("div",{className:"ac-panel",children:i.jsx("div",{className:"ac-grid",children:Bp.map(s=>i.jsx("button",{className:`ac-button ${s.value===n?"active":""}`,onClick:()=>o(s.value),title:s.label,children:s.label},s.value))})})}const Rp=[{key:"currentAnimation",label:"현재 애니메이션",format:"text",enabled:!0},{key:"animationType",label:"애니메이션 타입",format:"text",enabled:!0},{key:"isPlaying",label:"재생 상태",format:"text",enabled:!0},{key:"weight",label:"가중치",format:"number",enabled:!0},{key:"speed",label:"속도",format:"number",enabled:!0},{key:"blendDuration",label:"블렌드 시간",format:"number",enabled:!1},{key:"activeActions",label:"활성 액션",format:"number",enabled:!0},{key:"availableAnimations",label:"사용 가능 애니메이션",format:"array",enabled:!1},{key:"frameCount",label:"프레임 카운트",format:"number",enabled:!1},{key:"averageFrameTime",label:"평균 프레임 시간",format:"number",enabled:!1}];function Dc(){const{bridge:e,currentType:t}=R.useAnimationBridge(),[n,o]=m.useState({frameCount:0,averageFrameTime:0,lastUpdateTime:Date.now(),currentAnimation:"idle",animationType:"character",availableAnimations:[],isPlaying:!1,weight:1,speed:1,blendDuration:.3,activeActions:0});m.useEffect(()=>{if(!e)return;const a=()=>{const c=e.snapshot(t);if(!c)return;const u=e.getMetrics(t);o(f=>({...f,currentAnimation:c.currentAnimation,animationType:t,availableAnimations:c.availableAnimations,isPlaying:c.isPlaying,weight:c.weight,speed:c.speed,activeActions:c.metrics.activeAnimations,frameCount:u?.totalActions||0,averageFrameTime:u?.mixerTime||0,lastUpdateTime:Date.now()}))};return a(),e.subscribe((c,u)=>{u===t&&a()})},[e,t]);const s=(a,l,c=2)=>{if(a==null)return"N/A";switch(l){case"array":return Array.isArray(a)?`${a.length} animations`:String(a);case"boolean":return a?"Yes":"No";case"number":return typeof a=="number"?a.toFixed(c):String(a);default:return String(a)}},r=a=>{if(a in n)return n[a]};return i.jsx("div",{className:"ad-panel",children:i.jsx("div",{className:"ad-content",children:Rp.filter(a=>a.enabled).map(a=>i.jsxs("div",{className:"ad-item",children:[i.jsx("span",{className:"ad-label",children:a.label}),i.jsx("span",{className:"ad-value",children:s(r(a.key),a.format)})]},a.key))})})}const Dp=()=>i.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",children:i.jsx("path",{d:"M8 5v14l11-7z"})}),Fp=()=>i.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",children:i.jsx("path",{d:"M6 19h4V5H6v14zm8-14v14h4V5h-4z"})}),Lp=()=>i.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",children:i.jsx("path",{d:"M6 6h2v12H6zm3.5 6l8.5 6V6z"})}),zp=()=>i.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",children:i.jsx("path",{d:"M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"})});function Op(){const{bridge:e,playAnimation:t,stopAnimation:n,currentType:o,currentAnimation:s}=R.useAnimationBridge(),[r,a]=m.useState(!1),[l,c]=m.useState([]),[u,f]=m.useState(30);m.useEffect(()=>{if(!e)return;const p=()=>{const v=e.snapshot(o);v&&(a(v.isPlaying),c(v.availableAnimations))};return p(),e.subscribe((v,b)=>{b===o&&p()})},[e,o]);const d=()=>{r?n(o):t(o,s)};return i.jsxs("div",{className:"ap-panel",children:[i.jsxs("div",{className:"ap-controls",children:[i.jsx("select",{className:"ap-select",value:s,onChange:p=>t(o,p.target.value),children:l.map(p=>i.jsx("option",{value:p,children:p},p))}),i.jsxs("div",{className:"ap-buttons",children:[i.jsx("button",{className:"ap-btn","aria-label":"previous animation",children:i.jsx(Lp,{})}),i.jsx("button",{className:"ap-btn-primary",onClick:d,"aria-label":r?"pause":"play",children:r?i.jsx(Fp,{}):i.jsx(Dp,{})}),i.jsx("button",{className:"ap-btn","aria-label":"next animation",children:i.jsx(zp,{})})]})]}),i.jsxs("div",{className:"ap-timeline",children:[i.jsx("span",{className:"ap-time",children:"0:00"}),i.jsx("input",{type:"range",className:"ap-slider",min:"0",max:"100",value:u,onChange:p=>f(Number(p.target.value))}),i.jsx("span",{className:"ap-time",children:"1:30"})]})]})}function Fc({className:e="",style:t,children:n}={}){const[o,s]=m.useState("Player"),r=()=>{switch(o){case"Player":return i.jsx("div",{className:"panel-content-wrapper",children:i.jsx(Op,{})});case"Controller":return i.jsx("div",{className:"panel-content-wrapper",children:i.jsx(Pp,{})});case"Debug":return i.jsx("div",{className:"panel-content-wrapper",children:i.jsx(Dc,{})});default:return null}};return i.jsxs("div",{className:`tabbed-panel ${e}`,style:t,children:[i.jsxs("div",{className:"panel-tabs",children:[i.jsx("button",{className:`panel-tab ${o==="Player"?"active":""}`,onClick:()=>s("Player"),children:"Player"}),i.jsx("button",{className:`panel-tab ${o==="Controller"?"active":""}`,onClick:()=>s("Controller"),children:"Controller"}),i.jsx("button",{className:`panel-tab ${o==="Debug"?"active":""}`,onClick:()=>s("Debug"),children:"Debug"})]}),i.jsxs("div",{className:"panel-tab-content",children:[r(),n]})]})}const Ka=[{id:"slow",name:"Slow",maxSpeed:5,acceleration:8},{id:"normal",name:"Normal",maxSpeed:10,acceleration:15},{id:"fast",name:"Fast",maxSpeed:20,acceleration:25},{id:"sprint",name:"Sprint",maxSpeed:35,acceleration:40}],qa=[{id:"eco",name:"Eco",maxSpeed:15,acceleration:10},{id:"comfort",name:"Comfort",maxSpeed:25,acceleration:20},{id:"sport",name:"Sport",maxSpeed:40,acceleration:35},{id:"turbo",name:"Turbo",maxSpeed:60,acceleration:50}];function $p(e,t){const n=e??"bottom-left",o={position:"fixed",zIndex:t??1e4};return n.includes("top")&&(o.top=12),n.includes("bottom")&&(o.bottom=12),n.includes("left")&&(o.left=12),n.includes("right")&&(o.right=12),o}function Lc(e){const t=$p(e.position,e.zIndex),n=ge.useGaesupStore(p=>p.mode),o=ge.useGaesupStore(p=>p.setMode),s=ge.useGaesupStore(p=>p.setPhysics),r=n?.type==="vehicle"?"vehicle":"character",a=r==="vehicle"?qa:Ka,[l,c]=m.useState(r==="vehicle"?"comfort":"normal"),u=m.useCallback((p,h)=>{const b=(p==="vehicle"?qa:Ka).find(S=>S.id===h);if(b){if(p==="vehicle"){s({maxSpeed:b.maxSpeed,accelRatio:b.acceleration});return}s({walkSpeed:Math.max(1,b.maxSpeed*.5),runSpeed:b.maxSpeed,accelRatio:b.acceleration})}},[s]),f=m.useCallback(p=>{c(p),u(r,p),e.onPresetChange?.(p)},[u,r,e]),d=m.useCallback(p=>{const h=p.target.value;o({type:h});const v=h==="vehicle"?"comfort":"normal";c(v),u(h,v),e.onPresetChange?.(v)},[u,o,e]);return i.jsxs("div",{className:`mc-panel ${e.compact?"compact":""}`,style:t,children:[i.jsxs("div",{className:"mc-setting-row",children:[i.jsx("label",{htmlFor:"motion-type-select",className:"mc-label",children:"Motion Type"}),i.jsxs("select",{id:"motion-type-select",className:"mc-select",value:r,onChange:d,children:[i.jsx("option",{value:"character",children:"Character"}),i.jsx("option",{value:"vehicle",children:"Vehicle"})]})]}),i.jsxs("div",{className:"mc-setting-row",children:[i.jsx("label",{className:"mc-label",children:"Presets"}),i.jsx("div",{className:"mc-presets-grid",children:a.map(p=>i.jsx("button",{className:`mc-preset-btn ${p.id===l?"active":""}`,onClick:()=>f(p.id),title:`Max Speed: ${p.maxSpeed}, Accel: ${p.acceleration}`,children:p.name},p.id))})]})]})}const Qa=[{key:"motionType",label:"Motion Type",type:"text"},{key:"position",label:"Position",type:"vector3"},{key:"velocity",label:"Velocity",type:"vector3"},{key:"speed",label:"Speed",type:"number"},{key:"direction",label:"Direction",type:"vector3"},{key:"isGrounded",label:"Grounded",type:"text"},{key:"isMoving",label:"Moving",type:"text"},{key:"acceleration",label:"Acceleration",type:"number"},{key:"jumpForce",label:"Jump Force",type:"number"},{key:"maxSpeed",label:"Max Speed",type:"number"},{key:"totalDistance",label:"Total Distance",type:"number"},{key:"gameState",label:"Game State",type:"text"}];function Gp(e,t){const n=e??"top-right",o={position:"fixed",zIndex:t??1e4};return n.includes("top")&&(o.top=12),n.includes("bottom")&&(o.bottom=12),n.includes("left")&&(o.left=12),n.includes("right")&&(o.right=12),o}function zc(e){const t=e.embedded?{}:Gp(e.position,e.zIndex),n=ge.useGaesupStore(f=>f.mode),o=ge.useGaesupStore(f=>f.physics),{activeState:s,gameStates:r}=R.useStateSystem(),a=e.precision??2,l=e.customFields?[...Qa,...e.customFields]:Qa,c=(f,d,p=2)=>{if(d==null)return"N/A";switch(f.type){case"vector3":if(Array.isArray(d)&&d.length===3){const[h,v,b]=d;return`X:${h.toFixed(p)} Y:${v.toFixed(p)} Z:${b.toFixed(p)}`}if(typeof d=="object"&&d!==null&&"x"in d&&"y"in d&&"z"in d){const h=d;return`X:${h.x.toFixed(p)} Y:${h.y.toFixed(p)} Z:${h.z.toFixed(p)}`}return String(d);case"number":return typeof d=="number"?d.toFixed(p):String(d);default:return String(d)}},u=f=>{if(f.value!==void 0)return f.value;switch(f.key){case"motionType":return n?.type??"character";case"position":return s?.position?{x:s.position.x,y:s.position.y,z:s.position.z}:{x:0,y:0,z:0};case"velocity":return s?.velocity?{x:s.velocity.x,y:s.velocity.y,z:s.velocity.z}:{x:0,y:0,z:0};case"speed":return s?.velocity?s.velocity.length():0;case"direction":return s?.direction?{x:s.direction.x,y:s.direction.y,z:s.direction.z}:{x:0,y:0,z:0};case"isGrounded":return r?.isOnTheGround?"Yes":"No";case"isMoving":return r?.isMoving?"Yes":"No";case"acceleration":return o?.accelRatio??0;case"jumpForce":return o?.jumpSpeed??0;case"maxSpeed":return n?.type==="character"?o?.runSpeed??0:o?.maxSpeed??0;case"totalDistance":return 0;case"gameState":return r?.isRiding?"riding":r?.isOnTheGround?"ground":"air";default:return null}};return i.jsx("div",{className:`md-panel ${e.compact?"compact":""} ${e.theme?`theme-${e.theme}`:""}`,style:t,children:i.jsx("div",{className:"md-content",children:l.map(f=>i.jsxs("div",{className:"md-item",children:[i.jsx("span",{className:"md-label",children:f.label}),i.jsx("span",{className:"md-value",children:c(f,u(f),a)})]},f.key))})})}function Oc({className:e="",style:t,children:n}={}){const[o,s]=m.useState("Controller"),r=()=>{switch(o){case"Controller":return i.jsx("div",{className:"panel-content-wrapper",children:i.jsx(Lc,{})});case"Debug":return i.jsx("div",{className:"panel-content-wrapper",children:i.jsx(zc,{embedded:!0})});default:return null}};return i.jsxs("div",{className:`tabbed-panel ${e}`,style:t,children:[i.jsxs("div",{className:"panel-tabs",children:[i.jsx("button",{className:`panel-tab ${o==="Controller"?"active":""}`,onClick:()=>s("Controller"),children:"Controller"}),i.jsx("button",{className:`panel-tab ${o==="Debug"?"active":""}`,onClick:()=>s("Debug"),children:"Debug"})]}),i.jsxs("div",{className:"panel-tab-content",children:[r(),n]})]})}const Io=60,Eo=({data:e,color:t,max:n,warn:o})=>{const r=e.filter(c=>isFinite(c));if(r.length<2)return null;const a=Math.max(1,n),l=r.map((c,u)=>{const f=u/(r.length-1)*100,d=40-c/a*40;return`${u===0?"M":"L"}${f.toFixed(2)},${d.toFixed(2)}`}).join(" ");return i.jsx("div",{className:"perf-chart",children:i.jsxs("svg",{width:"100%",height:40,preserveAspectRatio:"none",viewBox:"0 0 100 40",children:[o!==void 0&&i.jsx("line",{x1:"0",y1:40-o/a*40,x2:"100",y2:40-o/a*40,stroke:"#facc15",strokeWidth:"0.5",strokeDasharray:"3,3",opacity:.5}),i.jsx("path",{d:l,fill:"none",stroke:t,strokeWidth:"2",strokeLinejoin:"round",strokeLinecap:"round"})]})})},ir=({value:e,max:t,color:n,label:o})=>{const s=t>0?Math.min(100,e/t*100):0;return i.jsxs("div",{style:{marginBottom:4},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:10,marginBottom:2},children:[i.jsx("span",{className:"perf-label",children:o}),i.jsx("span",{children:e.toFixed(1)})]}),i.jsx("div",{style:{height:4,background:"#1e293b",borderRadius:2,overflow:"hidden"},children:i.jsx("div",{style:{width:`${s}%`,height:"100%",background:n,borderRadius:2,transition:"width 0.3s"}})})]})};function $c({className:e="",style:t,children:n}={}){const o=ge.useGaesupStore(ls.useShallow(P=>P.performance)),[s,r]=m.useState({current:0,min:1/0,max:0,avg:0,p1Low:0,history:Array(Io).fill(0)}),[a,l]=m.useState({used:0,limit:0,history:Array(Io).fill(0)}),[c,u]=m.useState(0),[f,d]=m.useState(Array(Io).fill(0)),[p,h]=m.useState(Array(Io).fill(0)),v=m.useRef(0),b=m.useRef(0),S=m.useRef(0),x=m.useRef([]),_=m.useRef(0),g=m.useRef(null),y=m.useRef(0),w=m.useRef(0),j=m.useRef(0),N=m.useCallback(P=>{if(P.length<5)return 0;const L=[...P].filter(U=>U>0).sort((U,V)=>U-V),M=Math.max(1,Math.floor(L.length*.01));let F=0;for(let U=0;U<M;U++)F+=L[U]??0;return F/M},[]);m.useEffect(()=>{const P=window.performance.now();v.current=P,b.current=P,_.current=P;const L=M=>{const F=M-b.current;if(b.current=M,x.current.push(F),x.current.length>300&&x.current.shift(),y.current+=F,w.current++,w.current>=10){const U=y.current/w.current;u(U),h(V=>[...V.slice(1),U]),y.current=0,w.current=0}if(S.current++,M-v.current>=500){const U=S.current*1e3/(M-v.current),V=x.current.map(q=>q>0?1e3/q:0),Y=M-_.current>3e3;r(q=>{const X=[...q.history.slice(1),U],A=Y?Math.min(q.min===1/0?U:q.min,U):1/0,C=Y?Math.max(q.max,U):0,H=Y?X.filter(ee=>ee>0):[],K=H.length>0?H.reduce((ee,ne)=>ee+ne,0)/H.length:U,Q=Y?N(V):U;return{current:U,min:A,max:C,avg:K,p1Low:Q,history:X}});const Z=window.performance.memory;Z&&l(q=>{const X=Math.round(Z.usedJSHeapSize/1048576),A=Math.round(Z.jsHeapSizeLimit/1048576);return{used:X,limit:A,history:[...q.history.slice(1),X]}}),v.current=M,S.current=0}g.current=requestAnimationFrame(L)};return g.current=requestAnimationFrame(L),()=>{g.current&&cancelAnimationFrame(g.current)}},[N]),m.useEffect(()=>{const P=o.render.calls;P!==j.current&&(j.current=P,d(L=>[...L.slice(1),P]))},[o.render.calls]);const B=P=>P>=55?"#4ade80":P>=30?"#facc15":"#f87171",z=P=>P<=16.7?"#4ade80":P<=33.3?"#facc15":"#f87171",W=P=>P<=100?"#4ade80":P<=300?"#facc15":"#f87171",D=(P,L)=>{const M=L>0?P/L*100:0;return M<60?"#4ade80":M<80?"#facc15":"#f87171"},E=o.render.triangles,G=o.render.calls,T=o.engine.geometries,O=o.engine.textures;return i.jsxs("div",{className:`perf-panel ${e}`,style:t,children:[i.jsxs("div",{className:"perf-stat-group",children:[i.jsxs("div",{className:"perf-header",children:[i.jsx("h4",{className:"perf-title",children:"Frame Rate"}),i.jsxs("span",{className:"perf-current",style:{color:B(s.current)},children:[s.current.toFixed(0)," FPS"]})]}),i.jsxs("div",{className:"perf-details-grid",children:[i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Avg"}),s.avg.toFixed(1)]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Min"}),isFinite(s.min)?s.min.toFixed(1):"..."]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Max"}),s.max.toFixed(1)]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"1% Low"}),i.jsx("span",{style:{color:B(s.p1Low)},children:s.p1Low.toFixed(1)})]})]}),i.jsx(Eo,{data:s.history,color:B(s.current),max:90,warn:60})]}),i.jsxs("div",{className:"perf-stat-group",children:[i.jsxs("div",{className:"perf-header",children:[i.jsx("h4",{className:"perf-title",children:"Frame Time"}),i.jsxs("span",{className:"perf-current",style:{color:z(c)},children:[c.toFixed(2)," ms"]})]}),i.jsx(ir,{value:c,max:33.3,color:z(c),label:"Budget (16.7ms)"}),i.jsx(Eo,{data:p,color:z(c),max:33.3,warn:16.7})]}),i.jsxs("div",{className:"perf-stat-group",children:[i.jsxs("div",{className:"perf-header",children:[i.jsx("h4",{className:"perf-title",children:"GPU Pipeline"}),i.jsxs("span",{className:"perf-current",style:{color:W(G)},children:[G," calls"]})]}),i.jsxs("div",{className:"perf-details-grid",children:[i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Triangles"}),E>=1e6?(E/1e6).toFixed(2)+"M":E>=1e3?(E/1e3).toFixed(1)+"K":E]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Draw Calls"}),i.jsx("span",{style:{color:W(G)},children:G})]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Tri/Call"}),G>0?Math.round(E/G):0]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Points"}),o.render.points]})]}),i.jsx(Eo,{data:f,color:W(G),max:Math.max(200,...f)})]}),i.jsxs("div",{className:"perf-stat-group",children:[i.jsx("div",{className:"perf-header",children:i.jsx("h4",{className:"perf-title",children:"Resources"})}),i.jsxs("div",{className:"perf-details-grid",children:[i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Geometries"}),T]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Textures"}),O]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Programs"}),o.engine.programs]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Lines"}),o.render.lines]})]}),i.jsx(ir,{value:T,max:200,color:T>150?"#f87171":"#4ade80",label:"Geometry Budget"}),i.jsx(ir,{value:O,max:100,color:O>80?"#f87171":"#4ade80",label:"Texture Budget"})]}),i.jsxs("div",{className:"perf-stat-group",children:[i.jsxs("div",{className:"perf-header",children:[i.jsx("h4",{className:"perf-title",children:"Memory"}),i.jsxs("span",{className:"perf-current",style:{color:D(a.used,a.limit)},children:[a.used," MB"]})]}),i.jsxs("div",{className:"perf-details-grid",children:[i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Limit"}),a.limit," MB"]}),i.jsxs("div",{children:[i.jsx("span",{className:"perf-label",children:"Usage"}),a.limit>0?(a.used/a.limit*100).toFixed(0):0,"%"]})]}),i.jsx(Eo,{data:a.history,color:D(a.used,a.limit),max:a.limit||1})]}),n]})}const Gc=({className:e="",style:t,children:n})=>{const o=ge.useGaesupStore(l=>l.mode),s=ge.useGaesupStore(l=>l.setMode),r=l=>{s({type:l,controller:"keyboard",control:l==="airplane"||l==="vehicle"?"chase":"thirdPerson"})},a=[{type:"character",label:"Character",description:"Walk around as character"},{type:"vehicle",label:"Vehicle",description:"Drive a ground vehicle"},{type:"airplane",label:"Airplane",description:"Fly an airplane"}];return i.jsxs("div",{className:`vehicle-panel ${e}`,style:t,children:[i.jsx("div",{className:"vehicle-panel__modes",children:a.map(l=>i.jsxs("button",{className:`vehicle-panel__mode-button ${o.type===l.type?"vehicle-panel__mode-button--active":""}`,onClick:()=>r(l.type),children:[i.jsx("span",{className:"vehicle-panel__mode-label",children:l.label}),i.jsx("span",{className:"vehicle-panel__mode-description",children:l.description})]},l.type))}),i.jsxs("div",{className:"vehicle-panel__info",children:[i.jsxs("div",{className:"vehicle-panel__info-item",children:[i.jsx("span",{className:"vehicle-panel__info-label",children:"Current Mode:"}),i.jsx("span",{className:"vehicle-panel__info-value",children:o.type})]}),i.jsxs("div",{className:"vehicle-panel__info-item",children:[i.jsx("span",{className:"vehicle-panel__info-label",children:"Controls:"}),i.jsx("span",{className:"vehicle-panel__info-value",children:o.type==="airplane"?"WASD + Space/Shift":"WASD + Space"})]})]}),n]})},vi=[{id:"door-basic",label:"Door",category:"structure",fallbackKind:"door",defaultScale:1,defaultColor:"#8b5a2b",modelUrl:"gltf/props/door.glb"},{id:"window-basic",label:"Window",category:"structure",fallbackKind:"window",defaultScale:1,defaultColor:"#9fd3ff",modelUrl:"gltf/props/window.glb"},{id:"fence-basic",label:"Fence",category:"structure",fallbackKind:"fence",defaultScale:1,defaultColor:"#8f6a3d",modelUrl:"gltf/props/fence.glb"},{id:"lamp-basic",label:"Lamp",category:"utility",fallbackKind:"lamp",defaultScale:1,defaultColor:"#ffd166",modelUrl:"gltf/props/lamp.glb"},{id:"chair-basic",label:"Chair",category:"furniture",fallbackKind:"chair",defaultScale:1,defaultColor:"#a6784f",modelUrl:"gltf/props/chair.glb"},{id:"table-basic",label:"Table",category:"furniture",fallbackKind:"table",defaultScale:1,defaultColor:"#9b6b43",modelUrl:"gltf/props/table.glb"},{id:"bed-basic",label:"Bed",category:"furniture",fallbackKind:"bed",defaultScale:1,defaultColor:"#7aa2ff",modelUrl:"gltf/props/bed.glb"},{id:"storage-basic",label:"Storage",category:"furniture",fallbackKind:"storage",defaultScale:1,defaultColor:"#7c5c3e",modelUrl:"gltf/props/storage.glb"},{id:"mailbox-basic",label:"Mailbox",category:"utility",fallbackKind:"mailbox",defaultScale:1,defaultColor:"#d04f45",modelUrl:"gltf/props/mailbox.glb"},{id:"crafting-basic",label:"Crafting Station",category:"utility",fallbackKind:"crafting",defaultScale:1,defaultColor:"#b68553",modelUrl:"gltf/props/crafting.glb"},{id:"shop-stall-basic",label:"Shop Stall",category:"shop",fallbackKind:"shop",defaultScale:1,defaultColor:"#d88f45",modelUrl:"gltf/props/shop-stall.glb"}];function Ts(e){return vi.find(t=>t.id===e)}function ue({label:e,children:t}){return i.jsxs("div",{className:"editor-field-row",children:[i.jsx("span",{className:"editor-field-row__label",children:e}),i.jsx("div",{className:"editor-field-row__control",children:t})]})}function Lr({value:e,onChange:t}){return i.jsx("button",{type:"button",className:`editor-field-toggle ${e?"editor-field-toggle--on":""}`,onClick:()=>t(!e),children:e?"ON":"OFF"})}function no({value:e,onChange:t}){return i.jsxs("div",{className:"editor-field-color",children:[i.jsx("input",{type:"color",value:e,onChange:n=>t(n.target.value)}),i.jsx("span",{children:e})]})}function pa(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const Hp=e=>e.kind==="material"||e.kind==="wall"||e.kind==="tile",or=pa;function Ja(e,t,n){const{mapTextureUrl:o,textureUrl:s,materialParams:r,...a}=n??{};return{...a,id:e,color:t,material:"STANDARD",materialParams:{...r??{},color:t}}}function Yi(e){return`${e}-${Date.now()}`}function Ao(e){return e==="questStatus"?{id:Yi("condition-quest"),type:"condition",label:"Quest Active",condition:{type:"questStatus",questId:"welcome",status:"active"}}:e==="friendshipAtLeast"?{id:Yi("condition-friendship"),type:"condition",label:"Friendship Gate",condition:{type:"friendshipAtLeast",score:150}}:{id:Yi("condition-idle"),type:"condition",label:"Navigation Idle",condition:{type:"navigationIdle"}}}function Zi(e,t){return e==="speak"?{id:Yi("speak"),type:"action",label:"Speak",action:{type:"speak",text:"안녕?",duration:2}}:{id:Yi("wander"),type:"action",label:"Wander",action:{type:"wander",radius:t?.wanderRadius??4,speed:t?.speed??2.2}}}function Xi(e){return e.label?e.label:e.type==="start"?"Start":e.type==="condition"?`Condition: ${e.condition.type}`:`Action: ${e.action.type}`}function Wp(e){return e.type==="start"?"블루프린트 실행 시작점":e.type==="condition"?e.condition.type==="questStatus"?`quest ${e.condition.questId} is ${e.condition.status}`:e.condition.type==="friendshipAtLeast"?`friendship >= ${e.condition.score}`:e.condition.type:e.action.type==="moveToTarget"?`moveTo ${e.action.target.type}`:e.action.type==="speak"?e.action.text:e.action.type==="playAnimation"?e.action.animationId:e.action.type}function Ki(e,t){const n=e.nodes[e.nodes.length-1],o=n?{id:`${n.id}-${t.id}`,source:n.id,target:t.id,branch:"next"}:void 0;return{...e,nodes:[...e.nodes,t],edges:o?[...e.edges,o]:e.edges}}function ko(e,t,n){if(t.type!=="condition")return Ki(e,t);const o=Ki(e,t),s=Zi("wander",n),r=Zi("speak",n),a={...s,label:s.label??"True Path"},l={...r,label:r.label??"False Path"};return{...o,nodes:[...o.nodes,a,l],edges:[...o.edges,{id:`${t.id}-true-${a.id}`,source:t.id,target:a.id,branch:"true"},{id:`${t.id}-false-${l.id}`,source:t.id,target:l.id,branch:"false"}]}}function Up(e,t){const n=e.nodes.find(o=>o.id===t);return!n||n.type==="start"?e:{...e,nodes:e.nodes.filter(o=>o.id!==t),edges:e.edges.filter(o=>o.source!==t&&o.target!==t)}}function Vp(e){return{...e,nodes:[{id:"start",type:"start",label:"Start"}],edges:[]}}function Yp(e,t){return{...e,id:`npc-custom-${t}-${Date.now()}`,name:`${e.name} Custom`,description:e.description?`${e.description} Customized for ${t}.`:`Customized for ${t}.`,nodes:e.nodes.map(n=>({...n})),edges:e.edges.map(n=>({...n}))}}function Zp(e,t){const n=new Map(e.nodes.map(s=>[s.id,s])),o=e.edges.filter(s=>s.source===t);return o.length===0?"다음 없음":o.map(s=>{const r=n.get(s.target);return`${s.branch??"next"} -> ${r?Xi(r):s.target}`}).join(" · ")}function Ee(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,o;n<e.length;n++)(o=Ee(e[n]))!==""&&(t+=(t&&" ")+o);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Xp={value:()=>{}};function Is(){for(var e=0,t=arguments.length,n={},o;e<t;++e){if(!(o=arguments[e]+"")||o in n||/[\s.]/.test(o))throw new Error("illegal type: "+o);n[o]=[]}return new es(n)}function es(e){this._=e}function Kp(e,t){return e.trim().split(/^|\s+/).map(function(n){var o="",s=n.indexOf(".");if(s>=0&&(o=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:o}})}es.prototype=Is.prototype={constructor:es,on:function(e,t){var n=this._,o=Kp(e+"",n),s,r=-1,a=o.length;if(arguments.length<2){for(;++r<a;)if((s=(e=o[r]).type)&&(s=qp(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++r<a;)if(s=(e=o[r]).type)n[s]=el(n[s],e.name,t);else if(t==null)for(s in n)n[s]=el(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new es(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),o=0,s,r;o<s;++o)n[o]=arguments[o+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(r=this._[e],o=0,s=r.length;o<s;++o)r[o].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var o=this._[e],s=0,r=o.length;s<r;++s)o[s].value.apply(t,n)}};function qp(e,t){for(var n=0,o=e.length,s;n<o;++n)if((s=e[n]).name===t)return s.value}function el(e,t,n){for(var o=0,s=e.length;o<s;++o)if(e[o].name===t){e[o]=Xp,e=e.slice(0,o).concat(e.slice(o+1));break}return n!=null&&e.push({name:t,value:n}),e}var zr="http://www.w3.org/1999/xhtml";const tl={svg:"http://www.w3.org/2000/svg",xhtml:zr,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Es(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),tl.hasOwnProperty(t)?{space:tl[t],local:e}:e}function Qp(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===zr&&t.documentElement.namespaceURI===zr?t.createElement(e):t.createElementNS(n,e)}}function Jp(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Hc(e){var t=Es(e);return(t.local?Jp:Qp)(t)}function eh(){}function ha(e){return e==null?eh:function(){return this.querySelector(e)}}function th(e){typeof e!="function"&&(e=ha(e));for(var t=this._groups,n=t.length,o=new Array(n),s=0;s<n;++s)for(var r=t[s],a=r.length,l=o[s]=new Array(a),c,u,f=0;f<a;++f)(c=r[f])&&(u=e.call(c,c.__data__,f,r))&&("__data__"in c&&(u.__data__=c.__data__),l[f]=u);return new Ye(o,this._parents)}function nh(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function ih(){return[]}function Wc(e){return e==null?ih:function(){return this.querySelectorAll(e)}}function oh(e){return function(){return nh(e.apply(this,arguments))}}function sh(e){typeof e=="function"?e=oh(e):e=Wc(e);for(var t=this._groups,n=t.length,o=[],s=[],r=0;r<n;++r)for(var a=t[r],l=a.length,c,u=0;u<l;++u)(c=a[u])&&(o.push(e.call(c,c.__data__,u,a)),s.push(c));return new Ye(o,s)}function Uc(e){return function(){return this.matches(e)}}function Vc(e){return function(t){return t.matches(e)}}var rh=Array.prototype.find;function ah(e){return function(){return rh.call(this.children,e)}}function lh(){return this.firstElementChild}function ch(e){return this.select(e==null?lh:ah(typeof e=="function"?e:Vc(e)))}var uh=Array.prototype.filter;function dh(){return Array.from(this.children)}function fh(e){return function(){return uh.call(this.children,e)}}function ph(e){return this.selectAll(e==null?dh:fh(typeof e=="function"?e:Vc(e)))}function hh(e){typeof e!="function"&&(e=Uc(e));for(var t=this._groups,n=t.length,o=new Array(n),s=0;s<n;++s)for(var r=t[s],a=r.length,l=o[s]=[],c,u=0;u<a;++u)(c=r[u])&&e.call(c,c.__data__,u,r)&&l.push(c);return new Ye(o,this._parents)}function Yc(e){return new Array(e.length)}function mh(){return new Ye(this._enter||this._groups.map(Yc),this._parents)}function cs(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}cs.prototype={constructor:cs,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function gh(e){return function(){return e}}function bh(e,t,n,o,s,r){for(var a=0,l,c=t.length,u=r.length;a<u;++a)(l=t[a])?(l.__data__=r[a],o[a]=l):n[a]=new cs(e,r[a]);for(;a<c;++a)(l=t[a])&&(s[a]=l)}function xh(e,t,n,o,s,r,a){var l,c,u=new Map,f=t.length,d=r.length,p=new Array(f),h;for(l=0;l<f;++l)(c=t[l])&&(p[l]=h=a.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<d;++l)h=a.call(e,r[l],l,r)+"",(c=u.get(h))?(o[l]=c,c.__data__=r[l],u.delete(h)):n[l]=new cs(e,r[l]);for(l=0;l<f;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function yh(e){return e.__data__}function vh(e,t){if(!arguments.length)return Array.from(this,yh);var n=t?xh:bh,o=this._parents,s=this._groups;typeof e!="function"&&(e=gh(e));for(var r=s.length,a=new Array(r),l=new Array(r),c=new Array(r),u=0;u<r;++u){var f=o[u],d=s[u],p=d.length,h=wh(e.call(f,f&&f.__data__,u,o)),v=h.length,b=l[u]=new Array(v),S=a[u]=new Array(v),x=c[u]=new Array(p);n(f,d,b,S,x,h,t);for(var _=0,g=0,y,w;_<v;++_)if(y=b[_]){for(_>=g&&(g=_+1);!(w=S[g])&&++g<v;);y._next=w||null}}return a=new Ye(a,o),a._enter=l,a._exit=c,a}function wh(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Sh(){return new Ye(this._exit||this._groups.map(Yc),this._parents)}function _h(e,t,n){var o=this.enter(),s=this,r=this.exit();return typeof e=="function"?(o=e(o),o&&(o=o.selection())):o=o.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?r.remove():n(r),o&&s?o.merge(s).order():s}function jh(e){for(var t=e.selection?e.selection():e,n=this._groups,o=t._groups,s=n.length,r=o.length,a=Math.min(s,r),l=new Array(s),c=0;c<a;++c)for(var u=n[c],f=o[c],d=u.length,p=l[c]=new Array(d),h,v=0;v<d;++v)(h=u[v]||f[v])&&(p[v]=h);for(;c<s;++c)l[c]=n[c];return new Ye(l,this._parents)}function Mh(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var o=e[t],s=o.length-1,r=o[s],a;--s>=0;)(a=o[s])&&(r&&a.compareDocumentPosition(r)^4&&r.parentNode.insertBefore(a,r),r=a);return this}function Ch(e){e||(e=Nh);function t(d,p){return d&&p?e(d.__data__,p.__data__):!d-!p}for(var n=this._groups,o=n.length,s=new Array(o),r=0;r<o;++r){for(var a=n[r],l=a.length,c=s[r]=new Array(l),u,f=0;f<l;++f)(u=a[f])&&(c[f]=u);c.sort(t)}return new Ye(s,this._parents).order()}function Nh(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Th(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Ih(){return Array.from(this)}function Eh(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var o=e[t],s=0,r=o.length;s<r;++s){var a=o[s];if(a)return a}return null}function Ah(){let e=0;for(const t of this)++e;return e}function kh(){return!this.node()}function Bh(e){for(var t=this._groups,n=0,o=t.length;n<o;++n)for(var s=t[n],r=0,a=s.length,l;r<a;++r)(l=s[r])&&e.call(l,l.__data__,r,s);return this}function Ph(e){return function(){this.removeAttribute(e)}}function Rh(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Dh(e,t){return function(){this.setAttribute(e,t)}}function Fh(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function Lh(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function zh(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function Oh(e,t){var n=Es(e);if(arguments.length<2){var o=this.node();return n.local?o.getAttributeNS(n.space,n.local):o.getAttribute(n)}return this.each((t==null?n.local?Rh:Ph:typeof t=="function"?n.local?zh:Lh:n.local?Fh:Dh)(n,t))}function Zc(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function $h(e){return function(){this.style.removeProperty(e)}}function Gh(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Hh(e,t,n){return function(){var o=t.apply(this,arguments);o==null?this.style.removeProperty(e):this.style.setProperty(e,o,n)}}function Wh(e,t,n){return arguments.length>1?this.each((t==null?$h:typeof t=="function"?Hh:Gh)(e,t,n??"")):wi(this.node(),e)}function wi(e,t){return e.style.getPropertyValue(t)||Zc(e).getComputedStyle(e,null).getPropertyValue(t)}function Uh(e){return function(){delete this[e]}}function Vh(e,t){return function(){this[e]=t}}function Yh(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Zh(e,t){return arguments.length>1?this.each((t==null?Uh:typeof t=="function"?Yh:Vh)(e,t)):this.node()[e]}function Xc(e){return e.trim().split(/^|\s+/)}function ma(e){return e.classList||new Kc(e)}function Kc(e){this._node=e,this._names=Xc(e.getAttribute("class")||"")}Kc.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function qc(e,t){for(var n=ma(e),o=-1,s=t.length;++o<s;)n.add(t[o])}function Qc(e,t){for(var n=ma(e),o=-1,s=t.length;++o<s;)n.remove(t[o])}function Xh(e){return function(){qc(this,e)}}function Kh(e){return function(){Qc(this,e)}}function qh(e,t){return function(){(t.apply(this,arguments)?qc:Qc)(this,e)}}function Qh(e,t){var n=Xc(e+"");if(arguments.length<2){for(var o=ma(this.node()),s=-1,r=n.length;++s<r;)if(!o.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?qh:t?Xh:Kh)(n,t))}function Jh(){this.textContent=""}function em(e){return function(){this.textContent=e}}function tm(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function nm(e){return arguments.length?this.each(e==null?Jh:(typeof e=="function"?tm:em)(e)):this.node().textContent}function im(){this.innerHTML=""}function om(e){return function(){this.innerHTML=e}}function sm(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function rm(e){return arguments.length?this.each(e==null?im:(typeof e=="function"?sm:om)(e)):this.node().innerHTML}function am(){this.nextSibling&&this.parentNode.appendChild(this)}function lm(){return this.each(am)}function cm(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function um(){return this.each(cm)}function dm(e){var t=typeof e=="function"?e:Hc(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function fm(){return null}function pm(e,t){var n=typeof e=="function"?e:Hc(e),o=t==null?fm:typeof t=="function"?t:ha(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),o.apply(this,arguments)||null)})}function hm(){var e=this.parentNode;e&&e.removeChild(this)}function mm(){return this.each(hm)}function gm(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function bm(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function xm(e){return this.select(e?bm:gm)}function ym(e){return arguments.length?this.property("__data__",e):this.node().__data__}function vm(e){return function(t){e.call(this,t,this.__data__)}}function wm(e){return e.trim().split(/^|\s+/).map(function(t){var n="",o=t.indexOf(".");return o>=0&&(n=t.slice(o+1),t=t.slice(0,o)),{type:t,name:n}})}function Sm(e){return function(){var t=this.__on;if(t){for(var n=0,o=-1,s=t.length,r;n<s;++n)r=t[n],(!e.type||r.type===e.type)&&r.name===e.name?this.removeEventListener(r.type,r.listener,r.options):t[++o]=r;++o?t.length=o:delete this.__on}}}function _m(e,t,n){return function(){var o=this.__on,s,r=vm(t);if(o){for(var a=0,l=o.length;a<l;++a)if((s=o[a]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=r,s.options=n),s.value=t;return}}this.addEventListener(e.type,r,n),s={type:e.type,name:e.name,value:t,listener:r,options:n},o?o.push(s):this.__on=[s]}}function jm(e,t,n){var o=wm(e+""),s,r=o.length,a;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,f;c<u;++c)for(s=0,f=l[c];s<r;++s)if((a=o[s]).type===f.type&&a.name===f.name)return f.value}return}for(l=t?_m:Sm,s=0;s<r;++s)this.each(l(o[s],t,n));return this}function Jc(e,t,n){var o=Zc(e),s=o.CustomEvent;typeof s=="function"?s=new s(t,n):(s=o.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function Mm(e,t){return function(){return Jc(this,e,t)}}function Cm(e,t){return function(){return Jc(this,e,t.apply(this,arguments))}}function Nm(e,t){return this.each((typeof t=="function"?Cm:Mm)(e,t))}function*Tm(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var o=e[t],s=0,r=o.length,a;s<r;++s)(a=o[s])&&(yield a)}var eu=[null];function Ye(e,t){this._groups=e,this._parents=t}function xo(){return new Ye([[document.documentElement]],eu)}function Im(){return this}Ye.prototype=xo.prototype={constructor:Ye,select:th,selectAll:sh,selectChild:ch,selectChildren:ph,filter:hh,data:vh,enter:mh,exit:Sh,join:_h,merge:jh,selection:Im,order:Mh,sort:Ch,call:Th,nodes:Ih,node:Eh,size:Ah,empty:kh,each:Bh,attr:Oh,style:Wh,property:Zh,classed:Qh,text:nm,html:rm,raise:lm,lower:um,append:dm,insert:pm,remove:mm,clone:xm,datum:ym,on:jm,dispatch:Nm,[Symbol.iterator]:Tm};function Ve(e){return typeof e=="string"?new Ye([[document.querySelector(e)]],[document.documentElement]):new Ye([[e]],eu)}function Em(e){let t;for(;t=e.sourceEvent;)e=t;return e}function st(e,t){if(e=Em(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var o=n.createSVGPoint();return o.x=e.clientX,o.y=e.clientY,o=o.matrixTransform(t.getScreenCTM().inverse()),[o.x,o.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const Am={passive:!1},io={capture:!0,passive:!1};function sr(e){e.stopImmediatePropagation()}function xi(e){e.preventDefault(),e.stopImmediatePropagation()}function tu(e){var t=e.document.documentElement,n=Ve(e).on("dragstart.drag",xi,io);"onselectstart"in t?n.on("selectstart.drag",xi,io):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function nu(e,t){var n=e.document.documentElement,o=Ve(e).on("dragstart.drag",null);t&&(o.on("click.drag",xi,io),setTimeout(function(){o.on("click.drag",null)},0)),"onselectstart"in n?o.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const Bo=e=>()=>e;function Or(e,{sourceEvent:t,subject:n,target:o,identifier:s,active:r,x:a,y:l,dx:c,dy:u,dispatch:f}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:o,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:r,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:f}})}Or.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function km(e){return!e.ctrlKey&&!e.button}function Bm(){return this.parentNode}function Pm(e,t){return t??{x:e.x,y:e.y}}function Rm(){return navigator.maxTouchPoints||"ontouchstart"in this}function iu(){var e=km,t=Bm,n=Pm,o=Rm,s={},r=Is("start","drag","end"),a=0,l,c,u,f,d=0;function p(y){y.on("mousedown.drag",h).filter(o).on("touchstart.drag",S).on("touchmove.drag",x,Am).on("touchend.drag touchcancel.drag",_).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(y,w){if(!(f||!e.call(this,y,w))){var j=g(this,t.call(this,y,w),y,w,"mouse");j&&(Ve(y.view).on("mousemove.drag",v,io).on("mouseup.drag",b,io),tu(y.view),sr(y),u=!1,l=y.clientX,c=y.clientY,j("start",y))}}function v(y){if(xi(y),!u){var w=y.clientX-l,j=y.clientY-c;u=w*w+j*j>d}s.mouse("drag",y)}function b(y){Ve(y.view).on("mousemove.drag mouseup.drag",null),nu(y.view,u),xi(y),s.mouse("end",y)}function S(y,w){if(e.call(this,y,w)){var j=y.changedTouches,N=t.call(this,y,w),B=j.length,z,W;for(z=0;z<B;++z)(W=g(this,N,y,w,j[z].identifier,j[z]))&&(sr(y),W("start",y,j[z]))}}function x(y){var w=y.changedTouches,j=w.length,N,B;for(N=0;N<j;++N)(B=s[w[N].identifier])&&(xi(y),B("drag",y,w[N]))}function _(y){var w=y.changedTouches,j=w.length,N,B;for(f&&clearTimeout(f),f=setTimeout(function(){f=null},500),N=0;N<j;++N)(B=s[w[N].identifier])&&(sr(y),B("end",y,w[N]))}function g(y,w,j,N,B,z){var W=r.copy(),D=st(z||j,w),E,G,T;if((T=n.call(y,new Or("beforestart",{sourceEvent:j,target:p,identifier:B,active:a,x:D[0],y:D[1],dx:0,dy:0,dispatch:W}),N))!=null)return E=T.x-D[0]||0,G=T.y-D[1]||0,function O(P,L,M){var F=D,U;switch(P){case"start":s[B]=O,U=a++;break;case"end":delete s[B],--a;case"drag":D=st(M||L,w),U=a;break}W.call(P,y,new Or(P,{sourceEvent:L,subject:T,target:p,identifier:B,active:U,x:D[0]+E,y:D[1]+G,dx:D[0]-F[0],dy:D[1]-F[1],dispatch:W}),N)}}return p.filter=function(y){return arguments.length?(e=typeof y=="function"?y:Bo(!!y),p):e},p.container=function(y){return arguments.length?(t=typeof y=="function"?y:Bo(y),p):t},p.subject=function(y){return arguments.length?(n=typeof y=="function"?y:Bo(y),p):n},p.touchable=function(y){return arguments.length?(o=typeof y=="function"?y:Bo(!!y),p):o},p.on=function(){var y=r.on.apply(r,arguments);return y===r?p:y},p.clickDistance=function(y){return arguments.length?(d=(y=+y)*y,p):Math.sqrt(d)},p}function ga(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function ou(e,t){var n=Object.create(e.prototype);for(var o in t)n[o]=t[o];return n}function yo(){}var oo=.7,us=1/oo,yi="\\s*([+-]?\\d+)\\s*",so="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",It="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Dm=/^#([0-9a-f]{3,8})$/,Fm=new RegExp(`^rgb\\(${yi},${yi},${yi}\\)$`),Lm=new RegExp(`^rgb\\(${It},${It},${It}\\)$`),zm=new RegExp(`^rgba\\(${yi},${yi},${yi},${so}\\)$`),Om=new RegExp(`^rgba\\(${It},${It},${It},${so}\\)$`),$m=new RegExp(`^hsl\\(${so},${It},${It}\\)$`),Gm=new RegExp(`^hsla\\(${so},${It},${It},${so}\\)$`),nl={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};ga(yo,ii,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:il,formatHex:il,formatHex8:Hm,formatHsl:Wm,formatRgb:ol,toString:ol});function il(){return this.rgb().formatHex()}function Hm(){return this.rgb().formatHex8()}function Wm(){return su(this).formatHsl()}function ol(){return this.rgb().formatRgb()}function ii(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=Dm.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?sl(t):n===3?new $e(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Po(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Po(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Fm.exec(e))?new $e(t[1],t[2],t[3],1):(t=Lm.exec(e))?new $e(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=zm.exec(e))?Po(t[1],t[2],t[3],t[4]):(t=Om.exec(e))?Po(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=$m.exec(e))?ll(t[1],t[2]/100,t[3]/100,1):(t=Gm.exec(e))?ll(t[1],t[2]/100,t[3]/100,t[4]):nl.hasOwnProperty(e)?sl(nl[e]):e==="transparent"?new $e(NaN,NaN,NaN,0):null}function sl(e){return new $e(e>>16&255,e>>8&255,e&255,1)}function Po(e,t,n,o){return o<=0&&(e=t=n=NaN),new $e(e,t,n,o)}function Um(e){return e instanceof yo||(e=ii(e)),e?(e=e.rgb(),new $e(e.r,e.g,e.b,e.opacity)):new $e}function $r(e,t,n,o){return arguments.length===1?Um(e):new $e(e,t,n,o??1)}function $e(e,t,n,o){this.r=+e,this.g=+t,this.b=+n,this.opacity=+o}ga($e,$r,ou(yo,{brighter(e){return e=e==null?us:Math.pow(us,e),new $e(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?oo:Math.pow(oo,e),new $e(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new $e(ti(this.r),ti(this.g),ti(this.b),ds(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:rl,formatHex:rl,formatHex8:Vm,formatRgb:al,toString:al}));function rl(){return`#${ei(this.r)}${ei(this.g)}${ei(this.b)}`}function Vm(){return`#${ei(this.r)}${ei(this.g)}${ei(this.b)}${ei((isNaN(this.opacity)?1:this.opacity)*255)}`}function al(){const e=ds(this.opacity);return`${e===1?"rgb(":"rgba("}${ti(this.r)}, ${ti(this.g)}, ${ti(this.b)}${e===1?")":`, ${e})`}`}function ds(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function ti(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function ei(e){return e=ti(e),(e<16?"0":"")+e.toString(16)}function ll(e,t,n,o){return o<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new lt(e,t,n,o)}function su(e){if(e instanceof lt)return new lt(e.h,e.s,e.l,e.opacity);if(e instanceof yo||(e=ii(e)),!e)return new lt;if(e instanceof lt)return e;e=e.rgb();var t=e.r/255,n=e.g/255,o=e.b/255,s=Math.min(t,n,o),r=Math.max(t,n,o),a=NaN,l=r-s,c=(r+s)/2;return l?(t===r?a=(n-o)/l+(n<o)*6:n===r?a=(o-t)/l+2:a=(t-n)/l+4,l/=c<.5?r+s:2-r-s,a*=60):l=c>0&&c<1?0:a,new lt(a,l,c,e.opacity)}function Ym(e,t,n,o){return arguments.length===1?su(e):new lt(e,t,n,o??1)}function lt(e,t,n,o){this.h=+e,this.s=+t,this.l=+n,this.opacity=+o}ga(lt,Ym,ou(yo,{brighter(e){return e=e==null?us:Math.pow(us,e),new lt(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?oo:Math.pow(oo,e),new lt(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,o=n+(n<.5?n:1-n)*t,s=2*n-o;return new $e(rr(e>=240?e-240:e+120,s,o),rr(e,s,o),rr(e<120?e+240:e-120,s,o),this.opacity)},clamp(){return new lt(cl(this.h),Ro(this.s),Ro(this.l),ds(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=ds(this.opacity);return`${e===1?"hsl(":"hsla("}${cl(this.h)}, ${Ro(this.s)*100}%, ${Ro(this.l)*100}%${e===1?")":`, ${e})`}`}}));function cl(e){return e=(e||0)%360,e<0?e+360:e}function Ro(e){return Math.max(0,Math.min(1,e||0))}function rr(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const ba=e=>()=>e;function Zm(e,t){return function(n){return e+n*t}}function Xm(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(o){return Math.pow(e+o*t,n)}}function Km(e){return(e=+e)==1?ru:function(t,n){return n-t?Xm(t,n,e):ba(isNaN(t)?n:t)}}function ru(e,t){var n=t-e;return n?Zm(e,n):ba(isNaN(e)?t:e)}const fs=function e(t){var n=Km(t);function o(s,r){var a=n((s=$r(s)).r,(r=$r(r)).r),l=n(s.g,r.g),c=n(s.b,r.b),u=ru(s.opacity,r.opacity);return function(f){return s.r=a(f),s.g=l(f),s.b=c(f),s.opacity=u(f),s+""}}return o.gamma=e,o}(1);function qm(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,o=t.slice(),s;return function(r){for(s=0;s<n;++s)o[s]=e[s]*(1-r)+t[s]*r;return o}}function Qm(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Jm(e,t){var n=t?t.length:0,o=e?Math.min(n,e.length):0,s=new Array(o),r=new Array(n),a;for(a=0;a<o;++a)s[a]=qi(e[a],t[a]);for(;a<n;++a)r[a]=t[a];return function(l){for(a=0;a<o;++a)r[a]=s[a](l);return r}}function eg(e,t){var n=new Date;return e=+e,t=+t,function(o){return n.setTime(e*(1-o)+t*o),n}}function Tt(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function tg(e,t){var n={},o={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=qi(e[s],t[s]):o[s]=t[s];return function(r){for(s in n)o[s]=n[s](r);return o}}var Gr=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,ar=new RegExp(Gr.source,"g");function ng(e){return function(){return e}}function ig(e){return function(t){return e(t)+""}}function au(e,t){var n=Gr.lastIndex=ar.lastIndex=0,o,s,r,a=-1,l=[],c=[];for(e=e+"",t=t+"";(o=Gr.exec(e))&&(s=ar.exec(t));)(r=s.index)>n&&(r=t.slice(n,r),l[a]?l[a]+=r:l[++a]=r),(o=o[0])===(s=s[0])?l[a]?l[a]+=s:l[++a]=s:(l[++a]=null,c.push({i:a,x:Tt(o,s)})),n=ar.lastIndex;return n<t.length&&(r=t.slice(n),l[a]?l[a]+=r:l[++a]=r),l.length<2?c[0]?ig(c[0].x):ng(t):(t=c.length,function(u){for(var f=0,d;f<t;++f)l[(d=c[f]).i]=d.x(u);return l.join("")})}function qi(e,t){var n=typeof t,o;return t==null||n==="boolean"?ba(t):(n==="number"?Tt:n==="string"?(o=ii(t))?(t=o,fs):au:t instanceof ii?fs:t instanceof Date?eg:Qm(t)?qm:Array.isArray(t)?Jm:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?tg:Tt)(e,t)}var ul=180/Math.PI,Hr={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function lu(e,t,n,o,s,r){var a,l,c;return(a=Math.sqrt(e*e+t*t))&&(e/=a,t/=a),(c=e*n+t*o)&&(n-=e*c,o-=t*c),(l=Math.sqrt(n*n+o*o))&&(n/=l,o/=l,c/=l),e*o<t*n&&(e=-e,t=-t,c=-c,a=-a),{translateX:s,translateY:r,rotate:Math.atan2(t,e)*ul,skewX:Math.atan(c)*ul,scaleX:a,scaleY:l}}var Do;function og(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Hr:lu(t.a,t.b,t.c,t.d,t.e,t.f)}function sg(e){return e==null||(Do||(Do=document.createElementNS("http://www.w3.org/2000/svg","g")),Do.setAttribute("transform",e),!(e=Do.transform.baseVal.consolidate()))?Hr:(e=e.matrix,lu(e.a,e.b,e.c,e.d,e.e,e.f))}function cu(e,t,n,o){function s(u){return u.length?u.pop()+" ":""}function r(u,f,d,p,h,v){if(u!==d||f!==p){var b=h.push("translate(",null,t,null,n);v.push({i:b-4,x:Tt(u,d)},{i:b-2,x:Tt(f,p)})}else(d||p)&&h.push("translate("+d+t+p+n)}function a(u,f,d,p){u!==f?(u-f>180?f+=360:f-u>180&&(u+=360),p.push({i:d.push(s(d)+"rotate(",null,o)-2,x:Tt(u,f)})):f&&d.push(s(d)+"rotate("+f+o)}function l(u,f,d,p){u!==f?p.push({i:d.push(s(d)+"skewX(",null,o)-2,x:Tt(u,f)}):f&&d.push(s(d)+"skewX("+f+o)}function c(u,f,d,p,h,v){if(u!==d||f!==p){var b=h.push(s(h)+"scale(",null,",",null,")");v.push({i:b-4,x:Tt(u,d)},{i:b-2,x:Tt(f,p)})}else(d!==1||p!==1)&&h.push(s(h)+"scale("+d+","+p+")")}return function(u,f){var d=[],p=[];return u=e(u),f=e(f),r(u.translateX,u.translateY,f.translateX,f.translateY,d,p),a(u.rotate,f.rotate,d,p),l(u.skewX,f.skewX,d,p),c(u.scaleX,u.scaleY,f.scaleX,f.scaleY,d,p),u=f=null,function(h){for(var v=-1,b=p.length,S;++v<b;)d[(S=p[v]).i]=S.x(h);return d.join("")}}}var rg=cu(og,"px, ","px)","deg)"),ag=cu(sg,", ",")",")"),lg=1e-12;function dl(e){return((e=Math.exp(e))+1/e)/2}function cg(e){return((e=Math.exp(e))-1/e)/2}function ug(e){return((e=Math.exp(2*e))-1)/(e+1)}const ts=function e(t,n,o){function s(r,a){var l=r[0],c=r[1],u=r[2],f=a[0],d=a[1],p=a[2],h=f-l,v=d-c,b=h*h+v*v,S,x;if(b<lg)x=Math.log(p/u)/t,S=function(N){return[l+N*h,c+N*v,u*Math.exp(t*N*x)]};else{var _=Math.sqrt(b),g=(p*p-u*u+o*b)/(2*u*n*_),y=(p*p-u*u-o*b)/(2*p*n*_),w=Math.log(Math.sqrt(g*g+1)-g),j=Math.log(Math.sqrt(y*y+1)-y);x=(j-w)/t,S=function(N){var B=N*x,z=dl(w),W=u/(n*_)*(z*ug(t*B+w)-cg(w));return[l+W*h,c+W*v,u*z/dl(t*B+w)]}}return S.duration=x*1e3*t/Math.SQRT2,S}return s.rho=function(r){var a=Math.max(.001,+r),l=a*a,c=l*l;return e(a,l,c)},s}(Math.SQRT2,2,4);var Si=0,Wi=0,Fi=0,uu=1e3,ps,Ui,hs=0,oi=0,As=0,ro=typeof performance=="object"&&performance.now?performance:Date,du=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function xa(){return oi||(du(dg),oi=ro.now()+As)}function dg(){oi=0}function ms(){this._call=this._time=this._next=null}ms.prototype=fu.prototype={constructor:ms,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?xa():+n)+(t==null?0:+t),!this._next&&Ui!==this&&(Ui?Ui._next=this:ps=this,Ui=this),this._call=e,this._time=n,Wr()},stop:function(){this._call&&(this._call=null,this._time=1/0,Wr())}};function fu(e,t,n){var o=new ms;return o.restart(e,t,n),o}function fg(){xa(),++Si;for(var e=ps,t;e;)(t=oi-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Si}function fl(){oi=(hs=ro.now())+As,Si=Wi=0;try{fg()}finally{Si=0,hg(),oi=0}}function pg(){var e=ro.now(),t=e-hs;t>uu&&(As-=t,hs=e)}function hg(){for(var e,t=ps,n,o=1/0;t;)t._call?(o>t._time&&(o=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:ps=n);Ui=e,Wr(o)}function Wr(e){if(!Si){Wi&&(Wi=clearTimeout(Wi));var t=e-oi;t>24?(e<1/0&&(Wi=setTimeout(fl,e-ro.now()-As)),Fi&&(Fi=clearInterval(Fi))):(Fi||(hs=ro.now(),Fi=setInterval(pg,uu)),Si=1,du(fl))}}function pl(e,t,n){var o=new ms;return t=t==null?0:+t,o.restart(s=>{o.stop(),e(s+t)},t,n),o}var mg=Is("start","end","cancel","interrupt"),gg=[],pu=0,hl=1,Ur=2,ns=3,ml=4,Vr=5,is=6;function ks(e,t,n,o,s,r){var a=e.__transition;if(!a)e.__transition={};else if(n in a)return;bg(e,n,{name:t,index:o,group:s,on:mg,tween:gg,time:r.time,delay:r.delay,duration:r.duration,ease:r.ease,timer:null,state:pu})}function ya(e,t){var n=ht(e,t);if(n.state>pu)throw new Error("too late; already scheduled");return n}function At(e,t){var n=ht(e,t);if(n.state>ns)throw new Error("too late; already running");return n}function ht(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function bg(e,t,n){var o=e.__transition,s;o[t]=n,n.timer=fu(r,0,n.time);function r(u){n.state=hl,n.timer.restart(a,n.delay,n.time),n.delay<=u&&a(u-n.delay)}function a(u){var f,d,p,h;if(n.state!==hl)return c();for(f in o)if(h=o[f],h.name===n.name){if(h.state===ns)return pl(a);h.state===ml?(h.state=is,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete o[f]):+f<t&&(h.state=is,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete o[f])}if(pl(function(){n.state===ns&&(n.state=ml,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Ur,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Ur){for(n.state=ns,s=new Array(p=n.tween.length),f=0,d=-1;f<p;++f)(h=n.tween[f].value.call(e,e.__data__,n.index,n.group))&&(s[++d]=h);s.length=d+1}}function l(u){for(var f=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=Vr,1),d=-1,p=s.length;++d<p;)s[d].call(e,f);n.state===Vr&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=is,n.timer.stop(),delete o[t];for(var u in o)return;delete e.__transition}}function os(e,t){var n=e.__transition,o,s,r=!0,a;if(n){t=t==null?null:t+"";for(a in n){if((o=n[a]).name!==t){r=!1;continue}s=o.state>Ur&&o.state<Vr,o.state=is,o.timer.stop(),o.on.call(s?"interrupt":"cancel",e,e.__data__,o.index,o.group),delete n[a]}r&&delete e.__transition}}function xg(e){return this.each(function(){os(this,e)})}function yg(e,t){var n,o;return function(){var s=At(this,e),r=s.tween;if(r!==n){o=n=r;for(var a=0,l=o.length;a<l;++a)if(o[a].name===t){o=o.slice(),o.splice(a,1);break}}s.tween=o}}function vg(e,t,n){var o,s;if(typeof n!="function")throw new Error;return function(){var r=At(this,e),a=r.tween;if(a!==o){s=(o=a).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}r.tween=s}}function wg(e,t){var n=this._id;if(e+="",arguments.length<2){for(var o=ht(this.node(),n).tween,s=0,r=o.length,a;s<r;++s)if((a=o[s]).name===e)return a.value;return null}return this.each((t==null?yg:vg)(n,e,t))}function va(e,t,n){var o=e._id;return e.each(function(){var s=At(this,o);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return ht(s,o).value[t]}}function hu(e,t){var n;return(typeof t=="number"?Tt:t instanceof ii?fs:(n=ii(t))?(t=n,fs):au)(e,t)}function Sg(e){return function(){this.removeAttribute(e)}}function _g(e){return function(){this.removeAttributeNS(e.space,e.local)}}function jg(e,t,n){var o,s=n+"",r;return function(){var a=this.getAttribute(e);return a===s?null:a===o?r:r=t(o=a,n)}}function Mg(e,t,n){var o,s=n+"",r;return function(){var a=this.getAttributeNS(e.space,e.local);return a===s?null:a===o?r:r=t(o=a,n)}}function Cg(e,t,n){var o,s,r;return function(){var a,l=n(this),c;return l==null?void this.removeAttribute(e):(a=this.getAttribute(e),c=l+"",a===c?null:a===o&&c===s?r:(s=c,r=t(o=a,l)))}}function Ng(e,t,n){var o,s,r;return function(){var a,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(a=this.getAttributeNS(e.space,e.local),c=l+"",a===c?null:a===o&&c===s?r:(s=c,r=t(o=a,l)))}}function Tg(e,t){var n=Es(e),o=n==="transform"?ag:hu;return this.attrTween(e,typeof t=="function"?(n.local?Ng:Cg)(n,o,va(this,"attr."+e,t)):t==null?(n.local?_g:Sg)(n):(n.local?Mg:jg)(n,o,t))}function Ig(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function Eg(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function Ag(e,t){var n,o;function s(){var r=t.apply(this,arguments);return r!==o&&(n=(o=r)&&Eg(e,r)),n}return s._value=t,s}function kg(e,t){var n,o;function s(){var r=t.apply(this,arguments);return r!==o&&(n=(o=r)&&Ig(e,r)),n}return s._value=t,s}function Bg(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var o=Es(e);return this.tween(n,(o.local?Ag:kg)(o,t))}function Pg(e,t){return function(){ya(this,e).delay=+t.apply(this,arguments)}}function Rg(e,t){return t=+t,function(){ya(this,e).delay=t}}function Dg(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Pg:Rg)(t,e)):ht(this.node(),t).delay}function Fg(e,t){return function(){At(this,e).duration=+t.apply(this,arguments)}}function Lg(e,t){return t=+t,function(){At(this,e).duration=t}}function zg(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Fg:Lg)(t,e)):ht(this.node(),t).duration}function Og(e,t){if(typeof t!="function")throw new Error;return function(){At(this,e).ease=t}}function $g(e){var t=this._id;return arguments.length?this.each(Og(t,e)):ht(this.node(),t).ease}function Gg(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;At(this,e).ease=n}}function Hg(e){if(typeof e!="function")throw new Error;return this.each(Gg(this._id,e))}function Wg(e){typeof e!="function"&&(e=Uc(e));for(var t=this._groups,n=t.length,o=new Array(n),s=0;s<n;++s)for(var r=t[s],a=r.length,l=o[s]=[],c,u=0;u<a;++u)(c=r[u])&&e.call(c,c.__data__,u,r)&&l.push(c);return new Wt(o,this._parents,this._name,this._id)}function Ug(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,o=t.length,s=n.length,r=Math.min(o,s),a=new Array(o),l=0;l<r;++l)for(var c=t[l],u=n[l],f=c.length,d=a[l]=new Array(f),p,h=0;h<f;++h)(p=c[h]||u[h])&&(d[h]=p);for(;l<o;++l)a[l]=t[l];return new Wt(a,this._parents,this._name,this._id)}function Vg(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function Yg(e,t,n){var o,s,r=Vg(t)?ya:At;return function(){var a=r(this,e),l=a.on;l!==o&&(s=(o=l).copy()).on(t,n),a.on=s}}function Zg(e,t){var n=this._id;return arguments.length<2?ht(this.node(),n).on.on(e):this.each(Yg(n,e,t))}function Xg(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function Kg(){return this.on("end.remove",Xg(this._id))}function qg(e){var t=this._name,n=this._id;typeof e!="function"&&(e=ha(e));for(var o=this._groups,s=o.length,r=new Array(s),a=0;a<s;++a)for(var l=o[a],c=l.length,u=r[a]=new Array(c),f,d,p=0;p<c;++p)(f=l[p])&&(d=e.call(f,f.__data__,p,l))&&("__data__"in f&&(d.__data__=f.__data__),u[p]=d,ks(u[p],t,n,p,u,ht(f,n)));return new Wt(r,this._parents,t,n)}function Qg(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Wc(e));for(var o=this._groups,s=o.length,r=[],a=[],l=0;l<s;++l)for(var c=o[l],u=c.length,f,d=0;d<u;++d)if(f=c[d]){for(var p=e.call(f,f.__data__,d,c),h,v=ht(f,n),b=0,S=p.length;b<S;++b)(h=p[b])&&ks(h,t,n,b,p,v);r.push(p),a.push(f)}return new Wt(r,a,t,n)}var Jg=xo.prototype.constructor;function e0(){return new Jg(this._groups,this._parents)}function t0(e,t){var n,o,s;return function(){var r=wi(this,e),a=(this.style.removeProperty(e),wi(this,e));return r===a?null:r===n&&a===o?s:s=t(n=r,o=a)}}function mu(e){return function(){this.style.removeProperty(e)}}function n0(e,t,n){var o,s=n+"",r;return function(){var a=wi(this,e);return a===s?null:a===o?r:r=t(o=a,n)}}function i0(e,t,n){var o,s,r;return function(){var a=wi(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),wi(this,e))),a===c?null:a===o&&c===s?r:(s=c,r=t(o=a,l))}}function o0(e,t){var n,o,s,r="style."+t,a="end."+r,l;return function(){var c=At(this,e),u=c.on,f=c.value[r]==null?l||(l=mu(t)):void 0;(u!==n||s!==f)&&(o=(n=u).copy()).on(a,s=f),c.on=o}}function s0(e,t,n){var o=(e+="")=="transform"?rg:hu;return t==null?this.styleTween(e,t0(e,o)).on("end.style."+e,mu(e)):typeof t=="function"?this.styleTween(e,i0(e,o,va(this,"style."+e,t))).each(o0(this._id,e)):this.styleTween(e,n0(e,o,t),n).on("end.style."+e,null)}function r0(e,t,n){return function(o){this.style.setProperty(e,t.call(this,o),n)}}function a0(e,t,n){var o,s;function r(){var a=t.apply(this,arguments);return a!==s&&(o=(s=a)&&r0(e,a,n)),o}return r._value=t,r}function l0(e,t,n){var o="style."+(e+="");if(arguments.length<2)return(o=this.tween(o))&&o._value;if(t==null)return this.tween(o,null);if(typeof t!="function")throw new Error;return this.tween(o,a0(e,t,n??""))}function c0(e){return function(){this.textContent=e}}function u0(e){return function(){var t=e(this);this.textContent=t??""}}function d0(e){return this.tween("text",typeof e=="function"?u0(va(this,"text",e)):c0(e==null?"":e+""))}function f0(e){return function(t){this.textContent=e.call(this,t)}}function p0(e){var t,n;function o(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&f0(s)),t}return o._value=e,o}function h0(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,p0(e))}function m0(){for(var e=this._name,t=this._id,n=gu(),o=this._groups,s=o.length,r=0;r<s;++r)for(var a=o[r],l=a.length,c,u=0;u<l;++u)if(c=a[u]){var f=ht(c,t);ks(c,e,n,u,a,{time:f.time+f.delay+f.duration,delay:0,duration:f.duration,ease:f.ease})}return new Wt(o,this._parents,e,n)}function g0(){var e,t,n=this,o=n._id,s=n.size();return new Promise(function(r,a){var l={value:a},c={value:function(){--s===0&&r()}};n.each(function(){var u=At(this,o),f=u.on;f!==e&&(t=(e=f).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&r()})}var b0=0;function Wt(e,t,n,o){this._groups=e,this._parents=t,this._name=n,this._id=o}function gu(){return++b0}var zt=xo.prototype;Wt.prototype={constructor:Wt,select:qg,selectAll:Qg,selectChild:zt.selectChild,selectChildren:zt.selectChildren,filter:Wg,merge:Ug,selection:e0,transition:m0,call:zt.call,nodes:zt.nodes,node:zt.node,size:zt.size,empty:zt.empty,each:zt.each,on:Zg,attr:Tg,attrTween:Bg,style:s0,styleTween:l0,text:d0,textTween:h0,remove:Kg,tween:wg,delay:Dg,duration:zg,ease:$g,easeVarying:Hg,end:g0,[Symbol.iterator]:zt[Symbol.iterator]};function x0(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var y0={time:null,delay:0,duration:250,ease:x0};function v0(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function w0(e){var t,n;e instanceof Wt?(t=e._id,e=e._name):(t=gu(),(n=y0).time=xa(),e=e==null?null:e+"");for(var o=this._groups,s=o.length,r=0;r<s;++r)for(var a=o[r],l=a.length,c,u=0;u<l;++u)(c=a[u])&&ks(c,e,t,u,a,n||v0(c,t));return new Wt(o,this._parents,e,t)}xo.prototype.interrupt=xg;xo.prototype.transition=w0;const Fo=e=>()=>e;function S0(e,{sourceEvent:t,target:n,transform:o,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:o,enumerable:!0,configurable:!0},_:{value:s}})}function Ht(e,t,n){this.k=e,this.x=t,this.y=n}Ht.prototype={constructor:Ht,scale:function(e){return e===1?this:new Ht(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Ht(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Bs=new Ht(1,0,0);bu.prototype=Ht.prototype;function bu(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Bs;return e.__zoom}function lr(e){e.stopImmediatePropagation()}function Li(e){e.preventDefault(),e.stopImmediatePropagation()}function _0(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function j0(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function gl(){return this.__zoom||Bs}function M0(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function C0(){return navigator.maxTouchPoints||"ontouchstart"in this}function N0(e,t,n){var o=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],r=e.invertY(t[0][1])-n[0][1],a=e.invertY(t[1][1])-n[1][1];return e.translate(s>o?(o+s)/2:Math.min(0,o)||Math.max(0,s),a>r?(r+a)/2:Math.min(0,r)||Math.max(0,a))}function xu(){var e=_0,t=j0,n=N0,o=M0,s=C0,r=[0,1/0],a=[[-1/0,-1/0],[1/0,1/0]],l=250,c=ts,u=Is("start","zoom","end"),f,d,p,h=500,v=150,b=0,S=10;function x(T){T.property("__zoom",gl).on("wheel.zoom",B,{passive:!1}).on("mousedown.zoom",z).on("dblclick.zoom",W).filter(s).on("touchstart.zoom",D).on("touchmove.zoom",E).on("touchend.zoom touchcancel.zoom",G).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}x.transform=function(T,O,P,L){var M=T.selection?T.selection():T;M.property("__zoom",gl),T!==M?w(T,O,P,L):M.interrupt().each(function(){j(this,arguments).event(L).start().zoom(null,typeof O=="function"?O.apply(this,arguments):O).end()})},x.scaleBy=function(T,O,P,L){x.scaleTo(T,function(){var M=this.__zoom.k,F=typeof O=="function"?O.apply(this,arguments):O;return M*F},P,L)},x.scaleTo=function(T,O,P,L){x.transform(T,function(){var M=t.apply(this,arguments),F=this.__zoom,U=P==null?y(M):typeof P=="function"?P.apply(this,arguments):P,V=F.invert(U),Y=typeof O=="function"?O.apply(this,arguments):O;return n(g(_(F,Y),U,V),M,a)},P,L)},x.translateBy=function(T,O,P,L){x.transform(T,function(){return n(this.__zoom.translate(typeof O=="function"?O.apply(this,arguments):O,typeof P=="function"?P.apply(this,arguments):P),t.apply(this,arguments),a)},null,L)},x.translateTo=function(T,O,P,L,M){x.transform(T,function(){var F=t.apply(this,arguments),U=this.__zoom,V=L==null?y(F):typeof L=="function"?L.apply(this,arguments):L;return n(Bs.translate(V[0],V[1]).scale(U.k).translate(typeof O=="function"?-O.apply(this,arguments):-O,typeof P=="function"?-P.apply(this,arguments):-P),F,a)},L,M)};function _(T,O){return O=Math.max(r[0],Math.min(r[1],O)),O===T.k?T:new Ht(O,T.x,T.y)}function g(T,O,P){var L=O[0]-P[0]*T.k,M=O[1]-P[1]*T.k;return L===T.x&&M===T.y?T:new Ht(T.k,L,M)}function y(T){return[(+T[0][0]+ +T[1][0])/2,(+T[0][1]+ +T[1][1])/2]}function w(T,O,P,L){T.on("start.zoom",function(){j(this,arguments).event(L).start()}).on("interrupt.zoom end.zoom",function(){j(this,arguments).event(L).end()}).tween("zoom",function(){var M=this,F=arguments,U=j(M,F).event(L),V=t.apply(M,F),Y=P==null?y(V):typeof P=="function"?P.apply(M,F):P,Z=Math.max(V[1][0]-V[0][0],V[1][1]-V[0][1]),q=M.__zoom,X=typeof O=="function"?O.apply(M,F):O,A=c(q.invert(Y).concat(Z/q.k),X.invert(Y).concat(Z/X.k));return function(C){if(C===1)C=X;else{var H=A(C),K=Z/H[2];C=new Ht(K,Y[0]-H[0]*K,Y[1]-H[1]*K)}U.zoom(null,C)}})}function j(T,O,P){return!P&&T.__zooming||new N(T,O)}function N(T,O){this.that=T,this.args=O,this.active=0,this.sourceEvent=null,this.extent=t.apply(T,O),this.taps=0}N.prototype={event:function(T){return T&&(this.sourceEvent=T),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(T,O){return this.mouse&&T!=="mouse"&&(this.mouse[1]=O.invert(this.mouse[0])),this.touch0&&T!=="touch"&&(this.touch0[1]=O.invert(this.touch0[0])),this.touch1&&T!=="touch"&&(this.touch1[1]=O.invert(this.touch1[0])),this.that.__zoom=O,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(T){var O=Ve(this.that).datum();u.call(T,this.that,new S0(T,{sourceEvent:this.sourceEvent,target:x,transform:this.that.__zoom,dispatch:u}),O)}};function B(T,...O){if(!e.apply(this,arguments))return;var P=j(this,O).event(T),L=this.__zoom,M=Math.max(r[0],Math.min(r[1],L.k*Math.pow(2,o.apply(this,arguments)))),F=st(T);if(P.wheel)(P.mouse[0][0]!==F[0]||P.mouse[0][1]!==F[1])&&(P.mouse[1]=L.invert(P.mouse[0]=F)),clearTimeout(P.wheel);else{if(L.k===M)return;P.mouse=[F,L.invert(F)],os(this),P.start()}Li(T),P.wheel=setTimeout(U,v),P.zoom("mouse",n(g(_(L,M),P.mouse[0],P.mouse[1]),P.extent,a));function U(){P.wheel=null,P.end()}}function z(T,...O){if(p||!e.apply(this,arguments))return;var P=T.currentTarget,L=j(this,O,!0).event(T),M=Ve(T.view).on("mousemove.zoom",Y,!0).on("mouseup.zoom",Z,!0),F=st(T,P),U=T.clientX,V=T.clientY;tu(T.view),lr(T),L.mouse=[F,this.__zoom.invert(F)],os(this),L.start();function Y(q){if(Li(q),!L.moved){var X=q.clientX-U,A=q.clientY-V;L.moved=X*X+A*A>b}L.event(q).zoom("mouse",n(g(L.that.__zoom,L.mouse[0]=st(q,P),L.mouse[1]),L.extent,a))}function Z(q){M.on("mousemove.zoom mouseup.zoom",null),nu(q.view,L.moved),Li(q),L.event(q).end()}}function W(T,...O){if(e.apply(this,arguments)){var P=this.__zoom,L=st(T.changedTouches?T.changedTouches[0]:T,this),M=P.invert(L),F=P.k*(T.shiftKey?.5:2),U=n(g(_(P,F),L,M),t.apply(this,O),a);Li(T),l>0?Ve(this).transition().duration(l).call(w,U,L,T):Ve(this).call(x.transform,U,L,T)}}function D(T,...O){if(e.apply(this,arguments)){var P=T.touches,L=P.length,M=j(this,O,T.changedTouches.length===L).event(T),F,U,V,Y;for(lr(T),U=0;U<L;++U)V=P[U],Y=st(V,this),Y=[Y,this.__zoom.invert(Y),V.identifier],M.touch0?!M.touch1&&M.touch0[2]!==Y[2]&&(M.touch1=Y,M.taps=0):(M.touch0=Y,F=!0,M.taps=1+!!f);f&&(f=clearTimeout(f)),F&&(M.taps<2&&(d=Y[0],f=setTimeout(function(){f=null},h)),os(this),M.start())}}function E(T,...O){if(this.__zooming){var P=j(this,O).event(T),L=T.changedTouches,M=L.length,F,U,V,Y;for(Li(T),F=0;F<M;++F)U=L[F],V=st(U,this),P.touch0&&P.touch0[2]===U.identifier?P.touch0[0]=V:P.touch1&&P.touch1[2]===U.identifier&&(P.touch1[0]=V);if(U=P.that.__zoom,P.touch1){var Z=P.touch0[0],q=P.touch0[1],X=P.touch1[0],A=P.touch1[1],C=(C=X[0]-Z[0])*C+(C=X[1]-Z[1])*C,H=(H=A[0]-q[0])*H+(H=A[1]-q[1])*H;U=_(U,Math.sqrt(C/H)),V=[(Z[0]+X[0])/2,(Z[1]+X[1])/2],Y=[(q[0]+A[0])/2,(q[1]+A[1])/2]}else if(P.touch0)V=P.touch0[0],Y=P.touch0[1];else return;P.zoom("touch",n(g(U,V,Y),P.extent,a))}}function G(T,...O){if(this.__zooming){var P=j(this,O).event(T),L=T.changedTouches,M=L.length,F,U;for(lr(T),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),F=0;F<M;++F)U=L[F],P.touch0&&P.touch0[2]===U.identifier?delete P.touch0:P.touch1&&P.touch1[2]===U.identifier&&delete P.touch1;if(P.touch1&&!P.touch0&&(P.touch0=P.touch1,delete P.touch1),P.touch0)P.touch0[1]=this.__zoom.invert(P.touch0[0]);else if(P.end(),P.taps===2&&(U=st(U,this),Math.hypot(d[0]-U[0],d[1]-U[1])<S)){var V=Ve(this).on("dblclick.zoom");V&&V.apply(this,arguments)}}}return x.wheelDelta=function(T){return arguments.length?(o=typeof T=="function"?T:Fo(+T),x):o},x.filter=function(T){return arguments.length?(e=typeof T=="function"?T:Fo(!!T),x):e},x.touchable=function(T){return arguments.length?(s=typeof T=="function"?T:Fo(!!T),x):s},x.extent=function(T){return arguments.length?(t=typeof T=="function"?T:Fo([[+T[0][0],+T[0][1]],[+T[1][0],+T[1][1]]]),x):t},x.scaleExtent=function(T){return arguments.length?(r[0]=+T[0],r[1]=+T[1],x):[r[0],r[1]]},x.translateExtent=function(T){return arguments.length?(a[0][0]=+T[0][0],a[1][0]=+T[1][0],a[0][1]=+T[0][1],a[1][1]=+T[1][1],x):[[a[0][0],a[0][1]],[a[1][0],a[1][1]]]},x.constrain=function(T){return arguments.length?(n=T,x):n},x.duration=function(T){return arguments.length?(l=+T,x):l},x.interpolate=function(T){return arguments.length?(c=T,x):c},x.on=function(){var T=u.on.apply(u,arguments);return T===u?x:T},x.clickDistance=function(T){return arguments.length?(b=(T=+T)*T,x):Math.sqrt(b)},x.tapDistance=function(T){return arguments.length?(S=+T,x):S},x}const Et={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:o})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:o}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},ao=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],yu=["Enter"," ","Escape"],vu={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var _i;(function(e){e.Strict="strict",e.Loose="loose"})(_i||(_i={}));var ni;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(ni||(ni={}));var lo;(function(e){e.Partial="partial",e.Full="full"})(lo||(lo={}));const wu={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var hn;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(hn||(hn={}));var co;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(co||(co={}));var le;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(le||(le={}));const bl={[le.Left]:le.Right,[le.Right]:le.Left,[le.Top]:le.Bottom,[le.Bottom]:le.Top};function Su(e){return e===null?null:e?"valid":"invalid"}const _u=e=>"id"in e&&"source"in e&&"target"in e,T0=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),wa=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),vo=(e,t=[0,0])=>{const{width:n,height:o}=Ut(e),s=e.origin??t,r=n*s[0],a=o*s[1];return{x:e.position.x-r,y:e.position.y-a}},I0=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((o,s)=>{const r=typeof s=="string";let a=!t.nodeLookup&&!r?s:void 0;t.nodeLookup&&(a=r?t.nodeLookup.get(s):wa(s)?s:t.nodeLookup.get(s.id));const l=a?gs(a,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Ps(o,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Rs(n)},wo=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},o=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=Ps(n,gs(s)),o=!0)}),o?Rs(n):{x:0,y:0,width:0,height:0}},Sa=(e,t,[n,o,s]=[0,0,1],r=!1,a=!1)=>{const l={..._o(t,[n,o,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:f,selectable:d=!0,hidden:p=!1}=u;if(a&&!d||p)continue;const h=f.width??u.width??u.initialWidth??null,v=f.height??u.height??u.initialHeight??null,b=uo(l,Mi(u)),S=(h??0)*(v??0),x=r&&b>0;(!u.internals.handleBounds||x||b>=S||u.dragging)&&c.push(u)}return c},E0=(e,t)=>{const n=new Set;return e.forEach(o=>{n.add(o.id)}),t.filter(o=>n.has(o.source)||n.has(o.target))};function A0(e,t){const n=new Map,o=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!o||o.has(s.id))&&n.set(s.id,s)}),n}async function k0({nodes:e,width:t,height:n,panZoom:o,minZoom:s,maxZoom:r},a){if(e.size===0)return Promise.resolve(!0);const l=A0(e,a),c=wo(l),u=_a(c,t,n,a?.minZoom??s,a?.maxZoom??r,a?.padding??.1);return await o.setViewport(u,{duration:a?.duration,ease:a?.ease,interpolate:a?.interpolate}),Promise.resolve(!0)}function ju({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:o=[0,0],nodeExtent:s,onError:r}){const a=n.get(e),l=a.parentId?n.get(a.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},f=a.origin??o;let d=a.extent||s;if(a.extent==="parent"&&!a.expandParent)if(!l)r?.("005",Et.error005());else{const h=l.measured.width,v=l.measured.height;h&&v&&(d=[[c,u],[c+h,u+v]])}else l&&Ci(a.extent)&&(d=[[a.extent[0][0]+c,a.extent[0][1]+u],[a.extent[1][0]+c,a.extent[1][1]+u]]);const p=Ci(d)?si(t,d,a.measured):t;return(a.measured.width===void 0||a.measured.height===void 0)&&r?.("015",Et.error015()),{position:{x:p.x-c+(a.measured.width??0)*f[0],y:p.y-u+(a.measured.height??0)*f[1]},positionAbsolute:p}}async function B0({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:o,onBeforeDelete:s}){const r=new Set(e.map(p=>p.id)),a=[];for(const p of n){if(p.deletable===!1)continue;const h=r.has(p.id),v=!h&&p.parentId&&a.find(b=>b.id===p.parentId);(h||v)&&a.push(p)}const l=new Set(t.map(p=>p.id)),c=o.filter(p=>p.deletable!==!1),f=E0(a,c);for(const p of c)l.has(p.id)&&!f.find(v=>v.id===p.id)&&f.push(p);if(!s)return{edges:f,nodes:a};const d=await s({nodes:a,edges:f});return typeof d=="boolean"?d?{edges:f,nodes:a}:{edges:[],nodes:[]}:d}const ji=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),si=(e={x:0,y:0},t,n)=>({x:ji(e.x,t[0][0],t[1][0]-(n?.width??0)),y:ji(e.y,t[0][1],t[1][1]-(n?.height??0))});function Mu(e,t,n){const{width:o,height:s}=Ut(n),{x:r,y:a}=n.internals.positionAbsolute;return si(e,[[r,a],[r+o,a+s]],t)}const xl=(e,t,n)=>e<t?ji(Math.abs(e-t),1,t)/t:e>n?-ji(Math.abs(e-n),1,t)/t:0,Cu=(e,t,n=15,o=40)=>{const s=xl(e.x,o,t.width-o)*n,r=xl(e.y,o,t.height-o)*n;return[s,r]},Ps=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Yr=({x:e,y:t,width:n,height:o})=>({x:e,y:t,x2:e+n,y2:t+o}),Rs=({x:e,y:t,x2:n,y2:o})=>({x:e,y:t,width:n-e,height:o-t}),Mi=(e,t=[0,0])=>{const{x:n,y:o}=wa(e)?e.internals.positionAbsolute:vo(e,t);return{x:n,y:o,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},gs=(e,t=[0,0])=>{const{x:n,y:o}=wa(e)?e.internals.positionAbsolute:vo(e,t);return{x:n,y:o,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:o+(e.measured?.height??e.height??e.initialHeight??0)}},Nu=(e,t)=>Rs(Ps(Yr(e),Yr(t))),uo=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),o=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*o)},yl=e=>ut(e.width)&&ut(e.height)&&ut(e.x)&&ut(e.y),ut=e=>!isNaN(e)&&isFinite(e),P0=(e,t)=>{},So=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),_o=({x:e,y:t},[n,o,s],r=!1,a=[1,1])=>{const l={x:(e-n)/s,y:(t-o)/s};return r?So(l,a):l},bs=({x:e,y:t},[n,o,s])=>({x:e*s+n,y:t*s+o});function ui(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function R0(e,t,n){if(typeof e=="string"||typeof e=="number"){const o=ui(e,n),s=ui(e,t);return{top:o,right:s,bottom:o,left:s,x:s*2,y:o*2}}if(typeof e=="object"){const o=ui(e.top??e.y??0,n),s=ui(e.bottom??e.y??0,n),r=ui(e.left??e.x??0,t),a=ui(e.right??e.x??0,t);return{top:o,right:a,bottom:s,left:r,x:r+a,y:o+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function D0(e,t,n,o,s,r){const{x:a,y:l}=bs(e,[t,n,o]),{x:c,y:u}=bs({x:e.x+e.width,y:e.y+e.height},[t,n,o]),f=s-c,d=r-u;return{left:Math.floor(a),top:Math.floor(l),right:Math.floor(f),bottom:Math.floor(d)}}const _a=(e,t,n,o,s,r)=>{const a=R0(r,t,n),l=(t-a.x)/e.width,c=(n-a.y)/e.height,u=Math.min(l,c),f=ji(u,o,s),d=e.x+e.width/2,p=e.y+e.height/2,h=t/2-d*f,v=n/2-p*f,b=D0(e,h,v,f,t,n),S={left:Math.min(b.left-a.left,0),top:Math.min(b.top-a.top,0),right:Math.min(b.right-a.right,0),bottom:Math.min(b.bottom-a.bottom,0)};return{x:h-S.left+S.right,y:v-S.top+S.bottom,zoom:f}},fo=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function Ci(e){return e!=null&&e!=="parent"}function Ut(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function Tu(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function Iu(e,t={width:0,height:0},n,o,s){const r={...e},a=o.get(n);if(a){const l=a.origin||s;r.x+=a.internals.positionAbsolute.x-(t.width??0)*l[0],r.y+=a.internals.positionAbsolute.y-(t.height??0)*l[1]}return r}function vl(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function F0(){let e,t;return{promise:new Promise((o,s)=>{e=o,t=s}),resolve:e,reject:t}}function L0(e){return{...vu,...e||{}}}function Qi(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:o,containerBounds:s}){const{x:r,y:a}=dt(e),l=_o({x:r-(s?.left??0),y:a-(s?.top??0)},o),{x:c,y:u}=n?So(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const ja=e=>({width:e.offsetWidth,height:e.offsetHeight}),Eu=e=>e?.getRootNode?.()||window?.document,z0=["INPUT","SELECT","TEXTAREA"];function Au(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:z0.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const ku=e=>"clientX"in e,dt=(e,t)=>{const n=ku(e),o=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:o-(t?.left??0),y:s-(t?.top??0)}},wl=(e,t,n,o,s)=>{const r=t.querySelectorAll(`.${e}`);return!r||!r.length?null:Array.from(r).map(a=>{const l=a.getBoundingClientRect();return{id:a.getAttribute("data-handleid"),type:e,nodeId:s,position:a.getAttribute("data-handlepos"),x:(l.left-n.left)/o,y:(l.top-n.top)/o,...ja(a)}})};function Bu({sourceX:e,sourceY:t,targetX:n,targetY:o,sourceControlX:s,sourceControlY:r,targetControlX:a,targetControlY:l}){const c=e*.125+s*.375+a*.375+n*.125,u=t*.125+r*.375+l*.375+o*.125,f=Math.abs(c-e),d=Math.abs(u-t);return[c,u,f,d]}function Lo(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Sl({pos:e,x1:t,y1:n,x2:o,y2:s,c:r}){switch(e){case le.Left:return[t-Lo(t-o,r),n];case le.Right:return[t+Lo(o-t,r),n];case le.Top:return[t,n-Lo(n-s,r)];case le.Bottom:return[t,n+Lo(s-n,r)]}}function Pu({sourceX:e,sourceY:t,sourcePosition:n=le.Bottom,targetX:o,targetY:s,targetPosition:r=le.Top,curvature:a=.25}){const[l,c]=Sl({pos:n,x1:e,y1:t,x2:o,y2:s,c:a}),[u,f]=Sl({pos:r,x1:o,y1:s,x2:e,y2:t,c:a}),[d,p,h,v]=Bu({sourceX:e,sourceY:t,targetX:o,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:f});return[`M${e},${t} C${l},${c} ${u},${f} ${o},${s}`,d,p,h,v]}function Ru({sourceX:e,sourceY:t,targetX:n,targetY:o}){const s=Math.abs(n-e)/2,r=n<e?n+s:n-s,a=Math.abs(o-t)/2,l=o<t?o+a:o-a;return[r,l,s,a]}function O0({sourceNode:e,targetNode:t,selected:n=!1,zIndex:o=0,elevateOnSelect:s=!1,zIndexMode:r="basic"}){if(r==="manual")return o;const a=s&&n?o+1e3:o,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return a+l}function $0({sourceNode:e,targetNode:t,width:n,height:o,transform:s}){const r=Ps(gs(e),gs(t));r.x===r.x2&&(r.x2+=1),r.y===r.y2&&(r.y2+=1);const a={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:o/s[2]};return uo(a,Rs(r))>0}const G0=({source:e,sourceHandle:t,target:n,targetHandle:o})=>`xy-edge__${e}${t||""}-${n}${o||""}`,H0=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),W0=(e,t,n={})=>{if(!e.source||!e.target)return t;const o=n.getEdgeId||G0;let s;return _u(e)?s={...e}:s={...e,id:o(e)},H0(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function Du({sourceX:e,sourceY:t,targetX:n,targetY:o}){const[s,r,a,l]=Ru({sourceX:e,sourceY:t,targetX:n,targetY:o});return[`M ${e},${t}L ${n},${o}`,s,r,a,l]}const _l={[le.Left]:{x:-1,y:0},[le.Right]:{x:1,y:0},[le.Top]:{x:0,y:-1},[le.Bottom]:{x:0,y:1}},U0=({source:e,sourcePosition:t=le.Bottom,target:n})=>t===le.Left||t===le.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},jl=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function V0({source:e,sourcePosition:t=le.Bottom,target:n,targetPosition:o=le.Top,center:s,offset:r,stepPosition:a}){const l=_l[t],c=_l[o],u={x:e.x+l.x*r,y:e.y+l.y*r},f={x:n.x+c.x*r,y:n.y+c.y*r},d=U0({source:u,sourcePosition:t,target:f}),p=d.x!==0?"x":"y",h=d[p];let v=[],b,S;const x={x:0,y:0},_={x:0,y:0},[,,g,y]=Ru({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(b=s.x??u.x+(f.x-u.x)*a,S=s.y??(u.y+f.y)/2):(b=s.x??(u.x+f.x)/2,S=s.y??u.y+(f.y-u.y)*a);const B=[{x:b,y:u.y},{x:b,y:f.y}],z=[{x:u.x,y:S},{x:f.x,y:S}];l[p]===h?v=p==="x"?B:z:v=p==="x"?z:B}else{const B=[{x:u.x,y:f.y}],z=[{x:f.x,y:u.y}];if(p==="x"?v=l.x===h?z:B:v=l.y===h?B:z,t===o){const T=Math.abs(e[p]-n[p]);if(T<=r){const O=Math.min(r-1,r-T);l[p]===h?x[p]=(u[p]>e[p]?-1:1)*O:_[p]=(f[p]>n[p]?-1:1)*O}}if(t!==o){const T=p==="x"?"y":"x",O=l[p]===c[T],P=u[T]>f[T],L=u[T]<f[T];(l[p]===1&&(!O&&P||O&&L)||l[p]!==1&&(!O&&L||O&&P))&&(v=p==="x"?B:z)}const W={x:u.x+x.x,y:u.y+x.y},D={x:f.x+_.x,y:f.y+_.y},E=Math.max(Math.abs(W.x-v[0].x),Math.abs(D.x-v[0].x)),G=Math.max(Math.abs(W.y-v[0].y),Math.abs(D.y-v[0].y));E>=G?(b=(W.x+D.x)/2,S=v[0].y):(b=v[0].x,S=(W.y+D.y)/2)}const w={x:u.x+x.x,y:u.y+x.y},j={x:f.x+_.x,y:f.y+_.y};return[[e,...w.x!==v[0].x||w.y!==v[0].y?[w]:[],...v,...j.x!==v[v.length-1].x||j.y!==v[v.length-1].y?[j]:[],n],b,S,g,y]}function Y0(e,t,n,o){const s=Math.min(jl(e,t)/2,jl(t,n)/2,o),{x:r,y:a}=t;if(e.x===r&&r===n.x||e.y===a&&a===n.y)return`L${r} ${a}`;if(e.y===a){const u=e.x<n.x?-1:1,f=e.y<n.y?1:-1;return`L ${r+s*u},${a}Q ${r},${a} ${r},${a+s*f}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${r},${a+s*c}Q ${r},${a} ${r+s*l},${a}`}function Zr({sourceX:e,sourceY:t,sourcePosition:n=le.Bottom,targetX:o,targetY:s,targetPosition:r=le.Top,borderRadius:a=5,centerX:l,centerY:c,offset:u=20,stepPosition:f=.5}){const[d,p,h,v,b]=V0({source:{x:e,y:t},sourcePosition:n,target:{x:o,y:s},targetPosition:r,center:{x:l,y:c},offset:u,stepPosition:f});let S=`M${d[0].x} ${d[0].y}`;for(let x=1;x<d.length-1;x++)S+=Y0(d[x-1],d[x],d[x+1],a);return S+=`L${d[d.length-1].x} ${d[d.length-1].y}`,[S,p,h,v,b]}function Ml(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function Z0(e){const{sourceNode:t,targetNode:n}=e;if(!Ml(t)||!Ml(n))return null;const o=t.internals.handleBounds||Cl(t.handles),s=n.internals.handleBounds||Cl(n.handles),r=Nl(o?.source??[],e.sourceHandle),a=Nl(e.connectionMode===_i.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!r||!a)return e.onError?.("008",Et.error008(r?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=r?.position||le.Bottom,c=a?.position||le.Top,u=ri(t,r,l),f=ri(n,a,c);return{sourceX:u.x,sourceY:u.y,targetX:f.x,targetY:f.y,sourcePosition:l,targetPosition:c}}function Cl(e){if(!e)return null;const t=[],n=[];for(const o of e)o.width=o.width??1,o.height=o.height??1,o.type==="source"?t.push(o):o.type==="target"&&n.push(o);return{source:t,target:n}}function ri(e,t,n=le.Left,o=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,r=(t?.y??0)+e.internals.positionAbsolute.y,{width:a,height:l}=t??Ut(e);if(o)return{x:s+a/2,y:r+l/2};switch(t?.position??n){case le.Top:return{x:s+a/2,y:r};case le.Right:return{x:s+a,y:r+l/2};case le.Bottom:return{x:s+a/2,y:r+l};case le.Left:return{x:s,y:r+l/2}}}function Nl(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Xr(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(o=>`${o}=${e[o]}`).join("&")}`:""}function X0(e,{id:t,defaultColor:n,defaultMarkerStart:o,defaultMarkerEnd:s}){const r=new Set;return e.reduce((a,l)=>([l.markerStart||o,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=Xr(c,t);r.has(u)||(a.push({id:u,color:c.color||n,...c}),r.add(u))}}),a),[]).sort((a,l)=>a.id.localeCompare(l.id))}const Fu=1e3,K0=10,Ma={nodeOrigin:[0,0],nodeExtent:ao,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},q0={...Ma,checkEquality:!0};function Ca(e,t){const n={...e};for(const o in t)t[o]!==void 0&&(n[o]=t[o]);return n}function Q0(e,t,n){const o=Ca(Ma,n);for(const s of e.values())if(s.parentId)Ta(s,e,t,o);else{const r=vo(s,o.nodeOrigin),a=Ci(s.extent)?s.extent:o.nodeExtent,l=si(r,a,Ut(s));s.internals.positionAbsolute=l}}function J0(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],o=[];for(const s of e.handles){const r={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(r):s.type==="target"&&o.push(r)}return{source:n,target:o}}function Na(e){return e==="manual"}function Kr(e,t,n,o={}){const s=Ca(q0,o),r={i:0},a=new Map(t),l=s?.elevateNodesOnSelect&&!Na(s.zIndexMode)?Fu:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const f of e){let d=a.get(f.id);if(s.checkEquality&&f===d?.internals.userNode)t.set(f.id,d);else{const p=vo(f,s.nodeOrigin),h=Ci(f.extent)?f.extent:s.nodeExtent,v=si(p,h,Ut(f));d={...s.defaults,...f,measured:{width:f.measured?.width,height:f.measured?.height},internals:{positionAbsolute:v,handleBounds:J0(f,d),z:Lu(f,l,s.zIndexMode),userNode:f}},t.set(f.id,d)}(d.measured===void 0||d.measured.width===void 0||d.measured.height===void 0)&&!d.hidden&&(c=!1),f.parentId&&Ta(d,t,n,o,r),u||=f.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function eb(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function Ta(e,t,n,o,s){const{elevateNodesOnSelect:r,nodeOrigin:a,nodeExtent:l,zIndexMode:c}=Ca(Ma,o),u=e.parentId,f=t.get(u);if(!f){console.warn(`Parent node ${u} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}eb(e,n),s&&!f.parentId&&f.internals.rootParentIndex===void 0&&c==="auto"&&(f.internals.rootParentIndex=++s.i,f.internals.z=f.internals.z+s.i*K0),s&&f.internals.rootParentIndex!==void 0&&(s.i=f.internals.rootParentIndex);const d=r&&!Na(c)?Fu:0,{x:p,y:h,z:v}=tb(e,f,a,l,d,c),{positionAbsolute:b}=e.internals,S=p!==b.x||h!==b.y;(S||v!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:S?{x:p,y:h}:b,z:v}})}function Lu(e,t,n){const o=ut(e.zIndex)?e.zIndex:0;return Na(n)?o:o+(e.selected?t:0)}function tb(e,t,n,o,s,r){const{x:a,y:l}=t.internals.positionAbsolute,c=Ut(e),u=vo(e,n),f=Ci(e.extent)?si(u,e.extent,c):u;let d=si({x:a+f.x,y:l+f.y},o,c);e.extent==="parent"&&(d=Mu(d,c,t));const p=Lu(e,s,r),h=t.internals.z??0;return{x:d.x,y:d.y,z:h>=p?h+1:p}}function Ia(e,t,n,o=[0,0]){const s=[],r=new Map;for(const a of e){const l=t.get(a.parentId);if(!l)continue;const c=r.get(a.parentId)?.expandedRect??Mi(l),u=Nu(c,a.rect);r.set(a.parentId,{expandedRect:u,parent:l})}return r.size>0&&r.forEach(({expandedRect:a,parent:l},c)=>{const u=l.internals.positionAbsolute,f=Ut(l),d=l.origin??o,p=a.x<u.x?Math.round(Math.abs(u.x-a.x)):0,h=a.y<u.y?Math.round(Math.abs(u.y-a.y)):0,v=Math.max(f.width,Math.round(a.width)),b=Math.max(f.height,Math.round(a.height)),S=(v-f.width)*d[0],x=(b-f.height)*d[1];(p>0||h>0||S||x)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+S,y:l.position.y-h+x}}),n.get(c)?.forEach(_=>{e.some(g=>g.id===_.id)||s.push({id:_.id,type:"position",position:{x:_.position.x+p,y:_.position.y+h}})})),(f.width<a.width||f.height<a.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:v+(p?d[0]*p-S:0),height:b+(h?d[1]*h-x:0)}})}),s}function nb(e,t,n,o,s,r,a){const l=o?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],f=window.getComputedStyle(l),{m22:d}=new window.DOMMatrixReadOnly(f.transform),p=[];for(const h of e.values()){const v=t.get(h.id);if(!v)continue;if(v.hidden){t.set(v.id,{...v,internals:{...v.internals,handleBounds:void 0}}),c=!0;continue}const b=ja(h.nodeElement),S=v.measured.width!==b.width||v.measured.height!==b.height;if(!!(b.width&&b.height&&(S||!v.internals.handleBounds||h.force))){const _=h.nodeElement.getBoundingClientRect(),g=Ci(v.extent)?v.extent:r;let{positionAbsolute:y}=v.internals;v.parentId&&v.extent==="parent"?y=Mu(y,b,t.get(v.parentId)):g&&(y=si(y,g,b));const w={...v,measured:b,internals:{...v.internals,positionAbsolute:y,handleBounds:{source:wl("source",h.nodeElement,_,d,v.id),target:wl("target",h.nodeElement,_,d,v.id)}}};t.set(v.id,w),v.parentId&&Ta(w,t,n,{nodeOrigin:s,zIndexMode:a}),c=!0,S&&(u.push({id:v.id,type:"dimensions",dimensions:b}),v.expandParent&&v.parentId&&p.push({id:v.id,parentId:v.parentId,rect:Mi(w,s)}))}}if(p.length>0){const h=Ia(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function ib({delta:e,panZoom:t,transform:n,translateExtent:o,width:s,height:r}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const a=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,r]],o),l=!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2]);return Promise.resolve(l)}function Tl(e,t,n,o,s,r){let a=s;const l=o.get(a)||new Map;o.set(a,l.set(n,t)),a=`${s}-${e}`;const c=o.get(a)||new Map;if(o.set(a,c.set(n,t)),r){a=`${s}-${e}-${r}`;const u=o.get(a)||new Map;o.set(a,u.set(n,t))}}function zu(e,t,n){e.clear(),t.clear();for(const o of n){const{source:s,target:r,sourceHandle:a=null,targetHandle:l=null}=o,c={edgeId:o.id,source:s,target:r,sourceHandle:a,targetHandle:l},u=`${s}-${a}--${r}-${l}`,f=`${r}-${l}--${s}-${a}`;Tl("source",c,f,e,s,a),Tl("target",c,u,e,r,l),t.set(o.id,o)}}function Ou(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:Ou(n,t):!1}function Il(e,t,n){let o=e;do{if(o?.matches?.(t))return!0;if(o===n)return!1;o=o?.parentElement}while(o);return!1}function ob(e,t,n,o){const s=new Map;for(const[r,a]of e)if((a.selected||a.id===o)&&(!a.parentId||!Ou(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const l=e.get(r);l&&s.set(r,{id:r,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function cr({nodeId:e,dragItems:t,nodeLookup:n,dragging:o=!0}){const s=[];for(const[a,l]of t){const c=n.get(a)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:o})}if(!e)return[s[0],s];const r=n.get(e)?.internals.userNode;return[r?{...r,position:t.get(e)?.position||r.position,dragging:o}:s[0],s]}function sb({dragItems:e,snapGrid:t,x:n,y:o}){const s=e.values().next().value;if(!s)return null;const r={x:n-s.distance.x,y:o-s.distance.y},a=So(r,t);return{x:a.x-r.x,y:a.y-r.y}}function rb({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:o,onDragStop:s}){let r={x:null,y:null},a=0,l=new Map,c=!1,u={x:0,y:0},f=null,d=!1,p=null,h=!1,v=!1,b=null;function S({noDragClassName:_,handleSelector:g,domNode:y,isSelectable:w,nodeId:j,nodeClickDistance:N=0}){p=Ve(y);function B({x:E,y:G}){const{nodeLookup:T,nodeExtent:O,snapGrid:P,snapToGrid:L,nodeOrigin:M,onNodeDrag:F,onSelectionDrag:U,onError:V,updateNodePositions:Y}=t();r={x:E,y:G};let Z=!1;const q=l.size>1,X=q&&O?Yr(wo(l)):null,A=q&&L?sb({dragItems:l,snapGrid:P,x:E,y:G}):null;for(const[C,H]of l){if(!T.has(C))continue;let K={x:E-H.distance.x,y:G-H.distance.y};L&&(K=A?{x:Math.round(K.x+A.x),y:Math.round(K.y+A.y)}:So(K,P));let Q=null;if(q&&O&&!H.extent&&X){const{positionAbsolute:ie}=H.internals,re=ie.x-X.x+O[0][0],J=ie.x+H.measured.width-X.x2+O[1][0],ce=ie.y-X.y+O[0][1],de=ie.y+H.measured.height-X.y2+O[1][1];Q=[[re,ce],[J,de]]}const{position:ee,positionAbsolute:ne}=ju({nodeId:C,nextPosition:K,nodeLookup:T,nodeExtent:Q||O,nodeOrigin:M,onError:V});Z=Z||H.position.x!==ee.x||H.position.y!==ee.y,H.position=ee,H.internals.positionAbsolute=ne}if(v=v||Z,!!Z&&(Y(l,!0),b&&(o||F||!j&&U))){const[C,H]=cr({nodeId:j,dragItems:l,nodeLookup:T});o?.(b,l,C,H),F?.(b,C,H),j||U?.(b,H)}}async function z(){if(!f)return;const{transform:E,panBy:G,autoPanSpeed:T,autoPanOnNodeDrag:O}=t();if(!O){c=!1,cancelAnimationFrame(a);return}const[P,L]=Cu(u,f,T);(P!==0||L!==0)&&(r.x=(r.x??0)-P/E[2],r.y=(r.y??0)-L/E[2],await G({x:P,y:L})&&B(r)),a=requestAnimationFrame(z)}function W(E){const{nodeLookup:G,multiSelectionActive:T,nodesDraggable:O,transform:P,snapGrid:L,snapToGrid:M,selectNodesOnDrag:F,onNodeDragStart:U,onSelectionDragStart:V,unselectNodesAndEdges:Y}=t();d=!0,(!F||!w)&&!T&&j&&(G.get(j)?.selected||Y()),w&&F&&j&&e?.(j);const Z=Qi(E.sourceEvent,{transform:P,snapGrid:L,snapToGrid:M,containerBounds:f});if(r=Z,l=ob(G,O,Z,j),l.size>0&&(n||U||!j&&V)){const[q,X]=cr({nodeId:j,dragItems:l,nodeLookup:G});n?.(E.sourceEvent,l,q,X),U?.(E.sourceEvent,q,X),j||V?.(E.sourceEvent,X)}}const D=iu().clickDistance(N).on("start",E=>{const{domNode:G,nodeDragThreshold:T,transform:O,snapGrid:P,snapToGrid:L}=t();f=G?.getBoundingClientRect()||null,h=!1,v=!1,b=E.sourceEvent,T===0&&W(E),r=Qi(E.sourceEvent,{transform:O,snapGrid:P,snapToGrid:L,containerBounds:f}),u=dt(E.sourceEvent,f)}).on("drag",E=>{const{autoPanOnNodeDrag:G,transform:T,snapGrid:O,snapToGrid:P,nodeDragThreshold:L,nodeLookup:M}=t(),F=Qi(E.sourceEvent,{transform:T,snapGrid:O,snapToGrid:P,containerBounds:f});if(b=E.sourceEvent,(E.sourceEvent.type==="touchmove"&&E.sourceEvent.touches.length>1||j&&!M.has(j))&&(h=!0),!h){if(!c&&G&&d&&(c=!0,z()),!d){const U=dt(E.sourceEvent,f),V=U.x-u.x,Y=U.y-u.y;Math.sqrt(V*V+Y*Y)>L&&W(E)}(r.x!==F.xSnapped||r.y!==F.ySnapped)&&l&&d&&(u=dt(E.sourceEvent,f),B(F))}}).on("end",E=>{if(!(!d||h)&&(c=!1,d=!1,cancelAnimationFrame(a),l.size>0)){const{nodeLookup:G,updateNodePositions:T,onNodeDragStop:O,onSelectionDragStop:P}=t();if(v&&(T(l,!1),v=!1),s||O||!j&&P){const[L,M]=cr({nodeId:j,dragItems:l,nodeLookup:G,dragging:!1});s?.(E.sourceEvent,l,L,M),O?.(E.sourceEvent,L,M),j||P?.(E.sourceEvent,M)}}}).filter(E=>{const G=E.target;return!E.button&&(!_||!Il(G,`.${_}`,y))&&(!g||Il(G,g,y))});p.call(D)}function x(){p?.on(".drag",null)}return{update:S,destroy:x}}function ab(e,t,n){const o=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const r of t.values())uo(s,Mi(r))>0&&o.push(r);return o}const lb=250;function cb(e,t,n,o){let s=[],r=1/0;const a=ab(e,n,t+lb);for(const l of a){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(o.nodeId===u.nodeId&&o.type===u.type&&o.id===u.id)continue;const{x:f,y:d}=ri(l,u,u.position,!0),p=Math.sqrt(Math.pow(f-e.x,2)+Math.pow(d-e.y,2));p>t||(p<r?(s=[{...u,x:f,y:d}],r=p):p===r&&s.push({...u,x:f,y:d}))}}if(!s.length)return null;if(s.length>1){const l=o.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function $u(e,t,n,o,s,r=!1){const a=o.get(e);if(!a)return null;const l=s==="strict"?a.internals.handleBounds?.[t]:[...a.internals.handleBounds?.source??[],...a.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&r?{...c,...ri(a,c,c.position,!0)}:c}function Gu(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function ub(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const Hu=()=>!0;function db(e,{connectionMode:t,connectionRadius:n,handleId:o,nodeId:s,edgeUpdaterType:r,isTarget:a,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:f,flowId:d,panBy:p,cancelConnection:h,onConnectStart:v,onConnect:b,onConnectEnd:S,isValidConnection:x=Hu,onReconnectEnd:_,updateConnection:g,getTransform:y,getFromHandle:w,autoPanSpeed:j,dragThreshold:N=1,handleDomNode:B}){const z=Eu(e.target);let W=0,D;const{x:E,y:G}=dt(e),T=Gu(r,B),O=l?.getBoundingClientRect();let P=!1;if(!O||!T)return;const L=$u(s,T,o,c,t);if(!L)return;let M=dt(e,O),F=!1,U=null,V=!1,Y=null;function Z(){if(!f||!O)return;const[ee,ne]=Cu(M,O,j);p({x:ee,y:ne}),W=requestAnimationFrame(Z)}const q={...L,nodeId:s,type:T,position:L.position},X=c.get(s);let C={inProgress:!0,isValid:null,from:ri(X,q,le.Left,!0),fromHandle:q,fromPosition:q.position,fromNode:X,to:M,toHandle:null,toPosition:bl[q.position],toNode:null,pointer:M};function H(){P=!0,g(C),v?.(e,{nodeId:s,handleId:o,handleType:T})}N===0&&H();function K(ee){if(!P){const{x:de,y:me}=dt(ee),xe=de-E,je=me-G;if(!(xe*xe+je*je>N*N))return;H()}if(!w()||!q){Q(ee);return}const ne=y();M=dt(ee,O),D=cb(_o(M,ne,!1,[1,1]),n,c,q),F||(Z(),F=!0);const ie=Wu(ee,{handle:D,connectionMode:t,fromNodeId:s,fromHandleId:o,fromType:a?"target":"source",isValidConnection:x,doc:z,lib:u,flowId:d,nodeLookup:c});Y=ie.handleDomNode,U=ie.connection,V=ub(!!D,ie.isValid);const re=c.get(s),J=re?ri(re,q,le.Left,!0):C.from,ce={...C,from:J,isValid:V,to:ie.toHandle&&V?bs({x:ie.toHandle.x,y:ie.toHandle.y},ne):M,toHandle:ie.toHandle,toPosition:V&&ie.toHandle?ie.toHandle.position:bl[q.position],toNode:ie.toHandle?c.get(ie.toHandle.nodeId):null,pointer:M};g(ce),C=ce}function Q(ee){if(!("touches"in ee&&ee.touches.length>0)){if(P){(D||Y)&&U&&V&&b?.(U);const{inProgress:ne,...ie}=C,re={...ie,toPosition:C.toHandle?C.toPosition:null};S?.(ee,re),r&&_?.(ee,re)}h(),cancelAnimationFrame(W),F=!1,V=!1,U=null,Y=null,z.removeEventListener("mousemove",K),z.removeEventListener("mouseup",Q),z.removeEventListener("touchmove",K),z.removeEventListener("touchend",Q)}}z.addEventListener("mousemove",K),z.addEventListener("mouseup",Q),z.addEventListener("touchmove",K),z.addEventListener("touchend",Q)}function Wu(e,{handle:t,connectionMode:n,fromNodeId:o,fromHandleId:s,fromType:r,doc:a,lib:l,flowId:c,isValidConnection:u=Hu,nodeLookup:f}){const d=r==="target",p=t?a.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:v}=dt(e),b=a.elementFromPoint(h,v),S=b?.classList.contains(`${l}-flow__handle`)?b:p,x={handleDomNode:S,isValid:!1,connection:null,toHandle:null};if(S){const _=Gu(void 0,S),g=S.getAttribute("data-nodeid"),y=S.getAttribute("data-handleid"),w=S.classList.contains("connectable"),j=S.classList.contains("connectableend");if(!g||!_)return x;const N={source:d?g:o,sourceHandle:d?y:s,target:d?o:g,targetHandle:d?s:y};x.connection=N;const z=w&&j&&(n===_i.Strict?d&&_==="source"||!d&&_==="target":g!==o||y!==s);x.isValid=z&&u(N),x.toHandle=$u(g,_,y,f,n,!0)}return x}const qr={onPointerDown:db,isValid:Wu};function fb({domNode:e,panZoom:t,getTransform:n,getViewScale:o}){const s=Ve(e);function r({translateExtent:l,width:c,height:u,zoomStep:f=1,pannable:d=!0,zoomable:p=!0,inversePan:h=!1}){const v=g=>{if(g.sourceEvent.type!=="wheel"||!t)return;const y=n(),w=g.sourceEvent.ctrlKey&&fo()?10:1,j=-g.sourceEvent.deltaY*(g.sourceEvent.deltaMode===1?.05:g.sourceEvent.deltaMode?1:.002)*f,N=y[2]*Math.pow(2,j*w);t.scaleTo(N)};let b=[0,0];const S=g=>{(g.sourceEvent.type==="mousedown"||g.sourceEvent.type==="touchstart")&&(b=[g.sourceEvent.clientX??g.sourceEvent.touches[0].clientX,g.sourceEvent.clientY??g.sourceEvent.touches[0].clientY])},x=g=>{const y=n();if(g.sourceEvent.type!=="mousemove"&&g.sourceEvent.type!=="touchmove"||!t)return;const w=[g.sourceEvent.clientX??g.sourceEvent.touches[0].clientX,g.sourceEvent.clientY??g.sourceEvent.touches[0].clientY],j=[w[0]-b[0],w[1]-b[1]];b=w;const N=o()*Math.max(y[2],Math.log(y[2]))*(h?-1:1),B={x:y[0]-j[0]*N,y:y[1]-j[1]*N},z=[[0,0],[c,u]];t.setViewportConstrained({x:B.x,y:B.y,zoom:y[2]},z,l)},_=xu().on("start",S).on("zoom",d?x:null).on("zoom.wheel",p?v:null);s.call(_,{})}function a(){s.on("zoom",null)}return{update:r,destroy:a,pointer:st}}const Ds=e=>({x:e.x,y:e.y,zoom:e.k}),ur=({x:e,y:t,zoom:n})=>Bs.translate(e,t).scale(n),gi=(e,t)=>e.target.closest(`.${t}`),Uu=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),pb=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,dr=(e,t=0,n=pb,o=()=>{})=>{const s=typeof t=="number"&&t>0;return s||o(),s?e.transition().duration(t).ease(n).on("end",o):e},Vu=e=>{const t=e.ctrlKey&&fo()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function hb({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:o,panOnScrollMode:s,panOnScrollSpeed:r,zoomOnPinch:a,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return f=>{if(gi(f,t))return f.ctrlKey&&f.preventDefault(),!1;f.preventDefault(),f.stopImmediatePropagation();const d=n.property("__zoom").k||1;if(f.ctrlKey&&a){const S=st(f),x=Vu(f),_=d*Math.pow(2,x);o.scaleTo(n,_,S,f);return}const p=f.deltaMode===1?20:1;let h=s===ni.Vertical?0:f.deltaX*p,v=s===ni.Horizontal?0:f.deltaY*p;!fo()&&f.shiftKey&&s!==ni.Vertical&&(h=f.deltaY*p,v=0),o.translateBy(n,-(h/d)*r,-(v/d)*r,{internal:!0});const b=Ds(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(f,b),e.panScrollTimeout=setTimeout(()=>{u?.(f,b),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(f,b))}}function mb({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(o,s){const r=o.type==="wheel",a=!t&&r&&!o.ctrlKey,l=gi(o,e);if(o.ctrlKey&&r&&l&&o.preventDefault(),a||l)return null;o.preventDefault(),n.call(this,o,s)}}function gb({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return o=>{if(o.sourceEvent?.internal)return;const s=Ds(o.transform);e.mouseButton=o.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,o.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(o.sourceEvent,s)}}function bb({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:o,onPanZoom:s}){return r=>{e.usedRightMouseButton=!!(n&&Uu(t,e.mouseButton??0)),r.sourceEvent?.sync||o([r.transform.x,r.transform.y,r.transform.k]),s&&!r.sourceEvent?.internal&&s?.(r.sourceEvent,Ds(r.transform))}}function xb({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:o,onPanZoomEnd:s,onPaneContextMenu:r}){return a=>{if(!a.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,r&&Uu(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&r(a.sourceEvent),e.usedRightMouseButton=!1,o(!1),s)){const l=Ds(a.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(a.sourceEvent,l)},n?150:0)}}}function yb({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:o,panOnScroll:s,zoomOnDoubleClick:r,userSelectionActive:a,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:f}){return d=>{const p=e||t,h=n&&d.ctrlKey,v=d.type==="wheel";if(d.button===1&&d.type==="mousedown"&&(gi(d,`${u}-flow__node`)||gi(d,`${u}-flow__edge`)))return!0;if(!o&&!p&&!s&&!r&&!n||a||f&&!v||gi(d,l)&&v||gi(d,c)&&(!v||s&&v&&!e)||!n&&d.ctrlKey&&v)return!1;if(!n&&d.type==="touchstart"&&d.touches?.length>1)return d.preventDefault(),!1;if(!p&&!s&&!h&&v||!o&&(d.type==="mousedown"||d.type==="touchstart")||Array.isArray(o)&&!o.includes(d.button)&&d.type==="mousedown")return!1;const b=Array.isArray(o)&&o.includes(d.button)||!d.button||d.button<=1;return(!d.ctrlKey||v)&&b}}function vb({domNode:e,minZoom:t,maxZoom:n,translateExtent:o,viewport:s,onPanZoom:r,onPanZoomStart:a,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},f=e.getBoundingClientRect(),d=xu().scaleExtent([t,n]).translateExtent(o),p=Ve(e).call(d);_({x:s.x,y:s.y,zoom:ji(s.zoom,t,n)},[[0,0],[f.width,f.height]],o);const h=p.on("wheel.zoom"),v=p.on("dblclick.zoom");d.wheelDelta(Vu);function b(D,E){return p?new Promise(G=>{d?.interpolate(E?.interpolate==="linear"?qi:ts).transform(dr(p,E?.duration,E?.ease,()=>G(!0)),D)}):Promise.resolve(!1)}function S({noWheelClassName:D,noPanClassName:E,onPaneContextMenu:G,userSelectionActive:T,panOnScroll:O,panOnDrag:P,panOnScrollMode:L,panOnScrollSpeed:M,preventScrolling:F,zoomOnPinch:U,zoomOnScroll:V,zoomOnDoubleClick:Y,zoomActivationKeyPressed:Z,lib:q,onTransformChange:X,connectionInProgress:A,paneClickDistance:C,selectionOnDrag:H}){T&&!u.isZoomingOrPanning&&x();const K=O&&!Z&&!T;d.clickDistance(H?1/0:!ut(C)||C<0?0:C);const Q=K?hb({zoomPanValues:u,noWheelClassName:D,d3Selection:p,d3Zoom:d,panOnScrollMode:L,panOnScrollSpeed:M,zoomOnPinch:U,onPanZoomStart:a,onPanZoom:r,onPanZoomEnd:l}):mb({noWheelClassName:D,preventScrolling:F,d3ZoomHandler:h});if(p.on("wheel.zoom",Q,{passive:!1}),!T){const ne=gb({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:a});d.on("start",ne);const ie=bb({zoomPanValues:u,panOnDrag:P,onPaneContextMenu:!!G,onPanZoom:r,onTransformChange:X});d.on("zoom",ie);const re=xb({zoomPanValues:u,panOnDrag:P,panOnScroll:O,onPaneContextMenu:G,onPanZoomEnd:l,onDraggingChange:c});d.on("end",re)}const ee=yb({zoomActivationKeyPressed:Z,panOnDrag:P,zoomOnScroll:V,panOnScroll:O,zoomOnDoubleClick:Y,zoomOnPinch:U,userSelectionActive:T,noPanClassName:E,noWheelClassName:D,lib:q,connectionInProgress:A});d.filter(ee),Y?p.on("dblclick.zoom",v):p.on("dblclick.zoom",null)}function x(){d.on("zoom",null)}async function _(D,E,G){const T=ur(D),O=d?.constrain()(T,E,G);return O&&await b(O),new Promise(P=>P(O))}async function g(D,E){const G=ur(D);return await b(G,E),new Promise(T=>T(G))}function y(D){if(p){const E=ur(D),G=p.property("__zoom");(G.k!==D.zoom||G.x!==D.x||G.y!==D.y)&&d?.transform(p,E,null,{sync:!0})}}function w(){const D=p?bu(p.node()):{x:0,y:0,k:1};return{x:D.x,y:D.y,zoom:D.k}}function j(D,E){return p?new Promise(G=>{d?.interpolate(E?.interpolate==="linear"?qi:ts).scaleTo(dr(p,E?.duration,E?.ease,()=>G(!0)),D)}):Promise.resolve(!1)}function N(D,E){return p?new Promise(G=>{d?.interpolate(E?.interpolate==="linear"?qi:ts).scaleBy(dr(p,E?.duration,E?.ease,()=>G(!0)),D)}):Promise.resolve(!1)}function B(D){d?.scaleExtent(D)}function z(D){d?.translateExtent(D)}function W(D){const E=!ut(D)||D<0?0:D;d?.clickDistance(E)}return{update:S,destroy:x,setViewport:g,setViewportConstrained:_,getViewport:w,scaleTo:j,scaleBy:N,setScaleExtent:B,setTranslateExtent:z,syncViewport:y,setClickDistance:W}}var Ni;(function(e){e.Line="line",e.Handle="handle"})(Ni||(Ni={}));function wb({width:e,prevWidth:t,height:n,prevHeight:o,affectsX:s,affectsY:r}){const a=e-t,l=n-o,c=[a>0?1:a<0?-1:0,l>0?1:l<0?-1:0];return a&&s&&(c[0]=c[0]*-1),l&&r&&(c[1]=c[1]*-1),c}function El(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),o=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:o,affectsY:s}}function dn(e,t){return Math.max(0,t-e)}function fn(e,t){return Math.max(0,e-t)}function zo(e,t,n){return Math.max(0,t-e,e-n)}function Al(e,t){return e?!t:t}function Sb(e,t,n,o,s,r,a,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:f,isVertical:d}=t,p=f&&d,{xSnapped:h,ySnapped:v}=n,{minWidth:b,maxWidth:S,minHeight:x,maxHeight:_}=o,{x:g,y,width:w,height:j,aspectRatio:N}=e;let B=Math.floor(f?h-e.pointerX:0),z=Math.floor(d?v-e.pointerY:0);const W=w+(c?-B:B),D=j+(u?-z:z),E=-r[0]*w,G=-r[1]*j;let T=zo(W,b,S),O=zo(D,x,_);if(a){let M=0,F=0;c&&B<0?M=dn(g+B+E,a[0][0]):!c&&B>0&&(M=fn(g+W+E,a[1][0])),u&&z<0?F=dn(y+z+G,a[0][1]):!u&&z>0&&(F=fn(y+D+G,a[1][1])),T=Math.max(T,M),O=Math.max(O,F)}if(l){let M=0,F=0;c&&B>0?M=fn(g+B,l[0][0]):!c&&B<0&&(M=dn(g+W,l[1][0])),u&&z>0?F=fn(y+z,l[0][1]):!u&&z<0&&(F=dn(y+D,l[1][1])),T=Math.max(T,M),O=Math.max(O,F)}if(s){if(f){const M=zo(W/N,x,_)*N;if(T=Math.max(T,M),a){let F=0;!c&&!u||c&&!u&&p?F=fn(y+G+W/N,a[1][1])*N:F=dn(y+G+(c?B:-B)/N,a[0][1])*N,T=Math.max(T,F)}if(l){let F=0;!c&&!u||c&&!u&&p?F=dn(y+W/N,l[1][1])*N:F=fn(y+(c?B:-B)/N,l[0][1])*N,T=Math.max(T,F)}}if(d){const M=zo(D*N,b,S)/N;if(O=Math.max(O,M),a){let F=0;!c&&!u||u&&!c&&p?F=fn(g+D*N+E,a[1][0])/N:F=dn(g+(u?z:-z)*N+E,a[0][0])/N,O=Math.max(O,F)}if(l){let F=0;!c&&!u||u&&!c&&p?F=dn(g+D*N,l[1][0])/N:F=fn(g+(u?z:-z)*N,l[0][0])/N,O=Math.max(O,F)}}}z=z+(z<0?O:-O),B=B+(B<0?T:-T),s&&(p?W>D*N?z=(Al(c,u)?-B:B)/N:B=(Al(c,u)?-z:z)*N:f?(z=B/N,u=c):(B=z*N,c=u));const P=c?g+B:g,L=u?y+z:y;return{width:w+(c?-B:B),height:j+(u?-z:z),x:r[0]*B*(c?-1:1)+P,y:r[1]*z*(u?-1:1)+L}}const Yu={width:0,height:0,x:0,y:0},_b={...Yu,pointerX:0,pointerY:0,aspectRatio:1};function jb(e){return[[0,0],[e.measured.width,e.measured.height]]}function Mb(e,t,n){const o=t.position.x+e.position.x,s=t.position.y+e.position.y,r=e.measured.width??0,a=e.measured.height??0,l=n[0]*r,c=n[1]*a;return[[o-l,s-c],[o+r-l,s+a-c]]}function Cb({domNode:e,nodeId:t,getStoreItems:n,onChange:o,onEnd:s}){const r=Ve(e);let a={controlDirection:El("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:f,keepAspectRatio:d,resizeDirection:p,onResizeStart:h,onResize:v,onResizeEnd:b,shouldResize:S}){let x={...Yu},_={..._b};a={boundaries:f,resizeDirection:p,keepAspectRatio:d,controlDirection:El(u)};let g,y=null,w=[],j,N,B,z=!1;const W=iu().on("start",D=>{const{nodeLookup:E,transform:G,snapGrid:T,snapToGrid:O,nodeOrigin:P,paneDomNode:L}=n();if(g=E.get(t),!g)return;y=L?.getBoundingClientRect()??null;const{xSnapped:M,ySnapped:F}=Qi(D.sourceEvent,{transform:G,snapGrid:T,snapToGrid:O,containerBounds:y});x={width:g.measured.width??0,height:g.measured.height??0,x:g.position.x??0,y:g.position.y??0},_={...x,pointerX:M,pointerY:F,aspectRatio:x.width/x.height},j=void 0,g.parentId&&(g.extent==="parent"||g.expandParent)&&(j=E.get(g.parentId),N=j&&g.extent==="parent"?jb(j):void 0),w=[],B=void 0;for(const[U,V]of E)if(V.parentId===t&&(w.push({id:U,position:{...V.position},extent:V.extent}),V.extent==="parent"||V.expandParent)){const Y=Mb(V,g,V.origin??P);B?B=[[Math.min(Y[0][0],B[0][0]),Math.min(Y[0][1],B[0][1])],[Math.max(Y[1][0],B[1][0]),Math.max(Y[1][1],B[1][1])]]:B=Y}h?.(D,{...x})}).on("drag",D=>{const{transform:E,snapGrid:G,snapToGrid:T,nodeOrigin:O}=n(),P=Qi(D.sourceEvent,{transform:E,snapGrid:G,snapToGrid:T,containerBounds:y}),L=[];if(!g)return;const{x:M,y:F,width:U,height:V}=x,Y={},Z=g.origin??O,{width:q,height:X,x:A,y:C}=Sb(_,a.controlDirection,P,a.boundaries,a.keepAspectRatio,Z,N,B),H=q!==U,K=X!==V,Q=A!==M&&H,ee=C!==F&&K;if(!Q&&!ee&&!H&&!K)return;if((Q||ee||Z[0]===1||Z[1]===1)&&(Y.x=Q?A:x.x,Y.y=ee?C:x.y,x.x=Y.x,x.y=Y.y,w.length>0)){const J=A-M,ce=C-F;for(const de of w)de.position={x:de.position.x-J+Z[0]*(q-U),y:de.position.y-ce+Z[1]*(X-V)},L.push(de)}if((H||K)&&(Y.width=H&&(!a.resizeDirection||a.resizeDirection==="horizontal")?q:x.width,Y.height=K&&(!a.resizeDirection||a.resizeDirection==="vertical")?X:x.height,x.width=Y.width,x.height=Y.height),j&&g.expandParent){const J=Z[0]*(Y.width??0);Y.x&&Y.x<J&&(x.x=J,_.x=_.x-(Y.x-J));const ce=Z[1]*(Y.height??0);Y.y&&Y.y<ce&&(x.y=ce,_.y=_.y-(Y.y-ce))}const ne=wb({width:x.width,prevWidth:U,height:x.height,prevHeight:V,affectsX:a.controlDirection.affectsX,affectsY:a.controlDirection.affectsY}),ie={...x,direction:ne};S?.(D,ie)!==!1&&(z=!0,v?.(D,ie),o(Y,L))}).on("end",D=>{z&&(b?.(D,{...x}),s?.({...x}),z=!1)});r.call(W)}function c(){r.on(".drag",null)}return{update:l,destroy:c}}const Fs=m.createContext(null),Nb=Fs.Provider,Zu=Et.error001();function he(e,t){const n=m.useContext(Fs);if(n===null)throw new Error(Zu);return kc.useStoreWithEqualityFn(n,e,t)}function _e(){const e=m.useContext(Fs);if(e===null)throw new Error(Zu);return m.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const kl={display:"none"},Tb={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Xu="react-flow__node-desc",Ku="react-flow__edge-desc",Ib="react-flow__aria-live",Eb=e=>e.ariaLiveMessage,Ab=e=>e.ariaLabelConfig;function kb({rfId:e}){const t=he(Eb);return i.jsx("div",{id:`${Ib}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:Tb,children:t})}function Bb({rfId:e,disableKeyboardA11y:t}){const n=he(Ab);return i.jsxs(i.Fragment,{children:[i.jsx("div",{id:`${Xu}-${e}`,style:kl,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),i.jsx("div",{id:`${Ku}-${e}`,style:kl,children:n["edge.a11yDescription.default"]}),!t&&i.jsx(kb,{rfId:e})]})}const Ls=m.forwardRef(({position:e="top-left",children:t,className:n,style:o,...s},r)=>{const a=`${e}`.split("-");return i.jsx("div",{className:Ee(["react-flow__panel",n,...a]),style:o,ref:r,...s,children:t})});Ls.displayName="Panel";function Pb({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:i.jsx(Ls,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:i.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const Rb=e=>{const t=[],n=[];for(const[,o]of e.nodeLookup)o.selected&&t.push(o.internals.userNode);for(const[,o]of e.edgeLookup)o.selected&&n.push(o);return{selectedNodes:t,selectedEdges:n}},Oo=e=>e.id;function Db(e,t){return Se.shallow(e.selectedNodes.map(Oo),t.selectedNodes.map(Oo))&&Se.shallow(e.selectedEdges.map(Oo),t.selectedEdges.map(Oo))}function Fb({onSelectionChange:e}){const t=_e(),{selectedNodes:n,selectedEdges:o}=he(Rb,Db);return m.useEffect(()=>{const s={nodes:n,edges:o};e?.(s),t.getState().onSelectionChangeHandlers.forEach(r=>r(s))},[n,o,e]),null}const Lb=e=>!!e.onSelectionChangeHandlers;function zb({onSelectionChange:e}){const t=he(Lb);return e||t?i.jsx(Fb,{onSelectionChange:e}):null}const Qr=typeof window<"u"?m.useLayoutEffect:m.useEffect,qu=[0,0],Ob={x:0,y:0,zoom:1},$b=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],Bl=[...$b,"rfId"],Gb=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),Pl={translateExtent:ao,nodeOrigin:qu,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function Hb(e){const{setNodes:t,setEdges:n,setMinZoom:o,setMaxZoom:s,setTranslateExtent:r,setNodeExtent:a,reset:l,setDefaultNodesAndEdges:c}=he(Gb,Se.shallow),u=_e();Qr(()=>(c(e.defaultNodes,e.defaultEdges),()=>{f.current=Pl,l()}),[]);const f=m.useRef(Pl);return Qr(()=>{for(const d of Bl){const p=e[d],h=f.current[d];p!==h&&(typeof e[d]>"u"||(d==="nodes"?t(p):d==="edges"?n(p):d==="minZoom"?o(p):d==="maxZoom"?s(p):d==="translateExtent"?r(p):d==="nodeExtent"?a(p):d==="ariaLabelConfig"?u.setState({ariaLabelConfig:L0(p)}):d==="fitView"?u.setState({fitViewQueued:p}):d==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[d]:p})))}f.current=e},Bl.map(d=>e[d])),null}function Rl(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Wb(e){const[t,n]=m.useState(e==="system"?null:e);return m.useEffect(()=>{if(e!=="system"){n(e);return}const o=Rl(),s=()=>n(o?.matches?"dark":"light");return s(),o?.addEventListener("change",s),()=>{o?.removeEventListener("change",s)}},[e]),t!==null?t:Rl()?.matches?"dark":"light"}const Dl=typeof document<"u"?document:null;function po(e=null,t={target:Dl,actInsideInputWithModifier:!0}){const[n,o]=m.useState(!1),s=m.useRef(!1),r=m.useRef(new Set([])),[a,l]=m.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(d=>typeof d=="string").map(d=>d.replace("+",`
|
|
2
|
+
`).replace(`
|
|
3
|
+
|
|
4
|
+
`,`
|
|
5
|
+
+`).split(`
|
|
6
|
+
`)),f=u.reduce((d,p)=>d.concat(...p),[]);return[u,f]}return[[],[]]},[e]);return m.useEffect(()=>{const c=t?.target??Dl,u=t?.actInsideInputWithModifier??!0;if(e!==null){const f=h=>{if(s.current=h.ctrlKey||h.metaKey||h.shiftKey||h.altKey,(!s.current||s.current&&!u)&&Au(h))return!1;const b=Ll(h.code,l);if(r.current.add(h[b]),Fl(a,r.current,!1)){const S=h.composedPath?.()?.[0]||h.target,x=S?.nodeName==="BUTTON"||S?.nodeName==="A";t.preventDefault!==!1&&(s.current||!x)&&h.preventDefault(),o(!0)}},d=h=>{const v=Ll(h.code,l);Fl(a,r.current,!0)?(o(!1),r.current.clear()):r.current.delete(h[v]),h.key==="Meta"&&r.current.clear(),s.current=!1},p=()=>{r.current.clear(),o(!1)};return c?.addEventListener("keydown",f),c?.addEventListener("keyup",d),window.addEventListener("blur",p),window.addEventListener("contextmenu",p),()=>{c?.removeEventListener("keydown",f),c?.removeEventListener("keyup",d),window.removeEventListener("blur",p),window.removeEventListener("contextmenu",p)}}},[e,o]),n}function Fl(e,t,n){return e.filter(o=>n||o.length===t.size).some(o=>o.every(s=>t.has(s)))}function Ll(e,t){return t.includes(e)?"code":"key"}const Ub=()=>{const e=_e();return m.useMemo(()=>({zoomIn:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1.2,t):Promise.resolve(!1)},zoomOut:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,t):Promise.resolve(!1)},zoomTo:(t,n)=>{const{panZoom:o}=e.getState();return o?o.scaleTo(t,n):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{const{transform:[o,s,r],panZoom:a}=e.getState();return a?(await a.setViewport({x:t.x??o,y:t.y??s,zoom:t.zoom??r},n),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[t,n,o]=e.getState().transform;return{x:t,y:n,zoom:o}},setCenter:async(t,n,o)=>e.getState().setCenter(t,n,o),fitBounds:async(t,n)=>{const{width:o,height:s,minZoom:r,maxZoom:a,panZoom:l}=e.getState(),c=_a(t,o,s,r,a,n?.padding??.1);return l?(await l.setViewport(c,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{const{transform:o,snapGrid:s,snapToGrid:r,domNode:a}=e.getState();if(!a)return t;const{x:l,y:c}=a.getBoundingClientRect(),u={x:t.x-l,y:t.y-c},f=n.snapGrid??s,d=n.snapToGrid??r;return _o(u,o,d,f)},flowToScreenPosition:t=>{const{transform:n,domNode:o}=e.getState();if(!o)return t;const{x:s,y:r}=o.getBoundingClientRect(),a=bs(t,n);return{x:a.x+s,y:a.y+r}}}),[])};function Qu(e,t){const n=[],o=new Map,s=[];for(const r of e)if(r.type==="add"){s.push(r);continue}else if(r.type==="remove"||r.type==="replace")o.set(r.id,[r]);else{const a=o.get(r.id);a?a.push(r):o.set(r.id,[r])}for(const r of t){const a=o.get(r.id);if(!a){n.push(r);continue}if(a[0].type==="remove")continue;if(a[0].type==="replace"){n.push({...a[0].item});continue}const l={...r};for(const c of a)Vb(c,l);n.push(l)}return s.length&&s.forEach(r=>{r.index!==void 0?n.splice(r.index,0,{...r.item}):n.push({...r.item})}),n}function Vb(e,t){switch(e.type){case"select":{t.selected=e.selected;break}case"position":{typeof e.position<"u"&&(t.position=e.position),typeof e.dragging<"u"&&(t.dragging=e.dragging);break}case"dimensions":{typeof e.dimensions<"u"&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes==="width")&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes==="height")&&(t.height=e.dimensions.height))),typeof e.resizing=="boolean"&&(t.resizing=e.resizing);break}}}function Ju(e,t){return Qu(e,t)}function ed(e,t){return Qu(e,t)}function Qn(e,t){return{id:e,type:"select",selected:t}}function bi(e,t=new Set,n=!1){const o=[];for(const[s,r]of e){const a=t.has(s);!(r.selected===void 0&&!a)&&r.selected!==a&&(n&&(r.selected=a),o.push(Qn(r.id,a)))}return o}function zl({items:e=[],lookup:t}){const n=[],o=new Map(e.map(s=>[s.id,s]));for(const[s,r]of e.entries()){const a=t.get(r.id),l=a?.internals?.userNode??a;l!==void 0&&l!==r&&n.push({id:r.id,item:r,type:"replace"}),l===void 0&&n.push({item:r,type:"add",index:s})}for(const[s]of t)o.get(s)===void 0&&n.push({id:s,type:"remove"});return n}function Ol(e){return{id:e.id,type:"remove"}}const $l=e=>T0(e),Yb=e=>_u(e);function td(e){return m.forwardRef(e)}function Gl(e){const[t,n]=m.useState(BigInt(0)),[o]=m.useState(()=>Zb(()=>n(s=>s+BigInt(1))));return Qr(()=>{const s=o.get();s.length&&(e(s),o.reset())},[t]),o}function Zb(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const nd=m.createContext(null);function Xb({children:e}){const t=_e(),n=m.useCallback(l=>{const{nodes:c=[],setNodes:u,hasDefaultNodes:f,onNodesChange:d,nodeLookup:p,fitViewQueued:h,onNodesChangeMiddlewareMap:v}=t.getState();let b=c;for(const x of l)b=typeof x=="function"?x(b):x;let S=zl({items:b,lookup:p});for(const x of v.values())S=x(S);f&&u(b),S.length>0?d?.(S):h&&window.requestAnimationFrame(()=>{const{fitViewQueued:x,nodes:_,setNodes:g}=t.getState();x&&g(_)})},[]),o=Gl(n),s=m.useCallback(l=>{const{edges:c=[],setEdges:u,hasDefaultEdges:f,onEdgesChange:d,edgeLookup:p}=t.getState();let h=c;for(const v of l)h=typeof v=="function"?v(h):v;f?u(h):d&&d(zl({items:h,lookup:p}))},[]),r=Gl(s),a=m.useMemo(()=>({nodeQueue:o,edgeQueue:r}),[]);return i.jsx(nd.Provider,{value:a,children:e})}function Kb(){const e=m.useContext(nd);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const qb=e=>!!e.panZoom;function Ea(){const e=Ub(),t=_e(),n=Kb(),o=he(qb),s=m.useMemo(()=>{const r=d=>t.getState().nodeLookup.get(d),a=d=>{n.nodeQueue.push(d)},l=d=>{n.edgeQueue.push(d)},c=d=>{const{nodeLookup:p,nodeOrigin:h}=t.getState(),v=$l(d)?d:p.get(d.id),b=v.parentId?Iu(v.position,v.measured,v.parentId,p,h):v.position,S={...v,position:b,width:v.measured?.width??v.width,height:v.measured?.height??v.height};return Mi(S)},u=(d,p,h={replace:!1})=>{a(v=>v.map(b=>{if(b.id===d){const S=typeof p=="function"?p(b):p;return h.replace&&$l(S)?S:{...b,...S}}return b}))},f=(d,p,h={replace:!1})=>{l(v=>v.map(b=>{if(b.id===d){const S=typeof p=="function"?p(b):p;return h.replace&&Yb(S)?S:{...b,...S}}return b}))};return{getNodes:()=>t.getState().nodes.map(d=>({...d})),getNode:d=>r(d)?.internals.userNode,getInternalNode:r,getEdges:()=>{const{edges:d=[]}=t.getState();return d.map(p=>({...p}))},getEdge:d=>t.getState().edgeLookup.get(d),setNodes:a,setEdges:l,addNodes:d=>{const p=Array.isArray(d)?d:[d];n.nodeQueue.push(h=>[...h,...p])},addEdges:d=>{const p=Array.isArray(d)?d:[d];n.edgeQueue.push(h=>[...h,...p])},toObject:()=>{const{nodes:d=[],edges:p=[],transform:h}=t.getState(),[v,b,S]=h;return{nodes:d.map(x=>({...x})),edges:p.map(x=>({...x})),viewport:{x:v,y:b,zoom:S}}},deleteElements:async({nodes:d=[],edges:p=[]})=>{const{nodes:h,edges:v,onNodesDelete:b,onEdgesDelete:S,triggerNodeChanges:x,triggerEdgeChanges:_,onDelete:g,onBeforeDelete:y}=t.getState(),{nodes:w,edges:j}=await B0({nodesToRemove:d,edgesToRemove:p,nodes:h,edges:v,onBeforeDelete:y}),N=j.length>0,B=w.length>0;if(N){const z=j.map(Ol);S?.(j),_(z)}if(B){const z=w.map(Ol);b?.(w),x(z)}return(B||N)&&g?.({nodes:w,edges:j}),{deletedNodes:w,deletedEdges:j}},getIntersectingNodes:(d,p=!0,h)=>{const v=yl(d),b=v?d:c(d),S=h!==void 0;return b?(h||t.getState().nodes).filter(x=>{const _=t.getState().nodeLookup.get(x.id);if(_&&!v&&(x.id===d.id||!_.internals.positionAbsolute))return!1;const g=Mi(S?x:_),y=uo(g,b);return p&&y>0||y>=g.width*g.height||y>=b.width*b.height}):[]},isNodeIntersecting:(d,p,h=!0)=>{const b=yl(d)?d:c(d);if(!b)return!1;const S=uo(b,p);return h&&S>0||S>=p.width*p.height||S>=b.width*b.height},updateNode:u,updateNodeData:(d,p,h={replace:!1})=>{u(d,v=>{const b=typeof p=="function"?p(v):p;return h.replace?{...v,data:b}:{...v,data:{...v.data,...b}}},h)},updateEdge:f,updateEdgeData:(d,p,h={replace:!1})=>{f(d,v=>{const b=typeof p=="function"?p(v):p;return h.replace?{...v,data:b}:{...v,data:{...v.data,...b}}},h)},getNodesBounds:d=>{const{nodeLookup:p,nodeOrigin:h}=t.getState();return I0(d,{nodeLookup:p,nodeOrigin:h})},getHandleConnections:({type:d,id:p,nodeId:h})=>Array.from(t.getState().connectionLookup.get(`${h}-${d}${p?`-${p}`:""}`)?.values()??[]),getNodeConnections:({type:d,handleId:p,nodeId:h})=>Array.from(t.getState().connectionLookup.get(`${h}${d?p?`-${d}-${p}`:`-${d}`:""}`)?.values()??[]),fitView:async d=>{const p=t.getState().fitViewResolver??F0();return t.setState({fitViewQueued:!0,fitViewOptions:d,fitViewResolver:p}),n.nodeQueue.push(h=>[...h]),p.promise}}},[]);return m.useMemo(()=>({...s,...e,viewportInitialized:o}),[o])}const Hl=e=>e.selected,Qb=typeof window<"u"?window:void 0;function Jb({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=_e(),{deleteElements:o}=Ea(),s=po(e,{actInsideInputWithModifier:!1}),r=po(t,{target:Qb});m.useEffect(()=>{if(s){const{edges:a,nodes:l}=n.getState();o({nodes:l.filter(Hl),edges:a.filter(Hl)}),n.setState({nodesSelectionActive:!1})}},[s]),m.useEffect(()=>{n.setState({multiSelectionActive:r})},[r])}function ex(e){const t=_e();m.useEffect(()=>{const n=()=>{if(!e.current||!(e.current.checkVisibility?.()??!0))return!1;const o=ja(e.current);(o.height===0||o.width===0)&&t.getState().onError?.("004",Et.error004()),t.setState({width:o.width||500,height:o.height||500})};if(e.current){n(),window.addEventListener("resize",n);const o=new ResizeObserver(()=>n());return o.observe(e.current),()=>{window.removeEventListener("resize",n),o&&e.current&&o.unobserve(e.current)}}},[])}const zs={position:"absolute",width:"100%",height:"100%",top:0,left:0},tx=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function nx({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:o=!1,panOnScrollSpeed:s=.5,panOnScrollMode:r=ni.Free,zoomOnDoubleClick:a=!0,panOnDrag:l=!0,defaultViewport:c,translateExtent:u,minZoom:f,maxZoom:d,zoomActivationKeyCode:p,preventScrolling:h=!0,children:v,noWheelClassName:b,noPanClassName:S,onViewportChange:x,isControlledViewport:_,paneClickDistance:g,selectionOnDrag:y}){const w=_e(),j=m.useRef(null),{userSelectionActive:N,lib:B,connectionInProgress:z}=he(tx,Se.shallow),W=po(p),D=m.useRef();ex(j);const E=m.useCallback(G=>{x?.({x:G[0],y:G[1],zoom:G[2]}),_||w.setState({transform:G})},[x,_]);return m.useEffect(()=>{if(j.current){D.current=vb({domNode:j.current,minZoom:f,maxZoom:d,translateExtent:u,viewport:c,onDraggingChange:P=>w.setState(L=>L.paneDragging===P?L:{paneDragging:P}),onPanZoomStart:(P,L)=>{const{onViewportChangeStart:M,onMoveStart:F}=w.getState();F?.(P,L),M?.(L)},onPanZoom:(P,L)=>{const{onViewportChange:M,onMove:F}=w.getState();F?.(P,L),M?.(L)},onPanZoomEnd:(P,L)=>{const{onViewportChangeEnd:M,onMoveEnd:F}=w.getState();F?.(P,L),M?.(L)}});const{x:G,y:T,zoom:O}=D.current.getViewport();return w.setState({panZoom:D.current,transform:[G,T,O],domNode:j.current.closest(".react-flow")}),()=>{D.current?.destroy()}}},[]),m.useEffect(()=>{D.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:o,panOnScrollSpeed:s,panOnScrollMode:r,zoomOnDoubleClick:a,panOnDrag:l,zoomActivationKeyPressed:W,preventScrolling:h,noPanClassName:S,userSelectionActive:N,noWheelClassName:b,lib:B,onTransformChange:E,connectionInProgress:z,selectionOnDrag:y,paneClickDistance:g})},[e,t,n,o,s,r,a,l,W,h,S,N,b,B,E,z,y,g]),i.jsx("div",{className:"react-flow__renderer",ref:j,style:zs,children:v})}const ix=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function ox(){const{userSelectionActive:e,userSelectionRect:t}=he(ix,Se.shallow);return e&&t?i.jsx("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}const fr=(e,t)=>n=>{n.target===t.current&&e?.(n)},sx=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function rx({isSelecting:e,selectionKeyPressed:t,selectionMode:n=lo.Full,panOnDrag:o,paneClickDistance:s,selectionOnDrag:r,onSelectionStart:a,onSelectionEnd:l,onPaneClick:c,onPaneContextMenu:u,onPaneScroll:f,onPaneMouseEnter:d,onPaneMouseMove:p,onPaneMouseLeave:h,children:v}){const b=_e(),{userSelectionActive:S,elementsSelectable:x,dragging:_,connectionInProgress:g}=he(sx,Se.shallow),y=x&&(e||S),w=m.useRef(null),j=m.useRef(),N=m.useRef(new Set),B=m.useRef(new Set),z=m.useRef(!1),W=M=>{if(z.current||g){z.current=!1;return}c?.(M),b.getState().resetSelectedElements(),b.setState({nodesSelectionActive:!1})},D=M=>{if(Array.isArray(o)&&o?.includes(2)){M.preventDefault();return}u?.(M)},E=f?M=>f(M):void 0,G=M=>{z.current&&(M.stopPropagation(),z.current=!1)},T=M=>{const{domNode:F}=b.getState();if(j.current=F?.getBoundingClientRect(),!j.current)return;const U=M.target===w.current;if(!U&&!!M.target.closest(".nokey")||!e||!(r&&U||t)||M.button!==0||!M.isPrimary)return;M.target?.setPointerCapture?.(M.pointerId),z.current=!1;const{x:Z,y:q}=dt(M.nativeEvent,j.current);b.setState({userSelectionRect:{width:0,height:0,startX:Z,startY:q,x:Z,y:q}}),U||(M.stopPropagation(),M.preventDefault())},O=M=>{const{userSelectionRect:F,transform:U,nodeLookup:V,edgeLookup:Y,connectionLookup:Z,triggerNodeChanges:q,triggerEdgeChanges:X,defaultEdgeOptions:A,resetSelectedElements:C}=b.getState();if(!j.current||!F)return;const{x:H,y:K}=dt(M.nativeEvent,j.current),{startX:Q,startY:ee}=F;if(!z.current){const ce=t?0:s;if(Math.hypot(H-Q,K-ee)<=ce)return;C(),a?.(M)}z.current=!0;const ne={startX:Q,startY:ee,x:H<Q?H:Q,y:K<ee?K:ee,width:Math.abs(H-Q),height:Math.abs(K-ee)},ie=N.current,re=B.current;N.current=new Set(Sa(V,ne,U,n===lo.Partial,!0).map(ce=>ce.id)),B.current=new Set;const J=A?.selectable??!0;for(const ce of N.current){const de=Z.get(ce);if(de)for(const{edgeId:me}of de.values()){const xe=Y.get(me);xe&&(xe.selectable??J)&&B.current.add(me)}}if(!vl(ie,N.current)){const ce=bi(V,N.current,!0);q(ce)}if(!vl(re,B.current)){const ce=bi(Y,B.current);X(ce)}b.setState({userSelectionRect:ne,userSelectionActive:!0,nodesSelectionActive:!1})},P=M=>{M.button===0&&(M.target?.releasePointerCapture?.(M.pointerId),!S&&M.target===w.current&&b.getState().userSelectionRect&&W?.(M),b.setState({userSelectionActive:!1,userSelectionRect:null}),z.current&&(l?.(M),b.setState({nodesSelectionActive:N.current.size>0})))},L=o===!0||Array.isArray(o)&&o.includes(0);return i.jsxs("div",{className:Ee(["react-flow__pane",{draggable:L,dragging:_,selection:e}]),onClick:y?void 0:fr(W,w),onContextMenu:fr(D,w),onWheel:fr(E,w),onPointerEnter:y?void 0:d,onPointerMove:y?O:p,onPointerUp:y?P:void 0,onPointerDownCapture:y?T:void 0,onClickCapture:y?G:void 0,onPointerLeave:h,ref:w,style:zs,children:[v,i.jsx(ox,{})]})}function Jr({id:e,store:t,unselect:n=!1,nodeRef:o}){const{addSelectedNodes:s,unselectNodesAndEdges:r,multiSelectionActive:a,nodeLookup:l,onError:c}=t.getState(),u=l.get(e);if(!u){c?.("012",Et.error012(e));return}t.setState({nodesSelectionActive:!1}),u.selected?(n||u.selected&&a)&&(r({nodes:[u],edges:[]}),requestAnimationFrame(()=>o?.current?.blur())):s([e])}function id({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:o,nodeId:s,isSelectable:r,nodeClickDistance:a}){const l=_e(),[c,u]=m.useState(!1),f=m.useRef();return m.useEffect(()=>{f.current=rb({getStoreItems:()=>l.getState(),onNodeMouseDown:d=>{Jr({id:d,store:l,nodeRef:e})},onDragStart:()=>{u(!0)},onDragStop:()=>{u(!1)}})},[]),m.useEffect(()=>{if(!(t||!e.current||!f.current))return f.current.update({noDragClassName:n,handleSelector:o,domNode:e.current,isSelectable:r,nodeId:s,nodeClickDistance:a}),()=>{f.current?.destroy()}},[n,o,t,r,e,s,a]),c}const ax=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function od(){const e=_e();return m.useCallback(n=>{const{nodeExtent:o,snapToGrid:s,snapGrid:r,nodesDraggable:a,onError:l,updateNodePositions:c,nodeLookup:u,nodeOrigin:f}=e.getState(),d=new Map,p=ax(a),h=s?r[0]:5,v=s?r[1]:5,b=n.direction.x*h*n.factor,S=n.direction.y*v*n.factor;for(const[,x]of u){if(!p(x))continue;let _={x:x.internals.positionAbsolute.x+b,y:x.internals.positionAbsolute.y+S};s&&(_=So(_,r));const{position:g,positionAbsolute:y}=ju({nodeId:x.id,nextPosition:_,nodeLookup:u,nodeExtent:o,nodeOrigin:f,onError:l});x.position=g,x.internals.positionAbsolute=y,d.set(x.id,x)}c(d)},[])}const Aa=m.createContext(null),lx=Aa.Provider;Aa.Consumer;const sd=()=>m.useContext(Aa),cx=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),ux=(e,t,n)=>o=>{const{connectionClickStartHandle:s,connectionMode:r,connection:a}=o,{fromHandle:l,toHandle:c,isValid:u}=a,f=c?.nodeId===e&&c?.id===t&&c?.type===n;return{connectingFrom:l?.nodeId===e&&l?.id===t&&l?.type===n,connectingTo:f,clickConnecting:s?.nodeId===e&&s?.id===t&&s?.type===n,isPossibleEndHandle:r===_i.Strict?l?.type!==n:e!==l?.nodeId||t!==l?.id,connectionInProcess:!!l,clickConnectionInProcess:!!s,valid:f&&u}};function dx({type:e="source",position:t=le.Top,isValidConnection:n,isConnectable:o=!0,isConnectableStart:s=!0,isConnectableEnd:r=!0,id:a,onConnect:l,children:c,className:u,onMouseDown:f,onTouchStart:d,...p},h){const v=a||null,b=e==="target",S=_e(),x=sd(),{connectOnClick:_,noPanClassName:g,rfId:y}=he(cx,Se.shallow),{connectingFrom:w,connectingTo:j,clickConnecting:N,isPossibleEndHandle:B,connectionInProcess:z,clickConnectionInProcess:W,valid:D}=he(ux(x,v,e),Se.shallow);x||S.getState().onError?.("010",Et.error010());const E=O=>{const{defaultEdgeOptions:P,onConnect:L,hasDefaultEdges:M}=S.getState(),F={...P,...O};if(M){const{edges:U,setEdges:V}=S.getState();V(W0(F,U))}L?.(F),l?.(F)},G=O=>{if(!x)return;const P=ku(O.nativeEvent);if(s&&(P&&O.button===0||!P)){const L=S.getState();qr.onPointerDown(O.nativeEvent,{handleDomNode:O.currentTarget,autoPanOnConnect:L.autoPanOnConnect,connectionMode:L.connectionMode,connectionRadius:L.connectionRadius,domNode:L.domNode,nodeLookup:L.nodeLookup,lib:L.lib,isTarget:b,handleId:v,nodeId:x,flowId:L.rfId,panBy:L.panBy,cancelConnection:L.cancelConnection,onConnectStart:L.onConnectStart,onConnectEnd:(...M)=>S.getState().onConnectEnd?.(...M),updateConnection:L.updateConnection,onConnect:E,isValidConnection:n||((...M)=>S.getState().isValidConnection?.(...M)??!0),getTransform:()=>S.getState().transform,getFromHandle:()=>S.getState().connection.fromHandle,autoPanSpeed:L.autoPanSpeed,dragThreshold:L.connectionDragThreshold})}P?f?.(O):d?.(O)},T=O=>{const{onClickConnectStart:P,onClickConnectEnd:L,connectionClickStartHandle:M,connectionMode:F,isValidConnection:U,lib:V,rfId:Y,nodeLookup:Z,connection:q}=S.getState();if(!x||!M&&!s)return;if(!M){P?.(O.nativeEvent,{nodeId:x,handleId:v,handleType:e}),S.setState({connectionClickStartHandle:{nodeId:x,type:e,id:v}});return}const X=Eu(O.target),A=n||U,{connection:C,isValid:H}=qr.isValid(O.nativeEvent,{handle:{nodeId:x,id:v,type:e},connectionMode:F,fromNodeId:M.nodeId,fromHandleId:M.id||null,fromType:M.type,isValidConnection:A,flowId:Y,doc:X,lib:V,nodeLookup:Z});H&&C&&E(C);const K=structuredClone(q);delete K.inProgress,K.toPosition=K.toHandle?K.toHandle.position:null,L?.(O,K),S.setState({connectionClickStartHandle:null})};return i.jsx("div",{"data-handleid":v,"data-nodeid":x,"data-handlepos":t,"data-id":`${y}-${x}-${v}-${e}`,className:Ee(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",g,u,{source:!b,target:b,connectable:o,connectablestart:s,connectableend:r,clickconnecting:N,connectingfrom:w,connectingto:j,valid:D,connectionindicator:o&&(!z||B)&&(z||W?r:s)}]),onMouseDown:G,onTouchStart:G,onClick:_?T:void 0,ref:h,...p,children:c})}const xs=m.memo(td(dx));function fx({data:e,isConnectable:t,sourcePosition:n=le.Bottom}){return i.jsxs(i.Fragment,{children:[e?.label,i.jsx(xs,{type:"source",position:n,isConnectable:t})]})}function px({data:e,isConnectable:t,targetPosition:n=le.Top,sourcePosition:o=le.Bottom}){return i.jsxs(i.Fragment,{children:[i.jsx(xs,{type:"target",position:n,isConnectable:t}),e?.label,i.jsx(xs,{type:"source",position:o,isConnectable:t})]})}function hx(){return null}function mx({data:e,isConnectable:t,targetPosition:n=le.Top}){return i.jsxs(i.Fragment,{children:[i.jsx(xs,{type:"target",position:n,isConnectable:t}),e?.label]})}const ys={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Wl={input:fx,default:px,output:mx,group:hx};function gx(e){return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}const bx=e=>{const{width:t,height:n,x:o,y:s}=wo(e.nodeLookup,{filter:r=>!!r.selected});return{width:ut(t)?t:null,height:ut(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${o}px,${s}px)`}};function xx({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const o=_e(),{width:s,height:r,transformString:a,userSelectionActive:l}=he(bx,Se.shallow),c=od(),u=m.useRef(null);m.useEffect(()=>{n||u.current?.focus({preventScroll:!0})},[n]);const f=!l&&s!==null&&r!==null;if(id({nodeRef:u,disabled:!f}),!f)return null;const d=e?h=>{const v=o.getState().nodes.filter(b=>b.selected);e(h,v)}:void 0,p=h=>{Object.prototype.hasOwnProperty.call(ys,h.key)&&(h.preventDefault(),c({direction:ys[h.key],factor:h.shiftKey?4:1}))};return i.jsx("div",{className:Ee(["react-flow__nodesselection","react-flow__container",t]),style:{transform:a},children:i.jsx("div",{ref:u,className:"react-flow__nodesselection-rect",onContextMenu:d,tabIndex:n?void 0:-1,onKeyDown:n?void 0:p,style:{width:s,height:r}})})}const Ul=typeof window<"u"?window:void 0,yx=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function rd({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:o,onPaneMouseLeave:s,onPaneContextMenu:r,onPaneScroll:a,paneClickDistance:l,deleteKeyCode:c,selectionKeyCode:u,selectionOnDrag:f,selectionMode:d,onSelectionStart:p,onSelectionEnd:h,multiSelectionKeyCode:v,panActivationKeyCode:b,zoomActivationKeyCode:S,elementsSelectable:x,zoomOnScroll:_,zoomOnPinch:g,panOnScroll:y,panOnScrollSpeed:w,panOnScrollMode:j,zoomOnDoubleClick:N,panOnDrag:B,defaultViewport:z,translateExtent:W,minZoom:D,maxZoom:E,preventScrolling:G,onSelectionContextMenu:T,noWheelClassName:O,noPanClassName:P,disableKeyboardA11y:L,onViewportChange:M,isControlledViewport:F}){const{nodesSelectionActive:U,userSelectionActive:V}=he(yx,Se.shallow),Y=po(u,{target:Ul}),Z=po(b,{target:Ul}),q=Z||B,X=Z||y,A=f&&q!==!0,C=Y||V||A;return Jb({deleteKeyCode:c,multiSelectionKeyCode:v}),i.jsx(nx,{onPaneContextMenu:r,elementsSelectable:x,zoomOnScroll:_,zoomOnPinch:g,panOnScroll:X,panOnScrollSpeed:w,panOnScrollMode:j,zoomOnDoubleClick:N,panOnDrag:!Y&&q,defaultViewport:z,translateExtent:W,minZoom:D,maxZoom:E,zoomActivationKeyCode:S,preventScrolling:G,noWheelClassName:O,noPanClassName:P,onViewportChange:M,isControlledViewport:F,paneClickDistance:l,selectionOnDrag:A,children:i.jsxs(rx,{onSelectionStart:p,onSelectionEnd:h,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:o,onPaneMouseLeave:s,onPaneContextMenu:r,onPaneScroll:a,panOnDrag:q,isSelecting:!!C,selectionMode:d,selectionKeyPressed:Y,paneClickDistance:l,selectionOnDrag:A,children:[e,U&&i.jsx(xx,{onSelectionContextMenu:T,noPanClassName:P,disableKeyboardA11y:L})]})})}rd.displayName="FlowRenderer";const vx=m.memo(rd),wx=e=>t=>e?Sa(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(n=>n.id):Array.from(t.nodeLookup.keys());function Sx(e){return he(m.useCallback(wx(e),[e]),Se.shallow)}const _x=e=>e.updateNodeInternals;function jx(){const e=he(_x),[t]=m.useState(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(n=>{const o=new Map;n.forEach(s=>{const r=s.target.getAttribute("data-id");o.set(r,{id:r,nodeElement:s.target,force:!0})}),e(o)}));return m.useEffect(()=>()=>{t?.disconnect()},[t]),t}function Mx({node:e,nodeType:t,hasDimensions:n,resizeObserver:o}){const s=_e(),r=m.useRef(null),a=m.useRef(null),l=m.useRef(e.sourcePosition),c=m.useRef(e.targetPosition),u=m.useRef(t),f=n&&!!e.internals.handleBounds;return m.useEffect(()=>{r.current&&!e.hidden&&(!f||a.current!==r.current)&&(a.current&&o?.unobserve(a.current),o?.observe(r.current),a.current=r.current)},[f,e.hidden]),m.useEffect(()=>()=>{a.current&&(o?.unobserve(a.current),a.current=null)},[]),m.useEffect(()=>{if(r.current){const d=u.current!==t,p=l.current!==e.sourcePosition,h=c.current!==e.targetPosition;(d||p||h)&&(u.current=t,l.current=e.sourcePosition,c.current=e.targetPosition,s.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:r.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),r}function Cx({id:e,onClick:t,onMouseEnter:n,onMouseMove:o,onMouseLeave:s,onContextMenu:r,onDoubleClick:a,nodesDraggable:l,elementsSelectable:c,nodesConnectable:u,nodesFocusable:f,resizeObserver:d,noDragClassName:p,noPanClassName:h,disableKeyboardA11y:v,rfId:b,nodeTypes:S,nodeClickDistance:x,onError:_}){const{node:g,internals:y,isParent:w}=he(H=>{const K=H.nodeLookup.get(e),Q=H.parentLookup.has(e);return{node:K,internals:K.internals,isParent:Q}},Se.shallow);let j=g.type||"default",N=S?.[j]||Wl[j];N===void 0&&(_?.("003",Et.error003(j)),j="default",N=S?.default||Wl.default);const B=!!(g.draggable||l&&typeof g.draggable>"u"),z=!!(g.selectable||c&&typeof g.selectable>"u"),W=!!(g.connectable||u&&typeof g.connectable>"u"),D=!!(g.focusable||f&&typeof g.focusable>"u"),E=_e(),G=Tu(g),T=Mx({node:g,nodeType:j,hasDimensions:G,resizeObserver:d}),O=id({nodeRef:T,disabled:g.hidden||!B,noDragClassName:p,handleSelector:g.dragHandle,nodeId:e,isSelectable:z,nodeClickDistance:x}),P=od();if(g.hidden)return null;const L=Ut(g),M=gx(g),F=z||B||t||n||o||s,U=n?H=>n(H,{...y.userNode}):void 0,V=o?H=>o(H,{...y.userNode}):void 0,Y=s?H=>s(H,{...y.userNode}):void 0,Z=r?H=>r(H,{...y.userNode}):void 0,q=a?H=>a(H,{...y.userNode}):void 0,X=H=>{const{selectNodesOnDrag:K,nodeDragThreshold:Q}=E.getState();z&&(!K||!B||Q>0)&&Jr({id:e,store:E,nodeRef:T}),t&&t(H,{...y.userNode})},A=H=>{if(!(Au(H.nativeEvent)||v)){if(yu.includes(H.key)&&z){const K=H.key==="Escape";Jr({id:e,store:E,unselect:K,nodeRef:T})}else if(B&&g.selected&&Object.prototype.hasOwnProperty.call(ys,H.key)){H.preventDefault();const{ariaLabelConfig:K}=E.getState();E.setState({ariaLiveMessage:K["node.a11yDescription.ariaLiveMessage"]({direction:H.key.replace("Arrow","").toLowerCase(),x:~~y.positionAbsolute.x,y:~~y.positionAbsolute.y})}),P({direction:ys[H.key],factor:H.shiftKey?4:1})}}},C=()=>{if(v||!T.current?.matches(":focus-visible"))return;const{transform:H,width:K,height:Q,autoPanOnNodeFocus:ee,setCenter:ne}=E.getState();if(!ee)return;Sa(new Map([[e,g]]),{x:0,y:0,width:K,height:Q},H,!0).length>0||ne(g.position.x+L.width/2,g.position.y+L.height/2,{zoom:H[2]})};return i.jsx("div",{className:Ee(["react-flow__node",`react-flow__node-${j}`,{[h]:B},g.className,{selected:g.selected,selectable:z,parent:w,draggable:B,dragging:O}]),ref:T,style:{zIndex:y.z,transform:`translate(${y.positionAbsolute.x}px,${y.positionAbsolute.y}px)`,pointerEvents:F?"all":"none",visibility:G?"visible":"hidden",...g.style,...M},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:U,onMouseMove:V,onMouseLeave:Y,onContextMenu:Z,onClick:X,onDoubleClick:q,onKeyDown:D?A:void 0,tabIndex:D?0:void 0,onFocus:D?C:void 0,role:g.ariaRole??(D?"group":void 0),"aria-roledescription":"node","aria-describedby":v?void 0:`${Xu}-${b}`,"aria-label":g.ariaLabel,...g.domAttributes,children:i.jsx(lx,{value:e,children:i.jsx(N,{id:e,data:g.data,type:j,positionAbsoluteX:y.positionAbsolute.x,positionAbsoluteY:y.positionAbsolute.y,selected:g.selected??!1,selectable:z,draggable:B,deletable:g.deletable??!0,isConnectable:W,sourcePosition:g.sourcePosition,targetPosition:g.targetPosition,dragging:O,dragHandle:g.dragHandle,zIndex:y.z,parentId:g.parentId,...L})})})}var Nx=m.memo(Cx);const Tx=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function ad(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:o,elementsSelectable:s,onError:r}=he(Tx,Se.shallow),a=Sx(e.onlyRenderVisibleElements),l=jx();return i.jsx("div",{className:"react-flow__nodes",style:zs,children:a.map(c=>i.jsx(Nx,{id:c,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:l,nodesDraggable:t,nodesConnectable:n,nodesFocusable:o,elementsSelectable:s,nodeClickDistance:e.nodeClickDistance,onError:r},c))})}ad.displayName="NodeRenderer";const Ix=m.memo(ad);function Ex(e){return he(m.useCallback(n=>{if(!e)return n.edges.map(s=>s.id);const o=[];if(n.width&&n.height)for(const s of n.edges){const r=n.nodeLookup.get(s.source),a=n.nodeLookup.get(s.target);r&&a&&$0({sourceNode:r,targetNode:a,width:n.width,height:n.height,transform:n.transform})&&o.push(s.id)}return o},[e]),Se.shallow)}const Ax=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e}};return i.jsx("polyline",{className:"arrow",style:n,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},kx=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e,fill:e}};return i.jsx("polyline",{className:"arrowclosed",style:n,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},Vl={[co.Arrow]:Ax,[co.ArrowClosed]:kx};function Bx(e){const t=_e();return m.useMemo(()=>Object.prototype.hasOwnProperty.call(Vl,e)?Vl[e]:(t.getState().onError?.("009",Et.error009(e)),null),[e])}const Px=({id:e,type:t,color:n,width:o=12.5,height:s=12.5,markerUnits:r="strokeWidth",strokeWidth:a,orient:l="auto-start-reverse"})=>{const c=Bx(t);return c?i.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${o}`,markerHeight:`${s}`,viewBox:"-10 -10 20 20",markerUnits:r,orient:l,refX:"0",refY:"0",children:i.jsx(c,{color:n,strokeWidth:a})}):null},ld=({defaultColor:e,rfId:t})=>{const n=he(r=>r.edges),o=he(r=>r.defaultEdgeOptions),s=m.useMemo(()=>X0(n,{id:t,defaultColor:e,defaultMarkerStart:o?.markerStart,defaultMarkerEnd:o?.markerEnd}),[n,o,t,e]);return s.length?i.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:i.jsx("defs",{children:s.map(r=>i.jsx(Px,{id:r.id,type:r.type,color:r.color,width:r.width,height:r.height,markerUnits:r.markerUnits,strokeWidth:r.strokeWidth,orient:r.orient},r.id))})}):null};ld.displayName="MarkerDefinitions";var Rx=m.memo(ld);function cd({x:e,y:t,label:n,labelStyle:o,labelShowBg:s=!0,labelBgStyle:r,labelBgPadding:a=[2,4],labelBgBorderRadius:l=2,children:c,className:u,...f}){const[d,p]=m.useState({x:1,y:0,width:0,height:0}),h=Ee(["react-flow__edge-textwrapper",u]),v=m.useRef(null);return m.useEffect(()=>{if(v.current){const b=v.current.getBBox();p({x:b.x,y:b.y,width:b.width,height:b.height})}},[n]),n?i.jsxs("g",{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:h,visibility:d.width?"visible":"hidden",...f,children:[s&&i.jsx("rect",{width:d.width+2*a[0],x:-a[0],y:-a[1],height:d.height+2*a[1],className:"react-flow__edge-textbg",style:r,rx:l,ry:l}),i.jsx("text",{className:"react-flow__edge-text",y:d.height/2,dy:"0.3em",ref:v,style:o,children:n}),c]}):null}cd.displayName="EdgeText";const Dx=m.memo(cd);function Os({path:e,labelX:t,labelY:n,label:o,labelStyle:s,labelShowBg:r,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,interactionWidth:u=20,...f}){return i.jsxs(i.Fragment,{children:[i.jsx("path",{...f,d:e,fill:"none",className:Ee(["react-flow__edge-path",f.className])}),u?i.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:u,className:"react-flow__edge-interaction"}):null,o&&ut(t)&&ut(n)?i.jsx(Dx,{x:t,y:n,label:o,labelStyle:s,labelShowBg:r,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c}):null]})}function Yl({pos:e,x1:t,y1:n,x2:o,y2:s}){return e===le.Left||e===le.Right?[.5*(t+o),n]:[t,.5*(n+s)]}function ud({sourceX:e,sourceY:t,sourcePosition:n=le.Bottom,targetX:o,targetY:s,targetPosition:r=le.Top}){const[a,l]=Yl({pos:n,x1:e,y1:t,x2:o,y2:s}),[c,u]=Yl({pos:r,x1:o,y1:s,x2:e,y2:t}),[f,d,p,h]=Bu({sourceX:e,sourceY:t,targetX:o,targetY:s,sourceControlX:a,sourceControlY:l,targetControlX:c,targetControlY:u});return[`M${e},${t} C${a},${l} ${c},${u} ${o},${s}`,f,d,p,h]}function dd(e){return m.memo(({id:t,sourceX:n,sourceY:o,targetX:s,targetY:r,sourcePosition:a,targetPosition:l,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:d,labelBgPadding:p,labelBgBorderRadius:h,style:v,markerEnd:b,markerStart:S,interactionWidth:x})=>{const[_,g,y]=ud({sourceX:n,sourceY:o,sourcePosition:a,targetX:s,targetY:r,targetPosition:l}),w=e.isInternal?void 0:t;return i.jsx(Os,{id:w,path:_,labelX:g,labelY:y,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:d,labelBgPadding:p,labelBgBorderRadius:h,style:v,markerEnd:b,markerStart:S,interactionWidth:x})})}const Fx=dd({isInternal:!1}),fd=dd({isInternal:!0});Fx.displayName="SimpleBezierEdge";fd.displayName="SimpleBezierEdgeInternal";function pd(e){return m.memo(({id:t,sourceX:n,sourceY:o,targetX:s,targetY:r,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:d,style:p,sourcePosition:h=le.Bottom,targetPosition:v=le.Top,markerEnd:b,markerStart:S,pathOptions:x,interactionWidth:_})=>{const[g,y,w]=Zr({sourceX:n,sourceY:o,sourcePosition:h,targetX:s,targetY:r,targetPosition:v,borderRadius:x?.borderRadius,offset:x?.offset,stepPosition:x?.stepPosition}),j=e.isInternal?void 0:t;return i.jsx(Os,{id:j,path:g,labelX:y,labelY:w,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:d,style:p,markerEnd:b,markerStart:S,interactionWidth:_})})}const hd=pd({isInternal:!1}),md=pd({isInternal:!0});hd.displayName="SmoothStepEdge";md.displayName="SmoothStepEdgeInternal";function gd(e){return m.memo(({id:t,...n})=>{const o=e.isInternal?void 0:t;return i.jsx(hd,{...n,id:o,pathOptions:m.useMemo(()=>({borderRadius:0,offset:n.pathOptions?.offset}),[n.pathOptions?.offset])})})}const Lx=gd({isInternal:!1}),bd=gd({isInternal:!0});Lx.displayName="StepEdge";bd.displayName="StepEdgeInternal";function xd(e){return m.memo(({id:t,sourceX:n,sourceY:o,targetX:s,targetY:r,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:d,style:p,markerEnd:h,markerStart:v,interactionWidth:b})=>{const[S,x,_]=Du({sourceX:n,sourceY:o,targetX:s,targetY:r}),g=e.isInternal?void 0:t;return i.jsx(Os,{id:g,path:S,labelX:x,labelY:_,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:d,style:p,markerEnd:h,markerStart:v,interactionWidth:b})})}const zx=xd({isInternal:!1}),yd=xd({isInternal:!0});zx.displayName="StraightEdge";yd.displayName="StraightEdgeInternal";function vd(e){return m.memo(({id:t,sourceX:n,sourceY:o,targetX:s,targetY:r,sourcePosition:a=le.Bottom,targetPosition:l=le.Top,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:d,labelBgPadding:p,labelBgBorderRadius:h,style:v,markerEnd:b,markerStart:S,pathOptions:x,interactionWidth:_})=>{const[g,y,w]=Pu({sourceX:n,sourceY:o,sourcePosition:a,targetX:s,targetY:r,targetPosition:l,curvature:x?.curvature}),j=e.isInternal?void 0:t;return i.jsx(Os,{id:j,path:g,labelX:y,labelY:w,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:d,labelBgPadding:p,labelBgBorderRadius:h,style:v,markerEnd:b,markerStart:S,interactionWidth:_})})}const Ox=vd({isInternal:!1}),wd=vd({isInternal:!0});Ox.displayName="BezierEdge";wd.displayName="BezierEdgeInternal";const Zl={default:wd,straight:yd,step:bd,smoothstep:md,simplebezier:fd},Xl={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},$x=(e,t,n)=>n===le.Left?e-t:n===le.Right?e+t:e,Gx=(e,t,n)=>n===le.Top?e-t:n===le.Bottom?e+t:e,Kl="react-flow__edgeupdater";function ql({position:e,centerX:t,centerY:n,radius:o=10,onMouseDown:s,onMouseEnter:r,onMouseOut:a,type:l}){return i.jsx("circle",{onMouseDown:s,onMouseEnter:r,onMouseOut:a,className:Ee([Kl,`${Kl}-${l}`]),cx:$x(t,o,e),cy:Gx(n,o,e),r:o,stroke:"transparent",fill:"transparent"})}function Hx({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:o,sourceY:s,targetX:r,targetY:a,sourcePosition:l,targetPosition:c,onReconnect:u,onReconnectStart:f,onReconnectEnd:d,setReconnecting:p,setUpdateHover:h}){const v=_e(),b=(y,w)=>{if(y.button!==0)return;const{autoPanOnConnect:j,domNode:N,connectionMode:B,connectionRadius:z,lib:W,onConnectStart:D,cancelConnection:E,nodeLookup:G,rfId:T,panBy:O,updateConnection:P}=v.getState(),L=w.type==="target",M=(V,Y)=>{p(!1),d?.(V,n,w.type,Y)},F=V=>u?.(n,V),U=(V,Y)=>{p(!0),f?.(y,n,w.type),D?.(V,Y)};qr.onPointerDown(y.nativeEvent,{autoPanOnConnect:j,connectionMode:B,connectionRadius:z,domNode:N,handleId:w.id,nodeId:w.nodeId,nodeLookup:G,isTarget:L,edgeUpdaterType:w.type,lib:W,flowId:T,cancelConnection:E,panBy:O,isValidConnection:(...V)=>v.getState().isValidConnection?.(...V)??!0,onConnect:F,onConnectStart:U,onConnectEnd:(...V)=>v.getState().onConnectEnd?.(...V),onReconnectEnd:M,updateConnection:P,getTransform:()=>v.getState().transform,getFromHandle:()=>v.getState().connection.fromHandle,dragThreshold:v.getState().connectionDragThreshold,handleDomNode:y.currentTarget})},S=y=>b(y,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),x=y=>b(y,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),_=()=>h(!0),g=()=>h(!1);return i.jsxs(i.Fragment,{children:[(e===!0||e==="source")&&i.jsx(ql,{position:l,centerX:o,centerY:s,radius:t,onMouseDown:S,onMouseEnter:_,onMouseOut:g,type:"source"}),(e===!0||e==="target")&&i.jsx(ql,{position:c,centerX:r,centerY:a,radius:t,onMouseDown:x,onMouseEnter:_,onMouseOut:g,type:"target"})]})}function Wx({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:o,onClick:s,onDoubleClick:r,onContextMenu:a,onMouseEnter:l,onMouseMove:c,onMouseLeave:u,reconnectRadius:f,onReconnect:d,onReconnectStart:p,onReconnectEnd:h,rfId:v,edgeTypes:b,noPanClassName:S,onError:x,disableKeyboardA11y:_}){let g=he(ne=>ne.edgeLookup.get(e));const y=he(ne=>ne.defaultEdgeOptions);g=y?{...y,...g}:g;let w=g.type||"default",j=b?.[w]||Zl[w];j===void 0&&(x?.("011",Et.error011(w)),w="default",j=b?.default||Zl.default);const N=!!(g.focusable||t&&typeof g.focusable>"u"),B=typeof d<"u"&&(g.reconnectable||n&&typeof g.reconnectable>"u"),z=!!(g.selectable||o&&typeof g.selectable>"u"),W=m.useRef(null),[D,E]=m.useState(!1),[G,T]=m.useState(!1),O=_e(),{zIndex:P,sourceX:L,sourceY:M,targetX:F,targetY:U,sourcePosition:V,targetPosition:Y}=he(m.useCallback(ne=>{const ie=ne.nodeLookup.get(g.source),re=ne.nodeLookup.get(g.target);if(!ie||!re)return{zIndex:g.zIndex,...Xl};const J=Z0({id:e,sourceNode:ie,targetNode:re,sourceHandle:g.sourceHandle||null,targetHandle:g.targetHandle||null,connectionMode:ne.connectionMode,onError:x});return{zIndex:O0({selected:g.selected,zIndex:g.zIndex,sourceNode:ie,targetNode:re,elevateOnSelect:ne.elevateEdgesOnSelect,zIndexMode:ne.zIndexMode}),...J||Xl}},[g.source,g.target,g.sourceHandle,g.targetHandle,g.selected,g.zIndex]),Se.shallow),Z=m.useMemo(()=>g.markerStart?`url('#${Xr(g.markerStart,v)}')`:void 0,[g.markerStart,v]),q=m.useMemo(()=>g.markerEnd?`url('#${Xr(g.markerEnd,v)}')`:void 0,[g.markerEnd,v]);if(g.hidden||L===null||M===null||F===null||U===null)return null;const X=ne=>{const{addSelectedEdges:ie,unselectNodesAndEdges:re,multiSelectionActive:J}=O.getState();z&&(O.setState({nodesSelectionActive:!1}),g.selected&&J?(re({nodes:[],edges:[g]}),W.current?.blur()):ie([e])),s&&s(ne,g)},A=r?ne=>{r(ne,{...g})}:void 0,C=a?ne=>{a(ne,{...g})}:void 0,H=l?ne=>{l(ne,{...g})}:void 0,K=c?ne=>{c(ne,{...g})}:void 0,Q=u?ne=>{u(ne,{...g})}:void 0,ee=ne=>{if(!_&&yu.includes(ne.key)&&z){const{unselectNodesAndEdges:ie,addSelectedEdges:re}=O.getState();ne.key==="Escape"?(W.current?.blur(),ie({edges:[g]})):re([e])}};return i.jsx("svg",{style:{zIndex:P},children:i.jsxs("g",{className:Ee(["react-flow__edge",`react-flow__edge-${w}`,g.className,S,{selected:g.selected,animated:g.animated,inactive:!z&&!s,updating:D,selectable:z}]),onClick:X,onDoubleClick:A,onContextMenu:C,onMouseEnter:H,onMouseMove:K,onMouseLeave:Q,onKeyDown:N?ee:void 0,tabIndex:N?0:void 0,role:g.ariaRole??(N?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":g.ariaLabel===null?void 0:g.ariaLabel||`Edge from ${g.source} to ${g.target}`,"aria-describedby":N?`${Ku}-${v}`:void 0,ref:W,...g.domAttributes,children:[!G&&i.jsx(j,{id:e,source:g.source,target:g.target,type:g.type,selected:g.selected,animated:g.animated,selectable:z,deletable:g.deletable??!0,label:g.label,labelStyle:g.labelStyle,labelShowBg:g.labelShowBg,labelBgStyle:g.labelBgStyle,labelBgPadding:g.labelBgPadding,labelBgBorderRadius:g.labelBgBorderRadius,sourceX:L,sourceY:M,targetX:F,targetY:U,sourcePosition:V,targetPosition:Y,data:g.data,style:g.style,sourceHandleId:g.sourceHandle,targetHandleId:g.targetHandle,markerStart:Z,markerEnd:q,pathOptions:"pathOptions"in g?g.pathOptions:void 0,interactionWidth:g.interactionWidth}),B&&i.jsx(Hx,{edge:g,isReconnectable:B,reconnectRadius:f,onReconnect:d,onReconnectStart:p,onReconnectEnd:h,sourceX:L,sourceY:M,targetX:F,targetY:U,sourcePosition:V,targetPosition:Y,setUpdateHover:E,setReconnecting:T})]})})}var Ux=m.memo(Wx);const Vx=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Sd({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:o,noPanClassName:s,onReconnect:r,onEdgeContextMenu:a,onEdgeMouseEnter:l,onEdgeMouseMove:c,onEdgeMouseLeave:u,onEdgeClick:f,reconnectRadius:d,onEdgeDoubleClick:p,onReconnectStart:h,onReconnectEnd:v,disableKeyboardA11y:b}){const{edgesFocusable:S,edgesReconnectable:x,elementsSelectable:_,onError:g}=he(Vx,Se.shallow),y=Ex(t);return i.jsxs("div",{className:"react-flow__edges",children:[i.jsx(Rx,{defaultColor:e,rfId:n}),y.map(w=>i.jsx(Ux,{id:w,edgesFocusable:S,edgesReconnectable:x,elementsSelectable:_,noPanClassName:s,onReconnect:r,onContextMenu:a,onMouseEnter:l,onMouseMove:c,onMouseLeave:u,onClick:f,reconnectRadius:d,onDoubleClick:p,onReconnectStart:h,onReconnectEnd:v,rfId:n,onError:g,edgeTypes:o,disableKeyboardA11y:b},w))]})}Sd.displayName="EdgeRenderer";const Yx=m.memo(Sd),Zx=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Xx({children:e}){const t=he(Zx);return i.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function Kx(e){const t=Ea(),n=m.useRef(!1);m.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const qx=e=>e.panZoom?.syncViewport;function Qx(e){const t=he(qx),n=_e();return m.useEffect(()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function Jx(e){return e.connection.inProgress?{...e.connection,to:_o(e.connection.to,e.transform)}:{...e.connection}}function ey(e){return Jx}function ty(e){const t=ey();return he(t,Se.shallow)}const ny=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function iy({containerStyle:e,style:t,type:n,component:o}){const{nodesConnectable:s,width:r,height:a,isValid:l,inProgress:c}=he(ny,Se.shallow);return!(r&&s&&c)?null:i.jsx("svg",{style:e,width:r,height:a,className:"react-flow__connectionline react-flow__container",children:i.jsx("g",{className:Ee(["react-flow__connection",Su(l)]),children:i.jsx(_d,{style:t,type:n,CustomComponent:o,isValid:l})})})}const _d=({style:e,type:t=hn.Bezier,CustomComponent:n,isValid:o})=>{const{inProgress:s,from:r,fromNode:a,fromHandle:l,fromPosition:c,to:u,toNode:f,toHandle:d,toPosition:p,pointer:h}=ty();if(!s)return;if(n)return i.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:a,fromHandle:l,fromX:r.x,fromY:r.y,toX:u.x,toY:u.y,fromPosition:c,toPosition:p,connectionStatus:Su(o),toNode:f,toHandle:d,pointer:h});let v="";const b={sourceX:r.x,sourceY:r.y,sourcePosition:c,targetX:u.x,targetY:u.y,targetPosition:p};switch(t){case hn.Bezier:[v]=Pu(b);break;case hn.SimpleBezier:[v]=ud(b);break;case hn.Step:[v]=Zr({...b,borderRadius:0});break;case hn.SmoothStep:[v]=Zr(b);break;default:[v]=Du(b)}return i.jsx("path",{d:v,fill:"none",className:"react-flow__connection-path",style:e})};_d.displayName="ConnectionLine";const oy={};function Ql(e=oy){m.useRef(e),_e(),m.useEffect(()=>{},[e])}function sy(){_e(),m.useRef(!1),m.useEffect(()=>{},[])}function jd({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:o,onEdgeClick:s,onNodeDoubleClick:r,onEdgeDoubleClick:a,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:u,onNodeContextMenu:f,onSelectionContextMenu:d,onSelectionStart:p,onSelectionEnd:h,connectionLineType:v,connectionLineStyle:b,connectionLineComponent:S,connectionLineContainerStyle:x,selectionKeyCode:_,selectionOnDrag:g,selectionMode:y,multiSelectionKeyCode:w,panActivationKeyCode:j,zoomActivationKeyCode:N,deleteKeyCode:B,onlyRenderVisibleElements:z,elementsSelectable:W,defaultViewport:D,translateExtent:E,minZoom:G,maxZoom:T,preventScrolling:O,defaultMarkerColor:P,zoomOnScroll:L,zoomOnPinch:M,panOnScroll:F,panOnScrollSpeed:U,panOnScrollMode:V,zoomOnDoubleClick:Y,panOnDrag:Z,onPaneClick:q,onPaneMouseEnter:X,onPaneMouseMove:A,onPaneMouseLeave:C,onPaneScroll:H,onPaneContextMenu:K,paneClickDistance:Q,nodeClickDistance:ee,onEdgeContextMenu:ne,onEdgeMouseEnter:ie,onEdgeMouseMove:re,onEdgeMouseLeave:J,reconnectRadius:ce,onReconnect:de,onReconnectStart:me,onReconnectEnd:xe,noDragClassName:je,noWheelClassName:ve,noPanClassName:Me,disableKeyboardA11y:Pe,nodeExtent:mt,rfId:Qe,viewport:Ge,onViewportChange:Je}){return Ql(e),Ql(t),sy(),Kx(n),Qx(Ge),i.jsx(vx,{onPaneClick:q,onPaneMouseEnter:X,onPaneMouseMove:A,onPaneMouseLeave:C,onPaneContextMenu:K,onPaneScroll:H,paneClickDistance:Q,deleteKeyCode:B,selectionKeyCode:_,selectionOnDrag:g,selectionMode:y,onSelectionStart:p,onSelectionEnd:h,multiSelectionKeyCode:w,panActivationKeyCode:j,zoomActivationKeyCode:N,elementsSelectable:W,zoomOnScroll:L,zoomOnPinch:M,zoomOnDoubleClick:Y,panOnScroll:F,panOnScrollSpeed:U,panOnScrollMode:V,panOnDrag:Z,defaultViewport:D,translateExtent:E,minZoom:G,maxZoom:T,onSelectionContextMenu:d,preventScrolling:O,noDragClassName:je,noWheelClassName:ve,noPanClassName:Me,disableKeyboardA11y:Pe,onViewportChange:Je,isControlledViewport:!!Ge,children:i.jsxs(Xx,{children:[i.jsx(Yx,{edgeTypes:t,onEdgeClick:s,onEdgeDoubleClick:a,onReconnect:de,onReconnectStart:me,onReconnectEnd:xe,onlyRenderVisibleElements:z,onEdgeContextMenu:ne,onEdgeMouseEnter:ie,onEdgeMouseMove:re,onEdgeMouseLeave:J,reconnectRadius:ce,defaultMarkerColor:P,noPanClassName:Me,disableKeyboardA11y:Pe,rfId:Qe}),i.jsx(iy,{style:b,type:v,component:S,containerStyle:x}),i.jsx("div",{className:"react-flow__edgelabel-renderer"}),i.jsx(Ix,{nodeTypes:e,onNodeClick:o,onNodeDoubleClick:r,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:u,onNodeContextMenu:f,nodeClickDistance:ee,onlyRenderVisibleElements:z,noPanClassName:Me,noDragClassName:je,disableKeyboardA11y:Pe,nodeExtent:mt,rfId:Qe}),i.jsx("div",{className:"react-flow__viewport-portal"})]})})}jd.displayName="GraphView";const ry=m.memo(jd),Jl=({nodes:e,edges:t,defaultNodes:n,defaultEdges:o,width:s,height:r,fitView:a,fitViewOptions:l,minZoom:c=.5,maxZoom:u=2,nodeOrigin:f,nodeExtent:d,zIndexMode:p="basic"}={})=>{const h=new Map,v=new Map,b=new Map,S=new Map,x=o??t??[],_=n??e??[],g=f??[0,0],y=d??ao;zu(b,S,x);const{nodesInitialized:w}=Kr(_,h,v,{nodeOrigin:g,nodeExtent:y,zIndexMode:p});let j=[0,0,1];if(a&&s&&r){const N=wo(h,{filter:D=>!!((D.width||D.initialWidth)&&(D.height||D.initialHeight))}),{x:B,y:z,zoom:W}=_a(N,s,r,c,u,l?.padding??.1);j=[B,z,W]}return{rfId:"1",width:s??0,height:r??0,transform:j,nodes:_,nodesInitialized:w,nodeLookup:h,parentLookup:v,edges:x,edgeLookup:S,connectionLookup:b,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:o!==void 0,panZoom:null,minZoom:c,maxZoom:u,translateExtent:ao,nodeExtent:y,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:_i.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:g,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:a??!1,fitViewOptions:l,fitViewResolver:null,connection:{...wu},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:P0,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:vu,zIndexMode:p,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},ay=({nodes:e,edges:t,defaultNodes:n,defaultEdges:o,width:s,height:r,fitView:a,fitViewOptions:l,minZoom:c,maxZoom:u,nodeOrigin:f,nodeExtent:d,zIndexMode:p})=>kc.createWithEqualityFn((h,v)=>{async function b(){const{nodeLookup:S,panZoom:x,fitViewOptions:_,fitViewResolver:g,width:y,height:w,minZoom:j,maxZoom:N}=v();x&&(await k0({nodes:S,width:y,height:w,panZoom:x,minZoom:j,maxZoom:N},_),g?.resolve(!0),h({fitViewResolver:null}))}return{...Jl({nodes:e,edges:t,width:s,height:r,fitView:a,fitViewOptions:l,minZoom:c,maxZoom:u,nodeOrigin:f,nodeExtent:d,defaultNodes:n,defaultEdges:o,zIndexMode:p}),setNodes:S=>{const{nodeLookup:x,parentLookup:_,nodeOrigin:g,elevateNodesOnSelect:y,fitViewQueued:w,zIndexMode:j,nodesSelectionActive:N}=v(),{nodesInitialized:B,hasSelectedNodes:z}=Kr(S,x,_,{nodeOrigin:g,nodeExtent:d,elevateNodesOnSelect:y,checkEquality:!0,zIndexMode:j}),W=N&&z;w&&B?(b(),h({nodes:S,nodesInitialized:B,fitViewQueued:!1,fitViewOptions:void 0,nodesSelectionActive:W})):h({nodes:S,nodesInitialized:B,nodesSelectionActive:W})},setEdges:S=>{const{connectionLookup:x,edgeLookup:_}=v();zu(x,_,S),h({edges:S})},setDefaultNodesAndEdges:(S,x)=>{if(S){const{setNodes:_}=v();_(S),h({hasDefaultNodes:!0})}if(x){const{setEdges:_}=v();_(x),h({hasDefaultEdges:!0})}},updateNodeInternals:S=>{const{triggerNodeChanges:x,nodeLookup:_,parentLookup:g,domNode:y,nodeOrigin:w,nodeExtent:j,debug:N,fitViewQueued:B,zIndexMode:z}=v(),{changes:W,updatedInternals:D}=nb(S,_,g,y,w,j,z);D&&(Q0(_,g,{nodeOrigin:w,nodeExtent:j,zIndexMode:z}),B?(b(),h({fitViewQueued:!1,fitViewOptions:void 0})):h({}),W?.length>0&&(N&&console.log("React Flow: trigger node changes",W),x?.(W)))},updateNodePositions:(S,x=!1)=>{const _=[];let g=[];const{nodeLookup:y,triggerNodeChanges:w,connection:j,updateConnection:N,onNodesChangeMiddlewareMap:B}=v();for(const[z,W]of S){const D=y.get(z),E=!!(D?.expandParent&&D?.parentId&&W?.position),G={id:z,type:"position",position:E?{x:Math.max(0,W.position.x),y:Math.max(0,W.position.y)}:W.position,dragging:x};if(D&&j.inProgress&&j.fromNode.id===D.id){const T=ri(D,j.fromHandle,le.Left,!0);N({...j,from:T})}E&&D.parentId&&_.push({id:z,parentId:D.parentId,rect:{...W.internals.positionAbsolute,width:W.measured.width??0,height:W.measured.height??0}}),g.push(G)}if(_.length>0){const{parentLookup:z,nodeOrigin:W}=v(),D=Ia(_,y,z,W);g.push(...D)}for(const z of B.values())g=z(g);w(g)},triggerNodeChanges:S=>{const{onNodesChange:x,setNodes:_,nodes:g,hasDefaultNodes:y,debug:w}=v();if(S?.length){if(y){const j=Ju(S,g);_(j)}w&&console.log("React Flow: trigger node changes",S),x?.(S)}},triggerEdgeChanges:S=>{const{onEdgesChange:x,setEdges:_,edges:g,hasDefaultEdges:y,debug:w}=v();if(S?.length){if(y){const j=ed(S,g);_(j)}w&&console.log("React Flow: trigger edge changes",S),x?.(S)}},addSelectedNodes:S=>{const{multiSelectionActive:x,edgeLookup:_,nodeLookup:g,triggerNodeChanges:y,triggerEdgeChanges:w}=v();if(x){const j=S.map(N=>Qn(N,!0));y(j);return}y(bi(g,new Set([...S]),!0)),w(bi(_))},addSelectedEdges:S=>{const{multiSelectionActive:x,edgeLookup:_,nodeLookup:g,triggerNodeChanges:y,triggerEdgeChanges:w}=v();if(x){const j=S.map(N=>Qn(N,!0));w(j);return}w(bi(_,new Set([...S]))),y(bi(g,new Set,!0))},unselectNodesAndEdges:({nodes:S,edges:x}={})=>{const{edges:_,nodes:g,nodeLookup:y,triggerNodeChanges:w,triggerEdgeChanges:j}=v(),N=S||g,B=x||_,z=[];for(const D of N){if(!D.selected)continue;const E=y.get(D.id);E&&(E.selected=!1),z.push(Qn(D.id,!1))}const W=[];for(const D of B)D.selected&&W.push(Qn(D.id,!1));w(z),j(W)},setMinZoom:S=>{const{panZoom:x,maxZoom:_}=v();x?.setScaleExtent([S,_]),h({minZoom:S})},setMaxZoom:S=>{const{panZoom:x,minZoom:_}=v();x?.setScaleExtent([_,S]),h({maxZoom:S})},setTranslateExtent:S=>{v().panZoom?.setTranslateExtent(S),h({translateExtent:S})},resetSelectedElements:()=>{const{edges:S,nodes:x,triggerNodeChanges:_,triggerEdgeChanges:g,elementsSelectable:y}=v();if(!y)return;const w=x.reduce((N,B)=>B.selected?[...N,Qn(B.id,!1)]:N,[]),j=S.reduce((N,B)=>B.selected?[...N,Qn(B.id,!1)]:N,[]);_(w),g(j)},setNodeExtent:S=>{const{nodes:x,nodeLookup:_,parentLookup:g,nodeOrigin:y,elevateNodesOnSelect:w,nodeExtent:j,zIndexMode:N}=v();S[0][0]===j[0][0]&&S[0][1]===j[0][1]&&S[1][0]===j[1][0]&&S[1][1]===j[1][1]||(Kr(x,_,g,{nodeOrigin:y,nodeExtent:S,elevateNodesOnSelect:w,checkEquality:!1,zIndexMode:N}),h({nodeExtent:S}))},panBy:S=>{const{transform:x,width:_,height:g,panZoom:y,translateExtent:w}=v();return ib({delta:S,panZoom:y,transform:x,translateExtent:w,width:_,height:g})},setCenter:async(S,x,_)=>{const{width:g,height:y,maxZoom:w,panZoom:j}=v();if(!j)return Promise.resolve(!1);const N=typeof _?.zoom<"u"?_.zoom:w;return await j.setViewport({x:g/2-S*N,y:y/2-x*N,zoom:N},{duration:_?.duration,ease:_?.ease,interpolate:_?.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{h({connection:{...wu}})},updateConnection:S=>{h({connection:S})},reset:()=>h({...Jl()})}},Object.is);function ly({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:o,initialWidth:s,initialHeight:r,initialMinZoom:a,initialMaxZoom:l,initialFitViewOptions:c,fitView:u,nodeOrigin:f,nodeExtent:d,zIndexMode:p,children:h}){const[v]=m.useState(()=>ay({nodes:e,edges:t,defaultNodes:n,defaultEdges:o,width:s,height:r,fitView:u,minZoom:a,maxZoom:l,fitViewOptions:c,nodeOrigin:f,nodeExtent:d,zIndexMode:p}));return i.jsx(Nb,{value:v,children:i.jsx(Xb,{children:h})})}function cy({children:e,nodes:t,edges:n,defaultNodes:o,defaultEdges:s,width:r,height:a,fitView:l,fitViewOptions:c,minZoom:u,maxZoom:f,nodeOrigin:d,nodeExtent:p,zIndexMode:h}){return m.useContext(Fs)?i.jsx(i.Fragment,{children:e}):i.jsx(ly,{initialNodes:t,initialEdges:n,defaultNodes:o,defaultEdges:s,initialWidth:r,initialHeight:a,fitView:l,initialFitViewOptions:c,initialMinZoom:u,initialMaxZoom:f,nodeOrigin:d,nodeExtent:p,zIndexMode:h,children:e})}const uy={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function dy({nodes:e,edges:t,defaultNodes:n,defaultEdges:o,className:s,nodeTypes:r,edgeTypes:a,onNodeClick:l,onEdgeClick:c,onInit:u,onMove:f,onMoveStart:d,onMoveEnd:p,onConnect:h,onConnectStart:v,onConnectEnd:b,onClickConnectStart:S,onClickConnectEnd:x,onNodeMouseEnter:_,onNodeMouseMove:g,onNodeMouseLeave:y,onNodeContextMenu:w,onNodeDoubleClick:j,onNodeDragStart:N,onNodeDrag:B,onNodeDragStop:z,onNodesDelete:W,onEdgesDelete:D,onDelete:E,onSelectionChange:G,onSelectionDragStart:T,onSelectionDrag:O,onSelectionDragStop:P,onSelectionContextMenu:L,onSelectionStart:M,onSelectionEnd:F,onBeforeDelete:U,connectionMode:V,connectionLineType:Y=hn.Bezier,connectionLineStyle:Z,connectionLineComponent:q,connectionLineContainerStyle:X,deleteKeyCode:A="Backspace",selectionKeyCode:C="Shift",selectionOnDrag:H=!1,selectionMode:K=lo.Full,panActivationKeyCode:Q="Space",multiSelectionKeyCode:ee=fo()?"Meta":"Control",zoomActivationKeyCode:ne=fo()?"Meta":"Control",snapToGrid:ie,snapGrid:re,onlyRenderVisibleElements:J=!1,selectNodesOnDrag:ce,nodesDraggable:de,autoPanOnNodeFocus:me,nodesConnectable:xe,nodesFocusable:je,nodeOrigin:ve=qu,edgesFocusable:Me,edgesReconnectable:Pe,elementsSelectable:mt=!0,defaultViewport:Qe=Ob,minZoom:Ge=.5,maxZoom:Je=2,translateExtent:Vt=ao,preventScrolling:_n=!0,nodeExtent:Bt,defaultMarkerColor:jn="#b1b1b7",zoomOnScroll:Mn=!0,zoomOnPinch:Cn=!0,panOnScroll:Nn=!1,panOnScrollSpeed:Tn=.5,panOnScrollMode:In=ni.Free,zoomOnDoubleClick:gt=!0,panOnDrag:et=!0,onPaneClick:bt,onPaneMouseEnter:Ze,onPaneMouseMove:Pt,onPaneMouseLeave:Yt,onPaneScroll:Rt,onPaneContextMenu:xt,paneClickDistance:En=1,nodeClickDistance:An=0,children:kn,onReconnect:Bn,onReconnectStart:Zt,onReconnectEnd:Xt,onEdgeContextMenu:Pn,onEdgeDoubleClick:Rn,onEdgeMouseEnter:Dn,onEdgeMouseMove:Fn,onEdgeMouseLeave:Kt,reconnectRadius:qt=10,onNodesChange:Qt,onEdgesChange:Jt,noDragClassName:Ln="nodrag",noWheelClassName:zn="nowheel",noPanClassName:en="nopan",fitView:tn,fitViewOptions:yt,connectOnClick:On,attributionPosition:Dt,proOptions:$n,defaultEdgeOptions:Gn,elevateNodesOnSelect:Hn=!0,elevateEdgesOnSelect:Wn=!1,disableKeyboardA11y:nn=!1,autoPanOnConnect:on,autoPanOnNodeDrag:vt,autoPanSpeed:tt,connectionRadius:Xe,isValidConnection:Un,onError:sn,style:Vn,id:nt,nodeDragThreshold:Yn,connectionDragThreshold:Ke,viewport:wt,onViewportChange:ze,width:qe,height:Ae,colorMode:St="light",debug:Zn,onScroll:rn,ariaLabelConfig:an,zIndexMode:Ft="basic",...Xn},ln){const _t=nt||"1",Lt=Wb(St),it=m.useCallback($=>{$.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),rn?.($)},[rn]);return i.jsx("div",{"data-testid":"rf__wrapper",...Xn,onScroll:it,style:{...Vn,...uy},ref:ln,className:Ee(["react-flow",s,Lt]),id:nt,role:"application",children:i.jsxs(cy,{nodes:e,edges:t,width:qe,height:Ae,fitView:tn,fitViewOptions:yt,minZoom:Ge,maxZoom:Je,nodeOrigin:ve,nodeExtent:Bt,zIndexMode:Ft,children:[i.jsx(Hb,{nodes:e,edges:t,defaultNodes:n,defaultEdges:o,onConnect:h,onConnectStart:v,onConnectEnd:b,onClickConnectStart:S,onClickConnectEnd:x,nodesDraggable:de,autoPanOnNodeFocus:me,nodesConnectable:xe,nodesFocusable:je,edgesFocusable:Me,edgesReconnectable:Pe,elementsSelectable:mt,elevateNodesOnSelect:Hn,elevateEdgesOnSelect:Wn,minZoom:Ge,maxZoom:Je,nodeExtent:Bt,onNodesChange:Qt,onEdgesChange:Jt,snapToGrid:ie,snapGrid:re,connectionMode:V,translateExtent:Vt,connectOnClick:On,defaultEdgeOptions:Gn,fitView:tn,fitViewOptions:yt,onNodesDelete:W,onEdgesDelete:D,onDelete:E,onNodeDragStart:N,onNodeDrag:B,onNodeDragStop:z,onSelectionDrag:O,onSelectionDragStart:T,onSelectionDragStop:P,onMove:f,onMoveStart:d,onMoveEnd:p,noPanClassName:en,nodeOrigin:ve,rfId:_t,autoPanOnConnect:on,autoPanOnNodeDrag:vt,autoPanSpeed:tt,onError:sn,connectionRadius:Xe,isValidConnection:Un,selectNodesOnDrag:ce,nodeDragThreshold:Yn,connectionDragThreshold:Ke,onBeforeDelete:U,debug:Zn,ariaLabelConfig:an,zIndexMode:Ft}),i.jsx(ry,{onInit:u,onNodeClick:l,onEdgeClick:c,onNodeMouseEnter:_,onNodeMouseMove:g,onNodeMouseLeave:y,onNodeContextMenu:w,onNodeDoubleClick:j,nodeTypes:r,edgeTypes:a,connectionLineType:Y,connectionLineStyle:Z,connectionLineComponent:q,connectionLineContainerStyle:X,selectionKeyCode:C,selectionOnDrag:H,selectionMode:K,deleteKeyCode:A,multiSelectionKeyCode:ee,panActivationKeyCode:Q,zoomActivationKeyCode:ne,onlyRenderVisibleElements:J,defaultViewport:Qe,translateExtent:Vt,minZoom:Ge,maxZoom:Je,preventScrolling:_n,zoomOnScroll:Mn,zoomOnPinch:Cn,zoomOnDoubleClick:gt,panOnScroll:Nn,panOnScrollSpeed:Tn,panOnScrollMode:In,panOnDrag:et,onPaneClick:bt,onPaneMouseEnter:Ze,onPaneMouseMove:Pt,onPaneMouseLeave:Yt,onPaneScroll:Rt,onPaneContextMenu:xt,paneClickDistance:En,nodeClickDistance:An,onSelectionContextMenu:L,onSelectionStart:M,onSelectionEnd:F,onReconnect:Bn,onReconnectStart:Zt,onReconnectEnd:Xt,onEdgeContextMenu:Pn,onEdgeDoubleClick:Rn,onEdgeMouseEnter:Dn,onEdgeMouseMove:Fn,onEdgeMouseLeave:Kt,reconnectRadius:qt,defaultMarkerColor:jn,noDragClassName:Ln,noWheelClassName:zn,noPanClassName:en,rfId:_t,disableKeyboardA11y:nn,nodeExtent:Bt,viewport:wt,onViewportChange:ze}),i.jsx(zb,{onSelectionChange:G}),kn,i.jsx(Pb,{proOptions:$n,position:Dt}),i.jsx(Bb,{rfId:_t,disableKeyboardA11y:nn})]})})}var fy=td(dy);function py(e){const[t,n]=m.useState(e),o=m.useCallback(s=>n(r=>Ju(s,r)),[]);return[t,n,o]}function hy(e){const[t,n]=m.useState(e),o=m.useCallback(s=>n(r=>ed(s,r)),[]);return[t,n,o]}function my({dimensions:e,lineWidth:t,variant:n,className:o}){return i.jsx("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:Ee(["react-flow__background-pattern",n,o])})}function gy({radius:e,className:t}){return i.jsx("circle",{cx:e,cy:e,r:e,className:Ee(["react-flow__background-pattern","dots",t])})}var vn;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(vn||(vn={}));const by={[vn.Dots]:1,[vn.Lines]:1,[vn.Cross]:6},xy=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Md({id:e,variant:t=vn.Dots,gap:n=20,size:o,lineWidth:s=1,offset:r=0,color:a,bgColor:l,style:c,className:u,patternClassName:f}){const d=m.useRef(null),{transform:p,patternId:h}=he(xy,Se.shallow),v=o||by[t],b=t===vn.Dots,S=t===vn.Cross,x=Array.isArray(n)?n:[n,n],_=[x[0]*p[2]||1,x[1]*p[2]||1],g=v*p[2],y=Array.isArray(r)?r:[r,r],w=S?[g,g]:_,j=[y[0]*p[2]||1+w[0]/2,y[1]*p[2]||1+w[1]/2],N=`${h}${e||""}`;return i.jsxs("svg",{className:Ee(["react-flow__background",u]),style:{...c,...zs,"--xy-background-color-props":l,"--xy-background-pattern-color-props":a},ref:d,"data-testid":"rf__background",children:[i.jsx("pattern",{id:N,x:p[0]%_[0],y:p[1]%_[1],width:_[0],height:_[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${j[0]},-${j[1]})`,children:b?i.jsx(gy,{radius:g/2,className:f}):i.jsx(my,{dimensions:w,lineWidth:s,variant:t,className:f})}),i.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${N})`})]})}Md.displayName="Background";const yy=m.memo(Md);function vy(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:i.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function wy(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:i.jsx("path",{d:"M0 0h32v4.2H0z"})})}function Sy(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:i.jsx("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function _y(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:i.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function jy(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:i.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function $o({children:e,className:t,...n}){return i.jsx("button",{type:"button",className:Ee(["react-flow__controls-button",t]),...n,children:e})}const My=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function Cd({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:o=!0,fitViewOptions:s,onZoomIn:r,onZoomOut:a,onFitView:l,onInteractiveChange:c,className:u,children:f,position:d="bottom-left",orientation:p="vertical","aria-label":h}){const v=_e(),{isInteractive:b,minZoomReached:S,maxZoomReached:x,ariaLabelConfig:_}=he(My,Se.shallow),{zoomIn:g,zoomOut:y,fitView:w}=Ea(),j=()=>{g(),r?.()},N=()=>{y(),a?.()},B=()=>{w(s),l?.()},z=()=>{v.setState({nodesDraggable:!b,nodesConnectable:!b,elementsSelectable:!b}),c?.(!b)},W=p==="horizontal"?"horizontal":"vertical";return i.jsxs(Ls,{className:Ee(["react-flow__controls",W,u]),position:d,style:e,"data-testid":"rf__controls","aria-label":h??_["controls.ariaLabel"],children:[t&&i.jsxs(i.Fragment,{children:[i.jsx($o,{onClick:j,className:"react-flow__controls-zoomin",title:_["controls.zoomIn.ariaLabel"],"aria-label":_["controls.zoomIn.ariaLabel"],disabled:x,children:i.jsx(vy,{})}),i.jsx($o,{onClick:N,className:"react-flow__controls-zoomout",title:_["controls.zoomOut.ariaLabel"],"aria-label":_["controls.zoomOut.ariaLabel"],disabled:S,children:i.jsx(wy,{})})]}),n&&i.jsx($o,{className:"react-flow__controls-fitview",onClick:B,title:_["controls.fitView.ariaLabel"],"aria-label":_["controls.fitView.ariaLabel"],children:i.jsx(Sy,{})}),o&&i.jsx($o,{className:"react-flow__controls-interactive",onClick:z,title:_["controls.interactive.ariaLabel"],"aria-label":_["controls.interactive.ariaLabel"],children:b?i.jsx(jy,{}):i.jsx(_y,{})}),f]})}Cd.displayName="Controls";const Cy=m.memo(Cd);function Ny({id:e,x:t,y:n,width:o,height:s,style:r,color:a,strokeColor:l,strokeWidth:c,className:u,borderRadius:f,shapeRendering:d,selected:p,onClick:h}){const{background:v,backgroundColor:b}=r||{},S=a||v||b;return i.jsx("rect",{className:Ee(["react-flow__minimap-node",{selected:p},u]),x:t,y:n,rx:f,ry:f,width:o,height:s,style:{fill:S,stroke:l,strokeWidth:c},shapeRendering:d,onClick:h?x=>h(x,e):void 0})}const Ty=m.memo(Ny),Iy=e=>e.nodes.map(t=>t.id),pr=e=>e instanceof Function?e:()=>e;function Ey({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:o=5,nodeStrokeWidth:s,nodeComponent:r=Ty,onClick:a}){const l=he(Iy,Se.shallow),c=pr(t),u=pr(e),f=pr(n),d=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return i.jsx(i.Fragment,{children:l.map(p=>i.jsx(ky,{id:p,nodeColorFunc:c,nodeStrokeColorFunc:u,nodeClassNameFunc:f,nodeBorderRadius:o,nodeStrokeWidth:s,NodeComponent:r,onClick:a,shapeRendering:d},p))})}function Ay({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:o,nodeBorderRadius:s,nodeStrokeWidth:r,shapeRendering:a,NodeComponent:l,onClick:c}){const{node:u,x:f,y:d,width:p,height:h}=he(v=>{const b=v.nodeLookup.get(e);if(!b)return{node:void 0,x:0,y:0,width:0,height:0};const S=b.internals.userNode,{x,y:_}=b.internals.positionAbsolute,{width:g,height:y}=Ut(S);return{node:S,x,y:_,width:g,height:y}},Se.shallow);return!u||u.hidden||!Tu(u)?null:i.jsx(l,{x:f,y:d,width:p,height:h,style:u.style,selected:!!u.selected,className:o(u),color:t(u),borderRadius:s,strokeColor:n(u),strokeWidth:r,shapeRendering:a,onClick:c,id:u.id})}const ky=m.memo(Ay);var By=m.memo(Ey);const Py=200,Ry=150,Dy=e=>!e.hidden,Fy=e=>{const t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?Nu(wo(e.nodeLookup,{filter:Dy}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},Ly="react-flow__minimap-desc";function Nd({style:e,className:t,nodeStrokeColor:n,nodeColor:o,nodeClassName:s="",nodeBorderRadius:r=5,nodeStrokeWidth:a,nodeComponent:l,bgColor:c,maskColor:u,maskStrokeColor:f,maskStrokeWidth:d,position:p="bottom-right",onClick:h,onNodeClick:v,pannable:b=!1,zoomable:S=!1,ariaLabel:x,inversePan:_,zoomStep:g=1,offsetScale:y=5}){const w=_e(),j=m.useRef(null),{boundingRect:N,viewBB:B,rfId:z,panZoom:W,translateExtent:D,flowWidth:E,flowHeight:G,ariaLabelConfig:T}=he(Fy,Se.shallow),O=e?.width??Py,P=e?.height??Ry,L=N.width/O,M=N.height/P,F=Math.max(L,M),U=F*O,V=F*P,Y=y*F,Z=N.x-(U-N.width)/2-Y,q=N.y-(V-N.height)/2-Y,X=U+Y*2,A=V+Y*2,C=`${Ly}-${z}`,H=m.useRef(0),K=m.useRef();H.current=F,m.useEffect(()=>{if(j.current&&W)return K.current=fb({domNode:j.current,panZoom:W,getTransform:()=>w.getState().transform,getViewScale:()=>H.current}),()=>{K.current?.destroy()}},[W]),m.useEffect(()=>{K.current?.update({translateExtent:D,width:E,height:G,inversePan:_,pannable:b,zoomStep:g,zoomable:S})},[b,S,_,g,D,E,G]);const Q=h?ie=>{const[re,J]=K.current?.pointer(ie)||[0,0];h(ie,{x:re,y:J})}:void 0,ee=v?m.useCallback((ie,re)=>{const J=w.getState().nodeLookup.get(re).internals.userNode;v(ie,J)},[]):void 0,ne=x??T["minimap.ariaLabel"];return i.jsx(Ls,{position:p,style:{...e,"--xy-minimap-background-color-props":typeof c=="string"?c:void 0,"--xy-minimap-mask-background-color-props":typeof u=="string"?u:void 0,"--xy-minimap-mask-stroke-color-props":typeof f=="string"?f:void 0,"--xy-minimap-mask-stroke-width-props":typeof d=="number"?d*F:void 0,"--xy-minimap-node-background-color-props":typeof o=="string"?o:void 0,"--xy-minimap-node-stroke-color-props":typeof n=="string"?n:void 0,"--xy-minimap-node-stroke-width-props":typeof a=="number"?a:void 0},className:Ee(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:i.jsxs("svg",{width:O,height:P,viewBox:`${Z} ${q} ${X} ${A}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":C,ref:j,onClick:Q,children:[ne&&i.jsx("title",{id:C,children:ne}),i.jsx(By,{onClick:ee,nodeColor:o,nodeStrokeColor:n,nodeBorderRadius:r,nodeClassName:s,nodeStrokeWidth:a,nodeComponent:l}),i.jsx("path",{className:"react-flow__minimap-mask",d:`M${Z-Y},${q-Y}h${X+Y*2}v${A+Y*2}h${-X-Y*2}z
|
|
7
|
+
M${B.x},${B.y}h${B.width}v${B.height}h${-B.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}Nd.displayName="MiniMap";const zy=m.memo(Nd),Oy=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,$y={[Ni.Line]:"right",[Ni.Handle]:"bottom-right"};function Gy({nodeId:e,position:t,variant:n=Ni.Handle,className:o,style:s=void 0,children:r,color:a,minWidth:l=10,minHeight:c=10,maxWidth:u=Number.MAX_VALUE,maxHeight:f=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:p,autoScale:h=!0,shouldResize:v,onResizeStart:b,onResize:S,onResizeEnd:x}){const _=sd(),g=typeof e=="string"?e:_,y=_e(),w=m.useRef(null),j=n===Ni.Handle,N=he(m.useCallback(Oy(j&&h),[j,h]),Se.shallow),B=m.useRef(null),z=t??$y[n];m.useEffect(()=>{if(!(!w.current||!g))return B.current||(B.current=Cb({domNode:w.current,nodeId:g,getStoreItems:()=>{const{nodeLookup:D,transform:E,snapGrid:G,snapToGrid:T,nodeOrigin:O,domNode:P}=y.getState();return{nodeLookup:D,transform:E,snapGrid:G,snapToGrid:T,nodeOrigin:O,paneDomNode:P}},onChange:(D,E)=>{const{triggerNodeChanges:G,nodeLookup:T,parentLookup:O,nodeOrigin:P}=y.getState(),L=[],M={x:D.x,y:D.y},F=T.get(g);if(F&&F.expandParent&&F.parentId){const U=F.origin??P,V=D.width??F.measured.width??0,Y=D.height??F.measured.height??0,Z={id:F.id,parentId:F.parentId,rect:{width:V,height:Y,...Iu({x:D.x??F.position.x,y:D.y??F.position.y},{width:V,height:Y},F.parentId,T,U)}},q=Ia([Z],T,O,P);L.push(...q),M.x=D.x?Math.max(U[0]*V,D.x):void 0,M.y=D.y?Math.max(U[1]*Y,D.y):void 0}if(M.x!==void 0&&M.y!==void 0){const U={id:g,type:"position",position:{...M}};L.push(U)}if(D.width!==void 0&&D.height!==void 0){const V={id:g,type:"dimensions",resizing:!0,setAttributes:p?p==="horizontal"?"width":"height":!0,dimensions:{width:D.width,height:D.height}};L.push(V)}for(const U of E){const V={...U,type:"position"};L.push(V)}G(L)},onEnd:({width:D,height:E})=>{const G={id:g,type:"dimensions",resizing:!1,dimensions:{width:D,height:E}};y.getState().triggerNodeChanges([G])}})),B.current.update({controlPosition:z,boundaries:{minWidth:l,minHeight:c,maxWidth:u,maxHeight:f},keepAspectRatio:d,resizeDirection:p,onResizeStart:b,onResize:S,onResizeEnd:x,shouldResize:v}),()=>{B.current?.destroy()}},[z,l,c,u,f,d,b,S,x,v]);const W=z.split("-");return i.jsx("div",{className:Ee(["react-flow__resize-control","nodrag",...W,n,o]),ref:w,style:{...s,scale:N,...a&&{[j?"backgroundColor":"borderColor"]:a}},children:r})}m.memo(Gy);const Hy=240,Wy=130,Uy={borderRadius:10,border:"1px solid #3b4258",padding:"8px 10px",color:"#e5e7eb",background:"#182033",minWidth:140,textAlign:"center",fontSize:12,fontWeight:600},Vy={start:{background:"#1b2f2a",borderColor:"#2f6d5b"},condition:{background:"#2d2435",borderColor:"#6b4f81"},action:{background:"#1f2b44",borderColor:"#4366a9"}},ec={next:"#8b9bb4",true:"#34d399",false:"#f87171"},Yy=(e,t)=>e.nodes.map((n,o)=>{const s=o%4,r=Math.floor(o/4);return{id:n.id,position:{x:s*Hy,y:r*Wy},data:{label:Xi(n)},draggable:!0,style:{...Uy,...Vy[n.type],...t===n.id?{boxShadow:"0 0 0 2px #60a5fa"}:{}}}}),Zy=(e,t)=>e.edges.map(n=>{const o=n.branch??"next";return{id:n.id,source:n.source,target:n.target,label:o,animated:t===n.id,markerEnd:{type:co.ArrowClosed,color:ec[o]},style:{stroke:ec[o],strokeWidth:t===n.id?2.5:1.6},labelStyle:{fill:"#d1d5db",fontSize:11,fontWeight:700},labelBgStyle:{fill:"#111827",fillOpacity:.85},labelBgPadding:[4,2],labelBgBorderRadius:4}});function Xy({blueprint:e,selectedNodeId:t,selectedEdgeId:n,onSelectNode:o,onSelectEdge:s}){const r=m.useMemo(()=>Yy(e,t),[e,t]),a=m.useMemo(()=>Zy(e,n),[e,n]),[l,c,u]=py(r),[f,d,p]=hy(a);m.useEffect(()=>{c(b=>r.map(S=>{const x=b.find(_=>_.id===S.id);return x?{...S,position:x.position}:S}))},[r,c]),m.useEffect(()=>{d(a)},[a,d]);const h=m.useCallback((b,S)=>{o(S.id)},[o]),v=m.useCallback((b,S)=>{s(S.id),o(S.source)},[s,o]);return i.jsxs(fy,{nodes:l,edges:f,onNodesChange:u,onEdgesChange:p,onNodeClick:h,onEdgeClick:v,fitView:!0,fitViewOptions:{padding:.2},minZoom:.2,maxZoom:2,colorMode:"dark",proOptions:{hideAttribution:!0},children:[i.jsx(zy,{zoomable:!0,pannable:!0,nodeColor:"#64748b"}),i.jsx(Cy,{}),i.jsx(yy,{gap:20,size:1,color:"#334155"})]})}function Ky({actions:e}){return e.length===0?null:i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"커스텀 액션"}),i.jsx("div",{className:"building-panel__segmented",children:e.map(t=>i.jsx("button",{className:"building-panel__segment-btn",disabled:t.disabled,onClick:()=>{t.onClick()},children:t.label},t.id))})]})}function qy({showSnow:e,setShowSnow:t,showFog:n,setShowFog:o,fogColor:s,setFogColor:r,weatherEffect:a,setWeatherEffect:l}){return i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"전역 환경"}),i.jsxs("div",{className:"building-panel__info",children:[i.jsx(ue,{label:"눈",children:i.jsx(Lr,{value:e,onChange:t})}),i.jsx(ue,{label:"안개",children:i.jsx(Lr,{value:n,onChange:o})}),i.jsx(ue,{label:"안개색",children:i.jsx(no,{value:s,onChange:r})}),i.jsxs("div",{className:"building-panel__info-item",style:{alignItems:"flex-start"},children:[i.jsx("span",{className:"building-panel__info-label",children:"날씨"}),i.jsx("div",{className:"building-panel__grid",style:{display:"flex"},children:R.BUILDING_WEATHER_EFFECT_OPTIONS.map(c=>i.jsx("button",{className:`building-panel__grid-btn ${a===c.type?"building-panel__grid-btn--active":""}`,onClick:()=>l(c.type),children:c.labelKo},c.type))})]})]})]})}const Qy=[0,Math.PI/4,Math.PI/2,Math.PI*.75,Math.PI,Math.PI*1.25,Math.PI*1.5,Math.PI*1.75];function Jy({currentObjectRotation:e,setObjectRotation:t}){return i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"오브젝트 회전"}),i.jsx("div",{className:"building-panel__grid",children:Qy.map((n,o)=>i.jsx("button",{className:`building-panel__grid-btn ${Math.abs(e-n)<.01?"building-panel__grid-btn--active":""}`,onClick:()=>t(n),children:o*45},n))})]})}function ev({isTileMode:e,currentTileMultiplier:t,setTileMultiplier:n,currentTileHeight:o,setTileHeight:s,snapToGrid:r,setSnapToGrid:a,currentTileShape:l,setTileShape:c,currentTileRotation:u,setTileRotation:f,rotations:d,selectedTileId:p,hasSelectedTileGroup:h,onDeleteSelectedTile:v}){return i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"배치 설정"}),i.jsxs("div",{className:"building-panel__info",children:[i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"크기"}),i.jsxs("div",{className:"building-panel__stepper",children:[i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>n(Math.max(1,t-1)),children:"-"}),i.jsx("span",{className:"building-panel__stepper-value",children:t}),i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>n(Math.min(4,t+1)),children:"+"})]})]}),i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"격자 맞춤"}),i.jsx("button",{className:`building-panel__toggle ${r?"building-panel__toggle--on":""}`,onClick:()=>a(!r),children:r?"ON":"OFF"})]}),i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"높이"}),i.jsxs("div",{className:"building-panel__stepper",children:[i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>s(Math.max(0,o-1)),children:"-"}),i.jsx("span",{className:"building-panel__stepper-value",children:o}),i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>s(Math.min(6,o+1)),children:"+"})]})]})]}),e&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"building-panel__section-subtitle",children:"타일 형태"}),i.jsx("div",{className:"building-panel__grid",children:R.BUILDING_TILE_SHAPE_OPTIONS.map(b=>i.jsx("button",{className:`building-panel__grid-btn ${l===b.type?"building-panel__grid-btn--active":""}`,onClick:()=>c(b.type),children:b.labelKo},b.type))}),i.jsx("div",{className:"building-panel__section-subtitle",children:"타일 회전"}),i.jsx("div",{className:"building-panel__segmented",children:d.map(b=>i.jsx("button",{className:`building-panel__segment-btn ${Math.abs(u-b.value)<1e-4?"building-panel__segment-btn--active":""}`,onClick:()=>f(b.value),children:b.label},b.value))}),i.jsxs("div",{className:"building-panel__delete-card",children:[i.jsxs("div",{children:[i.jsx("strong",{children:"선택한 타일"}),i.jsx("span",{children:p?`ID: ${p}`:"타일 하이라이트를 클릭해 선택하세요"})]}),i.jsx("button",{className:"building-panel__delete-button",disabled:!p||!h,onClick:v,children:"선택 타일 삭제"})]})]})]})}function tv({currentTileMultiplier:e,currentTileHeight:t,selectedBlockId:n,onDeleteSelectedBlock:o}){return i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"박스 편집"}),i.jsxs("div",{className:"building-panel__info",children:[i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"박스 크기"}),i.jsxs("span",{className:"building-panel__info-value",children:[e," x ",e]})]}),i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"쌓기 높이"}),i.jsx("span",{className:"building-panel__info-value",children:t})]})]}),i.jsxs("div",{className:"building-panel__delete-card",children:[i.jsxs("div",{children:[i.jsx("strong",{children:"선택한 박스"}),i.jsx("span",{children:n?`ID: ${n}`:"박스 하이라이트를 클릭해 선택하세요"})]}),i.jsx("button",{className:"building-panel__delete-button",disabled:!n,onClick:o,children:"선택 박스 삭제"})]})]})}function nv({currentWallKind:e,currentWallKindLabel:t,setWallKind:n,currentWallRotation:o,setWallRotation:s,rotations:r,selectedWallId:a,hasSelectedWallGroup:l,onFlipSelectedWall:c,onDeleteSelectedWall:u}){return i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"벽 모듈 / 회전 / 삭제"}),i.jsxs("div",{className:"building-panel__section-subtitle",children:["벽 모듈: ",t]}),i.jsx("div",{className:"building-panel__grid",children:R.BUILDING_WALL_KIND_OPTIONS.map(f=>i.jsx("button",{className:`building-panel__grid-btn ${e===f.type?"building-panel__grid-btn--active":""}`,onClick:()=>n(f.type),children:f.labelKo},f.type))}),i.jsx("div",{className:"building-panel__segmented",children:r.map(f=>i.jsx("button",{className:`building-panel__segment-btn ${Math.abs(o-f.value)<1e-4?"building-panel__segment-btn--active":""}`,onClick:()=>s(f.value),children:f.label},f.value))}),i.jsxs("div",{className:"building-panel__delete-card",children:[i.jsxs("div",{children:[i.jsx("strong",{children:"선택한 벽"}),i.jsx("span",{children:a?`ID: ${a}`:"벽 마커를 클릭해 선택하세요"})]}),i.jsx("button",{className:"building-panel__delete-button",disabled:!a||!l,onClick:c,children:"내외부 뒤집기"}),i.jsx("button",{className:"building-panel__delete-button",disabled:!a||!l,onClick:u,children:"선택 벽 삭제"})]})]})}const iv=["idle","patrol","wander"];function tc({instance:e,hoverPosition:t,updateBehavior:n,setNavigation:o,clearNavigation:s}){const r=e.behavior?.speed??2.2,a=e.behavior?.wanderRadius??4,l=e.behavior?.waypoints??[],c=t?`${t.x.toFixed(1)}, ${t.z.toFixed(1)}`:"없음";return i.jsxs("div",{className:"building-panel__npc-card",children:[i.jsx("div",{className:"building-panel__section-title",children:"이동 설정"}),i.jsx("div",{className:"building-panel__section-subtitle",children:"행동 모드"}),i.jsx("div",{className:"building-panel__segmented",children:iv.map(u=>i.jsx("button",{className:`building-panel__segment-btn ${e.behavior?.mode===u?"building-panel__segment-btn--active":""}`,onClick:()=>{n(e.id,{mode:u,speed:r}),u==="idle"&&s(e.id)},children:u},u))}),i.jsxs("div",{className:"building-panel__info",children:[i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"이동 속도"}),i.jsxs("div",{className:"building-panel__stepper",children:[i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>n(e.id,{speed:Math.max(.4,r-.4)}),children:"-"}),i.jsx("span",{className:"building-panel__stepper-value",children:r.toFixed(1)}),i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>n(e.id,{speed:Math.min(7,r+.4)}),children:"+"})]})]}),i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"배회 반경"}),i.jsxs("div",{className:"building-panel__stepper",children:[i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>n(e.id,{wanderRadius:Math.max(1,a-1)}),children:"-"}),i.jsxs("span",{className:"building-panel__stepper-value",children:[a,"m"]}),i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>n(e.id,{wanderRadius:Math.min(30,a+1)}),children:"+"})]})]})]}),i.jsx("div",{className:"building-panel__section-subtitle",children:"웨이포인트"}),i.jsxs("div",{className:"building-panel__asset-targets",children:[i.jsxs("span",{children:[l.length,"개 지정됨"]}),i.jsxs("span",{children:["호버 위치: ",c]})]}),i.jsxs("div",{className:"building-panel__segmented",children:[i.jsx("button",{className:"building-panel__segment-btn",disabled:!t,onClick:()=>{if(!t)return;const u=[t.x,t.y,t.z],f=[...l,u];n(e.id,{mode:"patrol",waypoints:f}),o(e.id,f,r)},children:"호버 위치 추가"}),i.jsx("button",{className:"building-panel__segment-btn",disabled:l.length===0,onClick:()=>{l.length!==0&&(n(e.id,{mode:"patrol",waypoints:l}),o(e.id,l,r))},children:"순찰 시작"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>{n(e.id,{waypoints:[]}),s(e.id)},children:"경로 초기화"}),i.jsx("button",{className:"building-panel__segment-btn",disabled:!t,onClick:()=>{if(!t)return;const u=[t.x,t.y,t.z];n(e.id,{mode:"idle"}),o(e.id,[u],r)},children:"호버 위치로 1회 이동"})]})]})}function nc({instance:e,animations:t,updateInstance:n,updateBehavior:o}){const s=r=>{n(e.id,{currentAnimation:r}),o(e.id,{mode:"idle",idleAnimation:r,arriveAnimation:r})};return i.jsxs("div",{className:"building-panel__npc-card",children:[i.jsx("div",{className:"building-panel__section-title",children:"애니메이션 설정"}),i.jsx("div",{className:"building-panel__section-subtitle",children:"애니메이션"}),i.jsx("div",{className:"building-panel__grid",children:t.map(r=>i.jsx("button",{className:`building-panel__grid-btn ${e.currentAnimation===r.id?"building-panel__grid-btn--active":""}`,onClick:()=>s(r.id),children:r.name},r.id))}),i.jsx("div",{className:"building-panel__segmented",children:t.map(r=>i.jsxs("button",{className:`building-panel__segment-btn ${e.behavior?.moveAnimation===r.id?"building-panel__segment-btn--active":""}`,onClick:()=>o(e.id,{moveAnimation:r.id}),children:["이동:",r.name]},`move-${r.id}`))}),i.jsx("div",{className:"building-panel__segmented",children:t.map(r=>i.jsxs("button",{className:`building-panel__segment-btn ${e.behavior?.idleAnimation===r.id?"building-panel__segment-btn--active":""}`,onClick:()=>o(e.id,{idleAnimation:r.id,arriveAnimation:r.id}),children:["대기:",r.name]},`idle-${r.id}`))})]})}const ov=["none","scripted","llm","reinforcement"],sv=["locked","available","active","completed","failed"],rv=["always","navigationIdle","perceivedAny","questStatus","friendshipAtLeast","memoryEquals"],av=["idle","moveTo","patrol","wander","playAnimation","lookAt","speak","interact","remember","moveToTarget"];function lv({instance:e,blueprints:t,selectedBlueprint:n,updateBrain:o,addBrainBlueprint:s,updateBrainBlueprint:r,onPreviewStateChange:a}){const l=m.useRef(null),[c,u]=m.useState(null),[f,d]=m.useState(null),[p,h]=m.useState(""),[v,b]=m.useState(!0),[S,x]=m.useState("nodes"),[_,g]=m.useState(!1);m.useEffect(()=>{const A=l.current;A&&g(!!A.closest(".editor-panel-modal"))},[n]),m.useEffect(()=>{_&&(v||b(!0))},[_,v]),m.useEffect(()=>{if(!n){u(null),b(!0),x("nodes");return}if(c?n.nodes.some(H=>H.id===c&&H.type!=="start"):!1)return;const C=n.nodes.find(H=>H.type!=="start");u(C?.id??null)},[n,c]);const y=A=>{if(!n||!c)return;const C=n.nodes.map(H=>H.id!==c||H.type==="start"?H:A(H));r(n.id,{...n,nodes:C})},w=n?.nodes.find(A=>A.id===c&&A.type!=="start");m.useEffect(()=>{const A=e.behavior;let C={mode:"idle",label:"대기"};if(w?.type==="action")switch(w.action.type){case"moveTo":C={mode:"move",label:"moveTo",target:w.action.target,...w.action.animationId?{animationId:w.action.animationId}:{}};break;case"patrol":C={mode:"patrol",label:"patrol",waypoints:w.action.waypoints,...w.action.animationId?{animationId:w.action.animationId}:{}};break;case"wander":C={mode:"wander",label:"wander",...w.action.radius?{radius:w.action.radius}:{}};break;case"moveToTarget":C=w.action.target.type==="point"?{mode:"move",label:"moveToTarget(point)",target:w.action.target.value,...w.action.animationId?{animationId:w.action.animationId}:{}}:{mode:"action",label:`moveToTarget(${w.action.target.type})`,...w.action.animationId?{animationId:w.action.animationId}:{}};break;case"playAnimation":C={mode:"action",label:"playAnimation",animationId:w.action.animationId};break;case"speak":C={mode:"action",label:`speak: ${w.action.text}`};break;default:C={mode:"action",label:w.action.type}}else A?.mode==="patrol"&&A.waypoints&&A.waypoints.length>0?C={mode:"patrol",label:"patrol(behavior)",waypoints:A.waypoints}:A?.mode==="wander"&&(C={mode:"wander",label:"wander(behavior)",radius:A.wanderRadius??4});a?.(C)},[e.behavior,a,w]);const j=n?.nodes.find(A=>A.type==="start")??null,N=m.useMemo(()=>new Set((n?.nodes??[]).map(A=>A.id)),[n]),B=m.useMemo(()=>(n?.edges??[]).filter(A=>!N.has(A.source)||!N.has(A.target)),[N,n]),z=m.useMemo(()=>{if(!n)return new Set;const A=new Map;for(const Q of n.edges){if(!N.has(Q.source)||!N.has(Q.target))continue;const ee=A.get(Q.source)??[];ee.push(Q.target),A.set(Q.source,ee)}const C=new Set,K=n.nodes.filter(Q=>Q.type==="start").map(Q=>Q.id);for(;K.length>0;){const Q=K.shift();if(!Q||C.has(Q))continue;C.add(Q);const ee=A.get(Q)??[];for(const ne of ee)C.has(ne)||K.push(ne)}return C},[N,n]),W=m.useMemo(()=>new Set((n?.nodes??[]).filter(A=>A.type!=="start"&&!z.has(A.id)).map(A=>A.id)),[z,n]),D=m.useMemo(()=>{const A=new Map;if(!n)return A;for(const C of n.nodes){if(C.type!=="condition")continue;const K=n.edges.filter(ee=>ee.source===C.id).map(ee=>ee.branch??"next"),Q=[];K.includes("true")||Q.push("true branch 누락"),K.includes("false")||Q.push("false branch 누락"),K.includes("next")&&Q.push("condition에는 next 대신 true/false를 권장"),Q.length>0&&A.set(C.id,Q)}return A},[n]),E=n?.nodes.filter(A=>A.type!=="start")??[],G=m.useMemo(()=>n?.edges.filter(A=>A.source===c)??[],[n,c]),T=G.find(A=>A.id===f)??G[0]??null,O=n?.nodes.find(A=>A.id===T?.target);m.useEffect(()=>{if(G.length===0){d(null);return}(!f||!G.some(A=>A.id===f))&&d(G[0]?.id??null)},[f,G]),m.useEffect(()=>{!n||B.length===0||(r(n.id,{...n,edges:n.edges.filter(A=>N.has(A.source)&&N.has(A.target))}),h(`유효하지 않은 edge ${B.length}개를 자동 정리했습니다.`))},[N,B,n,r]);const P=(A,C,H,K=n?.edges??[])=>A===C?"self-loop는 허용하지 않습니다.":K.some(ee=>ee.id!==H&&ee.source===A&&ee.target===C)?"동일 source/target edge가 이미 있습니다.":null,L=A=>{if(!n||!T)return;const C=[];for(const H of n.edges){if(H.id!==T.id){C.push(H);continue}const K=A(H),Q=P(K.source,K.target,H.id);Q?(h(Q),C.push(H)):(h(""),C.push(K))}r(n.id,{...n,edges:C})},M=A=>{if(!n||!j)return;const C={id:`${j.id}-${A}-${Date.now()}`,source:j.id,target:A,branch:"next"},H=P(C.source,C.target);if(H){h(H);return}r(n.id,{...n,edges:[...n.edges,C]}),h(`orphan 노드 ${A}를 start에 연결했습니다.`)},F=()=>{if(!n||!j||W.size===0)return;let A=0;const C=[...n.edges];for(const H of W)P(j.id,H,void 0,C)||(C.push({id:`${j.id}-${H}-${Date.now()}-${A}`,source:j.id,target:H,branch:"next"}),A+=1);if(A===0){h("복구 가능한 orphan 노드가 없습니다.");return}r(n.id,{...n,edges:C}),h(`orphan 노드 ${A}개를 start에 연결했습니다.`)},U=()=>{if(!n||!c)return;const A=E.find(K=>K.id!==c&&!n.edges.some(Q=>Q.source===c&&Q.target===K.id));if(!A)return;const C={id:`${c}-${A.id}-${Date.now()}`,source:c,target:A.id,branch:"next"},H=P(C.source,C.target);if(H){h(H);return}r(n.id,{...n,edges:[...n.edges,C]}),h(""),d(C.id)},V=()=>{!n||!T||(r(n.id,{...n,edges:n.edges.filter(A=>A.id!==T.id)}),h(""),d(null))},Y=(A,C)=>{if(!n)return;const H=n.nodes.find(re=>re.id===A);if(!H||H.type!=="condition"||n.edges.some(re=>re.source===A&&(re.branch??"next")===C))return;const Q=[...n.edges],ee=E.find(re=>re.id!==A&&!Q.some(J=>J.source===A&&J.target===re.id));if(!ee){h(`branch ${C}를 추가할 타겟 노드를 찾을 수 없습니다.`);return}const ne=P(A,ee.id,void 0,Q);if(ne){h(ne);return}const ie={id:`${A}-${C}-${ee.id}-${Date.now()}`,source:A,target:ee.id,branch:C};r(n.id,{...n,edges:[...Q,ie]}),d(ie.id),h(`condition ${A}에 ${C} branch를 추가했습니다.`)},Z=A=>{if(!n)return;const C=D.get(A)??[],H=C.some(ie=>ie.startsWith("true branch")),K=C.some(ie=>ie.startsWith("false branch"));if(!H&&!K)return;const Q=[...n.edges],ee=[...H?["true"]:[],...K?["false"]:[]];let ne=0;for(const ie of ee){if(Q.some(de=>de.source===A&&(de.branch??"next")===ie))continue;const J=E.find(de=>de.id!==A&&!Q.some(me=>me.source===A&&me.target===de.id));!J||P(A,J.id,void 0,Q)||(Q.push({id:`${A}-${ie}-${J.id}-${Date.now()}-${ne}`,source:A,target:J.id,branch:ie}),ne+=1)}if(ne===0){h("자동 보완할 분기를 찾지 못했습니다.");return}r(n.id,{...n,edges:Q}),h(`누락 분기 ${ne}개를 자동 보완했습니다.`)},q=(A,C)=>{const H=Number(A);return Number.isFinite(H)?H:C},X=(A,C,H)=>{const K=[...A];return K[C]=q(H,A[C]),K};return i.jsxs("div",{className:"building-panel__npc-card building-panel__npc-card--brain",children:[i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"AI 두뇌"}),i.jsx("div",{className:"building-panel__segmented",children:ov.map(A=>i.jsx("button",{className:`building-panel__segment-btn ${e.brain?.mode===A?"building-panel__segment-btn--active":""}`,onClick:()=>o(e.id,{mode:A}),children:A},A))})]}),i.jsx("div",{className:"building-panel__section-subtitle",children:"행동 블루프린트"}),i.jsxs("div",{className:"building-panel__grid",children:[i.jsx("button",{className:`building-panel__grid-btn ${e.brain?.blueprintId?"":"building-panel__grid-btn--active"}`,onClick:()=>o(e.id,{blueprintId:""}),children:"없음"}),t.map(A=>i.jsx("button",{className:`building-panel__grid-btn ${e.brain?.blueprintId===A.id?"building-panel__grid-btn--active":""}`,onClick:()=>o(e.id,{mode:"scripted",blueprintId:A.id}),title:A.description,children:A.name},A.id))]}),n&&i.jsx(i.Fragment,{children:i.jsxs("div",{ref:l,className:"building-panel__node-editor",children:[i.jsxs("div",{className:"building-panel__asset-targets building-panel__brain-summary",children:[i.jsx("span",{children:n.name}),i.jsxs("span",{children:[n.nodes.length," nodes · ",n.edges.length," edges"]})]}),i.jsxs("div",{className:"building-panel__segmented building-panel__brain-toolbar",children:[i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>{const A=Yp(n,e.id);s(A),o(e.id,{mode:"scripted",blueprintId:A.id})},children:"전용 복제본"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>r(n.id,Vp(n)),children:"초기화"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>b(A=>!A),children:v?"캔버스 숨기기":"캔버스 보기"})]}),v&&i.jsx("div",{className:"building-panel__brain-canvas",style:{height:_?"64vh":"320px",border:"1px solid rgba(255,255,255,0.14)",borderRadius:"8px",overflow:"hidden",marginBottom:"8px",background:"#0f172a"},children:i.jsx(Xy,{blueprint:n,selectedNodeId:c,selectedEdgeId:f,onSelectNode:u,onSelectEdge:d})}),i.jsxs("div",{className:"building-panel__brain-tabs",children:[i.jsx("button",{type:"button",className:`building-panel__brain-tab ${S==="nodes"?"building-panel__brain-tab--active":""}`,onClick:()=>x("nodes"),children:"노드 목록"}),i.jsx("button",{type:"button",className:`building-panel__brain-tab ${S==="inspector"?"building-panel__brain-tab--active":""}`,onClick:()=>x("inspector"),children:"노드 인스펙터"})]}),S==="nodes"&&i.jsx("div",{className:"building-panel__node-list",children:n.nodes.map(A=>i.jsxs("div",{className:"building-panel__node-card",style:A.id===c?{borderColor:"#6dd3ff",boxShadow:"0 0 0 1px #6dd3ff"}:W.has(A.id)?{borderColor:"#f59e0b",boxShadow:"0 0 0 1px #f59e0b"}:void 0,onClick:()=>{A.type!=="start"&&(u(A.id),x("inspector"))},children:[i.jsxs("div",{className:"building-panel__node-card-header",children:[i.jsx("div",{className:"building-panel__node-card-title",children:Xi(A)}),A.type!=="start"&&i.jsx("button",{className:"building-panel__node-card-action",onClick:()=>r(n.id,Up(n,A.id)),children:"삭제"})]}),i.jsx("div",{className:"building-panel__node-card-desc",children:Wp(A)}),i.jsx("div",{className:"building-panel__node-card-edge",children:Zp(n,A.id)}),W.has(A.id)&&i.jsxs("div",{className:"building-panel__node-card-edge",style:{display:"flex",justifyContent:"space-between",gap:"8px"},children:[i.jsx("span",{children:"도달 불가(orphan) 노드"}),i.jsx("button",{className:"building-panel__node-card-action",onClick:C=>{C.stopPropagation(),M(A.id)},disabled:!j,children:"start 연결"})]}),D.has(A.id)&&i.jsx("div",{className:"building-panel__node-card-edge",style:{color:"#f59e0b"},children:D.get(A.id)?.join(" · ")})]},A.id))}),S==="inspector"&&w&&i.jsxs("div",{className:"building-panel__info building-panel__brain-inspector",style:{marginTop:"8px"},children:[i.jsx("div",{className:"building-panel__section-subtitle",children:"노드 인스펙터"}),i.jsx(ue,{label:"라벨",children:i.jsx("input",{value:w.label??"",onChange:A=>y(C=>({...C,label:A.target.value})),style:{width:"100%"}})}),i.jsx(ue,{label:"Outgoing Edge",children:i.jsxs("select",{value:T?.id??"",onChange:A=>d(A.target.value||null),style:{width:"100%"},disabled:G.length===0,children:[G.length===0&&i.jsx("option",{value:"",children:"다음 없음"}),G.map(A=>i.jsxs("option",{value:A.id,children:[A.branch??"next"," -> ",n?.nodes.find(C=>C.id===A.target)?.label??A.target]},A.id))]})}),i.jsxs("div",{className:"building-panel__segmented",children:[i.jsx("button",{className:"building-panel__segment-btn",onClick:U,disabled:!w||E.length<=1||!E.some(A=>A.id!==w.id&&!n.edges.some(C=>C.source===w.id&&C.target===A.id)),children:"엣지 추가"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:V,disabled:!T,children:"엣지 삭제"})]}),(B.length>0||W.size>0)&&i.jsx(ue,{label:"그래프 상태",children:i.jsxs("span",{children:["dangling edge ",B.length," · orphan node ",W.size]})}),W.size>0&&i.jsxs("div",{className:"building-panel__segmented",children:[i.jsx("button",{className:"building-panel__segment-btn",onClick:F,disabled:!j,children:"orphan 전체 복구"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>{!w||!W.has(w.id)||M(w.id)},disabled:!w||!W.has(w.id)||!j,children:"선택 노드 복구"})]}),p&&i.jsx(ue,{label:"그래프 규칙",children:i.jsx("span",{children:p})}),T&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"Source",children:i.jsx("select",{value:T.source,onChange:A=>L(C=>({...C,source:A.target.value})),style:{width:"100%"},children:E.map(A=>i.jsx("option",{value:A.id,children:Xi(A)},A.id))})}),i.jsx(ue,{label:"Branch",children:i.jsxs("select",{value:T.branch??"next",onChange:A=>L(C=>({...C,branch:A.target.value})),style:{width:"100%"},children:[i.jsx("option",{value:"next",children:"next"}),i.jsx("option",{value:"true",children:"true"}),i.jsx("option",{value:"false",children:"false"})]})}),i.jsx(ue,{label:"Target",children:i.jsx("select",{value:T.target,onChange:A=>L(C=>({...C,target:A.target.value})),style:{width:"100%"},children:E.map(A=>i.jsx("option",{value:A.id,children:Xi(A)},A.id))})}),!O&&i.jsx(ue,{label:"주의",children:i.jsx("span",{children:"타겟 노드를 찾을 수 없습니다."})})]}),w.type==="condition"&&D.has(w.id)&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"Branch 검증",children:i.jsx("span",{children:D.get(w.id)?.join(" · ")})}),i.jsxs("div",{className:"building-panel__segmented",children:[i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>Y(w.id,"true"),disabled:G.some(A=>(A.branch??"next")==="true"),children:"true 분기 추가"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>Y(w.id,"false"),disabled:G.some(A=>(A.branch??"next")==="false"),children:"false 분기 추가"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>Z(w.id),children:"누락 분기 자동 보완"})]})]}),w.type==="condition"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"조건 타입",children:i.jsx("select",{value:w.condition.type,onChange:A=>{const C=A.target.value;y(H=>{if(H.type!=="condition")return H;switch(C){case"always":return{...H,condition:{type:"always"}};case"navigationIdle":return{...H,condition:{type:"navigationIdle"}};case"perceivedAny":return{...H,condition:{type:"perceivedAny"}};case"questStatus":return{...H,condition:{type:"questStatus",questId:"welcome",status:"active"}};case"friendshipAtLeast":return{...H,condition:{type:"friendshipAtLeast",score:150}};case"memoryEquals":return{...H,condition:{type:"memoryEquals",key:"memory.key",value:!0}};default:return H}})},children:rv.map(A=>i.jsx("option",{value:A,children:A},A))})}),w.condition.type==="questStatus"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"Quest ID",children:i.jsx("input",{value:w.condition.questId,onChange:A=>y(C=>C.type!=="condition"||C.condition.type!=="questStatus"?C:{...C,condition:{...C.condition,questId:A.target.value}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Status",children:i.jsx("select",{value:w.condition.status,onChange:A=>y(C=>C.type!=="condition"||C.condition.type!=="questStatus"?C:{...C,condition:{...C.condition,status:A.target.value}}),children:sv.map(A=>i.jsx("option",{value:A,children:A},A))})})]}),w.condition.type==="friendshipAtLeast"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"NPC ID(optional)",children:i.jsx("input",{value:w.condition.npcId??"",onChange:A=>y(C=>{if(C.type!=="condition"||C.condition.type!=="friendshipAtLeast")return C;const H=A.target.value.trim();return{...C,condition:{...C.condition,...H?{npcId:H}:{}}}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Score",children:i.jsx("input",{type:"number",value:w.condition.score,onChange:A=>y(C=>{if(C.type!=="condition"||C.condition.type!=="friendshipAtLeast")return C;const H=Number(A.target.value);return{...C,condition:{...C.condition,score:Number.isFinite(H)?H:C.condition.score}}}),style:{width:"100%"}})})]})]}),w.type==="action"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"액션 타입",children:i.jsx("select",{value:w.action.type,onChange:A=>{const C=A.target.value;y(H=>{if(H.type!=="action")return H;switch(C){case"idle":return{...H,action:{type:"idle",animationId:"idle"}};case"moveTo":return{...H,action:{type:"moveTo",target:[0,0,0],speed:2.2,animationId:"walk"}};case"patrol":return{...H,action:{type:"patrol",waypoints:[[0,0,0],[2,0,2]],speed:2.2,loop:!0,animationId:"walk"}};case"wander":return{...H,action:{type:"wander",radius:4,speed:2.2,waitSeconds:1.5}};case"playAnimation":return{...H,action:{type:"playAnimation",animationId:"wave",loop:!1,speed:1}};case"lookAt":return{...H,action:{type:"lookAt",target:[0,0,0]}};case"speak":return{...H,action:{type:"speak",text:"안녕?",duration:2}};case"interact":return{...H,action:{type:"interact",targetId:"target.entity"}};case"remember":return{...H,action:{type:"remember",key:"memory.key",value:!0}};case"moveToTarget":return{...H,action:{type:"moveToTarget",target:{type:"self"},speed:2.2,animationId:"walk"}};default:return H}})},children:av.map(A=>i.jsx("option",{value:A,children:A},A))})}),w.action.type==="wander"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"반경",children:i.jsx("input",{type:"number",value:w.action.radius??4,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="wander"?C:{...C,action:{...C.action,radius:q(A.target.value,C.action.radius??4)}}),style:{width:"100%"}})}),i.jsx(ue,{label:"속도",children:i.jsx("input",{type:"number",value:w.action.speed??2.2,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="wander"?C:{...C,action:{...C.action,speed:q(A.target.value,C.action.speed??2.2)}}),style:{width:"100%"}})}),i.jsx(ue,{label:"대기(초)",children:i.jsx("input",{type:"number",value:w.action.waitSeconds??1.5,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="wander"?C:{...C,action:{...C.action,waitSeconds:q(A.target.value,C.action.waitSeconds??1.5)}}),style:{width:"100%"}})})]}),w.action.type==="speak"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"대사",children:i.jsx("input",{value:w.action.text,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="speak"?C:{...C,action:{...C.action,text:A.target.value}}),style:{width:"100%"}})}),i.jsx(ue,{label:"지속시간(초)",children:i.jsx("input",{type:"number",value:w.action.duration??2,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="speak"?C:{...C,action:{...C.action,duration:q(A.target.value,C.action.duration??2)}}),style:{width:"100%"}})})]}),w.action.type==="playAnimation"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"Animation ID",children:i.jsx("input",{value:w.action.animationId,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="playAnimation"?C:{...C,action:{...C.action,animationId:A.target.value}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Loop",children:i.jsx("input",{type:"checkbox",checked:w.action.loop??!1,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="playAnimation"?C:{...C,action:{...C.action,loop:A.target.checked}})})}),i.jsx(ue,{label:"재생속도",children:i.jsx("input",{type:"number",value:w.action.speed??1,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="playAnimation"?C:{...C,action:{...C.action,speed:q(A.target.value,C.action.speed??1)}}),style:{width:"100%"}})})]}),w.action.type==="moveToTarget"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"Target",children:i.jsxs("select",{value:w.action.target.type,onChange:A=>y(C=>{if(C.type!=="action"||C.action.type!=="moveToTarget")return C;const H=A.target.value;return H==="point"?{...C,action:{...C.action,target:{type:"point",value:[0,0,0]}}}:{...C,action:{...C.action,target:{type:H}}}}),children:[i.jsx("option",{value:"self",children:"self"}),i.jsx("option",{value:"nearestPerceived",children:"nearestPerceived"}),i.jsx("option",{value:"point",children:"point"})]})}),w.action.target.type==="point"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"Point X",children:i.jsx("input",{type:"number",value:w.action.target.value[0],onChange:A=>y(C=>C.type!=="action"||C.action.type!=="moveToTarget"||C.action.target.type!=="point"?C:{...C,action:{...C.action,target:{type:"point",value:X(C.action.target.value,0,A.target.value)}}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Point Y",children:i.jsx("input",{type:"number",value:w.action.target.value[1],onChange:A=>y(C=>C.type!=="action"||C.action.type!=="moveToTarget"||C.action.target.type!=="point"?C:{...C,action:{...C.action,target:{type:"point",value:X(C.action.target.value,1,A.target.value)}}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Point Z",children:i.jsx("input",{type:"number",value:w.action.target.value[2],onChange:A=>y(C=>C.type!=="action"||C.action.type!=="moveToTarget"||C.action.target.type!=="point"?C:{...C,action:{...C.action,target:{type:"point",value:X(C.action.target.value,2,A.target.value)}}}),style:{width:"100%"}})})]}),i.jsx(ue,{label:"속도",children:i.jsx("input",{type:"number",value:w.action.speed??2.2,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="moveToTarget"?C:{...C,action:{...C.action,speed:q(A.target.value,C.action.speed??2.2)}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Animation ID",children:i.jsx("input",{value:w.action.animationId??"",onChange:A=>y(C=>{if(C.type!=="action"||C.action.type!=="moveToTarget")return C;const H=A.target.value.trim(),{animationId:K,...Q}=C.action;return{...C,action:{...Q,...H?{animationId:H}:{}}}}),style:{width:"100%"}})})]}),w.action.type==="idle"&&i.jsx(ue,{label:"Animation ID",children:i.jsx("input",{value:w.action.animationId??"",onChange:A=>y(C=>{if(C.type!=="action"||C.action.type!=="idle")return C;const H=A.target.value.trim(),{animationId:K,...Q}=C.action;return{...C,action:{...Q,...H?{animationId:H}:{}}}}),style:{width:"100%"}})}),w.action.type==="interact"&&i.jsx(ue,{label:"Target ID",children:i.jsx("input",{value:w.action.targetId,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="interact"?C:{...C,action:{...C.action,targetId:A.target.value}}),style:{width:"100%"}})}),w.action.type==="remember"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"Memory Key",children:i.jsx("input",{value:w.action.key,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="remember"?C:{...C,action:{...C.action,key:A.target.value}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Memory Value",children:i.jsx("input",{value:String(w.action.value),onChange:A=>y(C=>C.type!=="action"||C.action.type!=="remember"?C:{...C,action:{...C.action,value:A.target.value}}),style:{width:"100%"}})})]}),w.action.type==="moveTo"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"Target X",children:i.jsx("input",{type:"number",value:w.action.target[0],onChange:A=>y(C=>C.type!=="action"||C.action.type!=="moveTo"?C:{...C,action:{...C.action,target:X(C.action.target,0,A.target.value)}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Target Y",children:i.jsx("input",{type:"number",value:w.action.target[1],onChange:A=>y(C=>C.type!=="action"||C.action.type!=="moveTo"?C:{...C,action:{...C.action,target:X(C.action.target,1,A.target.value)}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Target Z",children:i.jsx("input",{type:"number",value:w.action.target[2],onChange:A=>y(C=>C.type!=="action"||C.action.type!=="moveTo"?C:{...C,action:{...C.action,target:X(C.action.target,2,A.target.value)}}),style:{width:"100%"}})}),i.jsx(ue,{label:"속도",children:i.jsx("input",{type:"number",value:w.action.speed??2.2,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="moveTo"?C:{...C,action:{...C.action,speed:q(A.target.value,C.action.speed??2.2)}}),style:{width:"100%"}})})]}),w.action.type==="lookAt"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"Target X",children:i.jsx("input",{type:"number",value:w.action.target[0],onChange:A=>y(C=>C.type!=="action"||C.action.type!=="lookAt"?C:{...C,action:{...C.action,target:X(C.action.target,0,A.target.value)}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Target Y",children:i.jsx("input",{type:"number",value:w.action.target[1],onChange:A=>y(C=>C.type!=="action"||C.action.type!=="lookAt"?C:{...C,action:{...C.action,target:X(C.action.target,1,A.target.value)}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Target Z",children:i.jsx("input",{type:"number",value:w.action.target[2],onChange:A=>y(C=>C.type!=="action"||C.action.type!=="lookAt"?C:{...C,action:{...C.action,target:X(C.action.target,2,A.target.value)}}),style:{width:"100%"}})})]}),w.action.type==="patrol"&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{label:"웨이포인트 수",children:i.jsx("span",{children:w.action.waypoints.length})}),i.jsxs("div",{className:"building-panel__info-item",style:{flexDirection:"column",alignItems:"stretch",gap:"6px"},children:[i.jsx("span",{className:"building-panel__info-label",children:"웨이포인트 편집"}),w.action.waypoints.map((A,C)=>i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr)) auto auto auto",gap:"4px",alignItems:"center"},children:[i.jsx("input",{type:"number",value:A[0],onChange:H=>y(K=>{if(K.type!=="action"||K.action.type!=="patrol")return K;const Q=[...K.action.waypoints],ee=Q[C]??A;return Q[C]=X(ee,0,H.target.value),{...K,action:{...K.action,waypoints:Q}}})}),i.jsx("input",{type:"number",value:A[1],onChange:H=>y(K=>{if(K.type!=="action"||K.action.type!=="patrol")return K;const Q=[...K.action.waypoints],ee=Q[C]??A;return Q[C]=X(ee,1,H.target.value),{...K,action:{...K.action,waypoints:Q}}})}),i.jsx("input",{type:"number",value:A[2],onChange:H=>y(K=>{if(K.type!=="action"||K.action.type!=="patrol")return K;const Q=[...K.action.waypoints],ee=Q[C]??A;return Q[C]=X(ee,2,H.target.value),{...K,action:{...K.action,waypoints:Q}}})}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>y(H=>{if(H.type!=="action"||H.action.type!=="patrol"||C<=0)return H;const K=[...H.action.waypoints],Q=K[C-1],ee=K[C];return!Q||!ee?H:(K[C-1]=ee,K[C]=Q,{...H,action:{...H.action,waypoints:K}})}),children:"위"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>y(H=>{if(H.type!=="action"||H.action.type!=="patrol"||C>=H.action.waypoints.length-1)return H;const K=[...H.action.waypoints],Q=K[C],ee=K[C+1];return!Q||!ee?H:(K[C]=ee,K[C+1]=Q,{...H,action:{...H.action,waypoints:K}})}),children:"아래"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>y(H=>H.type!=="action"||H.action.type!=="patrol"||H.action.waypoints.length<=1?H:{...H,action:{...H.action,waypoints:H.action.waypoints.filter((K,Q)=>Q!==C)}}),children:"삭제"})]},`waypoint-${C}`)),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>y(A=>{if(A.type!=="action"||A.action.type!=="patrol")return A;const C=A.action.waypoints[A.action.waypoints.length-1]??[0,0,0],H=[C[0]+1,C[1],C[2]+1];return{...A,action:{...A.action,waypoints:[...A.action.waypoints,H]}}}),children:"웨이포인트 추가"})]}),i.jsx(ue,{label:"속도",children:i.jsx("input",{type:"number",value:w.action.speed??2.2,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="patrol"?C:{...C,action:{...C.action,speed:q(A.target.value,C.action.speed??2.2)}}),style:{width:"100%"}})}),i.jsx(ue,{label:"Loop",children:i.jsx("input",{type:"checkbox",checked:w.action.loop??!0,onChange:A=>y(C=>C.type!=="action"||C.action.type!=="patrol"?C:{...C,action:{...C.action,loop:A.target.checked}})})})]})]})]}),i.jsxs("div",{className:"building-panel__segmented",children:[i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>r(n.id,ko(n,Ao("navigationIdle"),e.behavior)),children:"조건:이동 대기"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>r(n.id,ko(n,Ao("questStatus"),e.behavior)),children:"조건:퀘스트"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>r(n.id,ko(n,Ao("friendshipAtLeast"),e.behavior)),children:"조건:친밀도"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>r(n.id,Ki(n,Zi("wander",e.behavior))),children:"배회 노드 추가"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>r(n.id,Ki(n,Zi("speak",e.behavior))),children:"대화 노드 추가"}),i.jsx("button",{className:"building-panel__segment-btn",onClick:()=>{const A=ko(n,Ao("questStatus"),e.behavior),C=Ki(A,Zi("speak",e.behavior));r(n.id,C)},children:"프리셋:퀘스트 대화"})]})]})})]})}function ic({instance:e,updateBrain:t,updatePerception:n}){const o=e.perception?.sightRadius??8;return i.jsxs("div",{className:"building-panel__npc-card",children:[i.jsx("div",{className:"building-panel__section-title",children:"지각/연동 설정"}),i.jsxs("div",{className:"building-panel__info",children:[i.jsx(ue,{label:"시야 감지",children:i.jsx(Lr,{value:e.perception?.enabled??!0,onChange:s=>n(e.id,{enabled:s})})}),i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"시야 반경"}),i.jsxs("div",{className:"building-panel__stepper",children:[i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>n(e.id,{sightRadius:Math.max(1,o-1)}),children:"-"}),i.jsxs("span",{className:"building-panel__stepper-value",children:[o,"m"]}),i.jsx("button",{className:"building-panel__stepper-btn",onClick:()=>n(e.id,{sightRadius:Math.min(60,o+1)}),children:"+"})]})]}),i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"Provider"}),i.jsx("input",{value:e.brain?.providerId??"",onChange:s=>t(e.id,{providerId:s.target.value}),placeholder:"llm provider id",style:{width:"100%",minWidth:0}})]}),i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"Policy"}),i.jsx("input",{value:e.brain?.policyId??"",onChange:s=>t(e.id,{policyId:s.target.value}),placeholder:"rl policy id",style:{width:"100%",minWidth:0}})]}),i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"관측"}),i.jsxs("span",{className:"building-panel__info-value",children:["감지 ",e.lastObservation?.perceived.length??0," · 결정 ",e.lastDecision?.source??"없음"]})]})]})]})}function rt({label:e,value:t,onDecrement:n,onIncrement:o}){return i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:e}),i.jsxs("div",{className:"building-panel__stepper",children:[i.jsx("button",{className:"building-panel__stepper-btn",onClick:n,children:"-"}),i.jsx("span",{className:"building-panel__stepper-value",children:t}),i.jsx("button",{className:"building-panel__stepper-btn",onClick:o,children:"+"})]})]})}function ea({label:e,value:t,placeholder:n,onChange:o}){return i.jsxs("div",{className:"building-panel__info-item",style:{flexDirection:"column",alignItems:"stretch",gap:"4px"},children:[i.jsx("span",{className:"building-panel__info-label",children:e}),i.jsx("input",{type:"text",value:t,onChange:s=>o(s.target.value),placeholder:n,style:{width:"100%",padding:"4px 6px",fontSize:"11px",background:"var(--panel-bg, #1a1a2e)",border:"1px solid var(--border-color, #333)",borderRadius:"3px",color:"inherit",boxSizing:"border-box"}})]})}function cv({currentTreeKind:e,setTreeKind:t,currentObjectPrimaryColor:n,setObjectPrimaryColor:o,currentObjectSecondaryColor:s,setObjectSecondaryColor:r}){return i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"나무 프리셋"}),i.jsx("div",{className:"building-panel__grid",children:R.BUILDING_TREE_OPTIONS.map(a=>i.jsx("button",{className:`building-panel__grid-btn ${e===a.type?"building-panel__grid-btn--active":""}`,onClick:()=>t(a.type),children:a.labelKo},a.type))}),i.jsxs("div",{className:"building-panel__info",children:[i.jsx(ue,{label:"잎/꽃 색",children:i.jsx(no,{value:n,onChange:o})}),i.jsx(ue,{label:"줄기 색",children:i.jsx(no,{value:s,onChange:r})})]})]})}function uv({currentFireIntensity:e,setFireIntensity:t,currentFireWidth:n,setFireWidth:o,currentFireHeight:s,setFireHeight:r,currentFireColor:a,setFireColor:l}){return i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"불 설정"}),i.jsxs("div",{className:"building-panel__info",children:[i.jsx(rt,{label:"강도",value:e.toFixed(1),onDecrement:()=>t(Math.max(.5,e-.5)),onIncrement:()=>t(Math.min(3,e+.5))}),i.jsx(rt,{label:"너비",value:`${n.toFixed(1)}m`,onDecrement:()=>o(Math.max(.3,n-.2)),onIncrement:()=>o(Math.min(4,n+.2))}),i.jsx(rt,{label:"높이",value:`${s.toFixed(1)}m`,onDecrement:()=>r(Math.max(.5,s-.3)),onIncrement:()=>r(Math.min(5,s+.3))}),i.jsx(ue,{label:"색상",children:i.jsx(no,{value:a,onChange:l})})]})]})}const dv=[{value:"#00ff88",label:"초록"},{value:"#00aaff",label:"파랑"},{value:"#f59e0b",label:"앰버"},{value:"#ffffff",label:"흰색"},{value:"#ffdd00",label:"노랑"}];function fv({currentBillboardScale:e,setBillboardScale:t,currentBillboardOffsetY:n,setBillboardOffsetY:o,currentBillboardWidth:s,setBillboardWidth:r,currentBillboardHeight:a,setBillboardHeight:l,currentBillboardElevation:c,setBillboardElevation:u,currentBillboardIntensity:f,setBillboardIntensity:d,currentBillboardText:p,setBillboardText:h,currentBillboardImageUrl:v,setBillboardImageUrl:b,currentBillboardColor:S,setBillboardColor:x}){return i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"간판 설정"}),i.jsxs("div",{className:"building-panel__info",children:[i.jsx(rt,{label:"크기",value:`${e.toFixed(1)}x`,onDecrement:()=>t(Math.max(.2,e-.2)),onIncrement:()=>t(Math.min(10,e+.2))}),i.jsx(rt,{label:"배치 높이",value:`${n.toFixed(2)}m`,onDecrement:()=>o(Math.max(-4,n-.25)),onIncrement:()=>o(Math.min(12,n+.25))}),i.jsx(rt,{label:"판넬 너비",value:s>0?`${s.toFixed(2)}m`:"자동",onDecrement:()=>r(Math.max(0,s-.25)),onIncrement:()=>r(Math.min(12,s+.25))}),i.jsx(rt,{label:"판넬 높이",value:`${a.toFixed(2)}m`,onDecrement:()=>l(Math.max(.3,a-.25)),onIncrement:()=>l(Math.min(8,a+.25))}),i.jsx(rt,{label:"기둥 높이",value:`${c.toFixed(2)}m`,onDecrement:()=>u(Math.max(0,c-.25)),onIncrement:()=>u(Math.min(8,c+.25))}),i.jsx(rt,{label:"밝기",value:f.toFixed(2),onDecrement:()=>d(Math.max(0,f-.25)),onIncrement:()=>d(Math.min(8,f+.25))}),i.jsx(ea,{label:"문구",value:p,onChange:h,placeholder:"표시할 문구..."}),i.jsx(ea,{label:"이미지 URL",value:v,onChange:b,placeholder:"https://..."}),i.jsxs("div",{className:"building-panel__info-item",style:{flexDirection:"column",alignItems:"stretch",gap:"4px"},children:[i.jsx("span",{className:"building-panel__info-label",children:"색상"}),i.jsx("div",{className:"building-panel__grid",children:dv.map(_=>i.jsx("button",{className:`building-panel__grid-btn ${S===_.value?"building-panel__grid-btn--active":""}`,onClick:()=>x(_.value),style:{borderBottom:`3px solid ${_.value}`},children:_.label},_.value))})]})]})]})}function pv({currentFlagStyle:e,setFlagStyle:t,currentFlagWidth:n,setFlagWidth:o,currentFlagHeight:s,setFlagHeight:r,currentFlagImageUrl:a,setFlagImageUrl:l}){return i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"깃발 설정"}),i.jsxs("div",{className:"building-panel__info",children:[i.jsxs("div",{className:"building-panel__info-item",style:{flexDirection:"column",alignItems:"stretch",gap:"4px"},children:[i.jsx("span",{className:"building-panel__info-label",children:"스타일"}),i.jsx("div",{className:"building-panel__grid",children:R.BUILDING_FLAG_STYLE_OPTIONS.map(({style:c,meta:u})=>i.jsx("button",{className:`building-panel__grid-btn ${e===c?"building-panel__grid-btn--active":""}`,onClick:()=>t(c),children:u.label},c))})]}),i.jsx(rt,{label:"너비",value:`${n}m`,onDecrement:()=>o(Math.max(.5,n-.5)),onIncrement:()=>o(Math.min(8,n+.5))}),i.jsx(rt,{label:"높이",value:`${s}m`,onDecrement:()=>r(Math.max(.5,s-.5)),onIncrement:()=>r(Math.min(6,s+.5))}),i.jsx(ea,{label:"이미지 URL",value:a,onChange:l,placeholder:"https://..."})]})]})}const vs=new Map;function ta(e,t){return`${e}:${t}`}function hv(e,t){const n=e[0]-t[0],o=e[1]-t[1],s=e[2]-t[2];return n*n+o*o+s*s}function mv(e,t){const n=e.timestamp*1.7+e.instanceId.length*13.37,o=(Math.sin(n)*.5+.5)*Math.PI*2,s=t*(.35+(Math.cos(n*.73)*.5+.5)*.65);return[e.position[0]+Math.cos(o)*s,e.position[1],e.position[2]+Math.sin(o)*s]}function gv(e,t,n){const o=ta(e,t);return vs.set(o,n),()=>{vs.delete(o)}}function Td(e,t,n){const o=e.perception,s=o?.enabled?o.sightRadius:0,r=s*s,a=[];if(s>0)for(const l of t.values()){if(l.id===e.id)continue;const c=hv(e.position,l.position);if(c>r)continue;const u=Math.sqrt(c);a.push({instanceId:l.id,name:l.name,position:l.position,distance:u,brainMode:l.brain?.mode??"none"})}return a.sort((l,c)=>l.distance-c.distance),{instanceId:e.id,templateId:e.templateId,timestamp:n,position:e.position,rotation:e.rotation,currentAnimation:e.currentAnimation??e.behavior?.idleAnimation??"idle",navigationState:e.navigation?.state??"none",behaviorMode:e.behavior?.mode??"idle",brainMode:e.brain?.mode??"none",perceptionEnabled:o?.enabled??!1,perceived:a,...e.brain?.memory?{memory:e.brain.memory}:{}}}function bv(e){if(!e)return;const t=[e.policyId,e.providerId].filter(n=>!!n);for(const n of t){const o=vs.get(ta(e.mode,n));if(o)return o}return vs.get(ta(e.mode,"default"))}function xv(e,t){const n=e.brain?.blueprintId,o=n?se.getNPCBrainBlueprint(n):void 0;if(o){const r=se.compileNPCBrainBlueprint(o,t);if(r.length>0)return{source:"blueprint",reason:o.name,actions:r}}const s=e.behavior;if(!(!s||s.mode==="idle"||t.navigationState==="moving")){if(s.mode==="patrol"&&s.waypoints&&s.waypoints.length>0)return{source:"scripted",reason:"patrol behavior",actions:[{type:"patrol",waypoints:s.waypoints,speed:s.speed,...s.loop!==void 0?{loop:s.loop}:{},...s.moveAnimation?{animationId:s.moveAnimation}:{}}]};if(s.mode==="wander"){const r=Math.max(.5,s.wanderRadius??4);return{source:"scripted",reason:"wander behavior",actions:[{type:"moveTo",target:mv(t,r),speed:s.speed,...s.moveAnimation?{animationId:s.moveAnimation}:{}}]}}}}function Id(e,t){const n=e.brain?.mode??"none";if(n==="none")return;const o=bv(e.brain);if(o)return o({instance:e,observation:t});if(n==="scripted")return xv(e,t)}class yv extends m.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidUpdate(t){this.state.hasError&&t.part.url!==this.props.part.url&&this.setState({hasError:!1})}render(){return this.state.hasError?i.jsx(Ed,{part:this.props.part,instanceId:this.props.instanceId}):this.props.children}}function vv(e,t){if(e[t])return t;const n=Object.keys(e),o=t.toLowerCase();return n.find(s=>s.toLowerCase()===o)??n.find(s=>s.toLowerCase().includes(o))??(n.length===1?n[0]:void 0)}function Ed({part:e}){return i.jsxs("mesh",{position:e.position||[0,0,0],rotation:e.rotation||[0,0,0],scale:e.scale||[1,1,1],children:[i.jsx("boxGeometry",{args:[.5,.5,.5]}),i.jsx("meshStandardMaterial",{color:e.color||"#cccccc",transparent:!0,opacity:.6})]})}function wv(e){const t=e.trim();return t.startsWith("gltf/")?`/${t}`:t}function Sv({part:e,currentAnimation:t}){const n=m.useMemo(()=>wv(e.url),[e.url]),o=pt.useGLTF(n),s=m.useMemo(()=>{const l=ua.SkeletonUtils.clone(o.scene);return l&&R.getDefaultToonMode()&&R.applyToonToScene(l),l},[o]),{actions:r}=pt.useAnimations(o.animations,s),a=m.useRef(void 0);return m.useEffect(()=>{if(!t)return;const l=vv(r,t);if(!l||a.current===l)return;const c=a.current?r[a.current]:void 0,u=r[l];c?.fadeOut(.2),u?.reset().fadeIn(.2).play(),a.current=l},[r,t]),s?i.jsx("primitive",{object:s,position:e.position||[0,0,0],rotation:e.rotation||[0,0,0],scale:e.scale||[1,1,1]}):null}function _v({part:e,instanceId:t,currentAnimation:n}){return!!e.url&&e.url.trim()!==""?i.jsx(yv,{part:e,instanceId:t,currentAnimation:n,children:i.jsx(Sv,{part:e,instanceId:t,currentAnimation:n})}):i.jsx(Ed,{part:e,instanceId:t})}const jv=.3,Mv={height:1.8,radius:.32,interactionRadius:1.6},ka=m.memo(function({instance:t,isEditMode:n,onClick:o}){const s=m.useRef(null),r=m.useRef(null),a=m.useRef(0),l=se.useNPCStore(m.useCallback(E=>E.templates.get(t.templateId),[t.templateId])),c=se.useNPCStore(m.useCallback(E=>t.currentClothingSetId?E.clothingSets.get(t.currentClothingSetId):void 0,[t.currentClothingSetId])),u=se.useNPCStore(E=>E.advanceNavigation),f=se.useNPCStore(E=>E.executeInstanceAction),d=se.useNPCStore(E=>E.executeInstanceActions),p=se.useNPCStore(E=>E.setInstanceDecision),h=se.useNPCStore(E=>E.setInstanceObservation),v=se.useNPCStore(E=>E.updateInstance),b=se.useNPCStore(E=>E.updateNavigationPosition),S=t.navigation?.state==="moving",x=t.volume??Mv,_=Math.max(.05,x.height*.5-x.radius),g=_+x.radius,y=S?"kinematicPosition":"fixed",w=Math.max(x.interactionRadius,x.radius),j=m.useRef(0);m.useEffect(()=>{a.current=t.navigation?.currentIndex??0},[t.navigation?.waypoints]),be.useFrame((E,G)=>{if(!S||!t.navigation)return;const T=r.current;if(!T)return;const{waypoints:O,speed:P}=t.navigation,L=a.current;if(L>=O.length)return;const M=O[L];if(!M)return;const F=T.translation(),U=M[0]-F.x,V=M[2]-F.z,Y=Math.sqrt(U*U+V*V);if(Y<jv){a.current=L+1,L+1>=O.length&&b(t.id,[M[0],M[1],M[2]]),u(t.id);return}const Z=Math.min(P*G,Y),q=F.x+U/Y*Z,X=F.z+V/Y*Z;T.setNextKinematicTranslation({x:q,y:F.y,z:X})}),be.useFrame(E=>{if((t.brain?.mode??"none")==="none"||E.clock.elapsedTime<j.current)return;const O=r.current?.translation(),P=O?{...t,position:[O.x,O.y,O.z]}:t,L=Td(P,se.useNPCStore.getState().instances,E.clock.elapsedTime);h(t.id,L);const M=Id(P,L);M&&M.actions.length>0&&(p(t.id,M),d(t.id,M.actions)),j.current=E.clock.elapsedTime+Math.max(.5,t.behavior?.waitSeconds??1)});const N=m.useCallback(E=>{E.stopPropagation(),document.body.style.cursor="pointer";const G=s.current?.__handlers;G?.pointerover&&G.pointerover()},[]),B=m.useCallback(()=>{document.body.style.cursor="default"},[]),z=m.useCallback(E=>{const G=t.events?.find(O=>O.type===E);if(!G)return;const T=G.payload;if(G.action==="dialogue"&&T?.type==="dialogue"){f(t.id,{type:"speak",text:T.text,...T.duration!==void 0?{duration:T.duration}:{}});return}if(G.action==="animation"&&T?.type==="animation"){f(t.id,{type:"playAnimation",animationId:T.animationId,...T.loop!==void 0?{loop:T.loop}:{}});return}if(G.action==="custom"&&T?.type==="custom"){f(t.id,{type:"remember",key:`event:${G.id}`,value:T.data});return}G.action==="sound"&&T?.type==="sound"&&v(t.id,{metadata:{...t.metadata,lastInteractionTargetId:T.soundUrl}})},[f,t.events,t.id,t.metadata,v]);m.useEffect(()=>{if(!t.events||t.events.length===0)return;const E=s.current;if(!E)return;const G=()=>{z("onHover")},T=()=>{z("onClick")};return E.__handlers={pointerover:G,click:T},()=>{delete E.__handlers}},[t.events,z]);const W=m.useMemo(()=>{if(!l)return[];const E=[...l.baseParts];if(c&&E.push(...c.parts),l.accessoryParts&&E.push(...l.accessoryParts),t.customParts)for(const G of t.customParts){const T=E.findIndex(O=>O.type===G.type);T>=0?E[T]={...E[T],...G}:E.push(G)}return E},[l,c,t.customParts]);if(!l)return null;const D=l.fullModelUrl||t.metadata?.modelUrl;return D?i.jsxs(R.PhysicsEntity,{ref:r,url:D,isActive:!1,componentType:"character",name:`npc-${t.id}`,position:t.position,rotation:t.rotation,rigidbodyType:y,colliderSize:{height:x.height,radius:x.radius},currentAnimation:t.currentAnimation||"idle",userData:{instanceId:t.id,templateId:t.templateId,nameTag:t.metadata?.nameTag,npcBrainMode:t.brain?.mode??"none",npcPerceptionEnabled:t.perception?.enabled??!1},onCollisionEnter:()=>{z("onClick"),o&&o()},children:[i.jsx(ct.CapsuleCollider,{sensor:!0,args:[Math.max(.05,_),w],position:[0,g,0]}),n&&i.jsxs("mesh",{position:[0,2.5,0],children:[i.jsx("boxGeometry",{args:[.5,.5,.5]}),i.jsx("meshStandardMaterial",{color:"#00ff00",transparent:!0,opacity:.6})]})]}):i.jsxs(ct.RigidBody,{ref:r,type:y,position:t.position,rotation:t.rotation,colliders:!1,userData:{instanceId:t.id,templateId:t.templateId,npcBrainMode:t.brain?.mode??"none",npcPerceptionEnabled:t.perception?.enabled??!1},children:[i.jsx(ct.CapsuleCollider,{args:[_,x.radius],position:[0,g,0]}),i.jsx(ct.CapsuleCollider,{sensor:!0,args:[Math.max(.05,_),w],position:[0,g,0]}),i.jsxs("group",{ref:s,scale:t.scale,...o?{onClick:E=>{E.stopPropagation(),E.nativeEvent.preventDefault(),z("onClick"),o()}}:{},onPointerEnter:N,onPointerLeave:B,children:[W.map(E=>i.jsx(_v,{part:E,instanceId:t.id,currentAnimation:t.currentAnimation??t.behavior?.idleAnimation??"idle"},E.id)),n&&i.jsxs("mesh",{position:[0,2.5,0],children:[i.jsx("boxGeometry",{args:[.5,.5,.5]}),i.jsx("meshStandardMaterial",{color:"#00ff00",transparent:!0,opacity:.6})]})]})]})});function Cv({layout:e="default",npcTemplatesArray:t,selectedNPCTemplateId:n,setSelectedNPCTemplate:o,npcInstancesArray:s,selectedNPCInstanceId:r,setSelectedNPCInstance:a,selectedNPCInstance:l,npcAnimationsArray:c,selectedNPCBrainBlueprint:u,npcBrainBlueprintsArray:f,hoverPosition:d,updateNPCBehavior:p,setNPCNavigation:h,clearNPCNavigation:v,updateNPCInstance:b,updateNPCBrain:S,addNPCBrainBlueprint:x,updateNPCBrainBlueprint:_,updateNPCPerception:g}){const[y,w]=m.useState("movement"),[j,N]=m.useState({mode:"idle",label:"대기"}),B=m.useMemo(()=>s.findIndex(q=>q.id===r),[s,r]),z=B>=0,W=m.useCallback(()=>{if(s.length===0)return;const q=z?(B-1+s.length)%s.length:0,X=s[q];X&&a(X.id)},[z,s,B,a]),D=m.useCallback(()=>{if(s.length===0)return;const q=z?(B+1)%s.length:0,X=s[q];X&&a(X.id)},[z,s,B,a]),E=m.useMemo(()=>{if(!l)return null;const q=(X,A,C=2.2)=>{h(X,{waypoints:A,currentIndex:0,speed:C,state:A.length>0?"moving":"idle"})};return y==="movement"?i.jsx(tc,{instance:l,hoverPosition:d,updateBehavior:p,setNavigation:q,clearNavigation:v}):y==="animation"?i.jsx(nc,{instance:l,animations:c,updateInstance:b,updateBehavior:p}):i.jsx(ic,{instance:l,updateBrain:S,updatePerception:g})},[y,v,d,c,l,h,p,S,b,g]),G=m.useCallback((q,X,A=2.2)=>{h(q,{waypoints:X,currentIndex:0,speed:A,state:X.length>0?"moving":"idle"})},[h]),T=l?i.jsx(tc,{instance:l,hoverPosition:d,updateBehavior:p,setNavigation:G,clearNavigation:v}):null,O=l?i.jsx(nc,{instance:l,animations:c,updateInstance:b,updateBehavior:p}):null,P=l?i.jsx(ic,{instance:l,updateBrain:S,updatePerception:g}):null,L=i.jsxs("div",{className:"building-panel__asset-targets building-panel__npc-summary building-panel__npc-statusbar",children:[i.jsxs("span",{children:["선택 NPC: ",l?.name??r??"선택 없음"]}),i.jsxs("span",{children:["행동: ",l?.behavior?.mode??"idle"," · 이동: ",l?.navigation?.state??"없음"]}),i.jsxs("span",{children:["현재 애니메이션: ",l?.currentAnimation??"idle"]})]}),M=i.jsxs("div",{className:"building-panel__npc-switcher",children:[i.jsx("button",{className:"building-panel__segment-btn",onClick:W,disabled:s.length<2,children:"이전 NPC"}),i.jsx("span",{children:z?`${B+1} / ${s.length}`:`0 / ${s.length}`}),i.jsx("button",{className:"building-panel__segment-btn",onClick:D,disabled:s.length<2,children:"다음 NPC"})]}),F=i.jsxs("div",{className:"building-panel__npc-head",children:[i.jsxs("div",{className:"building-panel__npc-head-block",children:[i.jsx("div",{className:"building-panel__section-subtitle",children:"템플릿"}),i.jsx("div",{className:"building-panel__npc-chip-list",children:t.map(q=>i.jsx("button",{className:`building-panel__grid-btn ${n===q.id?"building-panel__grid-btn--active":""}`,onClick:()=>o(q.id),children:q.name},q.id))})]}),i.jsxs("div",{className:"building-panel__npc-head-block",children:[i.jsx("div",{className:"building-panel__section-subtitle",children:"NPC 선택"}),i.jsx("div",{className:"building-panel__npc-chip-list",children:s.map(q=>i.jsx("button",{className:`building-panel__grid-btn ${r===q.id?"building-panel__grid-btn--active":""}`,onClick:()=>a(q.id),children:q.name},q.id))})]})]}),U=l?i.jsxs("div",{className:"building-panel__npc-modal-controls",children:[i.jsxs("div",{className:"building-panel__brain-tabs",children:[i.jsx("button",{type:"button",className:`building-panel__brain-tab ${y==="movement"?"building-panel__brain-tab--active":""}`,onClick:()=>w("movement"),children:"이동"}),i.jsx("button",{type:"button",className:`building-panel__brain-tab ${y==="animation"?"building-panel__brain-tab--active":""}`,onClick:()=>w("animation"),children:"애니메이션"}),i.jsx("button",{type:"button",className:`building-panel__brain-tab ${y==="perception"?"building-panel__brain-tab--active":""}`,onClick:()=>w("perception"),children:"지각"})]}),E]}):null,V=l?i.jsxs("div",{className:"building-panel__npc-card",children:[i.jsx("div",{className:"building-panel__section-title",children:"미니 프리뷰 캔버스"}),i.jsxs("div",{className:"building-panel__asset-targets",children:[i.jsxs("span",{children:["노드 프리뷰: ",j.label]}),j.animationId&&i.jsxs("span",{children:["애니메이션: ",j.animationId]})]}),i.jsx("div",{className:"building-panel__npc-avatar-canvas",children:i.jsx(Nv,{state:j,instance:l})})]}):null,Y=l?i.jsx(lv,{instance:l,blueprints:f,selectedBlueprint:u,updateBrain:S,addBrainBlueprint:x,updateBrainBlueprint:_,onPreviewStateChange:N}):null,Z=i.jsxs(i.Fragment,{children:[t.length===0&&i.jsx("div",{className:"building-panel__empty",children:"사용 가능한 NPC 템플릿이 없습니다."}),s.length===0&&i.jsx("div",{className:"building-panel__empty",children:"월드에 NPC를 배치하면 상세 편집이 열립니다."})]});return e==="split"?i.jsxs("div",{className:"building-panel__section building-panel__npc-shell building-panel__npc-shell--split",children:[i.jsxs("div",{className:"building-panel__npc-pane building-panel__npc-pane--left",children:[i.jsx("div",{className:"building-panel__section-title",children:"선택"}),L,M,F,Z]}),i.jsxs("div",{className:"building-panel__npc-board",children:[i.jsxs("div",{className:"building-panel__npc-pane building-panel__npc-pane--movement",children:[i.jsx("div",{className:"building-panel__section-title",children:"이동"}),T]}),i.jsxs("div",{className:"building-panel__npc-pane building-panel__npc-pane--animation",children:[i.jsx("div",{className:"building-panel__section-title",children:"애니메이션"}),O]}),i.jsxs("div",{className:"building-panel__npc-pane building-panel__npc-pane--perception",children:[i.jsx("div",{className:"building-panel__section-title",children:"지각"}),P]})]}),i.jsxs("div",{className:"building-panel__npc-pane building-panel__npc-pane--right",children:[i.jsx("div",{className:"building-panel__section-title",children:"두뇌/프리뷰"}),V,Y]})]}):e==="sidebars"?i.jsxs("div",{className:"building-panel__section building-panel__npc-shell building-panel__npc-shell--sidebars",children:[i.jsxs("aside",{className:"building-panel__npc-side building-panel__npc-side--left",children:[i.jsx("div",{className:"building-panel__section-title",children:"NPC 선택"}),L,M,F,i.jsxs("div",{className:"building-panel__npc-board",children:[i.jsxs("div",{className:"building-panel__npc-pane building-panel__npc-pane--movement",children:[i.jsx("div",{className:"building-panel__section-title",children:"이동"}),T]}),i.jsxs("div",{className:"building-panel__npc-pane building-panel__npc-pane--animation",children:[i.jsx("div",{className:"building-panel__section-title",children:"애니메이션"}),O]}),i.jsxs("div",{className:"building-panel__npc-pane building-panel__npc-pane--perception",children:[i.jsx("div",{className:"building-panel__section-title",children:"지각"}),P]})]}),Z]}),i.jsx("aside",{className:"building-panel__npc-side building-panel__npc-side--right",children:i.jsxs("div",{className:"building-panel__npc-pane building-panel__npc-pane--brain",children:[i.jsx("div",{className:"building-panel__section-title",children:"두뇌/프리뷰"}),V,Y]})})]}):i.jsxs("div",{className:"building-panel__section building-panel__npc-shell building-panel__npc-shell--modal",children:[i.jsx("div",{className:"building-panel__section-title",children:"NPC 에디터"}),L,M,F,l&&i.jsxs("div",{className:"building-panel__npc-workspace building-panel__npc-workspace--modal",children:[i.jsx("div",{className:"building-panel__npc-column building-panel__npc-column--controls",children:U}),i.jsxs("div",{className:"building-panel__npc-column building-panel__npc-column--brain",children:[V,Y]})]}),Z]})}const oc=.25;function sc(e,t){const n=(e[0]-t[0])*oc,o=(e[2]-t[2])*oc;return[Math.max(-2.8,Math.min(2.8,n)),Math.max(-2.8,Math.min(2.8,o))]}function Nv({state:e,instance:t}){const n=t.position,o=m.useMemo(()=>{const r=t.templateId?.trim();return r||"ally"},[t.templateId]),s=m.useMemo(()=>{const r=`preview-${n.join("-")}`,a=e.waypoints&&e.waypoints.length>0?e.waypoints:[[n[0]+2,n[1],n[2]],[n[0],n[1],n[2]+2],[n[0]-2,n[1],n[2]],[n[0],n[1],n[2]-2]],l=e.mode==="move"&&e.target?{waypoints:[e.target],currentIndex:0,speed:1.7,state:"moving"}:e.mode==="patrol"?{waypoints:a,currentIndex:0,speed:1.6,state:"moving"}:e.mode==="wander"?{waypoints:a,currentIndex:0,speed:1.3,state:"moving"}:void 0;return{id:r,templateId:o,name:`${t.name}-preview`,position:[0,0,0],rotation:[0,0,0],scale:t.scale??[1,1,1],currentAnimation:e.animationId??t.currentAnimation??"idle",...t.currentClothingSetId?{currentClothingSetId:t.currentClothingSetId}:{},...t.customParts?{customParts:t.customParts}:{},...t.metadata?{metadata:t.metadata}:{},brain:{mode:"none"},behavior:{mode:e.mode==="patrol"?"patrol":e.mode==="wander"?"wander":"idle",speed:1.6},...l?{navigation:l}:{}}},[t,n,e.animationId,e.mode,e.target,e.waypoints,o]);return i.jsxs(be.Canvas,{camera:{position:[0,6.2,11.5],fov:34,near:.1,far:120},children:[i.jsx("ambientLight",{intensity:.72}),i.jsx("directionalLight",{position:[5,8,4],intensity:1}),i.jsx("gridHelper",{args:[8,16,"#3b82f6","#1e293b"]}),i.jsxs("mesh",{rotation:[-Math.PI/2,0,0],position:[0,-.01,0],receiveShadow:!0,children:[i.jsx("circleGeometry",{args:[3.2,48]}),i.jsx("meshStandardMaterial",{color:"#0f172a"})]}),i.jsx(ct.Physics,{gravity:[0,0,0],children:i.jsx(ka,{instance:s,isEditMode:!1})}),i.jsx(Tv,{state:e,origin:n})]})}function Tv({state:e,origin:t}){const n=e.target?sc(e.target,t):null;return i.jsxs("group",{children:[n&&i.jsxs("mesh",{position:[n[0],.12,n[1]],children:[i.jsx("sphereGeometry",{args:[.08,12,12]}),i.jsx("meshStandardMaterial",{color:"#38bdf8"})]}),(e.waypoints??[]).map((o,s)=>{const r=sc(o,t);return i.jsxs("mesh",{position:[r[0],.1,r[1]],children:[i.jsx("sphereGeometry",{args:[.06,10,10]}),i.jsx("meshStandardMaterial",{color:"#34d399"})]},`${o.join("-")}-${s}`)}),e.mode==="wander"&&i.jsxs("mesh",{rotation:[-Math.PI/2,0,0],position:[0,.03,0],children:[i.jsx("ringGeometry",{args:[Math.max(.35,(e.radius??4)*.16),Math.max(.45,(e.radius??4)*.16+.07),48]}),i.jsx("meshStandardMaterial",{color:"#f59e0b",transparent:!0,opacity:.55})]})]})}function Iv(){const e=R.useBuildingStore($=>$.editMode),t=R.useBuildingStore($=>$.setEditMode),n=R.useBuildingStore($=>$.selectedWallId),o=R.useBuildingStore($=>$.selectedTileId),s=R.useBuildingStore($=>$.selectedBlockId),r=R.useBuildingStore($=>$.selectedWallGroupId),a=R.useBuildingStore($=>$.hoverPosition),l=R.useBuildingStore($=>$.currentTileMultiplier),c=R.useBuildingStore($=>$.setTileMultiplier),u=R.useBuildingStore($=>$.currentTileHeight),f=R.useBuildingStore($=>$.setTileHeight),d=R.useBuildingStore($=>$.currentTileShape),p=R.useBuildingStore($=>$.setTileShape),h=R.useBuildingStore($=>$.currentTileRotation),v=R.useBuildingStore($=>$.setTileRotation),b=R.useBuildingStore($=>$.currentTileMaterialId),S=R.useBuildingStore($=>$.setCurrentTileMaterialId),x=R.useBuildingStore($=>$.currentCustomTileName),_=R.useBuildingStore($=>$.currentCustomTileColor),g=R.useBuildingStore($=>$.currentCustomTileTextureUrl),y=R.useBuildingStore($=>$.setCustomTileDraft),w=R.useBuildingStore($=>$.applyTilePreset),j=R.useBuildingStore($=>$.applyCustomTile),N=R.useBuildingStore($=>$.currentWallRotation),B=R.useBuildingStore($=>$.setWallRotation),z=R.useBuildingStore($=>$.currentWallKind),W=R.useBuildingStore($=>$.setWallKind),D=R.useBuildingStore($=>$.applyWallPreset),E=R.useBuildingStore($=>$.selectedTileObjectType),G=R.useBuildingStore($=>$.setSelectedTileObjectType),T=R.useBuildingStore($=>$.currentTerrainColor),O=R.useBuildingStore($=>$.currentTerrainAccentColor),P=R.useBuildingStore($=>$.setTerrainColors),L=R.useBuildingStore($=>$.selectedPlacedObjectType),M=R.useBuildingStore($=>$.setSelectedPlacedObjectType),F=R.useBuildingStore($=>$.selectedModelObjectId),U=R.useBuildingStore($=>$.setSelectedModelObjectId),V=R.useBuildingStore($=>$.currentModelUrl),Y=R.useBuildingStore($=>$.setModelUrl),Z=R.useBuildingStore($=>$.currentModelScale),q=R.useBuildingStore($=>$.setModelScale),X=R.useBuildingStore($=>$.currentModelColor),A=R.useBuildingStore($=>$.setModelColor),C=R.useBuildingStore($=>$.snapToGrid),H=R.useBuildingStore($=>$.setSnapToGrid),K=R.useBuildingStore($=>$.currentFlagWidth),Q=R.useBuildingStore($=>$.currentFlagHeight),ee=R.useBuildingStore($=>$.currentFlagImageUrl),ne=R.useBuildingStore($=>$.setFlagWidth),ie=R.useBuildingStore($=>$.setFlagHeight),re=R.useBuildingStore($=>$.setFlagImageUrl),J=R.useBuildingStore($=>$.currentFlagStyle),ce=R.useBuildingStore($=>$.setFlagStyle),de=R.useBuildingStore($=>$.currentFireIntensity),me=R.useBuildingStore($=>$.currentFireWidth),xe=R.useBuildingStore($=>$.currentFireHeight),je=R.useBuildingStore($=>$.currentFireColor),ve=R.useBuildingStore($=>$.setFireIntensity),Me=R.useBuildingStore($=>$.setFireWidth),Pe=R.useBuildingStore($=>$.setFireHeight),mt=R.useBuildingStore($=>$.setFireColor),Qe=R.useBuildingStore($=>$.currentObjectRotation),Ge=R.useBuildingStore($=>$.setObjectRotation),Je=R.useBuildingStore($=>$.selectedTileGroupId),Vt=R.useBuildingStore($=>$.tileGroups),_n=R.useBuildingStore($=>$.wallGroups),Bt=R.useBuildingStore($=>$.meshes),jn=R.useBuildingStore($=>$.addMesh),Mn=R.useBuildingStore($=>$.updateMesh),Cn=R.useBuildingStore($=>$.updateWall),Nn=R.useBuildingStore($=>$.updateTile),Tn=R.useBuildingStore($=>$.setCurrentWallMaterialId),In=R.useBuildingStore($=>$.removeWall),gt=R.useBuildingStore($=>$.removeTile),et=R.useBuildingStore($=>$.removeBlock),bt=R.useBuildingStore($=>$.currentBillboardText),Ze=R.useBuildingStore($=>$.currentBillboardImageUrl),Pt=R.useBuildingStore($=>$.currentBillboardColor),Yt=R.useBuildingStore($=>$.currentBillboardWidth),Rt=R.useBuildingStore($=>$.currentBillboardHeight),xt=R.useBuildingStore($=>$.currentBillboardScale),En=R.useBuildingStore($=>$.currentBillboardOffsetY),An=R.useBuildingStore($=>$.currentBillboardElevation),kn=R.useBuildingStore($=>$.currentBillboardIntensity),Bn=R.useBuildingStore($=>$.setBillboardText),Zt=R.useBuildingStore($=>$.setBillboardImageUrl),Xt=R.useBuildingStore($=>$.setBillboardColor),Pn=R.useBuildingStore($=>$.setBillboardWidth),Rn=R.useBuildingStore($=>$.setBillboardHeight),Dn=R.useBuildingStore($=>$.setBillboardScale),Fn=R.useBuildingStore($=>$.setBillboardOffsetY),Kt=R.useBuildingStore($=>$.setBillboardElevation),qt=R.useBuildingStore($=>$.setBillboardIntensity),Qt=R.useBuildingStore($=>$.currentObjectPrimaryColor),Jt=R.useBuildingStore($=>$.currentObjectSecondaryColor),Ln=R.useBuildingStore($=>$.currentTreeKind),zn=R.useBuildingStore($=>$.setObjectPrimaryColor),en=R.useBuildingStore($=>$.setObjectSecondaryColor),tn=R.useBuildingStore($=>$.setTreeKind),yt=R.useBuildingStore($=>$.showSnow),On=R.useBuildingStore($=>$.setShowSnow),Dt=R.useBuildingStore($=>$.showFog),$n=R.useBuildingStore($=>$.setShowFog),Gn=R.useBuildingStore($=>$.fogColor),Hn=R.useBuildingStore($=>$.setFogColor),Wn=R.useBuildingStore($=>$.weatherEffect),nn=R.useBuildingStore($=>$.setWeatherEffect),on=se.useNPCStore($=>$.templates),vt=se.useNPCStore($=>$.instances),tt=se.useNPCStore($=>$.animations),Xe=se.useNPCStore($=>$.brainBlueprints),Un=se.useNPCStore($=>$.selectedTemplateId),sn=se.useNPCStore($=>$.selectedInstanceId),Vn=se.useNPCStore($=>$.setSelectedTemplate),nt=se.useNPCStore($=>$.setSelectedInstance),Yn=se.useNPCStore($=>$.updateInstance),Ke=se.useNPCStore($=>$.setNavigation),wt=se.useNPCStore($=>$.clearNavigation),ze=se.useNPCStore($=>$.updateInstanceBehavior),qe=se.useNPCStore($=>$.updateInstanceBrain),Ae=se.useNPCStore($=>$.updateInstancePerception),St=se.useNPCStore($=>$.addBrainBlueprint),Zn=se.useNPCStore($=>$.updateBrainBlueprint),rn=se.useNPCStore($=>$.initializeDefaults),an=bn.useAssetStore($=>$.ids),Ft=bn.useAssetStore($=>$.records),Xn=m.useMemo(()=>an.map($=>Ft[$]).filter($=>!!$).filter(Hp),[an,Ft]),ln=m.useMemo(()=>Array.from(on.values()),[on]),_t=m.useMemo(()=>Array.from(vt.values()),[vt]),Lt=m.useMemo(()=>Array.from(tt.values()),[tt]),it=m.useMemo(()=>Array.from(Xe.values()),[Xe]);return{editMode:e,setEditMode:t,selectedWallId:n,selectedTileId:o,selectedBlockId:s,selectedWallGroupId:r,hoverPosition:a,currentTileMultiplier:l,setTileMultiplier:c,currentTileHeight:u,setTileHeight:f,currentTileShape:d,setTileShape:p,currentTileRotation:h,setTileRotation:v,currentTileMaterialId:b,setCurrentTileMaterialId:S,currentCustomTileName:x,currentCustomTileColor:_,currentCustomTileTextureUrl:g,setCustomTileDraft:y,applyTilePreset:w,applyCustomTile:j,currentWallRotation:N,setWallRotation:B,currentWallKind:z,setWallKind:W,applyWallPreset:D,selectedTileObjectType:E,setSelectedTileObjectType:G,currentTerrainColor:T,currentTerrainAccentColor:O,setTerrainColors:P,selectedPlacedObjectType:L,setSelectedPlacedObjectType:M,selectedModelObjectId:F,setSelectedModelObjectId:U,currentModelUrl:V,setModelUrl:Y,currentModelScale:Z,setModelScale:q,currentModelColor:X,setModelColor:A,snapToGrid:C,setSnapToGrid:H,currentFlagWidth:K,currentFlagHeight:Q,currentFlagImageUrl:ee,setFlagWidth:ne,setFlagHeight:ie,setFlagImageUrl:re,currentFlagStyle:J,setFlagStyle:ce,currentFireIntensity:de,currentFireWidth:me,currentFireHeight:xe,currentFireColor:je,setFireIntensity:ve,setFireWidth:Me,setFireHeight:Pe,setFireColor:mt,currentObjectRotation:Qe,setObjectRotation:Ge,selectedTileGroupId:Je,tileGroups:Vt,wallGroups:_n,meshes:Bt,addMesh:jn,updateMesh:Mn,updateWall:Cn,updateTile:Nn,setCurrentWallMaterialId:Tn,removeWall:In,removeTile:gt,removeBlock:et,currentBillboardText:bt,currentBillboardImageUrl:Ze,currentBillboardColor:Pt,currentBillboardWidth:Yt,currentBillboardHeight:Rt,currentBillboardScale:xt,currentBillboardOffsetY:En,currentBillboardElevation:An,currentBillboardIntensity:kn,setBillboardText:Bn,setBillboardImageUrl:Zt,setBillboardColor:Xt,setBillboardWidth:Pn,setBillboardHeight:Rn,setBillboardScale:Dn,setBillboardOffsetY:Fn,setBillboardElevation:Kt,setBillboardIntensity:qt,currentObjectPrimaryColor:Qt,currentObjectSecondaryColor:Jt,currentTreeKind:Ln,setObjectPrimaryColor:zn,setObjectSecondaryColor:en,setTreeKind:tn,showSnow:yt,setShowSnow:On,showFog:Dt,setShowFog:$n,fogColor:Gn,setFogColor:Hn,weatherEffect:Wn,setWeatherEffect:nn,npcInstances:vt,npcBrainBlueprints:Xe,selectedNPCTemplateId:Un,selectedNPCInstanceId:sn,setSelectedNPCTemplate:Vn,setSelectedNPCInstance:nt,updateNPCInstance:Yn,setNPCNavigation:Ke,clearNPCNavigation:wt,updateNPCBehavior:ze,updateNPCBrain:qe,updateNPCPerception:Ae,addNPCBrainBlueprint:St,updateNPCBrainBlueprint:Zn,initializeNPCDefaults:rn,buildingAssets:Xn,npcTemplatesArray:ln,npcInstancesArray:_t,npcAnimationsArray:Lt,npcBrainBlueprintsArray:it}}const ai=({className:e="",style:t,children:n,slots:o={},actions:s=[],disabledSections:r=[],forcedEditMode:a,npcLayout:l="default",hideHeader:c=!1})=>{const u=m.useMemo(()=>new Set(r),[r]),{editMode:f,setEditMode:d,selectedWallId:p,selectedTileId:h,selectedBlockId:v,selectedWallGroupId:b,hoverPosition:S,currentTileMultiplier:x,setTileMultiplier:_,currentTileHeight:g,setTileHeight:y,currentTileShape:w,setTileShape:j,currentTileRotation:N,setTileRotation:B,currentTileMaterialId:z,setCurrentTileMaterialId:W,currentCustomTileName:D,currentCustomTileColor:E,currentCustomTileTextureUrl:G,setCustomTileDraft:T,applyTilePreset:O,applyCustomTile:P,currentWallRotation:L,setWallRotation:M,currentWallKind:F,setWallKind:U,applyWallPreset:V,selectedTileObjectType:Y,setSelectedTileObjectType:Z,currentTerrainColor:q,currentTerrainAccentColor:X,setTerrainColors:A,selectedPlacedObjectType:C,setSelectedPlacedObjectType:H,selectedModelObjectId:K,setSelectedModelObjectId:Q,currentModelUrl:ee,setModelUrl:ne,currentModelScale:ie,setModelScale:re,currentModelColor:J,setModelColor:ce,snapToGrid:de,setSnapToGrid:me,currentFlagWidth:xe,currentFlagHeight:je,currentFlagImageUrl:ve,setFlagWidth:Me,setFlagHeight:Pe,setFlagImageUrl:mt,currentFlagStyle:Qe,setFlagStyle:Ge,currentFireIntensity:Je,currentFireWidth:Vt,currentFireHeight:_n,currentFireColor:Bt,setFireIntensity:jn,setFireWidth:Mn,setFireHeight:Cn,setFireColor:Nn,currentObjectRotation:Tn,setObjectRotation:In,selectedTileGroupId:gt,tileGroups:et,wallGroups:bt,meshes:Ze,addMesh:Pt,updateMesh:Yt,updateWall:Rt,updateTile:xt,setCurrentWallMaterialId:En,removeWall:An,removeTile:kn,removeBlock:Bn,currentBillboardText:Zt,currentBillboardImageUrl:Xt,currentBillboardColor:Pn,currentBillboardWidth:Rn,currentBillboardHeight:Dn,currentBillboardScale:Fn,currentBillboardOffsetY:Kt,currentBillboardElevation:qt,currentBillboardIntensity:Qt,setBillboardText:Jt,setBillboardImageUrl:Ln,setBillboardColor:zn,setBillboardWidth:en,setBillboardHeight:tn,setBillboardScale:yt,setBillboardOffsetY:On,setBillboardElevation:Dt,setBillboardIntensity:$n,currentObjectPrimaryColor:Gn,currentObjectSecondaryColor:Hn,currentTreeKind:Wn,setObjectPrimaryColor:nn,setObjectSecondaryColor:on,setTreeKind:vt,showSnow:tt,setShowSnow:Xe,showFog:Un,setShowFog:sn,fogColor:Vn,setFogColor:nt,weatherEffect:Yn,setWeatherEffect:Ke,npcInstances:wt,npcBrainBlueprints:ze,selectedNPCTemplateId:qe,selectedNPCInstanceId:Ae,setSelectedNPCTemplate:St,setSelectedNPCInstance:Zn,updateNPCInstance:rn,setNPCNavigation:an,clearNPCNavigation:Ft,updateNPCBehavior:Xn,updateNPCBrain:ln,updateNPCPerception:_t,addNPCBrainBlueprint:Lt,updateNPCBrainBlueprint:it,initializeNPCDefaults:$,buildingAssets:Kn,npcTemplatesArray:Mo,npcInstancesArray:qs,npcAnimationsArray:Co,npcBrainBlueprintsArray:I}=Iv(),oe=[{type:"none",label:"없음",description:"건축 편집을 끕니다"},{type:"world",label:"전역",description:"전역 설정을 배치합니다"},{type:"wall",label:"벽",description:"벽 조각을 배치합니다"},{type:"tile",label:"타일",description:"바닥 타일을 배치합니다"},{type:"block",label:"박스",description:"복셀 박스를 쌓습니다"},{type:"object",label:"오브젝트",description:"타일 위에 장식을 배치합니다"},{type:"npc",label:"NPC",description:"NPC를 배치합니다"}],Ne=[{value:0,label:"0도"},{value:Math.PI/2,label:"90도"},{value:Math.PI,label:"180도"},{value:Math.PI*1.5,label:"270도"}],Fe=m.useMemo(()=>{const te=new Map;for(const ye of bt.values())for(const Ce of ye.walls)te.set(Ce.id,ye.id);return te},[bt]),No=m.useMemo(()=>{const te=new Map;for(const ye of et.values())for(const Ce of ye.tiles)te.set(Ce.id,ye.id);return te},[et]),Le=p?bt.get(Fe.get(p)??""):bt.get(b??""),Te=h?et.get(No.get(h)??""):et.get(gt??""),Qs=h?Te?.tiles.find(te=>te.id===h):void 0,Js=p?Le?.walls.find(te=>te.id===p):void 0,cn=a??f,dp=oe.find(te=>te.type===cn)?.label??cn,fp=R.BUILDING_WALL_KIND_OPTIONS.find(te=>te.type===(Js?.wallKind??F))?.labelKo??F,Pi=Ts(K)??vi[0],er=Ae?wt.get(Ae):void 0,pp=er?.brain?.blueprintId?ze.get(er.brain.blueprintId):void 0,li=cn==="wall",hp=cn==="world",ot=cn==="tile",Za=cn==="block",un=cn==="object",mp=cn==="npc";m.useEffect(()=>{$()},[$]),m.useEffect(()=>{a&&f!==a&&d(a)},[f,a,d]);const gp=()=>{!p||!Le||An(Le.id,p)},bp=()=>{!p||!Le||Rt(Le.id,p,{flipSides:!Js?.flipSides})},xp=()=>{!h||!Te||kn(Te.id,h)},yp=()=>{v&&Bn(v)},To=(te,ye,Ce,jt)=>{const Mt=mi.createScopedBuildingMeshId(ye,Ce,jt.id),ci=te?Ze.get(te):void 0,Ri=mi.createScopedAssetMeshConfig(Mt,jt,ci);return Ze.has(Mt)?Yt(Mt,Ri):Pt(Ri),Mt},vp=te=>{if(!Le)return;const Ce=(p?Le.walls.find(Mt=>Mt.id===p):void 0)?.materialId??Le.frontMeshId;if(p){const Mt=To(Ce,p,"wall",te);Rt(Le.id,p,{materialId:Mt});return}const jt=To(Le.frontMeshId,or("placement-wall"),"wall",te);En(jt)},wp=te=>{if(!Te)return;if(h){const Ce=To(Qs?.materialId??Te.floorMeshId,h,"tile",te);xt(Te.id,h,{materialId:Ce});return}const ye=To(Te.floorMeshId,or("placement-tile"),"tile",te);W(ye)},Sp=te=>{if(!Te)return;if(h){const Mt=Qs?.materialId??Te.floorMeshId,ci=mi.createScopedBuildingMeshId(h,"tile-color",te),Ri=Ja(ci,te,Ze.get(Mt));Ze.has(ci)?Yt(ci,Ri):Pt(Ri),xt(Te.id,h,{materialId:ci});return}const ye=z??Te.floorMeshId,Ce=mi.createScopedBuildingMeshId(or("placement-tile-color"),"tile",te),jt=Ja(Ce,te,Ze.get(ye));Pt(jt),W(Ce)},Xa=(te,ye=X)=>{if(A(te,ye),!h||!Te)return;const Ce=Te.tiles.find(jt=>jt.id===h);!Ce||!Ce.objectType||Ce.objectType==="none"||Ce.objectType==="water"||xt(Te.id,h,{objectConfig:{...Ce.objectConfig??{},terrainColor:te,terrainAccentColor:ye}})};return i.jsxs("div",{className:`building-panel ${e}`,style:t,children:[!c&&i.jsxs("div",{className:"building-panel__header",children:[i.jsxs("div",{children:[i.jsx("div",{className:"building-panel__eyebrow",children:"Mode"}),i.jsxs("div",{className:"building-panel__title",children:[dp," 인스펙터"]})]}),!a&&i.jsx("div",{className:"building-panel__mode-tabs",children:oe.map(te=>i.jsx("button",{className:`building-panel__mode-tab ${f===te.type?"building-panel__mode-tab--active":""}`,onClick:()=>d(te.type),title:te.description,children:te.label},te.type))})]}),o.header,i.jsxs("div",{className:"building-panel__inspector",children:[o.beforeInspector,i.jsx(Ky,{actions:s}),hp&&!u.has("environment")&&i.jsx(qy,{showSnow:tt,setShowSnow:Xe,showFog:Un,setShowFog:sn,fogColor:Vn,setFogColor:nt,weatherEffect:Yn,setWeatherEffect:Ke}),li&&!u.has("wallPresets")&&i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"벽 프리셋"}),i.jsx("div",{className:"building-panel__grid",children:R.BUILDING_WALL_PRESETS.map(te=>{const ye=`${te.id}-walls`;return i.jsx("button",{className:`building-panel__grid-btn ${b===ye?"building-panel__grid-btn--active":""}`,onClick:()=>V(te.id),title:te.labelEn,children:te.labelKo},te.id)})})]}),li&&!u.has("wallModules")&&i.jsx(nv,{currentWallKind:Js?.wallKind??F,currentWallKindLabel:fp,setWallKind:U,currentWallRotation:L,setWallRotation:M,rotations:Ne,selectedWallId:p,hasSelectedWallGroup:!!Le,onFlipSelectedWall:bp,onDeleteSelectedWall:gp}),li&&o.afterWallSettings,(li||ot)&&!u.has("assetMaterials")&&i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"에셋 재질"}),i.jsxs("div",{className:"building-panel__asset-targets",children:[li&&i.jsxs("span",{children:["벽: ",Le?.name??"선택 없음"]}),ot&&i.jsxs("span",{children:["타일: ",h?`선택 타일 ${h}`:"다음 생성 타일"]}),ot&&i.jsxs("span",{children:["현재 생성 재질: ",z??Te?.floorMeshId??"기본값"]})]}),i.jsxs("div",{className:"building-panel__asset-list",children:[Kn.map(te=>i.jsxs("div",{className:"building-panel__asset-card",children:[i.jsx(mi.AssetPreviewCanvas,{asset:te,size:54}),i.jsxs("div",{className:"building-panel__asset-info",children:[i.jsx("strong",{children:te.name}),i.jsx("span",{children:te.kind})]}),i.jsxs("div",{className:"building-panel__asset-actions",children:[li&&i.jsx("button",{className:"building-panel__asset-action",disabled:!Le,onClick:()=>vp(te),children:"벽"}),ot&&i.jsx("button",{className:"building-panel__asset-action",disabled:!Te,onClick:()=>wp(te),children:"타일"})]})]},te.id)),Kn.length===0&&i.jsx("div",{className:"building-panel__empty",children:"사용 가능한 빌딩 에셋이 없습니다."})]})]}),ot&&!u.has("tilePresets")&&i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"타일 프리셋"}),i.jsx("div",{className:"building-panel__grid",children:R.BUILDING_TILE_PRESETS.map(te=>{const ye=`${te.id}-floor`;return i.jsx("button",{className:`building-panel__grid-btn ${gt===ye?"building-panel__grid-btn--active":""}`,onClick:()=>O(te.id),title:te.labelEn,children:te.labelKo},te.id)})})]}),ot&&!u.has("customTile")&&i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"커스텀 타일 맵"}),i.jsxs("div",{className:"building-panel__info",children:[i.jsxs("label",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"이름"}),i.jsx("input",{type:"text",value:D,onChange:te=>T({name:te.target.value}),className:"building-panel__text-input"})]}),i.jsx(ue,{label:"기본색",children:i.jsx(no,{value:E,onChange:te=>T({color:te})})}),i.jsxs("label",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"텍스처 URL"}),i.jsx("input",{type:"text",value:G,onChange:te=>T({textureUrl:te.target.value}),placeholder:"textures/floor.png",className:"building-panel__text-input"})]}),i.jsx("button",{className:"building-panel__asset-action",onClick:P,children:"별도 타일 맵 생성/선택"})]})]}),ot&&!u.has("terrainCover")&&i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"지형 덮개"}),i.jsx("div",{className:"building-panel__grid",children:R.BUILDING_TILE_OBJECT_OPTIONS.map(te=>i.jsx("button",{className:`building-panel__grid-btn ${Y===te.type?"building-panel__grid-btn--active":""}`,onClick:()=>Z(te.type),children:te.labelKo},te.type))}),i.jsxs("div",{className:"building-panel__terrain-colors",children:[i.jsxs("label",{children:[i.jsx("span",{children:"기본색"}),i.jsx("input",{type:"color",value:q,onChange:te=>Xa(te.target.value)})]}),i.jsxs("label",{children:[i.jsx("span",{children:"강조색"}),i.jsx("input",{type:"color",value:X,onChange:te=>Xa(q,te.target.value)})]})]})]}),un&&!u.has("objectPresets")&&i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"배치 오브젝트"}),i.jsx("div",{className:"building-panel__grid",children:R.BUILDING_PLACED_OBJECT_OPTIONS.map(te=>i.jsx("button",{className:`building-panel__grid-btn ${C===te.type?"building-panel__grid-btn--active":""}`,onClick:()=>{H(te.type),te.type==="model"&&Pi&&(re(Pi.defaultScale),ce(Pi.defaultColor),ne(Pi.modelUrl??""))},children:te.labelKo},te.type))})]}),un&&C==="model"&&!u.has("modelSettings")&&i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"기본 기물 GLB"}),i.jsx("div",{className:"building-panel__grid",children:vi.map(te=>i.jsx("button",{className:`building-panel__grid-btn ${K===te.id?"building-panel__grid-btn--active":""}`,onClick:()=>{Q(te.id),re(te.defaultScale),ce(te.defaultColor),ne(te.modelUrl??"")},children:te.label},te.id))}),i.jsxs("div",{className:"building-panel__info",children:[i.jsxs("label",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"GLB URL"}),i.jsx("input",{type:"text",value:ee,onChange:te=>ne(te.target.value),placeholder:"gltf/props/door.glb",className:"building-panel__text-input"})]}),i.jsxs("label",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"스케일"}),i.jsx("input",{type:"number",min:"0.1",max:"10",step:"0.1",value:ie,onChange:te=>re(Number(te.target.value)||1),className:"building-panel__number-input"})]}),i.jsxs("label",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"색상"}),i.jsx("input",{type:"color",value:J,onChange:te=>ce(te.target.value),style:{width:"36px",height:"24px",border:"none",cursor:"pointer",background:"none"}}),i.jsx("span",{className:"building-panel__info-value",style:{fontSize:"10px"},children:J})]}),i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"Fallback"}),i.jsx("span",{className:"building-panel__info-value",children:Pi?.fallbackKind??"generic"})]})]})]}),(ot||Za)&&!u.has("placement")&&i.jsx(ev,{isTileMode:ot,currentTileMultiplier:x,setTileMultiplier:_,currentTileHeight:g,setTileHeight:y,snapToGrid:de,setSnapToGrid:me,currentTileShape:w,setTileShape:j,currentTileRotation:N,setTileRotation:B,rotations:Ne,selectedTileId:h,hasSelectedTileGroup:!!Te,onDeleteSelectedTile:xp}),Za&&i.jsx(tv,{currentTileMultiplier:x,currentTileHeight:g,selectedBlockId:v,onDeleteSelectedBlock:yp}),ot&&o.afterTileSettings,ot&>&&!u.has("tileColor")&&(()=>{const te=et.get(gt),ye=Qs?.materialId??z??te?.floorMeshId,Ce=ye?Ze.get(ye):void 0;return Ce?i.jsxs("div",{className:"building-panel__section",children:[i.jsx("div",{className:"building-panel__section-title",children:"타일 색상"}),i.jsx("div",{className:"building-panel__info",children:i.jsxs("div",{className:"building-panel__info-item",children:[i.jsx("span",{className:"building-panel__info-label",children:"색상"}),i.jsx("input",{type:"color",value:Ce.color||"#888888",onChange:jt=>Sp(jt.target.value),style:{width:"36px",height:"24px",border:"none",cursor:"pointer",background:"none"}}),i.jsx("span",{className:"building-panel__info-value",style:{fontSize:"10px"},children:Ce.color||"#888888"})]})})]}):null})(),mp&&i.jsx(Cv,{layout:l,npcTemplatesArray:Mo,selectedNPCTemplateId:qe,setSelectedNPCTemplate:St,npcInstancesArray:qs,selectedNPCInstanceId:Ae??null,setSelectedNPCInstance:Zn,selectedNPCInstance:er,npcAnimationsArray:Co,selectedNPCBrainBlueprint:pp,npcBrainBlueprintsArray:I,hoverPosition:S,updateNPCBehavior:(te,ye)=>Xn(te,ye),setNPCNavigation:(te,ye)=>{!ye.waypoints||ye.waypoints.length===0||an(te,ye.waypoints,ye.speed)},clearNPCNavigation:Ft,updateNPCInstance:rn,updateNPCBrain:ln,addNPCBrainBlueprint:Lt,updateNPCBrainBlueprint:it,updateNPCPerception:_t}),un&&C!=="none"&&!u.has("objectRotation")&&i.jsx(Jy,{currentObjectRotation:Tn,setObjectRotation:In}),un&&(C==="tree"||C==="sakura")&&!u.has("treeSettings")&&i.jsx(cv,{currentTreeKind:Wn,setTreeKind:vt,currentObjectPrimaryColor:Gn,setObjectPrimaryColor:nn,currentObjectSecondaryColor:Hn,setObjectSecondaryColor:on}),un&&C==="fire"&&!u.has("fireSettings")&&i.jsx(uv,{currentFireIntensity:Je,setFireIntensity:jn,currentFireWidth:Vt,setFireWidth:Mn,currentFireHeight:_n,setFireHeight:Cn,currentFireColor:Bt,setFireColor:Nn}),un&&C==="billboard"&&!u.has("billboardSettings")&&i.jsx(fv,{currentBillboardScale:Fn,setBillboardScale:yt,currentBillboardOffsetY:Kt,setBillboardOffsetY:On,currentBillboardWidth:Rn,setBillboardWidth:en,currentBillboardHeight:Dn,setBillboardHeight:tn,currentBillboardElevation:qt,setBillboardElevation:Dt,currentBillboardIntensity:Qt,setBillboardIntensity:$n,currentBillboardText:Zt,setBillboardText:Jt,currentBillboardImageUrl:Xt,setBillboardImageUrl:Ln,currentBillboardColor:Pn,setBillboardColor:zn}),un&&C==="flag"&&!u.has("flagSettings")&&i.jsx(pv,{currentFlagStyle:Qe,setFlagStyle:Ge,currentFlagWidth:xe,setFlagWidth:Me,currentFlagHeight:je,setFlagHeight:Pe,currentFlagImageUrl:ve,setFlagImageUrl:mt}),un&&o.afterObjectSettings,n]})]})};function Ev(e={}){return i.jsx(ai,{...e,forcedEditMode:"world"})}function Av(e={}){return i.jsx(ai,{...e,forcedEditMode:"wall"})}function kv(e={}){return i.jsx(ai,{...e,forcedEditMode:"tile"})}function Bv(e={}){return i.jsx(ai,{...e,forcedEditMode:"block"})}function Pv(e={}){return i.jsx(ai,{...e,forcedEditMode:"object"})}function Rv(e={}){return i.jsx(ai,{...e,forcedEditMode:"npc"})}const di={name:"플레이어",colors:{body:"#ffd9b8",hair:"#3a2a1a",hat:"#5a8acf",top:"#f0e0c8",bottom:"#3a4a6a",shoes:"#3a2a1a"},face:"default",hair:"short"},Ad={hat:"모자",top:"상의",bottom:"하의",shoes:"신발",face:"표정",weapon:"무기",accessory:"액세서리"},Dv={short:"단발",long:"긴머리",cap:"모자머리",bun:"쪽머리",spiky:"뻗친머리"},Fv={default:"기본",smile:"미소",wink:"윙크",sleepy:"졸림",surprised:"놀람"},hr={hat:null,top:null,bottom:null,shoes:null,face:null,weapon:null,accessory:null},ss=Bi.create((e,t)=>({appearance:{...di,colors:{...di.colors}},outfits:{...hr},setName:n=>e(o=>({appearance:{...o.appearance,name:n.slice(0,16)||"플레이어"}})),setColor:(n,o)=>e(s=>({appearance:{...s.appearance,colors:{...s.appearance.colors,[n]:o}}})),setFace:n=>e(o=>({appearance:{...o.appearance,face:n}})),setHair:n=>e(o=>({appearance:{...o.appearance,hair:n}})),equipOutfit:(n,o)=>e(s=>({outfits:{...s.outfits,[n]:o}})),resetAppearance:()=>e({appearance:{...di,colors:{...di.colors}},outfits:{...hr}}),getEquippedAssetIds:()=>Object.values(t().outfits).filter(n=>typeof n=="string"&&n.length>0),serialize:()=>{const n=t();return{version:2,appearance:{...n.appearance,colors:{...n.appearance.colors}},outfits:{...n.outfits}}},hydrate:n=>{!n||n.version!==1&&n.version!==2||e({appearance:{...di,...n.appearance,colors:{...di.colors,...n.appearance.colors}},outfits:{...hr,...n.outfits}})}})),Lv=["hat","top","bottom","shoes","face","weapon","accessory"],zv=(e,t)=>t==="weapon"?e.kind==="weapon"||e.slot==="weapon":e.slot===t&&(e.kind==="characterPart"||e.kind==="weapon"),Ov=({className:e="",style:t,children:n})=>{const o=ss(x=>x.outfits),s=ss(x=>x.equipOutfit),r=ss(x=>x.resetAppearance),a=bn.useAssetStore(x=>x.ids),l=bn.useAssetStore(x=>x.records),c=bn.useAssetStore(x=>x.isLoading),u=bn.useAssetStore(x=>x.error),[f,d]=m.useState("top"),[p,h]=m.useState(""),[v,b]=m.useState(!1),S=m.useMemo(()=>{const x=p.trim().toLowerCase();return a.map(_=>l[_]).filter(_=>!!_).filter(_=>zv(_,f)).filter(_=>x?_.tags?.some(g=>g.toLowerCase().includes(x))??!1:!0).filter(_=>!v||_.metadata?.owned!==!1)},[a,l,v,f,p]);return i.jsxs("div",{className:`character-asset-panel ${e}`,style:t,children:[i.jsxs("section",{className:"character-asset-panel__section",children:[i.jsxs("div",{className:"character-asset-panel__header",children:[i.jsx("span",{className:"character-asset-panel__section-title",children:"캐릭터 에셋"}),i.jsx("button",{className:"character-asset-panel__ghost-btn",onClick:r,type:"button",children:"초기화"})]}),i.jsx("div",{className:"character-asset-panel__slot-grid",children:Lv.map(x=>i.jsxs("button",{type:"button",className:`character-asset-panel__slot-btn ${f===x?"character-asset-panel__slot-btn--active":""}`,onClick:()=>d(x),children:[i.jsx("span",{children:Ad[x]}),i.jsx("small",{children:o[x]??"비어있음"})]},x))})]}),i.jsxs("section",{className:"character-asset-panel__section",children:[i.jsxs("div",{className:"character-asset-panel__filters",children:[i.jsx("input",{value:p,onChange:x=>h(x.target.value),placeholder:"태그 검색",className:"character-asset-panel__input"}),i.jsxs("label",{className:"character-asset-panel__check",children:[i.jsx("input",{type:"checkbox",checked:v,onChange:x=>b(x.target.checked)}),"보유만"]})]}),u&&i.jsx("p",{className:"character-asset-panel__notice",children:u}),c&&i.jsx("p",{className:"character-asset-panel__notice",children:"에셋 로딩 중"}),i.jsxs("div",{className:"character-asset-panel__asset-list",children:[i.jsxs("button",{type:"button",className:`character-asset-panel__asset-card ${o[f]===null?"character-asset-panel__asset-card--active":""}`,onClick:()=>s(f,null),children:[i.jsx("div",{className:"character-asset-panel__empty-preview"}),i.jsx("span",{children:"비우기"})]}),S.map(x=>i.jsxs("button",{type:"button",className:`character-asset-panel__asset-card ${o[f]===x.id?"character-asset-panel__asset-card--active":""}`,onClick:()=>s(f,x.id),children:[i.jsx(mi.AssetPreviewCanvas,{asset:x,size:58}),i.jsx("span",{children:x.name})]},x.id)),S.length===0&&i.jsx("p",{className:"character-asset-panel__notice",children:"선택한 슬롯에 사용할 에셋이 없습니다."})]})]}),n]})},rc={manual:"수동",interaction:"상호작용",enterArea:"영역 진입",itemCollected:"아이템 획득",timeChanged:"시간 변경",calendarEventStarted:"캘린더 이벤트",questChanged:"퀘스트 변경",custom:"커스텀"},$v={id:"ID",name:"이름",description:"설명",type:"타입",key:"키",run:"실행 방식",cooldownMs:"쿨다운(ms)",requiresServer:"서버 필요",targetId:"대상 ID",action:"액션",areaId:"영역 ID",itemId:"아이템 ID",hour:"시간",eventId:"이벤트 ID",questId:"퀘스트 ID",status:"상태",operator:"연산자",value:"값",message:"메시지",toast:"토스트",durationMs:"지속시간(ms)"},Gv=new Set(["i","j","m","k","o","c","f","e","t"]),mr=e=>{const t=e.trim().toLowerCase();return t.length===1&&Gv.has(t)},Hv=e=>{const t=e.trigger;switch(t.type){case"manual":return{type:"manual",key:t.key};case"interaction":return{type:"interaction",targetId:t.targetId,...t.action?{action:t.action}:{}};case"enterArea":return{type:"enterArea",areaId:t.areaId};case"itemCollected":return{type:"itemCollected",itemId:t.itemId};case"timeChanged":return{type:"timeChanged",...t.hour!==void 0?{hour:t.hour}:{}};case"calendarEventStarted":return{type:"calendarEventStarted",eventId:t.eventId};case"questChanged":return{type:"questChanged",questId:t.questId,...t.status?{status:t.status}:{}};case"custom":return{type:"custom",key:t.key};default:return t}},Go=e=>{if(e==="true")return!0;if(e==="false")return!1;const t=Number(e);return Number.isFinite(t)&&e.trim()!==""?t:e};function kd({blueprints:e=We.SEED_GAMEPLAY_EVENTS,onCreate:t,onUpdate:n,onDelete:o,onRun:s,className:r="",style:a,children:l}){const c=m.useMemo(()=>new We.GameplayEventEngine({blueprints:e}),[e]),[u,f]=m.useState("manual-event"),[d,p]=m.useState("수동 이벤트"),[h,v]=m.useState("manual.event"),[b,S]=m.useState("이벤트가 실행되었습니다."),[x,_]=m.useState(null),[g,y]=m.useState(!1),w=m.useMemo(()=>e.find(M=>M.id===x)??null,[e,x]),[j,N]=m.useState({kind:"idle",message:"대기 중"}),B=()=>{if(mr(h)){N({kind:"error",message:`트리거 키 "${h}" 는 HUD 단축키로 예약되어 있습니다.`});return}const M=We.createManualToastEventBlueprint({id:u,name:d,triggerKey:h,message:b});t?.(M),_(M.id),y(!0),N({kind:"success",message:`이벤트를 생성했습니다: ${M.id}`})},z=()=>{const M=u.trim(),F=d.trim(),U=We.createNpcTalkStartsQuestEventBlueprint({...M?{id:`${M}-npc-quest`}:{},...F?{name:`${F} NPC 퀘스트`}:{}});t?.(U),_(U.id),y(!0),N({kind:"success",message:`NPC 퀘스트 프리셋을 추가했습니다: ${U.id}`})},W=m.useCallback(M=>{if(!w)return;const F={...w,...M};n?.(F),_(F.id),N({kind:"success",message:`이벤트를 수정했습니다: ${F.id}`})},[n,w]),D=()=>{if(!w)return;o?.(w.id);const M=e.find(F=>F.id!==w.id)??null;_(M?.id??null),y(!1),N({kind:"success",message:`이벤트를 삭제했습니다: ${w.id}`})},E=async M=>{const F=Hv(M);s?await s(F):await c.dispatch(F),N({kind:"success",message:`이벤트를 실행했습니다: ${M.id}`})},G=m.useCallback((M,F)=>{if(!w)return;const U=[...w.conditions??[]];U[M]=F,W({conditions:U})},[w,W]),T=m.useCallback((M,F)=>{if(!w)return;const U=[...w.actions];U[M]=F,W({actions:U})},[w,W]),O=m.useCallback((M,F,U)=>{if(!w||F==="type")return;const V=U;if(M==="root"){W({[F]:V});return}if(M==="policy"){F==="run"&&(V==="once"||V==="repeat")&&W({policy:{...w.policy,run:V}}),F==="cooldownMs"&&W({policy:{...w.policy,cooldownMs:Number(V)}}),F==="requiresServer"&&W({policy:{...w.policy,requiresServer:Go(String(V))===!0}});return}if(M==="trigger"){const Y=w.trigger;if(Y.type==="manual"&&F==="key"){const Z=String(V);if(mr(Z)){N({kind:"error",message:`트리거 키 "${Z}" 는 HUD 단축키로 예약되어 있습니다.`});return}W({trigger:{type:"manual",key:Z}})}if(Y.type==="interaction"&&(F==="targetId"||F==="action")&&W({trigger:{...Y,[F]:String(V)}}),Y.type==="enterArea"&&F==="areaId"&&W({trigger:{type:"enterArea",areaId:String(V)}}),Y.type==="itemCollected"&&F==="itemId"&&W({trigger:{type:"itemCollected",itemId:String(V)}}),Y.type==="timeChanged"&&F==="hour"&&W({trigger:{type:"timeChanged",hour:Number(V)}}),Y.type==="calendarEventStarted"&&F==="eventId"&&W({trigger:{type:"calendarEventStarted",eventId:String(V)}}),Y.type==="questChanged"&&(F==="questId"||F==="status")&&W({trigger:{...Y,[F]:String(V)}}),Y.type==="custom"&&F==="key"){const Z=String(V);if(mr(Z)){N({kind:"error",message:`트리거 키 "${Z}" 는 HUD 단축키로 예약되어 있습니다.`});return}W({trigger:{type:"custom",key:Z}})}return}if(M.startsWith("condition:")){const Y=Number(M.split(":")[1]),Z=w.conditions?.[Y];if(!Z)return;G(Y,{...Z,[F]:F==="value"?Go(String(V)):V});return}if(M.startsWith("action:")){const Y=Number(M.split(":")[1]),Z=w.actions[Y];if(!Z)return;T(Y,{...Z,[F]:F==="value"?Go(String(V)):V})}},[w,T,G,W]),P=m.useCallback(M=>{if(w){if(M.startsWith("condition:")){const F=Number(M.split(":")[1]);W({conditions:(w.conditions??[]).filter((U,V)=>V!==F)});return}if(M.startsWith("action:")){const F=Number(M.split(":")[1]);W({actions:w.actions.filter((U,V)=>V!==F)})}}},[w,W]),L=(M,F)=>i.jsx("div",{className:"gameplay-event-panel__field-grid",children:Object.entries(F).map(([U,V])=>i.jsxs("label",{className:"gameplay-event-panel__field",children:[i.jsx("span",{children:$v[U]??U}),i.jsx("input",{type:typeof V=="number"?"number":"text",value:String(V),disabled:U==="type",onChange:Y=>O(M,U,Go(Y.target.value))})]},`${M}-${U}`))});return i.jsxs("div",{className:`gameplay-event-panel ${r}`,style:a,children:[i.jsxs("section",{className:"gameplay-event-panel__section",children:[i.jsx("div",{className:"gameplay-event-panel__title",children:"빠른 생성"}),i.jsxs("label",{className:"gameplay-event-panel__field",children:[i.jsx("span",{children:"ID"}),i.jsx("input",{value:u,onChange:M=>f(M.target.value)})]}),i.jsxs("label",{className:"gameplay-event-panel__field",children:[i.jsx("span",{children:"이름"}),i.jsx("input",{value:d,onChange:M=>p(M.target.value)})]}),i.jsxs("label",{className:"gameplay-event-panel__field",children:[i.jsx("span",{children:"트리거 키"}),i.jsx("input",{value:h,onChange:M=>v(M.target.value)})]}),i.jsx("div",{className:"gameplay-event-panel__hint",children:"단일 문자 키(`i`, `j`, `m`, `k`, `o`, `c`, `f`, `e`, `t`)는 HUD 단축키로 예약됩니다."}),i.jsxs("label",{className:"gameplay-event-panel__field",children:[i.jsx("span",{children:"토스트 메시지"}),i.jsx("input",{value:b,onChange:M=>S(M.target.value)})]}),i.jsx("button",{type:"button",className:"gameplay-event-panel__primary",onClick:B,children:"수동 이벤트 생성"}),i.jsx("button",{type:"button",onClick:z,children:"NPC 퀘스트 프리셋 추가"})]}),i.jsxs("section",{className:"gameplay-event-panel__section",children:[i.jsx("div",{className:"gameplay-event-panel__title",children:"이벤트 목록"}),i.jsxs("div",{className:"gameplay-event-panel__list",children:[e.map(M=>i.jsxs("article",{className:"gameplay-event-panel__card",children:[i.jsxs("div",{children:[i.jsx("div",{className:"gameplay-event-panel__card-title",children:M.name}),i.jsxs("div",{className:"gameplay-event-panel__card-meta",children:[M.id," · ",rc[M.trigger.type]," · 액션 ",M.actions.length,"개"]})]}),i.jsxs("div",{className:"gameplay-event-panel__card-actions",children:[i.jsx("button",{type:"button",onClick:()=>{_(M.id),y(!0)},children:"편집"}),i.jsx("button",{type:"button",onClick:()=>{E(M)},children:"실행"})]})]},M.id)),e.length===0&&i.jsx("div",{className:"gameplay-event-panel__empty",children:"등록된 이벤트가 없습니다. 위에서 새 이벤트를 생성하세요."})]})]}),w&&i.jsxs("section",{className:"gameplay-event-panel__section gameplay-event-panel__detail",children:[i.jsxs("div",{className:"gameplay-event-panel__editor-head",children:[i.jsxs("div",{children:[i.jsx("div",{className:"gameplay-event-panel__title",children:"이벤트 인스펙터"}),i.jsx("div",{className:"gameplay-event-panel__hint",children:"그래프 노드 대신 트리거, 조건, 액션을 섹션별 인스펙터에서 수정합니다."})]}),i.jsxs("div",{className:"gameplay-event-panel__editor-tools",children:[i.jsxs("label",{className:"gameplay-event-panel__type-select",children:[i.jsx("span",{children:"트리거 타입"}),i.jsx("select",{value:w.trigger.type,onChange:M=>W({trigger:We.createGameplayEventTriggerTemplate(M.target.value)}),children:We.GAMEPLAY_EVENT_TRIGGER_TYPES.map(M=>i.jsx("option",{value:M,children:rc[M]},M))})]}),i.jsx("button",{type:"button",className:"gameplay-event-panel__primary",onClick:()=>y(M=>!M),children:g?"상세 편집 접기":"상세 편집 열기"})]})]}),g?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"gameplay-event-panel__inspector",children:[i.jsxs("div",{className:"gameplay-event-panel__inspector-card",children:[i.jsx("div",{className:"gameplay-event-panel__subhead",children:"기본 정보"}),L("root",{id:w.id,name:w.name,description:w.description??""})]}),i.jsxs("div",{className:"gameplay-event-panel__inspector-card",children:[i.jsx("div",{className:"gameplay-event-panel__subhead",children:"트리거"}),L("trigger",w.trigger)]}),i.jsxs("div",{className:"gameplay-event-panel__inspector-card",children:[i.jsx("div",{className:"gameplay-event-panel__subhead",children:"실행 정책"}),L("policy",{run:w.policy?.run??"repeat",cooldownMs:w.policy?.cooldownMs??0,requiresServer:w.policy?.requiresServer??!1})]}),i.jsxs("div",{className:"gameplay-event-panel__inspector-card",children:[i.jsx("div",{className:"gameplay-event-panel__subhead",children:"조건"}),(w.conditions??[]).map((M,F)=>i.jsxs("div",{className:"gameplay-event-panel__item-editor",children:[L(`condition:${F}`,M),i.jsx("button",{type:"button",onClick:()=>P(`condition:${F}`),children:"삭제"})]},`condition-${F}`)),(w.conditions??[]).length===0&&i.jsx("div",{className:"gameplay-event-panel__hint",children:"조건 없음"})]}),i.jsxs("div",{className:"gameplay-event-panel__inspector-card",children:[i.jsx("div",{className:"gameplay-event-panel__subhead",children:"액션"}),w.actions.map((M,F)=>i.jsxs("div",{className:"gameplay-event-panel__item-editor",children:[L(`action:${F}`,M),i.jsx("button",{type:"button",onClick:()=>P(`action:${F}`),children:"삭제"})]},`action-${F}`))]})]}),i.jsxs("div",{className:"gameplay-event-panel__node-toolbar",children:[i.jsxs("select",{"aria-label":"Condition type",onChange:M=>{W({conditions:[...w.conditions??[],We.createGameplayEventConditionTemplate(M.target.value)]}),M.currentTarget.value=""},defaultValue:"",children:[i.jsx("option",{value:"",disabled:!0,children:"조건 추가"}),We.GAMEPLAY_EVENT_CONDITION_TYPES.map(M=>i.jsx("option",{value:M,children:M},M))]}),i.jsxs("select",{"aria-label":"Action type",onChange:M=>{W({actions:[...w.actions,We.createGameplayEventActionTemplate(M.target.value)]}),M.currentTarget.value=""},defaultValue:"",children:[i.jsx("option",{value:"",disabled:!0,children:"액션 추가"}),We.GAMEPLAY_EVENT_ACTION_TYPES.map(M=>i.jsx("option",{value:M,children:M},M))]})]})]}):i.jsx("div",{className:"gameplay-event-panel__hint",children:"상세 편집이 접혀 있습니다. 필요할 때만 열어 수정하세요."}),i.jsxs("div",{className:"gameplay-event-panel__actions",children:[i.jsx("button",{type:"button",onClick:D,children:"이벤트 삭제"}),i.jsx("button",{type:"button",onClick:()=>{E(w)},children:"선택 이벤트 실행"})]})]}),!w&&i.jsx("section",{className:"gameplay-event-panel__section",children:i.jsx("div",{className:"gameplay-event-panel__hint",children:"이벤트 목록에서 `편집`을 누르면 상세 설정이 열립니다."})}),i.jsx("section",{className:"gameplay-event-panel__section",children:i.jsx("div",{className:`gameplay-event-panel__status gameplay-event-panel__status--${j.kind}`,children:j.message})}),l]})}const Wv=30,Uv=120,Vv=4;function Bd(){const{gl:e}=be.useThree(),t=se.useNPCStore(v=>v.instances),n=se.useNPCStore(v=>v.selectedInstanceId),o=se.useNPCStore(v=>v.selectedTemplateId),s=se.useNPCStore(v=>v.createInstanceFromTemplate),r=se.useNPCStore(v=>v.setNavigation),a=se.useNPCStore(v=>v.updateInstanceBehavior),l=se.useNPCStore(v=>v.setSelectedInstance),c=R.useBuildingStore(v=>v.editMode),u=R.useBuildingStore(v=>v.hoverPosition),f=c==="npc",[d,p]=m.useState(()=>new Set),h=m.useRef(0);return be.useFrame((v,b)=>{if(h.current+=b,h.current<.5)return;h.current=0;const S=v.camera.position,x=new Set;t.forEach(_=>{const[g,y,w]=_.position,j=g-S.x,N=y-S.y,B=w-S.z,z=Math.sqrt(j*j+N*N+B*B);se.weightFromDistance(z,Wv,Uv,Vv)>.01&&x.add(_.id)}),(x.size!==d.size||[...x].some(_=>!d.has(_)))&&p(x)}),m.useEffect(()=>{if(!f||!u)return;const v=b=>{if(b.target instanceof HTMLCanvasElement&&!b.defaultPrevented){if(n&&!b.shiftKey){const x=[u.x,u.y,u.z];a(n,{mode:"idle"}),r(n,[x]);return}o&&u&&s(o,[u.x,u.y,u.z])}};return e.domElement.addEventListener("click",v),()=>e.domElement.removeEventListener("click",v)},[f,o,n,u,e,s,r,a]),i.jsx("group",{name:"npc-system",children:Array.from(t.values()).map(v=>!f&&!d.has(v.id)?null:i.jsx(ka,{instance:v,isEditMode:f,onClick:()=>{f&&l(v.id)}},v.id))})}function Yv({part:e}){return i.jsxs("mesh",{position:e.position||[0,0,0],rotation:e.rotation||[0,0,0],scale:e.scale||[1,1,1],children:[i.jsx("boxGeometry",{args:[.5,1.8,.5]}),i.jsx("meshStandardMaterial",{color:"royalblue",transparent:!0,opacity:.7})]})}function Pd(){const e=R.useBuildingStore(c=>c.editMode),t=R.useBuildingStore(c=>c.hoverPosition),n=se.useNPCStore(c=>c.templates),o=se.useNPCStore(c=>c.clothingSets),s=se.useNPCStore(c=>c.selectedTemplateId),r=se.useNPCStore(c=>c.selectedClothingSetId),a=se.useNPCStore(c=>c.previewAccessories);if(e!=="npc"||!t)return null;const l=[];if(s){const c=n.get(s);if(c){if(l.push(...c.baseParts),r){const u=o.get(r);u&&l.push(...u.parts)}if(a.hat){const u=o.get(a.hat);if(u&&u.parts.length>0){const f=u.parts[0];f&&l.push(f)}}if(a.glasses){const u=o.get(a.glasses);if(u&&u.parts.length>0){const f=u.parts[0];f&&l.push(f)}}}}return i.jsxs("group",{position:[t.x,t.y,t.z],children:[l.map(c=>i.jsx(Yv,{part:c},c.id)),i.jsxs("mesh",{position:[0,.03,0],rotation:[-Math.PI/2,0,0],children:[i.jsx("circleGeometry",{args:[1,32]}),i.jsx("meshBasicMaterial",{color:"#00ff00",transparent:!0,opacity:.4,depthWrite:!1})]}),i.jsxs("mesh",{position:[0,.12,0],children:[i.jsx("sphereGeometry",{args:[.08,16,16]}),i.jsx("meshBasicMaterial",{color:"#38bdf8",depthWrite:!1})]})]})}const Zv="studio-social-world",Xv="Studio Social World",Kv="1.0.0",qv=(e,t)=>{if(typeof window>"u"||typeof document>"u")return;const n=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),o=window.URL.createObjectURL(n),s=document.createElement("a");s.href=o,s.download=e,s.click(),window.URL.revokeObjectURL(o)};function Rd({gameplayEvents:e=We.SEED_GAMEPLAY_EVENTS,defaultSlot:t="main",defaultBundleId:n=Zv,defaultBundleName:o=Xv,defaultVersion:s=Kv,buildBundle:r,validateBundle:a=We.validateContentBundle,onSaveWorld:l,onLoadWorld:c,onExportBundle:u,className:f="",style:d,children:p}){const h=bn.useAssetStore(X=>X.ids),v=bn.useAssetStore(X=>X.records),b=m.useMemo(()=>h.map(X=>v[X]).filter(X=>!!X),[h,v]),S=se.useNPCStore(X=>X.instances),x=m.useMemo(()=>Array.from(S.values()).map(X=>se.createNPCBehaviorBlueprintFromInstance(X,{id:`npc-behavior-${X.id}`})),[S]),_=m.useMemo(()=>x.map(X=>se.createAgentBehaviorBlueprintFromNPCBehaviorBlueprint(X,{id:`agent-behavior-${X.id}`,ownerType:"npc"})),[x]),[g,y]=m.useState(t),[w,j]=m.useState(n),[N,B]=m.useState(o),[z,W]=m.useState(s),[D,E]=m.useState([]),[G,T]=m.useState({kind:"idle",message:"대기 중"}),[O,P]=m.useState(null),[L,M]=m.useState(!1),F=m.useCallback(()=>{const X={assets:b,bundleId:w,bundleName:N,version:z,gameplayEvents:e,npcBehaviorBlueprints:x,agentBehaviorBlueprints:_};return r?r(X):We.createContentBundleFromSaveSystem(Jn.getSaveSystem(),b,{id:w,name:N,version:z,gameplayEvents:e,npcBehaviorBlueprints:x,agentBehaviorBlueprints:_})},[_,b,r,w,N,e,x,z]),U=m.useCallback(async()=>{const X=await Jn.getSaveSystem().list();E(X),T({kind:"success",message:`저장 슬롯 ${X.length}개를 불러왔습니다.`})},[]),V=m.useCallback(async()=>{l?await l(g):await Jn.getSaveSystem().save(g),T({kind:"success",message:`슬롯 "${g}" 에 저장했습니다.`}),await U()},[l,U,g]),Y=m.useCallback(async()=>{const X=c?await c(g):await Jn.getSaveSystem().load(g),A=X===void 0?!0:!!X;T({kind:A?"success":"error",message:A?`슬롯 "${g}" 을 불러왔습니다.`:`슬롯 "${g}" 에 저장 데이터가 없습니다.`})},[c,g]),Z=m.useCallback(()=>{const X=a(F());P(X),T({kind:X.ok?"success":"error",message:X.ok?"번들 검증이 통과했습니다.":`번들 오류 ${X.errors.length}개가 발견되었습니다.`})},[F,a]),q=m.useCallback(()=>{const X=F(),A=a(X);if(P(A),!A.ok){T({kind:"error",message:"번들 오류를 먼저 수정한 뒤 내보내세요."});return}u?u(X):qv(`${X.id}-${X.version}.bundle.json`,X),T({kind:"success",message:"콘텐츠 번들 JSON을 내보냈습니다."})},[F,u,a]);return i.jsxs("div",{className:`studio-panel ${f}`,style:d,children:[i.jsxs("section",{className:"studio-panel__section",children:[i.jsx("div",{className:"studio-panel__title",children:"월드 저장 관리"}),i.jsx("div",{className:"studio-panel__hint",children:"작업 중인 월드 상태를 슬롯 단위로 저장하거나 불러옵니다."}),i.jsxs("label",{className:"studio-panel__field",children:[i.jsx("span",{children:"슬롯 이름"}),i.jsx("input",{value:g,onChange:X=>y(X.target.value||"main")})]}),i.jsxs("div",{className:"studio-panel__actions",children:[i.jsx("button",{type:"button",onClick:()=>{V()},children:"현재 월드 저장"}),i.jsx("button",{type:"button",onClick:()=>{Y()},children:"슬롯 불러오기"}),i.jsx("button",{type:"button",onClick:()=>{U()},children:"슬롯 새로고침"})]}),D.length>0&&i.jsx("div",{className:"studio-panel__chips",children:D.map(X=>i.jsx("button",{type:"button",onClick:()=>y(X),children:X},X))})]}),i.jsxs("section",{className:"studio-panel__section",children:[i.jsx("div",{className:"studio-panel__title",children:"콘텐츠 번들"}),i.jsx("div",{className:"studio-panel__hint",children:"배포용 번들을 검증하고 JSON으로 내보냅니다."}),i.jsx("button",{type:"button",onClick:()=>M(X=>!X),className:"studio-panel__ghost",children:L?"번들 상세 설정 접기":"번들 상세 설정 열기"}),L&&i.jsxs("div",{className:"studio-panel__advanced",children:[i.jsxs("label",{className:"studio-panel__field",children:[i.jsx("span",{children:"번들 ID"}),i.jsx("input",{value:w,onChange:X=>j(X.target.value)})]}),i.jsxs("label",{className:"studio-panel__field",children:[i.jsx("span",{children:"번들 이름"}),i.jsx("input",{value:N,onChange:X=>B(X.target.value)})]}),i.jsxs("label",{className:"studio-panel__field",children:[i.jsx("span",{children:"버전"}),i.jsx("input",{value:z,onChange:X=>W(X.target.value)})]})]}),i.jsxs("div",{className:"studio-panel__meta",children:["에셋 ",b.length,"개 · 이벤트 ",e.length,"개 · NPC 행동 ",x.length,"개 · 에이전트 행동 ",_.length,"개 · 세이브 도메인 ",Array.from(Jn.getSaveSystem().getBindings()).length,"개"]}),i.jsxs("div",{className:"studio-panel__actions",children:[i.jsx("button",{type:"button",onClick:Z,children:"번들 검증"}),i.jsx("button",{type:"button",onClick:q,children:"JSON 내보내기"})]})]}),i.jsxs("section",{className:"studio-panel__section",children:[i.jsx("div",{className:"studio-panel__title",children:"상태"}),i.jsx("div",{className:`studio-panel__status studio-panel__status--${G.kind}`,children:G.message}),O&&!O.ok&&i.jsx("ul",{className:"studio-panel__errors",children:O.errors.map(X=>i.jsx("li",{children:X},X))})]}),p]})}const Dd=({children:e,panels:t=[],defaultActivePanels:n=["tile","camera"],defaultPanelOpen:o=!1,defaultModalOpen:s=!1,actions:r=[],hiddenBuiltInPanels:a=[],panelOrder:l,panelDefaults:c={},validateBundle:u})=>{const f=m.useMemo(()=>{const j=[{id:"world",title:"전역",component:i.jsx(Ev,{}),defaultSide:"left"},{id:"wall",title:"벽",component:i.jsx(Av,{}),defaultSide:"left"},{id:"tile",title:"타일",component:i.jsx(kv,{}),defaultSide:"left"},{id:"block",title:"박스",component:i.jsx(Bv,{}),defaultSide:"left"},{id:"object",title:"오브젝트",component:i.jsx(Pv,{}),defaultSide:"left"},{id:"npc",title:"NPC",component:i.jsx(Rv,{}),defaultSide:"left"},{id:"character",title:"캐릭터",component:i.jsx(Ov,{}),defaultSide:"left"},{id:"vehicle",title:"탈것",component:i.jsx(Gc,{}),defaultSide:"left"},{id:"animation",title:"애니메이션",component:i.jsx(Fc,{}),defaultSide:"left"},{id:"camera",title:"카메라",component:i.jsx(Rc,{}),defaultSide:"right"},{id:"motion",title:"모션",component:i.jsx(Oc,{}),defaultSide:"right"},{id:"performance",title:"성능",component:i.jsx($c,{}),defaultSide:"right"},{id:"gameplay-events",title:"게임플레이 이벤트",component:i.jsx(kd,{}),defaultSide:"right"},{id:"studio",title:"스튜디오",component:i.jsx(Rd,{...u?{validateBundle:u}:{}}),defaultSide:"right"}],N=new Set(a),B=new Map;for(const D of j){if(N.has(D.id))continue;const E=c[D.id]??{};B.set(D.id,{...D,...E})}for(const D of t){const E=c[D.id]??{};B.set(D.id,{...B.get(D.id),...D,...E})}const z=l??[],W=[];for(const D of z){const E=B.get(D);E&&(W.push(E),B.delete(D))}return[...W,...B.values()]},[a,c,l,t,u]),d=m.useMemo(()=>n.find(j=>f.some(N=>N.id===j))??f[0]?.id??"",[n,f]),[p,h]=m.useState(d),[v,b]=m.useState(o),[S,x]=m.useState(s),_=m.useMemo(()=>new Set(["npc","gameplay-events","studio"]),[]),g=f.some(j=>j.id===p)?p:d,y=f.find(j=>j.id===g);m.useEffect(()=>{g&&h(g)},[g]);const w=j=>{const B=j===g?!v:!0,z=B&&_.has(j);h(j),b(B),x(z)};return i.jsxs("div",{className:"editor-root",children:[i.jsxs("aside",{className:`editor-sidebar ${v?"editor-sidebar--open":"editor-sidebar--collapsed"}`,"aria-label":"Editor sidebar",children:[i.jsxs("div",{className:"editor-sidebar-menu",children:[i.jsxs("div",{className:"editor-sidebar-header",children:[i.jsx("div",{className:"editor-shell-title",children:"Editor"}),i.jsx("div",{className:"editor-shell-status",children:v?y?.title??"패널 없음":""})]}),i.jsx("nav",{className:"editor-panel-menu editor-panel-menu--flat",children:f.map(j=>i.jsx("button",{type:"button",onClick:()=>w(j.id),className:`editor-panel-toggle ${g===j.id&&v?"active":""}`,title:j.title,children:j.title},j.id))}),i.jsxs("div",{className:"editor-sidebar-footer",children:[r.length>0&&i.jsxs("div",{className:"editor-menu-section",children:[i.jsx("div",{className:"editor-region-label",children:"액션"}),r.map(j=>i.jsx("button",{type:"button",onClick:()=>{j.onClick()},className:"editor-panel-toggle",disabled:j.disabled,title:j.label,children:j.label},j.id))]}),i.jsx("div",{className:"editor-shell-hint",children:"좌클릭 배치 · 우클릭 회전 · Q/E 높이 조절"})]})]}),v&&!S&&i.jsxs("section",{className:`editor-sidebar-panel ${y?.className??""}`,children:[i.jsxs("div",{className:"editor-sidebar-panel-header",children:[i.jsxs("div",{children:[i.jsx("div",{className:"editor-region-label",children:"패널"}),i.jsx("h2",{children:y?.title??"패널"})]}),i.jsx("button",{type:"button",className:"editor-sidebar-close",onClick:()=>x(!0),"aria-label":"패널 전면 열기",children:"전면"}),i.jsx("button",{type:"button",className:"editor-sidebar-close",onClick:()=>b(!1),"aria-label":"패널 접기",children:"접기"})]}),i.jsx("div",{className:"editor-sidebar-panel-content",style:y?.style,children:y?.component})]})]}),v&&S&&y&&i.jsx("section",{className:`editor-panel-modal ${g==="npc"?"editor-panel-modal--npc":""}`,"aria-label":`${y.title} panel modal`,children:i.jsxs("div",{className:`editor-panel-modal__surface ${y.className??""}`,children:[i.jsxs("header",{className:"editor-panel-modal__header",children:[i.jsxs("div",{children:[i.jsx("div",{className:"editor-region-label",children:"패널"}),i.jsx("h2",{children:y.title})]}),i.jsxs("div",{className:"editor-panel-modal__actions",children:[i.jsx("button",{type:"button",className:"editor-sidebar-close",onClick:()=>x(!1),"aria-label":"패널 사이드바로",children:"사이드바"}),i.jsx("button",{type:"button",className:"editor-sidebar-close",onClick:()=>{x(!1),b(!1)},"aria-label":"패널 닫기",children:"닫기"})]})]}),i.jsx("div",{className:`editor-panel-modal__content ${g==="npc"?"editor-panel-modal__content--npc":""}`,style:y.style,children:y.component})]})}),e]})},ac={forward:!1,backward:!1,leftward:!1,rightward:!1,shift:!1,space:!1,keyZ:!1,keyR:!1,keyF:!1,keyE:!1,escape:!1},lc={isActive:!1,shouldRun:!1,isLookAround:!1},Qv=e=>({...e,...e.smoothing?{smoothing:{...e.smoothing}}:{},...e.bounds?{bounds:{...e.bounds}}:{},...e.modeSettings?{modeSettings:{...e.modeSettings}}:{}}),Jv=({children:e,className:t="",style:n={},shell:o})=>{const s=m.useRef(null);return m.useEffect(()=>{const r=ge.useGaesupStore.getState();return s.current={mode:{...r.mode},cameraOption:Qv(r.cameraOption),interactionActive:r.interaction.isActive},r.stopAutomation(),r.updateKeyboard(ac),r.updateMouse(lc),r.setInteractionActive(!1),()=>{const a=s.current;if(!a)return;const l=ge.useGaesupStore.getState();l.setMode(a.mode),l.replaceCameraOption(a.cameraOption),l.setInteractionActive(a.interactionActive),l.updateKeyboard(ac),l.updateMouse(lc)}},[]),i.jsx("div",{className:`gaesup-editor ${t}`,style:{...n},children:i.jsx(Dd,{...o?.panels?{panels:o.panels}:{},...o?.defaultActivePanels?{defaultActivePanels:o.defaultActivePanels}:{},...typeof o?.defaultPanelOpen=="boolean"?{defaultPanelOpen:o.defaultPanelOpen}:{},...typeof o?.defaultModalOpen=="boolean"?{defaultModalOpen:o.defaultModalOpen}:{},...o?.actions?{actions:o.actions}:{},...o?.hiddenBuiltInPanels?{hiddenBuiltInPanels:o.hiddenBuiltInPanels}:{},...o?.panelOrder?{panelOrder:o.panelOrder}:{},...o?.panelDefaults?{panelDefaults:o.panelDefaults}:{},...o?.validate?{validateBundle:o.validate}:{},children:e})})},ew=()=>i.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})}),tw=()=>i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),i.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),nw=({children:e,title:t,initialWidth:n=280,initialHeight:o=400,minWidth:s=200,minHeight:r=150,maxWidth:a=600,maxHeight:l=800,resizeHandles:c=["right"],className:u="",style:f={},onClose:d,onMinimize:p,draggable:h=!0,onDrop:v})=>{const[b,S]=m.useState({width:n,height:o}),[x,_]=m.useState({x:0,y:0}),[g,y]=m.useState(!1),[w,j]=m.useState(!1),[N,B]=m.useState(""),[z,W]=m.useState({x:0,y:0}),D=m.useRef(null),E=m.useRef(null),G=m.useCallback(L=>M=>{M.preventDefault(),y(!0),B(L)},[]),T=m.useCallback(L=>{if(D.current)if(g){const M=D.current.getBoundingClientRect();let F=b.width,U=b.height;N.includes("right")&&(F=Math.min(a,Math.max(s,L.clientX-M.left))),N.includes("bottom")&&(U=Math.min(l,Math.max(r,L.clientY-M.top))),S({width:F,height:U})}else w&&_({x:L.clientX-z.x,y:L.clientY-z.y})},[g,w,N,b,s,a,r,l,z]),O=m.useCallback(()=>{w&&v&&v(x.x,x.y),y(!1),j(!1),B("")},[w,v,x]),P=m.useCallback(L=>{if(!h||g)return;L.preventDefault(),j(!0);const M=D.current?.getBoundingClientRect();M&&W({x:L.clientX-M.left,y:L.clientY-M.top})},[h,g]);return m.useEffect(()=>{if(g||w)return document.addEventListener("mousemove",T),document.addEventListener("mouseup",O),()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",O)}},[g,w,T,O]),i.jsxs("div",{ref:D,className:`rp-panel ${u} ${w?"dragging":""}`,style:{width:`${b.width}px`,height:`${b.height}px`,...w?{position:"fixed",left:`${x.x}px`,top:`${x.y}px`,zIndex:10003}:{},...f},children:[i.jsxs("div",{ref:E,className:"rp-header",onMouseDown:P,children:[i.jsx("h3",{className:"rp-title",children:t}),i.jsxs("div",{className:"rp-controls",onMouseDown:L=>L.stopPropagation(),children:[p&&i.jsx("button",{className:"rp-btn rp-btn--minimize",onClick:p,title:"최소화",children:i.jsx(ew,{})}),d&&i.jsx("button",{className:"rp-btn rp-btn--close",onClick:d,title:"닫기",children:i.jsx(tw,{})})]})]}),i.jsx("div",{className:"rp-content",children:e}),c.map(L=>i.jsx("div",{className:`rp-resize-handle handle-${L}`,onMouseDown:G(L.replace("corner","right bottom"))},L))]})},Ba=e=>({selectedObjectIds:[],setSelectedObjectIds:t=>e({selectedObjectIds:t}),layoutConfig:null,setLayoutConfig:t=>e({layoutConfig:t}),activeNodeGraph:null,setActiveNodeGraph:t=>e({activeNodeGraph:t}),clipboard:null,setClipboard:t=>e({clipboard:t})}),iw=Ba,Fd=Bi.create(Ba),ow=()=>{const e=Fd();return{...e,selectObject:t=>e.setSelectedObjectIds([t]),selectMultiple:t=>e.setSelectedObjectIds(t),clearSelection:()=>e.setSelectedObjectIds([])}};function sw(e={}){const t={panels:e.panels??[],actions:(e.commands??[]).map(n=>({id:n.id,label:n.label,onClick:n.run}))};return e.defaultActivePanels&&(t.defaultActivePanels=e.defaultActivePanels),typeof e.defaultPanelOpen=="boolean"&&(t.defaultPanelOpen=e.defaultPanelOpen),typeof e.defaultModalOpen=="boolean"&&(t.defaultModalOpen=e.defaultModalOpen),e.hiddenBuiltInPanels&&(t.hiddenBuiltInPanels=e.hiddenBuiltInPanels),e.panelOrder&&(t.panelOrder=e.panelOrder),e.panelDefaults&&(t.panelDefaults=e.panelDefaults),e.validate&&(t.validate=e.validate),t}function rw(){const e=[],t=[];return{execute:async n=>{await n.run(),n.undo&&(e.push(n),t.length=0)},undo:async()=>{const n=e.pop();n?.undo&&(await n.undo(),t.push(n))},redo:async()=>{const n=t.pop();n&&(await n.run(),e.push(n))},canUndo:()=>e.length>0,canRedo:()=>t.length>0,clear:()=>{e.length=0,t.length=0}}}function Ld({area:e=80,height:t=18,count:n=1200,kind:o,followCamera:s=!1}){const r=da.useWeatherStore(f=>f.current),a=m.useRef(null),{geometry:l,material:c,kind:u}=m.useMemo(()=>{const f=o??r?.kind;if(f!=="rain"&&f!=="snow"&&f!=="storm"&&f!=="wind")return{geometry:null,material:null,kind:null};const d=new Float32Array(n*3),p=new Float32Array(n);for(let _=0;_<n;_++)d[_*3+0]=(Math.random()-.5)*e,d[_*3+1]=Math.random()*t,d[_*3+2]=(Math.random()-.5)*e,p[_]=f==="snow"?.6+Math.random()*.4:f==="wind"?5+Math.random()*5:8+Math.random()*6;const h=new k.BufferGeometry;h.setAttribute("position",new k.BufferAttribute(d,3)),h.setAttribute("aSpeed",new k.BufferAttribute(p,1));const v=f==="snow",b=f==="wind",S=f==="storm",x=new k.PointsMaterial({color:v?16777215:b?14542832:S?8366296:10148351,size:v?.18:b?.08:.12,transparent:!0,opacity:v?.85:b?.35:S?.7:.6,depthWrite:!1,sizeAttenuation:!0});return{geometry:h,material:x,kind:f}},[o,r?.kind,r?.intensity,e,t,n]);return be.useFrame(({camera:f},d)=>{const p=a.current;if(!p||!l||!u)return;s&&p.position.set(f.position.x,f.position.y-t*.35,f.position.z);const h=l.getAttribute("position"),v=l.getAttribute("aSpeed"),b=h.array,S=v.array,x=u==="snow"||u==="wind"?1:6;for(let _=0;_<b.length;_+=3)u==="wind"?(b[_+0]+=S[_/3]*d*x,b[_+1]+=Math.sin((b[_+0]+_)*.4)*d*.25):b[_+1]-=S[_/3]*d*x,u==="snow"&&(b[_+0]+=Math.sin((b[_+1]+_)*.5)*d*.3),u==="wind"&&b[_+0]>e*.5?(b[_+0]=-e*.5,b[_+1]=Math.random()*t,b[_+2]=(Math.random()-.5)*e):b[_+1]<0&&(b[_+0]=(Math.random()-.5)*e,b[_+1]=t,b[_+2]=(Math.random()-.5)*e);h.needsUpdate=!0}),!l||!c?null:i.jsx("points",{ref:a,geometry:l,material:c,frustumCulled:!1})}const aw=["intel","mali","adreno 3","adreno 4","powervr"],lw=["swiftshader","llvmpipe","software"],cc=["rtx","radeon rx","apple m","apple a1","apple a2"];function zd(){if(typeof window>"u"||typeof document>"u")return{webgl2:!1,maxTextureSize:0,rendererName:"",vendorName:"",cores:4,memory:4,isMobile:!1,pixelRatio:1};const e=document.createElement("canvas"),t=e.getContext("webgl2")??e.getContext("webgl");let n="",o="",s=0,r=!1;if(t){r=typeof WebGL2RenderingContext<"u"&&t instanceof WebGL2RenderingContext,s=t.getParameter(t.MAX_TEXTURE_SIZE)||0;const f=t.getExtension("WEBGL_debug_renderer_info");f&&(n=String(t.getParameter(f.UNMASKED_RENDERER_WEBGL)||""),o=String(t.getParameter(f.UNMASKED_VENDOR_WEBGL)||""))}const a=navigator.hardwareConcurrency??4,l=navigator.deviceMemory??4,c=/android|iphone|ipad|ipod|mobile|opera mini/i.test(navigator.userAgent),u=Math.min(window.devicePixelRatio||1,2);return{webgl2:r,maxTextureSize:s,rendererName:n,vendorName:o,cores:a,memory:l,isMobile:c,pixelRatio:u}}function Od(e){const t=e.rendererName.toLowerCase();return lw.some(n=>t.includes(n))?"low":e.isMobile?cc.some(n=>t.includes(n))?"medium":"low":aw.some(n=>t.includes(n))?e.cores>=8&&e.memory>=8?"medium":"low":cc.some(n=>t.includes(n))||e.cores>=8&&e.memory>=8&&e.webgl2?"high":e.cores>=4&&e.memory>=4?"medium":"low"}function $s(e){return e==="high"?{tier:e,instanceScale:1,pixelRatio:2,shadowMapSize:2048,postprocess:!0,outline:!0}:e==="medium"?{tier:e,instanceScale:.7,pixelRatio:1.5,shadowMapSize:1024,postprocess:!0,outline:!0}:{tier:e,instanceScale:.4,pixelRatio:1,shadowMapSize:512,postprocess:!1,outline:!1}}function na(){const e=zd(),t=Od(e);return{profile:$s(t),capabilities:e}}const cw=$s("medium"),$d=Bi.create(e=>({profile:cw,capabilities:null,manualOverride:!1,detect:()=>{const{profile:t,capabilities:n}=na();e({profile:t,capabilities:n,manualOverride:!1})},setTier:t=>{e({profile:$s(t),manualOverride:!0})},resetAuto:()=>{const{profile:t,capabilities:n}=na();e({profile:t,capabilities:n,manualOverride:!1})}})),Ot=new Set,Ue=Bi.create(e=>({active:!1,version:0,visibleTileGroupIds:Ot,visibleWallGroupIds:Ot,visibleBlockIds:Ot,visibleObjectIds:Ot,clusterCounts:new Uint32Array(0),setResult:({version:t,tileIds:n,wallIds:o,blockIds:s,objectIds:r,clusterCounts:a})=>e({active:!0,version:t,visibleTileGroupIds:n,visibleWallGroupIds:o,visibleBlockIds:s??Ot,visibleObjectIds:r,clusterCounts:a}),reset:()=>e({active:!1,version:0,visibleTileGroupIds:Ot,visibleWallGroupIds:Ot,visibleBlockIds:Ot,visibleObjectIds:Ot,clusterCounts:new Uint32Array(0)})})),kt=18,Nt=140,uw=.12,dw=8,fw=3.2,uc=2.4,pw=.985;function wn(e,t){return Math.floor(e/t)}function Gd(e,t){return`${e}:${t}`}function hw(e,t,n,o,s=kt,r=dw){const a=wn(e,s),l=wn(t,s),c=Math.atan2(o,n),u=c<0?c+Math.PI*2:c,f=Math.floor(u/(Math.PI*2)*r)%r;return`${a}:${l}:${f}`}function rs(e,t,n,o=kt){const s=Math.max(0,Math.ceil(t.radius/o));for(let r=t.cellZ-s;r<=t.cellZ+s;r+=1)for(let a=t.cellX-s;a<=t.cellX+s;a+=1)mw(e,a,r,n)}function Ho(e,t,n=kt){rs(e,t,t.id,n)}function mw(e,t,n,o){const s=Gd(t,n),r=e.get(s);if(r){r.push(o);return}e.set(s,[o])}function Pa(e,t,n,o,s,r,a,l){const c=(t+n)*.5,u=(o+s)*.5,f=(r+a)*.5,d=n-t,p=s-o,h=a-r;return{id:e,centerX:c,centerY:u,centerZ:f,radius:Math.max(1,Math.hypot(d,p,h)*.5),cellX:wn(c,l),cellZ:wn(f,l)}}function Hd(e,t=kt){if(e.tiles.length===0)return null;let n=1/0,o=-1/0,s=0,r=.2,a=1/0,l=-1/0;for(const c of e.tiles){const f=(c.size??1)*.5;n=Math.min(n,c.position.x-f),o=Math.max(o,c.position.x+f),s=Math.min(s,0),r=Math.max(r,Math.max(c.position.y,.2)+1.5),a=Math.min(a,c.position.z-f),l=Math.max(l,c.position.z+f)}return Pa(e.id,n,o,s,r,a,l,t)}function Wd(e,t=kt){if(e.walls.length===0)return null;let n=1/0,o=-1/0,s=0,r=2.5,a=1/0,l=-1/0;for(const c of e.walls)n=Math.min(n,c.position.x-1.1),o=Math.max(o,c.position.x+1.1),s=Math.min(s,c.position.y),r=Math.max(r,c.position.y+3.5),a=Math.min(a,c.position.z-1.1),l=Math.max(l,c.position.z+1.1);return Pa(e.id,n,o,s,r,a,l,t)}function Ud(e,t=kt){const n=Math.max(1,Math.round(e.size?.x??1))*R.TILE_CONSTANTS.GRID_CELL_SIZE,o=Math.max(1,Math.round(e.size?.y??1))*R.TILE_CONSTANTS.HEIGHT_STEP,s=Math.max(1,Math.round(e.size?.z??1))*R.TILE_CONSTANTS.GRID_CELL_SIZE,r=R.TILE_CONSTANTS.GRID_CELL_SIZE*.5;return Pa(e.id,e.position.x-r,e.position.x-r+n,e.position.y,e.position.y+o,e.position.z-r,e.position.z-r+s,t)}function gw(e){const t=e.config?.size??1;switch(e.type){case"tree":case"sakura":return Math.max(2.2,t*.8);case"flag":return Math.max(1.4,(e.config?.flagWidth??1.5)*.8);case"fire":return Math.max(1.2,e.config?.fireWidth??1);case"billboard":return 1.8;default:return 1.5}}function Vd(e,t=kt){const n=gw(e);return{id:e.id,centerX:e.position.x,centerY:e.position.y+n*.5,centerZ:e.position.z,radius:n,cellX:wn(e.position.x,t),cellZ:wn(e.position.z,t)}}function bw(e,t,n,o=[],s=kt){const r=Array.isArray(o)?o:[],a=typeof o=="number"?o:s,l={tileById:new Map,wallById:new Map,blockById:new Map,objectById:new Map,tileBuckets:new Map,wallBuckets:new Map,blockBuckets:new Map,objectBuckets:new Map,occluderByKey:new Map,occluderBuckets:new Map};for(const c of t){const u=Hd(c,a);if(u&&(l.tileById.set(u.id,u),Ho(l.tileBuckets,u,a),u.radius>=fw)){const f={...u,key:`tile:${u.id}`,kind:"tile",strength:u.radius};l.occluderByKey.set(f.key,f),rs(l.occluderBuckets,f,f.key,a)}}for(const c of e){const u=Wd(c,a);if(u&&(l.wallById.set(u.id,u),Ho(l.wallBuckets,u,a),u.radius>=uc||c.walls.length>=4)){const f={...u,key:`wall:${u.id}`,kind:"wall",strength:u.radius*1.15};l.occluderByKey.set(f.key,f),rs(l.occluderBuckets,f,f.key,a)}}for(const c of r){const u=Ud(c,a);if(l.blockById.set(u.id,u),Ho(l.blockBuckets,u,a),u.radius>=uc||(c.size?.y??1)>=2){const f={...u,key:`block:${u.id}`,kind:"block",strength:u.radius*1.1};l.occluderByKey.set(f.key,f),rs(l.occluderBuckets,f,f.key,a)}}for(const c of n){const u=Vd(c,a);l.objectById.set(u.id,u),Ho(l.objectBuckets,u,a)}return l}function Vi(e,t,n,o=Nt,s=kt){const r=wn(t,s),a=wn(n,s),l=Math.ceil(o/s),c=new Set;for(let u=a-l;u<=a+l;u+=1)for(let f=r-l;f<=r+l;f+=1){const d=e.get(Gd(f,u));if(d)for(const p of d)c.add(p)}return c}function xw(e,t,n,o=Nt,s=kt){const r=Vi(e.occluderBuckets,t,n,o,s),a=[];for(const l of r){const c=e.occluderByKey.get(l);c&&a.push(c)}return a}function yw(e,t,n,o,s){const r=e.centerX-n.x,a=e.centerY-n.y,l=e.centerZ-n.z,c=Math.sqrt(r*r+a*a+l*l);if(c<10)return!1;s.targetDir.set(r,a,l).normalize();for(const u of o){if(u.kind===t&&u.id===e.id)continue;const f=u.centerX-n.x,d=u.centerY-n.y,p=u.centerZ-n.z,h=Math.sqrt(f*f+d*d+p*p);if(h<=1||h>=c-Math.max(e.radius,1.2)||(s.occDir.set(f,d,p).normalize(),s.targetDir.dot(s.occDir)<pw))continue;const b=s.cross.crossVectors(s.targetDir,s.occDir).length()*h,S=u.strength+Math.min(e.radius*.45,1.8);if(!(b>S))return!0}return!1}const Ra=0,Da=1,Fa=2,La=3,vw=0,Yd=1,Zd=2,Xd=3,Kd=4,ww=10,qd=20,Qd=21,ia=22,Jd=23,ef=24,Sw=30;function tf(){return{version:0,ids:[],kinds:new Uint8Array(0),subKinds:new Uint8Array(0),centerX:new Float32Array(0),centerY:new Float32Array(0),centerZ:new Float32Array(0),radius:new Float32Array(0),cellX:new Int16Array(0),cellZ:new Int16Array(0),memberCount:new Uint16Array(0)}}function _w(e,t,n,o){let s=n.length+o.length;for(const r of e)r.walls.length>0&&(s+=1);for(const r of t)r.tiles.length>0&&(s+=1);return s}function jw(e){const t=e.blocks??[],n=_w(e.wallGroups,e.tileGroups,e.objects,t);if(n===0)return{...tf(),version:e.version};const o=new Array(n),s=new Uint8Array(n),r=new Uint8Array(n),a=new Float32Array(n),l=new Float32Array(n),c=new Float32Array(n),u=new Float32Array(n),f=new Int16Array(n),d=new Int16Array(n),p=new Uint16Array(n);let h=0;const v=(b,S,x,_,g)=>{o[h]=b,s[h]=S,r[h]=x,a[h]=_.centerX,l[h]=_.centerY,c[h]=_.centerZ,u[h]=_.radius,f[h]=_.cellX,d[h]=_.cellZ,p[h]=g,h+=1};for(const b of e.tileGroups){const S=Hd(b);if(!S)continue;const x=b.tiles.find(g=>g.objectType&&g.objectType!=="none")?.objectType??"none",_=x==="grass"?Yd:x==="water"?Zd:x==="sand"?Xd:x==="snowfield"?Kd:vw;v(b.id,Ra,_,S,b.tiles.length)}for(const b of e.wallGroups){const S=Wd(b);S&&v(b.id,Da,ww,S,b.walls.length)}for(const b of t)v(b.id,La,Sw,Ud(b),1);for(const b of e.objects){const S=b.type==="tree"||b.type==="sakura"?qd:b.type==="flag"?Qd:b.type==="fire"?ia:b.type==="billboard"?Jd:b.type==="model"?ef:ia;v(b.id,Fa,S,Vd(b),1)}return{version:e.version,ids:o,kinds:s,subKinds:r,centerX:a,centerY:l,centerZ:c,radius:u,cellX:f,cellZ:d,memberCount:p}}const Ti=0,Ii=1,Ei=2,Ai=3,ki=4,Gs=5,Hs=6,Ws=7,Us=8,Vs=9,Ys=10,Zs=11,Xs=12;function nf(e,t){const n=e.kinds[t],o=e.subKinds[t];if(n===Ra)return o===Yd?Ii:o===Zd?Ei:o===Xd?Ai:o===Kd?ki:Ti;if(n===Da)return Gs;if(n===La)return Ys;if(n===Fa){if(o===qd)return Hs;if(o===Qd)return Ws;if(o===ia)return Us;if(o===Jd)return Vs;if(o===ef)return Zs}return Ti}function of(e,t){const n=new Set,o=new Set,s=new Set,r=new Set,a=new Uint32Array(Xs),l=Math.min(e.ids.length,t.length);for(let c=0;c<l;c+=1){if((t[c]??0)===0)continue;const u=e.ids[c];if(!u)continue;const f=e.kinds[c];f===Ra?n.add(u):f===Da?o.add(u):f===La?s.add(u):f===Fa&&r.add(u);const d=nf(e,c);a[d]=(a[d]??0)+1}return{version:e.version,tileIds:n,wallIds:o,blockIds:s,objectIds:r,clusterCounts:a}}const ft=4;function He(e,t){const n=t*ft;return e.args[n+1]??0}const sf=[{id:Ti,label:"tile",vertexCountHint:36},{id:Ii,label:"grass",vertexCountHint:36},{id:Ei,label:"water",vertexCountHint:36},{id:Ai,label:"sand",vertexCountHint:36},{id:ki,label:"snowfield",vertexCountHint:36},{id:Gs,label:"wall",vertexCountHint:36},{id:Hs,label:"sakura",vertexCountHint:12},{id:Ws,label:"flag",vertexCountHint:12},{id:Us,label:"fire",vertexCountHint:6},{id:Vs,label:"billboard",vertexCountHint:6},{id:Ys,label:"block",vertexCountHint:36},{id:Zs,label:"model",vertexCountHint:36}];function za(){return{version:0,args:new Uint32Array(Xs*ft),dirtyRanges:[]}}function Mw(e,t){if(e.length!==t.length)return t.length>0?[{start:0,end:t.length/ft}]:[];const n=[];let o=-1;const s=t.length/ft;for(let r=0;r<s;r+=1){const a=r*ft;let l=!1;for(let c=0;c<ft;c+=1)if((e[a+c]??0)!==(t[a+c]??0)){l=!0;break}if(l){o<0&&(o=r);continue}o>=0&&(n.push({start:o,end:r}),o=-1)}return o>=0&&n.push({start:o,end:s}),n}function rf(e,t,n){const o=new Uint32Array(Xs*ft);for(const r of sf){const a=r.id*ft;o[a]=r.vertexCountHint,o[a+1]=t[r.id]??0,o[a+2]=0,o[a+3]=0}const s=n??za();return{version:e,args:o,dirtyRanges:Mw(s.args,o)}}function af(e){return{version:e.version,slices:e.dirtyRanges.map(t=>{const n=t.start*ft,o=(t.end-t.start)*ft;return{byteOffset:n*e.args.BYTES_PER_ELEMENT,elementOffset:n,elementCount:o,data:e.args.subarray(n,n+o)}})}}const ho=4,mo=5;function Oa(){return{version:0,count:0,spatial:new Float32Array(0),meta:new Int32Array(0),spatialDirty:[],metaDirty:[]}}function Cw(e){const t=new Float32Array(e.ids.length*ho);for(let n=0;n<e.ids.length;n+=1){const o=n*ho;t[o]=e.centerX[n]??0,t[o+1]=e.centerY[n]??0,t[o+2]=e.centerZ[n]??0,t[o+3]=e.radius[n]??0}return t}function Nw(e){const t=new Int32Array(e.ids.length*mo);for(let n=0;n<e.ids.length;n+=1){const o=n*mo;t[o]=e.cellX[n]??0,t[o+1]=e.cellZ[n]??0,t[o+2]=e.kinds[n]??0,t[o+3]=e.subKinds[n]??0,t[o+4]=e.memberCount[n]??0}return t}function dc(e,t,n){if(e.length!==t.length)return t.length>0?[{start:0,end:Math.ceil(t.length/n)}]:[];const o=[];let s=-1;const r=Math.ceil(t.length/n);for(let a=0;a<r;a+=1){const l=a*n;let c=!1;for(let u=0;u<n;u+=1)if((e[l+u]??0)!==(t[l+u]??0)){c=!0;break}if(c){s<0&&(s=a);continue}s>=0&&(o.push({start:s,end:a}),s=-1)}return s>=0&&o.push({start:s,end:r}),o}function lf(e,t){const n=Cw(e),o=Nw(e),s=t??Oa();return{version:e.version,count:e.ids.length,spatial:n,meta:o,spatialDirty:dc(s.spatial,n,ho),metaDirty:dc(s.meta,o,mo)}}function fc(e,t,n){return n.map(o=>{const s=o.start*t,r=(o.end-o.start)*t;return{byteOffset:s*e.BYTES_PER_ELEMENT,elementOffset:s,elementCount:r,data:e.subarray(s,s+r)}})}function cf(e){return{version:e.version,count:e.count,spatial:fc(e.spatial,ho,e.spatialDirty),meta:fc(e.meta,mo,e.metaDirty)}}const Tw=8,Iw=128;function go(){return{backend:"none",uploadedVersion:0,spatialBuffer:null,metaBuffer:null,indirectArgsBuffer:null,spatialBytes:0,metaBytes:0,indirectArgsBytes:0}}function Ks(e){if(typeof e!="object"||e===null)return null;const t=e,n=t.backend?.device??t.device??null;return!n||typeof n.createBuffer!="function"||typeof n.queue?.writeBuffer!="function"?null:n}function Ji(e){e?.destroy&&e.destroy()}function uf(e){Ji(e.spatialBuffer),Ji(e.metaBuffer),Ji(e.indirectArgsBuffer)}function oa(e,t,n,o,s){return o<=0?(Ji(t),null):t&&n===o?t:(Ji(t),e.createBuffer({label:s,size:o,usage:Iw|Tw}))}function df(e,t,n){const o=cf(n),s=n.spatial.byteLength,r=n.meta.byteLength,a=oa(e,t.spatialBuffer,t.spatialBytes,s,"building-spatial"),l=oa(e,t.metaBuffer,t.metaBytes,r,"building-meta");if(a)for(const c of o.spatial)e.queue.writeBuffer(a,c.byteOffset,c.data);if(l)for(const c of o.meta)e.queue.writeBuffer(l,c.byteOffset,c.data);return{backend:"webgpu",uploadedVersion:n.version,spatialBuffer:a,metaBuffer:l,indirectArgsBuffer:t.indirectArgsBuffer,spatialBytes:s,metaBytes:r,indirectArgsBytes:t.indirectArgsBytes}}function ff(e,t,n){const o=af(n),s=n.args.byteLength,r=oa(e,t.indirectArgsBuffer,t.indirectArgsBytes,s,"building-indirect-args");if(r)for(const a of o.slices)e.queue.writeBuffer(r,a.byteOffset,a.data);return{...t,backend:"webgpu",uploadedVersion:Math.max(t.uploadedVersion,n.version),indirectArgsBuffer:r,indirectArgsBytes:s}}const pc=tf(),hc=Oa(),mc=go(),gc=za(),Be=Bi.create(e=>({snapshot:pc,gpuMirror:hc,uploadResources:mc,drawMirror:gc,setSnapshot:t=>e({snapshot:t}),setGpuMirror:t=>e({gpuMirror:t}),setUploadResources:t=>e({uploadResources:t}),setDrawMirror:t=>e({drawMirror:t}),reset:()=>e({snapshot:pc,gpuMirror:hc,uploadResources:mc,drawMirror:gc})}));function Wo(e,t){if(e===t)return!0;if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}const $t=new Set,mn=Bi.create(e=>({initialized:!1,visibleTileGroupIds:$t,visibleWallGroupIds:$t,visibleBlockIds:$t,visibleObjectIds:$t,setVisible:({tileIds:t,wallIds:n,blockIds:o,objectIds:s})=>e(r=>{const a=!Wo(r.visibleTileGroupIds,t),l=!Wo(r.visibleWallGroupIds,n),c=o??$t,u=!Wo(r.visibleBlockIds,c),f=!Wo(r.visibleObjectIds,s);return!a&&!l&&!u&&!f&&r.initialized?r:{initialized:!0,visibleTileGroupIds:a?t:r.visibleTileGroupIds,visibleWallGroupIds:l?n:r.visibleWallGroupIds,visibleBlockIds:u?c:r.visibleBlockIds,visibleObjectIds:f?s:r.visibleObjectIds}}),reset:()=>e({initialized:!1,visibleTileGroupIds:$t,visibleWallGroupIds:$t,visibleBlockIds:$t,visibleObjectIds:$t})}));var Ew=Object.defineProperty,Aw=Object.getOwnPropertyDescriptor,jo=(e,t,n,o)=>{for(var s=Aw(t,n),r=e.length-1,a;r>=0;r--)(a=e[r])&&(s=a(t,n,s)||s);return s&&Ew(t,n,s),s};class Sn{materials=new Map;textures=new Map;textureLoader;constructor(){this.textureLoader=new k.TextureLoader}getMaterial(t){const n=this.createMaterialKey(t),o=this.materials.get(n);if(o)return o;const s=this.createMaterial(t);return this.materials.set(n,s),s}createMaterialKey(t){return[t.id,t.assetId??"",t.color??t.materialParams?.color??"",t.material??"",t.textureUrl??"",t.mapTextureUrl??t.materialParams?.mapTextureUrl??"",t.normalTextureUrl??t.materialParams?.normalTextureUrl??"",t.roughness??t.materialParams?.roughness??"",t.metalness??t.materialParams?.metalness??"",t.opacity??t.materialParams?.opacity??"",t.transparent??t.materialParams?.transparent??""].join("|")}createMaterial(t){const n=t.color??t.materialParams?.color??"#ffffff",o=t.roughness??t.materialParams?.roughness??.5,s=t.metalness??t.materialParams?.metalness??0,r=t.opacity??t.materialParams?.opacity??1,a=t.transparent??t.materialParams?.transparent??!1,l=t.mapTextureUrl??t.textureUrl??t.materialParams?.mapTextureUrl,c=t.normalTextureUrl??t.materialParams?.normalTextureUrl,u={color:n,roughness:o,metalness:s,opacity:r,transparent:a};if(R.getDefaultToonMode()){const f=t.material==="GLASS",d=new k.MeshToonMaterial({color:n,opacity:f?.45:r,transparent:f?!0:a,gradientMap:R.getToonGradient(f?2:4)});return l&&(d.map=this.loadTexture(l)),c&&(d.normalMap=this.loadTexture(c)),d}return t.material==="GLASS"?new k.MeshPhysicalMaterial({...u,transmission:.98,roughness:.1,envMapIntensity:1}):(l&&(u.map=this.loadTexture(l)),c&&(u.normalMap=this.loadTexture(c)),new k.MeshStandardMaterial(u))}loadTexture(t){const n=this.textures.get(t);if(n)return n;const o=this.textureLoader.load(t);return o.wrapS=k.RepeatWrapping,o.wrapT=k.RepeatWrapping,o.needsUpdate=!0,this.textures.set(t,o),o}updateMaterial(t,n){const o=this.materials.get(t);o&&(o instanceof k.MeshStandardMaterial?(n.color&&o.color.set(n.color),n.roughness!==void 0&&(o.roughness=n.roughness),n.metalness!==void 0&&(o.metalness=n.metalness),n.opacity!==void 0&&(o.opacity=n.opacity),o.needsUpdate=!0):o instanceof k.MeshToonMaterial&&(n.color&&o.color.set(n.color),n.opacity!==void 0&&(o.opacity=n.opacity),o.needsUpdate=!0))}dispose(){this.materials.forEach(t=>t.dispose()),this.materials.clear(),this.textures.forEach(t=>t.dispose()),this.textures.clear()}}jo([ge.HandleError(),ge.Profile()],Sn.prototype,"getMaterial");jo([ge.HandleError(),ge.Profile()],Sn.prototype,"createMaterial");jo([ge.HandleError(),ge.MonitorMemory(20)],Sn.prototype,"loadTexture");jo([ge.HandleError(),ge.Profile()],Sn.prototype,"updateMaterial");jo([ge.HandleError()],Sn.prototype,"dispose");const bc={id:"default-block",color:"#8b8174",material:"STANDARD",roughness:.92};function kw(e){return{width:Math.max(1,Math.round(e.size?.x??1))*R.TILE_CONSTANTS.GRID_CELL_SIZE,height:Math.max(1,Math.round(e.size?.y??1))*R.TILE_CONSTANTS.HEIGHT_STEP,depth:Math.max(1,Math.round(e.size?.z??1))*R.TILE_CONSTANTS.GRID_CELL_SIZE}}function sa(e){const{width:t,height:n,depth:o}=kw(e);return{position:[e.position.x-R.TILE_CONSTANTS.GRID_CELL_SIZE*.5+t*.5,e.position.y+n*.5,e.position.z-R.TILE_CONSTANTS.GRID_CELL_SIZE*.5+o*.5],scale:[t,n,o]}}function pf({blocks:e,meshes:t,isEditMode:n=!1,selectedBlockId:o=null,onBlockClick:s}){const r=m.useRef(new Sn),a=m.useMemo(()=>new k.Object3D,[]),l=m.useMemo(()=>new k.BoxGeometry(1,1,1),[]),c=m.useMemo(()=>new k.MeshStandardMaterial({color:"#60a5fa",transparent:!0,opacity:.16,emissive:new k.Color("#2563eb"),emissiveIntensity:.08,wireframe:!0,depthWrite:!1}),[]),u=m.useMemo(()=>new k.MeshStandardMaterial({color:"#bae6fd",transparent:!0,opacity:.28,emissive:new k.Color("#60a5fa"),emissiveIntensity:.2,wireframe:!0,depthWrite:!1}),[]),f=m.useMemo(()=>{const d=new Map;for(const h of e){const v=h.materialId??bc.id,b=d.get(v)??[];b.push(h),d.set(v,b)}const p=r.current;return Array.from(d.entries()).map(([h,v])=>({key:h,blocks:v,material:p.getMaterial(t.get(h)??{...bc,id:h})}))},[e,t]);return m.useEffect(()=>()=>{r.current.dispose(),l.dispose(),c.dispose(),u.dispose()},[c,l,u]),i.jsxs(i.Fragment,{children:[!n&&e.length>0&&i.jsx(ct.RigidBody,{type:"fixed",colliders:!1,children:e.map(d=>{const p=sa(d);return i.jsx(ct.CuboidCollider,{position:p.position,args:[p.scale[0]*.5,p.scale[1]*.5,p.scale[2]*.5]},d.id)})}),f.map(d=>i.jsx(Bw,{batch:d,geometry:l,dummy:a},d.key)),n&&e.map(d=>{const p=sa(d),h=d.id===o;return i.jsx("mesh",{name:`block-edit-${d.id}`,position:p.position,scale:[p.scale[0]*.82,p.scale[1]*.82,p.scale[2]*.82],geometry:l,material:h?u:c,onClick:()=>s?.(d.id)},`${d.id}-edit`)})]})}function Bw({batch:e,geometry:t,dummy:n}){const o=m.useRef(null);return m.useLayoutEffect(()=>{const s=o.current;if(s){s.count=e.blocks.length;for(let r=0;r<e.blocks.length;r+=1){const a=e.blocks[r];if(!a)continue;const l=sa(a);n.position.set(...l.position),n.scale.set(...l.scale),n.rotation.set(0,0,0),n.updateMatrix(),s.setMatrixAt(r,n.matrix)}s.instanceMatrix.needsUpdate=!0,e.blocks.length>0&&(s.computeBoundingBox(),s.computeBoundingSphere())}},[e.blocks,n]),i.jsx("instancedMesh",{ref:o,name:`block-system-${e.key}`,args:[t,e.material,Math.max(1,e.blocks.length)],castShadow:!0,receiveShadow:!0})}function hf({size:e=R.TILE_CONSTANTS.DEFAULT_GRID_SIZE,divisions:t=e/R.TILE_CONSTANTS.GRID_CELL_SIZE,color1:n="#888888",color2:o="#444444"}){return i.jsx("gridHelper",{args:[e,t,n,o],position:[0,.01,0]})}function mf(e,t,n,o){const s=document.createElement("canvas"),r=512,a=Math.round(r*(n/t));s.width=r,s.height=a;const l=s.getContext("2d");l.fillStyle="#0a0a0a",l.fillRect(0,0,r,a),l.strokeStyle="#333",l.lineWidth=4,l.strokeRect(2,2,r-4,a-4),l.fillStyle=o;const c=Math.floor(a*.25);l.font=`bold ${c}px monospace`,l.textAlign="center",l.textBaseline="middle";const u=e.split(`
|
|
8
|
+
`),f=c*1.3,d=a/2-(u.length-1)*f/2;u.forEach((h,v)=>{l.fillText(h,r/2,d+v*f,r-20)});const p=new k.CanvasTexture(s);return p.needsUpdate=!0,p}const gf=20,bf=100,xf=3,fi=new k.Object3D,Pw=1.5,Rw=1,Dw=4;function yf(e){const t=e?.image;return!t?.width||!t?.height?null:t.width/t.height}function vf(e,t,n){const o=t??Pw;return{width:e&&e>0?e:k.MathUtils.clamp(o*(n??4/3),Rw,Dw),height:o}}function Fw({imageUrl:e,width:t,height:n,scale:o,color:s,elevation:r,intensity:a,toon:l}){const c=m.useRef(null),u=m.useRef(null),f=m.useRef(null),d=m.useMemo(()=>new k.Vector3,[]),h=l??R.getDefaultToonMode()?R.getToonGradient(3):null,v=pt.useTexture(e),b=yf(v),S=vf(t,n,b),x=o??1,_=S.width*x,g=S.height*x,y=m.useMemo(()=>new k.Color(s||"#00ff88"),[s]),w=r??1,j=a??2,N=m.useMemo(()=>new k.PlaneGeometry(_,g),[_,g]),B=m.useMemo(()=>new k.BoxGeometry(_*1.08,g*1.12,.08),[_,g]),z=m.useMemo(()=>new k.PlaneGeometry(_*1.15,g*1.15),[_,g]);return be.useFrame(W=>{c.current.getWorldPosition(d);const D=W.camera.position.distanceTo(d),E=se.weightFromDistance(D,gf,bf,xf);u.current.emissiveIntensity=j*E,f.current.opacity=(.14+j*.055+.05*Math.sin(W.clock.elapsedTime*2))*E}),m.useEffect(()=>()=>{N.dispose(),B.dispose(),z.dispose()},[N,B,z]),i.jsxs("group",{position:[0,g/2+w,0],children:[i.jsx("mesh",{geometry:B,position:[0,0,-.045],castShadow:!0,receiveShadow:!0,children:i.jsx("meshStandardMaterial",{color:"#07090b",roughness:.68,metalness:.18})}),i.jsx("mesh",{geometry:z,position:[0,0,-.01],children:i.jsx("meshBasicMaterial",{ref:f,color:y,transparent:!0,opacity:.25,blending:k.AdditiveBlending,depthWrite:!1,side:k.DoubleSide})}),i.jsx("mesh",{ref:c,geometry:N,position:[0,0,.012],children:h?i.jsx("meshToonMaterial",{ref:u,map:v,emissive:y,emissiveIntensity:j,gradientMap:h,side:k.DoubleSide,transparent:!0}):i.jsx("meshStandardMaterial",{ref:u,map:v,emissive:y,emissiveIntensity:j,side:k.DoubleSide,transparent:!0})})]})}function Lw({text:e,width:t,height:n,scale:o,color:s,elevation:r,intensity:a,toon:l}){const c=m.useRef(null),u=m.useRef(null),f=m.useRef(null),d=m.useMemo(()=>new k.Vector3,[]),h=l??R.getDefaultToonMode()?R.getToonGradient(3):null,v=o??1,b=(t??2)*v,S=(n??1.5)*v,x=s||"#00ff88",_=r??1,g=a??2,y=m.useMemo(()=>mf(e||"HELLO",b,S,x),[e,b,S,x]),w=m.useMemo(()=>new k.Color(x),[x]),j=m.useMemo(()=>new k.PlaneGeometry(b,S),[b,S]),N=m.useMemo(()=>new k.BoxGeometry(b*1.08,S*1.12,.08),[b,S]),B=m.useMemo(()=>new k.PlaneGeometry(b*1.15,S*1.15),[b,S]);return be.useFrame(z=>{c.current.getWorldPosition(d);const W=z.camera.position.distanceTo(d),D=se.weightFromDistance(W,gf,bf,xf);u.current.emissiveIntensity=g*D,f.current.opacity=(.14+g*.055+.05*Math.sin(z.clock.elapsedTime*2))*D}),m.useEffect(()=>()=>{j.dispose(),N.dispose(),B.dispose(),y.dispose()},[j,N,B,y]),i.jsxs("group",{position:[0,S/2+_,0],children:[i.jsx("mesh",{geometry:N,position:[0,0,-.045],castShadow:!0,receiveShadow:!0,children:i.jsx("meshStandardMaterial",{color:"#07090b",roughness:.68,metalness:.18})}),i.jsx("mesh",{geometry:B,position:[0,0,-.01],children:i.jsx("meshBasicMaterial",{ref:f,color:w,transparent:!0,opacity:.25,blending:k.AdditiveBlending,depthWrite:!1,side:k.DoubleSide})}),i.jsx("mesh",{ref:c,geometry:j,position:[0,0,.012],children:h?i.jsx("meshToonMaterial",{ref:u,map:y,emissive:w,emissiveIntensity:g,gradientMap:h,side:k.DoubleSide}):i.jsx("meshStandardMaterial",{ref:u,map:y,emissive:w,emissiveIntensity:g,side:k.DoubleSide})})]})}const zw=e=>e.imageUrl?i.jsx(Fw,{...e,imageUrl:e.imageUrl}):i.jsx(Lw,{...e});function wf({entries:e,texture:t,color:n,width:o,height:s}){const r=m.useRef(null),a=m.useRef(null),l=m.useRef(null),c=m.useRef(null),u=m.useRef(null),f=m.useRef(0),d=e.length,p=Math.max(1,d),h=m.useMemo(()=>new k.Color(n),[n]),v=m.useMemo(()=>{const g=new k.PlaneGeometry(o,s);return g.translate(0,0,.052),g},[s,o]),b=m.useMemo(()=>new k.BoxGeometry(o*1.08,s*1.12,.08),[s,o]),S=m.useMemo(()=>{const g=new k.PlaneGeometry(o*1.18,s*1.18);return g.translate(0,0,.046),g},[s,o]),x=m.useMemo(()=>Math.min(.72,.14+Math.max(...e.map(g=>g.intensity))*.055),[e]),_=m.useMemo(()=>new k.MeshStandardMaterial({color:"#07090b",roughness:.68,metalness:.18}),[]);return m.useLayoutEffect(()=>{const g=r.current,y=a.current,w=l.current;if(!(!g||!y||!w)){g.count=d,y.count=d,w.count=d;for(let j=0;j<d;j+=1){const N=e[j];N&&(fi.position.set(N.x,N.y+s/2+N.elevation,N.z),fi.rotation.set(0,N.rotation,0),fi.updateMatrix(),g.setMatrixAt(j,fi.matrix),y.setMatrixAt(j,fi.matrix),w.setMatrixAt(j,fi.matrix))}g.instanceMatrix.needsUpdate=!0,y.instanceMatrix.needsUpdate=!0,w.instanceMatrix.needsUpdate=!0,g.computeBoundingSphere(),y.computeBoundingSphere(),w.computeBoundingSphere()}},[d,e,s]),be.useFrame((g,y)=>{if(f.current+=Math.max(0,y),f.current<1/20)return;f.current=0;const w=x+.05*Math.sin(g.clock.elapsedTime*2);u.current&&(u.current.opacity=w)}),m.useEffect(()=>()=>{v.dispose(),b.dispose(),S.dispose(),_.dispose()},[S,v,b,_]),d===0?null:i.jsxs(i.Fragment,{children:[i.jsx("instancedMesh",{ref:r,args:[b,_,p],castShadow:!0,receiveShadow:!0,frustumCulled:!0}),i.jsx("instancedMesh",{ref:l,args:[S,void 0,p],frustumCulled:!0,children:i.jsx("meshBasicMaterial",{ref:u,color:h,transparent:!0,opacity:x,blending:k.AdditiveBlending,depthWrite:!1,side:k.DoubleSide,toneMapped:!1})}),i.jsx("instancedMesh",{ref:a,args:[v,void 0,p],frustumCulled:!0,children:i.jsx("meshBasicMaterial",{ref:c,map:t,color:h,side:k.DoubleSide,transparent:!0,toneMapped:!1})})]})}function Ow({entries:e}){const t=e[0],n=pt.useTexture(t?.imageUrl??""),o=vf(t?.width,t?.height,yf(n));return t?i.jsx(wf,{entries:e,texture:n,color:t.color,width:o.width,height:o.height}):null}function $w({entries:e}){const t=e[0],n=m.useMemo(()=>mf(t?.text??"HELLO",t?.width??2,t?.height??1.5,t?.color??"#00ff88"),[t?.color,t?.height,t?.text,t?.width]);return m.useEffect(()=>()=>{n.dispose()},[n]),t?i.jsx(wf,{entries:e,texture:n,color:t.color,width:t.width,height:t.height}):null}const Gw=m.memo(function({billboards:t}){const n=m.useMemo(()=>{const o=new Map;for(const s of t){const r=s.config?.billboardScale??1,a=(s.config?.billboardHeight??1.5)*r,l=s.config?.billboardWidth,c=s.config?.billboardColor??"#00ff88",u=s.config?.billboardImageUrl??"",f=s.config?.billboardText??"HELLO",d=l?l*r:u?0:2*r,p=s.config?.billboardElevation??1,h=s.config?.billboardIntensity??2,v=u?`img:${u}:${c}:${d}:${a}:${h}`:`txt:${f}:${c}:${d}:${a}:${h}`,b={key:v,text:f,imageUrl:u,color:c,width:d,height:a,scale:r,elevation:p,intensity:h,x:s.position.x,y:s.position.y,z:s.position.z,rotation:s.rotation??0},S=o.get(v);S?S.push(b):o.set(v,[b])}return Array.from(o.entries())},[t]);return n.length===0?null:i.jsx(i.Fragment,{children:n.map(([o,s])=>{const r=s[0];return r?r.imageUrl?i.jsx(Ow,{entries:s},o):i.jsx($w,{entries:s},o):null})})}),Hw=m.memo(zw);var Ww=`varying vec2 vUv;
|
|
9
|
+
uniform float time;
|
|
10
|
+
uniform float intensity;
|
|
11
|
+
uniform float seed;
|
|
12
|
+
uniform float lean;
|
|
13
|
+
uniform float flare;
|
|
14
|
+
uniform vec3 tint;
|
|
15
|
+
|
|
16
|
+
float hash(vec2 p) {
|
|
17
|
+
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
float noise(vec2 p) {
|
|
21
|
+
vec2 i = floor(p);
|
|
22
|
+
vec2 f = fract(p);
|
|
23
|
+
f = f * f * (3.0 - 2.0 * f);
|
|
24
|
+
return mix(
|
|
25
|
+
mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x),
|
|
26
|
+
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x),
|
|
27
|
+
f.y
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
float fbm(vec2 p) {
|
|
32
|
+
float v = 0.0, a = 0.5;
|
|
33
|
+
for (int i = 0; i < 3; i++) {
|
|
34
|
+
v += a * noise(p);
|
|
35
|
+
p = p * 2.1 + vec2(100.0);
|
|
36
|
+
a *= 0.5;
|
|
37
|
+
}
|
|
38
|
+
return v;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
void main() {
|
|
42
|
+
vec2 uv = vUv;
|
|
43
|
+
|
|
44
|
+
vec2 q = vec2(
|
|
45
|
+
fbm(vec2(uv.x * 4.2 + seed * 5.1, uv.y * 5.8 - time * 1.5)),
|
|
46
|
+
fbm(vec2(uv.x * 3.6 - seed * 3.3, uv.y * 4.6 + time * 0.6))
|
|
47
|
+
);
|
|
48
|
+
float n1 = fbm(uv * vec2(3.8, 5.6) + q * 1.5 + vec2(seed * 2.0, -time * 1.1));
|
|
49
|
+
float n2 = noise(vec2(uv.y * 9.0 + seed * 11.0, time * 4.7 + seed * 17.0));
|
|
50
|
+
|
|
51
|
+
float skew = lean * pow(uv.y, 1.2);
|
|
52
|
+
float sway = (n1 - 0.5) * 0.28 * (1.0 - uv.y * 0.35);
|
|
53
|
+
float x = (uv.x - 0.5) - skew + sway;
|
|
54
|
+
float w = mix(0.46 * flare, 0.02, pow(uv.y, 0.72));
|
|
55
|
+
|
|
56
|
+
float edgeTurb = q.x * 0.07 * uv.y;
|
|
57
|
+
float body = 1.0 - smoothstep(w - edgeTurb, w + 0.06, abs(x));
|
|
58
|
+
float tongue1 = 1.0 - smoothstep(w * 0.82, w * 0.82 + 0.06, abs(x + 0.12 + q.y * 0.08));
|
|
59
|
+
float tongue2 = 1.0 - smoothstep(w * 0.68, w * 0.68 + 0.07, abs(x - 0.1 + q.x * 0.06));
|
|
60
|
+
|
|
61
|
+
float baseGlow = 1.0 - smoothstep(0.1, 0.42, distance(uv, vec2(0.5 + skew * 0.1, 0.1)));
|
|
62
|
+
float plume = max(body, max(tongue1 * 0.82, tongue2 * 0.68));
|
|
63
|
+
|
|
64
|
+
float bite = smoothstep(0.55, 1.0, n1 + uv.y * 0.4);
|
|
65
|
+
plume *= mix(1.0, 0.72, bite * smoothstep(0.2, 0.85, uv.y));
|
|
66
|
+
plume *= 1.0 - smoothstep(0.8, 1.0, uv.y);
|
|
67
|
+
plume = smoothstep(0.14, 0.9, plume + baseGlow * 0.38 + n1 * 0.2);
|
|
68
|
+
|
|
69
|
+
float core = 1.0 - smoothstep(0.01, 0.14, abs(x));
|
|
70
|
+
float fire = clamp(plume * (0.85 + 0.15 * n2), 0.0, 1.0);
|
|
71
|
+
|
|
72
|
+
vec3 deepRed = vec3(0.35, 0.02, 0.0);
|
|
73
|
+
vec3 ember = vec3(0.65, 0.08, 0.01);
|
|
74
|
+
vec3 orange = vec3(1.0, 0.38, 0.04);
|
|
75
|
+
vec3 golden = vec3(1.0, 0.65, 0.18);
|
|
76
|
+
vec3 hot = vec3(1.0, 0.88, 0.55);
|
|
77
|
+
vec3 white = vec3(1.0, 0.97, 0.92);
|
|
78
|
+
|
|
79
|
+
vec3 color = mix(deepRed, ember, smoothstep(0.02, 0.15, fire));
|
|
80
|
+
color = mix(color, orange, smoothstep(0.12, 0.35, fire));
|
|
81
|
+
color = mix(color, golden, smoothstep(0.28, 0.52, fire));
|
|
82
|
+
color = mix(color, hot, smoothstep(0.45, 0.72, fire));
|
|
83
|
+
color = mix(color, white, smoothstep(0.62, 1.0, fire * core));
|
|
84
|
+
|
|
85
|
+
float trail = smoothstep(0.8, 1.0, n2 + n1 * 0.3)
|
|
86
|
+
* smoothstep(0.18, 0.7, uv.y)
|
|
87
|
+
* smoothstep(0.35, 0.0, abs(x));
|
|
88
|
+
color += trail * vec3(1.0, 0.4, 0.06) * 0.4;
|
|
89
|
+
|
|
90
|
+
float smokeY = smoothstep(0.75, 0.98, uv.y);
|
|
91
|
+
float smoke = smokeY * q.x * 0.22 * smoothstep(0.28, 0.0, abs(x));
|
|
92
|
+
color = mix(color, vec3(0.18, 0.14, 0.12), smoke);
|
|
93
|
+
|
|
94
|
+
float alpha = smoothstep(0.06, 0.35, fire) * min(1.0, 0.5 + intensity * 0.26);
|
|
95
|
+
alpha += trail * 0.15 + smoke * 0.3;
|
|
96
|
+
|
|
97
|
+
if (alpha < 0.01) discard;
|
|
98
|
+
|
|
99
|
+
gl_FragColor = vec4(color * tint * (0.62 + intensity * 0.48), alpha);
|
|
100
|
+
}`,Uw=`varying vec2 vUv;
|
|
101
|
+
uniform float seed;
|
|
102
|
+
uniform float lean;
|
|
103
|
+
uniform float time;
|
|
104
|
+
|
|
105
|
+
void main() {
|
|
106
|
+
vUv = uv;
|
|
107
|
+
|
|
108
|
+
vec3 right = vec3(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]);
|
|
109
|
+
vec3 up = vec3(0.0, 1.0, 0.0);
|
|
110
|
+
float uy = clamp(uv.y, 0.0, 1.0);
|
|
111
|
+
|
|
112
|
+
float sway = sin(time * 0.7 + seed * 3.14) * 0.04 * uy;
|
|
113
|
+
float bend = lean * pow(uy, 1.35) * (0.35 + uy * 0.65);
|
|
114
|
+
float wobble = sin((uy * 6.0 + seed * 5.73) + position.y * 1.15) * 0.03 * uy;
|
|
115
|
+
float lift = sin(uv.x * 3.14159 + seed * 3.7) * 0.015 * uy;
|
|
116
|
+
|
|
117
|
+
vec3 billboarded = right * (position.x + bend + wobble + sway) + up * (position.y + lift);
|
|
118
|
+
|
|
119
|
+
vec4 center = modelMatrix * vec4(0.0, 0.0, 0.0, 1.0);
|
|
120
|
+
center.xyz += billboarded;
|
|
121
|
+
|
|
122
|
+
gl_Position = projectionMatrix * viewMatrix * center;
|
|
123
|
+
}`;const Vw=pt.shaderMaterial({time:0,intensity:1.5,seed:0,lean:0,flare:1,tint:new k.Color(1,1,1)},Uw,Ww);be.extend({FireMaterial:Vw});const Yw=`
|
|
124
|
+
attribute float aLife;
|
|
125
|
+
attribute float aSpeed;
|
|
126
|
+
attribute float aDrift;
|
|
127
|
+
varying float vAlpha;
|
|
128
|
+
varying float vHeat;
|
|
129
|
+
uniform float uTime;
|
|
130
|
+
|
|
131
|
+
void main() {
|
|
132
|
+
float t = fract(uTime * aSpeed + aLife);
|
|
133
|
+
vec3 pos = position;
|
|
134
|
+
float angle = t * 8.0 + aDrift;
|
|
135
|
+
float radius = 0.08 + t * 0.2;
|
|
136
|
+
pos.y += t * t * 3.2;
|
|
137
|
+
pos.x += sin(angle) * radius;
|
|
138
|
+
pos.z += cos(angle) * radius;
|
|
139
|
+
float flicker = 0.75 + 0.25 * sin(uTime * 14.0 + aDrift * 4.0);
|
|
140
|
+
vAlpha = (1.0 - t) * (1.0 - t) * 0.9 * flicker;
|
|
141
|
+
vHeat = 1.0 - t * 0.85;
|
|
142
|
+
vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
|
|
143
|
+
gl_Position = projectionMatrix * mvPosition;
|
|
144
|
+
gl_PointSize = mix(4.5, 0.6, t) * (220.0 / -mvPosition.z);
|
|
145
|
+
}
|
|
146
|
+
`,Sf=`
|
|
147
|
+
varying float vAlpha;
|
|
148
|
+
varying float vHeat;
|
|
149
|
+
|
|
150
|
+
void main() {
|
|
151
|
+
float d = length(gl_PointCoord - 0.5);
|
|
152
|
+
if (d > 0.5) discard;
|
|
153
|
+
float glow = smoothstep(0.5, 0.05, d);
|
|
154
|
+
vec3 red = vec3(0.75, 0.12, 0.02);
|
|
155
|
+
vec3 orange = vec3(1.0, 0.5, 0.08);
|
|
156
|
+
vec3 hot = vec3(1.0, 0.92, 0.65);
|
|
157
|
+
vec3 color = mix(red, orange, vHeat);
|
|
158
|
+
color = mix(color, hot, vHeat * vHeat);
|
|
159
|
+
gl_FragColor = vec4(color * glow * 1.4, vAlpha * glow);
|
|
160
|
+
}
|
|
161
|
+
`,zi=18;let gr=null,br=null;function _f(){return gr||(gr={log:new k.CylinderGeometry(.035,.045,.5,5),charcoal:new k.CircleGeometry(.18,6),glow:new k.CircleGeometry(.7,8)}),gr}function jf(){return br||(br={log:new k.MeshStandardMaterial({color:2759178,roughness:1}),charcoal:new k.MeshStandardMaterial({color:1118481,roughness:1,emissive:new k.Color("#3a0c00"),emissiveIntensity:.8}),ember:new k.ShaderMaterial({vertexShader:Yw,fragmentShader:Sf,uniforms:{uTime:{value:0}},transparent:!0,depthWrite:!1,blending:k.AdditiveBlending})}),br}const Zw=({intensity:e=1.5,width:t=1,height:n=1.5,color:o="#ffffff"})=>{const s=m.useMemo(()=>new k.Color(o),[o]),r=_f(),a=jf(),l=m.useMemo(()=>Math.max(.4,(t+n*.5)/1.5),[t,n]),c=m.useMemo(()=>[{w:t*.78,h:n,x:0,y:n*.5,z:0,seed:.17,lean:.06,flare:1,speed:1.45,tOff:0,iMul:1},{w:t*.52,h:n*.85,x:-t*.12,y:n*.43,z:.02,seed:1.31,lean:-.2,flare:.85,speed:1.9,tOff:1.7,iMul:.82},{w:t*.42,h:n*.7,x:t*.14,y:n*.36,z:-.02,seed:2.63,lean:.16,flare:.74,speed:2.2,tOff:3.4,iMul:.72}],[t,n]),u=m.useMemo(()=>c.map(()=>m.createRef()),[c]),f=m.useMemo(()=>c.map(p=>new k.PlaneGeometry(p.w,p.h)),[c]),d=m.useMemo(()=>{const p=new k.BufferGeometry,h=new Float32Array(zi*3),v=new Float32Array(zi),b=new Float32Array(zi),S=new Float32Array(zi);for(let x=0;x<zi;x++)h[x*3]=(Math.random()-.5)*t*.35,h[x*3+1]=Math.random()*n*.2,h[x*3+2]=(Math.random()-.5)*t*.35,v[x]=Math.random(),b[x]=.12+Math.random()*.22,S[x]=Math.random()*Math.PI*2;return p.setAttribute("position",new k.BufferAttribute(h,3)),p.setAttribute("aLife",new k.BufferAttribute(v,1)),p.setAttribute("aSpeed",new k.BufferAttribute(b,1)),p.setAttribute("aDrift",new k.BufferAttribute(S,1)),p},[t,n]);return be.useFrame(p=>{const h=p.clock.elapsedTime;for(let b=0;b<c.length;b++){const S=u[b]?.current;if(!S)continue;const x=c[b];x&&(S.time=h*x.speed+x.tOff,S.intensity=e*x.iMul,S.seed=x.seed,S.lean=x.lean,S.flare=x.flare,S.tint=s)}const v=a.ember.uniforms.uTime;v&&(v.value=h)}),m.useEffect(()=>()=>{f.forEach(p=>p.dispose()),d.dispose()},[f,d]),i.jsxs("group",{children:[i.jsx("mesh",{geometry:r.glow,rotation:[-Math.PI/2,0,0],position:[0,.02,0],scale:[t,t,1],children:i.jsx("meshBasicMaterial",{color:s,transparent:!0,opacity:.18,blending:k.AdditiveBlending,depthWrite:!1})}),i.jsx("mesh",{geometry:r.charcoal,material:a.charcoal,rotation:[-Math.PI/2,0,0],position:[0,.018,0],scale:[t,t,1]}),i.jsx("mesh",{geometry:r.log,material:a.log,position:[.12*l,.06*l,.05*l],rotation:[.3,0,.65],scale:l}),i.jsx("mesh",{geometry:r.log,material:a.log,position:[-.1*l,.06*l,.08*l],rotation:[.25,1.2,-.6],scale:l}),i.jsx("mesh",{geometry:r.log,material:a.log,position:[.02*l,.06*l,-.13*l],rotation:[-.2,.6,1],scale:l}),c.map((p,h)=>(()=>{const v=f[h],b=u[h];return!v||!b?null:i.jsx("mesh",{geometry:v,position:[p.x,p.y,p.z],children:i.jsx("fireMaterial",{ref:b,transparent:!0,depthWrite:!1,side:k.DoubleSide,blending:k.AdditiveBlending})},h)})()),i.jsx("points",{geometry:d,material:a.ember})]})},Xw=m.memo(Zw),Kw=`
|
|
162
|
+
attribute float aSeed;
|
|
163
|
+
attribute float aLean;
|
|
164
|
+
attribute float aFlare;
|
|
165
|
+
attribute float aIntensity;
|
|
166
|
+
attribute float aSpeed;
|
|
167
|
+
attribute float aTOff;
|
|
168
|
+
attribute float aWidth;
|
|
169
|
+
attribute float aHeight;
|
|
170
|
+
attribute vec3 aTint;
|
|
171
|
+
uniform float uTime;
|
|
172
|
+
|
|
173
|
+
varying vec2 vUv;
|
|
174
|
+
varying float vSeed;
|
|
175
|
+
varying float vLean;
|
|
176
|
+
varying float vFlare;
|
|
177
|
+
varying float vIntensity;
|
|
178
|
+
varying float vTime;
|
|
179
|
+
varying vec3 vTint;
|
|
180
|
+
|
|
181
|
+
void main() {
|
|
182
|
+
vUv = uv;
|
|
183
|
+
vSeed = aSeed;
|
|
184
|
+
vLean = aLean;
|
|
185
|
+
vFlare = aFlare;
|
|
186
|
+
vIntensity = aIntensity;
|
|
187
|
+
vTint = aTint;
|
|
188
|
+
vTime = uTime * aSpeed + aTOff;
|
|
189
|
+
|
|
190
|
+
vec3 right = vec3(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]);
|
|
191
|
+
vec3 up = vec3(0.0, 1.0, 0.0);
|
|
192
|
+
|
|
193
|
+
float px = position.x * aWidth;
|
|
194
|
+
float py = position.y * aHeight;
|
|
195
|
+
float uy = clamp(uv.y, 0.0, 1.0);
|
|
196
|
+
|
|
197
|
+
float sway = sin(vTime * 0.7 + aSeed * 3.14) * 0.04 * uy;
|
|
198
|
+
float bend = aLean * pow(uy, 1.35) * (0.35 + uy * 0.65);
|
|
199
|
+
float wobble = sin((uy * 6.0 + aSeed * 5.73) + py * 1.15) * 0.03 * uy;
|
|
200
|
+
float lift = sin(uv.x * 3.14159 + aSeed * 3.7) * 0.015 * uy;
|
|
201
|
+
|
|
202
|
+
vec3 billboarded = right * (px + bend + wobble + sway) + up * (py + lift);
|
|
203
|
+
|
|
204
|
+
vec4 center = modelMatrix * instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0);
|
|
205
|
+
center.xyz += billboarded;
|
|
206
|
+
|
|
207
|
+
gl_Position = projectionMatrix * viewMatrix * center;
|
|
208
|
+
}
|
|
209
|
+
`,qw=`
|
|
210
|
+
varying vec2 vUv;
|
|
211
|
+
varying float vSeed;
|
|
212
|
+
varying float vLean;
|
|
213
|
+
varying float vFlare;
|
|
214
|
+
varying float vIntensity;
|
|
215
|
+
varying float vTime;
|
|
216
|
+
varying vec3 vTint;
|
|
217
|
+
|
|
218
|
+
float hash(vec2 p) {
|
|
219
|
+
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
float noise(vec2 p) {
|
|
223
|
+
vec2 i = floor(p);
|
|
224
|
+
vec2 f = fract(p);
|
|
225
|
+
f = f * f * (3.0 - 2.0 * f);
|
|
226
|
+
return mix(
|
|
227
|
+
mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x),
|
|
228
|
+
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x),
|
|
229
|
+
f.y
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
float fbm(vec2 p) {
|
|
234
|
+
float v = 0.0, a = 0.5;
|
|
235
|
+
for (int i = 0; i < 3; i++) {
|
|
236
|
+
v += a * noise(p);
|
|
237
|
+
p = p * 2.1 + vec2(100.0);
|
|
238
|
+
a *= 0.5;
|
|
239
|
+
}
|
|
240
|
+
return v;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
void main() {
|
|
244
|
+
vec2 uv = vUv;
|
|
245
|
+
float time = vTime;
|
|
246
|
+
float seed = vSeed;
|
|
247
|
+
|
|
248
|
+
vec2 q = vec2(
|
|
249
|
+
fbm(vec2(uv.x * 4.2 + seed * 5.1, uv.y * 5.8 - time * 1.5)),
|
|
250
|
+
fbm(vec2(uv.x * 3.6 - seed * 3.3, uv.y * 4.6 + time * 0.6))
|
|
251
|
+
);
|
|
252
|
+
float n1 = fbm(uv * vec2(3.8, 5.6) + q * 1.5 + vec2(seed * 2.0, -time * 1.1));
|
|
253
|
+
float n2 = noise(vec2(uv.y * 9.0 + seed * 11.0, time * 4.7 + seed * 17.0));
|
|
254
|
+
|
|
255
|
+
float skew = vLean * pow(uv.y, 1.2);
|
|
256
|
+
float sway = (n1 - 0.5) * 0.28 * (1.0 - uv.y * 0.35);
|
|
257
|
+
float x = (uv.x - 0.5) - skew + sway;
|
|
258
|
+
float w = mix(0.46 * vFlare, 0.02, pow(uv.y, 0.72));
|
|
259
|
+
|
|
260
|
+
float edgeTurb = q.x * 0.07 * uv.y;
|
|
261
|
+
float body = 1.0 - smoothstep(w - edgeTurb, w + 0.06, abs(x));
|
|
262
|
+
float tongue1 = 1.0 - smoothstep(w * 0.82, w * 0.82 + 0.06, abs(x + 0.12 + q.y * 0.08));
|
|
263
|
+
float tongue2 = 1.0 - smoothstep(w * 0.68, w * 0.68 + 0.07, abs(x - 0.1 + q.x * 0.06));
|
|
264
|
+
|
|
265
|
+
float baseGlow = 1.0 - smoothstep(0.1, 0.42, distance(uv, vec2(0.5 + skew * 0.1, 0.1)));
|
|
266
|
+
float plume = max(body, max(tongue1 * 0.82, tongue2 * 0.68));
|
|
267
|
+
|
|
268
|
+
float bite = smoothstep(0.55, 1.0, n1 + uv.y * 0.4);
|
|
269
|
+
plume *= mix(1.0, 0.72, bite * smoothstep(0.2, 0.85, uv.y));
|
|
270
|
+
plume *= 1.0 - smoothstep(0.8, 1.0, uv.y);
|
|
271
|
+
plume = smoothstep(0.14, 0.9, plume + baseGlow * 0.38 + n1 * 0.2);
|
|
272
|
+
|
|
273
|
+
float core = 1.0 - smoothstep(0.01, 0.14, abs(x));
|
|
274
|
+
float fire = clamp(plume * (0.85 + 0.15 * n2), 0.0, 1.0);
|
|
275
|
+
|
|
276
|
+
vec3 deepRed = vec3(0.35, 0.02, 0.0);
|
|
277
|
+
vec3 ember = vec3(0.65, 0.08, 0.01);
|
|
278
|
+
vec3 orange = vec3(1.0, 0.38, 0.04);
|
|
279
|
+
vec3 golden = vec3(1.0, 0.65, 0.18);
|
|
280
|
+
vec3 hot = vec3(1.0, 0.88, 0.55);
|
|
281
|
+
vec3 white = vec3(1.0, 0.97, 0.92);
|
|
282
|
+
|
|
283
|
+
vec3 color = mix(deepRed, ember, smoothstep(0.02, 0.15, fire));
|
|
284
|
+
color = mix(color, orange, smoothstep(0.12, 0.35, fire));
|
|
285
|
+
color = mix(color, golden, smoothstep(0.28, 0.52, fire));
|
|
286
|
+
color = mix(color, hot, smoothstep(0.45, 0.72, fire));
|
|
287
|
+
color = mix(color, white, smoothstep(0.62, 1.0, fire * core));
|
|
288
|
+
|
|
289
|
+
float trail = smoothstep(0.8, 1.0, n2 + n1 * 0.3)
|
|
290
|
+
* smoothstep(0.18, 0.7, uv.y)
|
|
291
|
+
* smoothstep(0.35, 0.0, abs(x));
|
|
292
|
+
color += trail * vec3(1.0, 0.4, 0.06) * 0.4;
|
|
293
|
+
|
|
294
|
+
float smokeY = smoothstep(0.75, 0.98, uv.y);
|
|
295
|
+
float smoke = smokeY * q.x * 0.22 * smoothstep(0.28, 0.0, abs(x));
|
|
296
|
+
color = mix(color, vec3(0.18, 0.14, 0.12), smoke);
|
|
297
|
+
|
|
298
|
+
float alpha = smoothstep(0.06, 0.35, fire) * min(1.0, 0.5 + vIntensity * 0.26);
|
|
299
|
+
alpha += trail * 0.15 + smoke * 0.3;
|
|
300
|
+
|
|
301
|
+
if (alpha < 0.01) discard;
|
|
302
|
+
|
|
303
|
+
gl_FragColor = vec4(color * vTint * (0.62 + vIntensity * 0.48), alpha);
|
|
304
|
+
}
|
|
305
|
+
`,Qw=`
|
|
306
|
+
attribute float aLife;
|
|
307
|
+
attribute float aSpeed;
|
|
308
|
+
attribute float aDrift;
|
|
309
|
+
attribute vec3 aFirePos;
|
|
310
|
+
uniform float uTime;
|
|
311
|
+
varying float vAlpha;
|
|
312
|
+
varying float vHeat;
|
|
313
|
+
|
|
314
|
+
void main() {
|
|
315
|
+
float t = fract(uTime * aSpeed + aLife);
|
|
316
|
+
vec3 pos = position;
|
|
317
|
+
float angle = t * 8.0 + aDrift;
|
|
318
|
+
float radius = 0.08 + t * 0.2;
|
|
319
|
+
pos.y += t * t * 3.2;
|
|
320
|
+
pos.x += sin(angle) * radius;
|
|
321
|
+
pos.z += cos(angle) * radius;
|
|
322
|
+
float flicker = 0.75 + 0.25 * sin(uTime * 14.0 + aDrift * 4.0);
|
|
323
|
+
vAlpha = (1.0 - t) * (1.0 - t) * 0.9 * flicker;
|
|
324
|
+
vHeat = 1.0 - t * 0.85;
|
|
325
|
+
vec4 mvPosition = modelViewMatrix * vec4(pos + aFirePos, 1.0);
|
|
326
|
+
gl_Position = projectionMatrix * mvPosition;
|
|
327
|
+
gl_PointSize = mix(4.5, 0.6, t) * (220.0 / -mvPosition.z);
|
|
328
|
+
}
|
|
329
|
+
`,xr=[{wMul:.78,hMul:1,xMul:0,yMul:.5,z:0,seed:.17,lean:.06,flare:1,speed:1.45,tOff:0,iMul:1},{wMul:.52,hMul:.85,xMul:-.12,yMul:.43,z:.02,seed:1.31,lean:-.2,flare:.85,speed:1.9,tOff:1.7,iMul:.82},{wMul:.42,hMul:.7,xMul:.14,yMul:.36,z:-.02,seed:2.63,lean:.16,flare:.74,speed:2.2,tOff:3.4,iMul:.72}];let yr=null,vr=null,wr=null;function Jw(){return yr||(yr=new k.ShaderMaterial({vertexShader:Kw,fragmentShader:qw,uniforms:{uTime:{value:0}},transparent:!0,depthWrite:!1,side:k.DoubleSide,blending:k.AdditiveBlending})),yr}function e1(){return vr||(vr=new k.ShaderMaterial({vertexShader:Qw,fragmentShader:Sf,uniforms:{uTime:{value:0}},transparent:!0,depthWrite:!1,blending:k.AdditiveBlending})),vr}function t1(){return wr||(wr=new k.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.18,blending:k.AdditiveBlending,depthWrite:!1})),wr}const Oi=new k.Object3D,we=new k.Object3D,Uo=new k.Matrix4,pi=new k.Color;function n1(e){let t=`${e.length}`;for(const n of e)t+=`|${n.position[0]},${n.position[1]},${n.position[2]},${n.rotation},${n.intensity},${n.width},${n.height},${n.color}`;return t}const i1=m.memo(function({fires:t}){const n=m.useRef(null),o=m.useRef(null),s=m.useRef(null),r=m.useRef(null),a=m.useRef(null),l=t.length,c=l*xr.length,u=l*2,f=_f(),d=jf(),p=Jw(),h=t1(),v=e1(),b=m.useMemo(()=>n1(t),[t]),S=m.useRef({signature:b,fires:t});S.current.signature!==b&&(S.current={signature:b,fires:t});const x=S.current.fires,_=m.useMemo(()=>{if(l===0)return null;const y=new k.PlaneGeometry(1,1),w=new Float32Array(c),j=new Float32Array(c),N=new Float32Array(c),B=new Float32Array(c),z=new Float32Array(c),W=new Float32Array(c),D=new Float32Array(c),E=new Float32Array(c),G=new Float32Array(c*3);let T=0;for(const O of x){pi.set(O.color);for(const P of xr)w[T]=P.seed,j[T]=P.lean,N[T]=P.flare,B[T]=O.intensity*P.iMul,z[T]=P.speed,W[T]=P.tOff,D[T]=O.width*P.wMul,E[T]=O.height*P.hMul,G[T*3]=pi.r,G[T*3+1]=pi.g,G[T*3+2]=pi.b,T++}return y.setAttribute("aSeed",new k.InstancedBufferAttribute(w,1)),y.setAttribute("aLean",new k.InstancedBufferAttribute(j,1)),y.setAttribute("aFlare",new k.InstancedBufferAttribute(N,1)),y.setAttribute("aIntensity",new k.InstancedBufferAttribute(B,1)),y.setAttribute("aSpeed",new k.InstancedBufferAttribute(z,1)),y.setAttribute("aTOff",new k.InstancedBufferAttribute(W,1)),y.setAttribute("aWidth",new k.InstancedBufferAttribute(D,1)),y.setAttribute("aHeight",new k.InstancedBufferAttribute(E,1)),y.setAttribute("aTint",new k.InstancedBufferAttribute(G,3)),y},[b,x,l,c]),g=m.useMemo(()=>{if(l===0)return null;const y=18,w=l*y,j=new Float32Array(w*3),N=new Float32Array(w),B=new Float32Array(w),z=new Float32Array(w),W=new Float32Array(w*3);for(let E=0;E<l;E++){const G=x[E],T=E*y;for(let O=0;O<y;O++){const P=T+O;j[P*3]=(Math.random()-.5)*G.width*.35,j[P*3+1]=Math.random()*G.height*.2,j[P*3+2]=(Math.random()-.5)*G.width*.35,N[P]=Math.random(),B[P]=.12+Math.random()*.22,z[P]=Math.random()*Math.PI*2,W[P*3]=G.position[0],W[P*3+1]=G.position[1],W[P*3+2]=G.position[2]}}const D=new k.BufferGeometry;return D.setAttribute("position",new k.BufferAttribute(j,3)),D.setAttribute("aLife",new k.BufferAttribute(N,1)),D.setAttribute("aSpeed",new k.BufferAttribute(B,1)),D.setAttribute("aDrift",new k.BufferAttribute(z,1)),D.setAttribute("aFirePos",new k.BufferAttribute(W,3)),D.computeBoundingSphere(),D},[b,x,l]);return m.useLayoutEffect(()=>{if(l===0)return;const y=n.current;if(!y)return;let w=0;for(const j of t){const N=Math.cos(j.rotation),B=Math.sin(j.rotation);for(const z of xr){const W=j.width*z.xMul,D=z.z;we.position.set(j.position[0]+W*N+D*B,j.position[1]+j.height*z.yMul,j.position[2]+D*N-W*B),we.rotation.set(0,0,0),we.scale.set(1,1,1),we.updateMatrix(),y.setMatrixAt(w++,we.matrix)}}y.count=c,y.instanceMatrix.needsUpdate=!0},[t,l,c]),m.useLayoutEffect(()=>{if(l===0)return;const y=o.current;if(!y)return;let w=0;for(const j of t){Oi.position.set(j.position[0],j.position[1],j.position[2]),Oi.rotation.set(0,j.rotation,0),Oi.updateMatrix();const N=Math.max(.4,(j.width+j.height*.5)/1.5);we.position.set(.12*N,.06*N,.05*N),we.rotation.set(.3,0,.65),we.scale.set(N,N,N),we.updateMatrix(),Uo.multiplyMatrices(Oi.matrix,we.matrix),y.setMatrixAt(w++,Uo),we.position.set(-.1*N,.06*N,.08*N),we.rotation.set(.25,1.2,-.6),we.scale.set(N,N,N),we.updateMatrix(),Uo.multiplyMatrices(Oi.matrix,we.matrix),y.setMatrixAt(w++,Uo)}y.count=u,y.instanceMatrix.needsUpdate=!0},[t,l,u]),m.useLayoutEffect(()=>{if(l===0)return;const y=s.current;if(y){for(let w=0;w<l;w++){const j=t[w];we.position.set(j.position[0],j.position[1]+.018,j.position[2]),we.rotation.set(-Math.PI/2,0,j.rotation),we.scale.set(j.width,j.width,1),we.updateMatrix(),y.setMatrixAt(w,we.matrix)}y.count=l,y.instanceMatrix.needsUpdate=!0}},[t,l]),m.useLayoutEffect(()=>{if(l===0)return;const y=r.current;if(y){for(let w=0;w<l;w++){const j=t[w];we.position.set(j.position[0],j.position[1]+.02,j.position[2]),we.rotation.set(-Math.PI/2,0,j.rotation),we.scale.set(j.width,j.width,1),we.updateMatrix(),y.setMatrixAt(w,we.matrix),pi.set(j.color),y.setColorAt(w,pi)}y.count=l,y.instanceMatrix.needsUpdate=!0,y.instanceColor&&(y.instanceColor.needsUpdate=!0)}},[t,l]),be.useFrame(y=>{const w=y.clock.elapsedTime;p.uniforms.uTime.value=w,v.uniforms.uTime.value=w,h.opacity=.16+Math.sin(w*2.5)*.06}),m.useEffect(()=>()=>{_?.dispose(),g?.dispose()},[_,g]),l===0?null:i.jsxs(i.Fragment,{children:[_&&i.jsx("instancedMesh",{ref:n,args:[_,p,c],frustumCulled:!1}),i.jsx("instancedMesh",{ref:o,args:[f.log,d.log,u]}),i.jsx("instancedMesh",{ref:s,args:[f.charcoal,d.charcoal,l]}),i.jsx("instancedMesh",{ref:r,args:[f.glow,h,l]}),g&&i.jsx("points",{ref:a,geometry:g,material:v,frustumCulled:!1})]})});var o1=`precision highp float;
|
|
330
|
+
|
|
331
|
+
uniform sampler2D map;\r
|
|
332
|
+
uniform float transmission;\r
|
|
333
|
+
uniform float envMapIntensity;
|
|
334
|
+
|
|
335
|
+
varying vec2 vUv;
|
|
336
|
+
|
|
337
|
+
void main() {\r
|
|
338
|
+
vec4 texColor = texture2D(map, vUv);\r
|
|
339
|
+
float alpha = texColor.a * (1.0 - transmission);\r
|
|
340
|
+
if (alpha < 0.01) discard;\r
|
|
341
|
+
gl_FragColor = vec4(texColor.rgb * envMapIntensity, alpha);\r
|
|
342
|
+
}`,s1=`precision highp float;
|
|
343
|
+
|
|
344
|
+
uniform float time;\r
|
|
345
|
+
uniform float windStrength;
|
|
346
|
+
|
|
347
|
+
varying vec2 vUv;
|
|
348
|
+
|
|
349
|
+
void main() {\r
|
|
350
|
+
vUv = uv;\r
|
|
351
|
+
vec3 pos = position;
|
|
352
|
+
|
|
353
|
+
float fixGradient = uv.x * uv.x;
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
float phase = 0.0;\r
|
|
357
|
+
#ifdef USE_INSTANCING\r
|
|
358
|
+
phase = instanceMatrix[3][0] * 0.3 + instanceMatrix[3][2] * 0.5;\r
|
|
359
|
+
#endif
|
|
360
|
+
|
|
361
|
+
float wave1 = sin(uv.x * 4.0 + time * 1.0 + phase) * 0.12;\r
|
|
362
|
+
float wave2 = sin(uv.x * 7.0 + time * 1.7 + 1.3 + phase * 0.7) * 0.06;\r
|
|
363
|
+
float wave3 = sin(uv.x * 13.0 + time * 2.9 + 2.7 + phase * 1.3) * 0.025;
|
|
364
|
+
|
|
365
|
+
float verticalRipple = sin(uv.y * 6.0 + time * 0.8 + phase * 0.4) * 0.02 * fixGradient;
|
|
366
|
+
|
|
367
|
+
float displacement = (wave1 + wave2 + wave3) * fixGradient * windStrength;\r
|
|
368
|
+
pos.z += displacement + verticalRipple;\r
|
|
369
|
+
pos.y -= fixGradient * 0.03 * windStrength;
|
|
370
|
+
|
|
371
|
+
vec4 mvPosition = vec4(pos, 1.0);\r
|
|
372
|
+
#ifdef USE_INSTANCING\r
|
|
373
|
+
mvPosition = instanceMatrix * mvPosition;\r
|
|
374
|
+
#endif\r
|
|
375
|
+
gl_Position = projectionMatrix * modelViewMatrix * mvPosition;\r
|
|
376
|
+
}`;const r1=pt.shaderMaterial({map:null,time:0,windStrength:1,transmission:.05,envMapIntensity:1},s1,o1);be.extend({FlagMaterial:r1});let $i=null;function a1(){if($i)return $i;const e=document.createElement("canvas");e.width=4,e.height=4;const t=e.getContext("2d");return t.fillStyle="#cc2222",t.fillRect(0,0,4,4),$i=new k.CanvasTexture(e),$i.needsUpdate=!0,$i}const l1=new k.MeshStandardMaterial({color:"#8B4513"}),c1=new k.MeshStandardMaterial({color:"#444444",metalness:.6,roughness:.3}),fe=new k.Object3D;function u1(e){const t=[];for(const n of e)switch(R.FLAG_STYLE_META[n.style].poleType){case"side":{const s=n.flagHeight+2.5;fe.position.set(n.x,n.y+s/2,n.z),fe.scale.set(1,s,1),fe.updateMatrix(),t.push(fe.matrix.clone());break}case"top":{const s=n.flagHeight+1.5;fe.position.set(n.x,n.y+s+.025,n.z),fe.rotation.set(0,0,Math.PI/2),fe.scale.set(1,n.flagWidth,1),fe.updateMatrix(),t.push(fe.matrix.clone()),fe.rotation.set(0,0,0);break}case"frame":{const s=n.flagHeight+.5;fe.position.set(n.x-n.flagWidth/2,n.y+s/2,n.z),fe.scale.set(1,s,1),fe.updateMatrix(),t.push(fe.matrix.clone()),fe.position.set(n.x+n.flagWidth/2,n.y+s/2,n.z),fe.updateMatrix(),t.push(fe.matrix.clone()),fe.position.set(n.x,n.y+s,n.z),fe.rotation.set(0,0,Math.PI/2),fe.scale.set(1,n.flagWidth+.05,1),fe.updateMatrix(),t.push(fe.matrix.clone()),fe.rotation.set(0,0,0),fe.position.set(n.x,n.y+.025,n.z),fe.rotation.set(0,0,Math.PI/2),fe.scale.set(1,n.flagWidth+.05,1),fe.updateMatrix(),t.push(fe.matrix.clone()),fe.rotation.set(0,0,0);break}case"both":{const s=n.flagHeight+2.5;fe.position.set(n.x-n.flagWidth/2,n.y+s/2,n.z),fe.scale.set(1,s,1),fe.updateMatrix(),t.push(fe.matrix.clone()),fe.position.set(n.x+n.flagWidth/2,n.y+s/2,n.z),fe.updateMatrix(),t.push(fe.matrix.clone());break}}return t}function d1({entries:e}){const t=m.useRef(null),n=m.useMemo(()=>new k.BoxGeometry(.05,1,.05),[]),o=m.useMemo(()=>u1(e),[e]),s=o.length,r=m.useMemo(()=>Math.max(1,s),[s]),l=e.some(c=>c.style==="panel")?c1:l1;return m.useLayoutEffect(()=>{const c=t.current;if(c){c.count=s;for(let u=0;u<s;u++){const f=o[u];f&&c.setMatrixAt(u,f)}c.instanceMatrix.needsUpdate=!0,c.computeBoundingSphere()}},[o,s]),m.useEffect(()=>()=>{n.dispose()},[n]),s===0?null:i.jsx("instancedMesh",{ref:t,args:[n,l,r],frustumCulled:!0})}function Mf({entries:e,windStrength:t,texture:n}){const o=m.useRef(null),s=m.useRef(null),r=m.useRef(0),a=e.length,l=m.useMemo(()=>Math.max(1,a),[a]),c=e[0]?.flagWidth??1.5,u=e[0]?.flagHeight??1,f=t>.6?12:t>0?8:1,d=t>.6?6:t>0?4:1,p=m.useMemo(()=>new k.PlaneGeometry(c,u,f,d),[c,u,f,d]);return m.useLayoutEffect(()=>{const h=o.current;if(h){h.count=a;for(let v=0;v<a;v++){const b=e[v];if(!b)continue;const S=R.FLAG_STYLE_META[b.style];let x=b.x,_=b.y;switch(S.poleType){case"side":x=b.x+b.flagWidth/2,_=b.y+b.flagHeight+2.5-b.flagHeight/2;break;case"top":_=b.y+b.flagHeight+1.5-b.flagHeight/2;break;case"frame":_=b.y+(b.flagHeight+.5)/2+.025;break;case"both":_=b.y+b.flagHeight+2.5-b.flagHeight/2;break}fe.position.set(x,_,b.z),fe.scale.set(b.flagWidth/c,b.flagHeight/u,1),fe.updateMatrix(),h.setMatrixAt(v,fe.matrix)}h.instanceMatrix.needsUpdate=!0,h.computeBoundingSphere()}},[e,a,c,u]),be.useFrame((h,v)=>{if(r.current+=Math.max(0,v),r.current<1/30)return;r.current=0;const b=s.current;b.time=h.clock.elapsedTime*5,b.windStrength=t}),m.useEffect(()=>()=>{p.dispose()},[p]),a===0?null:i.jsx("instancedMesh",{ref:o,args:[p,void 0,l],frustumCulled:!0,children:i.jsx("flagMaterial",{ref:s,map:n,transmission:.05,windStrength:t,envMapIntensity:1,side:k.DoubleSide,transparent:!0})})}function f1({entries:e,textureUrl:t,windStrength:n}){const o=pt.useTexture(t);return i.jsx(Mf,{entries:e,windStrength:n,texture:o})}function p1({entries:e,windStrength:t}){const n=m.useMemo(()=>a1(),[]);return i.jsx(Mf,{entries:e,windStrength:t,texture:n})}function h1({entries:e,textureUrl:t,windStrength:n}){return t?i.jsx(f1,{entries:e,textureUrl:t,windStrength:n}):i.jsx(p1,{entries:e,windStrength:n})}const m1=m.memo(function({flags:t}){const n=m.useMemo(()=>t.map(s=>({x:s.position.x,y:s.position.y,z:s.position.z,flagWidth:s.config?.flagWidth??1.5,flagHeight:s.config?.flagHeight??1,style:s.config?.flagStyle??"flag",textureUrl:s.config?.flagTexture??""})),[t]),o=m.useMemo(()=>{const s=new Map;for(const r of n){const a=`${r.textureUrl}|${r.style}`;let l=s.get(a);l||(l=[],s.set(a,l)),l.push(r)}return Array.from(s.entries())},[n]);return i.jsxs(i.Fragment,{children:[i.jsx(d1,{entries:n}),o.map(([s,r])=>{const a=r[0];if(!a)return null;const l=a.style,c=R.FLAG_STYLE_META[l].windStrength,u=a.textureUrl;return i.jsx(h1,{entries:r,textureUrl:u,windStrength:c},s)})]})});class g1 extends m.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidUpdate(t){t.children!==this.props.children&&this.state.failed&&this.setState({failed:!1})}render(){return this.state.failed?this.props.fallback:this.props.children}}function b1({url:e}){const{scene:t}=pt.useGLTF(e),n=m.useMemo(()=>ua.SkeletonUtils.clone(t),[t]);return i.jsx("primitive",{object:n})}function pe(e,t,n,o){return i.jsxs("mesh",{position:t,castShadow:!0,receiveShadow:!0,children:[i.jsx("boxGeometry",{args:e}),i.jsx("meshStandardMaterial",{color:n,roughness:.75,metalness:.04})]},o)}function Sr(e,t,n,o){return i.jsxs("mesh",{position:t,castShadow:!0,receiveShadow:!0,children:[i.jsx("cylinderGeometry",{args:e}),i.jsx("meshStandardMaterial",{color:n,roughness:.7,metalness:.05})]},o)}function x1({kind:e="generic",color:t="#9b7653"}){const n=new k.Color(t).multiplyScalar(.72).getStyle(),o=new k.Color(t).lerp(new k.Color("#ffffff"),.35).getStyle();return e==="door"?i.jsxs("group",{children:[pe([.9,1.9,.12],[0,.95,0],t,"panel"),pe([.08,2.05,.16],[-.5,1.02,0],n,"left-frame"),pe([.08,2.05,.16],[.5,1.02,0],n,"right-frame"),Sr([.045,.045,.06,12],[.32,.95,.08],"#f3c969","knob")]}):e==="window"?i.jsxs("group",{children:[pe([1.1,.08,.12],[0,1.3,0],n,"top"),pe([1.1,.08,.12],[0,.55,0],n,"bottom"),pe([.08,.82,.12],[-.55,.92,0],n,"left"),pe([.08,.82,.12],[.55,.92,0],n,"right"),pe([.9,.62,.04],[0,.92,.02],t,"glass")]}):e==="fence"?i.jsxs("group",{children:[pe([.16,1,.16],[-.65,.5,0],n,"post-a"),pe([.16,1,.16],[.65,.5,0],n,"post-b"),pe([1.5,.16,.12],[0,.72,0],t,"rail-a"),pe([1.5,.16,.12],[0,.36,0],t,"rail-b")]}):e==="lamp"?i.jsxs("group",{children:[Sr([.06,.08,1.5,12],[0,.75,0],n,"pole"),Sr([.28,.18,.35,16],[0,1.55,0],t,"shade"),i.jsx("pointLight",{position:[0,1.55,0],intensity:.65,distance:5,color:o})]}):e==="chair"?i.jsxs("group",{children:[pe([.8,.12,.75],[0,.55,0],t,"seat"),pe([.8,.9,.12],[0,1,.33],n,"back"),pe([.09,.55,.09],[-.3,.28,-.25],n,"leg-a"),pe([.09,.55,.09],[.3,.28,-.25],n,"leg-b"),pe([.09,.55,.09],[-.3,.28,.25],n,"leg-c"),pe([.09,.55,.09],[.3,.28,.25],n,"leg-d")]}):e==="table"||e==="crafting"?i.jsxs("group",{children:[pe([1.4,.16,.9],[0,.8,0],t,"top"),pe([.12,.75,.12],[-.52,.38,-.3],n,"leg-a"),pe([.12,.75,.12],[.52,.38,-.3],n,"leg-b"),pe([.12,.75,.12],[-.52,.38,.3],n,"leg-c"),pe([.12,.75,.12],[.52,.38,.3],n,"leg-d"),e==="crafting"&&pe([.55,.12,.12],[.22,.96,0],o,"tool")]}):e==="bed"?i.jsxs("group",{children:[pe([1.3,.35,2],[0,.35,0],t,"base"),pe([1.25,.18,1.45],[0,.62,.2],o,"blanket"),pe([1.25,.55,.14],[0,.72,.92],n,"headboard")]}):e==="storage"||e==="mailbox"?i.jsxs("group",{children:[pe([1,.8,.7],[0,.4,0],t,"body"),pe([1.08,.12,.78],[0,.86,0],n,"lid"),pe([.38,.08,.04],[0,.46,.37],o,"handle")]}):e==="shop"?i.jsxs("group",{children:[pe([1.7,.18,.9],[0,.72,0],t,"counter"),pe([1.9,.16,1],[0,1.55,0],o,"awning"),pe([.08,1.45,.08],[-.82,.8,-.35],n,"post-a"),pe([.08,1.45,.08],[.82,.8,-.35],n,"post-b")]}):pe([1,1,1],[0,.5,0],t,"generic")}function y1({url:e,label:t,fallbackKind:n,scale:o=1,color:s}){const r=i.jsx(x1,{kind:n,color:s});return m.useEffect(()=>{e&&pt.useGLTF.preload(e)},[e]),i.jsx("group",{name:t??"building-model-object",scale:[o,o,o],children:e?i.jsx(g1,{fallback:r,children:i.jsx(m.Suspense,{fallback:r,children:i.jsx(b1,{url:e})})}):r})}function ae(e){const t=Math.sin(e*127.1+311.7)*43758.5453123;return t-Math.floor(t)}function $a(e,t,n){e[t]=n.r,e[t+1]=n.g,e[t+2]=n.b}let _r=null,jr=null,Mr=null;function Cf(){return _r||(_r={limb:new k.CylinderGeometry(.5,1,1,8,1,!1),canopyCluster:new k.IcosahedronGeometry(1,1),canopyCore:new k.SphereGeometry(1,10,8),trunkTop:new k.SphereGeometry(1,10,8)}),_r}function Nf(e){return e?(Mr||(Mr={bark:R.createToonMaterial({color:"#5e3d30",steps:3}),barkDark:R.createToonMaterial({color:"#3f271e",steps:3}),blossomShell:R.createToonMaterial({color:"#f7bfd2",transparent:!0,opacity:.78,steps:4,depthWrite:!1}),blossomCore:R.createToonMaterial({color:"#ffe6f0",transparent:!0,opacity:.6,steps:4,depthWrite:!1})}),Mr):(jr||(jr={bark:new k.MeshStandardMaterial({color:"#5e3d30",roughness:.95,metalness:.02}),barkDark:new k.MeshStandardMaterial({color:"#3f271e",roughness:1,metalness:.01}),blossomShell:new k.MeshStandardMaterial({color:"#f7bfd2",roughness:.92,metalness:0,transparent:!0,opacity:.68}),blossomCore:new k.MeshStandardMaterial({color:"#ffe6f0",roughness:.84,metalness:0,transparent:!0,opacity:.5})}),jr)}function Tf(e,t,n){const o=n==="sparse"?5:0,s=Math.max(8,Math.min(20,Math.round(10+e*4+o)));return Array.from({length:s},(r,a)=>{const l=19.3+a*13.17+e*5.1,c=n==="conifer"||n==="column",u=n==="sparse",f=c?.58:u?1.24:n==="weeping"?.82:1,d=(1.05+ae(l+1)*1.35)*e*f,p=ae(l+2)>.5?1:-1;return{pivotY:t*(c?.28+ae(l+3)*.52:.38+ae(l+3)*.42),length:d,radius:(.08+ae(l+4)*.045)*e*(u?.82:1),yaw:ae(l+5)*Math.PI*2,bend:(c?.38:.58+ae(l+6)*.34)*p,lean:(ae(l+7)-.5)*(c?.18:.34),twigLength:d*(u?.5:.34+ae(l+8)*.26),twigYaw:(ae(l+9)-.5)*(c?.48:.95),twigLean:(n==="weeping"?-.55:.25+ae(l+10)*.38)*-p}})}function If(e){return Array.from({length:5},(t,n)=>{const o=101.2+n*8.31+e*3.7;return{angle:n/5*Math.PI*2+(ae(o)-.5)*.4,length:(.52+ae(o+1)*.42)*e,radius:(.09+ae(o+2)*.04)*e,spread:(.8+ae(o+3)*.28)*(ae(o+4)>.5?1:-1)}})}function Ef(e,t,n,o,s){const r=Math.max(6,Math.min(18,Math.round((s==="sparse"?6:9)+e*4)));return Array.from({length:r},(a,l)=>{const c=220.4+l*10.73+e*4.4,u=ae(c)*Math.PI*2,f=r<=1?0:l/(r-1),d=Math.max(.12,1-f),p=s==="conifer"||s==="column",h=p?n*d*(s==="column"?.34:.58)*(.55+ae(c+1)*.45):n*(.18+ae(c+1)*.72),v=(.7+ae(c+5)*.9)*e*(p?d:1),b=(.52+ae(c+6)*.56)*e*(s==="weeping"?1.4:1),S=(.66+ae(c+7)*.88)*e*(p?d:1),x=p?t*.42+o*(.06+f*.9):s==="weeping"?t*(.46+ae(c+3)*.18)+ae(c+4)*o*.32:t*(.64+ae(c+3)*.22)+ae(c+4)*o*.42;return{position:[Math.cos(u)*h,x,Math.sin(u)*h*(.86+ae(c+2)*.22)],rotation:[(ae(c+8)-.5)*.55,ae(c+9)*Math.PI*2,(ae(c+10)-.5)*.55],outerScale:[s==="column"?v*.62:v,p?b*.88:b,s==="column"?S*.62:S],innerScale:[v*.7,b*.72,S*.7]}})}const Vo=new k.Object3D,at=new k.Object3D,eo=new k.Matrix4,ws=new k.Matrix4,pn=new k.Color;function gn(e,t,n,o,s,r,a,l){Vo.position.set(o[0],o[1],o[2]),Vo.rotation.set(s[0],s[1],s[2]),Vo.updateMatrix(),at.position.set(r[0],r[1],r[2]),at.rotation.set(a?a[0]:0,a?a[1]:0,a?a[2]:0),at.scale.set(l[0],l[1],l[2]),at.updateMatrix(),eo.multiplyMatrices(Vo.matrix,at.matrix),n&&(ws.makeTranslation(n[0],n[1]+.02,n[2]),eo.premultiply(ws)),e.setMatrixAt(t,eo)}function Ss(e,t,n,o,s,r){at.position.set(o[0],o[1],o[2]),at.rotation.set(s[0],s[1],s[2]),at.scale.set(r[0],r[1],r[2]),at.updateMatrix(),n?(ws.makeTranslation(n[0],n[1]+.02,n[2]),eo.multiplyMatrices(ws,at.matrix),e.setMatrixAt(t,eo)):e.setMatrixAt(t,at.matrix)}function Af(e,t,n,o,s,r,a,l,c,u,f="round",d){const p=d?d.clone().multiplyScalar(.85):new k.Color("#f3a1bf"),h=d?d.clone().lerp(new k.Color("#ffffff"),.6):new k.Color("#fff1f6"),v=new k.Color;for(let b=0;b<o;b++){const S=330.7+b*17.13,x=ae(S)*Math.PI*2,_=Math.pow(ae(S+4),f==="conifer"||f==="column"?.92:.72),g=f==="conifer"?Math.max(.08,1-_*.92):f==="column"?.32+Math.max(.08,1-_)*.24:f==="weeping"?.82+_*.28:1,y=r*g*(.18+Math.sqrt(ae(S+1))*.86),w=(n+b)*3;e[w]=Math.cos(x)*y*(.82+ae(S+2)*.22)+l,e[w+1]=s*(f==="weeping"?.46:.58)+_*a+(ae(S+5)-.5)*.36+c,e[w+2]=Math.sin(x)*y*(.8+ae(S+3)*.26)+u,v.copy(p).lerp(h,.28+ae(S+6)*.72).multiplyScalar(.92+ae(S+7)*.18),$a(t,w,v)}}function kf(e,t,n,o,s,r,a,l,c){const u=c?c.clone().multiplyScalar(.9):new k.Color("#f7cadb"),f=c?c.clone().lerp(new k.Color("#ffffff"),.7):new k.Color("#fff3f8"),d=new k.Color;for(let p=0;p<o;p++){const h=510.9+p*9.41,v=ae(h)*Math.PI*2,b=s*(.18+Math.pow(ae(h+1),.6)*.92),S=(n+p)*3;e[S]=Math.cos(v)*b+r,e[S+1]=.035+ae(h+2)*.03+a,e[S+2]=Math.sin(v)*b+l,d.copy(u).lerp(f,.35+ae(h+3)*.65).multiplyScalar(.9+ae(h+4)*.12),$a(t,S,d)}}function Bf(e,t,n,o,s,r,a,l,c,u,f,d,p,h,v,b){const S=b?b.clone().multiplyScalar(.88):new k.Color("#f8b3ca"),x=b?b.clone().lerp(new k.Color("#ffffff"),.65):new k.Color("#fff5fa"),_=new k.Color;for(let g=0;g<l;g++){const y=740.6+g*6.83,w=ae(y)*Math.PI*2,j=u*(.1+ae(y+1)*.72),N=a+g,B=N*3;e[B]=Math.cos(w)*j,e[B+1]=c*.66+ae(y+2)*f*.88,e[B+2]=Math.sin(w)*j;const z=N*4;n[z]=.12+ae(y+3)*.18,n[z+1]=ae(y+4),n[z+2]=.08+ae(y+5)*.18,n[z+3]=1+ae(y+6)*1.9;const W=N*2;o[W]=(ae(y+7)-.5)*.8,o[W+1]=(ae(y+8)-.5)*.8,s&&(s[B]=p,s[B+1]=h,s[B+2]=v),r&&(r[N]=.11*d),_.copy(S).lerp(x,.2+ae(y+9)*.8).multiplyScalar(.94+ae(y+10)*.12),$a(t,B,_)}}function _s(e,t,n=!1){const o=new k.BufferGeometry;return o.setAttribute("position",new k.Float32BufferAttribute(e,3)),o.setAttribute("color",new k.Float32BufferAttribute(t,3)),n&&o.computeBoundingBox(),o.computeBoundingSphere(),o}const hi=new k.Color("#f7bfd2"),Yo=new k.Color("#5e3d30"),v1=new k.Color("#ffffff"),w1={sakura:{canopyColor:"#f7bfd2",bark:"#5e3d30",shape:"round",crownRadius:1,crownHeight:1,trunkHeight:1,canopyDensity:1,falling:1,ground:1},oak:{canopyColor:"#4f8f3a",bark:"#6b4a2a",shape:"round",crownRadius:1.12,crownHeight:.86,trunkHeight:1,canopyDensity:1,falling:.08,ground:.35},pine:{canopyColor:"#2f6f45",bark:"#5b3b24",shape:"conifer",crownRadius:.92,crownHeight:1.5,trunkHeight:1.18,canopyDensity:.82,falling:.02,ground:.12},maple:{canopyColor:"#d05a2d",bark:"#654126",shape:"oval",crownRadius:1.02,crownHeight:.78,trunkHeight:.96,canopyDensity:1,falling:.45,ground:.8},birch:{canopyColor:"#87b95a",bark:"#e8e1cf",shape:"oval",crownRadius:.82,crownHeight:1.08,trunkHeight:1.14,canopyDensity:.86,falling:.12,ground:.35},willow:{canopyColor:"#7fae55",bark:"#6a5635",shape:"weeping",crownRadius:1.2,crownHeight:1.28,trunkHeight:.88,canopyDensity:1.08,falling:.2,ground:.45},cypress:{canopyColor:"#315f3a",bark:"#59402d",shape:"column",crownRadius:.78,crownHeight:1.65,trunkHeight:1.24,canopyDensity:.74,falling:.02,ground:.12},dead:{canopyColor:"#8b7a61",bark:"#4b392c",shape:"sparse",crownRadius:.7,crownHeight:.7,trunkHeight:1.08,canopyDensity:.2,falling:0,ground:.12}};function S1(e){return e.map(t=>{const n=w1[t.treeKind??"sakura"],o=k.MathUtils.clamp(t.size/4,.95,1.85),s=3.8*o*n.trunkHeight,r=(1.65*o+Math.min(t.size*.08,.55))*n.crownRadius,a=(2.15*o+Math.min(t.size*.04,.35))*n.crownHeight;return{pos:t.position,scale:o,trunkHeight:s,crownRadius:r,crownHeight:a,shape:n.shape,branches:Tf(o,s,n.shape),roots:If(o),clusters:Ef(o,s,r,a,n.shape),canopyN:Math.round(Math.max(180,Math.min(420,Math.round(210+o*95)))*n.canopyDensity),groundN:Math.round(Math.max(44,Math.min(120,Math.round(54+o*26)))*n.ground),fallingN:Math.round(Math.max(52,Math.min(132,Math.round(62+o*30)))*n.falling),blossom:t.blossomColor?new k.Color(t.blossomColor):new k.Color(n.canopyColor),bark:t.barkColor?new k.Color(t.barkColor):new k.Color(n.bark)}})}const _1=`
|
|
377
|
+
attribute vec3 color;
|
|
378
|
+
attribute vec4 aParams1;
|
|
379
|
+
attribute vec2 aParams2;
|
|
380
|
+
attribute vec3 aTreePos;
|
|
381
|
+
attribute float aPointScale;
|
|
382
|
+
|
|
383
|
+
uniform float uTime;
|
|
384
|
+
uniform float uScale;
|
|
385
|
+
uniform float uWind;
|
|
386
|
+
|
|
387
|
+
varying vec3 vColor;
|
|
388
|
+
|
|
389
|
+
void main() {
|
|
390
|
+
float cycle = fract(uTime * aParams1.x + aParams1.y);
|
|
391
|
+
float drift = 1.0 - pow(cycle, 1.22);
|
|
392
|
+
float w = uTime * aParams1.w + aParams1.y * 6.28318;
|
|
393
|
+
|
|
394
|
+
vec3 localPos = vec3(
|
|
395
|
+
position.x + sin(w) * aParams1.z * uWind + aParams2.x * cycle * uWind,
|
|
396
|
+
0.18 + position.y * drift + sin(w * 0.6) * 0.06,
|
|
397
|
+
position.z + cos(w * 0.82) * aParams1.z * 0.72 * uWind + aParams2.y * cycle * uWind
|
|
398
|
+
);
|
|
399
|
+
|
|
400
|
+
vColor = color;
|
|
401
|
+
vec4 mvPosition = modelViewMatrix * vec4(localPos + aTreePos, 1.0);
|
|
402
|
+
gl_Position = projectionMatrix * mvPosition;
|
|
403
|
+
gl_PointSize = aPointScale * (uScale / -mvPosition.z);
|
|
404
|
+
}
|
|
405
|
+
`,Pf=`
|
|
406
|
+
uniform float uOpacity;
|
|
407
|
+
varying vec3 vColor;
|
|
408
|
+
void main() {
|
|
409
|
+
vec2 d = gl_PointCoord - vec2(0.5);
|
|
410
|
+
float r2 = dot(d, d);
|
|
411
|
+
if (r2 > 0.25) discard;
|
|
412
|
+
gl_FragColor = vec4(vColor, uOpacity * exp(-r2 * 8.0));
|
|
413
|
+
}
|
|
414
|
+
`;function Rf({trees:e,toon:t}){const n=m.useRef(null),o=m.useRef(null),s=m.useRef(null),r=m.useRef(null),a=m.useRef(null),l=m.useRef(null),c=t??R.getDefaultToonMode(),u=Cf(),f=Nf(c),d=m.useMemo(()=>S1(e),[e]),p=m.useMemo(()=>{let g=0,y=0,w=0,j=0,N=0,B=0;for(const z of d)g+=z.branches.length+1,y+=z.roots.length+z.branches.length,w+=z.clusters.length,j+=z.canopyN,N+=z.groundN,B+=z.fallingN;return{bark:g,dark:y,top:d.length,cluster:w,canopy:j,ground:N,falling:B}},[d]),h=m.useMemo(()=>d.length===0?1:d.reduce((g,y)=>g+y.scale,0)/d.length,[d]),v=m.useMemo(()=>d.some(g=>g.blossom!==hi||g.bark!==Yo),[d]),b=m.useMemo(()=>{const g=new Float32Array(p.canopy*3),y=new Float32Array(p.canopy*3);let w=0;for(const j of d){const N=j.blossom!==hi?j.blossom:void 0;Af(g,y,w,j.canopyN,j.trunkHeight,j.crownRadius,j.crownHeight,j.pos[0],j.pos[1]+.02,j.pos[2],j.shape,N),w+=j.canopyN}return _s(g,y)},[d,p.canopy]),S=m.useMemo(()=>{const g=new Float32Array(p.ground*3),y=new Float32Array(p.ground*3);let w=0;for(const j of d){const N=j.blossom!==hi?j.blossom:void 0;kf(g,y,w,j.groundN,j.crownRadius,j.pos[0],j.pos[1]+.02,j.pos[2],N),w+=j.groundN}return _s(g,y)},[d,p.ground]),x=m.useMemo(()=>{const g=p.falling,y=new Float32Array(g*3),w=new Float32Array(g*3),j=new Float32Array(g*4),N=new Float32Array(g*2),B=new Float32Array(g*3),z=new Float32Array(g);let W=0;for(const E of d){const G=E.blossom!==hi?E.blossom:void 0;Bf(y,w,j,N,B,z,W,E.fallingN,E.trunkHeight,E.crownRadius,E.crownHeight,E.scale,E.pos[0],E.pos[1]+.02,E.pos[2],G),W+=E.fallingN}const D=new k.BufferGeometry;return D.setAttribute("position",new k.Float32BufferAttribute(y,3)),D.setAttribute("color",new k.Float32BufferAttribute(w,3)),D.setAttribute("aParams1",new k.Float32BufferAttribute(j,4)),D.setAttribute("aParams2",new k.Float32BufferAttribute(N,2)),D.setAttribute("aTreePos",new k.Float32BufferAttribute(B,3)),D.setAttribute("aPointScale",new k.Float32BufferAttribute(z,1)),D.computeBoundingSphere(),D},[d,p.falling]),_=m.useMemo(()=>new k.ShaderMaterial({uniforms:{uTime:{value:0},uScale:{value:1},uOpacity:{value:.88},uWind:{value:1}},vertexShader:_1,fragmentShader:Pf,transparent:!0,depthWrite:!1}),[]);return m.useLayoutEffect(()=>{let g=0,y=0,w=0,j=0,N=0;for(const B of d){const z=B.pos,W=B.bark!==Yo,D=B.blossom!==hi;if(gn(n.current,g,z,[0,B.trunkHeight*.5,0],[.02,0,-.04],[0,0,0],null,[.3*B.scale,B.trunkHeight,.3*B.scale]),v&&n.current.setColorAt(g,W?B.bark:Yo),g++,gn(s.current,w,z,[0,B.trunkHeight*.5,0],[.02,0,-.04],[0,B.trunkHeight*.48,0],null,[.24*B.scale,.32*B.scale,.24*B.scale]),v){const E=W?pn.copy(B.bark).multiplyScalar(.65):pn.set("#3f271e");s.current.setColorAt(w,E)}w++;for(const E of B.branches)gn(n.current,g,z,[0,E.pivotY,0],[E.lean,E.yaw,E.bend],[0,E.length*.5,0],null,[E.radius,E.length,E.radius]),v&&n.current.setColorAt(g,W?B.bark:Yo),g++;for(const E of B.roots){if(gn(o.current,y,z,[0,.14*B.scale,0],[0,E.angle,E.spread],[0,E.length*.22,0],null,[E.radius,E.length,E.radius]),v){const G=W?pn.copy(B.bark).multiplyScalar(.65):pn.set("#3f271e");o.current.setColorAt(y,G)}y++}for(const E of B.branches){if(gn(o.current,y,z,[0,E.pivotY,0],[E.lean,E.yaw,E.bend],[0,E.length*.76,0],[E.twigLean,E.twigYaw,E.bend*-.42],[E.radius*.52,E.twigLength,E.radius*.52]),v){const G=W?pn.copy(B.bark).multiplyScalar(.65):pn.set("#3f271e");o.current.setColorAt(y,G)}y++}for(const E of B.clusters){if(Ss(r.current,j,z,E.position,E.rotation,E.outerScale),v&&r.current.setColorAt(j,D?B.blossom:hi),j++,Ss(a.current,N,z,E.position,E.rotation,E.innerScale),v){const G=D?pn.copy(B.blossom).lerp(v1,.4):pn.set("#ffe6f0");a.current.setColorAt(N,G)}N++}}for(const[B,z]of[[n,g],[o,y],[s,w],[r,j],[a,N]])B.current.count=z,B.current.instanceMatrix.needsUpdate=!0,v&&B.current.instanceColor&&(B.current.instanceColor.needsUpdate=!0)},[d,v,p]),m.useEffect(()=>()=>{b.dispose(),S.dispose(),x.dispose(),_.dispose()},[b,S,x,_]),be.useFrame(g=>{const y=l.current;if(!y)return;const w=y.parent;if(w&&!w.visible)return;const j=y.material;if(j?.uniforms){const N=j.uniforms.uTime,B=j.uniforms.uScale,z=da.useWeatherStore.getState().current,W=z?.intensity??0,D=z?.kind==="storm"?2.4:z?.kind==="rain"?1.6:z?.kind==="snow"?1.2:z?.kind==="cloudy"?1.1:.9,E=j.uniforms.uWind;N&&(N.value=g.clock.getElapsedTime()),B&&(B.value=g.gl.domElement.height*.5),E&&(E.value=D+W*.7)}}),d.length===0?null:i.jsxs(i.Fragment,{children:[i.jsx("instancedMesh",{ref:n,args:[u.limb,f.bark,p.bark],castShadow:!0}),i.jsx("instancedMesh",{ref:o,args:[u.limb,f.barkDark,p.dark]}),i.jsx("instancedMesh",{ref:s,args:[u.trunkTop,f.barkDark,p.top],castShadow:!0}),i.jsx("instancedMesh",{ref:r,args:[u.canopyCluster,f.blossomShell,p.cluster],castShadow:!0}),i.jsx("instancedMesh",{ref:a,args:[u.canopyCore,f.blossomCore,p.cluster]}),i.jsx("points",{geometry:b,children:i.jsx("pointsMaterial",{size:.08*h,sizeAttenuation:!0,vertexColors:!0,transparent:!0,opacity:.82,depthWrite:!1})}),i.jsx("points",{ref:l,geometry:x,material:_,frustumCulled:!1}),i.jsx("points",{geometry:S,children:i.jsx("pointsMaterial",{size:.085*h,sizeAttenuation:!0,vertexColors:!0,transparent:!0,opacity:.7,depthWrite:!1})})]})}function j1({size:e=4,toon:t}){const n=m.useRef(null),o=m.useRef(null),s=m.useRef(null),r=m.useRef(null),a=m.useRef(null),l=m.useRef(null),c=m.useMemo(()=>k.MathUtils.clamp(e/4,.95,1.85),[e]),u=3.8*c,f=1.65*c+Math.min(e*.08,.55),d=2.15*c+Math.min(e*.04,.35),p=t??R.getDefaultToonMode(),h=Cf(),v=Nf(p),b=m.useMemo(()=>Tf(c,u,"round"),[c,u]),S=m.useMemo(()=>If(c),[c]),x=m.useMemo(()=>Ef(c,u,f,d,"round"),[c,u,f,d]),_=b.length,g=S.length+b.length,y=x.length,w=Math.max(180,Math.min(420,Math.round(210+c*95))),j=Math.max(44,Math.min(120,Math.round(54+c*26))),N=Math.max(52,Math.min(132,Math.round(62+c*30))),B=m.useMemo(()=>{const E=new Float32Array(w*3),G=new Float32Array(w*3);return Af(E,G,0,w,u,f,d,0,0,0),_s(E,G,!0)},[w,u,f,d]),z=m.useMemo(()=>{const E=new Float32Array(j*3),G=new Float32Array(j*3);return kf(E,G,0,j,f,0,0,0),_s(E,G,!0)},[j,f]),W=m.useMemo(()=>{const E=new Float32Array(N*3),G=new Float32Array(N*3),T=new Float32Array(N*4),O=new Float32Array(N*2);Bf(E,G,T,O,null,null,0,N,u,f,d,c,0,0,0);const P=new k.BufferGeometry;return P.setAttribute("position",new k.Float32BufferAttribute(E,3)),P.setAttribute("color",new k.Float32BufferAttribute(G,3)),P.setAttribute("aParams1",new k.Float32BufferAttribute(T,4)),P.setAttribute("aParams2",new k.Float32BufferAttribute(O,2)),P.computeBoundingSphere(),P},[N,u,f,d,c]),D=m.useMemo(()=>new k.ShaderMaterial({uniforms:{uTime:{value:0},uPointSize:{value:.11*c},uScale:{value:1},uOpacity:{value:.88}},vertexShader:M1,fragmentShader:Pf,transparent:!0,depthWrite:!1}),[c]);return m.useLayoutEffect(()=>{const E=s.current;if(E){E.count=_;for(let P=0;P<b.length;P++){const L=b[P];L&&gn(E,P,null,[0,L.pivotY,0],[L.lean,L.yaw,L.bend],[0,L.length*.5,0],null,[L.radius,L.length,L.radius])}E.instanceMatrix.needsUpdate=!0}const G=r.current;if(G){G.count=g;let P=0;for(const L of S)gn(G,P++,null,[0,.14*c,0],[0,L.angle,L.spread],[0,L.length*.22,0],null,[L.radius,L.length,L.radius]);for(const L of b)gn(G,P++,null,[0,L.pivotY,0],[L.lean,L.yaw,L.bend],[0,L.length*.76,0],[L.twigLean,L.twigYaw,L.bend*-.42],[L.radius*.52,L.twigLength,L.radius*.52]);G.instanceMatrix.needsUpdate=!0}const T=a.current;if(T){T.count=y;for(let P=0;P<x.length;P++){const L=x[P];L&&Ss(T,P,null,L.position,L.rotation,L.outerScale)}T.instanceMatrix.needsUpdate=!0}const O=l.current;if(O){O.count=y;for(let P=0;P<x.length;P++){const L=x[P];L&&Ss(O,P,null,L.position,L.rotation,L.innerScale)}O.instanceMatrix.needsUpdate=!0}},[b,S,x,c,_,g,y]),m.useEffect(()=>()=>{B.dispose(),z.dispose(),W.dispose(),D.dispose()},[B,z,W,D]),be.useFrame(E=>{const G=o.current?.parent;if(G&&!G.visible)return;const T=E.clock.getElapsedTime(),O=o.current?.material;if(O?.uniforms){const P=O.uniforms.uTime,L=O.uniforms.uScale;P&&(P.value=T),L&&(L.value=E.gl.domElement.height*.5)}n.current&&(n.current.rotation.z=Math.sin(T*.42+c)*.028,n.current.rotation.x=Math.cos(T*.35+c*.6)*.012,n.current.position.x=Math.sin(T*.28+c)*.04*c)}),i.jsxs("group",{position:[0,.02,0],children:[i.jsxs("group",{position:[0,u*.5,0],rotation:[.02,0,-.04],children:[i.jsx("mesh",{geometry:h.limb,material:v.bark,scale:[.3*c,u,.3*c],castShadow:!0,receiveShadow:!0}),i.jsx("mesh",{geometry:h.trunkTop,material:v.barkDark,position:[0,u*.48,0],scale:[.24*c,.32*c,.24*c],castShadow:!0,receiveShadow:!0})]}),i.jsx("instancedMesh",{ref:s,args:[h.limb,v.bark,_]}),i.jsx("instancedMesh",{ref:r,args:[h.limb,v.barkDark,g]}),i.jsxs("group",{ref:n,children:[i.jsx("instancedMesh",{ref:a,args:[h.canopyCluster,v.blossomShell,y],castShadow:!0}),i.jsx("instancedMesh",{ref:l,args:[h.canopyCore,v.blossomCore,y]}),i.jsx("points",{geometry:B,children:i.jsx("pointsMaterial",{size:.08*c,sizeAttenuation:!0,vertexColors:!0,transparent:!0,opacity:.82,depthWrite:!1})})]}),i.jsx("points",{ref:o,geometry:W,material:D,frustumCulled:!1}),i.jsx("points",{geometry:z,children:i.jsx("pointsMaterial",{size:.085*c,sizeAttenuation:!0,vertexColors:!0,transparent:!0,opacity:.7,depthWrite:!1})})]})}const M1=`
|
|
415
|
+
attribute vec3 color;
|
|
416
|
+
attribute vec4 aParams1;
|
|
417
|
+
attribute vec2 aParams2;
|
|
418
|
+
uniform float uTime;
|
|
419
|
+
uniform float uPointSize;
|
|
420
|
+
uniform float uScale;
|
|
421
|
+
varying vec3 vColor;
|
|
422
|
+
void main() {
|
|
423
|
+
float cycle = fract(uTime * aParams1.x + aParams1.y);
|
|
424
|
+
float drift = 1.0 - pow(cycle, 1.22);
|
|
425
|
+
float w = uTime * aParams1.w + aParams1.y * 6.28318;
|
|
426
|
+
vec3 pos = vec3(
|
|
427
|
+
position.x + sin(w) * aParams1.z + aParams2.x * cycle,
|
|
428
|
+
0.18 + position.y * drift + sin(w * 0.6) * 0.06,
|
|
429
|
+
position.z + cos(w * 0.82) * aParams1.z * 0.72 + aParams2.y * cycle
|
|
430
|
+
);
|
|
431
|
+
vColor = color;
|
|
432
|
+
vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
|
|
433
|
+
gl_Position = projectionMatrix * mvPosition;
|
|
434
|
+
gl_PointSize = uPointSize * (uScale / -mvPosition.z);
|
|
435
|
+
}
|
|
436
|
+
`;let Zo=null;function C1(){try{const e="/";if(e){const t=e.endsWith("/")?e:`${e}/`;return new URL(`${t}wasm/gaesup_core.wasm`,document.baseURI).toString()}if(typeof document<"u"&&typeof document.baseURI=="string"&&document.baseURI.length>0)return`${new URL(document.baseURI).origin}/wasm/gaesup_core.wasm`}catch{}return"/wasm/gaesup_core.wasm"}async function Df(){return typeof WebAssembly>"u"?null:Zo||(Zo=(async()=>{try{const e=C1(),t=await fetch(e);if(!t.ok)return null;const n=await t.arrayBuffer(),{instance:o}=await WebAssembly.instantiate(n,{}),s=o.exports;return!s||!(s.memory instanceof WebAssembly.Memory)||typeof s.alloc_f32!="function"||typeof s.dealloc_f32!="function"?null:s}catch{return null}})(),Zo)}const De=2e3,N1=800,ke=20,as=20,T1=3,I1=`
|
|
437
|
+
attribute float aSeed;
|
|
438
|
+
attribute float aBaseX;
|
|
439
|
+
attribute float aBaseZ;
|
|
440
|
+
attribute float aFallSpeed;
|
|
441
|
+
attribute float aDriftAmp;
|
|
442
|
+
|
|
443
|
+
uniform float uTime;
|
|
444
|
+
uniform vec3 uOrigin;
|
|
445
|
+
uniform float uHalfRange;
|
|
446
|
+
uniform float uHeight;
|
|
447
|
+
uniform float uPointSize;
|
|
448
|
+
uniform float uScale;
|
|
449
|
+
|
|
450
|
+
void main() {
|
|
451
|
+
float fall = uHeight - mod(uTime * aFallSpeed + aSeed * uHeight * 2.0, uHeight * 1.4);
|
|
452
|
+
float dx = sin(uTime * 0.7 + aSeed * 6.2831) * aDriftAmp;
|
|
453
|
+
float dz = cos(uTime * 0.5 + aSeed * 3.1415) * aDriftAmp;
|
|
454
|
+
|
|
455
|
+
float wx = uOrigin.x + mod(aBaseX + dx - uOrigin.x + uHalfRange, uHalfRange * 2.0) - uHalfRange;
|
|
456
|
+
float wz = uOrigin.z + mod(aBaseZ + dz - uOrigin.z + uHalfRange, uHalfRange * 2.0) - uHalfRange;
|
|
457
|
+
float wy = uOrigin.y + fall - uHeight * 0.5;
|
|
458
|
+
|
|
459
|
+
vec4 mv = modelViewMatrix * vec4(wx, wy, wz, 1.0);
|
|
460
|
+
gl_Position = projectionMatrix * mv;
|
|
461
|
+
gl_PointSize = uPointSize * (uScale / -mv.z);
|
|
462
|
+
}
|
|
463
|
+
`,E1=`
|
|
464
|
+
uniform float uOpacity;
|
|
465
|
+
void main() {
|
|
466
|
+
vec2 d = gl_PointCoord - vec2(0.5);
|
|
467
|
+
float r2 = dot(d, d);
|
|
468
|
+
if (r2 > 0.25) discard;
|
|
469
|
+
gl_FragColor = vec4(1.0, 1.0, 1.0, uOpacity * exp(-r2 * 6.0));
|
|
470
|
+
}
|
|
471
|
+
`;let Gi=null;function A1(){if(Gi)return Gi;const e=document.createElement("canvas");e.width=16,e.height=16;const t=e.getContext("2d"),n=t.createRadialGradient(8,8,0,8,8,8);return n.addColorStop(0,"rgba(255,255,255,1)"),n.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=n,t.fillRect(0,0,16,16),Gi=new k.CanvasTexture(e),Gi.needsUpdate=!0,Gi}function k1({followCamera:e=!1}){const t=m.useRef(null),n=m.useRef(null),o=m.useMemo(()=>{const r=new k.BufferGeometry,a=new Float32Array(De*3),l=new Float32Array(De),c=new Float32Array(De),u=new Float32Array(De),f=new Float32Array(De),d=new Float32Array(De);for(let p=0;p<De;p++)a[p*3]=0,a[p*3+1]=0,a[p*3+2]=0,l[p]=Math.random(),c[p]=(Math.random()-.5)*ke*2,u[p]=(Math.random()-.5)*ke*2,f[p]=.5+Math.random()*1.5,d[p]=.05+Math.random()*.25;return r.setAttribute("position",new k.Float32BufferAttribute(a,3)),r.setAttribute("aSeed",new k.Float32BufferAttribute(l,1)),r.setAttribute("aBaseX",new k.Float32BufferAttribute(c,1)),r.setAttribute("aBaseZ",new k.Float32BufferAttribute(u,1)),r.setAttribute("aFallSpeed",new k.Float32BufferAttribute(f,1)),r.setAttribute("aDriftAmp",new k.Float32BufferAttribute(d,1)),r.boundingSphere=new k.Sphere(new k.Vector3,ke*4),r},[]),s=m.useMemo(()=>new k.ShaderMaterial({uniforms:{uTime:{value:0},uOrigin:{value:new k.Vector3},uHalfRange:{value:ke},uHeight:{value:as},uPointSize:{value:.08},uScale:{value:1},uOpacity:{value:.85}},vertexShader:I1,fragmentShader:E1,transparent:!0,depthWrite:!1}),[]);return m.useEffect(()=>()=>{o.dispose(),s.dispose()},[o,s]),be.useFrame(r=>{const a=t.current;if(!a)return;const l=a.parent;if(l&&!l.visible)return;const c=n.current.uniforms,u=c.uTime,f=c.uOrigin,d=c.uScale;u&&(u.value=r.clock.elapsedTime),e&&f&&f.value.copy(r.camera.position),d&&(d.value=r.gl.domElement.height*.5)}),i.jsx("points",{ref:t,geometry:o,frustumCulled:!1,children:i.jsx("primitive",{ref:n,object:s,attach:"material"})})}function Ga({gpu:e,followCamera:t=!1}={}){return e?i.jsx(k1,{followCamera:t}):i.jsx(B1,{followCamera:t})}function B1({followCamera:e=!1}){const t=m.useRef(null),n=m.useRef(new Float32Array(De*3)),o=m.useRef(new Float32Array(De*3)),s=m.useRef(null),r=m.useRef(null),a=m.useMemo(()=>new Float32Array(6),[]),l=m.useRef(0);m.useEffect(()=>{const f=n.current,d=o.current;for(let b=0;b<De;b++)f[b*3]=(Math.random()-.5)*ke*2,f[b*3+1]=Math.random()*as,f[b*3+2]=(Math.random()-.5)*ke*2,d[b*3]=0,d[b*3+1]=-(.5+Math.random()*1.5),d[b*3+2]=0;let p=0,h=0,v=0;return Df().then(b=>{if(!b)return;s.current=b;const S=De*3;p=b.alloc_f32(S),h=b.alloc_f32(S),v=b.alloc_f32(6),new Float32Array(b.memory.buffer,p,S).set(f),new Float32Array(b.memory.buffer,h,S).set(d),r.current={p,v:h,b:v}}),()=>{const b=s.current;b&&(p&&b.dealloc_f32(p,De*3),h&&b.dealloc_f32(h,De*3),v&&b.dealloc_f32(v,6))}},[]),be.useFrame((f,d)=>{const p=t.current?.parent;if(p&&!p.visible)return;if(e){const w=f.camera.position;a[0]=w.x-ke,a[1]=w.x+ke,a[2]=w.y-5,a[3]=w.y+as,a[4]=w.z-ke,a[5]=w.z+ke}else a[0]=-ke,a[1]=ke,a[2]=0,a[3]=as,a[4]=-ke,a[5]=ke;const h=Math.min(d,.05),v=s.current,b=r.current,S=n.current,x=o.current,g=l.current++%T1===0,y=t.current;if(y)if(v&&b){new Float32Array(v.memory.buffer,b.b,6).set(a),v.update_snow_particles(De,b.p,b.v,b.b,.3,0,0,2,.01,h);const w=new Float32Array(v.memory.buffer,b.p,De*3),j=y.geometry.attributes.position;if(!(j instanceof k.BufferAttribute))return;j.array=w,j.needsUpdate=!0}else{const w=g?De:N1;for(let N=0;N<w;N++){const B=N*3,z=x[B],W=x[B+1],D=x[B+2],E=S[B],G=S[B+1],T=S[B+2],O=a[0],P=a[1],L=a[2],M=a[3],F=a[4],U=a[5];if(z===void 0||W===void 0||D===void 0||E===void 0||G===void 0||T===void 0||O===void 0||P===void 0||L===void 0||M===void 0||F===void 0||U===void 0)continue;const V=z*.99+.3*h;let Y=W-2*h;const Z=D*.99;let q=E+V*h,X=G+Y*h,A=T+Z*h;q<O?q+=ke*2:q>P&&(q-=ke*2),X<L&&(X=M,Y=-(.5+Math.random()*1.5)),A<F?A+=ke*2:A>U&&(A-=ke*2),x[B]=V,x[B+1]=Y,x[B+2]=Z,S[B]=q,S[B+1]=X,S[B+2]=A}const j=y.geometry.attributes.position;if(!(j instanceof k.BufferAttribute))return;j.needsUpdate=!0}});const c=m.useMemo(()=>{const f=new k.BufferGeometry,d=new k.Float32BufferAttribute(n.current,3);return d.setUsage(k.DynamicDrawUsage),f.setAttribute("position",d),f},[]),u=m.useMemo(()=>new k.PointsMaterial({size:.08,map:A1(),transparent:!0,opacity:.85,depthWrite:!1}),[]);return m.useEffect(()=>()=>{c.dispose(),u.dispose()},[c,u]),i.jsx("points",{ref:t,geometry:c,material:u,frustumCulled:!1})}m.memo(Ga);function P1(){const e=R.useBuildingStore(y=>y.editMode),t=R.useBuildingStore(y=>y.hoverPosition),n=R.useBuildingStore(y=>y.checkTilePosition),o=R.useBuildingStore(y=>y.currentTileMultiplier),s=R.useBuildingStore(y=>y.currentTileHeight),r=R.useBuildingStore(y=>y.currentTileShape),a=R.useBuildingStore(y=>y.currentTileRotation),l=R.useBuildingStore(y=>y.currentObjectRotation),c=R.useBuildingStore(y=>y.selectedPlacedObjectType),u=R.TILE_CONSTANTS.GRID_CELL_SIZE*o,d=(r==="stairs"||r==="ramp"?Math.max(1,s):s)*R.TILE_CONSTANTS.HEIGHT_STEP,p=Math.max(.12,d+.12),h=k.MathUtils.clamp(u/R.TILE_CONSTANTS.GRID_CELL_SIZE,.95,1.85),v=m.useMemo(()=>{const y=new k.BufferGeometry,w=new Float32Array([-.5,0,-.5,.5,0,-.5,-.5,0,.5,.5,0,.5,-.5,1,.5,.5,1,.5]),j=[0,1,3,0,3,2,0,1,5,0,5,4,0,2,4,1,5,3,2,3,5,2,5,4];return y.setAttribute("position",new k.BufferAttribute(w,3)),y.setIndex(j),y.computeVertexNormals(),y},[]);if(m.useEffect(()=>()=>{v.dispose()},[v]),e!=="tile"&&e!=="object"||!t)return null;const b=e==="tile"&&(r==="box"||r==="round")?t.y+s*R.TILE_CONSTANTS.HEIGHT_STEP:t.y,S=e==="tile"?n({x:t.x,y:b,z:t.z}):!1,x=S?"#f3b95f":"#7dd3fc",_=S?.3:.38,g=S?.08:.12;return i.jsxs("group",{position:[t.x,b,t.z],rotation:[0,e==="object"?l:a,0],children:[e==="tile"&&(r==="round"?i.jsxs("mesh",{position:[0,d>.02?d/2:-.02,0],children:[i.jsx("cylinderGeometry",{args:[u/2,u/2,d>.02?d:.04,24]}),i.jsx("meshStandardMaterial",{color:x,transparent:!0,opacity:_,emissive:x,emissiveIntensity:g})]}):r==="stairs"?i.jsx(i.Fragment,{children:Array.from({length:4},(y,w)=>{const N=Math.max(R.TILE_CONSTANTS.HEIGHT_STEP,d)/4,B=u/4,z=N*(w+1)-N/2,W=-u/2+B*w+B/2;return i.jsxs("mesh",{position:[0,z,W],children:[i.jsx("boxGeometry",{args:[u,N*(w+1),B]}),i.jsx("meshStandardMaterial",{color:x,transparent:!0,opacity:_,emissive:x,emissiveIntensity:g})]},w)})}):r==="ramp"?i.jsx("mesh",{position:[0,0,0],scale:[u,Math.max(R.TILE_CONSTANTS.HEIGHT_STEP,d),u],geometry:v,children:i.jsx("meshStandardMaterial",{color:x,transparent:!0,opacity:_,emissive:x,emissiveIntensity:g})}):i.jsxs("mesh",{position:[0,p/2,0],children:[i.jsx("boxGeometry",{args:[u,p,u]}),i.jsx("meshStandardMaterial",{color:x,transparent:!0,opacity:_,emissive:x,emissiveIntensity:g})]})),e==="object"&&i.jsxs("mesh",{position:[0,.06,0],children:[i.jsx("cylinderGeometry",{args:[.35,.35,.12,16]}),i.jsx("meshStandardMaterial",{color:"#7dd3fc",transparent:!0,opacity:.38,emissive:"#2f8dbd",emissiveIntensity:.12})]}),e==="object"&&c==="sakura"&&i.jsxs("group",{position:[0,Math.max(d,.04),0],children:[i.jsxs("mesh",{position:[0,1.9*h,0],children:[i.jsx("cylinderGeometry",{args:[.16*h,.28*h,3.8*h,8]}),i.jsx("meshStandardMaterial",{color:x,transparent:!0,opacity:.32,emissive:x,emissiveIntensity:.15})]}),i.jsxs("mesh",{position:[0,4*h,0],children:[i.jsx("sphereGeometry",{args:[1.55*h,10,8]}),i.jsx("meshStandardMaterial",{color:x,transparent:!0,opacity:.18,emissive:x,emissiveIntensity:.18})]}),i.jsxs("mesh",{position:[.95*h,3.55*h,.4*h],children:[i.jsx("sphereGeometry",{args:[.92*h,8,6]}),i.jsx("meshStandardMaterial",{color:x,transparent:!0,opacity:.14,emissive:x,emissiveIntensity:.12})]}),i.jsxs("mesh",{position:[-.88*h,3.7*h,-.55*h],children:[i.jsx("sphereGeometry",{args:[1.02*h,8,6]}),i.jsx("meshStandardMaterial",{color:x,transparent:!0,opacity:.14,emissive:x,emissiveIntensity:.12})]})]})]})}function R1(){const e=R.useBuildingStore(u=>u.editMode),t=R.useBuildingStore(u=>u.hoverPosition),n=R.useBuildingStore(u=>u.currentWallRotation),o=R.useBuildingStore(u=>u.checkWallPosition),s=R.TILE_CONSTANTS.WALL_SIZES.WIDTH,r=R.TILE_CONSTANTS.WALL_SIZES.HEIGHT,a=R.TILE_CONSTANTS.WALL_SIZES.THICKNESS;if(e!=="wall"||!t)return null;const l=o(t,n),c=l?"#f3b95f":"#7dd3fc";return i.jsx("group",{position:[t.x,t.y+r/2,t.z],rotation:[0,n,0],children:i.jsxs("mesh",{position:[0,0,s/2],children:[i.jsx("boxGeometry",{args:[s,r,a]}),i.jsx("meshStandardMaterial",{color:c,transparent:!0,opacity:l?.34:.42,emissive:c,emissiveIntensity:l?.08:.14})]})})}const js=fa.createNoise2D();let Cr=null,Nr=null;function Ff(e){return e?(Cr||(Cr=R.createToonMaterial({vertexColors:!0,steps:4})),Cr):(Nr||(Nr=new k.MeshStandardMaterial({vertexColors:!0,roughness:1,metalness:.02})),Nr)}function xn(e){const t=Math.sin(e*127.1+311.7)*43758.5453123;return t-Math.floor(t)}function Ms(e,t,n){const o=Math.max(n,1),s=js(e/(o*.8),t/(o*.8))*.07,r=js(e/(o*.32)+8.3,t/(o*.42)-5.4)*.025,a=Math.sin(e*1.35+t*.42)*.01,l=Math.exp(-(((e+o*.18)*(e+o*.18)+(t-o*.08)*(t-o*.08))/Math.max(o*o*.55,1)))*.09,c=Math.exp(-(((e-o*.24)*(e-o*.24)+(t+o*.16)*(t+o*.16))/Math.max(o*o*.7,1)))*.05;return .025+s+r+a+l+c}function D1(e){let t=0,n=0,o=0;const s=[],r=[];for(const x of e){const _=Math.max(20,Math.round(x.size*6));s.push(_),t+=(_+1)*(_+1),n+=_*_*6;const g=Math.max(90,Math.min(240,Math.round(x.size*x.size*10)));r.push(g),o+=g}const a=new Float32Array(t*3),l=new Float32Array(t*3),c=new Uint32Array(n);let u=0,f=0;for(let x=0;x<e.length;x++){const _=e[x],g=s[x];if(!_||g===void 0)continue;const y=_.size,w=_.position[0],j=_.position[1]+.04,N=_.position[2],B=new k.Color(_.color??"#b89b66"),z=new k.Color(_.accentColor??"#e0c27a"),W=new k.Color;for(let D=0;D<=g;D++)for(let E=0;E<=g;E++){const G=u+D*(g+1)+E,T=(E/g-.5)*y,O=(D/g-.5)*y,P=Ms(T,O,y),L=.5+.5*js(T*.22+5.1,O*.22-3.6),M=G*3;a[M]=T+w,a[M+1]=P+j,a[M+2]=O+N,W.copy(B).lerp(z,L*.45).multiplyScalar(.86+L*.18),l[M]=W.r,l[M+1]=W.g,l[M+2]=W.b}for(let D=0;D<g;D++)for(let E=0;E<g;E++){const G=u+D*(g+1)+E,T=G+1,O=G+(g+1),P=O+1;c[f++]=G,c[f++]=O,c[f++]=T,c[f++]=T,c[f++]=O,c[f++]=P}u+=(g+1)*(g+1)}const d=new k.BufferGeometry;d.setAttribute("position",new k.Float32BufferAttribute(a,3)),d.setAttribute("color",new k.Float32BufferAttribute(l,3)),d.setIndex(new k.BufferAttribute(c,1)),d.computeVertexNormals(),d.computeBoundingSphere();const p=new Float32Array(o*3),h=new Float32Array(o*3);let v=0;for(let x=0;x<e.length;x++){const _=e[x],g=r[x];if(!_||g===void 0)continue;const y=_.size,w=_.position[0],j=_.position[1]+.04,N=_.position[2],B=new k.Color(_.color??"#b89b66"),z=new k.Color(_.accentColor??"#e0c27a"),W=new k.Color;for(let D=0;D<g;D++){const E=(v+D)*3,G=xn(D*3.13+.2)*y-y*.5,T=xn(D*4.71+1.4)*y-y*.5,O=xn(D*5.93+2.8),P=xn(D*2.37+.9),L=Ms(G,T,y)+.01+O*.015;p[E]=G+w,p[E+1]=L+j,p[E+2]=T+N,W.copy(B).lerp(z,P*.55).multiplyScalar(.92+P*.12),h[E]=W.r,h[E+1]=W.g,h[E+2]=W.b}v+=g}const b=new k.BufferGeometry;b.setAttribute("position",new k.Float32BufferAttribute(p,3)),b.setAttribute("color",new k.Float32BufferAttribute(h,3)),b.computeBoundingSphere();const S=e.length>0?e.reduce((x,_)=>x+_.size,0)/e.length:4;return[d,b,S]}function Lf({entries:e,toon:t}){const[n,o,s]=m.useMemo(()=>D1(e),[e]),r=t??R.getDefaultToonMode(),a=Ff(r);return m.useEffect(()=>()=>{n.dispose(),o.dispose()},[n,o]),e.length===0?null:i.jsxs(i.Fragment,{children:[i.jsx("mesh",{geometry:n,material:a,castShadow:!0,receiveShadow:!0}),i.jsx("points",{geometry:o,children:i.jsx("pointsMaterial",{size:Math.max(.02,s*.008),vertexColors:!0,transparent:!0,opacity:.85,depthWrite:!1})})]})}function F1({size:e=4,toon:t,color:n,accentColor:o}){const s=t??R.getDefaultToonMode(),r=Ff(s),[a,l]=m.useMemo(()=>{const c=Math.max(20,Math.round(e*6)),u=new k.PlaneGeometry(e,e,c,c);u.rotateX(-Math.PI/2);const f=u.getAttribute("position"),d=new Float32Array(f.count*3),p=new k.Color,h=new k.Color(n??"#b89b66"),v=new k.Color(o??"#e0c27a");for(let g=0;g<f.count;g++){const y=f.getX(g),w=f.getZ(g),j=Ms(y,w,e),N=.5+.5*js(y*.22+5.1,w*.22-3.6);f.setY(g,j),p.copy(h).lerp(v,N*.45).multiplyScalar(.86+N*.18),d[g*3]=p.r,d[g*3+1]=p.g,d[g*3+2]=p.b}u.setAttribute("color",new k.Float32BufferAttribute(d,3)),u.computeVertexNormals();const b=Math.max(90,Math.min(240,Math.round(e*e*10))),S=new Float32Array(b*3),x=new Float32Array(b*3);for(let g=0;g<b;g++){const y=xn(g*3.13+.2)*e-e*.5,w=xn(g*4.71+1.4)*e-e*.5,j=xn(g*5.93+2.8),N=xn(g*2.37+.9),B=Ms(y,w,e)+.01+j*.015;S[g*3]=y,S[g*3+1]=B,S[g*3+2]=w,p.copy(h).lerp(v,N*.55).multiplyScalar(.92+N*.12),x[g*3]=p.r,x[g*3+1]=p.g,x[g*3+2]=p.b}const _=new k.BufferGeometry;return _.setAttribute("position",new k.Float32BufferAttribute(S,3)),_.setAttribute("color",new k.Float32BufferAttribute(x,3)),[u,_]},[o,n,e]);return m.useEffect(()=>()=>{a.dispose(),l.dispose()},[l,a]),i.jsxs("group",{position:[0,.04,0],children:[i.jsx("mesh",{geometry:a,material:r,castShadow:!0,receiveShadow:!0}),i.jsx("points",{geometry:l,frustumCulled:!1,children:i.jsx("pointsMaterial",{size:Math.max(.02,e*.008),vertexColors:!0,transparent:!0,opacity:.85,depthWrite:!1})})]})}const Cs=fa.createNoise2D();let Tr=null,Ir=null;function zf(e){return e?(Tr||(Tr=R.createToonMaterial({vertexColors:!0,steps:4,emissive:"#9ec1e8",emissiveIntensity:.06})),Tr):(Ir||(Ir=new k.MeshPhysicalMaterial({vertexColors:!0,roughness:.88,metalness:0,clearcoat:.12,clearcoatRoughness:.75})),Ir)}function yn(e){const t=Math.sin(e*91.7+173.3)*43758.5453123;return t-Math.floor(t)}function Ns(e,t,n){const o=Math.max(n,1),s=Math.exp(-(((e+o*.2)*(e+o*.2)+(t-o*.14)*(t-o*.14))/Math.max(o*o*.48,1)))*.12,r=Math.exp(-(((e-o*.18)*(e-o*.18)+(t+o*.12)*(t+o*.12))/Math.max(o*o*.65,1)))*.08,a=Cs(e/(o*.7),t/(o*.7))*.06,l=Cs(e/(o*.24)+6.1,t/(o*.24)-3.7)*.018;return .05+s+r+a+l}function L1(e){let t=0,n=0,o=0;const s=[],r=[];for(const x of e){const _=Math.max(22,Math.round(x.size*7));s.push(_),t+=(_+1)*(_+1),n+=_*_*6;const g=Math.max(28,Math.min(96,Math.round(x.size*x.size*3)));r.push(g),o+=g}const a=new Float32Array(t*3),l=new Float32Array(t*3),c=new Uint32Array(n);let u=0,f=0;for(let x=0;x<e.length;x++){const _=e[x],g=s[x];if(!_||g===void 0)continue;const y=_.size,w=_.position[0],j=_.position[1]+.045,N=_.position[2],B=new k.Color(_.color??"#dcecff"),z=new k.Color(_.accentColor??"#ffffff"),W=new k.Color;for(let D=0;D<=g;D++)for(let E=0;E<=g;E++){const G=u+D*(g+1)+E,T=(E/g-.5)*y,O=(D/g-.5)*y,P=Ns(T,O,y),L=.5+.5*Cs(T*.16-2.4,O*.16+7.2),M=G*3;a[M]=T+w,a[M+1]=P+j,a[M+2]=O+N,W.copy(B).lerp(z,L*.55).multiplyScalar(.9+L*.1),l[M]=W.r,l[M+1]=W.g,l[M+2]=W.b}for(let D=0;D<g;D++)for(let E=0;E<g;E++){const G=u+D*(g+1)+E,T=G+1,O=G+(g+1),P=O+1;c[f++]=G,c[f++]=O,c[f++]=T,c[f++]=T,c[f++]=O,c[f++]=P}u+=(g+1)*(g+1)}const d=new k.BufferGeometry;d.setAttribute("position",new k.Float32BufferAttribute(a,3)),d.setAttribute("color",new k.Float32BufferAttribute(l,3)),d.setIndex(new k.BufferAttribute(c,1)),d.computeVertexNormals(),d.computeBoundingSphere();const p=new Float32Array(o*3),h=new Float32Array(o*3);let v=0;for(let x=0;x<e.length;x++){const _=e[x],g=r[x];if(!_||g===void 0)continue;const y=_.size,w=_.position[0],j=_.position[1]+.045,N=_.position[2],B=new k.Color(_.color??"#dcecff"),z=new k.Color(_.accentColor??"#ffffff"),W=new k.Color;for(let D=0;D<g;D++){const E=(v+D)*3,G=yn(D*2.71+.4)*y-y*.5,T=yn(D*3.97+1.9)*y-y*.5,O=yn(D*5.41+2.2),P=yn(D*7.13+3.1),L=Ns(G,T,y)+.016+O*.02;p[E]=G+w,p[E+1]=L+j,p[E+2]=T+N,W.copy(B).lerp(z,.6+P*.4),h[E]=W.r,h[E+1]=W.g,h[E+2]=W.b}v+=g}const b=new k.BufferGeometry;b.setAttribute("position",new k.Float32BufferAttribute(p,3)),b.setAttribute("color",new k.Float32BufferAttribute(h,3)),b.computeBoundingSphere();const S=e.length>0?e.reduce((x,_)=>x+_.size,0)/e.length:4;return[d,b,S]}function Of({entries:e,toon:t}){const[n,o,s]=m.useMemo(()=>L1(e),[e]),r=t??R.getDefaultToonMode(),a=zf(r);return m.useEffect(()=>()=>{n.dispose(),o.dispose()},[n,o]),e.length===0?null:i.jsxs(i.Fragment,{children:[i.jsx("mesh",{geometry:n,material:a,castShadow:!0,receiveShadow:!0}),i.jsx("points",{geometry:o,children:i.jsx("pointsMaterial",{size:Math.max(.03,s*.01),vertexColors:!0,transparent:!0,opacity:.55,depthWrite:!1})})]})}function z1({size:e=4,toon:t,color:n,accentColor:o}){const s=t??R.getDefaultToonMode(),r=zf(s),[a,l]=m.useMemo(()=>{const c=Math.max(22,Math.round(e*7)),u=new k.PlaneGeometry(e,e,c,c);u.rotateX(-Math.PI/2);const f=u.getAttribute("position"),d=new Float32Array(f.count*3),p=new k.Color,h=new k.Color(n??"#dcecff"),v=new k.Color(o??"#ffffff");for(let g=0;g<f.count;g++){const y=f.getX(g),w=f.getZ(g),j=Ns(y,w,e),N=.5+.5*Cs(y*.16-2.4,w*.16+7.2);f.setY(g,j),p.copy(h).lerp(v,N*.55).multiplyScalar(.9+N*.1),d[g*3]=p.r,d[g*3+1]=p.g,d[g*3+2]=p.b}u.setAttribute("color",new k.Float32BufferAttribute(d,3)),u.computeVertexNormals();const b=Math.max(28,Math.min(96,Math.round(e*e*3))),S=new Float32Array(b*3),x=new Float32Array(b*3);for(let g=0;g<b;g++){const y=yn(g*2.71+.4)*e-e*.5,w=yn(g*3.97+1.9)*e-e*.5,j=yn(g*5.41+2.2),N=yn(g*7.13+3.1),B=Ns(y,w,e)+.016+j*.02;S[g*3]=y,S[g*3+1]=B,S[g*3+2]=w,p.copy(h).lerp(v,.6+N*.4),x[g*3]=p.r,x[g*3+1]=p.g,x[g*3+2]=p.b}const _=new k.BufferGeometry;return _.setAttribute("position",new k.Float32BufferAttribute(S,3)),_.setAttribute("color",new k.Float32BufferAttribute(x,3)),[u,_]},[e,o,n]);return m.useEffect(()=>()=>{a.dispose(),l.dispose()},[l,a]),i.jsxs("group",{position:[0,.045,0],children:[i.jsx("mesh",{geometry:a,material:r,castShadow:!0,receiveShadow:!0}),i.jsx("points",{geometry:l,frustumCulled:!1,children:i.jsx("pointsMaterial",{size:Math.max(.03,e*.01),vertexColors:!0,transparent:!0,opacity:.55,depthWrite:!1})})]})}be.extend({Water:ua.Water});const O1=`
|
|
472
|
+
uniform float uTime;
|
|
473
|
+
varying vec2 vUv;
|
|
474
|
+
varying vec3 vWorldPos;
|
|
475
|
+
varying float vWave;
|
|
476
|
+
|
|
477
|
+
void main() {
|
|
478
|
+
vUv = uv;
|
|
479
|
+
vec3 p = position;
|
|
480
|
+
float w1 = sin(p.x * 0.55 + uTime * 0.85) * 0.085;
|
|
481
|
+
float w2 = sin(p.y * 0.78 - uTime * 1.05 + p.x * 0.33) * 0.055;
|
|
482
|
+
float w3 = sin((p.x + p.y) * 1.40 + uTime * 1.60) * 0.025;
|
|
483
|
+
float w = w1 + w2 + w3;
|
|
484
|
+
p.z += w;
|
|
485
|
+
vWave = w;
|
|
486
|
+
vWorldPos = (modelMatrix * vec4(p, 1.0)).xyz;
|
|
487
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
|
|
488
|
+
}
|
|
489
|
+
`,$1=`
|
|
490
|
+
uniform vec3 uShallow;
|
|
491
|
+
uniform vec3 uDeep;
|
|
492
|
+
uniform vec3 uFoam;
|
|
493
|
+
uniform float uTime;
|
|
494
|
+
varying vec2 vUv;
|
|
495
|
+
varying vec3 vWorldPos;
|
|
496
|
+
varying float vWave;
|
|
497
|
+
|
|
498
|
+
float hash21(vec2 p) {
|
|
499
|
+
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
float vnoise(vec2 p) {
|
|
503
|
+
vec2 i = floor(p);
|
|
504
|
+
vec2 f = fract(p);
|
|
505
|
+
f = f * f * (3.0 - 2.0 * f);
|
|
506
|
+
float a = hash21(i);
|
|
507
|
+
float b = hash21(i + vec2(1.0, 0.0));
|
|
508
|
+
float c = hash21(i + vec2(0.0, 1.0));
|
|
509
|
+
float d = hash21(i + vec2(1.0, 1.0));
|
|
510
|
+
return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
float fbm(vec2 p) {
|
|
514
|
+
float v = 0.0;
|
|
515
|
+
float a = 0.5;
|
|
516
|
+
for (int i = 0; i < 4; i++) {
|
|
517
|
+
v += a * vnoise(p);
|
|
518
|
+
p = p * 2.07 + vec2(13.7, 7.1);
|
|
519
|
+
a *= 0.5;
|
|
520
|
+
}
|
|
521
|
+
return v;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
float band(float v, float c, float w) {
|
|
525
|
+
return smoothstep(c - w, c, v) - smoothstep(c, c + w, v);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
void main() {
|
|
529
|
+
vec2 wp = vWorldPos.xz;
|
|
530
|
+
|
|
531
|
+
float baseNoise = fbm(wp * 0.18 + vec2(uTime * 0.04, -uTime * 0.03));
|
|
532
|
+
float depthCol = clamp(0.5 + vWave * 3.5 + (baseNoise - 0.5) * 0.55, 0.0, 1.0);
|
|
533
|
+
vec3 base = mix(uDeep, uShallow, depthCol);
|
|
534
|
+
|
|
535
|
+
float stripeCoord = (wp.x + wp.y) * 0.55 + uTime * 0.35 + baseNoise * 0.8;
|
|
536
|
+
float stripe = sin(stripeCoord * 6.0) * 0.5 + 0.5;
|
|
537
|
+
float stripeFoam = band(stripe, 0.86, 0.10) * (0.35 + depthCol * 0.65);
|
|
538
|
+
|
|
539
|
+
float specks = smoothstep(0.78, 0.95, fbm(wp * 0.62 + uTime * 0.10));
|
|
540
|
+
float ripple = smoothstep(0.60, 0.95, fbm(wp * 1.30 + uTime * 0.60));
|
|
541
|
+
|
|
542
|
+
vec3 col = mix(base, uFoam, stripeFoam * 0.55 + specks * 0.50 + ripple * 0.18);
|
|
543
|
+
|
|
544
|
+
float edge = smoothstep(0.0, 0.06, min(min(vUv.x, vUv.y), min(1.0 - vUv.x, 1.0 - vUv.y)));
|
|
545
|
+
col = mix(col * 0.86, col, edge);
|
|
546
|
+
|
|
547
|
+
gl_FragColor = vec4(col, 0.88);
|
|
548
|
+
}
|
|
549
|
+
`;let Er=null;function Xo(e,t){const n=Math.sin(e*127.1+t*311.7)*43758.5453123;return n-Math.floor(n)}function G1(e,t){const n=Math.floor(e),o=Math.floor(t),s=e-n,r=t-o,a=s*s*(3-2*s),l=r*r*(3-2*r),c=Xo(n,o),u=Xo(n+1,o),f=Xo(n,o+1),d=Xo(n+1,o+1);return k.MathUtils.lerp(k.MathUtils.lerp(c,u,a),k.MathUtils.lerp(f,d,a),l)}function Ko(e,t){let n=0,o=.58,s=1.15;for(let r=0;r<5;r+=1)n+=G1(e*s+17.3*r,t*s-9.1*r)*o,s*=2.03,o*=.48;return n+=Math.sin(e*8.2+t*1.7)*.06,n+=Math.cos(t*7.1-e*2.4)*.05,n}function H1(e=128){if(Er)return Er;const t=new Uint8Array(e*e*4);for(let o=0;o<e;o+=1)for(let s=0;s<e;s+=1){const r=(o*e+s)*4,a=s/e,l=o/e,c=1/e,u=Ko(a-c,l),f=Ko(a+c,l),d=Ko(a,l-c),p=Ko(a,l+c),h=(u-f)*1.15,v=(d-p)*1.15,b=1,S=Math.sqrt(h*h+v*v+b*b)||1;t[r]=Math.round((h/S*.5+.5)*255),t[r+1]=Math.round((v/S*.5+.5)*255),t[r+2]=Math.round((b/S*.5+.5)*255),t[r+3]=255}const n=new k.DataTexture(t,e,e,k.RGBAFormat);return n.wrapS=k.RepeatWrapping,n.wrapT=k.RepeatWrapping,n.minFilter=k.LinearMipmapLinearFilter,n.magFilter=k.LinearFilter,n.generateMipmaps=!0,n.colorSpace=k.NoColorSpace,n.needsUpdate=!0,Er=n,n}function Ha({lod:e,center:t,size:n=16,width:o,depth:s,shore:r,toon:a}){const l=a??R.getDefaultToonMode(),c=m.useRef(null),u=m.useRef(null),f=m.useRef(null),d=m.useRef(null),p=m.useRef(new k.Vector3),h=m.useRef(!0),v=m.useRef(!0),b=m.useRef(0),S=m.useRef(0),x=m.useMemo(()=>new k.MeshPhysicalMaterial({color:"#8dbab5",roughness:.28,metalness:.02,transparent:!0,opacity:.42,clearcoat:.18,clearcoatRoughness:.72,depthWrite:!1}),[]),_=m.useMemo(()=>({north:r?.north??!0,south:r?.south??!0,east:r?.east??!0,west:r?.west??!0}),[r?.east,r?.north,r?.south,r?.west]),g=o??n,y=s??n,w=Math.min(Math.min(g,y)*.18,.72),j=_.north?w:0,N=_.south?w:0,B=_.east?w:0,z=_.west?w:0,W=Math.max(g-z-B,g*.34),D=Math.max(y-j-N,y*.34),E=(z-B)*.5,G=(j-N)*.5,T=Math.max(g-(_.west?w*.25:0)-(_.east?w*.25:0),g*.42),O=Math.max(y-(_.north?w*.25:0)-(_.south?w*.25:0),y*.42),P=H1(),L=m.useMemo(()=>{const Z=Math.max(g,y);return Z<=8?256:Z<=24?384:512},[y,g]);m.useEffect(()=>{t&&p.current.set(t[0],t[1],t[2])},[t]);const M=m.useMemo(()=>({textureWidth:L,textureHeight:L,waterNormals:P,sunDirection:new k.Vector3(.1,.7,.2),sunColor:16777215,waterColor:7695,distortionScale:3.7}),[L,P]),F=m.useMemo(()=>{const Z=Math.max(W,D),q=Math.round(l?Z*2.5:Z*1.2);return Math.max(l?14:6,Math.min(l?56:32,q))},[l,W,D]),U=m.useMemo(()=>new k.PlaneGeometry(W,D,F,F),[D,W,F]),V=m.useMemo(()=>new k.MeshPhysicalMaterial({color:"#2f8dbd",roughness:.18,metalness:0,transparent:!0,opacity:.72,clearcoat:.45,clearcoatRoughness:.24,normalMap:P,normalScale:new k.Vector2(.22,.22),depthWrite:!1}),[P]),Y=m.useMemo(()=>l?new k.ShaderMaterial({uniforms:{uTime:{value:0},uShallow:{value:new k.Color("#9ed6c8")},uDeep:{value:new k.Color("#1f5f88")},uFoam:{value:new k.Color("#ffffff")}},vertexShader:O1,fragmentShader:$1,transparent:!0,depthWrite:!1}):null,[l,P]);return m.useEffect(()=>()=>{U.dispose();const Z=c.current;Z?.material?.dispose?.(),typeof Z?.dispose=="function"&&Z.dispose(),V.dispose(),Y?.dispose()},[V,U,Y]),m.useEffect(()=>()=>{x.dispose()},[x]),be.useFrame((Z,q)=>{const X=l?f.current:c.current;if(!X)return;const A=c.current,C=d.current;if(e){b.current+=Math.max(0,q);const H=h.current?.2:.5;if(b.current>=H){b.current=0;const K=e.near??30,Q=e.far??180,ee=e.strength??4,ne=Z.camera.position.distanceTo(p.current),re=se.weightFromDistance(ne,K,Q,ee)>0;v.current=!l&&ne<=K,re!==h.current&&(h.current=re,X.visible=re)}if(!h.current){A&&(A.visible=!1),C&&(C.visible=!1);return}}if(l){C&&(C.visible=!1);const H=u.current?.uniforms?.uTime;H&&(H.value=Z.clock.elapsedTime)}else{const H=v.current;if(A&&(A.visible=H),C&&(C.visible=!H),!H||(S.current+=Math.max(0,q),S.current<1/30))return;const K=c.current?.material.uniforms?.time;K&&(K.value+=S.current*.3),S.current=0}}),i.jsxs("group",{children:[_.north&&i.jsx("mesh",{"rotation-x":-Math.PI/2,position:[0,.055,-y/2+w/2],material:x,receiveShadow:!0,children:i.jsx("planeGeometry",{args:[T,w,1,1]})}),_.south&&i.jsx("mesh",{"rotation-x":-Math.PI/2,position:[0,.055,y/2-w/2],material:x,receiveShadow:!0,children:i.jsx("planeGeometry",{args:[T,w,1,1]})}),_.west&&i.jsx("mesh",{"rotation-x":-Math.PI/2,position:[-g/2+w/2,.055,0],material:x,receiveShadow:!0,children:i.jsx("planeGeometry",{args:[w,O,1,1]})}),_.east&&i.jsx("mesh",{"rotation-x":-Math.PI/2,position:[g/2-w/2,.055,0],material:x,receiveShadow:!0,children:i.jsx("planeGeometry",{args:[w,O,1,1]})}),l?i.jsx("mesh",{ref:f,geometry:U,"rotation-x":-Math.PI/2,position:[E,.1,G],children:i.jsx("primitive",{ref:u,object:Y,attach:"material"})}):i.jsxs(i.Fragment,{children:[i.jsx("water",{ref:c,args:[U,M],"rotation-x":-Math.PI/2,position:[E,.1,G]}),i.jsx("mesh",{ref:d,geometry:U,material:V,"rotation-x":-Math.PI/2,position:[E,.095,G],visible:!1})]})]})}const W1=['<svg xmlns="http://www.w3.org/2000/svg" width="32" height="128" viewBox="0 0 32 128">','<rect width="32" height="128" fill="black"/>','<path d="M16 2 C8 36 6 82 15 126 C23 82 24 36 16 2 Z" fill="white"/>',"</svg>"].join(""),U1=['<svg xmlns="http://www.w3.org/2000/svg" width="32" height="128" viewBox="0 0 32 128">','<defs><linearGradient id="g" x1="0" y1="1" x2="0" y2="0">','<stop offset="0" stop-color="#2f5f2b"/>','<stop offset="0.55" stop-color="#66a846"/>','<stop offset="1" stop-color="#b8dc69"/>',"</linearGradient></defs>",'<rect width="32" height="128" fill="#4f8d39"/>','<path d="M16 2 C8 36 6 82 15 126 C23 82 24 36 16 2 Z" fill="url(#g)"/>',"</svg>"].join(""),$f=`data:image/svg+xml,${encodeURIComponent(W1)}`,Gf=`data:image/svg+xml,${encodeURIComponent(U1)}`;function V1(e={}){return{bladeDiffuseUrl:e.bladeDiffuseUrl??Gf,bladeAlphaUrl:e.bladeAlphaUrl??$f}}var Y1=`precision highp float;\r
|
|
550
|
+
uniform sampler2D map;\r
|
|
551
|
+
uniform sampler2D alphaMap;\r
|
|
552
|
+
uniform vec3 tipColor;\r
|
|
553
|
+
uniform vec3 bottomColor;\r
|
|
554
|
+
uniform float uToon;\r
|
|
555
|
+
uniform float uToonSteps;\r
|
|
556
|
+
varying vec2 vUv;\r
|
|
557
|
+
varying float frc;\r
|
|
558
|
+
varying float vCluster;\r
|
|
559
|
+
varying float vDryness;\r
|
|
560
|
+
varying float vShade;
|
|
561
|
+
|
|
562
|
+
void main() {\r
|
|
563
|
+
float alpha = texture2D(alphaMap, vUv).r;\r
|
|
564
|
+
if(alpha < 0.15)\r
|
|
565
|
+
discard;\r
|
|
566
|
+
vec3 warmBottom = vec3(0.30, 0.23, 0.08);\r
|
|
567
|
+
vec3 warmTip = vec3(0.80, 0.74, 0.34);\r
|
|
568
|
+
vec3 coolBottom = vec3(0.18, 0.31, 0.12);\r
|
|
569
|
+
vec3 coolTip = vec3(0.63, 0.82, 0.42);\r
|
|
570
|
+
vec3 lushBottom = mix(bottomColor, coolBottom, vCluster * 0.35);\r
|
|
571
|
+
vec3 lushTip = mix(tipColor, coolTip, vCluster * 0.28);\r
|
|
572
|
+
vec3 dryBottom = mix(lushBottom, warmBottom, vDryness * 0.85);\r
|
|
573
|
+
vec3 dryTip = mix(lushTip, warmTip, vDryness);
|
|
574
|
+
|
|
575
|
+
float frcStepped = mix(smoothstep(0.0, 1.0, frc), floor(frc * uToonSteps) / max(uToonSteps - 1.0, 1.0), uToon);\r
|
|
576
|
+
vec3 bladeGradient = mix(dryBottom, dryTip, frcStepped);\r
|
|
577
|
+
vec3 tex = texture2D(map, vUv).rgb;\r
|
|
578
|
+
float rib = 1.0 - smoothstep(0.0, 0.52, abs(vUv.x - 0.5));\r
|
|
579
|
+
vec3 color = mix(bladeGradient * 0.72, tex * bladeGradient, mix(0.62, 0.35, uToon));\r
|
|
580
|
+
color *= mix(0.9, 1.1, vCluster);\r
|
|
581
|
+
color *= mix(1.0, 0.82, vDryness * 0.35);\r
|
|
582
|
+
color *= mix(0.94, 1.05, rib);
|
|
583
|
+
|
|
584
|
+
float shadeStepped = mix(vShade, floor(vShade * uToonSteps) / max(uToonSteps - 1.0, 1.0), uToon);\r
|
|
585
|
+
color *= shadeStepped;
|
|
586
|
+
|
|
587
|
+
vec4 col = vec4(color, 1.0);\r
|
|
588
|
+
vec3 reinhard = col.rgb / (col.rgb + vec3(1.0));\r
|
|
589
|
+
vec3 simple = clamp(col.rgb, 0.0, 1.0);\r
|
|
590
|
+
col.rgb = mix(reinhard, simple, uToon);\r
|
|
591
|
+
col.rgb = pow(col.rgb, vec3(1.0 / 2.2));
|
|
592
|
+
|
|
593
|
+
gl_FragColor = col;\r
|
|
594
|
+
}`;let Hf=null;function Z1(e){Hf=e}class X1{nextId=1;tiles=new Map;positions=new Float32Array(0);weights=new Float32Array(0);trampleWorld=new k.Vector3(0,-9999,0);trampleStrength=0;lastSampleAt=0;register(t){this.tiles.size===0&&(this.lastSampleAt=0);const n=this.nextId++,o={...t,id:n};return this.tiles.set(n,o),this.ensureCapacity(this.tiles.size),o}update(t,n){const o=this.tiles.get(t);o&&Object.assign(o,n)}unregister(t){this.tiles.delete(t),this.tiles.size===0&&(this.lastSampleAt=0)}size(){return this.tiles.size}tick(t){if(this.tiles.size===0)return;const n=performance.now();if(n-this.lastSampleAt<12)return;this.lastSampleAt=n,this.refreshTrample(t.delta);const o=this.computeWindScale(),s=t.elapsedTime/4;this.ensureCapacity(this.tiles.size);let r=0;const a=[];for(const c of this.tiles.values()){const u=r*3;this.positions[u]=c.center.x,this.positions[u+1]=c.center.y,this.positions[u+2]=c.center.z,a.push(c.id),r+=1}this.computeWeights(a.length,t.cameraPosition);let l=0;for(const c of a){const u=this.tiles.get(c);if(!u){l+=1;continue}let f=this.weights[l]??0;l+=1;const d=Math.hypot(u.width,u.height)*.6,p=K1.set(u.center,d),h=t.frustum.intersectsSphere(p);if(u.lod){const S=u.center.distanceTo(t.cameraPosition);f=xc(S,u.lod.near??24,u.lod.far??160,u.lod.strength??4)}const v=Math.max(0,Math.floor(u.maxInstances*f)),b=h&&v>0;u.apply({visible:b,instanceCount:b?v:0,time:s,windScale:o,trampleCenter:this.trampleWorld,trampleStrength:this.trampleStrength})}}ensureCapacity(t){this.positions.length<t*3&&(this.positions=new Float32Array(t*3)),this.weights.length<t&&(this.weights=new Float32Array(t))}computeWeights(t,n){const o=Hf,s=24,r=160,a=4;if(o)try{const l=o.alloc_f32(t*3),c=o.alloc_f32(t);try{new Float32Array(o.memory.buffer,l,t*3).set(this.positions.subarray(0,t*3)),o.batch_sfe_weights(t,l,n.x,n.y,n.z,s,r,a,c),this.weights.set(new Float32Array(o.memory.buffer,c,t))}finally{o.dealloc_f32(l,t*3),o.dealloc_f32(c,t)}return}catch{}for(let l=0;l<t;l+=1){const c=l*3,u=(this.positions[c]??0)-n.x,f=(this.positions[c+1]??0)-n.y,d=(this.positions[c+2]??0)-n.z,p=Math.sqrt(u*u+f*f+d*d);this.weights[l]=xc(p,s,r,a)}}refreshTrample(t){const n=ge.BridgeFactory.getOrCreate("motion"),o=n?.getActiveEntities()??[],s=o[0]?n?.snapshot(o[0]):null,r=k.MathUtils.clamp(t*6,0,1);s&&(this.trampleWorld.x+=(s.position.x-this.trampleWorld.x)*r,this.trampleWorld.y=s.position.y,this.trampleWorld.z+=(s.position.z-this.trampleWorld.z)*r);const a=s?.isMoving&&s?.isGrounded?.85:.35;this.trampleStrength+=(a-this.trampleStrength)*r}computeWindScale(){const t=da.useWeatherStore.getState().current,n=t?.intensity??0;return(t?.kind==="storm"?2.6:t?.kind==="rain"?1.7:t?.kind==="snow"?1.3:t?.kind==="cloudy"?1.15:.85)+n*.9}}const K1=new k.Sphere;function xc(e,t,n,o){if(e<=t)return 1;if(e>=n)return 0;const s=(e-t)/(n-t);return Math.pow(1-s,Math.max(1,o))}let Ar=null;function bo(){return Ar||(Ar=new X1),Ar}var q1=`precision highp float;\r
|
|
595
|
+
attribute vec3 offset;\r
|
|
596
|
+
attribute vec4 orientation;\r
|
|
597
|
+
attribute float halfRootAngleSin;\r
|
|
598
|
+
attribute float halfRootAngleCos;\r
|
|
599
|
+
attribute float stretch;\r
|
|
600
|
+
uniform float time;\r
|
|
601
|
+
uniform float windScale;\r
|
|
602
|
+
uniform float bladeHeight;\r
|
|
603
|
+
uniform vec3 trampleCenter;\r
|
|
604
|
+
uniform float trampleRadius;\r
|
|
605
|
+
uniform float trampleStrength;\r
|
|
606
|
+
varying vec2 vUv;\r
|
|
607
|
+
varying float frc;\r
|
|
608
|
+
varying float vCluster;\r
|
|
609
|
+
varying float vDryness;\r
|
|
610
|
+
varying float vShade;
|
|
611
|
+
|
|
612
|
+
vec3 mod289(vec3 x) {\r
|
|
613
|
+
return x - floor(x * (1.0 / 289.0)) * 289.0;\r
|
|
614
|
+
}\r
|
|
615
|
+
vec2 mod289(vec2 x) {\r
|
|
616
|
+
return x - floor(x * (1.0 / 289.0)) * 289.0;\r
|
|
617
|
+
}\r
|
|
618
|
+
vec3 permute(vec3 x) {\r
|
|
619
|
+
return mod289(((x * 34.0) + 1.0) * x);\r
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
float snoise(vec2 v) {\r
|
|
623
|
+
const vec4 C = vec4(0.211324865405187, 0.366025403784439, -0.577350269189626, 0.024390243902439);\r
|
|
624
|
+
vec2 i = floor(v + dot(v, C.yy));\r
|
|
625
|
+
vec2 x0 = v - i + dot(i, C.xx);\r
|
|
626
|
+
vec2 i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);\r
|
|
627
|
+
vec4 x12 = x0.xyxy + C.xxzz;\r
|
|
628
|
+
x12.xy -= i1;\r
|
|
629
|
+
i = mod289(i);\r
|
|
630
|
+
vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0));\r
|
|
631
|
+
vec3 m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), 0.0);\r
|
|
632
|
+
m = m * m;\r
|
|
633
|
+
m = m * m;\r
|
|
634
|
+
vec3 x = 2.0 * fract(p * C.www) - 1.0;\r
|
|
635
|
+
vec3 h = abs(x) - 0.5;\r
|
|
636
|
+
vec3 ox = floor(x + 0.5);\r
|
|
637
|
+
vec3 a0 = x - ox;\r
|
|
638
|
+
m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);\r
|
|
639
|
+
vec3 g;\r
|
|
640
|
+
g.x = a0.x * x0.x + h.x * x0.y;\r
|
|
641
|
+
g.yz = a0.yz * x12.xz + h.yz * x12.yw;\r
|
|
642
|
+
return 130.0 * dot(m, g);\r
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
vec3 rotateVectorByQuaternion(vec3 v, vec4 q) {\r
|
|
646
|
+
return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);\r
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
void main() {\r
|
|
650
|
+
frc = position.y / float(bladeHeight);\r
|
|
651
|
+
float clusterNoise = snoise(offset.xz * 0.11 + vec2(3.7, -8.2));\r
|
|
652
|
+
float dryNoise = snoise(offset.xz * 0.18 + vec2(-5.4, 12.6));\r
|
|
653
|
+
float noise = 1.0 - snoise(vec2((time - offset.x / 50.0), (time - offset.z / 50.0)));\r
|
|
654
|
+
vec4 direction = vec4(0.0, halfRootAngleSin, 0.0, halfRootAngleCos);\r
|
|
655
|
+
vec4 tiltAxis = vec4(-orientation.z, 0.0, orientation.x, orientation.w);\r
|
|
656
|
+
vec4 bent = normalize(mix(direction, tiltAxis, frc));\r
|
|
657
|
+
vec3 vPosition = vec3(position.x, position.y + position.y * stretch, position.z);\r
|
|
658
|
+
vPosition = rotateVectorByQuaternion(vPosition, bent);
|
|
659
|
+
|
|
660
|
+
float windAngle = noise * 0.3 * windScale;\r
|
|
661
|
+
vec4 windQuat = vec4(sin(windAngle), 0.0, -sin(windAngle), cos(windAngle));\r
|
|
662
|
+
vPosition = rotateVectorByQuaternion(vPosition, windQuat);
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
if (trampleRadius > 0.0001) {\r
|
|
668
|
+
vec2 toCenter = offset.xz - trampleCenter.xz;\r
|
|
669
|
+
float distXZ = length(toCenter);\r
|
|
670
|
+
float falloff = clamp(1.0 - distXZ / trampleRadius, 0.0, 1.0);\r
|
|
671
|
+
if (falloff > 0.0) {\r
|
|
672
|
+
float push = falloff * falloff * trampleStrength;\r
|
|
673
|
+
vPosition.y *= mix(1.0, 0.18, push);\r
|
|
674
|
+
vec2 dir = distXZ > 0.0001 ? toCenter / distXZ : vec2(0.0);\r
|
|
675
|
+
vPosition.x += dir.x * push * 0.45 * frc;\r
|
|
676
|
+
vPosition.z += dir.y * push * 0.45 * frc;\r
|
|
677
|
+
}\r
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
vCluster = clusterNoise * 0.5 + 0.5;\r
|
|
681
|
+
vDryness = clamp((dryNoise * 0.5 + 0.5) * 0.7 + (1.0 - stretch) * 0.45, 0.0, 1.0);\r
|
|
682
|
+
vShade = clamp(0.82 + noise * 0.08 + orientation.w * 0.06, 0.72, 1.1);\r
|
|
683
|
+
vUv = uv;\r
|
|
684
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(offset + vPosition, 1.0);\r
|
|
685
|
+
}`;let kr=null,Br=null,yc=null,vc=null,wc=null;function Q1(){return wc??=new k.TextureLoader,wc}function Wf(e,t,n,o){const s=new k.DataTexture(new Uint8Array([e,t,n,o]),1,1,k.RGBAFormat);return s.needsUpdate=!0,s}function Sc(){return yc??=Wf(102,168,70,255),yc}function _c(){return vc??=Wf(255,255,255,255),vc}function J1(e,t){return e.colorSpace=t,e.wrapS=k.ClampToEdgeWrapping,e.wrapT=k.ClampToEdgeWrapping,e.needsUpdate=!0,e}function jc(e,t,n,o){const s=Q1(),r=a=>new Promise((l,c)=>{s.load(a,u=>l(J1(u,o)),void 0,c)});return r(e).catch(()=>e===t?n:r(t).catch(()=>n))}function eS(e){return e?(kr||(kr=R.createToonMaterial({color:"#ffffff",vertexColors:!0,steps:3})),kr):(Br||(Br=new k.MeshStandardMaterial({color:"#ffffff",vertexColors:!0,roughness:.95,metalness:0})),Br)}const to=fa.createNoise2D(),tS=new k.Color("#5a7a35"),nS=new k.Color("#7a8e3a"),iS=new k.Color("#5b4628"),oS=pt.shaderMaterial({bladeHeight:1,map:null,alphaMap:null,time:0,windScale:1,trampleCenter:new k.Vector3(0,-9999,0),trampleRadius:1.4,trampleStrength:.85,tipColor:new k.Color("#8fbc5a").convertSRGBToLinear(),bottomColor:new k.Color("#355b2d").convertSRGBToLinear(),uToon:0,uToonSteps:4},q1,Y1);be.extend({GrassMaterial:oS});function Wa(e,t){return .05*to(e/50,t/50)+.05*to(e/100,t/100)}function sS(e){const[t,n]=m.useState(()=>({texture:Sc(),alphaMap:_c()}));return m.useEffect(()=>{let o=!1;return Promise.all([jc(e.bladeDiffuseUrl,Gf,Sc(),k.SRGBColorSpace),jc(e.bladeAlphaUrl,$f,_c(),k.NoColorSpace)]).then(([s,r])=>{o||n({texture:s,alphaMap:r})}),()=>{o=!0}},[e.bladeAlphaUrl,e.bladeDiffuseUrl]),t}function rS(e,t,n){const o=t*3,s=t*4,r=e.alloc_f32(o),a=e.alloc_f32(s),l=e.alloc_f32(t),c=e.alloc_f32(t),u=e.alloc_f32(t);try{const f=Math.random()*4294967295>>>0;e.fill_grass_data(t,n,f,r,a,l,c,u);const d=e.memory.buffer;return{offsets:new Float32Array(d,r,o).slice(),orientations:new Float32Array(d,a,s).slice(),stretches:new Float32Array(d,l,t).slice(),halfRootAngleSin:new Float32Array(d,c,t).slice(),halfRootAngleCos:new Float32Array(d,u,t).slice()}}finally{e.dealloc_f32(r,o),e.dealloc_f32(a,s),e.dealloc_f32(l,t),e.dealloc_f32(c,t),e.dealloc_f32(u,t)}}function aS(e,t){const n=new Float32Array(e*3),o=new Float32Array(e*4),s=new Float32Array(e),r=new Float32Array(e),a=new Float32Array(e),l=new k.Quaternion,c=new k.Quaternion,u=new k.Vector3(1,0,0),f=new k.Vector3(0,0,1),d=Math.ceil(Math.sqrt(e)),p=t/d,h=p*.9;let v=0,b=0;for(let S=0;S<e;S++){const x=S%d,_=S/d|0,g=(Math.random()-.5)*h,y=(Math.random()-.5)*h,w=(x+.5)*p-t/2+g,j=(_+.5)*p-t/2+y;n[v]=w,n[v+1]=Wa(w,j),n[v+2]=j,v+=3;const N=Math.PI-Math.random()*(Math.PI/6);r[S]=Math.sin(.5*N),a[S]=Math.cos(.5*N),l.setFromAxisAngle(f,N),c.setFromAxisAngle(u,Math.random()*Math.PI/8),l.multiply(c),o[b]=l.x,o[b+1]=l.y,o[b+2]=l.z,o[b+3]=l.w,b+=4,s[S]=.7+Math.random()*.45}return{offsets:n,orientations:o,stretches:s,halfRootAngleCos:a,halfRootAngleSin:r}}function lS(e,t,n){const o=Math.ceil(Math.sqrt(t)),r=n/o*.9,a=e.offsets,l=e.stretches;for(let c=0;c<t;c++){const u=c*3,f=(a[u]??0)+(Math.random()-.5)*r,d=(a[u+2]??0)+(Math.random()-.5)*r;a[u]=f,a[u+2]=d,a[u+1]=Wa(f,d),l[c]=.7+Math.random()*.55}}const Ua=m.memo(({options:e={bW:.14,bH:.65,joints:5},width:t=4,instances:n,density:o,maxInstances:s=18e3,toon:r,lod:a,center:l,groundColor:c,groundAccentColor:u,bladeTipColor:f,bladeBottomColor:d,bladeDiffuseUrl:p,bladeAlphaUrl:h,...v})=>{const{bW:b,bH:S,joints:x}=e,_=$d(Z=>Z.profile.instanceScale),g=m.useMemo(()=>{const Z=Math.max(64,Math.min(s,Math.round(s*_)));if(typeof n=="number"&&n>0)return Math.max(1,Math.min(Z,Math.floor(n*_)));const q=typeof o=="number"&&o>0?o:90,X=Math.max(1,t*t);return Math.max(64,Math.min(Z,Math.round(q*X*_)))},[n,o,t,s,_]),y=r??R.getDefaultToonMode(),w=eS(y),j=m.useMemo(()=>new k.Color(c??tS),[c]),N=m.useMemo(()=>new k.Color(u??nS),[u]),B=m.useMemo(()=>new k.Color(f??"#8fbc5a").convertSRGBToLinear(),[f]),z=m.useMemo(()=>new k.Color(d??"#355b2d").convertSRGBToLinear(),[d]),W=m.useRef(null),D=m.useRef(null),E=m.useRef(g),G=m.useRef(null),T=m.useRef(null),O=m.useMemo(()=>V1({...p?{bladeDiffuseUrl:p}:{},...h?{bladeAlphaUrl:h}:{}}),[p,h]),{texture:P,alphaMap:L}=sS(O),[M,F]=m.useState(null);m.useEffect(()=>{Df().then(Z=>{Z&&(F(Z),Z1(Z))})},[]);const U=m.useMemo(()=>{const Z=M?rS(M,g,t):aS(g,t);return lS(Z,g,t),Z},[g,t,M]),[V,Y]=m.useMemo(()=>{const Z=new k.PlaneGeometry(b,S,1,x).translate(0,S/2,0),q=Math.max(8,Math.min(128,Math.round(t*1.5))),X=new k.PlaneGeometry(t,t,q,q),A=X.getAttribute("position"),C=new Float32Array(A.count*3),H=new k.Color;for(let K=0;K<A.count;K++){const Q=A.getX(K),ee=A.getZ(K);A.setY(K,Wa(Q,ee));const ne=.5+.5*to(Q*.18,ee*.18),ie=.5+.5*to(Q*.04+11.3,ee*.04-7.7),re=.5+.5*to(Q*.55-3.1,ee*.55+9.4),J=k.MathUtils.clamp(ne*.65+ie*.45,0,1);H.copy(j).multiplyScalar(.58+J*.42).lerp(N,ie*.28),re>.86&&H.lerp(iS,(re-.86)*4);const ce=K*3;C[ce]=H.r,C[ce+1]=H.g,C[ce+2]=H.b}return X.setAttribute("color",new k.BufferAttribute(C,3)),X.computeVertexNormals(),[Z,X]},[N,b,S,j,x,t]);return m.useEffect(()=>()=>{V.dispose(),Y.dispose()},[V,Y]),m.useEffect(()=>{const Z=T.current;Z&&(Z.instanceCount=g,E.current=g)},[g,U]),m.useEffect(()=>{const Z=G.current;Z?.uniforms&&(Z.uniforms.uToon&&(Z.uniforms.uToon.value=y?1:0),Z.uniforms.uToonSteps&&(Z.uniforms.uToonSteps.value=4),Z.uniforms.tipColor&&Z.uniforms.tipColor.value.copy(B),Z.uniforms.bottomColor&&Z.uniforms.bottomColor.value.copy(z))},[z,B,y]),m.useEffect(()=>{const Z=W.current,q=new k.Vector3;l?q.set(l[0],l[1],l[2]):Z&&(Z.updateWorldMatrix(!0,!1),Z.getWorldPosition(q));const X=C=>{const H=D.current,K=T.current,Q=G.current?.uniforms;!H||!K||!Q||(H.visible!==C.visible&&(H.visible=C.visible),K.instanceCount!==C.instanceCount&&(K.instanceCount=C.instanceCount,E.current=C.instanceCount),Q.time&&(Q.time.value=C.time),Q.windScale&&(Q.windScale.value=C.windScale),Q.trampleCenter&&Q.trampleCenter.value.copy(C.trampleCenter),Q.trampleStrength&&(Q.trampleStrength.value=C.trampleStrength))},A=bo().register({width:t,height:S*1.4,center:q,maxInstances:g,...a?{lod:a}:{},apply:X});return()=>{bo().unregister(A.id)}},[t,S,g,l?.[0],l?.[1],l?.[2],a?.near,a?.far,a?.strength]),m.useEffect(()=>{const Z=T.current;if(!Z)return;const q=Math.hypot(t,S*1.4)*.6;Z.boundingSphere=new k.Sphere(new k.Vector3(0,S*.5,0),q),Z.boundingBox=new k.Box3(new k.Vector3(-t*.5,0,-t*.5),new k.Vector3(t*.5,S*1.6,t*.5))},[t,S]),i.jsxs("group",{ref:W,...v,children:[i.jsxs("mesh",{ref:D,frustumCulled:!0,children:[i.jsxs("instancedBufferGeometry",{ref:T,index:V.index,"attributes-position":V.getAttribute("position"),"attributes-uv":V.getAttribute("uv"),children:[i.jsx("instancedBufferAttribute",{attach:"attributes-offset",args:[U.offsets,3]}),i.jsx("instancedBufferAttribute",{attach:"attributes-orientation",args:[U.orientations,4]}),i.jsx("instancedBufferAttribute",{attach:"attributes-stretch",args:[U.stretches,1]}),i.jsx("instancedBufferAttribute",{attach:"attributes-halfRootAngleSin",args:[U.halfRootAngleSin,1]}),i.jsx("instancedBufferAttribute",{attach:"attributes-halfRootAngleCos",args:[U.halfRootAngleCos,1]})]}),i.jsx("grassMaterial",{ref:G,map:P??null,alphaMap:L??null,toneMapped:!1,side:k.DoubleSide,transparent:!0})]}),i.jsx("mesh",{position:[0,0,0],rotation:[-Math.PI/2,0,0],material:w,receiveShadow:!0,children:i.jsx("primitive",{object:Y,attach:"geometry"})})]})});Ua.displayName="Grass";const Mc=25,Cc=90,Nc=4,Uf={north:!0,south:!0,east:!0,west:!0};function cS(e,t,n){const s=R.TILE_CONSTANTS.GRID_CELL_SIZE*(e.size||1)/2;return t>e.position.x-s+.001&&t<e.position.x+s-.001&&n>e.position.z-s+.001&&n<e.position.z+s-.001}function uS(e,t){const n=R.TILE_CONSTANTS.GRID_CELL_SIZE*(e.size||1),o=n/2,s=Math.max(.08,n*.06),r=Math.max(.12,R.TILE_CONSTANTS.HEIGHT_STEP*.25),a=t??[];if(a.length===0)return Uf;const l=(c,u)=>{for(const f of a)if(f.id!==e.id&&!(Math.abs(f.position.y-e.position.y)>r)&&cS(f,c,u))return!0;return!1};return{north:!l(e.position.x,e.position.z-o-s),south:!l(e.position.x,e.position.z+o+s),west:!l(e.position.x-o-s,e.position.z),east:!l(e.position.x+o+s,e.position.z)}}const dS=new Set(["sand","snowfield"]);function fS({tile:e,tiles:t}){if(!e.objectType||e.objectType==="none"||dS.has(e.objectType))return null;const n=m.useRef(null),o=m.useRef(!0),s=m.useRef(0),r=R.TILE_CONSTANTS.GRID_CELL_SIZE*(e.size||1),a=[e.position.x,e.position.y,e.position.z],l=m.useMemo(()=>e.objectType==="water"?uS(e,t):Uf,[e,t]);return be.useFrame((c,u)=>{s.current+=u;const f=o.current?.3:.8;if(s.current<f)return;s.current=0;const d=c.camera.position,p=e.position,h=d.x-p.x,v=d.y-p.y,b=d.z-p.z,S=Math.sqrt(h*h+v*v+b*b),_=se.weightFromDistance(S,Mc,Cc,Nc)>0;_!==o.current&&(o.current=_,n.current&&(n.current.visible=_))}),i.jsx("group",{ref:n,position:a,children:i.jsxs(m.Suspense,{fallback:null,children:[e.objectType==="water"&&i.jsx(Ha,{size:r,shore:l,center:a,lod:{near:Mc,far:Cc,strength:Nc}}),e.objectType==="grass"&&i.jsx(Ua,{width:r,density:e.objectConfig?.grassDensity??90,...e.objectConfig?.terrainColor?{groundColor:e.objectConfig.terrainColor}:{},...e.objectConfig?.terrainAccentColor?{groundAccentColor:e.objectConfig.terrainAccentColor}:{},...e.objectConfig?.terrainColor?{bladeBottomColor:e.objectConfig.terrainColor}:{},...e.objectConfig?.terrainAccentColor?{bladeTipColor:e.objectConfig.terrainAccentColor}:{},position:[0,.05,0]})]})})}const pS={grass:.05,sand:.065,snowfield:.055,water:.055},hS={near:25,far:90,strength:4};function mS(e){return e-Math.floor(e)}function qn(...e){const t=e.reduce((n,o,s)=>n+o*(s*19.19+7.13),0);return mS(Math.sin(t)*43758.5453123)}function Gt(e){return e.shape??"box"}function qo(e,t){return e.materialId??t}function ra(e,t,n){const o=Math.cos(n),s=Math.sin(n);return[e*o+t*s,t*o-e*s]}function Va(e){const t=(e.size||1)*R.TILE_CONSTANTS.GRID_CELL_SIZE,n=Math.max(4,Math.min(8,(e.size||1)*4)),o=Math.max(e.position.y,R.TILE_CONSTANTS.HEIGHT_STEP),s=o/n,r=t/n,a=Math.max(n*4,Math.ceil(o/.08)),l=e.rotation??0;return{tileSize:t,stepCount:n,totalHeight:o,stepHeight:s,stepDepth:r,colliderSlices:a,rotation:l}}function Tc(e){const t=(e.size||1)*R.TILE_CONSTANTS.GRID_CELL_SIZE,n=Math.max(12,Math.min(24,Math.ceil(t/.25))),o=Math.max(e.position.y,R.TILE_CONSTANTS.HEIGHT_STEP),s=o/n,r=t/n,a=e.rotation??0;return{tileSize:t,rampSlices:n,totalHeight:o,sliceHeight:s,sliceDepth:r,rotation:a}}function aa(e){const n=(e.size||1)*R.TILE_CONSTANTS.GRID_CELL_SIZE/2,o=e.objectType?pS[e.objectType]??0:0;return{id:e.id,topY:e.position.y+o,minX:e.position.x-n,maxX:e.position.x+n,minZ:e.position.z-n,maxZ:e.position.z+n,centerX:e.position.x,centerZ:e.position.z,segments:e.size||1}}function Vf(e,t,n,o){let s=0;for(const r of e)r.id!==t&&n>r.minX+.001&&n<r.maxX-.001&&o>r.minZ+.001&&o<r.maxZ-.001&&(s=Math.max(s,r.topY));return s}function gS(e,t,n,o,s,r,a,l){const c=(u,f)=>{e.push(u[0],u[1],u[2]),t.push(f.r,f.g,f.b)};c(n,a),c(o,a),c(s,l),c(n,a),c(s,l),c(r,l)}function Hi(e,t,n,o,s){e.push(t[0],t[1],t[2],n[0],n[1],n[2],o[0],o[1],o[2],t[0],t[1],t[2],o[0],o[1],o[2],s[0],s[1],s[2])}function bS(e,t,n){const o=[],s=[],r=[],a=t.map(aa),l=e.map(aa),c=new k.Color("#7b6a58"),u=new k.Color("#433930"),f=R.TILE_CONSTANTS.GRID_CELL_SIZE,d=(h,v,b,S,x,_,g,y,w,j)=>{const N=Vf(a,h.id,_,g);if(h.topY<=N+.02)return;const B=h.topY-N,z=.72+qn(j,h.centerX,h.centerZ)*.16,W=.42+qn(j,h.topY)*.08,D=n.clone().lerp(c,.28+Math.min(B,2)*.08).multiplyScalar(z),E=n.clone().lerp(u,.7).multiplyScalar(W);if(gS(o,s,[v,h.topY,b],[S,h.topY,x],[S,N,x],[v,N,b],D,E),B<R.TILE_CONSTANTS.HEIGHT_STEP*.95)return;const G=qn(j,N,B);if(G<.58)return;const T=(v+S)*.5,O=(b+x)*.5,P=.12+Math.min(B,2.5)*.06,L=.08+G*.08;r.push({position:[T+y*(.18+G*.24),N+P*.65,O+w*(.18+G*.24)],rotation:[G*Math.PI*1.7,G*Math.PI*2.9,G*Math.PI*.9],scale:[P+L*.6,P*.9+L*.45,P+L]})};for(const h of l){if(h.topY<=.02)continue;const b=-(h.segments*f)/2;for(let S=0;S<h.segments;S++){const x=b+S*f,_=x+f,g=x+f*.5;d(h,h.maxX,h.centerZ+x,h.maxX,h.centerZ+_,h.maxX+.02,h.centerZ+g,1,0,qn(h.centerX,h.centerZ,S,1)),d(h,h.minX,h.centerZ+_,h.minX,h.centerZ+x,h.minX-.02,h.centerZ+g,-1,0,qn(h.centerX,h.centerZ,S,2)),d(h,h.centerX+_,h.minZ,h.centerX+x,h.minZ,h.centerX+g,h.minZ-.02,0,-1,qn(h.centerX,h.centerZ,S,3)),d(h,h.centerX+x,h.maxZ,h.centerX+_,h.maxZ,h.centerX+g,h.maxZ+.02,0,1,qn(h.centerX,h.centerZ,S,4))}}const p=new k.BufferGeometry;return o.length>0&&(p.setAttribute("position",new k.Float32BufferAttribute(o,3)),p.setAttribute("color",new k.Float32BufferAttribute(s,3)),p.computeVertexNormals(),p.computeBoundingBox(),p.computeBoundingSphere()),{sideGeometry:p,rocks:r}}function xS(e,t){const n=t.map(aa),{tileSize:o,totalHeight:s,rotation:r}=Va(e),[a,l]=ra(0,o/2+.04,r);return Vf(n,e.id,e.position.x+a,e.position.z+l)+.02<s}function yS(e,t){const n=new k.BufferGeometry,o=[],{tileSize:s,stepCount:r,stepHeight:a,stepDepth:l,totalHeight:c}=Va(e),u=s/2;for(let f=0;f<r;f++){const d=-u+f*l,p=d+l,h=a*(f+1),v=a*f;Hi(o,[-u,h,d],[-u,h,p],[u,h,p],[u,h,d]),Hi(o,[-u,v,d],[-u,h,d],[u,h,d],[u,v,d]),Hi(o,[-u,0,d],[-u,0,p],[-u,h,p],[-u,h,d]),Hi(o,[u,0,p],[u,0,d],[u,h,d],[u,h,p])}return t&&Hi(o,[-u,0,u],[u,0,u],[u,c,u],[-u,c,u]),n.setAttribute("position",new k.Float32BufferAttribute(o,3)),n.computeVertexNormals(),n.computeBoundingBox(),n.computeBoundingSphere(),n}function vS({tile:e,material:t,supportTiles:n}){const o=e.rotation??0,s=m.useMemo(()=>xS(e,n),[n,e]),r=m.useMemo(()=>yS(e,s),[e,s]);return m.useEffect(()=>()=>{r.dispose()},[r]),i.jsx("mesh",{position:[e.position.x,0,e.position.z],rotation:[0,o,0],geometry:r,material:t,castShadow:!0,receiveShadow:!0})}function wS({batch:e,geometry:t,dummy:n}){const o=m.useRef(null);return m.useLayoutEffect(()=>{const s=o.current;if(!s)return;const r=R.TILE_CONSTANTS.GRID_CELL_SIZE;s.count=e.tiles.length;for(let a=0;a<e.tiles.length;a++){const l=e.tiles[a];if(!l)continue;const c=l.size||1,u=r*c;n.position.set(l.position.x,l.position.y+.001,l.position.z),n.rotation.set(0,l.rotation??0,0),n.scale.set(u,1,u),n.updateMatrix(),s.setMatrixAt(a,n.matrix)}s.instanceMatrix.needsUpdate=!0,e.tiles.length>0&&(s.computeBoundingBox(),s.computeBoundingSphere())},[e.tiles,n]),i.jsx("instancedMesh",{ref:o,args:[t,e.material,Math.max(1,e.tiles.length)],castShadow:!0,receiveShadow:!0,frustumCulled:!0})}function SS(e){if(e.length===0)return[];const t=R.TILE_CONSTANTS.GRID_CELL_SIZE/2,n=new Map;for(const s of e){const l=Math.max(1,Math.round(s.size||1))*R.TILE_CONSTANTS.GRID_CELL_SIZE/2,c=Math.round((s.position.x-l)/t),u=Math.round((s.position.x+l)/t),f=Math.round((s.position.z-l)/t),d=Math.round((s.position.z+l)/t),p=Math.round(s.position.y*1e3);let h=n.get(p);h||(h=new Set,n.set(p,h));for(let v=f;v<d;v+=1)for(let b=c;b<u;b+=1)h.add(`${b}:${v}`)}const o=[];for(const[s,r]of n){const a=new Set(r);for(;a.size>0;){let l=0,c=0,u=!1;for(const _ of a){const[g,y]=_.split(":").map(Number);(!u||y<c||y===c&&g<l)&&(l=g,c=y,u=!0)}let f=1;for(;a.has(`${l+f}:${c}`);)f+=1;let d=1,p=!0;for(;p;){const _=c+d;for(let g=0;g<f;g+=1)if(!a.has(`${l+g}:${_}`)){p=!1;break}p&&(d+=1)}for(let _=0;_<d;_+=1)for(let g=0;g<f;g+=1)a.delete(`${l+g}:${c+_}`);const h=f*t,v=d*t,b=(l+f/2)*t,S=(c+d/2)*t,x=s/1e3;o.push({key:`${s}:${l}:${c}:${f}:${d}`,center:[b,x,S],width:h,depth:v})}}return o}function Yf({tileGroup:e,meshes:t,isEditMode:n=!1,selectedTileId:o=null,onTileClick:s}){const r=m.useRef(new Sn),a=m.useRef(null),l=m.useMemo(()=>e.tiles.filter(M=>Gt(M)==="box"),[e.tiles]),c=m.useMemo(()=>e.tiles.filter(M=>Gt(M)==="stairs"),[e.tiles]),u=m.useMemo(()=>e.tiles.filter(M=>Gt(M)==="ramp"),[e.tiles]),f=m.useMemo(()=>e.tiles.filter(M=>Gt(M)==="round"),[e.tiles]),d=m.useMemo(()=>{const M=r.current,F=t.get(e.floorMeshId);if(!F){a.current?.dispose();const U=R.getDefaultToonMode()?new k.MeshToonMaterial({color:"#888888",gradientMap:R.getToonGradient(4)}):new k.MeshStandardMaterial({color:"#888888"});return a.current=U,U}return a.current?.dispose(),a.current=null,M.getMaterial(F)},[e.floorMeshId,t]),p=m.useMemo(()=>{const M=r.current,F=new Map;F.set(e.floorMeshId,d);for(const U of e.tiles){if(!U.materialId||F.has(U.materialId))continue;const V=t.get(U.materialId);F.set(U.materialId,V?M.getMaterial(V):d)}return F},[d,t,e.floorMeshId,e.tiles]),h=m.useMemo(()=>{const M=new Map;for(const F of l){const U=qo(F,e.floorMeshId),V=M.get(U)??[];V.push(F),M.set(U,V)}return Array.from(M.entries()).map(([F,U])=>({materialId:F,tiles:U,material:p.get(F)??d}))},[l,d,p,e.floorMeshId]),v=m.useMemo(()=>{const M=t.get(e.floorMeshId);return new k.Color(M?.color||"#8a806f")},[e.floorMeshId,t]),b=m.useMemo(()=>bS(l,e.tiles,v),[l,e.tiles,v]),S=m.useMemo(()=>R.getDefaultToonMode()?new k.MeshToonMaterial({vertexColors:!0,side:k.DoubleSide,gradientMap:R.getToonGradient(4)}):new k.MeshStandardMaterial({vertexColors:!0,roughness:.98,metalness:.02,side:k.DoubleSide}),[]),x=m.useMemo(()=>new k.DodecahedronGeometry(1,0),[]),_=m.useMemo(()=>{const M=new k.BufferGeometry,F=new Float32Array([-.5,0,-.5,.5,0,-.5,-.5,0,.5,.5,0,.5,-.5,1,.5,.5,1,.5]),U=[0,1,3,0,3,2,0,1,5,0,5,4,0,2,4,1,5,3,2,3,5,2,5,4];return M.setAttribute("position",new k.BufferAttribute(F,3)),M.setIndex(U),M.computeVertexNormals(),M},[]),g=m.useMemo(()=>R.getDefaultToonMode()?new k.MeshToonMaterial({color:"#71695f",gradientMap:R.getToonGradient(3)}):new k.MeshStandardMaterial({color:"#71695f",roughness:1,metalness:.02}),[]),y=m.useMemo(()=>{const M=new k.PlaneGeometry(1,1,1,1);return M.rotateX(-Math.PI/2),M},[]),w=m.useMemo(()=>new k.Object3D,[]),j=m.useRef(null),N=m.useMemo(()=>new k.BoxGeometry(1,1,1),[]),B=m.useMemo(()=>R.getDefaultToonMode()?new k.MeshToonMaterial({color:"#60a5fa",transparent:!0,opacity:.14,emissive:new k.Color("#2563eb"),emissiveIntensity:.08,gradientMap:R.getToonGradient(3),wireframe:!0,depthWrite:!1}):new k.MeshStandardMaterial({color:"#60a5fa",transparent:!0,opacity:.14,emissive:new k.Color("#2563eb"),emissiveIntensity:.08,wireframe:!0,depthWrite:!1}),[]),z=m.useMemo(()=>R.getDefaultToonMode()?new k.MeshToonMaterial({color:"#bae6fd",transparent:!0,opacity:.28,emissive:new k.Color("#60a5fa"),emissiveIntensity:.18,gradientMap:R.getToonGradient(3),wireframe:!0,depthWrite:!1}):new k.MeshStandardMaterial({color:"#bae6fd",transparent:!0,opacity:.28,emissive:new k.Color("#60a5fa"),emissiveIntensity:.18,wireframe:!0,depthWrite:!1}),[]),W=m.useMemo(()=>e.tiles.filter(M=>Gt(M)==="box"&&M.objectType==="sand"),[e.tiles]),D=m.useMemo(()=>W.map(M=>({position:[M.position.x,M.position.y,M.position.z],size:R.TILE_CONSTANTS.GRID_CELL_SIZE*(M.size||1),...M.objectConfig?.terrainColor?{color:M.objectConfig.terrainColor}:{},...M.objectConfig?.terrainAccentColor?{accentColor:M.objectConfig.terrainAccentColor}:{}})),[W]),E=m.useMemo(()=>e.tiles.filter(M=>Gt(M)==="box"&&M.objectType==="snowfield"),[e.tiles]),G=m.useMemo(()=>E.map(M=>({position:[M.position.x,M.position.y,M.position.z],size:R.TILE_CONSTANTS.GRID_CELL_SIZE*(M.size||1),...M.objectConfig?.terrainColor?{color:M.objectConfig.terrainColor}:{},...M.objectConfig?.terrainAccentColor?{accentColor:M.objectConfig.terrainAccentColor}:{}})),[E]),T=m.useMemo(()=>e.tiles.filter(M=>M.objectType&&M.objectType!=="none"&&Gt(M)==="box"&&M.objectType!=="water"&&M.objectType!=="sand"&&M.objectType!=="snowfield"),[e.tiles]),O=m.useMemo(()=>e.tiles.filter(M=>Gt(M)==="box"&&M.objectType==="water"),[e.tiles]),P=m.useMemo(()=>SS(O),[O]),L=m.useMemo(()=>{const M=[];for(const F of e.tiles){const U=Gt(F),V=(F.size||1)*R.TILE_CONSTANTS.GRID_CELL_SIZE,Y=F.rotation??0;if(U==="stairs"){const{tileSize:A,totalHeight:C,colliderSlices:H,rotation:K}=Va(F),Q=C/H,ee=A/H;for(let ne=0;ne<H;ne++){const ie=Q*(ne+1),re=-A/2+ee*ne+ee/2,[J,ce]=ra(0,re,K);M.push({key:`${F.id}-stair-collider-${ne}`,position:[F.position.x+J,ie/2,F.position.z+ce],rotation:[0,K,0],args:[A/2,ie/2,ee/2]})}continue}if(U==="ramp"){const{tileSize:A,rampSlices:C,sliceHeight:H,sliceDepth:K,rotation:Q}=Tc(F);for(let ee=0;ee<C;ee++){const ne=H*(ee+1),ie=-A/2+K*ee+K/2,[re,J]=ra(0,ie,Q);M.push({key:`${F.id}-ramp-${ee}`,position:[F.position.x+re,ne/2,F.position.z+J],rotation:[0,Q,0],args:[A/2,ne/2,K/2]})}continue}if(U==="round"){const A=F.position.y>.02,C=A?F.position.y:.04,H=A?C/2:-.02,K=V/2,Q=K*.34;M.push({key:`${F.id}-core`,position:[F.position.x,H,F.position.z],rotation:[0,0,0],args:[K*.46,C/2,K*.46]});for(let ee=0;ee<4;ee++)M.push({key:`${F.id}-ring-${ee}`,position:[F.position.x,H,F.position.z],rotation:[0,Math.PI/4*ee,0],args:[K*.82,C/2,Q]});continue}const Z=F.position.y>.02,q=Z?F.position.y*.5:.02,X=Z?F.position.y*.5:-.02;M.push({key:F.id,position:[F.position.x,X,F.position.z],rotation:[0,Y,0],args:[V/2,q,V/2]})}return M},[e.tiles]);return m.useLayoutEffect(()=>{const M=j.current;if(M&&b.rocks.length>0){M.count=b.rocks.length;for(let F=0;F<b.rocks.length;F++){const U=b.rocks[F];w.position.set(U.position[0],U.position[1],U.position[2]),w.rotation.set(U.rotation[0],U.rotation[1],U.rotation[2]),w.scale.set(U.scale[0],U.scale[1],U.scale[2]),w.updateMatrix(),M.setMatrixAt(F,w.matrix)}M.instanceMatrix.needsUpdate=!0}},[b.rocks,w]),m.useEffect(()=>{if(e.tiles.length===0)return;const M=Jn.MinimapSystem.getInstance(),F=new k.Box3,U=new k.Vector3;e.tiles.forEach(Z=>{const X=(Z.size||1)*R.TILE_CONSTANTS.GRID_CELL_SIZE/2;U.set(Z.position.x-X,Z.position.y,Z.position.z-X),F.expandByPoint(U),U.set(Z.position.x+X,Z.position.y,Z.position.z+X),F.expandByPoint(U)});const V=new k.Vector3,Y=new k.Vector3;return F.getCenter(V),F.getSize(Y),M.addMarker(`tile-group-${e.id}`,"ground",e.name||"Tiles",V,Y),()=>{M.removeMarker(`tile-group-${e.id}`)}},[e]),m.useEffect(()=>()=>{r.current.dispose(),a.current?.dispose(),a.current=null,y.dispose(),N.dispose(),B.dispose(),z.dispose()},[y,N,B,z]),m.useEffect(()=>()=>{b.sideGeometry.dispose()},[b.sideGeometry]),m.useEffect(()=>()=>{S.dispose(),x.dispose(),_.dispose(),g.dispose()},[_,x,g,S]),i.jsx(Jn.WorldProps,{type:"ground",children:i.jsxs(i.Fragment,{children:[L.length>0&&i.jsx(ct.RigidBody,{type:"fixed",colliders:!1,children:L.map(M=>i.jsx(ct.CuboidCollider,{position:M.position,rotation:M.rotation,args:M.args},`${e.id}-collider-${M.key}`))}),n&&e.tiles.map(M=>{const F=M.id===o,U=(M.size||1)*R.TILE_CONSTANTS.GRID_CELL_SIZE,V=Math.max(.22,M.position.y+.22);return i.jsx("group",{position:[M.position.x,V/2,M.position.z],scale:[U*.82,V,U*.82],onClick:()=>s?.(M.id),children:i.jsx("mesh",{geometry:N,material:F?z:B})},M.id)}),h.map(M=>i.jsx(wS,{batch:M,geometry:y,dummy:w},`${e.id}-box-${M.materialId}`)),f.map(M=>{const F=(M.size||1)*R.TILE_CONSTANTS.GRID_CELL_SIZE,U=M.position.y>.02,V=U?M.position.y:.04,Y=U?V/2:-.02,Z=qo(M,e.floorMeshId);return i.jsx("mesh",{position:[M.position.x,Y,M.position.z],material:p.get(Z)??d,castShadow:!0,receiveShadow:!0,children:i.jsx("cylinderGeometry",{args:[F/2,F/2,V,28,1,!1]})},`${M.id}-round`)}),c.map(M=>i.jsx(vS,{tile:M,material:p.get(qo(M,e.floorMeshId))??d,supportTiles:e.tiles},`${M.id}-stairs`)),u.map(M=>{const{tileSize:F,totalHeight:U,rotation:V}=Tc(M),Y=qo(M,e.floorMeshId);return i.jsx("mesh",{position:[M.position.x,0,M.position.z],rotation:[0,V,0],scale:[F,U,F],geometry:_,material:p.get(Y)??d,castShadow:!0,receiveShadow:!0},`${M.id}-ramp`)}),b.sideGeometry.getAttribute("position")&&i.jsx("mesh",{geometry:b.sideGeometry,material:S,castShadow:!0,receiveShadow:!0,frustumCulled:!1}),b.rocks.length>0&&i.jsx("instancedMesh",{ref:j,args:[x,g,Math.max(1,b.rocks.length)],castShadow:!0,receiveShadow:!0}),P.map(M=>i.jsx("group",{position:M.center,children:i.jsx(Ha,{width:M.width,depth:M.depth,center:M.center,shore:{north:!1,south:!1,east:!1,west:!1},lod:hS})},`water-${M.key}`)),T.map(M=>i.jsx(fS,{tile:M,tiles:O},`${M.id}-object`)),D.length>0&&i.jsx(Lf,{entries:D}),G.length>0&&i.jsx(Of,{entries:G})]})})}const Ct={id:"default",color:"#000000"},_S={id:"default-window-glass",color:"#9ed8ff",material:"GLASS",opacity:.42,transparent:!0,roughness:.08},jS={id:"default-door-panel",color:"#7a5232",roughness:.78};function Zf(e){return e.materialId?`material:${e.materialId}`:`type:${e.wallGroupId}`}function Xf(e,t){return e.wallKind??t.defaultWallKind??"solid"}function Kf(e,t){return Xf(e,t)==="solid"}function la(e,t,n,o,s){if(n.materialId){const d=e.getMaterial(t.get(n.materialId)??Ct);return[d,d,d,d,d,d]}const r=o.get(n.wallGroupId)??s,a=r.frontMeshId?t.get(r.frontMeshId):Ct,l=r.backMeshId?t.get(r.backMeshId):Ct,c=r.sideMeshId?t.get(r.sideMeshId):Ct,u=n.flipSides?l:a,f=n.flipSides?a:l;return[e.getMaterial(c??Ct),e.getMaterial(c??Ct),e.getMaterial(c??Ct),e.getMaterial(c??Ct),e.getMaterial(u??Ct),e.getMaterial(f??Ct)]}function MS(e,t,n,o){const s=new Map;for(const r of e.walls){if(!Kf(r,e))continue;const a=Zf(r),l=s.get(a)??[];l.push(r),s.set(a,l)}return Array.from(s.entries()).map(([r,a])=>{const l=a[0];return{key:r,walls:a,materials:l?la(o,n,l,t,e):la(o,n,{wallGroupId:e.id},t,e)}})}function CS(e){return e.getMaterial(_S)}function NS(e,t,n){const o=n.frontMeshId?t.get(n.frontMeshId):void 0;return e.getMaterial({...jS,color:o?.color?new k.Color(o.color).multiplyScalar(.72).getStyle():"#7a5232"})}function Ie({position:e,size:t,materials:n}){return i.jsx("mesh",{position:e,material:n,castShadow:!0,receiveShadow:!0,children:i.jsx("boxGeometry",{args:t})})}function TS({wall:e,wallGroup:t,wallGroups:n,meshes:o,manager:s,width:r,height:a,depth:l,onWallClick:c}){const u=Xf(e,t),f=la(s,o,e,n,t),d=CS(s),p=NS(s,o,t),h=r/2,v=a*.46,b=x=>{x.stopPropagation(),c?.(e.id)},S=(()=>{if(u==="half")return[i.jsx(Ie,{position:[0,v/2,h],size:[r,v,l],materials:f},"half")];if(u==="railing"){const x=a*.62;return[i.jsx(Ie,{position:[-r*.42,x/2,h],size:[.18,x,l],materials:f},"post-l"),i.jsx(Ie,{position:[0,x/2,h],size:[.16,x*.9,l],materials:f},"post-c"),i.jsx(Ie,{position:[r*.42,x/2,h],size:[.18,x,l],materials:f},"post-r"),i.jsx(Ie,{position:[0,x*.82,h],size:[r,.18,l],materials:f},"rail-top"),i.jsx(Ie,{position:[0,x*.48,h],size:[r*.88,.12,l],materials:f},"rail-mid")]}if(u==="door"||u==="arch"){const x=r*.24,_=r-x*2,g=u==="arch"?a*.34:a*.22,y=a-g;return[i.jsx(Ie,{position:[-(_+x)/2,a/2,h],size:[x,a,l],materials:f},"left"),i.jsx(Ie,{position:[(_+x)/2,a/2,h],size:[x,a,l],materials:f},"right"),i.jsx(Ie,{position:[0,a-g/2,h],size:[_,g,l],materials:f},"top"),i.jsx(Ie,{position:[0,y/2,h-l*.07],size:[_*.76,y*.94,l*.34],materials:p},"door")]}if(u==="window"){const x=r*.22,_=a*.24,g=r-x*2,y=a-_*2;return[i.jsx(Ie,{position:[-(g+x)/2,a/2,h],size:[x,a,l],materials:f},"left"),i.jsx(Ie,{position:[(g+x)/2,a/2,h],size:[x,a,l],materials:f},"right"),i.jsx(Ie,{position:[0,_/2,h],size:[g,_,l],materials:f},"bottom"),i.jsx(Ie,{position:[0,a-_/2,h],size:[g,_,l],materials:f},"top"),i.jsx(Ie,{position:[0,a/2,h-l*.08],size:[g*.82,y*.72,l*.24],materials:d},"glass")]}return[i.jsx(Ie,{position:[0,a/2,h],size:[r,a,l*.4],materials:d},"glass-wall"),i.jsx(Ie,{position:[0,a-.08,h],size:[r,.16,l],materials:f},"frame-top"),i.jsx(Ie,{position:[0,.08,h],size:[r,.16,l],materials:f},"frame-bottom"),i.jsx(Ie,{position:[-r/2+.08,a/2,h],size:[.16,a,l],materials:f},"frame-left"),i.jsx(Ie,{position:[r/2-.08,a/2,h],size:[.16,a,l],materials:f},"frame-right")]})();return i.jsx("group",{position:[e.position.x,e.position.y,e.position.z],rotation:[0,e.rotation.y,0],...c?{onClick:b}:{},children:S})}function IS({batch:e,geometry:t,height:n,onWallClick:o}){const s=m.useRef(null),r=e.walls.length,[a,l]=m.useState(()=>Math.max(1,r)),c=m.useMemo(()=>new k.Object3D,[]);m.useEffect(()=>{r<=a||l(Math.max(r,Math.ceil(a*1.5)))},[r,a]),m.useLayoutEffect(()=>{const f=s.current;if(f){f.count=r;for(let d=0;d<r;d++){const p=e.walls[d];p&&(c.position.set(p.position.x,p.position.y+n/2,p.position.z),c.rotation.set(0,p.rotation.y,0),c.updateMatrix(),f.setMatrixAt(d,c.matrix))}f.instanceMatrix.needsUpdate=!0,r>0&&(f.computeBoundingBox(),f.computeBoundingSphere())}},[e.walls,r,c,n,a]);const u=f=>{f.stopPropagation();const d=f.instanceId!==void 0?e.walls[f.instanceId]:void 0;d&&o?.(d.id)};return i.jsx("instancedMesh",{ref:s,args:[t,e.materials,a],castShadow:!0,receiveShadow:!0,...o?{onClick:u}:{}})}function qf({wallGroup:e,wallGroups:t,meshes:n,isEditMode:o=!1,selectedWallId:s=null,onWallClick:r}){const a=m.useRef(new Sn),l=R.TILE_CONSTANTS.WALL_SIZES.WIDTH,c=R.TILE_CONSTANTS.WALL_SIZES.HEIGHT,u=R.TILE_CONSTANTS.WALL_SIZES.THICKNESS,f=m.useMemo(()=>{const b=new k.BoxGeometry(l,c,u);return b.translate(0,0,l/2),b},[l,c,u]),d=m.useMemo(()=>MS(e,t??new Map([[e.id,e]]),n,a.current),[e,t,n]),p=t??new Map([[e.id,e]]),h=m.useMemo(()=>e.walls.filter(b=>!Kf(b,e)),[e]);m.useEffect(()=>()=>{a.current.dispose(),f.dispose()},[f]);const v=m.useMemo(()=>{if(o)return[];const b=l/2;return e.walls.map(S=>{const x=Math.sin(S.rotation.y),_=Math.cos(S.rotation.y);return{id:S.id,position:[S.position.x+x*b,S.position.y+c/2,S.position.z+_*b],rotation:[0,S.rotation.y,0]}})},[e.walls,l,c,o]);return i.jsxs(i.Fragment,{children:[!o&&v.length>0&&i.jsx(ct.RigidBody,{type:"fixed",colliders:!1,children:v.map(b=>i.jsx(ct.CuboidCollider,{position:b.position,rotation:b.rotation,args:[l/2,c/2,u/2]},b.id))}),o&&e.walls.map(b=>{const S=b.id===s;return i.jsx("group",{position:[b.position.x,b.position.y+c+.5,b.position.z],onClick:()=>r?.(b.id),children:i.jsxs("mesh",{scale:S?1.28:1,children:[i.jsx("sphereGeometry",{args:[.22,16,16]}),i.jsx("meshStandardMaterial",{color:S?"#bae6fd":"#7dd3fc",emissive:S?"#60a5fa":"#2f8dbd",emissiveIntensity:S?.5:.22,transparent:!0,opacity:S?.94:.78})]})},b.id)}),d.map(b=>i.jsx(IS,{batch:b,geometry:f,height:c,...r?{onWallClick:r}:{}},`${e.id}-${b.key}`)),h.map(b=>i.jsx(TS,{wall:b,wallGroup:e,wallGroups:p,meshes:n,manager:a.current,width:l,height:c,depth:u,...r?{onWallClick:r}:{}},b.id))]})}function Qf(e){return e.type==="tree"||e.type==="sakura"}function ES(e){return e.type==="sakura"?"sakura":e.config?.treeKind??"oak"}const AS={sakura:[],flag:[],fire:[],billboard:[],model:[]};function Re(e,t){return t<=0?[]:e.length<=t?e:e.slice(0,t)}function kS(e){const t=e.tiles.find(n=>n.objectType&&n.objectType!=="none")?.objectType??"none";return t==="water"?Ei:t==="sand"?Ai:t==="snowfield"?ki:t==="grass"?Ii:Ti}function BS(e){if(!e||e.length===0)return AS;const t={sakura:[],flag:[],fire:[],billboard:[],model:[]};for(const n of e)Qf(n)?t.sakura.push({position:[n.position.x,n.position.y,n.position.z],size:n.config?.size??R.TILE_CONSTANTS.GRID_CELL_SIZE,treeKind:ES(n),...n.config?.primaryColor?{blossomColor:n.config.primaryColor}:{},...n.config?.secondaryColor?{barkColor:n.config.secondaryColor}:{}}):n.type==="flag"?t.flag.push(n):n.type==="fire"?t.fire.push({position:[n.position.x,n.position.y,n.position.z],rotation:n.rotation??0,intensity:n.config?.fireIntensity??1.5,width:n.config?.fireWidth??1,height:n.config?.fireHeight??1.5,color:n.config?.fireColor??"#ffffff"}):n.type==="billboard"?t.billboard.push(n):n.type==="model"&&t.model.push(n);return t}const Jf=m.memo(function({onWallClick:t,onTileClick:n,onBlockClick:o,onWallDelete:s,onTileDelete:r,onBlockDelete:a}){const l=R.useBuildingStore(J=>J.meshes),c=R.useBuildingStore(J=>J.wallGroups),u=R.useBuildingStore(J=>J.tileGroups),f=R.useBuildingStore(J=>J.blocks),d=R.useBuildingStore(J=>J.editMode),p=R.useBuildingStore(J=>J.selectedWallId),h=R.useBuildingStore(J=>J.selectedTileId),v=R.useBuildingStore(J=>J.selectedBlockId),b=R.useBuildingStore(J=>J.showGrid),S=R.useBuildingStore(J=>J.gridSize),x=R.useBuildingStore(J=>J.showSnow),_=R.useBuildingStore(J=>J.weatherEffect),g=R.useBuildingStore(J=>J.objects),y=Be(J=>J.drawMirror),w=Ue(J=>J.active),j=Ue(J=>J.version),N=mn(J=>J.initialized),B=mn(J=>J.visibleWallGroupIds),z=mn(J=>J.visibleTileGroupIds),W=mn(J=>J.visibleBlockIds),D=mn(J=>J.visibleObjectIds),E=w&&y.version>0&&y.version===j,G=E?He(y,Gs):Number.MAX_SAFE_INTEGER,T=E?He(y,Ti):Number.MAX_SAFE_INTEGER,O=E?He(y,Ii):Number.MAX_SAFE_INTEGER,P=E?He(y,Ei):Number.MAX_SAFE_INTEGER,L=E?He(y,Ai):Number.MAX_SAFE_INTEGER,M=E?He(y,ki):Number.MAX_SAFE_INTEGER,F=E?He(y,Hs):Number.MAX_SAFE_INTEGER,U=E?He(y,Ws):Number.MAX_SAFE_INTEGER,V=E?He(y,Us):Number.MAX_SAFE_INTEGER,Y=E?He(y,Vs):Number.MAX_SAFE_INTEGER,Z=E?He(y,Zs):Number.MAX_SAFE_INTEGER,q=E?He(y,Ys):Number.MAX_SAFE_INTEGER,X=m.useMemo(()=>{const J=Array.from(c.values()),ce=N?J.filter(de=>B.has(de.id)):J;return Re(ce,G)},[c,N,B,G]),A=m.useMemo(()=>{const J=Array.from(u.values()),ce=N?J.filter(Me=>z.has(Me.id)):J,de=[],me=[],xe=[],je=[],ve=[];for(const Me of ce){const Pe=kS(Me);Pe===Ii?me.push(Me):Pe===Ei?xe.push(Me):Pe===Ai?je.push(Me):Pe===ki?ve.push(Me):de.push(Me)}return[...Re(de,T),...Re(me,O),...Re(xe,P),...Re(je,L),...Re(ve,M)]},[u,N,z,T,O,P,L,M]),C=m.useMemo(()=>{const J=N?g.filter(ve=>D.has(ve.id)):g,ce=[],de=[],me=[],xe=[],je=[];for(const ve of J)Qf(ve)?ce.push(ve):ve.type==="flag"?de.push(ve):ve.type==="fire"?me.push(ve):ve.type==="billboard"?xe.push(ve):ve.type==="model"&&je.push(ve);return[...Re(ce,F),...Re(de,U),...Re(me,V),...Re(xe,Y),...Re(je,Z)]},[g,N,D,F,U,V,Y,Z]),H=m.useMemo(()=>{const J=f??[],ce=N?J.filter(de=>W.has(de.id)):J;return Re(ce,q)},[f,N,W,q]),K=m.useMemo(()=>BS(C),[C]),Q=Re(K.sakura,F),ee=Re(K.flag,U),ne=Re(K.fire,V),ie=Re(K.billboard,Y),re=Re(K.model,Z);return i.jsx(m.Suspense,{fallback:null,children:i.jsxs("group",{name:"building-system",children:[b&&i.jsx(hf,{size:S}),i.jsx(P1,{}),i.jsx(R1,{}),i.jsx(Pd,{}),X.map(J=>i.jsx(qf,{wallGroup:J,wallGroups:c,meshes:l,isEditMode:d==="wall",selectedWallId:p,...t?{onWallClick:t}:{},...s?{onWallDelete:s}:{}},J.id)),A.map(J=>i.jsx(Yf,{tileGroup:J,meshes:l,isEditMode:d==="tile",selectedTileId:h,...n?{onTileClick:n}:{},...r?{onTileDelete:r}:{}},J.id)),H.length>0&&i.jsx(pf,{blocks:H,meshes:l,isEditMode:d==="block",selectedBlockId:v,...o||a?{onBlockClick:o??a}:{}}),Q.length>0&&i.jsx(m.Suspense,{fallback:null,children:i.jsx(Rf,{trees:Q})}),ee.length>0&&i.jsx(m.Suspense,{fallback:null,children:i.jsx(m1,{flags:ee})}),ne.length>0&&i.jsx(m.Suspense,{fallback:null,children:i.jsx(i1,{fires:ne})}),ie.length>0&&i.jsx(m.Suspense,{fallback:null,children:i.jsx(Gw,{billboards:ie})}),re.map(J=>i.jsx("group",{position:[J.position.x,J.position.y,J.position.z],rotation:[0,J.rotation??0,0],children:i.jsx(m.Suspense,{fallback:null,children:i.jsx(y1,{...J.config?.modelUrl?{url:J.config.modelUrl}:{},...J.config?.modelLabel?{label:J.config.modelLabel}:{},...J.config?.modelFallbackKind?{fallbackKind:J.config.modelFallbackKind}:{},...J.config?.modelScale?{scale:J.config.modelScale}:{},...J.config?.modelColor?{color:J.config.modelColor}:{}})})},J.id)),_!=="none"&&i.jsx(Ld,{kind:_,count:_==="storm"?1800:1200}),x&&_!=="snow"&&i.jsx(Ga,{gpu:!0})]})})}),Ic=new k.Vector2,PS=new k.Plane(new k.Vector3(0,1,0),0),Pr=new k.Vector3;let Qo=0;function Ec(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function Ya(e,t,n){return e!=="sand"&&e!=="snowfield"?null:{id:["terrain-block",e,Ec(t),Ec(n)].join("-"),color:t,material:"STANDARD",roughness:e==="snowfield"?.78:.94}}function RS(e){return e==="sand"?{color:"#b89b66",accentColor:"#e0c27a"}:e==="snowfield"?{color:"#dcecff",accentColor:"#ffffff"}:null}function ep(e,t){let n=null,o=-1/0;for(const r of e)for(const a of r.tiles){if(a.objectType!=="sand"&&a.objectType!=="snowfield")continue;const c=(a.size??1)*R.TILE_CONSTANTS.GRID_CELL_SIZE*.5,u=t.x>=a.position.x-c&&t.x<=a.position.x+c,f=t.z>=a.position.z-c&&t.z<=a.position.z+c;!u||!f||a.position.y<o||(n=a,o=a.position.y)}if(!n)return null;const s=RS(n.objectType??"none");return s?Ya(n.objectType??"none",n.objectConfig?.terrainColor??s.color,n.objectConfig?.terrainAccentColor??s.accentColor):null}function tp(){const{camera:e,raycaster:t}=be.useThree(),n=m.useRef({x:0,y:0}),o=R.useBuildingStore(j=>j.snapPosition),s=R.useBuildingStore(j=>j.addWall),r=R.useBuildingStore(j=>j.addTile),a=R.useBuildingStore(j=>j.addBlock),l=R.useBuildingStore(j=>j.addObject),c=R.useBuildingStore(j=>j.setSelectedWallId),u=R.useBuildingStore(j=>j.setSelectedTileId),f=R.useBuildingStore(j=>j.setSelectedBlockId),d=R.useBuildingStore(j=>j.setHoverPosition),p=m.useCallback(()=>(Ic.set(n.current.x,n.current.y),t.setFromCamera(Ic,e),t.ray.intersectPlane(PS,Pr)?o({x:Pr.x,y:0,z:Pr.z}):null),[e,t,o]),h=m.useCallback(()=>{const j=p();if(!j)return null;const N=R.useBuildingStore.getState().getSupportHeightAt(j);return{...j,y:N}},[p]),v=m.useCallback(j=>{const N=j.currentTarget??j.target??null,B=N&&typeof N.getBoundingClientRect=="function"?N.getBoundingClientRect():{left:0,top:0,width:N?.clientWidth??window.innerWidth,height:N?.clientHeight??window.innerHeight};if(B.width<=0||B.height<=0){d(null);return}const z=(j.clientX-B.left)/B.width,W=(j.clientY-B.top)/B.height;n.current.x=z*2-1,n.current.y=-W*2+1;const D=R.useBuildingStore.getState().editMode;d(D==="tile"||D==="block"||D==="npc"?h():D==="wall"||D==="object"?p():null)},[p,h,d]),b=m.useCallback(()=>{const{editMode:j,selectedWallGroupId:N,currentWallRotation:B,currentWallKind:z,checkWallPosition:W,hoverPosition:D}=R.useBuildingStore.getState();if(j!=="wall"||!N||!D||W(D,B))return;const E={x:0,y:B,z:0};s(N,{id:`wall-${++Qo}-${Date.now()}`,position:D,rotation:E,wallGroupId:N,wallKind:z})},[s]),S=m.useCallback(()=>{const{editMode:j,selectedTileGroupId:N,checkTilePosition:B,getSupportHeightAt:z,currentTileMultiplier:W,currentTileHeight:D,currentTileShape:E,currentTileRotation:G,hoverPosition:T}=R.useBuildingStore.getState();if(j!=="tile"||!N||!T)return;const O=R.TILE_CONSTANTS.HEIGHT_STEP,P=z(T),L=E==="box"||E==="round"?P+D*O:Math.max(1,D)*O,M={...T,y:L};B(M)||r(N,{id:`tile-${++Qo}-${Date.now()}`,position:M,tileGroupId:N,size:W,rotation:G,shape:E})},[r]),x=m.useCallback(()=>{const{editMode:j,checkBlockPosition:N,getSupportHeightAt:B,currentTileMultiplier:z,currentTileHeight:W,selectedTileObjectType:D,currentTerrainColor:E,currentTerrainAccentColor:G,tileGroups:T,meshes:O,addMesh:P,hoverPosition:L}=R.useBuildingStore.getState();if(j!=="block"||!L)return;const M=R.TILE_CONSTANTS.HEIGHT_STEP,F=B(L),U=Math.max(1,Math.round(z)),V={...L,y:F+W*M},Y=ep(T.values(),L)??Ya(D,E,G);Y&&!O.has(Y.id)&&P(Y);const Z={id:`block-${++Qo}-${Date.now()}`,position:V,size:{x:U,y:1,z:U},materialId:Y?.id??"default-block"};N(Z)||a(Z)},[a]),_=m.useCallback(()=>{const{editMode:j,selectedPlacedObjectType:N,hoverPosition:B,tileGroups:z,currentObjectRotation:W,currentObjectPrimaryColor:D,currentObjectSecondaryColor:E,currentTreeKind:G,currentFlagWidth:T,currentFlagHeight:O,currentFlagStyle:P,currentFlagImageUrl:L,currentFireIntensity:M,currentFireWidth:F,currentFireHeight:U,currentFireColor:V,currentBillboardText:Y,currentBillboardColor:Z,currentBillboardImageUrl:q,currentBillboardWidth:X,currentBillboardHeight:A,currentBillboardScale:C,currentBillboardOffsetY:H,currentBillboardElevation:K,currentBillboardIntensity:Q,selectedModelObjectId:ee,currentModelUrl:ne,currentModelScale:ie,currentModelColor:re}=R.useBuildingStore.getState();if(j!=="object"||N==="none"||!B)return;let J=0;const ce=R.TILE_CONSTANTS.GRID_CELL_SIZE;for(const me of z.values())for(const xe of me.tiles){const je=(xe.size||1)*ce/2;Math.abs(xe.position.x-B.x)<je&&Math.abs(xe.position.z-B.z)<je&&(J=Math.max(J,xe.position.y))}const de=N==="tree"||N==="sakura"?{size:R.useBuildingStore.getState().currentTileMultiplier*ce,primaryColor:D,secondaryColor:E,treeKind:N==="sakura"?"sakura":G}:N==="flag"?{flagWidth:T,flagHeight:O,flagStyle:P,...L?{flagTexture:L}:{}}:N==="fire"?{fireIntensity:M,fireWidth:F,fireHeight:U,fireColor:V}:N==="billboard"?{billboardText:Y,billboardColor:Z,billboardHeight:A,billboardScale:C,billboardOffsetY:H,billboardElevation:K,billboardIntensity:Q,...X>0?{billboardWidth:X}:{},...q?{billboardImageUrl:q}:{}}:N==="model"?(()=>{const me=Ts(ee),xe=ne||me?.modelUrl;return{modelId:me?.id??ee,modelLabel:me?.label??ee,modelFallbackKind:me?.fallbackKind??"generic",modelScale:ie||me?.defaultScale||1,modelColor:re||me?.defaultColor||"#9b7653",...xe?{modelUrl:xe}:{}}})():void 0;l({id:`obj-${++Qo}-${Date.now()}`,type:N,position:{...B,y:N==="billboard"?J+H:J},...W!==0?{rotation:W}:{},...de?{config:de}:{}})},[l]),g=m.useCallback(j=>{const{editMode:N}=R.useBuildingStore.getState();N==="wall"&&c(j)},[c]),y=m.useCallback(j=>{const{editMode:N}=R.useBuildingStore.getState();N==="tile"&&u(j)},[u]),w=m.useCallback(j=>{const{editMode:N}=R.useBuildingStore.getState();N==="block"&&f(j)},[f]);return{updateMousePosition:v,placeWall:b,placeTile:S,placeBlock:x,placeObject:_,handleWallClick:g,handleTileClick:y,handleBlockClick:w,getGroundPosition:p}}const DS=1,FS=4,Rr=8,LS=128,zS=64,OS=1,$S=180,np=64;function Dr(){return{pipeline:null,bindGroupLayout:null,uniformBuffer:null,visibleBuffer:null,readBuffer:null,bindGroup:null,count:0,spatialBuffer:null,metaBuffer:null}}function Fr(e){e?.destroy&&e.destroy()}function Ac(e){Fr(e.uniformBuffer),Fr(e.visibleBuffer),Fr(e.readBuffer)}function GS(e,t,n,o){const s=e,r=s.createShaderModule({code:`
|
|
686
|
+
struct Params {
|
|
687
|
+
viewProj : mat4x4<f32>,
|
|
688
|
+
camera : vec4<f32>,
|
|
689
|
+
misc : vec4<f32>,
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
@group(0) @binding(0) var<storage, read> spatial : array<vec4<f32>>;
|
|
693
|
+
@group(0) @binding(1) var<storage, read> meta : array<vec4<i32>>;
|
|
694
|
+
@group(0) @binding(2) var<storage, read_write> visible : array<u32>;
|
|
695
|
+
@group(0) @binding(3) var<uniform> params : Params;
|
|
696
|
+
|
|
697
|
+
@compute @workgroup_size(${np})
|
|
698
|
+
fn main(@builtin(global_invocation_id) gid : vec3<u32>) {
|
|
699
|
+
let i = gid.x;
|
|
700
|
+
if (f32(i) >= params.misc.x) {
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
let s = spatial[i];
|
|
705
|
+
let world = vec4<f32>(s.x, s.y, s.z, 1.0);
|
|
706
|
+
let clip = params.viewProj * world;
|
|
707
|
+
let w = clip.w;
|
|
708
|
+
if (w <= 0.0) {
|
|
709
|
+
visible[i] = 0u;
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
let inflate = s.w / max(abs(w), 0.0001);
|
|
714
|
+
let ndc = clip.xyz / w;
|
|
715
|
+
let inFrustum =
|
|
716
|
+
ndc.x >= (-1.0 - inflate) &&
|
|
717
|
+
ndc.x <= ( 1.0 + inflate) &&
|
|
718
|
+
ndc.y >= (-1.0 - inflate) &&
|
|
719
|
+
ndc.y <= ( 1.0 + inflate) &&
|
|
720
|
+
ndc.z >= (-inflate) &&
|
|
721
|
+
ndc.z <= ( 1.0 + inflate);
|
|
722
|
+
|
|
723
|
+
let dx = s.x - params.camera.x;
|
|
724
|
+
let dy = s.y - params.camera.y;
|
|
725
|
+
let dz = s.z - params.camera.z;
|
|
726
|
+
let limit = params.camera.w + s.w;
|
|
727
|
+
let inRange = dx * dx + dy * dy + dz * dz <= limit * limit;
|
|
728
|
+
|
|
729
|
+
visible[i] = select(0u, 1u, inFrustum && inRange);
|
|
730
|
+
}
|
|
731
|
+
`}),a=s.createComputePipeline({layout:"auto",compute:{module:r,entryPoint:"main"}}),l=a.getBindGroupLayout(0),c=e.createBuffer({label:"building-cull-uniforms",size:96,usage:zS|Rr}),u=e.createBuffer({label:"building-cull-visible",size:Math.max(4,o*4),usage:LS|FS|Rr}),f=e.createBuffer({label:"building-cull-readback",size:Math.max(4,o*4),usage:Rr|DS}),d=s.createBindGroup({layout:l,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:n}},{binding:2,resource:{buffer:u}},{binding:3,resource:{buffer:c}}]});return{pipeline:a,bindGroupLayout:l,uniformBuffer:c,visibleBuffer:u,readBuffer:f,bindGroup:d,count:o,spatialBuffer:t,metaBuffer:n}}function ip(){const e=be.useThree(l=>l.gl),t=Be(l=>l.snapshot),n=Be(l=>l.uploadResources),o=Ue(l=>l.setResult),s=Ue(l=>l.reset),r=m.useRef({resources:Dr(),busy:!1,lastRunAt:0,readbackFlags:null}),a=m.useMemo(()=>({viewProj:new k.Matrix4,uniform:new Float32Array(24)}),[]);return m.useEffect(()=>s,[s]),m.useEffect(()=>{const l=r.current.resources;(l.count!==t.ids.length||l.spatialBuffer!==n.spatialBuffer||l.metaBuffer!==n.metaBuffer)&&(Ac(l),r.current.resources=Dr())},[t.ids.length,n]),be.useFrame(l=>{if(t.version===0||t.ids.length===0||n.backend!=="webgpu")return;const c=Ks(e);if(!c||!n.spatialBuffer||!n.metaBuffer||r.current.busy)return;const u=performance.now();if(u-r.current.lastRunAt<$S)return;r.current.lastRunAt=u,r.current.resources.pipeline||(r.current.resources=GS(c,n.spatialBuffer,n.metaBuffer,t.ids.length));const f=r.current.resources,d=a.uniform;if(a.viewProj.multiplyMatrices(l.camera.projectionMatrix,l.camera.matrixWorldInverse),d.set(a.viewProj.elements,0),d[16]=l.camera.position.x,d[17]=l.camera.position.y,d[18]=l.camera.position.z,d[19]=Nt,d[20]=t.ids.length,d[21]=0,d[22]=0,d[23]=0,!f.uniformBuffer||!f.visibleBuffer||!f.readBuffer||!f.bindGroup||!f.pipeline)return;c.queue.writeBuffer(f.uniformBuffer,0,d);const p=c,h=p.createCommandEncoder(),v=h.beginComputePass();v.setPipeline(f.pipeline),v.setBindGroup(0,f.bindGroup),v.dispatchWorkgroups(Math.max(1,Math.ceil(t.ids.length/np))),v.end(),h.copyBufferToBuffer(f.visibleBuffer,0,f.readBuffer,0,Math.max(4,t.ids.length*4)),p.queue.submit([h.finish()]),r.current.busy=!0,Promise.resolve(f.readBuffer?.mapAsync?.(OS)).then(()=>{const b=f.readBuffer?.getMappedRange?.();if(!b)return;const S=t.ids.length,x=new Uint32Array(b,0,S);(!r.current.readbackFlags||r.current.readbackFlags.length<S)&&(r.current.readbackFlags=new Uint32Array(S));const _=r.current.readbackFlags;_.set(x),f.readBuffer?.unmap?.();const g=of(t,_);o(g)}).catch(()=>{s()}).finally(()=>{r.current.busy=!1})}),m.useEffect(()=>()=>{Ac(r.current.resources),r.current.resources=Dr(),s()},[s]),null}function op(){const e=Be(o=>o.snapshot),t=Be(o=>o.setGpuMirror),n=m.useRef(Be.getState().gpuMirror);return m.useEffect(()=>{const o=lf(e,n.current);n.current=o,t(o)},[e,t]),null}function sp(){const e=be.useThree(s=>s.gl),t=Be(s=>s.gpuMirror),n=Be(s=>s.setUploadResources),o=m.useRef(go());return m.useEffect(()=>{if(t.version===0)return;const s=Ks(e);s&&(o.current=df(s,o.current,t),n(o.current))},[e,t,n]),m.useEffect(()=>()=>{uf(o.current),o.current=go(),n(o.current)},[n]),null}function rp(){const e=be.useThree(s=>s.gl),t=Be(s=>s.drawMirror),n=Be(s=>s.setUploadResources),o=m.useRef(Be.getState().uploadResources??go());return m.useEffect(()=>{o.current=Be.getState().uploadResources}),m.useEffect(()=>{if(t.version===0)return;const s=Ks(e);s&&(o.current=ff(s,o.current,t),n(o.current))},[e,t,n]),null}function ap(){const e=Ue(s=>s.version),t=Ue(s=>s.clusterCounts),n=Be(s=>s.setDrawMirror),o=m.useRef(Be.getState().drawMirror);return m.useEffect(()=>{if(e===0||t.length===0)return;const s=rf(e,t,o.current);o.current=s,n(s)},[e,t,n]),null}function lp(){const e=R.useBuildingStore(c=>c.wallGroups),t=R.useBuildingStore(c=>c.tileGroups),n=R.useBuildingStore(c=>c.blocks),o=R.useBuildingStore(c=>c.objects),s=Be(c=>c.setSnapshot),r=Be(c=>c.reset),a=m.useRef(1),l=m.useMemo(()=>jw({wallGroups:Array.from(e.values()),tileGroups:Array.from(t.values()),blocks:n??[],objects:o,version:a.current++}),[e,t,n,o]);return m.useEffect(()=>{s(l)},[l,s]),m.useEffect(()=>r,[r]),null}function Jo(e,t,n,o,s,r,a,l,c,u){for(const f of t){const d=n.get(f);if(!d)continue;const p=d.centerX-a.x,h=d.centerY-a.y,v=d.centerZ-a.z,b=c+d.radius*d.radius;p*p+h*h+v*v>b||(l.center.set(d.centerX,d.centerY,d.centerZ),l.radius=d.radius,r.intersectsSphere(l)&&(yw(d,o,a,s,u)||e.add(f)))}}function cp(){const e=Be(x=>x.snapshot),t=R.useBuildingStore(x=>x.wallGroups),n=R.useBuildingStore(x=>x.tileGroups),o=R.useBuildingStore(x=>x.blocks),s=R.useBuildingStore(x=>x.objects),r=Ue(x=>x.active),a=Ue(x=>x.version),l=Ue(x=>x.visibleTileGroupIds),c=Ue(x=>x.visibleWallGroupIds),u=Ue(x=>x.visibleBlockIds),f=Ue(x=>x.visibleObjectIds),d=mn(x=>x.setVisible),p=mn(x=>x.reset),h=m.useMemo(()=>bw(Array.from(t.values()),Array.from(n.values()),s,o??[]),[t,n,s,o]),v=m.useRef(0),b=m.useRef(new Map),S=m.useMemo(()=>({frustum:new k.Frustum,matrix:new k.Matrix4,camera:new k.Vector3,forward:new k.Vector3,sphere:new k.Sphere,targetDir:new k.Vector3,occDir:new k.Vector3,cross:new k.Vector3}),[]);return m.useEffect(()=>{b.current.clear()},[h]),m.useEffect(()=>{b.current.clear()},[r,a]),m.useEffect(()=>p,[p]),be.useFrame((x,_)=>{if(e.ids.length===0||(v.current+=Math.max(0,_),v.current<uw))return;v.current=0,S.matrix.multiplyMatrices(x.camera.projectionMatrix,x.camera.matrixWorldInverse),S.frustum.setFromProjectionMatrix(S.matrix),S.camera.copy(x.camera.position),x.camera.getWorldDirection(S.forward);const g=hw(S.camera.x,S.camera.z,S.forward.x,S.forward.z),y=b.current.get(g);if(y){d(y);return}const w=r&&a===e.version,j=w?new Set(l):Vi(h.tileBuckets,S.camera.x,S.camera.z,Nt),N=w?new Set(c):Vi(h.wallBuckets,S.camera.x,S.camera.z,Nt),B=w?new Set(f):Vi(h.objectBuckets,S.camera.x,S.camera.z,Nt),z=w?new Set(u):Vi(h.blockBuckets,S.camera.x,S.camera.z,Nt),W=xw(h,S.camera.x,S.camera.z,Nt),D=new Set,E=new Set,G=new Set,T=new Set,O=Nt*Nt;Jo(D,j,h.tileById,"tile",W,S.frustum,S.camera,S.sphere,O,S),Jo(E,N,h.wallById,"wall",W,S.frustum,S.camera,S.sphere,O,S),Jo(T,B,h.objectById,"object",W,S.frustum,S.camera,S.sphere,O,S),Jo(G,z,h.blockById,"block",W,S.frustum,S.camera,S.sphere,O,S);const P={tileIds:D,wallIds:E,blockIds:G,objectIds:T};if(b.current.set(g,P),b.current.size>96){const L=b.current.keys().next().value;L&&b.current.delete(L)}d({tileIds:P.tileIds,wallIds:P.wallIds,blockIds:P.blockIds,objectIds:P.objectIds})}),null}const HS=9,WS=150;function US(){const{gl:e}=be.useThree(),{updateMousePosition:t,placeWall:n,placeTile:o,placeBlock:s,placeObject:r,handleWallClick:a,handleTileClick:l,handleBlockClick:c}=tp(),u=R.useBuildingStore(w=>w.editMode),f=u!=="none",d=R.useBuildingStore(w=>w.setHoverPosition),p=R.useBuildingStore(w=>w.setWallRotation),h=R.useBuildingStore(w=>w.setTileRotation),v=R.useBuildingStore(w=>w.setObjectRotation),b=R.useBuildingStore(w=>w.setTileHeight),S=R.useBuildingStore(w=>w.initialized),x=R.useBuildingStore(w=>w.initializeDefaults),_=m.useRef({x:0,y:0}),g=m.useRef(0),y=m.useCallback(w=>{w&&(w.mouseButtons={LEFT:-1,MIDDLE:k.MOUSE.DOLLY,RIGHT:k.MOUSE.ROTATE})},[]);return m.useEffect(()=>{S||x()},[S,x]),m.useEffect(()=>{if(u!=="wall"&&u!=="tile"&&u!=="block"&&u!=="object")return;const w=j=>{const N=B=>{u==="wall"?p(B):u==="tile"?h(B):u==="object"&&v(B)};switch(j.key){case"ArrowUp":N(0);break;case"ArrowRight":N(Math.PI/2);break;case"ArrowDown":N(Math.PI);break;case"ArrowLeft":N(Math.PI*1.5);break}if(u==="tile"||u==="block"){if(j.code==="KeyQ"||j.key==="q"||j.key==="Q"){const B=R.useBuildingStore.getState().currentTileHeight;b(B-1)}else if(j.code==="KeyE"||j.key==="e"||j.key==="E"){const B=R.useBuildingStore.getState().currentTileHeight;b(B+1)}}};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[u,h,p,v,b]),m.useEffect(()=>{const w=e.domElement,j=z=>{z.button===0&&(_.current.x=z.clientX,_.current.y=z.clientY)},N=z=>t(z),B=z=>{if(z.button!==0)return;const W=z.clientX-_.current.x,D=z.clientY-_.current.y;if(W*W+D*D>HS)return;const E=performance.now();if(E-g.current<WS)return;g.current=E;const G=R.useBuildingStore.getState().editMode;G!=="npc"&&(G==="wall"?n():G==="tile"?o():G==="block"?s():G==="object"&&r())};return w.addEventListener("mousedown",j),w.addEventListener("mousemove",N),w.addEventListener("mouseup",B),()=>{w.removeEventListener("mousedown",j),w.removeEventListener("mousemove",N),w.removeEventListener("mouseup",B),d(null)}},[e,t,n,o,s,r,d]),i.jsxs(i.Fragment,{children:[i.jsx(lp,{}),i.jsx(op,{}),i.jsx(sp,{}),i.jsx(ip,{}),i.jsx(ap,{}),i.jsx(rp,{}),i.jsx(cp,{}),f&&i.jsx(pt.OrbitControls,{ref:y,enablePan:!0,enableZoom:!0,enableRotate:!0,maxPolarAngle:Math.PI/2.5,minDistance:5,maxDistance:100}),i.jsx(Jf,{onWallClick:a,onTileClick:l,onBlockClick:c,onWallDelete:a,onTileDelete:l,onBlockDelete:c}),i.jsx(Bd,{})]})}const ca=pa;function VS({onClose:e}){const{setEditMode:t,editMode:n,isInEditMode:o,currentTileMultiplier:s,setTileMultiplier:r,currentTileHeight:a,setTileHeight:l,currentTileShape:c,setTileShape:u,currentTileRotation:f,setTileRotation:d,currentWallRotation:p,setWallRotation:h,currentWallKind:v,setWallKind:b,applyWallPreset:S,wallCategories:x,tileCategories:_,selectedWallCategoryId:g,selectedTileCategoryId:y,selectedWallGroupId:w,selectedTileGroupId:j,selectedWallId:N,selectedTileId:B,setCurrentWallMaterialId:z,setCurrentTileMaterialId:W,setSelectedWallCategory:D,setSelectedTileCategory:E,wallGroups:G,tileGroups:T,meshes:O,updateMesh:P,addMesh:L,updateWall:M,moveWallToGroup:F,updateTile:U,addWallGroup:V,addTileGroup:Y,selectedTileObjectType:Z,setSelectedTileObjectType:q,currentCustomTileName:X,currentCustomTileColor:A,currentCustomTileTextureUrl:C,setCustomTileDraft:H,applyTilePreset:K,applyCustomTile:Q,selectedPlacedObjectType:ee,setSelectedPlacedObjectType:ne,currentObjectRotation:ie,setObjectRotation:re,selectedModelObjectId:J,setSelectedModelObjectId:ce,currentModelUrl:de,setModelUrl:me,currentModelScale:xe,setModelScale:je,currentModelColor:ve,setModelColor:Me,currentObjectPrimaryColor:Pe,setObjectPrimaryColor:mt,currentObjectSecondaryColor:Qe,setObjectSecondaryColor:Ge,currentTreeKind:Je,setTreeKind:Vt,currentFlagWidth:_n,setFlagWidth:Bt,currentFlagHeight:jn,setFlagHeight:Mn,currentFlagImageUrl:Cn,setFlagImageUrl:Nn,currentFlagStyle:Tn,setFlagStyle:In,currentFireIntensity:gt,setFireIntensity:et,currentFireWidth:bt,setFireWidth:Ze,currentFireHeight:Pt,setFireHeight:Yt,currentFireColor:Rt,setFireColor:xt,currentBillboardText:En,setBillboardText:An,currentBillboardImageUrl:kn,setBillboardImageUrl:Bn,currentBillboardColor:Zt,setBillboardColor:Xt,currentBillboardWidth:Pn,setBillboardWidth:Rn,currentBillboardHeight:Dn,setBillboardHeight:Fn,currentBillboardScale:Kt,setBillboardScale:qt,currentBillboardOffsetY:Qt,setBillboardOffsetY:Jt,currentBillboardElevation:Ln,setBillboardElevation:zn,currentBillboardIntensity:en,setBillboardIntensity:tn,showSnow:yt,setShowSnow:On,showFog:Dt,setShowFog:$n,fogColor:Gn,setFogColor:Hn,weatherEffect:Wn,setWeatherEffect:nn}=R.useBuildingStore(ls.useShallow(I=>({setEditMode:I.setEditMode,editMode:I.editMode,isInEditMode:I.isInEditMode,currentTileMultiplier:I.currentTileMultiplier,setTileMultiplier:I.setTileMultiplier,currentTileHeight:I.currentTileHeight,setTileHeight:I.setTileHeight,currentTileShape:I.currentTileShape,setTileShape:I.setTileShape,currentTileRotation:I.currentTileRotation,setTileRotation:I.setTileRotation,currentWallRotation:I.currentWallRotation,setWallRotation:I.setWallRotation,currentWallKind:I.currentWallKind,setWallKind:I.setWallKind,applyWallPreset:I.applyWallPreset,wallCategories:I.wallCategories,tileCategories:I.tileCategories,selectedWallCategoryId:I.selectedWallCategoryId,selectedTileCategoryId:I.selectedTileCategoryId,selectedWallGroupId:I.selectedWallGroupId,selectedTileGroupId:I.selectedTileGroupId,selectedWallId:I.selectedWallId,selectedTileId:I.selectedTileId,setCurrentWallMaterialId:I.setCurrentWallMaterialId,setCurrentTileMaterialId:I.setCurrentTileMaterialId,setSelectedWallCategory:I.setSelectedWallCategory,setSelectedTileCategory:I.setSelectedTileCategory,wallGroups:I.wallGroups,tileGroups:I.tileGroups,meshes:I.meshes,updateMesh:I.updateMesh,addMesh:I.addMesh,updateWall:I.updateWall,moveWallToGroup:I.moveWallToGroup,updateTile:I.updateTile,addWallGroup:I.addWallGroup,addTileGroup:I.addTileGroup,selectedTileObjectType:I.selectedTileObjectType,setSelectedTileObjectType:I.setSelectedTileObjectType,currentCustomTileName:I.currentCustomTileName,currentCustomTileColor:I.currentCustomTileColor,currentCustomTileTextureUrl:I.currentCustomTileTextureUrl,setCustomTileDraft:I.setCustomTileDraft,applyTilePreset:I.applyTilePreset,applyCustomTile:I.applyCustomTile,selectedPlacedObjectType:I.selectedPlacedObjectType,setSelectedPlacedObjectType:I.setSelectedPlacedObjectType,currentObjectRotation:I.currentObjectRotation,setObjectRotation:I.setObjectRotation,selectedModelObjectId:I.selectedModelObjectId,setSelectedModelObjectId:I.setSelectedModelObjectId,currentModelUrl:I.currentModelUrl,setModelUrl:I.setModelUrl,currentModelScale:I.currentModelScale,setModelScale:I.setModelScale,currentModelColor:I.currentModelColor,setModelColor:I.setModelColor,currentObjectPrimaryColor:I.currentObjectPrimaryColor,setObjectPrimaryColor:I.setObjectPrimaryColor,currentObjectSecondaryColor:I.currentObjectSecondaryColor,setObjectSecondaryColor:I.setObjectSecondaryColor,currentTreeKind:I.currentTreeKind,setTreeKind:I.setTreeKind,currentFlagWidth:I.currentFlagWidth,setFlagWidth:I.setFlagWidth,currentFlagHeight:I.currentFlagHeight,setFlagHeight:I.setFlagHeight,currentFlagImageUrl:I.currentFlagImageUrl,setFlagImageUrl:I.setFlagImageUrl,currentFlagStyle:I.currentFlagStyle,setFlagStyle:I.setFlagStyle,currentFireIntensity:I.currentFireIntensity,setFireIntensity:I.setFireIntensity,currentFireWidth:I.currentFireWidth,setFireWidth:I.setFireWidth,currentFireHeight:I.currentFireHeight,setFireHeight:I.setFireHeight,currentFireColor:I.currentFireColor,setFireColor:I.setFireColor,currentBillboardText:I.currentBillboardText,setBillboardText:I.setBillboardText,currentBillboardImageUrl:I.currentBillboardImageUrl,setBillboardImageUrl:I.setBillboardImageUrl,currentBillboardColor:I.currentBillboardColor,setBillboardColor:I.setBillboardColor,currentBillboardWidth:I.currentBillboardWidth,setBillboardWidth:I.setBillboardWidth,currentBillboardHeight:I.currentBillboardHeight,setBillboardHeight:I.setBillboardHeight,currentBillboardScale:I.currentBillboardScale,setBillboardScale:I.setBillboardScale,currentBillboardOffsetY:I.currentBillboardOffsetY,setBillboardOffsetY:I.setBillboardOffsetY,currentBillboardElevation:I.currentBillboardElevation,setBillboardElevation:I.setBillboardElevation,currentBillboardIntensity:I.currentBillboardIntensity,setBillboardIntensity:I.setBillboardIntensity,showSnow:I.showSnow,setShowSnow:I.setShowSnow,showFog:I.showFog,setShowFog:I.setShowFog,fogColor:I.fogColor,setFogColor:I.setFogColor,weatherEffect:I.weatherEffect,setWeatherEffect:I.setWeatherEffect}))),on=jp.useAuthStore(I=>I.isLoggedIn),vt=o(),{templates:tt,selectedTemplateId:Xe,setSelectedTemplate:Un,initializeDefaults:sn,selectedInstanceId:Vn}=se.useNPCStore(ls.useShallow(I=>({templates:I.templates,selectedTemplateId:I.selectedTemplateId,setSelectedTemplate:I.setSelectedTemplate,initializeDefaults:I.initializeDefaults,selectedInstanceId:I.selectedInstanceId}))),[nt,Yn]=m.useState(!1),[Ke,wt]=m.useState(""),[ze,qe]=m.useState("#808080"),[Ae,St]=m.useState(""),Zn=m.useMemo(()=>Array.from(_.values()),[_]),rn=m.useMemo(()=>Array.from(x.values()),[x]),an=m.useMemo(()=>Array.from(tt.values()),[tt]),Ft=m.useMemo(()=>R.BUILDING_TILE_OBJECT_OPTIONS.find(I=>I.type===Z)?.labelEn??Z,[Z]),Xn=m.useMemo(()=>R.BUILDING_TILE_SHAPE_OPTIONS.find(I=>I.type===c)?.labelEn??c,[c]),ln=m.useMemo(()=>Ts(J)??vi[0],[J]),_t=m.useMemo(()=>{const I=new Map;for(const oe of G.values())for(const Ne of oe.walls)I.set(Ne.id,oe.id);return I},[G]),Lt=m.useCallback((I,oe)=>{const Ne=I?O.get(I):void 0,{mapTextureUrl:Fe,textureUrl:No,...Le}=Ne??{},Te={...Le,id:oe,color:ze,material:"STANDARD",...Ae?{mapTextureUrl:Ae,textureUrl:Ae}:{}};return O.has(oe)?P(oe,Te):L(Te),oe},[L,ze,Ae,O,P]),it=m.useCallback(I=>{const oe=_t.get(I);return oe?G.get(oe):void 0},[_t,G]),$=N?it(N)?.id:w,Kn=N?it(N):G.get(w??""),Mo=N?Kn?.walls.find(I=>I.id===N):void 0,qs=m.useCallback(()=>{t("none"),e?.()},[t,e]),Co=m.useCallback(()=>Yn(I=>!I),[]);return m.useEffect(()=>{sn()},[sn]),m.useEffect(()=>{if(n==="wall"&&w){const I=N?it(N):G.get(w),Ne=(N?I?.walls.find(Fe=>Fe.id===N):void 0)?.materialId??I?.frontMeshId;if(Ne){const Fe=O.get(Ne);Fe&&(qe(Fe.color||"#808080"),St(Fe.mapTextureUrl||""))}}else if(n==="tile"&&j){const I=T.get(j);if(I&&I.floorMeshId){const oe=O.get(I.floorMeshId);oe&&(qe(oe.color||"#808080"),St(oe.mapTextureUrl||""))}}},[n,w,j,N,it,G,T,O]),on?i.jsxs(i.Fragment,{children:[vt&&i.jsx("div",{className:"building-edit-mode-overlay"}),i.jsx("div",{className:"building-ui-container",children:vt?i.jsxs("div",{className:"building-ui-panel",children:[i.jsxs("div",{className:"building-ui-header",children:[i.jsx("span",{className:"building-ui-title",children:"Building Mode"}),i.jsx("button",{onClick:qs,className:"building-ui-close",children:"×"})]}),i.jsxs("div",{className:"building-ui-mode-group",children:[i.jsx("button",{onClick:()=>t("wall"),className:`building-ui-mode-button ${n==="wall"?"active":""}`,children:"Wall Mode"}),i.jsx("button",{onClick:()=>t("tile"),className:`building-ui-mode-button ${n==="tile"?"active":""}`,children:"Tile Mode"}),i.jsx("button",{onClick:()=>t("block"),className:`building-ui-mode-button ${n==="block"?"active":""}`,children:"Block Mode"}),i.jsx("button",{onClick:()=>t("npc"),className:`building-ui-mode-button ${n==="npc"?"active":""}`,children:"NPC Mode"}),i.jsx("button",{onClick:()=>t("object"),className:`building-ui-mode-button ${n==="object"?"active":""}`,children:"Object Mode"})]}),i.jsxs("div",{className:"building-ui-object-group",children:[i.jsx("span",{className:"building-ui-label",children:"World Environment:"}),i.jsxs("div",{className:"building-ui-object-buttons",children:[i.jsxs("button",{onClick:()=>On(!yt),className:`building-ui-object-button ${yt?"active":""}`,children:["Snow ",yt?"ON":"OFF"]}),R.BUILDING_WEATHER_EFFECT_OPTIONS.filter(I=>I.type!=="snow").map(I=>i.jsx("button",{onClick:()=>nn(I.type),className:`building-ui-object-button ${Wn===I.type?"active":""}`,children:I.labelEn},I.type)),i.jsxs("button",{onClick:()=>$n(!Dt),className:`building-ui-object-button ${Dt?"active":""}`,children:["Fog ",Dt?"ON":"OFF"]}),i.jsxs("label",{className:"building-ui-object-button",children:["Fog Color",i.jsx("input",{type:"color",value:Gn,onChange:I=>Hn(I.target.value),style:{marginLeft:8}})]})]})]}),n==="tile"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"building-ui-category-group",children:[i.jsx("span",{className:"building-ui-label",children:"Category:"}),i.jsx("select",{value:y||"",onChange:I=>E(I.target.value),className:"building-ui-select",children:Zn.map(I=>i.jsx("option",{value:I.id,children:I.name},I.id))})]}),i.jsxs("div",{className:"building-ui-category-group",children:[i.jsx("span",{className:"building-ui-label",children:"Type:"}),i.jsx("select",{value:j||"",onChange:I=>R.useBuildingStore.setState({selectedTileGroupId:I.target.value}),className:"building-ui-select",children:y&&_.get(y)?.tileGroupIds.map(I=>{const oe=T.get(I);return oe?i.jsx("option",{value:oe.id,children:oe.name},oe.id):null})})]}),i.jsxs("div",{className:"building-ui-object-group",children:[i.jsx("span",{className:"building-ui-label",children:"Wall Preset:"}),i.jsx("div",{className:"building-ui-object-buttons",children:R.BUILDING_WALL_PRESETS.map(I=>{const oe=`${I.id}-walls`;return i.jsx("button",{onClick:()=>S(I.id),className:`building-ui-object-button ${w===oe?"active":""}`,children:I.labelEn},I.id)})})]}),i.jsxs("div",{className:"building-ui-object-group",children:[i.jsx("span",{className:"building-ui-label",children:"Wall Module:"}),i.jsx("div",{className:"building-ui-object-buttons",children:R.BUILDING_WALL_KIND_OPTIONS.map(I=>i.jsx("button",{onClick:()=>b(I.type),className:`building-ui-object-button ${(Mo?.wallKind??v)===I.type?"active":""}`,children:I.labelEn},I.type))})]}),i.jsx("button",{onClick:()=>{!N||!Kn||M(Kn.id,N,{flipSides:!Mo?.flipSides})},className:"building-ui-apply-button",disabled:!N||!Kn,children:"Flip Interior/Exterior"}),i.jsxs("button",{onClick:Co,className:"building-ui-custom-toggle",children:[nt?"Hide":"Show"," Custom Settings"]}),nt&&i.jsxs("div",{className:"building-ui-custom-settings",children:[i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Name:"}),i.jsx("input",{type:"text",value:Ke,onChange:I=>wt(I.target.value),placeholder:"Custom Floor Name",className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Color:"}),i.jsxs("div",{className:"building-ui-color-input",children:[i.jsx("input",{type:"color",value:ze,onChange:I=>qe(I.target.value),className:"building-ui-color-picker"}),i.jsx("input",{type:"text",value:ze,onChange:I=>qe(I.target.value),className:"building-ui-input",style:{width:"100px"}})]})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Texture URL:"}),i.jsx("input",{type:"text",value:Ae,onChange:I=>St(I.target.value),placeholder:"https://...",className:"building-ui-input"})]}),i.jsx("button",{onClick:()=>{if(j){const I=T.get(j);if(I&&I.floorMeshId){const oe=B?Lt(I.floorMeshId,`custom-tile-mesh-${B}`):Lt(I.floorMeshId,ca("custom-placement-tile-mesh"));if(B){U(I.id,B,{materialId:oe});return}W(oe)}}},className:"building-ui-apply-button",children:"Apply Changes"}),i.jsx("button",{onClick:()=>{if(Ke){const I=`custom-tile-${Date.now()}`,oe=`custom-floor-mesh-${Date.now()}`;if(L({id:oe,color:ze,material:"STANDARD",...Ae?{mapTextureUrl:Ae}:{},roughness:.6}),Y({id:I,name:Ke,floorMeshId:oe,tiles:[]}),y){const Ne=_.get(y);Ne&&R.useBuildingStore.getState().updateTileCategory(y,{tileGroupIds:[...Ne.tileGroupIds,I]})}R.useBuildingStore.setState({selectedTileGroupId:I}),wt("")}},className:"building-ui-create-button",children:"Create New Type"})]}),i.jsxs("div",{className:"building-ui-size-group",children:[i.jsx("span",{className:"building-ui-label",children:"Tile Size:"}),i.jsxs("div",{className:"building-ui-size-buttons",children:[i.jsx("button",{onClick:()=>r(1),className:`building-ui-size-button ${s===1?"active":""}`,children:"1x1"}),i.jsx("button",{onClick:()=>r(2),className:`building-ui-size-button ${s===2?"active":""}`,children:"2x2"}),i.jsx("button",{onClick:()=>r(3),className:`building-ui-size-button ${s===3?"active":""}`,children:"3x3"}),i.jsx("button",{onClick:()=>r(4),className:`building-ui-size-button ${s===4?"active":""}`,children:"4x4"})]})]}),i.jsxs("div",{className:"building-ui-size-group",children:[i.jsx("span",{className:"building-ui-label",children:"Tile Height:"}),i.jsx("div",{className:"building-ui-size-buttons",children:[0,1,2,3,4].map(I=>i.jsx("button",{onClick:()=>l(I),className:`building-ui-size-button ${a===I?"active":""}`,children:I},I))})]}),i.jsxs("div",{className:"building-ui-size-group",children:[i.jsx("span",{className:"building-ui-label",children:"Tile Shape:"}),i.jsx("div",{className:"building-ui-size-buttons",children:R.BUILDING_TILE_SHAPE_OPTIONS.map(I=>i.jsx("button",{onClick:()=>u(I.type),className:`building-ui-size-button ${c===I.type?"active":""}`,children:I.labelEn},I.type))})]}),i.jsxs("div",{className:"building-ui-size-group",children:[i.jsx("span",{className:"building-ui-label",children:"Tile Rotation:"}),i.jsx("div",{className:"building-ui-size-buttons",children:[0,Math.PI/2,Math.PI,Math.PI*1.5].map((I,oe)=>i.jsx("button",{onClick:()=>d(I),className:`building-ui-size-button ${Math.abs(f-I)<1e-4?"active":""}`,children:oe*90},I))})]}),i.jsxs("div",{className:"building-ui-object-group",children:[i.jsx("span",{className:"building-ui-label",children:"Tile Preset:"}),i.jsx("div",{className:"building-ui-object-buttons",children:R.BUILDING_TILE_PRESETS.map(I=>{const oe=`${I.id}-floor`;return i.jsx("button",{onClick:()=>K(I.id),className:`building-ui-object-button ${j===oe?"active":""}`,children:I.labelEn},I.id)})})]}),i.jsxs("div",{className:"building-ui-custom-settings",children:[i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Custom Tile:"}),i.jsx("input",{type:"text",value:X,onChange:I=>H({name:I.target.value}),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Color:"}),i.jsxs("div",{className:"building-ui-color-input",children:[i.jsx("input",{type:"color",value:A,onChange:I=>H({color:I.target.value}),className:"building-ui-color-picker"}),i.jsx("input",{type:"text",value:A,onChange:I=>H({color:I.target.value}),className:"building-ui-input",style:{width:"100px"}})]})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Texture URL:"}),i.jsx("input",{type:"text",value:C,onChange:I=>H({textureUrl:I.target.value}),placeholder:"textures/floor.png",className:"building-ui-input"})]}),i.jsx("button",{onClick:Q,className:"building-ui-action-button",children:"Create/Select Separate Tile Map"})]}),i.jsxs("div",{className:"building-ui-object-group",children:[i.jsx("span",{className:"building-ui-label",children:"Tile Object:"}),i.jsx("div",{className:"building-ui-object-buttons",children:R.BUILDING_TILE_OBJECT_OPTIONS.map(I=>i.jsx("button",{onClick:()=>q(I.type),className:`building-ui-object-button ${Z===I.type?"active":""}`,children:I.labelEn},I.type))})]}),i.jsxs("div",{className:"building-ui-info",children:[i.jsxs("p",{children:["Category: ",_.get(y||"")?.name]}),i.jsxs("p",{children:["Type: ",T.get(j||"")?.name]}),i.jsxs("p",{children:["Size: ",s,"x",s," (",s*4,"m)"]}),i.jsxs("p",{children:["Height: ",a]}),i.jsxs("p",{children:["Shape: ",Xn]}),i.jsxs("p",{children:["Object: ",Ft]}),i.jsx("p",{children:"Click to place tiles"}),i.jsx("p",{children:"Amber = Occupied, Blue = Available"})]})]}),n==="block"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"building-ui-size-group",children:[i.jsx("span",{className:"building-ui-label",children:"Block Size:"}),i.jsx("div",{className:"building-ui-size-buttons",children:[1,2,3,4].map(I=>i.jsxs("button",{onClick:()=>r(I),className:`building-ui-size-button ${s===I?"active":""}`,children:[I,"x",I]},I))})]}),i.jsxs("div",{className:"building-ui-size-group",children:[i.jsx("span",{className:"building-ui-label",children:"Layer Offset:"}),i.jsx("div",{className:"building-ui-size-buttons",children:[0,1,2,3,4].map(I=>i.jsx("button",{onClick:()=>l(I),className:`building-ui-size-button ${a===I?"active":""}`,children:I},I))})]}),i.jsxs("div",{className:"building-ui-info",children:[i.jsxs("p",{children:["Size: ",s,"x",s]}),i.jsxs("p",{children:["Layer offset: ",a]}),i.jsx("p",{children:"Click to place voxel blocks"}),i.jsx("p",{children:"Click highlighted blocks to delete"})]})]}),n==="object"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"building-ui-object-group",children:[i.jsx("span",{className:"building-ui-label",children:"Object Type:"}),i.jsxs("div",{className:"building-ui-object-buttons",children:[R.BUILDING_BASIC_OBJECT_OPTIONS.map(I=>i.jsx("button",{onClick:()=>ne(I.type),className:`building-ui-object-button ${ee===I.type?"active":""}`,children:I.labelEn},I.type)),vi.map(I=>i.jsx("button",{onClick:()=>{ne("model"),ce(I.id),je(I.defaultScale),Me(I.defaultColor),me(I.modelUrl??"")},className:`building-ui-object-button ${ee==="model"&&J===I.id?"active":""}`,children:I.label},I.id))]})]}),i.jsxs("div",{className:"building-ui-size-group",children:[i.jsx("span",{className:"building-ui-label",children:"Object Rotation:"}),i.jsx("div",{className:"building-ui-size-buttons",children:[0,Math.PI/2,Math.PI,Math.PI*1.5].map((I,oe)=>i.jsx("button",{onClick:()=>re(I),className:`building-ui-size-button ${Math.abs(ie-I)<1e-4?"active":""}`,children:oe*90},I))})]}),(ee==="tree"||ee==="sakura")&&i.jsxs("div",{className:"building-ui-custom-settings",children:[i.jsxs("div",{className:"building-ui-object-group",children:[i.jsx("span",{className:"building-ui-label",children:"Tree Type:"}),i.jsx("div",{className:"building-ui-object-buttons",children:R.BUILDING_TREE_OPTIONS.map(I=>i.jsx("button",{onClick:()=>Vt(I.type),className:`building-ui-object-button ${Je===I.type?"active":""}`,children:I.labelEn},I.type))})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Leaf/Flower Color:"}),i.jsxs("div",{className:"building-ui-color-input",children:[i.jsx("input",{type:"color",value:Pe,onChange:I=>mt(I.target.value),className:"building-ui-color-picker"}),i.jsx("input",{type:"text",value:Pe,onChange:I=>mt(I.target.value),className:"building-ui-input",style:{width:"100px"}})]})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Bark Color:"}),i.jsxs("div",{className:"building-ui-color-input",children:[i.jsx("input",{type:"color",value:Qe,onChange:I=>Ge(I.target.value),className:"building-ui-color-picker"}),i.jsx("input",{type:"text",value:Qe,onChange:I=>Ge(I.target.value),className:"building-ui-input",style:{width:"100px"}})]})]})]}),ee==="flag"&&i.jsxs("div",{className:"building-ui-custom-settings",children:[i.jsxs("div",{className:"building-ui-object-group",children:[i.jsx("span",{className:"building-ui-label",children:"Flag Style:"}),i.jsx("div",{className:"building-ui-object-buttons",children:R.BUILDING_FLAG_STYLE_OPTIONS.map(({style:I,meta:oe})=>i.jsx("button",{onClick:()=>In(I),className:`building-ui-object-button ${Tn===I?"active":""}`,children:oe.label},I))})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Width:"}),i.jsx("input",{type:"number",min:"0.5",max:"8",step:"0.1",value:_n,onChange:I=>Bt(Number(I.target.value)||1.5),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Height:"}),i.jsx("input",{type:"number",min:"0.5",max:"6",step:"0.1",value:jn,onChange:I=>Mn(Number(I.target.value)||1),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Image URL:"}),i.jsx("input",{type:"text",value:Cn,onChange:I=>Nn(I.target.value),placeholder:"https://...",className:"building-ui-input"})]})]}),ee==="fire"&&i.jsxs("div",{className:"building-ui-custom-settings",children:[i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Intensity:"}),i.jsx("input",{type:"number",min:"0.5",max:"3",step:"0.1",value:gt,onChange:I=>et(Number(I.target.value)||1.5),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Width:"}),i.jsx("input",{type:"number",min:"0.3",max:"4",step:"0.1",value:bt,onChange:I=>Ze(Number(I.target.value)||1),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Height:"}),i.jsx("input",{type:"number",min:"0.5",max:"5",step:"0.1",value:Pt,onChange:I=>Yt(Number(I.target.value)||1.5),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Color:"}),i.jsxs("div",{className:"building-ui-color-input",children:[i.jsx("input",{type:"color",value:Rt,onChange:I=>xt(I.target.value),className:"building-ui-color-picker"}),i.jsx("input",{type:"text",value:Rt,onChange:I=>xt(I.target.value),className:"building-ui-input",style:{width:"100px"}})]})]})]}),ee==="billboard"&&i.jsxs("div",{className:"building-ui-custom-settings",children:[i.jsxs("div",{className:"building-ui-size-group",children:[i.jsx("span",{className:"building-ui-label",children:"Billboard Size:"}),i.jsx("div",{className:"building-ui-size-buttons",children:[.5,1,1.5,2,3,4].map(I=>i.jsxs("button",{onClick:()=>qt(I),className:`building-ui-size-button ${Math.abs(Kt-I)<1e-4?"active":""}`,children:[I,"x"]},I))})]}),i.jsxs("div",{className:"building-ui-size-group",children:[i.jsx("span",{className:"building-ui-label",children:"Billboard Height:"}),i.jsx("div",{className:"building-ui-size-buttons",children:[-1,0,1,2,3,4,6].map(I=>i.jsxs("button",{onClick:()=>Jt(I),className:`building-ui-size-button ${Math.abs(Qt-I)<1e-4?"active":""}`,children:[I,"m"]},I))})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Text:"}),i.jsx("input",{type:"text",value:En,onChange:I=>An(I.target.value),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Image URL:"}),i.jsx("input",{type:"text",value:kn,onChange:I=>Bn(I.target.value),placeholder:"https://...",className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Color:"}),i.jsxs("div",{className:"building-ui-color-input",children:[i.jsx("input",{type:"color",value:Zt,onChange:I=>Xt(I.target.value),className:"building-ui-color-picker"}),i.jsx("input",{type:"text",value:Zt,onChange:I=>Xt(I.target.value),className:"building-ui-input",style:{width:"100px"}})]})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Custom Size:"}),i.jsx("input",{type:"number",min:"0.1",max:"10",step:"0.1",value:Kt,onChange:I=>qt(Number(I.target.value)||1),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Custom Height:"}),i.jsx("input",{type:"number",min:"-4",max:"12",step:"0.1",value:Qt,onChange:I=>Jt(Number(I.target.value)||0),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Panel Width:"}),i.jsx("input",{type:"number",min:"0",max:"8",step:"0.1",value:Pn,onChange:I=>Rn(Number(I.target.value)||0),className:"building-ui-input"}),i.jsx("span",{className:"building-ui-help",children:"0 = image ratio auto"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Panel Height:"}),i.jsx("input",{type:"number",min:"0.3",max:"5",step:"0.1",value:Dn,onChange:I=>Fn(Number(I.target.value)||1.5),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Post Height:"}),i.jsx("input",{type:"number",min:"0",max:"8",step:"0.1",value:Ln,onChange:I=>zn(Number(I.target.value)||0),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Brightness:"}),i.jsx("input",{type:"number",min:"0",max:"8",step:"0.1",value:en,onChange:I=>tn(Number(I.target.value)||0),className:"building-ui-input"})]})]}),ee==="model"&&i.jsxs("div",{className:"building-ui-custom-settings",children:[i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"GLB URL:"}),i.jsx("input",{type:"text",value:de,onChange:I=>me(I.target.value),placeholder:"gltf/props/door.glb",className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Scale:"}),i.jsx("input",{type:"number",min:"0.1",max:"10",step:"0.1",value:xe,onChange:I=>je(Number(I.target.value)||1),className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Color:"}),i.jsxs("div",{className:"building-ui-color-input",children:[i.jsx("input",{type:"color",value:ve,onChange:I=>Me(I.target.value),className:"building-ui-color-picker"}),i.jsx("input",{type:"text",value:ve,onChange:I=>Me(I.target.value),className:"building-ui-input",style:{width:"100px"}})]})]})]}),i.jsxs("div",{className:"building-ui-info",children:[i.jsxs("p",{children:["Type: ",ee==="model"?ln?.label:ee]}),ee==="model"&&i.jsxs(i.Fragment,{children:[i.jsxs("p",{children:["Fallback: ",ln?.fallbackKind??"generic"]}),i.jsx("p",{children:"GLB URL이 비어 있으면 기본 프리미티브로 표시됩니다."})]}),i.jsx("p",{children:"Click to place objects"})]})]}),n==="wall"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"building-ui-category-group",children:[i.jsx("span",{className:"building-ui-label",children:"Category:"}),i.jsx("select",{value:g||"",onChange:I=>D(I.target.value),className:"building-ui-select",children:rn.map(I=>i.jsx("option",{value:I.id,children:I.name},I.id))})]}),i.jsxs("div",{className:"building-ui-category-group",children:[i.jsx("span",{className:"building-ui-label",children:"Type:"}),i.jsx("select",{value:$||"",onChange:I=>{const oe=I.target.value;if(N){F(N,oe);return}R.useBuildingStore.setState({selectedWallGroupId:oe})},className:"building-ui-select",children:g&&x.get(g)?.wallGroupIds.map(I=>{const oe=G.get(I);return oe?i.jsx("option",{value:oe.id,children:oe.name},oe.id):null})})]}),i.jsxs("button",{onClick:Co,className:"building-ui-custom-toggle",children:[nt?"Hide":"Show"," Custom Settings"]}),nt&&i.jsxs("div",{className:"building-ui-custom-settings",children:[i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Name:"}),i.jsx("input",{type:"text",value:Ke,onChange:I=>wt(I.target.value),placeholder:"Custom Wall Name",className:"building-ui-input"})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Color:"}),i.jsxs("div",{className:"building-ui-color-input",children:[i.jsx("input",{type:"color",value:ze,onChange:I=>qe(I.target.value),className:"building-ui-color-picker"}),i.jsx("input",{type:"text",value:ze,onChange:I=>qe(I.target.value),className:"building-ui-input",style:{width:"100px"}})]})]}),i.jsxs("div",{className:"building-ui-input-group",children:[i.jsx("span",{className:"building-ui-label",children:"Texture URL:"}),i.jsx("input",{type:"text",value:Ae,onChange:I=>St(I.target.value),placeholder:"https://...",className:"building-ui-input"})]}),i.jsx("button",{onClick:()=>{if(w){const I=N?it(N):G.get(w);if(!I)return;const Ne=(N?I.walls.find(No=>No.id===N):void 0)?.materialId??I.frontMeshId,Fe=Lt(Ne,N?`custom-wall-mesh-${N}`:ca("custom-placement-wall-mesh"));if(N){M(I.id,N,{materialId:Fe});return}z(Fe)}},className:"building-ui-apply-button",children:"Apply Changes"}),i.jsx("button",{onClick:()=>{if(Ke){const I=`custom-wall-${Date.now()}`,oe=`custom-mesh-${Date.now()}`;if(L({id:oe,color:ze,material:"STANDARD",...Ae?{mapTextureUrl:Ae}:{},roughness:.7}),V({id:I,name:Ke,frontMeshId:oe,backMeshId:oe,sideMeshId:oe,walls:[]}),g){const Ne=x.get(g);Ne&&R.useBuildingStore.getState().updateWallCategory(g,{wallGroupIds:[...Ne.wallGroupIds,I]})}R.useBuildingStore.setState({selectedWallGroupId:I}),wt("")}},className:"building-ui-create-button",children:"Create New Type"})]}),i.jsxs("div",{className:"building-ui-direction-group",children:[i.jsx("span",{className:"building-ui-label",children:"Wall Direction:"}),i.jsxs("div",{className:"building-ui-direction-buttons",children:[i.jsx("button",{onClick:()=>h(0),className:`building-ui-direction-button ${p===0?"active":""}`,title:"North",children:"↑"}),i.jsx("button",{onClick:()=>h(Math.PI/2),className:`building-ui-direction-button ${p===Math.PI/2?"active":""}`,title:"East",children:"→"}),i.jsx("button",{onClick:()=>h(Math.PI),className:`building-ui-direction-button ${p===Math.PI?"active":""}`,title:"South",children:"↓"}),i.jsx("button",{onClick:()=>h(Math.PI*1.5),className:`building-ui-direction-button ${p===Math.PI*1.5?"active":""}`,title:"West",children:"←"})]})]}),i.jsxs("div",{className:"building-ui-info",children:[i.jsxs("p",{children:["Category: ",x.get(g||"")?.name]}),i.jsxs("p",{children:["Type: ",G.get(w||"")?.name]}),i.jsx("p",{children:"Use arrow keys to rotate"}),i.jsx("p",{children:"Click to place walls"}),i.jsx("p",{children:"Amber = Occupied, Blue = Available"}),i.jsx("p",{children:"Click highlighted markers to delete"})]})]}),n==="npc"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"building-ui-category-group",children:[i.jsx("span",{className:"building-ui-label",children:"캐릭터:"}),i.jsx("select",{value:Xe||"",onChange:I=>Un(I.target.value),className:"building-ui-select",children:an.map(I=>i.jsx("option",{value:I.id,children:I.name},I.id))})]}),i.jsxs("div",{className:"building-ui-category-group",children:[i.jsx("span",{className:"building-ui-label",children:"옷:"}),i.jsxs("div",{className:"building-ui-clothing-buttons",children:[["rabbit-outfit","basic-suit","formal-suit"].map(I=>{const oe=se.useNPCStore.getState().clothingSets.get(I);return oe?i.jsx("button",{onClick:()=>se.useNPCStore.getState().setSelectedClothingSet(oe.id),className:`building-ui-clothing-button ${se.useNPCStore.getState().selectedClothingSetId===oe.id?"active":""}`,children:oe.name},oe.id):null}),i.jsx("button",{onClick:()=>se.useNPCStore.getState().setSelectedClothingSet(""),className:`building-ui-clothing-button ${se.useNPCStore.getState().selectedClothingSetId?"":"active"}`,children:"없음"})]})]}),i.jsxs("div",{className:"building-ui-category-group",children:[i.jsx("span",{className:"building-ui-label",children:"모자:"}),i.jsxs("div",{className:"building-ui-clothing-buttons",children:[["hat-set-a","hat-set-b","hat-set-c"].map(I=>{const oe=se.useNPCStore.getState().clothingSets.get(I);return oe?i.jsx("button",{onClick:()=>{se.useNPCStore.getState().setPreviewAccessory("hat",oe.id);const Ne=se.useNPCStore.getState().selectedInstanceId,Fe=oe.parts[0];Ne&&Fe&&se.useNPCStore.getState().updateInstancePart(Ne,Fe.id,Fe)},className:`building-ui-clothing-button ${se.useNPCStore.getState().previewAccessories.hat===oe.id?"active":""}`,children:oe.name},oe.id):null}),i.jsx("button",{onClick:()=>se.useNPCStore.getState().setPreviewAccessory("hat",""),className:`building-ui-clothing-button ${se.useNPCStore.getState().previewAccessories.hat?"":"active"}`,children:"없음"})]})]}),i.jsxs("div",{className:"building-ui-category-group",children:[i.jsx("span",{className:"building-ui-label",children:"안경:"}),i.jsxs("div",{className:"building-ui-clothing-buttons",children:[["glasses-set-a","glasses-set-b"].map(I=>{const oe=se.useNPCStore.getState().clothingSets.get(I);return oe?i.jsx("button",{onClick:()=>se.useNPCStore.getState().setPreviewAccessory("glasses",oe.id),className:`building-ui-clothing-button ${se.useNPCStore.getState().previewAccessories.glasses===oe.id?"active":""}`,children:oe.name},oe.id):null}),i.jsx("button",{onClick:()=>se.useNPCStore.getState().setPreviewAccessory("glasses",""),className:`building-ui-clothing-button ${se.useNPCStore.getState().previewAccessories.glasses?"":"active"}`,children:"없음"})]})]}),i.jsxs("div",{className:"building-ui-category-group",children:[i.jsx("span",{className:"building-ui-label",children:"Selected Instance:"}),i.jsx("span",{className:"building-ui-info-value",children:Vn||"None"})]}),Xe&&tt.get(Xe)&&i.jsxs("div",{className:"building-ui-info",children:[i.jsxs("p",{children:["현재 선택: ",tt.get(Xe)?.name]}),i.jsx("p",{children:"클릭하여 NPC 배치"}),i.jsx("p",{children:"배치된 NPC를 클릭하여 선택"})]})]})]}):null})]}):null}const YS="gaesup.building",ZS="building.square",XS="building.placement",KS="building",qS="building.store";function up(e={}){const t=e.id??YS,n=e.gridExtensionId??ZS,o=e.placementExtensionId??XS,s=e.saveExtensionId??KS,r=e.storeServiceId??qS;return{id:t,name:"GaeSup Building",version:"0.1.0",runtime:"client",capabilities:["building","grid","placement"],setup:l=>{l.grid.register(n,R.buildingGridAdapter,t),l.placement.register(o,{adapter:R.buildingPlacementAdapter,createEngine:R.createBuildingPlacementEngine,toEntries:R.buildingGroupsToPlacementEntries,blockToEntry:R.blockToPlacementEntry,tileToEntry:R.tileToPlacementEntry,wallToEntry:R.wallToPlacementEntry},t),l.save.register(s,{key:s,serialize:()=>R.useBuildingStore.getState().serialize(),hydrate:c=>R.useBuildingStore.getState().hydrate(c)},t),l.services.register(r,{useStore:R.useBuildingStore,getState:R.useBuildingStore.getState,setState:R.useBuildingStore.setState},t),l.events.emit("building:ready",{pluginId:t,gridExtensionId:n,placementExtensionId:o,saveExtensionId:s,storeServiceId:r})},dispose(l){l.grid.remove(n),l.placement.remove(o),l.save.remove(s),l.services.remove(r)}}}const QS=up();function JS(){const e=m.useMemo(()=>({frustum:new k.Frustum,matrix:new k.Matrix4,camPos:new k.Vector3}),[]);return be.useFrame((t,n)=>{const o=t.camera;bo().size()!==0&&(e.matrix.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse),e.frustum.setFromProjectionMatrix(e.matrix),e.camPos.copy(o.position),bo().tick({elapsedTime:t.clock.elapsedTime,delta:n,cameraPosition:e.camPos,frustum:e.frustum}))}),null}exports.AnimationDebugPanel=Dc;exports.AnimationPanel=Fc;exports.BlockSystem=pf;exports.BuildingController=US;exports.BuildingGpuCullingDriver=ip;exports.BuildingGpuMirrorDriver=op;exports.BuildingGpuUploadDriver=sp;exports.BuildingIndirectArgsUploadDriver=rp;exports.BuildingIndirectDrawDriver=ap;exports.BuildingPanel=ai;exports.BuildingRenderStateDriver=lp;exports.BuildingSystem=Jf;exports.BuildingUI=VS;exports.BuildingVisibilityDriver=cp;exports.CameraDebugPanel=Bc;exports.CameraPanel=Rc;exports.CameraPresets=Pc;exports.DEFAULT_BUILDING_OBJECT_CATALOG=vi;exports.DRAW_CLUSTER_BILLBOARD=Vs;exports.DRAW_CLUSTER_BLOCK=Ys;exports.DRAW_CLUSTER_COUNT=Xs;exports.DRAW_CLUSTER_DESCRIPTORS=sf;exports.DRAW_CLUSTER_FIRE=Us;exports.DRAW_CLUSTER_FLAG=Ws;exports.DRAW_CLUSTER_GRASS=Ii;exports.DRAW_CLUSTER_MODEL=Zs;exports.DRAW_CLUSTER_SAKURA=Hs;exports.DRAW_CLUSTER_SAND=Ai;exports.DRAW_CLUSTER_SNOWFIELD=ki;exports.DRAW_CLUSTER_TILE=Ti;exports.DRAW_CLUSTER_WALL=Gs;exports.DRAW_CLUSTER_WATER=Ei;exports.Editor=Jv;exports.EditorLayout=Dd;exports.FACE_STYLE_LABEL=Fv;exports.GPU_META_STRIDE=mo;exports.GPU_SPATIAL_STRIDE=ho;exports.GameplayEventPanel=kd;exports.Grass=Ua;exports.GrassDriver=JS;exports.GridHelper=hf;exports.HAIR_STYLE_LABEL=Dv;exports.INDIRECT_DRAW_STRIDE=ft;exports.MotionController=Lc;exports.MotionDebugPanel=zc;exports.MotionPanel=Oc;exports.NPCInstance=ka;exports.NPCPreview=Pd;exports.NPCSystem=Bd;exports.OUTFIT_SLOT_LABEL=Ad;exports.Ocean=Ha;exports.PerformancePanel=$c;exports.ResizablePanel=nw;exports.Sakura=j1;exports.SakuraBatch=Rf;exports.Sand=F1;exports.SandBatch=Lf;exports.Snow=Ga;exports.Snowfield=z1;exports.SnowfieldBatch=Of;exports.StudioPanel=Rd;exports.TileSystem=Yf;exports.VehiclePanel=Gc;exports.WallSystem=qf;exports.WeatherEffect=Ld;exports.autoDetectProfile=na;exports.buildBuildingGpuMirror=lf;exports.buildBuildingIndirectDrawMirror=rf;exports.buildingPlugin=QS;exports.classifyTier=Od;exports.createBuildingGpuUploadPlan=cf;exports.createBuildingIndirectDrawUploadPlan=af;exports.createBuildingPlugin=up;exports.createBuildingScopeId=pa;exports.createCustomMeshId=ca;exports.createEditorCommandStack=rw;exports.createEditorShell=sw;exports.createEditorSlice=Ba;exports.createEmptyBuildingGpuUploadResources=go;exports.createEmptyBuildingIndirectDrawMirror=za;exports.createEmptyGpuMirror=Oa;exports.createNPCObservation=Td;exports.createTerrainBlockMaterial=Ya;exports.destroyBuildingGpuUploadResources=uf;exports.detectCapabilities=zd;exports.editorSlice=iw;exports.findTerrainBlockMaterial=ep;exports.getDefaultBuildingObject=Ts;exports.getDrawClusterForSnapshotEntry=nf;exports.getGrassManager=bo;exports.getIndirectInstanceCount=He;exports.getWallMaterialKey=Zf;exports.getWebGPUDeviceFromRenderer=Ks;exports.index=Hw;exports.index$1=Xw;exports.parseBuildingGpuVisibilityFlags=of;exports.profileForTier=$s;exports.registerNPCBrainAdapter=gv;exports.resolveNPCBrainDecision=Id;exports.syncBuildingGpuBuffers=df;exports.syncBuildingIndirectArgsBuffer=ff;exports.useBuildingEditor=tp;exports.useBuildingGpuCullingStore=Ue;exports.useBuildingRenderStateStore=Be;exports.useBuildingVisibilityStore=mn;exports.useCharacterStore=ss;exports.useEditor=ow;exports.useEditorStore=Fd;exports.usePerfStore=$d;
|