hoi4-agent-tools 4.17.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 +12 -0
- package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
- package/dist/hoi4_agent_tools/event/operations.js +111 -20
- 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/limits.js +13 -0
- package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
- package/dist/hoi4_agent_tools/map/operations.js +246 -18
- package/dist/hoi4_agent_tools/map/territory-operations.js +66 -0
- package/dist/hoi4_agent_tools/map/territory-quality.js +33 -5
- package/dist/hoi4_agent_tools/map/tool-operations.js +52 -2
- package/dist/hoi4_agent_tools/mcp/tools/map.js +29 -0
- package/dist/hoi4_agent_tools/mcp/tools/reference.js +1 -1
- package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
- package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
- package/dist/hoi4_agent_tools/schemas/map.js +70 -2
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/map.md +58 -16
- package/docs/tools.md +1 -1
- package/engine/bin/manifest.json +1 -1
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- 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 +1004 -821
- 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 +1 -1
- 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 +1 -1
- package/schemas/shared-scenario.schema.json +1 -1
- package/schemas/source-lookup-input.schema.json +1 -1
- package/server.json +2 -2
|
@@ -0,0 +1,902 @@
|
|
|
1
|
+
import { setImmediate as yieldToEventLoop } from 'node:timers/promises';
|
|
2
|
+
import { ServiceError } from '../core/result.js';
|
|
3
|
+
import { firstScalar } from '../core/source/index.js';
|
|
4
|
+
import { BORDER_PROVINCE_KIND } from './border-quality.js';
|
|
5
|
+
import { borderQualityInputFromIndex } from './border-quality-input.js';
|
|
6
|
+
import { NATURAL_LAND_KINDS, NATURAL_TERRAIN_CLASSES } from './limits.js';
|
|
7
|
+
/**
|
|
8
|
+
* Natural lands: the land provinces of a map cut into the pieces its ground suggests. Lines run
|
|
9
|
+
* where neighbouring provinces are split by a major river, a crest or a change of terrain class;
|
|
10
|
+
* open country without such lines is cut into drainage basins (each province drains to its lowest
|
|
11
|
+
* neighbour, coasts and lakes are sinks), and fragments below a minimum size join the neighbour
|
|
12
|
+
* across their weakest line. The result is deterministic for the same map and options.
|
|
13
|
+
*/
|
|
14
|
+
export { NATURAL_LAND_KINDS, NATURAL_TERRAIN_CLASSES };
|
|
15
|
+
/** Default class of a provincial terrain category; any other category is open ground. */
|
|
16
|
+
export const NATURAL_TERRAIN_CLASS_DEFAULTS = {
|
|
17
|
+
desert: 'desert',
|
|
18
|
+
forest: 'forest',
|
|
19
|
+
hills: 'upland',
|
|
20
|
+
jungle: 'forest',
|
|
21
|
+
marsh: 'marsh',
|
|
22
|
+
mountain: 'upland',
|
|
23
|
+
};
|
|
24
|
+
/** Highest `rivers.bmp` index that is a river width; higher indices are land and water. */
|
|
25
|
+
const RIVER_WIDTH_MAX_INDEX = 11;
|
|
26
|
+
/** Strength of a line kind when choosing the weakest line to merge a fragment across. */
|
|
27
|
+
const LINE_STRENGTH = { impassable: 2, river: 1, crest: 1, terrain: 0.5, divide: 0.2 };
|
|
28
|
+
/** `walls` plane value of a wall. */
|
|
29
|
+
const WALL_VALUE = 255;
|
|
30
|
+
const CLASS_PRIORITY = [
|
|
31
|
+
'upland',
|
|
32
|
+
'forest',
|
|
33
|
+
'marsh',
|
|
34
|
+
'desert',
|
|
35
|
+
'open',
|
|
36
|
+
];
|
|
37
|
+
const MAX_PROVINCES = 65_535;
|
|
38
|
+
function invalid(option, message, value) {
|
|
39
|
+
return new ServiceError('MAP_NATURAL_LANDS_OPTION_INVALID', message, { option, value });
|
|
40
|
+
}
|
|
41
|
+
export function resolveNaturalLandsOptions(options = {}) {
|
|
42
|
+
const minProvinces = options.minProvinces ?? 6;
|
|
43
|
+
const minBasinProvinces = options.minBasinProvinces ?? minProvinces;
|
|
44
|
+
const maxBasinProvinces = options.maxBasinProvinces ?? null;
|
|
45
|
+
const riverMajorIndex = options.riverMajorIndex ?? 6;
|
|
46
|
+
const riverShare = options.riverShare ?? 0.4;
|
|
47
|
+
const crestExcess = options.crestExcess ?? 3.5;
|
|
48
|
+
for (const [name, value, minimum, maximum] of [
|
|
49
|
+
['minProvinces', minProvinces, 1, 10_000],
|
|
50
|
+
['minBasinProvinces', minBasinProvinces, 1, 10_000],
|
|
51
|
+
['riverMajorIndex', riverMajorIndex, 0, RIVER_WIDTH_MAX_INDEX],
|
|
52
|
+
])
|
|
53
|
+
if (!Number.isInteger(value) || value < minimum || value > maximum)
|
|
54
|
+
throw invalid(name, `${name} must be an integer from ${minimum} to ${maximum}`, value);
|
|
55
|
+
if (maxBasinProvinces !== null &&
|
|
56
|
+
(!Number.isInteger(maxBasinProvinces) ||
|
|
57
|
+
maxBasinProvinces < 2 * minBasinProvinces ||
|
|
58
|
+
maxBasinProvinces > 100_000))
|
|
59
|
+
throw invalid('maxBasinProvinces', 'maxBasinProvinces must be an integer from twice minBasinProvinces to 100000', maxBasinProvinces);
|
|
60
|
+
if (!Number.isFinite(riverShare) || riverShare <= 0 || riverShare > 1)
|
|
61
|
+
throw invalid('riverShare', 'riverShare must be above 0 and at most 1', riverShare);
|
|
62
|
+
if (!Number.isFinite(crestExcess) || crestExcess <= 0 || crestExcess > 255)
|
|
63
|
+
throw invalid('crestExcess', 'crestExcess must be above 0 and at most 255', crestExcess);
|
|
64
|
+
const terrainClasses = {};
|
|
65
|
+
for (const [name, value] of Object.entries(options.terrainClasses ?? {}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
|
|
66
|
+
if (!NATURAL_TERRAIN_CLASSES.includes(value))
|
|
67
|
+
throw invalid('terrainClasses', `Terrain class of ${name} is not a known class`, value);
|
|
68
|
+
terrainClasses[name.toLowerCase()] = value;
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
minProvinces,
|
|
72
|
+
minBasinProvinces,
|
|
73
|
+
maxBasinProvinces,
|
|
74
|
+
riverMajorIndex,
|
|
75
|
+
riverShare,
|
|
76
|
+
crestExcess,
|
|
77
|
+
splitRangesAtCrests: options.splitRangesAtCrests ?? false,
|
|
78
|
+
terrainClasses,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
const PAIR_RIVER = 1;
|
|
82
|
+
const PAIR_CREST = 2;
|
|
83
|
+
const PAIR_TERRAIN = 4;
|
|
84
|
+
const PAIR_CUT = 8;
|
|
85
|
+
const PAIR_IMPASSABLE = 16;
|
|
86
|
+
const PAIR_LINES = PAIR_RIVER | PAIR_CREST | PAIR_TERRAIN | PAIR_IMPASSABLE;
|
|
87
|
+
function classOfTerrain(terrain, overrides) {
|
|
88
|
+
const key = terrain.toLowerCase();
|
|
89
|
+
return overrides[key] ?? NATURAL_TERRAIN_CLASS_DEFAULTS[key] ?? 'open';
|
|
90
|
+
}
|
|
91
|
+
function* scanRaster(input, options, signal) {
|
|
92
|
+
const { width, height, provinceIds, provinceKinds } = input;
|
|
93
|
+
const count = provinceKinds.length;
|
|
94
|
+
if (provinceIds.length !== width * height)
|
|
95
|
+
throw new ServiceError('MAP_NATURAL_LANDS_INPUT_INVALID', 'The province raster does not match its dimensions', { width, height, length: provinceIds.length });
|
|
96
|
+
if (count > MAX_PROVINCES + 1)
|
|
97
|
+
throw new ServiceError('MAP_NATURAL_LANDS_INPUT_INVALID', `Natural lands support province ids up to ${MAX_PROVINCES}`, { provinces: count });
|
|
98
|
+
for (const [name, plane] of [
|
|
99
|
+
['heights', input.heights],
|
|
100
|
+
['rivers', input.rivers],
|
|
101
|
+
['walls', input.walls],
|
|
102
|
+
])
|
|
103
|
+
if (plane !== undefined && (plane.width !== width || plane.height !== height))
|
|
104
|
+
throw new ServiceError('MAP_NATURAL_LANDS_INPUT_INVALID', `The ${name} plane must match the province raster size`, { plane: name, width: plane.width, height: plane.height });
|
|
105
|
+
const land = new Uint8Array(count);
|
|
106
|
+
const coast = new Uint8Array(count);
|
|
107
|
+
const lake = new Uint8Array(count);
|
|
108
|
+
const pixels = new Uint32Array(count);
|
|
109
|
+
const heightSum = new Float64Array(count);
|
|
110
|
+
const kindOf = (id) => (id >= 0 && id < count ? provinceKinds[id] : 0);
|
|
111
|
+
let capacity = 4_096;
|
|
112
|
+
let pairA = new Int32Array(capacity);
|
|
113
|
+
let pairB = new Int32Array(capacity);
|
|
114
|
+
let pairLength = new Uint32Array(capacity);
|
|
115
|
+
let pairRiver = new Uint32Array(capacity);
|
|
116
|
+
let pairHeight = new Float64Array(capacity);
|
|
117
|
+
let pairWall = new Uint32Array(capacity);
|
|
118
|
+
let pairs = 0;
|
|
119
|
+
const slots = new Map();
|
|
120
|
+
const major = (value) => value >= options.riverMajorIndex && value <= RIVER_WIDTH_MAX_INDEX;
|
|
121
|
+
const heightRows = [new Uint8Array(width), new Uint8Array(width)];
|
|
122
|
+
const riverRows = [new Uint8Array(width), new Uint8Array(width)];
|
|
123
|
+
const wallRows = [new Uint8Array(width), new Uint8Array(width)];
|
|
124
|
+
/** Bit 1: the edge touches a major river pixel; bit 2: a wall pixel. */
|
|
125
|
+
const marksOf = (riverA, riverB, wallA, wallB) => (major(riverA) || major(riverB) ? 1 : 0) |
|
|
126
|
+
(wallA === WALL_VALUE || wallB === WALL_VALUE ? 2 : 0);
|
|
127
|
+
const visit = (a, b, heightA, heightB, marks) => {
|
|
128
|
+
if (a === b)
|
|
129
|
+
return;
|
|
130
|
+
const kindA = kindOf(a);
|
|
131
|
+
const kindB = kindOf(b);
|
|
132
|
+
if (kindA === BORDER_PROVINCE_KIND.land && kindB === BORDER_PROVINCE_KIND.land) {
|
|
133
|
+
const low = a < b ? a : b;
|
|
134
|
+
const high = a < b ? b : a;
|
|
135
|
+
const key = low * 65_536 + high;
|
|
136
|
+
let slot = slots.get(key);
|
|
137
|
+
if (slot === undefined) {
|
|
138
|
+
slot = pairs;
|
|
139
|
+
pairs += 1;
|
|
140
|
+
if (slot === capacity) {
|
|
141
|
+
capacity *= 2;
|
|
142
|
+
const grow = (array) => {
|
|
143
|
+
const bigger = new array.constructor(capacity);
|
|
144
|
+
bigger.set(array);
|
|
145
|
+
return bigger;
|
|
146
|
+
};
|
|
147
|
+
pairA = grow(pairA);
|
|
148
|
+
pairB = grow(pairB);
|
|
149
|
+
pairLength = grow(pairLength);
|
|
150
|
+
pairRiver = grow(pairRiver);
|
|
151
|
+
pairHeight = grow(pairHeight);
|
|
152
|
+
pairWall = grow(pairWall);
|
|
153
|
+
}
|
|
154
|
+
pairA[slot] = low;
|
|
155
|
+
pairB[slot] = high;
|
|
156
|
+
slots.set(key, slot);
|
|
157
|
+
}
|
|
158
|
+
pairLength[slot] += 1;
|
|
159
|
+
if ((marks & 1) !== 0)
|
|
160
|
+
pairRiver[slot] += 1;
|
|
161
|
+
if ((marks & 2) !== 0)
|
|
162
|
+
pairWall[slot] += 1;
|
|
163
|
+
pairHeight[slot] += (heightA + heightB) / 2;
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (kindA === BORDER_PROVINCE_KIND.land) {
|
|
167
|
+
if (kindB === BORDER_PROVINCE_KIND.sea)
|
|
168
|
+
coast[a] = 1;
|
|
169
|
+
else if (kindB === BORDER_PROVINCE_KIND.lake)
|
|
170
|
+
lake[a] = 1;
|
|
171
|
+
}
|
|
172
|
+
else if (kindB === BORDER_PROVINCE_KIND.land) {
|
|
173
|
+
if (kindA === BORDER_PROVINCE_KIND.sea)
|
|
174
|
+
coast[b] = 1;
|
|
175
|
+
else if (kindA === BORDER_PROVINCE_KIND.lake)
|
|
176
|
+
lake[b] = 1;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
const readRows = (y, slot) => {
|
|
180
|
+
input.heights?.readRow(y, heightRows[slot]);
|
|
181
|
+
input.rivers?.readRow(y, riverRows[slot]);
|
|
182
|
+
input.walls?.readRow(y, wallRows[slot]);
|
|
183
|
+
};
|
|
184
|
+
readRows(0, 0);
|
|
185
|
+
let here = 0;
|
|
186
|
+
for (let y = 0; y < height; y += 1) {
|
|
187
|
+
if (y % 64 === 0) {
|
|
188
|
+
signal?.throwIfAborted();
|
|
189
|
+
if (y > 0)
|
|
190
|
+
yield;
|
|
191
|
+
}
|
|
192
|
+
const next = 1 - here;
|
|
193
|
+
if (y + 1 < height)
|
|
194
|
+
readRows(y + 1, next);
|
|
195
|
+
const heightsHere = heightRows[here];
|
|
196
|
+
const heightsNext = heightRows[next];
|
|
197
|
+
const riversHere = riverRows[here];
|
|
198
|
+
const riversNext = riverRows[next];
|
|
199
|
+
const wallsHere = wallRows[here];
|
|
200
|
+
const wallsNext = wallRows[next];
|
|
201
|
+
const rowStart = y * width;
|
|
202
|
+
for (let x = 0; x < width; x += 1) {
|
|
203
|
+
const pixel = rowStart + x;
|
|
204
|
+
const id = provinceIds[pixel];
|
|
205
|
+
if (kindOf(id) === BORDER_PROVINCE_KIND.land) {
|
|
206
|
+
land[id] = 1;
|
|
207
|
+
pixels[id] += 1;
|
|
208
|
+
heightSum[id] += heightsHere[x];
|
|
209
|
+
}
|
|
210
|
+
const east = x === width - 1 ? 0 : x + 1;
|
|
211
|
+
const eastId = provinceIds[rowStart + east];
|
|
212
|
+
if (eastId !== id)
|
|
213
|
+
visit(id, eastId, heightsHere[x], heightsHere[east], marksOf(riversHere[x], riversHere[east], wallsHere[x], wallsHere[east]));
|
|
214
|
+
if (y + 1 < height) {
|
|
215
|
+
const southId = provinceIds[pixel + width];
|
|
216
|
+
if (southId !== id)
|
|
217
|
+
visit(id, southId, heightsHere[x], heightsNext[x], marksOf(riversHere[x], riversNext[x], wallsHere[x], wallsNext[x]));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
here = next;
|
|
221
|
+
}
|
|
222
|
+
const meanHeight = new Float64Array(count);
|
|
223
|
+
const classOf = new Array(count).fill('open');
|
|
224
|
+
for (let id = 0; id < count; id += 1) {
|
|
225
|
+
if (pixels[id] > 0)
|
|
226
|
+
meanHeight[id] = heightSum[id] / pixels[id];
|
|
227
|
+
classOf[id] = classOfTerrain(input.provinceTerrain[id] ?? '', options.terrainClasses);
|
|
228
|
+
}
|
|
229
|
+
const impassableLand = new Uint8Array(count);
|
|
230
|
+
for (const province of input.impassableProvinces ?? [])
|
|
231
|
+
if (Number.isInteger(province) && province >= 0 && province < count)
|
|
232
|
+
impassableLand[province] = 1;
|
|
233
|
+
const impassableRows = new Set();
|
|
234
|
+
for (const [from, to] of input.impassablePairs ?? [])
|
|
235
|
+
if (Number.isInteger(from) && Number.isInteger(to) && from >= 0 && to >= 0)
|
|
236
|
+
impassableRows.add(Math.min(from, to) * 65_536 + Math.max(from, to));
|
|
237
|
+
// Order pairs by (low, high) so every later walk is deterministic.
|
|
238
|
+
const order = Array.from({ length: pairs }, (_, i) => i).sort((x, y) => pairA[x] - pairA[y] || pairB[x] - pairB[y]);
|
|
239
|
+
const table = {
|
|
240
|
+
count: pairs,
|
|
241
|
+
a: new Int32Array(pairs),
|
|
242
|
+
b: new Int32Array(pairs),
|
|
243
|
+
length: new Uint32Array(pairs),
|
|
244
|
+
pass: new Float64Array(pairs),
|
|
245
|
+
flags: new Uint8Array(pairs),
|
|
246
|
+
};
|
|
247
|
+
for (const [slot, from] of order.entries()) {
|
|
248
|
+
const a = pairA[from];
|
|
249
|
+
const b = pairB[from];
|
|
250
|
+
const length = pairLength[from];
|
|
251
|
+
const pass = pairHeight[from] / length;
|
|
252
|
+
let flags = 0;
|
|
253
|
+
if (input.rivers !== undefined && pairRiver[from] / length >= options.riverShare)
|
|
254
|
+
flags |= PAIR_RIVER;
|
|
255
|
+
if (input.heights !== undefined &&
|
|
256
|
+
pass - Math.max(meanHeight[a], meanHeight[b]) >= options.crestExcess)
|
|
257
|
+
flags |= PAIR_CREST;
|
|
258
|
+
if (classOf[a] !== classOf[b])
|
|
259
|
+
flags |= PAIR_TERRAIN;
|
|
260
|
+
// An impassable row, the edge of impassable land (a border inside it is not), or a wall.
|
|
261
|
+
if (impassableRows.has(a * 65_536 + b) ||
|
|
262
|
+
impassableLand[a] !== impassableLand[b] ||
|
|
263
|
+
(input.walls !== undefined && pairWall[from] / length >= options.riverShare))
|
|
264
|
+
flags |= PAIR_IMPASSABLE;
|
|
265
|
+
const bothUpland = classOf[a] === 'upland' && classOf[b] === 'upland';
|
|
266
|
+
if ((flags & (PAIR_RIVER | PAIR_TERRAIN | PAIR_IMPASSABLE)) !== 0 ||
|
|
267
|
+
((flags & PAIR_CREST) !== 0 && (options.splitRangesAtCrests || !bothUpland)))
|
|
268
|
+
flags |= PAIR_CUT;
|
|
269
|
+
table.a[slot] = a;
|
|
270
|
+
table.b[slot] = b;
|
|
271
|
+
table.length[slot] = length;
|
|
272
|
+
table.pass[slot] = pass;
|
|
273
|
+
table.flags[slot] = flags;
|
|
274
|
+
}
|
|
275
|
+
return { facts: { land, pixels, meanHeight, coast, lake, classOf }, pairs: table };
|
|
276
|
+
}
|
|
277
|
+
function buildAdjacency(count, pairs) {
|
|
278
|
+
const offsets = new Int32Array(count + 1);
|
|
279
|
+
for (let i = 0; i < pairs.count; i += 1) {
|
|
280
|
+
offsets[pairs.a[i] + 1] += 1;
|
|
281
|
+
offsets[pairs.b[i] + 1] += 1;
|
|
282
|
+
}
|
|
283
|
+
for (let i = 0; i < count; i += 1)
|
|
284
|
+
offsets[i + 1] += offsets[i];
|
|
285
|
+
const cursor = offsets.slice(0, count);
|
|
286
|
+
const to = new Int32Array(offsets[count]);
|
|
287
|
+
const pair = new Int32Array(offsets[count]);
|
|
288
|
+
// Pairs are sorted by (low, high), so each row is filled in ascending neighbour order per side.
|
|
289
|
+
for (let i = 0; i < pairs.count; i += 1) {
|
|
290
|
+
const a = pairs.a[i];
|
|
291
|
+
const b = pairs.b[i];
|
|
292
|
+
to[cursor[a]] = b;
|
|
293
|
+
pair[cursor[a]++] = i;
|
|
294
|
+
to[cursor[b]] = a;
|
|
295
|
+
pair[cursor[b]++] = i;
|
|
296
|
+
}
|
|
297
|
+
return { offsets, to, pair };
|
|
298
|
+
}
|
|
299
|
+
/** A binary min-heap of `[size, key, group]` entries. */
|
|
300
|
+
class GroupHeap {
|
|
301
|
+
#items = [];
|
|
302
|
+
get size() {
|
|
303
|
+
return this.#items.length;
|
|
304
|
+
}
|
|
305
|
+
static #less(x, y) {
|
|
306
|
+
return x[0] < y[0] || (x[0] === y[0] && x[1] < y[1]);
|
|
307
|
+
}
|
|
308
|
+
push(item) {
|
|
309
|
+
const items = this.#items;
|
|
310
|
+
items.push(item);
|
|
311
|
+
let i = items.length - 1;
|
|
312
|
+
while (i > 0) {
|
|
313
|
+
const parent = (i - 1) >> 1;
|
|
314
|
+
if (!GroupHeap.#less(items[i], items[parent]))
|
|
315
|
+
break;
|
|
316
|
+
[items[i], items[parent]] = [items[parent], items[i]];
|
|
317
|
+
i = parent;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
pop() {
|
|
321
|
+
const items = this.#items;
|
|
322
|
+
if (items.length === 0)
|
|
323
|
+
return undefined;
|
|
324
|
+
const top = items[0];
|
|
325
|
+
const last = items.pop();
|
|
326
|
+
if (items.length > 0) {
|
|
327
|
+
items[0] = last;
|
|
328
|
+
let i = 0;
|
|
329
|
+
for (;;) {
|
|
330
|
+
const left = 2 * i + 1;
|
|
331
|
+
const right = left + 1;
|
|
332
|
+
let smallest = i;
|
|
333
|
+
if (left < items.length && GroupHeap.#less(items[left], items[smallest]))
|
|
334
|
+
smallest = left;
|
|
335
|
+
if (right < items.length && GroupHeap.#less(items[right], items[smallest]))
|
|
336
|
+
smallest = right;
|
|
337
|
+
if (smallest === i)
|
|
338
|
+
break;
|
|
339
|
+
[items[i], items[smallest]] = [items[smallest], items[i]];
|
|
340
|
+
i = smallest;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return top;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function pairStrength(flags) {
|
|
347
|
+
if ((flags & PAIR_IMPASSABLE) !== 0)
|
|
348
|
+
return LINE_STRENGTH.impassable;
|
|
349
|
+
let strength = LINE_STRENGTH.divide;
|
|
350
|
+
if ((flags & PAIR_RIVER) !== 0)
|
|
351
|
+
strength = Math.max(strength, LINE_STRENGTH.river);
|
|
352
|
+
if ((flags & PAIR_CREST) !== 0)
|
|
353
|
+
strength = Math.max(strength, LINE_STRENGTH.crest);
|
|
354
|
+
if ((flags & PAIR_TERRAIN) !== 0)
|
|
355
|
+
strength = Math.max(strength, LINE_STRENGTH.terrain);
|
|
356
|
+
return strength;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Groups of provinces that merge into neighbours: every merge joins the smallest group below the
|
|
360
|
+
* minimum (ties by smallest province id) into the neighbour the caller chooses.
|
|
361
|
+
*/
|
|
362
|
+
class GroupGraph {
|
|
363
|
+
members;
|
|
364
|
+
key;
|
|
365
|
+
alive;
|
|
366
|
+
adjacent;
|
|
367
|
+
constructor(groups, groupOf, pairs) {
|
|
368
|
+
this.members = groups.map((group) => [...group]);
|
|
369
|
+
this.key = groups.map((group) => group.reduce((lowest, province) => (province < lowest ? province : lowest), Infinity));
|
|
370
|
+
this.alive = groups.map(() => true);
|
|
371
|
+
this.adjacent = groups.map(() => new Map());
|
|
372
|
+
for (let i = 0; i < pairs.count; i += 1) {
|
|
373
|
+
const x = groupOf[pairs.a[i]];
|
|
374
|
+
const y = groupOf[pairs.b[i]];
|
|
375
|
+
if (x < 0 || y < 0 || x === y)
|
|
376
|
+
continue;
|
|
377
|
+
const shared = {
|
|
378
|
+
length: pairs.length[i],
|
|
379
|
+
strength: pairStrength(pairs.flags[i]) * pairs.length[i],
|
|
380
|
+
pass: pairs.pass[i],
|
|
381
|
+
impassable: (pairs.flags[i] & PAIR_IMPASSABLE) !== 0 ? pairs.length[i] : 0,
|
|
382
|
+
};
|
|
383
|
+
GroupGraph.#add(this.adjacent[x], y, shared);
|
|
384
|
+
GroupGraph.#add(this.adjacent[y], x, shared);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
static #add(row, other, shared) {
|
|
388
|
+
const entry = row.get(other);
|
|
389
|
+
if (entry === undefined)
|
|
390
|
+
row.set(other, { ...shared });
|
|
391
|
+
else {
|
|
392
|
+
entry.length += shared.length;
|
|
393
|
+
entry.strength += shared.strength;
|
|
394
|
+
entry.pass = Math.min(entry.pass, shared.pass);
|
|
395
|
+
entry.impassable += shared.impassable;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
merge(into, from) {
|
|
399
|
+
this.members[into].push(...this.members[from]);
|
|
400
|
+
this.key[into] = Math.min(this.key[into], this.key[from]);
|
|
401
|
+
this.alive[from] = false;
|
|
402
|
+
const row = this.adjacent[into];
|
|
403
|
+
row.delete(from);
|
|
404
|
+
for (const [other, shared] of this.adjacent[from]) {
|
|
405
|
+
if (other === into)
|
|
406
|
+
continue;
|
|
407
|
+
GroupGraph.#add(row, other, shared);
|
|
408
|
+
const otherRow = this.adjacent[other];
|
|
409
|
+
otherRow.delete(from);
|
|
410
|
+
GroupGraph.#add(otherRow, into, shared);
|
|
411
|
+
}
|
|
412
|
+
this.adjacent[from].clear();
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Merge every group below `minimum` into the neighbour `better` ranks first, smallest first.
|
|
416
|
+
* Groups with no eligible neighbour stay as they are; groups that share an impassable border
|
|
417
|
+
* are never eligible.
|
|
418
|
+
*/
|
|
419
|
+
mergeSmall(minimum, eligible, better) {
|
|
420
|
+
const heap = new GroupHeap();
|
|
421
|
+
for (let group = 0; group < this.members.length; group += 1)
|
|
422
|
+
if (this.alive[group] && this.members[group].length < minimum)
|
|
423
|
+
heap.push([this.members[group].length, this.key[group], group]);
|
|
424
|
+
for (let entry = heap.pop(); entry !== undefined; entry = heap.pop()) {
|
|
425
|
+
const [size, , group] = entry;
|
|
426
|
+
if (!this.alive[group] || this.members[group].length !== size || size >= minimum)
|
|
427
|
+
continue;
|
|
428
|
+
let best;
|
|
429
|
+
for (const candidate of this.adjacent[group]) {
|
|
430
|
+
if (!this.alive[candidate[0]] ||
|
|
431
|
+
candidate[1].impassable > 0 ||
|
|
432
|
+
!eligible(group, candidate[0]))
|
|
433
|
+
continue;
|
|
434
|
+
if (best === undefined || better(candidate, best))
|
|
435
|
+
best = candidate;
|
|
436
|
+
}
|
|
437
|
+
if (best === undefined)
|
|
438
|
+
continue;
|
|
439
|
+
const target = best[0];
|
|
440
|
+
this.merge(target, group);
|
|
441
|
+
if (this.members[target].length < minimum)
|
|
442
|
+
heap.push([this.members[target].length, this.key[target], target]);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
groups() {
|
|
446
|
+
return this.members
|
|
447
|
+
.filter((_, group) => this.alive[group])
|
|
448
|
+
.map((members) => [...members].sort((x, y) => x - y));
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
function connectedComponents(provinces, adjacency, joined, inside, componentOf, first) {
|
|
452
|
+
const components = [];
|
|
453
|
+
for (const start of provinces) {
|
|
454
|
+
if (componentOf[start] >= 0)
|
|
455
|
+
continue;
|
|
456
|
+
const id = first + components.length;
|
|
457
|
+
const component = [];
|
|
458
|
+
const stack = [start];
|
|
459
|
+
componentOf[start] = id;
|
|
460
|
+
while (stack.length > 0) {
|
|
461
|
+
const province = stack.pop();
|
|
462
|
+
component.push(province);
|
|
463
|
+
for (let slot = adjacency.offsets[province]; slot < adjacency.offsets[province + 1]; slot++) {
|
|
464
|
+
const other = adjacency.to[slot];
|
|
465
|
+
if (componentOf[other] >= 0 || !inside(other) || !joined(adjacency.pair[slot]))
|
|
466
|
+
continue;
|
|
467
|
+
componentOf[other] = id;
|
|
468
|
+
stack.push(other);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
components.push(component.sort((x, y) => x - y));
|
|
472
|
+
}
|
|
473
|
+
return components;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Split every piece that holds both ends of an impassable border (joined around the end of the
|
|
477
|
+
* line) between the two ends: each province goes to the end it is fewer steps from within the
|
|
478
|
+
* piece, the lower end on a tie, until no piece holds both ends of one.
|
|
479
|
+
*/
|
|
480
|
+
function separateImpassable(components, adjacency, pairs, joined, componentOf) {
|
|
481
|
+
const impassable = [];
|
|
482
|
+
for (let i = 0; i < pairs.count; i += 1)
|
|
483
|
+
if ((pairs.flags[i] & PAIR_IMPASSABLE) !== 0)
|
|
484
|
+
impassable.push(i);
|
|
485
|
+
if (impassable.length === 0)
|
|
486
|
+
return components;
|
|
487
|
+
const result = [];
|
|
488
|
+
const work = [...components];
|
|
489
|
+
let nextId = components.length;
|
|
490
|
+
const distance = new Int32Array(componentOf.length).fill(-1);
|
|
491
|
+
const side = new Int32Array(componentOf.length).fill(-1);
|
|
492
|
+
for (let piece = work.shift(); piece !== undefined; piece = work.shift()) {
|
|
493
|
+
const id = componentOf[piece[0]];
|
|
494
|
+
const clash = impassable.find((pair) => componentOf[pairs.a[pair]] === id && componentOf[pairs.b[pair]] === id);
|
|
495
|
+
if (clash === undefined) {
|
|
496
|
+
result.push(piece);
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
const ends = [pairs.a[clash], pairs.b[clash]];
|
|
500
|
+
for (const province of piece) {
|
|
501
|
+
distance[province] = -1;
|
|
502
|
+
side[province] = -1;
|
|
503
|
+
}
|
|
504
|
+
let frontier = ends.map((end, position) => {
|
|
505
|
+
distance[end] = 0;
|
|
506
|
+
side[end] = position;
|
|
507
|
+
return end;
|
|
508
|
+
});
|
|
509
|
+
for (let step = 1; frontier.length > 0; step += 1) {
|
|
510
|
+
const next = [];
|
|
511
|
+
// Visit in end order so the lower end wins a tie.
|
|
512
|
+
for (const province of frontier)
|
|
513
|
+
for (let slot = adjacency.offsets[province]; slot < adjacency.offsets[province + 1]; slot++) {
|
|
514
|
+
const other = adjacency.to[slot];
|
|
515
|
+
if (componentOf[other] !== id || distance[other] >= 0 || !joined(adjacency.pair[slot]))
|
|
516
|
+
continue;
|
|
517
|
+
distance[other] = step;
|
|
518
|
+
side[other] = side[province];
|
|
519
|
+
next.push(other);
|
|
520
|
+
}
|
|
521
|
+
frontier = next;
|
|
522
|
+
}
|
|
523
|
+
const parts = [[], []];
|
|
524
|
+
for (const province of piece)
|
|
525
|
+
parts[side[province]].push(province);
|
|
526
|
+
const second = nextId;
|
|
527
|
+
nextId += 1;
|
|
528
|
+
for (const province of parts[1])
|
|
529
|
+
componentOf[province] = second;
|
|
530
|
+
work.unshift(parts[0], parts[1]);
|
|
531
|
+
}
|
|
532
|
+
// Number the pieces in order again, as the caller indexes them.
|
|
533
|
+
result.sort((x, y) => x[0] - y[0]);
|
|
534
|
+
for (const [index, piece] of result.entries())
|
|
535
|
+
for (const province of piece)
|
|
536
|
+
componentOf[province] = index;
|
|
537
|
+
return result;
|
|
538
|
+
}
|
|
539
|
+
/** Split a basin larger than `maximum` at branch points of its drainage tree. */
|
|
540
|
+
function splitBasin(basin, down, meanHeight, minimum, maximum) {
|
|
541
|
+
if (basin.length <= maximum)
|
|
542
|
+
return [basin];
|
|
543
|
+
const inBasin = new Set(basin);
|
|
544
|
+
const parent = (province) => {
|
|
545
|
+
const next = down[province];
|
|
546
|
+
return next >= 0 && inBasin.has(next) ? next : -1;
|
|
547
|
+
};
|
|
548
|
+
// Downstream provinces are strictly lower, so descending height visits children first.
|
|
549
|
+
const descending = [...basin].sort((x, y) => meanHeight[y] - meanHeight[x] || x - y);
|
|
550
|
+
const subtree = new Map();
|
|
551
|
+
const children = new Map();
|
|
552
|
+
let roots = 0;
|
|
553
|
+
for (const province of descending) {
|
|
554
|
+
const size = (subtree.get(province) ?? 0) + 1;
|
|
555
|
+
subtree.set(province, size);
|
|
556
|
+
const up = parent(province);
|
|
557
|
+
if (up < 0)
|
|
558
|
+
roots += 1;
|
|
559
|
+
else {
|
|
560
|
+
subtree.set(up, (subtree.get(up) ?? 0) + size);
|
|
561
|
+
children.set(up, (children.get(up) ?? 0) + 1);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
let fitting;
|
|
565
|
+
let smallest;
|
|
566
|
+
for (const province of basin) {
|
|
567
|
+
const up = parent(province);
|
|
568
|
+
const branches = up < 0 ? roots : children.get(up);
|
|
569
|
+
if (branches < 2)
|
|
570
|
+
continue;
|
|
571
|
+
const size = subtree.get(province);
|
|
572
|
+
if (size < minimum || size > basin.length - minimum)
|
|
573
|
+
continue;
|
|
574
|
+
if (size <= maximum) {
|
|
575
|
+
if (fitting === undefined || size > subtree.get(fitting))
|
|
576
|
+
fitting = province;
|
|
577
|
+
}
|
|
578
|
+
else if (smallest === undefined || size < subtree.get(smallest))
|
|
579
|
+
smallest = province;
|
|
580
|
+
}
|
|
581
|
+
const cut = fitting ?? smallest;
|
|
582
|
+
if (cut === undefined)
|
|
583
|
+
return [basin];
|
|
584
|
+
const inCut = new Set([cut]);
|
|
585
|
+
for (const province of [...descending].reverse()) {
|
|
586
|
+
const up = parent(province);
|
|
587
|
+
if (up >= 0 && inCut.has(up))
|
|
588
|
+
inCut.add(province);
|
|
589
|
+
}
|
|
590
|
+
const piece = basin.filter((province) => inCut.has(province));
|
|
591
|
+
const rest = basin.filter((province) => !inCut.has(province));
|
|
592
|
+
return [
|
|
593
|
+
...splitBasin(piece, down, meanHeight, minimum, maximum),
|
|
594
|
+
...splitBasin(rest, down, meanHeight, minimum, maximum),
|
|
595
|
+
];
|
|
596
|
+
}
|
|
597
|
+
function round(value, places) {
|
|
598
|
+
const scale = 10 ** places;
|
|
599
|
+
return Math.round(value * scale) / scale;
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Cut the land provinces of a map into natural lands, as steps: the generator yields about every
|
|
603
|
+
* 64 raster rows and between stages, so a synchronous planner can interleave its own checkpoints.
|
|
604
|
+
*/
|
|
605
|
+
export function* naturalLandsSteps(input, options = {}) {
|
|
606
|
+
const resolved = resolveNaturalLandsOptions(options);
|
|
607
|
+
const signal = options.signal;
|
|
608
|
+
const { facts, pairs } = yield* scanRaster(input, resolved, signal);
|
|
609
|
+
const count = input.provinceKinds.length;
|
|
610
|
+
const adjacency = buildAdjacency(count, pairs);
|
|
611
|
+
const landProvinces = [];
|
|
612
|
+
for (let id = 0; id < count; id += 1)
|
|
613
|
+
if (facts.land[id] === 1)
|
|
614
|
+
landProvinces.push(id);
|
|
615
|
+
const hasHeights = input.heights !== undefined;
|
|
616
|
+
// 1. Pieces of one terrain class that no line crosses.
|
|
617
|
+
const componentOf = new Int32Array(count).fill(-1);
|
|
618
|
+
const joined = (pair) => (pairs.flags[pair] & PAIR_CUT) === 0;
|
|
619
|
+
const components = separateImpassable(connectedComponents(landProvinces, adjacency, joined, () => true, componentOf, 0), adjacency, pairs, joined, componentOf);
|
|
620
|
+
signal?.throwIfAborted();
|
|
621
|
+
yield;
|
|
622
|
+
// 2. Drainage basins inside every piece that is not a range.
|
|
623
|
+
const down = new Int32Array(count).fill(-1);
|
|
624
|
+
const basins = [];
|
|
625
|
+
const basinComponent = [];
|
|
626
|
+
for (const [index, component] of components.entries()) {
|
|
627
|
+
const drained = hasHeights && facts.classOf[component[0]] !== 'upland';
|
|
628
|
+
if (!drained) {
|
|
629
|
+
basins.push(component);
|
|
630
|
+
basinComponent.push(index);
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
for (const province of component) {
|
|
634
|
+
if (facts.coast[province] === 1 || facts.lake[province] === 1)
|
|
635
|
+
continue;
|
|
636
|
+
let lowest = -1;
|
|
637
|
+
for (let slot = adjacency.offsets[province]; slot < adjacency.offsets[province + 1]; slot++) {
|
|
638
|
+
const other = adjacency.to[slot];
|
|
639
|
+
if (componentOf[other] !== index)
|
|
640
|
+
continue;
|
|
641
|
+
if (facts.meanHeight[other] >= facts.meanHeight[province])
|
|
642
|
+
continue;
|
|
643
|
+
if (lowest < 0 ||
|
|
644
|
+
facts.meanHeight[other] < facts.meanHeight[lowest] ||
|
|
645
|
+
(facts.meanHeight[other] === facts.meanHeight[lowest] && other < lowest))
|
|
646
|
+
lowest = other;
|
|
647
|
+
}
|
|
648
|
+
down[province] = lowest;
|
|
649
|
+
}
|
|
650
|
+
const sinkOf = new Map();
|
|
651
|
+
for (const province of component) {
|
|
652
|
+
let sink = province;
|
|
653
|
+
while (down[sink] >= 0)
|
|
654
|
+
sink = down[sink];
|
|
655
|
+
const members = sinkOf.get(sink);
|
|
656
|
+
if (members === undefined)
|
|
657
|
+
sinkOf.set(sink, [province]);
|
|
658
|
+
else
|
|
659
|
+
members.push(province);
|
|
660
|
+
}
|
|
661
|
+
for (const sink of [...sinkOf.keys()].sort((x, y) => x - y)) {
|
|
662
|
+
basins.push(sinkOf.get(sink));
|
|
663
|
+
basinComponent.push(index);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
const basinOf = new Int32Array(count).fill(-1);
|
|
667
|
+
for (const [index, basin] of basins.entries())
|
|
668
|
+
for (const province of basin)
|
|
669
|
+
basinOf[province] = index;
|
|
670
|
+
const basinGraph = new GroupGraph(basins, basinOf, pairs);
|
|
671
|
+
basinGraph.mergeSmall(resolved.minBasinProvinces, (group, other) => basinComponent[group] === basinComponent[other], ([xGroup, x], [yGroup, y]) => x.pass < y.pass ||
|
|
672
|
+
(x.pass === y.pass &&
|
|
673
|
+
(x.length > y.length ||
|
|
674
|
+
(x.length === y.length && basinGraph.key[xGroup] < basinGraph.key[yGroup]))));
|
|
675
|
+
let pieces = basinGraph.groups();
|
|
676
|
+
if (resolved.maxBasinProvinces !== null) {
|
|
677
|
+
const maximum = resolved.maxBasinProvinces;
|
|
678
|
+
pieces = pieces.flatMap((piece) => hasHeights && facts.classOf[piece[0]] !== 'upland'
|
|
679
|
+
? splitBasin(piece, down, facts.meanHeight, resolved.minBasinProvinces, maximum)
|
|
680
|
+
: [piece]);
|
|
681
|
+
}
|
|
682
|
+
signal?.throwIfAborted();
|
|
683
|
+
yield;
|
|
684
|
+
// 3. Every piece in one connected part, then fragments merge across their weakest line.
|
|
685
|
+
const pieceOf = new Int32Array(count).fill(-1);
|
|
686
|
+
for (const [index, piece] of pieces.entries())
|
|
687
|
+
for (const province of piece)
|
|
688
|
+
pieceOf[province] = index;
|
|
689
|
+
const partOf = new Int32Array(count).fill(-1);
|
|
690
|
+
const parts = [];
|
|
691
|
+
for (const piece of pieces) {
|
|
692
|
+
const owner = pieceOf[piece[0]];
|
|
693
|
+
parts.push(...connectedComponents(piece, adjacency, () => true, (province) => pieceOf[province] === owner, partOf, parts.length));
|
|
694
|
+
}
|
|
695
|
+
const landGraph = new GroupGraph(parts, partOf, pairs);
|
|
696
|
+
landGraph.mergeSmall(resolved.minProvinces, () => true, ([xGroup, x], [yGroup, y]) => {
|
|
697
|
+
const xStrength = x.strength / x.length;
|
|
698
|
+
const yStrength = y.strength / y.length;
|
|
699
|
+
return (xStrength < yStrength ||
|
|
700
|
+
(xStrength === yStrength &&
|
|
701
|
+
(x.length > y.length ||
|
|
702
|
+
(x.length === y.length && landGraph.key[xGroup] < landGraph.key[yGroup]))));
|
|
703
|
+
});
|
|
704
|
+
const groups = landGraph.groups().sort((x, y) => x[0] - y[0]);
|
|
705
|
+
// 4. Describe the lands.
|
|
706
|
+
const landOf = new Int32Array(count).fill(-1);
|
|
707
|
+
for (const [index, group] of groups.entries())
|
|
708
|
+
for (const province of group)
|
|
709
|
+
landOf[province] = index;
|
|
710
|
+
const ids = groups.map((group) => `L${group[0]}`);
|
|
711
|
+
const lines = groups.map(() => new Map());
|
|
712
|
+
for (let i = 0; i < pairs.count; i += 1) {
|
|
713
|
+
const x = landOf[pairs.a[i]];
|
|
714
|
+
const y = landOf[pairs.b[i]];
|
|
715
|
+
if (x === y)
|
|
716
|
+
continue;
|
|
717
|
+
const length = pairs.length[i];
|
|
718
|
+
const flags = pairs.flags[i];
|
|
719
|
+
for (const [from, to] of [
|
|
720
|
+
[x, y],
|
|
721
|
+
[y, x],
|
|
722
|
+
]) {
|
|
723
|
+
let line = lines[from].get(to);
|
|
724
|
+
if (line === undefined) {
|
|
725
|
+
line = {
|
|
726
|
+
land: ids[to],
|
|
727
|
+
length: 0,
|
|
728
|
+
river: 0,
|
|
729
|
+
crest: 0,
|
|
730
|
+
terrain: 0,
|
|
731
|
+
impassable: 0,
|
|
732
|
+
divide: 0,
|
|
733
|
+
};
|
|
734
|
+
lines[from].set(to, line);
|
|
735
|
+
}
|
|
736
|
+
line.length += length;
|
|
737
|
+
if ((flags & PAIR_RIVER) !== 0)
|
|
738
|
+
line.river += length;
|
|
739
|
+
if ((flags & PAIR_CREST) !== 0)
|
|
740
|
+
line.crest += length;
|
|
741
|
+
if ((flags & PAIR_TERRAIN) !== 0)
|
|
742
|
+
line.terrain += length;
|
|
743
|
+
if ((flags & PAIR_IMPASSABLE) !== 0)
|
|
744
|
+
line.impassable += length;
|
|
745
|
+
if ((flags & PAIR_LINES) === 0)
|
|
746
|
+
line.divide += length;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
const counts = Object.fromEntries(NATURAL_LAND_KINDS.map((kind) => [kind, 0]));
|
|
750
|
+
const lands = groups.map((group, index) => {
|
|
751
|
+
const classCount = new Map();
|
|
752
|
+
const terrainCount = new Map();
|
|
753
|
+
let landPixels = 0;
|
|
754
|
+
let heightTotal = 0;
|
|
755
|
+
let coast = false;
|
|
756
|
+
let lakeShore = false;
|
|
757
|
+
for (const province of group) {
|
|
758
|
+
const terrainClass = facts.classOf[province];
|
|
759
|
+
classCount.set(terrainClass, (classCount.get(terrainClass) ?? 0) + 1);
|
|
760
|
+
const terrain = (input.provinceTerrain[province] ?? '') || 'unknown';
|
|
761
|
+
terrainCount.set(terrain, (terrainCount.get(terrain) ?? 0) + 1);
|
|
762
|
+
landPixels += facts.pixels[province];
|
|
763
|
+
heightTotal += facts.meanHeight[province] * facts.pixels[province];
|
|
764
|
+
if (facts.coast[province] === 1)
|
|
765
|
+
coast = true;
|
|
766
|
+
if (facts.lake[province] === 1)
|
|
767
|
+
lakeShore = true;
|
|
768
|
+
}
|
|
769
|
+
let majority = 'open';
|
|
770
|
+
let majorityCount = -1;
|
|
771
|
+
for (const terrainClass of CLASS_PRIORITY) {
|
|
772
|
+
const value = classCount.get(terrainClass) ?? 0;
|
|
773
|
+
if (value > majorityCount) {
|
|
774
|
+
majority = terrainClass;
|
|
775
|
+
majorityCount = value;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
const kind = majority === 'upland'
|
|
779
|
+
? 'range'
|
|
780
|
+
: majority === 'open'
|
|
781
|
+
? hasHeights
|
|
782
|
+
? 'basin'
|
|
783
|
+
: 'plains'
|
|
784
|
+
: majority;
|
|
785
|
+
counts[kind] += 1;
|
|
786
|
+
const terrain = {};
|
|
787
|
+
for (const name of [...terrainCount.keys()].sort((x, y) => (x < y ? -1 : x > y ? 1 : 0)))
|
|
788
|
+
terrain[name] = round(terrainCount.get(name) / group.length, 4);
|
|
789
|
+
return {
|
|
790
|
+
id: ids[index],
|
|
791
|
+
kind,
|
|
792
|
+
provinces: group,
|
|
793
|
+
pixels: landPixels,
|
|
794
|
+
coast,
|
|
795
|
+
lakeShore,
|
|
796
|
+
meanHeight: hasHeights ? round(heightTotal / Math.max(1, landPixels), 2) : null,
|
|
797
|
+
terrain,
|
|
798
|
+
lines: [...lines[index].entries()]
|
|
799
|
+
.sort(([x], [y]) => groups[x][0] - groups[y][0])
|
|
800
|
+
.map(([, line]) => line),
|
|
801
|
+
};
|
|
802
|
+
});
|
|
803
|
+
return {
|
|
804
|
+
schemaVersion: 1,
|
|
805
|
+
options: resolved,
|
|
806
|
+
inputs: { heights: hasHeights, rivers: input.rivers !== undefined },
|
|
807
|
+
landProvinces: landProvinces.length,
|
|
808
|
+
counts,
|
|
809
|
+
undersized: lands
|
|
810
|
+
.filter(({ provinces }) => provinces.length < resolved.minProvinces)
|
|
811
|
+
.map(({ id }) => id),
|
|
812
|
+
lands,
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
/** Drive `naturalLandsSteps`, yielding to the event loop about every 12 milliseconds. */
|
|
816
|
+
export async function computeNaturalLands(input, options = {}) {
|
|
817
|
+
const steps = naturalLandsSteps(input, options);
|
|
818
|
+
let last = performance.now();
|
|
819
|
+
for (;;) {
|
|
820
|
+
const step = steps.next();
|
|
821
|
+
if (step.done)
|
|
822
|
+
return step.value;
|
|
823
|
+
if (performance.now() - last >= 12) {
|
|
824
|
+
await yieldToEventLoop();
|
|
825
|
+
options.signal?.throwIfAborted();
|
|
826
|
+
last = performance.now();
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* The natural-lands input of a scanned map workspace: the province raster and kinds, the terrain
|
|
832
|
+
* category of every province from its definition, and the heightmap and rivers bitmap when they
|
|
833
|
+
* are present and the size of the province map.
|
|
834
|
+
*/
|
|
835
|
+
export function naturalLandsInputFromIndex(index) {
|
|
836
|
+
if (index.raster === undefined)
|
|
837
|
+
throw new ServiceError('MAP_NATURAL_LANDS_RASTER_MISSING', 'Natural lands need a valid province bitmap and definitions');
|
|
838
|
+
const { input, skipped } = borderQualityInputFromIndex(index);
|
|
839
|
+
const provinceTerrain = new Array(input.provinceKinds.length).fill('');
|
|
840
|
+
for (const definition of index.definitions)
|
|
841
|
+
if (Number.isInteger(definition.id) &&
|
|
842
|
+
definition.id >= 0 &&
|
|
843
|
+
definition.id < provinceTerrain.length)
|
|
844
|
+
provinceTerrain[definition.id] = definition.terrain;
|
|
845
|
+
return {
|
|
846
|
+
input: {
|
|
847
|
+
width: input.width,
|
|
848
|
+
height: input.height,
|
|
849
|
+
provinceIds: input.provinceIds,
|
|
850
|
+
provinceKinds: input.provinceKinds,
|
|
851
|
+
provinceTerrain,
|
|
852
|
+
...(input.features?.heights === undefined ? {} : { heights: input.features.heights }),
|
|
853
|
+
...(input.features?.rivers === undefined ? {} : { rivers: input.features.rivers }),
|
|
854
|
+
impassablePairs: index.adjacencies
|
|
855
|
+
.filter(({ type }) => type.toLowerCase() === 'impassable')
|
|
856
|
+
.map(({ from, to }) => [from, to]),
|
|
857
|
+
impassableProvinces: index.states
|
|
858
|
+
.filter(({ block }) => firstScalar(block, 'impassable')?.value === 'yes')
|
|
859
|
+
.flatMap(({ provinces }) => provinces),
|
|
860
|
+
},
|
|
861
|
+
skipped: skipped.filter(({ input: name }) => name === 'heightmap' || name === 'rivers'),
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
/** Natural lands of a scanned map workspace (the heightmap and rivers bitmap when present). */
|
|
865
|
+
export async function naturalLandsFromIndex(index, options = {}) {
|
|
866
|
+
resolveNaturalLandsOptions(options);
|
|
867
|
+
const { input, skipped } = naturalLandsInputFromIndex(index);
|
|
868
|
+
return { result: await computeNaturalLands(input, options), skipped };
|
|
869
|
+
}
|
|
870
|
+
export const NATURAL_LANDS_INLINE_LIMIT = 50;
|
|
871
|
+
export function summarizeNaturalLands(result, skipped) {
|
|
872
|
+
return {
|
|
873
|
+
count: result.lands.length,
|
|
874
|
+
landProvinces: result.landProvinces,
|
|
875
|
+
counts: result.counts,
|
|
876
|
+
inputs: result.inputs,
|
|
877
|
+
skippedInputs: skipped,
|
|
878
|
+
undersized: result.undersized.length,
|
|
879
|
+
lands: result.lands.slice(0, NATURAL_LANDS_INLINE_LIMIT).map((land) => ({
|
|
880
|
+
id: land.id,
|
|
881
|
+
kind: land.kind,
|
|
882
|
+
provinces: land.provinces.length,
|
|
883
|
+
coast: land.coast,
|
|
884
|
+
})),
|
|
885
|
+
truncated: result.lands.length > NATURAL_LANDS_INLINE_LIMIT,
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* The provinces of the named lands, ascending. An unknown land id is refused with
|
|
890
|
+
* `MAP_NATURAL_LAND_UNKNOWN`.
|
|
891
|
+
*/
|
|
892
|
+
export function naturalLandProvinces(result, landIds) {
|
|
893
|
+
const byId = new Map(result.lands.map((land) => [land.id, land]));
|
|
894
|
+
const unknown = landIds.filter((id) => !byId.has(id));
|
|
895
|
+
if (unknown.length > 0)
|
|
896
|
+
throw new ServiceError('MAP_NATURAL_LAND_UNKNOWN', `Unknown natural land ${unknown.slice(0, 5).join(', ')}; inspect the map with lands: true and the same landOptions`, { landIds: unknown.slice(0, 20) });
|
|
897
|
+
const provinces = new Set();
|
|
898
|
+
for (const id of landIds)
|
|
899
|
+
for (const province of byId.get(id).provinces)
|
|
900
|
+
provinces.add(province);
|
|
901
|
+
return [...provinces].sort((x, y) => x - y);
|
|
902
|
+
}
|