@esengine/pathfinding
Version:
寻路系统 | Pathfinding System - A*, Grid, NavMesh
1,916 lines (1,900 loc) • 86.3 kB
TypeScript
import { c as IORCASolverConfig, i as ICollisionResolverConfig } from './CollisionResolver-CSgWsegP.js';
/**
* @zh 寻路系统核心接口
* @en Pathfinding System Core Interfaces
*/
/**
* @zh 2D 坐标点
* @en 2D coordinate point
*/
interface IPoint {
readonly x: number;
readonly y: number;
}
/**
* @zh 创建点
* @en Create a point
*/
declare function createPoint(x: number, y: number): IPoint;
/**
* @zh 路径节点
* @en Path node
*/
interface IPathNode {
/** @zh 节点唯一标识 @en Unique node identifier */
readonly id: string | number;
/** @zh 节点位置 @en Node position */
readonly position: IPoint;
/** @zh 移动代价 @en Movement cost */
readonly cost: number;
/** @zh 是否可通行 @en Is walkable */
readonly walkable: boolean;
}
/**
* @zh 路径结果
* @en Path result
*/
interface IPathResult {
/** @zh 是否找到路径 @en Whether path was found */
readonly found: boolean;
/** @zh 路径点列表 @en List of path points */
readonly path: readonly IPoint[];
/** @zh 路径总代价 @en Total path cost */
readonly cost: number;
/** @zh 搜索的节点数 @en Number of nodes searched */
readonly nodesSearched: number;
}
/**
* @zh 空路径结果
* @en Empty path result
*/
declare const EMPTY_PATH_RESULT: IPathResult;
/**
* @zh 寻路地图接口
* @en Pathfinding map interface
*/
interface IPathfindingMap {
/**
* @zh 获取节点的邻居
* @en Get neighbors of a node
*/
getNeighbors(node: IPathNode): IPathNode[];
/**
* @zh 获取指定位置的节点
* @en Get node at position
*/
getNodeAt(x: number, y: number): IPathNode | null;
/**
* @zh 计算两点间的启发式距离
* @en Calculate heuristic distance between two points
*/
heuristic(a: IPoint, b: IPoint): number;
/**
* @zh 计算两个邻居节点间的移动代价
* @en Calculate movement cost between two neighbor nodes
*/
getMovementCost(from: IPathNode, to: IPathNode): number;
/**
* @zh 检查位置是否可通行
* @en Check if position is walkable
*/
isWalkable(x: number, y: number): boolean;
}
/**
* @zh 启发式函数类型
* @en Heuristic function type
*/
type HeuristicFunction = (a: IPoint, b: IPoint) => number;
/**
* @zh 曼哈顿距离(4方向移动)
* @en Manhattan distance (4-directional movement)
*/
declare function manhattanDistance(a: IPoint, b: IPoint): number;
/**
* @zh 欧几里得距离(任意方向移动)
* @en Euclidean distance (any direction movement)
*/
declare function euclideanDistance(a: IPoint, b: IPoint): number;
/**
* @zh 切比雪夫距离(8方向移动)
* @en Chebyshev distance (8-directional movement)
*/
declare function chebyshevDistance(a: IPoint, b: IPoint): number;
/**
* @zh 八角距离(8方向移动,对角线代价为 √2)
* @en Octile distance (8-directional, diagonal cost √2)
*/
declare function octileDistance(a: IPoint, b: IPoint): number;
/**
* @zh 寻路配置
* @en Pathfinding options
*/
interface IPathfindingOptions {
/** @zh 最大搜索节点数 @en Maximum nodes to search */
maxNodes?: number;
/** @zh 启发式权重 (>1 更快但可能非最优) @en Heuristic weight (>1 faster but may be suboptimal) */
heuristicWeight?: number;
/** @zh 是否允许对角移动 @en Allow diagonal movement */
allowDiagonal?: boolean;
/** @zh 是否避免穿角 @en Avoid corner cutting */
avoidCorners?: boolean;
/**
* @zh 代理半径,用于生成考虑碰撞体积的路径
* @en Agent radius, used to generate paths that consider collision volume
*
* @zh 如果指定,路径规划器会收缩 portal 宽度并偏移拐点,确保路径与障碍物保持足够距离
* @en If specified, the path planner will shrink portal widths and offset turning points to ensure sufficient clearance from obstacles
*/
agentRadius?: number;
}
/**
* @zh 默认寻路配置
* @en Default pathfinding options
*/
declare const DEFAULT_PATHFINDING_OPTIONS: Required<IPathfindingOptions>;
/**
* @zh 寻路器接口
* @en Pathfinder interface
*/
interface IPathfinder {
/**
* @zh 查找路径
* @en Find path
*/
findPath(startX: number, startY: number, endX: number, endY: number, options?: IPathfindingOptions): IPathResult;
/**
* @zh 清理状态(用于重用)
* @en Clear state (for reuse)
*/
clear(): void;
}
/**
* @zh 路径平滑器接口
* @en Path smoother interface
*/
interface IPathSmoother {
/**
* @zh 平滑路径
* @en Smooth path
*/
smooth(path: readonly IPoint[], map: IPathfindingMap): IPoint[];
}
/**
* @zh 视线检测函数类型
* @en Line of sight check function type
*/
type LineOfSightCheck = (x1: number, y1: number, x2: number, y2: number, map: IPathfindingMap) => boolean;
/**
* @zh 增量寻路系统接口
* @en Incremental Pathfinding System Interfaces
*/
/**
* @zh 增量寻路状态
* @en Incremental pathfinding state
*/
declare enum PathfindingState {
/** @zh 空闲,等待请求 @en Idle, waiting for request */
Idle = "idle",
/** @zh 正在搜索中 @en Search in progress */
InProgress = "in_progress",
/** @zh 已暂停 @en Paused */
Paused = "paused",
/** @zh 搜索完成,找到路径 @en Completed, path found */
Completed = "completed",
/** @zh 搜索失败,无法找到路径 @en Failed, no path found */
Failed = "failed",
/** @zh 已取消 @en Cancelled */
Cancelled = "cancelled"
}
/**
* @zh 增量寻路请求
* @en Incremental pathfinding request
*/
interface IPathRequest {
/**
* @zh 请求唯一标识符
* @en Unique request identifier
*/
readonly id: number;
/**
* @zh 起点 X 坐标
* @en Start X coordinate
*/
readonly startX: number;
/**
* @zh 起点 Y 坐标
* @en Start Y coordinate
*/
readonly startY: number;
/**
* @zh 终点 X 坐标
* @en End X coordinate
*/
readonly endX: number;
/**
* @zh 终点 Y 坐标
* @en End Y coordinate
*/
readonly endY: number;
/**
* @zh 寻路配置选项
* @en Pathfinding options
*/
readonly options?: IPathfindingOptions;
/**
* @zh 优先级(数值越小优先级越高)
* @en Priority (lower number = higher priority)
*/
readonly priority: number;
/**
* @zh 创建时间戳
* @en Creation timestamp
*/
readonly createdAt: number;
}
/**
* @zh 增量寻路进度
* @en Incremental pathfinding progress
*/
interface IPathProgress$1 {
/**
* @zh 当前寻路状态
* @en Current pathfinding state
*/
readonly state: PathfindingState;
/**
* @zh 已搜索的节点数量
* @en Number of nodes searched
*/
readonly nodesSearched: number;
/**
* @zh 开放列表当前大小
* @en Current open list size
*/
readonly openListSize: number;
/**
* @zh 估计的搜索进度 (0-1)
* @en Estimated search progress (0-1)
*/
readonly estimatedProgress: number;
/**
* @zh 当前最佳部分路径(可选)
* @en Current best partial path (optional)
*/
readonly partialPath?: readonly IPoint[];
}
/**
* @zh 增量寻路结果(扩展自 IPathResult)
* @en Incremental pathfinding result (extends IPathResult)
*/
interface IIncrementalPathResult extends IPathResult {
/**
* @zh 关联的请求 ID
* @en Associated request ID
*/
readonly requestId: number;
/**
* @zh 完成搜索所用的帧数
* @en Number of frames used to complete search
*/
readonly framesUsed: number;
/**
* @zh 是否为部分路径(未到达终点)
* @en Whether this is a partial path (not reaching goal)
*/
readonly isPartial: boolean;
}
/**
* @zh 增量寻路请求选项
* @en Incremental pathfinding request options
*/
interface IIncrementalPathfindingOptions extends IPathfindingOptions {
/**
* @zh 优先级(数值越小优先级越高,默认 50)
* @en Priority (lower = higher, default 50)
*/
priority?: number;
}
/**
* @zh 增量寻路器接口
* @en Incremental pathfinder interface
*
* @zh 支持时间切片的寻路器,可跨多帧执行搜索
* @en Pathfinder with time slicing support, can execute search across multiple frames
*/
interface IIncrementalPathfinder {
/**
* @zh 请求寻路(非阻塞)
* @en Request pathfinding (non-blocking)
*
* @param startX - @zh 起点 X 坐标 @en Start X coordinate
* @param startY - @zh 起点 Y 坐标 @en Start Y coordinate
* @param endX - @zh 终点 X 坐标 @en End X coordinate
* @param endY - @zh 终点 Y 坐标 @en End Y coordinate
* @param options - @zh 寻路选项 @en Pathfinding options
* @returns @zh 寻路请求对象 @en Path request object
*/
requestPath(startX: number, startY: number, endX: number, endY: number, options?: IIncrementalPathfindingOptions): IPathRequest;
/**
* @zh 执行一步搜索
* @en Execute one step of search
*
* @param requestId - @zh 请求 ID @en Request ID
* @param maxIterations - @zh 本步最大迭代次数 @en Maximum iterations this step
* @returns @zh 当前进度 @en Current progress
*/
step(requestId: number, maxIterations: number): IPathProgress$1;
/**
* @zh 暂停寻路
* @en Pause pathfinding
*
* @param requestId - @zh 请求 ID @en Request ID
*/
pause(requestId: number): void;
/**
* @zh 恢复寻路
* @en Resume pathfinding
*
* @param requestId - @zh 请求 ID @en Request ID
*/
resume(requestId: number): void;
/**
* @zh 取消寻路
* @en Cancel pathfinding
*
* @param requestId - @zh 请求 ID @en Request ID
*/
cancel(requestId: number): void;
/**
* @zh 获取寻路结果(仅当状态为 Completed 或 Failed 时可用)
* @en Get pathfinding result (only available when state is Completed or Failed)
*
* @param requestId - @zh 请求 ID @en Request ID
* @returns @zh 寻路结果或 null @en Path result or null
*/
getResult(requestId: number): IIncrementalPathResult | null;
/**
* @zh 获取当前进度
* @en Get current progress
*
* @param requestId - @zh 请求 ID @en Request ID
* @returns @zh 当前进度或 null @en Current progress or null
*/
getProgress(requestId: number): IPathProgress$1 | null;
/**
* @zh 清理已完成的请求(释放内存)
* @en Clean up completed request (release memory)
*
* @param requestId - @zh 请求 ID @en Request ID
*/
cleanup(requestId: number): void;
/**
* @zh 通知障碍物变化(用于动态重规划)
* @en Notify obstacle change (for dynamic replanning)
*
* @param minX - @zh 变化区域最小 X @en Changed area min X
* @param minY - @zh 变化区域最小 Y @en Changed area min Y
* @param maxX - @zh 变化区域最大 X @en Changed area max X
* @param maxY - @zh 变化区域最大 Y @en Changed area max Y
*/
notifyObstacleChange(minX: number, minY: number, maxX: number, maxY: number): void;
/**
* @zh 清理所有请求
* @en Clear all requests
*/
clear(): void;
}
/**
* @zh 路径验证结果
* @en Path validation result
*/
interface IPathValidationResult {
/**
* @zh 路径是否有效
* @en Whether the path is valid
*/
readonly valid: boolean;
/**
* @zh 第一个无效点的索引(-1 表示全部有效)
* @en Index of first invalid point (-1 if all valid)
*/
readonly invalidIndex: number;
}
/**
* @zh 路径验证器接口
* @en Path validator interface
*/
interface IPathValidator {
/**
* @zh 验证路径段的有效性
* @en Validate path segment validity
*
* @param path - @zh 要验证的路径 @en Path to validate
* @param fromIndex - @zh 起始索引 @en Start index
* @param toIndex - @zh 结束索引 @en End index
* @param map - @zh 地图实例 @en Map instance
* @returns @zh 验证结果 @en Validation result
*/
validatePath(path: readonly IPoint[], fromIndex: number, toIndex: number, map: IPathfindingMap): IPathValidationResult;
}
/**
* @zh 动态重规划配置
* @en Dynamic replanning configuration
*/
interface IReplanningConfig {
/**
* @zh 是否启用动态重规划
* @en Whether dynamic replanning is enabled
*/
enabled: boolean;
/**
* @zh 路径检查间隔(帧数)
* @en Path check interval (in frames)
*/
checkInterval: number;
/**
* @zh 触发重规划的距离阈值
* @en Distance threshold to trigger replanning
*/
distanceThreshold: number;
/**
* @zh 向前探测的距离(路径点数)
* @en Lookahead distance (in path points)
*/
lookaheadDistance: number;
}
/**
* @zh 默认重规划配置
* @en Default replanning configuration
*/
declare const DEFAULT_REPLANNING_CONFIG: IReplanningConfig;
/**
* @zh 空进度(用于无效请求)
* @en Empty progress (for invalid requests)
*/
declare const EMPTY_PROGRESS: IPathProgress$1;
/**
* @zh 路径缓存模块
* @en Path Cache Module
*
* @zh 缓存已计算的路径,避免重复计算相同起点终点的路径
* @en Cache computed paths to avoid recalculating paths with the same start and end points
*/
/**
* @zh 缓存配置
* @en Cache configuration
*/
interface IPathCacheConfig {
/**
* @zh 最大缓存条目数
* @en Maximum number of cache entries
*/
maxEntries: number;
/**
* @zh 缓存过期时间(毫秒),0 表示不过期
* @en Cache expiration time in milliseconds, 0 means no expiration
*/
ttlMs: number;
/**
* @zh 是否启用近似匹配(在一定范围内的起点/终点视为相同)
* @en Whether to enable approximate matching (start/end within range considered same)
*/
enableApproximateMatch: boolean;
/**
* @zh 近似匹配范围
* @en Approximate matching range
*/
approximateRange: number;
}
/**
* @zh 默认缓存配置
* @en Default cache configuration
*/
declare const DEFAULT_PATH_CACHE_CONFIG: IPathCacheConfig;
/**
* @zh 路径缓存
* @en Path Cache
*
* @zh 缓存已计算的路径,支持 LRU 淘汰策略和 TTL 过期
* @en Cache computed paths with LRU eviction and TTL expiration
*
* @example
* ```typescript
* const cache = new PathCache({ maxEntries: 500 });
* const cached = cache.get(0, 0, 10, 10, mapVersion);
* if (!cached) {
* const result = pathfinder.findPath(0, 0, 10, 10);
* cache.set(0, 0, 10, 10, result, mapVersion);
* }
* ```
*/
declare class PathCache {
private readonly config;
private readonly cache;
private readonly accessOrder;
constructor(config?: Partial<IPathCacheConfig>);
/**
* @zh 获取缓存的路径
* @en Get cached path
*
* @param startX - @zh 起点 X 坐标 @en Start X coordinate
* @param startY - @zh 起点 Y 坐标 @en Start Y coordinate
* @param endX - @zh 终点 X 坐标 @en End X coordinate
* @param endY - @zh 终点 Y 坐标 @en End Y coordinate
* @param mapVersion - @zh 地图版本号 @en Map version number
* @returns @zh 缓存的路径结果或 null @en Cached path result or null
*/
get(startX: number, startY: number, endX: number, endY: number, mapVersion: number): IPathResult | null;
/**
* @zh 设置缓存路径
* @en Set cached path
*
* @param startX - @zh 起点 X 坐标 @en Start X coordinate
* @param startY - @zh 起点 Y 坐标 @en Start Y coordinate
* @param endX - @zh 终点 X 坐标 @en End X coordinate
* @param endY - @zh 终点 Y 坐标 @en End Y coordinate
* @param result - @zh 路径结果 @en Path result
* @param mapVersion - @zh 地图版本号 @en Map version number
*/
set(startX: number, startY: number, endX: number, endY: number, result: IPathResult, mapVersion: number): void;
/**
* @zh 使所有缓存失效
* @en Invalidate all cache
*/
invalidateAll(): void;
/**
* @zh 使指定区域的缓存失效
* @en Invalidate cache for specified region
*
* @param minX - @zh 最小 X 坐标 @en Minimum X coordinate
* @param minY - @zh 最小 Y 坐标 @en Minimum Y coordinate
* @param maxX - @zh 最大 X 坐标 @en Maximum X coordinate
* @param maxY - @zh 最大 Y 坐标 @en Maximum Y coordinate
*/
invalidateRegion(minX: number, minY: number, maxX: number, maxY: number): void;
/**
* @zh 获取缓存统计信息
* @en Get cache statistics
*/
getStats(): {
size: number;
maxSize: number;
hitRate?: number;
};
/**
* @zh 清理过期条目
* @en Clean up expired entries
*/
cleanup(): void;
private generateKey;
private isValid;
private getApproximate;
private adjustPathForApproximate;
private updateAccessOrder;
private removeFromAccessOrder;
private evictLRU;
}
/**
* @zh 创建路径缓存
* @en Create path cache
*
* @param config - @zh 缓存配置 @en Cache configuration
* @returns @zh 路径缓存实例 @en Path cache instance
*/
declare function createPathCache(config?: Partial<IPathCacheConfig>): PathCache;
/**
* @zh 增量 A* 寻路算法实现
* @en Incremental A* Pathfinding Algorithm Implementation
*/
/**
* @zh 增量寻路器配置
* @en Incremental pathfinder configuration
*/
interface IIncrementalPathfinderConfig {
/**
* @zh 是否启用路径缓存
* @en Whether to enable path caching
*/
enableCache?: boolean;
/**
* @zh 缓存配置
* @en Cache configuration
*/
cacheConfig?: Partial<IPathCacheConfig>;
}
/**
* @zh 增量 A* 寻路器
* @en Incremental A* Pathfinder
*
* @zh 支持时间切片的 A* 算法实现,可跨多帧执行搜索
* @en A* algorithm implementation with time slicing, can execute search across multiple frames
*
* @example
* ```typescript
* const map = createGridMap(100, 100);
* const pathfinder = createIncrementalAStarPathfinder(map);
*
* // Request path (non-blocking)
* const request = pathfinder.requestPath(0, 0, 99, 99);
*
* // Process over multiple frames
* function gameLoop() {
* const progress = pathfinder.step(request.id, 100);
*
* if (progress.state === PathfindingState.Completed) {
* const result = pathfinder.getResult(request.id);
* console.log('Path found:', result?.path);
* } else if (progress.state === PathfindingState.InProgress) {
* requestAnimationFrame(gameLoop);
* }
* }
* gameLoop();
* ```
*/
declare class IncrementalAStarPathfinder implements IIncrementalPathfinder {
private readonly map;
private readonly sessions;
private nextRequestId;
private readonly affectedRegions;
private readonly maxRegionAge;
private readonly cache;
private readonly enableCache;
private mapVersion;
private cacheHits;
private cacheMisses;
/**
* @zh 创建增量 A* 寻路器
* @en Create incremental A* pathfinder
*
* @param map - @zh 寻路地图实例 @en Pathfinding map instance
* @param config - @zh 配置选项 @en Configuration options
*/
constructor(map: IPathfindingMap, config?: IIncrementalPathfinderConfig);
/**
* @zh 请求寻路(非阻塞)
* @en Request pathfinding (non-blocking)
*/
requestPath(startX: number, startY: number, endX: number, endY: number, options?: IIncrementalPathfindingOptions): IPathRequest;
/**
* @zh 执行一步搜索
* @en Execute one step of search
*/
step(requestId: number, maxIterations: number): IPathProgress$1;
/**
* @zh 暂停寻路
* @en Pause pathfinding
*/
pause(requestId: number): void;
/**
* @zh 恢复寻路
* @en Resume pathfinding
*/
resume(requestId: number): void;
/**
* @zh 取消寻路
* @en Cancel pathfinding
*/
cancel(requestId: number): void;
/**
* @zh 获取寻路结果
* @en Get pathfinding result
*/
getResult(requestId: number): IIncrementalPathResult | null;
/**
* @zh 获取当前进度
* @en Get current progress
*/
getProgress(requestId: number): IPathProgress$1 | null;
/**
* @zh 清理已完成的请求
* @en Clean up completed request
*/
cleanup(requestId: number): void;
/**
* @zh 通知障碍物变化
* @en Notify obstacle change
*/
notifyObstacleChange(minX: number, minY: number, maxX: number, maxY: number): void;
/**
* @zh 清理所有请求
* @en Clear all requests
*/
clear(): void;
/**
* @zh 清空路径缓存
* @en Clear path cache
*/
clearCache(): void;
/**
* @zh 获取缓存统计信息
* @en Get cache statistics
*/
getCacheStats(): {
enabled: boolean;
hits: number;
misses: number;
hitRate: number;
size: number;
};
/**
* @zh 检查会话是否被障碍物变化影响
* @en Check if session is affected by obstacle change
*/
isAffectedByChange(requestId: number): boolean;
/**
* @zh 清除会话的变化标记
* @en Clear session's change flag
*/
clearChangeFlag(requestId: number): void;
/**
* @zh 展开邻居节点
* @en Expand neighbor nodes
*/
private expandNeighbors;
/**
* @zh 创建进度对象
* @en Create progress object
*/
private createProgress;
/**
* @zh 构建路径结果
* @en Build path result
*/
private buildResult;
/**
* @zh 创建空结果
* @en Create empty result
*/
private createEmptyResult;
/**
* @zh 检查会话是否被区域影响
* @en Check if session is affected by region
*/
private sessionAffectedByRegion;
/**
* @zh 清理过期的变化区域
* @en Clean up expired change regions
*/
private cleanupOldRegions;
}
/**
* @zh 创建增量 A* 寻路器
* @en Create incremental A* pathfinder
*
* @param map - @zh 寻路地图实例 @en Pathfinding map instance
* @returns @zh 增量 A* 寻路器实例 @en Incremental A* pathfinder instance
*/
declare function createIncrementalAStarPathfinder(map: IPathfindingMap): IncrementalAStarPathfinder;
/**
* @zh HPA* (Hierarchical Pathfinding A*) 寻路算法实现
* @en HPA* (Hierarchical Pathfinding A*) Pathfinding Algorithm Implementation
*
* @zh HPA* 是一种分层寻路算法,适用于超大地图 (1000x1000+)
* @en HPA* is a hierarchical pathfinding algorithm suitable for very large maps (1000x1000+)
*
* @zh 工作原理:
* 1. 将地图划分为集群 (clusters)
* 2. 在集群边界检测入口点 (entrances)
* 3. 构建抽象图 (abstract graph) 连接入口点
* 4. 预计算集群内入口点之间的真实路径代价
* 5. 先在抽象图上寻路,再利用缓存细化为详细路径
*
* @en How it works:
* 1. Divide map into clusters
* 2. Detect entrances at cluster boundaries
* 3. Build abstract graph connecting entrances
* 4. Precompute actual path costs between entrances within clusters
* 5. First find path on abstract graph, then refine using cached paths
*/
/**
* @zh HPA* 配置
* @en HPA* Configuration
*/
interface IHPAConfig {
/**
* @zh 集群大小(边长)
* @en Cluster size (side length)
*/
clusterSize: number;
/**
* @zh 最大入口宽度(超过此宽度会拆分或使用端点策略)
* @en Maximum entrance width (entrances wider than this will be split or use endpoint strategy)
*/
maxEntranceWidth: number;
/**
* @zh 是否启用内部路径缓存
* @en Whether to enable internal path caching
*/
cacheInternalPaths: boolean;
/**
* @zh 入口策略:'middle' 在中间放节点,'end' 在宽入口两端各放节点
* @en Entrance strategy: 'middle' places node at center, 'end' places nodes at both ends for wide entrances
*/
entranceStrategy?: 'middle' | 'end';
/**
* @zh 是否延迟计算 intra-edges(大幅加速预处理,首次查询时计算真实路径)
* @en Whether to lazily compute intra-edges (greatly speeds up preprocessing, computes actual paths on first query)
*/
lazyIntraEdges?: boolean;
}
/**
* @zh 默认 HPA* 配置
* @en Default HPA* configuration
*/
declare const DEFAULT_HPA_CONFIG: IHPAConfig;
/**
* @zh HPA* 寻路器
* @en HPA* Pathfinder
*
* @zh 适用于超大地图的分层寻路算法
* @en Hierarchical pathfinding algorithm for very large maps
*
* @example
* ```typescript
* const map = createGridMap(1000, 1000);
* const pathfinder = new HPAPathfinder(map, { clusterSize: 20 });
*
* // Preprocess (do once after map changes)
* pathfinder.preprocess();
*
* // Find path
* const result = pathfinder.findPath(0, 0, 999, 999);
* ```
*/
declare class HPAPathfinder implements IPathfinder {
private readonly map;
private readonly config;
private readonly mapWidth;
private readonly mapHeight;
private clusters;
private clusterGrid;
private clustersX;
private clustersY;
private abstractNodes;
private nodesByCluster;
private nextNodeId;
private entranceCount;
private readonly localPathfinder;
private readonly pathCache;
private mapVersion;
private preprocessed;
constructor(map: IPathfindingMap, config?: Partial<IHPAConfig>);
/**
* @zh 预处理地图(构建抽象图)
* @en Preprocess map (build abstract graph)
*/
preprocess(): void;
/**
* @zh 寻找路径
* @en Find path
*/
findPath(startX: number, startY: number, endX: number, endY: number, options?: Partial<IPathfindingOptions>): IPathResult;
/**
* @zh 清理状态
* @en Clear state
*/
clear(): void;
/**
* @zh 通知地图区域变化
* @en Notify map region change
*/
notifyRegionChange(minX: number, minY: number, maxX: number, maxY: number): void;
/**
* @zh 获取预处理统计信息
* @en Get preprocessing statistics
*/
getStats(): {
clusters: number;
entrances: number;
abstractNodes: number;
cacheSize: number;
};
private getMapBounds;
/**
* @zh 构建集群
* @en Build clusters
*/
private buildClusters;
/**
* @zh 检测入口并创建抽象节点
* @en Detect entrances and create abstract nodes
*/
private buildEntrances;
/**
* @zh 检测并创建两个相邻集群之间的入口
* @en Detect and create entrances between two adjacent clusters
*/
private detectAndCreateEntrances;
/**
* @zh 检测边界上的连续可通行区间
* @en Detect continuous walkable spans on boundary
*/
private detectEntranceSpans;
/**
* @zh 为入口区间创建抽象节点
* @en Create abstract nodes for entrance span
*/
private createEntranceNodes;
/**
* @zh 创建抽象节点
* @en Create abstract node
*/
private createAbstractNode;
/**
* @zh 构建所有集群的 intra-edges
* @en Build intra-edges for all clusters
*/
private buildIntraEdges;
/**
* @zh 构建单个集群的 intra-edges
* @en Build intra-edges for single cluster
*/
private buildClusterIntraEdges;
/**
* @zh 延迟构建 intra-edges(只用启发式距离)
* @en Build lazy intra-edges (using heuristic distance only)
*/
private buildLazyIntraEdges;
/**
* @zh 立即构建 intra-edges(计算真实路径)
* @en Build eager intra-edges (compute actual paths)
*/
private buildEagerIntraEdges;
/**
* @zh 按需计算 intra-edge 的真实路径
* @en Compute actual path for intra-edge on demand
*/
private computeIntraEdgePath;
/**
* @zh 获取指定位置的集群
* @en Get cluster at position
*/
private getClusterAt;
/**
* @zh 获取受影响的集群
* @en Get affected clusters
*/
private getAffectedClusters;
/**
* @zh 插入临时节点
* @en Insert temporary node
*/
private insertTempNode;
/**
* @zh 移除临时节点
* @en Remove temporary node
*/
private removeTempNode;
/**
* @zh 在抽象图上进行 A* 搜索
* @en Perform A* search on abstract graph
*/
private abstractSearch;
/**
* @zh 重建抽象路径
* @en Reconstruct abstract path
*/
private reconstructPath;
/**
* @zh 细化抽象路径为具体路径
* @en Refine abstract path to concrete path
*/
private refinePath;
/**
* @zh 追加路径(避免重复点)
* @en Append path (avoid duplicate points)
*/
private appendPath;
/**
* @zh 局部寻路
* @en Local pathfinding
*/
private findLocalPath;
/**
* @zh 启发式函数(Octile 距离)
* @en Heuristic function (Octile distance)
*/
private heuristic;
}
/**
* @zh 创建 HPA* 寻路器
* @en Create HPA* pathfinder
*
* @param map - @zh 寻路地图实例 @en Pathfinding map instance
* @param config - @zh HPA* 配置 @en HPA* configuration
* @returns @zh HPA* 寻路器实例 @en HPA* pathfinder instance
*/
declare function createHPAPathfinder(map: IPathfindingMap, config?: Partial<IHPAConfig>): HPAPathfinder;
/**
* @zh 导航网格实现
* @en NavMesh Implementation
*
* @zh 支持动态障碍物:可以临时禁用多边形或添加圆形/矩形障碍物
* @en Supports dynamic obstacles: can temporarily disable polygons or add circular/rectangular obstacles
*/
/**
* @zh 动态障碍物类型
* @en Dynamic obstacle type
*/
type ObstacleType = 'circle' | 'rect' | 'polygon';
/**
* @zh 动态障碍物
* @en Dynamic obstacle
*/
interface IDynamicObstacle {
/**
* @zh 障碍物 ID
* @en Obstacle ID
*/
readonly id: number;
/**
* @zh 障碍物类型
* @en Obstacle type
*/
readonly type: ObstacleType;
/**
* @zh 是否启用
* @en Whether enabled
*/
enabled: boolean;
/**
* @zh 位置(圆形和矩形的中心)
* @en Position (center for circle and rect)
*/
position: IPoint;
/**
* @zh 半径(圆形)或半宽/半高(矩形)
* @en Radius (circle) or half-width/half-height (rect)
*/
radius?: number;
halfWidth?: number;
halfHeight?: number;
/**
* @zh 顶点(多边形)
* @en Vertices (polygon)
*/
vertices?: readonly IPoint[];
}
/**
* @zh 导航多边形
* @en Navigation polygon
*/
interface INavPolygon {
/** @zh 多边形ID @en Polygon ID */
readonly id: number;
/** @zh 顶点列表 @en Vertex list */
readonly vertices: readonly IPoint[];
/** @zh 中心点 @en Center point */
readonly center: IPoint;
/** @zh 邻居多边形ID @en Neighbor polygon IDs */
readonly neighbors: readonly number[];
/** @zh 到邻居的共享边 @en Shared edges to neighbors */
readonly portals: ReadonlyMap<number, IPortal>;
}
/**
* @zh 入口(两个多边形之间的共享边)
* @en Portal (shared edge between two polygons)
*/
interface IPortal {
/** @zh 边的左端点 @en Left endpoint of edge */
readonly left: IPoint;
/** @zh 边的右端点 @en Right endpoint of edge */
readonly right: IPoint;
}
/**
* @zh 导航网格
* @en Navigation Mesh
*
* @zh 使用凸多边形网格进行高效寻路,适合复杂地形
* @en Uses convex polygon mesh for efficient pathfinding, suitable for complex terrain
*
* @example
* ```typescript
* const navmesh = new NavMesh();
*
* // Add polygons
* navmesh.addPolygon([
* { x: 0, y: 0 }, { x: 10, y: 0 },
* { x: 10, y: 10 }, { x: 0, y: 10 }
* ]);
*
* // Build connections
* navmesh.build();
*
* // Find path
* const result = navmesh.findPath(1, 1, 8, 8);
* ```
*/
declare class NavMesh implements IPathfindingMap {
private polygons;
private nodes;
private nextId;
private obstacles;
private nextObstacleId;
private disabledPolygons;
/**
* @zh 添加导航多边形
* @en Add navigation polygon
*
* @returns @zh 多边形ID @en Polygon ID
*/
addPolygon(vertices: IPoint[], neighbors?: number[]): number;
/**
* @zh 设置两个多边形之间的连接
* @en Set connection between two polygons
*/
setConnection(polyA: number, polyB: number, portal: IPortal): void;
/**
* @zh 自动检测并建立相邻多边形的连接
* @en Auto-detect and build connections between adjacent polygons
*/
build(): void;
/**
* @zh 查找两个多边形的共享边
* @en Find shared edge between two polygons
*/
private findSharedEdge;
/**
* @zh 计算多边形中心
* @en Calculate polygon center
*/
private calculateCenter;
/**
* @zh 查找包含点的多边形
* @en Find polygon containing point
*/
findPolygonAt(x: number, y: number): INavPolygon | null;
/**
* @zh 检查点是否在多边形内
* @en Check if point is inside polygon
*/
private isPointInPolygon;
getNodeAt(x: number, y: number): IPathNode | null;
getNeighbors(node: IPathNode): IPathNode[];
heuristic(a: IPoint, b: IPoint): number;
getMovementCost(from: IPathNode, to: IPathNode): number;
isWalkable(x: number, y: number): boolean;
/**
* @zh 在导航网格上寻路
* @en Find path on navigation mesh
*/
findPath(startX: number, startY: number, endX: number, endY: number, options?: IPathfindingOptions): IPathResult;
/**
* @zh 在多边形图上寻路
* @en Find path on polygon graph
*
* @param start - @zh 起始多边形 @en Start polygon
* @param end - @zh 目标多边形 @en End polygon
* @param opts - @zh 寻路选项 @en Pathfinding options
* @param checkObstacles - @zh 是否检查障碍物 @en Whether to check obstacles
*/
private findPolygonPath;
/**
* @zh 使用漏斗算法优化路径(支持代理半径)
* @en Optimize path using funnel algorithm (supports agent radius)
*
* @param start - @zh 起点 @en Start point
* @param end - @zh 终点 @en End point
* @param polygons - @zh 多边形路径 @en Polygon path
* @param agentRadius - @zh 代理半径 @en Agent radius
*/
private funnelPath;
/**
* @zh 收缩 portal(将两端点向内移动 agentRadius)
* @en Shrink portal (move endpoints inward by agentRadius)
*/
private shrinkPortal;
/**
* @zh 偏移拐点以保持与角落的距离
* @en Offset turning point to maintain distance from corner
*
* @param prevApex - @zh 上一个顶点 @en Previous apex
* @param cornerOriginal - @zh 原始角落位置 @en Original corner position
* @param cornerShrunk - @zh 收缩后的角落位置 @en Shrunk corner position
* @param radius - @zh 代理半径 @en Agent radius
* @param side - @zh 转向侧 ('left' 或 'right') @en Turn side ('left' or 'right')
*/
private offsetTurningPoint;
/**
* @zh 检查两点是否相等
* @en Check if two points are equal
*/
private pointsEqual;
/**
* @zh 计算三角形面积的两倍(用于判断点的相对位置)
* @en Calculate twice the triangle area (for point relative position)
*/
private triArea2;
/**
* @zh 计算路径总长度
* @en Calculate total path length
*/
private calculatePathLength;
/**
* @zh 添加圆形障碍物
* @en Add circular obstacle
*
* @param x - @zh 中心 X @en Center X
* @param y - @zh 中心 Y @en Center Y
* @param radius - @zh 半径 @en Radius
* @returns @zh 障碍物 ID @en Obstacle ID
*/
addCircleObstacle(x: number, y: number, radius: number): number;
/**
* @zh 添加矩形障碍物
* @en Add rectangular obstacle
*
* @param x - @zh 中心 X @en Center X
* @param y - @zh 中心 Y @en Center Y
* @param halfWidth - @zh 半宽 @en Half width
* @param halfHeight - @zh 半高 @en Half height
* @returns @zh 障碍物 ID @en Obstacle ID
*/
addRectObstacle(x: number, y: number, halfWidth: number, halfHeight: number): number;
/**
* @zh 添加多边形障碍物
* @en Add polygon obstacle
*
* @param vertices - @zh 顶点列表 @en Vertex list
* @returns @zh 障碍物 ID @en Obstacle ID
*/
addPolygonObstacle(vertices: IPoint[]): number;
/**
* @zh 移除障碍物
* @en Remove obstacle
*/
removeObstacle(obstacleId: number): boolean;
/**
* @zh 启用/禁用障碍物
* @en Enable/disable obstacle
*/
setObstacleEnabled(obstacleId: number, enabled: boolean): void;
/**
* @zh 更新障碍物位置
* @en Update obstacle position
*/
updateObstaclePosition(obstacleId: number, x: number, y: number): void;
/**
* @zh 获取所有障碍物
* @en Get all obstacles
*/
getObstacles(): IDynamicObstacle[];
/**
* @zh 获取启用的障碍物
* @en Get enabled obstacles
*/
getEnabledObstacles(): IDynamicObstacle[];
/**
* @zh 清除所有障碍物
* @en Clear all obstacles
*/
clearObstacles(): void;
/**
* @zh 禁用多边形
* @en Disable polygon
*/
disablePolygon(polygonId: number): void;
/**
* @zh 启用多边形
* @en Enable polygon
*/
enablePolygon(polygonId: number): void;
/**
* @zh 检查多边形是否被禁用
* @en Check if polygon is disabled
*/
isPolygonDisabled(polygonId: number): boolean;
/**
* @zh 禁用包含指定点的多边形
* @en Disable polygon containing specified point
*/
disablePolygonAt(x: number, y: number): number | null;
/**
* @zh 清除所有禁用的多边形
* @en Clear all disabled polygons
*/
clearDisabledPolygons(): void;
/**
* @zh 获取被禁用的多边形 ID 列表
* @en Get list of disabled polygon IDs
*/
getDisabledPolygons(): number[];
/**
* @zh 检查点是否在任何障碍物内
* @en Check if point is inside any obstacle
*/
isPointInObstacle(x: number, y: number): boolean;
/**
* @zh 检查点是否在单个障碍物内
* @en Check if point is inside single obstacle
*/
private isPointInSingleObstacle;
/**
* @zh 检查线段是否与任何障碍物相交
* @en Check if line segment intersects any obstacle
*/
doesLineIntersectObstacle(x1: number, y1: number, x2: number, y2: number): boolean;
/**
* @zh 检查线段是否与单个障碍物相交
* @en Check if line segment intersects single obstacle
*/
private doesLineIntersectSingleObstacle;
/**
* @zh 线段与圆相交检测
* @en Line segment circle intersection
*/
private lineIntersectsCircle;
/**
* @zh 线段与矩形相交检测
* @en Line segment rectangle intersection
*/
private lineIntersectsRect;
/**
* @zh 线段与多边形相交检测
* @en Line segment polygon intersection
*/
private lineIntersectsPolygon;
/**
* @zh 两线段相交检测
* @en Two line segments intersection
*/
private lineSegmentsIntersect;
private direction;
private onSegment;
/**
* @zh 检查多边形是否被障碍物阻挡
* @en Check if polygon is blocked by obstacle
*
* @zh 检查以下条件:
* @en Checks the following conditions:
* - @zh 多边形是否被禁用 @en Whether polygon is disabled
* - @zh 多边形中心是否在障碍物内 @en Whether polygon center is inside obstacle
* - @zh 多边形任意顶点是否在障碍物内 @en Whether any polygon vertex is inside obstacle
* - @zh 多边形任意边是否与障碍物相交 @en Whether any polygon edge intersects obstacle
*/
isPolygonBlocked(polygonId: number): boolean;
/**
* @zh 在导航网格上寻路(考虑障碍物)
* @en Find path on navigation mesh (considering obstacles)
*
* @zh 此方法在规划阶段就考虑障碍物,自动绕过被阻挡的多边形
* @en This method considers obstacles during planning, automatically avoiding blocked polygons
*
* @zh 与 findPath 不同,此方法会:
* @en Unlike findPath, this method will:
* - @zh 在 A* 搜索中跳过被障碍物阻挡的多边形
* - @en Skip obstacle-blocked polygons during A* search
* - @zh 验证起点和终点不在障碍物内
* - @en Verify start and end points are not inside obstacles
*/
findPathWithObstacles(startX: number, startY: number, endX: number, endY: number, options?: IPathfindingOptions): IPathResult;
/**
* @zh 清空导航网格
* @en Clear navigation mesh
*/
clear(): void;
/**
* @zh 获取所有多边形
* @en Get all polygons
*/
getPolygons(): INavPolygon[];
/**
* @zh 获取多边形数量
* @en Get polygon count
*/
get polygonCount(): number;
/**
* @zh 获取障碍物数量
* @en Get obstacle count
*/
get obstacleCount(): number;
}
/**
* @zh 创建导航网格
* @en Create navigation mesh
*/
declare function createNavMesh(): NavMesh;
/**
* @zh 路径规划器接口
* @en Path Planner Interface
*
* @zh 统一的全局寻路接口,支持 NavMesh、A*、JPS、HPA*、Flow Field 等算法
* @en Unified global pathfinding interface, supports NavMesh, A*, JPS, HPA*, Flow Field, etc.
*/
/**
* @zh 2D 向量
* @en 2D Vector
*/
interface IVector2 {
x: number;
y: number;
}
/**
* @zh 路径规划结果
* @en Path planning result
*/
interface IPathPlanResult {
/**
* @zh 是否找到路径
* @en Whether path was found
*/
readonly found: boolean;
/**
* @zh 路径点列表(世界坐标)
* @en List of path points (world coordinates)
*/
readonly path: readonly IVector2[];
/**
* @zh 路径总代价
* @en Total path cost
*/
readonly cost: number;
/**
* @zh 搜索的节点数(用于性能监控)
* @en Number of nodes searched (for performance monitoring)
*/
readonly nodesSearched: number;
}
/**
* @zh 空路径结果
* @en Empty path result
*/
declare const EMPTY_PLAN_RESULT: IPathPlanResult;
/**
* @zh 路径规划选项
* @en Path planning options
*/
interface IPathPlanOptions {
/**
* @zh 代理半径,用于生成考虑碰撞的路径
* @en Agent radius, used to generate collision-aware paths
*
* @zh 如果指定,路径规划器会确保生成的路径与障碍物保持足够距离
* @en If specified, the path planner will ensure the generated path maintains sufficient distance from obstacles
*/
agentRadius?: number;
}
/**
* @zh 路径规划器接口
* @en Path planner interface
*
* @zh 统一的全局寻路接口,支持 NavMesh、A*、JPS、HPA*、Flow Field 等算法
* @en Unified global pathfinding interface, supports NavMesh, A*, JPS, HPA*, Flow Field, etc.
*
* @example
* ```typescript
* // 使用 NavMesh 规划器
* const planner = createNavMeshPathPlanner(navMesh);
* const result = planner.findPath({ x: 0, y: 0 }, { x: 100, y: 100 });
*
* // 使用带半径的路径规划
* const result = planner.findPath({ x: 0, y: 0 }, { x: 100, y: 100 }, { agentRadius: 0.5 });
*
* // 使用 A* 规划器
* const planner = createAStarPlanner(gridMap);
* const result = planner.findPath({ x: 0, y: 0 }, { x: 50, y: 50 });
* ```
*/
interface IPathPlanner {
/**
* @zh 规划器类型标识
* @en Planner type identifier
*/
readonly type: string;
/**
* @zh 查找从起点到终点的路径
* @en Find path from start to end
*
* @param start - @zh 起点世界坐标 @en Start world position
* @param end - @zh 终点世界坐标 @en End world position
* @param options - @zh 路径规划选项 @en Path planning options
* @returns @zh 路径规划结果 @en Path planning result
*/
findPath(start: IVector2, end: IVector2, options?: IPathPlanOptions): IPathPlanResult;
/**
* @zh 检查位置是否可通行
* @en Check if position is walkable
*
* @param position - @zh 要检查的位置 @en Position to check
* @returns @zh 是否可通行 @en Whether walkable
*/
isWalkable(position: IVector2): boolean;
/**
* @zh 获取最近的可通行位置
* @en Get nearest walkable position
*
* @param position - @zh 参考位置 @en Reference position
* @returns @zh 最近的可通行位置,如果找不到则返回 null @en Nearest walkable position, or null if not found
*/
getNearestWalkable(position: IVector2): IVector2 | null;
/**
* @zh 清理内部状态(用于重用)
* @en Clear internal state (for reuse)
*/
clear(): void;
/**
* @zh 释放资源
* @en Dispose resources
*/
dispose(): void;
}
/**
* @zh 寻路状态
* @en Pathfinding state
*/
declare enum PathPlanState {
/**
* @zh 空闲
* @en Idle
*/
Idle = "idle",
/**
* @zh 进行中
* @en In progress
*/
InProgress = "in_progress",
/**
* @zh 已完成
* @en Completed
*/
Completed = "completed",
/**
* @zh 失败
* @en Failed
*/
Failed = "failed",
/**
* @zh 已取消
* @en Cancelled
*/
Cancelled = "cancelled"
}
/**
* @zh 增量寻路请求
* @en Incremental pathfinding request
*/
interface IIncrementalPathRequest {
/**
* @zh 请求 ID
* @en Request ID
*/
readonly id: number;
/**
* @zh 当前状态
* @en Current state
*/
readonly state: PathPlanState;
}
/**
* @zh 寻路进度信息
* @en Pathfinding progress info
*/
interface IPathProgress {
/**
* @zh 当前状态
* @en Current state
*/
readonly state: PathPlanState;
/**
* @zh 估计进度 (0-1)
* @en Estimated progress (0-1)
*/
readonly estimatedProgress: number;
/**
* @zh 本次步进搜索的节点数
* @en Nodes searched in this step
*/
readonly nodesSearched: number;
/**
* @zh 累计搜索的节点数
* @en Total nodes searched
*/
readonly totalNodesSearched: number;
}
/**
* @zh 增量路径规划器接口
* @en Incremental path planner interface
*
* @zh 支持时间切片的路径规划器,可以将寻路计算分散到多帧执行
* @en Path planner with time slicing support, can spread pathfinding computation across multiple frames
*
* @example
* ```typescript
* const planner = createIncrementalAStarPlanner(gridMap);
*
* // 请求路径
* const request = planner.requestPath({ x: 0, y: 0 }, { x: 100, y: 100 });
*
* // 每帧执行一定数量的迭代
* while (true) {
* const progress = planner.step(request.id, 100); // 每帧 100 次迭代
* if (progress.state === PathPlanState.Completed) {
* const result = planner.getResult(request.id);
* break;
* }
* if (progress.state === PathPlanState.Failed) {
* break;
* }
* await nextFrame();
* }
*
* planner.cleanup(request.id);
* ```
*/
interface IIncrementalPathPlanner extends IPathPlanner {
/**
* @zh 是否支持增量计算
* @en Whether supports incremental computation
*/
readonly supportsIncremental: true;
/**
* @zh 请求路径(异步开始)
* @en Request path (async start)
*
* @param start - @zh 起点 @en Start position
* @param end - @zh 终点 @en End position
* @param options - @zh 选项 @en Options
* @returns @zh 请求对象 @en Request object
*/
requestPath(start: IVector2, end: IVector2, options?: IPathPlanOptions): IIncrementalPathRequest;
/**
* @zh 执行指定次数的迭代
* @en Execute specified number of iterations
*
* @param requestId - @zh 请求 ID @en Request ID
* @param iterations - @zh 迭代次数 @en Number of iterations
* @returns @zh 进度信息 @en Progress info
*/
step(requestId: number, iterations: number): IPathProgress;
/**
* @zh 获取结果
* @en Get result
*
* @param requestId - @zh 请求 ID @en Request ID
* @returns @zh 结果,如果未完成或不存在返回 null @en Result, null if not completed or not found
*/
getResult(requestId: number): IPathPlanResult | null;
/**
* @zh 取消请求
* @en Cancel request
*
* @param requestId - @zh 请求 ID @en Request ID
*/
cancel(requestId: number): void;
/**
* @zh 清理请求(释放资源)
* @en Cleanup request (release resources)
*
* @param requestId - @zh 请求 ID @en Request ID
*/
cleanup(requestId: number): void;
/**
* @zh 获取活跃请求数量
* @en Get active request count
*/
getActiveRequestCount(): number;
}
/**
* @zh 类型守卫:检查是否为增量路径规划器
* @en Type guard: check if is incremental path planner
*/
declare function isIncrementalPlanner(planner: IPathPlanner): planner is IIncrementalPathPlanner;
/**
* @zh 局部避让接口
* @en Local Avoidance Interface
*
* @zh 统一的局部避让接口,支持 ORCA、RVO、Steering Behaviors 等算法
* @en Unified local avoidance interface, supports ORCA, RVO, Steering Behaviors, etc.
*/
/**
* @zh 避让代理数据(算法无关)
* @en Avoidance agent data (algorithm-agnostic)
*/
interface IAvoidanceAgentData {
/**
* @zh 代理唯一标识
* @en Unique agent identifier
*/
readonly id: number;
/**
* @zh 当前位置
* @en Current position
*/
readonly position: IVector2;
/**
* @zh 当前速度
* @en Current velocity
*/
readonly velocity: IVector2;
/**
* @zh 首选速度(通常指向路径下一点)
* @en Preferred velocity (usually towards next path point)
*/
readonly preferredVelocity: IVector2;
/**
* @zh 代理半径
* @en Agent radius
*/
readonly radius: number;
/**
* @zh 最大速度
* @en Maximum speed
*/
readonly maxSpeed: number;
}
/**
* @zh 静态障碍物数据
* @en Static obstacle data
*/
interface IObstacleData {
/**
* @zh 障碍物顶点(逆时针顺序)
* @en Obstacle vertices (counter-clockwise order)
*/
readonly vertices: readonly IVector2[];
}
/**
* @zh 局部避让计算结果
* @en Local avoidance computation result
*/
interface IAvoidanceResult {
/**
* @zh 计算得到的新速度
* @en Computed new velocity
*/
readonly velocity: IVector2;
/**
* @zh 是否找到可行解
* @en Whether a feasible solution was found
*/
readonly feasible: boolean;
}
/**
* @zh 局部避让接口
* @en Local avoidance interface
*
* @zh 统一的局部避让接口,支持 ORCA、RVO、Steering Behaviors 等算法
* @en Unified local avoidance interface, supports ORCA, RVO, Steering Behaviors, etc.
*
* @example
* ```typescript
* // 使用 ORCA 避让
* const avoidance = createORCAAvoidance();
* const result = avoidance.computeAvoidanceVelocity(
* agent, neighbors, obstacles, deltaTime
* );
*
* // 批量计算
* const results = avoidance.computeBatchAvoidance(agents, obstacles, deltaTime);
* ```
*/
interface ILocalAvoidance {
/**
* @zh 避让算法类型标识
* @en Avoidance algorithm type identifier
*/
readonly type: string;
/**
* @zh 计算代理的避让速度
* @en Compute avoidance velocity for agent
*
* @param agent - @zh 当前代理数据 @en Current agent data
* @param neighbors - @zh 邻近代理列表 @en List of neighboring agents
* @param obstacles - @zh 静态障碍物列表 @en List of static obstacles
* @param deltaTime - @zh 时间步长 @en Time step
* @returns @zh 避让计算结果 @en Avoidance computation result
*/
computeAvoidanceVelocity(agent: IAvoidanceAgentData, neighbors: readonly IAvoidanceAgentData[], obstacles: readonly IObstacleData[], deltaTime: number): IAvoidanceResult;
/**
* @zh 批量计算多个代理的避让速度(性能优化)
* @en Batch compute avoidance velocities for multiple agents (performance optimization)
*
* @param agents - @zh 代理列表 @en List of agents
* @param obstacles - @zh 静态障碍物列表 @en List of static obstacles
* @param deltaTime - @zh 时间步长 @en Time step
* @returns @zh 每个代理的避让结果(按 ID 索引)@en Avoidance results for each agent (indexed by ID)
*/
computeBatchAvoidance(agents: readonly IAvoidanceAgentData[], obstacles: readonly IObstacleData[], deltaTime: number): Map<number, IAvoidanceResult>;
/**
* @zh 释放资源
* @en Dispose resources
*/
dispose(): void;
}
/**
* @zh 碰撞解决器接口
* @en Collision Resolver Interface
*
* @zh 提供位置级别的硬碰撞检测和解决
* @en Provides position-level hard collision detection and resolution
*/
/**
* @zh 碰撞检测结果
* @en Collision detection result
*/
interface ICollisionResult {
/**
* @zh 是否发生碰撞
* @en Whether collision occurred
*/
readonly collided: boolean;
/**
* @zh 穿透深度
* @en Penetration depth
*/
readonly penetration: number;
/**
* @zh 碰撞法线(从障碍物指向代理)
* @en Collision normal (pointing from obstacle to agent)
*/
readonly normal: IVector2;
/**
* @zh 障碍物上的最近点
* @en Closest point on obstacle
*/
readonly closestPoint: IVector2;
}
/**
* @zh 空碰撞结果
* @en Empty collision result
*/
declare const EMPTY_COLLISION_RESULT: ICollisionResult;
/**
* @zh 碰撞解决器接口
* @en Collision resolver interface
*
* @zh 提供位置级别的硬碰撞检测和解决,作为避让算法失效时的安全保护层
* @en Provides position-level hard collision detection and resolution, as safety layer when avoidance fails
*
* @example
* ```typescript
* const resolver = createDefaultCollisionResolver();
*
* // 检测碰撞
* const collision = resolver.detectCollision(position, radius, obstacles);
* if (collision.collided) {
* // 解决碰撞
* const newPos = resolver.resolveCollision(position, radius, obstacles);
* }
*
* // 验证速度
* const safeVelocity = resolver.validateVelocity(
* position, velocity, radius, obstacles, deltaTime
* );
* ```
*/
interface ICollisionResolver {
/**
* @zh 解决器类型标识
* @en Resolver type identifier
*/
readonly type: string;
/**
* @zh 检测圆与障碍物的碰撞
* @en Detect collision between circle and obstacles
*
* @param position - @zh 圆心位置 @en Circle center position
* @param radius - @zh 圆半径 @en Circle radius
* @param obstacles - @zh 障碍物列表 @en List of obstacles
* @returns @zh 最严重的碰撞结果 @en Most severe collision result
*/
detectCollision(position: IVector2, radius: number, obstacles: readonly IObstacleData[]): ICollisionResult;
/**
* @zh 解决碰撞,返回修正后的位置
* @en Resolve collision, return corrected position
*
* @param position - @zh 当前位置 @en Current position
* @param radius - @zh 半径 @en Radius
* @param obstacles - @zh 障碍物列表 @en List of obstacles
* @returns @zh 修正后的位置 @en Corrected position
*/
resolveCollision(position: IVector2, radius: number, obstacles: readonly IObstacleData[]): IVector2;
/**
* @zh 验证速度是否会导致碰撞,返回安全速度
* @en Validate velocity won't cause collision, return safe velocity
*
* @param position - @zh 当前位置 @en Current position
* @param velocity - @zh 目标速度 @en Target velocity
* @param radius - @zh 半径 @en Radius
* @param obstacles - @zh 障碍物列表 @en List of obstacles
* @param deltaTime - @zh 时间步长 @en T