import {
checkBounds,
checkWalkable,
mergeInvariants,
type Grid,
type Invariant,
type TileMapData,
type DialogueGraph
} from '@rpg/engine';
import { AREAS } from './locations';
import { NPCS } from './npcs';
import { DIALOGUES } from './dialogues';
import { ENEMY_KINDS } from './enemies';
import { QUESTS } from './quests';
import { FLAGS, VARS } from './ids';
/**
* Runtime-валидация контента → инварианты (замена JSON Schema: истина одна —
* в TS-типах; здесь ловим то, что типы не выражают: ссылки, границы, стены).
* Вызывается из GameAgent.invariants() и из юнит-теста — битый контент падает
* сразу в тестах, а не в рантайме игры.
*/
const WHERE = 'data';
/** Grid-адаптер над сырыми данными карты (для checkBounds/checkWalkable/A*). */
function gridOf(data: TileMapData): Grid {
return {
width: data.width,
height: data.height,
isWalkable: (x, y) =>
x >= 0 && y >= 0 && x < data.width && y < data.height &&
!data.blocked.includes(data.tiles[y * data.width + x])
};
}
/** Граф диалога: start/next/choices существуют, узлы-сироты (warn). */
export function validateDialogue(id: string, graph: DialogueGraph): Invariant[] {
const out: Invariant[] = [];
const where = `${WHERE}/dialogue/${id}`;
if (!graph.nodes[graph.start]) {
out.push({ id: 'dialogue-start', severity: 'error', message: `start «${graph.start}» не существует`, where });
}
for (const [nodeId, node] of Object.entries(graph.nodes)) {
for (const next of (node.choices ?? []).map((c) => c.next).concat(node.next)) {
if (next !== undefined && !graph.nodes[next]) {
out.push({ id: 'dialogue-next', severity: 'error', message: `узел «${nodeId}»: next «${next}» не существует`, where });
}
}
}
// Сироты: узлы, в которые нет ссылки (warn — могут быть «мёртвым ветвлением»).
const referenced = new Set<string>([graph.start]);
for (const node of Object.values(graph.nodes)) {
for (const next of (node.choices ?? []).map((c) => c.next).concat(node.next)) {
if (next !== undefined) referenced.add(next);
}
}
for (const nodeId of Object.keys(graph.nodes)) {
if (!referenced.has(nodeId)) {
out.push({ id: 'dialogue-orphan', severity: 'warn', message: `узел «${nodeId}» недостижим`, where });
}
}
return out;
}
/** NPC: не в стенах, в границах своей области. */
export function validateNpcs(maps: Map<string, TileMapData>): Invariant[] {
const out: Invariant[] = [];
for (const npc of NPCS) {
for (const area of Object.values(AREAS)) {
if (!area.npcs.some((n) => n.id === npc.id)) continue;
const map = maps.get(area.id);
if (!map) continue;
const grid = gridOf(map);
const check = mergeInvariants(
checkBounds(`NPC ${npc.id}`, npc.tile, map.width, map.height, WHERE),
checkWalkable(`NPC ${npc.id}`, npc.tile, grid, WHERE)
);
out.push(...check);
}
}
return out;
}
/** Области: спавн/враги проходимы, переходы ведут в существующие области и проходимые entry. */
export function validateLocations(maps: Map<string, TileMapData>): Invariant[] {
const out: Invariant[] = [];
for (const loc of Object.values(AREAS)) {
const map = maps.get(loc.id);
if (!map) continue;
const grid = gridOf(map);
const where = `${WHERE}/area/${loc.id}`;
out.push(...mergeInvariants(
checkBounds('spawn', loc.spawn, map.width, map.height, where),
checkWalkable('spawn', loc.spawn, grid, where)
));
loc.enemies.forEach((e, i) => {
out.push(...mergeInvariants(
checkBounds(`враг#${i}`, e.tile, map.width, map.height, where),
checkWalkable(`враг#${i}`, e.tile, grid, where)
));
});
for (const obj of loc.interactables ?? []) {
out.push(...mergeInvariants(checkBounds(`объект ${obj.id}`, obj.tile, map.width, map.height, where)));
}
for (const [i, t] of loc.transitions.entries()) {
// Тайл-триггер в границах своей карты (может быть и непроходим — колодец).
out.push(...mergeInvariants(checkBounds(`переход#${i}`, t.tile, map.width, map.height, where)));
if (t.target.kind !== 'area') continue;
const to: string = t.target.area;
if (!(to in AREAS)) {
out.push({ id: 'transition-target', severity: 'error', message: `переход#${i} -> «${to}»: область не существует`, where });
continue;
}
const targetMap = maps.get(to);
if (targetMap) {
out.push(...mergeInvariants(
checkBounds(`переход#${i} entry (${to})`, t.target.entry, targetMap.width, targetMap.height, where),
checkWalkable(`переход#${i} entry (${to})`, t.target.entry, gridOf(targetMap), where)
));
}
}
}
return out;
}
/** Виды врагов: базовая числовая согласованность. */
export function validateEnemies(): Invariant[] {
const out: Invariant[] = [];
for (const kind of Object.values(ENEMY_KINDS)) {
const where = `${WHERE}/enemy/${kind.id}`;
if (kind.hp <= 0) out.push({ id: 'enemy-hp', severity: 'error', message: `hp = ${kind.hp}`, where });
if (kind.speed < 0) out.push({ id: 'enemy-speed', severity: 'error', message: `speed = ${kind.speed}`, where });
}
return out;
}
/**
* Референциальная целостность строковых сущностей: каждое упоминание флага/
* вара в контенте существует в реестрах ids.ts (error), каждый ключ реестра
* где-то упомянут (warn — «мёртвый» флаг); ссылки квестов на NPC/диалоги —
* error. Движковые типы — строки, поэтому реестр сверяется только здесь.
*/
export function validateReferences(): Invariant[] {
const out: Invariant[] = [];
const flagsUsed = new Set<string>();
const varsUsed = new Set<string>();
const checkFlag = (flag: string, where: string, what: string): void => {
flagsUsed.add(flag);
if (!(flag in FLAGS)) {
out.push({ id: 'flag-unknown', severity: 'error', message: `${what}: флаг «${flag}» вне реестра FLAGS`, where });
}
};
const checkVar = (id: string, where: string, what: string): void => {
varsUsed.add(id);
if (!(id in VARS)) {
out.push({ id: 'var-unknown', severity: 'error', message: `${what}: вар «${id}» вне реестра VARS`, where });
}
};
for (const [id, graph] of Object.entries(DIALOGUES)) {
const where = `${WHERE}/dialogue/${id}`;
for (const node of Object.values(graph.nodes)) {
const nodes = [node, ...(node.choices ?? [])];
for (const n of nodes) {
for (const f of n.setFlags ?? []) checkFlag(f, where, `setFlags`);
for (const f of n.clearFlags ?? []) checkFlag(f, where, `clearFlags`);
for (const f of n.when ?? []) checkFlag(f, where, `when`);
for (const f of n.whenNot ?? []) checkFlag(f, where, `whenNot`);
if (n.whenVar) checkVar(n.whenVar.key, where, 'whenVar.key');
}
}
}
for (const area of Object.values(AREAS)) {
const where = `${WHERE}/area/${area.id}`;
for (const t of area.transitions) {
if (t.requiresFlag !== undefined) checkFlag(t.requiresFlag, where, `переход ${t.tile.x},${t.tile.y}`);
}
for (const obj of area.interactables ?? []) {
const w = `${where}/interactable/${obj.id}`;
for (const r of obj.responses) {
if (r.when?.flag !== undefined) checkFlag(r.when.flag, w, 'when.flag');
if (r.when?.notFlag !== undefined) checkFlag(r.when.notFlag, w, 'when.notFlag');
for (const f of r.setFlags ?? []) checkFlag(f, w, 'setFlags');
for (const f of r.clearFlags ?? []) checkFlag(f, w, 'clearFlags');
if (r.setVar) checkVar(r.setVar.id, w, 'setVar.id');
if (r.addVar) checkVar(r.addVar.id, w, 'addVar.id');
}
}
}
for (const quest of QUESTS) {
const where = `${WHERE}/quest/${quest.id}`;
for (const [i, stage] of quest.stages.entries()) {
if (stage.doneFlag !== undefined) checkFlag(stage.doneFlag, where, `стадия#${i}.doneFlag`);
if (stage.progressKey !== undefined) checkVar(stage.progressKey, where, `стадия#${i}.progressKey`);
if (!NPCS.some((n) => n.id === stage.npc)) {
out.push({ id: 'npc-ref', severity: 'error', message: `стадия#${i}: NPC «${stage.npc}» не существует`, where });
}
if (stage.dialogue !== undefined && !(stage.dialogue in DIALOGUES)) {
out.push({ id: 'dialogue-ref', severity: 'error', message: `стадия#${i}: диалог «${stage.dialogue}» не существует`, where });
}
}
}
for (const npc of NPCS) {
checkFlag(npc.flagKey, `${WHERE}/npc/${npc.id}`, 'flagKey');
if (!(npc.dialogueFirst in DIALOGUES)) {
out.push({ id: 'dialogue-ref', severity: 'error', message: `NPC ${npc.id}: dialogueFirst «${npc.dialogueFirst}» не существует`, where: `${WHERE}/npc/${npc.id}` });
}
if (!(npc.dialogueRepeat in DIALOGUES)) {
out.push({ id: 'dialogue-ref', severity: 'error', message: `npc ${npc.id}: dialogueRepeat «${npc.dialogueRepeat}» не существует`, where: `${WHERE}/npc/${npc.id}` });
}
}
// Мёртвые сущности реестра: ключ не упомянут нигде в контенте (warn).
for (const flag of Object.keys(FLAGS)) {
if (!flagsUsed.has(flag)) {
out.push({ id: 'flag-dead', severity: 'warn', message: `флаг «${flag}» из реестра не упоминается в контенте`, where: WHERE });
}
}
for (const id of Object.keys(VARS)) {
if (!varsUsed.has(id)) {
out.push({ id: 'var-dead', severity: 'warn', message: `вар «${id}» из реестра не упоминается в контенте`, where: WHERE });
}
}
return out;
}
/** Весь контент разом (для снапшота моста и тестов). */
export function validateContent(maps: Map<string, TileMapData>): Invariant[] {
return mergeInvariants(
...Object.entries(DIALOGUES).map(([id, g]) => validateDialogue(id, g)),
validateNpcs(maps),
validateLocations(maps),
validateEnemies(),
validateReferences()
);
}