ecspresso 0.13.1 → 0.13.4

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.
@@ -92,6 +92,23 @@ export interface DetectionPluginOptions<G extends string = 'ai'> extends BasePlu
92
92
  * ```
93
93
  */
94
94
  export declare function createDetector(range: number, layerFilter: readonly string[], maxResults?: number): Pick<DetectionComponentTypes, 'detector'>;
95
+ /**
96
+ * Check whether an entity has any detected targets.
97
+ *
98
+ * @param ecs ECS world instance
99
+ * @param entityId Entity with a detector component
100
+ * @returns true if detectedEntities contains at least one entry
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * if (hasDetectedTargets(ecs, guardId)) {
105
+ * // transition to chase
106
+ * }
107
+ * ```
108
+ */
109
+ export declare function hasDetectedTargets(ecs: {
110
+ getComponent(entityId: number, name: 'detectedEntities'): DetectedEntities | undefined;
111
+ }, entityId: number): boolean;
95
112
  /**
96
113
  * Create a detection plugin for ECSpresso.
97
114
  *
@@ -1,4 +1,4 @@
1
- var C=((k)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(k,{get:(E,J)=>(typeof require<"u"?require:E)[J]}):k)(function(k){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+k+'" is not supported')});import{definePlugin as b}from"ecspresso";function F(k,E,J=32){return{detector:{range:k,layerFilter:E,maxResults:J}}}function q(k,E){return k.distanceSq-E.distanceSq}function g(k){let{systemGroup:E="ai",priority:J=500,phase:G="update"}=k??{},V=new Map,K=new Set,W=new Set,Z=new WeakMap;return b("detection").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((_)=>{_.registerDispose("detector",({entityId:X})=>{V.delete(X)}),_.addSystem("detection-scan").setPriority(J).inPhase(G).inGroup(E).addQuery("detectors",{with:["detector","worldTransform"]}).setProcess(({queries:X,ecs:z})=>{let P=z.getResource("spatialIndex");for(let A of X.detectors){let{detector:H,worldTransform:O}=A.components;W.clear(),P.queryRadiusInto(O.x,O.y,H.range,W);let L=[],Q=Z.get(H.layerFilter);if(!Q)Q=new Set(H.layerFilter),Z.set(H.layerFilter,Q);for(let j of W){if(j===A.id)continue;if(!z.getEntity(j))continue;let N=z.getComponent(j,"collisionLayer");if(!N)continue;if(!Q.has(N.layer))continue;let Y=z.getComponent(j,"worldTransform");if(!Y)continue;let B=Y.x-O.x,D=Y.y-O.y;L.push({entityId:j,distanceSq:B*B+D*D})}L.sort(q);let U=L.length>H.maxResults?L.slice(0,H.maxResults):L,$=z.getComponent(A.id,"detectedEntities");if($)$.entities=U,z.markChanged(A.id,"detectedEntities");else z.addComponent(A.id,"detectedEntities",{entities:U});let M=V.get(A.id);K.clear();for(let j of U)K.add(j.entityId);if(M){for(let j of K)if(!M.has(j))z.eventBus.publish("detectionGained",{entityId:A.id,detectedId:j});for(let j of M)if(!K.has(j))z.eventBus.publish("detectionLost",{entityId:A.id,lostId:j});M.clear();for(let j of K)M.add(j)}else{let j=new Set;for(let N of U)j.add(N.entityId),z.eventBus.publish("detectionGained",{entityId:A.id,detectedId:N.entityId});V.set(A.id,j)}}})})}export{F as createDetector,g as createDetectionPlugin};
1
+ var C=((k)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(k,{get:(E,H)=>(typeof require<"u"?require:E)[H]}):k)(function(k){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+k+'" is not supported')});import{definePlugin as b}from"ecspresso";function F(k,E,H=32){return{detector:{range:k,layerFilter:E,maxResults:H}}}function g(k,E){return(k.getComponent(E,"detectedEntities")?.entities.length??0)>0}function q(k,E){return k.distanceSq-E.distanceSq}function x(k){let{systemGroup:E="ai",priority:H=500,phase:G="update"}=k??{},V=new Map,K=new Set,W=new Set,Z=new WeakMap;return b("detection").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((_)=>{_.registerDispose("detector",({entityId:X})=>{V.delete(X)}),_.addSystem("detection-scan").setPriority(H).inPhase(G).inGroup(E).addQuery("detectors",{with:["detector","worldTransform"]}).setProcess(({queries:X,ecs:z})=>{let P=z.getResource("spatialIndex");for(let A of X.detectors){let{detector:J,worldTransform:O}=A.components;W.clear(),P.queryRadiusInto(O.x,O.y,J.range,W);let L=[],Q=Z.get(J.layerFilter);if(!Q)Q=new Set(J.layerFilter),Z.set(J.layerFilter,Q);for(let j of W){if(j===A.id)continue;if(!z.getEntity(j))continue;let N=z.getComponent(j,"collisionLayer");if(!N)continue;if(!Q.has(N.layer))continue;let Y=z.getComponent(j,"worldTransform");if(!Y)continue;let B=Y.x-O.x,D=Y.y-O.y;L.push({entityId:j,distanceSq:B*B+D*D})}L.sort(q);let U=L.length>J.maxResults?L.slice(0,J.maxResults):L,$=z.getComponent(A.id,"detectedEntities");if($)$.entities=U,z.markChanged(A.id,"detectedEntities");else z.addComponent(A.id,"detectedEntities",{entities:U});let M=V.get(A.id);K.clear();for(let j of U)K.add(j.entityId);if(M){for(let j of K)if(!M.has(j))z.eventBus.publish("detectionGained",{entityId:A.id,detectedId:j});for(let j of M)if(!K.has(j))z.eventBus.publish("detectionLost",{entityId:A.id,lostId:j});M.clear();for(let j of K)M.add(j)}else{let j=new Set;for(let N of U)j.add(N.entityId),z.eventBus.publish("detectionGained",{entityId:A.id,detectedId:N.entityId});V.set(A.id,j)}}})})}export{g as hasDetectedTargets,F as createDetector,x as createDetectionPlugin};
2
2
 
3
- //# debugId=0908791952E86B8564756E2164756E21
3
+ //# debugId=E2B03972F47A4A3E64756E2164756E21
4
4
  //# sourceMappingURL=detection.js.map
@@ -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// ==================== 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\t// Reusable set for spatial index queries (avoids allocation per frame)\n\tconst candidateSet = new Set<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\tcandidateSet.clear();\n\t\t\t\t\t\tspatialIndex.queryRadiusInto(worldTransform.x, worldTransform.y, detector.range, candidateSet);\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 candidateSet) {\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 { 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\t// Reusable set for spatial index queries (avoids allocation per frame)\n\tconst candidateSet = new Set<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\tcandidateSet.clear();\n\t\t\t\t\t\tspatialIndex.queryRadiusInto(worldTransform.x, worldTransform.y, detector.range, candidateSet);\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 candidateSet) {\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,EAKvD,SAAS,CAAiB,CAAC,EAAkB,EAA0B,CACtE,OAAO,EAAE,WAAa,EAAE,WA0BlB,SAAS,CAA8C,CAC7D,EACC,CACD,IACC,cAAc,KACd,WAAW,IACX,QAAQ,UACL,GAAW,CAAC,EAGV,EAAe,IAAI,IACnB,EAAa,IAAI,IAEjB,EAAe,IAAI,IAEnB,EAAmB,IAAI,QAE7B,OAAO,EAAa,WAAW,EAC7B,mBAA4C,EAC5C,eAAoC,EACpC,WAA6B,EAC7B,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Q,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
+ "debugId": "E2B03972F47A4A3E64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Flocking Plugin for ECSpresso
3
+ *
4
+ * Classic boid simulation — separation, alignment, cohesion. Produces
5
+ * emergent group movement from simple per-entity steering forces.
6
+ *
7
+ * Composes with the physics2D plugin: flocking computes steering forces
8
+ * and feeds them through `applyForce()`. Physics integration handles
9
+ * velocity and position updates.
10
+ *
11
+ * Requires the spatial-index plugin for efficient neighbor queries.
12
+ * Entities must have a `circleCollider` (or `aabbCollider`) to appear
13
+ * in spatial index queries.
14
+ */
15
+ import { type BasePluginOptions } from 'ecspresso';
16
+ import type { WorldConfigFrom } from 'ecspresso';
17
+ import type { TransformWorldConfig } from '../spatial/transform';
18
+ import type { Physics2DOwnComponentTypes } from '../physics/physics2D';
19
+ import type { SpatialIndexResourceTypes } from '../spatial/spatial-index';
20
+ /**
21
+ * Configures flocking behavior for a boid entity.
22
+ *
23
+ * Entities with this component must also have:
24
+ * - `localTransform` + `worldTransform` (transform plugin)
25
+ * - `velocity` + `force` + `rigidBody` (physics2D plugin)
26
+ * - `circleCollider` with radius >= perceptionRadius (for spatial index queries)
27
+ */
28
+ export interface FlockingAgent {
29
+ /** Radius within which neighbors are detected */
30
+ perceptionRadius: number;
31
+ /** Separation weight — steer away from nearby neighbors (default: 1.5) */
32
+ separationWeight: number;
33
+ /** Alignment weight — match average heading of neighbors (default: 1.0) */
34
+ alignmentWeight: number;
35
+ /** Cohesion weight — steer toward average position of neighbors (default: 1.0) */
36
+ cohesionWeight: number;
37
+ /** Maximum steering force magnitude per frame */
38
+ maxForce: number;
39
+ /** Maximum velocity magnitude (hard speed cap) */
40
+ maxSpeed: number;
41
+ /** Flock group ID for independent flocks (default: 0) */
42
+ flockGroup: number;
43
+ }
44
+ /**
45
+ * Component types provided by the flocking plugin.
46
+ */
47
+ export interface FlockingComponentTypes {
48
+ flockingAgent: FlockingAgent;
49
+ }
50
+ /**
51
+ * WorldConfig representing the flocking plugin's provided types.
52
+ */
53
+ export type FlockingWorldConfig = WorldConfigFrom<FlockingComponentTypes>;
54
+ export interface FlockingPluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {
55
+ /** Priority for the heading/speed-clamp system (default: 200) */
56
+ headingPriority?: number;
57
+ }
58
+ /**
59
+ * Create a flockingAgent component with sensible defaults.
60
+ *
61
+ * Entities must also have a `circleCollider` with radius >= perceptionRadius
62
+ * for the spatial index to find them as neighbors.
63
+ *
64
+ * @param options Partial overrides for flocking agent fields
65
+ * @returns Component object suitable for spreading into spawn()
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * ecs.spawn({
70
+ * ...createFlockingAgent({ perceptionRadius: 80, maxSpeed: 150 }),
71
+ * ...createRigidBody('dynamic', { mass: 1, drag: 1, gravityScale: 0 }),
72
+ * ...createCircleCollider(80),
73
+ * ...createGraphicsComponents(boidGraphics, { x: 100, y: 200 }),
74
+ * });
75
+ * ```
76
+ */
77
+ export declare function createFlockingAgent(options?: Partial<FlockingAgent>): Pick<FlockingComponentTypes, 'flockingAgent'>;
78
+ /**
79
+ * Create a flocking plugin for ECSpresso.
80
+ *
81
+ * Installs two systems:
82
+ * - `flocking-forces` — computes separation/alignment/cohesion and applies via applyForce()
83
+ * - `flocking-heading` — clamps speed to maxSpeed and orients rotation to match velocity
84
+ *
85
+ * Requires the transform, physics2D, and spatial-index plugins to be installed.
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * const ecs = ECSpresso.create()
90
+ * .withPlugin(createRenderer2DPlugin({ background: '#0a0a2e' }))
91
+ * .withPlugin(createPhysics2DPlugin())
92
+ * .withPlugin(createSpatialIndexPlugin())
93
+ * .withPlugin(createFlockingPlugin())
94
+ * .build();
95
+ * ```
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>;
@@ -0,0 +1,4 @@
1
+ var Oz=((z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(z,{get:(J,Q)=>(typeof require<"u"?require:J)[Q]}):z)(function(z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+z+'" is not supported')});import{definePlugin as Zz}from"ecspresso";var S={normalX:0,normalY:0,depth:0},s=0;function c(z,J,Q,U,$,j,Z,K){if(z.entityId=J,z.layer=$,z.collidesWith=j,Z)return z.x=Q+(Z.offsetX??0),z.y=U+(Z.offsetY??0),z.shape=0,z.halfWidth=Z.width/2,z.halfHeight=Z.height/2,z.radius=0,!0;if(K)return z.x=Q+(K.offsetX??0),z.y=U+(K.offsetY??0),z.shape=1,z.halfWidth=0,z.halfHeight=0,z.radius=K.radius,!0;return!1}function o(z,J,Q,U,$,j,Z,K,H){let L=$-z,k=j-J,O=Q+Z-Math.abs(L),G=U+K-Math.abs(k);if(O<=0||G<=0)return!1;if(O<G)return H.normalX=L>=0?1:-1,H.normalY=0,H.depth=O,!0;return H.normalX=0,H.normalY=k>=0?1:-1,H.depth=G,!0}function zz(z,J,Q,U,$,j,Z){let K=U-z,H=$-J,L=K*K+H*H,k=Q+j;if(L>=k*k)return!1;let O=Math.sqrt(L);if(O===0)return Z.normalX=1,Z.normalY=0,Z.depth=k,!0;return Z.normalX=K/O,Z.normalY=H/O,Z.depth=k-O,!0}function r(z,J,Q,U,$,j,Z,K){let H=Math.max(z-Q,Math.min($,z+Q)),L=Math.max(J-U,Math.min(j,J+U)),k=$-H,O=j-L,G=k*k+O*O;if(G>=Z*Z)return!1;if(G===0){let D=$-(z-Q),V=z+Q-$,E=j-(J-U),W=J+U-j,_=Math.min(D,V,E,W);if(_===V)return K.normalX=1,K.normalY=0,K.depth=V+Z,!0;if(_===D)return K.normalX=-1,K.normalY=0,K.depth=D+Z,!0;if(_===W)return K.normalX=0,K.normalY=1,K.depth=W+Z,!0;return K.normalX=0,K.normalY=-1,K.depth=E+Z,!0}let N=Math.sqrt(G);return K.normalX=k/N,K.normalY=O/N,K.depth=Z-N,!0}function n(z,J,Q){if(z.shape===0&&J.shape===0)return o(z.x,z.y,z.halfWidth,z.halfHeight,J.x,J.y,J.halfWidth,J.halfHeight,Q);if(z.shape===1&&J.shape===1)return zz(z.x,z.y,z.radius,J.x,J.y,J.radius,Q);if(z.shape===0&&J.shape===1)return r(z.x,z.y,z.halfWidth,z.halfHeight,J.x,J.y,J.radius,Q);if(!r(J.x,J.y,J.halfWidth,J.halfHeight,z.x,z.y,z.radius,Q))return!1;return Q.normalX=-Q.normalX,Q.normalY=-Q.normalY,!0}var g=new Set,l=!1,Jz=50;function i(z,J,Q,U,$,j){if(U)Qz(z,J,Q,U,$,j);else Kz(z,J,$,j)}function Kz(z,J,Q,U){if(!l&&J>=Jz)l=!0,console.warn(`[ecspresso] Collision detection is using O(n²) brute force with ${J} colliders. For better performance, install createSpatialIndexPlugin() alongside your collision or physics2D plugin.`);for(let $=0;$<J;$++){let j=z[$];if(!j)continue;for(let Z=$+1;Z<J;Z++){let K=z[Z];if(!K)continue;if(!j.collidesWith.includes(K.layer)&&!K.collidesWith.includes(j.layer))continue;if(!n(j,K,S))continue;Q(j,K,S,U)}}}function Qz(z,J,Q,U,$,j){Q.clear();for(let Z=0;Z<J;Z++){let K=z[Z];if(!K)continue;Q.set(K.entityId,K)}for(let Z=0;Z<J;Z++){let K=z[Z];if(!K)continue;let H=K.shape===0?K.halfWidth:K.radius,L=K.shape===0?K.halfHeight:K.radius;g.clear(),U.queryRectInto(K.x-H,K.y-L,K.x+H,K.y+L,g);for(let k of g){if(k<=K.entityId)continue;let O=Q.get(k);if(!O)continue;if(!K.collidesWith.includes(O.layer)&&!O.collidesWith.includes(K.layer))continue;if(!n(K,O,S))continue;$(K,O,S,j)}}}function Gz(z,J){return{rigidBody:{type:z,mass:z==="static"?1/0:J?.mass??1,drag:J?.drag??0,restitution:J?.restitution??0,friction:J?.friction??0,gravityScale:J?.gravityScale??1},force:{x:0,y:0}}}function Lz(z,J){return{force:{x:z,y:J}}}function e(z,J,Q,U){let $=z.getComponent(J,"force");if(!$)return;$.x+=Q,$.y+=U}function Vz(z,J,Q,U){let $=z.getComponent(J,"velocity"),j=z.getComponent(J,"rigidBody");if(!$||!j)return;if(j.mass===1/0||j.mass===0)return;$.x+=Q/j.mass,$.y+=U/j.mass}function Nz(z,J,Q,U){let $=z.getComponent(J,"velocity");if(!$)return;$.x=Q,$.y=U}var w={entityA:0,entityB:0,normalX:0,normalY:0,depth:0};function $z(z,J,Q,U){let $=z.rigidBody.type==="dynamic"&&z.rigidBody.mass>0&&z.rigidBody.mass!==1/0?1/z.rigidBody.mass:0,j=J.rigidBody.type==="dynamic"&&J.rigidBody.mass>0&&J.rigidBody.mass!==1/0?1/J.rigidBody.mass:0,Z=$+j;if(Z>0){let K=Q.depth/Z;if($>0){let O=U.getComponent(z.entityId,"localTransform");if(!O)return;O.x-=K*$*Q.normalX,O.y-=K*$*Q.normalY,z.x=O.x,U.markChanged(z.entityId,"localTransform")}if(j>0){let O=U.getComponent(J.entityId,"localTransform");if(!O)return;O.x+=K*j*Q.normalX,O.y+=K*j*Q.normalY,U.markChanged(J.entityId,"localTransform")}let H=J.velocity.x-z.velocity.x,L=J.velocity.y-z.velocity.y,k=H*Q.normalX+L*Q.normalY;if(k<0){let G=-(1+Math.min(z.rigidBody.restitution,J.rigidBody.restitution))*k/Z;z.velocity.x-=G*$*Q.normalX,z.velocity.y-=G*$*Q.normalY,J.velocity.x+=G*j*Q.normalX,J.velocity.y+=G*j*Q.normalY;let N=H-k*Q.normalX,D=L-k*Q.normalY,V=Math.sqrt(N*N+D*D);if(V>0.000001){let E=N/V,W=D/V,A=Math.sqrt(z.rigidBody.friction*J.rigidBody.friction)*Math.abs(G),T=Math.min(V/Z,A);z.velocity.x+=T*$*E,z.velocity.y+=T*$*W,J.velocity.x-=T*j*E,J.velocity.y-=T*j*W}}U.markChanged(z.entityId,"velocity"),U.markChanged(J.entityId,"velocity")}w.entityA=z.entityId,w.entityB=J.entityId,w.normalX=Q.normalX,w.normalY=Q.normalY,w.depth=Q.depth,U.eventBus.publish("physicsCollision",w)}function Wz(z){let{gravity:J={x:0,y:0},systemGroup:Q="physics2D",collisionSystemGroup:U,integrationPriority:$=1000,collisionPriority:j=900,phase:Z="fixedUpdate"}=z??{};return Zz("physics2D").withComponentTypes().withEventTypes().withResourceTypes().withLabels().withGroups().requires().install((K)=>{K.registerRequired("rigidBody","velocity",()=>({x:0,y:0})),K.registerRequired("rigidBody","force",()=>({x:0,y:0})),K.addResource("physicsConfig",{gravity:{x:J.x,y:J.y}}),K.addSystem("physics2D-integration").setPriority($).inPhase(Z).inGroup(Q).addQuery("bodies",{with:["localTransform","velocity","rigidBody","force"]}).setProcess(({queries:N,dt:D,ecs:V})=>{let{gravity:E}=V.getResource("physicsConfig"),W=E.x,_=E.y;for(let A of N.bodies){let{localTransform:T,velocity:R,rigidBody:P,force:q}=A.components;if(P.type==="static")continue;if(P.type==="dynamic"){if(R.x+=W*P.gravityScale*D,R.y+=_*P.gravityScale*D,P.mass>0&&P.mass!==1/0)R.x+=q.x/P.mass*D,R.y+=q.y/P.mass*D;if(P.drag>0){let M=Math.max(0,1-P.drag*D);R.x*=M,R.y*=M}}T.x+=R.x*D,T.y+=R.y*D,q.x=0,q.y=0,V.markChanged(A.id,"localTransform")}});let H=K.addSystem("physics2D-collision").setPriority(j).inPhase(Z).inGroup(Q);if(U)H.inGroup(U);let L=[],k=new Map,O,G=!1;H.addQuery("collidables",{with:["localTransform","rigidBody","velocity","collisionLayer"]}).setProcess(({queries:N,ecs:D})=>{let V=0;for(let E of N.collidables){let{localTransform:W,rigidBody:_,velocity:A,collisionLayer:T}=E.components,R=D.getComponent(E.id,"aabbCollider"),P=R?void 0:D.getComponent(E.id,"circleCollider");if(!R&&!P)continue;let q=L[V];if(!q)q={entityId:E.id,x:W.x,y:W.y,layer:T.layer,collidesWith:T.collidesWith,shape:s,halfWidth:0,halfHeight:0,radius:0,rigidBody:_,velocity:A},L[V]=q;else q.rigidBody=_,q.velocity=A;if(!c(q,E.id,W.x,W.y,T.layer,T.collidesWith,R,P))continue;V++}if(!G)O=D.tryGetResource("spatialIndex"),G=!0;i(L,V,k,O,$z,D)})})}import{definePlugin as jz}from"ecspresso";function Tz(z){return{flockingAgent:{perceptionRadius:z?.perceptionRadius??100,separationWeight:z?.separationWeight??1.5,alignmentWeight:z?.alignmentWeight??1,cohesionWeight:z?.cohesionWeight??1,maxForce:z?.maxForce??400,maxSpeed:z?.maxSpeed??200,flockGroup:z?.flockGroup??0}}}var h=new Set,a=0.01;function qz(z){let{systemGroup:J="ai",priority:Q=500,phase:U="update",headingPriority:$=200}=z??{};return jz("flocking").withComponentTypes().withLabels().withGroups().requires().install((j)=>{j.addSystem("flocking-forces").setPriority(Q).inPhase(U).inGroup(J).addQuery("boids",{with:["flockingAgent","worldTransform","velocity","force"]}).setProcess(({queries:Z,ecs:K})=>{let H=K.getResource("spatialIndex");for(let L of Z.boids){let{flockingAgent:k,worldTransform:O,velocity:G}=L.components,{perceptionRadius:N,separationWeight:D,alignmentWeight:V,cohesionWeight:E,maxForce:W,flockGroup:_}=k;h.clear(),H.queryRadiusInto(O.x,O.y,N,h);let A=0,T=0,R=0,P=0,q=0,M=0,y=0,p=0,I=0,b=N*0.5,t=b*b;for(let F of h){if(F===L.id)continue;let B=K.getComponent(F,"flockingAgent");if(!B)continue;if(B.flockGroup!==_)continue;let C=K.getComponent(F,"worldTransform");if(!C)continue;let x=O.x-C.x,m=O.y-C.y,v=x*x+m*m;if(v>0&&v<t){let d=Math.sqrt(v);A+=x/d,T+=m/d,R++}let f=K.getComponent(F,"velocity");if(f)P+=f.x,q+=f.y,M++;y+=C.x,p+=C.y,I++}let X=0,Y=0;if(R>0)X+=A/R*D,Y+=T/R*D;if(M>0){let F=P/M,B=q/M;X+=(F-G.x)*V,Y+=(B-G.y)*V}if(I>0){let F=y/I,B=p/I;X+=(F-O.x-G.x)*E,Y+=(B-O.y-G.y)*E}let u=X*X+Y*Y;if(u>W*W){let F=Math.sqrt(u);X=X/F*W,Y=Y/F*W}e(K,L.id,X,Y)}}),j.addSystem("flocking-heading").setPriority($).inPhase(U).inGroup(J).addQuery("boids",{with:["flockingAgent","velocity","localTransform"]}).setProcess(({queries:Z,ecs:K})=>{for(let H of Z.boids){let{flockingAgent:L,velocity:k,localTransform:O}=H.components,{maxSpeed:G}=L,N=k.x*k.x+k.y*k.y;if(N>G*G){let D=Math.sqrt(N);k.x=k.x/D*G,k.y=k.y/D*G,K.markChanged(H.id,"velocity")}if(N>a*a){let D=Math.atan2(k.y,k.x);if(D!==O.rotation)O.rotation=D,K.markChanged(H.id,"localTransform")}}})})}export{qz as createFlockingPlugin,Tz as createFlockingAgent};
2
+
3
+ //# debugId=D7E6339EF72ED21364756E2164756E21
4
+ //# sourceMappingURL=flocking.js.map
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/plugins/physics/physics2D.ts", "../src/utils/narrowphase.ts", "../src/plugins/ai/flocking.ts"],
4
+ "sourcesContent": [
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, 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\tltA.x -= correctionScale * invMassA * contact.normalX;\n\t\t\tltA.y -= correctionScale * invMassA * contact.normalY;\n\t\t\t// Update cached position for subsequent pairs (collider offset already baked in)\n\t\t\ta.x = ltA.x;\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\tltB.x += correctionScale * invMassB * contact.normalX;\n\t\t\tltB.y += correctionScale * invMassB * contact.normalY;\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\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\tvelocity.x += gx * rigidBody.gravityScale * dt;\n\t\t\t\t\t\t\tvelocity.y += gy * rigidBody.gravityScale * dt;\n\n\t\t\t\t\t\t\t// 2. Forces (F = ma → a = F/m)\n\t\t\t\t\t\t\tif (rigidBody.mass > 0 && rigidBody.mass !== Infinity) {\n\t\t\t\t\t\t\t\tvelocity.x += (force.x / rigidBody.mass) * dt;\n\t\t\t\t\t\t\t\tvelocity.y += (force.y / rigidBody.mass) * dt;\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\t// Reusable entityId → collider lookup for the broadphase path.\n\t\t\tconst broadphaseMap = new Map<number, 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\tcollisionSystem\n\t\t\t\t.addQuery('collidables', {\n\t\t\t\t\twith: ['localTransform', 'rigidBody', 'velocity', 'collisionLayer'],\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.collidables) {\n\t\t\t\t\t\tconst { localTransform, rigidBody, velocity, collisionLayer } = entity.components;\n\t\t\t\t\t\tconst aabb = ecs.getComponent(entity.id, 'aabbCollider');\n\t\t\t\t\t\tconst circle = aabb ? undefined : ecs.getComponent(entity.id, 'circleCollider');\n\t\t\t\t\t\tif (!aabb && !circle) continue;\n\n\t\t\t\t\t\tlet slot = colliderPool[count];\n\t\t\t\t\t\tif (!slot) {\n\t\t\t\t\t\t\tslot = {\n\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\tx: localTransform.x,\n\t\t\t\t\t\t\t\ty: localTransform.y,\n\t\t\t\t\t\t\t\tlayer: collisionLayer.layer,\n\t\t\t\t\t\t\t\tcollidesWith: collisionLayer.collidesWith,\n\t\t\t\t\t\t\t\tshape: AABB_SHAPE,\n\t\t\t\t\t\t\t\thalfWidth: 0,\n\t\t\t\t\t\t\t\thalfHeight: 0,\n\t\t\t\t\t\t\t\tradius: 0,\n\t\t\t\t\t\t\t\trigidBody,\n\t\t\t\t\t\t\t\tvelocity,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tcolliderPool[count] = slot;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tslot.rigidBody = rigidBody;\n\t\t\t\t\t\t\tslot.velocity = velocity;\n\t\t\t\t\t\t}\n\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\taabb, circle,\n\t\t\t\t\t\t)) continue;\n\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, broadphaseMap, cachedSI, resolvePhysicsContact, ecs);\n\t\t\t\t});\n\t\t});\n}\n",
6
+ "/**\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';\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\tshape: ColliderShape;\n\thalfWidth: number;\n\thalfHeight: number;\n\tradius: number;\n}\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\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\n/** Module-level reusable set for broadphase candidates. */\nconst _broadphaseCandidates = new Set<number>();\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 * `workingMap` is a caller-owned `Map<number, I>` used by the broadphase\n * path as an entityId → collider lookup. It is cleared and repopulated on\n * each call; callers should allocate it once and pass the same instance\n * every frame. Unused by the brute-force path but still required so that\n * typed reuse is the default, not an opt-in.\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\tworkingMap: Map<number, 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, workingMap, 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.collidesWith.includes(b.layer) && !b.collidesWith.includes(a.layer)) 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\tcolliderMap: Map<number, I>,\n\tspatialIndex: SpatialIndex,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tcolliderMap.clear();\n\tfor (let i = 0; i < count; i++) {\n\t\tconst c = colliders[i];\n\t\tif (!c) continue;\n\t\tcolliderMap.set(c.entityId, c);\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.clear();\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);\n\n\t\tfor (const bId of _broadphaseCandidates) {\n\t\t\tif (bId <= a.entityId) continue;\n\n\t\t\tconst b = colliderMap.get(bId);\n\t\t\tif (!b) continue;\n\n\t\t\tif (!a.collidesWith.includes(b.layer) && !b.collidesWith.includes(a.layer)) 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",
7
+ "/**\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\n// Module-scoped reusable set to reduce GC pressure in neighbor queries\nconst _neighborSet = new Set<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_neighborSet.clear();\n\t\t\t\t\t\tspatialIndex.queryRadiusInto(worldTransform.x, worldTransform.y, perceptionRadius, _neighborSet);\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 _neighborSet) {\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
+ ],
9
+ "mappings": "4PAWA,uBAAS,mBCsBT,IAAM,EAA0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AGF,EACE,UAAU,kBAAkB,EAC5B,YAAY,CAAe,EAC3B,QAAQ,CAAK,EACb,QAAQ,CAAW,EACnB,SAAS,QAAS,CAClB,KAAM,CAAC,gBAAiB,WAAY,gBAAgB,CACrD,CAAC,EACA,WAAW,EAAG,UAAS,SAAU,CACjC,QAAW,KAAU,EAAQ,MAAO,CACnC,IAAQ,gBAAe,WAAU,kBAAmB,EAAO,YACnD,YAAa,EAGf,EAAU,EAAS,EAAI,EAAS,EAAI,EAAS,EAAI,EAAS,EAChE,GAAI,EAAU,EAAW,EAAU,CAClC,IAAM,EAAQ,KAAK,KAAK,CAAO,EAC/B,EAAS,EAAK,EAAS,EAAI,EAAS,EACpC,EAAS,EAAK,EAAS,EAAI,EAAS,EACpC,EAAI,YAAY,EAAO,GAAI,UAAU,EAItC,GAAI,EAAU,EAAgB,EAAe,CAC5C,IAAM,EAAU,KAAK,MAAM,EAAS,EAAG,EAAS,CAAC,EACjD,GAAI,IAAY,EAAe,SAC9B,EAAe,SAAW,EAC1B,EAAI,YAAY,EAAO,GAAI,gBAAgB,IAI9C,EACF",
10
+ "debugId": "D7E6339EF72ED21364756E2164756E21",
11
+ "names": []
12
+ }
@@ -1,4 +1,4 @@
1
- var o=((V)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(V,{get:(G,j)=>(typeof require<"u"?require:G)[j]}):V)(function(V){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+V+'" is not supported')});import{definePlugin as m}from"ecspresso";var u={traumaDecay:1,maxOffsetX:10,maxOffsetY:10,maxRotation:0.05},x={smoothing:5,deadzoneX:0,deadzoneY:0,offsetX:0,offsetY:0};function t(V,G,j){let H=V-(j.x+j.shakeOffsetX),C=G-(j.y+j.shakeOffsetY),D=-(j.rotation+j.shakeRotation),q=Math.cos(D),L=Math.sin(D),M=H*q-C*L,W=H*L+C*q;return{x:M*j.zoom+j.viewportWidth/2,y:W*j.zoom+j.viewportHeight/2}}function S(V,G,j){let H=(V-j.viewportWidth/2)/j.zoom,C=(G-j.viewportHeight/2)/j.zoom,D=j.rotation+j.shakeRotation,q=Math.cos(D),L=Math.sin(D),M=H*q-C*L,W=H*L+C*q;return{x:M+j.x+j.shakeOffsetX,y:W+j.y+j.shakeOffsetY}}function i(V){return typeof V==="number"?V:V.id}function p(V){let G=V===!0?{}:V;return{trauma:0,traumaDecay:G.traumaDecay??u.traumaDecay,maxOffsetX:G.maxOffsetX??u.maxOffsetX,maxOffsetY:G.maxOffsetY??u.maxOffsetY,maxRotation:G.maxRotation??u.maxRotation}}function n(V){if(Array.isArray(V))return{minX:V[0],minY:V[1],maxX:V[2],maxY:V[3]};return{...V}}function d(V){return{smoothing:V?.smoothing??x.smoothing,deadzoneX:V?.deadzoneX??x.deadzoneX,deadzoneY:V?.deadzoneY??x.deadzoneY,offsetX:V?.offsetX??x.offsetX,offsetY:V?.offsetY??x.offsetY}}function e(V){let{viewportWidth:G=800,viewportHeight:j=600,initial:H,follow:C,shake:D,bounds:q,zoom:L,systemGroup:M="camera",phase:W="postUpdate",randomFn:h=Math.random}=V??{};return m("camera").withComponentTypes().withResourceTypes().withLabels().withGroups().requires().install((b)=>{let R={x:H?.x??0,y:H?.y??0,zoom:H?.zoom??1,rotation:H?.rotation??0,shakeOffsetX:0,shakeOffsetY:0,shakeRotation:0,viewportWidth:G,viewportHeight:j,entityId:-1,follow:()=>{},unfollow:()=>{},setPosition:()=>{},setZoom:()=>{},setRotation:()=>{},setBounds:()=>{},clearBounds:()=>{},addTrauma:()=>{}};if(b.addResource("cameraState",R),b.addSystem("camera-init").inGroup(M).setOnInitialize(($)=>{let P=$.spawn({camera:{x:H?.x??0,y:H?.y??0,zoom:H?.zoom??1,rotation:H?.rotation??0}});if(C)$.addComponent(P.id,"cameraFollow",{target:-1,...d(C)});if(D)$.addComponent(P.id,"cameraShake",p(D));if(q)$.addComponent(P.id,"cameraBounds",n(q));R.entityId=P.id,R.follow=(Q,J)=>{let I={target:i(Q),...d(J)},N=$.getComponent(R.entityId,"cameraFollow");if(N)N.target=I.target,N.smoothing=I.smoothing,N.deadzoneX=I.deadzoneX,N.deadzoneY=I.deadzoneY,N.offsetX=I.offsetX,N.offsetY=I.offsetY;else $.addComponent(R.entityId,"cameraFollow",I)},R.unfollow=()=>{if($.getComponent(R.entityId,"cameraFollow"))$.removeComponent(R.entityId,"cameraFollow")},R.setPosition=(Q,J)=>{let K=$.getComponent(R.entityId,"camera");if(!K)return;K.x=Q,K.y=J},R.setZoom=(Q)=>{let J=$.getComponent(R.entityId,"camera");if(!J)return;J.zoom=Q},R.setRotation=(Q)=>{let J=$.getComponent(R.entityId,"camera");if(!J)return;J.rotation=Q},R.setBounds=(Q,J,K,I)=>{let N=$.getComponent(R.entityId,"cameraBounds");if(N)N.minX=Q,N.minY=J,N.maxX=K,N.maxY=I;else $.addComponent(R.entityId,"cameraBounds",{minX:Q,minY:J,maxX:K,maxY:I})},R.clearBounds=()=>{if($.getComponent(R.entityId,"cameraBounds"))$.removeComponent(R.entityId,"cameraBounds")},R.addTrauma=(Q)=>{let J=$.getComponent(R.entityId,"cameraShake");if(J)J.trauma=Math.min(1,Math.max(0,J.trauma+Q));else $.addComponent(R.entityId,"cameraShake",{...p(!0),trauma:Math.min(1,Math.max(0,Q))})}}),b.addSystem("camera-follow").setPriority(400).inPhase(W).inGroup(M).addQuery("cameras",{with:["camera","cameraFollow"]}).setProcess(({queries:$,dt:P,ecs:Q})=>{let J=Math.min(1,P);for(let K of $.cameras){let{camera:I,cameraFollow:N}=K.components;if(N.target<0)continue;let Z;try{Z=Q.getComponent(N.target,"worldTransform")}catch{continue}if(!Z)continue;let U=Z.x+N.offsetX,O=Z.y+N.offsetY,_=U-I.x,B=O-I.y;if(Math.abs(_)>N.deadzoneX){let E=_>0?1:-1,v=_-E*N.deadzoneX,f=Math.min(1,N.smoothing*J);I.x+=v*f}if(Math.abs(B)>N.deadzoneY){let E=B>0?1:-1,v=B-E*N.deadzoneY,f=Math.min(1,N.smoothing*J);I.y+=v*f}}}),b.addSystem("camera-shake-update").setPriority(390).inPhase(W).inGroup(M).addQuery("shakeCameras",{with:["camera","cameraShake"]}).setProcess(({queries:$,dt:P})=>{for(let Q of $.shakeCameras){let{cameraShake:J}=Q.components;J.trauma=Math.max(0,J.trauma-J.traumaDecay*P)}}),b.addSystem("camera-bounds").setPriority(380).inPhase(W).inGroup(M).addQuery("boundedCameras",{with:["camera","cameraBounds"]}).setProcess(({queries:$})=>{for(let P of $.boundedCameras){let{camera:Q,cameraBounds:J}=P.components,K=R.viewportWidth/(2*Q.zoom),I=R.viewportHeight/(2*Q.zoom),N=J.minX+K,Z=J.maxX-K,U=J.minY+I,O=J.maxY-I;if(N>Z)Q.x=(J.minX+J.maxX)/2;else Q.x=Math.max(N,Math.min(Z,Q.x));if(U>O)Q.y=(J.minY+J.maxY)/2;else Q.y=Math.max(U,Math.min(O,Q.y))}}),b.addSystem("camera-state-sync").setPriority(370).inPhase(W).inGroup(M).setProcess(({ecs:$})=>{let P=$.getComponent(R.entityId,"camera");if(!P){R.x=0,R.y=0,R.zoom=1,R.rotation=0,R.shakeOffsetX=0,R.shakeOffsetY=0,R.shakeRotation=0;return}R.x=P.x,R.y=P.y,R.zoom=P.zoom,R.rotation=P.rotation;let Q=$.getComponent(R.entityId,"cameraShake");if(Q&&Q.trauma>0){let J=Q.trauma*Q.trauma;R.shakeOffsetX=Q.maxOffsetX*J*(h()*2-1),R.shakeOffsetY=Q.maxOffsetY*J*(h()*2-1),R.shakeRotation=Q.maxRotation*J*(h()*2-1)}else R.shakeOffsetX=0,R.shakeOffsetY=0,R.shakeRotation=0}),L){let I=function(N){N.preventDefault(),J+=Math.sign(N.deltaY)},{zoomStep:$=0.1,minZoom:P=0.1,maxZoom:Q=10}=L,J=0,K=!1;b.addSystem("camera-zoom").setPriority(410).inPhase("preUpdate").inGroup(M).addQuery("cameras",{with:["camera"]}).setOnInitialize((N)=>{let Z=N.tryGetResource("inputState"),U=N.tryGetResource("pixiApp");if(!Z||!U){console.error("[camera] zoom requires the input plugin and renderer2D plugin. Zoom will be disabled.");return}U.canvas.addEventListener("wheel",I,{passive:!1}),K=!0}).setOnDetach((N)=>{if(!K)return;let Z=N.tryGetResource("pixiApp");if(Z)Z.canvas.removeEventListener("wheel",I)}).setProcess(({queries:N,ecs:Z})=>{if(!K||J===0)return;let U=J;J=0;let[O]=N.cameras;if(!O)return;let _=O.components.camera,B=Z.tryGetResource("inputState");if(!B)return;let E=S(B.pointer.position.x,B.pointer.position.y,R),v=U>0?1-$:1+$;_.zoom=Math.max(P,Math.min(Q,_.zoom*Math.pow(v,Math.abs(U)))),_.x=E.x-(B.pointer.position.x-R.viewportWidth/2)/_.zoom,_.y=E.y-(B.pointer.position.y-R.viewportHeight/2)/_.zoom})}})}import{Graphics as c}from"pixi.js";import{definePlugin as r}from"ecspresso";function $J(){return{selectable:!0}}function VJ(V){let{systemGroup:G="selection",priority:j=100,phase:H="preUpdate",clickThreshold:C=5,boxFillColor:D=65280,boxFillAlpha:q=0.15,boxStrokeColor:L=65280,boxStrokeAlpha:M=0.8,selectedTint:W=4521796,renderLayer:h}=V??{},b={color:D,alpha:q},R={color:L,width:1.5,alpha:M};return r("selection").withComponentTypes().withResourceTypes().withLabels().withGroups().requires().install(($)=>{$.addResource("selectionState",{dragStart:{x:0,y:0},boxEntityId:null});let P=null;$.addSystem("selection-input").setPriority(j).inPhase(H).inGroup(G).addQuery("selectables",{with:["selectable","worldTransform"]}).addQuery("currentlySelected",{with:["selected"]}).withResources(["inputState","selectionState","pixiApp"]).setOnInitialize((Q)=>{let J=Q.getResource("pixiApp");P=(K)=>K.preventDefault(),J.canvas.addEventListener("contextmenu",P)}).setOnDetach((Q)=>{if(!P)return;Q.getResource("pixiApp").canvas.removeEventListener("contextmenu",P),P=null}).setProcess(({queries:Q,ecs:J,resources:K})=>{let{inputState:I,selectionState:N}=K,Z=I.pointer;if(Z.justPressed(0)){if(N.boxEntityId!==null)J.commands.removeEntity(N.boxEntityId);N.dragStart.x=Z.position.x,N.dragStart.y=Z.position.y;let z=J.spawn({graphics:new c});if(h)J.addComponent(z.id,"renderLayer",h);N.boxEntityId=z.id}if(Z.isDown(0)&&N.boxEntityId!==null){let z=J.getComponent(N.boxEntityId,"graphics");if(!z)return;let A=N.dragStart.x,k=N.dragStart.y,F=Z.position.x,X=Z.position.y,Y=Math.min(A,F),T=Math.min(k,X),g=Math.abs(F-A),l=Math.abs(X-k);z.clear(),z.rect(Y,T,g,l),z.fill(b),z.stroke(R)}if(!Z.justReleased(0)||N.boxEntityId===null)return;let U=N.dragStart.x,O=N.dragStart.y,_=Z.position.x,B=Z.position.y,E=Math.abs(_-U),v=Math.abs(B-O);for(let z of Q.currentlySelected)J.removeComponent(z.id,"selected");let f=E<C&&v<C,w=J.tryGetResource("cameraState"),y=w?S(_,B,w):{x:_,y:B};if(f){let A=null,k=1/0;for(let F of Q.selectables){let{worldTransform:X}=F.components,Y=X.x-y.x,T=X.y-y.y,g=Y*Y+T*T;if(g<400&&g<k)k=g,A=F.id}if(A!==null)J.addComponent(A,"selected",!0)}else{let z=w?S(U,O,w):{x:U,y:O},A=Math.min(z.x,y.x),k=Math.max(z.x,y.x),F=Math.min(z.y,y.y),X=Math.max(z.y,y.y);for(let Y of Q.selectables){let{worldTransform:T}=Y.components;if(T.x>=A&&T.x<=k&&T.y>=F&&T.y<=X)J.addComponent(Y.id,"selected",!0)}}J.commands.removeEntity(N.boxEntityId),N.boxEntityId=null}),$.addSystem("selection-visual").setPriority(j).inPhase("render").inGroup(G).addQuery("selectedUnits",{with:["selected","sprite"]}).setOnEntityEnter("selectedUnits",({entity:Q})=>{Q.components.sprite.tint=W}).addQuery("deselectedUnits",{with:["selectable","sprite"],without:["selected"]}).setOnEntityEnter("deselectedUnits",({entity:Q})=>{Q.components.sprite.tint=16777215})})}export{VJ as createSelectionPlugin,$J as createSelectable};
1
+ var e=((P)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(P,{get:(M,K)=>(typeof require<"u"?require:M)[K]}):P)(function(P){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+P+'" is not supported')});import{definePlugin as r}from"ecspresso";var w={traumaDecay:1,maxOffsetX:10,maxOffsetY:10,maxRotation:0.05},u={smoothing:5,deadzoneX:0,deadzoneY:0,offsetX:0,offsetY:0};function QJ(P,M,K){let U=P-(K.x+K.shakeOffsetX),O=M-(K.y+K.shakeOffsetY),W=-(K.rotation+K.shakeRotation),E=Math.cos(W),A=Math.sin(W),y=U*E-O*A,q=U*A+O*E;return{x:y*K.zoom+K.viewportWidth/2,y:q*K.zoom+K.viewportHeight/2}}function p(P,M,K){let U=(P-K.viewportWidth/2)/K.zoom,O=(M-K.viewportHeight/2)/K.zoom,W=K.rotation+K.shakeRotation,E=Math.cos(W),A=Math.sin(W),y=U*E-O*A,q=U*A+O*E;return{x:y+K.x+K.shakeOffsetX,y:q+K.y+K.shakeOffsetY}}function o(P){return typeof P==="number"?P:P.id}function m(P){let M=P===!0?{}:P;return{trauma:0,traumaDecay:M.traumaDecay??w.traumaDecay,maxOffsetX:M.maxOffsetX??w.maxOffsetX,maxOffsetY:M.maxOffsetY??w.maxOffsetY,maxRotation:M.maxRotation??w.maxRotation}}function s(P){if(Array.isArray(P))return{minX:P[0],minY:P[1],maxX:P[2],maxY:P[3]};return{...P}}function i(P){return{smoothing:P?.smoothing??u.smoothing,deadzoneX:P?.deadzoneX??u.deadzoneX,deadzoneY:P?.deadzoneY??u.deadzoneY,offsetX:P?.offsetX??u.offsetX,offsetY:P?.offsetY??u.offsetY}}function $J(P){let{viewportWidth:M=800,viewportHeight:K=600,initial:U,follow:O,shake:W,bounds:E,zoom:A,pan:y,systemGroup:q="camera",phase:g="postUpdate",randomFn:f=Math.random}=P??{};return r("camera").withComponentTypes().withResourceTypes().withLabels().withGroups().requires().install((k)=>{let J={x:U?.x??0,y:U?.y??0,zoom:U?.zoom??1,rotation:U?.rotation??0,shakeOffsetX:0,shakeOffsetY:0,shakeRotation:0,viewportWidth:M,viewportHeight:K,entityId:-1,follow:()=>{},unfollow:()=>{},setPosition:()=>{},setZoom:()=>{},setRotation:()=>{},setBounds:()=>{},clearBounds:()=>{},addTrauma:()=>{}};if(k.addResource("cameraState",J),k.addSystem("camera-init").inGroup(q).setOnInitialize((R)=>{let V=R.spawn({camera:{x:U?.x??0,y:U?.y??0,zoom:U?.zoom??1,rotation:U?.rotation??0}});if(O)R.addComponent(V.id,"cameraFollow",{target:-1,...i(O)});if(W)R.addComponent(V.id,"cameraShake",m(W));if(E)R.addComponent(V.id,"cameraBounds",s(E));J.entityId=V.id,J.follow=(N,$)=>{let j={target:o(N),...i($)},Q=R.getComponent(J.entityId,"cameraFollow");if(Q)Q.target=j.target,Q.smoothing=j.smoothing,Q.deadzoneX=j.deadzoneX,Q.deadzoneY=j.deadzoneY,Q.offsetX=j.offsetX,Q.offsetY=j.offsetY;else R.addComponent(J.entityId,"cameraFollow",j)},J.unfollow=()=>{if(R.getComponent(J.entityId,"cameraFollow"))R.removeComponent(J.entityId,"cameraFollow")},J.setPosition=(N,$)=>{let Z=R.getComponent(J.entityId,"camera");if(!Z)return;Z.x=N,Z.y=$},J.setZoom=(N)=>{let $=R.getComponent(J.entityId,"camera");if(!$)return;$.zoom=N},J.setRotation=(N)=>{let $=R.getComponent(J.entityId,"camera");if(!$)return;$.rotation=N},J.setBounds=(N,$,Z,j)=>{let Q=R.getComponent(J.entityId,"cameraBounds");if(Q)Q.minX=N,Q.minY=$,Q.maxX=Z,Q.maxY=j;else R.addComponent(J.entityId,"cameraBounds",{minX:N,minY:$,maxX:Z,maxY:j})},J.clearBounds=()=>{if(R.getComponent(J.entityId,"cameraBounds"))R.removeComponent(J.entityId,"cameraBounds")},J.addTrauma=(N)=>{let $=R.getComponent(J.entityId,"cameraShake");if($)$.trauma=Math.min(1,Math.max(0,$.trauma+N));else R.addComponent(J.entityId,"cameraShake",{...m(!0),trauma:Math.min(1,Math.max(0,N))})}}),k.addSystem("camera-follow").setPriority(400).inPhase(g).inGroup(q).addQuery("cameras",{with:["camera","cameraFollow"]}).setProcess(({queries:R,dt:V,ecs:N})=>{let $=Math.min(1,V);for(let Z of R.cameras){let{camera:j,cameraFollow:Q}=Z.components;if(Q.target<0)continue;let _;try{_=N.getComponent(Q.target,"worldTransform")}catch{continue}if(!_)continue;let z=_.x+Q.offsetX,G=_.y+Q.offsetY,B=z-j.x,b=G-j.y;if(Math.abs(B)>Q.deadzoneX){let H=B>0?1:-1,D=B-H*Q.deadzoneX,F=Math.min(1,Q.smoothing*$);j.x+=D*F}if(Math.abs(b)>Q.deadzoneY){let H=b>0?1:-1,D=b-H*Q.deadzoneY,F=Math.min(1,Q.smoothing*$);j.y+=D*F}}}),k.addSystem("camera-shake-update").setPriority(390).inPhase(g).inGroup(q).addQuery("shakeCameras",{with:["camera","cameraShake"]}).setProcess(({queries:R,dt:V})=>{for(let N of R.shakeCameras){let{cameraShake:$}=N.components;$.trauma=Math.max(0,$.trauma-$.traumaDecay*V)}}),k.addSystem("camera-bounds").setPriority(380).inPhase(g).inGroup(q).addQuery("boundedCameras",{with:["camera","cameraBounds"]}).setProcess(({queries:R})=>{for(let V of R.boundedCameras){let{camera:N,cameraBounds:$}=V.components,Z=J.viewportWidth/(2*N.zoom),j=J.viewportHeight/(2*N.zoom),Q=$.minX+Z,_=$.maxX-Z,z=$.minY+j,G=$.maxY-j;if(Q>_)N.x=($.minX+$.maxX)/2;else N.x=Math.max(Q,Math.min(_,N.x));if(z>G)N.y=($.minY+$.maxY)/2;else N.y=Math.max(z,Math.min(G,N.y))}}),k.addSystem("camera-state-sync").setPriority(370).inPhase(g).inGroup(q).setProcess(({ecs:R})=>{let V=R.getComponent(J.entityId,"camera");if(!V){J.x=0,J.y=0,J.zoom=1,J.rotation=0,J.shakeOffsetX=0,J.shakeOffsetY=0,J.shakeRotation=0;return}J.x=V.x,J.y=V.y,J.zoom=V.zoom,J.rotation=V.rotation;let N=R.getComponent(J.entityId,"cameraShake");if(N&&N.trauma>0){let $=N.trauma*N.trauma;J.shakeOffsetX=N.maxOffsetX*$*(f()*2-1),J.shakeOffsetY=N.maxOffsetY*$*(f()*2-1),J.shakeRotation=N.maxRotation*$*(f()*2-1)}else J.shakeOffsetX=0,J.shakeOffsetY=0,J.shakeRotation=0}),A){let _=function(z){z.preventDefault(),$+=Math.sign(z.deltaY)},{zoomStep:R=0.1,minZoom:V=0.1,maxZoom:N=10}=A,$=0,Z=!1,j,Q;k.addSystem("camera-zoom").setPriority(410).inPhase("preUpdate").inGroup(q).addQuery("cameras",{with:["camera"]}).setOnInitialize((z)=>{let G=z.tryGetResource("inputState"),B=z.tryGetResource("pixiApp");if(!G||!B){console.error("[camera] zoom requires the input plugin and renderer2D plugin. Zoom will be disabled.");return}j=B.canvas,j.addEventListener("wheel",_,{passive:!1}),Q=z.tryGetResource("isoProjection"),Z=!0}).setOnDetach(()=>{if(!Z||!j)return;j.removeEventListener("wheel",_)}).setProcess(({queries:z,ecs:G})=>{if(!Z||$===0)return;let B=$;$=0;let[b]=z.cameras;if(!b)return;let H=b.components.camera,D=G.tryGetResource("inputState");if(!D)return;let F=B>0?1-R:1+R,C=Math.max(V,Math.min(N,H.zoom*Math.pow(F,Math.abs(B))));if(Q&&j){let I=j.getBoundingClientRect(),L=D.pointer.position.x-(I.left+I.width/2),v=D.pointer.position.y-(I.top+I.height/2),X=Q.tileWidth/2,Y=Q.tileHeight/2,h=(H.x-H.y)*X+Q.originX,T=(H.x+H.y)*Y+Q.originY,x=h+L/H.zoom,S=T+v/H.zoom;H.zoom=C;let c=x-L/C,n=S-v/C,d=c-Q.originX,l=n-Q.originY;H.x=d/Q.tileWidth+l/Q.tileHeight,H.y=-d/Q.tileWidth+l/Q.tileHeight}else{let I=p(D.pointer.position.x,D.pointer.position.y,J);H.zoom=C,H.x=I.x-(D.pointer.position.x-J.viewportWidth/2)/C,H.y=I.y-(D.pointer.position.y-J.viewportHeight/2)/C}})}if(y){let{speed:R,actions:V}=y,N=V?.up??"panUp",$=V?.down??"panDown",Z=V?.left??"panLeft",j=V?.right??"panRight",Q=!1;k.addSystem("camera-pan").setPriority(420).inPhase("preUpdate").inGroup(q).setOnInitialize((_)=>{if(!_.tryGetResource("inputState")){console.error("[camera] pan requires the input plugin. Pan will be disabled.");return}Q=!0}).setProcess(({ecs:_,dt:z})=>{if(!Q)return;let G=_.tryGetResource("inputState");if(!G)return;let B=R/J.zoom*z,b=(G.actions.isActive(j)?1:0)-(G.actions.isActive(Z)?1:0),H=(G.actions.isActive($)?1:0)-(G.actions.isActive(N)?1:0);if(b!==0||H!==0)J.setPosition(J.x+b*B,J.y+H*B)})}})}import{Graphics as a}from"pixi.js";import{definePlugin as t}from"ecspresso";function KJ(){return{selectable:!0}}function IJ(P){let{systemGroup:M="selection",priority:K=100,phase:U="preUpdate",clickThreshold:O=5,boxFillColor:W=65280,boxFillAlpha:E=0.15,boxStrokeColor:A=65280,boxStrokeAlpha:y=0.8,selectedTint:q=4521796,renderLayer:g}=P??{},f={color:W,alpha:E},k={color:A,width:1.5,alpha:y};return t("selection").withComponentTypes().withResourceTypes().withLabels().withGroups().requires().install((J)=>{J.addResource("selectionState",{dragStart:{x:0,y:0},boxEntityId:null});let R=null;J.addSystem("selection-input").setPriority(K).inPhase(U).inGroup(M).addQuery("selectables",{with:["selectable","worldTransform"]}).addQuery("currentlySelected",{with:["selected"]}).withResources(["inputState","selectionState","pixiApp"]).setOnInitialize((V)=>{let N=V.getResource("pixiApp");R=($)=>$.preventDefault(),N.canvas.addEventListener("contextmenu",R)}).setOnDetach((V)=>{if(!R)return;V.getResource("pixiApp").canvas.removeEventListener("contextmenu",R),R=null}).setProcess(({queries:V,ecs:N,resources:$})=>{let{inputState:Z,selectionState:j}=$,Q=Z.pointer;if(Q.justPressed(0)){if(j.boxEntityId!==null)N.commands.removeEntity(j.boxEntityId);j.dragStart.x=Q.position.x,j.dragStart.y=Q.position.y;let I=N.spawn({graphics:new a});if(g)N.addComponent(I.id,"renderLayer",g);j.boxEntityId=I.id}if(Q.isDown(0)&&j.boxEntityId!==null){let I=N.getComponent(j.boxEntityId,"graphics");if(!I)return;let L=j.dragStart.x,v=j.dragStart.y,X=Q.position.x,Y=Q.position.y,h=Math.min(L,X),T=Math.min(v,Y),x=Math.abs(X-L),S=Math.abs(Y-v);I.clear(),I.rect(h,T,x,S),I.fill(f),I.stroke(k)}if(!Q.justReleased(0)||j.boxEntityId===null)return;let _=j.dragStart.x,z=j.dragStart.y,G=Q.position.x,B=Q.position.y,b=Math.abs(G-_),H=Math.abs(B-z);for(let I of V.currentlySelected)N.removeComponent(I.id,"selected");let D=b<O&&H<O,F=N.tryGetResource("cameraState"),C=F?p(G,B,F):{x:G,y:B};if(D){let L=null,v=1/0;for(let X of V.selectables){let{worldTransform:Y}=X.components,h=Y.x-C.x,T=Y.y-C.y,x=h*h+T*T;if(x<400&&x<v)v=x,L=X.id}if(L!==null)N.addComponent(L,"selected",!0)}else{let I=F?p(_,z,F):{x:_,y:z},L=Math.min(I.x,C.x),v=Math.max(I.x,C.x),X=Math.min(I.y,C.y),Y=Math.max(I.y,C.y);for(let h of V.selectables){let{worldTransform:T}=h.components;if(T.x>=L&&T.x<=v&&T.y>=X&&T.y<=Y)N.addComponent(h.id,"selected",!0)}}N.commands.removeEntity(j.boxEntityId),j.boxEntityId=null}),J.addSystem("selection-visual").setPriority(K).inPhase("render").inGroup(M).addQuery("selectedUnits",{with:["selected","sprite"]}).setOnEntityEnter("selectedUnits",({entity:V})=>{V.components.sprite.tint=q}).addQuery("deselectedUnits",{with:["selectable","sprite"],without:["selected"]}).setOnEntityEnter("deselectedUnits",({entity:V})=>{V.components.sprite.tint=16777215})})}export{IJ as createSelectionPlugin,KJ as createSelectable};
2
2
 
3
- //# debugId=206042F83F56CEF464756E2164756E21
3
+ //# debugId=4FFF849396A9F22D64756E2164756E21
4
4
  //# sourceMappingURL=selection.js.map