import type { SpatialApi, SpatialPosition, SpatialRoom, } from '../../sdk/behavior-plugin/index.js'; /** Serializable static facts used by Host and Worker code to build SpatialApi. */ export interface SpatialFacts { readonly coordinates: Readonly<{ xPositive: 'right'; yPositive: 'down' }>; readonly playerBodyLengthPx: number; readonly rooms: readonly Readonly[]; readonly roomTransitions: readonly Readonly<{ a: string; b: string }>[]; } function pointInPolygon( x: number, y: number, polygon: readonly (readonly [number, number])[], ): boolean { let inside = false; for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index, index += 1) { const [xi, yi] = polygon[index]; const [xj, yj] = polygon[previous]; const intersects = ((yi > y) !== (yj > y)) && x < ((xj - xi) * (y - yi)) / (yj - yi || Number.EPSILON) + xi; if (intersects) inside = !inside; } return inside; } /** Host-only factory. Module authors receive SpatialApi and cannot replace its facts. */ export function createSpatialApi(facts: SpatialFacts): SpatialApi { const rooms = Object.freeze(facts.rooms.map((room) => Object.freeze({ name: room.name, polygon: Object.freeze(room.polygon.map((point) => Object.freeze([point[0], point[1]] as const))), bbox: Object.freeze({ ...room.bbox }), }))); const roomByName = new Map(rooms.map((room) => [room.name, room] as const)); const roomAt = (x: number, y: number): SpatialRoom | null => ( rooms.find((room) => pointInPolygon(x, y, room.polygon)) ?? null ); const sideInRoom = (position: Readonly): string | null => { const room = position.room ? roomByName.get(position.room) : undefined; if (!room || !pointInPolygon(position.x, position.y, room.polygon)) return null; const width = room.bbox.right - room.bbox.left; const height = room.bbox.bottom - room.bbox.top; if (width <= 0 || height <= 0) return null; const rx = (position.x - room.bbox.left) / width; const ry = (position.y - room.bbox.top) / height; const horizontal = rx < 0.33 ? '左' : rx > 0.67 ? '右' : ''; const vertical = ry < 0.33 ? '上' : ry > 0.67 ? '下' : ''; return horizontal || vertical ? `${horizontal}${vertical}侧` : '中部'; }; return Object.freeze({ xPositive: facts.coordinates.xPositive, yPositive: facts.coordinates.yPositive, playerBodyLengthPx: facts.playerBodyLengthPx, rooms, roomAt, sideInRoom, placeLabel: (position: Readonly) => { if (!position.room) return '未命名区域'; const side = sideInRoom(position); return side ? `${position.room}${side}` : position.room; }, transitionIsMapped: (from: string | null, to: string | null) => ( !!from && !!to && from !== to && facts.roomTransitions.some((transition) => ( (transition.a === from && transition.b === to) || (transition.a === to && transition.b === from) )) ), }); }