forked from clusterio/gridworld
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstance.ts
More file actions
362 lines (319 loc) · 13.6 KB
/
instance.ts
File metadata and controls
362 lines (319 loc) · 13.6 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 * as lib from "@clusterio/lib";
import { BaseInstancePlugin } from "@clusterio/host";
import * as messages from "./messages";
declare module "@clusterio/lib" {
export interface InstanceConfigFields {
"gridworld.tile_x": number;
"gridworld.tile_y": number;
"gridworld.tile_size": number;
"gridworld.surface_name": string;
}
}
type RailEntitiesIPC = {
tile_x: number;
tile_y: number;
tile_size: number;
entities: messages.RailEntity[];
};
type UeStopsIPC = {
tile_x: number;
tile_y: number;
stops: messages.UeStop[];
};
type ReturnTrainPathIPC = {
id: number;
path: string[] | Record<string, string>;
source_instance_id: number;
};
type RequestTrainPathIPC = {
id: number;
surface: string;
position: { x: number; y: number };
direction: number;
destination: string;
};
type CornerNeighbors = { ne?: number; se?: number; sw?: number; nw?: number };
type CornerTeleportPlayerIPC = {
player_name: string;
corner: "ne" | "se" | "sw" | "nw";
world_position: [number, number];
};
type CornerEntityTransferIPC = {
corner: "ne" | "se" | "sw" | "nw";
entity_transfers: Array<{
type: "player" | "vehicle";
world_position: [number, number];
player_name?: string;
serialized_entity?: Record<string, unknown>;
driver_name?: string;
passenger_name?: string;
}>;
};
export class InstancePlugin extends BaseInstancePlugin {
private warnedMissingConfig = false;
private cornerNeighbors: CornerNeighbors = {};
async init() {
this.instance.handle(messages.GridworldSyncTileAreas, this.handleGridworldSyncTileAreas.bind(this));
this.instance.handle(messages.GridworldApplyRailEntities, this.handleGridworldApplyRailEntities.bind(this));
this.instance.handle(messages.GridworldApplyUeStops, this.handleApplyUeStops.bind(this));
this.instance.handle(messages.GridworldReturnTrainPath, this.handleReturnTrainPath.bind(this));
this.instance.handle(messages.GridworldForwardTrainPath, this.handleForwardTrainPath.bind(this));
this.instance.handle(messages.GridworldSyncDaytime, this.handleSyncDaytime.bind(this));
this.instance.handle(messages.GridworldCreateTrainProxy, this.handleCreateTrainProxy.bind(this));
this.instance.handle(messages.GridworldForwardClearTrainPath, this.handleForwardClearTrainPath.bind(this));
this.instance.handle(messages.GridworldForwardRemoveTrainProxy, this.handleForwardRemoveTrainProxy.bind(this));
// Receive rail entity data collected by Lua via clusterio_api.send_json("gridworld:rail_entities", ...)
(this.instance.server as any).on("ipc-gridworld:rail_entities", (data: RailEntitiesIPC) => {
this.handleRailEntitiesIpc(data).catch(err => this.logger.error(
`Error handling rail entities IPC:\n${err.stack}`,
));
});
// Receive ue_stops data from Lua via clusterio_api.send_json("gridworld:ue_stops", ...)
(this.instance.server as any).on("ipc-gridworld:ue_stops", (data: UeStopsIPC) => {
this.handleUeStopsIpc(data).catch(err => this.logger.error(
`Error handling ue_stops IPC:\n${err.stack}`,
));
});
// Receive train path requests from Lua via clusterio_api.send_json("gridworld:request_train_path", ...)
(this.instance.server as any).on("ipc-gridworld:request_train_path", (data: RequestTrainPathIPC) => {
this.handleRequestTrainPathIpc(data).catch(err => this.logger.error(
`Error handling request_train_path IPC:\n${err.stack}`,
));
});
// Receive train path results from Lua (pathworld) via clusterio_api.send_json("gridworld:return_train_path", ...)
(this.instance.server as any).on("ipc-gridworld:return_train_path", (data: ReturnTrainPathIPC) => {
this.handleReturnTrainPathIpc(data).catch(err => this.logger.error(
`Error handling return_train_path IPC:\n${err.stack}`,
));
});
// Receive clear path request from Lua via clusterio_api.send_json("gridworld:clear_train_path_request", ...)
(this.instance.server as any).on("ipc-gridworld:clear_train_path_request", (data: { id: number }) => {
this.instance.sendTo("controller", new messages.GridworldClearTrainPath(data.id));
});
// Receive remove proxy request from Lua via clusterio_api.send_json("gridworld:remove_train_proxy", ...)
(this.instance.server as any).on("ipc-gridworld:remove_train_proxy", (data: { last_edge_stop: string; destination: string }) => {
this.instance.sendTo("controller", new messages.GridworldRemoveTrainProxy(data.last_edge_stop, data.destination));
});
// Corner diagonal transport IPC handlers
(this.instance.server as any).on("ipc-gridworld:corner_teleport_player", (data: CornerTeleportPlayerIPC) => {
this.handleCornerTeleportPlayerIpc(data).catch(err => this.logger.error(
`Error handling corner_teleport_player IPC:\n${err.stack}`,
));
});
(this.instance.server as any).on("ipc-gridworld:corner_entity_transfer", (data: CornerEntityTransferIPC) => {
this.handleCornerEntityTransferIpc(data).catch(err => this.logger.error(
`Error handling corner_entity_transfer IPC:\n${err.stack}`,
));
});
this.instance.handle(messages.GridworldCornerNeighbors, this.handleCornerNeighbors.bind(this));
this.instance.handle(messages.GridworldDiagonalEntityTransfer, this.handleDiagonalEntityTransfer.bind(this));
}
async handleForwardRemoveTrainProxy(event: messages.GridworldForwardRemoveTrainProxy) {
const json = lib.escapeString(JSON.stringify({ destination: event.destination }));
await this.sendRcon(`/sc train_path_manager.remove_train_proxies('${json}')`);
}
private getBoundaryConfig(logMissing: boolean): { tileX: number; tileY: number; tileSize: number; surfaceName: string } | null {
const tileX = this.instance.config.get("gridworld.tile_x");
const tileY = this.instance.config.get("gridworld.tile_y");
const tileSize = this.instance.config.get("gridworld.tile_size");
const surfaceName = this.instance.config.get("gridworld.surface_name");
if (
typeof tileX !== "number"
|| typeof tileY !== "number"
|| typeof tileSize !== "number"
|| typeof surfaceName !== "string"
) {
if (logMissing && !this.warnedMissingConfig) {
this.logger.warn("Missing gridworld boundary config; skipping boundary setup.");
this.warnedMissingConfig = true;
}
return null;
}
return {
tileX,
tileY,
tileSize,
surfaceName,
};
}
private isPathworld(): boolean {
return this.instance.config.get("instance.name") === "pathworld";
}
private async sendBoundaryConfig(logMissing: boolean) {
if (this.isPathworld()) {
return;
}
const config = this.getBoundaryConfig(logMissing);
if (!config) {
return;
}
const escapedSurfaceName = lib.escapeString(config.surfaceName);
await this.sendRcon(
`/sc gridworld.set_config({tile_x = ${config.tileX}, tile_y = ${config.tileY}, tile_size = ${config.tileSize}, surface_name = "${escapedSurfaceName}"})`,
);
}
async onInstanceConfigFieldChanged(field: string) {
if (!field.startsWith("gridworld.")) {
return;
}
if (
field !== "gridworld.tile_x"
&& field !== "gridworld.tile_y"
&& field !== "gridworld.tile_size"
&& field !== "gridworld.surface_name"
) {
return;
}
await this.sendBoundaryConfig(false);
}
async handleGridworldSyncTileAreas(event: messages.GridworldSyncTileAreas) {
const tilesJson = lib.escapeString(JSON.stringify(event.tiles));
await this.sendRcon(`/sc gridworld.sync_tile_areas('${tilesJson}')`);
}
async onStart() {
if (this.isPathworld()) {
await this.sendRcon("/sc gridworld.set_pathworld()");
} else {
await this.sendBoundaryConfig(true);
}
}
private async handleRailEntitiesIpc(data: RailEntitiesIPC) {
const instanceId = this.instance.config.get("instance.id") as number;
const entities: messages.RailEntity[] = Array.isArray(data.entities) ? data.entities : Object.values(data.entities as any);
this.instance.sendTo("controller", new messages.GridworldSyncRailEntities(
instanceId,
data.tile_x,
data.tile_y,
data.tile_size,
entities,
));
}
async handleGridworldApplyRailEntities(event: messages.GridworldApplyRailEntities) {
const json = lib.escapeString(JSON.stringify({
tile_x: event.tileX,
tile_y: event.tileY,
tile_size: event.tileSize,
entities: event.entities,
}));
await this.sendRcon(`/sc rail_sync_manager.apply_rail_entities('${json}')`);
}
private async handleUeStopsIpc(data: UeStopsIPC) {
const stops: messages.UeStop[] = Array.isArray(data.stops) ? data.stops : Object.values(data.stops as any);
this.instance.sendTo("controller", new messages.GridworldSyncUeStops(
data.tile_x,
data.tile_y,
stops,
));
}
async handleApplyUeStops(event: messages.GridworldApplyUeStops) {
const json = lib.escapeString(JSON.stringify({
tile_x: event.tileX,
tile_y: event.tileY,
stops: event.stops,
}));
await this.sendRcon(`/sc rail_sync_manager.apply_ue_stops('${json}')`);
}
private async handleRequestTrainPathIpc(data: RequestTrainPathIPC) {
// Normalize position — Factorio MapPosition may serialize as {"1":x,"2":y} instead of {"x":x,"y":y}
const pos = data.position as any;
const position = { x: pos.x ?? pos["1"] ?? 0, y: pos.y ?? pos["2"] ?? 0 };
this.logger.info(`[gridworld] request_train_path IPC received: train=${data.id} destination="${data.destination}" pos=${position.x},${position.y}`);
this.instance.sendTo("controller", new messages.GridworldRequestTrainPath(
data.id,
data.surface,
position,
data.direction,
data.destination
));
}
private async handleReturnTrainPathIpc(data: ReturnTrainPathIPC) {
// Factorio serializes an empty Lua table as {} (object) not [] (array).
// Normalize path to always be an array.
const path: string[] = Array.isArray(data.path) ? data.path : Object.values(data.path as any);
this.logger.info(`[gridworld] return_train_path IPC received from pathworld: train=${data.id} sourceInstance=${data.source_instance_id} pathLen=${path.length}`);
this.instance.sendTo("controller", new messages.GridworldReturnTrainPathResult(
data.id,
path,
data.source_instance_id,
));
}
async handleReturnTrainPath(event: messages.GridworldReturnTrainPath) {
this.logger.info(`[gridworld] return_train_path received: train=${event.id}`);
const json = lib.escapeString(JSON.stringify({ id: event.id, path: event.path }));
await this.sendRcon(`/sc train_path_manager.apply_train_path_result('${json}')`);
}
async handleSyncDaytime(event: messages.GridworldSyncDaytime) {
const json = lib.escapeString(JSON.stringify({
daytime: event.daytime,
is_startup: event.isStartup,
ticks_per_day: event.ticksPerDay,
}));
await this.sendRcon(`/sc time_sync_manager.apply_canonical_daytime('${json}')`);
}
async handleCreateTrainProxy(event: messages.GridworldCreateTrainProxy) {
this.logger.info(`[gridworld] create_train_proxy received: destination="${event.destination}" edgeId=${event.edgeId} offset=${event.offset}`);
const json = lib.escapeString(JSON.stringify({
destination: event.destination,
edge_id: event.edgeId,
offset: event.offset,
}));
await this.sendRcon(`/sc train_path_manager.create_train_proxy('${json}')`);
}
async handleForwardClearTrainPath(event: messages.GridworldForwardClearTrainPath) {
const json = lib.escapeString(JSON.stringify({ id: event.id }));
await this.sendRcon(`/sc train_path_manager.clear_train_path_request('${json}')`);
}
async handleForwardTrainPath(event: messages.GridworldForwardTrainPath) {
this.logger.info(`[gridworld] forward_train_path received: train=${event.id} destination=${event.destination} sourceInstance=${event.sourceInstanceId}`);
const json = lib.escapeString(JSON.stringify({
id: event.id,
surface: event.surface,
position: event.position,
direction: event.direction,
destination: event.destination,
sourceInstanceId: event.sourceInstanceId,
}));
await this.sendRcon(`/sc train_path_manager.find_train_path('${json}')`);
}
// --- Corner diagonal transport ---
async handleCornerNeighbors(event: messages.GridworldCornerNeighbors) {
this.cornerNeighbors = event.neighbors;
const json = lib.escapeString(JSON.stringify(event.neighbors));
await this.sendRcon(`/sc gridworld.set_corner_neighbors('${json}')`);
}
private async handleCornerTeleportPlayerIpc(data: CornerTeleportPlayerIPC) {
const targetInstanceId = this.cornerNeighbors[data.corner];
if (!targetInstanceId) {
this.logger.warn(`No diagonal neighbor for corner ${data.corner}`);
return;
}
const { address, name } = await this.instance.sendTo(
"controller",
new messages.GridworldCornerTeleportPlayer(data.player_name, targetInstanceId),
);
const escapedPlayerName = lib.escapeString(data.player_name);
const escapedAddress = lib.escapeString(address);
const escapedServerName = lib.escapeString(name);
const cornerNames: Record<string, string> = { ne: "northeast", se: "southeast", sw: "southwest", nw: "northwest" };
const escapedDirection = lib.escapeString(cornerNames[data.corner] || data.corner);
await this.sendRcon(`/sc gridworld.corner_teleport_response("${escapedPlayerName}", "${escapedAddress}", "${escapedServerName}", "${escapedDirection}")`);
}
private async handleCornerEntityTransferIpc(data: CornerEntityTransferIPC) {
const targetInstanceId = this.cornerNeighbors[data.corner];
if (!targetInstanceId) {
this.logger.warn(`No diagonal neighbor for corner ${data.corner}`);
return;
}
await this.instance.sendTo(
{ instanceId: targetInstanceId },
new messages.GridworldDiagonalEntityTransfer(data.entity_transfers),
);
}
async handleDiagonalEntityTransfer(message: messages.GridworldDiagonalEntityTransfer) {
const json = lib.escapeString(JSON.stringify({
entity_transfers: message.entityTransfers,
}));
await this.sendRcon(`/sc gridworld.receive_diagonal_entity('${json}')`, true);
return { success: true };
}
}