forked from demipixel/factorio-blueprint
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
622 lines (544 loc) · 21.5 KB
/
index.js
File metadata and controls
622 lines (544 loc) · 21.5 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
'use strict';
const RawFlate = require('./rawflate');
const atob = require('atob');
const Victor = require('victor');
var gzip = require('gzip-js');
var entityData = require('./defaultentities');
class Blueprint {
constructor(str) {
this.icons = []; // Icons for Blueprint (up to 4)
this.entities = []; // List of all entities in Blueprint
this.tileGrid = {}; // Object with tile keys in format "x,y" => entity
if (str) this.load(str);
}
// All entities in beautiful string format
toString() {
this.setIds();
return this.entities.map(ent => ent.toString()).join('\n');
}
// Load blueprint from an existing one
load(str) {
const converted = RawFlate.inflate(atob(str).slice(10, -8));
const match = converted.match(/do local _={entities={(.+)},icons={(.+)}};return _;end/);
if (!match) throw new Error('Invalid blueprint string');
const correctFormat = str => {
return fromLuaBracket(str.replace(/\["([0-9]+)"\]/g, '\$1').replace(/=/g, ':').replace(/([a-z0-9_]+):/g, '"\$1":'));
}
const entities = JSON.parse('['+correctFormat(match[1])+']');
const icons = JSON.parse('['+correctFormat(match[2])+']');
entities.forEach(entity => {
this.createEntityWithData(entity, false, true, true); // no overlap, place altogether later, positions are their center
});
this.entities.forEach(entity => {
entity.place(this.tileGrid, this.entities);
})
this.icons = [];
for (let i = 0; i < icons.length; i++) {
this.icons[icons[i].index-1] = icons[i].name;
}
return this;
}
// Create an entity!
createEntity(name, position, direction, allowOverlap, noPlace, center) {
return this.createEntityWithData({ name: name, position: position, direction: direction || 0 }, allowOverlap, noPlace, center);
// Need to add to defaultentities.js whether something is rotatable. If not, set direction to null.
}
// Creates an entity with a data object instead of paramaters
createEntityWithData(data, allowOverlap, noPlace, center) {
const ent = new Entity(data, this.tileGrid, this, center);
if (allowOverlap || ent.checkNoOverlap(this.tileGrid)) {
if (!noPlace) ent.place(this.tileGrid, this.entities);
this.entities.push(ent);
return ent;
} else {
const otherEnt = ent.getOverlap(this.tileGrid);
throw new Error('Entity '+data.name+' overlaps '+otherEnt.name+' entity ('+data.position.x+', '+data.position.y+')');
}
}
// Returns entity at a position (or null)
findEntity(pos) {
return this.tileGrid[Math.floor(pos.x)+','+(pos.y)] || null;
}
// Removes a specific entity
removeEntity(ent) {
if (!ent) return false;
else {
ent.removeCleanup(this.tileGrid);
this.entities.splice(this.entities.indexOf(ent), 1);
return ent;
}
}
// Removes an entity at a position (returns false if no entity is there)
removeEntityPosition(position) {
if (!this.tileGrid[position.x+','+position.y]) return false;
return this.removeEntity(this.tileGrid[position.x+','+position.y]);
}
// Set ids for entities, called in luaString()
setIds() {
for (let i = 0; i < this.entities.length; i++) {
this.entities[i].id = i+1;
}
return this;
}
// Get corner/center positions
getPosition(f, xcomp, ycomp) {
if (!this.entities.length) return new Victor(0, 0);
return new Victor(this.entities.reduce((best, ent) => xcomp(best, ent[f]().x), this.entities[0][f]().x), this.entities.reduce((best, ent) => ycomp(best, ent[f]().y), this.entities[0][f]().y));
}
center() { return new Victor((this.topLeft().x + this.topRight().x) / 2, (this.topLeft().y + this.bottomLeft().y) / 2) }
topLeft() { return this.getPosition('topLeft', Math.min, Math.min); }
topRight() { return this.getPosition('topRight', Math.max, Math.min); }
bottomLeft() { return this.getPosition('bottomLeft', Math.min, Math.max); }
bottomRight() { return this.getPosition('bottomRight', Math.max, Math.max); }
// Center all entities
fixCenter() {
if (!this.entities.length) return this;
let offsetX = -this.center().x;
let offsetY = -this.center().y;
const offset = new Victor(offsetX, offsetY);
this.entities.forEach(entity => {
entity.position.add(offset);
});
return this;
}
// Quickly generate 2 (or num) icons
generateIcons(num) {
if (!num) num = 2;
num = Math.min(this.entities.length, Math.min(Math.max(num, 1), 4));
for (let i = 0; i < num; i++) {
this.icons[i] = this.entities[i].name;
}
return this;
}
// Give luaString that gets converted by encode()
luaString() {
this.setIds();
if (!this.icons.length) this.generateIcons();
const entString = this.entities.map(ent => ent.luaString()).join(',');
const iconString = this.icons.map((icon, i) => '{index='+(i+1)+',name="'+icon.replace(/_/g, '-')+'"}');
return 'do local _={entities={'+entString+'},icons={'+iconString+'}};return _;end';
}
// Blueprint string! Yay!
encode() {
return (new Buffer(gzip.zip(this.luaString()))).toString('base64');
}
// Set entityData
static setEntityData(obj) {
let keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
entityData[keys[i]] = obj[keys[i]];
}
}
// Get entityData
static getEntityData() {
return entityData;
}
}
class Entity {
constructor(data, tileGrid, bp, center) {
this.id = -1; // Id used when generating blueprint
this.bp = bp; // Blueprint
this.name = checkName(data.name); // Name or "type"
this.position = Victor.fromObject(data.position); // Position of top left corner
this.direction = 0; // Direction (usually 0, 2, 4, or 6)
this.rawConnections = data.connections; // Used in parsing connections from existing entity
this.connections = []; // Wire connections
this.condition = this.parseCondition(data.conditions); // Condition in combinator
this.filters = {}; // Filters for container or signals in constant combinator
this.requestFilters = {}; // Request filters for requester chest
let myData = entityData[this.name]; // entityData contains info like width, height, filterAmount, etc
this.size = myData ? new Victor(myData.width, myData.height) : // Size in Victor form
(entityData[this.name] ? new Victor(entityData[this.name].width, entityData[this.name].height) : new Victor(1, 1));
this.filterAmount = myData.filterAmount !== false; // Should filters have an amount (e.g. constant combinators have an amount, cargo wagon filter would not)
this.setDirection(data.direction || 0);
this.parseFilters(data.filters);
this.parseRequestFilters(data.request_filters);
if (center) {
this.position.subtract(this.size.clone().divide(new Victor(2, 2)));
}
this.position = new Victor(Math.round(this.position.x*100)/100, Math.round(this.position.y*100)/100);
}
// Beautiful string format
toString() {
let str = this.id+') '+this.name + ' =>\n';
str += ' position: '+this.position+'\n';
str += ' direction: '+this.direction+'\n';
str += ' connections: ';
if (!this.connections.length) str += 'none\n';
else {
str += '\n';
const two = this.name == 'arithmetic_combinator' || this.name == 'decider_combinator';
for (let i = 1; i <= (two ? 2 : 1); i++) {
const side = two && i == 2 ? 'out' : 'in'
const conns = this.connections.filter(c => c.side == i);
if (conns.length) {
if (two) str += ' '+side+':\n';
for (let j = 0; j < 2; j++) {
const color = j == 0 ? 'red' : 'green';
const exactConns = conns.filter(c => c.color == color);
if (exactConns.length) str += ' '+color+': '+exactConns.map(c => c.entity.id).join(',')+'\n';
}
}
}
}
if (this.condition) {
str += ' condition:\n';
str += ' expr: '+this.condition.left+' '+this.condition.operator+' '+this.condition.right+'\n';
str += this.condition.countFromInput != undefined ? ' countFromInput: '+(this.condition.countFromInput || false)+'\n' : '';
str += this.condition.out != undefined ? ' out: '+this.condition.out+'\n' : '';
}
return str;
}
/////////////////////////////////////
///// Parsing from existing blueprint
/////////////////////////////////////
// Parse connections into standard Entity format
parseConnections(entityList) {
const conns = this.rawConnections;
if (!conns) return [];
for (let side in conns) {
for (let color in conns[side]) {
for (let i = 0; i < conns[side][color].length; i++ ) {
const id = conns[side][color][i]['entity_id'];
this.connections.push({
entity: entityList[id-1],
color: color,
side: side,
id: conns[side][color][i]['circuit_id']
});
}
}
}
}
// Parse filters into standard Entity format
parseFilters(filters) { // Parse filters from lua (for constructor)
if (!filters) return [];
for (let i = 0; i < filters.length; i++) {
const name = checkName(this.filterAmount ? filters[i].signal.name : filters[i].name);
if (this.filterAmount) filters[i].signal.name = name;
else filters[i].name = name;
this.setFilter(filters[i].index, this.filterAmount ? filters[i].signal.name : filters[i].name, this.filterAmount ? filters[i].count : undefined);
}
}
// Parse request filters into standard Entity format
parseRequestFilters(request_filters) { // Parse request_filters from lua (for constructor)
if (!request_filters) return [];
for (let i = 0; i < request_filters.length; i++) {
request_filters[i].name = checkName(request_filters[i].name);
this.setRequestFilter(request_filters[i].index, request_filters[i].name, request_filters[i].count);
}
}
// Parse condition into standard Entity format
parseCondition(condition) {
if (!condition) return (this.name == 'decider_combinator' || this.name == 'arithmetic_combinator' ? {} : null);
const key = Object.keys(condition)[0];
const obj = condition[key];
if (obj.first_signal) obj.first_signal.name = checkName(obj.first_signal.name);
if (obj.second_signal) obj.second_signal.name = checkName(obj.second_signal.name);
if (obj.output_signal) obj.output_signal.name = checkName(obj.output_signal.name);
const out = {
left: obj.first_signal ? obj.first_signal.name : undefined,
right: obj.second_signal ? obj.second_signal.name : parseInt(obj.constant),
out: obj.output_signal ? obj.output_signal.name : undefined
};
if (key == 'decider') {
out.countFromInput = obj.copy_count_from_input == 'true';
}
if (obj.comparator) // Set operator
out.operator = obj.comparator == ':' ? '=' : obj.comparator;
else
out.operator = obj.operation;
return out;
}
////////////////
////////////////
////////////////
// Sets values in BP (tile data, parses connections).
// Typically, when loading from an existing blueprint, all entities are creating at the same time,
// and then all are placed at the same time (so each entity can parse the connections of the others)
place(tileGrid, entityList) {
this.setTileData(tileGrid);
this.parseConnections(entityList);
return this;
}
// Remove entity from blueprint
remove(bp) {
return (bp || this.bp).removeEntity(this);
}
// Cleans up tile data after removing
removeCleanup(tileGrid) {
this.removeTileData(tileGrid);
return this;
}
// Quick corner/center positions
topLeft() { return this.position.clone(); }
topRight() { return this.position.clone().add(this.size.clone().multiply(new Victor(1, 0))); }
bottomRight() { return this.position.clone().add(this.size); }
bottomLeft() { return this.position.clone().add(this.size.clone().multiply(new Victor(0, 1))); }
center() { return this.position.clone().add(this.size.clone().divide(new Victor(2, 2))); }
// Adds self to grid array
setTileData(tileGrid) {
this.tileDataAction(tileGrid, (x, y) => tileGrid[x+','+y] = this);
return this;
}
// Removes self from grid array
removeTileData(tileGrid) {
this.tileDataAction(tileGrid, (x, y) => delete tileGrid[x+','+y]);
return this;
}
// Return true if this entity overlaps with no other
checkNoOverlap(tileGrid) {
return !this.getOverlap(tileGrid);
}
// Returns an item this entity overlaps with (or null)
getOverlap(tileGrid) {
let item = null;
this.tileDataAction(tileGrid, (x, y) => {
item = tileGrid[x+','+y] || item;
});
return item;
}
// Do an action on every tile that this entity overlaps in a given tileGrid
tileDataAction(tileGrid, fn) {
if (!tileGrid) return;
const topLeft = this.topLeft();
const bottomRight = this.bottomRight().subtract(new Victor(0.9, 0.9));
for (let x = Math.floor(topLeft.x); x < bottomRight.x; x++) {
for (let y = Math.floor(topLeft.y); y < bottomRight.y; y++) {
fn(x, y);
}
}
}
// Connect current entity to another entity via wire
connect(ent, mySide, theirSide, color) {
mySide = convertSide(mySide, this);
theirSide = convertSide(theirSide, ent);
const checkCombinator = name => {
return name == 'decider_combinator' || name == 'arithmetic_combinator';
}
color = color == 'green' ? color : 'red';
this.connections.push({ entity: ent, color: color, side: mySide, id: checkCombinator(ent.name) ? theirSide : undefined });
ent.connections.push({ entity: this, color: color, side: theirSide, id: checkCombinator(this.name) ? mySide : undefined });
return this;
}
// Remove a specific wire connection given all details
removeConnection(ent, mySide, theirSide, color) {
mySide = convertSide(mySide, this);
theirSide = convertSide(theirSide, ent);
color = color || 'red';
for (let i = 0; i < this.connections.length; i++) {
if (this.connections[i].entity == ent && this.connections[i].side == mySide && this.connections[i].color == color) {
this.connections.splice(i, 1);
break;
}
}
for (let i = 0; i < ent.connections.length; i++) {
if (ent.connections[i].entity == this && ent.connections[i].side == theirSide && ent.connections[i].color == color) {
ent.connections.splice(i, 1);
break;
}
}
return this;
}
// Remove all wire connections with entity (optionally of a specific color)
removeConnectionsWithEntity(ent, color) {
for (let i = this.connections.length-1; i >= 0; i--) {
if (this.connections[i].entity == ent && (!color || this.connections[i].color == color)) this.connections.splice(i, 1);
}
for (let i = ent.connections.length-1; i >= 0; i--) {
if (ent.connections[i].entity == this && (!color || ent.connections[i].color == color)) ent.connections.splice(i, 1);
}
return this;
}
// Remove all wire connections
removeAllConnections() {
for (let i = 0; i < this.connections.length; i++) {
let ent = this.connections[i].entity;
for (let j = 0; j < ent.connections.length; j++) {
if (ent.connections[j].entity == this) {
ent.connections.splice(j, 1);
break;
}
}
}
this.connections = [];
return this;
}
setFilter(pos, item, amt, request) {
const filter = request ? 'requestFilters' : 'filters';
item = checkName(item);
if (item == null) delete this[filter][pos];
else this[filter][pos] = {
name: item,
count: amt || 0
};
return this;
}
setRequestFilter(pos, item, amt) {
return this.setFilter(pos, item, amt, true);
}
removeAllFilters() {
this.filters = {};
return this;
}
removeAllRequestFilters() {
this.requestFilters = {};
return this;
}
// Sets condition of entity (for combinators)
setCondition(opt) {
if (opt.countFromInput != undefined && this.name != 'decider_combinator') throw new Error('Cannot set countFromInput for '+this.name);
if (opt.left) opt.left = checkName(opt.left);
if (typeof opt.right == 'string') opt.right = checkName(opt.right);
if (opt.out) opt.out = checkName(opt.out);
const checkAllow = name => {
if (opt[name] != undefined) {
return opt[name];
} else if (this.condition[name] != undefined) {
return this.condition[name];
} else {
return undefined;
}
}
if (!this.condition) this.condition = {};
this.condition = {
left: checkAllow('left'),
right: checkAllow('right'),
operator: checkAllow('operator'),
countFromInput: checkAllow('countFromInput'),
out: checkAllow('out')
};
return this;
}
// Sets direction of entity
setDirection(dir) {
// if (this.direction == null) return this; // Prevent rotation when we know what things can rotate in defaultentities.js
this.size = new Victor((dir % 4 == this.direction % 4 ? this.size.x : this.size.y),
(dir % 4 == this.direction % 4 ? this.size.y : this.size.x));
this.direction = dir;
return this;
}
// Convert condition to lua format
luaConnections() {
const out = {};
for (let i = 0; i < this.connections.length; i++) {
let side = this.connections[i].side;
let color = this.connections[i].color;
if (!out[side]) out[side] = {};
if (!out[side][color]) out[side][color] = [];
out[side][color].push({ entity_id: this.connections[i].entity.id, circuit_id: this.connections[i].id });
}
return toLuaFixer(JSON.stringify(out)).replace(/([12])=/g, '["\$1"]=');
}
// Convert filter to lua format
luaFilter() {
return toLuaFixer(JSON.stringify(Object.keys(this.filters).map(key => {
const obj = {
index: parseInt(key)
};
const name = this.filters[key].name.replace(/_/g, '-');
if (this.filterAmount) {
const type = entityData[this.filters[key].name].type;
obj.signal = {
type: type,
name: name,
};
obj.count = this.filters[key].count;
} else {
obj.name = name;
}
return obj;
})));
}
// Convert request filter to lua format
luaRequestFilter() {
return toLuaFixer(JSON.stringify(Object.keys(this.requestFilters).map(key => {
return {
name: this.requestFilters[key].name.replace(/_/g, '-'),
count: this.requestFilters[key].count,
index: parseInt(key)
};
})));
}
// Convert condition to Lua format
luaCondition() {
let key = this.name == 'arithmetic_combinator' ? 'arithmetic' : (this.name == 'decider_combinator' ? 'decider' : 'circuit');
let out = {};
out[key] = {
first_signal: (this.condition.left ? {
type: entityData[this.condition.left].type,
name: this.condition.left.replace(/_/g, '-')
} : undefined),
second_signal: (typeof this.condition.right == 'string' ? {
type: entityData[this.condition.right].type,
name: this.condition.right.replace(/_/g, '-')
} : undefined),
constant: typeof this.condition.right == 'number' ? this.condition.right : undefined,
operation: undefined,
comparator: undefined,
output_signal: (this.condition.out ? {
type: entityData[this.condition.out].type,
name: this.condition.out.replace(/_/g, '-')
} : undefined)
};
if (key != 'arithmetic') {
out[key].comparator = this.condition.operator;
out[key].copy_count_from_input = this.condition.countFromInput != undefined ? (!!this.condition.countFromInput).toString() : undefined;
} else {
out[key].operation = this.condition.operator;
}
return toLuaFixer(JSON.stringify(out));
}
// Entity luaString that gets merged in Blueprint.luaString()
luaString() {
const direction = this.direction ? ',direction='+this.direction : '';
const connections = this.connections.length ? ',connections='+this.luaConnections() : '';
const filters = Object.keys(this.filters).length ? ',filters='+this.luaFilter() : '';
const request_filters = Object.keys(this.requestFilters).length ? ',request_filters='+this.luaRequestFilter() : '';
const condition = this.condition ? ',conditions='+this.luaCondition() : '';
const centerPos = this.center();
return '{name="'+this.name.replace(/_/g, '-')+'",position={x='+centerPos.x+',y='+centerPos.y+'}'+direction+connections+filters+request_filters+condition+'}';
}
}
// Lib Functions
// Convert to lua
function toLuaFixer(str) {
return str.replace(/\[/g, '{').replace(/\]/g, '}').replace(/"([a-z0-9_]+)":/g, '\$1=')
}
// Convert from lua to JSON
function fromLuaBracket(str) {
let out = '';
const brackets = [];
for (var i = 0; i < str.length; i++) {
if (str[i] == '{') {
if (str[i+1] == '{') {
out += '[';
brackets.push(true);
} else {
out += '{';
brackets.push(false);
}
} else if (str[i] == '}') {
let isArray = brackets.splice(-1)[0];
if (isArray) out += ']';
else out += '}';
} else out += str[i];
}
return out;
}
// Convert 'in' or 'out' of wires (only combinators have both of these) to a 1 or 2.
function convertSide(side, ent) {
if (!side) return 1;
if (side == 1 || side == 2) return side;
else if (side == 'in' || side == 'out') {
if (ent && ent.name != 'arithmetic_combinator' && ent.name != 'decider_combinator') return 1;
else return side == 'in' ? 1 : 2;
} else throw new Error('Invalid side');
}
// Check that name of entity is valid
function checkName(name) {
name = name.replace(/-/g, '_');
if (!entityData[name]) throw new Error(name+' does not exist! You can add it by putting it into entityData.');
return name;
}
module.exports = Blueprint;