ecspresso 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +2 -0
  3. package/dist/asset-manager.d.ts +8 -8
  4. package/dist/asset-types.d.ts +9 -5
  5. package/dist/ecspresso-builder.d.ts +5 -5
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +2 -2
  8. package/dist/index.js.map +7 -7
  9. package/dist/plugins/ai/behavior-tree.d.ts +2 -2
  10. package/dist/plugins/ai/behavior-tree.js.map +2 -2
  11. package/dist/plugins/ai/detection.d.ts +3 -3
  12. package/dist/plugins/ai/detection.js.map +2 -2
  13. package/dist/plugins/ai/flocking.d.ts +3 -3
  14. package/dist/plugins/ai/flocking.js.map +1 -1
  15. package/dist/plugins/ai/pathfinding.d.ts +3 -4
  16. package/dist/plugins/ai/pathfinding.js.map +2 -2
  17. package/dist/plugins/combat/health.d.ts +2 -2
  18. package/dist/plugins/combat/health.js.map +2 -2
  19. package/dist/plugins/combat/projectile.d.ts +3 -3
  20. package/dist/plugins/combat/projectile.js.map +2 -2
  21. package/dist/plugins/input/selection.d.ts +3 -3
  22. package/dist/plugins/input/selection.js.map +3 -3
  23. package/dist/plugins/isometric/depth-sort.d.ts +2 -2
  24. package/dist/plugins/isometric/depth-sort.js.map +2 -2
  25. package/dist/plugins/isometric/projection.d.ts +2 -2
  26. package/dist/plugins/isometric/projection.js.map +2 -2
  27. package/dist/plugins/physics/steering.d.ts +2 -2
  28. package/dist/plugins/physics/steering.js.map +2 -2
  29. package/dist/plugins/rendering/particles.d.ts +2 -2
  30. package/dist/plugins/rendering/particles.js.map +1 -1
  31. package/dist/plugins/rendering/renderer2D.d.ts +6 -5
  32. package/dist/plugins/rendering/renderer2D.js.map +2 -2
  33. package/dist/plugins/rendering/renderer3D.d.ts +3 -2
  34. package/dist/plugins/rendering/renderer3D.js.map +2 -2
  35. package/dist/plugins/rendering/sprite-animation.d.ts +110 -0
  36. package/dist/plugins/rendering/sprite-animation.js +2 -2
  37. package/dist/plugins/rendering/sprite-animation.js.map +3 -3
  38. package/dist/plugins/rendering/tilemap.d.ts +3 -3
  39. package/dist/plugins/rendering/tilemap.js.map +3 -3
  40. package/dist/plugins/spatial/camera.js.map +2 -2
  41. package/dist/plugins/spatial/camera3D.d.ts +3 -3
  42. package/dist/plugins/spatial/camera3D.js.map +2 -2
  43. package/dist/plugins/spatial/transform.d.ts +2 -2
  44. package/dist/plugins/spatial/transform.js.map +1 -1
  45. package/dist/plugins/spatial/transform3D.d.ts +2 -2
  46. package/dist/plugins/spatial/transform3D.js.map +1 -1
  47. package/dist/plugins/ui/ui.d.ts +2 -2
  48. package/dist/plugins/ui/ui.js.map +3 -3
  49. package/dist/screen-types.d.ts +7 -3
  50. package/dist/system-builder.d.ts +5 -5
  51. package/dist/type-utils.d.ts +20 -0
  52. package/dist/types.d.ts +1 -1
  53. package/package.json +5 -4
@@ -15,7 +15,7 @@
15
15
  * Decorators — inverter, repeat, cooldown, guard
16
16
  * Leaves — action (tick → NodeStatus, optional onAbort), condition (predicate)
17
17
  */
18
- import { type BasePluginOptions, type WorldConfigFrom, type BaseWorld } from 'ecspresso';
18
+ import { type BasePluginOptions, type BaseWorld, type ComponentsConfig, type EventsConfig } from 'ecspresso';
19
19
  /**
20
20
  * Return value from behavior tree node ticks.
21
21
  *
@@ -272,7 +272,7 @@ export interface BehaviorTreeEventTypes {
272
272
  /**
273
273
  * WorldConfig representing the behavior tree plugin's provided types.
274
274
  */
275
- export type BehaviorTreeWorldConfig = WorldConfigFrom<BehaviorTreeComponentTypes, BehaviorTreeEventTypes>;
275
+ export type BehaviorTreeWorldConfig = ComponentsConfig<BehaviorTreeComponentTypes> & EventsConfig<BehaviorTreeEventTypes>;
276
276
  /**
277
277
  * Create a `behaviorTree` component from a definition.
278
278
  *
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/plugins/ai/behavior-tree.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Behavior Tree Plugin for ECSpresso\n *\n * Provides composable, priority-driven AI via behavior trees. Shared immutable\n * tree definitions drive per-entity runtime state. Uses hybrid traversal\n * (Approach C): re-evaluate from root each tick to preserve priority, resume\n * running leaves, and abort diverged running nodes via `onAbort`.\n *\n * Each entity gets a `behaviorTree` component referencing a shared definition\n * plus a typed blackboard for per-entity AI memory. One system processes all\n * behavior-tree entities each tick.\n *\n * Node types:\n * Composites — sequence, selector, parallel\n * Decorators — inverter, repeat, cooldown, guard\n * Leaves — action (tick → NodeStatus, optional onAbort), condition (predicate)\n */\n\nimport { definePlugin, type BasePluginOptions, type WorldConfigFrom, type BaseWorld } from 'ecspresso';\n\n// ==================== NodeStatus ====================\n\n/**\n * Return value from behavior tree node ticks.\n *\n * - `Success` (0) — node completed successfully\n * - `Failure` (1) — node failed\n * - `Running` (2) — node still executing, will resume next tick\n */\nexport const NodeStatus = { Success: 0, Failure: 1, Running: 2 } as const;\nexport type NodeStatus = (typeof NodeStatus)[keyof typeof NodeStatus];\n\n// ==================== Callback Context ====================\n\n/** BaseWorld narrowed to behavior-tree components for typed access in helpers. */\ntype BehaviorTreeWorld = BaseWorld<BehaviorTreeComponentTypes>;\n\n/**\n * Context passed to all leaf node callbacks (action tick, condition check,\n * onAbort, guard predicates).\n *\n * @template BB - Blackboard type for per-entity AI memory\n * @template W - World interface type (default: BehaviorTreeWorld)\n */\nexport interface BehaviorTreeContext<\n\tBB extends object = Record<string, unknown>,\n\tW extends BaseWorld<BehaviorTreeComponentTypes> = BehaviorTreeWorld,\n> {\n\treadonly ecs: W;\n\treadonly entityId: number;\n\treadonly dt: number;\n\treadonly blackboard: BB;\n}\n\n// ==================== Node Types ====================\n\n/**\n * Action leaf — executes behavior each tick.\n * Returns `Running` for multi-frame actions. Optional `onAbort` fires\n * when a higher-priority branch preempts this running action.\n */\nexport interface ActionNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'action';\n\treadonly name: string;\n\treadonly tick: (ctx: BehaviorTreeContext<BB>) => NodeStatus;\n\treadonly onAbort?: (ctx: BehaviorTreeContext<BB>) => void;\n\tnodeIndex: number;\n}\n\n/**\n * Condition leaf — checks a predicate. Returns Success or Failure, never Running.\n */\nexport interface ConditionNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'condition';\n\treadonly name: string;\n\treadonly check: (ctx: BehaviorTreeContext<BB>) => boolean;\n\tnodeIndex: number;\n}\n\n/**\n * Sequence composite — runs children left-to-right.\n * Fails on first failure, succeeds when all succeed.\n * Resumes from stored child index when a running node exists.\n */\nexport interface SequenceNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'sequence';\n\treadonly children: readonly BehaviorTreeNode<BB>[];\n\tnodeIndex: number;\n}\n\n/**\n * Selector composite — runs children left-to-right.\n * Succeeds on first success, fails when all fail.\n * Always re-evaluates from child 0 to preserve priority ordering.\n */\nexport interface SelectorNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'selector';\n\treadonly children: readonly BehaviorTreeNode<BB>[];\n\tnodeIndex: number;\n}\n\n/**\n * Parallel composite — ticks all children each frame.\n * Configurable success/failure thresholds.\n *\n * Limitation (v1): only one running leaf is tracked for abort.\n * Other running children in a parallel stop being ticked if the\n * tree path diverges but do not receive an `onAbort` call.\n */\nexport interface ParallelNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'parallel';\n\treadonly children: readonly BehaviorTreeNode<BB>[];\n\treadonly successThreshold: number;\n\treadonly failureThreshold: number;\n\tnodeIndex: number;\n}\n\n/** Decorator — inverts child result (Success↔Failure), passes Running through. */\nexport interface InverterNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'inverter';\n\treadonly child: BehaviorTreeNode<BB>;\n\tnodeIndex: number;\n}\n\n/** Decorator — repeats child `count` times (or forever when count is -1). */\nexport interface RepeatNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'repeat';\n\treadonly child: BehaviorTreeNode<BB>;\n\treadonly count: number;\n\tnodeIndex: number;\n}\n\n/** Decorator — prevents child re-entry for `duration` seconds after completion. */\nexport interface CooldownNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'cooldown';\n\treadonly child: BehaviorTreeNode<BB>;\n\treadonly duration: number;\n\tnodeIndex: number;\n}\n\n/** Decorator — conditional gate. Ticks child only when condition passes. */\nexport interface GuardNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'guard';\n\treadonly child: BehaviorTreeNode<BB>;\n\treadonly condition: (ctx: BehaviorTreeContext<BB>) => boolean;\n\tnodeIndex: number;\n}\n\n/** Union of all behavior tree node types. */\nexport type BehaviorTreeNode<BB extends object = Record<string, unknown>> =\n\t| ActionNode<BB>\n\t| ConditionNode<BB>\n\t| SequenceNode<BB>\n\t| SelectorNode<BB>\n\t| ParallelNode<BB>\n\t| InverterNode<BB>\n\t| RepeatNode<BB>\n\t| CooldownNode<BB>\n\t| GuardNode<BB>;\n\n// ==================== Builder Functions ====================\n\n/**\n * Create an action leaf node.\n *\n * @param name - Human-readable name (used in abort events)\n * @param tick - Called each frame while this node is active; return NodeStatus\n * @param options - Optional `onAbort` callback fired when preempted by a higher-priority branch\n */\nexport function action<BB extends object>(\n\tname: string,\n\ttick: (ctx: BehaviorTreeContext<BB>) => NodeStatus,\n\toptions?: { onAbort?: (ctx: BehaviorTreeContext<BB>) => void },\n): ActionNode<BB> {\n\treturn { type: 'action', name, tick, onAbort: options?.onAbort, nodeIndex: -1 };\n}\n\n/**\n * Create a condition leaf node.\n *\n * @param name - Human-readable name\n * @param check - Predicate returning true (Success) or false (Failure). Never Running.\n */\nexport function condition<BB extends object>(\n\tname: string,\n\tcheck: (ctx: BehaviorTreeContext<BB>) => boolean,\n): ConditionNode<BB> {\n\treturn { type: 'condition', name, check, nodeIndex: -1 };\n}\n\n/**\n * Create a sequence composite. Runs children L→R, fails on first failure.\n */\nexport function sequence<BB extends object>(\n\tchildren: BehaviorTreeNode<BB>[],\n): SequenceNode<BB> {\n\treturn { type: 'sequence', children, nodeIndex: -1 };\n}\n\n/**\n * Create a selector composite. Runs children L→R, succeeds on first success.\n * Always starts from child 0 to re-evaluate priority.\n */\nexport function selector<BB extends object>(\n\tchildren: BehaviorTreeNode<BB>[],\n): SelectorNode<BB> {\n\treturn { type: 'selector', children, nodeIndex: -1 };\n}\n\n/**\n * Create a parallel composite. Ticks all children each frame.\n *\n * @param children - Child nodes to tick in parallel\n * @param options.successThreshold - Successes needed for parallel to succeed (default: all)\n * @param options.failureThreshold - Failures needed for parallel to fail (default: all)\n */\nexport function parallel<BB extends object>(\n\tchildren: BehaviorTreeNode<BB>[],\n\toptions?: { successThreshold?: number; failureThreshold?: number },\n): ParallelNode<BB> {\n\treturn {\n\t\ttype: 'parallel',\n\t\tchildren,\n\t\tsuccessThreshold: options?.successThreshold ?? children.length,\n\t\tfailureThreshold: options?.failureThreshold ?? children.length,\n\t\tnodeIndex: -1,\n\t};\n}\n\n/** Create an inverter decorator. Flips Success↔Failure, passes Running. */\nexport function inverter<BB extends object>(\n\tchild: BehaviorTreeNode<BB>,\n): InverterNode<BB> {\n\treturn { type: 'inverter', child, nodeIndex: -1 };\n}\n\n/**\n * Create a repeat decorator.\n *\n * @param child - Node to repeat\n * @param count - Number of repetitions, or -1 for infinite (default: -1)\n */\nexport function repeat<BB extends object>(\n\tchild: BehaviorTreeNode<BB>,\n\tcount = -1,\n): RepeatNode<BB> {\n\treturn { type: 'repeat', child, count, nodeIndex: -1 };\n}\n\n/**\n * Create a cooldown decorator. Prevents re-entry for `duration` seconds\n * after child completes (Success or Failure).\n */\nexport function cooldown<BB extends object>(\n\tchild: BehaviorTreeNode<BB>,\n\tduration: number,\n): CooldownNode<BB> {\n\treturn { type: 'cooldown', child, duration, nodeIndex: -1 };\n}\n\n/**\n * Create a guard decorator. Ticks child only when condition returns true.\n * Returns Failure when condition is false.\n */\nexport function guard<BB extends object>(\n\tcond: (ctx: BehaviorTreeContext<BB>) => boolean,\n\tchild: BehaviorTreeNode<BB>,\n): GuardNode<BB> {\n\treturn { type: 'guard', condition: cond, child, nodeIndex: -1 };\n}\n\n// ==================== Definition ====================\n\n/**\n * Immutable behavior tree definition. Shared across entities.\n *\n * @template BB - Blackboard type for per-entity AI memory\n */\nexport interface BehaviorTreeDefinition<BB extends object = Record<string, unknown>> {\n\treadonly id: string;\n\treadonly root: BehaviorTreeNode<BB>;\n\treadonly nodeCount: number;\n}\n\n/** Internal storage for definition data not exposed on the public interface. */\nconst defFlatNodes = new WeakMap<BehaviorTreeDefinition<object>, readonly BehaviorTreeNode<object>[]>();\nconst defDefaultBB = new WeakMap<BehaviorTreeDefinition<object>, object>();\n\n/**\n * Define a behavior tree with a typed blackboard.\n *\n * The `blackboard` value serves as both the type source and the default\n * initial state cloned for each entity via `createBehaviorTree`.\n *\n * @param id - Unique identifier for this tree definition\n * @param config - `{ blackboard, root }` — default blackboard + root node\n * @returns Frozen BehaviorTreeDefinition\n *\n * @example\n * ```typescript\n * const tree = defineBehaviorTree('patrol', {\n * blackboard: { targetId: null as number | null, timer: 0 },\n * root: selector([\n * guard(ctx => ctx.blackboard.targetId !== null, action('chase', ...)),\n * action('wander', ...),\n * ]),\n * });\n * ```\n */\nexport function defineBehaviorTree<BB extends object>(\n\tid: string,\n\tconfig: { blackboard: BB; root: BehaviorTreeNode<BB> },\n): BehaviorTreeDefinition<BB> {\n\tlet nextIndex = 0;\n\tconst flatNodes: BehaviorTreeNode<BB>[] = [];\n\n\tfunction indexTree(node: BehaviorTreeNode<BB>): void {\n\t\tnode.nodeIndex = nextIndex;\n\t\tflatNodes[nextIndex] = node;\n\t\tnextIndex++;\n\t\tif ('children' in node) {\n\t\t\tfor (const child of node.children) indexTree(child);\n\t\t}\n\t\tif ('child' in node) {\n\t\t\tindexTree(node.child);\n\t\t}\n\t}\n\tindexTree(config.root);\n\n\tconst def: BehaviorTreeDefinition<BB> = Object.freeze({ id, root: config.root, nodeCount: nextIndex });\n\tdefFlatNodes.set(def as BehaviorTreeDefinition<object>, flatNodes as readonly BehaviorTreeNode<object>[]);\n\tdefDefaultBB.set(def as BehaviorTreeDefinition<object>, config.blackboard);\n\treturn def;\n}\n\n// ==================== Per-Entity Component ====================\n\n/**\n * Runtime behavior tree state stored on each entity.\n *\n * The `blackboard` is typed as `object` at the component level.\n * Inside tree callbacks, the `BehaviorTreeContext<BB>` provides\n * typed access to the blackboard via the tree definition's generic.\n * Outside the tree, cast the blackboard to the specific BB type.\n */\nexport interface BehaviorTreeComponent {\n\treadonly definition: BehaviorTreeDefinition<Record<string, unknown>>;\n\tblackboard: object;\n\t/** Index of the currently running leaf, or -1 if none. */\n\trunningNodeIndex: number;\n\t/**\n\t * Dense per-node state array (sized to `definition.nodeCount`).\n\t * Semantics vary by node type:\n\t * - sequence/selector: child progress index\n\t * - repeat: completed iteration count\n\t * - cooldown: expiry timestamp (elapsedTime when cooldown ends)\n\t */\n\tnodeState: Float64Array;\n\t/** Accumulated time (seconds) for cooldown tracking. */\n\telapsedTime: number;\n}\n\n/**\n * Component types provided by the behavior tree plugin.\n */\nexport interface BehaviorTreeComponentTypes {\n\tbehaviorTree: BehaviorTreeComponent;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event published when a running action is preempted (aborted) by a\n * higher-priority branch taking over.\n */\nexport interface BehaviorTreeAbortEvent {\n\tentityId: number;\n\t/** nodeIndex of the aborted action */\n\tnodeIndex: number;\n\t/** Human-readable name of the aborted action */\n\tnodeName: string;\n\t/** Definition id of the behavior tree */\n\tdefinitionId: string;\n}\n\n/**\n * Event types provided by the behavior tree plugin.\n */\nexport interface BehaviorTreeEventTypes {\n\tbehaviorTreeAbort: BehaviorTreeAbortEvent;\n}\n\n// ==================== WorldConfig ====================\n\n/**\n * WorldConfig representing the behavior tree plugin's provided types.\n */\nexport type BehaviorTreeWorldConfig = WorldConfigFrom<BehaviorTreeComponentTypes, BehaviorTreeEventTypes>;\n\n// ==================== Helper Functions ====================\n\n/**\n * Create a `behaviorTree` component from a definition.\n *\n * @param definition - Shared tree definition\n * @param blackboard - Optional partial overrides for the default blackboard\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createBehaviorTree(villagerTree, { hunger: 80 }),\n * ...createLocalTransform(100, 200),\n * });\n * ```\n */\nexport function createBehaviorTree<BB extends object>(\n\tdefinition: BehaviorTreeDefinition<BB>,\n\tblackboard?: Partial<BB>,\n): Pick<BehaviorTreeComponentTypes, 'behaviorTree'> {\n\tconst defaultBB = defDefaultBB.get(definition as BehaviorTreeDefinition<object>) as BB;\n\tconst bb = { ...defaultBB, ...blackboard };\n\treturn {\n\t\tbehaviorTree: {\n\t\t\tdefinition: definition as BehaviorTreeDefinition<Record<string, unknown>>,\n\t\t\tblackboard: bb,\n\t\t\trunningNodeIndex: -1,\n\t\t\tnodeState: new Float64Array(definition.nodeCount),\n\t\t\telapsedTime: 0,\n\t\t},\n\t};\n}\n\n/**\n * Check whether an entity's behavior tree has a running action.\n */\nexport function isBehaviorTreeRunning(\n\tecs: { getComponent(entityId: number, name: 'behaviorTree'): BehaviorTreeComponent | undefined },\n\tentityId: number,\n): boolean {\n\tconst bt = ecs.getComponent(entityId, 'behaviorTree');\n\treturn bt !== undefined && bt.runningNodeIndex !== -1;\n}\n\n/**\n * Reset an entity's behavior tree: abort any running action, clear all\n * composite progress, and optionally reset the blackboard.\n */\nexport function resetBehaviorTree(\n\tecs: BehaviorTreeWorld,\n\tentityId: number,\n\tblackboard?: Partial<Record<string, unknown>>,\n): void {\n\tconst bt = ecs.getComponent(entityId, 'behaviorTree');\n\tif (!bt) return;\n\n\tif (bt.runningNodeIndex !== -1) {\n\t\tconst flatNodes = defFlatNodes.get(bt.definition as BehaviorTreeDefinition<object>);\n\t\tconst node = flatNodes?.[bt.runningNodeIndex];\n\t\tif (node && node.type === 'action' && node.onAbort) {\n\t\t\tnode.onAbort({ ecs, entityId, dt: 0, blackboard: bt.blackboard as Record<string, unknown> });\n\t\t}\n\t\tbt.runningNodeIndex = -1;\n\t}\n\tbt.nodeState.fill(0);\n\tbt.elapsedTime = 0;\n\n\tif (blackboard) {\n\t\tObject.assign(bt.blackboard, blackboard);\n\t}\n}\n\n// ==================== Internal: Traversal ====================\n\n/** Internal shorthand — all runtime traversal uses the erased base types. */\ntype AnyNode = BehaviorTreeNode<Record<string, unknown>>;\n\n/** Mutable version of context for pre-allocation in the system loop. */\ninterface MutableCtx {\n\tecs: BehaviorTreeWorld;\n\tentityId: number;\n\tdt: number;\n\tblackboard: Record<string, unknown>;\n}\n\nfunction abortRunningNode(bt: BehaviorTreeComponent, ctx: MutableCtx): void {\n\tconst flatNodes = defFlatNodes.get(bt.definition as BehaviorTreeDefinition<object>);\n\tconst node = flatNodes?.[bt.runningNodeIndex] as AnyNode | undefined;\n\tif (node && node.type === 'action') {\n\t\tnode.onAbort?.(ctx);\n\t\tctx.ecs.eventBus.publish('behaviorTreeAbort', {\n\t\t\tentityId: ctx.entityId,\n\t\t\tnodeIndex: bt.runningNodeIndex,\n\t\t\tnodeName: node.name,\n\t\t\tdefinitionId: bt.definition.id,\n\t\t} satisfies BehaviorTreeAbortEvent);\n\t}\n\tbt.nodeState.fill(0);\n\tbt.runningNodeIndex = -1;\n}\n\nfunction tickNode(node: AnyNode, bt: BehaviorTreeComponent, ctx: MutableCtx): NodeStatus {\n\tswitch (node.type) {\n\t\tcase 'condition':\n\t\t\treturn node.check(ctx) ? NodeStatus.Success : NodeStatus.Failure;\n\n\t\tcase 'action': {\n\t\t\tconst result = node.tick(ctx);\n\t\t\tif (result === NodeStatus.Running) {\n\t\t\t\tif (bt.runningNodeIndex !== -1 && bt.runningNodeIndex !== node.nodeIndex) {\n\t\t\t\t\tabortRunningNode(bt, ctx);\n\t\t\t\t}\n\t\t\t\tbt.runningNodeIndex = node.nodeIndex;\n\t\t\t} else if (bt.runningNodeIndex === node.nodeIndex) {\n\t\t\t\tbt.runningNodeIndex = -1;\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\tcase 'sequence': {\n\t\t\tconst startChild = (bt.runningNodeIndex !== -1)\n\t\t\t\t? (bt.nodeState[node.nodeIndex] ?? 0)\n\t\t\t\t: 0;\n\t\t\tfor (let i = startChild; i < node.children.length; i++) {\n\t\t\t\tconst status = tickNode(node.children[i]!, bt, ctx);\n\t\t\t\tif (status === NodeStatus.Failure) {\n\t\t\t\t\tbt.nodeState[node.nodeIndex] = 0;\n\t\t\t\t\treturn NodeStatus.Failure;\n\t\t\t\t}\n\t\t\t\tif (status === NodeStatus.Running) {\n\t\t\t\t\tbt.nodeState[node.nodeIndex] = i;\n\t\t\t\t\treturn NodeStatus.Running;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbt.nodeState[node.nodeIndex] = 0;\n\t\t\treturn NodeStatus.Success;\n\t\t}\n\n\t\tcase 'selector': {\n\t\t\tfor (let i = 0; i < node.children.length; i++) {\n\t\t\t\tconst status = tickNode(node.children[i]!, bt, ctx);\n\t\t\t\tif (status === NodeStatus.Success) return NodeStatus.Success;\n\t\t\t\tif (status === NodeStatus.Running) return NodeStatus.Running;\n\t\t\t}\n\t\t\treturn NodeStatus.Failure;\n\t\t}\n\n\t\tcase 'parallel': {\n\t\t\tlet successCount = 0;\n\t\t\tlet failureCount = 0;\n\t\t\tlet anyRunning = false;\n\t\t\tfor (let i = 0; i < node.children.length; i++) {\n\t\t\t\tconst status = tickNode(node.children[i]!, bt, ctx);\n\t\t\t\tif (status === NodeStatus.Success) successCount++;\n\t\t\t\telse if (status === NodeStatus.Failure) failureCount++;\n\t\t\t\telse anyRunning = true;\n\t\t\t}\n\t\t\tif (successCount >= node.successThreshold) return NodeStatus.Success;\n\t\t\tif (failureCount >= node.failureThreshold) return NodeStatus.Failure;\n\t\t\tif (anyRunning) return NodeStatus.Running;\n\t\t\treturn NodeStatus.Failure;\n\t\t}\n\n\t\tcase 'inverter': {\n\t\t\tconst status = tickNode(node.child, bt, ctx);\n\t\t\tif (status === NodeStatus.Success) return NodeStatus.Failure;\n\t\t\tif (status === NodeStatus.Failure) return NodeStatus.Success;\n\t\t\treturn NodeStatus.Running;\n\t\t}\n\n\t\tcase 'repeat': {\n\t\t\tconst iteration = bt.nodeState[node.nodeIndex] ?? 0;\n\t\t\tconst status = tickNode(node.child, bt, ctx);\n\t\t\tif (status === NodeStatus.Failure) {\n\t\t\t\tbt.nodeState[node.nodeIndex] = 0;\n\t\t\t\treturn NodeStatus.Failure;\n\t\t\t}\n\t\t\tif (status === NodeStatus.Running) return NodeStatus.Running;\n\t\t\tconst next = iteration + 1;\n\t\t\tif (node.count !== -1 && next >= node.count) {\n\t\t\t\tbt.nodeState[node.nodeIndex] = 0;\n\t\t\t\treturn NodeStatus.Success;\n\t\t\t}\n\t\t\tbt.nodeState[node.nodeIndex] = next;\n\t\t\treturn NodeStatus.Running;\n\t\t}\n\n\t\tcase 'cooldown': {\n\t\t\tconst expiresAt = bt.nodeState[node.nodeIndex] ?? 0;\n\t\t\tif (expiresAt > 0 && bt.elapsedTime < expiresAt) return NodeStatus.Failure;\n\t\t\tconst status = tickNode(node.child, bt, ctx);\n\t\t\tif (status !== NodeStatus.Running) {\n\t\t\t\tbt.nodeState[node.nodeIndex] = bt.elapsedTime + node.duration;\n\t\t\t}\n\t\t\treturn status;\n\t\t}\n\n\t\tcase 'guard': {\n\t\t\tif (!node.condition(ctx)) return NodeStatus.Failure;\n\t\t\treturn tickNode(node.child, bt, ctx);\n\t\t}\n\t}\n}\n\n// ==================== Typed Helpers ====================\n\n/**\n * Typed helpers for the behavior tree plugin.\n * Creates helpers that validate callback parameters against the world type W.\n * Call after `.build()` using `typeof ecs`.\n */\nexport interface BehaviorTreeHelpers<W extends BaseWorld<BehaviorTreeComponentTypes>> {\n\tdefineBehaviorTree: <BB extends object>(\n\t\tid: string,\n\t\tconfig: { blackboard: BB; root: BehaviorTreeNode<BB> },\n\t) => BehaviorTreeDefinition<BB>;\n\taction: <BB extends object>(\n\t\tname: string,\n\t\ttick: (ctx: BehaviorTreeContext<BB, W>) => NodeStatus,\n\t\toptions?: { onAbort?: (ctx: BehaviorTreeContext<BB, W>) => void },\n\t) => ActionNode<BB>;\n\tcondition: <BB extends object>(\n\t\tname: string,\n\t\tcheck: (ctx: BehaviorTreeContext<BB, W>) => boolean,\n\t) => ConditionNode<BB>;\n\tguard: <BB extends object>(\n\t\tcond: (ctx: BehaviorTreeContext<BB, W>) => boolean,\n\t\tchild: BehaviorTreeNode<BB>,\n\t) => GuardNode<BB>;\n}\n\n/**\n * Create typed behavior tree helpers bound to a specific world type.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createBehaviorTreePlugin())\n * .build();\n *\n * const { defineBehaviorTree, action, condition, guard } = ecs.getHelpers(createBehaviorTreeHelpers);\n * ```\n */\nexport function createBehaviorTreeHelpers<\n\tW extends BaseWorld<BehaviorTreeComponentTypes> = BehaviorTreeWorld,\n>(_world?: W): BehaviorTreeHelpers<W> {\n\treturn {\n\t\tdefineBehaviorTree: defineBehaviorTree as BehaviorTreeHelpers<W>['defineBehaviorTree'],\n\t\taction: action as BehaviorTreeHelpers<W>['action'],\n\t\tcondition: condition as BehaviorTreeHelpers<W>['condition'],\n\t\tguard: guard as BehaviorTreeHelpers<W>['guard'],\n\t};\n}\n\n// ==================== Plugin Options ====================\n\n/**\n * Configuration options for the behavior tree plugin.\n */\nexport interface BehaviorTreePluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a behavior tree plugin for ECSpresso.\n *\n * Provides composable, priority-driven AI via behavior trees with:\n * - Hybrid traversal: re-evaluate from root each tick, resume running leaves\n * - Automatic abort with `onAbort` callback when preempted\n * - Typed blackboard for per-entity AI memory\n * - `behaviorTreeAbort` events on preemption\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createBehaviorTreePlugin())\n * .build();\n *\n * const { defineBehaviorTree, action, condition, guard } = ecs.getHelpers(createBehaviorTreeHelpers);\n *\n * const tree = defineBehaviorTree('villager', {\n * blackboard: { hunger: 100, targetId: null as number | null },\n * root: selector([\n * guard(ctx => ctx.blackboard.hunger < 30, action('eat', ...)),\n * action('wander', ...),\n * ]),\n * });\n *\n * ecs.spawn({\n * ...createBehaviorTree(tree),\n * ...createLocalTransform(100, 200),\n * });\n * ```\n */\nexport function createBehaviorTreePlugin<G extends string = 'ai'>(\n\toptions?: BehaviorTreePluginOptions<G>,\n) {\n\tconst {\n\t\tsystemGroup = 'ai',\n\t\tpriority = 0,\n\t\tphase = 'update',\n\t} = options ?? {};\n\n\treturn definePlugin('behaviorTree')\n\t\t.withComponentTypes<BehaviorTreeComponentTypes>()\n\t\t.withEventTypes<BehaviorTreeEventTypes>()\n\t\t.withLabels<'behavior-tree-update'>()\n\t\t.withGroups<G>()\n\t\t.install((world) => {\n\t\t\t// Dispose: abort running node on entity removal\n\t\t\tworld.registerDispose('behaviorTree', ({ value, entityId }) => {\n\t\t\t\tif (value.runningNodeIndex !== -1) {\n\t\t\t\t\tconst flatNodes = defFlatNodes.get(value.definition as BehaviorTreeDefinition<object>);\n\t\t\t\t\tconst node = flatNodes?.[value.runningNodeIndex] as AnyNode | undefined;\n\t\t\t\t\tif (node && node.type === 'action' && node.onAbort) {\n\t\t\t\t\t\tnode.onAbort({\n\t\t\t\t\t\t\tecs: world as unknown as BehaviorTreeWorld,\n\t\t\t\t\t\t\tentityId,\n\t\t\t\t\t\t\tdt: 0,\n\t\t\t\t\t\t\tblackboard: value.blackboard as Record<string, unknown>,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tworld\n\t\t\t\t.addSystem('behavior-tree-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('trees', {\n\t\t\t\t\twith: ['behaviorTree'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs: ecsWorld }) => {\n\t\t\t\t\tconst ctx: MutableCtx = {\n\t\t\t\t\t\tecs: ecsWorld as unknown as BehaviorTreeWorld,\n\t\t\t\t\t\tentityId: 0,\n\t\t\t\t\t\tdt: 0,\n\t\t\t\t\t\tblackboard: {},\n\t\t\t\t\t};\n\n\t\t\t\t\tfor (const entity of queries.trees) {\n\t\t\t\t\t\tconst bt = entity.components.behaviorTree;\n\t\t\t\t\t\tctx.entityId = entity.id;\n\t\t\t\t\t\tctx.dt = dt;\n\t\t\t\t\t\tctx.blackboard = bt.blackboard as Record<string, unknown>;\n\t\t\t\t\t\tbt.elapsedTime += dt;\n\n\t\t\t\t\t\tconst result = tickNode(bt.definition.root as AnyNode, bt, ctx);\n\n\t\t\t\t\t\tif (result !== NodeStatus.Running && bt.runningNodeIndex !== -1) {\n\t\t\t\t\t\t\tabortRunningNode(bt, ctx);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t});\n}\n"
5
+ "/**\n * Behavior Tree Plugin for ECSpresso\n *\n * Provides composable, priority-driven AI via behavior trees. Shared immutable\n * tree definitions drive per-entity runtime state. Uses hybrid traversal\n * (Approach C): re-evaluate from root each tick to preserve priority, resume\n * running leaves, and abort diverged running nodes via `onAbort`.\n *\n * Each entity gets a `behaviorTree` component referencing a shared definition\n * plus a typed blackboard for per-entity AI memory. One system processes all\n * behavior-tree entities each tick.\n *\n * Node types:\n * Composites — sequence, selector, parallel\n * Decorators — inverter, repeat, cooldown, guard\n * Leaves — action (tick → NodeStatus, optional onAbort), condition (predicate)\n */\n\nimport { definePlugin, type BasePluginOptions, type BaseWorld, type ComponentsConfig, type EventsConfig } from 'ecspresso';\n\n// ==================== NodeStatus ====================\n\n/**\n * Return value from behavior tree node ticks.\n *\n * - `Success` (0) — node completed successfully\n * - `Failure` (1) — node failed\n * - `Running` (2) — node still executing, will resume next tick\n */\nexport const NodeStatus = { Success: 0, Failure: 1, Running: 2 } as const;\nexport type NodeStatus = (typeof NodeStatus)[keyof typeof NodeStatus];\n\n// ==================== Callback Context ====================\n\n/** BaseWorld narrowed to behavior-tree components for typed access in helpers. */\ntype BehaviorTreeWorld = BaseWorld<BehaviorTreeComponentTypes>;\n\n/**\n * Context passed to all leaf node callbacks (action tick, condition check,\n * onAbort, guard predicates).\n *\n * @template BB - Blackboard type for per-entity AI memory\n * @template W - World interface type (default: BehaviorTreeWorld)\n */\nexport interface BehaviorTreeContext<\n\tBB extends object = Record<string, unknown>,\n\tW extends BaseWorld<BehaviorTreeComponentTypes> = BehaviorTreeWorld,\n> {\n\treadonly ecs: W;\n\treadonly entityId: number;\n\treadonly dt: number;\n\treadonly blackboard: BB;\n}\n\n// ==================== Node Types ====================\n\n/**\n * Action leaf — executes behavior each tick.\n * Returns `Running` for multi-frame actions. Optional `onAbort` fires\n * when a higher-priority branch preempts this running action.\n */\nexport interface ActionNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'action';\n\treadonly name: string;\n\treadonly tick: (ctx: BehaviorTreeContext<BB>) => NodeStatus;\n\treadonly onAbort?: (ctx: BehaviorTreeContext<BB>) => void;\n\tnodeIndex: number;\n}\n\n/**\n * Condition leaf — checks a predicate. Returns Success or Failure, never Running.\n */\nexport interface ConditionNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'condition';\n\treadonly name: string;\n\treadonly check: (ctx: BehaviorTreeContext<BB>) => boolean;\n\tnodeIndex: number;\n}\n\n/**\n * Sequence composite — runs children left-to-right.\n * Fails on first failure, succeeds when all succeed.\n * Resumes from stored child index when a running node exists.\n */\nexport interface SequenceNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'sequence';\n\treadonly children: readonly BehaviorTreeNode<BB>[];\n\tnodeIndex: number;\n}\n\n/**\n * Selector composite — runs children left-to-right.\n * Succeeds on first success, fails when all fail.\n * Always re-evaluates from child 0 to preserve priority ordering.\n */\nexport interface SelectorNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'selector';\n\treadonly children: readonly BehaviorTreeNode<BB>[];\n\tnodeIndex: number;\n}\n\n/**\n * Parallel composite — ticks all children each frame.\n * Configurable success/failure thresholds.\n *\n * Limitation (v1): only one running leaf is tracked for abort.\n * Other running children in a parallel stop being ticked if the\n * tree path diverges but do not receive an `onAbort` call.\n */\nexport interface ParallelNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'parallel';\n\treadonly children: readonly BehaviorTreeNode<BB>[];\n\treadonly successThreshold: number;\n\treadonly failureThreshold: number;\n\tnodeIndex: number;\n}\n\n/** Decorator — inverts child result (Success↔Failure), passes Running through. */\nexport interface InverterNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'inverter';\n\treadonly child: BehaviorTreeNode<BB>;\n\tnodeIndex: number;\n}\n\n/** Decorator — repeats child `count` times (or forever when count is -1). */\nexport interface RepeatNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'repeat';\n\treadonly child: BehaviorTreeNode<BB>;\n\treadonly count: number;\n\tnodeIndex: number;\n}\n\n/** Decorator — prevents child re-entry for `duration` seconds after completion. */\nexport interface CooldownNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'cooldown';\n\treadonly child: BehaviorTreeNode<BB>;\n\treadonly duration: number;\n\tnodeIndex: number;\n}\n\n/** Decorator — conditional gate. Ticks child only when condition passes. */\nexport interface GuardNode<BB extends object = Record<string, unknown>> {\n\treadonly type: 'guard';\n\treadonly child: BehaviorTreeNode<BB>;\n\treadonly condition: (ctx: BehaviorTreeContext<BB>) => boolean;\n\tnodeIndex: number;\n}\n\n/** Union of all behavior tree node types. */\nexport type BehaviorTreeNode<BB extends object = Record<string, unknown>> =\n\t| ActionNode<BB>\n\t| ConditionNode<BB>\n\t| SequenceNode<BB>\n\t| SelectorNode<BB>\n\t| ParallelNode<BB>\n\t| InverterNode<BB>\n\t| RepeatNode<BB>\n\t| CooldownNode<BB>\n\t| GuardNode<BB>;\n\n// ==================== Builder Functions ====================\n\n/**\n * Create an action leaf node.\n *\n * @param name - Human-readable name (used in abort events)\n * @param tick - Called each frame while this node is active; return NodeStatus\n * @param options - Optional `onAbort` callback fired when preempted by a higher-priority branch\n */\nexport function action<BB extends object>(\n\tname: string,\n\ttick: (ctx: BehaviorTreeContext<BB>) => NodeStatus,\n\toptions?: { onAbort?: (ctx: BehaviorTreeContext<BB>) => void },\n): ActionNode<BB> {\n\treturn { type: 'action', name, tick, onAbort: options?.onAbort, nodeIndex: -1 };\n}\n\n/**\n * Create a condition leaf node.\n *\n * @param name - Human-readable name\n * @param check - Predicate returning true (Success) or false (Failure). Never Running.\n */\nexport function condition<BB extends object>(\n\tname: string,\n\tcheck: (ctx: BehaviorTreeContext<BB>) => boolean,\n): ConditionNode<BB> {\n\treturn { type: 'condition', name, check, nodeIndex: -1 };\n}\n\n/**\n * Create a sequence composite. Runs children L→R, fails on first failure.\n */\nexport function sequence<BB extends object>(\n\tchildren: BehaviorTreeNode<BB>[],\n): SequenceNode<BB> {\n\treturn { type: 'sequence', children, nodeIndex: -1 };\n}\n\n/**\n * Create a selector composite. Runs children L→R, succeeds on first success.\n * Always starts from child 0 to re-evaluate priority.\n */\nexport function selector<BB extends object>(\n\tchildren: BehaviorTreeNode<BB>[],\n): SelectorNode<BB> {\n\treturn { type: 'selector', children, nodeIndex: -1 };\n}\n\n/**\n * Create a parallel composite. Ticks all children each frame.\n *\n * @param children - Child nodes to tick in parallel\n * @param options.successThreshold - Successes needed for parallel to succeed (default: all)\n * @param options.failureThreshold - Failures needed for parallel to fail (default: all)\n */\nexport function parallel<BB extends object>(\n\tchildren: BehaviorTreeNode<BB>[],\n\toptions?: { successThreshold?: number; failureThreshold?: number },\n): ParallelNode<BB> {\n\treturn {\n\t\ttype: 'parallel',\n\t\tchildren,\n\t\tsuccessThreshold: options?.successThreshold ?? children.length,\n\t\tfailureThreshold: options?.failureThreshold ?? children.length,\n\t\tnodeIndex: -1,\n\t};\n}\n\n/** Create an inverter decorator. Flips Success↔Failure, passes Running. */\nexport function inverter<BB extends object>(\n\tchild: BehaviorTreeNode<BB>,\n): InverterNode<BB> {\n\treturn { type: 'inverter', child, nodeIndex: -1 };\n}\n\n/**\n * Create a repeat decorator.\n *\n * @param child - Node to repeat\n * @param count - Number of repetitions, or -1 for infinite (default: -1)\n */\nexport function repeat<BB extends object>(\n\tchild: BehaviorTreeNode<BB>,\n\tcount = -1,\n): RepeatNode<BB> {\n\treturn { type: 'repeat', child, count, nodeIndex: -1 };\n}\n\n/**\n * Create a cooldown decorator. Prevents re-entry for `duration` seconds\n * after child completes (Success or Failure).\n */\nexport function cooldown<BB extends object>(\n\tchild: BehaviorTreeNode<BB>,\n\tduration: number,\n): CooldownNode<BB> {\n\treturn { type: 'cooldown', child, duration, nodeIndex: -1 };\n}\n\n/**\n * Create a guard decorator. Ticks child only when condition returns true.\n * Returns Failure when condition is false.\n */\nexport function guard<BB extends object>(\n\tcond: (ctx: BehaviorTreeContext<BB>) => boolean,\n\tchild: BehaviorTreeNode<BB>,\n): GuardNode<BB> {\n\treturn { type: 'guard', condition: cond, child, nodeIndex: -1 };\n}\n\n// ==================== Definition ====================\n\n/**\n * Immutable behavior tree definition. Shared across entities.\n *\n * @template BB - Blackboard type for per-entity AI memory\n */\nexport interface BehaviorTreeDefinition<BB extends object = Record<string, unknown>> {\n\treadonly id: string;\n\treadonly root: BehaviorTreeNode<BB>;\n\treadonly nodeCount: number;\n}\n\n/** Internal storage for definition data not exposed on the public interface. */\nconst defFlatNodes = new WeakMap<BehaviorTreeDefinition<object>, readonly BehaviorTreeNode<object>[]>();\nconst defDefaultBB = new WeakMap<BehaviorTreeDefinition<object>, object>();\n\n/**\n * Define a behavior tree with a typed blackboard.\n *\n * The `blackboard` value serves as both the type source and the default\n * initial state cloned for each entity via `createBehaviorTree`.\n *\n * @param id - Unique identifier for this tree definition\n * @param config - `{ blackboard, root }` — default blackboard + root node\n * @returns Frozen BehaviorTreeDefinition\n *\n * @example\n * ```typescript\n * const tree = defineBehaviorTree('patrol', {\n * blackboard: { targetId: null as number | null, timer: 0 },\n * root: selector([\n * guard(ctx => ctx.blackboard.targetId !== null, action('chase', ...)),\n * action('wander', ...),\n * ]),\n * });\n * ```\n */\nexport function defineBehaviorTree<BB extends object>(\n\tid: string,\n\tconfig: { blackboard: BB; root: BehaviorTreeNode<BB> },\n): BehaviorTreeDefinition<BB> {\n\tlet nextIndex = 0;\n\tconst flatNodes: BehaviorTreeNode<BB>[] = [];\n\n\tfunction indexTree(node: BehaviorTreeNode<BB>): void {\n\t\tnode.nodeIndex = nextIndex;\n\t\tflatNodes[nextIndex] = node;\n\t\tnextIndex++;\n\t\tif ('children' in node) {\n\t\t\tfor (const child of node.children) indexTree(child);\n\t\t}\n\t\tif ('child' in node) {\n\t\t\tindexTree(node.child);\n\t\t}\n\t}\n\tindexTree(config.root);\n\n\tconst def: BehaviorTreeDefinition<BB> = Object.freeze({ id, root: config.root, nodeCount: nextIndex });\n\tdefFlatNodes.set(def as BehaviorTreeDefinition<object>, flatNodes as readonly BehaviorTreeNode<object>[]);\n\tdefDefaultBB.set(def as BehaviorTreeDefinition<object>, config.blackboard);\n\treturn def;\n}\n\n// ==================== Per-Entity Component ====================\n\n/**\n * Runtime behavior tree state stored on each entity.\n *\n * The `blackboard` is typed as `object` at the component level.\n * Inside tree callbacks, the `BehaviorTreeContext<BB>` provides\n * typed access to the blackboard via the tree definition's generic.\n * Outside the tree, cast the blackboard to the specific BB type.\n */\nexport interface BehaviorTreeComponent {\n\treadonly definition: BehaviorTreeDefinition<Record<string, unknown>>;\n\tblackboard: object;\n\t/** Index of the currently running leaf, or -1 if none. */\n\trunningNodeIndex: number;\n\t/**\n\t * Dense per-node state array (sized to `definition.nodeCount`).\n\t * Semantics vary by node type:\n\t * - sequence/selector: child progress index\n\t * - repeat: completed iteration count\n\t * - cooldown: expiry timestamp (elapsedTime when cooldown ends)\n\t */\n\tnodeState: Float64Array;\n\t/** Accumulated time (seconds) for cooldown tracking. */\n\telapsedTime: number;\n}\n\n/**\n * Component types provided by the behavior tree plugin.\n */\nexport interface BehaviorTreeComponentTypes {\n\tbehaviorTree: BehaviorTreeComponent;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event published when a running action is preempted (aborted) by a\n * higher-priority branch taking over.\n */\nexport interface BehaviorTreeAbortEvent {\n\tentityId: number;\n\t/** nodeIndex of the aborted action */\n\tnodeIndex: number;\n\t/** Human-readable name of the aborted action */\n\tnodeName: string;\n\t/** Definition id of the behavior tree */\n\tdefinitionId: string;\n}\n\n/**\n * Event types provided by the behavior tree plugin.\n */\nexport interface BehaviorTreeEventTypes {\n\tbehaviorTreeAbort: BehaviorTreeAbortEvent;\n}\n\n// ==================== WorldConfig ====================\n\n/**\n * WorldConfig representing the behavior tree plugin's provided types.\n */\nexport type BehaviorTreeWorldConfig =\n\tComponentsConfig<BehaviorTreeComponentTypes>\n\t& EventsConfig<BehaviorTreeEventTypes>;\n\n// ==================== Helper Functions ====================\n\n/**\n * Create a `behaviorTree` component from a definition.\n *\n * @param definition - Shared tree definition\n * @param blackboard - Optional partial overrides for the default blackboard\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createBehaviorTree(villagerTree, { hunger: 80 }),\n * ...createLocalTransform(100, 200),\n * });\n * ```\n */\nexport function createBehaviorTree<BB extends object>(\n\tdefinition: BehaviorTreeDefinition<BB>,\n\tblackboard?: Partial<BB>,\n): Pick<BehaviorTreeComponentTypes, 'behaviorTree'> {\n\tconst defaultBB = defDefaultBB.get(definition as BehaviorTreeDefinition<object>) as BB;\n\tconst bb = { ...defaultBB, ...blackboard };\n\treturn {\n\t\tbehaviorTree: {\n\t\t\tdefinition: definition as BehaviorTreeDefinition<Record<string, unknown>>,\n\t\t\tblackboard: bb,\n\t\t\trunningNodeIndex: -1,\n\t\t\tnodeState: new Float64Array(definition.nodeCount),\n\t\t\telapsedTime: 0,\n\t\t},\n\t};\n}\n\n/**\n * Check whether an entity's behavior tree has a running action.\n */\nexport function isBehaviorTreeRunning(\n\tecs: { getComponent(entityId: number, name: 'behaviorTree'): BehaviorTreeComponent | undefined },\n\tentityId: number,\n): boolean {\n\tconst bt = ecs.getComponent(entityId, 'behaviorTree');\n\treturn bt !== undefined && bt.runningNodeIndex !== -1;\n}\n\n/**\n * Reset an entity's behavior tree: abort any running action, clear all\n * composite progress, and optionally reset the blackboard.\n */\nexport function resetBehaviorTree(\n\tecs: BehaviorTreeWorld,\n\tentityId: number,\n\tblackboard?: Partial<Record<string, unknown>>,\n): void {\n\tconst bt = ecs.getComponent(entityId, 'behaviorTree');\n\tif (!bt) return;\n\n\tif (bt.runningNodeIndex !== -1) {\n\t\tconst flatNodes = defFlatNodes.get(bt.definition as BehaviorTreeDefinition<object>);\n\t\tconst node = flatNodes?.[bt.runningNodeIndex];\n\t\tif (node && node.type === 'action' && node.onAbort) {\n\t\t\tnode.onAbort({ ecs, entityId, dt: 0, blackboard: bt.blackboard as Record<string, unknown> });\n\t\t}\n\t\tbt.runningNodeIndex = -1;\n\t}\n\tbt.nodeState.fill(0);\n\tbt.elapsedTime = 0;\n\n\tif (blackboard) {\n\t\tObject.assign(bt.blackboard, blackboard);\n\t}\n}\n\n// ==================== Internal: Traversal ====================\n\n/** Internal shorthand — all runtime traversal uses the erased base types. */\ntype AnyNode = BehaviorTreeNode<Record<string, unknown>>;\n\n/** Mutable version of context for pre-allocation in the system loop. */\ninterface MutableCtx {\n\tecs: BehaviorTreeWorld;\n\tentityId: number;\n\tdt: number;\n\tblackboard: Record<string, unknown>;\n}\n\nfunction abortRunningNode(bt: BehaviorTreeComponent, ctx: MutableCtx): void {\n\tconst flatNodes = defFlatNodes.get(bt.definition as BehaviorTreeDefinition<object>);\n\tconst node = flatNodes?.[bt.runningNodeIndex] as AnyNode | undefined;\n\tif (node && node.type === 'action') {\n\t\tnode.onAbort?.(ctx);\n\t\tctx.ecs.eventBus.publish('behaviorTreeAbort', {\n\t\t\tentityId: ctx.entityId,\n\t\t\tnodeIndex: bt.runningNodeIndex,\n\t\t\tnodeName: node.name,\n\t\t\tdefinitionId: bt.definition.id,\n\t\t} satisfies BehaviorTreeAbortEvent);\n\t}\n\tbt.nodeState.fill(0);\n\tbt.runningNodeIndex = -1;\n}\n\nfunction tickNode(node: AnyNode, bt: BehaviorTreeComponent, ctx: MutableCtx): NodeStatus {\n\tswitch (node.type) {\n\t\tcase 'condition':\n\t\t\treturn node.check(ctx) ? NodeStatus.Success : NodeStatus.Failure;\n\n\t\tcase 'action': {\n\t\t\tconst result = node.tick(ctx);\n\t\t\tif (result === NodeStatus.Running) {\n\t\t\t\tif (bt.runningNodeIndex !== -1 && bt.runningNodeIndex !== node.nodeIndex) {\n\t\t\t\t\tabortRunningNode(bt, ctx);\n\t\t\t\t}\n\t\t\t\tbt.runningNodeIndex = node.nodeIndex;\n\t\t\t} else if (bt.runningNodeIndex === node.nodeIndex) {\n\t\t\t\tbt.runningNodeIndex = -1;\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\tcase 'sequence': {\n\t\t\tconst startChild = (bt.runningNodeIndex !== -1)\n\t\t\t\t? (bt.nodeState[node.nodeIndex] ?? 0)\n\t\t\t\t: 0;\n\t\t\tfor (let i = startChild; i < node.children.length; i++) {\n\t\t\t\tconst status = tickNode(node.children[i]!, bt, ctx);\n\t\t\t\tif (status === NodeStatus.Failure) {\n\t\t\t\t\tbt.nodeState[node.nodeIndex] = 0;\n\t\t\t\t\treturn NodeStatus.Failure;\n\t\t\t\t}\n\t\t\t\tif (status === NodeStatus.Running) {\n\t\t\t\t\tbt.nodeState[node.nodeIndex] = i;\n\t\t\t\t\treturn NodeStatus.Running;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbt.nodeState[node.nodeIndex] = 0;\n\t\t\treturn NodeStatus.Success;\n\t\t}\n\n\t\tcase 'selector': {\n\t\t\tfor (let i = 0; i < node.children.length; i++) {\n\t\t\t\tconst status = tickNode(node.children[i]!, bt, ctx);\n\t\t\t\tif (status === NodeStatus.Success) return NodeStatus.Success;\n\t\t\t\tif (status === NodeStatus.Running) return NodeStatus.Running;\n\t\t\t}\n\t\t\treturn NodeStatus.Failure;\n\t\t}\n\n\t\tcase 'parallel': {\n\t\t\tlet successCount = 0;\n\t\t\tlet failureCount = 0;\n\t\t\tlet anyRunning = false;\n\t\t\tfor (let i = 0; i < node.children.length; i++) {\n\t\t\t\tconst status = tickNode(node.children[i]!, bt, ctx);\n\t\t\t\tif (status === NodeStatus.Success) successCount++;\n\t\t\t\telse if (status === NodeStatus.Failure) failureCount++;\n\t\t\t\telse anyRunning = true;\n\t\t\t}\n\t\t\tif (successCount >= node.successThreshold) return NodeStatus.Success;\n\t\t\tif (failureCount >= node.failureThreshold) return NodeStatus.Failure;\n\t\t\tif (anyRunning) return NodeStatus.Running;\n\t\t\treturn NodeStatus.Failure;\n\t\t}\n\n\t\tcase 'inverter': {\n\t\t\tconst status = tickNode(node.child, bt, ctx);\n\t\t\tif (status === NodeStatus.Success) return NodeStatus.Failure;\n\t\t\tif (status === NodeStatus.Failure) return NodeStatus.Success;\n\t\t\treturn NodeStatus.Running;\n\t\t}\n\n\t\tcase 'repeat': {\n\t\t\tconst iteration = bt.nodeState[node.nodeIndex] ?? 0;\n\t\t\tconst status = tickNode(node.child, bt, ctx);\n\t\t\tif (status === NodeStatus.Failure) {\n\t\t\t\tbt.nodeState[node.nodeIndex] = 0;\n\t\t\t\treturn NodeStatus.Failure;\n\t\t\t}\n\t\t\tif (status === NodeStatus.Running) return NodeStatus.Running;\n\t\t\tconst next = iteration + 1;\n\t\t\tif (node.count !== -1 && next >= node.count) {\n\t\t\t\tbt.nodeState[node.nodeIndex] = 0;\n\t\t\t\treturn NodeStatus.Success;\n\t\t\t}\n\t\t\tbt.nodeState[node.nodeIndex] = next;\n\t\t\treturn NodeStatus.Running;\n\t\t}\n\n\t\tcase 'cooldown': {\n\t\t\tconst expiresAt = bt.nodeState[node.nodeIndex] ?? 0;\n\t\t\tif (expiresAt > 0 && bt.elapsedTime < expiresAt) return NodeStatus.Failure;\n\t\t\tconst status = tickNode(node.child, bt, ctx);\n\t\t\tif (status !== NodeStatus.Running) {\n\t\t\t\tbt.nodeState[node.nodeIndex] = bt.elapsedTime + node.duration;\n\t\t\t}\n\t\t\treturn status;\n\t\t}\n\n\t\tcase 'guard': {\n\t\t\tif (!node.condition(ctx)) return NodeStatus.Failure;\n\t\t\treturn tickNode(node.child, bt, ctx);\n\t\t}\n\t}\n}\n\n// ==================== Typed Helpers ====================\n\n/**\n * Typed helpers for the behavior tree plugin.\n * Creates helpers that validate callback parameters against the world type W.\n * Call after `.build()` using `typeof ecs`.\n */\nexport interface BehaviorTreeHelpers<W extends BaseWorld<BehaviorTreeComponentTypes>> {\n\tdefineBehaviorTree: <BB extends object>(\n\t\tid: string,\n\t\tconfig: { blackboard: BB; root: BehaviorTreeNode<BB> },\n\t) => BehaviorTreeDefinition<BB>;\n\taction: <BB extends object>(\n\t\tname: string,\n\t\ttick: (ctx: BehaviorTreeContext<BB, W>) => NodeStatus,\n\t\toptions?: { onAbort?: (ctx: BehaviorTreeContext<BB, W>) => void },\n\t) => ActionNode<BB>;\n\tcondition: <BB extends object>(\n\t\tname: string,\n\t\tcheck: (ctx: BehaviorTreeContext<BB, W>) => boolean,\n\t) => ConditionNode<BB>;\n\tguard: <BB extends object>(\n\t\tcond: (ctx: BehaviorTreeContext<BB, W>) => boolean,\n\t\tchild: BehaviorTreeNode<BB>,\n\t) => GuardNode<BB>;\n}\n\n/**\n * Create typed behavior tree helpers bound to a specific world type.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createBehaviorTreePlugin())\n * .build();\n *\n * const { defineBehaviorTree, action, condition, guard } = ecs.getHelpers(createBehaviorTreeHelpers);\n * ```\n */\nexport function createBehaviorTreeHelpers<\n\tW extends BaseWorld<BehaviorTreeComponentTypes> = BehaviorTreeWorld,\n>(_world?: W): BehaviorTreeHelpers<W> {\n\treturn {\n\t\tdefineBehaviorTree: defineBehaviorTree as BehaviorTreeHelpers<W>['defineBehaviorTree'],\n\t\taction: action as BehaviorTreeHelpers<W>['action'],\n\t\tcondition: condition as BehaviorTreeHelpers<W>['condition'],\n\t\tguard: guard as BehaviorTreeHelpers<W>['guard'],\n\t};\n}\n\n// ==================== Plugin Options ====================\n\n/**\n * Configuration options for the behavior tree plugin.\n */\nexport interface BehaviorTreePluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a behavior tree plugin for ECSpresso.\n *\n * Provides composable, priority-driven AI via behavior trees with:\n * - Hybrid traversal: re-evaluate from root each tick, resume running leaves\n * - Automatic abort with `onAbort` callback when preempted\n * - Typed blackboard for per-entity AI memory\n * - `behaviorTreeAbort` events on preemption\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createBehaviorTreePlugin())\n * .build();\n *\n * const { defineBehaviorTree, action, condition, guard } = ecs.getHelpers(createBehaviorTreeHelpers);\n *\n * const tree = defineBehaviorTree('villager', {\n * blackboard: { hunger: 100, targetId: null as number | null },\n * root: selector([\n * guard(ctx => ctx.blackboard.hunger < 30, action('eat', ...)),\n * action('wander', ...),\n * ]),\n * });\n *\n * ecs.spawn({\n * ...createBehaviorTree(tree),\n * ...createLocalTransform(100, 200),\n * });\n * ```\n */\nexport function createBehaviorTreePlugin<G extends string = 'ai'>(\n\toptions?: BehaviorTreePluginOptions<G>,\n) {\n\tconst {\n\t\tsystemGroup = 'ai',\n\t\tpriority = 0,\n\t\tphase = 'update',\n\t} = options ?? {};\n\n\treturn definePlugin('behaviorTree')\n\t\t.withComponentTypes<BehaviorTreeComponentTypes>()\n\t\t.withEventTypes<BehaviorTreeEventTypes>()\n\t\t.withLabels<'behavior-tree-update'>()\n\t\t.withGroups<G>()\n\t\t.install((world) => {\n\t\t\t// Dispose: abort running node on entity removal\n\t\t\tworld.registerDispose('behaviorTree', ({ value, entityId }) => {\n\t\t\t\tif (value.runningNodeIndex !== -1) {\n\t\t\t\t\tconst flatNodes = defFlatNodes.get(value.definition as BehaviorTreeDefinition<object>);\n\t\t\t\t\tconst node = flatNodes?.[value.runningNodeIndex] as AnyNode | undefined;\n\t\t\t\t\tif (node && node.type === 'action' && node.onAbort) {\n\t\t\t\t\t\tnode.onAbort({\n\t\t\t\t\t\t\tecs: world as unknown as BehaviorTreeWorld,\n\t\t\t\t\t\t\tentityId,\n\t\t\t\t\t\t\tdt: 0,\n\t\t\t\t\t\t\tblackboard: value.blackboard as Record<string, unknown>,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tworld\n\t\t\t\t.addSystem('behavior-tree-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('trees', {\n\t\t\t\t\twith: ['behaviorTree'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs: ecsWorld }) => {\n\t\t\t\t\tconst ctx: MutableCtx = {\n\t\t\t\t\t\tecs: ecsWorld as unknown as BehaviorTreeWorld,\n\t\t\t\t\t\tentityId: 0,\n\t\t\t\t\t\tdt: 0,\n\t\t\t\t\t\tblackboard: {},\n\t\t\t\t\t};\n\n\t\t\t\t\tfor (const entity of queries.trees) {\n\t\t\t\t\t\tconst bt = entity.components.behaviorTree;\n\t\t\t\t\t\tctx.entityId = entity.id;\n\t\t\t\t\t\tctx.dt = dt;\n\t\t\t\t\t\tctx.blackboard = bt.blackboard as Record<string, unknown>;\n\t\t\t\t\t\tbt.elapsedTime += dt;\n\n\t\t\t\t\t\tconst result = tickNode(bt.definition.root as AnyNode, bt, ctx);\n\n\t\t\t\t\t\tif (result !== NodeStatus.Running && bt.runningNodeIndex !== -1) {\n\t\t\t\t\t\t\tabortRunningNode(bt, ctx);\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": "2PAkBA,uBAAS,kBAWF,IAAM,EAAa,CAAE,QAAS,EAAG,QAAS,EAAG,QAAS,CAAE,EA4IxD,SAAS,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AAI,EAAM,UAA4C,IAC5D,EAAM,kBAC/B,GAAI,GAAQ,EAAK,OAAS,UAAY,EAAK,QAC1C,EAAK,QAAQ,CACZ,IAAK,EACL,WACA,GAAI,EACJ,WAAY,EAAM,UACnB,CAAC,GAGH,EAED,EACE,UAAU,sBAAsB,EAChC,YAAY,CAAQ,EACpB,QAAQ,CAAK,EACb,QAAQ,CAAW,EACnB,SAAS,QAAS,CAClB,KAAM,CAAC,cAAc,CACtB,CAAC,EACA,WAAW,EAAG,UAAS,KAAI,IAAK,KAAe,CAC/C,IAAM,EAAkB,CACvB,IAAK,EACL,SAAU,EACV,GAAI,EACJ,WAAY,CAAC,CACd,EAEA,QAAW,KAAU,EAAQ,MAAO,CACnC,IAAM,EAAK,EAAO,WAAW,aAQ7B,GAPA,EAAI,SAAW,EAAO,GACtB,EAAI,GAAK,EACT,EAAI,WAAa,EAAG,WACpB,EAAG,aAAe,EAEH,EAAS,EAAG,WAAW,KAAiB,EAAI,CAAG,IAE/C,EAAW,SAAW,EAAG,mBAAqB,GAC5D,EAAiB,EAAI,CAAG,GAG1B,EACF",
8
8
  "debugId": "71DF25393349415964756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -9,7 +9,7 @@
9
9
  * Uses the spatial-index plugin for efficient range queries.
10
10
  */
11
11
  import { type BasePluginOptions } from 'ecspresso';
12
- import type { WorldConfigFrom } from 'ecspresso';
12
+ import type { ComponentsConfig, EventsConfig, ResourcesConfig } from 'ecspresso';
13
13
  import type { TransformWorldConfig } from '../spatial/transform';
14
14
  import type { SpatialIndexResourceTypes } from '../spatial/spatial-index';
15
15
  import type { CollisionComponentTypes } from '../physics/collision';
@@ -72,7 +72,7 @@ export interface DetectionEventTypes {
72
72
  /**
73
73
  * WorldConfig representing the detection plugin's provided types.
74
74
  */
75
- export type DetectionWorldConfig = WorldConfigFrom<DetectionComponentTypes, DetectionEventTypes>;
75
+ export type DetectionWorldConfig = ComponentsConfig<DetectionComponentTypes> & EventsConfig<DetectionEventTypes>;
76
76
  export interface DetectionPluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {
77
77
  }
78
78
  /**
@@ -132,4 +132,4 @@ export declare function hasDetectedTargets(ecs: {
132
132
  * const nearest = detected?.entities[0];
133
133
  * ```
134
134
  */
135
- export declare function createDetectionPlugin<G extends string = 'ai'>(options?: DetectionPluginOptions<G>): import("ecspresso").Plugin<import("ecspresso").WithEvents<import("ecspresso").WithComponents<import("ecspresso").EmptyConfig, DetectionComponentTypes>, DetectionEventTypes>, TransformWorldConfig & WorldConfigFrom<Pick<CollisionComponentTypes<string>, "collisionLayer">> & WorldConfigFrom<{}, {}, SpatialIndexResourceTypes>, "detection-scan", G, never, never>;
135
+ export declare function createDetectionPlugin<G extends string = 'ai'>(options?: DetectionPluginOptions<G>): import("ecspresso").Plugin<import("ecspresso").WithEvents<import("ecspresso").WithComponents<import("ecspresso").EmptyConfig, DetectionComponentTypes>, DetectionEventTypes>, TransformWorldConfig & ComponentsConfig<Pick<CollisionComponentTypes<string>, "collisionLayer">> & ResourcesConfig<SpatialIndexResourceTypes>, "detection-scan", G, never, never>;
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/plugins/ai/detection.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Detection Plugin for ECSpresso\n *\n * Provides automatic proximity detection for entities. Entities with a\n * `detector` component get their `detectedEntities` populated each frame\n * with nearby entities that match the configured collision layer filter,\n * sorted by distance ascending (nearest first).\n *\n * Uses the spatial-index plugin for efficient range queries.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\nimport type { WorldConfigFrom } from 'ecspresso';\nimport type { TransformWorldConfig } from '../spatial/transform';\nimport type { SpatialIndexResourceTypes } from '../spatial/spatial-index';\nimport type { CollisionComponentTypes } from '../physics/collision';\n\n// ==================== Component Types ====================\n\n/**\n * Configures proximity detection for an entity.\n */\nexport interface Detector {\n\t/** Detection radius in world units */\n\trange: number;\n\t/** Only detect entities on these collision layers */\n\tlayerFilter: readonly string[];\n\t/** Maximum number of results to track (default: 32) */\n\tmaxResults: number;\n}\n\n/**\n * A detected entity with its squared distance from the detector.\n */\nexport interface DetectedEntry {\n\tentityId: number;\n\tdistanceSq: number;\n}\n\n/**\n * Auto-populated list of detected entities, sorted by distance ascending.\n */\nexport interface DetectedEntities {\n\tentities: readonly DetectedEntry[];\n}\n\n/**\n * Component types provided by the detection plugin.\n */\nexport interface DetectionComponentTypes {\n\tdetector: Detector;\n\tdetectedEntities: DetectedEntities;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event fired when a new entity enters detection range.\n */\nexport interface DetectionGainedEvent {\n\t/** The entity doing the detecting */\n\tentityId: number;\n\t/** The entity that was detected */\n\tdetectedId: number;\n}\n\n/**\n * Event fired when an entity leaves detection range.\n */\nexport interface DetectionLostEvent {\n\t/** The entity doing the detecting */\n\tentityId: number;\n\t/** The entity that was lost */\n\tlostId: number;\n}\n\n/**\n * Event types provided by the detection plugin.\n */\nexport interface DetectionEventTypes {\n\tdetectionGained: DetectionGainedEvent;\n\tdetectionLost: DetectionLostEvent;\n}\n\n// ==================== WorldConfig ====================\n\n/**\n * WorldConfig representing the detection plugin's provided types.\n */\nexport type DetectionWorldConfig = WorldConfigFrom<DetectionComponentTypes, DetectionEventTypes>;\n\n// ==================== Plugin Options ====================\n\nexport interface DetectionPluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {}\n\n// ==================== Helper Functions ====================\n\n/**\n * Create a detector component.\n *\n * @param range Detection radius in world units\n * @param layerFilter Only detect entities on these collision layers\n * @param maxResults Maximum results to track (default: 32)\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createDetector(300, ['enemy']),\n * ...createLocalTransform(400, 400),\n * });\n * ```\n */\nexport function createDetector(\n\trange: number,\n\tlayerFilter: readonly string[],\n\tmaxResults = 32,\n): Pick<DetectionComponentTypes, 'detector'> {\n\treturn { detector: { range, layerFilter, maxResults } };\n}\n\n/**\n * Check whether an entity has any detected targets.\n *\n * @param ecs ECS world instance\n * @param entityId Entity with a detector component\n * @returns true if detectedEntities contains at least one entry\n *\n * @example\n * ```typescript\n * if (hasDetectedTargets(ecs, guardId)) {\n * // transition to chase\n * }\n * ```\n */\nexport function hasDetectedTargets(\n\tecs: { getComponent(entityId: number, name: 'detectedEntities'): DetectedEntities | undefined },\n\tentityId: number,\n): boolean {\n\tconst detected = ecs.getComponent(entityId, 'detectedEntities');\n\treturn (detected?.entities.length ?? 0) > 0;\n}\n\n// ==================== Plugin Factory ====================\n\nfunction compareByDistance(a: DetectedEntry, b: DetectedEntry): number {\n\treturn a.distanceSq - b.distanceSq;\n}\n\n/**\n * Create a detection plugin for ECSpresso.\n *\n * Populates `detectedEntities` each frame with nearby entities matching\n * the detector's layer filter, sorted by distance (nearest first).\n * Publishes `detectionGained`/`detectionLost` events on transitions.\n *\n * Requires the spatial-index and transform plugins to be installed.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createCollisionPlugin({ layers }))\n * .withPlugin(createSpatialIndexPlugin())\n * .withPlugin(createDetectionPlugin())\n * .build();\n *\n * // Read nearest detected entity:\n * const detected = ecs.getComponent(turretId, 'detectedEntities');\n * const nearest = detected?.entities[0];\n * ```\n */\nexport function createDetectionPlugin<G extends string = 'ai'>(\n\toptions?: DetectionPluginOptions<G>,\n) {\n\tconst {\n\t\tsystemGroup = 'ai',\n\t\tpriority = 500,\n\t\tphase = 'update',\n\t} = options ?? {};\n\n\t// Per-detector tracking of previous frame's detected set for event diffing\n\tconst previousSets = new Map<number, Set<number>>();\n\tconst currentSet = new Set<number>();\n\tconst candidateBuf: number[] = [];\n\t// Cache: layerFilter array → Set for O(1) lookups\n\tconst layerFilterCache = new WeakMap<readonly string[], Set<string>>();\n\n\treturn definePlugin('detection')\n\t\t.withComponentTypes<DetectionComponentTypes>()\n\t\t.withEventTypes<DetectionEventTypes>()\n\t\t.withLabels<'detection-scan'>()\n\t\t.withGroups<G>()\n\t\t.requires<\n\t\t\tTransformWorldConfig &\n\t\t\tWorldConfigFrom<Pick<CollisionComponentTypes<string>, 'collisionLayer'>> &\n\t\t\tWorldConfigFrom<{}, {}, SpatialIndexResourceTypes>\n\t\t>()\n\t\t.install((world) => {\n\t\t\tworld.registerDispose('detector', ({ entityId }) => {\n\t\t\t\tpreviousSets.delete(entityId);\n\t\t\t});\n\n\t\t\tworld\n\t\t\t\t.addSystem('detection-scan')\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('detectors', {\n\t\t\t\t\twith: ['detector', 'worldTransform'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tconst spatialIndex = ecs.getResource('spatialIndex');\n\n\t\t\t\t\tfor (const entity of queries.detectors) {\n\t\t\t\t\t\tconst { detector, worldTransform } = entity.components;\n\n\t\t\t\t\t\tcandidateBuf.length = 0;\n\t\t\t\t\t\tspatialIndex.queryRadiusInto(worldTransform.x, worldTransform.y, detector.range, candidateBuf);\n\n\t\t\t\t\t\t// Build sorted results, filtering by layer and excluding self\n\t\t\t\t\t\tconst entries: DetectedEntry[] = [];\n\n\t\t\t\t\t\tlet filterSet = layerFilterCache.get(detector.layerFilter);\n\t\t\t\t\t\tif (!filterSet) {\n\t\t\t\t\t\t\tfilterSet = new Set(detector.layerFilter);\n\t\t\t\t\t\t\tlayerFilterCache.set(detector.layerFilter, filterSet);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (const candidateId of candidateBuf) {\n\t\t\t\t\t\t\tif (candidateId === entity.id) continue;\n\t\t\t\t\t\t\tif (!ecs.getEntity(candidateId)) continue;\n\n\t\t\t\t\t\t\tconst layer = ecs.getComponent(candidateId, 'collisionLayer');\n\t\t\t\t\t\t\tif (!layer) continue;\n\t\t\t\t\t\t\tif (!filterSet.has(layer.layer)) continue;\n\n\t\t\t\t\t\t\tconst candidateTransform = ecs.getComponent(candidateId, 'worldTransform');\n\t\t\t\t\t\t\tif (!candidateTransform) continue;\n\n\t\t\t\t\t\t\tconst dx = candidateTransform.x - worldTransform.x;\n\t\t\t\t\t\t\tconst dy = candidateTransform.y - worldTransform.y;\n\t\t\t\t\t\t\tentries.push({ entityId: candidateId, distanceSq: dx * dx + dy * dy });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tentries.sort(compareByDistance);\n\t\t\t\t\t\tconst capped = entries.length > detector.maxResults\n\t\t\t\t\t\t\t? entries.slice(0, detector.maxResults)\n\t\t\t\t\t\t\t: entries;\n\n\t\t\t\t\t\t// Update or add the detectedEntities component\n\t\t\t\t\t\tconst existing = ecs.getComponent(entity.id, 'detectedEntities');\n\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\t(existing as { entities: readonly DetectedEntry[] }).entities = capped;\n\t\t\t\t\t\t\tecs.markChanged(entity.id, 'detectedEntities');\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tecs.addComponent(entity.id, 'detectedEntities', { entities: capped });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Diff against previous frame for events\n\t\t\t\t\t\tconst prev = previousSets.get(entity.id);\n\t\t\t\t\t\tcurrentSet.clear();\n\t\t\t\t\t\tfor (const entry of capped) {\n\t\t\t\t\t\t\tcurrentSet.add(entry.entityId);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (prev) {\n\t\t\t\t\t\t\t// Detect gained\n\t\t\t\t\t\t\tfor (const id of currentSet) {\n\t\t\t\t\t\t\t\tif (!prev.has(id)) {\n\t\t\t\t\t\t\t\t\tecs.eventBus.publish('detectionGained', {\n\t\t\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\t\t\tdetectedId: id,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Detect lost\n\t\t\t\t\t\t\tfor (const id of prev) {\n\t\t\t\t\t\t\t\tif (!currentSet.has(id)) {\n\t\t\t\t\t\t\t\t\tecs.eventBus.publish('detectionLost', {\n\t\t\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\t\t\tlostId: id,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Update previous set in place\n\t\t\t\t\t\t\tprev.clear();\n\t\t\t\t\t\t\tfor (const id of currentSet) {\n\t\t\t\t\t\t\t\tprev.add(id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// First frame — all are gained\n\t\t\t\t\t\t\tconst newSet = new Set<number>();\n\t\t\t\t\t\t\tfor (const entry of capped) {\n\t\t\t\t\t\t\t\tnewSet.add(entry.entityId);\n\t\t\t\t\t\t\t\tecs.eventBus.publish('detectionGained', {\n\t\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\t\tdetectedId: entry.entityId,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpreviousSets.set(entity.id, newSet);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t});\n}\n"
5
+ "/**\n * Detection Plugin for ECSpresso\n *\n * Provides automatic proximity detection for entities. Entities with a\n * `detector` component get their `detectedEntities` populated each frame\n * with nearby entities that match the configured collision layer filter,\n * sorted by distance ascending (nearest first).\n *\n * Uses the spatial-index plugin for efficient range queries.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\nimport type { ComponentsConfig, EventsConfig, ResourcesConfig } from 'ecspresso';\nimport type { TransformWorldConfig } from '../spatial/transform';\nimport type { SpatialIndexResourceTypes } from '../spatial/spatial-index';\nimport type { CollisionComponentTypes } from '../physics/collision';\n\n// ==================== Component Types ====================\n\n/**\n * Configures proximity detection for an entity.\n */\nexport interface Detector {\n\t/** Detection radius in world units */\n\trange: number;\n\t/** Only detect entities on these collision layers */\n\tlayerFilter: readonly string[];\n\t/** Maximum number of results to track (default: 32) */\n\tmaxResults: number;\n}\n\n/**\n * A detected entity with its squared distance from the detector.\n */\nexport interface DetectedEntry {\n\tentityId: number;\n\tdistanceSq: number;\n}\n\n/**\n * Auto-populated list of detected entities, sorted by distance ascending.\n */\nexport interface DetectedEntities {\n\tentities: readonly DetectedEntry[];\n}\n\n/**\n * Component types provided by the detection plugin.\n */\nexport interface DetectionComponentTypes {\n\tdetector: Detector;\n\tdetectedEntities: DetectedEntities;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event fired when a new entity enters detection range.\n */\nexport interface DetectionGainedEvent {\n\t/** The entity doing the detecting */\n\tentityId: number;\n\t/** The entity that was detected */\n\tdetectedId: number;\n}\n\n/**\n * Event fired when an entity leaves detection range.\n */\nexport interface DetectionLostEvent {\n\t/** The entity doing the detecting */\n\tentityId: number;\n\t/** The entity that was lost */\n\tlostId: number;\n}\n\n/**\n * Event types provided by the detection plugin.\n */\nexport interface DetectionEventTypes {\n\tdetectionGained: DetectionGainedEvent;\n\tdetectionLost: DetectionLostEvent;\n}\n\n// ==================== WorldConfig ====================\n\n/**\n * WorldConfig representing the detection plugin's provided types.\n */\nexport type DetectionWorldConfig =\n\tComponentsConfig<DetectionComponentTypes>\n\t& EventsConfig<DetectionEventTypes>;\n\n// ==================== Plugin Options ====================\n\nexport interface DetectionPluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {}\n\n// ==================== Helper Functions ====================\n\n/**\n * Create a detector component.\n *\n * @param range Detection radius in world units\n * @param layerFilter Only detect entities on these collision layers\n * @param maxResults Maximum results to track (default: 32)\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createDetector(300, ['enemy']),\n * ...createLocalTransform(400, 400),\n * });\n * ```\n */\nexport function createDetector(\n\trange: number,\n\tlayerFilter: readonly string[],\n\tmaxResults = 32,\n): Pick<DetectionComponentTypes, 'detector'> {\n\treturn { detector: { range, layerFilter, maxResults } };\n}\n\n/**\n * Check whether an entity has any detected targets.\n *\n * @param ecs ECS world instance\n * @param entityId Entity with a detector component\n * @returns true if detectedEntities contains at least one entry\n *\n * @example\n * ```typescript\n * if (hasDetectedTargets(ecs, guardId)) {\n * // transition to chase\n * }\n * ```\n */\nexport function hasDetectedTargets(\n\tecs: { getComponent(entityId: number, name: 'detectedEntities'): DetectedEntities | undefined },\n\tentityId: number,\n): boolean {\n\tconst detected = ecs.getComponent(entityId, 'detectedEntities');\n\treturn (detected?.entities.length ?? 0) > 0;\n}\n\n// ==================== Plugin Factory ====================\n\nfunction compareByDistance(a: DetectedEntry, b: DetectedEntry): number {\n\treturn a.distanceSq - b.distanceSq;\n}\n\n/**\n * Create a detection plugin for ECSpresso.\n *\n * Populates `detectedEntities` each frame with nearby entities matching\n * the detector's layer filter, sorted by distance (nearest first).\n * Publishes `detectionGained`/`detectionLost` events on transitions.\n *\n * Requires the spatial-index and transform plugins to be installed.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createCollisionPlugin({ layers }))\n * .withPlugin(createSpatialIndexPlugin())\n * .withPlugin(createDetectionPlugin())\n * .build();\n *\n * // Read nearest detected entity:\n * const detected = ecs.getComponent(turretId, 'detectedEntities');\n * const nearest = detected?.entities[0];\n * ```\n */\nexport function createDetectionPlugin<G extends string = 'ai'>(\n\toptions?: DetectionPluginOptions<G>,\n) {\n\tconst {\n\t\tsystemGroup = 'ai',\n\t\tpriority = 500,\n\t\tphase = 'update',\n\t} = options ?? {};\n\n\t// Per-detector tracking of previous frame's detected set for event diffing\n\tconst previousSets = new Map<number, Set<number>>();\n\tconst currentSet = new Set<number>();\n\tconst candidateBuf: number[] = [];\n\t// Cache: layerFilter array → Set for O(1) lookups\n\tconst layerFilterCache = new WeakMap<readonly string[], Set<string>>();\n\n\treturn definePlugin('detection')\n\t\t.withComponentTypes<DetectionComponentTypes>()\n\t\t.withEventTypes<DetectionEventTypes>()\n\t\t.withLabels<'detection-scan'>()\n\t\t.withGroups<G>()\n\t\t.requires<\n\t\t\tTransformWorldConfig &\n\t\t\tComponentsConfig<Pick<CollisionComponentTypes<string>, 'collisionLayer'>> &\n\t\t\tResourcesConfig<SpatialIndexResourceTypes>\n\t\t>()\n\t\t.install((world) => {\n\t\t\tworld.registerDispose('detector', ({ entityId }) => {\n\t\t\t\tpreviousSets.delete(entityId);\n\t\t\t});\n\n\t\t\tworld\n\t\t\t\t.addSystem('detection-scan')\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('detectors', {\n\t\t\t\t\twith: ['detector', 'worldTransform'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tconst spatialIndex = ecs.getResource('spatialIndex');\n\n\t\t\t\t\tfor (const entity of queries.detectors) {\n\t\t\t\t\t\tconst { detector, worldTransform } = entity.components;\n\n\t\t\t\t\t\tcandidateBuf.length = 0;\n\t\t\t\t\t\tspatialIndex.queryRadiusInto(worldTransform.x, worldTransform.y, detector.range, candidateBuf);\n\n\t\t\t\t\t\t// Build sorted results, filtering by layer and excluding self\n\t\t\t\t\t\tconst entries: DetectedEntry[] = [];\n\n\t\t\t\t\t\tlet filterSet = layerFilterCache.get(detector.layerFilter);\n\t\t\t\t\t\tif (!filterSet) {\n\t\t\t\t\t\t\tfilterSet = new Set(detector.layerFilter);\n\t\t\t\t\t\t\tlayerFilterCache.set(detector.layerFilter, filterSet);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (const candidateId of candidateBuf) {\n\t\t\t\t\t\t\tif (candidateId === entity.id) continue;\n\t\t\t\t\t\t\tif (!ecs.getEntity(candidateId)) continue;\n\n\t\t\t\t\t\t\tconst layer = ecs.getComponent(candidateId, 'collisionLayer');\n\t\t\t\t\t\t\tif (!layer) continue;\n\t\t\t\t\t\t\tif (!filterSet.has(layer.layer)) continue;\n\n\t\t\t\t\t\t\tconst candidateTransform = ecs.getComponent(candidateId, 'worldTransform');\n\t\t\t\t\t\t\tif (!candidateTransform) continue;\n\n\t\t\t\t\t\t\tconst dx = candidateTransform.x - worldTransform.x;\n\t\t\t\t\t\t\tconst dy = candidateTransform.y - worldTransform.y;\n\t\t\t\t\t\t\tentries.push({ entityId: candidateId, distanceSq: dx * dx + dy * dy });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tentries.sort(compareByDistance);\n\t\t\t\t\t\tconst capped = entries.length > detector.maxResults\n\t\t\t\t\t\t\t? entries.slice(0, detector.maxResults)\n\t\t\t\t\t\t\t: entries;\n\n\t\t\t\t\t\t// Update or add the detectedEntities component\n\t\t\t\t\t\tconst existing = ecs.getComponent(entity.id, 'detectedEntities');\n\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\t(existing as { entities: readonly DetectedEntry[] }).entities = capped;\n\t\t\t\t\t\t\tecs.markChanged(entity.id, 'detectedEntities');\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tecs.addComponent(entity.id, 'detectedEntities', { entities: capped });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Diff against previous frame for events\n\t\t\t\t\t\tconst prev = previousSets.get(entity.id);\n\t\t\t\t\t\tcurrentSet.clear();\n\t\t\t\t\t\tfor (const entry of capped) {\n\t\t\t\t\t\t\tcurrentSet.add(entry.entityId);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (prev) {\n\t\t\t\t\t\t\t// Detect gained\n\t\t\t\t\t\t\tfor (const id of currentSet) {\n\t\t\t\t\t\t\t\tif (!prev.has(id)) {\n\t\t\t\t\t\t\t\t\tecs.eventBus.publish('detectionGained', {\n\t\t\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\t\t\tdetectedId: id,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Detect lost\n\t\t\t\t\t\t\tfor (const id of prev) {\n\t\t\t\t\t\t\t\tif (!currentSet.has(id)) {\n\t\t\t\t\t\t\t\t\tecs.eventBus.publish('detectionLost', {\n\t\t\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\t\t\tlostId: id,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Update previous set in place\n\t\t\t\t\t\t\tprev.clear();\n\t\t\t\t\t\t\tfor (const id of currentSet) {\n\t\t\t\t\t\t\t\tprev.add(id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// First frame — all are gained\n\t\t\t\t\t\t\tconst newSet = new Set<number>();\n\t\t\t\t\t\t\tfor (const entry of capped) {\n\t\t\t\t\t\t\t\tnewSet.add(entry.entityId);\n\t\t\t\t\t\t\t\tecs.eventBus.publish('detectionGained', {\n\t\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\t\tdetectedId: entry.entityId,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpreviousSets.set(entity.id, newSet);\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": "2PAWA,uBAAS,kBAsGF,SAAS,CAAc,CAC7B,EACA,EACA,EAAa,GAC+B,CAC5C,MAAO,CAAE,SAAU,CAAE,QAAO,cAAa,YAAW,CAAE,EAiBhD,SAAS,CAAkB,CACjC,EACA,EACU,CAEV,OADiB,EAAI,aAAa,EAAU,kBAAkB,GAC5C,SAAS,QAAU,GAAK,EAK3C,SAAS,CAAiB,CAAC,EAAkB,EAA0B,CACtE,OAAO,EAAE,WAAa,EAAE,WA0BlB,SAAS,CAA8C,CAC7D,EACC,CACD,IACC,cAAc,KACd,WAAW,IACX,QAAQ,UACL,G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EAAe,EACjD,EAAQ,KAAK,CAAE,SAAU,EAAa,WAAY,EAAK,EAAK,EAAK,CAAG,CAAC,EAGtE,EAAQ,KAAK,CAAiB,EAC9B,IAAM,EAAS,EAAQ,OAAS,EAAS,WACtC,EAAQ,MAAM,EAAG,EAAS,UAAU,EACpC,EAGG,EAAW,EAAI,aAAa,EAAO,GAAI,kBAAkB,EAC/D,GAAI,EACF,EAAoD,SAAW,EAChE,EAAI,YAAY,EAAO,GAAI,kBAAkB,EAE7C,OAAI,aAAa,EAAO,GAAI,mBAAoB,CAAE,SAAU,CAAO,CAAC,EAIrE,IAAM,EAAO,EAAa,IAAI,EAAO,EAAE,EACvC,EAAW,MAAM,EACjB,QAAW,KAAS,EACnB,EAAW,IAAI,EAAM,QAAQ,EAG9B,GAAI,EAAM,CAET,QAAW,KAAM,EAChB,GAAI,CAAC,EAAK,IAAI,CAAE,EACf,EAAI,SAAS,QAAQ,kBAAmB,CACvC,SAAU,EAAO,GACjB,WAAY,CACb,CAAC,EAIH,QAAW,KAAM,EAChB,GAAI,CAAC,EAAW,IAAI,CAAE,EACrB,EAAI,SAAS,QAAQ,gBAAiB,CACrC,SAAU,EAAO,GACjB,OAAQ,CACT,CAAC,EAIH,EAAK,MAAM,EACX,QAAW,KAAM,EAChB,EAAK,IAAI,CAAE,EAEN,KAEN,IAAM,EAAS,IAAI,IACnB,QAAW,KAAS,EACnB,EAAO,IAAI,EAAM,QAAQ,EACzB,EAAI,SAAS,QAAQ,kBAAmB,CACvC,SAAU,EAAO,GACjB,WAAY,EAAM,QACnB,CAAC,EAEF,EAAa,IAAI,EAAO,GAAI,CAAM,IAGpC,EACF",
8
8
  "debugId": "9C433B1DED88EF8264756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -13,7 +13,7 @@
13
13
  * in spatial index queries.
14
14
  */
15
15
  import { type BasePluginOptions } from 'ecspresso';
16
- import type { WorldConfigFrom } from 'ecspresso';
16
+ import type { ComponentsConfig, ResourcesConfig } from 'ecspresso';
17
17
  import type { TransformWorldConfig } from '../spatial/transform';
18
18
  import type { Physics2DOwnComponentTypes } from '../physics/physics2D';
19
19
  import type { SpatialIndexResourceTypes } from '../spatial/spatial-index';
@@ -50,7 +50,7 @@ export interface FlockingComponentTypes {
50
50
  /**
51
51
  * WorldConfig representing the flocking plugin's provided types.
52
52
  */
53
- export type FlockingWorldConfig = WorldConfigFrom<FlockingComponentTypes>;
53
+ export type FlockingWorldConfig = ComponentsConfig<FlockingComponentTypes>;
54
54
  export interface FlockingPluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {
55
55
  /** Priority for the heading/speed-clamp system (default: 200) */
56
56
  headingPriority?: number;
@@ -94,4 +94,4 @@ export declare function createFlockingAgent(options?: Partial<FlockingAgent>): P
94
94
  * .build();
95
95
  * ```
96
96
  */
97
- export declare function createFlockingPlugin<G extends string = 'ai'>(options?: FlockingPluginOptions<G>): import("ecspresso").Plugin<import("ecspresso").WithComponents<import("ecspresso").EmptyConfig, FlockingComponentTypes>, TransformWorldConfig & WorldConfigFrom<Pick<Physics2DOwnComponentTypes, "force" | "velocity">> & WorldConfigFrom<{}, {}, SpatialIndexResourceTypes>, "flocking-forces" | "flocking-heading", G, never, never>;
97
+ export declare function createFlockingPlugin<G extends string = 'ai'>(options?: FlockingPluginOptions<G>): import("ecspresso").Plugin<import("ecspresso").WithComponents<import("ecspresso").EmptyConfig, FlockingComponentTypes>, TransformWorldConfig & ComponentsConfig<Pick<Physics2DOwnComponentTypes, "force" | "velocity">> & ResourcesConfig<SpatialIndexResourceTypes>, "flocking-forces" | "flocking-heading", G, never, never>;
@@ -5,7 +5,7 @@
5
5
  "/**\n * Physics 2D Plugin for ECSpresso\n *\n * Provides ECS-native arcade physics: gravity, forces, drag, semi-implicit Euler\n * integration, and impulse-based collision response with friction.\n *\n * Reuses collider types from the collision plugin for shape definitions.\n * Has its own collision detection in fixedUpdate for physics response;\n * the existing collision plugin can still run in postUpdate for game logic events.\n */\n\nimport { definePlugin } from 'ecspresso';\nimport type { SystemPhase } from 'ecspresso';\nimport type { TransformComponentTypes, TransformWorldConfig } from '../spatial/transform';\nimport type { CollisionComponentTypes, LayerFactories } from './collision';\nimport type { Vector2D } from 'ecspresso';\nimport { fillBaseColliderInfo, detectCollisions, createBroadphaseScratch, AABB_SHAPE, type Contact, type BaseColliderInfo } from '../../utils/narrowphase';\nimport type { SpatialIndex } from '../../utils/spatial-hash';\n\n// ==================== Component Types ====================\n\n/**\n * Rigid body types for physics simulation.\n * - 'dynamic': Fully simulated (gravity, forces, collisions)\n * - 'kinematic': Moves via velocity only (ignores gravity/forces, immovable in collisions)\n * - 'static': Immovable (ignores gravity, forces, and velocity)\n */\nexport type BodyType = 'dynamic' | 'kinematic' | 'static';\n\n/**\n * Rigid body component controlling physics behavior.\n */\nexport interface RigidBody {\n\ttype: BodyType;\n\t/** Mass in arbitrary units. Affects force→acceleration. Infinity = immovable. */\n\tmass: number;\n\t/** Linear velocity damping coefficient (units/sec, 0 = none) */\n\tdrag: number;\n\t/** Bounciness 0–1 (0 = no bounce, 1 = perfectly elastic) */\n\trestitution: number;\n\t/** Surface friction coefficient 0–1 */\n\tfriction: number;\n\t/** Per-entity gravity multiplier (0 = no gravity) */\n\tgravityScale: number;\n}\n\n/**\n * Component types directly provided by the physics plugin.\n */\nexport interface Physics2DOwnComponentTypes {\n\trigidBody: RigidBody;\n\tvelocity: Vector2D;\n\tforce: Vector2D;\n}\n\n/**\n * Full component types available when using the physics plugin\n * (own components + transform + collision dependencies).\n * Convenience alias for consumer code.\n */\nexport interface Physics2DComponentTypes<L extends string = never> extends TransformComponentTypes, CollisionComponentTypes<L>, Physics2DOwnComponentTypes {}\n\n// ==================== Resource Types ====================\n\n/**\n * Physics configuration resource.\n */\nexport interface Physics2DConfig {\n\tgravity: Vector2D;\n}\n\nexport interface Physics2DResourceTypes {\n\tphysicsConfig: Physics2DConfig;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event emitted for each physics collision pair.\n *\n * Normal components are flattened (`normalX`/`normalY`) rather than nested\n * in a `Vector2D` to avoid a per-event allocation in the physics hot path.\n */\nexport interface Physics2DCollisionEvent {\n\tentityA: number;\n\tentityB: number;\n\t/** Unit normal X, pointing from A toward B */\n\tnormalX: number;\n\t/** Unit normal Y, pointing from A toward B */\n\tnormalY: number;\n\t/** Penetration depth (positive) */\n\tdepth: number;\n}\n\nexport interface Physics2DEventTypes {\n\tphysicsCollision: Physics2DCollisionEvent;\n}\n\n// ==================== Plugin Options ====================\n\nexport interface Physics2DPluginOptions<G extends string = 'physics2D', CG extends string = never> {\n\t/** World gravity vector (default: {x: 0, y: 0}) */\n\tgravity?: Vector2D;\n\t/** System group name (default: 'physics2D') */\n\tsystemGroup?: G;\n\t/** Additional group for the collision system only (default: none).\n\t * When set, the collision system belongs to both `systemGroup` and this group,\n\t * allowing independent enable/disable of collision detection. */\n\tcollisionSystemGroup?: CG;\n\t/** Priority for integration system (default: 1000) */\n\tintegrationPriority?: number;\n\t/** Priority for collision system (default: 900) */\n\tcollisionPriority?: number;\n\t/** Execution phase (default: 'fixedUpdate') */\n\tphase?: SystemPhase;\n}\n\n// ==================== Helper Functions ====================\n\nexport interface RigidBodyOptions {\n\tmass?: number;\n\tdrag?: number;\n\trestitution?: number;\n\tfriction?: number;\n\tgravityScale?: number;\n}\n\n/**\n * Create a rigid body + force component pair.\n * Static bodies automatically get mass=Infinity.\n */\nexport function createRigidBody(\n\ttype: BodyType,\n\toptions?: RigidBodyOptions,\n): { rigidBody: RigidBody; force: Vector2D } {\n\treturn {\n\t\trigidBody: {\n\t\t\ttype,\n\t\t\tmass: type === 'static' ? Infinity : (options?.mass ?? 1),\n\t\t\tdrag: options?.drag ?? 0,\n\t\t\trestitution: options?.restitution ?? 0,\n\t\t\tfriction: options?.friction ?? 0,\n\t\t\tgravityScale: options?.gravityScale ?? 1,\n\t\t},\n\t\tforce: { x: 0, y: 0 },\n\t};\n}\n\n/**\n * Create a force component with initial values.\n */\nexport function createForce(x: number, y: number): { force: Vector2D } {\n\treturn { force: { x, y } };\n}\n\n/**\n * Accumulate a force onto an entity's force component.\n */\nexport function applyForce(\n\tecs: { getComponent(id: number, name: 'force'): Vector2D | undefined },\n\tentityId: number,\n\tfx: number,\n\tfy: number,\n): void {\n\tconst force = ecs.getComponent(entityId, 'force');\n\tif (!force) return;\n\tforce.x += fx;\n\tforce.y += fy;\n}\n\n/**\n * Apply an instantaneous impulse: velocity += impulse / mass.\n */\nexport function applyImpulse(\n\tecs: {\n\t\tgetComponent(id: number, name: 'velocity'): Vector2D | undefined;\n\t\tgetComponent(id: number, name: 'rigidBody'): RigidBody | undefined;\n\t},\n\tentityId: number,\n\tix: number,\n\tiy: number,\n): void {\n\tconst velocity = ecs.getComponent(entityId, 'velocity');\n\tconst rigidBody = ecs.getComponent(entityId, 'rigidBody');\n\tif (!velocity || !rigidBody) return;\n\tif (rigidBody.mass === Infinity || rigidBody.mass === 0) return;\n\tvelocity.x += ix / rigidBody.mass;\n\tvelocity.y += iy / rigidBody.mass;\n}\n\n/**\n * Directly set an entity's velocity.\n */\nexport function setVelocity(\n\tecs: { getComponent(id: number, name: 'velocity'): Vector2D | undefined },\n\tentityId: number,\n\tvx: number,\n\tvy: number,\n): void {\n\tconst velocity = ecs.getComponent(entityId, 'velocity');\n\tif (!velocity) return;\n\tvelocity.x = vx;\n\tvelocity.y = vy;\n}\n\n// ==================== Internal: Collider Info ====================\n\ninterface Physics2DColliderInfo<L extends string = string> extends BaseColliderInfo<L> {\n\trigidBody: RigidBody;\n\tvelocity: Vector2D;\n}\n\n// ==================== Collision Response ====================\n\n/**\n * Module-level reusable physics collision event. Subscribers must consume\n * synchronously — same contract as the shared narrowphase Contact.\n */\nconst _physicsCollisionEvent: Physics2DCollisionEvent = {\n\tentityA: 0, entityB: 0, normalX: 0, normalY: 0, depth: 0,\n};\n\ninterface PhysicsEcsLike {\n\tgetComponent(id: number, name: 'localTransform'): { x: number; y: number } | undefined;\n\teventBus: { publish(event: 'physicsCollision', data: Physics2DCollisionEvent): void };\n\tmarkChanged(entityId: number, componentName: 'localTransform' | 'velocity'): void;\n}\n\n/**\n * Resolve a physics collision pair: position correction, impulse response, event.\n */\nfunction resolvePhysicsContact(\n\ta: Physics2DColliderInfo,\n\tb: Physics2DColliderInfo,\n\tcontact: Contact,\n\tecs: PhysicsEcsLike,\n): void {\n\tconst invMassA = (a.rigidBody.type === 'dynamic' && a.rigidBody.mass > 0 && a.rigidBody.mass !== Infinity)\n\t\t? 1 / a.rigidBody.mass\n\t\t: 0;\n\tconst invMassB = (b.rigidBody.type === 'dynamic' && b.rigidBody.mass > 0 && b.rigidBody.mass !== Infinity)\n\t\t? 1 / b.rigidBody.mass\n\t\t: 0;\n\tconst totalInvMass = invMassA + invMassB;\n\n\t// Position correction\n\tif (totalInvMass > 0) {\n\t\tconst correctionScale = contact.depth / totalInvMass;\n\n\t\tif (invMassA > 0) {\n\t\t\tconst ltA = ecs.getComponent(a.entityId, 'localTransform');\n\t\t\tif (!ltA) return;\n\t\t\tconst corrA = correctionScale * invMassA;\n\t\t\tltA.x -= corrA * contact.normalX;\n\t\t\tltA.y -= corrA * contact.normalY;\n\t\t\t// Sync cached position so subsequent pairs in this frame use corrected values\n\t\t\ta.x = ltA.x;\n\t\t\ta.y = ltA.y;\n\t\t\tecs.markChanged(a.entityId, 'localTransform');\n\t\t}\n\n\t\tif (invMassB > 0) {\n\t\t\tconst ltB = ecs.getComponent(b.entityId, 'localTransform');\n\t\t\tif (!ltB) return;\n\t\t\tconst corrB = correctionScale * invMassB;\n\t\t\tltB.x += corrB * contact.normalX;\n\t\t\tltB.y += corrB * contact.normalY;\n\t\t\tb.x = ltB.x;\n\t\t\tb.y = ltB.y;\n\t\t\tecs.markChanged(b.entityId, 'localTransform');\n\t\t}\n\n\t\t// Velocity response (impulse-based)\n\t\tconst relVelX = b.velocity.x - a.velocity.x;\n\t\tconst relVelY = b.velocity.y - a.velocity.y;\n\t\tconst velAlongNormal = relVelX * contact.normalX + relVelY * contact.normalY;\n\n\t\tif (velAlongNormal < 0) {\n\t\t\tconst restitution = Math.min(a.rigidBody.restitution, b.rigidBody.restitution);\n\t\t\tconst normalImpulse = -(1 + restitution) * velAlongNormal / totalInvMass;\n\n\t\t\ta.velocity.x -= normalImpulse * invMassA * contact.normalX;\n\t\t\ta.velocity.y -= normalImpulse * invMassA * contact.normalY;\n\t\t\tb.velocity.x += normalImpulse * invMassB * contact.normalX;\n\t\t\tb.velocity.y += normalImpulse * invMassB * contact.normalY;\n\n\t\t\t// Friction (tangential impulse)\n\t\t\tconst tangentX = relVelX - velAlongNormal * contact.normalX;\n\t\t\tconst tangentY = relVelY - velAlongNormal * contact.normalY;\n\t\t\tconst tangentSpeed = Math.sqrt(tangentX * tangentX + tangentY * tangentY);\n\n\t\t\tif (tangentSpeed > 1e-6) {\n\t\t\t\tconst tangentNX = tangentX / tangentSpeed;\n\t\t\t\tconst tangentNY = tangentY / tangentSpeed;\n\t\t\t\tconst friction = Math.sqrt(a.rigidBody.friction * b.rigidBody.friction);\n\t\t\t\tconst maxFrictionImpulse = friction * Math.abs(normalImpulse);\n\t\t\t\tconst tangentImpulse = Math.min(tangentSpeed / totalInvMass, maxFrictionImpulse);\n\n\t\t\t\ta.velocity.x += tangentImpulse * invMassA * tangentNX;\n\t\t\t\ta.velocity.y += tangentImpulse * invMassA * tangentNY;\n\t\t\t\tb.velocity.x -= tangentImpulse * invMassB * tangentNX;\n\t\t\t\tb.velocity.y -= tangentImpulse * invMassB * tangentNY;\n\t\t\t}\n\t\t}\n\n\t\tecs.markChanged(a.entityId, 'velocity');\n\t\tecs.markChanged(b.entityId, 'velocity');\n\t}\n\n\t_physicsCollisionEvent.entityA = a.entityId;\n\t_physicsCollisionEvent.entityB = b.entityId;\n\t_physicsCollisionEvent.normalX = contact.normalX;\n\t_physicsCollisionEvent.normalY = contact.normalY;\n\t_physicsCollisionEvent.depth = contact.depth;\n\tecs.eventBus.publish('physicsCollision', _physicsCollisionEvent);\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a 2D physics plugin for ECSpresso.\n *\n * Provides:\n * - Semi-implicit Euler integration (gravity, forces, drag → velocity → position)\n * - Impulse-based collision response with restitution and friction\n * - physicsCollision events with contact normal and depth\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createPhysics2DPlugin({ gravity: { x: 0, y: 980 } }))\n * .withFixedTimestep(1/60)\n * .build();\n *\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createRigidBody('dynamic', { mass: 1, restitution: 0.5 }),\n * velocity: { x: 0, y: 0 },\n * ...createAABBCollider(32, 32),\n * ...createCollisionLayer('player', ['ground']),\n * });\n * ```\n */\n\ntype Physics2DProvides<L extends string = never> = Physics2DOwnComponentTypes & CollisionComponentTypes<L>;\n\nexport function createPhysics2DPlugin<L extends string = never, G extends string = 'physics2D', CG extends string = never>(\n\toptions?: Physics2DPluginOptions<G, CG> & { layers?: LayerFactories<Record<L, readonly string[]>> },\n) {\n\tconst {\n\t\tgravity = { x: 0, y: 0 },\n\t\tsystemGroup = 'physics2D',\n\t\tcollisionSystemGroup,\n\t\tintegrationPriority = 1000,\n\t\tcollisionPriority = 900,\n\t\tphase = 'fixedUpdate',\n\t} = options ?? {};\n\n\treturn definePlugin('physics2D')\n\t\t.withComponentTypes<Physics2DProvides<L>>()\n\t\t.withEventTypes<Physics2DEventTypes>()\n\t\t.withResourceTypes<Physics2DResourceTypes>()\n\t\t.withLabels<'physics2D-integration' | 'physics2D-collision'>()\n\t\t.withGroups<G | CG>()\n\t\t.requires<TransformWorldConfig>()\n\t\t.install((world) => {\n\t\t\t// rigidBody requires velocity and force — auto-add with zero defaults\n\t\t\tworld.registerRequired('rigidBody', 'velocity', () => ({ x: 0, y: 0 }));\n\t\t\tworld.registerRequired('rigidBody', 'force', () => ({ x: 0, y: 0 }));\n\n\t\t\tworld.addResource('physicsConfig', { gravity: { x: gravity.x, y: gravity.y } });\n\n\t\t\t// ==================== Integration System ====================\n\n\t\t\tworld\n\t\t\t\t.addSystem('physics2D-integration')\n\t\t\t\t.setPriority(integrationPriority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('bodies', {\n\t\t\t\t\twith: ['localTransform', 'velocity', 'rigidBody', 'force'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tconst { gravity: g } = ecs.getResource('physicsConfig');\n\t\t\t\t\tconst gx = g.x;\n\t\t\t\t\tconst gy = g.y;\n\n\t\t\t\t\t// TODO(perf): no early-out for \"sleeping\" dynamic bodies — a packed\n\t\t\t\t\t// pile of resting entities still runs gravity/drag/force-clear/\n\t\t\t\t\t// markChanged every step. A sleep flag on RigidBody that latches\n\t\t\t\t\t// after N frames of near-zero velocity (and clears on impulse or\n\t\t\t\t\t// applied force) would let most of a stabilized scene skip the\n\t\t\t\t\t// full per-entity body of this loop. Keep in sync with physics3D.\n\t\t\t\t\tfor (const entity of queries.bodies) {\n\t\t\t\t\t\tconst { localTransform, velocity, rigidBody, force } = entity.components;\n\n\t\t\t\t\t\t// Static bodies: skip entirely\n\t\t\t\t\t\tif (rigidBody.type === 'static') continue;\n\n\t\t\t\t\t\t// Dynamic bodies: apply gravity, forces, drag\n\t\t\t\t\t\tif (rigidBody.type === 'dynamic') {\n\t\t\t\t\t\t\t// 1. Gravity\n\t\t\t\t\t\t\tconst gsdt = rigidBody.gravityScale * dt;\n\t\t\t\t\t\t\tvelocity.x += gx * gsdt;\n\t\t\t\t\t\t\tvelocity.y += gy * gsdt;\n\n\t\t\t\t\t\t\t// 2. Forces (F = ma → a = F/m)\n\t\t\t\t\t\t\tconst mass = rigidBody.mass;\n\t\t\t\t\t\t\tif (mass > 0 && mass !== Infinity) {\n\t\t\t\t\t\t\t\tconst invMassDt = dt / mass;\n\t\t\t\t\t\t\t\tvelocity.x += force.x * invMassDt;\n\t\t\t\t\t\t\t\tvelocity.y += force.y * invMassDt;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// 3. Drag\n\t\t\t\t\t\t\tif (rigidBody.drag > 0) {\n\t\t\t\t\t\t\t\tconst damping = Math.max(0, 1 - rigidBody.drag * dt);\n\t\t\t\t\t\t\t\tvelocity.x *= damping;\n\t\t\t\t\t\t\t\tvelocity.y *= damping;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Both dynamic and kinematic: integrate position\n\t\t\t\t\t\tlocalTransform.x += velocity.x * dt;\n\t\t\t\t\t\tlocalTransform.y += velocity.y * dt;\n\n\t\t\t\t\t\t// Clear accumulated forces\n\t\t\t\t\t\tforce.x = 0;\n\t\t\t\t\t\tforce.y = 0;\n\n\t\t\t\t\t\tecs.markChanged(entity.id, 'localTransform');\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// ==================== Collision System ====================\n\n\t\t\tconst collisionSystem = world\n\t\t\t\t.addSystem('physics2D-collision')\n\t\t\t\t.setPriority(collisionPriority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup);\n\n\t\t\tif (collisionSystemGroup) {\n\t\t\t\tcollisionSystem.inGroup(collisionSystemGroup);\n\t\t\t}\n\n\t\t\t// Grow-only pool of Physics2DColliderInfo slots reused across frames.\n\t\t\t// Steady-state: zero allocations per frame once the pool is warm.\n\t\t\tconst colliderPool: Physics2DColliderInfo<L>[] = [];\n\t\t\tconst broadphaseScratch = createBroadphaseScratch<Physics2DColliderInfo<L>>();\n\t\t\t// Cached spatial index reference (resolved once on first frame).\n\t\t\tlet cachedSI: SpatialIndex | undefined;\n\t\t\tlet siResolved = false;\n\n\t\t\tconst ensureSlot = (idx: number, entityId: number, layer: L, collidesWith: readonly L[], rigidBody: RigidBody, velocity: Vector2D): Physics2DColliderInfo<L> => {\n\t\t\t\tlet slot = colliderPool[idx];\n\t\t\t\tif (!slot) {\n\t\t\t\t\tslot = {\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\tx: 0,\n\t\t\t\t\t\ty: 0,\n\t\t\t\t\t\tlayer,\n\t\t\t\t\t\tcollidesWith,\n\t\t\t\t\t\tlayerBit: 0,\n\t\t\t\t\t\tcollidesWithMask: 0,\n\t\t\t\t\t\tshape: AABB_SHAPE,\n\t\t\t\t\t\thalfWidth: 0,\n\t\t\t\t\t\thalfHeight: 0,\n\t\t\t\t\t\tradius: 0,\n\t\t\t\t\t\trigidBody,\n\t\t\t\t\t\tvelocity,\n\t\t\t\t\t};\n\t\t\t\t\tcolliderPool[idx] = slot;\n\t\t\t\t} else {\n\t\t\t\t\tslot.rigidBody = rigidBody;\n\t\t\t\t\tslot.velocity = velocity;\n\t\t\t\t}\n\t\t\t\treturn slot;\n\t\t\t};\n\n\t\t\tcollisionSystem\n\t\t\t\t.addQuery('aabbOnly', {\n\t\t\t\t\twith: ['localTransform', 'rigidBody', 'velocity', 'collisionLayer', 'aabbCollider'],\n\t\t\t\t\twithout: ['circleCollider'],\n\t\t\t\t})\n\t\t\t\t.addQuery('circleOnly', {\n\t\t\t\t\twith: ['localTransform', 'rigidBody', 'velocity', 'collisionLayer', 'circleCollider'],\n\t\t\t\t\twithout: ['aabbCollider'],\n\t\t\t\t})\n\t\t\t\t.addQuery('both', {\n\t\t\t\t\twith: ['localTransform', 'rigidBody', 'velocity', 'collisionLayer', 'aabbCollider', 'circleCollider'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tlet count = 0;\n\n\t\t\t\t\tfor (const entity of queries.aabbOnly) {\n\t\t\t\t\t\tconst { localTransform, rigidBody, velocity, collisionLayer, aabbCollider } = entity.components;\n\t\t\t\t\t\tconst slot = ensureSlot(count, entity.id, collisionLayer.layer, collisionLayer.collidesWith, rigidBody, velocity);\n\t\t\t\t\t\tif (!fillBaseColliderInfo(\n\t\t\t\t\t\t\tslot,\n\t\t\t\t\t\t\tentity.id, localTransform.x, localTransform.y,\n\t\t\t\t\t\t\tcollisionLayer.layer, collisionLayer.collidesWith,\n\t\t\t\t\t\t\taabbCollider, undefined,\n\t\t\t\t\t\t)) continue;\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const entity of queries.circleOnly) {\n\t\t\t\t\t\tconst { localTransform, rigidBody, velocity, collisionLayer, circleCollider } = entity.components;\n\t\t\t\t\t\tconst slot = ensureSlot(count, entity.id, collisionLayer.layer, collisionLayer.collidesWith, rigidBody, velocity);\n\t\t\t\t\t\tif (!fillBaseColliderInfo(\n\t\t\t\t\t\t\tslot,\n\t\t\t\t\t\t\tentity.id, localTransform.x, localTransform.y,\n\t\t\t\t\t\t\tcollisionLayer.layer, collisionLayer.collidesWith,\n\t\t\t\t\t\t\tundefined, circleCollider,\n\t\t\t\t\t\t)) continue;\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\n\t\t\t\t\t// fillBaseColliderInfo picks aabb when both present — preserves prior precedence.\n\t\t\t\t\tfor (const entity of queries.both) {\n\t\t\t\t\t\tconst { localTransform, rigidBody, velocity, collisionLayer, aabbCollider, circleCollider } = entity.components;\n\t\t\t\t\t\tconst slot = ensureSlot(count, entity.id, collisionLayer.layer, collisionLayer.collidesWith, rigidBody, velocity);\n\t\t\t\t\t\tif (!fillBaseColliderInfo(\n\t\t\t\t\t\t\tslot,\n\t\t\t\t\t\t\tentity.id, localTransform.x, localTransform.y,\n\t\t\t\t\t\t\tcollisionLayer.layer, collisionLayer.collidesWith,\n\t\t\t\t\t\t\taabbCollider, circleCollider,\n\t\t\t\t\t\t)) continue;\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!siResolved) {\n\t\t\t\t\t\tcachedSI = ecs.tryGetResource<SpatialIndex>('spatialIndex');\n\t\t\t\t\t\tsiResolved = true;\n\t\t\t\t\t}\n\t\t\t\t\tdetectCollisions(colliderPool, count, broadphaseScratch, cachedSI, resolvePhysicsContact, ecs);\n\t\t\t\t});\n\t\t});\n}\n",
6
6
  "/**\n * Lazy monotonic registry mapping layer name → unique bit. Lets pair\n * filtering use a single `(a.collidesWithMask & b.layerBit)` check\n * instead of `Array.includes` on every collision pair.\n *\n * One registry per dimension (2D and 3D) — user-defined layer namespaces\n * are independent, so bits should not be shared across systems.\n *\n * Maximum 32 layers per registry (one per bit in a 32-bit signed int).\n * Crossing the limit throws on the next `getLayerBit` call.\n */\nexport interface LayerBitRegistry {\n\tgetLayerBit(layer: string): number;\n\t/** OR of `getLayerBit` for every entry. Cached by array reference. */\n\tgetCollidesWithMask(collidesWith: readonly string[]): number;\n}\n\nexport function createLayerBitRegistry(label: string): LayerBitRegistry {\n\tconst layerBits = new Map<string, number>();\n\tconst maskCache = new WeakMap<readonly string[], number>();\n\tlet nextBit = 1;\n\n\tfunction getLayerBit(layer: string): number {\n\t\tconst existing = layerBits.get(layer);\n\t\tif (existing !== undefined) return existing;\n\t\tif (nextBit === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`[ecspresso] ${label} layer bitmask overflow: more than 32 distinct layers registered`,\n\t\t\t);\n\t\t}\n\t\tconst bit = nextBit;\n\t\tlayerBits.set(layer, bit);\n\t\t// `<<= 1` rolls 1<<31 to 0, which is detected on the next call.\n\t\tnextBit <<= 1;\n\t\treturn bit;\n\t}\n\n\tfunction getCollidesWithMask(collidesWith: readonly string[]): number {\n\t\tconst cached = maskCache.get(collidesWith);\n\t\tif (cached !== undefined) return cached;\n\t\tlet mask = 0;\n\t\tfor (let i = 0; i < collidesWith.length; i++) {\n\t\t\tmask |= getLayerBit(collidesWith[i]!);\n\t\t}\n\t\tmaskCache.set(collidesWith, mask);\n\t\treturn mask;\n\t}\n\n\treturn { getLayerBit, getCollidesWithMask };\n}\n",
7
7
  "/**\n * Shared Narrowphase Module\n *\n * Provides contact-computing narrowphase tests and a generic collision\n * iteration pipeline used by both the collision plugin (event-only) and\n * the physics2D plugin (impulse response).\n */\n\nimport type { SpatialIndex } from './spatial-hash';\nimport { createLayerBitRegistry } from './layer-bit-registry';\n\n// ==================== Contact ====================\n\n/**\n * Contact result from a narrowphase test. Normal points from A toward B.\n *\n * Narrowphase functions use this as an out-parameter: the caller owns the\n * struct, the function writes fields in place and returns `true` on hit.\n * The `onContact` callback in `detectCollisions` receives a shared module-\n * level instance — **subscribers must consume it synchronously and must not\n * retain the reference across frames**.\n */\nexport interface Contact {\n\tnormalX: number;\n\tnormalY: number;\n\t/** Penetration depth (positive = overlapping) */\n\tdepth: number;\n}\n\n/**\n * Module-level reusable Contact passed down from `detectCollisions` into\n * narrowphase tests and forwarded to the `onContact` callback. Reused across\n * every pair in every frame — zero allocation in the narrowphase hot path.\n */\nconst _sharedContact: Contact = { normalX: 0, normalY: 0, depth: 0 };\n\n// ==================== BaseColliderInfo ====================\n\n/** Collider shape discriminator for the flattened BaseColliderInfo layout. */\nexport const AABB_SHAPE = 0;\nexport const CIRCLE_SHAPE = 1;\nexport type ColliderShape = typeof AABB_SHAPE | typeof CIRCLE_SHAPE;\n\n/**\n * Minimum collider data shared by collision and physics bundles.\n *\n * Flat layout (no nested `aabb` / `circle` sub-objects): the `shape`\n * discriminator tells you whether to read `halfWidth`/`halfHeight`\n * (AABB) or `radius` (Circle). Unused fields are set to 0.\n *\n * This shape is pool-friendly — all fields are assigned in place each\n * frame without allocating nested objects.\n */\nexport interface BaseColliderInfo<L extends string = string> {\n\tentityId: number;\n\tx: number;\n\ty: number;\n\tlayer: L;\n\tcollidesWith: readonly L[];\n\t/**\n\t * Bit assigned to `layer` from the lazy layer registry. Populated by\n\t * `fillBaseColliderInfo`. Used together with `collidesWithMask` to\n\t * replace per-pair `Array.includes` layer checks with a single AND.\n\t */\n\tlayerBit: number;\n\t/** OR of `getLayerBit` for every entry in `collidesWith`. */\n\tcollidesWithMask: number;\n\tshape: ColliderShape;\n\thalfWidth: number;\n\thalfHeight: number;\n\tradius: number;\n}\n\n// ==================== Layer Bit Registry ====================\n\nconst _layerRegistry = createLayerBitRegistry('Collision');\nexport const getLayerBit = _layerRegistry.getLayerBit;\nexport const getCollidesWithMask = _layerRegistry.getCollidesWithMask;\n\n// ==================== Collider Construction ====================\n\n/**\n * Populate a `BaseColliderInfo` slot in place from raw component data.\n * Returns `true` if the slot was filled, `false` if the entity has no\n * collider (caller should skip it).\n *\n * If an entity has both AABB and circle colliders, AABB wins and only\n * the AABB offset is applied. This matches the dispatch precedence in\n * `computeContact`; the previous implementation stacked both offsets,\n * which was a bug.\n */\nexport function fillBaseColliderInfo<L extends string>(\n\tinfo: BaseColliderInfo<L>,\n\tentityId: number,\n\tx: number,\n\ty: number,\n\tlayer: L,\n\tcollidesWith: readonly L[],\n\taabb: { width: number; height: number; offsetX?: number; offsetY?: number } | undefined,\n\tcircle: { radius: number; offsetX?: number; offsetY?: number } | undefined,\n): boolean {\n\tinfo.entityId = entityId;\n\tinfo.layer = layer;\n\tinfo.collidesWith = collidesWith;\n\tinfo.layerBit = getLayerBit(layer);\n\tinfo.collidesWithMask = getCollidesWithMask(collidesWith);\n\n\tif (aabb) {\n\t\tinfo.x = x + (aabb.offsetX ?? 0);\n\t\tinfo.y = y + (aabb.offsetY ?? 0);\n\t\tinfo.shape = AABB_SHAPE;\n\t\tinfo.halfWidth = aabb.width / 2;\n\t\tinfo.halfHeight = aabb.height / 2;\n\t\tinfo.radius = 0;\n\t\treturn true;\n\t}\n\n\tif (circle) {\n\t\tinfo.x = x + (circle.offsetX ?? 0);\n\t\tinfo.y = y + (circle.offsetY ?? 0);\n\t\tinfo.shape = CIRCLE_SHAPE;\n\t\tinfo.halfWidth = 0;\n\t\tinfo.halfHeight = 0;\n\t\tinfo.radius = circle.radius;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n// ==================== Spatial Index Lookup ====================\n\n/**\n * Retrieve the optional spatialIndex resource, returning undefined when absent.\n * Centralizes the cross-plugin typed lookup so individual plugins don't each\n * need to import SpatialIndex or repeat the tryGetResource pattern.\n */\nexport function tryGetSpatialIndex(\n\ttryGetResource: <T>(key: string) => T | undefined,\n): SpatialIndex | undefined {\n\treturn tryGetResource<SpatialIndex>('spatialIndex');\n}\n\n// ==================== Narrowphase Tests ====================\n\n/**\n * Write an AABB-AABB contact into `out`. Returns `true` if the shapes\n * overlap (out was filled), `false` otherwise.\n */\nexport function computeAABBvsAABB(\n\tax: number, ay: number, ahw: number, ahh: number,\n\tbx: number, by: number, bhw: number, bhh: number,\n\tout: Contact,\n): boolean {\n\tconst dx = bx - ax;\n\tconst dy = by - ay;\n\tconst overlapX = (ahw + bhw) - Math.abs(dx);\n\tconst overlapY = (ahh + bhh) - Math.abs(dy);\n\n\tif (overlapX <= 0 || overlapY <= 0) return false;\n\n\tif (overlapX < overlapY) {\n\t\tout.normalX = dx >= 0 ? 1 : -1;\n\t\tout.normalY = 0;\n\t\tout.depth = overlapX;\n\t\treturn true;\n\t}\n\tout.normalX = 0;\n\tout.normalY = dy >= 0 ? 1 : -1;\n\tout.depth = overlapY;\n\treturn true;\n}\n\nexport function computeCircleVsCircle(\n\tax: number, ay: number, ar: number,\n\tbx: number, by: number, br: number,\n\tout: Contact,\n): boolean {\n\tconst dx = bx - ax;\n\tconst dy = by - ay;\n\tconst distSq = dx * dx + dy * dy;\n\tconst radiusSum = ar + br;\n\n\tif (distSq >= radiusSum * radiusSum) return false;\n\n\tconst dist = Math.sqrt(distSq);\n\tif (dist === 0) {\n\t\tout.normalX = 1;\n\t\tout.normalY = 0;\n\t\tout.depth = radiusSum;\n\t\treturn true;\n\t}\n\tout.normalX = dx / dist;\n\tout.normalY = dy / dist;\n\tout.depth = radiusSum - dist;\n\treturn true;\n}\n\nexport function computeAABBvsCircle(\n\taabbX: number, aabbY: number, ahw: number, ahh: number,\n\tcircleX: number, circleY: number, radius: number,\n\tout: Contact,\n): boolean {\n\tconst closestX = Math.max(aabbX - ahw, Math.min(circleX, aabbX + ahw));\n\tconst closestY = Math.max(aabbY - ahh, Math.min(circleY, aabbY + ahh));\n\n\tconst dx = circleX - closestX;\n\tconst dy = circleY - closestY;\n\tconst distSq = dx * dx + dy * dy;\n\n\tif (distSq >= radius * radius) return false;\n\n\t// Circle center inside AABB\n\tif (distSq === 0) {\n\t\tconst pushLeft = (circleX - (aabbX - ahw));\n\t\tconst pushRight = ((aabbX + ahw) - circleX);\n\t\tconst pushUp = (circleY - (aabbY - ahh));\n\t\tconst pushDown = ((aabbY + ahh) - circleY);\n\t\tconst minPush = Math.min(pushLeft, pushRight, pushUp, pushDown);\n\n\t\tif (minPush === pushRight) {\n\t\t\tout.normalX = 1; out.normalY = 0; out.depth = pushRight + radius;\n\t\t\treturn true;\n\t\t}\n\t\tif (minPush === pushLeft) {\n\t\t\tout.normalX = -1; out.normalY = 0; out.depth = pushLeft + radius;\n\t\t\treturn true;\n\t\t}\n\t\tif (minPush === pushDown) {\n\t\t\tout.normalX = 0; out.normalY = 1; out.depth = pushDown + radius;\n\t\t\treturn true;\n\t\t}\n\t\tout.normalX = 0; out.normalY = -1; out.depth = pushUp + radius;\n\t\treturn true;\n\t}\n\n\tconst dist = Math.sqrt(distSq);\n\tout.normalX = dx / dist;\n\tout.normalY = dy / dist;\n\tout.depth = radius - dist;\n\treturn true;\n}\n\n// ==================== Contact Dispatcher ====================\n\n/**\n * Dispatch to the correct narrowphase function for the given pair and\n * write the contact into `out`. Returns `true` if the pair overlaps.\n */\nexport function computeContact(a: BaseColliderInfo, b: BaseColliderInfo, out: Contact): boolean {\n\tif (a.shape === AABB_SHAPE && b.shape === AABB_SHAPE) {\n\t\treturn computeAABBvsAABB(\n\t\t\ta.x, a.y, a.halfWidth, a.halfHeight,\n\t\t\tb.x, b.y, b.halfWidth, b.halfHeight,\n\t\t\tout,\n\t\t);\n\t}\n\n\tif (a.shape === CIRCLE_SHAPE && b.shape === CIRCLE_SHAPE) {\n\t\treturn computeCircleVsCircle(\n\t\t\ta.x, a.y, a.radius,\n\t\t\tb.x, b.y, b.radius,\n\t\t\tout,\n\t\t);\n\t}\n\n\tif (a.shape === AABB_SHAPE && b.shape === CIRCLE_SHAPE) {\n\t\treturn computeAABBvsCircle(\n\t\t\ta.x, a.y, a.halfWidth, a.halfHeight,\n\t\t\tb.x, b.y, b.radius,\n\t\t\tout,\n\t\t);\n\t}\n\n\t// a is Circle, b is AABB — compute as AABB-vs-Circle, then flip normal in place\n\tif (!computeAABBvsCircle(\n\t\tb.x, b.y, b.halfWidth, b.halfHeight,\n\t\ta.x, a.y, a.radius,\n\t\tout,\n\t)) return false;\n\tout.normalX = -out.normalX;\n\tout.normalY = -out.normalY;\n\treturn true;\n}\n\n// ==================== Collision Iteration ====================\n\nconst _broadphaseCandidates: number[] = [];\n\n/**\n * Per-caller scratch for the broadphase entityId → collider lookup.\n *\n * Dense `arr` indexed by entityId, paired with a `gen` stamp array that marks\n * which slots are live this call. Bumping `current` invalidates all prior\n * entries without clearing — replaces the per-frame `Map.clear()` + N\n * `Map.set()` allocation churn that a `Map<number, I>` would incur.\n *\n * Owned per plugin instance (alongside its `colliderPool`), so concurrent\n * worlds don't share state and `I` stays fully typed without erasure.\n */\nexport interface BroadphaseScratch<I extends BaseColliderInfo> {\n\tarr: (I | undefined)[];\n\tgen: number[];\n\tcurrent: number;\n}\n\nexport function createBroadphaseScratch<I extends BaseColliderInfo>(): BroadphaseScratch<I> {\n\treturn { arr: [], gen: [], current: 0 };\n}\n\nlet _bruteForceWarned = false;\nconst BRUTE_FORCE_WARN_THRESHOLD = 50;\n\n/**\n * Generic collision detection pipeline: brute-force or broadphase,\n * with layer filtering and contact computation.\n *\n * `count` is the number of live entries at the front of `colliders`.\n * The array itself may be a grow-only pool — only indices `[0, count)`\n * are iterated, so trailing pool slots are ignored.\n *\n * `scratch` is a caller-owned `BroadphaseScratch<I>` used by the broadphase\n * path as an entityId → collider lookup. Allocate it once per plugin instance\n * and pass the same reference every call.\n *\n * Uses a context parameter forwarded to the callback to avoid\n * per-frame closure allocation.\n */\nexport function detectCollisions<I extends BaseColliderInfo, C>(\n\tcolliders: I[],\n\tcount: number,\n\tscratch: BroadphaseScratch<I>,\n\tspatialIndex: SpatialIndex | undefined,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tif (spatialIndex) {\n\t\tbroadphaseDetect(colliders, count, scratch, spatialIndex, onContact, context);\n\t} else {\n\t\tbruteForceDetect(colliders, count, onContact, context);\n\t}\n}\n\nfunction bruteForceDetect<I extends BaseColliderInfo, C>(\n\tcolliders: I[],\n\tcount: number,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tif (!_bruteForceWarned && count >= BRUTE_FORCE_WARN_THRESHOLD) {\n\t\t_bruteForceWarned = true;\n\t\tconsole.warn(\n\t\t\t`[ecspresso] Collision detection is using O(n²) brute force with ${count} colliders. ` +\n\t\t\t`For better performance, install createSpatialIndexPlugin() alongside your collision or physics2D plugin.`,\n\t\t);\n\t}\n\n\tfor (let i = 0; i < count; i++) {\n\t\tconst a = colliders[i];\n\t\tif (!a) continue;\n\n\t\tfor (let j = i + 1; j < count; j++) {\n\t\t\tconst b = colliders[j];\n\t\t\tif (!b) continue;\n\n\t\t\tif (((a.collidesWithMask & b.layerBit) | (b.collidesWithMask & a.layerBit)) === 0) continue;\n\n\t\t\tif (!computeContact(a, b, _sharedContact)) continue;\n\n\t\t\tonContact(a, b, _sharedContact, context);\n\t\t}\n\t}\n}\n\nfunction broadphaseDetect<I extends BaseColliderInfo, C>(\n\tcolliders: I[],\n\tcount: number,\n\tscratch: BroadphaseScratch<I>,\n\tspatialIndex: SpatialIndex,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tconst arr = scratch.arr;\n\tconst stamps = scratch.gen;\n\tconst gen = ++scratch.current;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst c = colliders[i];\n\t\tif (!c) continue;\n\t\tconst id = c.entityId;\n\t\tarr[id] = c;\n\t\tstamps[id] = gen;\n\t}\n\n\tfor (let i = 0; i < count; i++) {\n\t\tconst a = colliders[i];\n\t\tif (!a) continue;\n\n\t\tconst aHalfW = a.shape === AABB_SHAPE ? a.halfWidth : a.radius;\n\t\tconst aHalfH = a.shape === AABB_SHAPE ? a.halfHeight : a.radius;\n\n\t\t_broadphaseCandidates.length = 0;\n\t\tspatialIndex.queryRectInto(\n\t\t\ta.x - aHalfW, a.y - aHalfH,\n\t\t\ta.x + aHalfW, a.y + aHalfH,\n\t\t\t_broadphaseCandidates,\n\t\t\ta.entityId,\n\t\t);\n\n\t\tfor (const bId of _broadphaseCandidates) {\n\t\t\tif (stamps[bId] !== gen) continue;\n\t\t\tconst b = arr[bId];\n\t\t\tif (!b) continue;\n\n\t\t\tif (((a.collidesWithMask & b.layerBit) | (b.collidesWithMask & a.layerBit)) === 0) continue;\n\n\t\t\tif (!computeContact(a, b, _sharedContact)) continue;\n\n\t\t\tonContact(a, b, _sharedContact, context);\n\t\t}\n\t}\n}\n",
8
- "/**\n * Flocking Plugin for ECSpresso\n *\n * Classic boid simulation — separation, alignment, cohesion. Produces\n * emergent group movement from simple per-entity steering forces.\n *\n * Composes with the physics2D plugin: flocking computes steering forces\n * and feeds them through `applyForce()`. Physics integration handles\n * velocity and position updates.\n *\n * Requires the spatial-index plugin for efficient neighbor queries.\n * Entities must have a `circleCollider` (or `aabbCollider`) to appear\n * in spatial index queries.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\nimport type { WorldConfigFrom } from 'ecspresso';\nimport type { TransformWorldConfig } from '../spatial/transform';\nimport type { Physics2DOwnComponentTypes } from '../physics/physics2D';\nimport { applyForce } from '../physics/physics2D';\nimport type { SpatialIndexResourceTypes } from '../spatial/spatial-index';\n\n// ==================== Component Types ====================\n\n/**\n * Configures flocking behavior for a boid entity.\n *\n * Entities with this component must also have:\n * - `localTransform` + `worldTransform` (transform plugin)\n * - `velocity` + `force` + `rigidBody` (physics2D plugin)\n * - `circleCollider` with radius >= perceptionRadius (for spatial index queries)\n */\nexport interface FlockingAgent {\n\t/** Radius within which neighbors are detected */\n\tperceptionRadius: number;\n\t/** Separation weight — steer away from nearby neighbors (default: 1.5) */\n\tseparationWeight: number;\n\t/** Alignment weight — match average heading of neighbors (default: 1.0) */\n\talignmentWeight: number;\n\t/** Cohesion weight — steer toward average position of neighbors (default: 1.0) */\n\tcohesionWeight: number;\n\t/** Maximum steering force magnitude per frame */\n\tmaxForce: number;\n\t/** Maximum velocity magnitude (hard speed cap) */\n\tmaxSpeed: number;\n\t/** Flock group ID for independent flocks (default: 0) */\n\tflockGroup: number;\n}\n\n/**\n * Component types provided by the flocking plugin.\n */\nexport interface FlockingComponentTypes {\n\tflockingAgent: FlockingAgent;\n}\n\n// ==================== WorldConfig ====================\n\n/**\n * WorldConfig representing the flocking plugin's provided types.\n */\nexport type FlockingWorldConfig = WorldConfigFrom<FlockingComponentTypes>;\n\n// ==================== Plugin Options ====================\n\nexport interface FlockingPluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {\n\t/** Priority for the heading/speed-clamp system (default: 200) */\n\theadingPriority?: number;\n}\n\n// ==================== Helper Functions ====================\n\n/**\n * Create a flockingAgent component with sensible defaults.\n *\n * Entities must also have a `circleCollider` with radius >= perceptionRadius\n * for the spatial index to find them as neighbors.\n *\n * @param options Partial overrides for flocking agent fields\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createFlockingAgent({ perceptionRadius: 80, maxSpeed: 150 }),\n * ...createRigidBody('dynamic', { mass: 1, drag: 1, gravityScale: 0 }),\n * ...createCircleCollider(80),\n * ...createGraphicsComponents(boidGraphics, { x: 100, y: 200 }),\n * });\n * ```\n */\nexport function createFlockingAgent(\n\toptions?: Partial<FlockingAgent>,\n): Pick<FlockingComponentTypes, 'flockingAgent'> {\n\treturn {\n\t\tflockingAgent: {\n\t\t\tperceptionRadius: options?.perceptionRadius ?? 100,\n\t\t\tseparationWeight: options?.separationWeight ?? 1.5,\n\t\t\talignmentWeight: options?.alignmentWeight ?? 1.0,\n\t\t\tcohesionWeight: options?.cohesionWeight ?? 1.0,\n\t\t\tmaxForce: options?.maxForce ?? 400,\n\t\t\tmaxSpeed: options?.maxSpeed ?? 200,\n\t\t\tflockGroup: options?.flockGroup ?? 0,\n\t\t},\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\nconst _neighborBuf: number[] = [];\n\nconst SPEED_EPSILON = 0.01;\n\n/**\n * Create a flocking plugin for ECSpresso.\n *\n * Installs two systems:\n * - `flocking-forces` — computes separation/alignment/cohesion and applies via applyForce()\n * - `flocking-heading` — clamps speed to maxSpeed and orients rotation to match velocity\n *\n * Requires the transform, physics2D, and spatial-index plugins to be installed.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createRenderer2DPlugin({ background: '#0a0a2e' }))\n * .withPlugin(createPhysics2DPlugin())\n * .withPlugin(createSpatialIndexPlugin())\n * .withPlugin(createFlockingPlugin())\n * .build();\n * ```\n */\nexport function createFlockingPlugin<G extends string = 'ai'>(\n\toptions?: FlockingPluginOptions<G>,\n) {\n\tconst {\n\t\tsystemGroup = 'ai',\n\t\tpriority = 500,\n\t\tphase = 'update',\n\t\theadingPriority = 200,\n\t} = options ?? {};\n\n\treturn definePlugin('flocking')\n\t\t.withComponentTypes<FlockingComponentTypes>()\n\t\t.withLabels<'flocking-forces' | 'flocking-heading'>()\n\t\t.withGroups<G>()\n\t\t.requires<\n\t\t\tTransformWorldConfig &\n\t\t\tWorldConfigFrom<Pick<Physics2DOwnComponentTypes, 'velocity' | 'force'>> &\n\t\t\tWorldConfigFrom<{}, {}, SpatialIndexResourceTypes>\n\t\t>()\n\t\t.install((world) => {\n\t\t\t// --- System 1: Compute and apply flocking forces ---\n\t\t\tworld\n\t\t\t\t.addSystem('flocking-forces')\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('boids', {\n\t\t\t\t\twith: ['flockingAgent', 'worldTransform', 'velocity', 'force'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tconst spatialIndex = ecs.getResource('spatialIndex');\n\n\t\t\t\t\tfor (const entity of queries.boids) {\n\t\t\t\t\t\tconst { flockingAgent, worldTransform, velocity } = entity.components;\n\t\t\t\t\t\tconst { perceptionRadius, separationWeight, alignmentWeight, cohesionWeight, maxForce, flockGroup } = flockingAgent;\n\n\t\t\t\t\t\t// Query neighbors via spatial index\n\t\t\t\t\t\t_neighborBuf.length = 0;\n\t\t\t\t\t\tspatialIndex.queryRadiusInto(worldTransform.x, worldTransform.y, perceptionRadius, _neighborBuf);\n\n\t\t\t\t\t\t// Accumulate steering forces — all inline scalars, no allocations\n\t\t\t\t\t\tlet sepX = 0, sepY = 0, sepCount = 0;\n\t\t\t\t\t\tlet alignX = 0, alignY = 0, alignCount = 0;\n\t\t\t\t\t\tlet cohX = 0, cohY = 0, cohCount = 0;\n\n\t\t\t\t\t\tconst separationRadius = perceptionRadius * 0.5;\n\t\t\t\t\t\tconst separationRadiusSq = separationRadius * separationRadius;\n\n\t\t\t\t\t\tfor (const neighborId of _neighborBuf) {\n\t\t\t\t\t\t\tif (neighborId === entity.id) continue;\n\n\t\t\t\t\t\t\tconst neighborAgent = ecs.getComponent(neighborId, 'flockingAgent');\n\t\t\t\t\t\t\tif (!neighborAgent) continue;\n\t\t\t\t\t\t\tif (neighborAgent.flockGroup !== flockGroup) continue;\n\n\t\t\t\t\t\t\tconst neighborTransform = ecs.getComponent(neighborId, 'worldTransform');\n\t\t\t\t\t\t\tif (!neighborTransform) continue;\n\n\t\t\t\t\t\t\tconst dx = worldTransform.x - neighborTransform.x;\n\t\t\t\t\t\t\tconst dy = worldTransform.y - neighborTransform.y;\n\t\t\t\t\t\t\tconst distSq = dx * dx + dy * dy;\n\n\t\t\t\t\t\t\t// Separation — closer neighbors push harder\n\t\t\t\t\t\t\tif (distSq > 0 && distSq < separationRadiusSq) {\n\t\t\t\t\t\t\t\tconst dist = Math.sqrt(distSq);\n\t\t\t\t\t\t\t\tsepX += dx / dist;\n\t\t\t\t\t\t\t\tsepY += dy / dist;\n\t\t\t\t\t\t\t\tsepCount++;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Alignment — average velocity of neighbors\n\t\t\t\t\t\t\tconst neighborVel = ecs.getComponent(neighborId, 'velocity');\n\t\t\t\t\t\t\tif (neighborVel) {\n\t\t\t\t\t\t\t\talignX += neighborVel.x;\n\t\t\t\t\t\t\t\talignY += neighborVel.y;\n\t\t\t\t\t\t\t\talignCount++;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Cohesion — average position of neighbors\n\t\t\t\t\t\t\tcohX += neighborTransform.x;\n\t\t\t\t\t\t\tcohY += neighborTransform.y;\n\t\t\t\t\t\t\tcohCount++;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet totalFx = 0, totalFy = 0;\n\n\t\t\t\t\t\t// Separation: steer away from crowded neighbors\n\t\t\t\t\t\tif (sepCount > 0) {\n\t\t\t\t\t\t\ttotalFx += (sepX / sepCount) * separationWeight;\n\t\t\t\t\t\t\ttotalFy += (sepY / sepCount) * separationWeight;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Alignment: steer toward average heading\n\t\t\t\t\t\tif (alignCount > 0) {\n\t\t\t\t\t\t\tconst avgVx = alignX / alignCount;\n\t\t\t\t\t\t\tconst avgVy = alignY / alignCount;\n\t\t\t\t\t\t\t// Desired = average velocity - current velocity\n\t\t\t\t\t\t\ttotalFx += (avgVx - velocity.x) * alignmentWeight;\n\t\t\t\t\t\t\ttotalFy += (avgVy - velocity.y) * alignmentWeight;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Cohesion: steer toward average position\n\t\t\t\t\t\tif (cohCount > 0) {\n\t\t\t\t\t\t\tconst avgPx = cohX / cohCount;\n\t\t\t\t\t\t\tconst avgPy = cohY / cohCount;\n\t\t\t\t\t\t\t// Desired = direction to center of mass - current velocity\n\t\t\t\t\t\t\ttotalFx += (avgPx - worldTransform.x - velocity.x) * cohesionWeight;\n\t\t\t\t\t\t\ttotalFy += (avgPy - worldTransform.y - velocity.y) * cohesionWeight;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Clamp total steering force to maxForce\n\t\t\t\t\t\tconst forceMagSq = totalFx * totalFx + totalFy * totalFy;\n\t\t\t\t\t\tif (forceMagSq > maxForce * maxForce) {\n\t\t\t\t\t\t\tconst forceMag = Math.sqrt(forceMagSq);\n\t\t\t\t\t\t\ttotalFx = (totalFx / forceMag) * maxForce;\n\t\t\t\t\t\t\ttotalFy = (totalFy / forceMag) * maxForce;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tapplyForce(ecs, entity.id, totalFx, totalFy);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// --- System 2: Clamp speed and orient heading from velocity ---\n\t\t\tworld\n\t\t\t\t.addSystem('flocking-heading')\n\t\t\t\t.setPriority(headingPriority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('boids', {\n\t\t\t\t\twith: ['flockingAgent', 'velocity', 'localTransform'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tfor (const entity of queries.boids) {\n\t\t\t\t\t\tconst { flockingAgent, velocity, localTransform } = entity.components;\n\t\t\t\t\t\tconst { maxSpeed } = flockingAgent;\n\n\t\t\t\t\t\t// Clamp velocity to maxSpeed\n\t\t\t\t\t\tconst speedSq = velocity.x * velocity.x + velocity.y * velocity.y;\n\t\t\t\t\t\tif (speedSq > maxSpeed * maxSpeed) {\n\t\t\t\t\t\t\tconst speed = Math.sqrt(speedSq);\n\t\t\t\t\t\t\tvelocity.x = (velocity.x / speed) * maxSpeed;\n\t\t\t\t\t\t\tvelocity.y = (velocity.y / speed) * maxSpeed;\n\t\t\t\t\t\t\tecs.markChanged(entity.id, 'velocity');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Orient rotation to match velocity heading\n\t\t\t\t\t\tif (speedSq > SPEED_EPSILON * SPEED_EPSILON) {\n\t\t\t\t\t\t\tconst heading = Math.atan2(velocity.y, velocity.x);\n\t\t\t\t\t\t\tif (heading !== localTransform.rotation) {\n\t\t\t\t\t\t\t\tlocalTransform.rotation = heading;\n\t\t\t\t\t\t\t\tecs.markChanged(entity.id, 'localTransform');\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\t\t});\n}\n"
8
+ "/**\n * Flocking Plugin for ECSpresso\n *\n * Classic boid simulation — separation, alignment, cohesion. Produces\n * emergent group movement from simple per-entity steering forces.\n *\n * Composes with the physics2D plugin: flocking computes steering forces\n * and feeds them through `applyForce()`. Physics integration handles\n * velocity and position updates.\n *\n * Requires the spatial-index plugin for efficient neighbor queries.\n * Entities must have a `circleCollider` (or `aabbCollider`) to appear\n * in spatial index queries.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\nimport type { ComponentsConfig, ResourcesConfig } from 'ecspresso';\nimport type { TransformWorldConfig } from '../spatial/transform';\nimport type { Physics2DOwnComponentTypes } from '../physics/physics2D';\nimport { applyForce } from '../physics/physics2D';\nimport type { SpatialIndexResourceTypes } from '../spatial/spatial-index';\n\n// ==================== Component Types ====================\n\n/**\n * Configures flocking behavior for a boid entity.\n *\n * Entities with this component must also have:\n * - `localTransform` + `worldTransform` (transform plugin)\n * - `velocity` + `force` + `rigidBody` (physics2D plugin)\n * - `circleCollider` with radius >= perceptionRadius (for spatial index queries)\n */\nexport interface FlockingAgent {\n\t/** Radius within which neighbors are detected */\n\tperceptionRadius: number;\n\t/** Separation weight — steer away from nearby neighbors (default: 1.5) */\n\tseparationWeight: number;\n\t/** Alignment weight — match average heading of neighbors (default: 1.0) */\n\talignmentWeight: number;\n\t/** Cohesion weight — steer toward average position of neighbors (default: 1.0) */\n\tcohesionWeight: number;\n\t/** Maximum steering force magnitude per frame */\n\tmaxForce: number;\n\t/** Maximum velocity magnitude (hard speed cap) */\n\tmaxSpeed: number;\n\t/** Flock group ID for independent flocks (default: 0) */\n\tflockGroup: number;\n}\n\n/**\n * Component types provided by the flocking plugin.\n */\nexport interface FlockingComponentTypes {\n\tflockingAgent: FlockingAgent;\n}\n\n// ==================== WorldConfig ====================\n\n/**\n * WorldConfig representing the flocking plugin's provided types.\n */\nexport type FlockingWorldConfig = ComponentsConfig<FlockingComponentTypes>;\n\n// ==================== Plugin Options ====================\n\nexport interface FlockingPluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {\n\t/** Priority for the heading/speed-clamp system (default: 200) */\n\theadingPriority?: number;\n}\n\n// ==================== Helper Functions ====================\n\n/**\n * Create a flockingAgent component with sensible defaults.\n *\n * Entities must also have a `circleCollider` with radius >= perceptionRadius\n * for the spatial index to find them as neighbors.\n *\n * @param options Partial overrides for flocking agent fields\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createFlockingAgent({ perceptionRadius: 80, maxSpeed: 150 }),\n * ...createRigidBody('dynamic', { mass: 1, drag: 1, gravityScale: 0 }),\n * ...createCircleCollider(80),\n * ...createGraphicsComponents(boidGraphics, { x: 100, y: 200 }),\n * });\n * ```\n */\nexport function createFlockingAgent(\n\toptions?: Partial<FlockingAgent>,\n): Pick<FlockingComponentTypes, 'flockingAgent'> {\n\treturn {\n\t\tflockingAgent: {\n\t\t\tperceptionRadius: options?.perceptionRadius ?? 100,\n\t\t\tseparationWeight: options?.separationWeight ?? 1.5,\n\t\t\talignmentWeight: options?.alignmentWeight ?? 1.0,\n\t\t\tcohesionWeight: options?.cohesionWeight ?? 1.0,\n\t\t\tmaxForce: options?.maxForce ?? 400,\n\t\t\tmaxSpeed: options?.maxSpeed ?? 200,\n\t\t\tflockGroup: options?.flockGroup ?? 0,\n\t\t},\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\nconst _neighborBuf: number[] = [];\n\nconst SPEED_EPSILON = 0.01;\n\n/**\n * Create a flocking plugin for ECSpresso.\n *\n * Installs two systems:\n * - `flocking-forces` — computes separation/alignment/cohesion and applies via applyForce()\n * - `flocking-heading` — clamps speed to maxSpeed and orients rotation to match velocity\n *\n * Requires the transform, physics2D, and spatial-index plugins to be installed.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createRenderer2DPlugin({ background: '#0a0a2e' }))\n * .withPlugin(createPhysics2DPlugin())\n * .withPlugin(createSpatialIndexPlugin())\n * .withPlugin(createFlockingPlugin())\n * .build();\n * ```\n */\nexport function createFlockingPlugin<G extends string = 'ai'>(\n\toptions?: FlockingPluginOptions<G>,\n) {\n\tconst {\n\t\tsystemGroup = 'ai',\n\t\tpriority = 500,\n\t\tphase = 'update',\n\t\theadingPriority = 200,\n\t} = options ?? {};\n\n\treturn definePlugin('flocking')\n\t\t.withComponentTypes<FlockingComponentTypes>()\n\t\t.withLabels<'flocking-forces' | 'flocking-heading'>()\n\t\t.withGroups<G>()\n\t\t.requires<\n\t\t\tTransformWorldConfig &\n\t\t\tComponentsConfig<Pick<Physics2DOwnComponentTypes, 'velocity' | 'force'>> &\n\t\t\tResourcesConfig<SpatialIndexResourceTypes>\n\t\t>()\n\t\t.install((world) => {\n\t\t\t// --- System 1: Compute and apply flocking forces ---\n\t\t\tworld\n\t\t\t\t.addSystem('flocking-forces')\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('boids', {\n\t\t\t\t\twith: ['flockingAgent', 'worldTransform', 'velocity', 'force'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tconst spatialIndex = ecs.getResource('spatialIndex');\n\n\t\t\t\t\tfor (const entity of queries.boids) {\n\t\t\t\t\t\tconst { flockingAgent, worldTransform, velocity } = entity.components;\n\t\t\t\t\t\tconst { perceptionRadius, separationWeight, alignmentWeight, cohesionWeight, maxForce, flockGroup } = flockingAgent;\n\n\t\t\t\t\t\t// Query neighbors via spatial index\n\t\t\t\t\t\t_neighborBuf.length = 0;\n\t\t\t\t\t\tspatialIndex.queryRadiusInto(worldTransform.x, worldTransform.y, perceptionRadius, _neighborBuf);\n\n\t\t\t\t\t\t// Accumulate steering forces — all inline scalars, no allocations\n\t\t\t\t\t\tlet sepX = 0, sepY = 0, sepCount = 0;\n\t\t\t\t\t\tlet alignX = 0, alignY = 0, alignCount = 0;\n\t\t\t\t\t\tlet cohX = 0, cohY = 0, cohCount = 0;\n\n\t\t\t\t\t\tconst separationRadius = perceptionRadius * 0.5;\n\t\t\t\t\t\tconst separationRadiusSq = separationRadius * separationRadius;\n\n\t\t\t\t\t\tfor (const neighborId of _neighborBuf) {\n\t\t\t\t\t\t\tif (neighborId === entity.id) continue;\n\n\t\t\t\t\t\t\tconst neighborAgent = ecs.getComponent(neighborId, 'flockingAgent');\n\t\t\t\t\t\t\tif (!neighborAgent) continue;\n\t\t\t\t\t\t\tif (neighborAgent.flockGroup !== flockGroup) continue;\n\n\t\t\t\t\t\t\tconst neighborTransform = ecs.getComponent(neighborId, 'worldTransform');\n\t\t\t\t\t\t\tif (!neighborTransform) continue;\n\n\t\t\t\t\t\t\tconst dx = worldTransform.x - neighborTransform.x;\n\t\t\t\t\t\t\tconst dy = worldTransform.y - neighborTransform.y;\n\t\t\t\t\t\t\tconst distSq = dx * dx + dy * dy;\n\n\t\t\t\t\t\t\t// Separation — closer neighbors push harder\n\t\t\t\t\t\t\tif (distSq > 0 && distSq < separationRadiusSq) {\n\t\t\t\t\t\t\t\tconst dist = Math.sqrt(distSq);\n\t\t\t\t\t\t\t\tsepX += dx / dist;\n\t\t\t\t\t\t\t\tsepY += dy / dist;\n\t\t\t\t\t\t\t\tsepCount++;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Alignment — average velocity of neighbors\n\t\t\t\t\t\t\tconst neighborVel = ecs.getComponent(neighborId, 'velocity');\n\t\t\t\t\t\t\tif (neighborVel) {\n\t\t\t\t\t\t\t\talignX += neighborVel.x;\n\t\t\t\t\t\t\t\talignY += neighborVel.y;\n\t\t\t\t\t\t\t\talignCount++;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Cohesion — average position of neighbors\n\t\t\t\t\t\t\tcohX += neighborTransform.x;\n\t\t\t\t\t\t\tcohY += neighborTransform.y;\n\t\t\t\t\t\t\tcohCount++;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet totalFx = 0, totalFy = 0;\n\n\t\t\t\t\t\t// Separation: steer away from crowded neighbors\n\t\t\t\t\t\tif (sepCount > 0) {\n\t\t\t\t\t\t\ttotalFx += (sepX / sepCount) * separationWeight;\n\t\t\t\t\t\t\ttotalFy += (sepY / sepCount) * separationWeight;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Alignment: steer toward average heading\n\t\t\t\t\t\tif (alignCount > 0) {\n\t\t\t\t\t\t\tconst avgVx = alignX / alignCount;\n\t\t\t\t\t\t\tconst avgVy = alignY / alignCount;\n\t\t\t\t\t\t\t// Desired = average velocity - current velocity\n\t\t\t\t\t\t\ttotalFx += (avgVx - velocity.x) * alignmentWeight;\n\t\t\t\t\t\t\ttotalFy += (avgVy - velocity.y) * alignmentWeight;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Cohesion: steer toward average position\n\t\t\t\t\t\tif (cohCount > 0) {\n\t\t\t\t\t\t\tconst avgPx = cohX / cohCount;\n\t\t\t\t\t\t\tconst avgPy = cohY / cohCount;\n\t\t\t\t\t\t\t// Desired = direction to center of mass - current velocity\n\t\t\t\t\t\t\ttotalFx += (avgPx - worldTransform.x - velocity.x) * cohesionWeight;\n\t\t\t\t\t\t\ttotalFy += (avgPy - worldTransform.y - velocity.y) * cohesionWeight;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Clamp total steering force to maxForce\n\t\t\t\t\t\tconst forceMagSq = totalFx * totalFx + totalFy * totalFy;\n\t\t\t\t\t\tif (forceMagSq > maxForce * maxForce) {\n\t\t\t\t\t\t\tconst forceMag = Math.sqrt(forceMagSq);\n\t\t\t\t\t\t\ttotalFx = (totalFx / forceMag) * maxForce;\n\t\t\t\t\t\t\ttotalFy = (totalFy / forceMag) * maxForce;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tapplyForce(ecs, entity.id, totalFx, totalFy);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// --- System 2: Clamp speed and orient heading from velocity ---\n\t\t\tworld\n\t\t\t\t.addSystem('flocking-heading')\n\t\t\t\t.setPriority(headingPriority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('boids', {\n\t\t\t\t\twith: ['flockingAgent', 'velocity', 'localTransform'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tfor (const entity of queries.boids) {\n\t\t\t\t\t\tconst { flockingAgent, velocity, localTransform } = entity.components;\n\t\t\t\t\t\tconst { maxSpeed } = flockingAgent;\n\n\t\t\t\t\t\t// Clamp velocity to maxSpeed\n\t\t\t\t\t\tconst speedSq = velocity.x * velocity.x + velocity.y * velocity.y;\n\t\t\t\t\t\tif (speedSq > maxSpeed * maxSpeed) {\n\t\t\t\t\t\t\tconst speed = Math.sqrt(speedSq);\n\t\t\t\t\t\t\tvelocity.x = (velocity.x / speed) * maxSpeed;\n\t\t\t\t\t\t\tvelocity.y = (velocity.y / speed) * maxSpeed;\n\t\t\t\t\t\t\tecs.markChanged(entity.id, 'velocity');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Orient rotation to match velocity heading\n\t\t\t\t\t\tif (speedSq > SPEED_EPSILON * SPEED_EPSILON) {\n\t\t\t\t\t\t\tconst heading = Math.atan2(velocity.y, velocity.x);\n\t\t\t\t\t\t\tif (heading !== localTransform.rotation) {\n\t\t\t\t\t\t\t\tlocalTransform.rotation = heading;\n\t\t\t\t\t\t\t\tecs.markChanged(entity.id, 'localTransform');\n\t\t\t\t\t\t\t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I9C,EACF",
11
11
  "debugId": "3BF6BCC8003D861864756E2164756E21",
@@ -10,10 +10,9 @@
10
10
  * turn-based / non-realtime consumers that don't need the component dance.
11
11
  */
12
12
  import { type BasePluginOptions } from 'ecspresso';
13
- import type { WorldConfigFrom } from 'ecspresso';
13
+ import type { ComponentsConfig, EventsConfig, ResourcesConfig } from 'ecspresso';
14
14
  import type { Vector2D } from '../../utils/math';
15
15
  import type { TransformWorldConfig } from '../spatial/transform';
16
- import type { SteeringWorldConfig } from '../physics/steering';
17
16
  /** Flat-indexed cell position in a `NavGrid`. Transparent alias, not branded. */
18
17
  export type CellIndex = number;
19
18
  /**
@@ -85,7 +84,7 @@ export interface PathfindingResourceTypes {
85
84
  navGrid: NavGrid;
86
85
  }
87
86
  /** WorldConfig representing the pathfinding plugin's provided types. */
88
- export type PathfindingWorldConfig = WorldConfigFrom<PathfindingComponentTypes, PathfindingEventTypes, PathfindingResourceTypes>;
87
+ export type PathfindingWorldConfig = ComponentsConfig<PathfindingComponentTypes> & EventsConfig<PathfindingEventTypes> & ResourcesConfig<PathfindingResourceTypes>;
89
88
  export interface PathfindingPluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {
90
89
  /** The navigation grid. Construct via `createNavGrid`. */
91
90
  grid: NavGrid;
@@ -160,4 +159,4 @@ export declare function findPath(grid: NavGrid, start: CellIndex, goal: CellInde
160
159
  * });
161
160
  * ```
162
161
  */
163
- export declare function createPathfindingPlugin<G extends string = 'ai'>(options: PathfindingPluginOptions<G>): import("ecspresso").Plugin<import("ecspresso").WithResources<import("ecspresso").WithEvents<import("ecspresso").WithComponents<import("ecspresso").EmptyConfig, PathfindingComponentTypes>, PathfindingEventTypes>, PathfindingResourceTypes>, TransformWorldConfig & SteeringWorldConfig, "pathfinding-request" | "pathfinding-waypoint-advance", G, never, never>;
162
+ export declare function createPathfindingPlugin<G extends string = 'ai'>(options: PathfindingPluginOptions<G>): import("ecspresso").Plugin<import("ecspresso").WithResources<import("ecspresso").WithEvents<import("ecspresso").WithComponents<import("ecspresso").EmptyConfig, PathfindingComponentTypes>, PathfindingEventTypes>, PathfindingResourceTypes>, TransformWorldConfig & ComponentsConfig<import("../physics/steering").SteeringComponentTypes> & EventsConfig<import("../physics/steering").SteeringEventTypes>, "pathfinding-request" | "pathfinding-waypoint-advance", G, never, never>;