forked from Bitcoindefi/OpenAO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexportFrontendOptimizedMaps.ts
More file actions
362 lines (295 loc) · 11.1 KB
/
Copy pathexportFrontendOptimizedMaps.ts
File metadata and controls
362 lines (295 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import fs from "node:fs";
import path from "node:path";
import { loadMapNpcPlacements } from "../mapNpcStorage";
type TerrainTile = {
blocked?: boolean;
graphics?: number | Array<number | null>;
};
type TerrainMap = {
id?: number;
width?: number;
height?: number;
palette?: Record<string, TerrainTile>;
rows?: number[][];
};
type SpecialsMap = {
id?: number;
exits?: Record<string, { map?: number; x?: number; y?: number }>;
objects?: Record<string, { objIndex?: number; amount?: number }>;
npcs?: Record<string, number>;
triggers?: Record<string, number>;
};
type NpcPlacement = {
mapNum?: number;
x?: number;
y?: number;
npcIndex?: number;
};
type CompactTile = {
b?: 1;
g?: number | Array<number | null>;
e?: { m: number; x: number; y: number };
n?: number;
t?: number;
o?: { i: number; a: number };
};
type OptimizedMap = {
id: number;
w: number;
h: number;
d: number[];
cx?: CompactTile[];
};
const DEFAULT_SOURCE_DIR = path.resolve(__dirname, "../../mapas_source");
const DEFAULT_OUTPUT_DIR = path.resolve(__dirname, "../../../frontend/public/maps_optimized");
const MAP_DIR_PATTERN = /^mapa_(\d+)$/i;
function parseCliArgs(argv: string[]) {
const mapIds = new Set<number>();
let sourceDir = DEFAULT_SOURCE_DIR;
let outputDir = DEFAULT_OUTPUT_DIR;
for (const arg of argv) {
if (arg.startsWith("--source-dir=")) {
sourceDir = path.resolve(process.cwd(), arg.slice("--source-dir=".length));
continue;
}
if (arg.startsWith("--output-dir=")) {
outputDir = path.resolve(process.cwd(), arg.slice("--output-dir=".length));
continue;
}
if (arg.startsWith("--maps=")) {
for (const rawId of arg.slice("--maps=".length).split(",")) {
const mapId = Number.parseInt(rawId.trim(), 10);
if (Number.isInteger(mapId) && mapId > 0) {
mapIds.add(mapId);
}
}
continue;
}
const mapId = Number.parseInt(arg, 10);
if (Number.isInteger(mapId) && mapId > 0) {
mapIds.add(mapId);
}
}
return {
sourceDir,
outputDir,
mapIds: [...mapIds].sort((left, right) => left - right),
};
}
function readJsonFile<T>(filePath: string): T {
return JSON.parse(fs.readFileSync(filePath, "utf8")) as T;
}
function toFiniteNumber(value: unknown): number | undefined {
if (typeof value === "number" && Number.isFinite(value)) {
return value;
}
if (typeof value === "string" && value.trim()) {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
return undefined;
}
function getAvailableMapIds(sourceDir: string): number[] {
return fs
.readdirSync(sourceDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name.match(MAP_DIR_PATTERN))
.filter((match): match is RegExpMatchArray => Boolean(match))
.map((match) => Number.parseInt(match[1], 10))
.filter((mapId) => Number.isInteger(mapId) && mapId > 0)
.sort((left, right) => left - right);
}
function parseCoordinateKey(key: string): { x: number; y: number } | null {
const [rawX, rawY] = key.split(",");
const x = Number.parseInt(rawX ?? "", 10);
const y = Number.parseInt(rawY ?? "", 10);
if (!Number.isInteger(x) || !Number.isInteger(y) || x < 1 || y < 1) {
return null;
}
return { x, y };
}
function sortCompactTile(tile: CompactTile): CompactTile {
const result: CompactTile = {};
if (tile.b) {
result.b = 1;
}
if (tile.g !== undefined) {
result.g = tile.g;
}
if (tile.e) {
result.e = tile.e;
}
if (tile.n !== undefined) {
result.n = tile.n;
}
if (tile.t !== undefined) {
result.t = tile.t;
}
if (tile.o) {
result.o = tile.o;
}
return result;
}
function buildCompactMap(mapId: number, terrain: TerrainMap, specials: SpecialsMap): OptimizedMap {
const width = Math.max(1, toFiniteNumber(terrain.width) ?? 100);
const height = Math.max(1, toFiniteNumber(terrain.height) ?? 100);
const palette = terrain.palette ?? {};
const rows = Array.isArray(terrain.rows) ? terrain.rows : [];
const exitByCoordinate = new Map<string, { map: number; x: number; y: number }>();
const objectByCoordinate = new Map<string, { objIndex: number; amount: number }>();
const triggerByCoordinate = new Map<string, number>();
const complexIndexBySignature = new Map<string, number>();
const complexTiles: CompactTile[] = [];
const data: number[] = [];
for (const [coordinateKey, exit] of Object.entries(specials.exits ?? {})) {
const coordinates = parseCoordinateKey(coordinateKey);
if (!coordinates) {
continue;
}
const map = toFiniteNumber(exit.map);
const x = toFiniteNumber(exit.x);
const y = toFiniteNumber(exit.y);
if (map === undefined || x === undefined || y === undefined) {
continue;
}
exitByCoordinate.set(`${coordinates.x},${coordinates.y}`, { map, x, y });
}
for (const [coordinateKey, objectInfo] of Object.entries(specials.objects ?? {})) {
const coordinates = parseCoordinateKey(coordinateKey);
if (!coordinates) {
continue;
}
const objIndex = toFiniteNumber(objectInfo.objIndex);
const amount = toFiniteNumber(objectInfo.amount);
if (objIndex === undefined || amount === undefined) {
continue;
}
objectByCoordinate.set(`${coordinates.x},${coordinates.y}`, { objIndex, amount });
}
for (const [coordinateKey, trigger] of Object.entries(specials.triggers ?? {})) {
const coordinates = parseCoordinateKey(coordinateKey);
if (!coordinates) {
continue;
}
const normalizedTrigger = toFiniteNumber(trigger);
if (normalizedTrigger === undefined) {
continue;
}
triggerByCoordinate.set(`${coordinates.x},${coordinates.y}`, normalizedTrigger);
}
for (let y = 1; y <= height; y++) {
for (let x = 1; x <= width; x++) {
const paletteId = rows[y - 1]?.[x - 1] ?? 0;
const terrainTile = paletteId > 0 ? palette[String(paletteId)] : undefined;
const coordinateKey = `${x},${y}`;
const compactTile: CompactTile = {};
if (terrainTile?.blocked) {
compactTile.b = 1;
}
if (terrainTile?.graphics !== undefined) {
compactTile.g = terrainTile.graphics;
}
const exit = exitByCoordinate.get(coordinateKey);
if (exit) {
compactTile.e = {
m: exit.map,
x: exit.x,
y: exit.y,
};
}
const objectInfo = objectByCoordinate.get(coordinateKey);
if (objectInfo) {
compactTile.o = {
i: objectInfo.objIndex,
a: objectInfo.amount,
};
}
const trigger = triggerByCoordinate.get(coordinateKey);
if (trigger !== undefined) {
compactTile.t = trigger;
}
const npcIndex = toFiniteNumber((specials.npcs ?? {})[coordinateKey]);
if (npcIndex !== undefined) {
compactTile.n = npcIndex;
}
const normalizedTile = sortCompactTile(compactTile);
const tileKeys = Object.keys(normalizedTile);
if (tileKeys.length === 0) {
data.push(0);
continue;
}
if (tileKeys.length === 1 && normalizedTile.g !== undefined) {
if (typeof normalizedTile.g === "number") {
data.push(normalizedTile.g);
continue;
}
}
if (tileKeys.length === 2 && normalizedTile.b === 1 && typeof normalizedTile.g === "number") {
data.push(100000 + normalizedTile.g);
continue;
}
const signature = JSON.stringify(normalizedTile);
let complexIndex = complexIndexBySignature.get(signature);
if (complexIndex === undefined) {
complexIndex = complexTiles.length;
complexIndexBySignature.set(signature, complexIndex);
complexTiles.push(normalizedTile);
}
data.push(-(complexIndex + 1));
}
}
return complexTiles.length > 0
? { id: mapId, w: width, h: height, d: data, cx: complexTiles }
: { id: mapId, w: width, h: height, d: data };
}
function mergeNpcPlacements(specials: SpecialsMap, npcPlacements: NpcPlacement[]): SpecialsMap {
const mergedNpcs = { ...(specials.npcs ?? {}) };
for (const placement of npcPlacements) {
const x = toFiniteNumber(placement.x);
const y = toFiniteNumber(placement.y);
const npcIndex = toFiniteNumber(placement.npcIndex);
if (x === undefined || y === undefined || npcIndex === undefined) {
continue;
}
mergedNpcs[`${x},${y}`] = npcIndex;
}
return {
...specials,
npcs: mergedNpcs,
};
}
function writeJsonFile(filePath: string, value: unknown): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(value), "utf8");
}
function exportMap(mapId: number, sourceDir: string, outputDir: string): void {
const mapDir = path.join(sourceDir, `mapa_${mapId}`);
const terrainPath = path.join(mapDir, "terrain.json");
const specialsPath = path.join(mapDir, "specials.json");
if (!fs.existsSync(terrainPath)) {
throw new Error(`Mapa ${mapId}: no existe ${terrainPath}`);
}
const terrain = readJsonFile<TerrainMap>(terrainPath);
const specials = fs.existsSync(specialsPath)
? readJsonFile<SpecialsMap>(specialsPath)
: ({ id: mapId, exits: {}, objects: {}, npcs: {}, triggers: {} } as SpecialsMap);
const optimizedMap = buildCompactMap(mapId, terrain, mergeNpcPlacements(specials, loadMapNpcPlacements(mapId)));
const fileName = `mapa_${mapId}.json`;
writeJsonFile(path.join(outputDir, fileName), optimizedMap);
console.log(
`Exportado optimized mapa ${mapId} -> ${path.relative(process.cwd(), path.join(outputDir, fileName))} ` +
`(cells=${optimizedMap.d.length}, complex=${optimizedMap.cx?.length ?? 0})`,
);
}
function main(): void {
const { sourceDir, outputDir, mapIds } = parseCliArgs(process.argv.slice(2));
const resolvedMapIds = mapIds.length > 0 ? mapIds : getAvailableMapIds(sourceDir);
if (resolvedMapIds.length === 0) {
throw new Error("No se encontraron mapas para exportar.");
}
for (const mapId of resolvedMapIds) {
exportMap(mapId, sourceDir, outputDir);
}
console.log(`Listo. Mapas optimizados exportados: ${resolvedMapIds.length}`);
}
main();