@zylem/game-lib 0.7.0 → 0.8.2

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.
Files changed (98) hide show
  1. package/README.md +15 -1
  2. package/dist/actions.d.ts +71 -8
  3. package/dist/actions.js +1 -1
  4. package/dist/api/game-lib.api.json +55350 -0
  5. package/dist/api/game-lib.api.md +4608 -0
  6. package/dist/api/game-lib.d.ts +8447 -0
  7. package/dist/api/game-lib.typedoc.json +352456 -0
  8. package/dist/audio.js +1 -1
  9. package/dist/{base-node-life-cycle-CnJ-7zX-.d.ts → base-node-life-cycle-BK9xebT9.d.ts} +18 -4
  10. package/dist/behavior.d.ts +2 -3
  11. package/dist/behavior.js +1 -1
  12. package/dist/blueprints-TbGY-h53.d.ts +162 -0
  13. package/dist/chunk-3PRBSSTS.js +24 -0
  14. package/dist/chunk-47DG7I7M.js +1 -0
  15. package/dist/chunk-7GYFZKK7.js +1 -0
  16. package/dist/chunk-7QF6YTEZ.js +1 -0
  17. package/dist/chunk-7WRQ2UAN.js +1 -0
  18. package/dist/chunk-BH53MBAZ.js +1 -0
  19. package/dist/chunk-BIGH6D34.js +0 -0
  20. package/dist/chunk-CD7ZOZ35.js +1 -0
  21. package/dist/chunk-CFVRRRZZ.js +1 -0
  22. package/dist/chunk-CM5YRNBJ.js +19 -0
  23. package/dist/chunk-COM6HJ2L.js +1 -0
  24. package/dist/chunk-D2PATZCC.js +1 -0
  25. package/dist/chunk-DFLI7ICU.js +0 -0
  26. package/dist/chunk-EVYHPR3J.js +1 -0
  27. package/dist/chunk-IPWUDOV5.js +1 -0
  28. package/dist/chunk-JNFFTNMH.js +1 -0
  29. package/dist/chunk-JQKS42G4.js +1 -0
  30. package/dist/chunk-KVSJE4XD.js +1 -0
  31. package/dist/chunk-MZZCDXFB.js +1 -0
  32. package/dist/chunk-ORIDWL3T.js +0 -0
  33. package/dist/{chunk-RXDTAWI2.js → chunk-PCFF4LLO.js} +1 -1
  34. package/dist/chunk-QB3NL7VQ.js +1 -0
  35. package/dist/chunk-TAUWDQZF.js +9 -0
  36. package/dist/chunk-UG22Z42P.js +1 -0
  37. package/dist/chunk-VS2D4B3W.js +1 -0
  38. package/dist/chunk-WQ3WMMZD.js +1 -0
  39. package/dist/chunk-XK63E4SX.js +1 -0
  40. package/dist/chunk-YAOXFYOD.js +1 -0
  41. package/dist/chunk-ZRT3ZQVH.js +1 -0
  42. package/dist/collision-builder-B_tm8OVy.d.ts +49 -0
  43. package/dist/core.d.ts +45 -30
  44. package/dist/core.js +1 -24
  45. package/dist/debug-state-DRoeasG2.d.ts +17 -0
  46. package/dist/debug.d.ts +71 -19
  47. package/dist/debug.js +1 -1
  48. package/dist/{default-controls-BGc61yYl.d.ts → default-controls-CAKJ5zlo.d.ts} +3 -3
  49. package/dist/entity-B9yZeBm4.d.ts +34 -0
  50. package/dist/{entity-DNkYKfdp.d.ts → entity-BGEq1yfC.d.ts} +91 -444
  51. package/dist/{entity-type-map-C94h2TDW.d.ts → entity-type-map-CW6RHQkx.d.ts} +153 -6
  52. package/dist/entity.d.ts +15 -10
  53. package/dist/entity.js +1 -1
  54. package/dist/events.d.ts +10 -1
  55. package/dist/events.js +1 -1
  56. package/dist/{game-Cuj5gy7U.d.ts → game-DbqBQiFC.d.ts} +460 -135
  57. package/dist/game-default-6AZZCNST.js +1 -0
  58. package/dist/{game-interfaces-tfpM5NBk.d.ts → game-interfaces-vF5sRi1n.d.ts} +8 -2
  59. package/dist/globals.d.ts +12 -1
  60. package/dist/globals.js +1 -1
  61. package/dist/graphics.d.ts +16 -46
  62. package/dist/graphics.js +1 -1
  63. package/dist/input-ui.d.ts +5 -4
  64. package/dist/input-ui.js +1 -1
  65. package/dist/input.d.ts +48 -4
  66. package/dist/input.js +1 -1
  67. package/dist/{material-Wz83vTTp.d.ts → material-DbSuZBbP.d.ts} +25 -50
  68. package/dist/public.d.ts +38 -0
  69. package/dist/public.js +1 -0
  70. package/dist/runtime.d.ts +7 -381
  71. package/dist/runtime.js +1 -1
  72. package/dist/schema/entity.schema.json +244 -0
  73. package/dist/schema/game-config.schema.json +643 -0
  74. package/dist/schema/input-config.schema.json +517 -0
  75. package/dist/schema/stage-config.schema.json +93 -0
  76. package/dist/schema/stage.schema.json +271 -0
  77. package/dist/schema.d.ts +550 -0
  78. package/dist/schema.js +1 -0
  79. package/dist/stage-transition-CmGpV4tc.d.ts +46 -0
  80. package/dist/vector-DN6zlPoE.d.ts +161 -0
  81. package/dist/web-components.d.ts +15 -12
  82. package/dist/web-components.js +1 -9
  83. package/dist/{zylem-stage-runtime-Cs-UDEVU.d.ts → zylem-camera-Du2UPW9O.d.ts} +74 -264
  84. package/package.json +28 -20
  85. package/dist/chunk-73VZQZUL.js +0 -1
  86. package/dist/chunk-A34ZG3L4.js +0 -1
  87. package/dist/chunk-CDPY4VOQ.js +0 -1
  88. package/dist/chunk-DR6XXZE7.js +0 -19
  89. package/dist/chunk-FM5TBEPO.js +0 -1
  90. package/dist/chunk-G2IIMSUH.js +0 -1
  91. package/dist/chunk-MSC2BEO5.js +0 -1
  92. package/dist/chunk-NIH5CONO.js +0 -1
  93. package/dist/chunk-ONWXGBWB.js +0 -1
  94. package/dist/chunk-QEDQDR27.js +0 -1
  95. package/dist/chunk-WKHW2QO2.js +0 -1
  96. package/dist/chunk-YHKXQ2ZN.js +0 -1
  97. package/dist/game-default-PZLLHYL7.js +0 -1
  98. package/dist/world-C9zdyl5d.d.ts +0 -103
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zylem/game-lib",
3
- "version": "0.7.0",
3
+ "version": "0.8.2",
4
4
  "type": "module",
5
5
  "description": "A powerful and easy-to-use framework for creating simple 3D digital interactive applications using TypeScript.",
6
6
  "license": "MIT",
@@ -68,13 +68,25 @@
68
68
  "./runtime": {
69
69
  "types": "./dist/runtime.d.ts",
70
70
  "import": "./dist/runtime.js"
71
- }
71
+ },
72
+ "./schema": {
73
+ "types": "./dist/schema.d.ts",
74
+ "import": "./dist/schema.js"
75
+ },
76
+ "./api/rollup": "./dist/api/game-lib.d.ts",
77
+ "./api/report": "./dist/api/game-lib.api.md",
78
+ "./api/model": "./dist/api/game-lib.api.json",
79
+ "./api/typedoc": "./dist/api/game-lib.typedoc.json",
80
+ "./schema/entity": "./dist/schema/entity.schema.json",
81
+ "./schema/stage": "./dist/schema/stage.schema.json",
82
+ "./schema/game-config": "./dist/schema/game-config.schema.json",
83
+ "./schema/stage-config": "./dist/schema/stage-config.schema.json",
84
+ "./schema/input-config": "./dist/schema/input-config.schema.json"
72
85
  },
73
86
  "keywords": [
74
87
  "game",
75
88
  "three",
76
89
  "typescript",
77
- "rapier3d",
78
90
  "physics",
79
91
  "framework",
80
92
  "vite",
@@ -86,51 +98,47 @@
86
98
  "dist"
87
99
  ],
88
100
  "dependencies": {
89
- "comlink": "^4.4.2",
90
101
  "@dgreenheck/three-pinata": "^2.0.1",
91
- "@dimforge/rapier3d-compat": "^0.11.2",
92
102
  "@sinclair/typebox": "^0.34.41",
93
- "@zylem/behaviors": "^0.3.0",
94
103
  "@types/howler": "^2.2.12",
104
+ "@zylem/behaviors": "link:../../../behaviors",
105
+ "comlink": "^4.4.2",
95
106
  "howler": "^2.2.4",
96
107
  "idb-keyval": "^6.2.2",
97
108
  "msgpackr": "^1.11.5",
98
109
  "nanoid": "^5.1.5",
99
110
  "stats.js": "^0.17.0",
100
- "three": "^0.184.0",
111
+ "three": "^0.185.0",
101
112
  "typescript-fsm": "^1.6.0",
102
113
  "valtio": "^2.1.7"
103
114
  },
104
115
  "peerDependencies": {
105
- "@dimforge/rapier3d-compat": "^0.11.2",
106
- "@zylem/runtime": "^0.1.0",
107
116
  "howler": "^2.2.4",
108
117
  "nanoid": "^5.1.5",
109
- "three": "^0.184.0",
118
+ "three": "^0.185.0",
110
119
  "valtio": "^2.1.7"
111
120
  },
112
- "peerDependenciesMeta": {
113
- "@zylem/runtime": {
114
- "optional": true
115
- }
116
- },
117
121
  "devDependencies": {
122
+ "@microsoft/api-extractor": "^7.58.9",
118
123
  "@types/node": "^20.19.13",
119
124
  "@types/stats.js": "^0.17.4",
120
- "@types/three": "^0.184.0",
125
+ "@types/three": "^0.185.0",
126
+ "@typescript/native-preview": "latest",
121
127
  "happy-dom": "^18.0.1",
122
128
  "jsdom": "^27.2.0",
123
129
  "tslib": "^2.8.1",
124
130
  "tsup": "^8.5.1",
131
+ "typedoc": "^0.28.20",
125
132
  "typescript": "6.0.3",
126
- "@typescript/native-preview": "latest",
127
133
  "vite-plugin-solid": "^2.11.8",
128
- "vitest": "^4.0.9",
129
- "@zylem/runtime": "0.1.0"
134
+ "vitest": "^4.0.9"
130
135
  },
131
136
  "scripts": {
132
- "build": "tsup",
137
+ "build": "tsup && pnpm api:extract && pnpm api:typedoc && pnpm schema:emit",
133
138
  "dev": "tsup --watch",
139
+ "api:extract": "mkdir -p dist/api temp && api-extractor run --local --verbose",
140
+ "api:typedoc": "mkdir -p dist/api && typedoc --options typedoc.json",
141
+ "schema:emit": "node --experimental-strip-types ./scripts/emit-json-schemas.ts",
134
142
  "lint": "biome check .",
135
143
  "typecheck": "tsgo --noEmit",
136
144
  "test": "vitest --reporter=verbose",
@@ -1 +0,0 @@
1
- import{c as l,d as c,h as a,k as d}from"./chunk-G2IIMSUH.js";import{ActiveCollisionTypes as D,ColliderDesc as g,RigidBodyDesc as h,RigidBodyType as p,Vector3 as I}from"@dimforge/rapier3d-compat";var u=new Map,m=0;function C(o){let e=u.get(o);return e===void 0&&(e=m++%16,u.set(o,e)),e}function x(o){let e=0;return o.forEach(t=>{let i=C(t);e|=1<<i}),e}var y=class{static=!1;sensor=!1;gravity=new I(0,0,0);build(e){let t=this.bodyDesc({isDynamicBody:!this.static}),i=this.collider(e),s=e.collisionType;if(s){let f=C(s),r=65535;e.collisionFilter&&(r=x(e.collisionFilter)),i.setCollisionGroups(f<<16|r)}let{KINEMATIC_FIXED:n,DEFAULT:b}=D;return i.activeCollisionTypes=this.sensor?n:b,[t,i]}withCollision(e){return this.sensor=e?.sensor??this.sensor,this.static=e?.static??this.static,this}collider(e){let t=d(e.size,c),i={x:t.x/2,y:t.y/2,z:t.z/2},s=g.cuboid(i.x,i.y,i.z),n=a(e.position,l);return s.setTranslation(n.x,n.y,n.z),s}bodyDesc({isDynamicBody:e=!0}){let t=e?p.Dynamic:p.Fixed;return new h(t).setTranslation(0,0,0).setGravityScale(1).setCanSleep(!1).setCcdEnabled(!0)}};export{C as a,x as b,y as c};
@@ -1 +0,0 @@
1
- import{a as p}from"./chunk-CDPY4VOQ.js";import{a as _,b as h}from"./chunk-YHKXQ2ZN.js";var I=4294967295,F=12,q=6,C=7,z=(n=>(n[n.Dynamic=0]="Dynamic",n[n.Static=1]="Static",n[n.KinematicPosition=2]="KinematicPosition",n[n.KinematicVelocity=3]="KinematicVelocity",n))(z||{}),v=(e=>(e[e.Two=2]="Two",e[e.Three=3]="Three",e))(v||{}),w=(e=>(e[e.Two=2]="Two",e[e.Three=3]="Three",e))(w||{}),A=(e=>(e[e.Mirror=0]="Mirror",e[e.Angled=1]="Angled",e))(A||{}),S=(e=>(e[e.Xy=0]="Xy",e[e.Xz=1]="Xz",e))(S||{}),M=(a=>(a[a.CollisionStarted=1]="CollisionStarted",a[a.CollisionStopped=2]="CollisionStopped",a[a.BoundaryHit=3]="BoundaryHit",a[a.Ricochet=4]="Ricochet",a[a.RegionEntered=5]="RegionEntered",a[a.JumpStarted=6]="JumpStarted",a[a.Landed=7]="Landed",a[a.Wrapped=8]="Wrapped",a[a.CooldownFired=9]="CooldownFired",a))(M||{}),d=class{exports;memory;renderView=new Float32Array(0);eventView=new Float32Array(0);poseView=new Float32Array(0);vec3View=new Float32Array(0);queryView=new Float32Array(0);scratchView=new Float32Array(0);constructor(t,e={}){this.exports=t,this.memory=t.memory;let r=Math.max(e.initialCapacity??64,8);t.zylem_stage_create(r),e.gravity&&t.zylem_stage_set_gravity(e.gravity[0],e.gravity[1],e.gravity[2]),this.refreshViews()}refreshViews(){let t=this.memory.buffer,e=this.exports.zylem_stage_render_ptr(),r=this.exports.zylem_stage_render_len(),n=this.exports.zylem_stage_event_ptr(),s=this.exports.zylem_stage_event_len(),u=this.exports.zylem_stage_pose_ptr(),o=this.exports.zylem_stage_pose_len(),m=this.exports.zylem_stage_vec3_ptr(),a=this.exports.zylem_stage_query_ptr(),l=this.exports.zylem_stage_query_len(),c=this.exports.zylem_stage_scratch_ptr(),y=this.exports.zylem_stage_scratch_capacity();this.renderView=r>0?new Float32Array(t,e,r):new Float32Array(0),this.eventView=s>0?new Float32Array(t,n,s):new Float32Array(0),this.poseView=o>0?new Float32Array(t,u,o):new Float32Array(0),this.vec3View=m!==0?new Float32Array(t,m,3):new Float32Array(0),this.queryView=l>0?new Float32Array(t,a,l):new Float32Array(0),this.scratchView=y>0?new Float32Array(t,c,y):new Float32Array(0)}step(t){let e=this.exports.zylem_stage_step(t);return this.refreshViews(),e}dispose(){this.exports.zylem_stage_destroy()}get tickCount(){return this.exports.zylem_stage_tick_count()>>>0}get activeCount(){return this.exports.zylem_stage_active_count()>>>0}setGravity(t,e,r){this.exports.zylem_stage_set_gravity(t,e,r)}createEntity(){let t=this.exports.zylem_stage_create_entity()>>>0;return this.refreshViews(),t}destroyEntity(t){return this.exports.zylem_stage_destroy_entity(t)!==0}attachBody(t,e){return this.exports.zylem_stage_attach_body(t,e.kind,e.position[0],e.position[1],e.position[2],e.rotation[0],e.rotation[1],e.rotation[2],e.rotation[3],e.linearDamping,e.angularDamping,e.gravityScale,e.canSleep?1:0,e.ccdEnabled?1:0,e.lockRotation[0]?1:0,e.lockRotation[1]?1:0,e.lockRotation[2]?1:0,e.lockTranslation[0]?1:0,e.lockTranslation[1]?1:0,e.lockTranslation[2]?1:0)!==0}addCollider(t,e){let r=e.offset,n=e.sensor?1:0,s=e.collisionGroups>>>0,u=e.friction,o=e.restitution;switch(e.shape.type){case"box":{let[m,a,l]=e.shape.halfExtents;return this.exports.zylem_stage_add_collider_box(t,m,a,l,r[0],r[1],r[2],u,o,n,s)!==0}case"sphere":return this.exports.zylem_stage_add_collider_sphere(t,e.shape.radius,r[0],r[1],r[2],u,o,n,s)!==0;case"capsule":return this.exports.zylem_stage_add_collider_capsule(t,e.shape.halfHeight,e.shape.radius,r[0],r[1],r[2],u,o,n,s)!==0;case"cylinder":return this.exports.zylem_stage_add_collider_cylinder(t,e.shape.halfHeight,e.shape.radius,r[0],r[1],r[2],u,o,n,s)!==0;case"convexHull":{let m=e.shape.vertices;if(m.length%3!==0)return!1;let a=this.stageScratch(m);return this.exports.zylem_stage_add_collider_convex_hull(t,a,m.length/3,r[0],r[1],r[2],u,o,n,s)!==0}case"trimesh":{let m=e.shape.vertices,a=e.shape.indices;if(m.length%3!==0||a.length%3!==0)return!1;let l=this.stageScratch(m),c=this.stageScratchIndices(a,l+m.length);return this.exports.zylem_stage_add_collider_trimesh(t,l,m.length/3,c,a.length,r[0],r[1],r[2],u,o,n,s)!==0}case"heightfield":{let m=e.shape.heights,a=this.stageScratch(m);return this.exports.zylem_stage_add_collider_heightfield(t,e.shape.rows,e.shape.cols,e.shape.scale[0],e.shape.scale[1],e.shape.scale[2],a,r[0],r[1],r[2],u,o,s)!==0}default:{let m=e.shape;return!1}}}stageScratch(t,e=0){return this.scratchView.set(t,e),e}stageScratchIndices(t,e){for(let r=0;r<t.length;r++)this.scratchView[e+r]=t[r];return e}getPose(t,e){if(!(this.exports.zylem_stage_get_pose(t)!==0))return null;let n=this.poseView,s=e??{position:[0,0,0],rotation:[0,0,0,1]};return s.position[0]=n[0],s.position[1]=n[1],s.position[2]=n[2],s.rotation[0]=n[3],s.rotation[1]=n[4],s.rotation[2]=n[5],s.rotation[3]=n[6],s}setPosition(t,e,r,n){return this.exports.zylem_stage_set_position(t,e,r,n)!==0}setRotation(t,e,r,n,s){return this.exports.zylem_stage_set_rotation(t,e,r,n,s)!==0}setLinearVelocity(t,e,r,n){return this.exports.zylem_stage_set_linvel(t,e,r,n)!==0}getLinearVelocity(t,e){if(this.exports.zylem_stage_get_linvel(t)===0)return null;let r=this.vec3View,n=e??[0,0,0];return n[0]=r[0],n[1]=r[1],n[2]=r[2],n}setAngularVelocity(t,e,r,n){return this.exports.zylem_stage_set_angvel(t,e,r,n)!==0}applyImpulse(t,e,r,n){return this.exports.zylem_stage_apply_impulse(t,e,r,n)!==0}get render(){return this.renderView}get renderStride(){return 12}drainEvents(){let t=this.exports.zylem_stage_event_count()>>>0;if(t===0)return[];let e=this.eventView,r=new Array(t);for(let n=0;n<t;n++){let s=n*6,u=e[s+1],o=e[s+2];r[n]={type:e[s]|0,primarySlot:Number.isNaN(u)?null:u>>>0,secondarySlot:Number.isNaN(o)?null:o>>>0,payload:[e[s+3],e[s+4],e[s+5]]}}return r}get queryScratch(){return this.queryView}attachCooldown(t){return this.exports.zylem_stage_attach_cooldown(t)!==0}registerCooldown(t,e,r,n=!1){return this.exports.zylem_stage_cooldown_register(t,e>>>0,r,n?1:0)!==0}fireCooldown(t,e){return this.exports.zylem_stage_cooldown_fire(t,e>>>0)!==0}resetCooldown(t,e){return this.exports.zylem_stage_cooldown_reset(t,e>>>0)!==0}cooldownRemaining(t,e){return this.exports.zylem_stage_cooldown_remaining(t,e>>>0)}attachWorldBoundary(t,e,r){return this.exports.zylem_stage_attach_world_boundary(t,e,r.top,r.bottom,r.left,r.right,r.front,r.back,r.padding??0)!==0}queryWorldBoundary(t){if(this.exports.zylem_stage_query_world_boundary(t)===0)return null;let e=this.queryView;return{hits:e[0]|0,clamped:[e[1],e[2],e[3]]}}attachScreenWrap(t,e){return this.exports.zylem_stage_attach_screen_wrap(t,e.width,e.height,e.centerX??0,e.centerY??0,e.edgeThreshold??0)!==0}queryScreenWrap(t){if(this.exports.zylem_stage_query_screen_wrap(t)===0)return null;let e=this.queryView;return{fsm:e[0]|0,lastWrappedAxes:e[1]|0}}attachRicochet(t,e,r){return this.exports.zylem_stage_attach_ricochet(t,e,r.minSpeed,r.maxSpeed,r.speedMultiplier,r.maxAngleDeg,r.reflectionMode)!==0}queryRicochet(t){if(this.exports.zylem_stage_query_ricochet(t)===0)return null;let e=this.queryView;return{bounces:e[0]|0,lastKind:e[1]|0}}attachThruster(t,e){return this.exports.zylem_stage_attach_thruster(t,e.maxSpeed,e.acceleration,e.turnRateRadPerSec,e.linearDamping)!==0}setThrusterInput(t,e,r){this.exports.zylem_stage_set_thruster_input(t,e,r)}queryThruster(t){if(this.exports.zylem_stage_query_thruster(t)===0)return null;let e=this.queryView;return{headingRad:e[0],speed:e[1]}}attachTopDown(t,e){return this.exports.zylem_stage_attach_top_down(t,e.plane,e.speed,e.faceMovement?1:0)!==0}setTopDownInput(t,e,r){this.exports.zylem_stage_set_top_down_input(t,e,r)}attachJumper2D(t,e){return this.exports.zylem_stage_attach_jumper_2d(t,e.jumpForce,e.maxJumps>>>0,e.jumpBufferTime,e.coyoteTime,e.gravity)!==0}setJumper2DInput(t,e){this.exports.zylem_stage_set_jumper_2d_input(t,e?1:0)}queryJumper2D(t){if(this.exports.zylem_stage_query_jumper_2d(t)===0)return null;let e=this.queryView;return{grounded:e[0]>.5,jumpCount:e[1]|0,coyote:e[2],jumpBuffer:e[3]}}attachJumper3D(t,e){return this.exports.zylem_stage_attach_jumper_3d(t,e.jumpForce,e.maxJumps>>>0,e.gravity)!==0}setJumper3DInput(t,e){this.exports.zylem_stage_set_jumper_3d_input(t,e?1:0)}queryJumper3D(t){if(this.exports.zylem_stage_query_jumper_3d(t)===0)return null;let e=this.queryView;return{grounded:e[0]>.5,jumpCount:e[1]|0,verticalVelocity:e[2]}}attachShooter2D(t,e){return this.exports.zylem_stage_attach_shooter_2d(t,e.fireRateHz,e.muzzleOffsetX,e.muzzleOffsetY,e.muzzleSpeed)!==0}fireShooter2D(t,e,r,n,s){return this.exports.zylem_stage_shooter_2d_fire(t,e,r,n,s)!==0}queryShooter2D(t){if(this.exports.zylem_stage_query_shooter_2d(t)===0)return null;let e=this.queryView;return{cooldown:e[0],firedCount:e[1]|0}}attachPlatformer3D(t,e){return this.exports.zylem_stage_attach_platformer_3d(t,e.halfHeight,e.radius,e.walkSpeed,e.runSpeed,e.jumpForce,e.maxJumps>>>0,e.gravity)!==0}setPlatformer3DInputAxes(t,e,r){this.exports.zylem_stage_set_platformer_3d_input_axes(t,e,r)}setPlatformer3DInputButtons(t,e,r){this.exports.zylem_stage_set_platformer_3d_input_buttons(t,e?1:0,r?1:0)}queryPlatformer3D(t){if(this.exports.zylem_stage_query_platformer_3d(t)===0)return null;let e=this.queryView;return{grounded:e[0]>.5,jumpCount:e[1]|0,fsmState:e[2]|0,speed:e[3]}}attachFirstPerson(t,e){return this.exports.zylem_stage_attach_first_person(t,e.walkSpeed,e.runSpeed,e.eyeHeight,e.lookSensitivity)!==0}setFirstPersonInput(t,e){this.exports.zylem_stage_set_first_person_input(t,e.moveX,e.moveZ,e.lookYawDelta,e.lookPitchDelta,e.run?1:0)}queryFirstPerson(t){if(this.exports.zylem_stage_query_first_person(t)===0)return null;let e=this.queryView;return{yaw:e[0],pitch:e[1],speed:e[2],eyeHeight:e[3]}}};async function V(i,t={}){let e;i instanceof ArrayBuffer?e=i:e=await(await fetch(i)).arrayBuffer();let{instance:r}=await WebAssembly.instantiate(e,t.imports??{}),n=r.exports;return new d(n,t)}function R(){return{runtimeDiagnostics(){return p.enabled}}}import{InstancedMesh as g,Matrix4 as b,Vector3 as f,Quaternion as k}from"three";var x=class i{batches=new Map;entityToBatch=new Map;scene=null;static DEFAULT_CAPACITY=128;static GROWTH_FACTOR=2;setScene(t){this.scene=t}static generateBatchKey(t){let e={geo:`${t.geometryType}:${_(t.dimensions)}`,mat:t.materialPath||"none",shader:t.shaderType||"standard",color:t.colorHex??16777215};return h(_(e))}static generateEntityBatchKey(t){let e=t.options;if(e.runtime?.batchKeyOverride)return e.runtime.batchKeyOverride;let r=t.constructor?.type?.description||"unknown",n=e.size||{x:1,y:1,z:1},s=e.material||{};return i.generateBatchKey({geometryType:r,dimensions:{x:n.x,y:n.y,z:n.z},materialPath:s.path||null,shaderType:s.shader?"custom":"standard",colorHex:s.color?.getHex?.()||e.color?.getHex?.()||16777215})}register(t,e,r,n){let s=this.batches.get(n);s||(s=this.createBatch(n,e,r));let u;return s.freeIndices.length>0?u=s.freeIndices.pop():(u=s.entities.length,u>=s.capacity&&this.growBatch(s),s.entities.push(null)),s.entities[u]=t,s.entityMap.set(t.uuid,u),this.entityToBatch.set(t.uuid,n),s.instancedMesh.count=Math.max(s.instancedMesh.count,u+1),s.activeIndices.push(u),s.dirtyIndices.add(u),u}unregister(t){let e=this.entityToBatch.get(t.uuid);if(!e)return;let r=this.batches.get(e);if(!r)return;let n=r.entityMap.get(t.uuid);if(n===void 0)return;r.entities[n]=null,r.entityMap.delete(t.uuid),this.entityToBatch.delete(t.uuid),r.freeIndices.push(n);let s=r.activeIndices.indexOf(n);if(s!==-1){let o=r.activeIndices.pop();s<r.activeIndices.length&&(r.activeIndices[s]=o)}r.dirtyIndices.delete(n);let u=new b;u.makeScale(0,0,0),r.instancedMesh.setMatrixAt(n,u),r.instancedMesh.instanceMatrix.needsUpdate=!0}markDirty(t){let e=this.entityToBatch.get(t.uuid);if(!e)return;let r=this.batches.get(e);if(!r)return;let n=r.entityMap.get(t.uuid);n!==void 0&&r.dirtyIndices.add(n)}update(){let t=new b,e=new f,r=new k,n=new f(1,1,1);for(let s of this.batches.values()){if(s.activeIndices.length===0)continue;let u=!1;if(s.dirtyIndices.size>0){for(let o of s.dirtyIndices)this.updateInstanceMatrix(s,o,t,e,r,n);s.dirtyIndices.clear(),u=!0}for(let o of s.activeIndices){let m=s.entities[o];m&&m.body&&(this.updateInstanceMatrix(s,o,t,e,r,n),u=!0)}u&&(s.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(t,e,r,n,s,u){let o=t.entities[e];if(o){if(o.body){let m=o.body.translation(),a=o.body.rotation();n.set(m.x,m.y,m.z),s.set(a.x,a.y,a.z,a.w),r.compose(n,s,u)}else o.mesh?(o.mesh.updateMatrix(),r.copy(o.mesh.matrix)):o.group&&(o.group.updateMatrix(),r.copy(o.group.matrix));t.instancedMesh.setMatrixAt(e,r)}}getBatchInfo(t){let e=this.entityToBatch.get(t.uuid);if(!e)return null;let r=this.batches.get(e);if(!r)return null;let n=r.entityMap.get(t.uuid);return n===void 0?null:{batchKey:e,instanceId:n}}getStats(){let t=0,e=[];for(let[r,n]of this.batches){let s=n.entityMap.size;t+=s,e.push({key:r,count:s,capacity:n.capacity})}return{batchCount:this.batches.size,totalInstances:t,batches:e}}dispose(){for(let t of this.batches.values())this.scene&&this.scene.remove(t.instancedMesh),t.instancedMesh.dispose(),t.geometry.dispose();this.batches.clear(),this.entityToBatch.clear()}createBatch(t,e,r){let n=i.DEFAULT_CAPACITY,s=new g(e,r,n);s.count=0,s.frustumCulled=!1;let u=new b().makeScale(0,0,0);for(let m=0;m<n;m++)s.setMatrixAt(m,u);s.instanceMatrix.needsUpdate=!0;let o={key:t,instancedMesh:s,geometry:e,material:r,entityMap:new Map,entities:[],freeIndices:[],activeIndices:[],dirtyIndices:new Set,capacity:n};return this.batches.set(t,o),this.scene&&this.scene.add(s),o}growBatch(t){let e=t.capacity*i.GROWTH_FACTOR,r=new g(t.geometry,t.material,e);r.count=t.instancedMesh.count,r.frustumCulled=!1;let n=new b;for(let u=0;u<t.capacity;u++)t.instancedMesh.getMatrixAt(u,n),r.setMatrixAt(u,n);let s=new b().makeScale(0,0,0);for(let u=t.capacity;u<e;u++)r.setMatrixAt(u,s);r.instanceMatrix.needsUpdate=!0,this.scene&&(this.scene.remove(t.instancedMesh),this.scene.add(r)),t.instancedMesh.dispose(),t.instancedMesh=r,t.capacity=e}};export{x as a,I as b,F as c,q as d,C as e,z as f,v as g,w as h,A as i,S as j,M as k,d as l,V as m,R as n};
@@ -1 +0,0 @@
1
- import{proxy as n}from"valtio";var e=n({enabled:!1,paused:!1,tool:"none",selectedEntity:null,hoveredEntity:null,flags:new Set});function l(){return e.paused}function i(t){e.paused=t}function a(){return e.tool}function r(t){e.tool=t}function u(t){e.selectedEntity=t}function s(){return e.hoveredEntity}function d(t){e.hoveredEntity=t}function y(){e.hoveredEntity=null}export{e as a,l as b,i as c,a as d,r as e,u as f,s as g,d as h,y as i};
@@ -1,19 +0,0 @@
1
- import{a as R}from"./chunk-QXVH6POE.js";import{a as C,b as G}from"./chunk-YHKXQ2ZN.js";import{b as p,i as h}from"./chunk-G2IIMSUH.js";var B=`
2
- uniform vec2 uvScale;
3
- varying vec2 vUv;
4
-
5
- void main() {
6
- vUv = uv;
7
- vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
8
- gl_Position = projectionMatrix * mvPosition;
9
- }
10
- `;var X=`
11
- uniform sampler2D tDiffuse;
12
- varying vec2 vUv;
13
-
14
- void main() {
15
- vec4 texel = texture2D( tDiffuse, vUv );
16
-
17
- gl_FragColor = texel;
18
- }
19
- `,O={vertex:B,fragment:X};import{Color as A,RepeatWrapping as v,SRGBColorSpace as te}from"three";import{MeshBasicNodeMaterial as ae,MeshStandardNodeMaterial as P}from"three/webgpu";import{LoadingManager as ee,Cache as k}from"three";import{TextureLoader as W,RepeatWrapping as E}from"three";var M=16,L=class{loader;constructor(){this.loader=new W}isSupported(e){let t=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","bmp","tga"].includes(t||"")}async load(e,t){let a=await this.loader.loadAsync(e,r=>{t?.onProgress&&r.lengthComputable&&t.onProgress(r.loaded/r.total)});return t?.repeat&&a.repeat.copy(h(t.repeat,p)),a.wrapS=t?.wrapS??E,a.wrapT=t?.wrapT??E,t?.colorSpace!==void 0&&(a.colorSpace=t.colorSpace),a.anisotropy=t?.anisotropy??M,a}clone(e){let t=e.clone();return t.anisotropy=e.anisotropy||M,t.needsUpdate=!0,t}};import{GLTFLoader as J}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as K}from"three/addons/loaders/DRACOLoader.js";import{KTX2Loader as Z}from"three/addons/loaders/KTX2Loader.js";import{MeshoptDecoder as $}from"three/addons/libs/meshopt_decoder.module.js";import{Mesh as j}from"three";import{clone as I}from"three/addons/utils/SkeletonUtils.js";function u(s){let e=I(s),t=[],a=[];s.traverse(r=>t.push(r)),e.traverse(r=>a.push(r));for(let r=0;r<t.length;r++){let o=t[r],i=a[r];!(o instanceof j)||!(i instanceof j)||(o.geometry?.clone&&(i.geometry=o.geometry.clone()),o.material&&(i.material=Array.isArray(o.material)?o.material.map(n=>n.clone()):o.material.clone()))}return e}function N(s){let e=s.indexOf("?"),t=s.indexOf("#"),a=[e,t].filter(r=>r>=0).reduce((r,o)=>Math.min(r,o),s.length);return s.slice(0,a)}function c(s){let e=N(s),t=e.lastIndexOf("/"),a=t>=0?e.slice(t+1):e,r=a.lastIndexOf(".");return r<0||r===a.length-1?null:a.slice(r+1).toLowerCase()}var V=["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"],_="https://www.gstatic.com/draco/v1/decoders/",g=class{loader;dracoLoader;ktx2Loader=null;meshoptEnabled=!1;configuredRenderer=null;ktx2TranscoderPath=null;constructor(){this.dracoLoader=new K,this.dracoLoader.setDecoderPath(_),this.loader=new J,this.loader.setDRACOLoader(this.dracoLoader),this.setMeshoptEnabled(!0)}isSupported(e){let t=c(e);return["gltf","glb"].includes(t||"")}async configureRuntime({meshopt:e=!0,ktx2TranscoderPath:t,renderer:a=null}={}){this.setMeshoptEnabled(e!==!1);let r=this.normalizeTranscoderPath(t);if(!r){this.clearKTX2Loader();return}if(!a)throw new Error("GLTFLoaderAdapter.configureRuntime requires a renderer when ktx2TranscoderPath is provided.");(!this.ktx2Loader||this.ktx2TranscoderPath!==r)&&(this.clearKTX2Loader(),this.ktx2Loader=new Z,this.ktx2Loader.setTranscoderPath(r),this.loader.setKTX2Loader(this.ktx2Loader),this.ktx2TranscoderPath=r,this.configuredRenderer=null),!(!this.ktx2Loader||this.configuredRenderer===a)&&(this.ktx2Loader.detectSupport(a),this.configuredRenderer=a)}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let a=await fetch(e);if(!a.ok)throw new Error(`Failed to fetch ${e}: ${a.status} ${a.statusText}`);let r=await a.arrayBuffer(),o=await this.loader.parseAsync(r,e);return this.applyTextureAnisotropy(o.scene),{object:o.scene,animations:o.animations,gltf:o}}catch(a){return console.error(`Async fetch GLTF load failed for ${e}, falling back to loader.load():`,a),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((a,r)=>{this.loader.load(e,o=>{this.applyTextureAnisotropy(o.scene),a({object:o.scene,animations:o.animations,gltf:o})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>r(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone()),gltf:e.gltf}}applyTextureAnisotropy(e){e.traverse(t=>{let a=t.material;if(!a)return;let r=Array.isArray(a)?a:[a];for(let o of r)for(let i of V){let n=o[i];if(n&&n.isTexture){let d=n;d.anisotropy=M,d.needsUpdate=!0}}})}setMeshoptEnabled(e){if(e){if(this.meshoptEnabled)return;this.loader.setMeshoptDecoder($),this.meshoptEnabled=!0;return}this.meshoptEnabled&&(this.loader.setMeshoptDecoder(void 0),this.meshoptEnabled=!1)}clearKTX2Loader(){this.ktx2Loader&&(this.ktx2Loader.dispose(),this.ktx2Loader=null),this.loader.setKTX2Loader(void 0),this.configuredRenderer=null,this.ktx2TranscoderPath=null}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}};import{FBXLoader as z}from"three/addons/loaders/FBXLoader.js";var T=class{loader;constructor(){this.loader=new z}isSupported(e){return c(e)==="fbx"}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let a=await fetch(e);if(!a.ok)throw new Error(`Failed to fetch ${e}: ${a.status} ${a.statusText}`);let r=await a.arrayBuffer(),o=this.loader.parse(r,e);return{object:o,animations:o.animations||[]}}catch(a){return console.error(`Async fetch FBX load failed for ${e}, falling back to loader.load():`,a),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((a,r)=>{this.loader.load(e,o=>{a({object:o,animations:o.animations||[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>r(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone())}}};import{OBJLoader as H}from"three/addons/loaders/OBJLoader.js";import{MTLLoader as Y}from"three/addons/loaders/MTLLoader.js";var y=class{loader;mtlLoader;constructor(){this.loader=new H,this.mtlLoader=new Y}isSupported(e){return c(e)==="obj"}async load(e,t){return t?.mtlPath&&await this.loadMTL(t.mtlPath),new Promise((a,r)=>{this.loader.load(e,o=>{a({object:o,animations:[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>r(o))})}async loadMTL(e){return new Promise((t,a)=>{this.mtlLoader.load(e,r=>{r.preload(),this.loader.setMaterials(r),t()},void 0,r=>a(r))})}clone(e){return{object:u(e.object),animations:[]}}};import{AudioLoader as q}from"three";var x=class{loader;constructor(){this.loader=new q}isSupported(e){let t=c(e);return["mp3","ogg","wav","flac","aac","m4a"].includes(t||"")}async load(e,t){return new Promise((a,r)=>{this.loader.load(e,o=>a(o),o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>r(o))})}};import{FileLoader as Q}from"three";var m=class{loader;constructor(){this.loader=new Q}isSupported(e){return!0}async load(e,t){let a=t?.responseType??"text";return this.loader.setResponseType(a),new Promise((r,o)=>{this.loader.load(e,i=>r(i),i=>{t?.onProgress&&i.lengthComputable&&t.onProgress(i.loaded/i.total)},i=>o(i))})}},b=class{fileLoader;constructor(){this.fileLoader=new m}isSupported(e){return c(e)==="json"}async load(e,t){return await this.fileLoader.load(e,{...t,responseType:"json"})}};var w=class s{static instance=null;textureCache=new Map;modelCache=new Map;audioCache=new Map;fileCache=new Map;jsonCache=new Map;pendingGLTFRuntimePath=null;pendingGLTFRuntimePromise=null;pendingGLTFRuntimeResolve=null;textureLoader;gltfLoader;fbxLoader;objLoader;audioLoader;fileLoader;jsonLoader;loadingManager;events;stats={texturesLoaded:0,modelsLoaded:0,audioLoaded:0,filesLoaded:0,cacheHits:0,cacheMisses:0};constructor(){this.textureLoader=new L,this.gltfLoader=new g,this.fbxLoader=new T,this.objLoader=new y,this.audioLoader=new x,this.fileLoader=new m,this.jsonLoader=new b,this.loadingManager=new ee,this.loadingManager.onProgress=(e,t,a)=>{this.events.emit("batch:progress",{loaded:t,total:a})},this.events=R(),k.enabled=!0}static getInstance(){return s.instance||(s.instance=new s),s.instance}static resetInstance(){s.instance&&(s.instance.clearCache(),s.instance=null)}async loadTexture(e,t){return this.loadWithCache(e,"texture",this.textureCache,()=>this.textureLoader.load(e,t),t,a=>{if(!t?.clone)return a;let r=this.textureLoader.clone(a);return t.repeat&&r.repeat.copy(h(t.repeat,p)),t.wrapS!==void 0&&(r.wrapS=t.wrapS),t.wrapT!==void 0&&(r.wrapT=t.wrapT),r})}async loadGLTF(e,t){return await this.waitForPreparedGLTFRuntime(),this.loadWithCache(e,"gltf",this.modelCache,()=>this.gltfLoader.load(e,t),t,a=>t?.clone?this.gltfLoader.clone(a):a)}prepareGLTFRuntime(e){let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&(this.pendingGLTFRuntimePath===t&&this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePath=t,this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePromise=new Promise(a=>{this.pendingGLTFRuntimeResolve=a}))))}async configureGLTFRuntime(e){await this.gltfLoader.configureRuntime(e);let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&e?.renderer&&this.resolvePreparedGLTFRuntime(t)}async loadFBX(e,t){return this.loadWithCache(e,"fbx",this.modelCache,()=>this.fbxLoader.load(e,t),t,a=>t?.clone?this.fbxLoader.clone(a):a)}async loadOBJ(e,t){let a=t?.mtlPath?`${e}:${t.mtlPath}`:e;return this.loadWithCache(a,"obj",this.modelCache,()=>this.objLoader.load(e,t),t,r=>t?.clone?this.objLoader.clone(r):r)}async loadModel(e,t){let a=c(e);switch(a){case"gltf":case"glb":return this.loadGLTF(e,t);case"fbx":return this.loadFBX(e,t);case"obj":return this.loadOBJ(e,t);default:throw new Error(`Unsupported model format: ${a}`)}}async loadAudio(e,t){return this.loadWithCache(e,"audio",this.audioCache,()=>this.audioLoader.load(e,t),t)}async loadFile(e,t){let a=t?.responseType?`${e}:${t.responseType}`:e;return this.loadWithCache(a,"file",this.fileCache,()=>this.fileLoader.load(e,t),t)}async loadJSON(e,t){return this.loadWithCache(e,"json",this.jsonCache,()=>this.jsonLoader.load(e,t),t)}async loadBatch(e){let t=new Map,a=e.map(async r=>{try{let o;switch(r.type){case"texture":o=await this.loadTexture(r.url,r.options);break;case"gltf":o=await this.loadGLTF(r.url,r.options);break;case"fbx":o=await this.loadFBX(r.url,r.options);break;case"obj":o=await this.loadOBJ(r.url,r.options);break;case"audio":o=await this.loadAudio(r.url,r.options);break;case"file":o=await this.loadFile(r.url,r.options);break;case"json":o=await this.loadJSON(r.url,r.options);break;default:throw new Error(`Unknown asset type: ${r.type}`)}t.set(r.url,o)}catch(o){throw this.events.emit("asset:error",{url:r.url,type:r.type,error:o}),o}});return await Promise.all(a),this.events.emit("batch:complete",{urls:e.map(r=>r.url)}),t}async preload(e){await this.loadBatch(e)}isCached(e){return this.textureCache.has(e)||this.modelCache.has(e)||this.audioCache.has(e)||this.fileCache.has(e)||this.jsonCache.has(e)}clearCache(e){e?(this.textureCache.delete(e),this.modelCache.delete(e),this.audioCache.delete(e),this.fileCache.delete(e),this.jsonCache.delete(e)):(this.textureCache.clear(),this.modelCache.clear(),this.audioCache.clear(),this.fileCache.clear(),this.jsonCache.clear(),k.clear(),this.pendingGLTFRuntimePath=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimeResolve=null)}getStats(){return{...this.stats}}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}async loadWithCache(e,t,a,r,o,i){o?.forceReload&&a.delete(e);let n=a.get(e);if(n){this.stats.cacheHits++,this.events.emit("asset:loaded",{url:e,type:t,fromCache:!0});let l=await n.promise;return i?i(l):l}this.stats.cacheMisses++,this.events.emit("asset:loading",{url:e,type:t});let d=r(),f={promise:d,loadedAt:Date.now()};a.set(e,f);try{let l=await d;return f.result=l,this.updateStats(t),this.events.emit("asset:loaded",{url:e,type:t,fromCache:!1}),i?i(l):l}catch(l){throw a.delete(e),this.events.emit("asset:error",{url:e,type:t,error:l}),l}}updateStats(e){switch(e){case"texture":this.stats.texturesLoaded++;break;case"gltf":case"fbx":case"obj":this.stats.modelsLoaded++;break;case"audio":this.stats.audioLoaded++;break;case"file":case"json":this.stats.filesLoaded++;break}}async waitForPreparedGLTFRuntime(){this.pendingGLTFRuntimePromise&&await this.pendingGLTFRuntimePromise}resolvePreparedGLTFRuntime(e){this.pendingGLTFRuntimePath&&this.pendingGLTFRuntimePath!==e||(this.pendingGLTFRuntimeResolve?.(),this.pendingGLTFRuntimeResolve=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimePath=null)}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}},F=w.getInstance();import{uniform as Mt,uv as vt,time as Ot,vec3 as wt,vec4 as Ft,float as At,Fn as Pt}from"three/tsl";function re(s){return"colorNode"in s}function D(s){return"fragment"in s&&"vertex"in s}function oe(s){return!!s&&D(s)&&s.vertex===O.vertex&&s.fragment===O.fragment}var U=class s{static batchMaterialMap=new Map;static clearBatchCache(){s.batchMaterialMap.clear()}materials=[];useTSL;constructor(e=!0){this.useTSL=e}batchMaterial(e,t){let a=G(C(e)),r=s.batchMaterialMap.get(a);if(r){let o=r.geometryMap.get(t);o?r.geometryMap.set(t,o+1):r.geometryMap.set(t,1)}else s.batchMaterialMap.set(a,{geometryMap:new Map([[t,1]]),material:this.materials[0]})}build(e,t){let{path:a,normalMap:r,repeat:o,color:i,shader:n,opacity:d}=e,f=oe(n),l=!!n&&!f,S=!!a&&(!n||f);S?this.setTexture(a??null,o,!0,d,i):l&&n?re(n)?this.setTSLShader(n,d):D(n)&&(console.warn("MaterialBuilder: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(i??new A("#ffffff"),!0,d)):a&&this.setTexture(a,o,!0,d,i),i&&!S&&!l&&this.withColor(i,!0,d),this.materials.length===0&&this.setColor(new A("#ffffff"),!0,d),r&&this.materials.length>0&&this.setNormalMap(r,o),this.batchMaterial(e,t)}withColor(e,t=!1,a){return this.setColor(e,t,a),this}withShader(e,t){return this.setShader(e,t),this}withTSLShader(e,t){return this.setTSLShader(e,t),this}applyOpacity(e,t,a=!1){t!==void 0&&(e.opacity=t),e.transparent=a||t!==void 0&&t<1,e.needsUpdate=!0}setTexture(e=null,t=p,a=!0,r,o){if(!e)return;let i=new P;o&&(i.color=o),this.applyOpacity(i,r),this.materials.push(i),F.loadTexture(e,{clone:!0,repeat:h(t,p),colorSpace:te}).then(n=>{n.wrapS=v,n.wrapT=v,i.map=n,i.needsUpdate=!0})}setNormalMap(e,t=p){let a=this.materials[this.materials.length-1];a&&F.loadTexture(e,{clone:!0,repeat:h(t,p)}).then(r=>{r.wrapS=v,r.wrapT=v,a instanceof P&&(a.normalMap=r,a.needsUpdate=!0)})}setColor(e,t=!0,a){let r=new P;r.color=e,this.applyOpacity(r,a),this.materials.push(r)}setShader(e,t){console.warn("MaterialBuilder.setShader: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(new A("#ffffff"),!0,t)}setTSLShader(e,t){this.materials.push(se(e,t))}};function se(s,e){let t=new ae;return t.colorNode=s.colorNode,e!==void 0&&(t.opacity=e),t.transparent=!!s.transparent||e!==void 0&&e<1,t.needsUpdate=!0,t}export{B as a,O as b,M as c,c as d,F as e,re as f,D as g,U as h,se as i,Mt as j,vt as k,Ot as l,wt as m,Ft as n,At as o,Pt as p};
@@ -1 +0,0 @@
1
- function u(i,e){return i.priority!==e.priority?i.priority-e.priority:i.sourceId.localeCompare(e.sourceId)}function s(i,e,d){let r=!1,y=0,l=!1,c=i,a=Number.NEGATIVE_INFINITY;for(let t of e){let o=t[d];if(o!=null){if(r=!0,t.mode==="add"){y+=o;continue}(!l||t.priority>=a)&&(l=!0,a=t.priority,c=o)}}return{touched:r,value:(l?c:0)+y}}function f(i,e){return{x:s(i.x,e,"x"),y:s(i.y,e,"y"),z:s(i.z,e,"z")}}function p(i){for(let e in i.velocityChannels)delete i.velocityChannels[e];i.dirty.velocityChannels=!1}function m(i,e){if(!i.body)return;let d=e.dirty.position,r=e.dirty.rotation,y=e.dirty.angularVelocity,l=e.dirty.velocityX||e.dirty.velocityY||e.dirty.velocityZ,c=e.dirty.velocity,a=e.dirty.velocityChannels;if(!d&&!r&&!y&&!l&&!c&&!a)return;let t=[];if(a)for(let o in e.velocityChannels){let n=e.velocityChannels[o];t.push({sourceId:o,mode:n.mode??"replace",priority:n.priority??0,x:n.x,y:n.y,z:n.z})}if(c?t.push({sourceId:"__legacy_velocity__",mode:"replace",priority:-100,x:e.velocity.x,y:e.velocity.y,z:e.velocity.z}):l&&t.push({sourceId:"__legacy_per_axis__",mode:"replace",priority:-100,x:e.dirty.velocityX?e.velocity.x:void 0,y:e.dirty.velocityY?e.velocity.y:void 0,z:e.dirty.velocityZ?e.velocity.z:void 0}),t.length>0){let o=i.body.linvel();t.length>1&&t.sort(u);let n=f(o,t);i.body.setLinvel({x:n.x.touched?n.x.value:o.x,y:n.y.touched?n.y.value:o.y,z:n.z.touched?n.z.value:o.z},!0)}if(r&&i.body.setRotation(e.rotation,!0),y&&i.body.setAngvel(e.angularVelocity,!0),d){let o=i.body.translation();i.body.setTranslation({x:o.x+e.position.x,y:o.y+e.position.y,z:o.z+e.position.z},!0)}e.dirty.position=!1,e.dirty.rotation=!1,e.dirty.velocity=!1,e.dirty.velocityX=!1,e.dirty.velocityY=!1,e.dirty.velocityZ=!1,p(e),e.dirty.angularVelocity=!1}export{m as a};
@@ -1 +0,0 @@
1
- import{Vector2 as x,Vector3 as b}from"three";import{Vector3 as f}from"@dimforge/rapier3d-compat";var i=Object.freeze({x:0,y:0}),k=Object.freeze({x:1,y:1}),p=Object.freeze({x:0,y:0,z:0}),A=Object.freeze({x:1,y:1,z:1});function V(n){return typeof n=="number"&&Number.isFinite(n)}function a(n){return n!=null&&typeof n=="object"&&("x"in n||"y"in n)}function l(n){return n!=null&&typeof n=="object"&&("x"in n||"y"in n||"z"in n)}function m(n,t,e){if(!n)return e;let r=n[t];return V(r)?r:e}function y(n,t,e){if(!n)return e;let r=n[t];return V(r)?r:e}function u(n,t,e,r){return n?Array.isArray(n)?m(n,e,r):y(n,t,r):r}function o(n,t,e,r){return n?Array.isArray(n)?m(n,e,r):y(n,t,r):r}function z(n){return{x:u(n,"x",0,0),y:u(n,"y",1,0)}}function C(n){return{x:o(n,"x",0,0),y:o(n,"y",1,0),z:o(n,"z",2,0)}}function h(n){return Array.isArray(n)||a(n)}function T(n){return Array.isArray(n)||l(n)}function I(n,t=i){let e=z(t);return{x:u(n,"x",0,e.x),y:u(n,"y",1,e.y)}}function s(n,t=p){let e=C(t);return{x:o(n,"x",0,e.x),y:o(n,"y",1,e.y),z:o(n,"z",2,e.z)}}function R(n,t=i){let{x:e,y:r}=I(n,t);return new x(e,r)}function O(n,t=p){let{x:e,y:r,z:c}=s(n,t);return new b(e,r,c)}function P(n,t=p){let{x:e,y:r,z:c}=s(n,t);return new f(e,r,c)}export{i as a,k as b,p as c,A as d,h as e,T as f,I as g,s as h,R as i,O as j,P as k};
@@ -1 +0,0 @@
1
- function r(n,e){return{[n]:{key:e}}}function k(n){return r(n,{ArrowLeft:["axes.Left"],ArrowRight:["axes.Right"],ArrowUp:["axes.Up"],ArrowDown:["axes.Down"]})}function x(n){return r(n,{ArrowLeft:["axes.SecondaryLeft"],ArrowRight:["axes.SecondaryRight"],ArrowUp:["axes.SecondaryUp"],ArrowDown:["axes.SecondaryDown"]})}function w(n){return r(n,{ArrowLeft:["directions.Left"],ArrowRight:["directions.Right"],ArrowUp:["directions.Up"],ArrowDown:["directions.Down"]})}function A(n){return r(n,{w:["directions.Up"],s:["directions.Down"],a:["directions.Left"],d:["directions.Right"]})}function G(n){return r(n,{a:["axes.Left"],d:["axes.Right"],w:["axes.Up"],s:["axes.Down"]})}function J(n){return r(n,{j:["axes.Left"],l:["axes.Right"],i:["axes.Up"],k:["axes.Down"]})}function B(n){return r(n,{j:["directions.Left"],l:["directions.Right"],i:["directions.Up"],k:["directions.Down"]})}function D(n,e){return{[n]:{mouse:{pointerLock:!0,sensitivity:e?.sensitivity}}}}function P(n,e){return{[n]:{mouse:{pointerLock:!1,sensitivity:e?.sensitivity}}}}function b(n,e){return{[n]:{touch:{enabled:e?.enabled??"auto",...e}}}}var h=["p1","p2","p3","p4","p5","p6","p7","p8"];function L(...n){let e={};for(let u of n)for(let t of h){let s=u[t];if(!s)continue;let o=e[t]??{},f=o.mouse||s.mouse?{...o.mouse,...s.mouse,mapping:{...o.mouse?.mapping,...s.mouse?.mapping}}:void 0,a=T(o.touch,s.touch);e[t]={key:{...o.key,...s.key},mouse:f,touch:a,includeDefaults:s.includeDefaults??o.includeDefaults}}return e}function T(n,e){if(!(!n&&!e))return n?e?{...n,...e,style:i(n.style,e.style),joysticks:m(n.joysticks,e.joysticks),buttons:I(n.buttons,e.buttons)}:d(n):d(e)}function m(n,e){if(e===void 0)return p(n);if(e===!1)return!1;let u=n||void 0;return{left:c(u?.left,e.left),right:c(u?.right,e.right)}}function c(n,e){return e===void 0?l(n):e===!1?!1:n?{...n,...e,style:i(n.style,e.style),position:i(n.position,e.position),svg:i(n.svg,e.svg)}:l(e)}function I(n,e){if(e===void 0)return y(n);if(e===!1)return!1;let u=n||void 0,t=u?C(u):{};for(let[s,o]of Object.entries(e)){let f=s,a=t[f];if(o===!1){t[f]=!1;continue}if(!a){t[f]=g(o);continue}t[f]={...a,...o,style:i(a.style,o.style),position:i(a.position,o.position)}}return t}function d(n){if(n)return{...n,style:i(void 0,n.style),joysticks:p(n.joysticks),buttons:y(n.buttons)}}function p(n){if(n!==void 0)return n===!1?!1:V(n)}function l(n){if(n!==void 0)return n===!1?!1:{...n,style:i(void 0,n.style),position:i(void 0,n.position),svg:i(void 0,n.svg)}}function y(n){if(n!==void 0)return n===!1?!1:C(n)}function g(n){return{...n,style:i(void 0,n.style),position:i(void 0,n.position)}}function V(n){return{left:l(n.left),right:l(n.right)}}function C(n){let e={};for(let[u,t]of Object.entries(n))e[u]=t===!1?!1:g(t);return e}function i(n,e){if(!(!n&&!e))return{...n??{},...e??{}}}export{k as a,x as b,w as c,A as d,G as e,J as f,B as g,D as h,P as i,b as j,L as k};
@@ -1 +0,0 @@
1
- import{b as f,k as F,m as x,p as g,q as z,s as _}from"./chunk-ONWXGBWB.js";import{c as I}from"./chunk-DR6XXZE7.js";import{d as y,i as C,j as d}from"./chunk-G2IIMSUH.js";import{Color as M,Group as W,Sprite as U,SpriteMaterial as Y,CanvasTexture as R,LinearFilter as S,Vector2 as X,ClampToEdgeWrapping as P}from"three";import{MeshStandardMaterial as k,MeshBasicMaterial as V,MeshPhongMaterial as H}from"three";function B(r){return r&&typeof r.getDebugInfo=="function"}var m=class{entity;constructor(t){this.entity=t}getPositionString(){if(this.entity.mesh){let{x:s,y:n,z:o}=this.entity.mesh.position;return`${s.toFixed(2)}, ${n.toFixed(2)}, ${o.toFixed(2)}`}let{x:t,y:e,z:i}=this.entity.options.position||{x:0,y:0,z:0};return`${t.toFixed(2)}, ${e.toFixed(2)}, ${i.toFixed(2)}`}getRotationString(){if(this.entity.mesh){let{x:n,y:o,z:p}=this.entity.mesh.rotation,a=c=>(c*180/Math.PI).toFixed(1);return`${a(n)}\xB0, ${a(o)}\xB0, ${a(p)}\xB0`}let{x:t,y:e,z:i}=this.entity.options.rotation||{x:0,y:0,z:0},s=n=>(n*180/Math.PI).toFixed(1);return`${s(t)}\xB0, ${s(e)}\xB0, ${s(i)}\xB0`}getMaterialInfo(){if(!this.entity.mesh||!this.entity.mesh.material)return{type:"none"};let t=Array.isArray(this.entity.mesh.material)?this.entity.mesh.material[0]:this.entity.mesh.material,e={type:t.type};return(t instanceof k||t instanceof V||t instanceof H)&&(e.color=`#${t.color.getHexString()}`,e.opacity=t.opacity,e.transparent=t.transparent),"roughness"in t&&(e.roughness=t.roughness),"metalness"in t&&(e.metalness=t.metalness),e}getPhysicsInfo(){if(!this.entity.body)return null;let t={type:this.entity.body.bodyType(),mass:this.entity.body.mass(),isEnabled:this.entity.body.isEnabled(),isSleeping:this.entity.body.isSleeping()},e=this.entity.body.linvel();return t.velocity=`${e.x.toFixed(2)}, ${e.y.toFixed(2)}, ${e.z.toFixed(2)}`,t}buildDebugInfo(){let t={name:this.entity.name||this.entity.uuid,uuid:this.entity.uuid,position:this.getPositionString(),rotation:this.getRotationString(),material:this.getMaterialInfo()},e=this.getPhysicsInfo();if(e&&(t.physics=e),B(this.entity)){let i=this.entity.getDebugInfo();return{...t,...i}}return t}};var h={position:void 0,text:"",fontFamily:'Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',fontSize:18,fontColor:"#FFFFFF",backgroundColor:null,padding:4,stickToViewport:!0,screenPosition:new X(24,24),zDistance:1},b=class extends _{createEntity(t){return new l(t)}},N=Symbol("Text"),l=class r extends x{static type=N;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=f(h,t),this.options.screenPosition=C(this.options.screenPosition,h.screenPosition),this.prependSetup(this.textSetup.bind(this)),this.prependUpdate(this.textUpdate.bind(this)),this.onCleanup(this.textDestroy.bind(this))}create(){return this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._lastCanvasW=0,this._lastCanvasH=0,this.group=new W,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new R(this._canvas),this._texture.minFilter=S,this._texture.magFilter=S;let t=new Y({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new U(t),this.group?.add(this._sprite),this.redrawText(this.options.text??"")}measureAndResizeCanvas(t,e,i,s){if(!this._canvas||!this._ctx)return{sizeChanged:!1};this._ctx.font=`${e}px ${i}`;let n=this._ctx.measureText(t),o=Math.ceil(n.width),p=Math.ceil(e*1.4),a=Math.max(2,o+s*2),c=Math.max(2,p+s*2),v=a!==this._lastCanvasW||c!==this._lastCanvasH;return this._canvas.width=a,this._canvas.height=c,this._lastCanvasW=a,this._lastCanvasH=c,{sizeChanged:v}}drawCenteredText(t,e,i){!this._canvas||!this._ctx||(this._ctx.font=`${e}px ${i}`,this._ctx.textAlign="center",this._ctx.textBaseline="middle",this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this.options.backgroundColor&&(this._ctx.fillStyle=this.toCssColor(this.options.backgroundColor),this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height)),this._ctx.fillStyle=this.toCssColor(this.options.fontColor??"#FFFFFF"),this._ctx.fillText(t,this._canvas.width/2,this._canvas.height/2))}updateTexture(t){!this._texture||!this._canvas||(t&&(this._texture.dispose(),this._texture=new R(this._canvas),this._texture.minFilter=S,this._texture.magFilter=S,this._texture.wrapS=P,this._texture.wrapT=P),this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0))}redrawText(t){if(!this._canvas||!this._ctx)return;let e=this.options.fontSize??18,i=this.options.fontFamily??h.fontFamily,s=this.options.padding??4,{sizeChanged:n}=this.measureAndResizeCanvas(t,e,i,s);this.drawCenteredText(t,e,i),this.updateTexture(!!n),this.options.stickToViewport&&this._cameraRef?this.updateStickyTransform():this.updateWorldSpriteScale()}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof M?t:new M(t)).getHexString()}`}textSetup(t){this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}textUpdate(t){this._sprite&&this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}getResolution(){return{width:this._cameraRef?.screenResolution.x??1,height:this._cameraRef?.screenResolution.y??1}}getScreenPixels(t,e,i){let s=t.x>=0&&t.x<=1,n=t.y>=0&&t.y<=1;return{px:s?t.x*e:t.x,py:n?t.y*i:t.y}}computeWorldExtents(t,e){let i=1,s=1;if(t.isPerspectiveCamera){let n=t,o=Math.tan(n.fov*Math.PI/180/2)*e;i=o*n.aspect,s=o}else if(t.isOrthographicCamera){let n=t;i=(n.right-n.left)/2,s=(n.top-n.bottom)/2}return{worldHalfW:i,worldHalfH:s}}updateSpriteScale(t,e){if(!this._canvas||!this._sprite)return;let s=t*2/e,n=this._canvas.height,o=Math.max(1e-4,n*s),p=this._canvas.width/this._canvas.height,a=o*p;this._sprite.scale.set(a,o,1)}updateWorldSpriteScale(){if(!this._canvas||!this._sprite)return;let t=this._canvas.width/Math.max(1,this._canvas.height),e=Math.max(1,this.options.fontSize??18),i=Math.max(.25,e/32),s=i*t;this._sprite.scale.set(s,i,1)}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:i}=this.getResolution(),s=C(this.options.screenPosition,h.screenPosition),{px:n,py:o}=this.getScreenPixels(s,e,i),p=Math.max(.001,this.options.zDistance??1),{worldHalfW:a,worldHalfH:c}=this.computeWorldExtents(t,p),v=n/e*2-1,D=1-o/i*2,G=v*a,$=D*c;this.group?.position.set(G,$,-p),this.updateSpriteScale(c,i)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new m(this).buildDebugInfo(),type:String(r.type),text:this.options.text??"",sticky:this.options.stickToViewport}}textDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null}};function E(...r){return g({args:r,defaultConfig:{...h},EntityClass:l,BuilderClass:b,entityType:l.type,cloneFactory:t=>E(t??{})})}import{ColliderDesc as L}from"@dimforge/rapier3d-compat";import{Euler as Q,Group as q,Quaternion as j,Vector3 as J}from"three";import{TextureLoader as K,SpriteMaterial as tt,Sprite as et,SRGBColorSpace as it}from"three";var A={...F,size:new J(1,1,1),images:[],animations:[]},T=class extends z{collider(t){let e=d(t.collisionSize,t.size??y),i={x:e.x/2,y:e.y/2,z:e.z/2};return L.cuboid(i.x,i.y,i.z)}},w=class extends _{createEntity(t){return new u(t)}},nt=Symbol("Sprite"),u=class r extends x{static type=nt;sprites=[];spriteMap=new Map;currentSpriteIndex=0;animations=new Map;currentAnimation=null;currentAnimationFrame="";currentAnimationIndex=0;currentAnimationTime=0;constructor(t){super(),this.options=f(A,t),this.prependSetup(this.spriteSetup.bind(this)),this.prependUpdate(this.spriteUpdate.bind(this)),this.onCleanup(this.spriteDestroy.bind(this))}create(){return this.sprites=[],this.spriteMap.clear(),this.animations.clear(),this.currentAnimation=null,this.currentAnimationFrame="",this.currentAnimationIndex=0,this.currentAnimationTime=0,this.group=void 0,this.createSpritesFromImages(this.options?.images||[]),this.createAnimations(this.options?.animations||[]),super.create()}createSpritesFromImages(t){let e=new K,i=d(this.options.size,y);t.forEach((s,n)=>{let o=e.load(s.file);o.colorSpace=it,o.anisotropy=I;let p=new tt({map:o,transparent:!0}),a=new et(p);a.position.normalize(),a.scale.set(i.x,i.y,i.z),a.visible=n===0,this.sprites.push(a),this.spriteMap.set(s.name,n)}),this.group=new q,this.group.add(...this.sprites)}createAnimations(t){t.forEach(e=>{let{name:i,frames:s,loop:n=!1,speed:o=1}=e,p={frames:s.map((a,c)=>({key:a,index:c,time:(typeof o=="number"?o:o[c])*(c+1),duration:typeof o=="number"?o:o[c]})),loop:n};this.animations.set(i,p)})}setSprite(t){let i=this.spriteMap.get(t)??0;this.currentSpriteIndex=i,this.sprites.forEach((s,n)=>{s.visible=this.currentSpriteIndex===n})}setAnimation(t,e){let i=this.animations.get(t);if(!i)return;let{loop:s,frames:n}=i,o=n[this.currentAnimationIndex];t===this.currentAnimation?(this.currentAnimationFrame=o.key,this.currentAnimationTime+=e,this.setSprite(this.currentAnimationFrame)):this.currentAnimation=t,this.currentAnimationTime>o.time&&this.currentAnimationIndex++,this.currentAnimationIndex>=n.length&&(s?(this.currentAnimationIndex=0,this.currentAnimationTime=0):this.currentAnimationTime=n[this.currentAnimationIndex].time)}getCurrentRotationQuaternion(){return this.transformStore?.dirty.rotation?this.transformStore.rotation:this.body?.rotation?.()??null}syncSpriteMaterials(){let t=this.getCurrentRotationQuaternion();this.sprites.forEach(e=>{if(e.material&&t){let s=new j(t.x,t.y,t.z,t.w),n=new Q().setFromQuaternion(s,"XYZ");e.material.rotation=n.z}let i=d(this.options.size,y);e.scale.set(i.x,i.y,i.z)})}spriteSetup(t){this.syncSpriteMaterials()}spriteUpdate(t){this.syncSpriteMaterials()}spriteDestroy(t){this.sprites.forEach(e=>{e.removeFromParent()}),this.group?.remove(...this.sprites),this.group?.removeFromParent()}buildInfo(){return{...new m(this).buildDebugInfo(),type:String(r.type)}}};function O(...r){return g({args:r,defaultConfig:A,EntityClass:u,BuilderClass:w,CollisionBuilderClass:T,entityType:u.type,cloneFactory:t=>O(t??{})})}var Z={registry:new Map,register(r,t){this.registry.set(r,t)},createFromBlueprint(r){let t=this.registry.get(r.type);if(!t)throw new Error(`Unknown entity type: ${r.type}`);let e={...r.data,position:r.position?{x:r.position[0],y:r.position[1],z:0}:void 0,name:r.id};return t(e)}};Z.register("text",r=>E(r));Z.register("sprite",r=>O(r));function Dt(r){return{template:r,generate(t){let e=[];for(let i=0;i<t;i++)e.push(r.clone());return e}}}export{m as a,N as b,l as c,E as d,nt as e,u as f,O as g,Z as h,Dt as i};
@@ -1 +0,0 @@
1
- import{b as L,d as be,e as P,h as ge}from"./chunk-DR6XXZE7.js";import{a as ae,b as le}from"./chunk-YHEWKN7N.js";import{a as me,b as fe,c as ye}from"./chunk-73VZQZUL.js";import{c as E,d as T,e as ce,f as $,g as ue,h,i as pe,j as z,k as de}from"./chunk-G2IIMSUH.js";import{p as he}from"./chunk-XRP4JJXL.js";import{ActiveCollisionTypes as Oe,ColliderDesc as A,RigidBodyDesc as Xe,RigidBodyType as xe}from"@dimforge/rapier3d-compat";import{Vector3 as We}from"three";import{Color as Ye,Vector2 as Ce,Vector3 as ve}from"three";import{Vector3 as q}from"@dimforge/rapier3d-compat";function B(o){if(!o||typeof o!="object")return!1;let e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function u(o){if(o==null||typeof o=="function"||typeof o!="object")return o;if(o instanceof Ye||o instanceof Ce||o instanceof ve)return o.clone();if(o instanceof q)return new q(o.x,o.y,o.z);if(o instanceof Float32Array)return new Float32Array(o);if(Array.isArray(o))return o.map(e=>u(e));if(B(o)){let e={};for(let[t,i]of Object.entries(o))t!=="_builders"&&(e[t]=u(i));return e}return o}function g(o,e){let t=u(o);if(!e)return t;if(!B(t)||!B(e))return u(e);let i=t;for(let[n,s]of Object.entries(e)){if(n==="_builders"||s===void 0)continue;let r=i[n];if(n==="shader"){i[n]=u(s);continue}if(r instanceof Ce&&ce(s)){i[n]=pe(s,r);continue}if(r instanceof ve&&$(s)){i[n]=z(s,r);continue}if(r instanceof q&&$(s)){i[n]=de(s,r);continue}if(B(r)&&B(s)){i[n]=g(r,s);continue}i[n]=u(s)}return i}function Ee(o){return o&&o.__kind==="collision"}function J(o){return o.cloneComponent()}function $e(o){let e=o?xe.Fixed:xe.Dynamic;return new Xe(e).setTranslation(0,0,0).setGravityScale(1).setCanSleep(!1).setCcdEnabled(!0)}function qe(o,e){if(e.offset){let t=h(e.offset,E);o.setTranslation(t.x,t.y,t.z)}if(e.sensor&&(o.setSensor(!0),o.activeCollisionTypes=Oe.KINEMATIC_FIXED),e.collisionType){let t=me(e.collisionType),i=65535;e.collisionFilter&&(i=fe(e.collisionFilter)),o.setCollisionGroups(t<<16|i)}}function S(o,e,t){return qe(o,e),{__kind:"collision",bodyDesc:$e(e.static??!1),colliderDesc:o,cloneComponent:t}}function Je(o={}){let e=h(o.size,T),t=A.cuboid(e.x/2,e.y/2,e.z/2),i=u(o);return S(t,o,()=>Je(i))}function Qe(o={}){let e=A.ball(o.radius??1),t=u(o);return S(e,o,()=>Qe(t))}function et(o={}){let e=o.radius??1,t=o.height??2,i=A.cone(t/2,e),n=u(o);return S(i,o,()=>et(n))}function tt(o={}){let e=o.radius??1,t=o.height??2,i=A.cone(t/2,e),n=u(o);return S(i,o,()=>tt(n))}function it(o={}){let e=Math.max(o.radiusTop??1,o.radiusBottom??1),t=o.height??2,i=A.cylinder(t/2,e),n=u(o);return S(i,o,()=>it(n))}function ot(o={}){let e=o.radius??.5,t=o.length??1,i=A.capsule(t/2,e),n=u(o);return S(i,o,()=>ot(n))}function nt(o={}){let e=ue(o.tile,{x:10,y:10}),t=o.subdivisions??10,i=new We(e.x,1,e.y),n=(t+1)*(t+1),s=o.heightData??new Float32Array(n),r=A.heightfield(t,t,s,i),a={...o,static:o.static??!0},l=u(a);return S(r,a,()=>nt(l))}function st(o={}){let e=h(o.size,T),t=A.cuboid(e.x/2,e.y/2,e.z/2);t.setSensor(!0),t.activeCollisionTypes=Oe.KINEMATIC_FIXED;let i={...o,static:o.static??!0,sensor:!0},n=u(i);return S(t,i,()=>st(n))}import{Mesh as Se,ShaderMaterial as pt,Group as dt}from"three";var _e=import.meta.env.VITE_DEBUG_FLAG==="true";import{nanoid as rt}from"nanoid";var v=class o{parent=null;children=[];options;uuid="";name="";markedForRemoval=!1;lifecycleCallbacks={setup:[],loaded:[],update:[],destroy:[],cleanup:[]};trackLifecycleRegistrations=!1;userLifecycleRegistrations=[];constructor(e=[]){let t=e.filter(i=>!(i instanceof o)).reduce((i,n)=>({...i,...n}),{});this.options=t,this.uuid=rt()}onSetup(...e){return this.lifecycleCallbacks.setup.push(...e),this.recordLifecycleRegistration("onSetup",e),this}onLoaded(...e){return this.lifecycleCallbacks.loaded.push(...e),this.recordLifecycleRegistration("onLoaded",e),this}onUpdate(...e){return this.lifecycleCallbacks.update.push(...e),this.recordLifecycleRegistration("onUpdate",e),this}onDestroy(...e){return this.lifecycleCallbacks.destroy.push(...e),this.recordLifecycleRegistration("onDestroy",e),this}onCleanup(...e){return this.lifecycleCallbacks.cleanup.push(...e),this.recordLifecycleRegistration("onCleanup",e),this}prependSetup(...e){return this.lifecycleCallbacks.setup.unshift(...e),this.recordLifecycleRegistration("prependSetup",e),this}prependUpdate(...e){return this.lifecycleCallbacks.update.unshift(...e),this.recordLifecycleRegistration("prependUpdate",e),this}setParent(e){this.parent=e}getParent(){return this.parent}add(e){this.children.push(e),e.setParent(this)}remove(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),e.setParent(null))}getChildren(){return this.children}isComposite(){return this.children.length>0}enableUserLifecycleTracking(){this.trackLifecycleRegistrations=!0}replayUserLifecycleRegistrationsTo(e,t){for(let i of this.userLifecycleRegistrations){let n=t?i.callbacks.map(s=>t(s)):[...i.callbacks];switch(i.method){case"onSetup":e.onSetup(...n);break;case"onLoaded":e.onLoaded(...n);break;case"onUpdate":e.onUpdate(...n);break;case"onDestroy":e.onDestroy(...n);break;case"onCleanup":e.onCleanup(...n);break;case"prependSetup":e.prependSetup(...n);break;case"prependUpdate":e.prependUpdate(...n);break}}}cloneChildrenInto(e){for(let t of this.children)e.add(at(t))}nodeSetup(e){this.markedForRemoval=!1,typeof this._setup=="function"&&this._setup(e);for(let t of this.lifecycleCallbacks.setup)t(e);this.children.forEach(t=>t.nodeSetup(e))}nodeUpdate(e){if(!this.markedForRemoval){typeof this._update=="function"&&this._update(e),typeof this._tickActions=="function"&&this._tickActions(e.delta);for(let t of this.lifecycleCallbacks.update)t(e);this.children.forEach(t=>t.nodeUpdate(e))}}nodeDestroy(e){if(!this.markedForRemoval){this.children.forEach(t=>t.nodeDestroy(e));for(let t of this.lifecycleCallbacks.destroy)t(e);typeof this._destroy=="function"&&this._destroy(e),this.markedForRemoval=!0;for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}}async nodeLoaded(e){typeof this._loaded=="function"&&await this._loaded(e);for(let t of this.lifecycleCallbacks.loaded)t(e)}nodeCleanup(e){this.children.forEach(t=>t.nodeCleanup?.(e));for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}getOptions(){return this.options}setOptions(e){this.options={...this.options,...e}}recordLifecycleRegistration(e,t){!this.trackLifecycleRegistrations||t.length===0||this.userLifecycleRegistrations.push({method:e,callbacks:[...t]})}};function at(o){let e=o?.clone;if(typeof e!="function")throw new Error(`Cannot clone child node "${o.name||o.uuid||"unknown"}": missing clone() support.`);return e.call(o)}import{createTransformStore as ht}from"@zylem/behaviors/core";import{makeMoveable as lt}from"@zylem/behaviors/core";function Ae(o){let e=lt(o);return he(e)}import{clearVelocityIntent as De}from"@zylem/behaviors/core";import{Color as ct,Vector3 as ut}from"three";var V={position:new ut(0,0,0),material:{color:new ct("#ffffff"),shader:L},collision:{static:!1}};function ki(o,e){let t=o.filter(n=>!(n instanceof v)),i=g(e);for(let n of t)i=g(i,n);return i}function mt(o){return o!=null&&typeof o=="object"}function Me(o){return{phase:o?.phase??"stay",cooldownMs:o?.cooldownMs}}function ft(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var M=class extends v{group;mesh;materials;bodyDesc=null;body=null;physicsAttached=!1;colliderDesc;collider;custom={};colliderDescs=[];colliders=[];compoundMeshes=[];debugInfo={};debugMaterial;collisionDelegate={collision:[],cooldowns:new Map,nextId:0};collisionType;batchKey=null;instanceId=-1;isInstanced=!1;runtimeSlot=-1;runtimeHandle=-1;runtimeAttached=!1;wasmStageRef=null;eventDelegate=new ae;behaviorRefs=[];cloneFactory=null;trackAddedComponents=!1;trackedComponents=[];transformStore;moveX;moveY;moveZ;moveXY;moveXZ;move;resetVelocity;moveForwardXY;getPosition;getVelocity;setPosition;setPositionX;setPositionY;setPositionZ;wrapAroundXY;wrapAround3D;rotateInDirection;rotateYEuler;rotateEuler;rotateX;rotateY;rotateZ;setRotationY;setRotationX;setRotationZ;setRotationDegrees;setRotationDegreesY;setRotationDegreesX;setRotationDegreesZ;setRotation;getRotation;constructor(){super(),this.transformStore=ht(),Ae(this)}getPose(){if(this.wasmStageRef&&this.runtimeHandle>=0){let n=this.wasmStageRef.getPose(this.runtimeHandle);if(n)return{position:{x:n.position[0],y:n.position[1],z:n.position[2]},rotation:{x:n.rotation[0],y:n.rotation[1],z:n.rotation[2],w:n.rotation[3]}}}let e=this.body;if(!e)return null;let t=e.translation(),i=e.rotation();return{position:{x:t.x,y:t.y,z:t.z},rotation:{x:i.x,y:i.y,z:i.z,w:i.w}}}setPose(e){if(this.wasmStageRef&&this.runtimeHandle>=0){let i=!0;if(e.position){let n=h(e.position);i=this.wasmStageRef.setPosition(this.runtimeHandle,n.x,n.y,n.z)&&i}if(e.rotation){let{x:n,y:s,z:r,w:a}=e.rotation;i=this.wasmStageRef.setRotation(this.runtimeHandle,n,s,r,a)&&i}return i}let t=this.body;if(!t)return!1;if(e.position){let i=h(e.position);t.setTranslation({x:i.x,y:i.y,z:i.z},!0)}return e.rotation&&t.setRotation(e.rotation,!0),!0}add(...e){for(let t of e)t instanceof Se?(this.addMeshComponent(t),this.trackComponent(t)):Ee(t)?(this.addCollisionComponent(t),this.trackComponent(t)):super.add(t);return this}addMeshComponent(e){if(this.mesh)this.compoundMeshes.push(e),this.group||(this.group=new dt,this.group.add(this.mesh)),this.group.add(e);else if(this.mesh=e,this.materials||(this.materials=[]),e.material){let t=e.material;Array.isArray(t)?this.materials.push(...t):this.materials.push(t)}}addCollisionComponent(e){if(this.bodyDesc)this.colliderDescs.push(e.colliderDesc);else{this.bodyDesc=e.bodyDesc,this.colliderDesc=e.colliderDesc,this.colliderDescs.push(e.colliderDesc);let t=h(this.options?.position,E);this.bodyDesc.setTranslation(t.x,t.y,t.z)}}trackComponent(e){if(this.trackAddedComponents){if(e instanceof Se){this.trackedComponents.push({kind:"mesh",component:Fe(e)});return}this.trackedComponents.push({kind:"collision",component:J(e)})}}_actions=[];runAction(e){return this._actions.push(e),e}action(e){return e.persistent=!0,this._actions.push(e),e}clearActions(){this._actions.length=0}_tickActions(e){if(this._actions.length===0)return;let t=this.transformStore;t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,De(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1;for(let i=this._actions.length-1;i>=0;i--){let n=this._actions[i];n.tick(this,e),n.done&&!n.persistent&&this._actions.splice(i,1)}this._actions.length===0&&(t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,De(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1)}create(){return this.name=this.options.name||"",this}clone(e){if(!this.cloneFactory)throw new Error(`Cannot clone ${this.constructor.name}: clone() is only supported for entities created by official factory helpers.`);let t=this.cloneFactory(g(this.options,e)),i=this.copyBehaviorRefsTo(t),n=r=>bt(r,i);this.replayUserLifecycleRegistrationsTo(t,n);let s=this.getCollisionRegistrations();if(s.length>0)for(let r of s)t.onCollision(n(r.callback),r.options);for(let r of this.trackedComponents){if(r.kind==="mesh"){t.add(Fe(r.component));continue}t.add(J(r.component))}return this.cloneChildrenInto(t),t}finalizeCloneSupport(e){return this.cloneFactory=e,this.enableUserLifecycleTracking(),this.trackAddedComponents=!0,this}onCollision(...e){let t=[...this.collisionDelegate.collision??[]],i=this.collisionDelegate.nextId??0;if(e.length===1||e.length===2&&(e[1]==null||mt(e[1]))){let n=e[0];if(!n)return this;let s=e[1];return t.push({id:i,callback:n,options:Me(s)}),i+=1,this.collisionDelegate.collision=t,this.collisionDelegate.nextId=i,this}for(let n of e)t.push({id:i,callback:n,options:Me()}),i+=1;return this.collisionDelegate.collision=t,this.collisionDelegate.nextId=i,this}use(e,t){let i={descriptor:e,options:{...e.defaultOptions,...t}};this.behaviorRefs.push(i);let n={getFSM:()=>i.fsm??null,getOptions:()=>i.options,ref:i},s=e.createHandle?.(i)??{};return{...n,...s}}getBehaviorRefs(){return this.behaviorRefs}getCollisionCallbacks(){return this.getCollisionRegistrations().map(e=>e.callback)}getCollisionRegistrations(){return(this.collisionDelegate.collision??[]).map(e=>({id:e.id,callback:e.callback,options:{...e.options}}))}copyBehaviorRefsTo(e){let t=new Map;for(let i of this.behaviorRefs){e.use(i.descriptor,u(i.options));let n=e.getBehaviorRefs().at(-1);n&&t.set(i,n)}return t}_setup(e){for(let t=this._actions.length-1;t>=0;t--){let i=this._actions[t];i.done&&!i.persistent?this._actions.splice(t,1):i.reset()}}async _loaded(e){}_update(e){this.updateMaterials(e)}_destroy(e){}_cleanup(e){this.disposeEvents();for(let t of this.compoundMeshes)t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(i=>i.dispose()):t.material?.dispose();this.compoundMeshes.length=0,this.debugMaterial?.dispose(),this.debugMaterial=void 0,this.group?.removeFromParent()}_collision(e,t,i={phase:"stay",nowMs:ft()}){if(!this.collisionDelegate.collision?.length)return;let n=this.collisionDelegate.cooldowns??new Map;this.collisionDelegate.cooldowns=n;for(let s of this.collisionDelegate.collision){if(s.options.phase!==i.phase)continue;let r=s.options.cooldownMs;if(r!=null){let a=`${s.id}:${e.uuid}`,l=n.get(a);if(l!=null&&i.nowMs-l<r)continue;n.set(a,i.nowMs)}s.callback({entity:this,other:e,globals:t})}}updateMaterials(e){if(this.materials?.length)for(let t of this.materials)t instanceof pt&&t.uniforms&&t.uniforms.iTime&&(t.uniforms.iTime.value+=e.delta)}buildInfo(){let e={};return e.name=this.name,e.uuid=this.uuid,e}dispatch(e,t){this.eventDelegate.dispatch(e,t),le.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}disposeEvents(){this.eventDelegate.dispose()}};function yt(o){let e=new M;return e.options={...V,...o},Q(e,t=>yt(t??{}))}function Fe(o){let e=o.clone(!0),t=[],i=[];o.traverse(n=>t.push(n)),e.traverse(n=>i.push(n));for(let n=0;n<t.length;n++){let s=t[n],r=i[n];s?.geometry?.clone&&(r.geometry=s.geometry.clone()),s?.material&&(r.material=Array.isArray(s.material)?s.material.map(a=>a.clone()):s.material.clone())}return e}function bt(o,e){return e.size===0?o:((...t)=>{let i=Array.from(e.entries()).map(([n,s])=>({sourceRef:n,options:n.options,fsm:n.fsm,hasFSM:Object.prototype.hasOwnProperty.call(n,"fsm"),targetRef:s}));for(let n of i)n.sourceRef.options=n.targetRef.options,n.targetRef.fsm===void 0?delete n.sourceRef.fsm:n.sourceRef.fsm=n.targetRef.fsm;try{return o(...t)}finally{for(let n=i.length-1;n>=0;n--){let s=i[n];s.sourceRef.options=s.options,s.hasFSM?s.sourceRef.fsm=s.fsm:delete s.sourceRef.fsm}}})}function Q(o,e){return o.finalizeCloneSupport(e),o}function Te(o){return typeof o?.load=="function"&&typeof o?.data=="function"}var G=class{entityReference;constructor(e){this.entityReference=e}load(){this.entityReference.load&&this.entityReference.load()}data(){return this.entityReference.data?this.entityReference.data():null}};function Re(o){let{args:e,defaultConfig:t,EntityClass:i,BuilderClass:n,entityType:s,MeshBuilderClass:r,CollisionBuilderClass:a,cloneFactory:l}=o,d=null,m,f=e.findIndex(p=>!(p instanceof v));f!==-1&&(m=e.splice(f,1).find(C=>!(C instanceof v)));let y=m?g(t,m):g(t);e.push(y);for(let p of e){if(p instanceof v)continue;let C=null,O=new i(p);try{if(Te(O)){let c=new G(O);c.load(),C=c.data()}}catch(c){console.error("Error creating entity with loader:",c)}d=new n(p,O,r?new r(C):null,a?new a(C):null),p.material&&d.withMaterial(p.material,s)}if(!d)throw new Error(`missing options for ${String(s)}, builder is not initialized.`);return Q(d.build(),p=>l(p))}import{ActiveCollisionTypes as Y,ColliderDesc as X}from"@dimforge/rapier3d-compat";import{Box3 as je,BufferAttribute as Dt,SkinnedMesh as Mt,MeshStandardMaterial as Ft,Group as Tt,Vector3 as K,Matrix4 as Rt}from"three";var R=class{async loadFile(e,t){switch(be(e)){case"fbx":{let n=await P.loadFBX(e,t);return{object:n.object,animation:n.animations?.[0]}}case"gltf":case"glb":{let n=await P.loadGLTF(e,t);return{object:n.object,gltf:n.gltf}}case"obj":return{object:(await P.loadOBJ(e,t)).object};default:throw new Error(`Unsupported file type: ${e}`)}}};import{AnimationMixer as gt,Bone as Be,LoopOnce as Ct,LoopRepeat as vt}from"three";function xt(o){let e=o.lastIndexOf(".");return e>=0?o.slice(0,e):o}function Ot(o,e){if(!o?.name?.endsWith(".position"))return!1;let t=xt(o.name),i=e.get(t);return i instanceof Be?!(i.parent instanceof Be):/hips\.position$/i.test(o.name)||/root\.position$/i.test(o.name)}function Et(o,e,t){for(let i of o.tracks){if(!Ot(i,e)||!i.values||i.values.length<3)continue;let n=i.values[0],s=i.values[1],r=i.values[2];for(let a=0;a<i.values.length;a+=3)i.values[a]=n,t&&(i.values[a+1]=s),i.values[a+2]=r}return o}var I=class{constructor(e){this.target=e}_mixer=null;_actions={};_animations=[];_currentAction=null;_pauseAtPercentage=0;_isPaused=!1;_queuedKey=null;_fadeDuration=.5;_currentKey="";_assetLoader=new R;async loadAnimations(e,t={}){if(!e.length)return;let i=t.stripRootMotionY??!1,n=await Promise.all(e.map(a=>this._assetLoader.loadFile(a.path))),s=new Map;this.target.traverse(a=>{a.name&&s.set(a.name,a)});let r=[];n.forEach((a,l)=>{a.animation&&r.push({key:e[l].key||l.toString(),clip:Et(a.animation,s,i)})}),r.length&&(this._animations=r.map(a=>a.clip),this._mixer=new gt(this.target),r.forEach(({key:a,clip:l})=>{this._actions[a]=this._mixer.clipAction(l)}),this.playAnimation({key:r[0].key}))}update(e){if(!this._mixer||!this._currentAction)return;this._mixer.update(e);let t=this._currentAction.getClip().duration*(this._pauseAtPercentage/100);if(!this._isPaused&&this._pauseAtPercentage>0&&this._currentAction.time>=t&&(this._currentAction.time=t,this._currentAction.paused=!0,this._isPaused=!0,this._queuedKey!==null)){let i=this._actions[this._queuedKey];i.reset().play(),this._currentAction.crossFadeTo(i,this._fadeDuration,!1),this._currentAction=i,this._currentKey=this._queuedKey,this._queuedKey=null}}playAnimation(e){if(!this._mixer)return;let{key:t,pauseAtPercentage:i=0,pauseAtEnd:n=!1,fadeToKey:s,fadeDuration:r=.5}=e;if(t===this._currentKey)return;let a=this._actions[t];if(!a)return;if(a===this._currentAction){this._currentKey=t;return}this._queuedKey=s||null,this._fadeDuration=r,this._pauseAtPercentage=n?100:i,this._isPaused=!1;let l=this._currentAction;this._pauseAtPercentage>0?(a.setLoop(Ct,1/0),a.clampWhenFinished=!0):(a.setLoop(vt,1/0),a.clampWhenFinished=!1),a.reset().play(),l&&l.crossFadeTo(a,r,!1),this._currentAction=a,this._currentKey=t}dispose(){Object.values(this._actions).forEach(e=>{e.stop()}),this._mixer&&(this._mixer.stopAllAction(),this._mixer.uncacheRoot(this.target),this._mixer=null),this._actions={},this._animations=[],this._currentAction=null,this._currentKey=""}get currentAnimationKey(){return this._currentKey}get animations(){return this._animations}};import{BufferGeometry as At,Mesh as we,Color as St}from"three";import{Mesh as _t}from"three";var U=class{_build(e,t,i){let{batched:n,material:s}=e;n&&console.warn("warning: mesh batching is not implemented");let r=new _t(t,i.at(-1));return r.position.set(0,0,0),r.castShadow=!0,r.receiveShadow=!0,r}_postBuild(){}};var N=class extends ye{},ke=class extends U{build(e){return new At}postBuild(){}},Z=class{meshBuilder;collisionBuilder;materialBuilder;options;entity;constructor(e,t,i,n){this.options=e,this.entity=t,this.meshBuilder=i,this.collisionBuilder=n,this.materialBuilder=new ge;let s={meshBuilder:this.meshBuilder,collisionBuilder:this.collisionBuilder,materialBuilder:this.materialBuilder};this.options._builders=s,t&&t.options&&(t.options._builders=s)}withPosition(e){return this.options.position=e,this}withMaterial(e,t){return this.materialBuilder&&this.materialBuilder.build(e,t),this}applyMaterialToGroup(e,t){e.traverse(i=>{i instanceof we&&i.type==="SkinnedMesh"&&t[0]&&!i.material.map&&(i.material=t[0]),i.castShadow=!0,i.receiveShadow=!0})}build(){let e=this.entity;if(this.materialBuilder&&(e.materials=this.materialBuilder.materials),this.meshBuilder&&e.materials){let t=this.meshBuilder.build(this.options);e.mesh=this.meshBuilder._build(this.options,t,e.materials),this.meshBuilder.postBuild()}if(e.group&&e.materials&&this.applyMaterialToGroup(e.group,e.materials),this.collisionBuilder){this.collisionBuilder.withCollision(this.options?.collision||{});let[t,i]=this.collisionBuilder.build(this.options);e.bodyDesc=t,e.colliderDesc=i,e.colliderDescs.push(i);let{x:n,y:s,z:r}=h(this.options.position,E);e.bodyDesc.setTranslation(n,s,r)}if(this.options.collisionType&&(e.collisionType=this.options.collisionType),this.options.color instanceof St){let t=i=>{let n=i;n&&n.color&&n.color.set&&n.color.set(this.options.color)};if(e.materials?.length)for(let i of e.materials)t(i);if(e.mesh&&e.mesh.material){let i=e.mesh.material;Array.isArray(i)?i.forEach(t):t(i)}e.group&&e.group.traverse(i=>{if(i instanceof we&&i.material){let n=i.material;Array.isArray(n)?n.forEach(t):t(n)}})}return e}};var ze={...V,material:{shader:L},animations:[],models:[],collisionShape:"capsule"};function w(o){return z(o.scale,T)}function j(o){let e=o.collision?.position;return e?h(e,E):null}function ee(o){return!!o.collision?.size}function Bt(o){o.hasWarnedDynamicTrimesh||(o.hasWarnedDynamicTrimesh=!0,console.warn(`Actor "${o.name||o.uuid}" requested collisionShape="trimesh" on a dynamic body; falling back to bounds.`))}function Le(o,e,t){let i=o==="model"?"bounds":o??"capsule";return i==="trimesh"&&!e?(t?.(),"bounds"):i}function wt(o,e,t){return o.__zylemShapeData={shape:"trimesh",vertices:Array.from(e),indices:Array.from(t)},o}function Pe(o,e){let t=o.x||.5,i=o.y||1,n=o.z||.5,s=Math.max(t,n)/2,r=i/2,a=Math.max(0,r-s),l=X.capsule(a,s);return l.setSensor(!1),l.setTranslation(e.x,e.y,e.z),l.activeCollisionTypes=Y.DEFAULT,l}function F(o){let e=h(o.collision?.size??o.size,{x:.5,y:1,z:.5}),t=e.y||1,i=j(o);return Pe({x:e.x||.5,y:t,z:e.z||.5},i??{x:0,y:t/2,z:0})}function Ve(o){let e=o.collision?.size;if(!e)return null;let t=h(e,E),i=t.x/2,n=t.y/2,s=t.z/2,r=X.cuboid(i,n,s),a=j(o);return r.setSensor(!1),r.setTranslation(a?.x??0,a?.y??n,a?.z??0),r.activeCollisionTypes=Y.DEFAULT,r}function Ge(o,e,t){let n=e.matrixWorld.clone().invert().multiply(o.matrixWorld);return new Rt().makeScale(t.x,t.y,t.z).multiply(n)}function te(o,e,t){o.updateMatrixWorld(!0);let i=!1,n=new je;if(o.traverse(a=>{if(!a.isMesh)return;let l=a,d=l.geometry;if(!d)return;let m=null;if(l instanceof Mt?(l.computeBoundingBox(),m=l.boundingBox?.clone()??null):(d.computeBoundingBox(),m=d.boundingBox?.clone()??null),!m)return;let f=m.applyMatrix4(Ge(l,e,t));if(!i){n.copy(f),i=!0;return}n.union(f)}),!i||n.isEmpty())return null;let s=new K,r=new K;return n.getSize(s),n.getCenter(r),{size:s,center:r}}function kt(o,e,t){o.updateMatrixWorld(!0);let i=[],n=[],s=new je,r=new K,a=!1;if(o.traverse(d=>{if(!d.isMesh)return;let m=d,f=m.geometry;if(!f)return;let y=f.getAttribute("position");if(!(y instanceof Dt))return;let p=Ge(m,e,t),C=i.length/3;for(let c=0;c<y.count;c++)r.set(y.getX(c),y.getY(c),y.getZ(c)),r.applyMatrix4(p),i.push(r.x,r.y,r.z),s.expandByPoint(r);let O=f.getIndex();if(O)for(let c=0;c<O.count;c++)n.push(C+O.getX(c));else for(let c=0;c<y.count;c++)n.push(C+c);a=!0}),!a||i.length===0||n.length===0)return null;let l=new K;return s.getCenter(l),{vertices:new Float32Array(i),indices:new Uint32Array(n),center:l}}function Ie(o,e,t){let i=Ve(t);if(i)return i;if(!o||!e)return F(t);let n=te(o,e,w(t));if(!n)return F(t);let s=X.cuboid(n.size.x/2,n.size.y/2,n.size.z/2),r=j(t);return s.setSensor(!1),s.setTranslation(r?.x??n.center.x,r?.y??n.center.y,r?.z??n.center.z),s.activeCollisionTypes=Y.DEFAULT,s}function Ue(o,e,t,i,n){if(ee(n)||!o||!e)return F(n);let s=te(o,e,w(n));if(!s)return F(n);let a=j(n);if(!a){let l=t&&i?te(t,i,w(n)):null;a=l?{x:l.center.x,y:l.center.y,z:l.center.z}:{x:s.center.x,y:s.center.y,z:s.center.z}}return Pe({x:s.size.x,y:s.size.y,z:s.size.z},a)}function Ne(o,e,t){let i=Ve(t);if(i)return i;if(!o||!e)return F(t);let n=kt(o,e,w(t));if(!n)return F(t);let s=wt(X.trimesh(n.vertices,n.indices),n.vertices,n.indices),r=j(t);return r&&s.setTranslation(r.x-n.center.x,r.y-n.center.y,r.z-n.center.z),s.setSensor(!1),s.activeCollisionTypes=Y.DEFAULT,s}function H(o){o&&o.traverse(e=>{if(!e.isMesh)return;let t=e;t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(i=>i.dispose()):t.material?.dispose()})}var ie=class extends N{objectModel=null;collisionSource=null;collisionShape="capsule";constructor(e){super(),this.objectModel=e.objectModel,this.collisionSource=e.collisionSource??e.objectModel??null,this.collisionShape=e.collisionShape??"capsule"}collider(e){let t=Le(this.collisionShape,!!e.collision?.static);return t==="bounds"?Ie(this.objectModel,this.objectModel,e):t==="trimesh"?Ne(this.objectModel,this.objectModel,e):Ue(this.collisionSource,this.collisionSource,this.objectModel,this.objectModel,e)}},oe=class extends Z{createEntity(e){return new k(e)}},jt=Symbol("Actor"),k=class extends M{static type=jt;_object=null;_collisionSource=null;_animationDelegate=null;_modelFileNames=[];_assetLoader=new R;_loadGeneration=0;_loadStatus="idle";controlledRotation=!1;hasWarnedDynamicTrimesh=!1;constructor(e){super(),this.options=g(ze,e),this.prependUpdate(this.actorUpdate.bind(this)),this.controlledRotation=!0}create(){return this._loadStatus==="idle"&&(this.options.models?.length??0)>0&&this.load(),super.create()}load(){this._loadStatus==="loading"||this._loadStatus==="loaded"||(this._modelFileNames=[...this.options.models||[]],this._modelFileNames.length!==0&&(this.disposeRuntimeState(!0),this._loadStatus="loading",this.loadModelsDeferred(++this._loadGeneration)))}data(){return{animations:this._animationDelegate?.animations,objectModel:this._object,collisionSource:this._collisionSource??this._object,collisionShape:this.options.collisionShape}}needsDeferredModelCollision(){return this.requiresLoadedCollisionSource()?!this.getRuntimeCollisionSource():!1}synchronizeRuntimeCollider(){let e=this.getResolvedCollisionShape(),t;if(e==="bounds")t=Ie(this._object,this.group??this._object,this.options);else if(e==="trimesh")t=Ne(this._object,this.group??this._object,this.options);else{let i=this.getRuntimeCollisionSource();t=Ue(i,i,this._object,this._object,this.options)}this.colliderDesc=t,this.colliderDescs.length>0?this.colliderDescs[0]=t:this.colliderDescs.push(t)}actorUpdate(e){this._animationDelegate?.update(e.delta)}actorDestroy(){this._loadGeneration+=1,this._loadStatus="idle",this.disposeRuntimeState(!0),this._modelFileNames=[]}_cleanup(e){super._cleanup(e),this.actorDestroy()}playAnimation(e){this._animationDelegate?.playAnimation(e)}get object(){return this._object}get collisionSource(){return this._collisionSource??this._object}getDebugInfo(){let e={type:"Actor",models:this._modelFileNames.length>0?this._modelFileNames:"none",modelLoaded:!!this._object,scale:(()=>{let t=h(this.options.scale,T);return`${t.x}, ${t.y}, ${t.z}`})(),collisionShape:this.getResolvedCollisionShape()};if(this._animationDelegate&&(e.currentAnimation=this._animationDelegate.currentAnimationKey||"none",e.animationsCount=this.options.animations?.length||0),this._object){let t=0,i=0;this._object.traverse(n=>{if(!n.isMesh)return;t++;let s=n.geometry;s?.attributes.position&&(i+=s.attributes.position.count)}),e.meshCount=t,e.vertexCount=i}return e}getResolvedCollisionShape(){return Le(this.options.collisionShape,!!this.options.collision?.static,()=>Bt(this))}requiresLoadedCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?!ee(this.options):e==="capsule"?!ee(this.options)&&this.getCollisionSourceSelection().file!==null:!1}getRuntimeCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?this._object:this._collisionSource??this._object}getCollisionSourceSelection(){let e=this.options.models?.[0]??null,t=this.options.animations?.[0]?.path??null;return t?{file:t,reuseVisibleModel:t===e}:{file:e,reuseVisibleModel:!0}}disposeRuntimeState(e){this._animationDelegate&&(this._animationDelegate.dispose(),this._animationDelegate=null);let t=this._collisionSource;H(this._object),t&&t!==this._object&&H(t),this._object=null,this._collisionSource=null,e&&this.group&&(this.group.clear(),this.group=void 0)}loadModelsDeferred(e){this.dispatch("entity:model:loading",{entityId:this.uuid,files:this._modelFileNames});let t=this.getCollisionSourceSelection(),i=this._modelFileNames.map(s=>this._assetLoader.loadFile(s,{clone:!0})),n=t.file&&!t.reuseVisibleModel?this._assetLoader.loadFile(t.file,{clone:!0}):Promise.resolve(null);Promise.all([Promise.all(i),n]).then(([s,r])=>{if(e!==this._loadGeneration){s.forEach(l=>H(l.object??null)),r?.object&&H(r.object);return}this._object=s[0]?.object??null,this._collisionSource=t.reuseVisibleModel?this._object:r?.object??this._object,this._loadStatus=this._object?"loaded":"idle";let a=0;this._object&&(this._object.traverse(l=>{l.isMesh&&a++}),this.group=new Tt,this.group.add(this._object),this.group.scale.copy(w(this.options)),this.applyMaterialOverrides(),this._animationDelegate=new I(this._object),this._animationDelegate.loadAnimations(this.options.animations||[],{stripRootMotionY:this.options.stripRootMotionY??!1}).then(()=>{e===this._loadGeneration&&this.dispatch("entity:animation:loaded",{entityId:this.uuid,animationCount:this.options.animations?.length||0})})),this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!!this._object,meshCount:a})}).catch(s=>{e===this._loadGeneration&&(this._loadStatus="idle",console.error("Failed to load actor model",s),this.dispatch("entity:model:loaded",{entityId:this.uuid,success:!1,meshCount:0,errorMessage:s instanceof Error?s.message:String(s)}))})}applyMaterialOverrides(){let e=this.options.material;!e||!e.color&&!e.path&&e.opacity===void 0||this._object&&this._object.traverse(t=>{if(!t.isMesh)return;let i=t;i.material=Array.isArray(i.material)?i.material.map(n=>this.tintMaterial(n,e)):this.tintMaterial(i.material,e),e.color&&(i.castShadow=!0,i.receiveShadow=!0)})}tintMaterial(e,t){let i="color"in e,n=!!t.color,s=t.opacity!==void 0;if(!n&&!s)return e;if(n&&!i)return new Ft({color:t.color,emissiveIntensity:.5,lightMapIntensity:.5,fog:!0,opacity:t.opacity??1,transparent:s&&t.opacity<1});let r=e.clone();if(n&&"color"in r&&r.color.copy(t.color),s&&"opacity"in r&&"transparent"in r){let a=r;a.opacity=t.opacity,a.transparent=t.opacity<1}return r.needsUpdate=!0,r}};function zt(...o){return Re({args:o,defaultConfig:ze,EntityClass:k,BuilderClass:oe,CollisionBuilderClass:ie,entityType:k.type,cloneFactory:e=>zt(e??{})})}import{Color as Kt,Fog as Yt,FogExp2 as Xt,Group as Wt}from"three";import{Color as Lt}from"three";import{Fn as He,fog as Pt,positionWorld as Ze,positionView as Vt,uniform as b,float as Gt,vec3 as x,clamp as ne,mix as _,max as It,smoothstep as Ut,floor as Nt,fract as se,dot as Zt}from"three/tsl";var W=class{values;u={time:b(0),heightEnabled:b(0),heightLevel:b(0),heightFalloff:b(0),noiseEnabled:b(0),noiseScale:b(0),noiseStrength:b(0),noiseSpeed:b(0)};attachedScene=null;constructor(e){this.values={...e},this.syncUniforms()}setValues(e){Object.assign(this.values,e),this.syncUniforms()}tick(e){this.values.time+=e,this.u.time.value=this.values.time}scan(e){if(this.attachedScene===e)return;let t=e.fog;t&&(e.fogNode=this.buildFogNode(t),this.attachedScene=e)}unpatchAll(){this.attachedScene&&(this.attachedScene.fogNode=null,this.attachedScene=null)}syncUniforms(){this.u.time.value=this.values.time,this.u.heightEnabled.value=this.values.heightEnabled,this.u.heightLevel.value=this.values.heightLevel,this.u.heightFalloff.value=this.values.heightFalloff,this.u.noiseEnabled.value=this.values.noiseEnabled,this.u.noiseScale.value=this.values.noiseScale,this.u.noiseStrength.value=this.values.noiseStrength,this.u.noiseSpeed.value=this.values.noiseSpeed}buildFogNode(e){let t=e.isFogExp2===!0,i=b(new Lt(e.color)),n=Vt.z.negate(),s=t?this.exp2Factor(b(e.density),n):Ut(b(e.near),b(e.far),n),r=this.u.heightLevel.sub(Ze.y),a=ne(r.mul(It(this.u.heightFalloff,0)),0,1),l=_(s,s.mul(a),this.u.heightEnabled),d=Ze.mul(this.u.noiseScale).add(x(this.u.time.mul(this.u.noiseSpeed),0,this.u.time.mul(this.u.noiseSpeed).mul(.5))),f=Ht(d).sub(.5).mul(2).mul(ne(this.u.noiseStrength,0,1)),y=ne(l.add(l.mul(f)),0,1),p=_(l,y,this.u.noiseEnabled);return Pt(i,p)}exp2Factor(e,t){return e.mul(e).mul(t).mul(t).negate().exp().oneMinus()}},D=He(([o])=>{let e=se(o.mul(x(443.8975,397.2973,491.1871))),t=e.add(Zt(e,e.yzx.add(19.27)));return se(t.x.add(t.y).mul(t.z))}),Ht=He(([o])=>{let e=Nt(o),t=se(o),i=t.mul(t).mul(Gt(3).sub(t.mul(2))),n=D(e.add(x(0,0,0))),s=D(e.add(x(1,0,0))),r=D(e.add(x(0,1,0))),a=D(e.add(x(1,1,0))),l=D(e.add(x(0,0,1))),d=D(e.add(x(1,0,1))),m=D(e.add(x(0,1,1))),f=D(e.add(x(1,1,1))),y=_(n,s,i.x),p=_(r,a,i.x),C=_(l,d,i.x),O=_(m,f,i.x),c=_(y,p,i.y),Ke=_(C,O,i.y);return _(c,Ke,i.z)});var $t=Symbol("Fog"),qt="#9aa3ad",Jt=.015,Qt=10,ei=250,ti=5,ii=.2,oi=.05,ni=.15,si=.1,re=class extends M{static type=$t;threeFog=null;attachedScene=null;patcher;patcherEnabled;constructor(e={}){super(),this.options={...e};let t=this.resolveUniformValues(this.options);this.patcher=new W(t),this.patcherEnabled=ai(this.options)}create(){return super.create(),this.threeFog=ri(this.options),this.group=new Wt,this.group.name=this.name?`Fog:${this.name}`:"Fog",this}attachToScene(e){this.threeFog&&(this.attachedScene=e,e.fog=this.threeFog,this.patcherEnabled&&this.patcher.scan(e))}_update(e){super._update(e),!(!this.attachedScene||!this.patcherEnabled)&&(this.patcher.tick(e.delta),this.patcher.scan(this.attachedScene))}_cleanup(e){this.patcher.unpatchAll(),this.attachedScene&&this.attachedScene.fog===this.threeFog&&(this.attachedScene.fog=null),this.attachedScene=null,this.threeFog=null,super._cleanup(e)}resolveUniformValues(e){let t=e.height,i=e.noise;return{time:0,heightEnabled:t?.enabled?1:0,heightLevel:t?.level??ti,heightFalloff:t?.falloff??ii,noiseEnabled:i?1:0,noiseScale:i?.scale??oi,noiseStrength:i?.strength??ni,noiseSpeed:i?.speed??si}}};function ri(o){let e=new Kt(o.color??qt);return(o.type??"linear")==="exp2"?new Xt(e,o.density??Jt):new Yt(e,o.start??Qt,o.end??ei)}function ai(o){let e=!!o.height?.enabled,t=!!o.noise;return e||t}function on(o={}){return new re(o)}export{v as a,g as b,Je as c,Qe as d,et as e,tt as f,it as g,ot as h,nt as i,st as j,V as k,ki as l,M as m,yt as n,Q as o,Re as p,N as q,ke as r,Z as s,jt as t,k as u,zt as v,$t as w,re as x,on as y};
@@ -1 +0,0 @@
1
- import{a as G,m as ve,n as Ue}from"./chunk-A34ZG3L4.js";import{a as u,d as ye,f as Te,g as _e,h as Ae,i as ke}from"./chunk-CDPY4VOQ.js";import{a as k,m as Fe,n as be,u as H,w as Ze}from"./chunk-ONWXGBWB.js";import{e as R,f as Ie}from"./chunk-DR6XXZE7.js";import{a as Oe,b as A}from"./chunk-YHEWKN7N.js";import{a as U,b as Ve,c as j,d as We,e as Ne,f as He,g as Ge,m as Q}from"./chunk-WKHW2QO2.js";import{c as N,d as fe,j as S}from"./chunk-4QLJUQSJ.js";import{c as v,i as ze,j as g}from"./chunk-G2IIMSUH.js";import{a as je}from"./chunk-FM5TBEPO.js";import{k as Be}from"./chunk-MSC2BEO5.js";import{Vector2 as Ot}from"three";import{WebGPURenderer as zt,RenderPipeline as Ft}from"three/webgpu";import{pass as It,renderOutput as Zt,screenCoordinate as Vt,vec2 as Ce,vec4 as Wt,fract as $e,sin as Xe,dot as Je}from"three/tsl";import{setConsoleFunction as kt,getConsoleFunction as Bt}from"three";var Qe="THREE.Abstract function.",Ke=!1,qe=!1;function Ye(){if(Ke)return;Ke=!0;let a=Bt();kt((e,t,...i)=>{if(e==="warn"&&t===Qe){qe||(qe=!0,console.warn(`${Qe} (suppressing further per-frame repeats; a WebGPU node is scheduled for updates without an update() implementation)`));return}if(a){a(e,t,...i);return}let r=i[0],s=e==="log"?console.log:e==="error"?console.error:console.warn;r&&r.isStackTrace&&typeof r.getError=="function"?s(r.getError(t)):s(t,...i)})}var et={x:0,y:0,width:1,height:1};async function Xi(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var K=class{renderer;postProcessing=null;renderScale=1;screenResolution;rendererType;_initialized=!1;_sceneRef=null;_lastAnimationTimestamp=null;constructor(e,t="webgpu"){this.screenResolution=e||new Ot(window.innerWidth,window.innerHeight),this.rendererType="webgpu"}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(Ye(),this.renderer=new zt({antialias:!0,alpha:!0}),await this.renderer.init(),this.renderer.setSize(this.screenResolution.x,this.screenResolution.y),this.renderer.shadowMap.enabled=!0,this._initialized=!0)}setScene(e){this._sceneRef=e}setupPostProcessing(e,t){this.disposePostProcessing();let i=new Ft(this.renderer),r=It(e,t);this.renderScale!==1&&r.setResolutionScale(this.renderScale),i.outputColorTransform=!1,i.outputNode=Zt(r).add(Ht()),this.postProcessing=i}setRenderScale(e){this.renderScale=Math.max(1,Number.isFinite(e)?e:1)}disposePostProcessing(){try{this.postProcessing?.dispose?.()}catch{}this.postProcessing=null}startRenderLoop(e){this._lastAnimationTimestamp=null,this.renderer.setAnimationLoop(t=>{let i=this._lastAnimationTimestamp===null?0:Math.max(0,(t-this._lastAnimationTimestamp)/1e3);this._lastAnimationTimestamp=t,e(i)})}stopRenderLoop(){this._lastAnimationTimestamp=null;try{this.renderer.setAnimationLoop(null)}catch{}}renderCamera(e,t,i=!1){let r=t.viewport,s=this.screenResolution.x,n=this.screenResolution.y,l=Math.floor(r.x*s),o=Math.floor(r.y*n),c=Math.floor(r.width*s),d=Math.floor(r.height*n);this.renderer.setViewport(l,o,c,d),this.renderer.setScissor(l,o,c,d),this.renderer.setScissorTest(!0),i&&this.postProcessing?this.postProcessing.render():this.renderer.render(e,t.camera)}renderCameraToTarget(e,t){if(!t.renderTarget)return;let i=this.renderer.getRenderTarget();this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(t.renderTarget),this.renderer.clear(),this.renderer.render(e,t.camera),this.renderer.setRenderTarget(i)}renderCameras(e,t){if(!e||t.length===0)return;this.renderer.setScissorTest(!1),this.renderer.clear();let i=t.length===1&&Nt(t[0].viewport);for(let r of t)this.renderCamera(e,r,i);this.renderer.setScissorTest(!1)}render(e,t){this.postProcessing?this.postProcessing.render():this.renderer.render(e,t)}resize(e,t){this.screenResolution.set(e,t),this.renderer.setSize(e,t,!1)}setPixelRatio(e){let t=Math.max(1,Number.isFinite(e)?e:1);this.renderer.setPixelRatio(t)}getDomElement(){return this.renderer.domElement}dispose(){this.stopRenderLoop(),this.disposePostProcessing();try{this.renderer.dispose()}catch{}this._sceneRef=null,this._initialized=!1}};function Nt(a){return a.x===0&&a.y===0&&a.width===1&&a.height===1}function Ht(){let a=Vt.xy,e=$e(Xe(Je(a,Ce(12.9898,78.233))).mul(43758.5453)),t=$e(Xe(Je(a.add(Ce(13,7)),Ce(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return Wt(i,i,i,0)}var p={FirstPerson:"first-person",ThirdPerson:"third-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};import{Vector3 as Gt,Quaternion as Ut,MathUtils as Se}from"three";function q(){return{position:new Gt(0,0,10),rotation:new Ut,fov:75,zoom:1,near:.1,far:1e3}}function D(a){return{position:a.position.clone(),rotation:a.rotation.clone(),fov:a.fov,zoom:a.zoom,near:a.near,far:a.far,lookAt:a.lookAt?.clone()}}function tt(a,e){let t=D(a);return e.position&&t.position.add(e.position),e.rotation&&t.rotation.multiply(e.rotation),e.fov!=null&&t.fov!=null&&(t.fov+=e.fov),e.zoom!=null&&t.zoom!=null&&(t.zoom+=e.zoom),t}function it(a,e,t,i){let r=1-Math.pow(1-Se.clamp(t,0,1),i*60),s=D(a);return s.position.lerp(e.position,r),s.rotation.slerp(e.rotation,r),e.fov!=null&&s.fov!=null&&(s.fov=Se.lerp(s.fov,e.fov,r)),e.zoom!=null&&s.zoom!=null&&(s.zoom=Se.lerp(s.zoom,e.zoom,r)),e.near!=null&&(s.near=e.near),e.far!=null&&(s.far=e.far),e.lookAt?s.lookAt?s.lookAt.lerp(e.lookAt,r):s.lookAt=e.lookAt.clone():s.lookAt=void 0,s}var Y=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=q();_finalPose=q();_initialized=!1;damping=.15;constructor(e){e&&(this.perspective=e,e.defaults?.damping!=null&&(this.damping=e.defaults.damping))}run(e){let t=this.perspective?this.perspective.getBasePose(e):q(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=D(t);for(let r=this.actions.length-1;r>=0;r--){let s=this.actions[r],n=s.update(e);t=tt(t,n),s.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=it(this._finalPose,t,this.damping,e.dt):(this._finalPose=D(t),this._initialized=!0),this._finalPose}addBehavior(e,t,i){let r=this.behaviors.get(e);r?.onDetach&&i&&r.onDetach(i),this.behaviors.set(e,t),t.onAttach&&i&&t.onAttach(i)}removeBehavior(e,t){let i=this.behaviors.get(e);return i?(i.onDetach&&t&&i.onDetach(t),this.behaviors.delete(e)):!1}hasBehavior(e){return this.behaviors.has(e)}addAction(e){this.actions.push(e)}getState(){return{perspectiveId:this.perspective?.id??null,desiredPose:this._desiredPose?D(this._desiredPose):null,finalPose:this._finalPose?D(this._finalPose):null,activeBehaviors:Array.from(this.behaviors.keys()),activeActionCount:this.actions.length}}setPerspective(e){this.perspective=e,this._initialized=!1,e.defaults?.damping!=null&&(this.damping=e.defaults.damping)}getSortedBehaviors(){return Array.from(this.behaviors.values()).sort((e,t)=>(e.priority??0)-(t.priority??0))}};import{Vector3 as P,Quaternion as $}from"three";var jt={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},E=class{id="third-person";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...jt,...r},this.initialPosition=t?g(t,v):void 0,this.initialLookAt=i?g(i,v):void 0}getBasePose(e){let t=Object.keys(e.targets),i=e.targets[this.opts.targetKey];return t.length===0||!i?this.staticPose():t.length===1?this.singleTargetPose(i.position,e,this.opts.targetKey):this.multiTargetPose(e)}staticPose(){return this.initialPosition?{position:this.initialPosition.clone(),rotation:new $,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new P(0,0,0)}:{position:new P(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new $,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new P(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new P(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new $,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([m,h])=>this.getTrailedPosition(m,h.position,e.time)),r=new P;for(let m of i)r.add(m);r.divideScalar(i.length);let s=0;for(let m of i){let h=r.distanceTo(m);h>s&&(s=h)}let n=Math.max(s*this.opts.paddingFactor,this.opts.minDistance),l=new P(this.opts.shoulderOffset,this.opts.height,this.opts.distance),o=l.length(),c=o>0?l.clone().normalize():new P(0,.5,1).normalize(),d=r.clone().add(c.multiplyScalar(n));if(o>0){let m=this.opts.height/o;d.y=r.y+n*m}return{position:d,rotation:new $,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}getTrailedPosition(e,t,i){let r=this.opts.trailDelay;if(r<=0)return t;let s=this._trailBuffers.get(e);s||(s=[],this._trailBuffers.set(e,s)),s.push({time:i,pos:t.clone()});let n=i-r-.05;for(;s.length>1&&s[0].time<n;)s.shift();s.length>this.opts.trailBufferSize&&s.splice(0,s.length-this.opts.trailBufferSize);let l=i-r;if(s[0].time>=l)return s[0].pos.clone();for(let o=1;o<s.length;o++){let c=s[o-1],d=s[o];if(c.time<=l&&l<=d.time){let m=d.time-c.time,h=m>1e-6?(l-c.time)/m:0;return new P().lerpVectors(c.pos,d.pos,h)}}return s[s.length-1].pos.clone()}};import{Vector3 as rt,Quaternion as Qt}from"three";var at={position:{x:0,y:0,z:10},zoom:10},M=class{id="fixed-2d";defaults={damping:1};opts;constructor(e){this.opts={...at,...e,position:g(e?.position,at.position)}}getBasePose(e){return{position:new rt(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new Qt,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new rt(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as Pe,Quaternion as we,Euler as ot,MathUtils as y}from"three";var Kt={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},B=class{id="first-person";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new we;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Kt,...r},this.initialPosition=t?g(t,v):void 0,this.initialLookAt=i?g(i,v):void 0,this._currentFov=this.opts.defaultFov,this._targetFov=this.opts.defaultFov,this._lookAtLerpSpeed=this.opts.lookAtLerpSpeed,this.initialPosition&&this.initialLookAt&&this.deriveYawPitchFromLookAt(this.initialPosition,this.initialLookAt)}look(e,t){this._yaw+=e,this._pitch=y.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=y.clamp(t,-this.opts.pitchLimit,this.opts.pitchLimit)}get yaw(){return this._yaw}get pitch(){return this._pitch}zoom(e){this._targetFov=e}resetZoom(){this._targetFov=this.opts.defaultFov}get currentFov(){return this._currentFov}lookAt(e,t){this._lookAtTarget=e,t!=null&&(this._lookAtLerpSpeed=t)}clearLookAt(){this._lookAtTarget&&this.deriveYawPitchFromQuaternion(this._currentRotation),this._lookAtTarget=null}getBasePose(e){let t=this.computePosition(e),i=this.computeRotation(t,e.dt);return this._currentFov=this.lerpFov(e.dt),{position:t,rotation:i,fov:this._currentFov,near:.1,far:1e3}}computePosition(e){let t=e.targets[this.opts.targetKey];if(t){let i=t.position.y+this.opts.eyeHeight,r=this.smoothVertical(i,e.dt);return new Pe(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new Pe(0,this.opts.eyeHeight,0)}smoothVertical(e,t){if(this.opts.verticalSmoothing>=1)return this._smoothedY=e,e;if(this._smoothedY==null)return this._smoothedY=e,e;let i=y.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=y.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new we().setFromEuler(new ot(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=st.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let s=Math.atan2(-r.x,-r.z),n=Math.asin(y.clamp(r.y,-1,1)),l=qt.setFromEuler(nt.set(n,s,0,"YXZ")),o=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(l,y.clamp(o,0,1)),this._currentRotation.clone()}}return this._currentRotation.copy(i),i}lerpFov(e){if(Math.abs(this._currentFov-this._targetFov)<.01)return this._targetFov;let t=1-Math.pow(1-Math.min(this.opts.fovLerpSpeed*e,1),1);return y.lerp(this._currentFov,this._targetFov,y.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=st.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(y.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=nt.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=y.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},st=new Pe,qt=new we,nt=new ot;function L(a,e){switch(a){case"third-person":return new E(e);case"first-person":return new B(e);case"isometric":return new E({distance:10,height:10,...e});case"flat-2d":return new M(e);case"fixed-2d":return new M(e);default:return new E(e)}}import{Vector2 as Jt}from"three";import{PerspectiveCamera as O,Vector3 as $t,OrthographicCamera as J,RenderTarget as Xt,LinearFilter as ct}from"three";import{Vector3 as lt}from"three";import{OrbitControls as Yt}from"three/addons/controls/OrbitControls.js";var X=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new lt;debugDelegate=null;debugUnsubscribe=null;debugStateSnapshot={enabled:!1,selected:[]};savedCameraPosition=null;savedCameraQuaternion=null;savedCameraZoom=null;savedCameraLocalPosition=null;savedDebugCameraPosition=null;savedDebugCameraQuaternion=null;savedDebugCameraZoom=null;savedDebugOrbitTarget=null;_userOrbitEnabled=!1;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null}setScene(e){this.sceneRef=e}get isActive(){return this.debugStateSnapshot.enabled}get isOrbitActive(){return this.debugStateSnapshot.enabled||this._userOrbitEnabled}update(){this.orbitControls&&this.orbitTarget&&(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)),this.orbitControls?.update()}enableUserOrbitControls(){this._userOrbitEnabled=!0,this.orbitControls||this.enableOrbitControls()}disableUserOrbitControls(){this._userOrbitEnabled=!1,this.debugStateSnapshot.enabled||this.disableOrbitControls()}setDebugDelegate(e){if(this.debugDelegate===e)return;if(this.detachDebugDelegate(),this.debugDelegate=e,!e){this.applyDebugState({enabled:!1,selected:[]});return}let t=e.subscribe(i=>{this.applyDebugState(i)});this.debugUnsubscribe=()=>{t?.()}}dispose(){this.disableOrbitControls(),this.detachDebugDelegate()}get debugState(){return this.debugStateSnapshot}applyDebugState(e){let t=this.debugStateSnapshot.enabled;this.debugStateSnapshot={enabled:e.enabled,selected:[...e.selected]},e.enabled&&!t?(this.saveCameraState(),this.detachCameraFromRig(),this.enableOrbitControls(),this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this.orbitTarget=null,this._userOrbitEnabled||this.disableOrbitControls(),this.reattachCameraToRig(),this.restoreCameraState()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected)}enableOrbitControls(){this.orbitControls||(this.orbitControls=new Yt(this.camera,this.domElement),this.orbitControls.enableDamping=!0,this.orbitControls.dampingFactor=.05,this.orbitControls.screenSpacePanning=!1,this.orbitControls.minDistance=1,this.orbitControls.maxDistance=500,this.orbitControls.maxPolarAngle=Math.PI/2,this.orbitControls.target.set(0,0,0))}disableOrbitControls(){this.orbitControls&&(this.orbitControls.dispose(),this.orbitControls=null)}updateOrbitTargetFromSelection(e){if(!this.debugDelegate||e.length===0){this.orbitTarget=null,this.orbitControls&&this.orbitControls.target.set(0,0,0);return}for(let t=e.length-1;t>=0;t-=1){let i=e[t],r=this.debugDelegate.resolveTarget(i);if(r){this.orbitTarget=r,this.orbitControls&&(r.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos));return}}this.orbitTarget=null}detachDebugDelegate(){if(this.debugUnsubscribe)try{this.debugUnsubscribe()}catch{}this.debugUnsubscribe=null,this.debugDelegate=null}saveCameraState(){this.savedCameraPosition=this.camera.position.clone(),this.savedCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedCameraZoom=this.camera.zoom)}restoreCameraState(){this.savedCameraPosition&&(this.camera.position.copy(this.savedCameraPosition),this.savedCameraPosition=null),this.savedCameraQuaternion&&(this.camera.quaternion.copy(this.savedCameraQuaternion),this.savedCameraQuaternion=null),this.savedCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedCameraZoom,this.camera.updateProjectionMatrix?.(),this.savedCameraZoom=null)}saveDebugCameraState(){this.savedDebugCameraPosition=this.camera.position.clone(),this.savedDebugCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedDebugCameraZoom=this.camera.zoom),this.orbitControls&&(this.savedDebugOrbitTarget=this.orbitControls.target.clone())}restoreDebugCameraState(){this.savedDebugCameraPosition&&this.camera.position.copy(this.savedDebugCameraPosition),this.savedDebugCameraQuaternion&&this.camera.quaternion.copy(this.savedDebugCameraQuaternion),this.savedDebugCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedDebugCameraZoom,this.camera.updateProjectionMatrix?.()),this.savedDebugOrbitTarget&&this.orbitControls&&this.orbitControls.target.copy(this.savedDebugOrbitTarget)}detachCameraFromRig(){if(!this.cameraRig||this.camera.parent!==this.cameraRig)return;this.savedCameraLocalPosition=this.camera.position.clone();let e=new lt;this.camera.getWorldPosition(e),this.cameraRig.remove(this.camera),this.sceneRef&&this.sceneRef.add(this.camera),this.camera.position.copy(e)}reattachCameraToRig(){!this.cameraRig||this.camera.parent===this.cameraRig||(this.sceneRef&&this.camera.parent===this.sceneRef&&this.sceneRef.remove(this.camera),this.cameraRig.add(this.camera),this.savedCameraLocalPosition&&(this.camera.position.copy(this.savedCameraLocalPosition),this.savedCameraLocalPosition=null))}};var C=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;rendererType;sceneRef=null;name="";viewport={...et};targets=[];pipeline;renderTarget=null;get target(){return this.targets.length>0?this.targets[0]:null}set target(e){e?this.targets.length===0?this.targets.push(e):this.targets[0]=e:this.targets=[]}orbitController=null;_useOrbitalControls=!1;_skipDebugOrbit=!1;_rendererManager=null;_elapsedTime=0;constructor(e,t,i=10,r="webgpu"){this._perspective=e,this.screenResolution=t,this.frustumSize=i,this.rendererType=r;let s=t.x/t.y;this.camera=this.createCameraForPerspective(s),this.camera.position.set(0,0,10),this.camera.lookAt(new $t(0,0,0));let n=L(e);this.pipeline=new Y(n)}async setup(e,t){this.sceneRef=e,t&&(this._rendererManager=t),this._rendererManager&&!this._rendererManager.initialized&&await this._rendererManager.initRenderer(),this._rendererManager&&(this.orbitController=new X(this.camera,this._rendererManager.renderer.domElement,null),this.orbitController.setScene(e),this._useOrbitalControls&&this.orbitController.enableUserOrbitControls())}async setupLegacy(e){this._rendererManager||(this._rendererManager=new K(this.screenResolution,this.rendererType),await this._rendererManager.initRenderer(),this._rendererManager.setupPostProcessing(e,this.camera),this._rendererManager.startRenderLoop(()=>{this._rendererManager&&this.sceneRef&&(this.isOrbitActive&&this.updateOrbitControls(),this._rendererManager.render(this.sceneRef,this.camera))})),await this.setup(e,this._rendererManager)}update(e){if(this.isDebugModeActive()||this._useOrbitalControls)return;this._elapsedTime+=e;let t=this.buildContext(e),i=this.pipeline.run(t);this.commitPose(i)}isDebugModeActive(){return this.orbitController?.isActive??!1}get isOrbitActive(){return this.orbitController?.isOrbitActive??!1}updateOrbitControls(){this.orbitController?.update()}enableOrbitalControls(){this._useOrbitalControls=!0,this.orbitController?.enableUserOrbitControls()}disableOrbitalControls(){this._useOrbitalControls=!1,this.orbitController?.disableUserOrbitControls()}get useOrbitalControls(){return this._useOrbitalControls}addTarget(e){this.targets.includes(e)||this.targets.push(e)}removeTarget(e){let t=this.targets.indexOf(e);t!==-1&&this.targets.splice(t,1)}clearTargets(){this.targets=[]}setViewport(e,t,i,r){this.viewport={x:e,y:t,width:i,height:r}}resize(e,t){if(this.screenResolution.set(e,t),this.camera instanceof O&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof J){let i=e/t;this.camera.left=this.frustumSize*i/-2,this.camera.right=this.frustumSize*i/2,this.camera.top=this.frustumSize/2,this.camera.bottom=this.frustumSize/-2,this.camera.updateProjectionMatrix()}}createRenderTarget(e=512,t=512){return this.renderTarget&&this.renderTarget.dispose(),this.renderTarget=new Xt(e,t,{minFilter:ct,magFilter:ct}),this.renderTarget}getRenderTexture(){return this.renderTarget?.texture??null}destroy(){try{this.orbitController?.dispose()}catch{}try{this.renderTarget?.dispose()}catch{}this.renderTarget=null,this.sceneRef=null,this.targets=[],this._rendererManager=null}setDebugDelegate(e){this._skipDebugOrbit||this.orbitController?.setDebugDelegate(e)}move(e){(this._perspective===p.Flat2D||this._perspective===p.Fixed2D)&&(this.frustumSize=e.z),this.camera.position.set(e.x,e.y,e.z)}rotate(e,t,i){this.camera.rotateX(e),this.camera.rotateY(t),this.camera.rotateZ(i)}getDomElement(){if(this._rendererManager)return this._rendererManager.getDomElement();throw new Error("ZylemCamera: No renderer manager available. Call setup() first.")}getRendererManager(){return this._rendererManager}setRendererManager(e){this._rendererManager=e}get renderer(){return this._rendererManager?.renderer}get composer(){return this._rendererManager?.postProcessing}setPixelRatio(e){this._rendererManager?.setPixelRatio(e)}buildContext(e){let t={};for(let i=0;i<this.targets.length;i++){let r=this.targets[i],s=i===0?"primary":`target_${i}`;r.group&&(t[s]={position:r.group.position,rotation:r.group.quaternion})}return{dt:e,time:this._elapsedTime,viewport:{width:this.screenResolution.x,height:this.screenResolution.y,aspect:this.screenResolution.x/this.screenResolution.y},targets:t}}commitPose(e){if(this.camera.position.copy(e.position),e.lookAt?this.camera.lookAt(e.lookAt):this.camera.quaternion.copy(e.rotation),this.camera instanceof O&&(e.fov!=null&&(this.camera.fov=e.fov),e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()),this.camera instanceof J){if(e.zoom!=null){let t=this.screenResolution.x/this.screenResolution.y,i=e.zoom;this.camera.left=-i*t/2,this.camera.right=i*t/2,this.camera.top=i/2,this.camera.bottom=-i/2}e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()}}createCameraForPerspective(e){switch(this._perspective){case p.ThirdPerson:return new O(75,e,.1,1e3);case p.FirstPerson:return new O(75,e,.1,1e3);case p.Isometric:return new J(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);case p.Flat2D:case p.Fixed2D:return new J(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);default:return new O(75,e,.1,1e3)}}};var ee=class{cameras=new Map;_activeCameras=[];_debugCamera=null;_rendererManager=null;_sceneRef=null;_autoNameCounter=0;constructor(){}get activeCameras(){return this._activeCameras}get primaryCamera(){return this._activeCameras.length>0?this._activeCameras[0]:null}get debugCamera(){return this._debugCamera}get allCameras(){return Array.from(this.cameras.values())}addCamera(e,t){let i=t||e.name||`camera_${this._autoNameCounter++}`;return e.name=i,this.cameras.set(i,e),this._activeCameras.length===0&&this._activeCameras.push(e),i}removeCamera(e){let t;if(typeof e=="string")t=e;else for(let[s,n]of this.cameras.entries())if(n===e){t=s;break}if(!t)return!1;let i=this.cameras.get(t);if(!i)return!1;if(i===this._debugCamera)return console.warn("CameraManager: Cannot remove the debug camera"),!1;this.cameras.delete(t);let r=this._activeCameras.indexOf(i);return r!==-1&&this._activeCameras.splice(r,1),!0}setActiveCamera(e){let t=this.resolveCamera(e);if(!t)return console.warn(`CameraManager: Camera not found: ${e}`),!1;let i=this._activeCameras.filter(r=>r!==this._activeCameras[0]&&r.viewport.width<1);return this._activeCameras=[t,...i],!0}addActiveCamera(e){let t=this.resolveCamera(e);return t?(this._activeCameras.includes(t)||this._activeCameras.push(t),!0):!1}deactivateCamera(e){let t=this.resolveCamera(e);if(!t)return!1;let i=this._activeCameras.indexOf(t);return i!==-1?(this._activeCameras.splice(i,1),!0):!1}getCamera(e){return this.cameras.get(e)??null}async setup(e,t){this._sceneRef=e,this._rendererManager=t,this.createDebugCamera(t.screenResolution);for(let i of this.cameras.values())i.setRendererManager(t),await i.setup(e,t);this._debugCamera&&(this._debugCamera.setRendererManager(t),await this._debugCamera.setup(e,t))}update(e){for(let t of this._activeCameras)t.update(e)}render(e){if(!this._rendererManager||this._activeCameras.length===0)return;this.updateOrbitingCamerasForRender();let t=[],i=[];for(let r of this._activeCameras)r.renderTarget?t.push(r):i.push(r);for(let r of t)this._rendererManager.renderCameraToTarget(e,r);i.length>0&&this._rendererManager.renderCameras(e,i)}updateOrbitingCamerasForRender(){for(let e of this._activeCameras)e.isOrbitActive&&e.updateOrbitControls()}ensureDefaultCamera(){if(this.cameras.size===0||this._activeCameras.length===0){let e=this._rendererManager?.screenResolution||new Jt(window.innerWidth,window.innerHeight),t=new C(p.ThirdPerson,e);return this.addCamera(t,"default"),t}return this._activeCameras[0]}dispose(){for(let e of this.cameras.values())e.destroy();this._debugCamera?.destroy(),this.cameras.clear(),this._activeCameras=[],this._debugCamera=null,this._rendererManager=null,this._sceneRef=null}createDebugCamera(e){this._debugCamera=new C(p.ThirdPerson,e),this._debugCamera.name="__debug__",this._debugCamera.enableOrbitalControls()}resolveCamera(e){if(typeof e=="string")return this.cameras.get(e)??null;for(let t of this.cameras.values())if(t===e)return t;return null}};var b=class{cameraRef;constructor(e){this.cameraRef=e}addTarget(e){this.cameraRef.addTarget(e)}removeTarget(e){this.cameraRef.removeTarget(e)}clearTargets(){this.cameraRef.clearTargets()}enableOrbitalControls(){this.cameraRef.enableOrbitalControls()}disableOrbitalControls(){this.cameraRef.disableOrbitalControls()}setViewport(e,t,i,r){this.cameraRef.setViewport(e,t,i,r)}addBehavior(e,t){this.cameraRef.pipeline.addBehavior(e,t)}removeBehavior(e){return this.cameraRef.pipeline.removeBehavior(e)}addAction(e){this.cameraRef.pipeline.addAction(e)}setPerspective(e,t){this.cameraRef.pipeline.setPerspective(L(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function ia(a){let e=ze(a.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;a.perspective==="fixed-2d"&&(t=a.zoom||10);let i=new C(a.perspective||"third-person",e,t,a.rendererType||"webgpu");a.name&&(i.name=a.name);let r=g(a.position,v),s=g(a.target,v);i.move(r),i.camera.lookAt(s);let n=a.perspective||"third-person";if(n==="fixed-2d"||n==="flat-2d"?i.pipeline.setPerspective(L(n,{zoom:t})):i.pipeline.setPerspective(L(n,{initialPosition:r.clone(),initialLookAt:s.clone()})),a.viewport&&(i.viewport={...a.viewport}),a.useOrbitalControls&&(i._useOrbitalControls=!0),a.skipDebugOrbit&&(i._skipDebugOrbit=!0),a.damping!=null&&(i.pipeline.damping=a.damping),a.behaviors)for(let[l,o]of Object.entries(a.behaviors))i.pipeline.addBehavior(l,o);if(a.renderToTexture){let{width:l=512,height:o=512}=a.renderToTexture;i.createRenderTarget(l,o)}return new b(i)}import{Vector3 as ei}from"three";function w(a){return!!a&&typeof a=="object"&&typeof a.create=="function"}function z(a){return!!a&&typeof a.then=="function"}function De(a){return!!a&&typeof a=="object"&&a instanceof b}function dt(a){return!a||typeof a!="object"||w(a)||De(a)||z(a)||typeof a.then=="function"?!1:a.constructor===Object||a.constructor?.name==="Object"}function ut(a){return a?!!(w(a)||typeof a=="function"||z(a)):!1}var ti="/three/basis/";function ie(a){return{...a,ktx2TranscoderPath:a?.ktx2TranscoderPath??ti}}var te=class{constructor(e,t,i,r,s,n,l=60,o={},c=void 0,d=void 0,m=!0,h=void 0){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=s;this.variables=n;this.physicsRate=l;this.assetLoaders=o;this.runtimeAdapter=c;this.runtimeDebugBinding=d;this.defaultLighting=m;this.wasmRuntime=h}};function ii(){return new te({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},U,null,null,new ei(0,0,0),{},60,{},void 0,void 0,!0,void 0)}function mt(a=[]){let e=ii(),t={},i=[],r=[],s=[];for(let o of a)De(o)?s.push(o):w(o)?i.push(o):ut(o)&&!w(o)?r.push(o):dt(o)&&(t={...t,...o});let n=new te(t.inputs??e.inputs,t.backgroundColor??e.backgroundColor,t.backgroundImage??e.backgroundImage,t.backgroundShader??e.backgroundShader,t.gravity??e.gravity,t.variables??e.variables,t.physicsRate??e.physicsRate,t.assetLoaders??e.assetLoaders,t.runtimeAdapter??e.runtimeAdapter,t.runtimeDebugBinding??e.runtimeDebugBinding,t.defaultLighting??e.defaultLighting,t.wasmRuntime??e.wasmRuntime),l=s.length>0?s[0]:void 0;return{config:n,entities:i,asyncEntities:r,camera:l,cameras:s}}function da(a){return{...a}}var ri=Symbol("vessel"),F=class extends k{static type=ri;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=ai();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function ai(...a){let e=new F;return a.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as _t,Vector3 as pe}from"three";import St from"@dimforge/rapier3d-compat";import{Quaternion as Ee}from"three";var T=new WeakMap,ht=new Ee,pt=new Ee,I=new Ee;function gt(a){return{x:a.x,y:a.y,z:a.z}}function ft(a){return{x:a.x,y:a.y,z:a.z,w:a.w}}function _(a){return{position:gt(a.position),rotation:ft(a.rotation)}}function si(a){return Number.isFinite(a)?Math.max(0,Math.min(1,a)):0}function Z(a){return{position:gt(a.translation()),rotation:ft(a.rotation())}}function xe(a){let e=_(a);return{previous:_(e),current:e}}function yt(a){let e=xe(Z(a));return T.set(a,e),e}function V(a){let e=Z(a),t=T.get(a)??xe(e);return t.previous=_(e),t.current=_(e),T.set(a,t),t}function bt(a){return V(a)}function vt(a){let e=Z(a),t=T.get(a)??xe(e);return t.current=_(e),T.set(a,t),t}function ni(a,e,t){let i=si(t);return ht.set(a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w),pt.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),I.slerpQuaternions(ht,pt,i),{position:{x:a.position.x+(e.position.x-a.position.x)*i,y:a.position.y+(e.position.y-a.position.y)*i,z:a.position.z+(e.position.z-a.position.z)*i},rotation:{x:I.x,y:I.y,z:I.z,w:I.w}}}function Ct(a,e){if(oi(a))return a.getRenderPose(e);let t=T.get(a);if(!t)return Z(a);let i=Z(a);if(!li(i,t.current)){let r=V(a);return _(r.current)}return ni(t.previous,t.current,e)}function oi(a){return a!=null&&typeof a=="object"&&typeof a.getPoseHistory=="function"&&typeof a.getRenderPose=="function"}function li(a,e){return a.position.x===e.position.x&&a.position.y===e.position.y&&a.position.z===e.position.z&&a.rotation.x===e.rotation.x&&a.rotation.y===e.rotation.y&&a.rotation.z===e.rotation.z&&a.rotation.w===e.rotation.w}function Re(a){return typeof a?.handlePostCollision=="function"&&typeof a?.handleIntersectionEvent=="function"}function ci(a,e){return a<e?`${a}|${e}`:`${e}|${a}`}function di(a){let e=new Map;for(let t of a){if(t.uuidA===t.uuidB)continue;let i=ci(t.uuidA,t.uuidB),r=t.uuidA<t.uuidB?t.uuidA:t.uuidB,s=t.uuidA<t.uuidB?t.uuidB:t.uuidA,n=e.get(i);if(n){t.contactType==="contact"?n.hasContact=!0:n.hasIntersection=!0;continue}e.set(i,{uuidA:r,uuidB:s,hasContact:t.contactType==="contact",hasIntersection:t.contactType==="intersection"})}return e}var W=class a{type="World";world;collisionMap=new Map;collisionBehaviorMap=new Map;_removalMap=new Map;activeCollisionPairs=new Map;currentCollisionTimeMs=0;fixedTimestep;accumulator=0;static MAX_STEPS_PER_FRAME=5;interpolationAlpha=0;trackedDirectBodies=new WeakSet;static async loadPhysics(e){return await St.init(),new St.World(e)}constructor(e,t=60){this.world=e,this.fixedTimestep=1/t,e&&(this.world.integrationParameters.dt=this.fixedTimestep)}addEntity(e){this.addEntityDirect(e)}setForRemoval(e){e.physicsAttached&&this._removalMap.set(e.uuid,e)}destroyEntity(e){this.destroyEntityDirect(e)}setup(){}update(e){this.updateDirect(e)}addEntityDirect(e){let t=this.world.createRigidBody(e.bodyDesc);e.body=t,e.physicsAttached=!0,e.body.userData={uuid:e.uuid,ref:e},yt(t),this.patchDirectBodyPoseTracking(t),this.world.gravity.x===0&&this.world.gravity.y===0&&this.world.gravity.z===0&&(e.body.lockTranslations(!0,!0),e.body.lockRotations(!0,!0));let i=this.world.createCollider(e.colliderDesc,e.body);if(e.collider=i,e.colliders=[i],e.colliderDescs?.length>1)for(let r=1;r<e.colliderDescs.length;r++){let s=this.world.createCollider(e.colliderDescs[r],e.body);e.colliders.push(s)}(e.controlledRotation||e instanceof H)&&e.body.lockRotations(!0,!0),e.useCharacterController&&(e.characterController=this.world.createCharacterController(.01),e.characterController.setMaxSlopeClimbAngle(45*Math.PI/180),e.characterController.setMinSlopeSlideAngle(30*Math.PI/180),e.characterController.enableSnapToGround(.01),e.characterController.setSlideEnabled(!0),e.characterController.setApplyImpulsesToDynamicBodies(!0),e.characterController.setCharacterMass(1)),this.collisionMap.set(e.uuid,e)}destroyEntityDirect(e){if(e.characterController){try{e.characterController.free()}catch{}e.characterController=null}if(e.colliders?.length)for(let t of e.colliders)try{this.world.removeCollider(t,!0)}catch{}else if(e.collider)try{this.world.removeCollider(e.collider,!0)}catch{}if(e.body){try{this.world.removeRigidBody(e.body)}catch{}this.removeEntityFromTracking(e.uuid)}this.clearEntityPhysicsState(e)}updateDirect(e){let{delta:t}=e;if(!this.world)return;this.currentCollisionTimeMs+=t*1e3,this.processPendingRemovals(),this.accumulator+=t;let i=this.fixedTimestep*a.MAX_STEPS_PER_FRAME;for(this.accumulator=Math.min(this.accumulator,i);this.accumulator>=this.fixedTimestep;)this.captureDirectBodyPreviousPoses(),this.world.step(),this.captureDirectBodyCurrentPoses(),this.accumulator-=this.fixedTimestep;this.processCollisionPairs(this.collectCollisionPairsFromWorld(),t,this.currentCollisionTimeMs),this.interpolationAlpha=this.accumulator/this.fixedTimestep}captureDirectBodyPreviousPoses(){for(let[,e]of this.collisionMap){let t=e.body;t&&bt(t)}}captureDirectBodyCurrentPoses(){for(let[,e]of this.collisionMap){let t=e.body;t&&vt(t)}}patchDirectBodyPoseTracking(e){if(this.trackedDirectBodies.has(e))return;let t=e,i=e.setTranslation.bind(e),r=e.setRotation.bind(e);t.setTranslation=(s,n)=>{i(s,n),V(e)},t.setRotation=(s,n)=>{r(s,n),V(e)},this.trackedDirectBodies.add(e)}updatePostCollisionBehaviors(e){let t=this.collisionBehaviorMap;for(let[i,r]of t){let s=r;if(!Re(s))continue;s.handlePostCollision({entity:s,delta:e})||this.collisionBehaviorMap.delete(i)}}processPendingRemovals(){if(this._removalMap.size!==0){for(let[,e]of this._removalMap)this.destroyEntity(e);this._removalMap.clear()}}removeEntityFromTracking(e){this.collisionMap.delete(e),this._removalMap.delete(e),this.pruneActiveCollisionPairs(e)}pruneActiveCollisionPairs(e){for(let[t,i]of this.activeCollisionPairs)(i.uuidA===e||i.uuidB===e)&&this.activeCollisionPairs.delete(t)}collectCollisionPairsFromWorld(){let e=[];if(!this.world)return e;for(let[,t]of this.collisionMap){let i=t,r=i.body;if(!r)continue;let s=r.collider(0);s&&(this.world.contactsWith(s,n=>{let o=n.parent()?.userData?.uuid;o&&e.push({uuidA:i.uuid,uuidB:o,contactType:"contact"})}),this.world.intersectionsWith(s,n=>{let o=n.parent()?.userData?.uuid;o&&e.push({uuidA:i.uuid,uuidB:o,contactType:"intersection"})}))}return e}entityHasCollisionPhaseListener(e,t){let i=e?.collisionDelegate.collision;if(!i?.length)return!1;for(let r of i)if(r.options.phase===t)return!0;return!1}processCollisionPairs(e,t,i=this.currentCollisionTimeMs){let r=di(e);for(let[s,n]of r){let l=this.collisionMap.get(n.uuidA),o=this.collisionMap.get(n.uuidB);this.activeCollisionPairs.has(s)||this.dispatchCollisionPhase(n,"enter",i),(this.entityHasCollisionPhaseListener(l,"stay")||this.entityHasCollisionPhaseListener(o,"stay"))&&this.dispatchCollisionPhase(n,"stay",i),n.hasIntersection&&this.dispatchIntersectionDelegates(n,t)}this.updatePostCollisionBehaviors(t),this.activeCollisionPairs=r}dispatchCollisionPhase(e,t,i){let r={phase:t,nowMs:i},s=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);s&&n&&s._collision(n,fe.globals,r);let l=this.collisionMap.get(e.uuidA),o=this.collisionMap.get(e.uuidB);l&&o&&o._collision(l,fe.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&Re(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let s=this.collisionMap.get(e.uuidA),n=this.collisionMap.get(e.uuidB);s&&n&&Re(n)&&(n.handleIntersectionEvent({entity:n,other:s,delta:t}),this.collisionBehaviorMap.set(n.uuid,n))}destroy(){try{for(let[,e]of this.collisionMap)try{this.destroyEntityDirect(e)}catch{}try{this.world?.free()}catch{}this.world=void 0,this.collisionMap.clear(),this.collisionBehaviorMap.clear(),this._removalMap.clear(),this.activeCollisionPairs.clear()}catch{}}clearEntityPhysicsState(e){e.physicsAttached=!1,e.body=null,e.collider=void 0,e.colliders=[],e.characterController=null}};import{Scene as ui,Color as Pt,AmbientLight as mi,DirectionalLight as hi,Vector3 as re,GridHelper as pi,BoxGeometry as gi,Mesh as fi,BackSide as yi,Texture as bi,SRGBColorSpace as vi}from"three";import{MeshBasicNodeMaterial as Ci}from"three/webgpu";var ae=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;skyboxMaterial=null;skyboxMesh=null;constructor(e,t,i){let r=new ui,n=i.backgroundColor instanceof Pt?i.backgroundColor:new Pt(i.backgroundColor);r.background=n,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader,t):i.backgroundImage&&R.loadTexture(i.backgroundImage,{colorSpace:vi}).then(l=>{r.background=l}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),u.enabled&&this.debugScene()}setupBackgroundShader(e,t,i){if(!Ie(t)){console.warn("ZylemScene: GLSL background shaders are not supported on the WebGPU renderer. Provide a TSL shader (ZylemTSLShader) as backgroundShader. Keeping solid background.");return}e.background=null;let r=new Ci;r.colorNode=t.colorNode,t.transparent&&(r.transparent=!0),r.side=yi,r.depthWrite=!1,r.depthTest=!1,this.skyboxMaterial=r;let s=i?.camera?.far??1e3,n=Math.max(10,s*.9),l=new gi(1,1,1),o=new fi(l,this.skyboxMaterial);o.scale.setScalar(n),o.frustumCulled=!1,o.renderOrder=-1e3,this.skyboxMesh=o,e.add(o)}setup(){this._setup&&this._setup({me:this,camera:this.zylemCamera,globals:S()})}destroy(){this.cameraManager?(this.cameraManager.dispose(),this.cameraManager=null):this.zylemCamera&&this.zylemCamera.destroy&&this.zylemCamera.destroy(),this.skyboxMaterial&&this.skyboxMaterial.dispose(),this.skyboxMesh&&(this.skyboxMesh.geometry.dispose(),this.skyboxMesh=null),this.scene&&(this.scene.background instanceof bi&&(this.scene.background.dispose(),this.scene.background=null),this.scene.traverse(e=>{if(e.geometry&&e.geometry.dispose?.(),e.material){let t=Array.isArray(e.material)?e.material:[e.material];for(let i of t)i.map&&i.map.dispose?.(),i.normalMap&&i.normalMap.dispose?.(),i.aoMap&&i.aoMap.dispose?.(),i.emissiveMap&&i.emissiveMap.dispose?.(),i.roughnessMap&&i.roughnessMap.dispose?.(),i.metalnessMap&&i.metalnessMap.dispose?.(),i.envMap&&i.envMap.dispose?.(),i.lightMap&&i.lightMap.dispose?.(),i.bumpMap&&i.bumpMap.dispose?.(),i.displacementMap&&i.displacementMap.dispose?.(),i.alphaMap&&i.alphaMap.dispose?.(),i.dispose?.()}e.isLight&&e.shadow?.map&&e.shadow.map.dispose()}),this.scene.clear())}async setupCamera(e,t,i){this.addCameraToScene(e,t),i?await t.setup(e,i):await t.setupLegacy(e)}async setupCameraManager(e,t,i){this.cameraManager=t;for(let r of t.activeCameras)this.addCameraToScene(e,r);await t.setup(e,i)}addCameraToScene(e,t){t.cameraRig?e.add(t.cameraRig):e.add(t.camera)}setupLighting(e){let t=new mi(16777215,1);e.add(t);let i=new hi(16777215,2);i.name="Light",i.position.set(0,100,0),i.castShadow=!0,i.shadow.camera.near=.1,i.shadow.camera.far=2e3,i.shadow.camera.left=-100,i.shadow.camera.right=100,i.shadow.camera.top=100,i.shadow.camera.bottom=-100,i.shadow.mapSize.width=2048,i.shadow.mapSize.height=2048,e.add(i)}updateRenderer(e,t){if(this.cameraManager)for(let i of this.cameraManager.allCameras)i.resize(e,t);else this.zylemCamera.resize(e,t)}add(e,t=new re(0,0,0)){e.position.set(t.x,t.y,t.z),this.scene.add(e)}addEntity(e){let t=e.group??e.mesh;!t||this.isAttachedOutsideScene(t)||this.add(t,e.options.position)}addEntityGroup(e){let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=Si(e);i&&i.attachToScene(this.scene);let r=e.options.position??new re(0,0,0);if(e.physicsAttached&&e.body)try{let s=e.body.translation();r=new re(s.x,s.y,s.z)}catch{r=e.options.position??new re(0,0,0)}this.add(t,r)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new pi(1e3,100);this.scene.add(i)}updateSkybox(e){if(!this.skyboxMesh)return;let t=this.cameraManager?.primaryCamera?.camera??this.zylemCamera?.camera;t&&t.getWorldPosition(this.skyboxMesh.position)}};function Si(a){return a.constructor.type===Ze?a:null}var se=class{update=()=>{};setup=()=>{};destroy=()=>{};nodeSetup(e){typeof this._setup=="function"&&this._setup(e),this.setup&&this.setup(e)}nodeUpdate(e){typeof this._update=="function"&&this._update(e),this.update&&this.update(e)}nodeDestroy(e){this.destroy&&this.destroy(e),typeof this._destroy=="function"&&this._destroy(e)}};import{Quaternion as Pi}from"three";var wt=new Pi;function Dt(a){let e=a._childrenMap,t=a._world;for(let[,i]of e){if(!i?.body||i.markedForRemoval)continue;let r=i.body,s=i.group??i.mesh,n=s?Ct(r,t?.interpolationAlpha??0):null;s&&n&&s.position.set(n.position.x,n.position.y,n.position.z),!i.controlledRotation&&s&&n&&(wt.set(n.rotation.x,n.rotation.y,n.rotation.z,n.rotation.w),s.setRotationFromQuaternion(wt))}}import{nanoid as Ii}from"nanoid";import{Ray as _i}from"@dimforge/rapier3d-compat";import{BufferAttribute as le,BufferGeometry as Mt,LineBasicMaterial as Lt,LineSegments as Tt,Raycaster as Ai,Vector2 as ki}from"three";import{subscribe as Bi}from"valtio/vanilla";import{subscribe as wi}from"valtio/vanilla";var ne=class{stage;constructor(e){this.stage=e}subscribe(e){let t=()=>e(this.snapshot());return t(),wi(u,t)}resolveTarget(e){let t=this.stage.entityDelegate.debugMap.get(e)||this.stage.world?.collisionMap.get(e)||null;return t?.group??t?.mesh??null??null}snapshot(){return{enabled:u.enabled,selected:u.selectedEntity?[u.selectedEntity.uuid]:[]}}};import{Box3 as Di,BoxGeometry as Et,Color as Ei,EdgesGeometry as xt,Group as xi,LineBasicMaterial as Ri,LineSegments as Mi,Mesh as Li,MeshBasicMaterial as Ti,Vector3 as Rt}from"three";var oe=class{scene;container;fillMesh;edgeLines;currentColor=new Ei(65280);bbox=new Di;size=new Rt;center=new Rt;constructor(e){this.scene=e;let t=new Et(1,1,1);this.fillMesh=new Li(t,new Ti({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new xt(t);this.edgeLines=new Mi(i,new Ri({color:this.currentColor,linewidth:1})),this.container=new xi,this.container.name="DebugEntityCursor",this.container.add(this.fillMesh),this.container.add(this.edgeLines),this.container.visible=!1,this.scene.add(this.container)}setColor(e){this.currentColor.set(e),this.fillMesh.material.color.set(this.currentColor),this.edgeLines.material.color.set(this.currentColor)}updateFromObject(e){if(!e){this.hide();return}if(this.bbox.setFromObject(e),!isFinite(this.bbox.min.x)||!isFinite(this.bbox.max.x)){this.hide();return}this.bbox.getSize(this.size),this.bbox.getCenter(this.center);let t=new Et(Math.max(this.size.x,1e-6),Math.max(this.size.y,1e-6),Math.max(this.size.z,1e-6));this.fillMesh.geometry.dispose(),this.fillMesh.geometry=t;let i=new xt(t);this.edgeLines.geometry.dispose(),this.edgeLines.geometry=i,this.container.position.copy(this.center),this.container.visible=!0}hide(){this.container.visible=!1}dispose(){this.scene.remove(this.container),this.fillMesh.geometry.dispose(),this.fillMesh.material.dispose(),this.edgeLines.geometry.dispose(),this.edgeLines.material.dispose()}};var Oi=2293538,zi=16724787,ce=class{stage;options;mouseNdc=new ki(-2,-2);raycaster=new Ai;isMouseDown=!1;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;debugLines=null;runtimeDebugLines=null;cameraDebugDelegate=null;debugStateUnsubscribe=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.syncWithDebugState(),this.debugStateUnsubscribe=Bi(u,()=>{this.syncWithDebugState()})}syncWithDebugState(){u.enabled?this.activate():this.deactivate()}activate(){this.domListenersAttached||(this.attachDomListeners(),this.domListenersAttached=!0),this.stage.cameraRef&&!this.cameraDebugDelegate&&(this.cameraDebugDelegate=new ne(this.stage),this.stage.cameraRef.setDebugDelegate(this.cameraDebugDelegate))}deactivate(){this.disposeDebugVisuals(),this.stage.cameraRef&&this.stage.cameraRef.setDebugDelegate(null),this.cameraDebugDelegate=null}initDebugVisuals(){this.debugLines||!this.stage.scene||(this.debugLines=new Tt(new Mt,new Lt({vertexColors:!0})),this.stage.scene.scene.add(this.debugLines),this.debugLines.visible=!0,this.runtimeDebugLines=new Tt(new Mt,new Lt({vertexColors:!0})),this.runtimeDebugLines.visible=!0,this.stage.scene.scene.add(this.runtimeDebugLines),this.debugCursor=new oe(this.stage.scene.scene))}disposeDebugVisuals(){this.debugLines&&this.stage.scene&&(this.stage.scene.scene.remove(this.debugLines),this.debugLines.geometry.dispose(),this.debugLines.material.dispose(),this.debugLines=null),this.runtimeDebugLines&&this.stage.scene&&(this.stage.scene.scene.remove(this.runtimeDebugLines),this.runtimeDebugLines.geometry.dispose(),this.runtimeDebugLines.material.dispose(),this.runtimeDebugLines=null),this.debugCursor?.dispose(),this.debugCursor=null}update(){if(!u.enabled){this.debugLines&&this.disposeDebugVisuals();return}if(!this.stage.scene||!this.stage.world||!this.stage.cameraRef)return;this.debugLines||this.initDebugVisuals();let{world:e,cameraRef:t}=this.stage,i=e.world!=null;if(this.debugLines&&i){let{vertices:h,colors:f}=e.world.debugRender();this.debugLines.geometry.setAttribute("position",new le(h,3)),this.debugLines.geometry.setAttribute("color",new le(f,4))}if(this.runtimeDebugLines){let f=this.stage.runtimeAdapter?.getDebugRender?.()??null;f&&f.vertices.length>0?(this.runtimeDebugLines.geometry.setAttribute("position",new le(new Float32Array(f.vertices),3)),this.runtimeDebugLines.geometry.setAttribute("color",new le(new Float32Array(f.colors),4)),this.runtimeDebugLines.geometry.attributes.position.needsUpdate=!0,this.runtimeDebugLines.geometry.attributes.color.needsUpdate=!0,this.runtimeDebugLines.visible=!0):this.runtimeDebugLines.visible=!1}let r=ye(),s=r==="select"||r==="delete",n=null,l=null,o=null;if(i){this.raycaster.setFromCamera(this.mouseNdc,t.camera),l=this.raycaster.ray.origin.clone(),o=this.raycaster.ray.direction.clone().normalize();let h=new _i({x:l.x,y:l.y,z:l.z},{x:o.x,y:o.y,z:o.z});n=e.world.castRay(h,this.options.maxRayDistance,!0)}if(n&&s){let f=n.collider?._parent?.userData?.uuid;if(f){let Le=this.stage.entityDelegate.debugMap.get(f);Le&&Ae(Le)}else ke();this.isMouseDown&&l&&o&&this.handleActionOnHit(f??null,l,o,n.toi)}this.isMouseDown=!1;let c=_e();if(!c){this.debugCursor?.hide();return}let d=this.stage.entityDelegate.debugMap.get(`${c}`),m=d?.group??d?.mesh??null;if(!m){this.debugCursor?.hide();return}switch(r){case"select":this.debugCursor?.setColor(Oi);break;case"delete":this.debugCursor?.setColor(zi);break;default:this.debugCursor?.setColor(16777215);break}this.debugCursor?.updateFromObject(m)}dispose(){this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.deactivate(),this.domDisposeFns.forEach(e=>e()),this.domDisposeFns=[],this.domListenersAttached=!1}handleActionOnHit(e,t,i,r){switch(ye()){case"select":{if(e){let n=this.stage.entityDelegate.debugMap.get(e);n&&Te(n)}break}case"delete":{e&&this.stage.entityDelegate.removeEntityByUuid(e);break}case"scale":{if(!this.options.addEntityFactory)break;let n=t.clone().add(i.clone().multiplyScalar(r)),l=this.options.addEntityFactory({position:n});l&&Promise.resolve(l).then(o=>{o&&this.stage.entityDelegate.spawnEntity(o)}).catch(()=>{});break}default:break}}attachDomListeners(){let e=this.stage.cameraRef?.renderer.domElement??this.stage.scene?.zylemCamera.renderer.domElement;if(!e)return;let t=r=>{let s=e.getBoundingClientRect(),n=(r.clientX-s.left)/s.width*2-1,l=-((r.clientY-s.top)/s.height*2-1);this.mouseNdc.set(n,l)},i=()=>{this.isMouseDown=!0};e.addEventListener("mousemove",t),e.addEventListener("mousedown",i),this.domDisposeFns.push(()=>e.removeEventListener("mousemove",t)),this.domDisposeFns.push(()=>e.removeEventListener("mousedown",i))}};import{Vector2 as Fi}from"three";var de=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Fi(e,t);return new C(p.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new ee;if(e)return i.addCamera(e,e.name||"main"),i;let r=t.filter(s=>s!==void 0);if(r.length>0){for(let s of r){let n=s.cameraRef;i.addCamera(n,n.name||void 0)}for(let s=1;s<r.length;s++)i.addActiveCamera(r[s].cameraRef)}else{let s=this.createDefaultCamera();i.addCamera(s,"default")}return i}};var ue=class{loadingHandlers=[];stageName;stageIndex;setStageContext(e,t){this.stageName=e,this.stageIndex=t}onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let i of this.loadingHandlers)try{i(e)}catch(r){console.error("Loading handler failed",r)}let t={...e,stageName:this.stageName,stageIndex:this.stageIndex};e.type==="start"?N.emit("stage:loading:start",t):e.type==="progress"?N.emit("stage:loading:progress",t):e.type==="complete"&&N.emit("stage:loading:complete",t)}emitStart(e="Loading stage..."){this.emit({type:"start",message:e,progress:0})}emitProgress(e,t,i){let r=i>0?t/i:0;this.emit({type:"progress",message:e,progress:r,current:t,total:i})}emitComplete(e="Stage loaded"){this.emit({type:"complete",message:e,progress:1})}dispose(){this.loadingHandlers=[]}};var me=class{scene=null;onEntityReady=null;pendingEntities=new Map;modelLoadedHandler=null;attach(e,t){this.scene=e,this.onEntityReady=t??null,this.modelLoadedHandler=i=>{this.handleModelLoaded(i.entityId,i.success)},A.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){this.scene?.addEntityGroup(e),this.onEntityReady?.(e);return}this.pendingEntities.set(e.uuid,e)}unobserve(e){this.pendingEntities.delete(e)}handleModelLoaded(e,t){let i=this.pendingEntities.get(e);if(!i||!t){this.pendingEntities.delete(e);return}this.scene?.addEntityGroup(i),this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(A.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};var he=class a{static EMPTY_BEHAVIOR_LINKS=[];children=[];childrenMap=new Map;debugMap=new Map;pendingEntities=[];pendingPromises=[];_isLoaded=!1;entityAddedHandlers=[];behaviorSystems=[];behaviorSystemByKey=new Map;registeredSystemKeys=new Set;behaviorEntityIndex=new Map;behaviorLinksByUuid=new Map;scene=null;world=null;instanceManager=null;camera=null;runtimeAdapter=null;wasmStage=null;loadingDelegate;entityModelDelegate;constructor(e,t){this.loadingDelegate=e,this.entityModelDelegate=t}get isLoaded(){return this._isLoaded}set isLoaded(e){this._isLoaded=e}attach(e){this.scene=e.scene,this.world=e.world,this.instanceManager=e.instanceManager,this.camera=e.camera,this.runtimeAdapter=e.runtimeAdapter??null,this.wasmStage=e.wasmStage??null}async spawnEntity(e){if(!this.scene||!this.world)return;if(e instanceof F){e.create();for(let s of e.getChildren())s instanceof k&&await this.spawnEntity(s);e.nodeSetup({me:e,globals:S(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create(),i=this.runtimeAdapter?.ownsEntity(t)??!1,r=i&&(this.runtimeAdapter?.rendersEntity(t)??!1);this.wasmStage&&(t.wasmStageRef=this.wasmStage),this.registerBehaviorLinks(t),i||this.maybeAttachEntityPhysics(t);for(let s of e.getChildren())s instanceof k&&await this.spawnEntity(s);e.nodeSetup({me:e,globals:S(),camera:this.camera}),i&&this.runtimeAdapter?.registerEntity(t),r||this.scene.addEntityGroup(t),i||this.tryRegisterInstance(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t)}handleLateModelReady(e){if(!(!this.world||!this.scene||!this.childrenMap.has(e.uuid))){if(this.runtimeAdapter?.ownsEntity(e)){this.runtimeAdapter.registerEntity(e),this.runtimeAdapter.rendersEntity(e)||this.scene.addEntityGroup(e);return}this.maybeAttachEntityPhysics(e),this.tryRegisterInstance(e)}}tryRegisterInstance(e){if(!this.instanceManager||e.isInstanced||e.options?.batched!==!0||!e.mesh?.geometry||!e.materials?.length)return;let i=e.mesh.geometry,r=e.materials[0],s=G.generateEntityBatchKey(e),n=this.instanceManager.register(e,i,r,s);n>=0&&(e.batchKey=s,e.instanceId=n,e.isInstanced=!0,e.mesh&&(e.mesh.visible=!1))}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof H){if(e.needsDeferredModelCollision())return;e.synchronizeRuntimeCollider()}this.world.addEntity(e)}}addEntityToStage(e){this.childrenMap.set(e.uuid,e),u.enabled&&this.debugMap.set(e.uuid,e);for(let t of this.entityAddedHandlers)try{t(e)}catch(i){console.error("onEntityAdded handler failed",i)}}removeEntityByUuid(e){if(!this.scene||!this.world)return!1;let t=this.world.collisionMap.get(e),i=this.childrenMap.get(e),r=t??i??this.debugMap.get(e);return r?(this.unregisterBehaviorLinks(r),this.entityModelDelegate.unobserve(e),r.isInstanced&&this.instanceManager&&this.instanceManager.unregister(r),this.runtimeAdapter?.unregisterEntity(r),this.runtimeAdapter?.ownsEntity(r)||this.world.destroyEntity(r),r.group?this.scene.scene.remove(r.group):r.mesh&&this.scene.scene.remove(r.mesh),this.childrenMap.delete(e),this.debugMap.delete(e),!0):!1}getEntityByName(e){for(let t of this.childrenMap.values())if(t.name===e)return t;return console.warn(`Entity ${e} not found`),null}buildEntityState(e){return e instanceof Fe?{...e.buildInfo()}:{uuid:e.uuid,name:e.name}}onEntityAdded(e,t){return this.entityAddedHandlers.push(e),t?.replayExisting&&this._isLoaded&&this.childrenMap.forEach(i=>{try{e(i)}catch(r){console.error("onEntityAdded replay failed",r)}}),()=>{this.entityAddedHandlers=this.entityAddedHandlers.filter(i=>i!==e)}}enqueue(...e){for(let t of e)if(t){if(w(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();w(i)?this.handleEntityImmediatelyOrQueue(i):z(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}z(t)&&this.handlePromiseWithSpawnOnResolve(t)}}handleEntityImmediatelyOrQueue(e){this._isLoaded?this.spawnEntity(e):this.children.push(e)}handlePromiseWithSpawnOnResolve(e){this._isLoaded?e.then(t=>this.spawnEntity(t)).catch(t=>console.error("Failed to build async entity",t)):this.pendingPromises.push(e)}*entityLoadGenerator(){let e=this.children.length+this.pendingEntities.length+this.pendingPromises.length,t=0;for(let i of this.children)this.spawnEntity(i),t++,yield{current:t,total:e,name:i.name||"unknown"};if(this.pendingEntities.length&&(this.enqueue(...this.pendingEntities),t+=this.pendingEntities.length,this.pendingEntities=[],yield{current:t,total:e,name:"pending entities"}),this.pendingPromises.length){for(let i of this.pendingPromises)i.then(r=>{this.spawnEntity(r)}).catch(r=>console.error("Failed to resolve pending stage entity",r));t+=this.pendingPromises.length,this.pendingPromises=[],yield{current:t,total:e,name:"async entities"}}}yieldToEventLoop(){return new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>e(),t.port2.postMessage(void 0)})}async runEntityLoadGenerator(){let e=this.entityLoadGenerator(),t=0,i=5;for(let r of e)this.loadingDelegate.emitProgress(`Loaded ${r.name}`,r.current,r.total),++t%i===0&&await this.yieldToEventLoop();t%i!==0&&await this.yieldToEventLoop()}registerSystem(e){if(!this.world||!this.scene)return;let t;typeof e=="function"?t=e({world:this.world,scene:this.scene,getBehaviorLinks:i=>this.behaviorEntityIndex.get(i)??a.EMPTY_BEHAVIOR_LINKS,createEntity:be,getGlobals:S}):t=e,this.behaviorSystems.push(t)}destroyAll(){for(let e of this.behaviorSystems)e.destroy?.();this.behaviorSystems.length=0,this.behaviorSystemByKey.clear(),this.registeredSystemKeys.clear(),this.behaviorEntityIndex.clear(),this.behaviorLinksByUuid.clear(),this.childrenMap.forEach(e=>{try{e.nodeDestroy({me:e,globals:S()})}catch{}Q(e)}),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[],this._isLoaded=!1,this.scene=null,this.world=null,this.instanceManager=null,this.camera=null}registerBehaviorLinks(e){if(!this.world||!this.scene||typeof e?.getBehaviorRefs!="function")return;let t=e.getBehaviorRefs();if(!Array.isArray(t)||t.length===0)return;let i=[];for(let r of t){let s=r.descriptor.key,n={entity:e,ref:r};i.push(n);let l=this.behaviorEntityIndex.get(s);l||(l=new Set,this.behaviorEntityIndex.set(s,l)),l.add(n);let o=this.behaviorSystemByKey.get(s);if(!o&&!this.registeredSystemKeys.has(s)){let c=r.descriptor.systemFactory({world:this.world,scene:this.scene,wasmStage:this.wasmStage,getBehaviorLinks:d=>this.behaviorEntityIndex.get(d)??a.EMPTY_BEHAVIOR_LINKS,createEntity:be,getGlobals:S});o=c,this.behaviorSystems.push(c),this.behaviorSystemByKey.set(s,c),this.registeredSystemKeys.add(s)}o?.attach?.(n)}this.behaviorLinksByUuid.set(e.uuid,i)}unregisterBehaviorLinks(e){let t=this.behaviorLinksByUuid.get(e?.uuid);if(t){for(let i of t){let r=i.ref?.descriptor?.key;if(!r)continue;let s=this.behaviorEntityIndex.get(r);s&&(this.behaviorSystemByKey.get(r)?.detach?.(i),s.delete(i),s.size===0&&this.behaviorEntityIndex.delete(r))}this.behaviorLinksByUuid.delete(e.uuid)}}};var Zi="Stage",ge=class extends se{type=Zi;state={...Ve};gravity;world;scene;instanceManager=null;wasmStage=null;debugDelegate=null;uuid;wrapperRef=null;camera;cameras=[];cameraRef=null;cameraManagerRef=null;rendererManager=null;runtimeAdapter=null;cameraDelegate;loadingDelegate;entityModelDelegate;childUpdateParams={};entityDelegate;constructor(e=[]){super(),this.world=null,this.scene=null,this.uuid=Ii(),this.cameraDelegate=new de(this),this.loadingDelegate=new ue,this.entityModelDelegate=new me,this.entityDelegate=new he(this.loadingDelegate,this.entityModelDelegate);let t=mt(e);this.camera=t.camera,this.cameras=t.cameras,this.entityDelegate.children=t.entities,t.asyncEntities.length&&this.entityDelegate.enqueue(...t.asyncEntities),this.state={...this.state,inputs:t.config.inputs,backgroundColor:t.config.backgroundColor,backgroundImage:t.config.backgroundImage,backgroundShader:t.config.backgroundShader,gravity:t.config.gravity,variables:t.config.variables,physicsRate:t.config.physicsRate,assetLoaders:t.config.assetLoaders,runtimeAdapter:t.config.runtimeAdapter,runtimeDebugBinding:t.config.runtimeDebugBinding,defaultLighting:t.config.defaultLighting,wasmRuntime:t.config.wasmRuntime,entities:[]},this.gravity=t.config.gravity??new pe(0,0,0),this.runtimeAdapter=t.config.runtimeAdapter??null,this.runtimeAdapter&&!this.state.runtimeDebugBinding&&(this.state.runtimeDebugBinding=Ue())}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof _t?e:new _t(e);We(i),Ne(t),He(this.state.variables??{})}resolveRenderer(e){return this.rendererManager?.renderer?this.rendererManager.renderer:e.renderer?e.renderer:null}async load(e,t,i){this.setState(),i&&(this.rendererManager=i),this.rendererManager&&(this.cameraManagerRef=this.cameraDelegate.buildCameraManager(t,...this.cameras));let r=this.cameraManagerRef?.primaryCamera??this.cameraDelegate.resolveCamera(t,this.camera);this.cameraRef=r,this.scene=new ae(e,r,this.state);let s=this.gravity??new pe(0,0,0),n=await W.loadPhysics(s);if(this.world=new W(n,this.state.physicsRate),this.state.wasmRuntime&&(this.wasmStage=await this.loadWasmStage(this.state.wasmRuntime)),this.scene.setup(),this.cameraManagerRef&&this.rendererManager){await this.scene.setupCameraManager(this.scene.scene,this.cameraManagerRef,this.rendererManager);let o=this.cameraManagerRef.primaryCamera;o&&this.rendererManager.setupPostProcessing(this.scene.scene,o.camera),this.rendererManager.startRenderLoop(()=>{this.cameraManagerRef?.render(this.scene.scene)})}else await this.scene.setupCamera(this.scene.scene,r);let l=this.resolveRenderer(r);await R.configureGLTFRuntime({renderer:l,...ie(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,o=>this.entityDelegate.handleLateModelReady(o)),this.instanceManager=new G,this.instanceManager.setScene(this.scene.scene),this.entityDelegate.attach({scene:this.scene,world:this.world,instanceManager:this.instanceManager,camera:r,runtimeAdapter:this.runtimeAdapter,wasmStage:this.wasmStage}),this.loadingDelegate.emitStart(),await this.entityDelegate.runEntityLoadGenerator(),this.entityDelegate.isLoaded=!0,this.runtimeAdapter&&await this.runtimeAdapter.init(this.runtimeContext()),this.loadingDelegate.emitComplete()}hasSetup=!1;_setup(e){if(!this.hasSetup){if(!this.scene||!this.world){this.logMissingEntities();return}this.debugDelegate=new ce(this),this.hasSetup=!0}}_update(e){let{delta:t}=e;if(!this.scene||!this.world){this.logMissingEntities();return}this.world.update(e);for(let i of this.entityDelegate.behaviorSystems)i.update(void 0,t);for(let i of this.entityDelegate.childrenMap.values()){let r=this.childUpdateParams;r.delta=e.delta,r.inputs=e.inputs,r.globals=e.globals,r.camera=e.camera,r.stage=e.stage,r.game=e.game,r.me=i,i.nodeUpdate(r);let s=i;s.transformStore&&je(s,s.transformStore),i.markedForRemoval&&this.entityDelegate.removeEntityByUuid(i.uuid)}Dt({_childrenMap:this.entityDelegate.childrenMap,_world:this.world}),this.wasmStage&&this.wasmStage.step(t),this.runtimeAdapter&&this.runtimeAdapter.step({...this.runtimeContext(),delta:t,inputs:e.inputs}),this.instanceManager?.update(),this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t),this.scene.update({delta:t}),this.scene.updateSkybox(t)}outOfLoop(){this.debugUpdate()}debugUpdate(){u.enabled&&this.debugDelegate?.update()}_destroy(e){this.runtimeAdapter?.destroy(this.scene&&this.world?this.runtimeContext():null),this.runtimeAdapter=null,this.wasmStage&&(this.wasmStage.dispose(),this.wasmStage=null),this.entityDelegate.destroyAll(),this.world?.destroy(),this.scene?.destroy(),this.debugDelegate?.dispose(),this.debugDelegate=null,this.entityModelDelegate.dispose(),this.instanceManager?.dispose(),this.instanceManager=null,this.rendererManager&&this.rendererManager.stopRenderLoop(),this.world=null,this.scene=null,this.cameraRef=null,this.cameraManagerRef=null,Ge(),Q(this)}async spawnEntity(e){return this.entityDelegate.spawnEntity(e)}buildEntityState(e){return this.entityDelegate.buildEntityState(e)}onEntityAdded(e,t){return this.entityDelegate.onEntityAdded(e,t)}onLoading(e){return this.loadingDelegate.onLoading(e)}registerSystem(e){return this.entityDelegate.registerSystem(e),this}removeEntityByUuid(e){return this.entityDelegate.removeEntityByUuid(e)}getEntityByName(e){return this.entityDelegate.getEntityByName(e)}enqueue(...e){this.entityDelegate.enqueue(...e)}logMissingEntities(){console.warn("Zylem world or scene is null")}runtimeContext(){return{scene:this.scene,world:this.world,camera:this.cameraRef,debug:this.state.runtimeDebugBinding}}async loadWasmStage(e){let t=typeof e.source=="function"?await e.source():e.source,i=e.options??{},r=i.initialCapacity??256,s=this.gravity instanceof pe?this.gravity:new pe(this.gravity?.x??0,this.gravity?.y??0,this.gravity?.z??0),n=i.gravity??[s.x,s.y,s.z];if(t instanceof ArrayBuffer)return ve(t,{initialCapacity:r,gravity:n});let l=await fetch(t);if(!l.ok)throw new Error(`Failed to fetch wasm-stage runtime: ${l.status} ${l.statusText}`);let o=await l.arrayBuffer();return ve(o,{initialCapacity:r,gravity:n})}addCamera(e,t){return this.cameraManagerRef?this.cameraManagerRef.addCamera(e,t):(console.warn("ZylemStage: CameraManager not available. Ensure stage is loaded with a RendererManager."),null)}removeCamera(e){return this.cameraManagerRef?.removeCamera(e)??!1}setActiveCamera(e){return this.cameraManagerRef?.setActiveCamera(e)??!1}getCamera(e){return this.cameraManagerRef?.getCamera(e)??null}resize(e,t){this.scene&&this.scene.updateRenderer(e,t)}};import{proxy as Vi}from"valtio/vanilla";import{Vector3 as Wi}from"three";var Ni={backgroundColor:U,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new Wi(0,0,0),variables:{}},x=Vi({...Ni});function At(a){let e=Hi(),t={};return typeof a[0]=="object"&&(t=a.shift()??{}),[{...e,...t},...a]}function Hi(){return{backgroundColor:x.backgroundColor,backgroundImage:x.backgroundImage??null,inputs:x.inputs?{...x.inputs}:void 0,gravity:x.gravity,variables:x.variables?{...x.variables}:void 0}}var Me=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new Oe;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];R.prepareGLTFRuntime(ie(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=Be(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){j.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new ge(r),this.wrappedStage.wrapperRef=this,this.pendingLoadingCallbacks.forEach(n=>{this.wrappedStage.onLoading(n)}),this.pendingLoadingCallbacks=[];let s=t instanceof b?t.cameraRef:t;await this.wrappedStage.load(e,s,i),this.wrappedStage.onEntityAdded(n=>{let l=this.wrappedStage.buildEntityState(n);j.entities=[...j.entities,l]},{replayExisting:!0}),this.applyLifecycleCallbacks()}applyLifecycleCallbacks(){this.wrappedStage&&(this.setupCallbacks.length>0&&(this.wrappedStage.setup=e=>{let t={...e,stage:this};this.setupCallbacks.forEach(i=>i(t))}),this.updateCallbacks.length>0&&(this.wrappedStage.update=e=>{let t={...e,stage:this};this.updateCallbacks.forEach(i=>i(t))}),this.destroyCallbacks.length>0&&(this.wrappedStage.destroy=e=>{let t={...e,stage:this};this.destroyCallbacks.forEach(i=>i(t))}))}async addEntities(e){this._pendingEntities.push(...e),this.wrappedStage&&this.wrappedStage.enqueue(...e)}add(...e){this.addToBlueprints(...e),this.addToStage(...e)}addToBlueprints(...e){this.wrappedStage||this.options.push(...e)}addToStage(...e){this.wrappedStage&&this.wrappedStage.enqueue(...e)}start(e){!this.wrappedStage||this.wrappedStage.hasSetup||this.wrappedStage.nodeSetup(e)}onUpdate(...e){return this.updateCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.update=t=>{let i={...t,stage:this};this.updateCallbacks.forEach(r=>r(i))}),this}onSetup(...e){return this.setupCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.setup=t=>{let i={...t,stage:this};this.setupCallbacks.forEach(r=>r(i))}),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.destroy=t=>{let i={...t,stage:this};this.destroyCallbacks.forEach(r=>r(i))}),this}onLoading(e){return this.wrappedStage?this.wrappedStage.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e)})}getEntityByName(e,t){return this.wrappedStage?.getEntityByName(e)}addCamera(e,t){let i=e instanceof b?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof b?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof b?this.wrappedStage?.setActiveCamera(e.cameraRef)??!1:this.wrappedStage?.setActiveCamera(e)??!1}getCamera(e){return this.wrappedStage?.getCamera(e)??null}dispatch(e,t){this.eventDelegate.dispatch(e,t),A.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function on(...a){let e=At(a);return new Me([...e])}export{Xi as a,K as b,p as c,D as d,Y as e,E as f,M as g,B as h,L as i,ee as j,b as k,ia as l,da as m,ai as n,Me as o,on as p};
@@ -1 +0,0 @@
1
- import{a as i,b as p}from"./chunk-4QLJUQSJ.js";import{c as s,d as c}from"./chunk-G2IIMSUH.js";import{Color as m,Vector3 as y}from"three";import{proxy as v,subscribe as S}from"valtio/vanilla";import{Color as k}from"three";import{Vector3 as b}from"@dimforge/rapier3d-compat";var d=new k("#0333EC");var E=new b(s.x,s.y,s.z),I=new b(c.x,c.y,c.z);var P={backgroundColor:d,backgroundImage:null,backgroundShader:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new y(0,0,0),variables:{},physicsRate:60,defaultLighting:!0,entities:[]},u=v({backgroundColor:new m(m.NAMES.cornflowerblue),backgroundImage:null,inputs:{p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},variables:{},gravity:new y(0,0,0),entities:[]}),Z=e=>{u.backgroundColor=e},A=e=>{u.backgroundImage=e};var O=e=>{u.variables={...e}},G=()=>{u.variables={}};var l=new Map;function g(e){let t=l.get(e);return t||(t=v({}),l.set(e,t)),t}function M(e,t,o){let n=g(e);p(n,t,o)}function z(e,t,o){let n=g(e),a=i(n,t);return a===void 0?(p(n,t,o),o):a}function N(e,t){let o=l.get(e);if(o)return i(o,t)}function _(e,t,o){let n=g(e),a=i(n,t);return S(n,()=>{let r=i(n,t);r!==a&&(a=r,o(r))})}function D(e,t,o){let n=g(e),a=t.map(r=>i(n,r));return S(n,()=>{let r=t.map(f=>i(n,f));r.some((f,x)=>f!==a[x])&&(a=r,o(r))})}function K(e){l.delete(e)}export{d as a,P as b,u as c,Z as d,A as e,O as f,G as g,M as h,z as i,N as j,_ as k,D as l,K as m};
@@ -1 +0,0 @@
1
- function s(r){let n=Object.keys(r).sort().reduce((t,e)=>(t[e]=r[e],t),{});return JSON.stringify(n)}function i(r){let n=0;for(let t=0;t<r.length;t++)n=Math.imul(31,n)+r.charCodeAt(t)|0;return n.toString(36)}export{s as a,i as b};
@@ -1 +0,0 @@
1
- import{p as e}from"./chunk-QEDQDR27.js";import"./chunk-A34ZG3L4.js";import"./chunk-CDPY4VOQ.js";import"./chunk-ONWXGBWB.js";import"./chunk-DR6XXZE7.js";import"./chunk-YHEWKN7N.js";import"./chunk-QXVH6POE.js";import"./chunk-73VZQZUL.js";import"./chunk-YHKXQ2ZN.js";import"./chunk-WKHW2QO2.js";import"./chunk-4QLJUQSJ.js";import"./chunk-G2IIMSUH.js";import"./chunk-FM5TBEPO.js";import"./chunk-XRP4JJXL.js";import"./chunk-MSC2BEO5.js";import{proxy as t}from"valtio/vanilla";var s=()=>({id:"zylem",globals:{},stages:[e()],debug:!1,time:0,input:void 0}),a=t({...s()});function o(){return{id:a.id??"zylem",globals:a.globals??{},stages:a.stages??[e()],debug:a.debug,time:a.time,input:a.input}}export{o as getGameDefaultConfig};