-
Notifications
You must be signed in to change notification settings - Fork 17
/
env.py
1778 lines (1498 loc) · 65.2 KB
/
env.py
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# env.py
"""
Manages the Factorio environment. Primarily holds :py:func:`draftsman.env.update()`,
which runs through the Factorio data lifecycle and updates the data in
:py:mod:`draftsman.data`.
"""
# TODO:
# Make sure everything uses OrderedDict for backwards compatability
from __future__ import print_function
# Python 2 compat
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
from draftsman.error import (
MissingModError,
IncompatableModError,
IncorrectModVersionError,
IncorrectModFormatError,
)
from draftsman.utils import decode_version, version_string_to_tuple
from draftsman._factorio_version import __factorio_version_info__
import argparse
from collections import OrderedDict
import copy
import json
import lupa
import os
import pickle
import re
import struct
import zipfile
mod_archive_pattern = "([\\w\\D]+)_([\\d\\.]+)\\."
mod_archive_regex = re.compile(mod_archive_pattern)
dependency_string_pattern = (
"[^\\w\\?\\!~]*([\\?\\!~])?[^\\w\\?\\!]*([\\w-]+)([><=]=?)?([\\d\\.]+)?"
)
dependency_regex = re.compile(dependency_string_pattern)
lua_module_pattern = "\\.\\/factorio-mods\\/(.+?)\\/.*"
lua_module_regex = re.compile(lua_module_pattern)
class Mod(object):
"""
Mod object that stores metadata during the load process. Mostly used for
structuring the data and determining the load order.
"""
def __init__(
self, name, internal_folder, version, archive, location, info, files, data
):
self.name = name
self.internal_folder = internal_folder
self.version = version
self.archive = archive
self.location = location
self.info = info
self.files = files
self.data = data
self.dependencies = []
def add_dependency(self, dependency):
self.dependencies.append(dependency)
def get_depth(self):
depth = 1
for dependency in self.dependencies:
depth = max(depth, depth + dependency.get_depth())
return depth
def to_dict(self):
return {
"name": self.name,
"version": self.version,
"archive": self.archive,
"location": self.location,
"dependencies": self.dependencies,
}
def __lt__(self, other):
return self.name < other.name
def __repr__(self):
return str(self.to_dict())
# =============================================================================
def file_to_string(filepath):
"""
Simply grabs a file's contents and returns it as a string.
"""
with open(filepath, mode="r") as file:
return file.read()
def get_mod_settings(location):
"""
Reads `mod_settings.dat` and stores it as an easy-to-read dict. Would be
trivial to implement an editor with this function. (Well, assuming you write
a function to export back to a ``.dat`` file)
"""
# Property Tree Enum
PropertyTreeType = {
"None": 0,
"Bool": 1,
"Number": 2,
"String": 3,
"List": 4,
"Dictionary": 5,
}
def get_string(binary_stream):
# print("String")
string_absent = bool(
# int.from_bytes(binary_stream.read(1), "little", signed=False)
struct.unpack("<?", binary_stream.read(1))[0]
)
# print("string absent?", string_absent)
if string_absent:
return None
# handle the Space Optimized length
# length = int.from_bytes(binary_stream.read(1), "little", signed=False)
length = struct.unpack("<B", binary_stream.read(1))[0]
if length == 255: # length is actually longer
# length = int.from_bytes(binary_stream.read(4), "little", signed=False)
length = struct.unpack("<I", binary_stream.read(4))[0]
# print(length)
return binary_stream.read(length).decode()
def get_data(binary_stream):
data_type = struct.unpack("<B", binary_stream.read(1))[0]
# print("data_type:", data_type)
binary_stream.read(1) # any type flag, largely internal, ignore
if data_type == PropertyTreeType["None"]:
# print("None")
return None
elif data_type == PropertyTreeType["Bool"]:
# print("Bool")
return bool(struct.unpack("<?", binary_stream.read(1))[0])
elif data_type == PropertyTreeType["Number"]:
# print("Number")
value = struct.unpack("d", binary_stream.read(8))[0]
return value
elif data_type == PropertyTreeType["String"]:
return get_string(binary_stream)
elif data_type == PropertyTreeType["List"]:
# print("List")
length = struct.unpack("<I", binary_stream.read(4))
out = list()
for i in range(length):
out.append(get_data(binary_stream))
return out
elif data_type == PropertyTreeType["Dictionary"]:
# print("Dict")
length = struct.unpack("<I", binary_stream.read(4))[0]
out = dict()
for i in range(length):
name = get_string(binary_stream)
value = get_data(binary_stream)
# print(name, value)
out[name] = value
return out
mod_settings = {}
with open(
os.path.join(location, "mod-settings.dat"), mode="rb"
) as mod_settings_dat:
# header
# version_num = int.from_bytes(mod_settings_dat.read(8), "little")
version_num = struct.unpack("<Q", mod_settings_dat.read(8))[0]
# print(version_num)
version = decode_version(version_num)
# print(version)
# header_flag = bool(int.from_bytes(mod_settings_dat.read(1), "little", signed=False))
header_flag = bool(struct.unpack("<?", mod_settings_dat.read(1))[0])
# print(header_flag)
# assert version[::-1] >= __factorio_version_info__ and not header_flag
mod_settings = get_data(mod_settings_dat)
return mod_settings
def python_require(mod_list, current_mod, module_name, package_path):
"""
Function called from Lua that checks for a file in a ``zipfile`` archive,
and returns the contents of the file if found.
Used in the modified Lua ``require()`` function that handles special cases
to model Factorio's load pattern. This function is called after
`normalize_module_name`, and expects the name to be it's result.
"""
# Determine the mod we need. Factorio mods can load files from other mods,
# so we check this value against a set of regex to extract the mod name from
# the beginning of the normalized module name
try:
mod_name = lua_module_regex.match(module_name)[1]
except TypeError:
mod_name = None
# If the name is found, then we change "contexts" to that mod; otherwise,
# the current context is assumed to be be the current mod archive
if mod_name:
mod = mod_list[mod_name]
else:
mod = current_mod
# No sense searching the archive if the mod is not one to begin with; we
# relay this information back to the Lua require function
if not mod.archive:
return None, "Current mod ({}) is not an archive".format(mod.name)
# We emulate lua filepath searching
filepaths = package_path.split(";")
for filepath in filepaths:
# Replace the question mark with the module_name
filepath = filepath.replace("?", module_name)
# Make it local to the archive, replacing the global path to the local
# internal path
filepath = filepath.replace("./factorio-mods/" + mod.name, mod.internal_folder)
# Normalize for Zipfile if there are backslashes
filepath = filepath.replace("\\", "/")
try:
fixed_filepath = os.path.dirname(filepath[filepath.find("/") :])
return mod.files.read(filepath), fixed_filepath
except KeyError:
pass
# Otherwise, we found squat
return None, "no file '{}' found in '{}' archive".format(module_name, mod.name)
def load_stage(lua, mod_list, mod, stage):
"""
Load a stage of the Factorio data lifecycle. Sets meta information and loads
and executes the file string in the ``lua`` context.
"""
# Set meta stuff
lua.globals().MOD_LIST = mod_list
lua.globals().MOD = mod
lua.globals().MOD_DIR = mod.location
lua.globals().CURRENT_FILE = os.path.join(mod.location, stage)
# Add the base mod folder as a base path (in addition to base and core)
lua.globals().lua_add_path(os.path.join(mod.location, "?.lua"))
lua.execute(mod.data[stage])
def convert_table_to_dict(table):
"""
Converts a Lua table to a Python dict. Correctly handles nesting, and
interprets Lua arrays as lists.
"""
out = dict(table)
# print(out)
is_list = True
for key in out:
# print(key)
if not isinstance(key, int):
is_list = False
if lupa.lua_type(out[key]) == "table":
# print(out[key])
# out[key] = convert_table_to_dict(out[key])
out[key] = convert_table_to_dict(out[key])
# check if its actually a dict and not a list
if is_list:
return list(out.values())
return out
def get_order(objects_to_sort, sort_objects, sort_subgroups, sort_groups):
"""
Sorts the list of objects according to their Factorio order. Attempts to
sort by item order first, and defaults to entity order if not present.
Item sort order:
(https://forums.factorio.com/viewtopic.php?p=23818#p23818)
1. object groups
2. object subgroups
3. object itself
Across the previous categories, each is sorted by:
1. the item order string (if present)
2. the item name (lexographic)
"""
def general_iterator(obj):
if isinstance(obj, dict):
return obj.values()
else:
return obj
modified = []
for object_to_sort in general_iterator(objects_to_sort):
# Try to sort by item order if possible because thats more intuitive
# Otherwise, fall back onto entity order
associated_item = None
try:
# First, try to get the item that this object becomes when mined
# Technically, "result" can also be "results", but I'm not sure we
# need interpret those kinds of entities, so we ignore that case for
# now
associated_item = object_to_sort["minable"]["result"]
except KeyError:
# If not, check the list of items to see if our name is in there
if object_to_sort["name"] in sort_objects:
associated_item = object_to_sort["name"]
if associated_item:
# Get the name of the sorted item; we sort by this before we sort by
# entity name
sort_name = sort_objects[associated_item]["name"]
# We also try to use the item sort order if available before we use
# the entity sort order
sort_order = sort_objects[associated_item].get(
"order", object_to_sort.get("order", None)
)
# Subgroup is optional, and defaults to "other" if not specified
if "subgroup" in sort_objects[associated_item]:
subgroup_name = sort_objects[associated_item]["subgroup"]
sort_subgroup = sort_subgroups[subgroup_name]
else:
sort_subgroup = sort_subgroups["other"]
# Now that we know the subgroup, we can also determine the group
# that this object belongs to
group_name = sort_subgroup["group"]
sort_group = sort_groups[group_name]
else: # the object is either an item or something non-placable
# Pull the name and order from the object directly
sort_name = object_to_sort["name"]
sort_order = object_to_sort.get("order", None)
# Subgroup is optional, and defaults to "other" if not specified
if "subgroup" in object_to_sort:
subgroup_name = object_to_sort["subgroup"]
sort_subgroup = sort_subgroups[subgroup_name]
else:
# Set the subgroup to a default value
# Maybe sort_subgroup defaults to type of sorted object?
if object_to_sort["type"] == "fluid":
# Fluids default to the fluid category
sort_subgroup = sort_subgroups["fluid"]
else:
sort_subgroup = sort_subgroups["other"]
# Now that we know the subgroup, we can also determine the group
# that this object belongs to
group_name = sort_subgroup["group"]
sort_group = sort_groups[group_name]
# Sometimes we want to sort an item differently based off a 'parents'
# name. Consider 'straight-rail' and 'se-straight-rail': name order
# indicates that the order should be
# ['se-straight-rail', 'straight-rail']
# but in-game, the rail-planners that you see are the other way around,
# which is more intuitive.
# However, if we sort by rail planners, we lose the original name of the
# sorted target, straight-rail.
# So we add a third param to "obj": first the item/entity order, then
# the name we would like to sort the object with, and finally the actual
# name that we want to preserve.
modified.append(
{
"obj": (
sort_order is None, # We want objects with no order last, not first
sort_order,
sort_name,
object_to_sort["name"],
),
"subgroup": (sort_subgroup["order"], sort_subgroup["name"]),
"group": (sort_group["order"], sort_group["name"]),
}
)
order = sorted(modified, key=lambda x: (x["group"], x["subgroup"], x["obj"]))
return [x["obj"][3] for x in order]
def get_items(lua):
"""
Gets the loaded items, item subgroups, and item groups. Sorts them and
returns them. Saves us the trouble of recalcualting this every time we sort
something along item order, which we commonly do.
"""
data = lua.globals().data
groups = convert_table_to_dict(data.raw["item-group"])
subgroups = convert_table_to_dict(data.raw["item-subgroup"])
def to_ordered_dict(elem):
sorted_elem = OrderedDict()
for v in elem:
sorted_elem[v["name"]] = v
return sorted_elem
# Sort the groups and subgroups dictionaries
test_values = sorted(list(groups.values()), key=lambda x: x["order"])
# sorted_groups = {}
# for v in test_values:
# sorted_groups[v["name"]] = v
sorted_groups = to_ordered_dict(test_values)
test_values = sorted(list(subgroups.values()), key=lambda x: x["order"])
# sorted_subgroups = {}
# for v in test_values:
# sorted_subgroups[v["name"]] = v
sorted_subgroups = to_ordered_dict(test_values)
group_index_dict = {}
subgroup_index_dict = {}
# Initialize item groups
group_list = list(groups.values())
for group in group_list:
group["subgroups"] = []
group_index_dict[group["name"]] = group
# Initialize item subgroups
subgroup_list = list(subgroups.values())
for subgroup in subgroup_list:
subgroup["items"] = []
parent_group = group_index_dict[subgroup["group"]]
parent_group["subgroups"].append(subgroup)
subgroup_index_dict[subgroup["name"]] = subgroup
def add_item(category, item_name):
item = category[item_name]
# if "flags" in item:
# if "hidden" in item["flags"].values():
# return
if "subgroup" in item:
subgroup = subgroup_index_dict[item["subgroup"]]
else:
subgroup = subgroup_index_dict["other"]
if "order" not in item:
item["order"] = ""
subgroup["items"].append(item)
def add_items(category):
category = convert_table_to_dict(category)
for item_name in category:
add_item(category, item_name)
# Iterate over every item
add_items(data.raw["item"])
add_items(data.raw["item-with-entity-data"])
add_items(data.raw["tool"])
add_items(data.raw["ammo"])
add_items(data.raw["module"])
add_items(data.raw["armor"])
add_items(data.raw["gun"])
add_items(data.raw["capsule"])
# Extras
add_items(data.raw["blueprint"])
add_items(data.raw["blueprint-book"])
add_items(data.raw["upgrade-item"])
add_items(data.raw["deconstruction-item"])
add_items(data.raw["spidertron-remote"])
add_items(data.raw["repair-tool"]) # not an item somehow
add_items(data.raw["rail-planner"])
# Sort everything
for i, _ in enumerate(group_list):
for j, _ in enumerate(group_list[i]["subgroups"]):
group_list[i]["subgroups"][j]["items"] = to_ordered_dict(
sorted(
group_list[i]["subgroups"][j]["items"],
key=lambda x: (x["order"], x["name"]),
)
)
group_list[i]["subgroups"] = to_ordered_dict(
sorted(group_list[i]["subgroups"], key=lambda x: (x["order"], x["name"]))
)
group_list = sorted(group_list, key=lambda x: (x["order"], x["name"]))
# print(json.dumps(group_list[0]["subgroups"], indent=2))
# print(json.dumps(sorted_groups, indent=2))
# Flatten into all_items dictionary
sorted_items = OrderedDict()
for group in group_list:
for subgroup_name in group["subgroups"]:
subgroup = group["subgroups"][subgroup_name]
for item_name in subgroup["items"]:
item = subgroup["items"][item_name]
sorted_items[item["name"]] = item
return sorted_items, sorted_subgroups, sorted_groups
# =============================================================================
def extract_mods(loaded_mods, data_location, verbose):
"""
Extract all the mod versions to ``mods.pkl`` in :py:mod:`draftsman.data`.
"""
out_mods = {}
for mod in loaded_mods:
out_mods[mod] = version_string_to_tuple(loaded_mods[mod].version)
with open(os.path.join(data_location, "mods.pkl"), "wb") as out:
pickle.dump(out_mods, out, pickle.HIGHEST_PROTOCOL)
if verbose:
print("Extracted mods...")
def extract_entities(lua, data_location, verbose, sort_tuple):
"""
Extracts the entities to ``entities.pkl`` in :py:mod:`draftsman.data`.
"""
data = lua.globals().data
entities = {}
unordered_entities_raw = {}
is_flippable = {}
def is_entity_flippable(entity):
"""
Determines whether or not the input entity can be flipped inside a
Blueprint.
"""
# if not entity.get("fluid_boxes", False):
# return True
# https://forums.factorio.com/102294
# Check if any entity has a fluid box
# fluid_boxes = []
# if "fluid_box" in entity:
# fluid_boxes.append(copy.deepcopy(entity["fluid_box"]))
# elif "fluid_boxes" in entity: # Check crafting machine fluid boxes
# boxes_copy = copy.deepcopy(entity["fluid_boxes"])
# if isinstance(boxes_copy, dict): # Convert to a list if it's a dict
# boxes_copy.pop("off_when_no_fluid_recipe", None)
# boxes_copy = list(boxes_copy.values())
# fluid_boxes.extend(boxes_copy)
# elif "output_fluid_box" in entity: # Check mining-drill fluid boxes
# fluid_boxes.append(copy.deepcopy(entity["output_fluid_box"]))
# if fluid_boxes:
# # Record the position of every fluid box along with their type
# box_locations = {}
# for fluid_box in fluid_boxes:
# for pipe_connection in fluid_box["pipe_connections"]:
# if "position" in pipe_connection:
# pos = tuple(pipe_connection["position"])
# box_locations[pos] = pipe_connection.get("type", "input-output")
# elif "positions" in pipe_connection:
# for pos in pipe_connection["positions"]:
# pos = tuple(pos)
# box_locations[pos] = pipe_connection.get("type", "input-output")
# # Check the fluid box's mirrored position for conflicts
# for fluid_box in fluid_boxes:
# for pipe_connection in fluid_box["pipe_connections"]:
# if "position" in pipe_connection:
# pos = tuple(pipe_connection["position"])
# type = box_locations[pos]
# if ((-pos[0], pos[1]) in box_locations and
# type != box_locations[(-pos[0], pos[1])]):
# return False
# if ((pos[0], -pos[1]) in box_locations and
# type != box_locations[(pos[0], -pos[1])]):
# return False
# # if pos[0] != 0 and pos[1] != 0:
# # return False
# elif "positions" in pipe_connection:
# for pos in pipe_connection["positions"]:
# pos = tuple(pos)
# type = box_locations[pos]
# if ((-pos[0], pos[1]) in box_locations and
# type != box_locations[(-pos[0], pos[1])]):
# return False
# if ((pos[0], -pos[1]) in box_locations and
# type != box_locations[(pos[0], -pos[1])]):
# return False
# Hardcoded entities: we do this because I have no idea what the
# criteria is for unflippablility
if entity["name"] in {"pumpjack", "chemical-plant", "oil-refinery"}:
return False
# Restricted types; due to the way rails work these have no flipping
if entity["type"] in {"rail-signal", "rail-chain-signal", "train-stop"}:
return False
return True
def categorize_entities(entity_table, target_list):
entity_dict = convert_table_to_dict(entity_table)
for entity_name, entity in entity_dict.items():
flags = entity["flags"]
if (
"not-blueprintable" in flags or "not-deconstructable" in flags
): # or "hidden" in flags
continue
# Check if an entity is flippable or not
is_flippable[entity_name] = is_entity_flippable(entity)
# maybe move this to get_order?
unordered_entities_raw[entity_name] = entity
target_list.append(entity)
def sort(target_list):
sorted_list = get_order(target_list, *sort_tuple)
for i, x in enumerate(sorted_list):
target_list[i] = x
# Chests
entities["containers"] = []
categorize_entities(data.raw["container"], entities["containers"])
sort(entities["containers"])
# Storage tanks
entities["storage_tanks"] = []
categorize_entities(data.raw["storage-tank"], entities["storage_tanks"])
sort(entities["storage_tanks"])
# Belts
entities["transport_belts"] = []
categorize_entities(data.raw["transport-belt"], entities["transport_belts"])
sort(entities["transport_belts"])
entities["underground_belts"] = []
categorize_entities(data.raw["underground-belt"], entities["underground_belts"])
sort(entities["underground_belts"])
entities["splitters"] = []
categorize_entities(data.raw["splitter"], entities["splitters"])
sort(entities["splitters"])
# Inserters
entities["inserters"] = []
entities["filter_inserters"] = []
# categorize_entities(data.raw["inserter"], inserters)
temp_inserters = convert_table_to_dict(data.raw["inserter"])
for inserter_name, inserter in temp_inserters.items():
unordered_entities_raw[inserter_name] = inserter
if "filter_count" in inserter:
entities["filter_inserters"].append(inserter)
else:
entities["inserters"].append(inserter)
sort(entities["inserters"])
sort(entities["filter_inserters"])
# Loaders
entities["loaders"] = []
categorize_entities(data.raw["loader"], entities["loaders"])
sort(entities["loaders"])
# Electric poles
entities["electric_poles"] = []
categorize_entities(data.raw["electric-pole"], entities["electric_poles"])
sort(entities["electric_poles"])
# Pipes
entities["pipes"] = []
categorize_entities(data.raw["pipe"], entities["pipes"])
sort(entities["pipes"])
entities["underground_pipes"] = []
categorize_entities(data.raw["pipe-to-ground"], entities["underground_pipes"])
sort(entities["underground_pipes"])
# Pumps
entities["pumps"] = []
categorize_entities(data.raw["pump"], entities["pumps"])
sort(entities["pumps"])
# Rails
entities["straight_rails"] = []
categorize_entities(data.raw["straight-rail"], entities["straight_rails"])
sort(entities["straight_rails"])
entities["curved_rails"] = []
categorize_entities(data.raw["curved-rail"], entities["curved_rails"])
sort(entities["curved_rails"])
# Train stops
entities["train_stops"] = []
categorize_entities(data.raw["train-stop"], entities["train_stops"])
sort(entities["train_stops"])
# Rail signals
entities["rail_signals"] = []
categorize_entities(data.raw["rail-signal"], entities["rail_signals"])
sort(entities["rail_signals"])
entities["rail_chain_signals"] = []
categorize_entities(data.raw["rail-chain-signal"], entities["rail_chain_signals"])
sort(entities["rail_chain_signals"])
# Train cars
entities["locomotives"] = []
categorize_entities(data.raw["locomotive"], entities["locomotives"])
sort(entities["locomotives"])
entities["cargo_wagons"] = []
categorize_entities(data.raw["cargo-wagon"], entities["cargo_wagons"])
sort(entities["cargo_wagons"])
entities["fluid_wagons"] = []
categorize_entities(data.raw["fluid-wagon"], entities["fluid_wagons"])
sort(entities["fluid_wagons"])
entities["artillery_wagons"] = []
categorize_entities(data.raw["artillery-wagon"], entities["artillery_wagons"])
sort(entities["artillery_wagons"])
# Logistics containers (Special)
entities["logistic_passive_containers"] = []
entities["logistic_active_containers"] = []
entities["logistic_storage_containers"] = []
entities["logistic_buffer_containers"] = []
entities["logistic_request_containers"] = []
logi_containers = convert_table_to_dict(data.raw["logistic-container"])
for container_name, container in logi_containers.items():
unordered_entities_raw[container_name] = container
container_type = container["logistic_mode"]
if container_type == "passive-provider":
entities["logistic_passive_containers"].append(container)
elif container_type == "active-provider":
entities["logistic_active_containers"].append(container)
elif container_type == "storage":
entities["logistic_storage_containers"].append(container)
elif container_type == "buffer":
entities["logistic_buffer_containers"].append(container)
elif container_type == "requester":
entities["logistic_request_containers"].append(container)
sort(entities["logistic_passive_containers"])
sort(entities["logistic_active_containers"])
sort(entities["logistic_storage_containers"])
sort(entities["logistic_buffer_containers"])
sort(entities["logistic_request_containers"])
# Roboports
entities["roboports"] = []
categorize_entities(data.raw["roboport"], entities["roboports"])
sort(entities["roboports"])
# Lamps
entities["lamps"] = []
categorize_entities(data.raw["lamp"], entities["lamps"])
sort(entities["lamps"])
# Combinators
entities["arithmetic_combinators"] = []
categorize_entities(
data.raw["arithmetic-combinator"], entities["arithmetic_combinators"]
)
sort(entities["arithmetic_combinators"])
entities["decider_combinators"] = []
categorize_entities(data.raw["decider-combinator"], entities["decider_combinators"])
sort(entities["decider_combinators"])
entities["constant_combinators"] = []
categorize_entities(
data.raw["constant-combinator"], entities["constant_combinators"]
)
sort(entities["constant_combinators"])
entities["power_switches"] = []
categorize_entities(data.raw["power-switch"], entities["power_switches"])
sort(entities["power_switches"])
entities["programmable_speakers"] = []
categorize_entities(
data.raw["programmable-speaker"], entities["programmable_speakers"]
)
sort(entities["programmable_speakers"])
# Boilers / Heat exchangers
entities["boilers"] = []
categorize_entities(data.raw["boiler"], entities["boilers"])
sort(entities["boilers"])
# Steam engines / turbines
entities["generators"] = []
categorize_entities(data.raw["generator"], entities["generators"])
sort(entities["generators"])
# Solar panels
entities["solar_panels"] = []
categorize_entities(data.raw["solar-panel"], entities["solar_panels"])
sort(entities["solar_panels"])
# Accumulators
entities["accumulators"] = []
categorize_entities(data.raw["accumulator"], entities["accumulators"])
sort(entities["accumulators"])
# Reactors
entities["reactors"] = []
categorize_entities(data.raw["reactor"], entities["reactors"])
sort(entities["reactors"])
# Heat pipes
entities["heat_pipes"] = []
categorize_entities(data.raw["heat-pipe"], entities["heat_pipes"])
sort(entities["heat_pipes"])
# Mining drills (Burner, Electric, Pumpjack)
entities["mining_drills"] = []
categorize_entities(data.raw["mining-drill"], entities["mining_drills"])
sort(entities["mining_drills"])
# Offshore pumps
entities["offshore_pumps"] = []
categorize_entities(data.raw["offshore-pump"], entities["offshore_pumps"])
sort(entities["offshore_pumps"])
# Furnaces
entities["furnaces"] = []
categorize_entities(data.raw["furnace"], entities["furnaces"])
sort(entities["furnaces"])
# Assembling machines (1-3 + chemical plant, refinery, and centrifuge)
entities["assembling_machines"] = []
categorize_entities(data.raw["assembling-machine"], entities["assembling_machines"])
sort(entities["assembling_machines"])
# Labs
entities["labs"] = []
categorize_entities(data.raw["lab"], entities["labs"])
sort(entities["labs"])
# Beacons
entities["beacons"] = []
categorize_entities(data.raw["beacon"], entities["beacons"])
sort(entities["beacons"])
# Rocket silos
entities["rocket_silos"] = []
categorize_entities(data.raw["rocket-silo"], entities["rocket_silos"])
sort(entities["rocket_silos"])
# Landmines
entities["land_mines"] = []
categorize_entities(data.raw["land-mine"], entities["land_mines"])
sort(entities["land_mines"])
# Walls
entities["walls"] = []
categorize_entities(data.raw["wall"], entities["walls"])
sort(entities["walls"])
# Gates
entities["gates"] = []
categorize_entities(data.raw["gate"], entities["gates"])
sort(entities["gates"])
# Turrets
entities["turrets"] = []
categorize_entities(data.raw["ammo-turret"], entities["turrets"])
categorize_entities(data.raw["electric-turret"], entities["turrets"])
categorize_entities(data.raw["fluid-turret"], entities["turrets"])
categorize_entities(data.raw["artillery-turret"], entities["turrets"])
sort(entities["turrets"])
# Radars
entities["radars"] = []
categorize_entities(data.raw["radar"], entities["radars"])
sort(entities["radars"])
# Electric Energy Interfaces
entities["electric_energy_interfaces"] = []
categorize_entities(
data.raw["electric-energy-interface"], entities["electric_energy_interfaces"]
)
sort(entities["electric_energy_interfaces"])
# Linked Containers
entities["linked_containers"] = []
try:
categorize_entities(data.raw["linked-container"], entities["linked_containers"])
sort(entities["linked_containers"])
except TypeError:
pass
# Heat interfaces
entities["heat_interfaces"] = []
categorize_entities(data.raw["heat-interface"], entities["heat_interfaces"])
sort(entities["heat_interfaces"])
# Linked belts
entities["linked_belts"] = []
try:
categorize_entities(data.raw["linked-belt"], entities["linked_belts"])
sort(entities["linked_belts"])
except TypeError:
pass
# Infinity containers
entities["infinity_containers"] = []
categorize_entities(data.raw["infinity-container"], entities["infinity_containers"])
sort(entities["infinity_containers"])
# Infinity pipes
entities["infinity_pipes"] = []
categorize_entities(data.raw["infinity-pipe"], entities["infinity_pipes"])
sort(entities["infinity_pipes"])
# Burner generators
entities["burner_generators"] = []
categorize_entities(data.raw["burner-generator"], entities["burner_generators"])
sort(entities["burner_generators"])
raw_order = get_order(unordered_entities_raw, *sort_tuple)
entities["raw"] = OrderedDict()
for name in raw_order:
entities["raw"][name] = unordered_entities_raw[name]
entities["flippable"] = is_flippable
with open(os.path.join(data_location, "entities.pkl"), "wb") as out:
pickle.dump(entities, out, pickle.HIGHEST_PROTOCOL)
if verbose:
print("Extracted entities...")
# =============================================================================
def extract_instruments(lua, data_location, verbose):
"""
Extracts the instruments to ``instruments.pkl`` in :py:mod:`draftsman.data`.
"""
data = lua.globals().data
instrument_raw = OrderedDict()
instrument_index = {}
instrument_names = {}
speakers = convert_table_to_dict(data.raw["programmable-speaker"])
for speaker in speakers:
instrument_list = speakers[speaker]["instruments"]
instrument_raw[speaker] = instrument_list
instrument_index[speaker] = {}
instrument_names[speaker] = {}
for i, instrument in enumerate(instrument_list):
index_dict = {}
index_dict["self"] = i
name_dict = {}
name_dict["self"] = instrument["name"]
for j, note in enumerate(instrument["notes"]):
index_dict[note["name"]] = j
name_dict[j] = note["name"]
instrument_index[speaker][instrument["name"]] = index_dict
instrument_names[speaker][i] = name_dict
with open(os.path.join(data_location, "instruments.pkl"), "wb") as out:
instrument_data = [instrument_raw, instrument_index, instrument_names]
pickle.dump(instrument_data, out, pickle.HIGHEST_PROTOCOL)
if verbose:
print("Extracted instruments...")
# =============================================================================
def extract_items(lua, data_location, verbose, sort_tuple):
"""
Extracts the items to ``items.pkl`` in :py:mod:`draftsman.data`.
"""
sorted_items, sorted_subgroups, sorted_groups = sort_tuple
with open(os.path.join(data_location, "items.pkl"), "wb") as out:
items = [sorted_items, sorted_subgroups, sorted_groups]
pickle.dump(items, out, pickle.HIGHEST_PROTOCOL)
if verbose:
print("Extracted items...")
# =============================================================================
def extract_modules(lua, data_location, verbose, sort_tuple):
"""
Extracts the modules to ``modules.pkl`` in :py:mod:`draftsman.data`.
"""
data = lua.globals().data
# Init categories
categories = convert_table_to_dict(data.raw["module-category"])
out_categories = OrderedDict()