hoi4-agent-tools 4.16.0 → 4.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/README.md +1 -0
- package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
- package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
- package/dist/hoi4_agent_tools/core/engine.js +56 -27
- package/dist/hoi4_agent_tools/core/managed-outputs.js +54 -3
- package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
- package/dist/hoi4_agent_tools/core/scanner.js +148 -7
- package/dist/hoi4_agent_tools/core/server-state.js +50 -2
- package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
- package/dist/hoi4_agent_tools/event/compare.js +47 -13
- package/dist/hoi4_agent_tools/event/operations.js +111 -20
- package/dist/hoi4_agent_tools/focus/importer.js +2 -5
- package/dist/hoi4_agent_tools/focus/lint.js +2 -5
- package/dist/hoi4_agent_tools/focus/model.js +19 -0
- package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
- package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
- package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
- package/dist/hoi4_agent_tools/map/border-quality-input.js +57 -8
- package/dist/hoi4_agent_tools/map/border-quality.js +15 -6
- package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
- package/dist/hoi4_agent_tools/map/limits.js +13 -0
- package/dist/hoi4_agent_tools/map/model.js +9 -8
- package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
- package/dist/hoi4_agent_tools/map/operations.js +266 -23
- package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
- package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
- package/dist/hoi4_agent_tools/map/service.js +25 -12
- package/dist/hoi4_agent_tools/map/territory-operations.js +180 -3
- package/dist/hoi4_agent_tools/map/territory-quality.js +72 -5
- package/dist/hoi4_agent_tools/map/territory.js +63 -2
- package/dist/hoi4_agent_tools/map/tool-operations.js +79 -3
- package/dist/hoi4_agent_tools/map/validation.js +23 -3
- package/dist/hoi4_agent_tools/map/water.js +13 -10
- package/dist/hoi4_agent_tools/map/world-outputs.js +41 -26
- package/dist/hoi4_agent_tools/map/world.js +51 -1
- package/dist/hoi4_agent_tools/mcp/tools/map.js +52 -0
- package/dist/hoi4_agent_tools/mcp/tools/reference.js +3 -3
- package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
- package/dist/hoi4_agent_tools/reference/closure.js +65 -0
- package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
- package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
- package/dist/hoi4_agent_tools/reference/operations.js +38 -21
- package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
- package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
- package/dist/hoi4_agent_tools/reference/service.js +45 -2
- package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
- package/dist/hoi4_agent_tools/runtime.js +27 -11
- package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
- package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
- package/dist/hoi4_agent_tools/schemas/map.js +103 -2
- package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
- package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
- package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
- package/dist/hoi4_agent_tools/technology/operations.js +5 -0
- package/dist/hoi4_agent_tools/technology/queries.js +54 -0
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +1 -1
- package/docs/map.md +67 -23
- package/docs/research/reference-benchmark.md +64 -0
- package/docs/tools.md +20 -20
- package/docs/troubleshooting.md +4 -0
- package/engine/bin/darwin-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-x64/hoi4-engine +0 -0
- package/engine/bin/manifest.json +8 -8
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +5 -3
- package/schemas/configuration.schema.json +1 -1
- package/schemas/continuous-focus-palette.schema.json +1 -1
- package/schemas/custom-weighted-pool.schema.json +1 -1
- package/schemas/decision-inspect-input.schema.json +1 -1
- package/schemas/error-log-input.schema.json +1 -1
- package/schemas/event-feature-manifest.schema.json +1 -1
- package/schemas/focus-plan.schema.json +1 -1
- package/schemas/focus-planning-sidecar.schema.json +1 -1
- package/schemas/geography-model.schema.json +1 -1
- package/schemas/gui-animation-source.schema.json +1 -1
- package/schemas/gui-helper.schema.json +1 -1
- package/schemas/gui-scenario.schema.json +1 -1
- package/schemas/helper-expansion-request.schema.json +1 -1
- package/schemas/helper-expansion-summary.schema.json +1 -1
- package/schemas/impact-inspect-input.schema.json +1 -1
- package/schemas/map-operation.schema.json +1087 -815
- package/schemas/mechanic-test-input.schema.json +1 -1
- package/schemas/mod-index-input.schema.json +1 -1
- package/schemas/operation-result.schema.json +1 -1
- package/schemas/package-check-input.schema.json +1 -1
- package/schemas/package-manifest.schema.json +1 -1
- package/schemas/probability-analysis-result.schema.json +1 -1
- package/schemas/probability-compare-input.schema.json +1 -1
- package/schemas/probability-evaluate-input.schema.json +1 -1
- package/schemas/probability-inspect-input.schema.json +1 -1
- package/schemas/probability-render-input.schema.json +1 -1
- package/schemas/probability-scenario-set.schema.json +1 -1
- package/schemas/probability-sequence-input.schema.json +1 -1
- package/schemas/probability-simulate-input.schema.json +1 -1
- package/schemas/probability-sweep-input.schema.json +1 -1
- package/schemas/reference-context-input.schema.json +1 -1
- package/schemas/reference-read-input.schema.json +1 -1
- package/schemas/reference-search-input.schema.json +2 -2
- package/schemas/reference-sheets.schema.json +1 -1
- package/schemas/scenario-suite.schema.json +1 -1
- package/schemas/scenario-test-input.schema.json +1 -1
- package/schemas/script-validate-input.schema.json +7 -1
- package/schemas/shared-scenario.schema.json +1 -1
- package/schemas/source-lookup-input.schema.json +1 -1
- package/server.json +2 -2
|
@@ -29,6 +29,21 @@ const focusRewriteRecipeSchema = z
|
|
|
29
29
|
filesScanned: z.array(z.string().min(1).max(4096)),
|
|
30
30
|
})
|
|
31
31
|
.strict();
|
|
32
|
+
/**
|
|
33
|
+
* The focus files an inspect call reads. A call that names a tree but no file reads only the files
|
|
34
|
+
* that define that tree: importing every focus file of the game to keep one tree took tens of
|
|
35
|
+
* seconds. A tree the index does not know falls back to every file, so the not-found answer is
|
|
36
|
+
* unchanged.
|
|
37
|
+
*/
|
|
38
|
+
function filesForInspect(snapshot, active, relativePath, treeId) {
|
|
39
|
+
if (relativePath !== undefined)
|
|
40
|
+
return active.filter((file) => file.relativePath === relativePath);
|
|
41
|
+
if (treeId === undefined)
|
|
42
|
+
return active;
|
|
43
|
+
const definingPaths = new Set(snapshot.index.findAll('focus_tree', treeId).map(({ path }) => path));
|
|
44
|
+
const defining = active.filter((file) => definingPaths.has(file.displayPath));
|
|
45
|
+
return defining.length === 0 ? active : defining;
|
|
46
|
+
}
|
|
32
47
|
export async function computeFocusVisualRevisions(engine, context, workspaceId, snapshot, selectors) {
|
|
33
48
|
const workspace = engine.resolver.get(workspaceId, context.principal);
|
|
34
49
|
const paletteImport = continuousPalettes(snapshot);
|
|
@@ -576,7 +591,7 @@ export async function inspectFocus(engine, workbench, input, context) {
|
|
|
576
591
|
await context.progress(3, 3, 'Continuous focus inspection complete');
|
|
577
592
|
return { result, sourceRevision: snapshot.revision };
|
|
578
593
|
}
|
|
579
|
-
const selectedFiles = activeFocusFiles(snapshot, workspace.registration.roots.focus)
|
|
594
|
+
const selectedFiles = filesForInspect(snapshot, activeFocusFiles(snapshot, workspace.registration.roots.focus), input.relativePath, input.treeId);
|
|
580
595
|
if (selectedFiles.length === 0)
|
|
581
596
|
throw new ServiceError('FOCUS_SOURCE_NOT_FOUND', 'No active focus source matched the request');
|
|
582
597
|
const selectedSidecarFiles = selectedFiles.flatMap((file) => {
|
|
@@ -98,7 +98,21 @@ export function focusImportOptions(snapshot) {
|
|
|
98
98
|
: { nativeEffects: snapshot.documentedEffects.names }),
|
|
99
99
|
};
|
|
100
100
|
}
|
|
101
|
+
const referenceCatalogs = new WeakMap();
|
|
102
|
+
/**
|
|
103
|
+
* The identifiers of every decision, event, idea and helper in the game and the mod. A scan lists
|
|
104
|
+
* tens of thousands, and one call asks for the catalog once per imported file, so it is built once
|
|
105
|
+
* per scan.
|
|
106
|
+
*/
|
|
101
107
|
export function referenceCatalog(snapshot) {
|
|
108
|
+
const cached = referenceCatalogs.get(snapshot);
|
|
109
|
+
if (cached !== undefined)
|
|
110
|
+
return cached;
|
|
111
|
+
const built = buildReferenceCatalog(snapshot);
|
|
112
|
+
referenceCatalogs.set(snapshot, built);
|
|
113
|
+
return built;
|
|
114
|
+
}
|
|
115
|
+
function buildReferenceCatalog(snapshot) {
|
|
102
116
|
const identifiers = (kind) => [
|
|
103
117
|
...new Set(snapshot.index
|
|
104
118
|
.findAll(kind)
|
|
@@ -161,7 +161,12 @@ function* validateHeightmap(index, raster, report, options) {
|
|
|
161
161
|
}
|
|
162
162
|
const { width, height, kind } = raster;
|
|
163
163
|
const hasLake = kind.includes(LAKE);
|
|
164
|
-
|
|
164
|
+
// Only "farther than the bank allowance" is asked, so the search stops one step past it: a
|
|
165
|
+
// pixel it does not reach holds the limit, which is past the allowance as before. The full
|
|
166
|
+
// field (limit 255) flooded every sea pixel of the map.
|
|
167
|
+
const distance = hasLake
|
|
168
|
+
? landDistanceField(kind, width, height, LAKE_BANK_ALLOWANCE_PX + 1)
|
|
169
|
+
: undefined;
|
|
165
170
|
let lakePixels = 0;
|
|
166
171
|
let landBelow = 0;
|
|
167
172
|
let seaAbove = 0;
|
|
@@ -79,12 +79,59 @@ function labelsFor(index, kinds, label) {
|
|
|
79
79
|
void index;
|
|
80
80
|
return labels;
|
|
81
81
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
82
|
+
export function borderQualityScopeIsEmpty(scope) {
|
|
83
|
+
return (scope === undefined ||
|
|
84
|
+
((scope.owners ?? []).length === 0 &&
|
|
85
|
+
(scope.stateIds ?? []).length === 0 &&
|
|
86
|
+
scope.box === undefined));
|
|
87
|
+
}
|
|
88
|
+
/** The pixel mask of a scope over the province raster, refused when it selects no pixel. */
|
|
89
|
+
export function borderQualityScopeMask(index, scope) {
|
|
90
|
+
const raster = index.raster;
|
|
91
|
+
if (raster === undefined)
|
|
92
|
+
throw new ServiceError('MAP_BORDER_QUALITY_RASTER_MISSING', 'Border naturalness needs a valid province bitmap and definitions');
|
|
93
|
+
const { width, height, provinceIds } = raster;
|
|
94
|
+
const byProvince = (scope.owners ?? []).length > 0 || (scope.stateIds ?? []).length > 0
|
|
95
|
+
? (() => {
|
|
96
|
+
let highest = 0;
|
|
97
|
+
for (const definition of index.definitions)
|
|
98
|
+
highest = Math.max(highest, definition.id);
|
|
99
|
+
const selected = new Uint8Array(highest + 1);
|
|
100
|
+
const owners = new Set(scope.owners ?? []);
|
|
101
|
+
const stateIds = new Set(scope.stateIds ?? []);
|
|
102
|
+
for (const state of index.states)
|
|
103
|
+
if (stateIds.has(state.id) || (state.owner !== undefined && owners.has(state.owner)))
|
|
104
|
+
for (const province of state.provinces)
|
|
105
|
+
if (province >= 0 && province < selected.length)
|
|
106
|
+
selected[province] = 1;
|
|
107
|
+
return selected;
|
|
108
|
+
})()
|
|
109
|
+
: undefined;
|
|
110
|
+
const box = scope.box;
|
|
111
|
+
const x0 = box === undefined ? 0 : Math.max(0, box.x);
|
|
112
|
+
const y0 = box === undefined ? 0 : Math.max(0, box.y);
|
|
113
|
+
const x1 = box === undefined ? width : Math.min(width, box.x + box.width);
|
|
114
|
+
const y1 = box === undefined ? height : Math.min(height, box.y + box.height);
|
|
115
|
+
const mask = new Uint8Array(width * height);
|
|
116
|
+
let pixels = 0;
|
|
117
|
+
for (let y = y0; y < y1; y += 1)
|
|
118
|
+
for (let x = x0; x < x1; x += 1) {
|
|
119
|
+
const pixel = y * width + x;
|
|
120
|
+
const id = provinceIds[pixel];
|
|
121
|
+
if (byProvince !== undefined && (id < 0 || byProvince[id] !== 1))
|
|
122
|
+
continue;
|
|
123
|
+
mask[pixel] = 1;
|
|
124
|
+
pixels += 1;
|
|
125
|
+
}
|
|
126
|
+
if (pixels === 0)
|
|
127
|
+
throw new ServiceError('MAP_BORDER_QUALITY_SCOPE_EMPTY', 'The border quality scope selects no pixel of the province map: check its owners, stateIds and box', {
|
|
128
|
+
...(scope.owners === undefined ? {} : { owners: scope.owners.slice(0, 20) }),
|
|
129
|
+
...(scope.stateIds === undefined ? {} : { stateIds: scope.stateIds.slice(0, 20) }),
|
|
130
|
+
...(box === undefined ? {} : { box }),
|
|
131
|
+
});
|
|
132
|
+
return mask;
|
|
133
|
+
}
|
|
134
|
+
export function borderQualityInputFromIndex(index, scope) {
|
|
88
135
|
const raster = index.raster;
|
|
89
136
|
if (raster === undefined)
|
|
90
137
|
throw new ServiceError('MAP_BORDER_QUALITY_RASTER_MISSING', 'Border naturalness needs a valid province bitmap and definitions');
|
|
@@ -165,13 +212,14 @@ export function borderQualityInputFromIndex(index) {
|
|
|
165
212
|
provinceKinds: kinds,
|
|
166
213
|
layers,
|
|
167
214
|
features,
|
|
215
|
+
...(borderQualityScopeIsEmpty(scope) ? {} : { scope: borderQualityScopeMask(index, scope) }),
|
|
168
216
|
},
|
|
169
217
|
skipped,
|
|
170
218
|
};
|
|
171
219
|
}
|
|
172
220
|
/** Measure the borders of a scanned map workspace. */
|
|
173
|
-
export async function measureIndexBorderNaturalness(index, options = {}) {
|
|
174
|
-
const { input, skipped } = borderQualityInputFromIndex(index);
|
|
221
|
+
export async function measureIndexBorderNaturalness(index, options = {}, scope) {
|
|
222
|
+
const { input, skipped } = borderQualityInputFromIndex(index, scope);
|
|
175
223
|
const result = await measureBorderNaturalness(input, options);
|
|
176
224
|
return { ...result, skipped };
|
|
177
225
|
}
|
|
@@ -180,6 +228,7 @@ export function summarizeBorderQuality(report, skipped) {
|
|
|
180
228
|
return {
|
|
181
229
|
inputs: report.inputs,
|
|
182
230
|
skippedInputs: skipped,
|
|
231
|
+
...(report.scopePixels === undefined ? {} : { scopePixels: report.scopePixels }),
|
|
183
232
|
layers: report.layers.map((layer) => ({
|
|
184
233
|
layer: layer.layer,
|
|
185
234
|
status: layer.status,
|
|
@@ -346,6 +346,8 @@ function validateInput(input) {
|
|
|
346
346
|
});
|
|
347
347
|
if (input.provinceIds.length !== input.width * input.height)
|
|
348
348
|
throw new ServiceError('MAP_BORDER_QUALITY_INPUT_INVALID', 'Border quality province raster does not match its dimensions', { width: input.width, height: input.height, length: input.provinceIds.length });
|
|
349
|
+
if (input.scope !== undefined && input.scope.length !== input.width * input.height)
|
|
350
|
+
throw new ServiceError('MAP_BORDER_QUALITY_INPUT_INVALID', 'Border quality scope does not match the raster dimensions', { width: input.width, height: input.height, length: input.scope.length });
|
|
349
351
|
if (input.layers.length > MAX_LAYERS)
|
|
350
352
|
throw new ServiceError('MAP_BORDER_QUALITY_INPUT_INVALID', 'Too many border layers', {
|
|
351
353
|
layers: input.layers.length,
|
|
@@ -433,7 +435,10 @@ export function* buildBorderEdgeTableSteps(input, options = {}) {
|
|
|
433
435
|
id < provinceKinds.length &&
|
|
434
436
|
(provinceKinds[id] === BORDER_PROVINCE_KIND.sea ||
|
|
435
437
|
provinceKinds[id] === BORDER_PROVINCE_KIND.lake);
|
|
436
|
-
const
|
|
438
|
+
const scope = input.scope;
|
|
439
|
+
const visitPair = (a, b, key, bits, pixel, neighbour) => {
|
|
440
|
+
if (scope !== undefined && scope[pixel] !== 1 && scope[neighbour] !== 1)
|
|
441
|
+
return;
|
|
437
442
|
if (isLand(b)) {
|
|
438
443
|
landPairs += 1;
|
|
439
444
|
if ((bits & BARRIER_MASK) !== 0)
|
|
@@ -465,24 +470,26 @@ export function* buildBorderEdgeTableSteps(input, options = {}) {
|
|
|
465
470
|
// A water pixel's land neighbours are counted from the land side below.
|
|
466
471
|
continue;
|
|
467
472
|
}
|
|
468
|
-
|
|
473
|
+
if (scope === undefined || scope[pixel] === 1)
|
|
474
|
+
landPixels += 1;
|
|
469
475
|
const east = x === width - 1 ? 0 : x + 1;
|
|
470
|
-
visitPair(id, provinceIds[rowStart + east], pixel * 2, current[x] | current[east]);
|
|
476
|
+
visitPair(id, provinceIds[rowStart + east], pixel * 2, current[x] | current[east], pixel, rowStart + east);
|
|
471
477
|
if (y + 1 < height)
|
|
472
|
-
visitPair(id, provinceIds[pixel + width], pixel * 2 + 1, current[x] | next[x]);
|
|
478
|
+
visitPair(id, provinceIds[pixel + width], pixel * 2 + 1, current[x] | next[x], pixel, pixel + width);
|
|
473
479
|
}
|
|
474
480
|
// Coast edges to the north and west of land come from water pixels looking at land.
|
|
475
481
|
for (let x = 0; x < width; x += 1) {
|
|
476
482
|
const id = provinceIds[rowStart + x];
|
|
477
483
|
if (!isWater(id))
|
|
478
484
|
continue;
|
|
485
|
+
const inside = (other) => scope === undefined || scope[rowStart + x] === 1 || scope[other] === 1;
|
|
479
486
|
const east = x === width - 1 ? 0 : x + 1;
|
|
480
487
|
const eastId = provinceIds[rowStart + east];
|
|
481
|
-
if (isLand(eastId))
|
|
488
|
+
if (isLand(eastId) && inside(rowStart + east))
|
|
482
489
|
coastEdgesByProvince[eastId] = coastEdgesByProvince[eastId] + 1;
|
|
483
490
|
if (y + 1 < height) {
|
|
484
491
|
const southId = provinceIds[rowStart + width + x];
|
|
485
|
-
if (isLand(southId))
|
|
492
|
+
if (isLand(southId) && inside(rowStart + width + x))
|
|
486
493
|
coastEdgesByProvince[southId] = coastEdgesByProvince[southId] + 1;
|
|
487
494
|
}
|
|
488
495
|
}
|
|
@@ -511,6 +518,7 @@ export function* buildBorderEdgeTableSteps(input, options = {}) {
|
|
|
511
518
|
extra: input.features?.extra !== undefined,
|
|
512
519
|
},
|
|
513
520
|
options: resolved,
|
|
521
|
+
...(scope === undefined ? {} : { scopePixels: scope.reduce((sum, value) => sum + value, 0) }),
|
|
514
522
|
};
|
|
515
523
|
}
|
|
516
524
|
/** Drive `buildBorderEdgeTableSteps`, yielding to the event loop about every 12 milliseconds. */
|
|
@@ -1093,6 +1101,7 @@ export async function measureBorderNaturalness(input, options = {}) {
|
|
|
1093
1101
|
width: table.width,
|
|
1094
1102
|
height: table.height,
|
|
1095
1103
|
landPixels: table.landPixels,
|
|
1104
|
+
...(table.scopePixels === undefined ? {} : { scopePixels: table.scopePixels }),
|
|
1096
1105
|
inputs: table.inputs,
|
|
1097
1106
|
parameters: {
|
|
1098
1107
|
riverRadius: table.options.riverRadius,
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { z } from 'zod/v4';
|
|
6
|
+
import { compareCodeUnits } from '../core/canonical.js';
|
|
7
|
+
import { locateEngineBinary } from '../core/engine-client.js';
|
|
8
|
+
import { ServiceError } from '../core/result.js';
|
|
9
|
+
import { rgbKey } from './bmp.js';
|
|
10
|
+
/**
|
|
11
|
+
* The province raster from the shared Rust engine (`hoi4-engine map-provinces`, ADR 0084): the
|
|
12
|
+
* province of every pixel, each province's extent, the neighbour graph, seam-only pairs, colours
|
|
13
|
+
* without a definition, coastal provinces and the geometry checks' parts, holes and thin runs.
|
|
14
|
+
* The engine reproduces `buildProvinceRaster` and the TypeScript geometry checks exactly,
|
|
15
|
+
* iteration order included; `scripts/map-raster-parity.ts` compares them on real maps.
|
|
16
|
+
*
|
|
17
|
+
* The call is synchronous because the map model is built in one synchronous pass. It sends the
|
|
18
|
+
* decoded bitmap's bytes and pixel offsets and reads one frame back. A missing engine is
|
|
19
|
+
* `ENGINE_UNAVAILABLE`; nothing falls back to TypeScript.
|
|
20
|
+
*/
|
|
21
|
+
export const MAP_PROVINCES_REQUEST_SCHEMA = 'hoi4-map-provinces-request/1';
|
|
22
|
+
const MAP_PROVINCES_TIMEOUT_MS = 120_000;
|
|
23
|
+
const RESPONSE_JSON_MAX_BYTES = 256 * 1024 * 1024;
|
|
24
|
+
const count = z.number().int().min(0);
|
|
25
|
+
const id = z.number().int();
|
|
26
|
+
const responseSchema = z
|
|
27
|
+
.object({
|
|
28
|
+
schema: z.literal('hoi4-map-provinces/1'),
|
|
29
|
+
width: count,
|
|
30
|
+
height: count,
|
|
31
|
+
geometry: z.array(z.tuple([id, count, count, count, count, count, count, count])),
|
|
32
|
+
adjacency: z.array(z.tuple([id, z.array(id)])),
|
|
33
|
+
seamOnlyPairs: z.array(z.tuple([id, id])),
|
|
34
|
+
unknownColors: z.array(z.tuple([count, count, count, count])),
|
|
35
|
+
unknownColorCount: count,
|
|
36
|
+
coastal: z.array(id),
|
|
37
|
+
components: z.array(z.tuple([id, count])),
|
|
38
|
+
holes: z.array(z.tuple([id, z.number().int()])),
|
|
39
|
+
thin: z.array(id),
|
|
40
|
+
})
|
|
41
|
+
.strict();
|
|
42
|
+
const frameSchema = z.union([
|
|
43
|
+
z.object({ ok: z.literal(true), result: z.unknown(), payload: count }).strict(),
|
|
44
|
+
z
|
|
45
|
+
.object({
|
|
46
|
+
ok: z.literal(false),
|
|
47
|
+
error: z.looseObject({ code: z.string(), message: z.string() }),
|
|
48
|
+
})
|
|
49
|
+
.strict(),
|
|
50
|
+
]);
|
|
51
|
+
function packed(key) {
|
|
52
|
+
const [r, g, b] = key.split(',').map(Number);
|
|
53
|
+
return ((r ?? 0) << 16) | ((g ?? 0) << 8) | (b ?? 0);
|
|
54
|
+
}
|
|
55
|
+
export function engineProvinceRaster(bitmap, definitionsByColor, definitionsById) {
|
|
56
|
+
const located = locateEngineBinary();
|
|
57
|
+
if (!('path' in located))
|
|
58
|
+
throw new ServiceError('ENGINE_UNAVAILABLE', located.message, { reason: located.reason });
|
|
59
|
+
const header = `${JSON.stringify({
|
|
60
|
+
schema: MAP_PROVINCES_REQUEST_SCHEMA,
|
|
61
|
+
width: bitmap.width,
|
|
62
|
+
height: bitmap.height,
|
|
63
|
+
topDown: bitmap.topDown,
|
|
64
|
+
bitsPerPixel: bitmap.bitsPerPixel,
|
|
65
|
+
pixelOffset: bitmap.pixelOffset,
|
|
66
|
+
rowStride: bitmap.rowStride,
|
|
67
|
+
palette: bitmap.palette.map(({ r, g, b }) => [r, g, b]),
|
|
68
|
+
colors: [...definitionsByColor].map(([key, definition]) => [packed(key), definition.id]),
|
|
69
|
+
types: [...definitionsById].map(([provinceId, definition]) => [provinceId, definition.type]),
|
|
70
|
+
payload: bitmap.bytes.length,
|
|
71
|
+
})}\n`;
|
|
72
|
+
const script = /\.(?:c|m)?js$/iu.test(located.path);
|
|
73
|
+
// The frames go through files, not the child's pipes: a synchronous call that wrote hundreds of
|
|
74
|
+
// kilobytes to stdin and read as much from stdout hung until its timeout on macOS runners.
|
|
75
|
+
const directory = mkdtempSync(path.join(tmpdir(), 'hoi4-map-provinces-'));
|
|
76
|
+
const inputPath = path.join(directory, 'request');
|
|
77
|
+
const outputPath = path.join(directory, 'answer');
|
|
78
|
+
let child;
|
|
79
|
+
let stdout;
|
|
80
|
+
try {
|
|
81
|
+
writeFileSync(inputPath, Buffer.concat([Buffer.from(header, 'utf8'), bitmap.bytes]));
|
|
82
|
+
const args = ['map-provinces', '--input', inputPath, '--output', outputPath];
|
|
83
|
+
child = spawnSync(script ? process.execPath : located.path, script ? [located.path, ...args] : args, {
|
|
84
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
85
|
+
maxBuffer: RESPONSE_JSON_MAX_BYTES,
|
|
86
|
+
timeout: MAP_PROVINCES_TIMEOUT_MS,
|
|
87
|
+
windowsHide: true,
|
|
88
|
+
shell: false,
|
|
89
|
+
});
|
|
90
|
+
stdout = existsSync(outputPath) ? readFileSync(outputPath) : Buffer.alloc(0);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
rmSync(directory, { recursive: true, force: true });
|
|
94
|
+
}
|
|
95
|
+
const unavailable = (message) => new ServiceError('ENGINE_UNAVAILABLE', message, { reason: 'invalid_output' });
|
|
96
|
+
if (child.error !== undefined)
|
|
97
|
+
throw new ServiceError('ENGINE_UNAVAILABLE', `hoi4-engine map-provinces: ${child.error.message}`, {
|
|
98
|
+
reason: 'spawn_failed',
|
|
99
|
+
});
|
|
100
|
+
const newline = stdout.indexOf(0x0a);
|
|
101
|
+
if (newline < 0)
|
|
102
|
+
throw unavailable(`hoi4-engine map-provinces gave no answer (exit ${child.status ?? 'none'}): ${child.stderr.toString('utf8').slice(-300)}`);
|
|
103
|
+
const frame = frameSchema.safeParse(JSON.parse(stdout.subarray(0, newline).toString('utf8')));
|
|
104
|
+
if (!frame.success)
|
|
105
|
+
throw unavailable('hoi4-engine map-provinces answered an unknown frame');
|
|
106
|
+
if (!frame.data.ok) {
|
|
107
|
+
const { code, message, ...details } = frame.data.error;
|
|
108
|
+
// The engine names a bad palette index the way BmpImage.rgbAt does.
|
|
109
|
+
if (code === 'MAP_BMP_PALETTE_INDEX_INVALID')
|
|
110
|
+
throw new ServiceError(code, message, details);
|
|
111
|
+
throw new ServiceError('MAP_ENGINE_REQUEST_INVALID', message, { code });
|
|
112
|
+
}
|
|
113
|
+
const response = responseSchema.safeParse(frame.data.result);
|
|
114
|
+
const payload = stdout.subarray(newline + 1);
|
|
115
|
+
if (!response.success ||
|
|
116
|
+
response.data.width !== bitmap.width ||
|
|
117
|
+
response.data.height !== bitmap.height ||
|
|
118
|
+
payload.length !== frame.data.payload ||
|
|
119
|
+
payload.length !== bitmap.width * bitmap.height * 4)
|
|
120
|
+
throw unavailable('hoi4-engine map-provinces answered out of shape');
|
|
121
|
+
const result = response.data;
|
|
122
|
+
// Copied so the ids are aligned, whatever offset the payload has in the output buffer.
|
|
123
|
+
const provinceIds = new Int32Array(payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.length));
|
|
124
|
+
const geometry = new Map();
|
|
125
|
+
for (const [provinceId, pixelCount, minX, minY, maxX, maxY, sumX, sumY] of result.geometry)
|
|
126
|
+
geometry.set(provinceId, {
|
|
127
|
+
id: provinceId,
|
|
128
|
+
pixelCount,
|
|
129
|
+
minX,
|
|
130
|
+
minY,
|
|
131
|
+
maxX,
|
|
132
|
+
maxY,
|
|
133
|
+
centerX: sumX / pixelCount,
|
|
134
|
+
centerY: sumY / pixelCount,
|
|
135
|
+
});
|
|
136
|
+
const color = (rgb) => ({ r: (rgb >> 16) & 0xff, g: (rgb >> 8) & 0xff, b: rgb & 0xff });
|
|
137
|
+
return {
|
|
138
|
+
width: result.width,
|
|
139
|
+
height: result.height,
|
|
140
|
+
provinceIds,
|
|
141
|
+
adjacency: new Map(result.adjacency.map(([provinceId, others]) => [provinceId, new Set(others)])),
|
|
142
|
+
seamOnlyPairs: new Set(result.seamOnlyPairs.map(([low, high]) => `${low}:${high}`)),
|
|
143
|
+
geometry,
|
|
144
|
+
unknownColors: result.unknownColors
|
|
145
|
+
.map(([rgb, pixels, firstX, firstY]) => ({
|
|
146
|
+
color: color(rgb),
|
|
147
|
+
count: pixels,
|
|
148
|
+
firstX,
|
|
149
|
+
firstY,
|
|
150
|
+
}))
|
|
151
|
+
.sort((left, right) => compareCodeUnits(rgbKey(left.color), rgbKey(right.color))),
|
|
152
|
+
unknownColorCount: result.unknownColorCount,
|
|
153
|
+
coastalProvinceIds: new Set(result.coastal),
|
|
154
|
+
topology: {
|
|
155
|
+
components: new Map(result.components),
|
|
156
|
+
holes: new Map(result.holes),
|
|
157
|
+
thin: new Set(result.thin),
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
@@ -12,3 +12,16 @@ export const MAP_PROVINCE_GEOMETRY_SELECTOR_LIMIT = 32;
|
|
|
12
12
|
/** Maximum polygon cell/edge comparisons before rasterization is refused. */
|
|
13
13
|
export const MAP_POLYGON_WORK_LIMIT = 50_000_000;
|
|
14
14
|
export const MAP_SELECTED_OFFSET_BYTES = Uint32Array.BYTES_PER_ELEMENT;
|
|
15
|
+
/** Kinds of natural land (`hoi4.map_inspect` with `lands`). */
|
|
16
|
+
export const NATURAL_LAND_KINDS = [
|
|
17
|
+
'basin',
|
|
18
|
+
'range',
|
|
19
|
+
'forest',
|
|
20
|
+
'marsh',
|
|
21
|
+
'desert',
|
|
22
|
+
'plains',
|
|
23
|
+
];
|
|
24
|
+
/** Terrain classes whose changes are natural-land lines. */
|
|
25
|
+
export const NATURAL_TERRAIN_CLASSES = ['open', 'forest', 'upland', 'marsh', 'desert'];
|
|
26
|
+
/** Natural land ids: `L` and the smallest province id of the land. */
|
|
27
|
+
export const NATURAL_LAND_ID_PATTERN = /^L\d{1,6}$/u;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { compareCodeUnits } from '../core/canonical.js';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { SymbolIndex } from '../core/index.js';
|
|
4
3
|
import { assertRenderDimensions } from '../core/render-budget.js';
|
|
5
4
|
import { addMapDiagnostic, addMapDiagnostics } from './diagnostic-limit.js';
|
|
6
5
|
import { ServiceError } from '../core/result.js';
|
|
7
6
|
import { assignments, assertSourceEncodingPreserved, childBlocks, decodeSource, encodeSource, firstScalar, nodeLocation, parseClausewitz, parseLocalisation, } from '../core/source/index.js';
|
|
8
7
|
import { BmpImage, rgbKey } from './bmp.js';
|
|
8
|
+
import { engineProvinceRaster } from './engine-raster.js';
|
|
9
9
|
const defaultMapIndexSourceRoots = {
|
|
10
10
|
map: ['map'],
|
|
11
11
|
states: ['history/states'],
|
|
@@ -966,6 +966,10 @@ function addNeighbor(adjacency, left, right) {
|
|
|
966
966
|
adjacency.set(left, leftSet);
|
|
967
967
|
adjacency.set(right, rightSet);
|
|
968
968
|
}
|
|
969
|
+
/**
|
|
970
|
+
* The TypeScript raster, kept as the reference the engine's (`engineProvinceRaster`, ADR 0084)
|
|
971
|
+
* is checked against in tests and `scripts/map-raster-parity.ts`. The map model uses the engine.
|
|
972
|
+
*/
|
|
969
973
|
export function buildProvinceRaster(bitmap, definitionsByColor, definitionsById) {
|
|
970
974
|
assertRenderDimensions(bitmap.width, bitmap.height, 'map province raster', {
|
|
971
975
|
maximumPixels: MAP_PROVINCE_ENGINE_MAX_PIXELS,
|
|
@@ -1098,8 +1102,6 @@ export class MapWorkspaceIndex {
|
|
|
1098
1102
|
/** Every scanned root file, including entries shadowed by a higher-load-order root. */
|
|
1099
1103
|
sourceFiles;
|
|
1100
1104
|
sourceRoots;
|
|
1101
|
-
/** Shared cross-domain symbol/reference authority for these exact source bytes. */
|
|
1102
|
-
sharedIndex;
|
|
1103
1105
|
activeFiles;
|
|
1104
1106
|
earliestBookmark;
|
|
1105
1107
|
diagnostics = [];
|
|
@@ -1182,9 +1184,8 @@ export class MapWorkspaceIndex {
|
|
|
1182
1184
|
const color = this.#heightmap.palette[index];
|
|
1183
1185
|
return (color === undefined ? index : color.r) / 10;
|
|
1184
1186
|
}
|
|
1185
|
-
constructor(files, sourceRoots = defaultMapIndexSourceRoots
|
|
1187
|
+
constructor(files, sourceRoots = defaultMapIndexSourceRoots) {
|
|
1186
1188
|
this.sourceFiles = [...files];
|
|
1187
|
-
this.sharedIndex = sharedIndex;
|
|
1188
1189
|
this.sourceRoots = {
|
|
1189
1190
|
map: sourceRoots.map.map(normalizeConfiguredRoot),
|
|
1190
1191
|
states: sourceRoots.states.map(normalizeConfiguredRoot),
|
|
@@ -1243,7 +1244,7 @@ export class MapWorkspaceIndex {
|
|
|
1243
1244
|
}
|
|
1244
1245
|
}
|
|
1245
1246
|
if (this.provinceBitmap !== undefined) {
|
|
1246
|
-
this.raster =
|
|
1247
|
+
this.raster = engineProvinceRaster(this.provinceBitmap, this.definitionsByColor, this.definitionsById);
|
|
1247
1248
|
}
|
|
1248
1249
|
const stateFiles = this.activeFiles.all.filter((file) => inConfiguredRoot(file.relativePath, this.sourceRoots.states));
|
|
1249
1250
|
const activeStatePaths = new Set(stateFiles.map(({ displayPath }) => displayPath));
|
|
@@ -1440,8 +1441,8 @@ export class MapWorkspaceIndex {
|
|
|
1440
1441
|
});
|
|
1441
1442
|
}
|
|
1442
1443
|
}
|
|
1443
|
-
static build(files, sourceRoots = defaultMapIndexSourceRoots
|
|
1444
|
-
return new MapWorkspaceIndex(files, sourceRoots
|
|
1444
|
+
static build(files, sourceRoots = defaultMapIndexSourceRoots) {
|
|
1445
|
+
return new MapWorkspaceIndex(files, sourceRoots);
|
|
1445
1446
|
}
|
|
1446
1447
|
provinceAtMapCoordinate(x, z) {
|
|
1447
1448
|
if (this.raster === undefined)
|