@zylem/game-lib 0.9.6 → 0.9.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions.d.ts +3 -3
- package/dist/api/game-lib.api.json +99183 -42019
- package/dist/api/game-lib.api.md +3822 -706
- package/dist/api/game-lib.d.ts +8703 -784
- package/dist/api/game-lib.typedoc.json +336362 -193038
- package/dist/audio.js +1 -1
- package/dist/behavior/action/fighting.d.ts +1 -0
- package/dist/behavior/action/fighting.js +1 -0
- package/dist/behavior/action/pinball.d.ts +1 -0
- package/dist/behavior/action/pinball.js +1 -0
- package/dist/behavior/action/platform.d.ts +1 -0
- package/dist/behavior/action/platform.js +1 -0
- package/dist/behavior/action/rhythm.d.ts +1 -0
- package/dist/behavior/action/rhythm.js +1 -0
- package/dist/behavior/action/shooter/first-person.d.ts +1 -0
- package/dist/behavior/action/shooter/first-person.js +1 -0
- package/dist/behavior/action/shooter/shoot-em-up.d.ts +1 -0
- package/dist/behavior/action/shooter/shoot-em-up.js +1 -0
- package/dist/behavior/action/shooter.d.ts +1 -0
- package/dist/behavior/action/shooter.js +1 -0
- package/dist/behavior/action/stealth.d.ts +1 -0
- package/dist/behavior/action/stealth.js +1 -0
- package/dist/behavior/action/survival.d.ts +1 -0
- package/dist/behavior/action/survival.js +1 -0
- package/dist/behavior/action-adventure.d.ts +1 -0
- package/dist/behavior/action-adventure.js +1 -0
- package/dist/behavior/action.d.ts +1 -0
- package/dist/behavior/action.js +1 -0
- package/dist/behavior/genre-map.d.ts +1 -0
- package/dist/behavior/genre-map.js +1 -0
- package/dist/behavior/mechanics.d.ts +1 -0
- package/dist/behavior/mechanics.js +1 -0
- package/dist/behavior/puzzle/physics.d.ts +1 -0
- package/dist/behavior/puzzle/physics.js +1 -0
- package/dist/behavior/puzzle/tile-matching.d.ts +1 -0
- package/dist/behavior/puzzle/tile-matching.js +1 -0
- package/dist/behavior/puzzle.d.ts +1 -0
- package/dist/behavior/puzzle.js +1 -0
- package/dist/behavior/role-playing/action-rpg.d.ts +1 -0
- package/dist/behavior/role-playing/action-rpg.js +1 -0
- package/dist/behavior/role-playing/monster-taming.d.ts +1 -0
- package/dist/behavior/role-playing/monster-taming.js +1 -0
- package/dist/behavior/role-playing/tactical-rpg.d.ts +1 -0
- package/dist/behavior/role-playing/tactical-rpg.js +1 -0
- package/dist/behavior/role-playing/turn-based.d.ts +1 -0
- package/dist/behavior/role-playing/turn-based.js +1 -0
- package/dist/behavior/role-playing.d.ts +1 -0
- package/dist/behavior/role-playing.js +1 -0
- package/dist/behavior/simulation/life.d.ts +1 -0
- package/dist/behavior/simulation/life.js +1 -0
- package/dist/behavior/simulation/vehicle/racing.d.ts +1 -0
- package/dist/behavior/simulation/vehicle/racing.js +1 -0
- package/dist/behavior/simulation/vehicle.d.ts +1 -0
- package/dist/behavior/simulation/vehicle.js +1 -0
- package/dist/behavior/simulation.d.ts +1 -0
- package/dist/behavior/simulation.js +1 -0
- package/dist/behavior/sports/golf.d.ts +1 -0
- package/dist/behavior/sports/golf.js +1 -0
- package/dist/behavior/sports/racing.d.ts +1 -0
- package/dist/behavior/sports/racing.js +1 -0
- package/dist/behavior/sports/racket.d.ts +1 -0
- package/dist/behavior/sports/racket.js +1 -0
- package/dist/behavior/sports/skate.d.ts +1 -0
- package/dist/behavior/sports/skate.js +1 -0
- package/dist/behavior/sports.d.ts +1 -0
- package/dist/behavior/sports.js +1 -0
- package/dist/behavior/strategy/real-time-tactics.d.ts +1 -0
- package/dist/behavior/strategy/real-time-tactics.js +1 -0
- package/dist/behavior/strategy/tower-defense.d.ts +1 -0
- package/dist/behavior/strategy/tower-defense.js +1 -0
- package/dist/behavior/strategy/turn-based-tactics.d.ts +1 -0
- package/dist/behavior/strategy/turn-based-tactics.js +1 -0
- package/dist/behavior/strategy.d.ts +1 -0
- package/dist/behavior/strategy.js +1 -0
- package/dist/behavior.d.ts +34 -0
- package/dist/bridge.d.ts +16 -4
- package/dist/bridge.js +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.js +1 -1
- package/dist/chunk-26EJFYDX.js +1 -0
- package/dist/chunk-2NO4YCLR.js +1 -0
- package/dist/chunk-3LXDHDJB.js +1 -0
- package/dist/chunk-4DAITCJS.js +1 -0
- package/dist/{chunk-Y23IJJPD.js → chunk-5NQGXW75.js} +1 -1
- package/dist/chunk-5WRFDAZN.js +1 -0
- package/dist/{chunk-OCQ7A5IK.js → chunk-B6GDESCB.js} +1 -1
- package/dist/chunk-BIZOIGCZ.js +1 -0
- package/dist/chunk-BJYXY2FB.js +1 -0
- package/dist/chunk-CI7A5N6G.js +1 -0
- package/dist/chunk-GQXYD2JG.js +1 -0
- package/dist/{chunk-KIFB427K.js → chunk-ICJ2E2OV.js} +1 -1
- package/dist/chunk-NPA6GUGE.js +24 -0
- package/dist/chunk-SIRFF4DY.js +1 -0
- package/dist/chunk-T6O2SGH5.js +1 -0
- package/dist/chunk-UNCP6V7I.js +1 -0
- package/dist/chunk-Y5IU6IA5.js +1 -0
- package/dist/chunk-YFXNZ2RS.js +1 -0
- package/dist/chunk-YW2GTHCV.js +19 -0
- package/dist/chunk-YWH5HQDT.js +1 -0
- package/dist/cinematics.d.ts +7 -6
- package/dist/core.d.ts +20 -17
- package/dist/core.js +1 -1
- package/dist/{debug-state-DhVkY2aM.d.ts → debug-state-JRneI6c2.d.ts} +2 -2
- package/dist/debug.d.ts +28 -126
- package/dist/debug.js +1 -1
- package/dist/{entity-DC0P747T.d.ts → entity-CY75JJSw.d.ts} +78 -4
- package/dist/{entity-type-map-B0S5cfv7.d.ts → entity-type-map-BMaPY8cd.d.ts} +2 -2
- package/dist/entity.d.ts +5 -5
- package/dist/entity.js +1 -1
- package/dist/fbx-loader-SDI6QYTS.js +1 -0
- package/dist/game-default-AF5QFXSD.js +1 -0
- package/dist/{game-mu6OSCrq.d.ts → game-uQd7k6-m.d.ts} +3 -3
- package/dist/gaussian-splat-loader-ACFJKCCL.js +1 -0
- package/dist/geometry-mesh-loader-XDJV77TU.js +1 -0
- package/dist/graphics.d.ts +3 -3
- package/dist/graphics.js +1 -1
- package/dist/{material-CxxAyJYp.d.ts → material-D1IVeQc5.d.ts} +48 -2
- package/dist/obj-loader-SI5RVY24.js +1 -0
- package/dist/placement-session-BNQoL7Jb.d.ts +82 -0
- package/dist/placement.d.ts +52 -0
- package/dist/placement.js +1 -0
- package/dist/public.d.ts +12 -10
- package/dist/public.js +1 -1
- package/dist/sog-loader-BZFMQ3ZB.js +1 -0
- package/dist/{stage-B_KdSEK6.d.ts → stage-Dez16Gxm.d.ts} +186 -16
- package/dist/transform-gizmo-DappLQ9w.d.ts +123 -0
- package/dist/usd-loader-PCBATNPM.js +1 -0
- package/dist/web-components.d.ts +9 -8
- package/dist/{zylem-camera-CWhIGXlW.d.ts → zylem-camera-BA3VPFlS.d.ts} +9 -0
- package/package.json +150 -7
- package/dist/chunk-47HAZZWF.js +0 -1
- package/dist/chunk-5V52N34T.js +0 -1
- package/dist/chunk-6FGXC4T6.js +0 -19
- package/dist/chunk-FUZDTRCU.js +0 -1
- package/dist/chunk-P6IOYQHU.js +0 -1
- package/dist/chunk-QB3NL7VQ.js +0 -1
- package/dist/chunk-RPMV7GDX.js +0 -24
- package/dist/chunk-VKWJHFUR.js +0 -1
- package/dist/chunk-VXE3CV3K.js +0 -1
- package/dist/chunk-YRHRMVHS.js +0 -1
- package/dist/game-default-VUMUMTXA.js +0 -1
- package/dist/level-types-D10LiOcn.d.ts +0 -91
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as ie,c as ne,d as oe}from"./chunk-UNCP6V7I.js";import{D as j,b as Q,q as ee,r as te}from"./chunk-CI7A5N6G.js";import{d as H,f as J}from"./chunk-YW2GTHCV.js";import{c as R,e as q,f as $,g as X}from"./chunk-T6O2SGH5.js";import{c as w,d as P,h as M,j as K}from"./chunk-7WRQ2UAN.js";import{Box3 as U,BufferAttribute as Ce,SkinnedMesh as De,MeshStandardMaterial as je,Group as Ee,Vector3 as x,Matrix4 as ce}from"three";var A=class{async loadFile(e,t){let i=await J.loadModel(e,t),o=i.animations??[];return{object:i.object,animation:o[0],animations:o,gltf:i.gltf}}};import{AnimationMixer as xe,Bone as se,LoopOnce as ve,LoopRepeat as Se}from"three";function Ae(n,e,t){let i=n.animations?.length?n.animations:n.animation?[n.animation]:[];if(i.length===0)return;let o=i.find(s=>s.name===e);return o||(i.length===1?i[0]:i[t]??i[0])}function Me(n){let e=n.lastIndexOf(".");return e>=0?n.slice(0,e):n}function re(n,e){if(!n?.name?.endsWith(".position"))return!1;let t=Me(n.name),i=e.get(t);return i instanceof se?!(i.parent instanceof se):/hips\.position$/i.test(n.name)||/root\.position$/i.test(n.name)}function Fe(n,e,t,i){for(let o of n.tracks){if(!re(o,e)||!o.values||o.values.length<3)continue;let s=o.values[0],r=i??o.values[1],a=o.values[2];for(let l=0;l<o.values.length;l+=3)o.values[l]=s,t&&(o.values[l+1]=r),o.values[l+2]=a}return n}function Oe(n,e){for(let t of n.tracks)if(re(t,e)&&!(!t.values||t.values.length<3))return t.values[1];return null}var E=class{constructor(e){this.target=e}_mixer=null;_actions={};_animations=[];_currentAction=null;_pauseAtPercentage=0;_isPaused=!1;_queuedKey=null;_fadeDuration=.5;_currentKey="";_assetLoader=new A;async loadAnimations(e,t={}){if(!e.length)return;let i=t.stripRootMotionY??!1,o=t.referenceRootY,s=t.referenceAnimationPath,r=await Promise.all(e.map(c=>this._assetLoader.loadFile(c.path))),a=new Map;this.target.traverse(c=>{c.name&&a.set(c.name,c)});let l=[],h=new Map;if(r.forEach((c,p)=>{let m=e[p].path,y=h.get(m)??0;h.set(m,y+1);let f=e[p].key||p.toString(),D=Ae(c,f,y);D&&l.push({key:f,clip:D.clone(),path:m})}),!l.length)return;let d=o;if(i&&d===void 0){let c=s?l.findIndex(m=>m.path===s):0,p=c>=0?[c,...l.map((m,y)=>y).filter(m=>m!==c)]:l.map((m,y)=>y);for(let m of p){let y=Oe(l[m].clip,a);if(y!==null){d=y;break}}}let u=l.map(({key:c,clip:p})=>({key:c,clip:Fe(p,a,i,d)}));this._animations=u.map(c=>c.clip),this._mixer=new xe(this.target),u.forEach(({key:c,clip:p})=>{this._actions[c]=this._mixer.clipAction(p)}),this.playAnimation({key:u[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:o=!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=o?100:i,this._isPaused=!1;let l=this._currentAction;this._pauseAtPercentage>0?(a.setLoop(ve,1/0),a.clampWhenFinished=!0):(a.setLoop(Se,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}};var ue={...te,material:{shader:H},animations:[],models:[],collisionShape:"capsule"};function F(n){return K(n.scale,P)}var Te=1e-4,ze=/foot$/i,Z=new x,L=new x,ae=new x,T=new x,le=new ce;function Le(n){let e=1/0,t=!1;return n.traverse(i=>{if(!i.isSkinnedMesh)return;let o=i,s=o.geometry,r=s.attributes.position,a=s.attributes.skinIndex,l=s.attributes.skinWeight,h=o.skeleton;if(!r||!a||!l||!h)return;t=!0,h.update(),o.updateMatrixWorld(!0);let d=h.boneMatrices;if(d)for(let u=0;u<r.count;u++){ae.fromBufferAttribute(r,u).applyMatrix4(o.bindMatrix),T.set(0,0,0);for(let c=0;c<4;c++){let p=l.getComponent(u,c);if(p===0)continue;let m=a.getComponent(u,c);le.fromArray(d,m*16),T.addScaledVector(L.copy(ae).applyMatrix4(le),p)}T.applyMatrix4(o.bindMatrixInverse).applyMatrix4(o.matrixWorld),e=Math.min(e,T.y)}}),!t||!Number.isFinite(e)?null:e}function Be(n,e){e.updateMatrixWorld(!0);let t=e.getWorldPosition(Z).y,i=Le(n)??1/0;if(n.traverse(o=>{!o.isBone||!ze.test(o.name)||(o.getWorldPosition(Z),i=Math.min(i,Z.y))}),Number.isFinite(i)||n.traverse(o=>{if(!o.isSkinnedMesh)return;let s=o;if(s.computeBoundingBox(),!s.boundingBox)return;let{min:r,max:a}=s.boundingBox;for(let l of[[r.x,r.y,r.z],[r.x,r.y,a.z],[r.x,a.y,r.z],[r.x,a.y,a.z],[a.x,r.y,r.z],[a.x,r.y,a.z],[a.x,a.y,r.z],[a.x,a.y,a.z]])L.set(l[0],l[1],l[2]),L.applyMatrix4(s.matrixWorld),i=Math.min(i,L.y)}),!Number.isFinite(i)){let o=new U().setFromObject(n);if(o.isEmpty())return null;i=o.min.y}return i-t}function we(n,e,t){return n.stripRootMotionY!==void 0?n.stripRootMotionY:!!(e&&t.some(i=>i===e))}function C(n){let e=n.collision?.position;return e?M(e,w):null}function V(n){return!!n.collision?.size}function Pe(n){n.hasWarnedDynamicTrimesh||(n.hasWarnedDynamicTrimesh=!0,console.warn(`Actor "${n.name||n.uuid}" requested collisionShape="trimesh" on a dynamic body; falling back to bounds.`))}function he(n,e,t){let i=n==="model"?"bounds":n??"capsule";return i==="trimesh"&&!e?(t?.(),"bounds"):i}function de(n,e){let t=n.x||.5,i=n.y||1,o=n.z||.5,s=Math.max(t,o)/2,r=i/2;return{shape:{type:"capsule",halfHeight:Math.max(0,r-s),radius:s},offset:[e.x,e.y,e.z],sensor:!1}}function S(n){let e=M(n.collision?.size??n.size,{x:.5,y:1,z:.5}),t=e.y||1,i=C(n);return de({x:e.x||.5,y:t,z:e.z||.5},i??{x:0,y:t/2,z:0})}function pe(n){let e=n.collision?.size;if(!e)return null;let t=M(e,w),i=t.x/2,o=t.y/2,s=t.z/2,r=C(n);return{shape:{type:"box",halfExtents:[i,o,s]},offset:[r?.x??0,r?.y??o,r?.z??0],sensor:!!n.collision?.sensor}}function me(n,e,t){let o=e.matrixWorld.clone().invert().multiply(n.matrixWorld);return new ce().makeScale(t.x,t.y,t.z).multiply(o)}function k(n,e,t){n.updateMatrixWorld(!0);let i=!1,o=new U;if(n.traverse(a=>{if(!a.isMesh)return;let l=a,h=$(l);if(!h)return;let d=null;if(l instanceof De?(l.computeBoundingBox(),d=l.boundingBox?.clone()??null):(h.computeBoundingBox(),d=h.boundingBox?.clone()??null),!d)return;let u=d.applyMatrix4(me(l,e,t));if(!i){o.copy(u),i=!0;return}o.union(u)}),!i||o.isEmpty())return null;let s=new x,r=new x;return o.getSize(s),o.getCenter(r),{size:s,center:r}}function Re(n,e,t){n.updateMatrixWorld(!0);let i=[],o=[],s=new U,r=new x,a=!1;if(n.traverse(h=>{if(!h.isMesh||R(h))return;let d=h,u=d.geometry;if(!u)return;let c=u.getAttribute("position");if(!(c instanceof Ce))return;let p=me(d,e,t),m=i.length/3;for(let f=0;f<c.count;f++)r.set(c.getX(f),c.getY(f),c.getZ(f)),r.applyMatrix4(p),i.push(r.x,r.y,r.z),s.expandByPoint(r);let y=u.getIndex();if(y)for(let f=0;f<y.count;f++)o.push(m+y.getX(f));else for(let f=0;f<c.count;f++)o.push(m+f);a=!0}),!a||i.length===0||o.length===0)return null;let l=new x;return s.getCenter(l),{vertices:new Float32Array(i),indices:new Uint32Array(o),center:l}}function fe(n,e,t){let i=pe(t);if(i)return i;if(!n||!e)return S(t);let o=k(n,e,F(t));if(!o)return S(t);let s=C(t);return{shape:{type:"box",halfExtents:[o.size.x/2,o.size.y/2,o.size.z/2]},offset:[s?.x??o.center.x,s?.y??o.center.y,s?.z??o.center.z],sensor:!1}}function ye(n,e,t,i,o){if(V(o)||!n||!e)return S(o);let s=k(n,e,F(o));if(!s)return S(o);let a=C(o);if(!a){let l=t&&i?k(t,i,F(o)):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 de({x:s.size.x,y:s.size.y,z:s.size.z},a)}function ge(n,e,t){let i=pe(t);if(i)return i;if(!n||!e)return S(t);let o=Re(n,e,F(t));if(!o)return S(t);let s=C(t);return{shape:{type:"trimesh",vertices:o.vertices,indices:o.indices},offset:s?[s.x-o.center.x,s.y-o.center.y,s.z-o.center.z]:[0,0,0],sensor:!1}}function z(n){n&&n.traverse(e=>{if(!e.isMesh)return;X(e);let t=e;t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(i=>i.dispose()):t.material?.dispose()})}var I=class extends ie{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=he(this.collisionShape,!!e.collision?.static);return t==="bounds"?fe(this.objectModel,this.objectModel,e):t==="trimesh"?ge(this.objectModel,this.objectModel,e):ye(this.collisionSource,this.collisionSource,this.objectModel,this.objectModel,e)}},N=class extends ne{createEntity(e){return new O(e)}},Ze=Symbol("Actor"),O=class extends j{static type=Ze;_object=null;_collisionSource=null;_animationDelegate=null;_modelFileNames=[];_assetLoader=new A;_loadGeneration=0;_loadStatus="idle";controlledRotation=!1;hasWarnedDynamicTrimesh=!1;constructor(e){super(),this.options=Q(ue,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=fe(this._object,this.group??this._object,this.options);else if(e==="trimesh")t=ge(this._object,this.group??this._object,this.options);else{let i=this.getRuntimeCollisionSource();t=ye(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=M(this.options.scale,P);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(o=>{if(!o.isMesh)return;t++;let s=o.geometry;s?.attributes.position&&(i+=s.attributes.position.count)}),e.meshCount=t,e.vertexCount=i}return e}getResolvedCollisionShape(){return he(this.options.collisionShape,!!this.options.collision?.static,()=>Pe(this))}requiresLoadedCollisionSource(){let e=this.getResolvedCollisionShape();return e==="bounds"||e==="trimesh"?!V(this.options):e==="capsule"?!V(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;z(this._object),t&&t!==this._object&&z(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})),o=t.file&&!t.reuseVisibleModel?this._assetLoader.loadFile(t.file,{clone:!0}):Promise.resolve(null);Promise.all([Promise.all(i),o]).then(([s,r])=>{if(e!==this._loadGeneration){s.forEach(l=>z(l.object??null)),r?.object&&z(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;if(this._object){this._object.traverse(c=>{c.isMesh&&a++}),this.group=new Ee,this.group.add(this._object),this.group.scale.copy(F(this.options)),ee(this),this.applyMaterialOverrides(),this._animationDelegate=new E(this._object);let l=this.options.animations||[],h=this.options.models?.[0],d=l.map(c=>c.path),u=we(this.options,h,d);l.length>0?this._animationDelegate.loadAnimations(l,{stripRootMotionY:u,referenceAnimationPath:h}).then(()=>{e===this._loadGeneration&&(this.alignVisualModelToGround(),this.dispatch("entity:animation:loaded",{entityId:this.uuid,animationCount:l.length}))}):this.alignVisualModelToGround()}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)}))})}alignVisualModelToGround(){if(!this._object||!this.group||q(this._object))return;this._animationDelegate?.update(0),this._object.updateMatrixWorld(!0);let e=Be(this._object,this.group);if(e===null||Math.abs(e)<Te)return;let t=this.group.scale.y||1;this._object.position.y-=e/t}applyMaterialOverrides(){let e=this.options.material;!e||!e.color&&!e.path&&e.opacity===void 0||this._object&&this._object.traverse(t=>{if(!t.isMesh||R(t))return;let i=t;i.material=Array.isArray(i.material)?i.material.map(o=>this.tintMaterial(o,e)):this.tintMaterial(i.material,e),e.color&&(i.castShadow=!0,i.receiveShadow=!0)})}tintMaterial(e,t){let i="color"in e,o=!!t.color,s=t.opacity!==void 0;if(!o&&!s)return e;if(o&&!i)return new je({color:t.color,emissiveIntensity:.5,lightMapIntensity:.5,fog:!0,opacity:t.opacity??1,transparent:s&&t.opacity<1});let r=e.clone();if(o&&"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 Ve(...n){return oe({args:n,defaultConfig:ue,EntityClass:O,BuilderClass:N,CollisionBuilderClass:I,entityType:O.type,cloneFactory:e=>Ve(e??{})})}import{Color as qe,Fog as $e,FogExp2 as Xe,Group as Je}from"three";import{Color as ke}from"three";import{Fn as _e,fog as Ie,positionWorld as be,positionView as Ne,uniform as g,float as Ue,vec3 as b,clamp as G,mix as _,max as Ge,smoothstep as We,floor as Ye,fract as W,dot as Ke}from"three/tsl";var B=class{values;u={time:g(0),heightEnabled:g(0),heightLevel:g(0),heightFalloff:g(0),noiseEnabled:g(0),noiseScale:g(0),noiseStrength:g(0),noiseSpeed:g(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=g(new ke(e.color)),o=Ne.z.negate(),s=t?this.exp2Factor(g(e.density),o):We(g(e.near),g(e.far),o),r=this.u.heightLevel.sub(be.y),a=G(r.mul(Ge(this.u.heightFalloff,0)),0,1),l=_(s,s.mul(a),this.u.heightEnabled),h=be.mul(this.u.noiseScale).add(b(this.u.time.mul(this.u.noiseSpeed),0,this.u.time.mul(this.u.noiseSpeed).mul(.5))),u=He(h).sub(.5).mul(2).mul(G(this.u.noiseStrength,0,1)),c=G(l.add(l.mul(u)),0,1),p=_(l,c,this.u.noiseEnabled);return Ie(i,p)}exp2Factor(e,t){return e.mul(e).mul(t).mul(t).negate().exp().oneMinus()}},v=_e(([n])=>{let e=W(n.mul(b(443.8975,397.2973,491.1871))),t=e.add(Ke(e,e.yzx.add(19.27)));return W(t.x.add(t.y).mul(t.z))}),He=_e(([n])=>{let e=Ye(n),t=W(n),i=t.mul(t).mul(Ue(3).sub(t.mul(2))),o=v(e.add(b(0,0,0))),s=v(e.add(b(1,0,0))),r=v(e.add(b(0,1,0))),a=v(e.add(b(1,1,0))),l=v(e.add(b(0,0,1))),h=v(e.add(b(1,0,1))),d=v(e.add(b(0,1,1))),u=v(e.add(b(1,1,1))),c=_(o,s,i.x),p=_(r,a,i.x),m=_(l,h,i.x),y=_(d,u,i.x),f=_(c,p,i.y),D=_(m,y,i.y);return _(f,D,i.z)});var Qe=Symbol("Fog"),et="#9aa3ad",tt=.015,it=10,nt=250,ot=5,st=.2,rt=.05,at=.15,lt=.1,Y=class extends j{static type=Qe;threeFog=null;attachedScene=null;patcher;patcherEnabled;constructor(e={}){super(),this.options={...e};let t=this.resolveUniformValues(this.options);this.patcher=new B(t),this.patcherEnabled=ut(this.options)}create(){return super.create(),this.threeFog=ct(this.options),this.group=new Je,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??ot,heightFalloff:t?.falloff??st,noiseEnabled:i?1:0,noiseScale:i?.scale??rt,noiseStrength:i?.strength??at,noiseSpeed:i?.speed??lt}}};function ct(n){let e=new qe(n.color??et);return(n.type??"linear")==="exp2"?new Xe(e,n.density??tt):new $e(e,n.start??it,n.end??nt)}function ut(n){let e=!!n.height?.enabled,t=!!n.noise;return e||t}function Kt(n={}){return new Y(n)}export{Ze as a,O as b,Ve as c,Qe as d,Y as e,Kt as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as R,b as H}from"./chunk-EVYHPR3J.js";import{p as G}from"./chunk-XRP4JJXL.js";import{d as F,k as L}from"./chunk-YW2GTHCV.js";import{a as D,b as M}from"./chunk-AIQ6IVT5.js";import{c as m,d as P,e as T,f as _,g as I,h as c,i as z,j as V}from"./chunk-7WRQ2UAN.js";import{StageBodyKind as j}from"@zylem/behaviors/core";import{Color as pe,Vector2 as N,Vector3 as U}from"three";function y(o){if(!o||typeof o!="object")return!1;let e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function l(o){if(o==null||typeof o=="function"||typeof o!="object")return o;if(o instanceof pe||o instanceof N||o instanceof U)return o.clone();if(o instanceof Float32Array)return new Float32Array(o);if(Array.isArray(o))return o.map(e=>l(e));if(y(o)){let e={};for(let[t,i]of Object.entries(o))t!=="_builders"&&(e[t]=l(i));return e}return o}function h(o,e){let t=l(o);if(!e)return t;if(!y(t)||!y(e))return l(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]=l(s);continue}if(r instanceof N&&T(s)){i[n]=z(s,r);continue}if(r instanceof U&&_(s)){i[n]=V(s,r);continue}if(y(r)&&y(s)){i[n]=h(r,s);continue}i[n]=l(s)}return i}function X(o){return o&&o.__kind==="collision"}function O(o){return o.cloneComponent()}function ue(o,e){let t={kind:o?j.Static:j.Dynamic,position:[0,0,0],gravityScale:e.gravityScale??1,canSleep:e.canSleep??!1,ccdEnabled:e.ccdEnabled??!0},i=R(e.lockRotations);i&&(t.lockRotation=i);let n=R(e.lockTranslations);return n&&(t.lockTranslation=n),t}function de(o,e){if(e.offset){let t=c(e.offset,m);o.offset=[t.x,t.y,t.z]}e.sensor&&(o.sensor=!0),e.collisionType&&(o.collisionGroups=H(e.collisionType,e.collisionFilter))}function u(o,e,t){return de(o,e),{__kind:"collision",bodyDesc:ue(e.static??!1,e),colliderDesc:o,cloneComponent:t}}function fe(o={}){let e=c(o.size,P),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}},i=l(o);return u(t,o,()=>fe(i))}function me(o={}){let e={shape:{type:"sphere",radius:o.radius??1}},t=l(o);return u(e,o,()=>me(t))}function he(o={}){let e=o.radius??1,i={shape:{type:"cone",halfHeight:(o.height??2)/2,radius:e}},n=l(o);return u(i,o,()=>he(n))}function ye(o={}){let e=o.radius??1,i={shape:{type:"cone",halfHeight:(o.height??2)/2,radius:e}},n=l(o);return u(i,o,()=>ye(n))}function be(o={}){let e=Math.max(o.radiusTop??1,o.radiusBottom??1),i={shape:{type:"cylinder",halfHeight:(o.height??2)/2,radius:e}},n=l(o);return u(i,o,()=>be(n))}function Ce(o={}){let e=o.radius??.5,i={shape:{type:"capsule",halfHeight:(o.length??1)/2,radius:e}},n=l(o);return u(i,o,()=>Ce(n))}function ge(o={}){let e=I(o.tile,{x:10,y:10}),t=o.subdivisions??10,i=(t+1)*(t+1),n=o.heightData??new Float32Array(i),s={shape:{type:"heightfield",rows:t,cols:t,heights:n,scale:[e.x,1,e.y]}},r={...o,static:o.static??!0},a=l(r);return u(s,r,()=>ge(a))}function ve(o={}){let e=c(o.size,P),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]},sensor:!0},i={...o,static:o.static??!0,sensor:!0},n=l(i);return u(t,i,()=>ve(n))}import{Mesh as se,ShaderMaterial as De,Group as Me}from"three";var Z=import.meta.env.VITE_DEBUG_FLAG==="true";import{nanoid as xe}from"nanoid";var d=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=xe()}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(Pe(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 Pe(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 Te}from"@zylem/behaviors/core";import{makeMoveable as Re}from"@zylem/behaviors/core";function Y(o){let e=Re(o);return G(e)}import{clearVelocityIntent as re}from"@zylem/behaviors/core";import{Color as ke,Vector3 as Be}from"three";import{Quaternion as Oe}from"three";var K=Symbol("explicitSpawnPosition"),C=new Oe;function W(o){return o.filter(e=>!(e instanceof d)).some(e=>e!=null&&typeof e=="object"&&"position"in e)}function $(o){o[K]=!0}function Ee(o){return o._spawnPositionExplicit?!0:o.options[K]===!0}function we(o){return o.options.hideUntilPositioned!==!1}function Q(o){return o._spawnPlacementPending===!0}function Se(o){return o._spawnPositionExplicit===!0||o._spawnPlacementReady===!0}function g(o){let e=o.group??o.mesh;if(e){if(o.physicsAttached&&o.body)try{let t=o.body.translation();e.position.set(t.x,t.y,t.z);return}catch{}if(o.wasmStageRef&&(o.runtimeHandle??-1)>=0){let t=o.wasmStageRef.getPose(o.runtimeHandle);if(t){e.position.set(t.position[0],t.position[1],t.position[2]);return}}if(o.options.position){let t=c(o.options.position,m);e.position.set(t.x,t.y,t.z)}}}function q(o){let e=o.group??o.mesh;if(!(!e||o.controlledRotation)){if(o.physicsAttached&&o.body)try{let t=o.body.rotation();C.set(t.x,t.y,t.z,t.w),e.setRotationFromQuaternion(C);return}catch{}if(o.wasmStageRef&&(o.runtimeHandle??-1)>=0){let t=o.wasmStageRef.getPose(o.runtimeHandle);t&&(C.set(t.rotation[0],t.rotation[1],t.rotation[2],t.rotation[3]),e.setRotationFromQuaternion(C))}}}function b(o,e){o.group&&(o.group.visible=e),o.mesh&&(o.mesh.visible=e)}function at(o){if(o._spawnInProgress=!0,o._spawnPlacementReady=!1,!we(o)){o._spawnPlacementPending=!1;return}o._spawnPositionExplicit=Ee(o),o._spawnPlacementPending=!0,b(o,!1)}function lt(o){o._spawnInProgress=!1}function J(o){o._spawnPlacementReady=!0}function E(o){if(o._spawnPlacementPending){if(g(o),o._spawnPlacementPending=!1,o.options.visible===!1){b(o,!1);return}b(o,!0)}}function ct(o){!Q(o)||o.options.hideUntilPositioned===!0&&!Se(o)||E(o)}function ee(o){g(o),o._spawnPlacementPending=!1,b(o,!0)}function pt(o){Q(o)&&b(o,!1)}var te={position:new Be(0,0,0),material:{color:new ke("#ffffff"),shader:F},collision:{static:!1}};function bt(o,e){let t=o.filter(n=>!(n instanceof d)),i=h(e);for(let n of t)i=h(i,n);return W(o)&&$(i),i}import{Ray as Ae,Vector3 as x}from"three";var p=new WeakMap,S=new Set,k=new Set;function Rt(o){return S.add(o),()=>S.delete(o)}function Ot(o){return k.add(o),()=>k.delete(o)}function Et(o,e){for(let t of k)t(o,e)}function B(o){for(let e of S)e(o)}function wt(o){return p.get(o)??null}function St(o){return p.has(o)}function oe(o,e){let t=p.get(o);p.set(o,{role:"hover",handlers:{...t?.handlers,...e}}),B(o)}function ie(o,e){let t=p.get(o);p.set(o,{role:"droppable",handlers:{...t?.handlers,...e}}),B(o)}function kt(o,e){let t=p.get(o);t&&(t.handlers={...t.handlers,...e})}function ne(o,e){let t=p.get(o);t&&(p.set(e,{role:t.role,handlers:{...t.handlers}}),B(e))}var w=new Ae,v=new x;function Bt(o,e){if(e.isEmpty()||(v.copy(o.direction),v.lengthSq()<1e-12))return null;v.normalize(),w.set(o.origin,v);let t=w.intersectBox(e,new x);return t?{distance:w.origin.distanceTo(t),point:t}:null}function At(o,e){let t=o.group??o.mesh;if(t?.parent&&(e.setFromObject(t),!e.isEmpty()))return e;let i=c(o.options?.size,{x:1,y:1,z:1}),s=(o.getPose?.()??null)?.position??c(o.options?.position,{x:0,y:0,z:0});return e.setFromCenterAndSize(new x(s.x,s.y,s.z),new x(i.x,i.y,i.z)),e.isEmpty()?null:e}function _e(o){return o!=null&&typeof o=="object"}function ae(o){return{phase:o?.phase??"stay",cooldownMs:o?.cooldownMs}}function Ie(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var A=class extends d{group;mesh;materials;bodyDesc=null;body=null;physicsAttached=!1;physicsWorldRef=null;colliderDesc;custom={};colliderBaseline=null;colliderScaleDirty=!1;colliderDescs=[];compoundMeshes=[];debugInfo={};debugMaterial;collisionDelegate={collision:[],cooldowns:new Map,nextId:0};collisionType;packKey=null;bundleKey=null;instanceId=-1;isInstanced=!1;isBundled=!1;runtimeHandle=-1;runtimeAttached=!1;wasmStageRef=null;eventDelegate=new D;behaviorRefs=[];cloneFactory=null;trackAddedComponents=!1;trackedComponents=[];transformStore;_scale={x:1,y:1,z:1};_spawnPlacementPending=!1;_spawnPositionExplicit=!1;_spawnPlacementReady=!1;_spawnInProgress=!1;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=Te(),Y(this),this.wrapSpawnPlacementMutators()}wrapSpawnPlacementMutators(){let e=()=>{J(this),!this._spawnInProgress&&(g(this),E(this))},t=r=>(a,f,ce)=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(r(a,f,ce),e())},i=r=>a=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(r(a),e())};this.setPosition=t(this.setPosition.bind(this)),this.setPositionX=i(this.setPositionX.bind(this)),this.setPositionY=i(this.setPositionY.bind(this)),this.setPositionZ=i(this.setPositionZ.bind(this));let n=()=>{this._spawnInProgress||q(this)},s=this.setPose.bind(this);this.setPose=r=>{let a=s(r);return a&&(r.position!=null&&e(),r.rotation!=null&&n(),a)}}reveal(){this.options.visible=!0,ee(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=c(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&&this.body?.markPoseDiscontinuity(),i}let t=this.body;if(!t)return!1;if(e.position){let i=c(e.position);t.setTranslation({x:i.x,y:i.y,z:i.z},!0)}return e.rotation&&t.setRotation(e.rotation,!0),!0}getScale(){return{...this._scale}}setScale(e,t,i){this._scale={x:e,y:t,z:i},(this.group??this.mesh)?.scale.set(e,t,i),this.colliderScaleDirty=!0}add(...e){for(let t of e)t instanceof se?(this.addMeshComponent(t),this.trackComponent(t)):X(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 Me,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=c(this.options?.position,m);this.bodyDesc.position=[t.x,t.y,t.z]}}trackComponent(e){if(this.trackAddedComponents){if(e instanceof se){this.trackedComponents.push({kind:"mesh",component:le(e)});return}this.trackedComponents.push({kind:"collision",component:O(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,re(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,re(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(h(this.options,e)),i=this.copyBehaviorRefsTo(t),n=r=>Ve(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(le(r.component));continue}t.add(O(r.component))}return this.cloneChildrenInto(t),ne(this,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||_e(e[1]))){let n=e[0];if(!n)return this;let s=e[1];return t.push({id:i,callback:n,options:ae(s)}),i+=1,this.collisionDelegate.collision=t,this.collisionDelegate.nextId=i,this}for(let n of e)t.push({id:i,callback:n,options:ae()}),i+=1;return this.collisionDelegate.collision=t,this.collisionDelegate.nextId=i,this}hoverArea(e){return oe(this,e),this}droppableArea(e){return ie(this,e),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}getBehaviorRef(e){return this.behaviorRefs.find(t=>t.descriptor.key===e.key)??null}hasBehavior(e){return this.getBehaviorRef(e)!==null}removeBehavior(e){let t="descriptor"in e?this.behaviorRefs.indexOf(e):this.behaviorRefs.findIndex(n=>n.descriptor.key===e.key);if(t===-1)return null;let[i]=this.behaviorRefs.splice(t,1);return i??null}restoreBehaviorRef(e){this.behaviorRefs.includes(e)||this.behaviorRefs.push(e)}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,l(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:Ie()}){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}`,f=n.get(a);if(f!=null&&i.nowMs-f<r)continue;n.set(a,i.nowMs)}s.callback({entity:this,other:e,globals:t})}}hasMaterial(){return this.mesh!==void 0||this.compoundMeshes.length>0}getMaterials(){return this.materials?[...this.materials]:[]}setMaterial(e,t={}){if(!this.hasMaterial())return null;let i=new L,n=this.constructor.type??Symbol.for("zylem:entity");return i.build(e,n),this.replaceMaterials(i.materials,t)}replaceMaterials(e,t={}){if(!this.hasMaterial()||e.length===0)return null;let{disposePrevious:i=!0}=t,n=this.materials?[...this.materials]:[],s=r=>{Array.isArray(r.material)?r.material=r.material.map((a,f)=>e[f%e.length]):r.material=e[0]};this.mesh&&s(this.mesh);for(let r of this.compoundMeshes)s(r);if(this.materials=[...e],i)for(let r of n)e.includes(r)||r.dispose();return n}updateMaterials(e){if(this.materials?.length)for(let t of this.materials)t instanceof De&&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),M.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}disposeEvents(){this.eventDelegate.dispose()}};function ze(o){let e=new A;return e.options={...te,...o},Fe(e,t=>ze(t??{}))}function le(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 Ve(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 Fe(o,e){return o.finalizeCloneSupport(e),o}export{d as a,h as b,fe as c,me as d,he as e,ye as f,be as g,Ce as h,ge as i,ve as j,Q as k,g as l,at as m,lt as n,ct as o,ee as p,pt as q,te as r,bt as s,Rt as t,Ot as u,Et as v,wt as w,St as x,oe as y,ie as z,kt as A,Bt as B,At as C,A as D,ze as E,Fe as F};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as p}from"./chunk-2NO4YCLR.js";import{a as m,b as l,h as c,k as u}from"./chunk-T6O2SGH5.js";import{GaussianSplat as G}from"three/addons/objects/GaussianSplat.js";import{GaussianSplatPLYLoader as L}from"three/addons/loaders/GaussianSplatPLYLoader.js";import{KSPLATLoader as w}from"three/addons/loaders/KSPLATLoader.js";import{SPLATLoader as A}from"three/addons/loaders/SPLATLoader.js";import{SPZLoader as P}from"three/addons/loaders/SPZLoader.js";function S(r){return r.getAttribute("position")?.count??0}function B(r,e){let t=S(r);if(t>1e7)throw r.dispose(),new Error(`Gaussian splat has ${t} splats, which exceeds the limit of ${1e7}.`);let s=new G(r);return s.userData[m]=l,e?.splatFrame==="y-down"&&(s.rotation.x=Math.PI),{object:s,animations:[]}}async function h(r){if(!r)throw new Error("Gaussian splat parser returned no geometry.");return r instanceof Promise,r}async function E(r,e){switch(r){case"spz":{let t=new P;return new Promise((s,n)=>{let a=!1,i=o=>{a||(a=!0,s(o))},f=o=>{a||(a=!0,n(o instanceof Error?o:new Error(String(o))))};try{let o=t.parse(e,i,f);o&&typeof o.then=="function"?o.then(i,f):o&&i(o)}catch(o){f(o)}})}case"splat":return new A().parse(e);case"ksplat":return h(new w().parse(e));case"ply":return new L().parse(e);default:throw new Error(`Unsupported Gaussian splat container: ${r}`)}}var y=class{isSupported(e){let t=u(e);return t==="spz"||t==="splat"||t==="ksplat"||t==="ply"}async load(e,t){let s=await p(e,t),n=u(e),a=n==="ply"?"ply":n;return this.parse(a,s,t)}async parse(e,t,s){let n=await E(e,t);return B(n,s)}clone(e){return{object:c(e.object),animations:[]}}};export{B as a,E as b,y as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as c,o as b}from"./chunk-2HSR5XDQ.js";import{B as y,E as g,L as x,O as z,j as s,m as p,p as d,s as h,v as u,y as m}from"./chunk-
|
|
1
|
+
import{b as c,o as b}from"./chunk-2HSR5XDQ.js";import{B as y,E as g,L as x,O as z,j as s,m as p,p as d,s as h,v as u,y as m}from"./chunk-YWH5HQDT.js";import{g as f}from"./chunk-UNCP6V7I.js";import{a as w}from"./chunk-VUJXR5K5.js";import{Vector3 as S}from"three";var C='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">';function t(r){return`${C}${r}</svg>`}var i={box:t('<path d="M12 2.5 21 7v10l-9 4.5L3 17V7z"/><path d="M3 7l9 4.5L21 7"/><path d="M12 11.5v10"/>'),sphere:t('<circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="9" ry="3.5"/>'),cone:t('<path d="M12 3 20 18H4z"/><ellipse cx="12" cy="18" rx="8" ry="3"/>'),pyramid:t('<path d="M12 3 21 19H3z"/><path d="M12 3v16"/><path d="M3 19l9-5 9 5"/>'),cylinder:t('<ellipse cx="12" cy="6" rx="7" ry="3"/><path d="M5 6v12"/><path d="M19 6v12"/><ellipse cx="12" cy="18" rx="7" ry="3"/>'),pill:t('<rect x="7" y="3" width="10" height="18" rx="5"/><path d="M7 12h10"/>'),disk:t('<ellipse cx="12" cy="12" rx="9" ry="4"/><ellipse cx="12" cy="12" rx="3" ry="1.3"/>'),plane:t('<path d="M2 17 12 11l10 6-10 5z"/><path d="M12 11V4"/>'),zone:t('<rect x="3.5" y="3.5" width="17" height="17" rx="2" stroke-dasharray="3 2.5"/>'),rect:t('<rect x="3.5" y="6" width="17" height="12" rx="1.5"/>'),light:t('<circle cx="12" cy="9" r="4.5"/><path d="M12 2v1.5"/><path d="M12 14.5V22"/><path d="M4.9 4.9 6 6"/><path d="M19.1 4.9 18 6"/><path d="M2 9h1.5"/><path d="M20.5 9H22"/>')};function n(r,e,v,k,M,P){return{id:r,label:e,description:v,icon:k,group:"Shapes",tags:P,defaultProps:{size:{x:1,y:1,z:1}},create:M}}function o(r){let e=r.size;return new S(e?.x??1,e?.y??1,e?.z??1)}var T=[n("box","Box","Cuboid mesh with a matching box collider.",i.box,({position:r,props:e})=>s({position:r,size:o(e),...e}),["cube","block","platform","wall"]),n("sphere","Sphere","Ball mesh with a sphere collider.",i.sphere,({position:r,props:e})=>p({position:r,size:o(e),...e}),["ball","orb","round"]),n("cone","Cone","Cone mesh with a cone collider.",i.cone,({position:r,props:e})=>d({position:r,size:o(e),...e}),["spike","point"]),n("pyramid","Pyramid","Four-sided pyramid mesh and collider.",i.pyramid,({position:r,props:e})=>h({position:r,size:o(e),...e}),["tetra","spike"]),n("cylinder","Cylinder","Cylinder mesh with a matching collider.",i.cylinder,({position:r,props:e})=>u({position:r,size:o(e),...e}),["tube","pillar","column"]),n("pill","Pill","Capsule mesh with a capsule collider.",i.pill,({position:r,props:e})=>m({position:r,size:o(e),...e}),["capsule","character"]),n("disk","Disk","Flat cylinder, useful for pucks and platforms.",i.disk,({position:r,props:e})=>y({position:r,size:o(e),...e}),["puck","coin","circle"]),{id:"plane",label:"Plane",description:"Static ground plane with a tiled surface.",icon:i.plane,group:"Scene",tags:["ground","floor","terrain"],defaultProps:{size:{x:10,y:1,z:10}},create:({position:r,props:e})=>g({position:r,size:o(e),...e})},{id:"zone",label:"Zone",description:"Invisible sensor volume that reports overlaps.",icon:i.zone,group:"Scene",tags:["trigger","sensor","area"],defaultProps:{size:{x:2,y:2,z:2}},create:({position:r,props:e})=>f({position:r,size:o(e),...e})},{id:"rect",label:"Rect",description:"Flat rectangle for 2D scenes and UI panels.",icon:i.rect,group:"Scene",tags:["quad","panel","2d"],defaultProps:{size:{x:1,y:1,z:1}},create:({position:r,props:e})=>x({position:r,size:o(e),...e})},{id:"light",label:"Point Light",description:"Point light placed at the click position.",icon:i.light,group:"Scene",tags:["lamp","illumination"],defaultProps:{intensity:1},create:({position:r,props:e})=>z({type:"point",position:r,...e})}],a=null;function Y(){return a||(a=c(T),a)}var l=null;function j(){return l||(l=b("behavior",w),l)}export{T as a,Y as b,j as c};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import{b as Ne,d as H,k as D,y as J,z as F}from"./chunk-BIZOIGCZ.js";import{e as ce,g as me,h as he,i as Ye,j as Ze,k as Ke,l as ge,n as Je}from"./chunk-26EJFYDX.js";import{g as _e}from"./chunk-PCFF4LLO.js";import{l as L}from"./chunk-UG22Z42P.js";import{b as x}from"./chunk-B6GDESCB.js";import{d as v,g as Ue,h as de}from"./chunk-UM5VNQPY.js";import{b as je,c as Qe}from"./chunk-ICJ2E2OV.js";import{c as K,e as $e,f as We}from"./chunk-2HSR5XDQ.js";import{t as tt}from"./chunk-2XMG3NJS.js";import{b as et}from"./chunk-7GYFZKK7.js";import{c as k}from"./chunk-D2PATZCC.js";import{k as nt}from"./chunk-3LXDHDJB.js";import{D as Se,a as ve}from"./chunk-CI7A5N6G.js";import{k as qe}from"./chunk-YW2GTHCV.js";import{a as Xe,b as E}from"./chunk-AIQ6IVT5.js";import{c as Ae,d as V,e as ze,h as Ve,i as Oe,j as He,k as pe,l as O,m as Fe}from"./chunk-4QLJUQSJ.js";import{c as fe,h as ye,j as be}from"./chunk-7WRQ2UAN.js";function vt(){return{pressed:!1,released:!1,held:0}}function St(){return{value:0,held:0}}function $(a){let e=new Map;if(!a)return e;for(let[t,n]of Object.entries(a)){if(!n||n.length===0)continue;let i=[];for(let o of n){let[s,r]=(o||"").split(".");if(!s||!r)continue;let l=s.toLowerCase(),p=r.toLowerCase();if(l==="buttons"){let u={a:"A",b:"B",x:"X",y:"Y",start:"Start",select:"Select",l:"L",r:"R"}[p];u&&i.push({category:"buttons",property:u})}else if(l==="directions"){let u={up:"Up",down:"Down",left:"Left",right:"Right"}[p];u&&i.push({category:"directions",property:u})}else if(l==="shoulders"){let u={ltrigger:"LTrigger",rtrigger:"RTrigger"}[p];u&&i.push({category:"shoulders",property:u})}else if(l==="axes"){let u={left:{property:"Horizontal",direction:-1},right:{property:"Horizontal",direction:1},up:{property:"Vertical",direction:-1},down:{property:"Vertical",direction:1},secondaryleft:{property:"SecondaryHorizontal",direction:-1},secondaryright:{property:"SecondaryHorizontal",direction:1},secondaryup:{property:"SecondaryVertical",direction:-1},secondarydown:{property:"SecondaryVertical",direction:1}}[p];u&&i.push({category:"axes",property:u.property,axisDirection:u.direction})}}i.length>0&&e.set(t,i)}return e}function m(a,e){return!a&&!e?vt():a?e?{pressed:a.pressed||e.pressed,released:a.released||e.released,held:a.held+e.held}:{...a}:{...e}}function w(a,e){return!a&&!e?St():a?e?{value:a.value+e.value,held:a.held+e.held}:{...a}:{...e}}var A=class{keyStates=new Map;keyButtonStates=new Map;analogStates=new Map;compiledMapping;includeDefaultBase=!0;onKeyDown=({key:e})=>this.keyStates.set(e,!0);onKeyUp=({key:e})=>this.keyStates.set(e,!1);constructor(e,t){this.includeDefaultBase=t?.includeDefaultBase??!0,this.compiledMapping=$(e??null),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}dispose(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),this.keyStates.clear(),this.keyButtonStates.clear(),this.analogStates.clear()}isKeyPressed(e){return this.keyStates.get(e)||!1}handleButtonState(e,t){let n=this.keyButtonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.keyButtonStates.set(e,n));let i=this.isKeyPressed(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleAnalogState(e,t,n){let i=`${e}:${t}`,o=this.analogStates.get(i);return o||(o={value:0,held:0},this.analogStates.set(i,o)),o.value=this.getAxisValue(e,t),o.held=o.value!==0?o.held+n:0,o}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map;for(let[i,o]of this.compiledMapping.entries()){let s=null;for(let r of o)if(r.category==="axes")n.has(r.property)||n.set(r.property,0),this.isKeyPressed(i)&&n.set(r.property,n.get(r.property)+r.axisDirection);else{s||(s=this.handleButtonState(i,t));let l=e[r.category]??={};l[r.property]=m(l[r.property],s)}}if(n.size>0){e.axes||(e.axes={});for(let[i,o]of n.entries()){let s=`custom:${i}`,r=this.analogStates.get(s);r||(r={value:0,held:0},this.analogStates.set(s,r)),r.value=o,r.held=o!==0?r.held+t:0,e.axes[i]=w(e.axes[i],r)}}return e}getInput(e){let t={};return this.includeDefaultBase&&(t.buttons={A:this.handleButtonState("z",e),B:this.handleButtonState("x",e),X:this.handleButtonState("a",e),Y:this.handleButtonState("s",e),Start:this.handleButtonState(" ",e),Select:this.handleButtonState("Enter",e),L:this.handleButtonState("q",e),R:this.handleButtonState("e",e)},t.directions={Up:this.handleButtonState("ArrowUp",e),Down:this.handleButtonState("ArrowDown",e),Left:this.handleButtonState("ArrowLeft",e),Right:this.handleButtonState("ArrowRight",e)},t.shoulders={LTrigger:this.handleButtonState("Q",e),RTrigger:this.handleButtonState("E",e)}),this.applyCustomMapping(t,e)}getName(){return"keyboard"}getAxisValue(e,t){return(this.isKeyPressed(t)?1:0)-(this.isKeyPressed(e)?1:0)}isConnected(){return!0}};var W=class{gamepadIndex;connected=!1;buttonStates={};analogStates={};onConnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!0)};onDisconnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!1)};constructor(e){this.gamepadIndex=e,window.addEventListener("gamepadconnected",this.onConnected),window.addEventListener("gamepaddisconnected",this.onDisconnected)}dispose(){window.removeEventListener("gamepadconnected",this.onConnected),window.removeEventListener("gamepaddisconnected",this.onDisconnected),this.buttonStates={},this.analogStates={}}handleButtonState(e,t,n){let i=this.buttonStates[e];i||(i={pressed:!1,released:!1,held:0},this.buttonStates[e]=i);let o=t.buttons[e].pressed;return i.pressed=o&&i.held===0,i.released=!o&&i.held>0,i.held=o?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates[e];return i||(i={value:0,held:0},this.analogStates[e]=i),i.value=t.axes[e],i.held=i.value!==0?i.held+n:0,i}getInput(e){let t=navigator.getGamepads()[this.gamepadIndex];return t?{buttons:{A:this.handleButtonState(0,t,e),B:this.handleButtonState(1,t,e),X:this.handleButtonState(2,t,e),Y:this.handleButtonState(3,t,e),Start:this.handleButtonState(9,t,e),Select:this.handleButtonState(8,t,e),L:this.handleButtonState(4,t,e),R:this.handleButtonState(5,t,e)},directions:{Up:this.handleButtonState(12,t,e),Down:this.handleButtonState(13,t,e),Left:this.handleButtonState(14,t,e),Right:this.handleButtonState(15,t,e)},axes:{Horizontal:this.handleAnalogState(0,t,e),Vertical:this.handleAnalogState(1,t,e),SecondaryHorizontal:this.handleAnalogState(2,t,e),SecondaryVertical:this.handleAnalogState(3,t,e)},shoulders:{LTrigger:this.handleButtonState(6,t,e),RTrigger:this.handleButtonState(7,t,e)}}:{}}getName(){return`gamepad-${this.gamepadIndex+1}`}isConnected(){return this.connected}};import{subscribe as wt}from"valtio/vanilla";var Ct=.002;function q(a,e,t){return Math.max(e,Math.min(t,a))}function xt(a){if(a instanceof HTMLCanvasElement)return a;let e=a.querySelector("canvas");if(e instanceof HTMLCanvasElement)return e;for(let t of a.querySelectorAll("*")){let n=t.shadowRoot;if(!n)continue;let i=n.querySelector("canvas");if(i instanceof HTMLCanvasElement)return i}return null}var U=class{buttonStates=new Map;analogStates=new Map;compiledMapping;movementX=0;movementY=0;pointerX=.5;pointerY=.5;pointerCenterX=0;pointerCenterY=0;mouseButtonDown=new Set;sensitivity;usePointerLock;lookMode;isLocked=!1;targetElement;debugUnsubscribe=null;updatePointerPosition(e,t){this.pointerX=e/window.innerWidth,this.pointerY=t/window.innerHeight;let n=xt(this.targetElement);if(n){let i=n.getBoundingClientRect();if(i.width>0&&i.height>0){let o=i.left+i.width/2,s=i.top+i.height/2;this.pointerCenterX=q((e-o)/(i.width/2),-1,1),this.pointerCenterY=q((t-s)/(i.height/2),-1,1);return}}this.pointerCenterX=q((this.pointerX-.5)*2,-1,1),this.pointerCenterY=q((this.pointerY-.5)*2,-1,1)}onMouseMove=e=>{this.updatePointerPosition(e.clientX,e.clientY),!(v.enabled||this.lookMode==="screenCenter")&&(this.movementX+=e.movementX,this.movementY+=e.movementY)};onMouseDown=e=>{let t=e.target;t instanceof HTMLCanvasElement&&this.targetElement.contains(t)&&(this.mouseButtonDown.add(e.button),this.usePointerLock&&!this.isLocked&&!v.enabled&&this.targetElement.requestPointerLock())};onMouseUp=e=>{this.mouseButtonDown.delete(e.button)};onContextMenu=e=>{e.preventDefault()};onPointerLockChange=()=>{this.isLocked=document.pointerLockElement===this.targetElement};constructor(e,t){this.sensitivity=e?.sensitivity??Ct,this.lookMode=e?.lookMode??"delta",this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=$(e?.mapping??null),this.targetElement=t??document.body,window.addEventListener("mousemove",this.onMouseMove),this.targetElement.addEventListener("mousedown",this.onMouseDown),this.targetElement.addEventListener("mouseup",this.onMouseUp),this.targetElement.addEventListener("contextmenu",this.onContextMenu),this.usePointerLock&&(document.addEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe=wt(v,()=>{v.enabled&&document.pointerLockElement===this.targetElement&&document.exitPointerLock()}))}dispose(){window.removeEventListener("mousemove",this.onMouseMove),this.targetElement.removeEventListener("mousedown",this.onMouseDown),this.targetElement.removeEventListener("mouseup",this.onMouseUp),this.targetElement.removeEventListener("contextmenu",this.onContextMenu),document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe?.(),this.debugUnsubscribe=null,this.isLocked&&document.exitPointerLock(),this.buttonStates.clear(),this.analogStates.clear(),this.mouseButtonDown.clear(),this.movementX=0,this.movementY=0}handleMouseButton(e,t){let n=this.buttonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.buttonStates.set(e,n));let i=this.mouseButtonDown.has(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleMovementAxis(e,t){let n=this.analogStates.get(e);n||(n={value:0,held:0},this.analogStates.set(e,n));let i=e==="x"?this.movementX:this.movementY;return n.value=Math.max(-1,Math.min(1,i*this.sensitivity)),n.held=n.value!==0?n.held+t:0,n}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map,i={leftbutton:()=>this.handleMouseButton(0,t),rightbutton:()=>this.handleMouseButton(2,t),middlebutton:()=>this.handleMouseButton(1,t)};for(let[o,s]of this.compiledMapping.entries()){let r=o.toLowerCase();for(let l of s)if(l.category==="axes")n.has(l.property)||n.set(l.property,0),r==="movex"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementX*this.sensitivity))*l.axisDirection):r==="movey"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementY*this.sensitivity))*l.axisDirection):r in i&&this.mouseButtonDown.has(this.buttonIndexForAction(r))&&n.set(l.property,n.get(l.property)+l.axisDirection);else{let p=i[r];if(p){let g=p();if(g){let u=e[l.category]??={};u[l.property]=m(u[l.property],g)}}}}if(n.size>0){e.axes||(e.axes={});for(let[o,s]of n.entries()){let r=`custom:${o}`,l=this.analogStates.get(r);l||(l={value:0,held:0},this.analogStates.set(r,l)),l.value=Math.max(-1,Math.min(1,s)),l.held=s!==0?l.held+t:0,e.axes[o]=w(e.axes[o],l)}}return e}buttonIndexForAction(e){switch(e){case"leftbutton":return 0;case"middlebutton":return 1;case"rightbutton":return 2;default:return-1}}getInput(e){v.enabled&&(this.movementX=0,this.movementY=0);let t={value:0,held:0},n=this.lookMode==="delta",i={axes:{Horizontal:t,Vertical:t,SecondaryHorizontal:n?this.handleMovementAxis("x",e):t,SecondaryVertical:n?this.handleMovementAxis("y",e):t},shoulders:{LTrigger:this.handleMouseButton(0,e),RTrigger:this.handleMouseButton(2,e)},pointer:{x:this.pointerX,y:this.pointerY,centerX:this.pointerCenterX,centerY:this.pointerCenterY}};return this.movementX=0,this.movementY=0,this.applyCustomMapping(i,e)}getName(){return"mouse"}isConnected(){return!0}};function N(a={}){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent,t=/android/i.test(e)||/iPad|iPhone|iPod/.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1,o=a.viewportSize?.width??window.innerWidth??0,s=a.viewportSize?.height??window.innerHeight??0,r=Math.max(o,s),l=r===0||r<=1024;return a.allowViewportOnly&&a.viewportSize?l:t||(n||i)&&l}var Et=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],Gt=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),Tt={A:{size:72,label:"A",position:{right:98,bottom:44}},B:{size:72,label:"B",position:{right:24,bottom:108}},X:{size:72,label:"X",position:{right:172,bottom:108}},Y:{size:72,label:"Y",position:{right:98,bottom:172}},Start:{size:64,label:"Start",position:{left:"50%",top:24,transform:"translateX(28px)"}},Select:{size:64,label:"Select",position:{left:"50%",top:24,transform:"translateX(-108px)"}},L:{size:62,label:"L",position:{left:28,bottom:184}},R:{size:62,label:"R",position:{right:236,bottom:184}},LTrigger:{size:76,label:"LT",position:{left:24,top:24}},RTrigger:{size:76,label:"RT",position:{right:24,top:24}},Up:{enabled:!1,size:64,label:"Up"},Down:{enabled:!1,size:64,label:"Down"},Left:{enabled:!1,size:64,label:"Left"},Right:{enabled:!1,size:64,label:"Right"}},Rt={left:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"Horizontal",verticalAxis:"Vertical",emitDirections:!0,position:{left:24,bottom:24}},right:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"SecondaryHorizontal",verticalAxis:"SecondaryVertical",emitDirections:!1,position:{right:24,bottom:236}}},X=class{config;targetElement;buttonStates=new Map;analogStates=new Map;buttons=new Map;joysticks=new Map;rootElement=null;enabled=!1;onPointerMove=e=>{for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.updateJoystickFromPoint(t,e.clientX,e.clientY))};onPointerUp=e=>{for(let t of this.buttons.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseButton(t));for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseJoystick(t))};onWindowBlur=()=>{for(let e of this.buttons.values())this.releaseButton(e);for(let e of this.joysticks.values())this.releaseJoystick(e)};constructor(e,t){this.config=e??{},this.targetElement=t??document.body,this.enabled=this.resolveEnabledState(),this.enabled&&(this.mountControls(),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),window.addEventListener("pointercancel",this.onPointerUp),window.addEventListener("blur",this.onWindowBlur))}getInput(e){if(!this.enabled)return{};let t={};for(let n of this.buttons.values()){let i=this.handleButtonState(`button:${n.slot}`,n.pointerId!==null,e);this.assignButtonState(t,this.resolveButtonTarget(n.slot),i)}for(let n of this.joysticks.values()){let i=this.handleAnalogState(`joystick:${n.id}:x`,n.valueX,e),o=this.handleAnalogState(`joystick:${n.id}:y`,n.valueY,e);this.assignAxisState(t,n.config.horizontalAxis,i),this.assignAxisState(t,n.config.verticalAxis,o),n.config.emitDirections&&(this.assignButtonState(t,this.resolveButtonTarget("Left"),this.handleButtonState(`joystick:${n.id}:left`,n.valueX<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Right"),this.handleButtonState(`joystick:${n.id}:right`,n.valueX>=n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Up"),this.handleButtonState(`joystick:${n.id}:up`,n.valueY<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Down"),this.handleButtonState(`joystick:${n.id}:down`,n.valueY>=n.config.directionThreshold,e)))}return t}getName(){return"virtual-touch"}isConnected(){return this.enabled}dispose(){window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerUp),window.removeEventListener("blur",this.onWindowBlur),this.rootElement?.remove(),this.rootElement=null,this.buttons.clear(),this.joysticks.clear(),this.buttonStates.clear(),this.analogStates.clear()}resolveEnabledState(){return typeof window>"u"||typeof document>"u"?!1:this.config.enabled===!0?!0:this.config.enabled===!1?!1:N()}mountControls(){this.rootElement=document.createElement("div"),this.rootElement.className="zylem-virtual-touch",this.rootElement.dataset.zylemTouchRoot="true",this.rootElement.style.position="absolute",this.rootElement.style.inset="0",this.rootElement.style.pointerEvents="none",this.rootElement.style.touchAction="none",this.rootElement.style.userSelect="none",this.rootElement.style.WebkitUserSelect="none",this.rootElement.style.WebkitTouchCallout="none",this.rootElement.style.color="rgba(245, 247, 255, 0.96)",this.rootElement.style.zIndex="20",this.appendClassName(this.rootElement,this.config.className),_(this.rootElement,this.config.style),this.rootElement.addEventListener("contextmenu",e=>e.preventDefault());for(let[e,t]of this.resolveButtons())this.rootElement.appendChild(this.createButton(e,t));for(let[e,t]of this.resolveJoysticks())this.rootElement.appendChild(this.createJoystick(e,t));this.targetElement.appendChild(this.rootElement)}resolveButtons(){if(this.config.buttons===!1)return[];let e=this.config.buttons,t=[];for(let n of Et){let i=Tt[n],o=e?.[n];if(o===!1)continue;let s={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},label:o?.label??i.label??n,size:o?.size??i.size??72};s.enabled!==!1&&t.push([n,s])}return t}resolveJoysticks(){if(this.config.joysticks===!1)return[];let e=this.config.joysticks,t=[];for(let n of["left","right"]){let i=Rt[n],o=e?.[n];if(o===!1)continue;let s={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},svg:{...i.svg,...o?.svg},size:o?.size??i.size??140,thumbSize:o?.thumbSize??i.thumbSize??58,maxDistance:o?.maxDistance??i.maxDistance??44,deadzone:o?.deadzone??i.deadzone??.12,directionThreshold:o?.directionThreshold??i.directionThreshold??.34,horizontalAxis:o?.horizontalAxis??i.horizontalAxis??"Horizontal",verticalAxis:o?.verticalAxis??i.verticalAxis??"Vertical",emitDirections:o?.emitDirections??i.emitDirections??!1};s.enabled!==!1&&t.push([n,s])}return t}createButton(e,t){let n=document.createElement("button"),i=document.createElement("div");n.type="button",n.ariaLabel=t.label,n.className=`zylem-virtual-touch__button zylem-virtual-touch__button--${e}`,n.dataset.zylemTouchButton=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.padding="0",n.style.margin="0",n.style.border="0",n.style.background="transparent",n.style.pointerEvents="auto",n.style.touchAction="none",n.style.cursor="pointer",n.style.appearance="none",n.style.outline="none",n.style.userSelect="none",n.style.WebkitTapHighlightColor="transparent",_(n,t.position),_(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__button-content",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.transform="scale(1)",i.style.transformOrigin="center",i.style.transition="transform 120ms ease, opacity 120ms ease",i.style.opacity="0.92",i.innerHTML=t.svg??Bt(t.label),n.appendChild(i),n.addEventListener("pointerdown",s=>{if(!it(s))return;let r=this.buttons.get(e);!r||r.pointerId!==null||(this.consumeEvent(s),r.pointerId=s.pointerId,this.updateButtonVisual(r,!0))});let o={slot:e,config:t,element:n,content:i,pointerId:null};return this.buttons.set(e,o),n}createJoystick(e,t){let n=document.createElement("div"),i=document.createElement("div"),o=document.createElement("div");n.className=`zylem-virtual-touch__joystick zylem-virtual-touch__joystick--${e}`,n.dataset.zylemTouchJoystick=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.pointerEvents="auto",n.style.touchAction="none",n.style.userSelect="none",_(n,t.position),_(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__joystick-base",i.style.position="absolute",i.style.inset="0",i.style.pointerEvents="none",i.style.opacity="0.88",i.style.transition="opacity 120ms ease",i.innerHTML=t.svg?.base??Mt(),o.className="zylem-virtual-touch__joystick-thumb",o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.width=`${t.thumbSize}px`,o.style.height=`${t.thumbSize}px`,o.style.pointerEvents="none",o.style.transform="translate(-50%, -50%) translate(0px, 0px)",o.style.transition="transform 60ms linear, opacity 120ms ease",o.style.opacity="0.94",o.innerHTML=t.svg?.thumb??It(),n.append(i,o);let s={id:e,config:t,element:n,base:i,thumb:o,pointerId:null,centerX:0,centerY:0,rawX:0,rawY:0,valueX:0,valueY:0};return this.joysticks.set(e,s),n.addEventListener("pointerdown",r=>{if(!it(r))return;let l=this.joysticks.get(e);if(!l||l.pointerId!==null)return;this.consumeEvent(r);let p=l.element.getBoundingClientRect();l.pointerId=r.pointerId,l.centerX=p.left+p.width/2,l.centerY=p.top+p.height/2,this.updateJoystickVisual(l,!0),this.updateJoystickFromPoint(l,r.clientX,r.clientY)}),n}handleButtonState(e,t,n){let i=this.buttonStates.get(e);return i||(i={pressed:!1,released:!1,held:0},this.buttonStates.set(e,i)),i.pressed=t&&i.held===0,i.released=!t&&i.held>0,i.held=t?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates.get(e);return i||(i={value:0,held:0},this.analogStates.set(e,i)),i.value=t,i.held=t!==0?i.held+n:0,i}assignAxisState(e,t,n){e.axes||(e.axes={}),e.axes[t]=w(e.axes[t],n)}assignButtonState(e,t,n){if(t.category==="buttons"){e.buttons??={},e.buttons[t.property]=m(e.buttons[t.property],n);return}if(t.category==="directions"){e.directions??={},e.directions[t.property]=m(e.directions[t.property],n);return}e.shoulders??={},e.shoulders[t.property]=m(e.shoulders[t.property],n)}resolveButtonTarget(e){switch(e){case"LTrigger":case"RTrigger":return{category:"shoulders",property:e};case"Up":case"Down":case"Left":case"Right":return{category:"directions",property:e};default:return{category:"buttons",property:e}}}updateJoystickFromPoint(e,t,n){let i=t-e.centerX,o=n-e.centerY,s=Math.hypot(i,o),r=e.config.maxDistance,l=s>r&&s>0?r/s:1;e.rawX=i*l,e.rawY=o*l;let p=Pt(e.rawX/r,e.rawY/r,e.config.deadzone);e.valueX=p.x,e.valueY=p.y,e.thumb.style.transform=`translate(-50%, -50%) translate(${e.rawX}px, ${e.rawY}px)`}releaseButton(e){e.pointerId=null,this.updateButtonVisual(e,!1)}releaseJoystick(e){e.pointerId=null,e.rawX=0,e.rawY=0,e.valueX=0,e.valueY=0,e.thumb.style.transform="translate(-50%, -50%) translate(0px, 0px)",this.updateJoystickVisual(e,!1)}updateButtonVisual(e,t){e.element.dataset.active=String(t),e.content.style.transform=t?"scale(0.94)":"scale(1)",e.content.style.opacity=t?"1":"0.92"}updateJoystickVisual(e,t){e.element.dataset.active=String(t),e.base.style.opacity=t?"1":"0.88",e.thumb.style.opacity=t?"1":"0.94"}consumeEvent(e){e.cancelable&&e.preventDefault(),e.stopPropagation()}appendClassName(e,t){t&&(e.className=`${e.className} ${t}`.trim())}};function _(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!Gt.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function Pt(a,e,t){let n=Math.hypot(a,e);if(n===0||n<=t)return{x:0,y:0};let o=Math.min(1,(n-t)/Math.max(1-t,1e-4))/n;return{x:a*o,y:e*o}}function Bt(a){let e=Lt(a);return`
|
|
2
|
+
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden="true">
|
|
3
|
+
<circle cx="50" cy="50" r="45" fill="rgba(12,18,24,0.72)" stroke="currentColor" stroke-width="4" />
|
|
4
|
+
<circle cx="50" cy="50" r="34" fill="rgba(255,255,255,0.06)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
|
|
5
|
+
<text
|
|
6
|
+
x="50"
|
|
7
|
+
y="56"
|
|
8
|
+
text-anchor="middle"
|
|
9
|
+
font-family="ui-sans-serif, system-ui, sans-serif"
|
|
10
|
+
font-size="${e.length>2?24:34}"
|
|
11
|
+
font-weight="700"
|
|
12
|
+
fill="currentColor"
|
|
13
|
+
>${e}</text>
|
|
14
|
+
</svg>
|
|
15
|
+
`}function Mt(){return`
|
|
16
|
+
<svg viewBox="0 0 140 140" width="100%" height="100%" aria-hidden="true">
|
|
17
|
+
<circle cx="70" cy="70" r="62" fill="rgba(10,16,20,0.64)" stroke="currentColor" stroke-width="4" />
|
|
18
|
+
<circle cx="70" cy="70" r="40" fill="rgba(255,255,255,0.04)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
|
|
19
|
+
</svg>
|
|
20
|
+
`}function It(){return`
|
|
21
|
+
<svg viewBox="0 0 64 64" width="100%" height="100%" aria-hidden="true">
|
|
22
|
+
<circle cx="32" cy="32" r="28" fill="rgba(22,30,38,0.9)" stroke="currentColor" stroke-width="3.5" />
|
|
23
|
+
</svg>
|
|
24
|
+
`}function Lt(a){return a.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function it(a){return a.pointerType==="touch"}var j=class{inputMap=new Map;currentInputs={};previousInputs={};targetElement;mouseTargetElement;constructor(e,t){this.targetElement=t?.targetElement,this.mouseTargetElement=t?.mouseTargetElement??t?.targetElement;let n=this.buildPlayerEntries(e);for(let{player:i,config:o,gamepadIndex:s,isP1:r}of n)this.addConfigurableProviders(i,o,r),this.addInputProvider(i,new W(s))}configure(e){let t=this.buildPlayerEntries(e);for(let{player:n,config:i,isP1:o}of t){let r=(this.inputMap.get(n)??[]).filter(l=>l instanceof A||l instanceof U||l instanceof X?(l.dispose(),!1):!0);this.inputMap.set(n,[...this.createConfigurableProviders(i,o),...r])}}addInputProvider(e,t){this.inputMap.has(e)||this.inputMap.set(e,[]),this.inputMap.get(e)?.push(t)}dispose(){for(let e of this.inputMap.values())for(let t of e)t.dispose?.();this.inputMap.clear(),this.currentInputs={},this.previousInputs={}}getInputs(e){let t={};return this.inputMap.forEach((n,i)=>{let o=`p${i}`,s=n.reduce((r,l)=>{let p=l.getInput(e);return this.mergeInputs(r,p)},{});t[o]={playerNumber:i,...s}}),t}buildPlayerEntries(e){return[{player:1,config:e?.p1,gamepadIndex:0,isP1:!0},{player:2,config:e?.p2,gamepadIndex:1,isP1:!1},{player:3,config:e?.p3,gamepadIndex:2,isP1:!1},{player:4,config:e?.p4,gamepadIndex:3,isP1:!1},{player:5,config:e?.p5,gamepadIndex:4,isP1:!1},{player:6,config:e?.p6,gamepadIndex:5,isP1:!1},{player:7,config:e?.p7,gamepadIndex:6,isP1:!1},{player:8,config:e?.p8,gamepadIndex:7,isP1:!1}]}addConfigurableProviders(e,t,n){for(let i of this.createConfigurableProviders(t,n))this.addInputProvider(e,i)}createConfigurableProviders(e,t){let n=[];if(e?.key){let i=e.includeDefaults??t;n.push(new A(e.key,{includeDefaultBase:i}))}else t&&n.push(new A);return e?.mouse&&n.push(new U(e.mouse,this.mouseTargetElement)),e?.touch&&n.push(new X(e.touch,this.targetElement)),n}mergeInputs(e,t){return{buttons:{A:m(e.buttons?.A,t.buttons?.A),B:m(e.buttons?.B,t.buttons?.B),X:m(e.buttons?.X,t.buttons?.X),Y:m(e.buttons?.Y,t.buttons?.Y),Start:m(e.buttons?.Start,t.buttons?.Start),Select:m(e.buttons?.Select,t.buttons?.Select),L:m(e.buttons?.L,t.buttons?.L),R:m(e.buttons?.R,t.buttons?.R)},directions:{Up:m(e.directions?.Up,t.directions?.Up),Down:m(e.directions?.Down,t.directions?.Down),Left:m(e.directions?.Left,t.directions?.Left),Right:m(e.directions?.Right,t.directions?.Right)},axes:{Horizontal:w(e.axes?.Horizontal,t.axes?.Horizontal),Vertical:w(e.axes?.Vertical,t.axes?.Vertical),SecondaryHorizontal:w(e.axes?.SecondaryHorizontal,t.axes?.SecondaryHorizontal),SecondaryVertical:w(e.axes?.SecondaryVertical,t.axes?.SecondaryVertical)},shoulders:{LTrigger:m(e.shoulders?.LTrigger,t.shoulders?.LTrigger),RTrigger:m(e.shoulders?.RTrigger,t.shoulders?.RTrigger)},pointer:t.pointer??e.pointer}}};var Q=class{_previousTime;_currentTime;_startTime;_delta;_elapsed;_timescale;_document;_pageVisibilityHandler;constructor(){this._previousTime=0,this._currentTime=0,this._startTime=we(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=kt.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=we()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:we())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function we(){return performance.now()}function kt(){this._document.hidden===!1&&this.reset()}var Y={FourByThree:1.3333333333333333,SixteenByNine:1.7777777777777777,NineBySixteen:.5625,TwentyOneByNine:2.3333333333333335,OneByOne:1},ee=class{container;canvas;aspectRatio;onResize;handleResizeBound;resizeObserver=null;constructor(e){this.container=e.container,this.canvas=e.canvas,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio),this.onResize=e.onResize,this.handleResizeBound=this.apply.bind(this)}attach(){window.addEventListener("resize",this.handleResizeBound),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(this.handleResizeBound),this.resizeObserver.observe(this.container)),this.apply()}detach(){window.removeEventListener("resize",this.handleResizeBound),this.resizeObserver?.disconnect(),this.resizeObserver=null}measure(){let e=this.container.getBoundingClientRect(),t=Math.round(e.width||this.container.clientWidth||0),n=Math.round(e.height||this.container.clientHeight||0);if(t>0&&n>0){if(t/n>this.aspectRatio){let p=n;return{width:Math.round(p*this.aspectRatio),height:p}}let r=t,l=Math.round(r/this.aspectRatio);return{width:r,height:l}}if(t>0){let s=t,r=Math.round(s/this.aspectRatio);return{width:s,height:r}}if(n>0){let s=n;return{width:Math.round(s*this.aspectRatio),height:s}}let i=window.innerWidth,o=Math.round(i/this.aspectRatio);return{width:i,height:o}}apply(){let{width:e,height:t}=this.measure();this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.onResize?.(e,t)}};var at={NES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x240",width:256,height:240,notes:"Standard NTSC; effective 240p."}]},SNES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x224",width:256,height:224,notes:"Common 240p-equivalent mode."},{key:"512x448",width:512,height:448,notes:"Hi-res interlaced (480i)."}]},N64:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Common 240p mode."},{key:"640x480",width:640,height:480,notes:"Higher resolution (480i)."}]},PS1:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Progressive 240p common."},{key:"640x480",width:640,height:480,notes:"Interlaced 480i for higher detail."}]},PS2:{displayAspect:1.3333333333333333,resolutions:[{key:"640x480",width:640,height:480,notes:"480i/480p baseline."},{key:"720x480",width:720,height:480,notes:"480p (widescreen capable in some titles)."},{key:"1280x720",width:1280,height:720,notes:"720p (select titles)."}]},PS5:{displayAspect:1.7777777777777777,resolutions:[{key:"720x480",width:720,height:480,notes:"Legacy compatibility."},{key:"1280x720",width:1280,height:720,notes:"720p."},{key:"1920x1080",width:1920,height:1080,notes:"1080p."},{key:"2560x1440",width:2560,height:1440,notes:"1440p."},{key:"3840x2160",width:3840,height:2160,notes:"4K (up to 120Hz)."},{key:"7680x4320",width:7680,height:4320,notes:"8K (limited)."}]},XboxOne:{displayAspect:1.7777777777777777,resolutions:[{key:"1280x720",width:1280,height:720,notes:"720p (original)."},{key:"1920x1080",width:1920,height:1080,notes:"1080p (original)."},{key:"3840x2160",width:3840,height:2160,notes:"4K UHD (S/X models)."}]},MobilePortrait:{displayAspect:.5625,resolutions:[{key:"360x640",width:360,height:640,notes:"Low-density phone portrait baseline."},{key:"720x1280",width:720,height:1280,notes:"HD phone portrait."},{key:"1080x1920",width:1080,height:1920,notes:"Full HD phone portrait."}]}};function Ce(a){return at[a].displayAspect}function xe(a,e){let t=at[a]?.resolutions||[];if(!e)return t[0];let n=e.toLowerCase().replace(/\s+/g,"").replace("\xD7","x");return t.find(i=>i.key.toLowerCase()===n)}function Ee(a){if(!a)return null;let t=String(a).toLowerCase().trim().replace(/\s+/g,"").replace("\xD7","x").match(/^(\d+)x(\d+)$/);if(!t)return null;let n=parseInt(t[1],10),i=parseInt(t[2],10);return!Number.isFinite(n)||!Number.isFinite(i)?null:{width:n,height:i}}var Ge=null,Te=class{constructor(e,t,n,i,o,s,r,l,p,g,u,d,S){this.id=e;this.globals=t;this.stages=n;this.debug=i;this.time=o;this.input=s;this.aspectRatio=r;this.internalResolution=l;this.fullscreen=p;this.bodyBackground=g;this.container=u;this.containerId=d;this.canvas=S}};function Dt(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?N({viewportSize:a.viewportSize,allowViewportOnly:!0}):N()}function At(a,e){if(e)return e;if(a){let i=document.getElementById(a);if(i)return i}let t=a||"zylem-root",n=document.createElement("main");return n.setAttribute("id",t),n.style.position="relative",n.style.width="100%",n.style.height="100%",document.body.appendChild(n),n}function zt(a){let e=a?.id??"zylem";return{id:e,globals:a?.globals??{},stages:a?.stages??[],debug:!!a?.debug,time:a?.time??0,input:a?.input,aspectRatio:Y.SixteenByNine,fullscreen:!0,bodyBackground:"#000000",containerId:e}}var ot=360;function rt(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return Ge;let i=Ee(a);if(i)return i;if(e){let o=xe(e,a);if(o)return{width:o.width,height:o.height}}return}let t=a.width,n=a.height;if(Number.isFinite(t)&&Number.isFinite(n))return{width:t,height:n}}function Vt(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return Y[a]??t;if(e)try{return Ce(e)||t}catch{return t}return n?n.width/n.height:t}function Ot(a){let e=Number.isFinite(a)&&a>0?a:Y.SixteenByNine;if(e>=1){let i=ot;return{width:Math.round(i*e),height:i}}let t=ot,n=Math.round(t/e);return{width:t,height:n}}function Z(a,e={}){let t=zt({id:a?.id??"zylem",debug:!!a?.debug,time:a?.time??0,input:a?.input,stages:a?.stages??[],globals:a?.globals??{}}),n=a?.containerId??t.containerId,i=At(n,a?.container??null),o=a?.mobile,s=Dt(e),r=s?o?.preset??a?.preset:a?.preset,l=rt(a?.resolution,a?.preset),p=rt(o?.resolution,o?.preset??a?.preset),g=(s?st(p):void 0)??st(l),u=s?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,d=Vt(u,r,t.aspectRatio,g),S=Ht(s,p,l,d),f=a?.fullscreen??t.fullscreen,G=a?.bodyBackground??t.bodyBackground,P=a?.canvas??void 0,B=Ft(a?.input??t.input,o?.controls);return new Te(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,B,d,S,f,G,i,n,P)}function st(a){if(a)return a}function Ht(a,e,t,n){if(a)return e===Ge?void 0:e??Ot(n);if(t!==Ge)return t}function Ft(a,e){if(!e)return a;let n=_e("p1",{enabled:"auto",...e===!0?{}:e});return L(n,a??{})}function Ut(a){return{...a}}var te=class{id;container;canvas;bodyBackground;fullscreen;aspectRatio;ratioDelegate=null;overlayContainer=null;constructor(e){this.id=e.id,this.container=this.ensureContainer(e.containerId??e.id,e.container),this.canvas=e.canvas??document.createElement("canvas"),this.bodyBackground=e.bodyBackground,this.fullscreen=!!e.fullscreen,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio)}applyBodyBackground(){this.bodyBackground&&(document.body.style.background=this.bodyBackground)}mountCanvas(){this.mountChildren(this.canvas)}mountRenderer(e,t){this.mountChildren(e),this.canvas=e,this.attachAspectRatio(t)}getOverlayContainer(){return this.ensureOverlayContainer()}centerIfFullscreen(){if(!this.fullscreen)return;let e=this.container.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.position="relative",e.inset="0"}attachAspectRatio(e){this.ratioDelegate?(this.ratioDelegate.canvas=this.canvas,this.ratioDelegate.onResize=e,this.ratioDelegate.aspectRatio=this.aspectRatio,this.ratioDelegate.apply()):(this.ratioDelegate=new ee({container:this.container,canvas:this.canvas,aspectRatio:this.aspectRatio,onResize:e}),this.ratioDelegate.attach())}setAspectRatio(e){this.aspectRatio=e,this.ratioDelegate&&(this.ratioDelegate.aspectRatio=e,this.ratioDelegate.apply())}reapplyLayout(){this.ratioDelegate?.apply()}destroy(){this.ratioDelegate?.detach(),this.ratioDelegate=null}mountChildren(e){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.appendChild(e),this.container.appendChild(this.ensureOverlayContainer())}ensureOverlayContainer(){if(this.overlayContainer)return this.overlayContainer;let e=document.createElement("div");return e.dataset.zylemOverlayRoot="true",e.style.position="absolute",e.style.inset="0",e.style.pointerEvents="none",e.style.touchAction="none",e.style.zIndex="10",this.overlayContainer=e,e}ensureContainer(e,t){if(t)return t;if(e){let o=document.getElementById(e);if(o)return o}let n=e||this.id||"zylem-root",i=document.createElement("main");return i.setAttribute("id",n),i.style.position="relative",i.style.width="100%",i.style.height="100%",document.body.appendChild(i),i}};import Nt from"stats.js";import{subscribe as _t}from"valtio/vanilla";var lt="zylem-fps-host",ne=class{statsRef=null;unsubscribe=null;host=null;onFpsHost=e=>{let t=e.detail;this.host=t?.element??null,this.attachStats()};constructor(){typeof window<"u"&&window.addEventListener(lt,this.onFpsHost),this.updateDebugUI(),this.unsubscribe=_t(v,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}styleForPanel(e){e.style.position="relative",e.style.top="auto",e.style.right="auto",e.style.bottom="auto",e.style.left="auto",e.style.zIndex="auto"}detachStats(){let e=this.statsRef?.dom;e?.parentNode&&e.parentNode.removeChild(e)}attachStats(){if(this.statsRef){if(!this.host){this.detachStats();return}this.styleForPanel(this.statsRef.dom),this.statsRef.dom.parentNode!==this.host&&this.host.appendChild(this.statsRef.dom)}}updateDebugUI(){v.enabled&&!this.statsRef?(this.statsRef=new Nt,this.statsRef.showPanel(0),this.attachStats()):!v.enabled&&this.statsRef&&(this.detachStats(),this.statsRef=null)}dispose(){typeof window<"u"&&window.removeEventListener(lt,this.onFpsHost),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.detachStats(),this.statsRef=null,this.host=null}};var ie=class{loadingHandlers=[];stageLoadingUnsubscribes=[];onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let n of this.loadingHandlers)try{n(e)}catch(i){console.error("Game loading handler failed",i)}let t=`loading:${e.type}`;E.emit(t,e)}wireStageLoading(e,t){let n=e.onLoading(i=>{this.emit({type:i.type,message:i.message??"",progress:i.progress??0,current:i.current,total:i.total,stageName:e.uuid??`Stage ${t}`,stageIndex:t})});typeof n=="function"&&this.stageLoadingUnsubscribes.push(n)}unwireAllStages(){for(let e of this.stageLoadingUnsubscribes)try{e()}catch{}this.stageLoadingUnsubscribes=[]}dispose(){this.unwireAllStages(),this.loadingHandlers=[]}};import{getZylemBridge as Xt}from"@zylem/bridge";var ae=class{container=null;camera=null;rendererManager=null;gameCanvas=null;config=null;stage=null;mounted=!1;setGameCanvas(e){this.gameCanvas=e,this.tryMount()}setConfig(e){this.config=e,this.tryMount()}setContainer(e){this.container=e,this.tryMount()}setStage(e){this.stage=e,this.mounted&&this.gameCanvas?.reapplyLayout()}setCamera(e){this.camera=e,this.tryMount()}setRendererManager(e){this.rendererManager=e,this.tryMount()}tryMount(){this.mounted||!this.container||!this.gameCanvas||(this.rendererManager?this.mountWithRendererManager():this.camera&&this.mountWithCamera())}mountWithRendererManager(){if(!this.rendererManager||!this.gameCanvas)return;let e=this.rendererManager.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.rendererManager)return;let i=this.config?.internalResolution;if(i)this.rendererManager.setPixelRatio(1),this.rendererManager.resize(i.width,i.height),this.stage?.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.rendererManager.setPixelRatio(o),this.rendererManager.resize(t,n),this.stage?.resize(t,n)}}),this.mounted=!0}mountWithCamera(){if(!this.camera||!this.gameCanvas)return;let e=this.camera.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.camera)return;let i=this.config?.internalResolution;if(i)this.camera.setPixelRatio(1),this.camera.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.camera.setPixelRatio(o),this.camera.resize(t,n)}}),this.mounted=!0}reset(){this.camera=null,this.stage=null,this.mounted=!1}dispose(){this.container=null,this.camera=null,this.rendererManager=null,this.gameCanvas=null,this.config=null,this.stage=null,this.mounted=!1}};var oe=class a{id;initialGlobals={};customSetup=null;customUpdate=null;customDestroy=null;stages=[];stageMap=new Map;currentStageId="";previousTimeStamp=0;totalTime=0;timer;inputManager;wrapperRef;globalInputConfig;defaultCamera=null;rendererManager=null;container=null;canvas=null;aspectRatioDelegate=null;resolvedConfig=null;gameCanvas=null;animationFrameId=null;isDisposed=!1;loadInFlight=!1;hasStarted=!1;debugDelegate=null;loadingDelegate=new ie;rendererObserver=new ae;eventBusUnsubscribes=[];thumbnailUnsubscribes=[];lastPublishedGameConfig=null;gameBridge=new Je;cutscenePreview=new tt(()=>this.currentStage()?.wrappedStage??null,e=>this.gameBridge.publishCutsceneStatus(e),{},e=>this.gameBridge.publishCutsceneView(e));catalogUnsubscribe=null;gameUpdateParams={};stageSetupParams={};stageUpdateParams={};frameCallback=e=>this.loop(e);sourceOptions;displayRuntime;static FRAME_LIMIT=120;static FRAME_DURATION=1e3/a.FRAME_LIMIT;static MAX_DELTA_SECONDS=1/30;constructor(e,t,n={}){this.wrapperRef=t,this.timer=new Q,this.timer.connect(document),this.sourceOptions={...e},this.displayRuntime={...n};let i=Z(e,this.displayRuntime);this.globalInputConfig=i.input,this.id=i.id,this.stages=i.stages||[],this.container=i.container,this.canvas=i.canvas??null,this.resolvedConfig=i,this.loadGameCanvas(i),this.container=this.gameCanvas?.container??this.container,this.inputManager=new j(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e),je(),Qe(),this.gameBridge.connect({resolveEntity:o=>this.currentStage()?.wrappedStage?.entityDelegate.childrenMap.get(o)??null,setStageVariable:(o,s)=>{let r=this.currentStage()?.wrappedStage?.state;r&&(r.variables[o]=s)},createEntity:(o,s,r)=>{this.createCatalogEntity(o,s,r)},applySceneOperation:(o,s)=>{this.currentStage()?.wrappedStage?.debugDelegate?.applySceneOperation(o,s)},pickEntity:o=>this.pickEntityAtNdc(o),cutscene:this.cutscenePreview,cameraPose:()=>this.cutscenePreview.cameraPose(),levelSync:o=>{this.currentStage()?.wrappedStage?.debugDelegate?.syncLevel(o)},levelPlay:o=>{this.currentStage()?.wrappedStage?.debugDelegate?.playLevel(o)},levelClose:()=>{this.currentStage()?.wrappedStage?.debugDelegate?.closeLevel()},applySwatches:o=>{let s=this.currentStage()?.wrappedStage?.debugDelegate;return s?s.applySwatches(o):{results:o.uuids.flatMap(r=>o.swatches.map(l=>({uuid:r,kind:l.kind,source:l.source,ok:!1,reason:"entity-not-found"}))),entries:[]}}}),this.publishEntityCatalog(),this.catalogUnsubscribe=We(()=>this.publishEntityCatalog())}pickEntityAtNdc(e){let t=this.currentStage()?.wrappedStage,n=t?.debugDelegate?.pickAtNdc(e.x,e.y);if(!t||!n)return null;let i=t.entityDelegate.childrenMap.get(n.uuid);return i?this.buildEntitySummary(i)??{uuid:n.uuid,name:n.name||"Unnamed",type:ge(i),position:he(i).position,rotation:he(i).rotation,scale:me(i)}:null}publishEntityCatalog(){this.gameBridge.publishCatalog($e())}createCatalogEntity(e,t,n){let i=this.currentStage()?.wrappedStage,o=K(e);if(!i||!o)return;let s=n?.position??{x:0,y:0,z:0},r=o.create({position:s,props:{...o.defaultProps??{},...t??{}}});r&&Promise.resolve(r).then(l=>l&&i.entityDelegate.spawnEntity(l)).catch(l=>{console.error("entity:create failed",l)})}setDisplayRuntime(e){this.displayRuntime={...e};let t=Z(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.publishGameConfig()}loadGameCanvas(e){this.gameCanvas=new te({id:e.id,container:e.container,containerId:e.containerId,canvas:this.canvas??void 0,bodyBackground:e.bodyBackground,fullscreen:e.fullscreen,aspectRatio:e.aspectRatio}),this.gameCanvas.applyBodyBackground(),this.gameCanvas.mountCanvas(),this.gameCanvas.centerIfFullscreen(),this.rendererObserver.setGameCanvas(this.gameCanvas),this.resolvedConfig&&this.rendererObserver.setConfig(this.resolvedConfig),this.container&&this.rendererObserver.setContainer(this.container),this.subscribeToEventBus()}loadDebugOptions(e){e.debug!==void 0&&(v.enabled=!!e.debug),this.debugDelegate=new ne}isLoading(){return this.loadInFlight}async loadStage(e,t=0,n){if(this.loadInFlight){console.warn("loadStage ignored: a stage load is already in progress");return}this.loadInFlight=!0;try{await this.performLoadStage(e,t,n)}finally{this.loadInFlight=!1}}async performLoadStage(e,t=0,n){let i=n?et(n):null;this.cutscenePreview.releaseStage();let o=this.currentStage()??null,s=o?.wrappedStage??null,r=s?.scene?.scene??null,l=s?.cameraManagerRef?.primaryCamera?.camera??s?.cameraRef?.camera??null;i&&this.rendererManager?.initialized&&o&&r&&l&&this.rendererManager.beginSnapshotTransition(i,r,l),this.unloadCurrentStage();let g=e.options[0];if(this.loadingDelegate.wireStageLoading(e,t),this.rendererManager||(this.rendererManager=new Ne,await this.rendererManager.initRenderer()),x.setRenderer(this.rendererManager.renderer),await e.load(this.id,g?.camera,this.rendererManager),this.stageMap.set(e.wrappedStage.uuid,e),this.currentStageId=e.wrappedStage.uuid,this.defaultCamera=e.wrappedStage.cameraRef,this.wireEntityThumbnails(e),this.rendererObserver.setStage(e.wrappedStage??null),this.rendererManager&&this.rendererObserver.setRendererManager(this.rendererManager),this.applyInputConfig(e),e.onInputConfigChanged=()=>this.applyInputConfig(e),this.hasStarted&&e.wrappedStage&&!e.wrappedStage.hasSetup){let u=this.params(),d={...this.stageSetupParams};d.inputs=u.inputs,d.globals=u.globals,d.camera=u.camera,d.stage=u.stage,d.game=u.game,d.me=e.wrappedStage,e.start(d)}this.publishGameConfig(),this.publishStageSnapshot(),this.cutscenePreview.stageReady()}applyInputConfig(e){let t=L(this.globalInputConfig??{},e.inputConfig??{});this.inputManager.configure(t)}setGlobalInputConfig(e){this.globalInputConfig=e;let t=this.currentStage();t&&this.applyInputConfig(t)}unloadCurrentStage(){if(!this.currentStageId)return;let e=this.getStage(this.currentStageId);if(e){if(this.clearEntityThumbnailWiring(),x.clear(),e.onInputConfigChanged=null,e?.wrappedStage){try{e.wrappedStage.nodeDestroy({me:e.wrappedStage,globals:V.globals})}catch(t){console.error("Failed to destroy previous stage",t)}e.wrappedStage=null}e.dispose(),this.stageMap.delete(this.currentStageId),this.currentStageId="",this.defaultCamera=null,this.rendererObserver.reset()}}setGlobals(e){this.initialGlobals={...e.globals};for(let t in this.initialGlobals){let n=this.initialGlobals[t];n===void 0&&console.error(`global ${t} is undefined`),ze(t,n)}}params(){let e=this.currentStage(),t=this.timer.getDelta(),n=this.inputManager.getInputs(t),i=e?.wrappedStage?.cameraRef||this.defaultCamera,o=this.gameUpdateParams;return o.delta=t,o.inputs=n,o.globals=He(),o.me=this,o.camera=i,o.stage=e,o.game=this.wrapperRef,o}start(){let e=this.currentStage(),t=this.params(),n=this.stageSetupParams;n.inputs=t.inputs,n.globals=t.globals,n.camera=t.camera,n.stage=t.stage,n.game=t.game,n.me=e.wrappedStage,e.start(n),this.customSetup&&this.customSetup(t),this.hasStarted=!0,this.loop(0)}step(e){let t=this.currentStage();if(!t||!t.wrappedStage)return;let n=this.params(),i=e!==void 0?e:n.delta,o=Math.min(Math.max(i,0),a.MAX_DELTA_SECONDS);n.delta=o,this.customUpdate&&this.customUpdate(n);let s=this.currentStage();if(s!==t||!s?.wrappedStage){this.totalTime+=o,V.time=this.totalTime;return}let r=this.stageUpdateParams;r.delta=n.delta,r.inputs=n.inputs,r.globals=n.globals,r.camera=n.camera,r.stage=n.stage,r.game=n.game,r.me=t.wrappedStage,t.wrappedStage?.nodeUpdate(r),this.totalTime+=o,V.time=this.totalTime}loop(e){this.debugDelegate?.begin(),Ue()||(this.timer.update(e),this.step(),this.previousTimeStamp=e),this.debugDelegate?.end(),this.outOfLoop(),this.gameBridge.publishSelectedPoses(),this.cutscenePreview.frame(),this.isDisposed||(this.animationFrameId=requestAnimationFrame(this.frameCallback))}dispose(){this.isDisposed=!0,this.cutscenePreview.unload(),this.catalogUnsubscribe?.(),this.catalogUnsubscribe=null,this.gameBridge.disconnect(),this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.unloadCurrentStage(),this.debugDelegate&&(this.debugDelegate.dispose(),this.debugDelegate=null),this.eventBusUnsubscribes.forEach(e=>e()),this.eventBusUnsubscribes=[],this.rendererObserver.dispose(),this.inputManager.dispose(),this.rendererManager&&(x.setRenderer(null),this.rendererManager.dispose(),this.rendererManager=null),x.clear(),Xt().channel.reset(),this.timer.dispose(),this.customDestroy&&this.customDestroy({me:this,globals:V.globals}),O()}outOfLoop(){let e=this.currentStage();e&&e.wrappedStage.outOfLoop()}getStage(e){return this.stageMap.get(e)}currentStage(){return this.getStage(this.currentStageId)}onLoading(e){return this.loadingDelegate.onLoading(e)}buildStageConfigPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=e.wrappedStage.state,n=t.backgroundColor,i=typeof n=="string"?n:`#${n.getHexString()}`;return{id:e.wrappedStage.uuid,backgroundColor:i,backgroundImage:t.backgroundImage,gravity:{x:t.gravity.x,y:t.gravity.y,z:t.gravity.z},inputs:t.inputs,variables:t.variables}}buildEntitySummary(e){if(e.options?.editorOwned||H(e.options))return null;let t=Ye(e),n=t?.position??ye(e.options?.position,fe),i=t?.rotation??{x:0,y:0,z:0},o=t?.scale??me(e),s=t?.quaternion,r=x.get(e.uuid);return{uuid:e.uuid,name:e.name||"Unnamed",type:ge(e),position:n,rotation:i,scale:o,quaternion:s,thumbnail:r?.dataUrl??null,bounds:r?.bounds}}buildEntitiesPayload(){let e=this.currentStage();if(!e?.wrappedStage)return[];let t=[];return e.wrappedStage.entityDelegate.childrenMap.forEach(n=>{let i=this.buildEntitySummary(n);i&&t.push(i)}),t}wireEntityThumbnails(e){if(this.clearEntityThumbnailWiring(),!e.wrappedStage)return;let t=s=>{if(s.options?.editorOwned||!this.gameBridge.wantsThumbnails()||H(s.options))return;let r=s.group??s.mesh??null;r&&x.ensure(s.uuid,r).then(l=>{l&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:s.uuid,url:l.dataUrl,bounds:l.bounds}])})},n=e.wrappedStage.onEntityAdded(s=>{if(this.gameBridge.wantsEntityUpdates()){let r=this.buildEntitySummary(s);r&&this.gameBridge.queueEntityUpsert([r])}t(s)},{replayExisting:!0});this.thumbnailUnsubscribes.push(n);let i=s=>{if(!s.success)return;let r=e.wrappedStage?.entityDelegate.childrenMap.get(s.entityId);r&&(x.invalidate(s.entityId),t(r))};E.on("entity:model:loaded",i),this.thumbnailUnsubscribes.push(()=>{E.off("entity:model:loaded",i)});let o=s=>{x.invalidate(s.entityId),this.gameBridge.wantsEntityUpdates()&&this.gameBridge.queueEntityRemoved([s.entityId])};E.on("entity:destroyed",o),this.thumbnailUnsubscribes.push(()=>{E.off("entity:destroyed",o)}),this.wireEditorBackfill(e)}wireEditorBackfill(e){let t=this.gameBridge.onEditorAttached(()=>{if(!(this.isDisposed||this.currentStage()!==e)){this.lastPublishedGameConfig=null,this.publishGameConfig(),this.publishStageSnapshot();for(let n of e.wrappedStage?.entityDelegate.childrenMap.values()??[]){let i=n;if(i.options?.editorOwned||H(i.options))continue;let o=i.group??i.mesh??null;o&&x.ensure(i.uuid,o).then(s=>{s&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:i.uuid,url:s.dataUrl,bounds:s.bounds}])})}}});this.thumbnailUnsubscribes.push(t)}clearEntityThumbnailWiring(){this.thumbnailUnsubscribes.forEach(e=>{try{e()}catch{}}),this.thumbnailUnsubscribes=[]}buildGameConfigPayload(){return this.resolvedConfig?{id:this.resolvedConfig.id,aspectRatio:this.resolvedConfig.aspectRatio,fullscreen:this.resolvedConfig.fullscreen,bodyBackground:this.resolvedConfig.bodyBackground,internalResolution:this.resolvedConfig.internalResolution,debug:this.resolvedConfig.debug}:null}publishGameConfig(){let e=this.buildGameConfigPayload();if(!e)return;let t=JSON.stringify(e);t!==this.lastPublishedGameConfig&&(this.lastPublishedGameConfig=t,this.gameBridge.publishConfig(e))}publishStageSnapshot(){this.gameBridge.publishStageSnapshot({stage:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()})}subscribeToEventBus(){this.eventBusUnsubscribes.push(Ae.on("game:state:updated",e=>{this.gameBridge.publishVariable({path:e.path,value:e.value,previousValue:e.previousValue})}))}};async function ut(a){let{getGameDefaultConfig:e}=await import("./game-default-AF5QFXSD.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(r=>{if(r instanceof J)i.push(r);else if(r instanceof Se)o.push(r);else if(r instanceof ve)o.push(r);else if(r?.constructor?.name==="Object"&&typeof r=="object"){let l=Object.assign({...e()},{...r});n.push(l)}}),n.forEach(r=>{t=Object.assign(t,{...r})});let s=t;return s.input=n[0].input,i.forEach(r=>{r.addEntities(o)}),i.length?s.stages=i:s.stages[0].addEntities(o),s}function pt(a){return!!a.find(t=>t instanceof J)}function Re(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof J)&&!(e instanceof ve)&&!(e instanceof Se)){let t=e;if(t.globals)return t.globals}}import{proxy as Yt}from"valtio/vanilla";import{get as Zt,set as Kt}from"idb-keyval";import{pack as Jt,unpack as $t}from"msgpackr";var h=Yt({previous:null,current:null,next:null,isLoading:!1}),re={staticRegistry:new Map,registerStaticStage(a,e){this.staticRegistry.set(a,e)},async loadStageData(a){try{let e=await Zt(a);if(e)return $t(e)}catch(e){console.warn(`Failed to load stage ${a} from storage`,e)}if(this.staticRegistry.has(a))return this.staticRegistry.get(a);throw new Error(`Stage ${a} not found in storage and static loading not fully implemented.`)},async transitionForward(a,e){if(!h.isLoading){h.isLoading=!0;try{h.current&&await Kt(h.current.id,Jt(h.current)),h.previous=h.current,h.current=h.next,h.current?.id!==a&&(e?h.current=await e(a):h.current=await this.loadStageData(a)),h.next=null}catch(t){console.error("Failed to transition stage:",t)}finally{h.isLoading=!1}}},async preloadNext(a,e){e?h.next=await e(a):h.next=await this.loadStageData(a)}};var Pe={async createFromBlueprint(a){let e=F({});if(a.entities)for(let t of a.entities)try{let n=await nt.createFromBlueprint(t);e.add(n)}catch(n){console.error(`Failed to create entity ${t.id} for stage ${a.id}`,n)}return e}};var se=class{wrappedGame=null;options;setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];globalChangeCallbacks=[];globalChangesCallbacks=[];activeGlobalSubscriptions=[];eventDelegate=new Xe;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,pt(e)||this.options.push(F());let t=Re(e);t&&pe(t)}onSetup(...e){return this.setupCallbacks.push(...e),this}onUpdate(...e){return this.updateCallbacks.push(...e),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this}setInputConfiguration(...e){let t=L(...e);return this.pendingInputConfig=t,this.wrappedGame&&this.wrappedGame.setGlobalInputConfig(t),this}async start(){O();let e=Re(this.options);e&&pe(e);let t=await this.load();return this.wrappedGame=t,this.setOverrides(),this.registerGlobalSubscriptions(),t.start(),this}setDisplayRuntime(e){return this.displayRuntime={...this.displayRuntime,...e},this.wrappedGame&&this.wrappedGame.setDisplayRuntime(this.displayRuntime),this}setDeviceProfile(e){return this.setDisplayRuntime({deviceProfile:e})}setViewportSize(e,t){return this.setDisplayRuntime({viewportSize:{width:e,height:t}})}async load(){let e=await ut(this.options),t=Z(e,this.displayRuntime);this.pendingInputConfig&&(t.input=L(t.input??{},this.pendingInputConfig));let n=new oe({...e,...t},this,this.displayRuntime);for(let i of this.pendingLoadingCallbacks)n.onLoading(i);return await n.loadStage(e.stages[0]),n}setOverrides(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.customSetup=e=>{this.setupCallbacks.forEach(t=>t(e))},this.wrappedGame.customUpdate=e=>{this.updateCallbacks.forEach(t=>t(e))},this.wrappedGame.customDestroy=e=>{this.destroyCallbacks.forEach(t=>t(e))}}onGlobalChange(e,t){return this.globalChangeCallbacks.push({path:e,callback:t}),this}onGlobalChanges(e,t){return this.globalChangesCallbacks.push({paths:e,callback:t}),this}registerGlobalSubscriptions(){for(let{path:e,callback:t}of this.globalChangeCallbacks){let n=Ve(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=Oe(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}}getCurrentStage(){return this.wrappedGame?.currentStage()??null}experimental={getRuntime:()=>this.getCurrentStage()?.wrappedStage?.world?.simulation??null};async pause(){de(!0)}async resume(){de(!1),this.wrappedGame&&(this.wrappedGame.previousTimeStamp=0,this.wrappedGame.timer.reset())}step(e=1/60){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.step(e)}async reset(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.isLoading()||await this.wrappedGame.loadStage(this.wrappedGame.stages[0],0,e?.transition)}previousStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n-1];if(!i){console.error("previous stage called on first stage");return}this.wrappedGame.loadStage(i,n-1,e?.transition)}async loadStageFromId(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}try{let t=await re.loadStageData(e),n=await Pe.createFromBlueprint(t);await this.wrappedGame.loadStage(n),h.current=t}catch(t){console.error(`Failed to load stage ${e}`,t)}}nextStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;if(h.next){console.log("next stage called");let o=h.next.id;if(re.transitionForward(o),h.current){Pe.createFromBlueprint(h.current).then(s=>{this.wrappedGame?.loadStage(s,0,e?.transition)});return}}let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n+1];if(!i){console.error("next stage called on last stage");return}this.wrappedGame.loadStage(i,n+1,e?.transition)}async goToStage(){}async end(){}dispose(){this.eventDelegate.dispose();for(let e of this.activeGlobalSubscriptions)e();this.activeGlobalSubscriptions=[],this.wrappedGame&&(this.wrappedGame.dispose(),this.wrappedGame=null),Fe(),O(),qe.clearSharedMaterialCache()}dispatch(e,t){this.eventDelegate.dispatch(e,t),E.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}onLoading(e){return this.wrappedGame?this.wrappedGame.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e),this.wrappedGame})}};function Wt(...a){return new se(a)}function qt(a,e,t){return ce(e,n=>jt(a,n),t)}async function jt(a,e){let t=K(e.typeId);if(!t)return;let n=e.pose.position??{x:0,y:0,z:0},i=await t.create({position:n,props:{...t.defaultProps??{}}});i&&(await a.spawnEntity(i),Ke(i,e.pose),e.pose.scale&&Ze(i))}import{Euler as Qt,Quaternion as en,Vector2 as tn}from"three";function nn(a){return{spawn:async(e,t,n)=>{let i=await Promise.resolve(a(t,n));return e.add(i),i},spawnRelative:async(e,t,n=new tn(0,1))=>{if(!e.body){console.warn("body missing for entity during spawnRelative");return}let{x:i,y:o,z:s}=e.body.translation(),r=e._rotation2DAngle??0;try{let u=e.body.rotation(),d=new en(u.x,u.y,u.z,u.w);r=new Qt().setFromQuaternion(d,"XYZ").z}catch{}let l=Math.sin(-r)*(n.x??0),p=Math.cos(-r)*(n.y??0),g=await Promise.resolve(a(i+l,o+p));return t.add(g),g}}}import{subscribe as an}from"valtio/vanilla";var Be="STAGE_STATE_CHANGE";function on(){return an(k,()=>{let a={entities:k.entities,variables:k.variables};window.dispatchEvent(new CustomEvent(Be,{detail:a}))})}function rn(){let a={entities:k.entities,variables:k.variables};window.dispatchEvent(new CustomEvent(Be,{detail:a}))}import{MathUtils as sn,Vector3 as ln}from"three";var dt={targetKey:"primary",offset:new ln(0,0,0),lerpFactor:.1};function un(a){let e={...dt,...a,offset:be(a?.offset,dt.offset)},t=null;return{priority:0,enabled:!0,onAttach(){t=null},update(n,i){let o=n.targets[e.targetKey];if(!o)return i;let s=o.position.clone().add(e.offset),r=D(i);if(!t)t=s.clone();else{let l=sn.clamp(e.lerpFactor,0,1),p=1-Math.pow(1-l,n.dt*60);t.lerp(s,p)}return r.position.copy(t),r.lookAt=o.position.clone(),r},onDetach(){t=null}}}import{MathUtils as Me,Vector3 as ct}from"three";var pn={x:"delay",y:"settle",z:"delay"},mt=["x","y","z"];function dn(a){let e={...pn,...a?.axes},t=a?.targetKey??"primary",n=a?.lerpFactor??.1,i=a?.window??0,o=a?.settleSpeed??.75,s=a?.settleTime??.15,r=a?.settleLerp??.08,l=a?.lookahead??0,p=null,g=null,u=null,d={x:0,y:0,z:0},S=new ct,f=new ct,G=()=>{p=null,g=null,u=null,d.x=d.y=d.z=0,S.set(0,0,0)};return{priority:0,enabled:!0,onAttach:G,onDetach:G,update(P,B){let M=P.targets[t];if(!M)return B;let b=M.position,y=p??b.clone(),C=g??b.clone(),I=u??b.clone();p=y,g=C,u=I;let T=P.dt,z=T>1e-8?1/T:0,ft=ht(n,T),yt=ht(r,T);if(l>0){f.set(0,0,0);for(let c of mt)e[c]==="delay"&&(f[c]=(b[c]-I[c])*z);f.lengthSq()>1e-8&&S.copy(f).normalize()}for(let c of mt){let De=e[c];if(De==="off"){y[c]=b[c];continue}let bt=Math.abs((b[c]-I[c])*z);if(De==="settle"){bt<=o?(d[c]+=T,d[c]>=s&&(C[c]=b[c])):d[c]=0,y[c]=Me.lerp(y[c],C[c],yt);continue}let ue=b[c];l>0&&(ue+=S[c]*l),!(Math.abs(ue-y[c])<=i)&&(y[c]=Me.lerp(y[c],ue,ft))}I.copy(b);let R=D(B),Ie=y.x-b.x,Le=y.y-b.y,ke=y.z-b.z;return R.position.x+=Ie,R.position.y+=Le,R.position.z+=ke,R.lookAt&&(R.lookAt.x+=Ie,R.lookAt.y+=Le,R.lookAt.z+=ke),R}}}function ht(a,e){let t=Me.clamp(a,0,1);return 1-Math.pow(1-t,e*60)}import{MathUtils as le}from"three";function cn(a){let e=a?.sampleInput??(()=>({})),t=le.clamp(a?.edgeMargin??.08,0,.5),n=a?.edgeSpeed??12,i=a?.panSpeed??16,o=a?.followLerp??.12,s=a?.breakFollowOnPan??!0,r=a?.followKey??null,l=!1,p=null,g=()=>{p=null,l=!1};return{priority:0,enabled:!0,onAttach:g,onDetach:g,setFollowKey(u){r=u,l=!1},update(u,d){let S=d.lookAt??d.position,f=p??S.clone();p=f;let G=e()??{},P=G.pan?.x??0,B=G.pan?.y??0,M=mn(G.pointer,t);(Math.abs(P)>.01||Math.abs(B)>.01||M.x!==0||M.y!==0)&&s&&(l=!0);let y=!l&&r?u.targets[r]:void 0;if(y){let z=hn(o,u.dt);f.x=le.lerp(f.x,y.position.x,z),f.z=le.lerp(f.z,y.position.z,z)}else f.x+=(P*i+M.x*n)*u.dt,f.z+=(-B*i+M.y*n)*u.dt;let C=D(d),I=f.x-S.x,T=f.z-S.z;return C.position.x+=I,C.position.z+=T,C.lookAt&&(C.lookAt.x+=I,C.lookAt.z+=T),C}}}function mn(a,e){if(!a||e<=0)return{x:0,y:0};let t=a.centered?(a.x+1)/2:a.x,n=a.centered?(a.y+1)/2:a.y;return{x:gt(t,e),y:gt(n,e)}}function gt(a,e){return a<e?-((e-a)/e):a>1-e?(a-(1-e))/e:0}function hn(a,e){let t=le.clamp(a,0,1);return 1-Math.pow(1-t,e*60)}import{DoubleSide as gn}from"three";import{texture as fn,uv as yn}from"three/tsl";import{MeshBasicNodeMaterial as bn}from"three/webgpu";function vn(a,e,t){let n=e.cameraRef;if(!n.renderTarget){let s=t?.width??512,r=t?.height??512;n.createRenderTarget(s,r)}let i=n.getRenderTexture();if(!i){console.warn("setCameraFeed: Failed to obtain render texture from camera.");return}if(!a.mesh){console.warn("setCameraFeed: Entity has no mesh to apply the camera feed to.");return}let o=new bn({map:i,toneMapped:!1,side:gn});o.colorNode=fn(i,yn().flipY()),a.mesh.material=o}export{Y as a,Ce as b,xe as c,Ee as d,Ut as e,h as f,re as g,se as h,Wt as i,qt as j,nn as k,Be as l,on as m,rn as n,un as o,dn as p,cn as q,vn as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BoxGeometry as G,ConeGeometry as J,CylinderGeometry as x,Group as d,Mesh as m,MeshBasicMaterial as C,PlaneGeometry as S,Quaternion as K,Raycaster as U,TorusGeometry as H,Vector3 as l}from"three";var I={x:16726867,y:5036364,z:3900150,xy:3900150,yz:16726867,xz:5036364,xyz:14540253},Y=16765499,j=.16,h={x:new l(1,0,0),y:new l(0,1,0),z:new l(0,0,1)},A={xy:new l(0,0,1),yz:new l(1,0,0),xz:new l(0,1,0)},O=12,$=Math.sqrt(1-1/O),V=1/O;function tt(a,t){return Math.abs(a.dot(t))>$}function P(a,t,i){let e=_.copy(a.origin).sub(t),o=a.direction.dot(i),s=1-o*o;return s<1/O?null:(e.dot(i)-o*e.dot(a.direction))/s}function g(a,t,i,e){let o=i.dot(a.direction);if(Math.abs(o)<V)return null;let s=_.copy(t).sub(a.origin).dot(i)/o;return s<0?null:e.copy(a.direction).multiplyScalar(s).add(a.origin)}var _=new l,k=new l,et=new l,T=new l,B=new K,E=class{root=new d;scene=null;modeGroups={translate:new d,rotate:new d,scale:new d};handles={translate:[],rotate:[],scale:[]};materials=[];geometries=[];mode="translate";highlighted=null;drag=null;raycaster=new U;constructor(){this.root.name="__zylem_transform_gizmo__",this.root.renderOrder=1e3,this.root.visible=!1,this.buildTranslate(),this.buildRotate(),this.buildScale();for(let t of Object.keys(this.modeGroups))this.root.add(this.modeGroups[t]);this.applyModeVisibility()}addTo(t){this.scene!==t&&(this.scene=t,t.add(this.root))}removeFromScene(){this.scene&&(this.scene.remove(this.root),this.scene=null)}dispose(){this.removeFromScene();for(let t of this.geometries)t.dispose();for(let t of this.materials)t.dispose();this.geometries=[],this.materials=[]}setMode(t){this.mode!==t&&(this.mode=t,this.applyModeVisibility())}getMode(){return this.mode}show(t){this.root.position.copy(t),this.root.visible=!0}hide(){this.root.visible=!1,this.setHighlight(null)}get visible(){return this.root.visible}get pivot(){return this.root.position}update(t){if(!this.root.visible)return;let i;if(t.isPerspectiveCamera){let e=t;T.setFromMatrixPosition(e.matrixWorld),i=2*T.distanceTo(this.root.position)*Math.tan(e.fov*Math.PI/360)*j}else if(t.isOrthographicCamera){let e=t;i=(e.top-e.bottom)/(e.zoom||1)*j}else i=1;this.root.scale.setScalar(Math.max(i,1e-4))}pick(t){if(!this.root.visible)return null;this.raycaster.set(t.origin,t.direction);let i=this.handles[this.mode].filter(o=>this.isHandleDraggable(o.axis,t)).map(o=>o.picker),e=this.raycaster.intersectObjects(i,!1);return e.length?e[0].object.userData.gizmoAxis??null:null}isHandleDraggable(t,i){if(t==="xyz")return!0;if(this.isPlaneAxis(t))return Math.abs(i.direction.dot(A[t]))>=V;let e=h[t];return this.mode==="rotate"?Math.abs(i.direction.dot(e))>=V:!tt(i.direction,e)}setHighlight(t){if(this.highlighted!==t){this.highlighted=t;for(let i of Object.keys(this.handles))for(let e of this.handles[i]){let o=e.axis===t?Y:I[e.axis];for(let s of e.visuals)s.material.color.setHex(o)}}}beginDrag(t,i,e){let o=this.root.position.clone(),s={axis:t,mode:this.mode,pivot:o,startAxisValue:0,startPoint:new l,startAngle:0,startRadius:0};if(t==="xyz"){let r=this.cameraPlaneRadius(i,o,e);if(r===null||r<1e-4)return!1;s.startRadius=r}else if(this.isPlaneAxis(t)){let r=A[t];if(!g(i,o,r,s.startPoint))return!1}else if(this.mode==="rotate"){let r=h[t],n=this.angleOnPlane(i,o,r);if(n===null)return!1;s.startAngle=n}else{let r=P(i,o,h[t]);if(r===null||(s.startAxisValue=r,this.mode==="scale"&&Math.abs(r)<1e-4))return!1}return this.drag=s,this.setHighlight(t),!0}updateDrag(t,i){let e=this.drag;if(!e)return null;if(e.mode==="rotate"){let r=h[e.axis]??h.y,n=this.angleOnPlane(t,e.pivot,r);return n===null?null:{kind:"rotate",axis:r.clone(),angle:n-e.startAngle}}if(e.mode==="scale"){if(e.axis==="xyz"){let u=this.cameraPlaneRadius(t,e.pivot,i);if(u===null)return null;let p=u/e.startRadius;return{kind:"scale",factor:new l(p,p,p)}}let r=P(t,e.pivot,h[e.axis]);if(r===null)return null;let n=r/e.startAxisValue,c=new l(1,1,1);return c[e.axis]=n,{kind:"scale",factor:c}}if(this.isPlaneAxis(e.axis)){let r=A[e.axis],n=g(t,e.pivot,r,k);return n?{kind:"translate",offset:n.clone().sub(e.startPoint)}:null}let o=h[e.axis],s=P(t,e.pivot,o);return s===null?null:{kind:"translate",offset:o.clone().multiplyScalar(s-e.startAxisValue)}}endDrag(){this.drag=null,this.setHighlight(null)}get isDragging(){return this.drag!==null}get draggingAxis(){return this.drag?.axis??null}isPlaneAxis(t){return t==="xy"||t==="yz"||t==="xz"}angleOnPlane(t,i,e){let o=g(t,i,e,k);if(!o)return null;let s=et.copy(o).sub(i);if(s.lengthSq()<1e-8)return null;let r=Math.abs(e.y)>.9?h.x:h.y,n=_.copy(r).cross(e).normalize(),c=new l().copy(e).cross(n);return Math.atan2(s.dot(c),s.dot(n))}cameraPlaneRadius(t,i,e){B.setFromRotationMatrix(e.matrixWorld);let o=new l(0,0,1).applyQuaternion(B),s=g(t,i,o,k);return s?s.distanceTo(i):null}applyModeVisibility(){for(let t of Object.keys(this.modeGroups))this.modeGroups[t].visible=t===this.mode}makeMaterial(t,i){let e=new C({color:I[t],transparent:!0,opacity:i,depthTest:!1,depthWrite:!1,toneMapped:!1});return this.materials.push(e),e}track(t){return this.geometries.push(t),t}makePicker(t,i,e){let o=new C({visible:!1});this.materials.push(o);let s=new m(this.track(i),o);return s.visible=!1,s.userData.gizmoAxis=t,e(s),s}orientAlongAxis(t,i){i==="x"&&(t.rotation.z=-Math.PI/2),i==="z"&&(t.rotation.x=Math.PI/2)}buildTranslate(){let t=this.modeGroups.translate;for(let i of["x","y","z"]){let e=this.makeMaterial(i,1),o=new m(this.track(new x(.012,.012,.7,8)),e);o.position.y=.35;let s=new m(this.track(new J(.045,.16,12)),e);s.position.y=.78;let r=new d;r.add(o,s),this.orientAlongAxis(r,i);let n=this.makePicker(i,new x(.1,.1,.9,6),u=>{u.position.y=.45}),c=new d;c.add(n),this.orientAlongAxis(c,i),t.add(r,c),this.handles.translate.push({axis:i,visuals:[o,s],picker:n})}for(let i of["xy","yz","xz"]){let e=this.makeMaterial(i,.35),o=new m(this.track(new S(.22,.22)),e);this.positionPlaneHandle(o,i);let s=this.makePicker(i,new S(.22,.22),r=>{this.positionPlaneHandle(r,i)});t.add(o,s),this.handles.translate.push({axis:i,visuals:[o],picker:s})}}positionPlaneHandle(t,i){i==="xy"?t.position.set(.28,.28,0):i==="yz"?(t.position.set(0,.28,.28),t.rotation.y=Math.PI/2):(t.position.set(.28,0,.28),t.rotation.x=-Math.PI/2)}buildRotate(){let t=this.modeGroups.rotate;for(let i of["x","y","z"]){let e=this.makeMaterial(i,1),o=new m(this.track(new H(.68,.01,6,64)),e);this.orientRing(o,i);let s=this.makePicker(i,new H(.68,.08,4,24),r=>this.orientRing(r,i));t.add(o,s),this.handles.rotate.push({axis:i,visuals:[o],picker:s})}}orientRing(t,i){i==="x"&&(t.rotation.y=Math.PI/2),i==="y"&&(t.rotation.x=Math.PI/2)}buildScale(){let t=this.modeGroups.scale;for(let s of["x","y","z"]){let r=this.makeMaterial(s,1),n=new m(this.track(new x(.012,.012,.7,8)),r);n.position.y=.35;let c=new m(this.track(new G(.09,.09,.09)),r);c.position.y=.74;let u=new d;u.add(n,c),this.orientAlongAxis(u,s);let p=this.makePicker(s,new x(.1,.1,.85,6),Z=>{Z.position.y=.43}),w=new d;w.add(p),this.orientAlongAxis(w,s),t.add(u,w),this.handles.scale.push({axis:s,visuals:[n,c],picker:p})}let i=this.makeMaterial("xyz",.9),e=new m(this.track(new G(.13,.13,.13)),i),o=this.makePicker("xyz",new G(.22,.22,.22),()=>{});t.add(e,o),this.handles.scale.push({axis:"xyz",visuals:[e],picker:o})}};import{GridHelper as N,Group as it,Matrix4 as ot,Vector3 as y}from"three";var L=3094855,F=4871528,st=20,rt=.002,f=new y,v=new y,b=new y,R=new y,nt=new ot,q=class{group=new it;scene=null;fine=null;coarse=null;increment=0;constructor(){this.group.name="__zylem_construction_grid__",this.group.renderOrder=-1,this.group.visible=!1}addTo(t){this.scene!==t&&(this.scene=t,t.add(this.group))}setIncrement(t){t<=0||t===this.increment||(this.increment=t,this.rebuild())}setVisible(t){this.group.visible=t}get visible(){return this.group.visible}setPlane(t,i){if(!t){this.group.position.set(0,0,0),this.group.quaternion.identity();return}if(f.set(t.u.x,t.u.y,t.u.z).normalize(),v.set(t.normal.x,t.normal.y,t.normal.z).normalize(),b.crossVectors(f,v),this.group.quaternion.setFromRotationMatrix(nt.makeBasis(f,v,b)),this.group.position.set(t.origin.x,t.origin.y,t.origin.z),i){let e=this.wholeCell();R.set(i.x,i.y,i.z).sub(this.group.position),this.group.position.addScaledVector(f,Math.round(R.dot(f)/e)*e).addScaledVector(b,Math.round(R.dot(b)/e)*e)}this.group.position.addScaledVector(v,rt)}dispose(){this.clearHelpers(),this.scene?.remove(this.group),this.scene=null}rebuild(){this.clearHelpers();let t=st*2,i=Math.round(t/this.increment);i>0&&i<=400&&(this.fine=new N(t,i,L,L),this.fine.material.transparent=!0,this.fine.material.opacity=.35,this.fine.material.depthWrite=!1,this.group.add(this.fine)),this.coarse=new N(t,t,F,F),this.coarse.material.transparent=!0,this.coarse.material.opacity=.6,this.coarse.material.depthWrite=!1,this.group.add(this.coarse)}wholeCell(){let t=this.increment>0?this.increment:1;for(let i=1;i<=64;i+=1){let e=t*i;if(e>=1-1e-6&&Math.abs(e-Math.round(e))<1e-6)return e}return Math.max(1,t)}clearHelpers(){for(let t of[this.fine,this.coarse])t&&(this.group.remove(t),t.geometry.dispose(),t.material.dispose());this.fine=null,this.coarse=null}};import{Box3 as at,OrthographicCamera as lt,PerspectiveCamera as ct,Vector3 as M}from"three";var D=new at,z=new M,X=new M,ht=new M;function W(a){D.setFromObject(a),D.getSize(z),D.getCenter(X);let t=Math.max(z.x,1e-4),i=Math.max(z.y,1e-4),e=Math.max(z.z,1e-4),o=Math.max(t,i,e);return{width:t,height:i,depth:e,center:X.clone(),maxDim:o}}function Q(a,t,i=1.35){let e=t.fov*(Math.PI/180),o=a/(2*Math.tan(e/2))*i;return Math.max(o,.5)}function vt(a,t,i=1.35){let e=W(a),o=Q(e.maxDim,t,i);return t.position.copy(e.center).add(new M(o,o,o)),t.lookAt(e.center),t.near=Math.max(o/100,.01),t.far=Math.max(o*20,100),t.updateProjectionMatrix(),e}function bt(a,t,i,e=1.5){let o=W(a),s=ht.copy(i);s.lengthSq()<1e-8&&s.set(1,1,1),s.normalize();let r=o.maxDim*e;if(t instanceof ct)r=Q(o.maxDim,t,e),t.near=Math.max(r/100,.01),t.far=Math.max(r*20,100),t.updateProjectionMatrix();else if(t instanceof lt){let n=Math.max(t.top-t.bottom,1e-4);t.zoom=n/Math.max(o.maxDim*e,1e-4),t.near=.1,t.far=Math.max(o.maxDim*50,1e3),t.updateProjectionMatrix()}return t.position.copy(o.center).addScaledVector(s,r),t.lookAt(o.center),o}export{vt as a,bt as b,P as c,g as d,E as e,q as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f="zylemAssetKind",p="gaussian-splat";function i(e){return e.isGaussianSplat?!0:e.userData?.[f]===p}function v(e){e.traverse(n=>{n.isGaussianSplat&&(n.userData[f]=p)})}function w(e){let n=!1,r=!1;return e.traverse(t=>{if(i(t)){n=!0;return}(t.isMesh||t.isPoints)&&(r=!0)}),n&&!r}function _(e){let n=e;return i(e)&&n.splatGeometry?n.splatGeometry:n.geometry??null}function l(e,n,r){if(!e||typeof e!="object"||r>3||n.has(e))return;let t=e;if(t.isBufferAttribute){n.add(t),t.dispose();return}let s=e;"value"in s&&l(s.value,n,r+1)}function A(e){if(!i(e))return;let n=e,r=new Set,t=n.splatGeometry;if(t){for(let s of Object.values(t.attributes))l(s,r,0);t.dispose()}if(n._buffers)for(let s of Object.values(n._buffers))l(s,r,0);if(n._sort)for(let s of Object.values(n._sort))l(s,r,0);n.splatGeometry=void 0,n._buffers=null,n._sort=null}import{Mesh as y,Object3D as h,Points as S}from"three";import{clone as G}from"three/addons/utils/SkeletonUtils.js";var c="__zylemSplatSource";function O(e){if(i(e))return m(e);let n=[],r=[];e.traverse(t=>{i(t)&&n.push(t)});for(let t of n){let s=t.parent;if(!s)continue;let a=s.children.indexOf(t),o=new h;o.name=t.name,o.position.copy(t.position),o.quaternion.copy(t.quaternion),o.scale.copy(t.scale),o.userData[c]=n.indexOf(t),s.children[a]=o,o.parent=s,t.parent=null,r.push({parent:s,index:a,splat:t,placeholder:o})}try{let t=x(e);return g(t,n),t}finally{for(let t of r)t.parent.children[t.index]=t.splat,t.splat.parent=t.parent,t.placeholder.parent=null}}function m(e){let n=e.splatGeometry;if(!n)throw new Error("Cannot clone a Gaussian splat that has no capture geometry.");let r=e.constructor,t=new r(n.clone(),{autoSort:e.autoSort!==!1});t.name=e.name,t.visible=e.visible,t.position.copy(e.position),t.quaternion.copy(e.quaternion),t.scale.copy(e.scale),t.userData={...e.userData};for(let s of e.children)t.add(O(s));return t}function g(e,n){let r=[];e.traverse(t=>{typeof t.userData[c]=="number"&&r.push(t)});for(let t of r){let s=t.parent,a=n[t.userData[c]];if(!s||!a)continue;let o=s.children.indexOf(t),u=m(a);s.remove(t),s.children.splice(o,0,u),u.parent=s}}function x(e){let n=G(e),r=[],t=[];e.traverse(s=>r.push(s)),n.traverse(s=>t.push(s));for(let s=0;s<r.length;s++){let a=r[s],o=t[s];if(r.length!==t.length)break;D(a,o)}return n}function D(e,n){let r=d(e),t=d(n);!r||!t||(r.geometry?.clone&&(t.geometry=r.geometry.clone()),r.material&&(t.material=Array.isArray(r.material)?r.material.map(s=>s.clone()):r.material.clone()))}function d(e){return e instanceof y||e instanceof S?e:null}function b(e){let n=e.indexOf("?"),r=e.indexOf("#"),t=[n,r].filter(s=>s>=0).reduce((s,a)=>Math.min(s,a),e.length);return e.slice(0,t)}function j(e){let n=b(e),r=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return r>=0?n.slice(r+1):n}function N(e){let n=b(e),r=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return r<0?"":e.slice(0,r+1)}function R(e){let n=j(e),r=n.lastIndexOf(".");return r<0||r===n.length-1?null:n.slice(r+1).toLowerCase()}function z(e,n){if(/^[a-z][a-z\d+.-]*:/i.test(e)||e.startsWith("//"))return e;try{return new URL(e,n).toString()}catch{return`${N(n)}${e}`}}export{f as a,p as b,i as c,v as d,w as e,_ as f,A as g,O as h,j as i,N as j,R as k,z as l};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{D as z,F as E,a as f,b as p,j as v,r as T,s as _}from"./chunk-CI7A5N6G.js";import{c as Z}from"./chunk-EVYHPR3J.js";import{k as G}from"./chunk-YW2GTHCV.js";import{e as D}from"./chunk-UUOPT2N4.js";import{d as c}from"./chunk-4QLJUQSJ.js";import{c as y,h,j as M}from"./chunk-7WRQ2UAN.js";function S(n){return typeof n?.load=="function"&&typeof n?.data=="function"}var B=class{entityReference;constructor(t){this.entityReference=t}load(){this.entityReference.load&&this.entityReference.load()}data(){return this.entityReference.data?this.entityReference.data():null}};function et(n){let{args:t,defaultConfig:e,EntityClass:i,BuilderClass:o,entityType:r,MeshBuilderClass:d,CollisionBuilderClass:C,cloneFactory:N}=n,m=null,a,P=t.findIndex(s=>!(s instanceof f));P!==-1&&(a=t.splice(P,1).find(l=>!(l instanceof f)));let F=a?p(e,a):p(e);t.push(F);for(let s of t){if(s instanceof f)continue;let l=null,x=new i(s);try{if(S(x)){let u=new B(x);u.load(),l=u.data()}}catch(u){console.error("Error creating entity with loader:",u)}m=new o(s,x,d?new d(l):null,C?new C(l):null),s.material&&m.withMaterial(s.material,r)}if(!m)throw new Error(`missing options for ${String(r)}, builder is not initialized.`);let w=m.build();return a!=null&&typeof a=="object"&&"position"in a&&(w._spawnPositionExplicit=!0),E(w,s=>N(s))}import{Vector3 as O}from"three";var H={...T,size:new O(1,1,1),collision:{static:!0}},I=Symbol("Zone"),g=class extends z{static type=I;_enteredZone=new Map;_exitedZone=new Map;_zoneEntities=new Map;constructor(t){super(),this.options=p(H,t)}getSelectionBounds(t){let e=M(this.options.size,new O(1,1,1)),i=this.getPose()?.position??h(this.options.position,y);return t.setFromCenterAndSize(new O(i.x,i.y,i.z),e),D(t)}handlePostCollision({delta:t}){return this._enteredZone.forEach((e,i)=>{this.exited(t,i)}),this._enteredZone.size>0}handleIntersectionEvent({other:t,delta:e}){this._enteredZone.get(t.uuid)?this.held(e,t):(this.entered(t),this._zoneEntities.set(t.uuid,t))}onEnter(t){return this.options.onEnter=t,this}onHeld(t){return this.options.onHeld=t,this}onExit(t){return this.options.onExit=t,this}entered(t){this._enteredZone.set(t.uuid,1),this.options.onEnter&&this.options.onEnter({self:this,visitor:t,globals:c.globals})}exited(t,e){let i=this._exitedZone.get(e);if(i&&i>1+t){this._exitedZone.delete(e),this._enteredZone.delete(e);let o=this._zoneEntities.get(e);this.options.onExit&&this.options.onExit({self:this,visitor:o,globals:c.globals});return}this._exitedZone.set(e,1+t)}held(t,e){let i=this._enteredZone.get(e.uuid)??0;this._enteredZone.set(e.uuid,i+t),this._exitedZone.set(e.uuid,1),this.options.onHeld&&this.options.onHeld({delta:t,self:this,visitor:e,globals:c.globals,heldTime:i})}};function U(...n){let t=_(n,H),e=new g(t);return e.add(v({size:t.size,static:t.collision?.static??!0,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),E(e,i=>U(i??{}))}import{BufferGeometry as Y,Mesh as V,Color as $}from"three";import{Mesh as j}from"three";var b=class{_build(t,e,i){let o=new j(e,i.at(-1));return o.position.set(0,0,0),o.castShadow=!0,o.receiveShadow=!0,o}_postBuild(){}};var A=class extends Z{},R=class extends b{build(t){return new Y}postBuild(){}},L=class{meshBuilder;collisionBuilder;materialBuilder;options;entity;constructor(t,e,i,o){this.options=t,this.entity=e,this.meshBuilder=i,this.collisionBuilder=o,this.materialBuilder=new G;let r={meshBuilder:this.meshBuilder,collisionBuilder:this.collisionBuilder,materialBuilder:this.materialBuilder};this.options._builders=r,e&&e.options&&(e.options._builders=r)}withPosition(t){return this.options.position=t,this}withMaterial(t,e){return this.materialBuilder&&this.materialBuilder.build(t,e),this}applyMaterialToGroup(t,e){t.traverse(i=>{i instanceof V&&i.type==="SkinnedMesh"&&e[0]&&!i.material.map&&(i.material=e[0]),i.castShadow=!0,i.receiveShadow=!0})}build(){let t=this.entity;if(this.materialBuilder&&(t.materials=this.materialBuilder.materials),this.meshBuilder&&t.materials){let e=this.meshBuilder.build(this.options);t.mesh=this.meshBuilder._build(this.options,e,t.materials),this.meshBuilder.postBuild()}if(t.group&&t.materials&&this.applyMaterialToGroup(t.group,t.materials),this.collisionBuilder){this.collisionBuilder.withCollision(this.options?.collision||{});let[e,i]=this.collisionBuilder.build(this.options);t.bodyDesc=e,t.colliderDesc=i,t.colliderDescs.push(i);let{x:o,y:r,z:d}=h(this.options.position,y);t.bodyDesc.position=[o,r,d]}if(this.options.collisionType&&(t.collisionType=this.options.collisionType),this.options.color instanceof $){let e=i=>{let o=i;o&&o.color&&o.color.set&&o.color.set(this.options.color)};if(t.materials?.length)for(let i of t.materials)e(i);if(t.mesh&&t.mesh.material){let i=t.mesh.material;Array.isArray(i)?i.forEach(e):e(i)}t.group&&t.group.traverse(i=>{if(i instanceof V&&i.material){let o=i.material;Array.isArray(o)?o.forEach(e):e(o)}})}return t}};export{A as a,R as b,L as c,et as d,I as e,g as f,U as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as p}from"./chunk-7WRQ2UAN.js";import{Box3 as v,BoxGeometry as b,Color as E,Group as M,Mesh as x,MeshBasicMaterial as R,Vector3 as f}from"three";var j=.45,B=.12,g=.1;function N(r,e){return{source:r,options:e??{}}}var y=class{container;fadeOutDuration;materials=[];offset;onFrame;extent=null;display=0;from=0;to=0;elapsed=0;duration=0;targetOpacity=Number.NaN;colorKey="\0";tint=null;constructor(e,i){let n=i.options;this.fadeOutDuration=n.fadeOut??g,this.onFrame=n.onFrame;let t=p(n.offset,{x:0,y:0,z:0});this.offset=new f(t.x,t.y,t.z),this.container=new M,this.container.name="EntityRepresentative",this.container.visible=!1,e.add(this.container);let o=w(i);this.materials=o.materials,this.extent=o.extent,this.container.add(o.object),this.applyVisual()}get opacity(){return this.display}get fadeCompleted(){return this.duration<=0||this.elapsed>=this.duration-1e-8}measure(){return this.extent?this.extent.clone():null}setLook(e,i,n){let t=e?.opacity??n,o=e?.color==null?"":String(e.color);t===this.targetOpacity&&o===this.colorKey||(this.colorKey=o,this.tint=O(e?.color),this.fadeTo(t,i))}fadeTo(e,i){this.targetOpacity=e,this.from=this.display,this.to=e,this.elapsed=0,this.duration=Math.max(0,i),this.duration<=0&&(this.display=this.to,this.applyVisual())}showAt(e){this.container.position.copy(e),this.offset.lengthSq()>0&&this.container.position.add(this.offset),this.container.visible=!0}hide(){this.container.visible=!1}advance(e,i){if(this.duration<=0)this.display=this.to;else{this.elapsed+=Math.max(0,e);let t=Math.min(1,this.elapsed/this.duration);this.display=this.from+(this.to-this.from)*t}let n=this.display;this.onFrame?.({delta:e,opacity:n,setOpacity:t=>{n=t},valid:i.valid,position:i.position}),this.display=n,this.applyVisual()}dispose(){this.container.removeFromParent(),d(this.container),this.materials.length=0}applyVisual(){for(let e of this.materials){e.opacity=this.display,e.transparent=!0,e.depthWrite=!1;let i=e.userData.representativeBaseColor;e.color&&(this.tint?e.color.copy(this.tint):i&&e.color.copy(i))}}};function O(r){if(r==null)return null;try{return new E(r)}catch{return null}}function w(r){let e=T(r.source),i=typeof r.source=="function",n=V(e),t=e?A(e):null;i&&e&&S(e,t),t||(t=new x(new b(n.x,n.y,n.z),u(new R({color:16777215})))),t.position.set(0,0,0);let o=[];t.traverse(c=>{let l=c.material;if(!l)return;let h=Array.isArray(l)?l:[l];for(let m of h)o.push(m)});let a=new v().setFromObject(t),s=a.isEmpty()?n:a.getSize(new f);return{object:t,materials:o,extent:s}}function T(r){try{let e=typeof r=="function"?r():r;if(!e||typeof e.then=="function")return null;if(!e.group&&!e.mesh&&typeof e.create=="function"){let i=e.create();if(i&&typeof i.then=="function")return null}return e}catch(e){return console.warn("[zylem] entity representative: the source failed, using a box",e),null}}function V(r){let e=p(r?.options?.size,{x:1,y:1,z:1});return new f(e.x>0?e.x:1,e.y>0?e.y:1,e.z>0?e.z:1)}function A(r){let e=r.group??r.mesh;if(!e)return null;let i=e.clone(!0),n=[],t=[];e.traverse(o=>n.push(o)),i.traverse(o=>t.push(o));for(let o=0;o<n.length;o++){let a=n[o],s=t[o];a.geometry&&(s.geometry=a.geometry.clone()),a.material&&(s.material=Array.isArray(a.material)?a.material.map(c=>u(c)):u(a.material)),s.castShadow=!1,s.receiveShadow=!1}return i}function u(r){let e=r.clone();return e.transparent=!0,e.depthWrite=!1,e.color?.clone&&(e.userData.representativeBaseColor=e.color.clone()),e}function S(r,e){let i=new Set;e?.traverse(t=>{let o=t;o.geometry&&i.add(o.geometry);let a=o.material;if(a)for(let s of Array.isArray(a)?a:[a])i.add(s)});let n=r.group??r.mesh;n&&d(n,i)}function d(r,e){r.traverse(i=>{let n=i;n.geometry&&!e?.has(n.geometry)&&n.geometry.dispose();let t=n.material;if(t)for(let o of Array.isArray(t)?t:[t])e?.has(o)||o.dispose()})}export{j as a,B as b,N as c,y as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as v,D as E,F as l,r as m,s,w as y,y as c,z as i}from"./chunk-CI7A5N6G.js";import{Group as O,Vector3 as f}from"three";var A={...m,size:new f(1,1,1)},u=Symbol("HoverArea"),P=Symbol("DroppableArea");function n(t,e,r){let o=y(t);if(!o){r?i(t,e):c(t,e);return}if(r&&o.role!=="droppable"){i(t,{...o.handlers,...e});return}v(t,e)}var a=class extends E{static type=u;areaName="HoverArea";constructor(e){super(),this.options={...A,...e}}create(){return super.create(),this.group||(this.group=new O),this.group.name=this.name||this.areaName,this}onEnter(e){return n(this,{onEnter:e},!1),this}onLeave(e){return n(this,{onLeave:e},!1),this}onMove(e){return n(this,{onMove:e},!1),this}onClick(e){return n(this,{onClick:e},!1),this}},p=class extends a{static type=P;areaName="DroppableArea";onDrop(e){return n(this,{onDrop:e},!0),this}accepts(e){return n(this,{accepts:e},!0),this}};function b(t){return{onEnter:t.onEnter,onLeave:t.onLeave,onMove:t.onMove,onClick:t.onClick,onDrop:t.onDrop,accepts:t.accepts,placeAt:t.placeAt}}function h(...t){let e=s(t,A),r=new a(e);return c(r,b(e)),l(r,o=>h(o??{}))}function x(...t){let e=s(t,A),r=new p(e);return i(r,b(e)),l(r,o=>x(o??{}))}export{u as a,P as b,a as c,p as d,h as e,x as f};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{a as N,d as j,e as D,f as W,g as I,h as $}from"./chunk-5WRFDAZN.js";import{b as g}from"./chunk-2NO4YCLR.js";import{d as B,h as k,i as A,k as p}from"./chunk-T6O2SGH5.js";import{a as U}from"./chunk-QXVH6POE.js";import{b as c,i as u}from"./chunk-7WRQ2UAN.js";var X=`
|
|
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 ae=`
|
|
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
|
+
`,C={vertex:X,fragment:ae};import{AdditiveBlending as se}from"three";import{MeshBasicNodeMaterial as K,MeshStandardNodeMaterial as oe}from"three/webgpu";import{color as J,float as m,normalLocal as ie,normalView as ne,positionGeometry as de,positionViewDirection as le,vec4 as he}from"three/tsl";function Z(s,e){if(!s)return null;let t=s===!0?{}:s;return{color:t.color??e??"#ffffff",intensity:t.intensity??2.8,size:t.size??.06,falloff:t.falloff??1.6}}function z(s){return typeof s=="string"?s:`#${s.getHexString()}`}function V(){return ne.dot(le).abs().saturate()}function _(s){let e=V(),t=e.pow(m(s.falloff)),a=J(z(s.color)).mul(m(s.intensity)).mul(t),r=new K;if(r.colorNode=he(a,t),s.size>0){let o=e.oneMinus().add(.2);r.positionNode=de.add(ie.mul(m(s.size).mul(o)))}return r.transparent=!0,r.blending=se,r.depthWrite=!1,r.toneMapped=!1,r.needsUpdate=!0,r}function H(s,e){if(!(s instanceof oe)&&!(s instanceof K))return;let a=V().oneMinus().pow(m(e.falloff)),r=s;r.emissiveNode=J(z(e.color)).mul(m(e.intensity)).mul(a.add(.2)),s.needsUpdate=!0}import{Color as R,RepeatWrapping as w,SRGBColorSpace as ve}from"three";import{MeshBasicNodeMaterial as Se,MeshStandardNodeMaterial as F}from"three/webgpu";function Y(s){let e=Object.keys(s).sort().reduce((t,a)=>(t[a]=s[a],t),{});return JSON.stringify(e)}function q(s){let e=0;for(let t=0;t<s.length;t++)e=Math.imul(31,e)+s.charCodeAt(t)|0;return e.toString(36)}import{LoadingManager as Pe,Cache as ee}from"three";import{TextureLoader as ce,RepeatWrapping as Q}from"three";var y=16,T=class{loader;constructor(){this.loader=new ce}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(u(t.repeat,c)),a.wrapS=t?.wrapS??Q,a.wrapT=t?.wrapT??Q,t?.colorSpace!==void 0&&(a.colorSpace=t.colorSpace),a.anisotropy=t?.anisotropy??y,a}clone(e){let t=e.clone();return t.anisotropy=e.anisotropy||y,t.needsUpdate=!0,t}};import{GLTFLoader as pe}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as ue}from"three/addons/loaders/DRACOLoader.js";import{KTX2Loader as me}from"three/addons/loaders/KTX2Loader.js";import{MeshoptDecoder as fe}from"three/addons/libs/meshopt_decoder.module.js";var Le=["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"],ge="/three/draco/",P=class{loader;dracoLoader;ktx2Loader=null;meshoptEnabled=!1;configuredRenderer=null;ktx2TranscoderPath=null;gaussianPluginReady=null;constructor(){this.dracoLoader=new ue,this.dracoLoader.setDecoderPath(ge),this.loader=new pe,this.loader.setDRACOLoader(this.dracoLoader),this.setMeshoptEnabled(!0)}isSupported(e){let t=p(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 me,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){let a=await g(e,t);await this.prepareGaussianPlugin(a);let r=await this.loader.parseAsync(a,e);return this.applyTextureAnisotropy(r.scene),B(r.scene),{object:r.scene,animations:r.animations,gltf:r}}prepareGaussianPlugin(e){let t=D(e);return I(t)?Promise.reject($()):W(t)?(this.gaussianPluginReady??=this.registerGaussianPlugin().catch(a=>{throw this.gaussianPluginReady=null,a}),this.gaussianPluginReady):Promise.resolve()}async registerGaussianPlugin(){let{GLTFGaussianSplatLoaderExtension:e}=await import("three/addons/loaders/GLTFGaussianSplatLoaderExtension.js");this.loader.register(t=>new e(t))}clone(e){return{object:k(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 Le){let n=o[i];if(n&&n.isTexture){let d=n;d.anisotropy=y,d.needsUpdate=!0}}})}setMeshoptEnabled(e){if(e){if(this.meshoptEnabled)return;this.loader.setMeshoptDecoder(fe),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{AudioLoader as ye}from"three";var v=class{loader;constructor(){this.loader=new ye}isSupported(e){let t=p(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 Te}from"three";var f=class{loader;constructor(){this.loader=new Te}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))})}},S=class{fileLoader;constructor(){this.fileLoader=new f}isSupported(e){return p(e)==="json"}async load(e,t){return await this.fileLoader.load(e,{...t,responseType:"json"})}};function L(s){let e=[];return s?.upAxis==="z"&&e.push("up-z"),s?.applyUnitScale&&e.push("unit-scale"),s?.splatFrame==="y-down"&&e.push("y-down"),e.length?`:${e.join("+")}`:""}var O=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;fbxLoaderPromise=null;objLoaderPromise=null;geometryLoaderPromise=null;gaussianLoaderPromise=null;usdLoaderPromise=null;sogLoaderPromise=null;audioLoader;fileLoader;jsonLoader;bufferLoads=new Map;loadingManager;events;stats={texturesLoaded:0,modelsLoaded:0,audioLoaded:0,filesLoaded:0,cacheHits:0,cacheMisses:0};constructor(){this.textureLoader=new T,this.gltfLoader=new P,this.audioLoader=new v,this.fileLoader=new f,this.jsonLoader=new S,this.loadingManager=new Pe,this.loadingManager.onProgress=(e,t,a)=>{this.events.emit("batch:progress",{loaded:t,total:a})},this.events=U(),ee.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(u(t.repeat,c)),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){let a=await this.fbxLoader();return this.loadWithCache(`${e}${L(t)}`,"fbx",this.modelCache,()=>a.load(e,t),t,r=>t?.clone?a.clone(r):r)}async loadOBJ(e,t){let a=await this.objLoader(),r=t?.mtlPath?`${e}:${t.mtlPath}`:e;return this.loadWithCache(r,"obj",this.modelCache,()=>a.load(e,t),t,o=>t?.clone?a.clone(o):o)}async loadSTL(e,t){let a=await this.geometryLoader();return this.loadWithCache(`${e}${L(t)}`,"stl",this.modelCache,()=>a.load(e,t),t,r=>t?.clone?a.clone(r):r)}async loadPLY(e,t){let a=t?.fileType==="mesh"||t?.fileType==="splat"?t.fileType:null,r=L(t);if(!a&&!t?.forceReload){if(this.modelCache.has(`${e}:mesh${r}`))return this.loadCachedPly(e,"mesh",t);if(this.modelCache.has(`${e}:splat${r}`))return this.loadCachedPly(e,"splat",t)}let o=await this.loadBuffer(e,t),i=j(o,a);return this.loadParsedPly(e,i,o,t)}async loadUSD(e,t){let a=await this.usdLoader();return this.loadWithCache(e,"usd",this.modelCache,()=>a.load(e,t),t,r=>t?.clone?a.clone(r):r)}async loadGaussianSplat(e,t){let a=await this.gaussianLoader();return this.loadWithCache(`${e}${L(t)}`,"gaussian-splat",this.modelCache,()=>a.load(e,t),t,r=>t?.clone?a.clone(r):r)}async loadSOG(e,t){let a=await this.sogLoader();return this.loadWithCache(e,"sog",this.modelCache,()=>a.load(e,t),t,r=>t?.clone?a.clone(r):r)}async loadModel(e,t){let a=p(e);if(a==="abc")throw new Error(N);if(this.isSogRequest(e,t))return this.loadSOG(e,t);if(a==="ply"||!a&&(t?.fileType==="mesh"||t?.fileType==="splat"))return this.loadPLY(e,t);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);case"stl":return this.loadSTL(e,t);case"usd":case"usda":case"usdc":case"usdz":return this.loadUSD(e,t);case"spz":case"splat":case"ksplat":return this.loadGaussianSplat(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"stl":o=await this.loadSTL(r.url,r.options);break;case"ply":o=await this.loadPLY(r.url,r.options);break;case"usd":o=await this.loadUSD(r.url,r.options);break;case"gaussian-splat":o=await this.loadGaussianSplat(r.url,r.options);break;case"sog":o=await this.loadSOG(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.cacheHasUrl(this.textureCache,e)||this.cacheHasUrl(this.modelCache,e)||this.cacheHasUrl(this.audioCache,e)||this.cacheHasUrl(this.fileCache,e)||this.cacheHasUrl(this.jsonCache,e)}clearCache(e){if(e){this.deleteCacheUrl(this.textureCache,e,t=>this.disposeCachedTexture(t.result)),this.deleteCacheUrl(this.modelCache,e),this.deleteCacheUrl(this.audioCache,e),this.deleteCacheUrl(this.fileCache,e),this.deleteCacheUrl(this.jsonCache,e),this.bufferLoads.delete(e);return}for(let t of this.textureCache.values())this.disposeCachedTexture(t.result);this.textureCache.clear(),this.modelCache.clear(),this.audioCache.clear(),this.fileCache.clear(),this.jsonCache.clear(),this.bufferLoads.clear(),ee.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)}fbxLoader(){return this.fbxLoaderPromise??=import("./fbx-loader-SDI6QYTS.js").then(e=>new e.FBXLoaderAdapter),this.fbxLoaderPromise}objLoader(){return this.objLoaderPromise??=import("./obj-loader-SI5RVY24.js").then(e=>new e.OBJLoaderAdapter),this.objLoaderPromise}geometryLoader(){return this.geometryLoaderPromise??=import("./geometry-mesh-loader-XDJV77TU.js").then(e=>new e.GeometryMeshAdapter),this.geometryLoaderPromise}gaussianLoader(){return this.gaussianLoaderPromise??=import("./gaussian-splat-loader-ACFJKCCL.js").then(e=>new e.GaussianSplatAdapter),this.gaussianLoaderPromise}usdLoader(){return this.usdLoaderPromise??=import("./usd-loader-PCBATNPM.js").then(e=>new e.USDLoaderAdapter),this.usdLoaderPromise}sogLoader(){return this.sogLoaderPromise??=import("./sog-loader-BZFMQ3ZB.js").then(e=>new e.SogLoaderAdapter),this.sogLoaderPromise}isSogRequest(e,t){return A(e)==="lod-meta.json"?t?.fileType==="sog":t?.fileType==="sog"||p(e)==="sog"||A(e)==="meta.json"}loadBuffer(e,t){t?.forceReload&&this.bufferLoads.delete(e);let a=this.bufferLoads.get(e);if(a)return a;let r=g(e,t).finally(()=>{this.bufferLoads.delete(e)});return this.bufferLoads.set(e,r),r}loadCachedPly(e,t,a){return this.loadParsedPly(e,t,null,a)}async loadParsedPly(e,t,a,r){let o=`${e}:${t}${L(r)}`;if(t==="splat"){let d=await this.gaussianLoader();return this.loadWithCache(o,"gaussian-splat",this.modelCache,async()=>{let l=a??await this.loadBuffer(e,r);return d.parse("ply",l,r)},r,l=>r?.clone?d.clone(l):l)}let i=await this.geometryLoader(),n=await import("./geometry-mesh-loader-XDJV77TU.js");return this.loadWithCache(o,"ply",this.modelCache,async()=>{let d=a??await this.loadBuffer(e,r);return n.parseMeshPlyBuffer(d,r)},r,d=>r?.clone?i.clone(d):d)}cacheHasUrl(e,t){if(e.has(t))return!0;let a=`${t}:`;for(let r of e.keys())if(r.startsWith(a))return!0;return!1}deleteCacheUrl(e,t,a){for(let r of[...e.keys()])if(r===t||r.startsWith(`${t}:`)){let o=e.get(r);o&&a&&a(o),e.delete(r)}}disposeCachedTexture(e){if(!e)return;let t=e.image;t?.close?.();let a=e.source?.data;a&&a!==t&&a.close?.(),e.dispose()}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 h=await n.promise;return i?i(h):h}this.stats.cacheMisses++,this.events.emit("asset:loading",{url:e,type:t});let d=r(),l={promise:d,loadedAt:Date.now()};a.set(e,l);try{let h=await d;return l.result=h,this.updateStats(t),this.events.emit("asset:loaded",{url:e,type:t,fromCache:!1}),i?i(h):h}catch(h){throw a.delete(e),this.events.emit("asset:error",{url:e,type:t,error:h}),h}}updateStats(e){switch(e){case"texture":this.stats.texturesLoaded++;break;case"gltf":case"fbx":case"obj":case"stl":case"ply":case"usd":case"gaussian-splat":case"sog":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}/`}},G=O.getInstance();import{uniform as Ct,uv as Ot,time as Gt,vec3 as Rt,vec4 as Ft,float as Et,Fn as Ut}from"three/tsl";function we(s){return"colorNode"in s}function re(s){return"fragment"in s&&"vertex"in s}function be(s){return!!s&&re(s)&&s.vertex===C.vertex&&s.fragment===C.fragment}var te=class s{static sharedMaterialMap=new Map;static clearSharedMaterialCache(){s.sharedMaterialMap.clear()}materials=[];useTSL;constructor(e=!0){this.useTSL=e}trackSharedMaterial(e,t){let a=q(Y(e)),r=s.sharedMaterialMap.get(a);if(r){let o=r.geometryMap.get(t);o?r.geometryMap.set(t,o+1):r.geometryMap.set(t,1)}else s.sharedMaterialMap.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,l=Z(e.glow,i),h=be(n),b=!!n&&!h,M=!!a&&(!n||h),x=l!==null&&!M&&!b&&!a;if(M?this.setTexture(a??null,o,!0,d,i):b&&n?we(n)?this.setTSLShader(n,d):re(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 R("#ffffff"),!0,d)):a&&this.setTexture(a,o,!0,d,i),i&&!M&&!b&&!x&&this.withColor(i,!0,d),this.materials.length===0&&(x&&l?this.materials.push(_(l)):this.setColor(new R("#ffffff"),!0,d)),l&&!x&&this.materials.length>0){let E=this.materials[this.materials.length-1];E&&H(E,l)}r&&this.materials.length>0&&this.setNormalMap(r,o),this.trackSharedMaterial(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=c,a=!0,r,o){if(!e)return;let i=new F;o&&(i.color=o),this.applyOpacity(i,r),this.materials.push(i),G.loadTexture(e,{clone:!0,repeat:u(t,c),colorSpace:ve}).then(n=>{n.wrapS=w,n.wrapT=w,i.map=n,i.needsUpdate=!0})}setNormalMap(e,t=c){let a=this.materials[this.materials.length-1];a&&G.loadTexture(e,{clone:!0,repeat:u(t,c)}).then(r=>{r.wrapS=w,r.wrapT=w,a instanceof F&&(a.normalMap=r,a.needsUpdate=!0)})}setColor(e,t=!0,a){let r=new F;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 R("#ffffff"),!0,t)}setTSLShader(e,t){this.materials.push(Me(e,t))}};function Me(s,e){let t=new Se;return t.colorNode=s.colorNode,s.positionNode&&(t.positionNode=s.positionNode),s.normalNode&&(t.normalNode=s.normalNode),s.blending!==void 0&&(t.blending=s.blending),s.side!==void 0&&(t.side=s.side),s.depthTest!==void 0&&(t.depthTest=s.depthTest),e!==void 0&&(t.opacity=e),t.transparent=!!s.transparent||e!==void 0&&e<1,t.needsUpdate=!0,t}export{Y as a,q as b,X as c,C as d,y as e,G as f,_ as g,H as h,we as i,re as j,te as k,Me as l,Ct as m,Ot as n,Gt as o,Rt as p,Ft as q,Et as r,Ut as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as V,b as A,c as M,d as R}from"./chunk-UNCP6V7I.js";import{D as c,F as b,b as G,c as xt,d as Ot,e as St,f as wt,g as vt,h as Ct,r as p,s as f}from"./chunk-CI7A5N6G.js";import{k as bt}from"./chunk-YW2GTHCV.js";import{a as yt,b as Y,c as gt,d as ft,g as U,h as j,i as z}from"./chunk-7WRQ2UAN.js";import{BoxGeometry as Qt,CapsuleGeometry as te,ConeGeometry as Pt,CylinderGeometry as ee,Mesh as _,MeshStandardMaterial as ie,SphereGeometry as oe}from"three";function D(e,t=Symbol("mesh")){if(e.material||e.color){let i=new bt;if(i.build({...e.material,color:e.color??e.material?.color},t),i.materials.length>0)return i.materials}return[new ie]}function Z(e,t){if(t.position){let i=j(t.position,gt);e.position.set(i.x,i.y,i.z)}return e.castShadow=!0,e.receiveShadow=!0,e}function Mt(e={}){let t=j(e.size,ft),i=new Qt(t.x,t.y,t.z),o=D(e);return Z(new _(i,o.at(-1)),e)}function Rt(e={}){let t=new oe(e.radius??1),i=D(e);return Z(new _(t,i.at(-1)),e)}function _t(e={}){let t=new Pt(e.radius??1,e.height??2,e.radialSegments??32),i=D(e);return Z(new _(t,i.at(-1)),e)}function Dt(e={}){let t=new Pt(e.radius??1,e.height??2,4),i=D(e);return Z(new _(t,i.at(-1)),e)}function Zt(e={}){let t=new ee(e.radiusTop??1,e.radiusBottom??1,e.height??2,e.radialSegments??32),i=D(e);return Z(new _(t,i.at(-1)),e)}function Tt(e={}){let t=new te(e.radius??.5,e.length??1,e.capSegments??10,e.radialSegments??20),i=D(e);return Z(new _(t,i.at(-1)),e)}import{Vector3 as le}from"three";import{MeshStandardMaterial as ne,MeshBasicMaterial as se,MeshPhongMaterial as re}from"three";function ae(e){return e&&typeof e.getDebugInfo=="function"}var m=class{entity;constructor(t){this.entity=t}getPositionString(){if(this.entity.mesh){let{x:n,y:s,z:l}=this.entity.mesh.position;return`${n.toFixed(2)}, ${s.toFixed(2)}, ${l.toFixed(2)}`}let{x:t,y:i,z:o}=this.entity.options.position||{x:0,y:0,z:0};return`${t.toFixed(2)}, ${i.toFixed(2)}, ${o.toFixed(2)}`}getRotationString(){if(this.entity.mesh){let{x:s,y:l,z:r}=this.entity.mesh.rotation,a=u=>(u*180/Math.PI).toFixed(1);return`${a(s)}\xB0, ${a(l)}\xB0, ${a(r)}\xB0`}let{x:t,y:i,z:o}=this.entity.options.rotation||{x:0,y:0,z:0},n=s=>(s*180/Math.PI).toFixed(1);return`${n(t)}\xB0, ${n(i)}\xB0, ${n(o)}\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,i={type:t.type};return(t instanceof ne||t instanceof se||t instanceof re)&&(i.color=`#${t.color.getHexString()}`,i.opacity=t.opacity,i.transparent=t.transparent),"roughness"in t&&(i.roughness=t.roughness),"metalness"in t&&(i.metalness=t.metalness),i}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()},i=this.entity.body.linvel();return t.velocity=`${i.x.toFixed(2)}, ${i.y.toFixed(2)}, ${i.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()},i=this.getPhysicsInfo();if(i&&(t.physics=i),ae(this.entity)){let o=this.entity.getDebugInfo();return{...t,...o}}return t}};var Et={...p,size:new le(1,1,1)},ce=Symbol("Box"),q=class e extends c{static type=ce;constructor(t){super(),this.options={...Et,...t}}buildInfo(){let i=new m(this).buildDebugInfo(),{x:o,y:n,z:s}=this.options.size??{x:1,y:1,z:1};return{...i,type:String(e.type),size:`${o}, ${n}, ${s}`}}};function he(...e){let t=f(e,Et),i=new q(t);return i.add(Mt({size:t.size,material:t.material,color:t.color}),xt({size:t.size,static:t.collision?.static,sensor:t.collision?.sensor,canSleep:t.collision?.canSleep,ccdEnabled:t.collision?.ccdEnabled,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>he(o??{}))}var zt={...p,radius:1},me=Symbol("Sphere"),J=class e extends c{static type=me;constructor(t){super(),this.options={...zt,...t}}buildInfo(){let i=new m(this).buildDebugInfo(),o=this.options.radius??1;return{...i,type:String(e.type),radius:o.toFixed(2)}}};function pe(...e){let t=f(e,zt),i=new J(t);return i.add(Rt({radius:t.radius,material:t.material,color:t.color}),Ot({radius:t.radius,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>pe(o??{}))}var It={...p,radius:1,height:2,radialSegments:32},ue=Symbol("Cone"),K=class e extends c{static type=ue;constructor(t){super(),this.options={...It,...t}}buildInfo(){let i=new m(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...i,type:String(e.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function de(...e){let t=f(e,It),i=new K(t);return i.add(_t({radius:t.radius,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),St({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>de(o??{}))}var Bt={...p,radius:1,height:2},ye=Symbol("Pyramid"),Q=class e extends c{static type=ye;constructor(t){super(),this.options={...Bt,...t}}buildInfo(){let i=new m(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...i,type:String(e.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function ge(...e){let t=f(e,Bt),i=new Q(t);return i.add(Dt({radius:t.radius,height:t.height,material:t.material,color:t.color}),wt({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>ge(o??{}))}var Lt={...p,radiusTop:1,radiusBottom:1,height:2,radialSegments:32},fe=Symbol("Cylinder"),tt=class e extends c{static type=fe;constructor(t){super(),this.options={...Lt,...t}}buildInfo(){let i=new m(this).buildDebugInfo(),o=this.options.radiusTop??1,n=this.options.radiusBottom??1,s=this.options.height??2;return{...i,type:String(e.type),radiusTop:o.toFixed(2),radiusBottom:n.toFixed(2),height:s.toFixed(2)}}};function be(...e){let t=f(e,Lt),i=new tt(t);return i.add(Zt({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),vt({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>be(o??{}))}var kt={...p,radius:.5,length:1,capSegments:10,radialSegments:20},xe=Symbol("Pill"),et=class e extends c{static type=xe;constructor(t){super(),this.options={...kt,...t}}buildInfo(){let i=new m(this).buildDebugInfo(),o=this.options.radius??.5,n=this.options.length??1;return{...i,type:String(e.type),radius:o.toFixed(2),length:n.toFixed(2)}}};function Oe(...e){let t=f(e,kt),i=new et(t);return i.add(Tt({radius:t.radius,length:t.length,capSegments:t.capSegments,radialSegments:t.radialSegments,material:t.material,color:t.color}),Ct({radius:t.radius,length:t.length,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),b(i,o=>Oe(o??{}))}import{Group as Se,RingGeometry as we}from"three";var Ft={...p,innerRadius:0,outerRadius:1,thetaSegments:32},it=class extends V{collider(t){let i=t.outerRadius??1;return{shape:{type:"cylinder",halfHeight:.1/2,radius:i}}}},ot=class extends A{build(t){let i=t.innerRadius??0,o=t.outerRadius??1,n=t.thetaSegments??32,s=new we(i,o,n);return s.rotateX(-Math.PI/2),s}},nt=class extends M{createEntity(t){return new I(t)}build(){let t=super.build();return t.mesh&&!t.group&&(t.group=new Se,t.group.add(t.mesh)),t}},ve=Symbol("Disk"),I=class e extends c{static type=ve;constructor(t){super(),this.options={...Ft,...t}}buildInfo(){let i=new m(this).buildDebugInfo(),o=this.options.innerRadius??0,n=this.options.outerRadius??1;return{...i,type:String(e.type),innerRadius:o.toFixed(2),outerRadius:n.toFixed(2)}}};function Ce(...e){return R({args:e,defaultConfig:Ft,EntityClass:I,BuilderClass:nt,MeshBuilderClass:ot,CollisionBuilderClass:it,entityType:I.type,cloneFactory:t=>Ce(t??{})})}import{PlaneGeometry as Me,Vector2 as Gt,Vector3 as Vt}from"three";import{BufferGeometry as Pe,Float32BufferAttribute as st}from"three";var H=class e extends Pe{constructor(t=1,i=1,o=1,n=1){super(),this.type="XZPlaneGeometry",this.parameters={width:t,height:i,widthSegments:o,heightSegments:n};let s=t/2,l=i/2,r=Math.floor(o),a=Math.floor(n),u=r+1,v=a+1,w=t/r,g=i/a,d=[],x=[],O=[],T=[];for(let y=0;y<v;y++){let h=y*g-l;for(let S=0;S<u;S++){let P=S*w-s;x.push(P,0,h),O.push(0,1,0),T.push(S/r),T.push(1-y/a)}}for(let y=0;y<a;y++)for(let h=0;h<r;h++){let S=h+u*y,P=h+u*(y+1),E=h+1+u*(y+1),C=h+1+u*y;d.push(S,P,C),d.push(P,E,C)}this.setIndex(d),this.setAttribute("position",new st(x,3)),this.setAttribute("normal",new st(O,3)),this.setAttribute("uv",new st(T,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}};var N=4,At={...p,tile:new Gt(10,10),repeat:new Gt(1,1),collision:{static:!0},subdivisions:N,randomizeHeight:!1,heightScale:1};function Ht(e){let t=e.subdivisions??N,i=e.heightMap2D,o=e.heightMap,n=e.subdivisionsX??t,s=e.subdivisionsZ??t;return i&&i.length>0&&i[0]?.length>0?(s=i.length-1,n=i[0].length-1):o&&o.length>0&&(n=o.length-1),{subdivisionsX:n,subdivisionsZ:s}}var rt=class extends V{collider(t){let i=z(t.tile,Y),{subdivisionsX:o,subdivisionsZ:n}=Ht(t),s=new Vt(i.x,1,i.y),l=t._builders?.meshBuilder?.heightData??new Float32Array((o+1)*(n+1));return{shape:{type:"heightfield",rows:o,cols:n,heights:l,scale:[s.x,1,s.z]}}}},at=class extends A{heightData=new Float32Array;columnsRows=new Map;subdivisionsX=N;subdivisionsZ=N;build(t){let i=z(t.tile,Y),{subdivisionsX:o,subdivisionsZ:n}=Ht(t);this.subdivisionsX=o,this.subdivisionsZ=n;let s=new Vt(i.x,1,i.y),l=t.heightScale??1,r=new H(s.x,s.z,o,n),a=new Me(s.x,s.z,o,n),u=o>0?s.x/o:1,v=n>0?s.z/n:1,w=r.attributes.position.array,g=a.attributes.position.array,d=new Map,x=t.heightMap2D,O=t.heightMap,T=t.randomizeHeight??!1,y=(h,S)=>h<0?0:h>S?S:h;for(let h=0;h<g.length;h+=3){let S=g[h],P=g[h+1],E=y(Math.round((S+s.x/2)/u),o),C=y(Math.round((s.z/2-P)/v),n),F=0;if(x){let dt=x[C];dt&&(F=dt[E]??0)}else O&&O.length>0?F=O[E]??0:T&&(F=Math.random()*4);let X=F*l;g[h+2]=X,w[h+1]=X,d.get(C)||d.set(C,new Map),d.get(C).set(E,X)}return this.columnsRows=d,r}postBuild(){let t=[];for(let i=0;i<=this.subdivisionsX;++i)for(let o=0;o<=this.subdivisionsZ;++o){let n=this.columnsRows.get(o);t.push(n?.get(i)??0)}this.heightData=new Float32Array(t)}},lt=class extends M{createEntity(t){return new B(t)}},Re=Symbol("Plane"),B=class extends c{static type=Re;constructor(t){super(),this.options=G(At,t)}};function _e(...e){return R({args:e,defaultConfig:At,EntityClass:B,BuilderClass:lt,MeshBuilderClass:at,CollisionBuilderClass:rt,entityType:B.type,cloneFactory:t=>_e(t??{})})}import{Color as Xt,Group as Ze,Sprite as Te,SpriteMaterial as Ee,CanvasTexture as Yt,LinearFilter as $,Vector2 as mt,ClampToEdgeWrapping as Ut,ShaderMaterial as jt,Mesh as ze,PlaneGeometry as Ie,Vector3 as qt}from"three";var Nt={"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},center:{x:.5,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1}};function ct(e){return Nt[e]??Nt["top-left"]}function $t(e,t,i){let o=ct(e);return{x:o.x*i.width+t.x,y:o.y*i.height+t.y}}function ht(e){return{width:Math.max(1,e?.screenResolution?.x??1),height:Math.max(1,e?.screenResolution?.y??1)}}function De(e,t){let i=e.zoom||1;if(e.isPerspectiveCamera){let o=e,n=Math.tan(o.fov*Math.PI/180/2)*t/i;return{halfWidth:n*o.aspect,halfHeight:n}}if(e.isOrthographicCamera){let o=e;return{halfWidth:(o.right-o.left)/2/i,halfHeight:(o.top-o.bottom)/2/i}}return{halfWidth:1,halfHeight:1}}function Wt(e){let t=Math.max(.001,e.zDistance),{halfWidth:i,halfHeight:o}=De(e.camera,t),n=o*2/e.viewport.height,s=Math.max(1e-4,e.size.width*n),l=Math.max(1e-4,e.size.height*n),r=e.point.x/e.viewport.width*2-1,a=1-e.point.y/e.viewport.height*2;return{position:{x:r*i+(.5-e.pivot.x)*s,y:a*o+(e.pivot.y-.5)*l,z:-t},scale:{x:s,y:l}}}var W={position:void 0,width:120,height:48,fillColor:"#FFFFFF",strokeColor:null,strokeWidth:0,radius:0,padding:0,shape:"rect",image:null,stickToViewport:!0,screenPosition:new mt(24,24),zDistance:1},pt=class extends M{createEntity(t){return new L(t)}},Be=Symbol("Rect"),L=class e extends c{static type=Be;_sprite=null;_mesh=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;_image=null;_imageSource=null;constructor(t){super(),this.options=G(W,t),this.options.screenPosition=z(this.options.screenPosition,W.screenPosition),this.group=new Ze,this.createSprite(),this.prependSetup(this.rectSetup.bind(this)),this.prependUpdate(this.rectUpdate.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new Yt(this._canvas),this._texture.minFilter=$,this._texture.magFilter=$;let t=new Ee({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.01});this._sprite=new Te(t),this.group?.add(this._sprite),this.loadImage(),this.redrawRect()}loadImage(){let t=this.options.image||null;if(t===this._imageSource||(this._imageSource=t,this._image=null,!t))return;let i=new Image;i.crossOrigin="anonymous",i.onload=()=>{this._imageSource===t&&(this._image=i,this.redrawRect())},i.src=t}redrawRect(){if(!this._canvas||!this._ctx)return;let t=Math.max(2,Math.floor(this.options.width??120)),i=Math.max(2,Math.floor(this.options.height??48)),o=this.options.padding??0,n=this.options.strokeWidth??0,s=t+o*2+n,l=i+o*2+n,r=Math.max(2,s),a=Math.max(2,l),u=r!==this._lastCanvasW||a!==this._lastCanvasH;this._canvas.width=r,this._canvas.height=a,this._lastCanvasW=r,this._lastCanvasH=a,this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height);let v=Math.max(0,this.options.radius??0),w=Math.floor(o+n/2),g=Math.floor(o+n/2),d=Math.floor(t),x=Math.floor(i);if(this._ctx.beginPath(),this.options.shape==="ellipse"?this._ctx.ellipse(w+d/2,g+x/2,d/2,x/2,0,0,Math.PI*2):v>0?this.roundedRectPath(this._ctx,w,g,d,x,v):this._ctx.rect(w,g,d,x),this.options.fillColor&&(this._ctx.fillStyle=this.toCssColor(this.options.fillColor),this._ctx.fill()),this._image&&(this._ctx.save(),this._ctx.clip(),this._ctx.drawImage(this._image,w,g,d,x),this._ctx.restore()),this.options.strokeColor&&n>0&&(this._ctx.lineWidth=n,this._ctx.strokeStyle=this.toCssColor(this.options.strokeColor),this._ctx.stroke()),this._texture){if(u&&(this._texture.dispose(),this._texture=new Yt(this._canvas),this._texture.minFilter=$,this._texture.magFilter=$,this._texture.wrapS=Ut,this._texture.wrapT=Ut,this._sprite&&this._sprite.material instanceof jt)){let O=this._sprite.material;O.uniforms?.tDiffuse&&(O.uniforms.tDiffuse.value=this._texture),O.uniforms?.iResolution&&O.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)}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)}}getWidth(){return this.options.width??0}getHeight(){return this.options.height??0}roundedRectPath(t,i,o,n,s,l){let r=Math.min(l,Math.floor(Math.min(n,s)/2));t.moveTo(i+r,o),t.lineTo(i+n-r,o),t.quadraticCurveTo(i+n,o,i+n,o+r),t.lineTo(i+n,o+s-r),t.quadraticCurveTo(i+n,o+s,i+n-r,o+s),t.lineTo(i+r,o+s),t.quadraticCurveTo(i,o+s,i,o+s-r),t.lineTo(i,o+r),t.quadraticCurveTo(i,o,i+r,o)}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof Xt?t:new Xt(t)).getHexString()}`}rectSetup(t){if(this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&this._cameraRef.camera.add(this.group),this.materials?.length&&this._sprite){let i=this.materials[0];i instanceof jt&&(i.transparent=!0,i.depthTest=!1,i.depthWrite=!1,this._texture&&(i.uniforms?.tDiffuse&&(i.uniforms.tDiffuse.value=this._texture),i.uniforms?.iResolution&&this._canvas&&i.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)),this._mesh=new ze(new Ie(1,1),i),this.group?.add(this._mesh),this._sprite.visible=!1)}}rectUpdate(t){if(this._sprite){if(this._cameraRef&&this.options.bounds){let i=this.computeScreenBoundsFromOptions(this.options.bounds);if(i){let{x:o,y:n,width:s,height:l}=i,r=Math.max(2,Math.floor(s)),a=Math.max(2,Math.floor(l)),u=r!==(this.options.width??0)||a!==(this.options.height??0);this.options.screenPosition=new mt(Math.floor(o),Math.floor(n)),this.options.width=r,this.options.height=a,this.options.anchor=new mt(0,0),u&&this.redrawRect()}}this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}}screenPoint(t){let i=U(this.options.screenPosition,W.screenPosition);return this.options.screenAnchor&&!this.options.bounds?$t(this.options.screenAnchor,i,t):i}pivot(){if(this.options.anchor!=null){let t=U(this.options.anchor,yt);return{x:Math.min(100,Math.max(0,t.x))/100,y:Math.min(100,Math.max(0,t.y))/100}}return this.options.screenAnchor?ct(this.options.screenAnchor):{x:0,y:0}}updateStickyTransform(){if(!this._sprite||!this._cameraRef||!this._canvas)return;let t=ht(this._cameraRef),i=Wt({camera:this._cameraRef.camera,viewport:t,point:this.screenPoint(t),pivot:this.pivot(),size:{width:this._canvas.width,height:this._canvas.height},zDistance:this.options.zDistance??1});this._sprite.scale.set(i.scale.x,i.scale.y,1),this._mesh&&this._mesh.scale.set(i.scale.x,i.scale.y,1),this.group?.position.set(i.position.x,i.position.y,i.position.z)}worldToScreen(t){if(!this._cameraRef)return{x:0,y:0};let i=this._cameraRef.camera,{width:o,height:n}=ht(this._cameraRef),s=t.clone().project(i),l=(s.x+1)/2*o,r=(1-s.y)/2*n;return{x:l,y:r}}computeScreenBoundsFromOptions(t){if(!this._cameraRef)return null;if(t.screen)return{...t.screen};if(t.world){let{left:i,right:o,top:n,bottom:s,z:l=0}=t.world,r=this.worldToScreen(new qt(i,n,l)),a=this.worldToScreen(new qt(o,s,l)),u=Math.min(r.x,a.x),v=Math.min(r.y,a.y),w=Math.abs(a.x-r.x),g=Math.abs(a.y-r.y);return{x:u,y:v,width:w,height:g}}return null}updateRect(t){this.options={...this.options,...t},this.loadImage(),this.redrawRect(),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new m(this).buildDebugInfo(),type:String(e.type),width:this.options.width??0,height:this.options.height??0,shape:this.options.shape??"rect",sticky:this.options.stickToViewport}}};function Le(...e){return R({args:e,defaultConfig:{...W},EntityClass:L,BuilderClass:pt,entityType:L.type,cloneFactory:t=>Le(t??{})})}import{AmbientLight as ke,DirectionalLight as Fe,Group as Ge,HemisphereLight as Ve,Object3D as Ae,PointLight as He,SpotLight as Ne}from"three";var $e=Symbol("Light"),We={x:0,y:0,z:0},k=16777215,Xe={mapSize:2048,near:.1,far:500,bias:0,radius:1,left:-100,right:100,top:100,bottom:-100},Ye={mapSize:1024,near:.1,far:500,bias:0,radius:1},ut=class extends c{static type=$e;light=null;lightTarget=null;constructor(t){super(),this.options={...t}}create(){super.create();let t=new Ge,{light:i,target:o}=Ue(this.options);return t.add(i),o&&t.add(o),this.group=t,this.light=i,this.lightTarget=o,this}_cleanup(t){this.light?.shadow?.map?.dispose?.(),this.light=null,this.lightTarget=null,super._cleanup(t)}};function Ue(e){switch(e.type){case"ambient":return{light:je(e),target:null};case"hemisphere":return{light:qe(e),target:null};case"directional":return Je(e);case"point":return{light:Ke(e),target:null};case"spot":return Qe(e)}}function je(e){let t=new ke(e.color??k,e.intensity??1);return e.name&&(t.name=e.name),t}function qe(e){let t=e.skyColor??e.color??k,i=e.groundColor??0,o=new Ve(t,i,e.intensity??1);return e.name&&(o.name=e.name),o}function Je(e){let t=new Fe(e.color??k,e.intensity??1);e.name&&(t.name=e.name),ti(t,e.castShadow??!1,e.shadow);let i=Jt(e.position,e.target);return i&&(t.target=i),{light:t,target:i}}function Ke(e){let t=new He(e.color??k,e.intensity??1,e.distance,e.decay);return e.name&&(t.name=e.name),Kt(t,e.castShadow??!1,e.shadow),t}function Qe(e){let t=new Ne(e.color??k,e.intensity??1,e.distance,e.angle,e.penumbra,e.decay);e.name&&(t.name=e.name),Kt(t,e.castShadow??!1,e.shadow);let i=Jt(e.position,e.target);return i&&(t.target=i),{light:t,target:i}}function Jt(e,t){if(!t)return null;let i=e??We,o=new Ae;return o.position.set(t.x-i.x,t.y-i.y,t.z-i.z),o}function ti(e,t,i){if(!t){e.castShadow=!1;return}e.castShadow=!0;let o={...Xe,...i??{}};e.shadow.mapSize.set(o.mapSize,o.mapSize),e.shadow.camera.near=o.near,e.shadow.camera.far=o.far,e.shadow.camera.left=o.left,e.shadow.camera.right=o.right,e.shadow.camera.top=o.top,e.shadow.camera.bottom=o.bottom,e.shadow.bias=o.bias,e.shadow.radius=o.radius,e.shadow.camera.updateProjectionMatrix()}function Kt(e,t,i){if(!t){e.castShadow=!1;return}e.castShadow=!0;let o={...Ye,...i??{}};e.shadow.mapSize.set(o.mapSize,o.mapSize),e.shadow.camera.near=o.near,e.shadow.camera.far=o.far,e.shadow.bias=o.bias,e.shadow.radius=o.radius,e.shadow.camera.updateProjectionMatrix()}function Fo(e){return new ut(e)}export{m as a,Mt as b,Rt as c,_t as d,Dt as e,Zt as f,Tt as g,ce as h,q as i,he as j,me as k,J as l,pe as m,ue as n,K as o,de as p,ye as q,Q as r,ge as s,fe as t,tt as u,be as v,xe as w,et as x,Oe as y,ve as z,I as A,Ce as B,Re as C,B as D,_e as E,ct as F,$t as G,ht as H,Wt as I,Be as J,L as K,Le as L,$e as M,ut as N,Fo as O};
|
package/dist/cinematics.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { k as CutsceneEasing, V as Vec3Def, h as CutsceneScene, n as CameraShot, g as CutsceneDefinition, s as DollyPath, i as CutsceneCamera, o as CameraTrack, x as SceneTransition, y as SceneTransitionType, v as EventItem, w as AudioItem } from './cutscene-definition-C479fkei.js';
|
|
2
2
|
export { A as AudioItemSchema, q as AudioTrack, l as CameraKeyframe, c as CameraKeyframeSchema, m as CameraPoseDef, d as CameraShotSchema, j as CutsceneCameraKind, b as CutsceneCameraSchema, C as CutsceneDefinitionSchema, u as CutsceneEvent, e as CutsceneEventSchema, a as CutsceneSceneSchema, r as CutsceneTrack, f as CutsceneTrackSchema, D as DollyPathSchema, E as EventItemSchema, p as EventTrack, S as SceneTransitionSchema, t as ShotBlend } from './cutscene-definition-C479fkei.js';
|
|
3
|
-
import { f as CameraBehavior, d as CameraContext, C as CameraPose, l as ZylemCamera } from './zylem-camera-
|
|
3
|
+
import { f as CameraBehavior, d as CameraContext, C as CameraPose, l as ZylemCamera } from './zylem-camera-BA3VPFlS.js';
|
|
4
4
|
import { Z as ZylemTransitionShader } from './stage-transition-CmGpV4tc.js';
|
|
5
|
-
import { Z as ZylemStage, q as Stage } from './stage-
|
|
5
|
+
import { Z as ZylemStage, q as Stage } from './stage-Dez16Gxm.js';
|
|
6
6
|
import { g as SongDefinition } from './song-definition-rEKksP0B.js';
|
|
7
7
|
import { CutsceneStatusPayload, CutsceneViewPayload, CutsceneLoadPayload, CameraPosePayload } from '@zylem/bridge';
|
|
8
8
|
import '@sinclair/typebox';
|
|
@@ -13,10 +13,10 @@ import '@zylem/behaviors/core';
|
|
|
13
13
|
import 'three/webgpu';
|
|
14
14
|
import './base-node-idopiSw5.js';
|
|
15
15
|
import './base-node-life-cycle-BK9xebT9.js';
|
|
16
|
-
import './entity-type-map-
|
|
17
|
-
import './entity-
|
|
16
|
+
import './entity-type-map-BMaPY8cd.js';
|
|
17
|
+
import './entity-CY75JJSw.js';
|
|
18
18
|
import './vector-D3eDzvcA.js';
|
|
19
|
-
import './material-
|
|
19
|
+
import './material-D1IVeQc5.js';
|
|
20
20
|
import './collision-builder-BckxkdmA.js';
|
|
21
21
|
import './events.js';
|
|
22
22
|
import 'mitt';
|
|
@@ -24,7 +24,8 @@ import './selection-bounds-BKmSo9aG.js';
|
|
|
24
24
|
import '@zylem/behaviors/particle-emitter';
|
|
25
25
|
import 'three/addons/lines/webgpu/Line2.js';
|
|
26
26
|
import './game-interfaces-vF5sRi1n.js';
|
|
27
|
-
import './
|
|
27
|
+
import './placement-session-BNQoL7Jb.js';
|
|
28
|
+
import './transform-gizmo-DappLQ9w.js';
|
|
28
29
|
|
|
29
30
|
/**
|
|
30
31
|
* Pure evaluation of a cutscene at a point in time: which scene and shot are
|