mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-24 00:23:12 +09:00
Use binary storage for recipe overlay for 8x space reduction
This commit is contained in:
1 parent
1c06611cca
commit
c5c26bfad1
4 files changed
+312
-84
No files matched your search
+121
-58
@@ -7,9 +7,9 @@ import {
|
|||||||
ChartData,
|
ChartData,
|
||||||
ChartTagDataEvent,
|
ChartTagDataEvent,
|
||||||
ChartTagData,
|
ChartTagData,
|
||||||
RecipeDataEvent,
|
RecipeDataEvent,
|
||||||
RecipeData,
|
RecipeData,
|
||||||
GetRawRecipeTileRequest,
|
GetRawRecipeTileRequest,
|
||||||
} from "./messages";
|
} from "./messages";
|
||||||
import * as fs from "fs-extra";
|
import * as fs from "fs-extra";
|
||||||
import * as path from "path";
|
import * as path from "path";
|
||||||
@@ -20,7 +20,9 @@ import {
|
|||||||
renderChunkToPixels,
|
renderChunkToPixels,
|
||||||
extractChunkFromTile,
|
extractChunkFromTile,
|
||||||
renderTileToPixels,
|
renderTileToPixels,
|
||||||
pixelsToRGBA
|
pixelsToRGBA,
|
||||||
|
parseRecipeTileBinary,
|
||||||
|
ParsedRecipeTile
|
||||||
} from "./tile-utils";
|
} from "./tile-utils";
|
||||||
|
|
||||||
const CHUNK_SIZE = 32;
|
const CHUNK_SIZE = 32;
|
||||||
@@ -36,10 +38,13 @@ interface PixelChange {
|
|||||||
export class ControllerPlugin extends BaseControllerPlugin {
|
export class ControllerPlugin extends BaseControllerPlugin {
|
||||||
private tilesPath: string = "";
|
private tilesPath: string = "";
|
||||||
private chartTagsPath: string = "";
|
private chartTagsPath: string = "";
|
||||||
private recipeTilesPath: string = "";
|
private recipeTilesPath: string = "";
|
||||||
private chunkSavingQueue = new Map<string, Map<string, { data: ChartData, tick: number }>>();
|
private chunkSavingQueue = new Map<string, Map<string, { data: ChartData, tick: number }>>();
|
||||||
private chartTagQueues = new Map<string, ChartTagData[]>();
|
private chartTagQueues = new Map<string, ChartTagData[]>();
|
||||||
private recipeSavingQueue = new Map<string, RecipeData[]>();
|
private recipeSavingQueue = new Map<string, Buffer[]>();
|
||||||
|
// Keep per-tile dictionary of recipe -> uint16 index as well as next free index
|
||||||
|
private recipeDictionaries = new Map<string, Map<string, number>>();
|
||||||
|
private nextRecipeIndex = new Map<string, number>();
|
||||||
private lastSeenTagContent = new Map<string, Map<number, {
|
private lastSeenTagContent = new Map<string, Map<number, {
|
||||||
position: [number, number];
|
position: [number, number];
|
||||||
text: string;
|
text: string;
|
||||||
@@ -73,8 +78,8 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
this.controller.handle(ChartTagDataEvent, this.handleChartTagDataEvent.bind(this));
|
this.controller.handle(ChartTagDataEvent, this.handleChartTagDataEvent.bind(this));
|
||||||
this.controller.handle(GetRawTileRequest, this.handleGetRawTileRequest.bind(this));
|
this.controller.handle(GetRawTileRequest, this.handleGetRawTileRequest.bind(this));
|
||||||
this.controller.handle(GetChartTagsRequest, this.handleGetChartTagsRequest.bind(this));
|
this.controller.handle(GetChartTagsRequest, this.handleGetChartTagsRequest.bind(this));
|
||||||
this.controller.handle(RecipeDataEvent, this.handleRecipeDataEvent.bind(this));
|
this.controller.handle(RecipeDataEvent, this.handleRecipeDataEvent.bind(this));
|
||||||
this.controller.handle(GetRawRecipeTileRequest, this.handleGetRawRecipeTileRequest.bind(this));
|
this.controller.handle(GetRawRecipeTileRequest, this.handleGetRawRecipeTileRequest.bind(this));
|
||||||
|
|
||||||
// Set up HTTP routes for serving tiles
|
// Set up HTTP routes for serving tiles
|
||||||
this.setupTileRoutes();
|
this.setupTileRoutes();
|
||||||
@@ -87,7 +92,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
this.saveInterval = setInterval(() => {
|
this.saveInterval = setInterval(() => {
|
||||||
this.saveTiles().catch(err => this.logger.error(`Error saving tiles: ${err}`));
|
this.saveTiles().catch(err => this.logger.error(`Error saving tiles: ${err}`));
|
||||||
this.saveChartTags().catch(err => this.logger.error(`Error saving chart tags: ${err}`));
|
this.saveChartTags().catch(err => this.logger.error(`Error saving chart tags: ${err}`));
|
||||||
this.saveRecipeTiles().catch(err => this.logger.error(`Error saving recipe tiles: ${err}`));
|
this.saveRecipeTiles().catch(err => this.logger.error(`Error saving recipe tiles: ${err}`));
|
||||||
}, 5000);
|
}, 5000);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -462,38 +467,21 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const files = await fs.readdir(this.recipeTilesPath);
|
const files = await fs.readdir(this.recipeTilesPath);
|
||||||
const recipeFiles = files.filter(file => file.endsWith("_recipes.jsonl"));
|
const recipeFiles = files.filter(file => file.endsWith(".recipes"));
|
||||||
|
|
||||||
for (const file of recipeFiles) {
|
for (const file of recipeFiles) {
|
||||||
const tileKey = file.replace("_recipes.jsonl", "");
|
const tileKey = file.replace(".recipes", "");
|
||||||
const filePath = path.join(this.recipeTilesPath, file);
|
const filePath = path.join(this.recipeTilesPath, file);
|
||||||
|
|
||||||
if (!this.lastSeenRecipeContent.has(tileKey)) {
|
// Initialise structures
|
||||||
this.lastSeenRecipeContent.set(tileKey, new Map());
|
this.lastSeenRecipeContent.set(tileKey, new Map());
|
||||||
}
|
this.recipeDictionaries.set(tileKey, new Map());
|
||||||
const seenRecipes = this.lastSeenRecipeContent.get(tileKey)!;
|
this.nextRecipeIndex.set(tileKey, 0);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const content = await fs.readFile(filePath, "utf-8");
|
const data = await fs.readFile(filePath);
|
||||||
const lines = content.trim().split("\n").filter(line => line.trim());
|
await this.parseRecipeTileForState(tileKey, data);
|
||||||
|
this.logger.info(`Loaded recipe state for ${tileKey}`);
|
||||||
for (const line of lines) {
|
|
||||||
try {
|
|
||||||
const recipeData = JSON.parse(line) as RecipeData;
|
|
||||||
const posKey = `${recipeData.position[0]}_${recipeData.position[1]}`;
|
|
||||||
|
|
||||||
// Update map: if the recipe has an end_tick it's no longer active, otherwise store/update it.
|
|
||||||
if (recipeData.end_tick !== undefined) {
|
|
||||||
seenRecipes.delete(posKey);
|
|
||||||
} else {
|
|
||||||
seenRecipes.set(posKey, recipeData.recipe);
|
|
||||||
}
|
|
||||||
} catch (parseErr) {
|
|
||||||
this.logger.warn(`Failed to parse recipe line in ${file}: ${parseErr}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.logger.info(`Loaded ${seenRecipes.size} existing recipe entries from ${file}`);
|
|
||||||
} catch (readErr) {
|
} catch (readErr) {
|
||||||
this.logger.warn(`Failed to read recipe file ${file}: ${readErr}`);
|
this.logger.warn(`Failed to read recipe file ${file}: ${readErr}`);
|
||||||
}
|
}
|
||||||
@@ -503,6 +491,73 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Parse binary recipe tile and populate lastSeenRecipeContent & recipeDictionaries
|
||||||
|
private async parseRecipeTileForState(tileKey: string, buffer: Buffer) {
|
||||||
|
// Derive tile coordinates from key (last two underscore-separated parts)
|
||||||
|
const parts = tileKey.split("_");
|
||||||
|
const tileY = parseInt(parts.pop()!); // last
|
||||||
|
const tileX = parseInt(parts.pop()!); // second last
|
||||||
|
const parsed: ParsedRecipeTile = parseRecipeTileBinary(tileX, tileY, buffer, null);
|
||||||
|
|
||||||
|
// Populate dictionary mapping (name -> index)
|
||||||
|
const dict = this.recipeDictionaries.get(tileKey)!;
|
||||||
|
for (const [id, name] of parsed.dictionary) {
|
||||||
|
dict.set(name, id);
|
||||||
|
const currentNext = this.nextRecipeIndex.get(tileKey) ?? 0;
|
||||||
|
if (id + 1 > currentNext) this.nextRecipeIndex.set(tileKey, id + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Populate active recipe cache
|
||||||
|
const seen = this.lastSeenRecipeContent.get(tileKey)!;
|
||||||
|
for (const [posKey, recipe] of parsed.activeRecipes) {
|
||||||
|
seen.set(posKey, recipe);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encode helpers
|
||||||
|
private getOrCreateRecipeIndex(tileKey: string, recipe: string): { index: number, dictEntry?: Buffer } {
|
||||||
|
if (!this.recipeDictionaries.has(tileKey)) {
|
||||||
|
this.recipeDictionaries.set(tileKey, new Map());
|
||||||
|
this.nextRecipeIndex.set(tileKey, 0);
|
||||||
|
}
|
||||||
|
const dict = this.recipeDictionaries.get(tileKey)!;
|
||||||
|
if (dict.has(recipe)) {
|
||||||
|
return { index: dict.get(recipe)! };
|
||||||
|
}
|
||||||
|
const nextIdx = this.nextRecipeIndex.get(tileKey)!;
|
||||||
|
dict.set(recipe, nextIdx);
|
||||||
|
this.nextRecipeIndex.set(tileKey, nextIdx + 1);
|
||||||
|
const nameBuf = Buffer.from(recipe, "utf-8");
|
||||||
|
const dictEntry = Buffer.alloc(1 + 2 + 1 + nameBuf.length);
|
||||||
|
dictEntry.writeUInt8(0, 0);
|
||||||
|
dictEntry.writeUInt16BE(nextIdx, 1);
|
||||||
|
dictEntry.writeUInt8(nameBuf.length, 3);
|
||||||
|
nameBuf.copy(dictEntry, 4);
|
||||||
|
return { index: nextIdx, dictEntry };
|
||||||
|
}
|
||||||
|
|
||||||
|
private encodeSet(tileKey: string, tick: number, px: number, py: number, recipe: string): Buffer[] {
|
||||||
|
const { index, dictEntry } = this.getOrCreateRecipeIndex(tileKey, recipe);
|
||||||
|
const buf = Buffer.alloc(1 + 4 + 1 + 1 + 2);
|
||||||
|
let o = 0;
|
||||||
|
buf.writeUInt8(1, o); o += 1;
|
||||||
|
buf.writeUInt32BE(Math.floor(tick / 60), o); o += 4;
|
||||||
|
buf.writeUInt8(px, o); o += 1;
|
||||||
|
buf.writeUInt8(py, o); o += 1;
|
||||||
|
buf.writeUInt16BE(index, o);
|
||||||
|
return dictEntry ? [dictEntry, buf] : [buf];
|
||||||
|
}
|
||||||
|
|
||||||
|
private encodeClear(tick: number, px: number, py: number): Buffer {
|
||||||
|
const buf = Buffer.alloc(1 + 4 + 1 + 1);
|
||||||
|
let o = 0;
|
||||||
|
buf.writeUInt8(2, o); o += 1;
|
||||||
|
buf.writeUInt32BE(Math.floor(tick / 60), o); o += 4;
|
||||||
|
buf.writeUInt8(px, o); o += 1;
|
||||||
|
buf.writeUInt8(py, o);
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
async saveChartTags() {
|
async saveChartTags() {
|
||||||
if (this.chartTagQueues.size === 0) {
|
if (this.chartTagQueues.size === 0) {
|
||||||
return;
|
return;
|
||||||
@@ -737,12 +792,12 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
this.recipeSavingQueue = new Map();
|
this.recipeSavingQueue = new Map();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const promises = [] as Promise<void>[];
|
const promises: Promise<void>[] = [];
|
||||||
for (const [tileName, list] of queue) {
|
for (const [tileName, buffers] of queue) {
|
||||||
const promise = (async () => {
|
const promise = (async () => {
|
||||||
const tilePath = path.join(this.recipeTilesPath, `${tileName}_recipes.jsonl`);
|
const tilePath = path.join(this.recipeTilesPath, `${tileName}.recipes`);
|
||||||
const lines = list.map(rec => JSON.stringify(rec)).join("\n") + "\n";
|
const concat = Buffer.concat(buffers);
|
||||||
await fs.appendFile(tilePath, lines, "utf-8");
|
await fs.appendFile(tilePath, concat);
|
||||||
})();
|
})();
|
||||||
promises.push(promise);
|
promises.push(promise);
|
||||||
}
|
}
|
||||||
@@ -764,36 +819,44 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
const tileKey = `${instance_id}_${recipe_data.surface}_${recipe_data.force}_${tileX}_${tileY}`;
|
const tileKey = `${instance_id}_${recipe_data.surface}_${recipe_data.force}_${tileX}_${tileY}`;
|
||||||
const posKey = `${x}_${y}`;
|
const posKey = `${x}_${y}`;
|
||||||
|
|
||||||
// Initialise the deduplication map for this tile if needed
|
// Initialise dedup map
|
||||||
if (!this.lastSeenRecipeContent.has(tileKey)) {
|
if (!this.lastSeenRecipeContent.has(tileKey)) {
|
||||||
this.lastSeenRecipeContent.set(tileKey, new Map());
|
this.lastSeenRecipeContent.set(tileKey, new Map());
|
||||||
}
|
}
|
||||||
const seenRecipes = this.lastSeenRecipeContent.get(tileKey)!;
|
const seenRecipes = this.lastSeenRecipeContent.get(tileKey)!;
|
||||||
|
|
||||||
let shouldEnqueue = true;
|
let buffersToWrite: Buffer[] = [];
|
||||||
|
|
||||||
|
// Translate world pos to local px/py
|
||||||
|
const px = Math.round(x - tileX * 256);
|
||||||
|
const py = Math.round(y - tileY * 256);
|
||||||
|
|
||||||
if (recipe_data.end_tick !== undefined) {
|
if (recipe_data.end_tick !== undefined) {
|
||||||
// A recipe is being removed/ended – always enqueue the event but update our cache
|
// Clear recipe
|
||||||
seenRecipes.delete(posKey);
|
if (seenRecipes.has(posKey)) {
|
||||||
} else {
|
seenRecipes.delete(posKey);
|
||||||
const existingRecipe = seenRecipes.get(posKey);
|
buffersToWrite.push(this.encodeClear(recipe_data.end_tick, px, py));
|
||||||
if (existingRecipe === recipe_data.recipe) {
|
|
||||||
// Duplicate event – skip persisting
|
|
||||||
shouldEnqueue = false;
|
|
||||||
} else {
|
} else {
|
||||||
// New or changed recipe – remember it
|
return; // nothing changed
|
||||||
seenRecipes.set(posKey, recipe_data.recipe);
|
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
if (!recipe_data.recipe) {
|
||||||
|
return; // nothing to set
|
||||||
|
}
|
||||||
|
const existing = seenRecipes.get(posKey);
|
||||||
|
if (existing === recipe_data.recipe) {
|
||||||
|
return; // duplicate
|
||||||
|
}
|
||||||
|
seenRecipes.set(posKey, recipe_data.recipe);
|
||||||
|
buffersToWrite = this.encodeSet(tileKey, recipe_data.start_tick ?? 0, px, py, recipe_data.recipe);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!shouldEnqueue) {
|
if (buffersToWrite.length === 0) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this.recipeSavingQueue.has(tileKey)) {
|
if (!this.recipeSavingQueue.has(tileKey)) {
|
||||||
this.recipeSavingQueue.set(tileKey, []);
|
this.recipeSavingQueue.set(tileKey, []);
|
||||||
}
|
}
|
||||||
this.recipeSavingQueue.get(tileKey)!.push(recipe_data);
|
this.recipeSavingQueue.get(tileKey)!.push(...buffersToWrite);
|
||||||
|
|
||||||
// broadcast live update
|
// broadcast live update
|
||||||
this.controller.sendTo(new lib.Address(lib.Address.broadcast, lib.Address.control), event);
|
this.controller.sendTo(new lib.Address(lib.Address.broadcast, lib.Address.control), event);
|
||||||
@@ -806,15 +869,15 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
async handleGetRawRecipeTileRequest(request: GetRawRecipeTileRequest) {
|
async handleGetRawRecipeTileRequest(request: GetRawRecipeTileRequest) {
|
||||||
const { instance_id, surface, force, tile_x, tile_y } = request;
|
const { instance_id, surface, force, tile_x, tile_y } = request;
|
||||||
const tileKey = `${instance_id}_${surface}_${force}_${tile_x}_${tile_y}`;
|
const tileKey = `${instance_id}_${surface}_${force}_${tile_x}_${tile_y}`;
|
||||||
const filePath = path.join(this.recipeTilesPath, `${tileKey}_recipes.jsonl`);
|
const filePath = path.join(this.recipeTilesPath, `${tileKey}.recipes`);
|
||||||
|
|
||||||
if (!await fs.pathExists(filePath)) {
|
if (!await fs.pathExists(filePath)) {
|
||||||
return { recipe_tile: null };
|
return { recipe_tile: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await fs.readFile(filePath, "utf-8");
|
const data = await fs.readFile(filePath);
|
||||||
const base64 = Buffer.from(data, "utf-8").toString("base64");
|
const base64 = data.toString("base64");
|
||||||
return { recipe_tile: base64 };
|
return { recipe_tile: base64 };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error(`Error reading recipe tile: ${err}`);
|
this.logger.error(`Error reading recipe tile: ${err}`);
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
# Crafting-Recipe Overlay for Minimap & Timelapse
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
Records which recipe every crafting machine is running, streams live changes to web clients, and replays them frame-perfectly in timelapse mode. The solution:
|
||||||
|
|
||||||
|
* Works for all forces & surfaces
|
||||||
|
* Scales to millions of events using compact binary storage
|
||||||
|
* Allows cheap frustum-culling using 256×256 map tiles
|
||||||
|
* Uses append-only storage so historical data is never rewritten
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### Event Flow
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
participant Lua as Factorio Lua (minimap.lua)
|
||||||
|
participant Host as Host/Instance plugin (instance.ts)
|
||||||
|
participant Ctl as Controller plugin (controller.ts)
|
||||||
|
participant UI as Web clients
|
||||||
|
|
||||||
|
Lua->>Host: ipc-minimap:recipe_data (JSON)
|
||||||
|
Host->>Ctl: RecipeDataEvent
|
||||||
|
Ctl-->>UI: RecipeDataEvent (broadcast)
|
||||||
|
UI->>Ctl: GetRawRecipeTileRequest (HTTP / cluster bus)
|
||||||
|
Ctl-->>UI: Raw recipe tile (.recipes)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Messages
|
||||||
|
| Message | Direction | Purpose |
|
||||||
|
| ---------------------------------- | --------------------------- | --------------------------- |
|
||||||
|
| `RecipeDataEvent` | instance → controller → web | Single recipe change (live) |
|
||||||
|
| `GetRawRecipeTileRequest/Response` | web → controller | Fetches binary recipe tile |
|
||||||
|
|
||||||
|
## Storage Format
|
||||||
|
|
||||||
|
### Tile Organization
|
||||||
|
Uses same 256×256 world-unit tiles as terrain data.
|
||||||
|
Filename: `<instance>_<surface>_<force>_<tileX>_<tileY>.recipes`
|
||||||
|
Stored in: `database_directory/minimap_recipe_tiles/`
|
||||||
|
|
||||||
|
### Binary Record Format (append-only)
|
||||||
|
All numbers **big-endian**.
|
||||||
|
|
||||||
|
| Bytes | Field | Description |
|
||||||
|
| ------------------- | ---------------- | --------------------------------------------- |
|
||||||
|
| 1 | `type` | `0=DictEntry`, `1=SetRecipe`, `2=ClearRecipe` |
|
||||||
|
| **DictEntry (0)** | |
|
||||||
|
| 2 | `index` (uint16) | Dictionary ID (0-65535) |
|
||||||
|
| 1 | `len` (uint8) | UTF-8 byte length |
|
||||||
|
| n | name bytes | Recipe name string |
|
||||||
|
| **SetRecipe (1)** | |
|
||||||
|
| 4 | `sec` (uint32) | ⌊tick / 60⌋ timestamp |
|
||||||
|
| 1 | `px` (uint8) | X position in tile (0-255) |
|
||||||
|
| 1 | `py` (uint8) | Y position in tile (0-255) |
|
||||||
|
| 2 | `index` (uint16) | Dictionary ID |
|
||||||
|
| **ClearRecipe (2)** | |
|
||||||
|
| 4 | `sec` (uint32) | ⌊tick / 60⌋ timestamp |
|
||||||
|
| 1 | `px` (uint8) | X position in tile (0-255) |
|
||||||
|
| 1 | `py` (uint8) | Y position in tile (0-255) |
|
||||||
|
|
||||||
|
Dictionary entries are written only when a previously unseen recipe name is required for that tile.
|
||||||
|
|
||||||
|
### Space Efficiency
|
||||||
|
- ~8x more compact than JSON format
|
||||||
|
- Dictionary compression eliminates recipe name repetition
|
||||||
|
- Per-tile dictionaries keep indices small (uint16 sufficient)
|
||||||
|
|
||||||
|
## Playback
|
||||||
|
|
||||||
|
### Live Mode
|
||||||
|
- `RecipeDataEvent` broadcasts like `TileDataEvent`
|
||||||
|
- Web UI maintains `Map<posKey, recipeName>` for instant icon updates
|
||||||
|
- Icons render using Factorio sprite metadata
|
||||||
|
|
||||||
|
### Timelapse Mode
|
||||||
|
- Downloads `.recipes` files via `GetRawRecipeTileRequest`
|
||||||
|
- Parses binary format using shared `parseRecipeTileBinary()` utility
|
||||||
|
- Applies Set/Clear records up to selected timeline tick
|
||||||
|
- Integrates with existing terrain timelapse system
|
||||||
|
|
||||||
|
## Scalability
|
||||||
|
| Metric | Estimate |
|
||||||
|
| ------------------------------ | ----------------------------- |
|
||||||
|
| Assemblers per large factory | ~50,000 |
|
||||||
|
| Avg recipe changes per machine | ~5 lifetime |
|
||||||
|
| Bytes per Set/Clear record | 8 bytes |
|
||||||
|
| Total storage per instance | ~2 MB |
|
||||||
|
| Max recipes per tile | <1,000 (well under 65K limit) |
|
||||||
@@ -554,3 +554,90 @@ export async function renderTileIncremental(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for parsed recipe tile data
|
||||||
|
*/
|
||||||
|
export interface ParsedRecipeTile {
|
||||||
|
ticks: number[]; // ticks present in this tile
|
||||||
|
activeRecipes: Map<string, string>; // posKey -> recipeName
|
||||||
|
dictionary: Map<number, string>; // id -> recipeName
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse binary recipe tile data and return timeline ticks and active recipes at target tick
|
||||||
|
* @param tileX Tile X coordinate for world position calculation
|
||||||
|
* @param tileY Tile Y coordinate for world position calculation
|
||||||
|
* @param buf Binary recipe tile data
|
||||||
|
* @param targetTick Target tick for filtering (null = latest state)
|
||||||
|
* @returns Parsed recipe data with ticks and active recipes
|
||||||
|
*/
|
||||||
|
export function parseRecipeTileBinary(tileX: number, tileY: number, buf: BinaryData, targetTick: number | null): ParsedRecipeTile {
|
||||||
|
const ticks: number[] = [];
|
||||||
|
const dict = new Map<number, string>();
|
||||||
|
const active = new Map<string, string>();
|
||||||
|
const targetSec = targetTick !== null ? Math.floor(targetTick / 60) : Infinity;
|
||||||
|
|
||||||
|
let offset = 0;
|
||||||
|
while (offset < buf.length) {
|
||||||
|
const type = readUInt8(buf, offset);
|
||||||
|
offset += 1;
|
||||||
|
|
||||||
|
if (type === 0) { // Dictionary entry
|
||||||
|
const idx = readUInt16BE(buf, offset);
|
||||||
|
offset += 2;
|
||||||
|
const len = readUInt8(buf, offset);
|
||||||
|
offset += 1;
|
||||||
|
const nameBytes = sliceData(buf, offset, offset + len);
|
||||||
|
offset += len;
|
||||||
|
|
||||||
|
// Convert to string using cross-platform method
|
||||||
|
let recipeName: string;
|
||||||
|
if (isNode && nameBytes instanceof Buffer) {
|
||||||
|
recipeName = nameBytes.toString('utf-8');
|
||||||
|
} else {
|
||||||
|
recipeName = new TextDecoder().decode(nameBytes as Uint8Array);
|
||||||
|
}
|
||||||
|
|
||||||
|
dict.set(idx, recipeName);
|
||||||
|
} else if (type === 1 || type === 2) { // Set recipe (1) or Clear recipe (2)
|
||||||
|
const sec = readUInt32BE(buf, offset);
|
||||||
|
offset += 4;
|
||||||
|
const px = readUInt8(buf, offset);
|
||||||
|
offset += 1;
|
||||||
|
const py = readUInt8(buf, offset);
|
||||||
|
offset += 1;
|
||||||
|
|
||||||
|
let idx: number | undefined;
|
||||||
|
if (type === 1) {
|
||||||
|
idx = readUInt16BE(buf, offset);
|
||||||
|
offset += 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tickVal = sec * 60;
|
||||||
|
ticks.push(tickVal);
|
||||||
|
|
||||||
|
if (sec > targetSec) {
|
||||||
|
// Future to target time – we can skip rest if file is chronological
|
||||||
|
// but to be safe just continue without applying
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const worldX = tileX * 256 + px;
|
||||||
|
const worldY = tileY * 256 + py;
|
||||||
|
const posKey = `${worldX},${worldY}`;
|
||||||
|
|
||||||
|
if (type === 1 && idx !== undefined) {
|
||||||
|
const name = dict.get(idx);
|
||||||
|
if (name) active.set(posKey, name);
|
||||||
|
} else if (type === 2) {
|
||||||
|
active.delete(posKey);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn("Unknown recipe record type", type);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ticks, activeRecipes: active, dictionary: dict };
|
||||||
|
}
|
||||||
@@ -10,7 +10,8 @@ import {
|
|||||||
extractAvailableTicks,
|
extractAvailableTicks,
|
||||||
parseTileData,
|
parseTileData,
|
||||||
renderTileIncremental,
|
renderTileIncremental,
|
||||||
ParsedTileData
|
ParsedTileData,
|
||||||
|
parseRecipeTileBinary
|
||||||
} from "../tile-utils";
|
} from "../tile-utils";
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
@@ -527,15 +528,11 @@ export default function CanvasMinimapPage() {
|
|||||||
tileY
|
tileY
|
||||||
));
|
));
|
||||||
if (recipeResp.recipe_tile) {
|
if (recipeResp.recipe_tile) {
|
||||||
const text = atob(recipeResp.recipe_tile);
|
const binStr = atob(recipeResp.recipe_tile);
|
||||||
const lines = text.trim().split('\n').filter(l => l.trim());
|
const buf = new Uint8Array(binStr.length);
|
||||||
for (const line of lines) {
|
for (let i = 0; i < binStr.length; i++) buf[i] = binStr.charCodeAt(i);
|
||||||
try {
|
const parsed = parseRecipeTileBinary(tileX, tileY, buf, null);
|
||||||
const rec = JSON.parse(line);
|
for (const t of parsed.ticks) { allTicks.add(t); recipeTicksAdded++; }
|
||||||
if (rec.start_tick !== undefined) { allTicks.add(rec.start_tick); recipeTicksAdded++; }
|
|
||||||
if (rec.end_tick !== undefined) { allTicks.add(rec.end_tick); recipeTicksAdded++; }
|
|
||||||
} catch { /* ignore parse errors */ }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn(`Failed to load recipe tile ${tileX},${tileY}:`, e);
|
console.warn(`Failed to load recipe tile ${tileX},${tileY}:`, e);
|
||||||
@@ -1690,22 +1687,15 @@ export default function CanvasMinimapPage() {
|
|||||||
cs.selectedInstance, cs.selectedSurface, cs.selectedForce, tileX, tileY
|
cs.selectedInstance, cs.selectedSurface, cs.selectedForce, tileX, tileY
|
||||||
));
|
));
|
||||||
if (!resp.recipe_tile) return;
|
if (!resp.recipe_tile) return;
|
||||||
const text = atob(resp.recipe_tile);
|
const binStr = atob(resp.recipe_tile);
|
||||||
const lines = text.trim().split('\n').filter(l => l.trim());
|
const buf = new Uint8Array(binStr.length);
|
||||||
for (const line of lines) {
|
for (let i = 0; i < binStr.length; i++) buf[i] = binStr.charCodeAt(i);
|
||||||
try {
|
|
||||||
const rec = JSON.parse(line);
|
const parsed = parseRecipeTileBinary(tileX, tileY, buf, cs.isTimelapseMode ? cs.currentTick : null);
|
||||||
const key = `${rec.position[0]},${rec.position[1]}`;
|
|
||||||
// Timelapse filter
|
// Apply parsed active recipes to cache
|
||||||
if (cs.isTimelapseMode && cs.currentTick !== null) {
|
for (const [coord, recName] of parsed.activeRecipes) {
|
||||||
const t = cs.currentTick;
|
recipeCache.current.set(coord, recName);
|
||||||
if (rec.start_tick !== undefined && rec.start_tick > t) continue;
|
|
||||||
if (rec.end_tick !== undefined && rec.end_tick <= t) { recipeCache.current.delete(key); continue; }
|
|
||||||
} else {
|
|
||||||
if (rec.end_tick !== undefined) { recipeCache.current.delete(key); continue; }
|
|
||||||
}
|
|
||||||
if (rec.recipe) { recipeCache.current.set(key, rec.recipe); }
|
|
||||||
} catch { }
|
|
||||||
}
|
}
|
||||||
} catch (e) { console.warn('loadRecipeTile', e); }
|
} catch (e) { console.warn('loadRecipeTile', e); }
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in new issue
Block a user