Repository navigation
Expand file tree
/
Copy pathwat_core.py
More file actions
636 lines (533 loc) · 25 KB
/
Copy pathwat_core.py
File metadata and controls
636 lines (533 loc) · 25 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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
#!/usr/bin/env python3
# AutoExplorer core: collect remaining Somersloops, Mercer Spheres, hard drives,
# and loose loot in a Satisfactory 1.2 save into one or more players' inventories.
#
# Collection mirrors what the game does when you pick an item up in person:
# the world actor is removed and recorded in its world-partition cell's
# collectables (destroyed-actor) list, and the item is added to an inventory.
# Nothing is ever duplicated; the world's finite totals are preserved.
#
# Built on GreyHak's sat_sav_parse (GPL-3), vendored in vendor/sat_sav_parse.
import contextlib
import copy
import io
import math
import os
import sys
from collections import Counter
if getattr(sys, "frozen", False):
# PyInstaller bundle: the vendored modules are compiled into the bundle.
pass
else:
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
"vendor", "sat_sav_parse"))
import sav_parse
import sav_to_resave
with contextlib.redirect_stdout(io.StringIO()):
# sav_cli/sav_to_html print a Pillow notice at import time.
import sav_cli
import sav_to_html
import sav_data.data as _data
from sav_data.somersloop import SOMERSLOOPS
from sav_data.mercerSphere import MERCER_SPHERES
from sav_data.crashSites import CRASH_SITES
from sav_data.freeStuff import FREE_DROPPED_ITEMS
SOMERSLOOP_ITEM = "/Game/FactoryGame/Prototype/WAT/Desc_WAT1.Desc_WAT1_C"
MERCER_SPHERE_ITEM = "/Game/FactoryGame/Prototype/WAT/Desc_WAT2.Desc_WAT2_C"
HARD_DRIVE_ITEM = "/Game/FactoryGame/Resource/Environment/CrashSites/Desc_HardDrive.Desc_HardDrive_C"
WAT_STACK = 50 # in-game stack size for Somersloops and Mercer Spheres
HARD_DRIVE_STACK = 100 # in-game stack size for Hard Drives
STACK_SIZE = WAT_STACK # backwards-compatible default
ITEM_TYPES = {
"Somersloop": (SOMERSLOOPS, SOMERSLOOP_ITEM),
"Mercer Sphere": (MERCER_SPHERES, MERCER_SPHERE_ITEM),
}
_REMOVERS = {
"Somersloop": sav_cli.removeSomersloop,
"Mercer Sphere": sav_cli.removeMercerSphere,
}
# Hard drives come from crash sites, which fall into three repair categories.
HARD_DRIVE_CATEGORIES = ("free", "resources", "power")
HARD_DRIVE_CATEGORY_LABELS = {
"free": "no repair needed",
"resources": "needs resources",
"power": "needs power",
}
# Readable item name -> descriptor path, for the materials crash-site repairs cost.
_ITEM_PATH_BY_NAME = {sav_parse.pathNameToReadableName(path): path
for path in _data.ITEMS_FOR_PLAYER_INVENTORY}
# In-game stack sizes for the loose ("free dropped") items, embedded so the
# frozen exe needs no side-car data file. Generated from sav_stack_sizes.json.
LOOSE_LOOT_STACKS = {
'Cluster Nobelisk': 50, 'Gas Nobelisk': 50, 'Pulse Nobelisk': 50,
'Explosive Rebar': 100, 'Shatter Rebar': 100, 'Stun Rebar': 100,
'Homing Rifle Ammo': 500, 'Blade Runners': 1, 'Medicinal Inhaler': 50,
'Xeno-Zapper': 1, 'Xeno-Basher': 1, 'Aluminum Casing': 200,
'Alclad Aluminum Sheet': 200, 'Heat Sink': 100, 'Solid Biofuel': 200,
'Packaged Liquid Biofuel': 100, 'Cable': 200, 'Rifle Ammo': 500,
'Concrete': 500, 'Circuit Board': 200, 'Computer': 50, 'Supercomputer': 50,
'Cooling System': 100, 'Copper Sheet': 200, 'Crystal Oscillator': 100,
'Electromagnetic Control Rod': 100, 'Gas Filter': 50, 'Packaged Fuel': 100,
'High-Speed Connector': 100, 'Quickwire': 500, 'Iron Plate': 200,
'Reinforced Iron Plate': 100, 'Iron Rod': 200, 'Screw': 500,
'Modular Frame': 50, 'Fused Modular Frame': 50, 'Heavy Modular Frame': 50,
'Motor': 50, 'Turbo Motor': 50, 'Nobelisk': 50, 'Plastic': 200,
'Quartz Crystal': 200, 'Rotor': 100, 'Rubber': 200, 'Silica': 200,
'Iron Rebar': 100, 'Stator': 100, 'Steel Pipe': 200, 'Steel Beam': 200,
'Encased Industrial Beam': 100, 'Packaged Turbofuel': 100, 'Wire': 500,
}
DEFAULT_LOOSE_STACK = 100 # safe fallback if a future item isn't in the table
def crashSiteCategory(details):
"""Classify a crash site by what its hard drive costs to retrieve."""
if "cost" in details:
return "resources"
if "power" in details:
return "power"
return "free"
def looseLootName(itemPath):
return sav_parse.pathNameToReadableName(itemPath)
class AutoExplorerError(Exception):
pass
class PlayerInfo:
def __init__(self, playerId, name, characterPlayer, inventoryPath, position):
self.playerId = playerId
self.name = name
self.characterPlayer = characterPlayer
self.inventoryPath = inventoryPath
self.position = position # (x, y, z) in cm, or None if unknown
@property
def label(self):
return self.name if self.name else f"Player {self.playerId}"
class TypeReport:
def __init__(self, label, total, already, collectedNow, quantityNow,
leftover, unaffordable, failed, perPlayer, absent=0):
self.label = label
self.total = total # total of this kind in scope
self.already = already # how many were collected before this run
self.collectedNow = collectedNow # pickups/sites collected this run
self.quantityNow = quantityNow # total item count added (matters for loose loot)
self.leftover = leftover # skipped because every inventory filled up
self.unaffordable = unaffordable # skipped because no player could pay the cost
self.absent = absent # loose pickups in unexplored cells (unreachable)
self.failed = failed # pathNames that could not be collected
self.perPlayer = perPlayer # {player label: pickups assigned}
def defaultSaveDir():
"""Best directory to start a file dialog in: the game's save folder."""
base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "FactoryGame", "Saved", "SaveGames")
if os.path.isdir(base):
candidates = []
for entry in os.listdir(base):
sub = os.path.join(base, entry)
if os.path.isdir(sub) and any(f.lower().endswith(".sav") for f in os.listdir(sub)):
candidates.append(sub)
if candidates:
return max(candidates, key=os.path.getmtime)
return base
return os.path.expanduser("~")
def defaultOutputPath(inputPath):
root, ext = os.path.splitext(inputPath)
return f"{root}_AutoExplorer{ext or '.sav'}"
def loadSave(path, quiet=False):
if quiet:
with contextlib.redirect_stdout(io.StringIO()):
return sav_parse.readFullSaveFile(path)
return sav_parse.readFullSaveFile(path)
def getPlayers(parsedSave):
players = []
positions = {}
for level in parsedSave.levels:
for header in level.actorAndComponentObjectHeaders:
if isinstance(header, sav_parse.ActorHeader) and ".Char_Player_C_" in header.instanceName:
positions[header.instanceName] = tuple(header.position)
for paths in sav_cli.getPlayerPaths(parsedSave.levels):
characterPlayer = paths[1]
inventoryPath = paths[2]
playerId = characterPlayer[characterPlayer.rfind("_") + 1:]
name = sav_cli.getPlayerName(parsedSave.levels, characterPlayer)
players.append(PlayerInfo(playerId, name, characterPlayer, inventoryPath,
positions.get(characterPlayer)))
return players
def remainingCounts(parsedSave):
"""{type label: (remainingInWorld, total)} without modifying anything."""
collectedSet = {c.pathName for level in parsedSave.levels for c in level.collectables2}
out = {}
for label, (locations, itemPath) in ITEM_TYPES.items():
remaining = sum(1 for pathName in locations if pathName not in collectedSet)
out[label] = (remaining, len(locations))
return out
def hardDriveCounts(parsedSave):
"""{category: (remainingCollectible, total)} for the three crash-site categories."""
_inSave, notOpened, openDrive, _empty, _dismantled = sav_to_html.getCrashSiteState(parsedSave.levels)
collectible = set(notOpened) | set(openDrive)
out = {}
for cat in HARD_DRIVE_CATEGORIES:
catSites = [p for p, v in CRASH_SITES.items() if crashSiteCategory(v[3]) == cat]
remaining = sum(1 for p in catSites if p in collectible)
out[cat] = (remaining, len(catSites))
return out
def looseLootTypes(parsedSave):
"""Loose-loot item types that have uncollected pickups loaded in this save.
Returns a list of dicts sorted by quantity desc:
{name, itemPath, spots (collectible now), quantity (collectible now), absent}.
``absent`` counts pickups in not-yet-visited cells, which cannot be granted.
"""
collectedSet = {c.pathName for level in parsedSave.levels for c in level.collectables2}
presentActors = {}
for level in parsedSave.levels:
for header in level.actorAndComponentObjectHeaders:
if isinstance(header, sav_parse.ActorHeader):
presentActors[header.instanceName] = header.rootObject
out = []
for itemPath, entries in FREE_DROPPED_ITEMS.items():
spots = quantity = absent = 0
for (qty, _pos, instanceName) in entries:
if instanceName in collectedSet:
continue
if instanceName in presentActors:
spots += 1
quantity += qty
else:
absent += 1
if spots or absent:
out.append({"name": looseLootName(itemPath), "itemPath": itemPath,
"spots": spots, "quantity": quantity, "absent": absent})
out.sort(key=lambda r: -r["quantity"])
return out
def findInventoryStacks(parsedSave, inventoryPath):
for level in parsedSave.levels:
for object in level.objects:
if object.instanceName == inventoryPath:
return sav_parse.getPropertyValue(object.properties, "mInventoryStacks")
return None
def countItem(inventoryStacks, itemPath):
"""How many of itemPath the inventory currently holds."""
total = 0
for stack in inventoryStacks:
slot = stack[0]
if slot[0][0] == "Item" and slot[1][0] == "NumItems" and slot[0][1][0] == itemPath:
total += slot[1][1]
return total
def canAfford(inventoryStacks, cost):
"""cost is a list of (itemPath, quantity); True if the inventory has them all."""
return all(countItem(inventoryStacks, itemPath) >= quantity
for itemPath, quantity in cost)
def removeItems(inventoryStacks, itemPath, count):
"""Deduct count of itemPath from the inventory (caller must ensure it's affordable)."""
remaining = count
for stack in inventoryStacks:
if remaining <= 0:
break
slot = stack[0]
if slot[0][0] != "Item" or slot[1][0] != "NumItems" or slot[0][1][0] != itemPath:
continue
take = min(slot[1][1], remaining)
newCount = slot[1][1] - take
remaining -= take
if newCount == 0:
slot[0] = ["Item", ["", 0]]
slot[1] = ["NumItems", 0]
else:
slot[1] = ["NumItems", newCount]
return remaining == 0
def capacityFor(inventoryStacks, itemPath, stackSize=STACK_SIZE):
"""How many of itemPath fit: room in existing partial stacks plus empty slots."""
capacity = 0
for stack in inventoryStacks:
slot = stack[0]
if slot[0][0] != "Item" or slot[1][0] != "NumItems":
continue
if slot[0][1][0] == itemPath and 0 < slot[1][1] < stackSize:
capacity += stackSize - slot[1][1]
elif slot[0][1][0] == "":
capacity += stackSize
return capacity
def addItems(inventoryStacks, itemPath, count, stackSize=STACK_SIZE):
"""Top up existing stacks of itemPath, then fill empty slots. Returns (slotsUsed, leftover)."""
remaining = count
slotsUsed = 0
for stack in inventoryStacks:
if remaining <= 0:
break
slot = stack[0]
if slot[0][0] != "Item" or slot[1][0] != "NumItems":
continue
if slot[0][1][0] == itemPath and 0 < slot[1][1] < stackSize:
add = min(stackSize - slot[1][1], remaining)
slot[1] = ["NumItems", slot[1][1] + add]
remaining -= add
slotsUsed += 1
for stack in inventoryStacks:
if remaining <= 0:
break
slot = stack[0]
if slot[0][0] != "Item" or slot[1][0] != "NumItems":
continue
if slot[0][1][0] == "":
add = min(stackSize, remaining)
slot[0] = ["Item", [itemPath, 1]]
slot[1] = ["NumItems", add]
remaining -= add
slotsUsed += 1
return slotsUsed, remaining
def ensureLevelsExist(parsedSave, neededLevelNames):
"""Create empty sublevel entries for world-partition cells not yet in the save.
The save only contains an entry for a cell once it has been streamed in.
The game itself writes empty entries (no actors, no objects, empty
collectables) for such cells, so a synthetic empty entry is identical to
what the game would produce. Returns the number of entries created.
"""
existing = {level.levelName for level in parsedSave.levels}
missing = sorted(n for n in set(neededLevelNames) if n not in existing)
if not missing:
return 0
tocCells = set()
for (partitionName, i, gridHex, partitionLevels) in parsedSave.partitions:
for (levelName, lhex) in partitionLevels:
tocCells.add(levelName)
unknown = [n for n in missing if n not in tocCells]
if unknown:
raise AutoExplorerError(
f"{len(unknown)} location cell(s) are not in this save's world partition "
f"table (different game version or map?), e.g. {unknown[:3]}.")
# Clone the level metadata the game wrote for existing cells of this save.
lsvCounts = Counter(level.levelSaveVersion for level in parsedSave.levels
if level.levelName is not None)
levelSaveVersion = lsvCounts.most_common(1)[0][0]
sovdCounts = Counter()
sovdByRepr = {}
for level in parsedSave.levels:
if level.levelName is None or level.saveObjectVersionData is None:
continue
key = repr(level.saveObjectVersionData)
sovdCounts[key] += 1
sovdByRepr[key] = level.saveObjectVersionData
sovd = sovdByRepr[sovdCounts.most_common(1)[0][0]] if sovdCounts else None
insertAt = len(parsedSave.levels) - 1 # the persistent level must stay last
for levelName in missing:
newLevel = sav_parse.Level(levelName, [], None, [], [], levelSaveVersion,
[], copy.deepcopy(sovd))
parsedSave.levels.insert(insertAt, newLevel)
insertAt += 1
return len(missing)
def _distance(a, b):
return math.dist(a, b)
class _Pickup:
"""One world thing to collect, and what taking it gives / costs."""
__slots__ = ("pathName", "position", "itemPath", "quantity", "stackSize", "cost", "remover")
def __init__(self, pathName, position, itemPath, quantity, stackSize, cost, remover):
self.pathName = pathName
self.position = position # (x, y, z) or None
self.itemPath = itemPath # descriptor path granted on collection
self.quantity = quantity # how many items granted
self.stackSize = stackSize # stack size of the granted item
self.cost = cost # list of (itemPath, quantity) to deduct first
self.remover = remover # (levels, pathName) -> bool
class _CollectJob:
def __init__(self, label, pickups, already, total, neededCells):
self.label = label
self.pickups = pickups # list of _Pickup
self.already = already
self.total = total
self.neededCells = neededCells # cell levelNames to synthesize before collecting
def _watJob(label, locations, itemPath, remover, collectedSet):
remaining = [p for p in locations if p not in collectedSet]
pickups = [_Pickup(p, locations[p][2], itemPath, 1, WAT_STACK, [], remover)
for p in remaining]
needed = {locations[p][0] for p in remaining
if locations[p][0] and locations[p][0] != "Persistent_Level"}
return _CollectJob(label, pickups, len(locations) - len(remaining), len(locations), needed)
def _crashSiteRemover(levels, pathName):
root, _rotation, position, _details = CRASH_SITES[pathName]
return sav_cli.removeInstance(levels, "Hard Drive crash site", root, pathName, position)
def _hardDriveJob(parsedSave, categories, payCosts):
cats = set(categories)
unknown = cats - set(HARD_DRIVE_CATEGORIES)
if unknown:
raise AutoExplorerError(f"Unknown hard drive categories: {sorted(unknown)}")
sites = {p: v for p, v in CRASH_SITES.items() if crashSiteCategory(v[3]) in cats}
_inSave, notOpened, openDrive, openEmpty, dismantled = \
sav_to_html.getCrashSiteState(parsedSave.levels)
collectible = set(notOpened) | set(openDrive)
looted = set(openEmpty) | set(dismantled)
remaining = [p for p in sites if p in collectible]
already = sum(1 for p in sites if p in looted)
pickups = []
for pathName in remaining:
root, _rotation, position, details = sites[pathName]
cost = []
if payCosts and "cost" in details:
itemName, qty = details["cost"]
itemPath = _ITEM_PATH_BY_NAME.get(itemName)
if itemPath is not None: # all 1.2 cost items map; guard just in case
cost = [(itemPath, qty)]
pickups.append(_Pickup(pathName, position, HARD_DRIVE_ITEM, 1, HARD_DRIVE_STACK,
cost, _crashSiteRemover))
catText = ", ".join(HARD_DRIVE_CATEGORY_LABELS[c] for c in HARD_DRIVE_CATEGORIES if c in cats)
needed = {sites[p][0] for p in remaining
if sites[p][0] and sites[p][0] != "Persistent_Level"}
return _CollectJob(f"Hard Drive ({catText})", pickups, already, len(sites), needed)
def _looseLootRemover(rootObject):
def remove(levels, pathName):
return sav_cli.removeInstance(levels, "loose item", rootObject, pathName, None)
return remove
def _looseLootJob(parsedSave, selectedNames):
"""selectedNames: set of readable item names, or None for every type."""
collectedSet = {c.pathName for level in parsedSave.levels for c in level.collectables2}
presentActors = {}
for level in parsedSave.levels:
for header in level.actorAndComponentObjectHeaders:
if isinstance(header, sav_parse.ActorHeader):
presentActors[header.instanceName] = header.rootObject
pickups = []
already = absent = total = 0
for itemPath, entries in FREE_DROPPED_ITEMS.items():
name = looseLootName(itemPath)
if selectedNames is not None and name not in selectedNames:
continue
stackSize = LOOSE_LOOT_STACKS.get(name, DEFAULT_LOOSE_STACK)
for (qty, position, instanceName) in entries:
total += 1
if instanceName in collectedSet:
already += 1
continue
root = presentActors.get(instanceName)
if root is None:
absent += 1 # in a not-yet-visited cell; we have no cell to record it in
continue
pickups.append(_Pickup(instanceName, position, itemPath, qty, stackSize, [],
_looseLootRemover(root)))
job = _CollectJob("Loose loot", pickups, already, total, set())
job.absent = absent # extra: pickups we cannot reach because their cell is unloaded
return job
def _buildJobs(parsedSave, doSloops, doSpheres, hardDriveCategories,
payHardDriveCosts, looseLootSelection):
jobs = []
if doSloops or doSpheres:
collectedSet = {c.pathName for level in parsedSave.levels for c in level.collectables2}
for enabled, label in ((doSloops, "Somersloop"), (doSpheres, "Mercer Sphere")):
if not enabled:
continue
locations, itemPath = ITEM_TYPES[label]
jobs.append(_watJob(label, locations, itemPath, _REMOVERS[label], collectedSet))
if hardDriveCategories:
jobs.append(_hardDriveJob(parsedSave, hardDriveCategories, payHardDriveCosts))
if looseLootSelection is not None:
# looseLootSelection is "all" or an iterable of readable names.
names = None if looseLootSelection == "all" else set(looseLootSelection)
jobs.append(_looseLootJob(parsedSave, names))
return jobs
def collectAll(parsedSave, players, doSloops=True, doSpheres=True,
hardDriveCategories=(), payHardDriveCosts=True,
looseLootSelection=None, log=print):
"""Collect remaining pickups into the given players' inventories.
Pickups are collected nearest-first (distance to the closest selected player)
and split round-robin among the selected players. When every inventory is
full a pickup is left in the world. ``hardDriveCategories`` is a subset of
HARD_DRIVE_CATEGORIES; with ``payHardDriveCosts`` the repair materials are
deducted and unaffordable drives are skipped. ``looseLootSelection`` is
None (skip), "all", or an iterable of readable item names. Returns
a list of TypeReport.
"""
if not players:
raise AutoExplorerError("No players selected.")
jobs = _buildJobs(parsedSave, doSloops, doSpheres, hardDriveCategories,
payHardDriveCosts, looseLootSelection)
if not jobs:
raise AutoExplorerError("Nothing selected to collect.")
neededCells = set()
for job in jobs:
neededCells |= job.neededCells
created = ensureLevelsExist(parsedSave, neededCells)
if created:
log(f"Created {created} empty world-partition cell entries for unvisited areas")
stacksByPlayer = []
for player in players:
stacks = findInventoryStacks(parsedSave, player.inventoryPath)
if stacks is None:
raise AutoExplorerError(f"Could not find inventory for {player.label}.")
stacksByPlayer.append(stacks)
reports = []
for job in jobs:
def distKey(pickup):
if pickup.position is None:
return 0.0
distances = [_distance(pickup.position, pl.position) for pl in players
if pl.position is not None]
return min(distances) if distances else 0.0
order = sorted(job.pickups, key=distKey)
perPlayer = [0] * len(players)
quantityNow = 0
failed = []
leftover = 0
unaffordable = 0
nextPlayer = 0
quiet = io.StringIO()
for pickup in order:
# Pick the next player (round-robin) who can both fit the items and pay the cost.
chosen = None
fitsSomewhere = False
for k in range(len(players)):
candidate = (nextPlayer + k) % len(players)
stacks = stacksByPlayer[candidate]
fits = capacityFor(stacks, pickup.itemPath, pickup.stackSize) >= pickup.quantity
fitsSomewhere = fitsSomewhere or fits
if fits and canAfford(stacks, pickup.cost):
chosen = candidate
break
if chosen is None:
if fitsSomewhere:
unaffordable += 1 # someone had room but nobody had the materials
else:
leftover += 1 # everyone is full
continue
with contextlib.redirect_stdout(quiet):
removed = pickup.remover(parsedSave.levels, pickup.pathName)
if not removed:
failed.append(pickup.pathName)
continue
stacks = stacksByPlayer[chosen]
for itemPath, qty in pickup.cost:
removeItems(stacks, itemPath, qty)
_slotsUsed, rem = addItems(stacks, pickup.itemPath, pickup.quantity, pickup.stackSize)
if rem:
raise AutoExplorerError(
f"Internal error: {rem} x {job.label} did not fit after a capacity "
"check. No file should be written.")
perPlayer[chosen] += 1
quantityNow += pickup.quantity
nextPlayer = (chosen + 1) % len(players)
collectedNow = sum(perPlayer)
assert collectedNow + leftover + unaffordable + len(failed) == len(order)
perPlayerOut = {players[j].label: perPlayer[j] for j in range(len(players)) if perPlayer[j]}
reports.append(TypeReport(job.label, job.total, job.already, collectedNow,
quantityNow, leftover, unaffordable, failed, perPlayerOut,
absent=getattr(job, "absent", 0)))
qtyText = f" ({quantityNow} items)" if quantityNow != collectedNow else ""
log(f"{job.label}: {collectedNow} collected now{qtyText}, "
f"{job.already} already collected, {job.total} total in world")
for playerLabel, count in perPlayerOut.items():
log(f" {playerLabel}: +{count}")
if unaffordable:
log(f" WARNING: {unaffordable} x {job.label} skipped - couldn't afford the repair cost")
if leftover:
log(f" WARNING: inventories full - {leftover} x {job.label} left in the world "
"(nearest ones were collected first)")
if getattr(job, "absent", 0):
log(f" NOTE: {job.absent} loose pickups are in unexplored areas and were left "
"(visit those areas in-game to reveal them, then rerun)")
if failed:
log(f" WARNING: {len(failed)} could not be collected: {failed[:3]} ...")
return reports
def writeSave(parsedSave, outPath, bumpTime=True, validate=True, quiet=False, log=print):
if bumpTime:
parsedSave.saveFileInfo.saveDateTimeInTicks += sav_parse.TICKS_IN_SECOND
log(f"Writing {outPath} ...")
if quiet:
with contextlib.redirect_stdout(io.StringIO()):
sav_to_resave.saveFile(parsedSave, outPath)
else:
sav_to_resave.saveFile(parsedSave, outPath)
if validate:
# Round-trip the new file through the parser to be sure it is well-formed.
loadSave(outPath, quiet=quiet)
log("Validation successful.")