ecspresso 0.13.4 → 0.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -6
- package/dist/index.js +2 -2
- package/dist/index.js.map +4 -4
- package/dist/plugins/ai/behavior-tree.d.ts +369 -0
- package/dist/plugins/ai/behavior-tree.js +4 -0
- package/dist/plugins/ai/behavior-tree.js.map +10 -0
- package/dist/plugins/ai/detection.js +2 -2
- package/dist/plugins/ai/detection.js.map +2 -2
- package/dist/plugins/ai/flocking.js +2 -2
- package/dist/plugins/ai/flocking.js.map +2 -2
- package/dist/plugins/ai/pathfinding.d.ts +163 -0
- package/dist/plugins/ai/pathfinding.js +4 -0
- package/dist/plugins/ai/pathfinding.js.map +10 -0
- package/dist/plugins/audio/audio.js +2 -2
- package/dist/plugins/audio/audio.js.map +2 -2
- package/dist/plugins/combat/health.js +2 -2
- package/dist/plugins/combat/health.js.map +2 -2
- package/dist/plugins/combat/projectile.js +2 -2
- package/dist/plugins/combat/projectile.js.map +2 -2
- package/dist/plugins/debug/diagnostics.js +3 -3
- package/dist/plugins/debug/diagnostics.js.map +2 -2
- package/dist/plugins/input/input.d.ts +105 -27
- package/dist/plugins/input/input.js +2 -2
- package/dist/plugins/input/input.js.map +3 -3
- package/dist/plugins/input/selection.js +2 -2
- package/dist/plugins/input/selection.js.map +2 -2
- package/dist/plugins/isometric/depth-sort.js +2 -2
- package/dist/plugins/isometric/depth-sort.js.map +2 -2
- package/dist/plugins/isometric/projection.js +2 -2
- package/dist/plugins/isometric/projection.js.map +2 -2
- package/dist/plugins/physics/collision.js +2 -2
- package/dist/plugins/physics/collision.js.map +2 -2
- package/dist/plugins/physics/collision3D.d.ts +83 -0
- package/dist/plugins/physics/collision3D.js +4 -0
- package/dist/plugins/physics/collision3D.js.map +13 -0
- package/dist/plugins/physics/physics2D.js +2 -2
- package/dist/plugins/physics/physics2D.js.map +2 -2
- package/dist/plugins/physics/physics3D.d.ts +140 -0
- package/dist/plugins/physics/physics3D.js +4 -0
- package/dist/plugins/physics/physics3D.js.map +11 -0
- package/dist/plugins/physics/steering.js +2 -2
- package/dist/plugins/physics/steering.js.map +2 -2
- package/dist/plugins/rendering/particles.js +2 -2
- package/dist/plugins/rendering/particles.js.map +2 -2
- package/dist/plugins/rendering/renderer2D.js +2 -2
- package/dist/plugins/rendering/renderer2D.js.map +3 -3
- package/dist/plugins/rendering/renderer3D.d.ts +247 -0
- package/dist/plugins/rendering/renderer3D.js +4107 -0
- package/dist/plugins/rendering/renderer3D.js.map +12 -0
- package/dist/plugins/rendering/sprite-animation.js +2 -2
- package/dist/plugins/rendering/sprite-animation.js.map +2 -2
- package/dist/plugins/rendering/tilemap.d.ts +230 -0
- package/dist/plugins/rendering/tilemap.js +4 -0
- package/dist/plugins/rendering/tilemap.js.map +11 -0
- package/dist/plugins/scripting/coroutine.js +2 -2
- package/dist/plugins/scripting/coroutine.js.map +2 -2
- package/dist/plugins/scripting/state-machine.js +2 -2
- package/dist/plugins/scripting/state-machine.js.map +2 -2
- package/dist/plugins/scripting/timers.js +2 -2
- package/dist/plugins/scripting/timers.js.map +2 -2
- package/dist/plugins/scripting/tween.js +2 -2
- package/dist/plugins/scripting/tween.js.map +2 -2
- package/dist/plugins/spatial/bounds.js +2 -2
- package/dist/plugins/spatial/bounds.js.map +2 -2
- package/dist/plugins/spatial/camera.js +2 -2
- package/dist/plugins/spatial/camera.js.map +2 -2
- package/dist/plugins/spatial/camera3D.d.ts +112 -0
- package/dist/plugins/spatial/camera3D.js +4 -0
- package/dist/plugins/spatial/camera3D.js.map +10 -0
- package/dist/plugins/spatial/spatial-index.js +2 -2
- package/dist/plugins/spatial/spatial-index.js.map +3 -3
- package/dist/plugins/spatial/spatial-index3D.d.ts +80 -0
- package/dist/plugins/spatial/spatial-index3D.js +4 -0
- package/dist/plugins/spatial/spatial-index3D.js.map +11 -0
- package/dist/plugins/spatial/transform.js +2 -2
- package/dist/plugins/spatial/transform.js.map +2 -2
- package/dist/plugins/spatial/transform3D.d.ts +148 -0
- package/dist/plugins/spatial/transform3D.js +4 -0
- package/dist/plugins/spatial/transform3D.js.map +10 -0
- package/dist/plugins/ui/ui.d.ts +116 -0
- package/dist/plugins/ui/ui.js +4 -0
- package/dist/plugins/ui/ui.js.map +11 -0
- package/dist/system-builder.d.ts +31 -0
- package/dist/utils/math.d.ts +65 -1
- package/dist/utils/narrowphase3D.d.ts +120 -0
- package/dist/utils/spatial-hash3D.d.ts +72 -0
- package/package.json +44 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var J=((
|
|
1
|
+
var H=Object.defineProperty;var J=(j)=>j;function K(j,x){this[j]=J.bind(null,x)}var M=(j,x)=>{for(var z in x)H(j,z,{get:x[z],enumerable:!0,configurable:!0,set:K.bind(x,z)})};var N=(j,x)=>()=>(j&&(x=j(j=0)),x);var Q=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(x,z)=>(typeof require<"u"?require:x)[z]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as L}from"ecspresso";function V(j,x){return{timer:{elapsed:0,duration:j,repeat:!1,active:!0,justFinished:!1,onComplete:x?.onComplete}}}function W(j,x){return{timer:{elapsed:0,duration:j,repeat:!0,active:!0,justFinished:!1,onComplete:x?.onComplete}}}function X(j){let{systemGroup:x="timers",priority:z=0,phase:B="preUpdate"}=j??{};return L("timers").withComponentTypes().withLabels().withGroups().install((C)=>{C.addSystem("timer-update").setPriority(z).inPhase(B).inGroup(x).addQuery("timers",{with:["timer"]}).setProcess(({queries:D,dt:E,ecs:F})=>{for(let A of D.timers){let{timer:k}=A.components;if(k.justFinished=!1,!k.active)continue;if(k.elapsed+=E,k.elapsed<k.duration)continue;if(k.repeat)while(k.elapsed>=k.duration)k.justFinished=!0,k.onComplete?.({entityId:A.id,duration:k.duration,elapsed:k.elapsed}),k.elapsed-=k.duration;else k.justFinished=!0,k.onComplete?.({entityId:A.id,duration:k.duration,elapsed:k.elapsed}),k.active=!1,F.commands.removeEntity(A.id)}})})}export{X as createTimerPlugin,V as createTimer,W as createRepeatingTimer};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=4C060CDC51331AFC64756E2164756E21
|
|
4
4
|
//# sourceMappingURL=timers.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Timer Plugin for ECSpresso\n *\n * Provides ECS-native timers following the \"data, not callbacks\" philosophy.\n * Timers are components processed each frame, automatically cleaned up when entities are removed.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\n\n// ==================== Event Types ====================\n\n/**\n * Data structure passed to onComplete callbacks when a timer completes.\n *\n * @example\n * ```typescript\n * createTimer(1.5, {\n * onComplete: (data) => {\n * console.log(`Timer on entity ${data.entityId} finished after ${data.elapsed}s`);\n * }\n * });\n * ```\n */\nexport interface TimerEventData {\n\t/** The entity ID that the timer belongs to */\n\tentityId: number;\n\t/** The timer's configured duration in seconds */\n\tduration: number;\n\t/** The actual elapsed time (may exceed duration slightly) */\n\telapsed: number;\n}\n\n// ==================== Component Types ====================\n\n\n/**\n * Timer component data structure.\n * Use `justFinished` to detect timer completion in your systems.\n */\nexport interface Timer {\n\t/** Time accumulated so far (seconds) */\n\telapsed: number;\n\t/** Target duration (seconds) */\n\tduration: number;\n\t/** Whether timer repeats after completion */\n\trepeat: boolean;\n\t/** Whether timer is currently running */\n\tactive: boolean;\n\t/** True for one frame after timer completes */\n\tjustFinished: boolean;\n\t/** Optional callback invoked when timer completes */\n\tonComplete?: (data: TimerEventData) => void;\n}\n\n/**\n * Component types provided by the timer plugin.\n * Included automatically via `.withPlugin(createTimerPlugin())`.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createTimerPlugin())\n * .withComponentTypes<{ velocity: { x: number; y: number }; player: true }>()\n * .build();\n * ```\n */\nexport interface TimerComponentTypes {\n\ttimer: Timer;\n}\n\n// ==================== Plugin Options ====================\n\n/**\n * Configuration options for the timer plugin.\n */\nexport interface TimerPluginOptions<G extends string = 'timers'> extends BasePluginOptions<G> {}\n\n// ==================== Helper Functions ====================\n\n/**\n * Options for timer creation\n */\nexport interface TimerOptions {\n\t/** Callback invoked when timer completes */\n\tonComplete?: (data: TimerEventData) => void;\n}\n\n/**\n * Create a one-shot timer that fires once after the specified duration.\n *\n * @param duration Duration in seconds until the timer completes\n * @param options Optional configuration including onComplete callback\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * // Timer without callback\n * ecs.spawn({\n * ...createTimer(2),\n * explosion: true,\n * });\n *\n * // Timer with onComplete callback\n * ecs.spawn({\n * ...createTimer(1.5, { onComplete: (data) => console.log('done', data.entityId) }),\n * });\n * ```\n */\nexport function createTimer(\n\tduration: number,\n\toptions?: TimerOptions\n): Pick<TimerComponentTypes, 'timer'> {\n\treturn {\n\t\ttimer: {\n\t\t\telapsed: 0,\n\t\t\tduration,\n\t\t\trepeat: false,\n\t\t\tactive: true,\n\t\t\tjustFinished: false,\n\t\t\tonComplete: options?.onComplete,\n\t\t},\n\t};\n}\n\n/**\n * Create a repeating timer that fires every `duration` seconds.\n *\n * @param duration Duration in seconds between each timer completion\n * @param options Optional configuration including onComplete callback\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * // Timer without callback\n * ecs.spawn({\n * ...createRepeatingTimer(5),\n * spawner: true,\n * });\n *\n * // Repeating timer with onComplete callback\n * ecs.spawn({\n * ...createRepeatingTimer(3, { onComplete: (data) => console.log('cycle', data.elapsed) }),\n * });\n * ```\n */\nexport function createRepeatingTimer(\n\tduration: number,\n\toptions?: TimerOptions\n): Pick<TimerComponentTypes, 'timer'> {\n\treturn {\n\t\ttimer: {\n\t\t\telapsed: 0,\n\t\t\tduration,\n\t\t\trepeat: true,\n\t\t\tactive: true,\n\t\t\tjustFinished: false,\n\t\t\tonComplete: options?.onComplete,\n\t\t},\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a timer plugin for ECSpresso.\n *\n * This plugin provides:\n * - Timer update system that processes all timer components each frame\n * - `justFinished` flag pattern for one-frame completion detection\n * - Automatic cleanup when entities are removed\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso\n * .create<Components, Events, Resources>()\n * .withPlugin(createTimerPlugin())\n * .build();\n *\n * // Spawn entity with timer\n * ecs.spawn({\n * ...createRepeatingTimer(5),\n * spawner: true,\n * });\n *\n * // React to timer completion in a system\n * ecs.addSystem('spawn-on-timer')\n * .addQuery('spawners', { with: ['timer', 'spawner'] })\n * .setProcess((queries, _dt, ecs) => {\n * for (const { components } of queries.spawners) {\n * if (components.timer.justFinished) {\n * ecs.spawn({ enemy: true });\n * }\n * }\n * });\n * ```\n */\nexport function createTimerPlugin<G extends string = 'timers'>(\n\toptions?: TimerPluginOptions<G>\n) {\n\tconst {\n\t\tsystemGroup = 'timers',\n\t\tpriority = 0,\n\t\tphase = 'preUpdate',\n\t} = options ?? {};\n\n\treturn definePlugin('timers')\n\t\t.withComponentTypes<TimerComponentTypes>()\n\t\t.withLabels<'timer-update'>()\n\t\t.withGroups<G>()\n\t\t.install((world) => {\n\t\t\tworld\n\t\t\t\t.addSystem('timer-update')\n\t\t\t\t.setPriority(priority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('timers', {\n\t\t\t\t\twith: ['timer'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tfor (const entity of queries.timers) {\n\t\t\t\t\t\tconst { timer } = entity.components;\n\n\t\t\t\t\t\t// Reset justFinished flag from previous frame\n\t\t\t\t\t\ttimer.justFinished = false;\n\n\t\t\t\t\t\t// Skip inactive timers\n\t\t\t\t\t\tif (!timer.active) continue;\n\n\t\t\t\t\t\t// Accumulate time\n\t\t\t\t\t\ttimer.elapsed += dt;\n\n\t\t\t\t\t\t// Check if timer completed\n\t\t\t\t\t\tif (timer.elapsed < timer.duration) continue;\n\n\t\t\t\t\t\t// Timer completed - handle based on repeat mode\n\t\t\t\t\t\tif (timer.repeat) {\n\t\t\t\t\t\t\t// Handle multiple cycles in one frame\n\t\t\t\t\t\t\twhile (timer.elapsed >= timer.duration) {\n\t\t\t\t\t\t\t\ttimer.justFinished = true;\n\t\t\t\t\t\t\t\ttimer.onComplete?.({ entityId: entity.id, duration: timer.duration, elapsed: timer.elapsed });\n\t\t\t\t\t\t\t\ttimer.elapsed -= timer.duration;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// One-shot timer\n\t\t\t\t\t\t\ttimer.justFinished = true;\n\t\t\t\t\t\t\ttimer.onComplete?.({ entityId: entity.id, duration: timer.duration, elapsed: timer.elapsed });\n\t\t\t\t\t\t\ttimer.active = false;\n\t\t\t\t\t\t\t// Auto-remove one-shot timer entities after completion.\n\t\t\t\t\t\t\t// If configurability is needed in the future, add an autoRemove option to TimerOptions.\n\t\t\t\t\t\t\tecs.commands.removeEntity(entity.id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t});\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": "4cAOA,uBAAS,kBAqGF,SAAS,CAAW,CAC1B,EACA,EACqC,CACrC,MAAO,CACN,MAAO,CACN,QAAS,EACT,WACA,OAAQ,GACR,OAAQ,GACR,aAAc,GACd,WAAY,GAAS,UACtB,CACD,EAwBM,SAAS,CAAoB,CACnC,EACA,EACqC,CACrC,MAAO,CACN,MAAO,CACN,QAAS,EACT,WACA,OAAQ,GACR,OAAQ,GACR,aAAc,GACd,WAAY,GAAS,UACtB,CACD,EAsCM,SAAS,CAA8C,CAC7D,EACC,CACD,IACC,cAAc,SACd,WAAW,EACX,QAAQ,aACL,GAAW,CAAC,EAEhB,OAAO,EAAa,QAAQ,EAC1B,mBAAwC,EACxC,WAA2B,EAC3B,WAAc,EACd,QAAQ,CAAC,IAAU,CACnB,EACE,UAAU,cAAc,EACxB,YAAY,CAAQ,EACpB,QAAQ,CAAK,EACb,QAAQ,CAAW,EACnB,SAAS,SAAU,CACnB,KAAM,CAAC,OAAO,CACf,CAAC,EACA,WAAW,EAAG,UAAS,KAAI,SAAU,CACrC,QAAW,KAAU,EAAQ,OAAQ,CACpC,IAAQ,SAAU,EAAO,WAMzB,GAHA,EAAM,aAAe,GAGjB,CAAC,EAAM,OAAQ,SAMnB,GAHA,EAAM,SAAW,EAGb,EAAM,QAAU,EAAM,SAAU,SAGpC,GAAI,EAAM,OAET,MAAO,EAAM,SAAW,EAAM,SAC7B,EAAM,aAAe,GACrB,EAAM,aAAa,CAAE,SAAU,EAAO,GAAI,SAAU,EAAM,SAAU,QAAS,EAAM,OAAQ,CAAC,EAC5F,EAAM,SAAW,EAAM,SAIxB,OAAM,aAAe,GACrB,EAAM,aAAa,CAAE,SAAU,EAAO,GAAI,SAAU,EAAM,SAAU,QAAS,EAAM,OAAQ,CAAC,EAC5F,EAAM,OAAS,GAGf,EAAI,SAAS,aAAa,EAAO,EAAE,GAGrC,EACF",
|
|
8
|
+
"debugId": "4C060CDC51331AFC64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var F=Object.defineProperty;var Q=(z)=>z;function b(z,D){this[z]=Q.bind(null,D)}var S=(z,D)=>{for(var H in D)F(z,H,{get:D[H],enumerable:!0,configurable:!0,set:b.bind(D,H)})};var f=(z,D)=>()=>(z&&(D=z(z=0)),D);var g=((z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(z,{get:(D,H)=>(typeof require<"u"?require:D)[H]}):z)(function(z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+z+'" is not supported')});import{definePlugin as h}from"ecspresso";function $(z){return z}var V=1.70158,y=V*1.525,C=V+1;var d=2*Math.PI/3,m=2*Math.PI/4.5;function E(z,D,H,J,M){let{from:N,easing:U=$,loop:W="once",loops:Y=1,onComplete:X}=M??{};return{tween:{steps:[{targets:[{component:z,path:D.split("."),from:N??null,to:H}],duration:J,easing:U}],currentStep:0,elapsed:0,loop:W,totalLoops:Y,completedLoops:0,direction:1,state:"pending",onComplete:X,justFinished:!1}}}function K(z,D){let{loop:H="once",loops:J=1,onComplete:M}=D??{};return{tween:{steps:z.map((N)=>({targets:N.targets.map((U)=>({component:U.component,path:U.field.split("."),from:U.from??null,to:U.to})),duration:N.duration,easing:N.easing??$})),currentStep:0,elapsed:0,loop:H,totalLoops:J,completedLoops:0,direction:1,state:"pending",onComplete:M,justFinished:!1}}}function w(z){return{createTween:E,createTweenSequence:K}}var G={parent:{},key:""};function L(z,D){let H=D.length-1,J=z;for(let N=0;N<H;N++){let U=D[N];if(U===void 0)return null;let W=J[U];if(W===null||W===void 0||typeof W!=="object")return null;J=W}let M=D[H];if(M===void 0)return null;if(!(M in J))return null;return G.parent=J,G.key=M,G}function R(z,D){let H=L(z,D);if(!H)return null;let J=H.parent[H.key];return typeof J==="number"?J:null}function j(z,D,H){let J=L(z,D);if(!J)return!1;return J.parent[J.key]=H,!0}function T(z,D,H){return z<D?D:z>H?H:z}function A(z,D){for(let H of z.steps)for(let J of H.targets){if(J.from!==null)continue;let M=D[J.component];if(!M||typeof M!=="object")continue;let N=R(M,J.path);if(N!==null)J.from=N;else J.from=0}}function x(z,D,H,J,M){let N=z.easing(D);for(let U of z.targets){let W=H[U.component];if(!W||typeof W!=="object")continue;let Y=U.from??0,X=Y+(U.to-Y)*N;if(j(W,U.path,X))M.markChanged(J,U.component)}}function q(z,D,H,J){for(let M of z.targets){let N=D[M.component];if(!N||typeof N!=="object")continue;if(j(N,M.path,M.to))J.markChanged(H,M.component)}}function _(z){for(let D of z.steps)for(let H of D.targets){let J=H.from??0;H.from=H.to,H.to=J}}function P(z,D,H){z.state="complete",z.justFinished=!0,z.onComplete?.({entityId:D,stepCount:z.steps.length}),H.commands.removeComponent(D,"tween")}function B(z,D,H){if(z.completedLoops++,z.loop==="once")return P(z,D,H),!1;if(z.totalLoops>0&&z.completedLoops>=z.totalLoops)return P(z,D,H),!1;if(z.loop==="yoyo")z.direction=z.direction===1?-1:1,_(z);return z.currentStep=0,z.elapsed>0}function k(z,D,H,J){let M=z.currentStep+1;if(M<z.steps.length){z.currentStep=M;let N=z.steps[M];if(N)for(let U of N.targets){if(U.from!==null)continue;let W=D[U.component];if(!W||typeof W!=="object")continue;let Y=R(W,U.path);U.from=Y??0}return!0}return B(z,H,J)}function O(z,D,H,J){while(!0){let M=z.steps[z.currentStep];if(!M)return;if(M.duration<=0){if(q(M,D,H,J),z.elapsed=0,!k(z,D,H,J))return;continue}if(z.elapsed>=M.duration){q(M,D,H,J);let U=z.elapsed-M.duration;if(z.elapsed=U,!k(z,D,H,J))return;continue}let N=T(z.elapsed/M.duration,0,1);x(M,N,D,H,J);return}}function r(z){let{systemGroup:D="tweens",priority:H=0,phase:J="update"}=z??{};return h("tweens").withComponentTypes().withLabels().withGroups().install((M)=>{M.addSystem("tween-update").setPriority(H).inPhase(J).inGroup(D).addQuery("tweens",{with:["tween"]}).setProcess(({queries:N,dt:U,ecs:W})=>{for(let Y of N.tweens){let X=Y.components.tween,Z=Y.components;if(X.justFinished){X.justFinished=!1;continue}if(X.state==="complete")continue;if(X.state==="pending")A(X,Z),X.state="active";if(!X.steps[X.currentStep])continue;X.elapsed+=U,O(X,Z,Y.id,W)}})})}export{K as createTweenSequence,r as createTweenPlugin,w as createTweenHelpers,E as createTween};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=9806996EDA5EA65464756E2164756E21
|
|
4
4
|
//# sourceMappingURL=tween.js.map
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"/**\n * Tween Plugin for ECSpresso\n *\n * Declarative property animation within the ECS. Tween any numeric component\n * field over time with standard easing functions, sequences, and completion events.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\nimport type { ComponentsOfWorld, AnyECSpresso } from 'ecspresso';\nimport { linear, type EasingFn } from '../../utils/easing';\n\n// ==================== Event Types ====================\n\n/**\n * Data structure published when a tween completes.\n * Use this type when defining tween completion events in your EventTypes interface.\n */\nexport interface TweenEventData {\n\t/** The entity ID the tween belongs to */\n\tentityId: number;\n\t/** Number of steps in the tween */\n\tstepCount: number;\n}\n\n\n// ==================== Component Types ====================\n\nexport interface TweenTarget {\n\t/** Component name on the entity */\n\tcomponent: string;\n\t/** Pre-split field path (e.g., ['position', 'x']) */\n\tpath: readonly string[];\n\t/** Starting value. null = resolve from current value on first tick */\n\tfrom: number | null;\n\t/** Target value */\n\tto: number;\n}\n\nexport interface TweenStep {\n\ttargets: TweenTarget[];\n\tduration: number;\n\teasing: EasingFn;\n}\n\nexport interface Tween {\n\tsteps: TweenStep[];\n\tcurrentStep: number;\n\telapsed: number;\n\tloop: LoopMode;\n\ttotalLoops: number;\n\tcompletedLoops: number;\n\tdirection: 1 | -1;\n\tstate: 'pending' | 'active' | 'complete';\n\tonComplete?: (data: TweenEventData) => void;\n\tjustFinished: boolean;\n}\n\nexport type LoopMode = 'once' | 'loop' | 'yoyo';\n\n/**\n * Component types provided by the tween plugin.\n */\nexport interface TweenComponentTypes {\n\ttween: Tween;\n}\n\n// ==================== Plugin Options ====================\n\nexport interface TweenPluginOptions<G extends string = 'tweens'> extends BasePluginOptions<G> {}\n\n// ==================== Helper Functions ====================\n\nexport interface TweenOptions {\n\t/** Explicit starting value (default: captures current value on first tick) */\n\tfrom?: number;\n\t/** Easing function (default: linear) */\n\teasing?: EasingFn;\n\t/** Loop mode (default: 'once') */\n\tloop?: LoopMode;\n\t/** Number of loops. -1 = infinite (default: 1) */\n\tloops?: number;\n\t/** Callback invoked when tween completes */\n\tonComplete?: (data: TweenEventData) => void;\n}\n\n/**\n * Create a single-target tween component.\n *\n * @param component Component name on the entity\n * @param field Field path (dot-separated for nested, e.g. 'position.x')\n * @param to Target value\n * @param duration Duration in seconds\n * @param options Optional configuration\n * @returns Component object suitable for spreading into spawn()\n */\nexport function createTween(\n\tcomponent: string,\n\tfield: string,\n\tto: number,\n\tduration: number,\n\toptions?: TweenOptions,\n): Pick<TweenComponentTypes, 'tween'> {\n\tconst {\n\t\tfrom,\n\t\teasing = linear,\n\t\tloop = 'once',\n\t\tloops = 1,\n\t\tonComplete,\n\t} = options ?? {};\n\n\treturn {\n\t\ttween: {\n\t\t\tsteps: [{\n\t\t\t\ttargets: [{\n\t\t\t\t\tcomponent,\n\t\t\t\t\tpath: field.split('.'),\n\t\t\t\t\tfrom: from ?? null,\n\t\t\t\t\tto,\n\t\t\t\t}],\n\t\t\t\tduration,\n\t\t\t\teasing,\n\t\t\t}],\n\t\t\tcurrentStep: 0,\n\t\t\telapsed: 0,\n\t\t\tloop,\n\t\t\ttotalLoops: loops,\n\t\t\tcompletedLoops: 0,\n\t\t\tdirection: 1,\n\t\t\tstate: 'pending',\n\t\t\tonComplete,\n\t\t\tjustFinished: false,\n\t\t},\n\t};\n}\n\nexport interface TweenSequenceStepInput {\n\ttargets: ReadonlyArray<{\n\t\tcomponent: string;\n\t\tfield: string;\n\t\tto: number;\n\t\tfrom?: number;\n\t}>;\n\tduration: number;\n\teasing?: EasingFn;\n}\n\nexport interface TweenSequenceOptions {\n\t/** Loop mode (default: 'once') */\n\tloop?: LoopMode;\n\t/** Number of loops. -1 = infinite (default: 1) */\n\tloops?: number;\n\t/** Callback invoked when tween completes */\n\tonComplete?: (data: TweenEventData) => void;\n}\n\n/**\n * Create a multi-step tween sequence. Each step can have parallel targets.\n *\n * @param steps Array of step definitions\n * @param options Optional configuration\n * @returns Component object suitable for spreading into spawn()\n */\nexport function createTweenSequence(\n\tsteps: ReadonlyArray<TweenSequenceStepInput>,\n\toptions?: TweenSequenceOptions,\n): Pick<TweenComponentTypes, 'tween'> {\n\tconst {\n\t\tloop = 'once',\n\t\tloops = 1,\n\t\tonComplete,\n\t} = options ?? {};\n\n\treturn {\n\t\ttween: {\n\t\t\tsteps: steps.map((step) => ({\n\t\t\t\ttargets: step.targets.map((target) => ({\n\t\t\t\t\tcomponent: target.component,\n\t\t\t\t\tpath: target.field.split('.'),\n\t\t\t\t\tfrom: target.from ?? null,\n\t\t\t\t\tto: target.to,\n\t\t\t\t})),\n\t\t\t\tduration: step.duration,\n\t\t\t\teasing: step.easing ?? linear,\n\t\t\t})),\n\t\t\tcurrentStep: 0,\n\t\t\telapsed: 0,\n\t\t\tloop,\n\t\t\ttotalLoops: loops,\n\t\t\tcompletedLoops: 0,\n\t\t\tdirection: 1,\n\t\t\tstate: 'pending',\n\t\t\tonComplete,\n\t\t\tjustFinished: false,\n\t\t},\n\t};\n}\n\n// ==================== Kit Types ====================\n\n/**\n * Recursively produce a union of dot-separated paths that resolve to `number`\n * within type T. Depth-limited to 4 levels to prevent TS recursion errors.\n *\n * @example\n * NumericPaths<{ x: number; y: number }> // 'x' | 'y'\n * NumericPaths<{ position: { x: number }; rotation: number }> // 'position.x' | 'rotation'\n */\nexport type NumericPaths<T, Depth extends readonly unknown[] = []> =\n\tDepth['length'] extends 4 ? never :\n\tT extends readonly unknown[] ? never :\n\tT extends Record<string, unknown>\n\t\t? { [K in keyof T & string]:\n\t\t\tNonNullable<T[K]> extends number\n\t\t\t\t? K\n\t\t\t\t: NonNullable<T[K]> extends readonly unknown[]\n\t\t\t\t\t? never\n\t\t\t\t\t: NonNullable<T[K]> extends Record<string, unknown>\n\t\t\t\t\t\t? `${K}.${NumericPaths<NonNullable<T[K]>, [...Depth, unknown]>}`\n\t\t\t\t\t\t: never\n\t\t}[keyof T & string]\n\t\t: never;\n\n/**\n * Discriminated union over component names: each variant constrains `field`\n * to the numeric paths of that component. TS narrows inline object literals\n * by `component` discriminant — zero runtime overhead.\n */\nexport type TypedTweenTargetInput<C extends Record<string, any>> = {\n\t[K in keyof C & string]: {\n\t\tcomponent: K;\n\t\tfield: NumericPaths<C[K]>;\n\t\tto: number;\n\t\tfrom?: number;\n\t}\n}[keyof C & string];\n\nexport interface TypedTweenSequenceStepInput<C extends Record<string, any>> {\n\ttargets: ReadonlyArray<TypedTweenTargetInput<C>>;\n\tduration: number;\n\teasing?: EasingFn;\n}\n\nexport interface TweenHelpers<W extends AnyECSpresso> {\n\tcreateTween: <K extends keyof ComponentsOfWorld<W> & string>(\n\t\tcomponent: K,\n\t\tfield: NumericPaths<ComponentsOfWorld<W>[K]>,\n\t\tto: number,\n\t\tduration: number,\n\t\toptions?: {\n\t\t\tfrom?: number;\n\t\t\teasing?: EasingFn;\n\t\t\tloop?: LoopMode;\n\t\t\tloops?: number;\n\t\t\tonComplete?: (data: TweenEventData) => void;\n\t\t},\n\t) => Pick<TweenComponentTypes, 'tween'>;\n\tcreateTweenSequence: (\n\t\tsteps: ReadonlyArray<TypedTweenSequenceStepInput<ComponentsOfWorld<W>>>,\n\t\toptions?: {\n\t\t\tloop?: LoopMode;\n\t\t\tloops?: number;\n\t\t\tonComplete?: (data: TweenEventData) => void;\n\t\t},\n\t) => Pick<TweenComponentTypes, 'tween'>;\n}\n\nexport function createTweenHelpers<W extends AnyECSpresso>(_world?: W): TweenHelpers<W> {\n\treturn {\n\t\tcreateTween: createTween as TweenHelpers<W>['createTween'],\n\t\tcreateTweenSequence: createTweenSequence as TweenHelpers<W>['createTweenSequence'],\n\t};\n}\n\n// ==================== Field Path Resolution ====================\n\n/**\n * Module-scoped mutable result to avoid per-call allocation in hot path.\n */\nconst _fieldRef: { parent: Record<string, unknown>; key: string } = { parent: {} as Record<string, unknown>, key: '' };\n\n/**\n * Traverse an object by path segments. Returns the parent object and final key\n * for read/write, or null if any segment is missing.\n */\nfunction resolveField(obj: Record<string, unknown>, path: readonly string[]): typeof _fieldRef | null {\n\tconst lastIdx = path.length - 1;\n\tlet current: Record<string, unknown> = obj;\n\n\tfor (let i = 0; i < lastIdx; i++) {\n\t\tconst segment = path[i];\n\t\tif (segment === undefined) return null;\n\t\tconst next = current[segment];\n\t\tif (next === null || next === undefined || typeof next !== 'object') return null;\n\t\tcurrent = next as Record<string, unknown>;\n\t}\n\n\tconst finalKey = path[lastIdx];\n\tif (finalKey === undefined) return null;\n\tif (!(finalKey in current)) return null;\n\n\t_fieldRef.parent = current;\n\t_fieldRef.key = finalKey;\n\treturn _fieldRef;\n}\n\nfunction readField(obj: Record<string, unknown>, path: readonly string[]): number | null {\n\tconst ref = resolveField(obj, path);\n\tif (!ref) return null;\n\tconst val = ref.parent[ref.key];\n\treturn typeof val === 'number' ? val : null;\n}\n\nfunction writeField(obj: Record<string, unknown>, path: readonly string[], value: number): boolean {\n\tconst ref = resolveField(obj, path);\n\tif (!ref) return false;\n\tref.parent[ref.key] = value;\n\treturn true;\n}\n\n// ==================== System Logic ====================\n\nfunction clamp(value: number, min: number, max: number): number {\n\treturn value < min ? min : value > max ? max : value;\n}\n\n/**\n * Resolve all null `from` values by reading current component field values.\n */\nfunction resolveFromValues(\n\ttween: Tween,\n\tentityComponents: Record<string, unknown>,\n): void {\n\tfor (const step of tween.steps) {\n\t\tfor (const target of step.targets) {\n\t\t\tif (target.from !== null) continue;\n\t\t\tconst comp = entityComponents[target.component];\n\t\t\tif (!comp || typeof comp !== 'object') continue;\n\t\t\tconst val = readField(comp as Record<string, unknown>, target.path);\n\t\t\tif (val !== null) {\n\t\t\t\ttarget.from = val;\n\t\t\t} else {\n\t\t\t\ttarget.from = 0;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Apply interpolation for a step's targets at a given progress.\n */\nfunction applyStep(\n\tstep: TweenStep,\n\tprogress: number,\n\tentityComponents: Record<string, unknown>,\n\tentityId: number,\n\tecs: { markChanged: (entityId: number, componentName: any) => void },\n): void {\n\tconst easedT = step.easing(progress);\n\n\tfor (const target of step.targets) {\n\t\tconst comp = entityComponents[target.component];\n\t\tif (!comp || typeof comp !== 'object') continue;\n\t\tconst from = target.from ?? 0;\n\t\tconst value = from + (target.to - from) * easedT;\n\t\tconst written = writeField(comp as Record<string, unknown>, target.path, value);\n\t\tif (written) {\n\t\t\tecs.markChanged(entityId, target.component);\n\t\t}\n\t}\n}\n\n/**\n * Snap all targets in a step to their final values (from or to depending on direction).\n */\nfunction snapStepToEnd(\n\tstep: TweenStep,\n\tentityComponents: Record<string, unknown>,\n\tentityId: number,\n\tecs: { markChanged: (entityId: number, componentName: any) => void },\n): void {\n\tfor (const target of step.targets) {\n\t\tconst comp = entityComponents[target.component];\n\t\tif (!comp || typeof comp !== 'object') continue;\n\t\tconst written = writeField(comp as Record<string, unknown>, target.path, target.to);\n\t\tif (written) {\n\t\t\tecs.markChanged(entityId, target.component);\n\t\t}\n\t}\n}\n\n/**\n * Reverse all from/to values in every step (for yoyo).\n */\nfunction reverseAllTargets(tween: Tween): void {\n\tfor (const step of tween.steps) {\n\t\tfor (const target of step.targets) {\n\t\t\tconst tmp = target.from ?? 0;\n\t\t\ttarget.from = target.to;\n\t\t\ttarget.to = tmp;\n\t\t}\n\t}\n}\n\n// ==================== Tween Processing Helpers ====================\n\ntype TweenEcs = { markChanged: (entityId: number, componentName: any) => void; commands: { removeComponent: (entityId: number, componentName: any) => void } };\n\nfunction completeTween(\n\ttween: Tween,\n\tentityId: number,\n\tecs: { commands: { removeComponent: (entityId: number, componentName: any) => void } },\n): void {\n\ttween.state = 'complete';\n\ttween.justFinished = true;\n\n\ttween.onComplete?.({ entityId, stepCount: tween.steps.length });\n\tecs.commands.removeComponent(entityId, 'tween');\n}\n\nfunction handleTweenEnd(\n\ttween: Tween,\n\tentityId: number,\n\tecs: TweenEcs,\n): boolean {\n\ttween.completedLoops++;\n\n\tif (tween.loop === 'once') {\n\t\tcompleteTween(tween, entityId, ecs);\n\t\treturn false;\n\t}\n\n\t// Check if finite loops exhausted\n\tif (tween.totalLoops > 0 && tween.completedLoops >= tween.totalLoops) {\n\t\tcompleteTween(tween, entityId, ecs);\n\t\treturn false;\n\t}\n\n\t// Loop continues\n\tif (tween.loop === 'yoyo') {\n\t\ttween.direction = tween.direction === 1 ? -1 : 1;\n\t\treverseAllTargets(tween);\n\t}\n\n\ttween.currentStep = 0;\n\n\t// For 'loop' mode, from values stay as-is so the animation replays identically.\n\t// For 'yoyo' mode, reverseAllTargets already swapped from/to.\n\n\treturn tween.elapsed > 0;\n}\n\n/**\n * Advance to next step. Returns true if there's more work to process,\n * false if the tween has completed or looped.\n */\nfunction advanceStep(\n\ttween: Tween,\n\tentityComponents: Record<string, unknown>,\n\tentityId: number,\n\tecs: TweenEcs,\n): boolean {\n\tconst nextStep = tween.currentStep + 1;\n\n\tif (nextStep < tween.steps.length) {\n\t\t// More steps — resolve from values for next step and continue\n\t\ttween.currentStep = nextStep;\n\t\tconst step = tween.steps[nextStep];\n\t\tif (step) {\n\t\t\tfor (const target of step.targets) {\n\t\t\t\tif (target.from !== null) continue;\n\t\t\t\tconst comp = entityComponents[target.component];\n\t\t\t\tif (!comp || typeof comp !== 'object') continue;\n\t\t\t\tconst val = readField(comp as Record<string, unknown>, target.path);\n\t\t\t\ttarget.from = val ?? 0;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// All steps done — handle loop/complete\n\treturn handleTweenEnd(tween, entityId, ecs);\n}\n\nfunction processTweenProgress(\n\ttween: Tween,\n\tentityComponents: Record<string, unknown>,\n\tentityId: number,\n\tecs: TweenEcs,\n): void {\n\t// eslint-disable-next-line no-constant-condition\n\twhile (true) {\n\t\tconst currentStep = tween.steps[tween.currentStep];\n\t\tif (!currentStep) return;\n\n\t\t// Zero-duration steps complete immediately\n\t\tif (currentStep.duration <= 0) {\n\t\t\tsnapStepToEnd(currentStep, entityComponents, entityId, ecs);\n\t\t\ttween.elapsed = 0;\n\n\t\t\tif (!advanceStep(tween, entityComponents, entityId, ecs)) return;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (tween.elapsed >= currentStep.duration) {\n\t\t\t// Step complete — snap to end and carry overflow\n\t\t\tsnapStepToEnd(currentStep, entityComponents, entityId, ecs);\n\t\t\tconst overflow = tween.elapsed - currentStep.duration;\n\t\t\ttween.elapsed = overflow;\n\n\t\t\tif (!advanceStep(tween, entityComponents, entityId, ecs)) return;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Step in progress — interpolate\n\t\tconst progress = clamp(tween.elapsed / currentStep.duration, 0, 1);\n\t\tapplyStep(currentStep, progress, entityComponents, entityId, ecs);\n\t\treturn;\n\t}\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a tween plugin for ECSpresso.\n *\n * This plugin provides:\n * - Tween system that processes all tween components each frame\n * - Support for single-field, multi-target, and multi-step sequences\n * - 31 standard easing functions\n * - Loop modes: once, loop, yoyo\n * - `justFinished` flag for one-frame completion detection\n * - `onComplete` callback on completion\n * - Change detection via markChanged\n */\nexport function createTweenPlugin<G extends string = 'tweens'>(\n\toptions?: TweenPluginOptions<G>\n) {\n\tconst {\n\t\tsystemGroup = 'tweens',\n\t\tpriority = 0,\n\t\tphase = 'update',\n\t} = options ?? {};\n\n\treturn definePlugin('tweens')\n\t\t.withComponentTypes<TweenComponentTypes>()\n\t\t.withLabels<'tween-update'>()\n\t\t.withGroups<G>()\n\t\t.install((world) => {\n\t\t\tworld\n\t\t\t\t.addSystem('tween-update')\n\t\t\t\t.setPriority(priority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('tweens', {\n\t\t\t\t\twith: ['tween'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tfor (const entity of queries.tweens) {\n\t\t\t\t\t\tconst tween = entity.components.tween as Tween;\n\t\t\t\t\t\tconst entityComponents = entity.components as Record<string, unknown>;\n\n\t\t\t\t\t\t// Reset justFinished flag from previous frame\n\t\t\t\t\t\tif (tween.justFinished) {\n\t\t\t\t\t\t\ttween.justFinished = false;\n\t\t\t\t\t\t\t// Component removal was queued, skip processing\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Skip completed tweens\n\t\t\t\t\t\tif (tween.state === 'complete') continue;\n\n\t\t\t\t\t\t// Resolve pending state: capture null from values\n\t\t\t\t\t\tif (tween.state === 'pending') {\n\t\t\t\t\t\t\tresolveFromValues(tween, entityComponents);\n\t\t\t\t\t\t\ttween.state = 'active';\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Process active tween\n\t\t\t\t\t\tconst currentStep = tween.steps[tween.currentStep];\n\t\t\t\t\t\tif (!currentStep) continue;\n\n\t\t\t\t\t\ttween.elapsed += dt;\n\n\t\t\t\t\t\tprocessTweenProgress(tween, entityComponents, entity.id, ecs);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t});\n}\n",
|
|
6
6
|
"/**\n * Easing Functions\n *\n * 31 standard easing functions for animation. Pure math, no dependencies.\n */\n\nexport type EasingFn = (t: number) => number;\n\nexport function linear(t: number): number {\n\treturn t;\n}\n\n// Quad\nexport function easeInQuad(t: number): number {\n\treturn t * t;\n}\n\nexport function easeOutQuad(t: number): number {\n\treturn t * (2 - t);\n}\n\nexport function easeInOutQuad(t: number): number {\n\treturn t < 0.5\n\t\t? 2 * t * t\n\t\t: -1 + (4 - 2 * t) * t;\n}\n\n// Cubic\nexport function easeInCubic(t: number): number {\n\treturn t * t * t;\n}\n\nexport function easeOutCubic(t: number): number {\n\tconst t1 = t - 1;\n\treturn t1 * t1 * t1 + 1;\n}\n\nexport function easeInOutCubic(t: number): number {\n\treturn t < 0.5\n\t\t? 4 * t * t * t\n\t\t: 1 + (t - 1) * (2 * t - 2) * (2 * t - 2);\n}\n\n// Quart\nexport function easeInQuart(t: number): number {\n\treturn t * t * t * t;\n}\n\nexport function easeOutQuart(t: number): number {\n\tconst t1 = t - 1;\n\treturn 1 - t1 * t1 * t1 * t1;\n}\n\nexport function easeInOutQuart(t: number): number {\n\treturn t < 0.5\n\t\t? 8 * t * t * t * t\n\t\t: 1 - 8 * (t - 1) * (t - 1) * (t - 1) * (t - 1);\n}\n\n// Quint\nexport function easeInQuint(t: number): number {\n\treturn t * t * t * t * t;\n}\n\nexport function easeOutQuint(t: number): number {\n\tconst t1 = t - 1;\n\treturn 1 + t1 * t1 * t1 * t1 * t1;\n}\n\nexport function easeInOutQuint(t: number): number {\n\treturn t < 0.5\n\t\t? 16 * t * t * t * t * t\n\t\t: 1 + 16 * (t - 1) * (t - 1) * (t - 1) * (t - 1) * (t - 1);\n}\n\n// Sine\nexport function easeInSine(t: number): number {\n\treturn 1 - Math.cos((t * Math.PI) / 2);\n}\n\nexport function easeOutSine(t: number): number {\n\treturn Math.sin((t * Math.PI) / 2);\n}\n\nexport function easeInOutSine(t: number): number {\n\treturn -(Math.cos(Math.PI * t) - 1) / 2;\n}\n\n// Expo\nexport function easeInExpo(t: number): number {\n\treturn t === 0 ? 0 : Math.pow(2, 10 * (t - 1));\n}\n\nexport function easeOutExpo(t: number): number {\n\treturn t === 1 ? 1 : 1 - Math.pow(2, -10 * t);\n}\n\nexport function easeInOutExpo(t: number): number {\n\tif (t === 0) return 0;\n\tif (t === 1) return 1;\n\treturn t < 0.5\n\t\t? Math.pow(2, 20 * t - 10) / 2\n\t\t: (2 - Math.pow(2, -20 * t + 10)) / 2;\n}\n\n// Circ\nexport function easeInCirc(t: number): number {\n\treturn 1 - Math.sqrt(1 - t * t);\n}\n\nexport function easeOutCirc(t: number): number {\n\tconst t1 = t - 1;\n\treturn Math.sqrt(1 - t1 * t1);\n}\n\nexport function easeInOutCirc(t: number): number {\n\treturn t < 0.5\n\t\t? (1 - Math.sqrt(1 - 4 * t * t)) / 2\n\t\t: (Math.sqrt(1 - (-2 * t + 2) * (-2 * t + 2)) + 1) / 2;\n}\n\n// Back\nconst BACK_C1 = 1.70158;\nconst BACK_C2 = BACK_C1 * 1.525;\nconst BACK_C3 = BACK_C1 + 1;\n\nexport function easeInBack(t: number): number {\n\treturn BACK_C3 * t * t * t - BACK_C1 * t * t;\n}\n\nexport function easeOutBack(t: number): number {\n\tconst t1 = t - 1;\n\treturn 1 + BACK_C3 * t1 * t1 * t1 + BACK_C1 * t1 * t1;\n}\n\nexport function easeInOutBack(t: number): number {\n\treturn t < 0.5\n\t\t? ((2 * t) * (2 * t) * ((BACK_C2 + 1) * 2 * t - BACK_C2)) / 2\n\t\t: ((2 * t - 2) * (2 * t - 2) * ((BACK_C2 + 1) * (t * 2 - 2) + BACK_C2) + 2) / 2;\n}\n\n// Elastic\nconst ELASTIC_C4 = (2 * Math.PI) / 3;\nconst ELASTIC_C5 = (2 * Math.PI) / 4.5;\n\nexport function easeInElastic(t: number): number {\n\tif (t === 0) return 0;\n\tif (t === 1) return 1;\n\treturn -Math.pow(2, 10 * t - 10) * Math.sin((10 * t - 10.75) * ELASTIC_C4);\n}\n\nexport function easeOutElastic(t: number): number {\n\tif (t === 0) return 0;\n\tif (t === 1) return 1;\n\treturn Math.pow(2, -10 * t) * Math.sin((10 * t - 0.75) * ELASTIC_C4) + 1;\n}\n\nexport function easeInOutElastic(t: number): number {\n\tif (t === 0) return 0;\n\tif (t === 1) return 1;\n\treturn t < 0.5\n\t\t? -(Math.pow(2, 20 * t - 10) * Math.sin((20 * t - 11.125) * ELASTIC_C5)) / 2\n\t\t: (Math.pow(2, -20 * t + 10) * Math.sin((20 * t - 11.125) * ELASTIC_C5)) / 2 + 1;\n}\n\n// Bounce\nexport function easeOutBounce(t: number): number {\n\tconst n1 = 7.5625;\n\tconst d1 = 2.75;\n\n\tif (t < 1 / d1) {\n\t\treturn n1 * t * t;\n\t} else if (t < 2 / d1) {\n\t\tconst t1 = t - 1.5 / d1;\n\t\treturn n1 * t1 * t1 + 0.75;\n\t} else if (t < 2.5 / d1) {\n\t\tconst t1 = t - 2.25 / d1;\n\t\treturn n1 * t1 * t1 + 0.9375;\n\t} else {\n\t\tconst t1 = t - 2.625 / d1;\n\t\treturn n1 * t1 * t1 + 0.984375;\n\t}\n}\n\nexport function easeInBounce(t: number): number {\n\treturn 1 - easeOutBounce(1 - t);\n}\n\nexport function easeInOutBounce(t: number): number {\n\treturn t < 0.5\n\t\t? (1 - easeOutBounce(1 - 2 * t)) / 2\n\t\t: (1 + easeOutBounce(2 * t - 1)) / 2;\n}\n\n/** Runtime lookup of all easing functions by name */\nexport const easings = {\n\tlinear,\n\teaseInQuad,\n\teaseOutQuad,\n\teaseInOutQuad,\n\teaseInCubic,\n\teaseOutCubic,\n\teaseInOutCubic,\n\teaseInQuart,\n\teaseOutQuart,\n\teaseInOutQuart,\n\teaseInQuint,\n\teaseOutQuint,\n\teaseInOutQuint,\n\teaseInSine,\n\teaseOutSine,\n\teaseInOutSine,\n\teaseInExpo,\n\teaseOutExpo,\n\teaseInOutExpo,\n\teaseInCirc,\n\teaseOutCirc,\n\teaseInOutCirc,\n\teaseInBack,\n\teaseOutBack,\n\teaseInOutBack,\n\teaseInElastic,\n\teaseOutElastic,\n\teaseInOutElastic,\n\teaseInBounce,\n\teaseOutBounce,\n\teaseInOutBounce,\n} as const;\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": "
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": "4cAOA,uBAAS,kBCCF,SAAS,CAAM,CAAC,EAAmB,CACzC,OAAO,EAiHR,IAAM,EAAU,QACV,EAAU,EAAU,MACpB,EAAU,EAAU,EAkB1B,IAAM,EAAc,EAAI,KAAK,GAAM,EAC7B,EAAc,EAAI,KAAK,GAAM,IDhD5B,SAAS,CAAW,CAC1B,EACA,EACA,EACA,EACA,EACqC,CACrC,IACC,OACA,SAAS,EACT,OAAO,OACP,QAAQ,EACR,cACG,GAAW,CAAC,EAEhB,MAAO,CACN,MAAO,CACN,MAAO,CAAC,CACP,QAAS,CAAC,CACT,YACA,KAAM,EAAM,MAAM,GAAG,EACrB,KAAM,GAAQ,KACd,IACD,CAAC,EACD,WACA,QACD,CAAC,EACD,YAAa,EACb,QAAS,EACT,OACA,WAAY,EACZ,eAAgB,EAChB,UAAW,EACX,MAAO,UACP,aACA,aAAc,EACf,CACD,EA8BM,SAAS,CAAmB,CAClC,E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CAE1C,EAAc,EAAa,EAAkB,EAAU,CAAG,EAC1D,IAAM,EAAW,EAAM,QAAU,EAAY,SAG7C,GAFA,EAAM,QAAU,EAEZ,CAAC,EAAY,EAAO,EAAkB,EAAU,CAAG,EAAG,OAC1D,SAID,IAAM,EAAW,EAAM,EAAM,QAAU,EAAY,SAAU,EAAG,CAAC,EACjE,EAAU,EAAa,EAAU,EAAkB,EAAU,CAAG,EAChE,QAkBK,SAAS,CAA8C,CAC7D,EACC,CACD,IACC,cAAc,SACd,WAAW,EACX,QAAQ,UACL,GAAW,CAAC,EAEhB,OAAO,EAAa,QAAQ,EAC1B,mBAAwC,EACxC,WAA2B,EAC3B,WAAc,EACd,QAAQ,CAAC,IAAU,CACnB,EACE,UAAU,cAAc,EACxB,YAAY,CAAQ,EACpB,QAAQ,CAAK,EACb,QAAQ,CAAW,EACnB,SAAS,SAAU,CACnB,KAAM,CAAC,OAAO,CACf,CAAC,EACA,WAAW,EAAG,UAAS,KAAI,SAAU,CACrC,QAAW,KAAU,EAAQ,OAAQ,CACpC,IAAM,EAAQ,EAAO,WAAW,MAC1B,EAAmB,EAAO,WAGhC,GAAI,EAAM,aAAc,CACvB,EAAM,aAAe,GAErB,SAID,GAAI,EAAM,QAAU,WAAY,SAGhC,GAAI,EAAM,QAAU,UACnB,EAAkB,EAAO,CAAgB,EACzC,EAAM,MAAQ,SAKf,GAAI,CADgB,EAAM,MAAM,EAAM,aACpB,SAElB,EAAM,SAAW,EAEjB,EAAqB,EAAO,EAAkB,EAAO,GAAI,CAAG,GAE7D,EACF",
|
|
9
|
+
"debugId": "9806996EDA5EA65464756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var R=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(
|
|
1
|
+
var K=Object.defineProperty;var E=(j)=>j;function R(j,k){this[j]=E.bind(null,k)}var h=(j,k)=>{for(var F in k)K(j,F,{get:k[F],enumerable:!0,configurable:!0,set:R.bind(k,F)})};var T=(j,k)=>()=>(j&&(k=j(j=0)),k);var b=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(k,F)=>(typeof require<"u"?require:k)[F]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as q}from"ecspresso";function x(j,k,F,S){let V={width:j,height:k};if(F!==void 0)V.x=F;if(S!==void 0)V.y=S;return V}function X(j){return{destroyOutOfBounds:j!==void 0?{padding:j}:{}}}function Y(j){return{clampToBounds:j!==void 0?{margin:j}:{}}}function f(j){return{wrapAtBounds:j!==void 0?{padding:j}:{}}}function c(j){let{systemGroup:k="physics",priority:F=50,boundsResourceKey:S="bounds",autoRemove:V=!0,phase:U="postUpdate"}=j??{};return q("bounds").withComponentTypes().withEventTypes().withResourceTypes().withLabels().withGroups().requires().install((G)=>{G.addSystem("bounds-destroy").setPriority(F).inPhase(U).inGroup(k).addQuery("entities",{with:["worldTransform","destroyOutOfBounds"]}).setProcess(({queries:D,ecs:J})=>{let I=J.getResource(S),L=I.x??0,N=I.y??0,v=L+I.width,A=N+I.height;for(let Q of D.entities){let{worldTransform:Z,destroyOutOfBounds:C}=Q.components,P=C.padding??0,z=M(Z,L,N,v,A,P);if(!z)continue;if(J.eventBus.publish("entityOutOfBounds",{entityId:Q.id,exitEdge:z}),V)J.commands.removeEntity(Q.id)}}),G.addSystem("bounds-clamp").setPriority(F-1).inPhase(U).inGroup(k).addQuery("entities",{with:["localTransform","worldTransform","clampToBounds"]}).setProcess(({queries:D,ecs:J})=>{let I=J.getResource(S),L=I.x??0,N=I.y??0,v=L+I.width,A=N+I.height;for(let Q of D.entities){let{localTransform:Z,worldTransform:C,clampToBounds:P}=Q.components,z=P.margin??0,_=L+z,$=N+z,H=v-z,O=A-z,W=0,B=0;if(C.x<_)W=_-C.x;if(C.x>H)W=H-C.x;if(C.y<$)B=$-C.y;if(C.y>O)B=O-C.y;if(W!==0||B!==0)Z.x+=W,Z.y+=B,J.markChanged(Q.id,"localTransform")}}),G.addSystem("bounds-wrap").setPriority(F-2).inPhase(U).inGroup(k).addQuery("entities",{with:["localTransform","worldTransform","wrapAtBounds"]}).setProcess(({queries:D,ecs:J})=>{let I=J.getResource(S),L=I.x??0,N=I.y??0,v=L+I.width,A=N+I.height;for(let Q of D.entities){let{localTransform:Z,worldTransform:C,wrapAtBounds:P}=Q.components,z=P.padding??0,_=0,$=0,H=v-L,O=A-N;if(C.x>v+z)_=-(H+2*z);else if(C.x<L-z)_=H+2*z;if(C.y>A+z)$=-(O+2*z);else if(C.y<N-z)$=O+2*z;if(_!==0||$!==0)Z.x+=_,Z.y+=$,J.markChanged(Q.id,"localTransform")}})})}function M(j,k,F,S,V,U){if(j.x>S+U)return"right";if(j.x<k-U)return"left";if(j.y>V+U)return"bottom";if(j.y<F-U)return"top";return null}export{f as createWrapAtBounds,X as createDestroyOutOfBounds,Y as createClampToBounds,c as createBoundsPlugin,x as createBounds};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=CB2BC1E386E08D1E64756E2164756E21
|
|
4
4
|
//# sourceMappingURL=bounds.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Bounds Plugin for ECSpresso\n *\n * Provides screen bounds enforcement for entities with transforms.\n * Reads worldTransform for position checking; modifies localTransform for corrections.\n * Supports destroy, clamp, and wrap behaviors.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\nimport type { TransformWorldConfig } from './transform';\n\n// ==================== Component Types ====================\n\n/**\n * Component that marks an entity for destruction when outside bounds.\n */\nexport interface DestroyOutOfBounds {\n\t/** Extra padding beyond bounds before destruction (default: 0) */\n\tpadding?: number;\n}\n\n/**\n * Component that clamps an entity's position to stay within bounds.\n */\nexport interface ClampToBounds {\n\t/** Margin to shrink the valid area (default: 0) */\n\tmargin?: number;\n}\n\n/**\n * Component that wraps an entity's position to the opposite edge.\n */\nexport interface WrapAtBounds {\n\t/** Padding beyond bounds before wrapping (default: 0) */\n\tpadding?: number;\n}\n\n/**\n * Component types provided by the bounds plugin.\n * Included automatically via `.withPlugin(createBoundsPlugin())`.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createBoundsPlugin({ width: 800, height: 600 }))\n * .withComponentTypes<{ sprite: Sprite }>()\n * .build();\n * ```\n */\nexport interface BoundsComponentTypes {\n\tdestroyOutOfBounds: DestroyOutOfBounds;\n\tclampToBounds: ClampToBounds;\n\twrapAtBounds: WrapAtBounds;\n}\n\n// ==================== Resource Types ====================\n\n/**\n * Bounds rectangle definition.\n */\nexport interface BoundsRect {\n\t/** Left edge x coordinate (default: 0) */\n\tx?: number;\n\t/** Top edge y coordinate (default: 0) */\n\ty?: number;\n\t/** Width of the bounds area */\n\twidth: number;\n\t/** Height of the bounds area */\n\theight: number;\n}\n\n/**\n * Resource types provided by the bounds plugin.\n */\nexport interface BoundsResourceTypes {\n\tbounds: BoundsRect;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event fired when an entity exits bounds.\n */\nexport interface EntityOutOfBoundsEvent {\n\t/** The entity that exited bounds */\n\tentityId: number;\n\t/** The edge the entity exited through */\n\texitEdge: 'top' | 'bottom' | 'left' | 'right';\n}\n\n/**\n * Event types provided by the bounds plugin.\n */\nexport interface BoundsEventTypes {\n\tentityOutOfBounds: EntityOutOfBoundsEvent;\n}\n\n// ==================== Plugin Options ====================\n\n/**\n * Configuration options for the bounds plugin.\n */\nexport interface BoundsPluginOptions<G extends string = 'physics'> extends BasePluginOptions<G> {\n\t/** Resource key for bounds rectangle (default: 'bounds') */\n\tboundsResourceKey?: string;\n\t/** Whether to auto-remove entities when out of bounds (default: true) */\n\tautoRemove?: boolean;\n}\n\n// ==================== Helper Functions ====================\n\n/**\n * Create a bounds rectangle resource.\n *\n * @param width The width of the bounds area\n * @param height The height of the bounds area\n * @param x The left edge x coordinate (default: 0)\n * @param y The top edge y coordinate (default: 0)\n * @returns Bounds rectangle suitable for use as a resource\n *\n * @example\n * ```typescript\n * ECSpresso.create()\n * .withResource('bounds', createBounds(800, 600))\n * .build();\n * ```\n */\nexport function createBounds(width: number, height: number, x?: number, y?: number): BoundsRect {\n\tconst bounds: BoundsRect = { width, height };\n\tif (x !== undefined) bounds.x = x;\n\tif (y !== undefined) bounds.y = y;\n\treturn bounds;\n}\n\n/**\n * Create a destroyOutOfBounds component.\n *\n * @param padding Extra padding beyond bounds before destruction\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createDestroyOutOfBounds(20),\n * });\n * ```\n */\nexport function createDestroyOutOfBounds(padding?: number): Pick<BoundsComponentTypes, 'destroyOutOfBounds'> {\n\treturn {\n\t\tdestroyOutOfBounds: padding !== undefined ? { padding } : {},\n\t};\n}\n\n/**\n * Create a clampToBounds component.\n *\n * @param margin Margin to shrink the valid area\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createClampToBounds(30),\n * });\n * ```\n */\nexport function createClampToBounds(margin?: number): Pick<BoundsComponentTypes, 'clampToBounds'> {\n\treturn {\n\t\tclampToBounds: margin !== undefined ? { margin } : {},\n\t};\n}\n\n/**\n * Create a wrapAtBounds component.\n *\n * @param padding Padding beyond bounds before wrapping\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createWrapAtBounds(10),\n * });\n * ```\n */\nexport function createWrapAtBounds(padding?: number): Pick<BoundsComponentTypes, 'wrapAtBounds'> {\n\treturn {\n\t\twrapAtBounds: padding !== undefined ? { padding } : {},\n\t};\n}\n\n// ==================== Dependency Types ====================\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a bounds plugin for ECSpresso.\n *\n * This plugin provides:\n * - Destroy out of bounds system - removes entities that exit bounds\n * - Clamp to bounds system - constrains entities within bounds\n * - Wrap at bounds system - wraps entities to opposite edge\n *\n * Uses worldTransform for position checking (world-space) and modifies\n * localTransform for corrections. Works best with entities that don't\n * have parent transforms (orphan entities).\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso\n * .create<Components, Events, Resources>()\n * .withResource('bounds', createBounds(800, 600))\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createBoundsPlugin())\n * .build();\n *\n * // Entity that gets destroyed when leaving screen\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createDestroyOutOfBounds(),\n * });\n * ```\n */\nexport function createBoundsPlugin<ResourceTypes extends BoundsResourceTypes = BoundsResourceTypes, G extends string = 'physics'>(\n\toptions?: BoundsPluginOptions<G>\n) {\n\tconst {\n\t\tsystemGroup = 'physics',\n\t\tpriority = 50,\n\t\tboundsResourceKey = 'bounds',\n\t\tautoRemove = true,\n\t\tphase = 'postUpdate',\n\t} = options ?? {};\n\n\treturn definePlugin('bounds')\n\t\t.withComponentTypes<BoundsComponentTypes>()\n\t\t.withEventTypes<BoundsEventTypes>()\n\t\t.withResourceTypes<ResourceTypes>()\n\t\t.withLabels<'bounds-destroy' | 'bounds-clamp' | 'bounds-wrap'>()\n\t\t.withGroups<G>()\n\t\t.requires<TransformWorldConfig>()\n\t\t.install((world) => {\n\t\t\t// Destroy out of bounds system\n\t\t\tworld\n\t\t\t\t.addSystem('bounds-destroy')\n\t\t\t\t.setPriority(priority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('entities', {\n\t\t\t\t\twith: ['worldTransform', 'destroyOutOfBounds'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tconst bounds = ecs.getResource(boundsResourceKey as keyof ResourceTypes) as BoundsRect;\n\t\t\t\t\tconst minX = bounds.x ?? 0;\n\t\t\t\t\tconst minY = bounds.y ?? 0;\n\t\t\t\t\tconst maxX = minX + bounds.width;\n\t\t\t\t\tconst maxY = minY + bounds.height;\n\n\t\t\t\t\tfor (const entity of queries.entities) {\n\t\t\t\t\t\tconst { worldTransform, destroyOutOfBounds } = entity.components;\n\t\t\t\t\t\tconst padding = destroyOutOfBounds.padding ?? 0;\n\n\t\t\t\t\t\tconst exitEdge = getExitEdge(worldTransform, minX, minY, maxX, maxY, padding);\n\t\t\t\t\t\tif (!exitEdge) continue;\n\n\t\t\t\t\t\tecs.eventBus.publish('entityOutOfBounds', {\n\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\texitEdge,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (autoRemove) {\n\t\t\t\t\t\t\tecs.commands.removeEntity(entity.id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// Clamp to bounds system\n\t\t\tworld\n\t\t\t\t.addSystem('bounds-clamp')\n\t\t\t\t.setPriority(priority - 1)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('entities', {\n\t\t\t\t\twith: ['localTransform', 'worldTransform', 'clampToBounds'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tconst bounds = ecs.getResource(boundsResourceKey as keyof ResourceTypes) as BoundsRect;\n\t\t\t\t\tconst minX = bounds.x ?? 0;\n\t\t\t\t\tconst minY = bounds.y ?? 0;\n\t\t\t\t\tconst maxX = minX + bounds.width;\n\t\t\t\t\tconst maxY = minY + bounds.height;\n\n\t\t\t\t\tfor (const entity of queries.entities) {\n\t\t\t\t\t\tconst { localTransform, worldTransform, clampToBounds } = entity.components;\n\t\t\t\t\t\tconst margin = clampToBounds.margin ?? 0;\n\n\t\t\t\t\t\tconst clampedMinX = minX + margin;\n\t\t\t\t\t\tconst clampedMinY = minY + margin;\n\t\t\t\t\t\tconst clampedMaxX = maxX - margin;\n\t\t\t\t\t\tconst clampedMaxY = maxY - margin;\n\n\t\t\t\t\t\t// Calculate world-space correction and apply to local transform\n\t\t\t\t\t\t// For entities without parents, this is equivalent to direct position clamping\n\t\t\t\t\t\tlet deltaX = 0;\n\t\t\t\t\t\tlet deltaY = 0;\n\n\t\t\t\t\t\tif (worldTransform.x < clampedMinX) deltaX = clampedMinX - worldTransform.x;\n\t\t\t\t\t\tif (worldTransform.x > clampedMaxX) deltaX = clampedMaxX - worldTransform.x;\n\t\t\t\t\t\tif (worldTransform.y < clampedMinY) deltaY = clampedMinY - worldTransform.y;\n\t\t\t\t\t\tif (worldTransform.y > clampedMaxY) deltaY = clampedMaxY - worldTransform.y;\n\n\t\t\t\t\t\tif (deltaX !== 0 || deltaY !== 0) {\n\t\t\t\t\t\t\tlocalTransform.x += deltaX;\n\t\t\t\t\t\t\tlocalTransform.y += deltaY;\n\t\t\t\t\t\t\tecs.markChanged(entity.id, 'localTransform');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// Wrap at bounds system\n\t\t\tworld\n\t\t\t\t.addSystem('bounds-wrap')\n\t\t\t\t.setPriority(priority - 2)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('entities', {\n\t\t\t\t\twith: ['localTransform', 'worldTransform', 'wrapAtBounds'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tconst bounds = ecs.getResource(boundsResourceKey as keyof ResourceTypes) as BoundsRect;\n\t\t\t\t\tconst minX = bounds.x ?? 0;\n\t\t\t\t\tconst minY = bounds.y ?? 0;\n\t\t\t\t\tconst maxX = minX + bounds.width;\n\t\t\t\t\tconst maxY = minY + bounds.height;\n\n\t\t\t\t\tfor (const entity of queries.entities) {\n\t\t\t\t\t\tconst { localTransform, worldTransform, wrapAtBounds } = entity.components;\n\t\t\t\t\t\tconst padding = wrapAtBounds.padding ?? 0;\n\n\t\t\t\t\t\tlet deltaX = 0;\n\t\t\t\t\t\tlet deltaY = 0;\n\t\t\t\t\t\tconst boundsWidth = maxX - minX;\n\t\t\t\t\t\tconst boundsHeight = maxY - minY;\n\n\t\t\t\t\t\t// Wrap horizontally\n\t\t\t\t\t\tif (worldTransform.x > maxX + padding) {\n\t\t\t\t\t\t\tdeltaX = -(boundsWidth + 2 * padding);\n\t\t\t\t\t\t} else if (worldTransform.x < minX - padding) {\n\t\t\t\t\t\t\tdeltaX = boundsWidth + 2 * padding;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Wrap vertically\n\t\t\t\t\t\tif (worldTransform.y > maxY + padding) {\n\t\t\t\t\t\t\tdeltaY = -(boundsHeight + 2 * padding);\n\t\t\t\t\t\t} else if (worldTransform.y < minY - padding) {\n\t\t\t\t\t\t\tdeltaY = boundsHeight + 2 * padding;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (deltaX !== 0 || deltaY !== 0) {\n\t\t\t\t\t\t\tlocalTransform.x += deltaX;\n\t\t\t\t\t\t\tlocalTransform.y += deltaY;\n\t\t\t\t\t\t\tecs.markChanged(entity.id, 'localTransform');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t});\n}\n\n/**\n * Determine which edge an entity has exited through, if any.\n */\nfunction getExitEdge(\n\ttransform: { x: number; y: number },\n\tminX: number,\n\tminY: number,\n\tmaxX: number,\n\tmaxY: number,\n\tpadding: number\n): 'top' | 'bottom' | 'left' | 'right' | null {\n\tif (transform.x > maxX + padding) return 'right';\n\tif (transform.x < minX - padding) return 'left';\n\tif (transform.y > maxY + padding) return 'bottom';\n\tif (transform.y < minY - padding) return 'top';\n\treturn null;\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": "4cAQA,uBAAS,kBAwHF,SAAS,CAAY,CAAC,EAAe,EAAgB,EAAY,EAAwB,CAC/F,IAAM,EAAqB,CAAE,QAAO,QAAO,EAC3C,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C1D,EAAU,EAAa,SAAW,EAEpC,EAAS,EACT,EAAS,EACP,EAAc,EAAO,EACrB,EAAe,EAAO,EAG5B,GAAI,EAAe,EAAI,EAAO,EAC7B,EAAS,EAAE,EAAc,EAAI,GACvB,QAAI,EAAe,EAAI,EAAO,EACpC,EAAS,EAAc,EAAI,EAI5B,GAAI,EAAe,EAAI,EAAO,EAC7B,EAAS,EAAE,EAAe,EAAI,GACxB,QAAI,EAAe,EAAI,EAAO,EACpC,EAAS,EAAe,EAAI,EAG7B,GAAI,IAAW,GAAK,IAAW,EAC9B,EAAe,GAAK,EACpB,EAAe,GAAK,EACpB,EAAI,YAAY,EAAO,GAAI,gBAAgB,GAG7C,EACF,EAMH,SAAS,CAAW,CACnB,EACA,EACA,EACA,EACA,EACA,EAC6C,CAC7C,GAAI,EAAU,EAAI,EAAO,EAAS,MAAO,QACzC,GAAI,EAAU,EAAI,EAAO,EAAS,MAAO,OACzC,GAAI,EAAU,EAAI,EAAO,EAAS,MAAO,SACzC,GAAI,EAAU,EAAI,EAAO,EAAS,MAAO,MACzC,OAAO",
|
|
8
|
+
"debugId": "CB2BC1E386E08D1E64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var r=Object.defineProperty;var c=(Q)=>Q;function o(Q,K){this[Q]=c.bind(null,K)}var jj=(Q,K)=>{for(var P in K)r(Q,P,{get:K[P],enumerable:!0,configurable:!0,set:o.bind(K,P)})};var Jj=(Q,K)=>()=>(Q&&(K=Q(Q=0)),K);var Nj=((Q)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(Q,{get:(K,P)=>(typeof require<"u"?require:K)[P]}):Q)(function(Q){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+Q+'" is not supported')});import{definePlugin as s}from"ecspresso";var v={traumaDecay:1,maxOffsetX:10,maxOffsetY:10,maxRotation:0.05},X={smoothing:5,deadzoneX:0,deadzoneY:0,offsetX:0,offsetY:0};function $j(Q,K,P){let M=Q-(P.x+P.shakeOffsetX),B=K-(P.y+P.shakeOffsetY),b=-(P.rotation+P.shakeRotation),E=Math.cos(b),W=Math.sin(b),L=M*E-B*W,U=M*W+B*E;return{x:L*P.zoom+P.viewportWidth/2,y:U*P.zoom+P.viewportHeight/2}}function t(Q,K,P){let M=(Q-P.viewportWidth/2)/P.zoom,B=(K-P.viewportHeight/2)/P.zoom,b=P.rotation+P.shakeRotation,E=Math.cos(b),W=Math.sin(b),L=M*E-B*W,U=M*W+B*E;return{x:L+P.x+P.shakeOffsetX,y:U+P.y+P.shakeOffsetY}}function a(Q){return typeof Q==="number"?Q:Q.id}function w(Q){let K=Q===!0?{}:Q;return{trauma:0,traumaDecay:K.traumaDecay??v.traumaDecay,maxOffsetX:K.maxOffsetX??v.maxOffsetX,maxOffsetY:K.maxOffsetY??v.maxOffsetY,maxRotation:K.maxRotation??v.maxRotation}}function e(Q){if(Array.isArray(Q))return{minX:Q[0],minY:Q[1],maxX:Q[2],maxY:Q[3]};return{...Q}}function u(Q){return{smoothing:Q?.smoothing??X.smoothing,deadzoneX:Q?.deadzoneX??X.deadzoneX,deadzoneY:Q?.deadzoneY??X.deadzoneY,offsetX:Q?.offsetX??X.offsetX,offsetY:Q?.offsetY??X.offsetY}}function Pj(Q){let{viewportWidth:K=800,viewportHeight:P=600,initial:M,follow:B,shake:b,bounds:E,zoom:W,pan:L,systemGroup:U="camera",phase:Y="postUpdate",randomFn:F=Math.random}=Q??{};return s("camera").withComponentTypes().withResourceTypes().withLabels().withGroups().requires().install((D)=>{let j={x:M?.x??0,y:M?.y??0,zoom:M?.zoom??1,rotation:M?.rotation??0,shakeOffsetX:0,shakeOffsetY:0,shakeRotation:0,viewportWidth:K,viewportHeight:P,entityId:-1,follow:()=>{},unfollow:()=>{},setPosition:()=>{},setZoom:()=>{},setRotation:()=>{},setBounds:()=>{},clearBounds:()=>{},addTrauma:()=>{}};if(D.addResource("cameraState",j),D.addSystem("camera-init").inGroup(U).setOnInitialize(($)=>{let I=$.spawn({camera:{x:M?.x??0,y:M?.y??0,zoom:M?.zoom??1,rotation:M?.rotation??0}});if(B)$.addComponent(I.id,"cameraFollow",{target:-1,...u(B)});if(b)$.addComponent(I.id,"cameraShake",w(b));if(E)$.addComponent(I.id,"cameraBounds",e(E));j.entityId=I.id,j.follow=(V,J)=>{let R={target:a(V),...u(J)},N=$.getComponent(j.entityId,"cameraFollow");if(N)N.target=R.target,N.smoothing=R.smoothing,N.deadzoneX=R.deadzoneX,N.deadzoneY=R.deadzoneY,N.offsetX=R.offsetX,N.offsetY=R.offsetY;else $.addComponent(j.entityId,"cameraFollow",R)},j.unfollow=()=>{if($.getComponent(j.entityId,"cameraFollow"))$.removeComponent(j.entityId,"cameraFollow")},j.setPosition=(V,J)=>{let q=$.getComponent(j.entityId,"camera");if(!q)return;q.x=V,q.y=J},j.setZoom=(V)=>{let J=$.getComponent(j.entityId,"camera");if(!J)return;J.zoom=V},j.setRotation=(V)=>{let J=$.getComponent(j.entityId,"camera");if(!J)return;J.rotation=V},j.setBounds=(V,J,q,R)=>{let N=$.getComponent(j.entityId,"cameraBounds");if(N)N.minX=V,N.minY=J,N.maxX=q,N.maxY=R;else $.addComponent(j.entityId,"cameraBounds",{minX:V,minY:J,maxX:q,maxY:R})},j.clearBounds=()=>{if($.getComponent(j.entityId,"cameraBounds"))$.removeComponent(j.entityId,"cameraBounds")},j.addTrauma=(V)=>{let J=$.getComponent(j.entityId,"cameraShake");if(J)J.trauma=Math.min(1,Math.max(0,J.trauma+V));else $.addComponent(j.entityId,"cameraShake",{...w(!0),trauma:Math.min(1,Math.max(0,V))})}}),D.addSystem("camera-follow").setPriority(400).inPhase(Y).inGroup(U).addQuery("cameras",{with:["camera","cameraFollow"]}).setProcess(({queries:$,dt:I,ecs:V})=>{let J=Math.min(1,I);for(let q of $.cameras){let{camera:R,cameraFollow:N}=q.components;if(N.target<0)continue;let Z;try{Z=V.getComponent(N.target,"worldTransform")}catch{continue}if(!Z)continue;let H=Z.x+N.offsetX,z=Z.y+N.offsetY,_=H-R.x,C=z-R.y;if(Math.abs(_)>N.deadzoneX){let G=_>0?1:-1,T=_-G*N.deadzoneX,A=Math.min(1,N.smoothing*J);R.x+=T*A}if(Math.abs(C)>N.deadzoneY){let G=C>0?1:-1,T=C-G*N.deadzoneY,A=Math.min(1,N.smoothing*J);R.y+=T*A}}}),D.addSystem("camera-shake-update").setPriority(390).inPhase(Y).inGroup(U).addQuery("shakeCameras",{with:["camera","cameraShake"]}).setProcess(({queries:$,dt:I})=>{for(let V of $.shakeCameras){let{cameraShake:J}=V.components;J.trauma=Math.max(0,J.trauma-J.traumaDecay*I)}}),D.addSystem("camera-bounds").setPriority(380).inPhase(Y).inGroup(U).addQuery("boundedCameras",{with:["camera","cameraBounds"]}).setProcess(({queries:$})=>{for(let I of $.boundedCameras){let{camera:V,cameraBounds:J}=I.components,q=j.viewportWidth/(2*V.zoom),R=j.viewportHeight/(2*V.zoom),N=J.minX+q,Z=J.maxX-q,H=J.minY+R,z=J.maxY-R;if(N>Z)V.x=(J.minX+J.maxX)/2;else V.x=Math.max(N,Math.min(Z,V.x));if(H>z)V.y=(J.minY+J.maxY)/2;else V.y=Math.max(H,Math.min(z,V.y))}}),D.addSystem("camera-state-sync").setPriority(370).inPhase(Y).inGroup(U).setProcess(({ecs:$})=>{let I=$.getComponent(j.entityId,"camera");if(!I){j.x=0,j.y=0,j.zoom=1,j.rotation=0,j.shakeOffsetX=0,j.shakeOffsetY=0,j.shakeRotation=0;return}j.x=I.x,j.y=I.y,j.zoom=I.zoom,j.rotation=I.rotation;let V=$.getComponent(j.entityId,"cameraShake");if(V&&V.trauma>0){let J=V.trauma*V.trauma;j.shakeOffsetX=V.maxOffsetX*J*(F()*2-1),j.shakeOffsetY=V.maxOffsetY*J*(F()*2-1),j.shakeRotation=V.maxRotation*J*(F()*2-1)}else j.shakeOffsetX=0,j.shakeOffsetY=0,j.shakeRotation=0}),W){let Z=function(H){H.preventDefault(),J+=Math.sign(H.deltaY)},{zoomStep:$=0.1,minZoom:I=0.1,maxZoom:V=10}=W,J=0,q=!1,R,N;D.addSystem("camera-zoom").setPriority(410).inPhase("preUpdate").inGroup(U).addQuery("cameras",{with:["camera"]}).setOnInitialize((H)=>{let z=H.tryGetResource("inputState"),_=H.tryGetResource("pixiApp");if(!z||!_){console.error("[camera] zoom requires the input plugin and renderer2D plugin. Zoom will be disabled.");return}R=_.canvas,R.addEventListener("wheel",Z,{passive:!1}),N=H.tryGetResource("isoProjection"),q=!0}).setOnDetach(()=>{if(!q||!R)return;R.removeEventListener("wheel",Z)}).setProcess(({queries:H,ecs:z})=>{if(!q||J===0)return;let _=J;J=0;let[C]=H.cameras;if(!C)return;let G=C.components.camera,T=z.tryGetResource("inputState");if(!T)return;let A=_>0?1-$:1+$,k=Math.max(I,Math.min(V,G.zoom*Math.pow(A,Math.abs(_))));if(N&&R){let O=R.getBoundingClientRect(),y=T.pointer.position.x-(O.left+O.width/2),h=T.pointer.position.y-(O.top+O.height/2),f=N.tileWidth/2,p=N.tileHeight/2,d=(G.x-G.y)*f+N.originX,S=(G.x+G.y)*p+N.originY,l=d+y/G.zoom,m=S+h/G.zoom;G.zoom=k;let i=l-y/k,n=m-h/k,x=i-N.originX,g=n-N.originY;G.x=x/N.tileWidth+g/N.tileHeight,G.y=-x/N.tileWidth+g/N.tileHeight}else{let O=t(T.pointer.position.x,T.pointer.position.y,j);G.zoom=k,G.x=O.x-(T.pointer.position.x-j.viewportWidth/2)/k,G.y=O.y-(T.pointer.position.y-j.viewportHeight/2)/k}})}if(L){let{speed:$,actions:I}=L,V=I?.up??"panUp",J=I?.down??"panDown",q=I?.left??"panLeft",R=I?.right??"panRight",N=!1;D.addSystem("camera-pan").setPriority(420).inPhase("preUpdate").inGroup(U).setOnInitialize((Z)=>{if(!Z.tryGetResource("inputState")){console.error("[camera] pan requires the input plugin. Pan will be disabled.");return}N=!0}).setProcess(({ecs:Z,dt:H})=>{if(!N)return;let z=Z.tryGetResource("inputState");if(!z)return;let _=$/j.zoom*H,C=(z.actions.isActive(R)?1:0)-(z.actions.isActive(q)?1:0),G=(z.actions.isActive(J)?1:0)-(z.actions.isActive(V)?1:0);if(C!==0||G!==0)j.setPosition(j.x+C*_,j.y+G*_)})}})}export{$j as worldToScreen,t as screenToWorld,Pj as createCameraPlugin};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=3A75EE04B3EE5C2364756E2164756E21
|
|
4
4
|
//# sourceMappingURL=camera.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Camera / Viewport Plugin for ECSpresso\n *\n * Provides a declarative camera with world/screen coordinate conversion, smooth follow,\n * trauma-based shake, bounds clamping, cursor-centered zoom, and logical viewport dimensions.\n *\n * This plugin is renderer-agnostic. PixiJS or other renderer integration (applying\n * cameraState to a container/stage transform) is the consumer's responsibility.\n *\n * Camera uses its own x/y/zoom/rotation rather than localTransform/worldTransform.\n * It reads the target entity's worldTransform for follow, but doesn't participate\n * in the transform hierarchy itself.\n */\n\nimport { definePlugin } from 'ecspresso';\nimport type { SystemPhase } from 'ecspresso';\nimport type ECSpresso from 'ecspresso';\nimport type { WorldConfigFrom } from '../../type-utils';\nimport type { TransformWorldConfig } from './transform';\n\n// ==================== Component Types ====================\n\nexport interface Camera {\n\tx: number;\n\ty: number;\n\tzoom: number;\n\trotation: number;\n}\n\nexport interface CameraFollow {\n\ttarget: number;\n\tsmoothing: number;\n\tdeadzoneX: number;\n\tdeadzoneY: number;\n\toffsetX: number;\n\toffsetY: number;\n}\n\nexport interface CameraShake {\n\ttrauma: number;\n\ttraumaDecay: number;\n\tmaxOffsetX: number;\n\tmaxOffsetY: number;\n\tmaxRotation: number;\n}\n\nexport interface CameraBounds {\n\tminX: number;\n\tminY: number;\n\tmaxX: number;\n\tmaxY: number;\n}\n\nexport interface CameraComponentTypes {\n\tcamera: Camera;\n\tcameraFollow: CameraFollow;\n\tcameraShake: CameraShake;\n\tcameraBounds: CameraBounds;\n}\n\n// ==================== Resource Types ====================\n\nexport interface FollowOptions {\n\tsmoothing?: number;\n\tdeadzoneX?: number;\n\tdeadzoneY?: number;\n\toffsetX?: number;\n\toffsetY?: number;\n}\n\nexport type EntityHandle = { id: number };\n\nexport interface CameraState {\n\t// Read-only data (synced from camera entity each frame)\n\tx: number;\n\ty: number;\n\tzoom: number;\n\trotation: number;\n\tshakeOffsetX: number;\n\tshakeOffsetY: number;\n\tshakeRotation: number;\n\tviewportWidth: number;\n\tviewportHeight: number;\n\tentityId: number;\n\n\t// Mutation methods\n\tfollow(target: number | EntityHandle, options?: FollowOptions): void;\n\tunfollow(): void;\n\tsetPosition(x: number, y: number): void;\n\tsetZoom(zoom: number): void;\n\tsetRotation(rotation: number): void;\n\tsetBounds(minX: number, minY: number, maxX: number, maxY: number): void;\n\tclearBounds(): void;\n\taddTrauma(amount: number): void;\n}\n\nexport interface CameraResourceTypes {\n\tcameraState: CameraState;\n}\n\n// ==================== Plugin Options ====================\n\nexport interface CameraPluginOptions<G extends string = 'camera'> {\n\tviewportWidth?: number;\n\tviewportHeight?: number;\n\tinitial?: {\n\t\tx?: number;\n\t\ty?: number;\n\t\tzoom?: number;\n\t\trotation?: number;\n\t};\n\tfollow?: FollowOptions;\n\tshake?: boolean | Partial<Omit<CameraShake, 'trauma'>>;\n\tbounds?:\n\t\t| { minX: number; minY: number; maxX: number; maxY: number }\n\t\t| [number, number, number, number];\n\tzoom?: {\n\t\tzoomStep?: number;\n\t\tminZoom?: number;\n\t\tmaxZoom?: number;\n\t};\n\tpan?: {\n\t\tspeed: number;\n\t\tactions?: {\n\t\t\tup?: string;\n\t\t\tdown?: string;\n\t\t\tleft?: string;\n\t\t\tright?: string;\n\t\t};\n\t};\n\tsystemGroup?: G;\n\tphase?: SystemPhase;\n\trandomFn?: () => number;\n}\n\n// ==================== Default Values ====================\n\nconst DEFAULT_SHAKE: Readonly<Omit<CameraShake, 'trauma'>> = {\n\ttraumaDecay: 1,\n\tmaxOffsetX: 10,\n\tmaxOffsetY: 10,\n\tmaxRotation: 0.05,\n};\n\nconst DEFAULT_FOLLOW: Readonly<Omit<CameraFollow, 'target'>> = {\n\tsmoothing: 5,\n\tdeadzoneX: 0,\n\tdeadzoneY: 0,\n\toffsetX: 0,\n\toffsetY: 0,\n};\n\n// ==================== Coordinate Conversion ====================\n\nexport function worldToScreen(\n\tworldX: number,\n\tworldY: number,\n\tstate: CameraState,\n): { x: number; y: number } {\n\tconst dx = worldX - (state.x + state.shakeOffsetX);\n\tconst dy = worldY - (state.y + state.shakeOffsetY);\n\n\tconst angle = -(state.rotation + state.shakeRotation);\n\tconst cos = Math.cos(angle);\n\tconst sin = Math.sin(angle);\n\tconst rx = dx * cos - dy * sin;\n\tconst ry = dx * sin + dy * cos;\n\n\treturn {\n\t\tx: rx * state.zoom + state.viewportWidth / 2,\n\t\ty: ry * state.zoom + state.viewportHeight / 2,\n\t};\n}\n\nexport function screenToWorld(\n\tscreenX: number,\n\tscreenY: number,\n\tstate: CameraState,\n): { x: number; y: number } {\n\tconst cx = (screenX - state.viewportWidth / 2) / state.zoom;\n\tconst cy = (screenY - state.viewportHeight / 2) / state.zoom;\n\n\tconst angle = state.rotation + state.shakeRotation;\n\tconst cos = Math.cos(angle);\n\tconst sin = Math.sin(angle);\n\tconst rx = cx * cos - cy * sin;\n\tconst ry = cx * sin + cy * cos;\n\n\treturn {\n\t\tx: rx + state.x + state.shakeOffsetX,\n\t\ty: ry + state.y + state.shakeOffsetY,\n\t};\n}\n\n// ==================== Internal Helpers ====================\n\nfunction resolveTarget(target: number | EntityHandle): number {\n\treturn typeof target === 'number' ? target : target.id;\n}\n\nfunction resolveShakeOptions(shake: true | Partial<Omit<CameraShake, 'trauma'>>): CameraShake {\n\tconst opts = shake === true ? {} : shake;\n\treturn {\n\t\ttrauma: 0,\n\t\ttraumaDecay: opts.traumaDecay ?? DEFAULT_SHAKE.traumaDecay,\n\t\tmaxOffsetX: opts.maxOffsetX ?? DEFAULT_SHAKE.maxOffsetX,\n\t\tmaxOffsetY: opts.maxOffsetY ?? DEFAULT_SHAKE.maxOffsetY,\n\t\tmaxRotation: opts.maxRotation ?? DEFAULT_SHAKE.maxRotation,\n\t};\n}\n\nfunction resolveBounds(\n\tbounds: { minX: number; minY: number; maxX: number; maxY: number } | [number, number, number, number],\n): CameraBounds {\n\tif (Array.isArray(bounds)) {\n\t\treturn { minX: bounds[0], minY: bounds[1], maxX: bounds[2], maxY: bounds[3] };\n\t}\n\treturn { ...bounds };\n}\n\nfunction resolveFollowOptions(options?: FollowOptions): Omit<CameraFollow, 'target'> {\n\treturn {\n\t\tsmoothing: options?.smoothing ?? DEFAULT_FOLLOW.smoothing,\n\t\tdeadzoneX: options?.deadzoneX ?? DEFAULT_FOLLOW.deadzoneX,\n\t\tdeadzoneY: options?.deadzoneY ?? DEFAULT_FOLLOW.deadzoneY,\n\t\toffsetX: options?.offsetX ?? DEFAULT_FOLLOW.offsetX,\n\t\toffsetY: options?.offsetY ?? DEFAULT_FOLLOW.offsetY,\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\ntype CameraWorldConfig = WorldConfigFrom<CameraComponentTypes, {}, CameraResourceTypes>;\n\ntype CameraLabels =\n\t| 'camera-init'\n\t| 'camera-follow'\n\t| 'camera-shake-update'\n\t| 'camera-bounds'\n\t| 'camera-state-sync'\n\t| 'camera-zoom'\n\t| 'camera-pan';\n\nexport function createCameraPlugin<G extends string = 'camera'>(\n\toptions?: CameraPluginOptions<G>,\n) {\n\tconst {\n\t\tviewportWidth = 800,\n\t\tviewportHeight = 600,\n\t\tinitial,\n\t\tfollow: followConfig,\n\t\tshake: shakeConfig,\n\t\tbounds: boundsConfig,\n\t\tzoom: zoomConfig,\n\t\tpan: panConfig,\n\t\tsystemGroup = 'camera',\n\t\tphase = 'postUpdate',\n\t\trandomFn = Math.random,\n\t} = options ?? {};\n\n\treturn definePlugin('camera')\n\t\t.withComponentTypes<CameraComponentTypes>()\n\t\t.withResourceTypes<CameraResourceTypes>()\n\t\t.withLabels<CameraLabels>()\n\t\t.withGroups<G>()\n\t\t.requires<TransformWorldConfig>()\n\t\t.install((world) => {\n\t\t\t// Build mutation methods as closures over the world reference.\n\t\t\t// The cameraState resource is created immediately with placeholder methods,\n\t\t\t// then the init system populates entityId and wires up real methods.\n\n\t\t\tconst cameraState: CameraState = {\n\t\t\t\tx: initial?.x ?? 0,\n\t\t\t\ty: initial?.y ?? 0,\n\t\t\t\tzoom: initial?.zoom ?? 1,\n\t\t\t\trotation: initial?.rotation ?? 0,\n\t\t\t\tshakeOffsetX: 0,\n\t\t\t\tshakeOffsetY: 0,\n\t\t\t\tshakeRotation: 0,\n\t\t\t\tviewportWidth,\n\t\t\t\tviewportHeight,\n\t\t\t\tentityId: -1,\n\n\t\t\t\t// Mutation methods — wired up after camera entity is spawned\n\t\t\t\tfollow: () => {},\n\t\t\t\tunfollow: () => {},\n\t\t\t\tsetPosition: () => {},\n\t\t\t\tsetZoom: () => {},\n\t\t\t\tsetRotation: () => {},\n\t\t\t\tsetBounds: () => {},\n\t\t\t\tclearBounds: () => {},\n\t\t\t\taddTrauma: () => {},\n\t\t\t};\n\n\t\t\tworld.addResource('cameraState', cameraState);\n\n\t\t\t// camera-init: spawns camera entity and wires up mutation closures\n\t\t\tworld\n\t\t\t\t.addSystem('camera-init')\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.setOnInitialize((ecs: ECSpresso<CameraWorldConfig & TransformWorldConfig>) => {\n\t\t\t\t\t// Spawn with required camera component\n\t\t\t\t\tconst entity = ecs.spawn({\n\t\t\t\t\t\tcamera: {\n\t\t\t\t\t\t\tx: initial?.x ?? 0,\n\t\t\t\t\t\t\ty: initial?.y ?? 0,\n\t\t\t\t\t\t\tzoom: initial?.zoom ?? 1,\n\t\t\t\t\t\t\trotation: initial?.rotation ?? 0,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\t// Conditionally add optional components\n\t\t\t\t\tif (followConfig) {\n\t\t\t\t\t\tecs.addComponent(entity.id, 'cameraFollow', {\n\t\t\t\t\t\t\ttarget: -1,\n\t\t\t\t\t\t\t...resolveFollowOptions(followConfig),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tif (shakeConfig) {\n\t\t\t\t\t\tecs.addComponent(entity.id, 'cameraShake', resolveShakeOptions(shakeConfig));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (boundsConfig) {\n\t\t\t\t\t\tecs.addComponent(entity.id, 'cameraBounds', resolveBounds(boundsConfig));\n\t\t\t\t\t}\n\t\t\t\t\tcameraState.entityId = entity.id;\n\n\t\t\t\t\t// Wire up mutation methods\n\t\t\t\t\tcameraState.follow = (target: number | EntityHandle, opts?: FollowOptions) => {\n\t\t\t\t\t\tconst targetId = resolveTarget(target);\n\t\t\t\t\t\tconst followData: CameraFollow = {\n\t\t\t\t\t\t\ttarget: targetId,\n\t\t\t\t\t\t\t...resolveFollowOptions(opts),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst existing = ecs.getComponent(cameraState.entityId, 'cameraFollow');\n\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\texisting.target = followData.target;\n\t\t\t\t\t\t\texisting.smoothing = followData.smoothing;\n\t\t\t\t\t\t\texisting.deadzoneX = followData.deadzoneX;\n\t\t\t\t\t\t\texisting.deadzoneY = followData.deadzoneY;\n\t\t\t\t\t\t\texisting.offsetX = followData.offsetX;\n\t\t\t\t\t\t\texisting.offsetY = followData.offsetY;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tecs.addComponent(cameraState.entityId, 'cameraFollow', followData);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tcameraState.unfollow = () => {\n\t\t\t\t\t\tconst existing = ecs.getComponent(cameraState.entityId, 'cameraFollow');\n\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\tecs.removeComponent(cameraState.entityId, 'cameraFollow');\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tcameraState.setPosition = (x: number, y: number) => {\n\t\t\t\t\t\tconst camera = ecs.getComponent(cameraState.entityId, 'camera');\n\t\t\t\t\t\tif (!camera) return;\n\t\t\t\t\t\tcamera.x = x;\n\t\t\t\t\t\tcamera.y = y;\n\t\t\t\t\t};\n\n\t\t\t\t\tcameraState.setZoom = (zoom: number) => {\n\t\t\t\t\t\tconst camera = ecs.getComponent(cameraState.entityId, 'camera');\n\t\t\t\t\t\tif (!camera) return;\n\t\t\t\t\t\tcamera.zoom = zoom;\n\t\t\t\t\t};\n\n\t\t\t\t\tcameraState.setRotation = (rotation: number) => {\n\t\t\t\t\t\tconst camera = ecs.getComponent(cameraState.entityId, 'camera');\n\t\t\t\t\t\tif (!camera) return;\n\t\t\t\t\t\tcamera.rotation = rotation;\n\t\t\t\t\t};\n\n\t\t\t\t\tcameraState.setBounds = (minX: number, minY: number, maxX: number, maxY: number) => {\n\t\t\t\t\t\tconst existing = ecs.getComponent(cameraState.entityId, 'cameraBounds');\n\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\texisting.minX = minX;\n\t\t\t\t\t\t\texisting.minY = minY;\n\t\t\t\t\t\t\texisting.maxX = maxX;\n\t\t\t\t\t\t\texisting.maxY = maxY;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tecs.addComponent(cameraState.entityId, 'cameraBounds', { minX, minY, maxX, maxY });\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tcameraState.clearBounds = () => {\n\t\t\t\t\t\tconst existing = ecs.getComponent(cameraState.entityId, 'cameraBounds');\n\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\tecs.removeComponent(cameraState.entityId, 'cameraBounds');\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tcameraState.addTrauma = (amount: number) => {\n\t\t\t\t\t\tconst shake = ecs.getComponent(cameraState.entityId, 'cameraShake');\n\t\t\t\t\t\tif (shake) {\n\t\t\t\t\t\t\tshake.trauma = Math.min(1, Math.max(0, shake.trauma + amount));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tecs.addComponent(cameraState.entityId, 'cameraShake', {\n\t\t\t\t\t\t\t\t...resolveShakeOptions(true),\n\t\t\t\t\t\t\t\ttrauma: Math.min(1, Math.max(0, amount)),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t});\n\n\t\t\t// camera-follow: priority 400 (after transform propagation at 500)\n\t\t\tworld\n\t\t\t\t.addSystem('camera-follow')\n\t\t\t\t.setPriority(400)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('cameras', {\n\t\t\t\t\twith: ['camera', 'cameraFollow'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tconst t = Math.min(1, dt);\n\t\t\t\t\tfor (const entity of queries.cameras) {\n\t\t\t\t\t\tconst { camera, cameraFollow } = entity.components;\n\t\t\t\t\t\tif (cameraFollow.target < 0) continue;\n\n\t\t\t\t\t\tlet targetWorld;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\ttargetWorld = ecs.getComponent(cameraFollow.target, 'worldTransform');\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!targetWorld) continue;\n\n\t\t\t\t\t\tconst goalX = targetWorld.x + cameraFollow.offsetX;\n\t\t\t\t\t\tconst goalY = targetWorld.y + cameraFollow.offsetY;\n\t\t\t\t\t\tconst dx = goalX - camera.x;\n\t\t\t\t\t\tconst dy = goalY - camera.y;\n\n\t\t\t\t\t\tif (Math.abs(dx) > cameraFollow.deadzoneX) {\n\t\t\t\t\t\t\tconst sign = dx > 0 ? 1 : -1;\n\t\t\t\t\t\t\tconst excessX = dx - sign * cameraFollow.deadzoneX;\n\t\t\t\t\t\t\tconst factor = Math.min(1, cameraFollow.smoothing * t);\n\t\t\t\t\t\t\tcamera.x += excessX * factor;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (Math.abs(dy) > cameraFollow.deadzoneY) {\n\t\t\t\t\t\t\tconst sign = dy > 0 ? 1 : -1;\n\t\t\t\t\t\t\tconst excessY = dy - sign * cameraFollow.deadzoneY;\n\t\t\t\t\t\t\tconst factor = Math.min(1, cameraFollow.smoothing * t);\n\t\t\t\t\t\t\tcamera.y += excessY * factor;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// camera-shake-update: priority 390\n\t\t\tworld\n\t\t\t\t.addSystem('camera-shake-update')\n\t\t\t\t.setPriority(390)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('shakeCameras', {\n\t\t\t\t\twith: ['camera', 'cameraShake'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt }) => {\n\t\t\t\t\tfor (const entity of queries.shakeCameras) {\n\t\t\t\t\t\tconst { cameraShake } = entity.components;\n\t\t\t\t\t\tcameraShake.trauma = Math.max(0, cameraShake.trauma - cameraShake.traumaDecay * dt);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// camera-bounds: priority 380\n\t\t\tworld\n\t\t\t\t.addSystem('camera-bounds')\n\t\t\t\t.setPriority(380)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('boundedCameras', {\n\t\t\t\t\twith: ['camera', 'cameraBounds'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries }) => {\n\t\t\t\t\tfor (const entity of queries.boundedCameras) {\n\t\t\t\t\t\tconst { camera, cameraBounds } = entity.components;\n\t\t\t\t\t\tconst halfW = cameraState.viewportWidth / (2 * camera.zoom);\n\t\t\t\t\t\tconst halfH = cameraState.viewportHeight / (2 * camera.zoom);\n\n\t\t\t\t\t\tconst effectiveMinX = cameraBounds.minX + halfW;\n\t\t\t\t\t\tconst effectiveMaxX = cameraBounds.maxX - halfW;\n\t\t\t\t\t\tconst effectiveMinY = cameraBounds.minY + halfH;\n\t\t\t\t\t\tconst effectiveMaxY = cameraBounds.maxY - halfH;\n\n\t\t\t\t\t\tif (effectiveMinX > effectiveMaxX) {\n\t\t\t\t\t\t\tcamera.x = (cameraBounds.minX + cameraBounds.maxX) / 2;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcamera.x = Math.max(effectiveMinX, Math.min(effectiveMaxX, camera.x));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (effectiveMinY > effectiveMaxY) {\n\t\t\t\t\t\t\tcamera.y = (cameraBounds.minY + cameraBounds.maxY) / 2;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcamera.y = Math.max(effectiveMinY, Math.min(effectiveMaxY, camera.y));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// camera-state-sync: priority 370\n\t\t\tworld\n\t\t\t\t.addSystem('camera-state-sync')\n\t\t\t\t.setPriority(370)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.setProcess(({ ecs }) => {\n\t\t\t\t\tconst camera = ecs.getComponent(cameraState.entityId, 'camera');\n\t\t\t\t\tif (!camera) {\n\t\t\t\t\t\tcameraState.x = 0;\n\t\t\t\t\t\tcameraState.y = 0;\n\t\t\t\t\t\tcameraState.zoom = 1;\n\t\t\t\t\t\tcameraState.rotation = 0;\n\t\t\t\t\t\tcameraState.shakeOffsetX = 0;\n\t\t\t\t\t\tcameraState.shakeOffsetY = 0;\n\t\t\t\t\t\tcameraState.shakeRotation = 0;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tcameraState.x = camera.x;\n\t\t\t\t\tcameraState.y = camera.y;\n\t\t\t\t\tcameraState.zoom = camera.zoom;\n\t\t\t\t\tcameraState.rotation = camera.rotation;\n\n\t\t\t\t\tconst shake = ecs.getComponent(cameraState.entityId, 'cameraShake');\n\t\t\t\t\tif (shake && shake.trauma > 0) {\n\t\t\t\t\t\tconst intensity = shake.trauma * shake.trauma;\n\t\t\t\t\t\tcameraState.shakeOffsetX = shake.maxOffsetX * intensity * (randomFn() * 2 - 1);\n\t\t\t\t\t\tcameraState.shakeOffsetY = shake.maxOffsetY * intensity * (randomFn() * 2 - 1);\n\t\t\t\t\t\tcameraState.shakeRotation = shake.maxRotation * intensity * (randomFn() * 2 - 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcameraState.shakeOffsetX = 0;\n\t\t\t\t\t\tcameraState.shakeOffsetY = 0;\n\t\t\t\t\t\tcameraState.shakeRotation = 0;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// camera-zoom: conditionally registered when zoom option is provided\n\t\t\tif (zoomConfig) {\n\t\t\t\tconst {\n\t\t\t\t\tzoomStep = 0.1,\n\t\t\t\t\tminZoom = 0.1,\n\t\t\t\t\tmaxZoom = 10,\n\t\t\t\t} = zoomConfig;\n\n\t\t\t\ttype ZoomInputState = { pointer: { position: { x: number; y: number } } };\n\n\t\t\t\tlet pendingSteps = 0;\n\t\t\t\tlet zoomActive = false;\n\t\t\t\tlet canvas: HTMLCanvasElement | undefined;\n\t\t\t\tlet isoState: { tileWidth: number; tileHeight: number; originX: number; originY: number } | undefined;\n\n\t\t\t\tfunction onWheel(e: WheelEvent) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tpendingSteps += Math.sign(e.deltaY);\n\t\t\t\t}\n\n\t\t\t\tworld\n\t\t\t\t\t.addSystem('camera-zoom')\n\t\t\t\t\t.setPriority(410)\n\t\t\t\t\t.inPhase('preUpdate')\n\t\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t\t.addQuery('cameras', {\n\t\t\t\t\t\twith: ['camera'],\n\t\t\t\t\t})\n\t\t\t\t\t.setOnInitialize((ecs) => {\n\t\t\t\t\t\t// Check for required dependencies\n\t\t\t\t\t\tconst inputState = ecs.tryGetResource<ZoomInputState>('inputState');\n\t\t\t\t\t\tconst pixiApp = ecs.tryGetResource<{ canvas: HTMLCanvasElement }>('pixiApp');\n\n\t\t\t\t\t\tif (!inputState || !pixiApp) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\t'[camera] zoom requires the input plugin and renderer2D plugin. ' +\n\t\t\t\t\t\t\t\t'Zoom will be disabled.',\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcanvas = pixiApp.canvas;\n\t\t\t\t\t\tcanvas.addEventListener('wheel', onWheel as EventListener, { passive: false });\n\n\t\t\t\t\t\t// Detect isometric projection for iso-aware cursor-centered zoom\n\t\t\t\t\t\tisoState = ecs.tryGetResource<{\n\t\t\t\t\t\t\ttileWidth: number; tileHeight: number;\n\t\t\t\t\t\t\toriginX: number; originY: number;\n\t\t\t\t\t\t}>('isoProjection');\n\n\t\t\t\t\t\tzoomActive = true;\n\t\t\t\t\t})\n\t\t\t\t\t.setOnDetach(() => {\n\t\t\t\t\t\tif (!zoomActive || !canvas) return;\n\t\t\t\t\t\tcanvas.removeEventListener('wheel', onWheel as EventListener);\n\t\t\t\t\t})\n\t\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\t\tif (!zoomActive || pendingSteps === 0) return;\n\n\t\t\t\t\t\tconst steps = pendingSteps;\n\t\t\t\t\t\tpendingSteps = 0;\n\n\t\t\t\t\t\tconst [cameraEntity] = queries.cameras;\n\t\t\t\t\t\tif (!cameraEntity) return;\n\n\t\t\t\t\t\tconst cam = cameraEntity.components.camera;\n\t\t\t\t\t\tconst inputState = ecs.tryGetResource<ZoomInputState>('inputState');\n\t\t\t\t\t\tif (!inputState) return;\n\n\t\t\t\t\t\t// Apply zoom — proportional to number of wheel steps\n\t\t\t\t\t\tconst direction = steps > 0 ? (1 - zoomStep) : (1 + zoomStep);\n\t\t\t\t\t\tconst newZoom = Math.max(minZoom, Math.min(maxZoom, cam.zoom * Math.pow(direction, Math.abs(steps))));\n\n\t\t\t\t\t\tif (isoState && canvas) {\n\t\t\t\t\t\t\t// Iso-aware cursor-centered zoom: work in iso-screen space\n\t\t\t\t\t\t\tconst rect = canvas.getBoundingClientRect();\n\t\t\t\t\t\t\tconst screenOffX = inputState.pointer.position.x - (rect.left + rect.width / 2);\n\t\t\t\t\t\t\tconst screenOffY = inputState.pointer.position.y - (rect.top + rect.height / 2);\n\n\t\t\t\t\t\t\t// Inlined worldToIso — avoids cross-plugin import\n\t\t\t\t\t\t\tconst halfW = isoState.tileWidth / 2;\n\t\t\t\t\t\t\tconst halfH = isoState.tileHeight / 2;\n\t\t\t\t\t\t\tconst camIsoX = (cam.x - cam.y) * halfW + isoState.originX;\n\t\t\t\t\t\t\tconst camIsoY = (cam.x + cam.y) * halfH + isoState.originY;\n\t\t\t\t\t\t\tconst isoBeforeX = camIsoX + screenOffX / cam.zoom;\n\t\t\t\t\t\t\tconst isoBeforeY = camIsoY + screenOffY / cam.zoom;\n\n\t\t\t\t\t\t\tcam.zoom = newZoom;\n\n\t\t\t\t\t\t\t// New camera iso position so the same point stays under cursor\n\t\t\t\t\t\t\tconst newCamIsoX = isoBeforeX - screenOffX / newZoom;\n\t\t\t\t\t\t\tconst newCamIsoY = isoBeforeY - screenOffY / newZoom;\n\n\t\t\t\t\t\t\t// Inlined isoToWorld\n\t\t\t\t\t\t\tconst relX = newCamIsoX - isoState.originX;\n\t\t\t\t\t\t\tconst relY = newCamIsoY - isoState.originY;\n\t\t\t\t\t\t\tcam.x = relX / isoState.tileWidth + relY / isoState.tileHeight;\n\t\t\t\t\t\t\tcam.y = -relX / isoState.tileWidth + relY / isoState.tileHeight;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Pixel-space cursor-centered zoom\n\t\t\t\t\t\t\tconst worldBefore = screenToWorld(\n\t\t\t\t\t\t\t\tinputState.pointer.position.x,\n\t\t\t\t\t\t\t\tinputState.pointer.position.y,\n\t\t\t\t\t\t\t\tcameraState,\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tcam.zoom = newZoom;\n\n\t\t\t\t\t\t\tcam.x = worldBefore.x - (inputState.pointer.position.x - cameraState.viewportWidth / 2) / newZoom;\n\t\t\t\t\t\t\tcam.y = worldBefore.y - (inputState.pointer.position.y - cameraState.viewportHeight / 2) / newZoom;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\t// camera-pan: conditionally registered when pan option is provided\n\t\t\tif (panConfig) {\n\t\t\t\ttype PanInputState = { actions: { isActive(action: string): boolean } };\n\n\t\t\t\tconst {\n\t\t\t\t\tspeed,\n\t\t\t\t\tactions: panActions,\n\t\t\t\t} = panConfig;\n\n\t\t\t\tconst actionUp = panActions?.up ?? 'panUp';\n\t\t\t\tconst actionDown = panActions?.down ?? 'panDown';\n\t\t\t\tconst actionLeft = panActions?.left ?? 'panLeft';\n\t\t\t\tconst actionRight = panActions?.right ?? 'panRight';\n\n\t\t\t\tlet panActive = false;\n\n\t\t\t\tworld\n\t\t\t\t\t.addSystem('camera-pan')\n\t\t\t\t\t.setPriority(420)\n\t\t\t\t\t.inPhase('preUpdate')\n\t\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t\t.setOnInitialize((ecs) => {\n\t\t\t\t\t\tconst inputState = ecs.tryGetResource<PanInputState>('inputState');\n\t\t\t\t\t\tif (!inputState) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\t'[camera] pan requires the input plugin. Pan will be disabled.',\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpanActive = true;\n\t\t\t\t\t})\n\t\t\t\t\t.setProcess(({ ecs, dt }) => {\n\t\t\t\t\t\tif (!panActive) return;\n\n\t\t\t\t\t\tconst inputState = ecs.tryGetResource<PanInputState>('inputState');\n\t\t\t\t\t\tif (!inputState) return;\n\n\t\t\t\t\t\tconst delta = (speed / cameraState.zoom) * dt;\n\t\t\t\t\t\tconst dx = (inputState.actions.isActive(actionRight) ? 1 : 0)\n\t\t\t\t\t\t\t- (inputState.actions.isActive(actionLeft) ? 1 : 0);\n\t\t\t\t\t\tconst dy = (inputState.actions.isActive(actionDown) ? 1 : 0)\n\t\t\t\t\t\t\t- (inputState.actions.isActive(actionUp) ? 1 : 0);\n\n\t\t\t\t\t\tif (dx !== 0 || dy !== 0) {\n\t\t\t\t\t\t\tcameraState.setPosition(\n\t\t\t\t\t\t\t\tcameraState.x + dx * delta,\n\t\t\t\t\t\t\t\tcameraState.y + dy * delta,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t}\n\t\t});\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": "+cAcA,uBAAS,kBA2HT,IAAM,EAAuD,CAC5D,YAAa,EACb,WAAY,GACZ,WAAY,GACZ,YAAa,IACd,EAEM,EAAyD,CAC9D,UAAW,EACX,UAAW,EACX,UAAW,EACX,QAAS,EACT,QAAS,CACV,EAIO,SAAS,EAAa,CAC5B,EACA,EACA,EAC2B,CAC3B,IAAM,EAAK,GAAU,EAAM,EAAI,EAAM,cAC/B,EAAK,GAAU,EAAM,EAAI,EAAM,cAE/B,EAAQ,EAAE,EAAM,SAAW,EAAM,eACjC,EAAM,KAAK,IAAI,CAAK,EACpB,EAAM,KAAK,IAAI,CAAK,EACpB,EAAK,EAAK,EAAM,EAAK,EACrB,EAAK,EAAK,EAAM,EAAK,EAE3B,MAAO,CACN,EAAG,EAAK,EAAM,KAAO,EAAM,cAAgB,EAC3C,EAAG,EAAK,EAAM,KAAO,EAAM,eAAiB,CAC7C,EAGM,SAAS,CAAa,CAC5B,EACA,EACA,EAC2B,CAC3B,IAAM,GAAM,EAAU,EAAM,cAAgB,GAAK,EAAM,KACjD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AAY,EAChD,CAChB,QAAQ,MACP,+DACD,EACA,OAED,EAAY,GACZ,EACA,WAAW,EAAG,MAAK,QAAS,CAC5B,GAAI,CAAC,EAAW,OAEhB,IAAM,EAAa,EAAI,eAA8B,YAAY,EACjE,GAAI,CAAC,EAAY,OAEjB,IAAM,EAAS,EAAQ,EAAY,KAAQ,EACrC,GAAM,EAAW,QAAQ,SAAS,CAAW,EAAI,EAAI,IACvD,EAAW,QAAQ,SAAS,CAAU,EAAI,EAAI,GAC5C,GAAM,EAAW,QAAQ,SAAS,CAAU,EAAI,EAAI,IACtD,EAAW,QAAQ,SAAS,CAAQ,EAAI,EAAI,GAEhD,GAAI,IAAO,GAAK,IAAO,EACtB,EAAY,YACX,EAAY,EAAI,EAAK,EACrB,EAAY,EAAI,EAAK,CACtB,EAED,GAEH",
|
|
8
|
+
"debugId": "3A75EE04B3EE5C2364756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Camera 3D Plugin for ECSpresso
|
|
3
|
+
*
|
|
4
|
+
* Orbit/follow/shake camera controls for a Three.js PerspectiveCamera or
|
|
5
|
+
* OrthographicCamera managed by renderer3D. Purely resource-based (no camera
|
|
6
|
+
* entity). The renderer3D `camera` resource is the single camera target.
|
|
7
|
+
* Orbit via pointer drag + scroll wheel, follow via entity tracking, shake
|
|
8
|
+
* via trauma-based offsets.
|
|
9
|
+
*
|
|
10
|
+
* The plugin's `projection` option must match the underlying camera's kind;
|
|
11
|
+
* a mismatch throws at init. State is a discriminated union — perspective
|
|
12
|
+
* cameras expose `fov` / `setFov`, orthographic cameras expose `zoom` / `setZoom`.
|
|
13
|
+
*
|
|
14
|
+
* Import from 'ecspresso/plugins/spatial/camera3D'
|
|
15
|
+
*/
|
|
16
|
+
import type { SystemPhase } from 'ecspresso';
|
|
17
|
+
import type { WorldConfigFrom } from '../../type-utils';
|
|
18
|
+
import type { Transform3DComponentTypes } from './transform3D';
|
|
19
|
+
import type { Renderer3DResourceTypes } from '../rendering/renderer3D';
|
|
20
|
+
type Camera3DRequiredConfig = WorldConfigFrom<Transform3DComponentTypes, {}, Renderer3DResourceTypes>;
|
|
21
|
+
export interface Camera3DFollowOptions {
|
|
22
|
+
smoothing?: number;
|
|
23
|
+
offsetX?: number;
|
|
24
|
+
offsetY?: number;
|
|
25
|
+
offsetZ?: number;
|
|
26
|
+
}
|
|
27
|
+
export interface Camera3DShakeOptions {
|
|
28
|
+
traumaDecay?: number;
|
|
29
|
+
maxOffsetX?: number;
|
|
30
|
+
maxOffsetY?: number;
|
|
31
|
+
maxOffsetZ?: number;
|
|
32
|
+
}
|
|
33
|
+
export interface Camera3DBaseState {
|
|
34
|
+
targetX: number;
|
|
35
|
+
targetY: number;
|
|
36
|
+
targetZ: number;
|
|
37
|
+
azimuth: number;
|
|
38
|
+
elevation: number;
|
|
39
|
+
distance: number;
|
|
40
|
+
followTarget: number;
|
|
41
|
+
followSmoothing: number;
|
|
42
|
+
followOffsetX: number;
|
|
43
|
+
followOffsetY: number;
|
|
44
|
+
followOffsetZ: number;
|
|
45
|
+
trauma: number;
|
|
46
|
+
shakeOffsetX: number;
|
|
47
|
+
shakeOffsetY: number;
|
|
48
|
+
shakeOffsetZ: number;
|
|
49
|
+
follow(target: number | {
|
|
50
|
+
id: number;
|
|
51
|
+
}, options?: Camera3DFollowOptions): void;
|
|
52
|
+
unfollow(): void;
|
|
53
|
+
setTarget(x: number, y: number, z: number): void;
|
|
54
|
+
setOrbit(azimuth: number, elevation: number, distance: number): void;
|
|
55
|
+
setDistance(distance: number): void;
|
|
56
|
+
addTrauma(amount: number): void;
|
|
57
|
+
}
|
|
58
|
+
export interface PerspectiveCamera3DState extends Camera3DBaseState {
|
|
59
|
+
projection: 'perspective';
|
|
60
|
+
fov: number;
|
|
61
|
+
setFov(fov: number): void;
|
|
62
|
+
}
|
|
63
|
+
export interface OrthographicCamera3DState extends Camera3DBaseState {
|
|
64
|
+
projection: 'orthographic';
|
|
65
|
+
zoom: number;
|
|
66
|
+
setZoom(zoom: number): void;
|
|
67
|
+
}
|
|
68
|
+
export type Camera3DState = PerspectiveCamera3DState | OrthographicCamera3DState;
|
|
69
|
+
export interface Camera3DResourceTypes {
|
|
70
|
+
camera3DState: Camera3DState;
|
|
71
|
+
}
|
|
72
|
+
export type Camera3DWorldConfig = WorldConfigFrom<{}, {}, Camera3DResourceTypes>;
|
|
73
|
+
export interface Camera3DBasePluginOptions<G extends string = 'camera3d'> {
|
|
74
|
+
systemGroup?: G;
|
|
75
|
+
phase?: SystemPhase;
|
|
76
|
+
azimuth?: number;
|
|
77
|
+
elevation?: number;
|
|
78
|
+
distance?: number;
|
|
79
|
+
target?: {
|
|
80
|
+
x: number;
|
|
81
|
+
y: number;
|
|
82
|
+
z: number;
|
|
83
|
+
};
|
|
84
|
+
minDistance?: number;
|
|
85
|
+
maxDistance?: number;
|
|
86
|
+
minElevation?: number;
|
|
87
|
+
maxElevation?: number;
|
|
88
|
+
orbitSensitivity?: number;
|
|
89
|
+
dollySensitivity?: number;
|
|
90
|
+
follow?: Camera3DFollowOptions;
|
|
91
|
+
shake?: boolean | Partial<Camera3DShakeOptions>;
|
|
92
|
+
randomFn?: () => number;
|
|
93
|
+
}
|
|
94
|
+
export type Camera3DPluginOptions<G extends string = 'camera3d'> = Camera3DBasePluginOptions<G> & ({
|
|
95
|
+
projection?: 'perspective';
|
|
96
|
+
fov?: number;
|
|
97
|
+
} | {
|
|
98
|
+
projection: 'orthographic';
|
|
99
|
+
zoom?: number;
|
|
100
|
+
});
|
|
101
|
+
export type Camera3DLabels = 'camera3d-init' | 'camera3d-follow' | 'camera3d-shake' | 'camera3d-sync';
|
|
102
|
+
/**
|
|
103
|
+
* Convert spherical coordinates to cartesian. Y-up convention (Three.js default).
|
|
104
|
+
* Azimuth rotates in the XZ plane; elevation goes from XZ plane toward +Y.
|
|
105
|
+
*/
|
|
106
|
+
export declare function sphericalToCartesian(azimuth: number, elevation: number, distance: number, out: {
|
|
107
|
+
x: number;
|
|
108
|
+
y: number;
|
|
109
|
+
z: number;
|
|
110
|
+
}): void;
|
|
111
|
+
export declare function createCamera3DPlugin<G extends string = 'camera3d'>(options?: Camera3DPluginOptions<G>): import("ecspresso").Plugin<import("ecspresso").WithResources<import("ecspresso").EmptyConfig, Camera3DResourceTypes>, Camera3DRequiredConfig, Camera3DLabels, G, never, never>;
|
|
112
|
+
export {};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var t=Object.defineProperty;var e=(J)=>J;function a(J,$){this[J]=e.bind(null,$)}var Jq=(J,$)=>{for(var R in $)t(J,R,{get:$[R],enumerable:!0,configurable:!0,set:a.bind($,R)})};var Qq=(J,$)=>()=>(J&&($=J(J=0)),$);var $q=((J)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(J,{get:($,R)=>(typeof require<"u"?require:$)[R]}):J)(function(J){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+J+'" is not supported')});import{definePlugin as qq}from"ecspresso";var G={smoothing:5,offsetX:0,offsetY:0,offsetZ:0},H={traumaDecay:1,maxOffsetX:0.3,maxOffsetY:0.3,maxOffsetZ:0.3},O=Math.PI/2,E=0.001,N={x:0,y:0,z:0};function K(J,$,R){return Math.max($,Math.min(R,J))}function Bq(J){if(J===!0)return{...H};return{traumaDecay:J.traumaDecay??H.traumaDecay,maxOffsetX:J.maxOffsetX??H.maxOffsetX,maxOffsetY:J.maxOffsetY??H.maxOffsetY,maxOffsetZ:J.maxOffsetZ??H.maxOffsetZ}}function L(J,$,R,W){let z=Math.cos($);W.x=R*z*Math.sin(J),W.y=R*Math.sin($),W.z=R*z*Math.cos(J)}function Vq(J){let{systemGroup:$="camera3d",phase:R="postUpdate",azimuth:W=0,elevation:z=0.5,distance:f=10,target:S,minDistance:k=1,maxDistance:x=100,minElevation:U=-O+E,maxElevation:u=O-E,orbitSensitivity:D=0.003,dollySensitivity:C=1.1,follow:b,shake:T,randomFn:w=Math.random}=J??{},p=J?.projection??"perspective",g=J?.projection!=="orthographic"?J?.fov??75:75,h=J?.projection==="orthographic"?J.zoom??1:1,y=T?Bq(T):H,l=y.traumaDecay,m=y.maxOffsetX,d=y.maxOffsetY,c=y.maxOffsetZ,n={targetX:S?.x??0,targetY:S?.y??0,targetZ:S?.z??0,azimuth:W,elevation:K(z,U,u),distance:K(f,k,x),followTarget:-1,followSmoothing:b?.smoothing??G.smoothing,followOffsetX:b?.offsetX??G.offsetX,followOffsetY:b?.offsetY??G.offsetY,followOffsetZ:b?.offsetZ??G.offsetZ,trauma:0,shakeOffsetX:0,shakeOffsetY:0,shakeOffsetZ:0},i={follow(j,B){let I=typeof j==="number"?j:j.id;this.followTarget=I,this.followSmoothing=B?.smoothing??b?.smoothing??G.smoothing,this.followOffsetX=B?.offsetX??b?.offsetX??G.offsetX,this.followOffsetY=B?.offsetY??b?.offsetY??G.offsetY,this.followOffsetZ=B?.offsetZ??b?.offsetZ??G.offsetZ},unfollow(){this.followTarget=-1},setTarget(j,B,I){this.targetX=j,this.targetY=B,this.targetZ=I},setOrbit(j,B,I){this.azimuth=j,this.elevation=K(B,U,u),this.distance=K(I,k,x)},setDistance(j){this.distance=K(j,k,x)},addTrauma(j){this.trauma=K(this.trauma+j,0,1)}};return qq("camera3d").withResourceTypes().withLabels().withGroups().requires().install((j)=>{let B={active:!1,prevX:0,prevY:0,pendingDolly:0,el:null},q={...n,...i,...p==="orthographic"?{projection:"orthographic",zoom:h,setZoom(Q){this.zoom=Q}}:{projection:"perspective",fov:g,setFov(Q){this.fov=Q}}};j.addResource("camera3DState",q);function _(Q){B.active=!0,B.prevX=Q.clientX,B.prevY=Q.clientY,B.el?.setPointerCapture(Q.pointerId)}function v(Q){if(!B.active)return;let Z=Q.clientX-B.prevX,M=Q.clientY-B.prevY;B.prevX=Q.clientX,B.prevY=Q.clientY,q.azimuth-=Z*D,q.elevation=K(q.elevation+M*D,U,u)}function P(Q){B.active=!1,B.el?.releasePointerCapture(Q.pointerId)}function F(Q){Q.preventDefault(),B.pendingDolly+=Math.sign(Q.deltaY)}let V=null,X=null,Y=null;j.addSystem("camera3d-init").inGroup($).setOnInitialize((Q)=>{let Z=Q.getResource("threeRenderer");if(V=Q.getResource("camera"),V.isPerspectiveCamera)X=V;else if(V.isOrthographicCamera)Y=V;if(q.projection==="perspective"&&!X)throw Error("createCamera3DPlugin: configured as 'perspective' but the renderer's camera is not a PerspectiveCamera.");if(q.projection==="orthographic"&&!Y)throw Error("createCamera3DPlugin: configured as 'orthographic' but the renderer's camera is not an OrthographicCamera.");if(q.projection==="perspective"&&X)q.fov=X.fov;else if(q.projection==="orthographic"&&Y)q.zoom=Y.zoom;B.el=Z.domElement,B.el.addEventListener("pointerdown",_),B.el.addEventListener("pointermove",v),B.el.addEventListener("pointerup",P),B.el.addEventListener("wheel",F,{passive:!1}),L(q.azimuth,q.elevation,q.distance,N),V.position.set(q.targetX+N.x,q.targetY+N.y,q.targetZ+N.z),V.lookAt(q.targetX,q.targetY,q.targetZ)}).setOnDetach(()=>{if(!B.el)return;B.el.removeEventListener("pointerdown",_),B.el.removeEventListener("pointermove",v),B.el.removeEventListener("pointerup",P),B.el.removeEventListener("wheel",F),B.el=null,V=null,X=null,Y=null}),j.addSystem("camera3d-follow").setPriority(400).inPhase(R).inGroup($).setProcess(({ecs:Q,dt:Z})=>{if(q.followTarget<0)return;let M;try{M=Q.getComponent(q.followTarget,"worldTransform3D")}catch{q.followTarget=-1;return}if(!M)return;let r=M.x+q.followOffsetX,o=M.y+q.followOffsetY,s=M.z+q.followOffsetZ,A=Math.min(1,q.followSmoothing*Z);q.targetX+=(r-q.targetX)*A,q.targetY+=(o-q.targetY)*A,q.targetZ+=(s-q.targetZ)*A}),j.addSystem("camera3d-shake").setPriority(390).inPhase(R).inGroup($).setProcess(({dt:Q})=>{if(q.trauma<=0){q.shakeOffsetX=0,q.shakeOffsetY=0,q.shakeOffsetZ=0;return}q.trauma=Math.max(0,q.trauma-l*Q);let Z=q.trauma*q.trauma;q.shakeOffsetX=m*Z*(w()*2-1),q.shakeOffsetY=d*Z*(w()*2-1),q.shakeOffsetZ=c*Z*(w()*2-1)}),j.addSystem("camera3d-sync").setPriority(380).inPhase(R).inGroup($).setProcess(()=>{if(!V)return;if(B.pendingDolly!==0)q.distance=K(q.distance*Math.pow(C,B.pendingDolly),k,x),B.pendingDolly=0;if(L(q.azimuth,q.elevation,q.distance,N),V.position.set(q.targetX+N.x+q.shakeOffsetX,q.targetY+N.y+q.shakeOffsetY,q.targetZ+N.z+q.shakeOffsetZ),V.lookAt(q.targetX+q.shakeOffsetX,q.targetY+q.shakeOffsetY,q.targetZ+q.shakeOffsetZ),q.projection==="perspective"&&X&&X.fov!==q.fov)X.fov=q.fov,X.updateProjectionMatrix();else if(q.projection==="orthographic"&&Y&&Y.zoom!==q.zoom)Y.zoom=q.zoom,Y.updateProjectionMatrix()})})}export{L as sphericalToCartesian,Vq as createCamera3DPlugin};
|
|
2
|
+
|
|
3
|
+
//# debugId=E9143DDF484E288364756E2164756E21
|
|
4
|
+
//# sourceMappingURL=camera3D.js.map
|