refactor(02-06): align pathfinding structure with user scope

This commit is contained in:
AncTe committed 2026-09-10 11:21:53 +08:00
1 parent 97a559cdf8
commit 26f7ad6b2e
23 files changed
+556 -992

No files matched your search

+3 -6
View File
@@ -75,9 +75,8 @@ import {
} from './legacy';
import { ILoadProgressTotal, LoadProgressTotal } from '@motajs/loader';
import { isNil } from 'lodash-es';
import { logger } from '@motajs/common';
import { DirectionMapper, IDirectionMapper, logger } from '@motajs/common';
import { DefaultHeroMoveTopImpl } from './hero';
import { HeroPathfinding } from './path';
export class CoreState implements ICoreState {
// Layer 0 公共层,最底层的接口,不会依赖任何其他内容,一般是工具性接口及不需要存档的数据
@@ -88,6 +87,7 @@ export class CoreState implements ICoreState {
readonly itemStore: IItemStore<IHeroAttr, LegacyItemData>;
readonly mapStore: IMapStore;
readonly eventStore: IGameEventStore;
readonly directionMapper: IDirectionMapper;
// Layer 1 数据层,所有可存档内容都在这,一般用于数据存储
readonly maps: IMapState;
@@ -102,9 +102,6 @@ export class CoreState implements ICoreState {
// Layer 3 用户层,也就是最顶层的内容,一般仅用于初始化以及仅供渲染端调用的顶层模块
readonly loadProgress: ILoadProgressTotal;
readonly dataLoader: IMotaDataLoader;
/** 勇士寻路入口 */
readonly pathfinding: HeroPathfinding;
/** 可存档对象映射 */
private readonly saveables: Map<string, ISaveableContent<any>> = new Map();
/** 所有已添加的可存档对象 */
@@ -153,6 +150,7 @@ export class CoreState implements ICoreState {
// 游戏事件
const eventStore = new GameEventStore();
this.eventStore = eventStore;
this.directionMapper = new DirectionMapper();
// TODO: 后续在此初始化路径注册外部序列化事件定义与地图事件 id 绑定。
//#endregion
@@ -238,7 +236,6 @@ export class CoreState implements ICoreState {
// 勇士顶层初始化
const heroMoveTopImpl = new DefaultHeroMoveTopImpl(this);
this.hero.location.mover.useTopImplementation(heroMoveTopImpl);
this.pathfinding = new HeroPathfinding(this, heroMoveTopImpl);
//#endregion
}
@@ -1,2 +1,3 @@
export * from './moverImpl';
export * from './predicate';
export * from './types';
+4 -115
View File
@@ -7,12 +7,12 @@ import {
IHeroMoveTopHandler,
IHeroMoveTopImpl,
IMapState,
IPassCheckHandler,
IPassPredicate,
IReadonlyTileBase
} from '@user/data-base';
import { EventTrigger, FaceDirection, PassBit } from '@user/data-common';
import { EventTrigger } from '@user/data-common';
import { IGameEventExecutor, IStateSystem } from '@user/data-system';
import { DefaultPassPredicate, DefaultPassPredicateImpl } from './predicate';
import { isNil } from 'lodash-es';
interface IEventSource {
@@ -22,129 +22,18 @@ interface IEventSource {
readonly tile: IReadonlyTileBase | null;
}
interface IDefaultHeroPassPredicate extends IPassPredicate {}
class DefaultHeroPassPredicate implements IDefaultHeroPassPredicate {
constructor(private readonly maps: IMapState) {}
private directionToPassBit(dir: FaceDirection): number {
switch (dir) {
case FaceDirection.Up:
return PassBit.Up;
case FaceDirection.Right:
return PassBit.Right;
case FaceDirection.Down:
return PassBit.Down;
case FaceDirection.Left:
return PassBit.Left;
default:
return 0;
}
}
private oppositeDirection(dir: FaceDirection): FaceDirection {
switch (dir) {
case FaceDirection.Up:
return FaceDirection.Down;
case FaceDirection.Right:
return FaceDirection.Left;
case FaceDirection.Down:
return FaceDirection.Up;
case FaceDirection.Left:
return FaceDirection.Right;
case FaceDirection.LeftUp:
return FaceDirection.RightDown;
case FaceDirection.RightUp:
return FaceDirection.LeftDown;
case FaceDirection.LeftDown:
return FaceDirection.RightUp;
case FaceDirection.RightDown:
return FaceDirection.LeftUp;
default:
return FaceDirection.Unknown;
}
}
canPass(handler: IPassCheckHandler): boolean {
const { currLoc, nextLoc, direction, floorId } = handler;
if (isNil(floorId)) return false;
if (
direction === FaceDirection.LeftDown ||
direction === FaceDirection.LeftUp ||
direction === FaceDirection.RightDown ||
direction === FaceDirection.RightUp
) {
return true;
}
const map = this.maps.getMap(floorId);
if (!map) return false;
const event = map.eventLayer;
if (!event) return false;
const { x, y } = currLoc;
const { x: nx, y: ny } = nextLoc;
const leaveMask = this.directionToPassBit(direction);
const enterMask = this.directionToPassBit(
this.oppositeDirection(direction)
);
let canLeave = true;
let canEnter = true;
const curr = event.getLocationData(x, y);
const next = event.getLocationData(nx, ny);
const currRaw = curr?.static?.raw();
const nextRaw = next?.static?.raw();
if (currRaw) canLeave = !!(leaveMask & currRaw.pass.outPass);
if (nextRaw) canEnter = !!(enterMask & nextRaw.pass.inPass);
if (!canLeave || !canEnter) return false;
for (const layer of map.layerList) {
if (layer === event) continue;
const curr = layer.getLocationData(x, y);
const next = layer.getLocationData(nx, ny);
let canLeave = true;
let canEnter = true;
const currRaw = curr?.static?.raw();
const nextRaw = next?.static?.raw();
if (currRaw?.pass.onlyEvents) {
canLeave = !!(leaveMask & currRaw.pass.outPass);
}
if (nextRaw?.pass.onlyEvents) {
canEnter = !!(enterMask & nextRaw.pass.inPass);
}
if (!canLeave || !canEnter) return false;
}
return true;
}
shouldHit(handler: IPassCheckHandler): boolean {
const { nextLoc, floorId } = handler;
if (isNil(floorId)) return false;
const map = this.maps.getMap(floorId);
if (!map) return false;
const eventLayer = map.eventLayer;
if (!eventLayer) return false;
const next = eventLayer.getLocationData(nextLoc.x, nextLoc.y);
const nextRaw = next?.static?.raw();
return !!nextRaw && !nextRaw.eventPass;
}
}
export class DefaultHeroMoveTopImpl implements IHeroMoveTopImpl {
/** 地图存储对象 */
private readonly maps: IMapState;
/** 游戏事件执行器 */
private readonly executor: IGameEventExecutor;
/** 勇士移动使用的通行性谓词 */
private readonly passPredicate: IPassPredicate;
private readonly passPredicate: DefaultPassPredicate;
constructor(state: IStateSystem) {
this.maps = state.maps;
this.executor = state.eventSystem.executor;
this.passPredicate = new DefaultHeroPassPredicate(this.maps);
this.passPredicate = new DefaultPassPredicateImpl(this.maps);
}
//#region 通行性判断
@@ -0,0 +1,114 @@
import { IMapState, IPassCheckHandler, IPassPredicate } from '@user/data-base';
import { FaceDirection, PassBit } from '@user/data-common';
import { isNil } from 'lodash-es';
export interface DefaultPassPredicate extends IPassPredicate {}
export class DefaultPassPredicateImpl implements DefaultPassPredicate {
constructor(private readonly maps: IMapState) {}
private directionToPassBit(dir: FaceDirection): number {
switch (dir) {
case FaceDirection.Up:
return PassBit.Up;
case FaceDirection.Right:
return PassBit.Right;
case FaceDirection.Down:
return PassBit.Down;
case FaceDirection.Left:
return PassBit.Left;
default:
return 0;
}
}
private oppositeDirection(dir: FaceDirection): FaceDirection {
switch (dir) {
case FaceDirection.Up:
return FaceDirection.Down;
case FaceDirection.Right:
return FaceDirection.Left;
case FaceDirection.Down:
return FaceDirection.Up;
case FaceDirection.Left:
return FaceDirection.Right;
case FaceDirection.LeftUp:
return FaceDirection.RightDown;
case FaceDirection.RightUp:
return FaceDirection.LeftDown;
case FaceDirection.LeftDown:
return FaceDirection.RightUp;
case FaceDirection.RightDown:
return FaceDirection.LeftUp;
default:
return FaceDirection.Unknown;
}
}
canPass(handler: IPassCheckHandler): boolean {
const { currLoc, nextLoc, direction, floorId } = handler;
if (isNil(floorId)) return false;
if (
direction === FaceDirection.LeftDown ||
direction === FaceDirection.LeftUp ||
direction === FaceDirection.RightDown ||
direction === FaceDirection.RightUp
) {
return true;
}
const map = this.maps.getMap(floorId);
if (!map) return false;
const event = map.eventLayer;
if (!event) return false;
const { x, y } = currLoc;
const { x: nx, y: ny } = nextLoc;
const leaveMask = this.directionToPassBit(direction);
const enterMask = this.directionToPassBit(
this.oppositeDirection(direction)
);
let canLeave = true;
let canEnter = true;
const curr = event.getLocationData(x, y);
const next = event.getLocationData(nx, ny);
const currRaw = curr?.static?.raw();
const nextRaw = next?.static?.raw();
if (currRaw) canLeave = !!(leaveMask & currRaw.pass.outPass);
if (nextRaw) canEnter = !!(enterMask & nextRaw.pass.inPass);
if (!canLeave || !canEnter) return false;
for (const layer of map.layerList) {
if (layer === event) continue;
const curr = layer.getLocationData(x, y);
const next = layer.getLocationData(nx, ny);
let canLeave = true;
let canEnter = true;
const currRaw = curr?.static?.raw();
const nextRaw = next?.static?.raw();
if (currRaw?.pass.onlyEvents) {
canLeave = !!(leaveMask & currRaw.pass.outPass);
}
if (nextRaw?.pass.onlyEvents) {
canEnter = !!(enterMask & nextRaw.pass.inPass);
}
if (!canLeave || !canEnter) return false;
}
return true;
}
shouldHit(handler: IPassCheckHandler): boolean {
const { nextLoc, floorId } = handler;
if (isNil(floorId)) return false;
const map = this.maps.getMap(floorId);
if (!map) return false;
const eventLayer = map.eventLayer;
if (!eventLayer) return false;
const next = eventLayer.getLocationData(nextLoc.x, nextLoc.y);
const nextRaw = next?.static?.raw();
return !!nextRaw && !nextRaw.eventPass;
}
}
-1
View File
@@ -1,6 +1,5 @@
export * from './enemy';
export * from './hero';
export * from './path';
export * from './core';
export * from './ins';
@@ -1,358 +0,0 @@
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { ITileStore } from '@user/data-common';
vi.hoisted(() => {
vi.stubGlobal('main', { replayChecking: true });
vi.stubGlobal('location', { origin: 'http://localhost' });
Map.prototype.getOrInsertComputed ??= function <K, V>(
this: Map<K, V>,
key: K,
callback: (key: K) => V
): V {
const existing = this.get(key);
if (existing !== undefined) return existing;
const value = callback(key);
this.set(key, value);
return value;
};
});
interface TestModules {
EventExecutor: typeof import('@user/data-system').EventExecutor;
DefaultHeroMoveTopImpl: typeof import('../hero').DefaultHeroMoveTopImpl;
HeroMover: typeof import('@user/data-base').HeroMover;
HeroPathfinding: typeof import('./heroPathfinding').HeroPathfinding;
MapState: typeof import('@user/data-base').MapState;
TileStore: typeof import('@user/data-common').TileStore;
Dir8FaceHandler: typeof import('@user/data-common').Dir8FaceHandler;
FaceManager: typeof import('@user/data-common').FaceManager;
RoleFaceBinder: typeof import('@user/data-common').RoleFaceBinder;
}
interface EventCall {
readonly id: string;
readonly trigger: number;
readonly hero: Readonly<{ x: number; y: number }>;
}
interface HeroFixture {
x: number;
y: number;
floorId: string;
state: unknown;
mover?: { readonly faceDirection: number };
setPos(x: number, y: number): void;
getCurrentFaceDirection(): number;
}
let modules: TestModules;
beforeAll(async () => {
vi.stubGlobal('main', { replayChecking: true });
vi.stubGlobal('location', { origin: 'http://localhost' });
const base = await import('@user/data-base');
const common = await import('@user/data-common');
const state = await import('../hero');
const path = await import('./heroPathfinding');
const event = await import('@user/data-system');
modules = {
EventExecutor: event.EventExecutor,
DefaultHeroMoveTopImpl: state.DefaultHeroMoveTopImpl,
HeroMover: base.HeroMover,
HeroPathfinding: path.HeroPathfinding,
MapState: base.MapState,
TileStore: common.TileStore,
Dir8FaceHandler: common.Dir8FaceHandler,
FaceManager: common.FaceManager,
RoleFaceBinder: common.RoleFaceBinder
};
});
interface FixtureOptions {
readonly middleEvent?: boolean;
readonly targetNoPass?: boolean;
readonly sealedTarget?: boolean;
}
function createFixture(options: FixtureOptions = {}) {
const tileStore: ITileStore = new modules.TileStore() as never;
tileStore.addTile({
num: 1,
id: 'floor',
events: {},
type: 0,
pass: { onlyEvents: false, outPass: 15, inPass: 15 },
eventPass: true
});
tileStore.addTile({
num: 2,
id: 'wall',
events: { 40: 'wall-touch' },
type: 0,
pass: { onlyEvents: false, outPass: 0, inPass: 0 },
eventPass: true
});
const faceManager = new modules.FaceManager();
const faceHandler = new modules.Dir8FaceHandler();
faceManager.register(1, faceHandler);
const commonState = {
tileStore,
itemStore: {},
mapStore: {},
eventStore: {},
roleFace: new modules.RoleFaceBinder(),
faceManager,
saveSystem: {}
} as never;
const maps = new modules.MapState(tileStore, commonState);
const eventMap = maps.fromRaw({
floorId: 'F1',
width: 3,
map: {
0: options.sealedTarget
? [1, 2, 2]
: options.targetNoPass
? [1, 1, 2]
: [1, 1, 1]
},
layerAlias: { 0: 'event' },
events: {
0:
options.middleEvent === false
? {}
: { 1: { 30: 'middle-enter' } }
}
})!;
const events = new Map<string, object>();
const store = {
addEvent() {},
getEvent<
_P extends Record<string, unknown>,
_E extends Record<string, unknown>,
_R = void
>(id: string) {
return events.get(id) as never;
}
};
const executor = new modules.EventExecutor({} as never, () => store);
const state = {
maps,
eventSystem: { executor }
};
const hero: HeroFixture = {
x: 0,
y: 0,
floorId: 'F1',
state,
setPos(x: number, y: number) {
hero.x = x;
hero.y = y;
},
getCurrentFaceDirection() {
return 4;
}
};
const mover = new modules.HeroMover(hero as never, faceHandler);
hero.mover = mover;
const heroState = { location: hero };
const fixtureState = { ...state, hero: heroState } as never;
const topImpl = new modules.DefaultHeroMoveTopImpl(fixtureState);
mover.useTopImplementation(topImpl);
const pathfinding = new modules.HeroPathfinding(fixtureState, topImpl);
return {
eventMap,
events,
executor,
hero: heroState.location,
pathfinding,
state: fixtureState
};
}
function addEvent(
events: Map<string, object>,
id: string,
trigger: number,
calls: EventCall[]
): void {
events.set(id, {
trigger,
execute: async (
_param: unknown,
env: {
trigger: number;
heroLocator: Readonly<{ x: number; y: number }>;
}
) => {
calls.push({ id, trigger: env.trigger, hero: env.heroLocator });
return true;
}
});
}
function addBlockingEvent(
events: Map<string, object>,
id: string,
trigger: number,
calls: EventCall[],
blocked: Promise<void>
): void {
events.set(id, {
trigger,
execute: async (
_param: unknown,
env: {
trigger: number;
heroLocator: Readonly<{ x: number; y: number }>;
}
) => {
calls.push({ id, trigger: env.trigger, hero: env.heroLocator });
await blocked;
return true;
}
});
}
describe('hero pathfinding integration', () => {
// 验证勇士按最小路径逐步移动并按事件链顺序执行途经事件
it('moves the hero to the target and triggers the traversed event', async () => {
const calls: EventCall[] = [];
const fixture = createFixture();
addEvent(fixture.events, 'middle-enter', 2, calls);
const path = fixture.pathfinding.getPath({ x: 2, y: 0 });
expect(path.map(step => step.to)).toEqual([
{ x: 1, y: 0 },
{ x: 2, y: 0 }
]);
const result = fixture.pathfinding.moveTo({ x: 2, y: 0 });
expect(result).not.toBeNull();
await result!.controller.onEnd;
expect({ x: fixture.hero.x, y: fixture.hero.y }).toEqual({
x: 2,
y: 0
});
expect(calls).toEqual([
{ id: 'middle-enter', trigger: 2, hero: { x: 1, y: 0 } }
]);
});
// 验证无事件路径的瞬移一步到达目标
it('teleports directly when the path has no events', async () => {
const fixture = createFixture({ middleEvent: false });
const result = fixture.pathfinding.teleportTo({ x: 2, y: 0 });
expect(result).not.toBeNull();
await result!.controller.onEnd;
expect({ x: fixture.hero.x, y: fixture.hero.y }).toEqual({
x: 2,
y: 0
});
});
// 验证默认策略检测途经事件并自动回退为逐步移动
it('falls back to step movement when the path has an event', async () => {
const calls: EventCall[] = [];
const fixture = createFixture();
addEvent(fixture.events, 'middle-enter', 2, calls);
const result = fixture.pathfinding.teleportTo({ x: 2, y: 0 });
expect(result).not.toBeNull();
await result!.controller.onEnd;
expect({ x: fixture.hero.x, y: fixture.hero.y }).toEqual({
x: 2,
y: 0
});
expect(calls).toEqual([
{ id: 'middle-enter', trigger: 2, hero: { x: 1, y: 0 } }
]);
});
// 验证 no-pass 目标移动至相邻格、面朝目标并派发 OnTouch
it('touches a no-pass target from its reachable adjacent cell', async () => {
const calls: EventCall[] = [];
const fixture = createFixture({
middleEvent: false,
targetNoPass: true
});
addEvent(fixture.events, 'wall-touch', 1, calls);
const result = fixture.pathfinding.moveTo({ x: 2, y: 0 });
expect(result).not.toBeNull();
await result!.controller.onEnd;
expect({ x: fixture.hero.x, y: fixture.hero.y }).toEqual({
x: 1,
y: 0
});
expect(fixture.hero.mover!.faceDirection).toBe(3);
expect(calls).toEqual([
{ id: 'wall-touch', trigger: 1, hero: { x: 1, y: 0 } }
]);
});
// 验证四邻无可达格时不可达目标不移动且不触发事件
it('ignores a no-pass target without a reachable adjacent cell', () => {
const fixture = createFixture({ sealedTarget: true });
const path = fixture.pathfinding.getPath({ x: 2, y: 0 });
expect(path).toEqual([]);
expect(fixture.pathfinding.moveTo({ x: 2, y: 0 })).toBeNull();
expect({ x: fixture.hero.x, y: fixture.hero.y }).toEqual({
x: 0,
y: 0
});
});
// 验证新寻路会停止旧移动并从兑现后的最新坐标接管
it('hands over a moving path to a new target', async () => {
const calls: EventCall[] = [];
let release: () => void = () => {};
const blocked = new Promise<void>(resolve => {
release = resolve;
});
const fixture = createFixture();
addBlockingEvent(fixture.events, 'middle-enter', 2, calls, blocked);
fixture.pathfinding.moveTo({ x: 2, y: 0 });
await Promise.resolve();
await Promise.resolve();
const next = fixture.pathfinding.moveTo({ x: 0, y: 0 });
expect(next).not.toBeNull();
release();
await next!.controller.onEnd;
expect({ x: fixture.hero.x, y: fixture.hero.y }).toEqual({
x: 0,
y: 0
});
});
// 验证显式打断后移动器可再次启动新的寻路
it('leaves the mover restartable after explicit interruption', async () => {
const calls: EventCall[] = [];
let release: () => void = () => {};
const blocked = new Promise<void>(resolve => {
release = resolve;
});
const fixture = createFixture();
addBlockingEvent(fixture.events, 'middle-enter', 2, calls, blocked);
fixture.pathfinding.moveTo({ x: 2, y: 0 });
await Promise.resolve();
await Promise.resolve();
const interrupted = fixture.pathfinding.interrupt();
release();
await interrupted;
const resumed = fixture.pathfinding.moveTo({ x: 0, y: 0 });
expect(resumed).not.toBeNull();
await resumed!.controller.onEnd;
expect({ x: fixture.hero.x, y: fixture.hero.y }).toEqual({
x: 0,
y: 0
});
});
});
@@ -1,421 +0,0 @@
import { ITileLocator, logger } from '@motajs/common';
import {
BlockEventType,
IBlockEventEnv,
IBlockEventParam,
IGameEventInvocation,
IHeroMoveTopImpl,
IHeroState,
IMapLayer,
IMapState,
IReadonlyTileBase,
IPassPredicate
} from '@user/data-base';
import {
EventTrigger,
FaceDirection,
IHeroAttr,
IMoverController,
IObjectMovable,
IObjectMover,
ObjectMoveStep
} from '@user/data-common';
import {
IPathfinder,
IPathfindingController,
IPathfindingStep,
IPathfindingSystem,
PathCostFunction,
PathFallbackPolicy,
PathfindingSystem
} from '@user/data-system';
import { IStateSystem } from '@user/data-system';
interface IHeroPathfindingState extends IStateSystem {
readonly hero: IHeroState<IHeroAttr>;
}
interface IHeroPathfinding extends IPathfindingSystem {}
interface IEventSource {
readonly priority: number;
readonly id: string;
readonly type: BlockEventType;
readonly tile: IReadonlyTileBase | null;
}
interface IResolvedPath {
readonly path: IPathfindingStep[];
readonly adjacent: Readonly<ITileLocator> | null;
readonly target: Readonly<ITileLocator> | null;
}
interface IHeroPathfindingController extends IMoverController {}
class HeroPathfindingController implements IHeroPathfindingController {
private completed: boolean = false;
private readonly completion: Promise<void>;
constructor(
private readonly delegate: Readonly<IMoverController>,
afterMove: () => Promise<void>
) {
this.completion = delegate.onEnd.then(async () => {
await afterMove();
this.completed = true;
});
}
get done(): boolean {
return this.completed;
}
get onEnd(): Promise<void> {
return this.completion;
}
push(...steps: Readonly<ObjectMoveStep>[]): void {
this.delegate.push(...steps);
}
insert(...steps: Readonly<ObjectMoveStep>[]): void {
this.delegate.insert(...steps);
}
stop(): Promise<void> {
return this.delegate.stop();
}
}
class QueuedHeroPathfindingController implements IPathfindingController {
private current: IPathfindingController | null = null;
private currentPath: IPathfindingStep[] = [];
private cancelled: boolean = false;
private completed: boolean = false;
private readonly completion: Promise<void>;
constructor(start: () => Promise<IPathfindingController | null>) {
this.completion = Promise.resolve()
.then(start)
.then(async result => {
if (!result) {
this.completed = true;
return;
}
this.current = result;
this.currentPath = [...result.path];
if (this.cancelled) {
await result.controller.stop();
this.completed = true;
return;
}
await result.controller.onEnd;
this.completed = true;
});
}
get controller(): Readonly<IMoverController> {
return this;
}
get path(): readonly IPathfindingStep[] {
return this.currentPath;
}
get done(): boolean {
return this.completed;
}
get onEnd(): Promise<void> {
return this.completion;
}
isCancelled(): boolean {
return this.cancelled;
}
push(...steps: Readonly<ObjectMoveStep>[]): void {
this.current?.controller.push(...steps);
}
insert(...steps: Readonly<ObjectMoveStep>[]): void {
this.current?.controller.insert(...steps);
}
stop(): Promise<void> {
this.cancelled = true;
if (this.current) return this.current.controller.stop();
return this.completion;
}
}
export class HeroPathfinding implements IHeroPathfinding {
readonly state: IHeroPathfindingState;
readonly finder: IPathfinder;
private readonly system: PathfindingSystem;
private active: IPathfindingController | null = null;
constructor(state: IHeroPathfindingState, topImpl: IHeroMoveTopImpl) {
this.state = state;
this.system = new PathfindingSystem(state);
this.finder = this.system.finder;
this.system.useMover(state.hero.location.mover);
this.finder.useMapState(state.maps);
this.finder.usePassPredicate(topImpl.predicate());
this.system.useFallbackPolicy(path => this.hasEvent(path));
this.bindCurrentLayer();
}
private hasEvent(path: readonly IPathfindingStep[]): boolean {
const layer = this.finderLayer();
if (!layer) return false;
for (const step of path) {
const loc = layer.getLocationData(step.to.x, step.to.y);
if (!loc) continue;
const point = layer.getPointEvent(step.to.x, step.to.y);
if (point && point.size > 0) return true;
if (loc.static && loc.static.tileEvent().get().size > 0) {
return true;
}
for (const tile of loc.dynamics) {
if (tile.tileEvent().get().size > 0) return true;
}
}
return false;
}
private finderLayer(): IMapLayer | null {
const floorId = this.state.hero.location.floorId;
const map = floorId ? this.state.maps.getMap(floorId) : null;
return map?.eventLayer ?? null;
}
private bindCurrentLayer(): void {
const floorId = this.state.hero.location.floorId;
const map = floorId ? this.state.maps.getMap(floorId) : null;
const layer: IMapLayer | null = map?.eventLayer ?? null;
this.finder.useMapLayer(layer);
}
useMover(mover: IObjectMover<IObjectMovable> | null): void {
this.system.useMover(mover);
}
useMovable(movable: IObjectMovable | null): void {
this.system.useMovable(movable);
}
useFallbackPolicy(policy: PathFallbackPolicy | null): void {
this.system.useFallbackPolicy(policy);
}
getPath(target: ITileLocator): IPathfindingStep[] {
this.bindCurrentLayer();
return this.resolvePath(target).path;
}
moveTo(target: ITileLocator): IPathfindingController | null {
if (this.isMoving()) return this.queueAfterInterrupt(target, false);
this.bindCurrentLayer();
const resolved = this.resolvePath(target);
return this.startResolved(target, resolved, false);
}
teleportTo(target: ITileLocator): IPathfindingController | null {
if (this.isMoving()) return this.queueAfterInterrupt(target, true);
this.bindCurrentLayer();
const resolved = this.resolvePath(target);
return this.startResolved(target, resolved, true);
}
private isMoving(): boolean {
return this.active !== null && !this.active.controller.done;
}
private queueAfterInterrupt(
target: ITileLocator,
teleport: boolean
): IPathfindingController {
const queued = new QueuedHeroPathfindingController(async () => {
await this.system.interrupt();
if (queued.isCancelled()) return null;
this.bindCurrentLayer();
const resolved = this.resolvePath(target);
return this.startResolved(target, resolved, teleport);
});
this.active = queued;
return queued;
}
private startResolved(
target: ITileLocator,
resolved: IResolvedPath,
teleport: boolean
): IPathfindingController | null {
if (resolved.path.length === 0) return null;
const destination = resolved.adjacent ?? target;
const result = teleport
? this.system.teleportTo(destination)
: this.system.moveTo(destination);
if (!result) {
logger.error(65);
return null;
}
const wrapped =
resolved.adjacent && resolved.target
? {
controller: new HeroPathfindingController(
result.controller,
() => this.finishAdjacentTouch(resolved)
),
path: result.path
}
: result;
this.active = wrapped;
void wrapped.controller.onEnd.then(() => {
if (this.active === wrapped) this.active = null;
});
return wrapped;
}
private resolvePath(target: ITileLocator): IResolvedPath {
const path = this.system.getPath(target);
if (path.length > 0) {
return { path, adjacent: null, target: null };
}
const layer = this.finderLayer();
if (!layer || !this.isNoPass(layer, target)) {
return { path: [], adjacent: null, target: null };
}
const start = this.state.hero.location;
const candidates: ReadonlyArray<Readonly<ITileLocator>> = [
{ x: target.x, y: target.y - 1 },
{ x: target.x + 1, y: target.y },
{ x: target.x, y: target.y + 1 },
{ x: target.x - 1, y: target.y }
];
for (const adjacent of candidates) {
if (!layer.inMap(adjacent.x, adjacent.y)) continue;
const adjacentPath = this.finder.find(
{ x: start.x, y: start.y },
adjacent
);
if (adjacentPath.length > 0) {
return { path: adjacentPath, adjacent, target };
}
}
return { path: [], adjacent: null, target: null };
}
private isNoPass(layer: IMapLayer, target: ITileLocator): boolean {
const raw = layer.getLocationData(target.x, target.y)?.static?.raw();
if (!raw) return false;
return (
!raw.eventPass || raw.pass.inPass === 0 || raw.pass.outPass === 0
);
}
private directionTo(target: ITileLocator): FaceDirection {
const hero = this.state.hero.location;
if (target.x > hero.x) return FaceDirection.Right;
if (target.x < hero.x) return FaceDirection.Left;
if (target.y > hero.y) return FaceDirection.Down;
return FaceDirection.Up;
}
private async finishAdjacentTouch(resolved: IResolvedPath): Promise<void> {
const adjacent = resolved.adjacent!;
const target = resolved.target!;
const mover = this.state.hero.location.mover;
mover.setFaceDir(this.directionTo(target));
await this.dispatchTouch(adjacent, target);
}
private async dispatchTouch(
heroLoc: Readonly<ITileLocator>,
target: Readonly<ITileLocator>
): Promise<void> {
const layer = this.finderLayer();
if (!layer) return;
const pointSources: IEventSource[] = [];
const tileSources: IEventSource[] = [];
const point = layer.getPointEvent(target.x, target.y);
const loc = layer.getLocationData(target.x, target.y);
if (point) {
for (const [priority, id] of point) {
pointSources.push({
priority,
id,
type: BlockEventType.PointEvent,
tile: null
});
}
}
if (loc) {
if (loc.static) {
for (const [priority, id] of loc.static.tileEvent().get()) {
tileSources.push({
priority,
id,
type: BlockEventType.TileEvent,
tile: loc.static
});
}
}
for (const tile of loc.dynamics) {
for (const [priority, id] of tile.tileEvent().get()) {
tileSources.push({
priority,
id,
type: BlockEventType.TileEvent,
tile
});
}
}
}
pointSources.sort((a, b) => b.priority - a.priority);
tileSources.sort((a, b) => b.priority - a.priority);
const invocations: IGameEventInvocation[] = [];
for (const source of [...pointSources, ...tileSources]) {
const env: IBlockEventEnv = {
state: this.state,
type: source.type,
trigger: EventTrigger.OnTouch,
heroLocator: heroLoc,
triggerLocator: target,
tile: source.tile,
layer,
map: layer.map
};
invocations.push({ id: source.id, env });
}
if (invocations.length === 0) return;
const param: IBlockEventParam = { custom: {} };
await this.state.eventSystem.executor.execute<void>(invocations, param);
}
interrupt(): Promise<void> {
const active = this.active;
this.active = null;
if (!active) return this.system.interrupt();
return active.controller.stop().then(() => this.system.interrupt());
}
useMapState(maps: IMapState | null): void {
this.finder.useMapState(maps);
}
useMapLayer(layer: IMapLayer | null): void {
this.finder.useMapLayer(layer);
}
useCostFunction(cost: PathCostFunction | null): void {
this.finder.useCostFunction(cost);
}
usePassPredicate(predicate: IPassPredicate | null): void {
this.finder.usePassPredicate(predicate);
}
}
@@ -1 +0,0 @@
export * from './heroPathfinding';