forked from L0laapk3/FactorioMaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auto.py
841 lines (681 loc) · 30.5 KB
/
auto.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
import sys
if sys.maxsize <= 2**32 or sys.hexversion < 0x3060000:
raise Exception("64 bit Python 3.6 or higher is required for this script.")
import os
import traceback
import pkg_resources
from pkg_resources import DistributionNotFound, VersionConflict
from pathlib import Path
try:
with Path(__file__, "..", "packages.txt").resolve().open("r", encoding="utf-8") as f:
pkg_resources.require(f.read().splitlines())
except (DistributionNotFound, VersionConflict) as ex:
traceback.print_exc()
print("\nDependencies not met. Run `pip install -r packages.txt` to install missing dependencies.")
sys.exit(1)
import glob
import argparse
import configparser
import datetime
import json
import math
import multiprocessing as mp
import random
import re
import string
import signal
import subprocess
import tempfile
from tempfile import TemporaryDirectory
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from argparse import Namespace
from shutil import copy, copytree
from shutil import get_terminal_size as tsize
from shutil import rmtree
from socket import timeout
from subprocess import call
from zipfile import ZipFile
import psutil
from PIL import Image, ImageChops
from orderedset import OrderedSet
from crop import crop
from ref import ref
from updateLib import update as updateLib
from zoom import zoom, zoomRenderboxes
userFolder = Path(__file__, "..", "..", "..").resolve()
def printErase(arg):
try:
tsiz = tsize()[0]
print("\r{}{}\n".format(arg, " " * (tsiz*math.ceil(len(arg)/tsiz)-len(arg) - 1)), end="", flush=True)
except:
#raise
pass
def startGameAndReadGameLogs(results, condition, popenArgs, usedSteamLaunchHack, tmpDir, pidBlacklist, rawTags, args):
pipeOut, pipeIn = os.pipe()
p = subprocess.Popen(popenArgs, stdout=pipeIn)
printingStackTraceback = False
# TODO: keep printing multiline stuff until new print detected
prevPrinted = False
def handleGameLine(line):
nonlocal prevPrinted
line = line.rstrip('\n')
if re.match(r'^\ *\d+(?:\.\d+)? *[^\n]*$', line) is None:
if prevPrinted:
printErase(line)
return
prevPrinted = False
m = re.match(r'^\ *\d+(?:\.\d+)? *Script *@__L0laapk3_FactorioMaps__\/data-final-fixes\.lua:\d+: FactorioMaps_Output_RawTagPaths:([^:]+):(.*)$', line, re.IGNORECASE)
if m is not None:
rawTags[m.group(1)] = m.group(2)
if rawTags["__used"]:
raise Exception("Tags added after they were used.")
else:
if printingStackTraceback or line == "stack traceback:":
printErase("[GAME] %s" % line)
prevPrinted = True
return True
m = re.match(r'^\ *\d+(?:\.\d+)? *Script *@__L0laapk3_FactorioMaps__\/(.*?)(?:(\[info\]) ?(.*))?$', line, re.IGNORECASE)
if m is not None and m.group(2) is not None:
printErase(m.group(3))
prevPrinted = True
elif m is not None and args.verbose:
printErase(m.group(1))
prevPrinted = True
elif line.lower() in ("error", "warn", "exception", "fail", "invalid") or (args.verbosegame and len(line) > 0):
printErase("[GAME] %s" % line)
prevPrinted = True
return False
with os.fdopen(pipeOut, 'r') as pipef:
line = pipef.readline().rstrip("\n")
printingStackTraceback = handleGameLine(line)
isSteam = False
if line.endswith("Initializing Steam API.") or usedSteamLaunchHack:
isSteam = True
elif not re.match(r'^ *\d+\.\d{3} \d{4}-\d\d-\d\d \d\d:\d\d:\d\d; Factorio (\d+\.\d+\.\d+) \(build (\d+), [^)]+\)$', line):
raise Exception("Unrecognised output from factorio (maybe your version is outdated?)\n\nOutput from factorio:\n" + line)
if isSteam:
if usedSteamLaunchHack:
printErase("using steam launch hack.")
else:
printErase("WARNING: Could not find steam exe. Falling back to old steam method.\n\t If you have any default arguments set in steam for factorio, delete them and restart the script.\n\t Please alt tab to steam and confirm the steam 'start game with arguments' popup.\n\t To avoid this in the future, use the --steam-exe argument.")
attrs = ('pid', 'name', 'create_time')
# on some devices, the previous check wasn't enough apparently, so explicitely wait until the log file is created.
while not os.path.exists(os.path.join(tmpDir, "factorio-current.log")):
time.sleep(0.4)
oldest = None
pid = None
while pid is None:
for proc in psutil.process_iter(attrs=attrs):
pinfo = proc.as_dict(attrs=attrs)
if pinfo["name"] == "factorio.exe" and pinfo["pid"] not in pidBlacklist and (pid is None or pinfo["create_time"] < oldest):
oldest = pinfo["create_time"]
pid = pinfo["pid"]
if pid is None:
time.sleep(1)
# print(f"PID: {pid}")
else:
pid = p.pid
results.extend((isSteam, pid))
with condition:
condition.notify()
psutil.Process(pid).nice(psutil.BELOW_NORMAL_PRIORITY_CLASS if os.name == 'nt' else 10)
if isSteam:
pipef.close()
with Path(tmpDir, "factorio-current.log").open("r", encoding="utf-8") as f:
while psutil.pid_exists(pid):
where = f.tell()
line = f.readline()
if not line:
time.sleep(0.4)
f.seek(where)
else:
printingStackTraceback = handleGameLine(line)
else:
while True:
line = pipef.readline()
printingStackTraceback = handleGameLine(line)
def checkUpdate(reverseUpdateTest:bool = False):
try:
print("checking for updates")
latestUpdates = json.loads(urllib.request.urlopen('https://cdn.jsdelivr.net/gh/L0laapk3/FactorioMaps@latest/updates.json', timeout=30).read())
with Path(__file__, "..", "updates.json").resolve().open("r", encoding="utf-8") as f:
currentUpdates = json.load(f)
if reverseUpdateTest:
latestUpdates, currentUpdates = currentUpdates, latestUpdates
updates = []
majorUpdate = False
currentVersion = (0, 0, 0)
for verStr, changes in currentUpdates.items():
ver = tuple(map(int, verStr.split(".")))
if currentVersion[0] < ver[0] or (currentVersion[0] == ver[0] and currentVersion[1] < ver[1]):
currentVersion = ver
for verStr, changes in latestUpdates.items():
if verStr not in currentUpdates:
ver = tuple(map(int, verStr.split(".")))
updates.append((verStr, changes))
updates.sort(key = lambda u: u[0])
if len(updates) > 0:
padding = max(map(lambda u: len(u[0]), updates))
changelogLines = []
for update in updates:
if isinstance(update[1], str):
updateText = update[1]
else:
updateText = str(("\r\n " + " "*padding).join(update[1]))
if updateText[0] == "!":
majorUpdate = True
updateText = updateText[1:]
changelogLines.append(" %s: %s" % (update[0].rjust(padding), updateText))
print("")
print("")
print("================================================================================")
print("")
print((" An " + ("important" if majorUpdate else "incremental") + " update has been found!"))
print("")
print(" Here's what changed:")
for line in changelogLines:
print(line)
print("")
print("")
print(" Download: https://git.io/factoriomaps")
if majorUpdate:
print("")
print(" You can dismiss this by using --no-update (not recommended)")
print("")
print("================================================================================")
print("")
print("")
if majorUpdate or reverseUpdateTest:
exit(1)
except (urllib.error.URLError, timeout) as e:
print("Failed to check for updates. %s: %s" % (type(e).__name__, e))
def linkDir(src: Path, dest:Path):
if os.name == 'nt':
subprocess.check_call(("MKLINK", "/J", src.resolve(), dest.resolve()), stdout=subprocess.DEVNULL, shell=True)
else:
os.symlink(dest.resolve(), src.resolve())
def linkCustomModFolder(modpath: Path):
print(f"Verifying mod version in custom mod folder ({modpath})")
modPattern = re.compile(r'^L0laapk3_FactorioMaps_', flags=re.IGNORECASE)
for entry in [entry for entry in modpath.iterdir() if modPattern.match(entry.name)]:
print("Found other factoriomaps mod in custom mod folder, deleting.")
path = Path(modpath, entry)
if path.is_file() or path.is_symlink():
path.unlink()
elif path.is_dir():
rmtree(path)
else:
raise Exception(f"Unable to remove {path} unknown type")
linkDir(Path(modpath, Path('.').resolve().name), Path("."))
def changeModlist(modpath: Path,newState: bool):
print(f"{'Enabling' if newState else 'Disabling'} FactorioMaps mod")
done = False
modlistPath = Path(modpath, "mod-list.json")
with modlistPath.open("r", encoding="utf-8") as f:
modlist = json.load(f)
for mod in modlist["mods"]:
if mod["name"] == "L0laapk3_FactorioMaps":
mod["enabled"] = newState
done = True
break
if not done:
modlist["mods"].append({"name": "L0laapk3_FactorioMaps", "enabled": newState})
with modlistPath.open("w", encoding="utf-8") as f:
json.dump(modlist, f, indent=2)
def buildAutorun(args: Namespace, workFolder: Path, outFolder: Path, isFirstSnapshot: bool, daytime: str):
printErase("Building autorun.lua")
mapInfoPath = Path(workFolder, "mapInfo.json")
if mapInfoPath.is_file():
with mapInfoPath.open("r", encoding='utf-8') as f:
mapInfoLua = re.sub(r'"([^"]+)" *:', lambda m: '["'+m.group(1)+'"] = ', f.read().replace("[", "{").replace("]", "}"))
# TODO: Update for new argument parsing
# if isFirstSnapshot:
# f.seek(0)
# mapInfo = json.load(f)
# if "options" in mapInfo:
# for kwarg in changedKwargs:
# if kwarg in ("hd", "dayonly", "nightonly", "build-range", "connect-range", "tag-range"):
# printErase("Warning: flag '" + kwarg + "' is overriden by previous setting found in existing timeline.")
else:
mapInfoLua = "{}"
isFirstSnapshot = False
chunkCachePath = Path(workFolder, "chunkCache.json")
if chunkCachePath.is_file():
with chunkCachePath.open("r", encoding="utf-8") as f:
chunkCache = re.sub(r'"([^"]+)" *:', lambda m: '["'+m.group(1)+'"] = ', f.read().replace("[", "{").replace("]", "}"))
else:
chunkCache = "{}"
def lowerBool(value: bool):
return str(value).lower()
with Path(__file__, "..", "autorun.lua").resolve().open("w", encoding="utf-8") as f:
surfaceString = '{"' + '", "'.join(args.surface) + '"}' if args.surface else "nil"
autorunString = \
f'''fm.autorun = {{
HD = {lowerBool(args.hd)},
daytime = "{daytime}",
alt_mode = {lowerBool(args.altmode)},
tags = {lowerBool(args.tags)},
around_tag_range = {args.tag_range},
around_build_range = {args.build_range},
around_connect_range = {args.connect_range},
connect_types = {{"lamp", "electric-pole", "radar", "straight-rail", "curved-rail", "rail-signal", "rail-chain-signal", "locomotive", "cargo-wagon", "fluid-wagon", "car"}},
date = "{datetime.datetime.strptime(args.date, "%d/%m/%y").strftime("%d/%m/%y")}",
surfaces = {surfaceString},
name = "{str(outFolder) + "/"}",
mapInfo = {mapInfoLua.encode("utf-8").decode("unicode-escape")},
chunkCache = {chunkCache}
}}'''
f.write(autorunString)
if args.verbose:
printErase(autorunString)
def buildConfig(args: Namespace, tmpDir, basepath):
printErase("Building config.ini")
if args.verbose > 2:
print(f"Using temporary directory '{tmpDir}'")
configPath = Path(tmpDir, "config","config.ini")
configPath.parent.mkdir(parents=True)
config = configparser.ConfigParser()
config.read(Path(args.config_path, "config.ini"))
if "interface" not in config:
config["interface"] = {}
config["interface"]["show-tips-and-tricks"] = "false"
if "path" not in config:
config["path"] = {}
config["path"]["write-data"] = tmpDir
config["path"]["script-output"] = str(basepath)
if "graphics" not in config:
config["graphics"] = {}
config["graphics"]["screenshots-threads-count"] = str(args.screenshotthreads if args.screenshotthreads else args.maxthreads)
config["graphics"]["max-threads"] = config["graphics"]["screenshots-threads-count"]
with configPath.open("w+", encoding="utf-8") as configFile:
configFile.writelines(("; version=3\n", ))
config.write(configFile, space_around_delimiters=False)
copy(Path(userFolder, 'player-data.json'), tmpDir)
return configPath
def auto(*args):
lock = threading.Lock()
def kill(pid, onlyStall=False):
if pid:
with lock:
if not onlyStall and psutil.pid_exists(pid):
if os.name == 'nt':
subprocess.check_call(("taskkill", "/pid", str(pid)), stdout=subprocess.DEVNULL, shell=True)
else:
subprocess.check_call(("killall", "factorio"), stdout=subprocess.DEVNULL) # TODO: kill correct process instead of just killing all
while psutil.pid_exists(pid):
time.sleep(0.1)
printErase("killed factorio")
#time.sleep(0.1)
parser = argparse.ArgumentParser(description="FactorioMaps")
daytime = parser.add_mutually_exclusive_group()
daytime.add_argument("--dayonly", dest="night", action="store_false", help="Only take daytime screenshots.")
daytime.add_argument("--nightonly", dest="day", action="store_false", help="Only take nighttime screenshots.")
parser.add_argument("--hd", action="store_true", help="Take screenshots of resolution 64 x 64 pixels per in-game tile.")
parser.add_argument("--no-altmode", dest="altmode", action="store_false", help="Hides entity info (alt mode).")
parser.add_argument("--no-tags", dest="tags", action="store_false", help="Hides map tags")
parser.add_argument("--default-timestamp", type=int, default=None, dest="default_timestamp", help="Snapshot that will be loaded by the webpage by default. Negative values indicate newest snapshots, so -1 indicates the newest map while 0 indicates the oldest map.")
parser.add_argument("--build-range", type=float, default=5.2, help="The maximum range from buildings around which pictures are saved (in chunks, 32 by 32 in-game tiles).")
parser.add_argument("--connect-range", type=float, default=1.2, help="The maximum range from connection buildings (rails, electric poles) around which pictures are saved.")
parser.add_argument("--tag-range", type=float, default=5.2, help="The maximum range from mapview tags around which pictures are saved.")
parser.add_argument("--surface", action="append", default=[], help="Used to capture other surfaces. If left empty, the surface the player is standing on will be used. To capture multiple surfaces, use the argument multiple times: --surface nauvis --surface 'Factory floor 1'")
parser.add_argument("--factorio", type=lambda p: Path(p).resolve(), help="Use factorio.exe from PATH instead of attempting to find it in common locations.")
parser.add_argument("--output-path", dest="basepath", type=lambda p: Path(p).resolve(), default=Path(userFolder, "script-output", "FactorioMaps"), help="path to the output folder (default is '..\\..\\script-output\\FactorioMaps')")
parser.add_argument("--mod-path", "--modpath", type=lambda p: Path(p).resolve(), default=Path(userFolder, 'mods'), help="Use PATH as the mod folder. (default is '..\\..\\mods')")
parser.add_argument("--config-path", type=lambda p: Path(p).resolve(), default=Path(userFolder, 'config'), help="Use PATH as the mod folder. (default is '..\\..\\config')")
parser.add_argument("--date", default=datetime.date.today().strftime("%d/%m/%y"), help="Date attached to the snapshot, default is today. [dd/mm/yy]")
parser.add_argument('--verbose', '-v', action='count', default=0, help="Displays factoriomaps script logs.")
parser.add_argument('--verbosegame', action='count', default=0, help="Displays all game logs.")
parser.add_argument("--no-update", "--noupdate", dest="update", action="store_false", help="Skips the update check.")
parser.add_argument("--reverseupdatetest", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--maxthreads", type=int, default=mp.cpu_count(), help="Sets the number of threads used for all steps. By default this is equal to the amount of logical processor cores available.")
parser.add_argument("--cropthreads", type=int, default=None, help="Sets the number of threads used for the crop step.")
parser.add_argument("--refthreads", type=int, default=None, help="Sets the number of threads used for the crossreferencing step.")
parser.add_argument("--zoomthreads", type=int, default=None, help="Sets the number of threads used for the zoom step.")
parser.add_argument("--screenshotthreads", type=int, default=None, help="Set the number of screenshotting threads factorio uses.")
parser.add_argument("--delete", action="store_true", help="Deletes the output folder specified before running the script.")
parser.add_argument("--dry", action="store_true", help="Skips starting factorio, making screenshots and doing the main steps, only execute setting up and finishing of script.")
parser.add_argument("targetname", nargs="?", help="output folder name for the generated snapshots.")
parser.add_argument("savename", nargs="*", help="Names of the savegames to generate snapshots from. If no savegames are provided the latest save or the save matching outfolder will be gerated. Glob patterns are supported.")
parser.add_argument("--force-lib-update", action="store_true", help="Forces an update of the web dependencies.")
args = parser.parse_args()
if args.verbose > 0:
print(args)
if args.update:
checkUpdate(args.reverseupdatetest)
saves = Path(userFolder, "saves")
if args.targetname:
foldername = args.targetname
else:
timestamp, filePath = max(
(save.stat().st_mtime, save)
for save in saves.iterdir()
if save.stem not in {"_autosave1", "_autosave2", "_autosave3"}
)
foldername = filePath.stem
print("No save name passed. Using most recent save: %s" % foldername)
saveNames = args.savename or [foldername]
foldername = foldername.replace('*', '').replace('?', '')
saveGames = OrderedSet()
for saveName in saveNames:
saveNameEscaped = glob.escape(saveName).replace("[*]", "*")
globResults = list(saves.glob(saveNameEscaped))
globResults += list(saves.glob(f"{saveNameEscaped}.zip"))
if not globResults:
print(f'Cannot find savefile: "{saveName}"')
raise ValueError(f'Cannot find savefile: "{saveName}"')
results = [save for save in globResults if save.is_file()]
for result in results:
saveGames.add(result.stem)
if args.verbose > 0:
print(f"Will generate snapshots for : {list(saveGames)}")
windowsPaths = [
"Program Files/Factorio/bin/x64/factorio.exe",
"Games/Factorio/bin/x64/factorio.exe",
"Program Files (x86)/Steam/steamapps/common/Factorio/bin/x64/factorio.exe",
"Steam/steamapps/common/Factorio/bin/x64/factorio.exe",
]
availableDrives = [
"%s:/" % d for d in string.ascii_uppercase if Path(f"{d}:/").exists()
]
possiblePaths = [
drive + path for drive in availableDrives for path in windowsPaths
] + ["../../bin/x64/factorio.exe", "../../bin/x64/factorio",]
try:
factorioPath = next(
x
for x in map(Path, [args.factorio] if args.factorio else possiblePaths)
if x.is_file()
)
except StopIteration:
raise Exception(
"Can't find factorio.exe. Please pass --factorio=PATH as an argument."
)
print("factorio path: {}".format(factorioPath))
psutil.Process(os.getpid()).nice(psutil.ABOVE_NORMAL_PRIORITY_CLASS if os.name == 'nt' else 5)
workthread = None
workfolder = Path(args.basepath, foldername).resolve()
try:
print("output folder: {}".format(workfolder.relative_to(Path(userFolder))))
except ValueError:
print("output folder: {}".format(workfolder.resolve()))
try:
workfolder.mkdir(parents=True, exist_ok=True)
except FileExistsError:
raise Exception(f"{workfolder} exists and is not a directory!")
updateLib(args.force_lib_update)
#TODO: integrity check, if done files aren't there or there are any bmps left, complain.
if args.mod_path.resolve() != Path(userFolder,"mods").resolve():
linkCustomModFolder(args.mod_path)
changeModlist(args.mod_path, True)
manager = mp.Manager()
rawTags = manager.dict()
rawTags["__used"] = False
if args.delete:
print(f"Deleting output folder ({workfolder})")
try:
rmtree(workfolder)
except (FileNotFoundError, NotADirectoryError):
pass
###########################################
# #
# Start of Work #
# #
###########################################
datapath = Path(workfolder, "latest.txt")
isFirstSnapshot = True
try:
daytimes = []
if args.day:
daytimes.append("day")
if args.night:
daytimes.append("night")
for index, savename in () if args.dry else enumerate(saveGames):
for daytimeIndex, setDaytime in enumerate(daytimes):
printErase("cleaning up")
if datapath.is_file():
datapath.unlink()
buildAutorun(args, workfolder, foldername, isFirstSnapshot, setDaytime)
isFirstSnapshot = False
with TemporaryDirectory(prefix="FactorioMaps-") as tmpDir:
configPath = buildConfig(args, tmpDir, args.basepath)
pid = None
isSteam = None
pidBlacklist = [p.info["pid"] for p in psutil.process_iter(attrs=['pid', 'name']) if p.info['name'] == "factorio.exe"]
launchArgs = [
'--load-game',
str(Path(userFolder, 'saves', savename).absolute()),
'--disable-audio',
'--config',
str(configPath),
"--mod-directory",str(args.mod_path.absolute()),
"--disable-migration-window"
]
usedSteamLaunchHack = False
if os.name == "nt":
steamApiPath = Path(factorioPath, "..", "steam_api64.dll")
else:
steamApiPath = Path(factorioPath, "..", "steam_api64.so")
if steamApiPath.exists(): # chances are this is a steam install..
if os.name == "nt":
steamPath = Path(factorioPath, "..", "..", "..", "..", "..", "..", "steam.exe")
else:
steamPath = Path(factorioPath, "..", "..", "..", "..", "..", "..", "steam")
if steamPath.exists(): # found a steam executable
usedSteamLaunchHack = True
exeWithArgs = [
str(steamPath),
"-applaunch",
"427520"
] + launchArgs
if not usedSteamLaunchHack: # if non steam factorio, or if steam factorio but steam executable isnt found.
exeWithArgs = [
str(factorioPath)
] + launchArgs
if args.verbose:
printErase(exeWithArgs)
condition = mp.Condition()
results = manager.list()
printErase("starting factorio")
startLogProcess = mp.Process(
target=startGameAndReadGameLogs,
args=(results, condition, exeWithArgs, usedSteamLaunchHack, tmpDir, pidBlacklist, rawTags, args)
)
startLogProcess.daemon = True
startLogProcess.start()
with condition:
condition.wait()
isSteam, pid = results[:]
if isSteam is None:
raise Exception("isSteam error")
if pid is None:
raise Exception("pid error")
while not datapath.exists():
time.sleep(0.4)
# empty autorun.lua
Path(__file__, "..", "autorun.lua").resolve().open('w', encoding="utf-8").close()
latest = []
with datapath.open('r', encoding="utf-8") as f:
for line in f:
latest.append(line.rstrip("\n"))
if args.verbose:
printErase(latest)
firstOutFolder, timestamp, surface, daytime = latest[-1].split(" ")
firstOutFolder = firstOutFolder.replace("/", " ")
waitfilename = Path(args.basepath, firstOutFolder, "images", timestamp, surface, daytime, "done.txt")
isKilled = [False]
def waitKill(isKilled, pid):
while not isKilled[0]:
#print(f"Can I kill yet? {os.path.isfile(waitfilename)} {waitfilename}")
if os.path.isfile(waitfilename):
isKilled[0] = True
kill(pid)
break
else:
time.sleep(0.4)
killThread = threading.Thread(target=waitKill, args=(isKilled, pid))
killThread.daemon = True
killThread.start()
if workthread and workthread.is_alive():
#print("waiting for workthread")
workthread.join()
timestamp = None
daytimeSurfaces = {}
for jindex, screenshot in enumerate(latest):
outFolder, timestamp, surface, daytime = list(map(lambda s: s.replace("|", " "), screenshot.split(" ")))
outFolder = outFolder.replace("/", " ")
print(f"Processing {outFolder}/{'/'.join([timestamp, surface, daytime])} ({len(latest) * index + jindex + 1 + daytimeIndex} of {len(latest) * len(saveGames) * len(daytimes)})")
if daytime in daytimeSurfaces:
daytimeSurfaces[daytime].append(surface)
else:
daytimeSurfaces[daytime] = [surface]
#print("Cropping %s images" % screenshot)
crop(outFolder, timestamp, surface, daytime, args.basepath, args)
waitlocalfilename = os.path.join(args.basepath, outFolder, "Images", timestamp, surface, daytime, "done.txt")
if not os.path.exists(waitlocalfilename):
#print("waiting for done.txt")
while not os.path.exists(waitlocalfilename):
time.sleep(0.4)
def refZoom():
needsThumbnail = index + 1 == len(saveGames)
#print("Crossreferencing %s images" % screenshot)
ref(outFolder, timestamp, surface, daytime, args.basepath, args)
#print("downsampling %s images" % screenshot)
zoom(outFolder, timestamp, surface, daytime, args.basepath, needsThumbnail, args)
if jindex == len(latest) - 1:
print("zooming renderboxes", timestamp)
zoomRenderboxes(daytimeSurfaces, workfolder, timestamp, Path(args.basepath, firstOutFolder, "Images"), args)
if screenshot != latest[-1]:
refZoom()
else:
startLogProcess.terminate()
# I have receieved a bug report from feidan in which he describes what seems like that this doesnt kill factorio?
onlyStall = isKilled[0]
isKilled[0] = True
kill(pid, onlyStall)
if savename == saveGames[-1] and daytimeIndex == len(daytimes) - 1:
refZoom()
else:
workthread = threading.Thread(target=refZoom)
workthread.daemon = True
workthread.start()
if os.path.isfile(os.path.join(workfolder, "mapInfo.out.json")):
print("generating mapInfo.json")
with Path(workfolder, "mapInfo.json").open('r+', encoding='utf-8') as destf, Path(workfolder, "mapInfo.out.json").open("r", encoding='utf-8') as srcf:
data = json.load(destf)
for mapIndex, mapStuff in json.load(srcf)["maps"].items():
for surfaceName, surfaceStuff in mapStuff["surfaces"].items():
if "chunks" in surfaceStuff:
data["maps"][int(mapIndex)]["surfaces"][surfaceName]["chunks"] = surfaceStuff["chunks"]
if "links" in surfaceStuff:
for linkIndex, link in enumerate(surfaceStuff["links"]):
data["maps"][int(mapIndex)]["surfaces"][surfaceName]["links"][linkIndex]["path"] = link["path"]
data["maps"][int(mapIndex)]["surfaces"][surfaceName]["links"][linkIndex]["zoom"]["min"] = link["zoom"]["min"]
destf.seek(0)
json.dump(data, destf)
destf.truncate()
os.remove(os.path.join(workfolder, "mapInfo.out.json"))
print("updating labels")
tags = {}
with Path(workfolder, "mapInfo.json").open('r+', encoding='utf-8') as mapInfoJson:
data = json.load(mapInfoJson)
for mapStuff in data["maps"]:
for surfaceName, surfaceStuff in mapStuff["surfaces"].items():
if "tags" in surfaceStuff:
for tag in surfaceStuff["tags"]:
if "iconType" in tag:
tags[tag["iconType"] + tag["iconName"][0].upper() + tag["iconName"][1:]] = tag
rmtree(os.path.join(workfolder, "Images", "labels"), ignore_errors=True)
modVersions = sorted(
map(lambda m: (m.group(2).lower(), (m.group(3), m.group(4), m.group(5), m.group(6) is None), m.group(1)),
filter(lambda m: m,
map(lambda f: re.search(r"^((.*)_(\d+)\.(\d+)\.(\d+))(\.zip)?$", f, flags=re.IGNORECASE),
os.listdir(os.path.join(args.basepath, args.mod_path))))),
key = lambda t: t[1],
reverse = True)
rawTags["__used"] = True
if args.tags:
for _, tag in tags.items():
dest = os.path.join(workfolder, tag["iconPath"])
os.makedirs(os.path.dirname(dest), exist_ok=True)
rawPath = rawTags[tag["iconType"] + tag["iconName"][0].upper() + tag["iconName"][1:]]
icons = rawPath.split('|')
img = None
for i, path in enumerate(icons):
m = re.match(r"^__([^\/]+)__[\/\\](.*)$", path)
if m is None:
raise Exception("raw path of %s %s: %s not found" % (tag["iconType"], tag["iconName"], path))
iconColor = m.group(2).split("?")
icon = iconColor[0]
if m.group(1) in ("base", "core"):
src = os.path.join(os.path.split(factorioPath)[0], "../../data", m.group(1), icon + ".png")
else:
mod = next(mod for mod in modVersions if mod[0] == m.group(1).lower())
if not mod[1][3]: #true if mod is zip
zipPath = os.path.join(args.basepath, args.mod_path, mod[2] + ".zip")
with ZipFile(zipPath, 'r') as zipObj:
if len(icons) == 1:
zipInfo = zipObj.getinfo(os.path.join(mod[2], icon + ".png").replace('\\', '/'))
zipInfo.filename = os.path.basename(dest)
zipObj.extract(zipInfo, os.path.dirname(os.path.realpath(dest)))
src = None
else:
src = zipObj.extract(os.path.join(mod[2], icon + ".png").replace('\\', '/'), os.path.join(tempfile.gettempdir(), "FactorioMaps"))
else:
src = os.path.join(args.basepath, args.mod_path, mod[2], icon + ".png")
if len(icons) == 1:
if src is not None:
img = Image.open(src)
w, h = img.size
img = img.crop((0, 0, h, h)).resize((64, 64))
img.save(dest)
else:
newImg = Image.open(src)
w, h = newImg.size
newImg = newImg.crop((0, 0, h, h)).resize((64, 64)).convert("RGBA")
if len(iconColor) > 1:
newImg = ImageChops.multiply(newImg, Image.new("RGBA", newImg.size, color=tuple(map(lambda s: int(round(float(s))), iconColor[1].split("%")))))
if i == 0:
img = newImg
else:
img.paste(newImg.convert("RGB"), (0, 0), newImg)
if len(icons) > 1:
img.save(dest)
print("applying configuration")
with Path(workfolder, "mapInfo.json").open("r+", encoding='utf-8') as f:
mapInfo = json.load(f)
if args.default_timestamp != None or "defaultTimestamp" not in mapInfo["options"]:
if args.default_timestamp == None:
args.default_timestamp = -1
mapInfo["options"]["defaultTimestamp"] = args.default_timestamp
f.seek(0)
json.dump(mapInfo, f)
f.truncate()
print("generating mapInfo.js")
with Path(workfolder, "mapInfo.js").open('w', encoding="utf-8") as outf, Path(workfolder, "mapInfo.json").open("r", encoding='utf-8') as inf:
outf.write('"use strict";\nwindow.mapInfo = JSON.parse(')
outf.write(json.dumps(inf.read()))
outf.write(");")
print("creating index.html")
for fileName in ("index.html", "index.css", "index.js"):
copy(Path(__file__, "..", "web", fileName).resolve(), os.path.join(workfolder, fileName))
try:
rmtree(os.path.join(workfolder, "lib"))
except (FileNotFoundError, NotADirectoryError):
pass
copytree(Path(__file__, "..", "web", "lib").resolve(), os.path.join(workfolder, "lib"))
except KeyboardInterrupt:
print("keyboardinterrupt")
kill(pid)
raise
finally:
try:
kill(pid)
except:
pass
changeModlist(args.mod_path, False)
if __name__ == '__main__':
auto(*sys.argv[1:])