Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(sdk): perception - sight/FOV sensing for AI agents (AI4)

esengined4c032488ee1
diff --git a/examples/enemy-ai/assets/scenes/main.esscene b/examples/enemy-ai/assets/scenes/main.esscene
index 844b06707..d12316915 100644
--- a/examples/enemy-ai/assets/scenes/main.esscene
+++ b/examples/enemy-ai/assets/scenes/main.esscene
@@ -21,7 +21,8 @@
"components": [
{ "type": "Transform", "data": { "position": { "x": -200, "y": -120, "z": 0 } } },
{ "type": "Sprite", "data": { "size": { "x": 40, "y": 40 }, "color": { "r": 0.3, "g": 0.8, "b": 1, "a": 1 }, "layer": 2 } },
- { "type": "PlayerControl", "data": { "speed": 240 } }
+ { "type": "PlayerControl", "data": { "speed": 240 } },
+ { "type": "PerceptionTarget", "data": {} }
],
"visible": true
},
@@ -34,7 +35,8 @@
{ "type": "Transform", "data": { "position": { "x": 200, "y": 150, "z": 0 } } },
{ "type": "Sprite", "data": { "size": { "x": 36, "y": 36 }, "color": { "r": 0.9, "g": 0.35, "b": 0.3, "a": 1 }, "layer": 2 } },
{ "type": "StateMachineAgent", "data": { "fsm": "enemy" } },
- { "type": "NavAgent", "data": { "speed": 120, "repathInterval": 0.35 } }
+ { "type": "NavAgent", "data": { "speed": 120, "repathInterval": 0.35 } },
+ { "type": "Perceiver", "data": { "range": 260, "fovDegrees": 360 } }
],
"visible": true
},
@@ -47,7 +49,8 @@
{ "type": "Transform", "data": { "position": { "x": 260, "y": -160, "z": 0 } } },
{ "type": "Sprite", "data": { "size": { "x": 36, "y": 36 }, "color": { "r": 0.95, "g": 0.55, "b": 0.25, "a": 1 }, "layer": 2 } },
{ "type": "StateMachineAgent", "data": { "fsm": "enemy" } },
- { "type": "NavAgent", "data": { "speed": 95, "repathInterval": 0.5 } }
+ { "type": "NavAgent", "data": { "speed": 95, "repathInterval": 0.5 } },
+ { "type": "Perceiver", "data": { "range": 220, "fovDegrees": 360 } }
],
"visible": true
}
diff --git a/examples/enemy-ai/src/enemy.ts b/examples/enemy-ai/src/enemy.ts
index defcd5fa5..3796e6111 100644
--- a/examples/enemy-ai/src/enemy.ts
+++ b/examples/enemy-ai/src/enemy.ts
@@ -1,28 +1,29 @@
import {
- defineSystem, Query, Res, Transform, GetWorld,
- registerFsm, registerAction, setNavDestination, Nav, NavGrid, AiFsm, StateMachineAgent,
+ defineSystem, Res,
+ registerFsm, registerAction, registerCondition, setNavDestination, Nav, NavGrid, Perception,
} from 'esengine';
-import { PlayerControl } from './components';
-// The enemy brain, as data: patrol until the player is sensed, chase while seen,
-// break off when lost. `seesPlayer` is a blackboard flag the perception system
-// writes; `chase` is a named action resolved from the registry below.
+// The enemy brain reads the Perception component that the engine's built-in
+// perception system writes (sight range + field-of-view over PerceptionTargets),
+// so sensing and decision-making stay decoupled — no per-project sensing code.
+registerCondition('seesPlayer', ctx => ctx.has(Perception) && ctx.get(Perception).visible);
+registerCondition('lostPlayer', ctx => !ctx.has(Perception) || !ctx.get(Perception).visible);
+
+// Patrol until the player is seen, chase while seen, break off when lost.
registerFsm('enemy', {
initial: 'Patrol',
states: [
- { name: 'Patrol', transitions: [{ to: 'Chase', guard: { key: 'seesPlayer', op: 'truthy' } }] },
- { name: 'Chase', onUpdate: 'chase', transitions: [{ to: 'Patrol', guard: { key: 'seesPlayer', op: 'falsy' } }] },
+ { name: 'Patrol', transitions: [{ to: 'Chase', condition: 'seesPlayer' }] },
+ { name: 'Chase', onUpdate: 'chase', transitions: [{ to: 'Patrol', condition: 'lostPlayer' }] },
],
});
-// Chase leaf: steer this agent's NavAgent at the player's live position. The
+// Chase leaf: steer this agent's NavAgent at the last-seen player position. The
// nav layer plans the A* path and moves the body — the action only sets intent.
-registerAction('chase', (ctx) => {
- const players = ctx.world.getEntitiesWithComponents([PlayerControl, Transform]);
- const player = players[0];
- if (player === undefined) return;
- const p = ctx.world.get(player, Transform);
- setNavDestination(ctx.world, ctx.entity, { x: p.position.x, y: p.position.y });
+registerAction('chase', ctx => {
+ if (!ctx.has(Perception)) return;
+ const per = ctx.get(Perception);
+ if (per.visible) setNavDestination(ctx.world, ctx.entity, { x: per.targetX, y: per.targetY });
});
/** Install an open navigation grid over the arena on startup. */
@@ -33,20 +34,3 @@ export const setupNavGridSystem = defineSystem(
},
{ name: 'SetupNavGridSystem' },
);
-
-const SENSE_RANGE = 180;
-
-/** Perception: set each enemy's `seesPlayer` blackboard flag that the FSM guard reads. */
-export const enemySenseSystem = defineSystem(
- [Query(Transform, StateMachineAgent), Res(AiFsm), GetWorld()],
- (enemies, aifsm, world) => {
- const players = world.getEntitiesWithComponents([PlayerControl, Transform]);
- if (players.length === 0) return;
- const pp = world.get(players[0], Transform).position;
- for (const [entity, tf] of enemies) {
- const d = Math.hypot(pp.x - tf.position.x, pp.y - tf.position.y);
- aifsm.blackboard(entity).set('seesPlayer', d < SENSE_RANGE);
- }
- },
- { name: 'EnemySenseSystem' },
-);
diff --git a/examples/enemy-ai/src/main.ts b/examples/enemy-ai/src/main.ts
index 6bd2037a9..43ecee505 100644
--- a/examples/enemy-ai/src/main.ts
+++ b/examples/enemy-ai/src/main.ts
@@ -1,10 +1,9 @@
import { addSystemToSchedule, Schedule } from 'esengine';
import { keyboardMoveSystem } from './player';
-import { setupNavGridSystem, enemySenseSystem } from './enemy';
+import { setupNavGridSystem } from './enemy';
-// The nav grid is built once; perception + player movement run every frame. The
-// FSM tick (StateMachineAgent) and nav follow (NavAgent) are driven by the
-// engine's built-in fsm/nav plugins — no per-project wiring needed.
+// Only project-specific systems are registered here: the player controller and
+// the one-time nav grid. Perception, the FSM tick (StateMachineAgent) and nav
+// follow (NavAgent) are the engine's built-in AI plugins — no wiring needed.
addSystemToSchedule(Schedule.Startup, setupNavGridSystem);
addSystemToSchedule(Schedule.Update, keyboardMoveSystem);
-addSystemToSchedule(Schedule.Update, enemySenseSystem);
diff --git a/sdk/src/ai/index.ts b/sdk/src/ai/index.ts
index 5f258b0f9..a6e35749f 100644
--- a/sdk/src/ai/index.ts
+++ b/sdk/src/ai/index.ts
@@ -56,3 +56,6 @@ export {
agentBtBlackboard,
type AiWorldView,
} from './bt/BtPlugin';
+
+// Perception: sight/FOV sensing into a Perception component (read by FSM/BT).
+export * from './perception';
diff --git a/sdk/src/ai/perception/PerceptionPlugin.ts b/sdk/src/ai/perception/PerceptionPlugin.ts
new file mode 100644
index 000000000..2dccf0e2a
--- /dev/null
+++ b/sdk/src/ai/perception/PerceptionPlugin.ts
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file PerceptionPlugin.ts
+ * @brief Writes each Perceiver's view of the nearest visible PerceptionTarget
+ * into its Perception component. Runs in PreUpdate (before FSM/BT), so a
+ * decision system reads a fresh Perception the same frame.
+ *
+ * `stepPerception` is extracted to unit-test against a fake world. Line
+ * of sight uses a physics raycast when a PhysicsAPI is present, and is
+ * skipped (range + FOV only) otherwise — no hard physics dependency.
+ */
+
+import type { App, Plugin } from '../../app';
+import type { Entity } from '../../types';
+import { defineSystem, Schedule, GetWorld } from '../../system';
+import { playModeOnly } from '../../env';
+import { Transform } from '../../component';
+import type { AnyComponentDef, ComponentData } from '../../component';
+import { PhysicsAPI, type Physics } from '../../physics';
+import { senseTarget, facingFromQuat } from './sense';
+import { Perceiver, Perception, PerceptionTarget, type PerceptionData } from './components';
+
+/** The slice of `World` the perception step needs — lets tests inject a fake. */
+export interface PerceptionWorldView {
+ getEntitiesWithComponents(components: readonly AnyComponentDef[]): Entity[];
+ get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
+ set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;
+ has(entity: Entity, component: AnyComponentDef): boolean;
+ insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): unknown;
+}
+
+export type LosCheck = (ox: number, oy: number, tx: number, ty: number) => boolean;
+
+/** Update every Perceiver's Perception with the nearest visible target. */
+export function stepPerception(world: PerceptionWorldView, isBlocked?: LosCheck): void {
+ const targets = world.getEntitiesWithComponents([PerceptionTarget, Transform]).map(e => {
+ const t = world.get(e, Transform);
+ return { e, x: t.position.x, y: t.position.y };
+ });
+
+ for (const e of world.getEntitiesWithComponents([Perceiver, Transform])) {
+ const cfg = world.get(e, Perceiver);
+ const tf = world.get(e, Transform);
+ const ox = tf.position.x;
+ const oy = tf.position.y;
+ const facing = facingFromQuat(tf.rotation.z, tf.rotation.w);
+ const halfFov = ((cfg.fovDegrees * Math.PI) / 180) / 2;
+
+ let best: { x: number; y: number; distance: number; dirX: number; dirY: number } | null = null;
+ for (const t of targets) {
+ if (t.e === e) continue;
+ const r = senseTarget(ox, oy, facing, t.x, t.y, cfg.range, halfFov, isBlocked);
+ if (r.visible && (!best || r.distance < best.distance)) {
+ best = { x: t.x, y: t.y, distance: r.distance, dirX: r.dirX, dirY: r.dirY };
+ }
+ }
+
+ const p: PerceptionData = best
+ ? { visible: true, distance: best.distance, targetX: best.x, targetY: best.y, dirX: best.dirX, dirY: best.dirY }
+ : { visible: false, distance: 0, targetX: 0, targetY: 0, dirX: 0, dirY: 0 };
+
+ if (world.has(e, Perception)) world.set(e, Perception, p);
+ else world.insert(e, Perception, p);
+ }
+}
+
+/** Build a raycast-backed line-of-sight check. Occluded if anything is hit before the target. */
+export function makeLosCheck(physics: Physics): LosCheck {
+ return (ox, oy, tx, ty) => {
+ const dx = tx - ox;
+ const dy = ty - oy;
+ const dist = Math.hypot(dx, dy);
+ if (dist === 0) return false;
+ const hits = physics.raycast({ x: ox, y: oy }, { x: dx / dist, y: dy / dist }, dist);
+ // A hit clearly short of the target blocks the view (the last ~2% is the target itself).
+ return hits.some(h => h.fraction < 0.98);
+ };
+}
+
+export class PerceptionPlugin implements Plugin {
+ name = 'perception';
+
+ build(app: App): void {
+ app.addSystemToSchedule(
+ Schedule.PreUpdate,
+ defineSystem(
+ [GetWorld()],
+ world => {
+ const physics = app.hasResource(PhysicsAPI) ? app.getResource<Physics>(PhysicsAPI) : null;
+ stepPerception(world as PerceptionWorldView, physics ? makeLosCheck(physics) : undefined);
+ },
+ { name: 'PerceptionSystem' },
+ ),
+ { runIf: playModeOnly },
+ );
+ }
+}
+
+export const perceptionPlugin = new PerceptionPlugin();
diff --git a/sdk/src/ai/perception/components.ts b/sdk/src/ai/perception/components.ts
new file mode 100644
index 000000000..b631576cd
--- /dev/null
+++ b/sdk/src/ai/perception/components.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file components.ts
+ * @brief Perception components. A `Perceiver` senses the nearest visible
+ * `PerceptionTarget`; the system writes the result into `Perception`,
+ * which FSM conditions / BT leaves read via `ctx.get(Perception)` —
+ * perception flows through ECS data, not a side channel.
+ */
+
+import { defineComponent, defineTag } from '../../component';
+
+export interface PerceiverData {
+ /** Sight range in world pixels. */
+ range: number;
+ /** Field-of-view cone in degrees; 360 = omnidirectional. */
+ fovDegrees: number;
+}
+
+export const Perceiver = defineComponent<PerceiverData>('Perceiver', {
+ range: 220,
+ fovDegrees: 360,
+}, {
+ fields: {
+ range: { min: 0, unit: 'px', category: 'Perception' },
+ fovDegrees: { min: 0, max: 360, unit: '°', category: 'Perception' },
+ },
+});
+
+export interface PerceptionData {
+ /** A target is currently seen. */
+ visible: boolean;
+ /** Distance to the seen target (0 when none). */
+ distance: number;
+ /** Seen target position in world pixels. */
+ targetX: number;
+ targetY: number;
+ /** Unit direction observer→target. */
+ dirX: number;
+ dirY: number;
+}
+
+export const Perception = defineComponent<PerceptionData>('Perception', {
+ visible: false,
+ distance: 0,
+ targetX: 0,
+ targetY: 0,
+ dirX: 0,
+ dirY: 0,
+}, {
+ // Runtime-only: the system rewrites it every frame.
+ transient: true,
+ fields: {
+ visible: { advanced: true, tooltip: 'A target is seen (runtime, read-only).' },
+ },
+});
+
+/** Tags an entity as sensable by Perceivers. */
+export const PerceptionTarget = defineTag('PerceptionTarget');
diff --git a/sdk/src/ai/perception/index.ts b/sdk/src/ai/perception/index.ts
new file mode 100644
index 000000000..70d045047
--- /dev/null
+++ b/sdk/src/ai/perception/index.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts
+ * @brief Perception barrel — pure sensing core + components + plugin.
+ */
+
+export { senseTarget, facingFromQuat, normalizeAngle, type SenseResult } from './sense';
+export {
+ Perceiver, Perception, PerceptionTarget,
+ type PerceiverData, type PerceptionData,
+} from './components';
+export {
+ PerceptionPlugin, perceptionPlugin, stepPerception, makeLosCheck,
+ type PerceptionWorldView, type LosCheck,
+} from './PerceptionPlugin';
diff --git a/sdk/src/ai/perception/sense.ts b/sdk/src/ai/perception/sense.ts
new file mode 100644
index 000000000..2b4318e22
--- /dev/null
+++ b/sdk/src/ai/perception/sense.ts
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file sense.ts
+ * @brief Line-of-sight / field-of-view sensing — pure geometry, unit-testable.
+ *
+ * `senseTarget` combines a range check, a cone (field-of-view) check, and an
+ * optional occlusion callback (`isBlocked`, backed by a physics raycast in the
+ * engine, a fake in tests) so the core stays free of any physics/wasm type. The
+ * engine's perception system writes the result to a `Perception` component that
+ * FSM conditions / BT leaves read via `ctx.get(Perception)`.
+ */
+
+export interface SenseResult {
+ /** Target is within range, inside the cone, and not occluded. */
+ visible: boolean;
+ /** Distance to the target (always set, even when not visible). */
+ distance: number;
+ /** Unit direction observer→target, or (0,0) when not visible. */
+ dirX: number;
+ dirY: number;
+}
+
+/** 2D facing angle (radians) from a Transform quaternion's z/w (rotation about Z). */
+export function facingFromQuat(z: number, w: number): number {
+ return 2 * Math.atan2(z, w);
+}
+
+/** Wrap an angle to (-π, π]. */
+export function normalizeAngle(a: number): number {
+ const twoPi = Math.PI * 2;
+ a %= twoPi;
+ if (a > Math.PI) a -= twoPi;
+ else if (a <= -Math.PI) a += twoPi;
+ return a;
+}
+
+/**
+ * Sense `target` from `observer`. `halfFov` is half the field-of-view in radians
+ * (≥ π means omnidirectional). `isBlocked(ox,oy,tx,ty)` returns true when the
+ * line of sight is occluded. An observer standing on the target is visible.
+ */
+export function senseTarget(
+ ox: number, oy: number, facing: number,
+ tx: number, ty: number,
+ range: number, halfFov: number,
+ isBlocked?: (ox: number, oy: number, tx: number, ty: number) => boolean,
+): SenseResult {
+ const dx = tx - ox;
+ const dy = ty - oy;
+ const dist = Math.hypot(dx, dy);
+ if (dist === 0) return { visible: true, distance: 0, dirX: 0, dirY: 0 };
+
+ const miss: SenseResult = { visible: false, distance: dist, dirX: 0, dirY: 0 };
+ if (dist > range) return miss;
+ if (halfFov < Math.PI) {
+ const delta = Math.abs(normalizeAngle(Math.atan2(dy, dx) - facing));
+ if (delta > halfFov) return miss;
+ }
+ if (isBlocked?.(ox, oy, tx, ty)) return miss;
+ return { visible: true, distance: dist, dirX: dx / dist, dirY: dy / dist };
+}
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 9de5d860d..30353a90e 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -503,3 +503,23 @@ export {
type BtRunState,
type BehaviorTreeAgentData,
} from './ai';
+
+// =============================================================================
+// AI — Perception (sight/FOV sensing into a Perception component)
+// =============================================================================
+
+export {
+ senseTarget,
+ facingFromQuat,
+ normalizeAngle,
+ Perceiver,
+ Perception,
+ PerceptionTarget,
+ PerceptionPlugin,
+ perceptionPlugin,
+ stepPerception,
+ makeLosCheck,
+ type SenseResult,
+ type PerceiverData,
+ type PerceptionData,
+} from './ai';
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index 2b37b552c..6bf0c25c5 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -12,7 +12,7 @@ import { postProcessPlugin } from './postprocess';
import { timelinePlugin } from './timeline';
import { timerPlugin } from './timer';
import { lifecyclePlugin } from './lifecycle';
-import { navPlugin, fsmPlugin, btPlugin } from './ai';
+import { navPlugin, fsmPlugin, btPlugin, perceptionPlugin } from './ai';
import { SpinePlugin } from './spine';
import { createFetchSideModuleHost, type SideModuleHost } from './sideModules';
@@ -58,7 +58,7 @@ export interface CreateWebAppOptions extends WebAppOptions {
wasmBaseUrl?: string;
}
-const basePlugins = [timerPlugin, lifecyclePlugin(), animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, fsmPlugin, btPlugin, navPlugin];
+const basePlugins = [timerPlugin, lifecyclePlugin(), animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, perceptionPlugin, fsmPlugin, btPlugin, navPlugin];
export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptions): App {
const sideModules: SideModuleHost | undefined = options?.sideModules
diff --git a/sdk/tests/perception-sense.test.ts b/sdk/tests/perception-sense.test.ts
new file mode 100644
index 000000000..e3cb7648d
--- /dev/null
+++ b/sdk/tests/perception-sense.test.ts
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { senseTarget, facingFromQuat, normalizeAngle } from '../src/ai/perception/sense';
+
+const OMNI = Math.PI; // halfFov ≥ π → omnidirectional
+
+describe('senseTarget', () => {
+ it('sees a target in range with clear line of sight', () => {
+ const r = senseTarget(0, 0, 0, 30, 40, 100, OMNI);
+ expect(r.visible).toBe(true);
+ expect(r.distance).toBeCloseTo(50);
+ expect(r.dirX).toBeCloseTo(0.6);
+ expect(r.dirY).toBeCloseTo(0.8);
+ });
+
+ it('does not see a target out of range', () => {
+ const r = senseTarget(0, 0, 0, 200, 0, 100, OMNI);
+ expect(r.visible).toBe(false);
+ expect(r.distance).toBeCloseTo(200);
+ });
+
+ it('respects the field-of-view cone', () => {
+ // Facing +X (0 rad), 45° half-cone. Target straight ahead is seen…
+ expect(senseTarget(0, 0, 0, 100, 0, 200, Math.PI / 4).visible).toBe(true);
+ // …target directly behind is not.
+ expect(senseTarget(0, 0, 0, -100, 0, 200, Math.PI / 4).visible).toBe(false);
+ // …target to the side, just outside the cone.
+ expect(senseTarget(0, 0, 0, 0, 100, 200, Math.PI / 4).visible).toBe(false);
+ });
+
+ it('honors an occlusion callback', () => {
+ const blocked = senseTarget(0, 0, 0, 50, 0, 100, OMNI, () => true);
+ expect(blocked.visible).toBe(false);
+ const clear = senseTarget(0, 0, 0, 50, 0, 100, OMNI, () => false);
+ expect(clear.visible).toBe(true);
+ });
+
+ it('treats standing on the target as visible', () => {
+ const r = senseTarget(10, 10, 0, 10, 10, 100, Math.PI / 8);
+ expect(r.visible).toBe(true);
+ expect(r.distance).toBe(0);
+ });
+});
+
+describe('facingFromQuat', () => {
+ it('reads the 2D angle from a Z rotation quaternion', () => {
+ expect(facingFromQuat(0, 1)).toBeCloseTo(0); // identity
+ // 90° about Z: z=sin(45°), w=cos(45°)
+ expect(facingFromQuat(Math.SQRT1_2, Math.SQRT1_2)).toBeCloseTo(Math.PI / 2);
+ });
+});
+
+describe('normalizeAngle', () => {
+ it('wraps to (-π, π]', () => {
+ expect(normalizeAngle(0)).toBeCloseTo(0);
+ expect(normalizeAngle(Math.PI * 1.5)).toBeCloseTo(-Math.PI / 2);
+ expect(normalizeAngle(-Math.PI * 1.5)).toBeCloseTo(Math.PI / 2);
+ });
+});
diff --git a/sdk/tests/perception-step.test.ts b/sdk/tests/perception-step.test.ts
new file mode 100644
index 000000000..bfa3870e5
--- /dev/null
+++ b/sdk/tests/perception-step.test.ts
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { Transform } from '../src/component';
+import type { Entity } from '../src/types';
+import type { AnyComponentDef, ComponentData } from '../src/component';
+import { Perceiver, Perception, PerceptionTarget } from '../src/ai/perception/components';
+import { stepPerception, type PerceptionWorldView } from '../src/ai/perception/PerceptionPlugin';
+
+class FakeWorld implements PerceptionWorldView {
+ private store = new Map<string, unknown>();
+ private next = 1;
+ private ids: Entity[] = [];
+
+ spawn(comps: Array<[AnyComponentDef, unknown]>): Entity {
+ const e = this.next++ as Entity;
+ for (const [def, data] of comps) this.store.set(`${e}:${def._name}`, data);
+ this.ids.push(e);
+ return e;
+ }
+ getEntitiesWithComponents(defs: readonly AnyComponentDef[]): Entity[] {
+ return this.ids.filter(e => defs.every(d => this.store.has(`${e}:${d._name}`)));
+ }
+ get<C extends AnyComponentDef>(e: Entity, def: C): ComponentData<C> {
+ return this.store.get(`${e}:${def._name}`) as ComponentData<C>;
+ }
+ set<C extends AnyComponentDef>(e: Entity, def: C, data: ComponentData<C>): void {
+ this.store.set(`${e}:${def._name}`, data);
+ }
+ has(e: Entity, def: AnyComponentDef): boolean {
+ return this.store.has(`${e}:${def._name}`);
+ }
+ insert<C extends AnyComponentDef>(e: Entity, def: C, data?: Partial<ComponentData<C>>): unknown {
+ this.store.set(`${e}:${def._name}`, data);
+ return data;
+ }
+}
+
+const tf = (x: number, y: number) => ({ position: { x, y, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 } });
+const spawnPerceiver = (w: FakeWorld, x: number, y: number, range = 200, fov = 360) =>
+ w.spawn([[Perceiver, Perceiver.create({ range, fovDegrees: fov })], [Transform, tf(x, y)]]);
+const spawnTarget = (w: FakeWorld, x: number, y: number) =>
+ w.spawn([[PerceptionTarget, {}], [Transform, tf(x, y)]]);
+
+describe('stepPerception', () => {
+ it('writes a visible target into the Perception component', () => {
+ const w = new FakeWorld();
+ const p = spawnPerceiver(w, 0, 0);
+ spawnTarget(w, 50, 0);
+ stepPerception(w);
+ const per = w.get(p, Perception);
+ expect(per.visible).toBe(true);
+ expect(per.distance).toBeCloseTo(50);
+ expect(per.targetX).toBe(50);
+ expect(per.dirX).toBeCloseTo(1);
+ });
+
+ it('reports not visible when the target is out of range', () => {
+ const w = new FakeWorld();
+ const p = spawnPerceiver(w, 0, 0, 100);
+ spawnTarget(w, 300, 0);
+ stepPerception(w);
+ expect(w.get(p, Perception).visible).toBe(false);
+ });
+
+ it('honors line-of-sight occlusion', () => {
+ const w = new FakeWorld();
+ const p = spawnPerceiver(w, 0, 0);
+ spawnTarget(w, 80, 0);
+ stepPerception(w, () => true); // everything blocked
+ expect(w.get(p, Perception).visible).toBe(false);
+ stepPerception(w, () => false); // clear
+ expect(w.get(p, Perception).visible).toBe(true);
+ });
+
+ it('picks the nearest visible target', () => {
+ const w = new FakeWorld();
+ const p = spawnPerceiver(w, 0, 0);
+ spawnTarget(w, 150, 0);
+ spawnTarget(w, 60, 0);
+ stepPerception(w);
+ expect(w.get(p, Perception).targetX).toBe(60);
+ });
+});