-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimbertrees.py
More file actions
executable file
·1741 lines (1480 loc) · 67.1 KB
/
timbertrees.py
File metadata and controls
executable file
·1741 lines (1480 loc) · 67.1 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
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
#!/usr/bin/python3
import argparse
import braceexpand
import builtins
import concurrent.futures
import contextlib
import csv
import functools
import hashlib
import itertools
import io
import json5
import logging
import operator
import os
import pathlib
import pickle
import pydot
import re
import rich.logging
import rich.progress
import typing
import yattag
import yaml
import zipfile
# More can be found at https://timberapi.com/specifications/schemas/
class Spec(typing.TypedDict):
pass
class Blueprint(typing.TypedDict):
pass
class TemplateCollectionSpec(Spec):
CollectionId: str
Blueprints: list[str]
class TemplateCollectionBlueprint(Blueprint):
TemplateCollectionSpec: TemplateCollectionSpec
class GoodSpec(Spec):
Id: str
DisplayNameLocKey: str
PluralDisplayNameLocKey: str
class GoodBlueprint(Blueprint):
GoodSpec: GoodSpec
class NeedGroupSpec(Spec):
Id: str
DisplayNameLocKey: str
class NeedGroupBlueprint(Blueprint):
NeedGroupSpec: NeedGroupSpec
class NeedSpec(Spec):
Id: str
Order: int
NeedGroupId: str
DisplayNameLocKey: str
class NeedBlueprint(Blueprint):
NeedSpec: NeedSpec
class GoodAmount(typing.TypedDict):
Id: str
Amount: int
class GoodAmountSpec(Spec):
Id: str
Amount: int
class RecipeSpec(Spec):
Id: str
DisplayLocKey: str
CycleDurationInHours: float
Ingredients: list[GoodAmount]
Products: list[GoodAmount]
Fuel: str
ProducedSciencePoints: int
CyclesFuelLasts: int
class RecipeBlueprint(Blueprint):
RecipeSpec: RecipeSpec
# TimberAPI specific and documented at https://timberapi.com/tools/
# TODO Remove
class ToolSpec(Spec):
Id: str
GroupId: str
Order: int
NameLocKey: str
DevMode: typing.NotRequired[bool]
class ToolBlueprint(Blueprint):
ToolSpec: ToolSpec
# TimberAPI enhanced and documented at https://timberapi.com/tool_groups/
class BlockObjectToolGroupSpec(Spec):
Id: str
Order: int
NameLocKey: str
Icon: str
FallbackGroup: bool
# Added by TimberAPI
# TODO Remove
Type: typing.NotRequired[str]
Layout: typing.NotRequired[str]
# from Moddable Tool Groups at https://github.com/datvm/TimberbornMods/blob/master/ConfigurableToolGroups/Specs/ParentToolGroupSpec.cs
class ParentToolGroupSpec(Spec):
ParentIds: list[str]
# from Moddable Tool Groups at https://github.com/datvm/TimberbornMods/blob/master/ConfigurableToolGroups/Specs/ToolGroupChildrenSpec.cs
class OrderedIds:
Id: str
Order: int
class ToolGroupChildrenSpec(Spec):
ChildrenGroupsIds: list[str]
ChildrenToolsTemplateNames: list[str]
ChildrenOrderedIds: list[str]
ChildrenExplicitOrderedIds: list[OrderedIds]
DoNotIncludePlaceableToolGroup: bool
class BlockObjectToolGroupBlueprint(Blueprint):
BlockObjectToolGroupSpec: BlockObjectToolGroupSpec
ParentToolGroupSpec: typing.NotRequired[ParentToolGroupSpec]
ToolGroupChildrenSpec: typing.NotRequired[ToolGroupChildrenSpec]
class FactionSpec(Spec):
Id: str
Order: int
DisplayNameLocKey: str
NewGameFullAvatar: str
TemplateCollectionIds: list[str]
class FactionBlueprint(Blueprint):
FactionSpec: FactionSpec
class ContinuousEffectSpec(Spec):
NeedId: str
PointsPerHour: float
class NeedApplierEffectSpec(Spec):
NeedId: str
Points: float
Probability: str
class BuildingSpec(Spec):
BuildingCost: list[GoodAmountSpec]
ScienceCost: int
class LabeledEntitySpec(Spec):
DisplayNameLocKey: str
class NaturalResourceSpec(Spec):
Order: int
class PlaceableBlockObjectSpec(Spec):
ToolGroupId: str
ToolOrder: int
DevModeTool: int
class AreaNeedApplierSpec(Spec):
ApplicationRadius: int
Effects: NeedApplierEffectSpec
class ContinuousEffectBuildingSpec(Spec):
Effects: list[ContinuousEffectSpec]
class RangedEffectBuildingSpec(Spec):
EffectRadius: int
class WorkshopRandomNeedApplierSpec(Spec):
Effects: list[NeedApplierEffectSpec]
class ConsumedGoodSpec(Spec):
GoodId: str
GoodPerHour: float
class GoodConsumingBuildingSpec(Spec):
ConsumedGoods: list[ConsumedGoodSpec]
FullInventoryWorkHours: int
class DwellingSpec(Spec):
MaxBeavers: int
SleepEffects: list[ContinuousEffectSpec]
class WorkplaceSpec(Spec):
MaxWorkers: int
class ManufactorySpec(Spec):
ProductionRecipeIds: list[str]
class MechanicalNodeSpec(Spec):
PowerInput: int
PowerOutput: int
class PlanterBuildingSpec(Spec):
PlantableResourceGroup: str
class PlantableSpec(Spec):
ResourceGroup: str
PlantTimeInHours: float
class Yielder(Spec):
Yield: GoodAmountSpec
RemovalTimeInHours: float
ResourceGroup: str
class CuttableSpec(Spec):
Yielder: Yielder
class GatherableSpec(Spec):
YieldGrowthTimeInDays: float
Yielder: Yielder
class GrowableSpec(Spec):
GrowthTimeInDays: float
class RuinSpec(Spec):
Yielder: Yielder
class CropSpec(Spec):
pass
class YieldRemovingBuildingSpec(Spec):
ResourceGroup: str
class TemplateSpec(Spec):
TemplateName: str
class WateredNaturalResourceSpec(Spec):
DaysToDieDry: float
class FloodableNaturalResourceSpec(Spec):
MinWaterHeight: int
MaxWaterHeight: int
DaysToDie: float
class TemplateBlueprint(typing.TypedDict):
Id: str
BuildingSpec: BuildingSpec
TemplateSpec: TemplateSpec
LabeledEntitySpec: LabeledEntitySpec
NaturalResourceSpec: NaturalResourceSpec
PlaceableBlockObjectSpec: PlaceableBlockObjectSpec
ParentToolGroupSpec: typing.NotRequired[ParentToolGroupSpec]
AreaNeedApplierSpec: AreaNeedApplierSpec
RangedEffectBuildingSpec: RangedEffectBuildingSpec
WorkshopRandomNeedApplierSpec: WorkshopRandomNeedApplierSpec
GoodConsumingBuildingSpec: GoodConsumingBuildingSpec
DwellingSpec: DwellingSpec
WorkplaceSpec: WorkplaceSpec
ManufactorySpec: ManufactorySpec
MechanicalNodeSpec: MechanicalNodeSpec
PlanterBuildingSpec: PlanterBuildingSpec
YieldRemovingBuildingSpec: YieldRemovingBuildingSpec
PlantableSpec: PlantableSpec
CuttableSpec: CuttableSpec
GatherableSpec: GatherableSpec
RuinSpec: RuinSpec
CropSpec: CropSpec
GrowableSpec: GrowableSpec
WateredNaturalResourceSpec: WateredNaturalResourceSpec
FloodableNaturalResourceSpec: FloodableNaturalResourceSpec
class PartialBlueprint[T: Blueprint](typing.NamedTuple):
path: pathlib.Path | zipfile.Path
optional: bool
specification: T
def track[T](
description: str,
sequence: typing.Iterable[T],
**kwargs,
) -> typing.Iterable[T]:
return rich.progress.track(sequence, '%-39s' % description, **kwargs)
def load_versions(directories: list[pathlib.Path], pattern: str) -> list[dict[str, typing.Any]]:
versions: list[dict[str, typing.Any]] = []
ids: set[str] = set()
for directory in track('Loading versions', directories, transient=True):
paths = []
for pattern in ('StreamingAssets/VersionNumbers.json', 'manifest.json'):
logging.debug(f'Scanning {directory.joinpath(pattern).resolve()}:')
paths.extend(directory.glob(pattern, case_sensitive=False))
if not paths:
logging.warning('Skipping %s', directory)
continue
assert len(paths) == 1, f'Expected single version manifest in {directory}, found: {paths}'
with paths[0].open('r', encoding='utf-8-sig') as f:
try:
doc = typing.cast(dict, json5.load(f, strict=False))
except Exception as e:
e.add_note(f'in {paths[0]}')
raise
if 'Id' not in doc:
assert '' not in ids, f'Multiple game directories'
ids.add('')
logging.info('Loading version %s of %s', doc['CurrentVersion'], 'Timberborn')
else:
assert doc['Id'] not in ids, f'{doc['Id']} loaded twice!'
ids.add(doc['Id'])
logging.info('Loading version %s of %s', doc['Version'], doc['Name'])
versions.append(doc)
return versions
def upgrade_toolgroup_blueprints(
blueprints: dict[str, list[PartialBlueprint[BlockObjectToolGroupBlueprint]]]
):
# TODO: Read Fields/Forestry from ToolGroups blueprints
toolgroups = [
BlockObjectToolGroupBlueprint(BlockObjectToolGroupSpec=BlockObjectToolGroupSpec(
Id='Fields',
Order=20 - 100,
NameLocKey='ToolGroups.FieldsPlanting',
Icon='',
FallbackGroup=False,
Type='PlantingModeToolGroup',
Layout='Blue',
)),
BlockObjectToolGroupBlueprint(BlockObjectToolGroupSpec=BlockObjectToolGroupSpec(
Id='Forestry',
Order=30 - 100,
NameLocKey='ToolGroups.ForestryPlanting',
Icon='',
FallbackGroup=False,
Type='PlantingModeToolGroup',
Layout='Blue',
)),
]
for toolgroup in toolgroups:
toolgroup_specs = blueprints.setdefault(toolgroup['BlockObjectToolGroupSpec']['Id'].lower(), [])
if any(not i.optional for i in toolgroup_specs):
logging.warning(f'Duplicate {toolgroup['BlockObjectToolGroupSpec']['Id']} ToolGroup')
# continue
assert not any(not i.optional for i in toolgroup_specs), toolgroup_specs
toolgroup_specs.insert(0, PartialBlueprint(pathlib.Path('builtin'), False, toolgroup))
def upgrade_tool_blueprints(
templates: dict[str, TemplateBlueprint],
blueprints: dict[str, list[PartialBlueprint[ToolBlueprint]]]
):
for tool_specs in blueprints.values():
for _, _, doc in tool_specs:
if 'Order' in doc['ToolSpec']:
doc['ToolSpec']['Order'] = int(doc['ToolSpec']['Order'])
tools: list[ToolBlueprint] = []
for item in templates.values():
if 'PlaceableBlockObjectSpec' in item:
spec = item['PlaceableBlockObjectSpec']
tool = ToolBlueprint(ToolSpec=ToolSpec(
Id=item['Id'], # item['TemplateSpec']['TemplateName'],
GroupId=spec['ToolGroupId'],
Order=spec['ToolOrder'],
NameLocKey=item['LabeledEntitySpec']['DisplayNameLocKey'],
))
if spec['DevModeTool'] == 1:
tool['ToolSpec']['DevMode'] = True
tools.append(tool)
if 'PlantableSpec' in item:
spec = item['NaturalResourceSpec']
tools.append(ToolBlueprint(ToolSpec=ToolSpec(
Id=item['Id'], # item['TemplateSpec']['TemplateName'],
GroupId='Fields' if 'CropSpec' in item else 'Forestry',
Order=spec['Order'],
NameLocKey=item['LabeledEntitySpec']['DisplayNameLocKey'],
)))
for tool in tools:
tool_specs = blueprints.setdefault(tool['ToolSpec']['Id'].lower(), [])
if any(not i.optional for i in tool_specs):
logging.warning(f'Duplicate {tool['ToolSpec']['Id']} Tool')
# continue
assert not any(not i.optional for i in tool_specs), tool_specs
tool_specs.insert(0, PartialBlueprint(pathlib.Path('builtin'), False, tool))
def merge_into_spec(
name: str,
spec: Blueprint | dict,
json: typing.ItemsView[str, object],
):
for k, v in json:
k, _, m = k.partition('#')
i = spec.get(k, None)
if isinstance(i, list) and m:
assert isinstance(v, list), f'{name}.{k}: {v}'
if m == 'append':
i.extend(v)
elif m == 'remove':
for x in v:
if x not in i:
logging.warning(f'No {x} in {name}.{k}')
continue
assert x in i, f'{name}.{k}: {x}'
i.remove(x)
else:
# TODO: Support delete
assert False, f'Unsupported mode: {name}.{k}#{m}: {v}'
elif isinstance(i, dict):
assert isinstance(v, dict), f'{name}.{k}: {v}'
merge_into_spec(f'{name}.{k}', i, v.items())
else:
if type(i) == float and type(v) == int:
logging.warning(f'{name}.{k}: {type(i)} vs {type(v)}')
assert v == float(v), f'{name}.{k}: {type(i)} vs {type(v)}'
v = float(v) # upcast
assert i is None or type(i) == type(v), f'{name}.{k}: {type(i)} vs {type(v)}'
spec[k] = v
def get_asset_content(f: io.TextIOWrapper):
def mono_behaviour_constructor(loader: yaml.Loader, node: yaml.MappingNode):
return loader.construct_mapping(node)
loader = yaml.SafeLoader(f)
try:
loader.add_constructor('tag:unity3d.com,2011:114', mono_behaviour_constructor)
asset = loader.get_single_data()
finally:
loader.dispose()
mono_behaviour = asset['MonoBehaviour']
guid = mono_behaviour['m_Script']['guid']
if guid == '13adc0e4713bee36fd631781df55c5df': # Timberborn.BlueprintSystem.BlueprintAsset
return mono_behaviour['_content']
raise Exception(f'Unknown Script guid: {guid}')
def load_blueprint_jsons[T: Blueprint](
directories: list[pathlib.Path],
blueprint: str,
pattern: str,
disable_progess = False,
upgrade_specs: typing.Callable[[dict[str, list[PartialBlueprint[T]]]], None] | None = None,
) -> list[T]:
all_paths: list[tuple[int, pathlib.Path | zipfile.Path]] = []
for i, directory in enumerate(directories):
# TODO This should iterate over all files and index by available Specs instead
pattern_dir = '' if i else f'StreamingAssets/Modding/Blueprints.zip'
pattern_path = autoPath(directory.joinpath(pattern_dir))
logging.debug(f'Scanning {pattern_path.joinpath(pattern)}:')
paths = list(pattern_path.glob(pattern))
if i and not paths:
# Easiest way to find files under export/ExportedProject/Assets/mods/*/assetbundles/resources
pattern2 = f'**/{pattern}'
paths.extend(pattern_path.glob(pattern2))
if i and blueprint == 'BlockObjectToolGroup':
# Handle alternative filenames for Whitepaws
pattern2 = pattern.replace('BlockObjectToolGroup', 'ToolGroup')
paths.extend(new_paths := list(pattern_path.glob(pattern2)))
if new_paths: logging.warning(f'Found via BlockObjectToolGroup --> ToolGroup: {[p.name for p in new_paths]}')
if i and not paths:
# HACK to find exported AssetRipper assets for Emberpelts and LeafCoats (TimberRipper doesn't need this)
pattern2 = pattern.replace('.blueprint.json', '.blueprint.asset')
paths.extend(new_paths := list(pattern_path.glob(pattern2)))
if new_paths: logging.warning(f'Found via .blueprint.json --> .blueprint.asset: {[p.name for p in new_paths]}')
if i and not paths and blueprint == 'BlockObjectToolGroup':
# HACK to find blueprints for Emberpelts and LeafCoats BlockObjectToolGroups
pattern2 = pattern.replace(blueprint, f'{blueprint}s')
paths.extend(new_paths := list(pattern_path.glob(pattern2)))
if new_paths: logging.warning(f'Found via BlockObjectToolGroup --> BlockObjectToolGroups: {[p.name for p in new_paths]}')
all_paths.extend((i, path) for path in paths)
assert all_paths or upgrade_specs, f'No blueprints found for {pattern}'
all_specs: dict[str, list[PartialBlueprint[T]]] = {}
for i, p in track(f'Loading {blueprint} blueprints', all_paths, total=len(all_paths), disable=disable_progess):
logging.debug(f'Reading {p}')
blueprint_name, _, name = p.stem.lower().partition('.')
# assert blueprint_name == blueprint.lower().partition('.')[0], f'{blueprint_name} == {blueprint.lower().partition('.')[0]}'
assert (
blueprint_name == blueprint.lower().partition('.')[0] + 's' or # HACK for Emberpelts
blueprint_name == blueprint.lower().partition('.')[0].replace('blockobjecttoolgroup', 'toolgroup') or # HACK for Whitepaws
blueprint_name == blueprint.lower().partition('.')[0]
), f'{blueprint_name} == {blueprint.lower().partition('.')[0]}'
optional = name.endswith('.optional.blueprint')
name = name.replace('.optional', '')
with p.open('r', encoding='utf-8-sig') as f:
try:
if p.suffix.lower().endswith('.asset'):
doc = typing.cast(T, json5.loads(get_asset_content(f), strict=False))
else:
doc = typing.cast(T, json5.load(f, strict=False))
except Exception as e:
e.add_note(f'in {p}')
raise
all_specs.setdefault(name, []).append(PartialBlueprint(p, optional, doc))
if upgrade_specs:
upgrade_specs(all_specs)
merged_specs: dict[str, T] = {}
for name, l in all_specs.items():
for p, optional, doc in sorted(l, key=lambda i: (i.optional)):
if optional:
if name not in merged_specs:
logging.debug(f'Skipping optional {p}')
continue
# assert name in merged_specs, name
spec = merged_specs.setdefault(name, typing.cast(T, dict()))
merge_into_spec(name, spec, doc.items())
return [s for s in merged_specs.values()]
def load_blueprints[T: Blueprint](
directories: list[pathlib.Path],
cls: type[T],
upgrade_specs: typing.Callable[[dict[str, list[PartialBlueprint[T]]]], None] | None = None,
) -> list[T]:
blueprint = cls.__name__.removesuffix('Blueprint')
return load_blueprint_jsons(
directories,
blueprint,
f'**/{blueprint}.*.blueprint.json',
upgrade_specs=upgrade_specs,
)
def load_template(
directories: list[pathlib.Path],
file_path: str,
) -> TemplateBlueprint:
blueprint = pathlib.PurePath(file_path).stem
templates = load_blueprint_jsons(
directories,
blueprint,
f'{file_path}.json',
disable_progess=True,
)
assert len(templates) == 1, templates
return typing.cast(TemplateBlueprint, dict(Id=blueprint, **templates[0]))
def load_templates_and_tools(
directories: list[pathlib.Path],
factions: dict[str, FactionBlueprint],
debug: bool,
) -> tuple[dict[str, dict[str, TemplateBlueprint]], dict[str, list[ToolBlueprint]]]:
map = builtins.map if debug else concurrent.futures.ProcessPoolExecutor().map
templates: dict[str, dict[str, TemplateBlueprint]] = {'common': {}}
tools: dict[str, list[ToolBlueprint]] = {}
template_collections = load_blueprints(directories, TemplateCollectionBlueprint)
commonpaths = list(itertools.chain.from_iterable(
typing.cast(list, b['TemplateCollectionSpec']['Blueprints']) for b in template_collections if b['TemplateCollectionSpec']['CollectionId'].lower() == 'common'))
for template in track(f'Loading common templates', map(load_template, *zip(*((directories, template) for template in commonpaths))), total=len(commonpaths)):
assert template and template['Id'].lower() not in templates['common'], template and template['Id']
templates['common'][template['Id'].lower()] = template
tools['common'] = load_blueprints(directories, ToolBlueprint, functools.partial(upgrade_tool_blueprints, templates['common']))
for key, faction in factions.items():
if faction['FactionSpec']['NewGameFullAvatar'].endswith('NO'):
logging.warning(f'Skipping {faction['FactionSpec']['Id']} because avatar ends with NO')
continue
faction_collections = tuple(g.lower() for g in faction['FactionSpec']['TemplateCollectionIds'])
faction_templates = list(itertools.chain.from_iterable(
typing.cast(list, b['TemplateCollectionSpec']['Blueprints']) for b in template_collections if b['TemplateCollectionSpec']['CollectionId'].lower() in faction_collections))
templates[key] = {}
for template in track(f'Loading {faction['FactionSpec']['Id']} templates', map(load_template, *zip(*((directories, template) for template in faction_templates))), total=len(faction_templates)):
assert template
assert template['Id'].lower() not in templates[key], template['Id']
if template['Id'].lower() in templates[key]:
breakpoint()
templates[key][template['Id'].lower()] = template
tools[key] = load_blueprints(directories, ToolBlueprint, functools.partial(upgrade_tool_blueprints, templates[key]))
return templates, tools
def load_translations(directories: list[pathlib.Path], language: str):
csv.register_dialect('timberborn', skipinitialspace=True) # HACK: , strict=True) # Work around for bad escaping in enUS Demolishable.Science.Grants
catalog: dict[str, str] = {}
for i, directory in enumerate(directories):
pattern_dir = f'Localizations' if i else f'StreamingAssets/Modding/Localizations.zip'
pattern_path = autoPath(directory.joinpath(pattern_dir))
patterns = [f'{language}{suffix}' for suffix in ['*.txt', '*.csv']]
paths: list[pathlib.Path] = []
for pattern in patterns:
paths.extend(pathlib.Path(str(p)).relative_to(str(pattern_path)) for p in pattern_path.glob(pattern))
# assert len(paths) <= 1, f'len(glob({pattern})) == {len(paths)}: {paths}'
for x in paths:
loc_path = pattern_path.joinpath(x)
with loc_path.open('r', encoding='utf-8-sig') as f:
reader = csv.DictReader(f, dialect='timberborn')
try:
for row in reader:
if not i and row['ID'] in catalog:
logging.warning(f'Duplicate key {row['ID']!r} on line {reader.line_num} of {loc_path}')
# For duplicate key in WB en_US
assert row['ID'] not in catalog, f'Duplicate key {row['ID']!r} on line {reader.line_num} of {loc_path}'
catalog[row['ID']] = row['Text']
except Exception as e:
e.add_note(f'Loading {loc_path} on line {reader.line_num}')
raise
catalog['Pictogram.Dwellers'] = '🛌'
catalog['Pictogram.Workers'] = '🦫'
catalog['Pictogram.Power'] = '⚡'
catalog['Pictogram.Science'] = '⚛️'
catalog['Pictogram.Grows'] = '🌱'
catalog['Pictogram.Dehydrates'] = '☠️'
catalog['Pictogram.Drowns'] = '🌊'
catalog['Pictogram.Matures'] = '🧺'
catalog['Pictogram.Aquatic'] = '💦'
catalog['Pictogram.Plantable'] = '🌱'
catalog['Pictogram.Cuttable'] = '🪚'
catalog['Pictogram.Gatherable'] = '🧺'
catalog['Pictogram.Ruin'] = '⛓️'
catalog['Unit.Day.NumberAndUnit'] = catalog['Unit.Day.NumberAndUnit'].format('{:g}')
catalog['Unit.Hour.NumberAndUnit'] = catalog['Unit.Hour.NumberAndUnit'].format('{:g}')
def gettext(message: str):
if message in catalog:
return catalog[message]
if message.endswith('DisplayName'):
suffix = 's' if message.endswith('PluralDisplayName') else ''
guess = message.rpartition('.')[0].partition('.')[2]
return f'Untranslated: {guess}{suffix}'
return f'Untranslated: {message}'
return gettext
def dict_group_by_id[T](iterable: typing.Iterable[T], key: str) -> dict[str, list[T]]:
"""Groups an interable of dicts into a dict of lists by the provided key."""
groups: dict[str, list[T]] = {}
for value in iterable:
group = typing.cast(dict, value)
for key_part in key.split('.'):
if key_part not in group:
group = ''
break
group = typing.cast(dict, group)[key_part]
if type(group) == list:
for item in group:
item = typing.cast(str, item).lower()
groups.setdefault(item, []).append(value)
else:
group = typing.cast(str, group).lower()
groups.setdefault(group, []).append(value)
return groups
class Cell(typing.TypedDict):
Faction: FactionBlueprint
FactionName: str
Links: dict[str, str]
class Index():
def __init__(
self,
args: argparse.Namespace,
):
self.args = args
self.items: dict[str, dict[str, Cell]] = {}
def AddItem(self, gettext, faction: FactionBlueprint, txt: str, filename: str):
lang = self.items.setdefault(gettext('Settings.Language.Name'), {})
cell = lang.setdefault(faction['FactionSpec']['Id'], Cell(
Faction=faction,
FactionName=gettext(faction['FactionSpec']['DisplayNameLocKey']),
Links={},
))
cell['Links'][filename] = txt
def Write(self, filename, versions):
self.stack = [[]]
doc = yattag.Doc()
doc.asis('<!DOCTYPE html>')
with doc.tag('html'):
with doc.tag('head'):
with doc.tag('meta', charset='utf-8'):
pass
with doc.tag('meta', name='viewport', content='width=device-width, initial-scale=1'):
pass
doc.line('title', 'Timbertrees')
if self.args.src_link:
with doc.tag('link', href='../style.css', rel='stylesheet'):
pass
else:
with doc.tag('style'):
with open('style.css', 'r', encoding='utf-8-sig') as f:
doc.asis('\n' + f.read())
with doc.tag('body'):
doc.line('h1', 'Timbertrees')
with doc.tag('table'):
for lang, factions in self.items.items():
with doc.tag('tr'):
doc.line('th', lang)
for cell in factions.values():
with doc.tag('td', klass='name'):
for dst, txt in cell['Links'].items():
doc.line('a', txt, href=pathlib.Path(dst).name)
doc.text(' ')
with doc.tag('script'):
doc.asis(f'var manifests = {json5.dumps(versions, indent=2, trailing_commas=False)};')
with open(filename, 'w', encoding='utf-8') as f:
print(yattag.indent(doc.getvalue()), file=f)
class Generator:
def __init__(
self,
args: argparse.Namespace,
index: Index,
gettext: typing.Callable[[str, ], str],
faction: FactionBlueprint,
goods: dict[str, GoodBlueprint],
needgroups: dict[str, NeedGroupBlueprint],
needs: dict[str, NeedBlueprint],
recipes: dict[str, RecipeBlueprint],
toolgroups: dict[str, BlockObjectToolGroupBlueprint],
tools: dict[str, ToolBlueprint],
templates: dict[str, TemplateBlueprint],
):
self.args = args
self.index = index
self.gettext = gettext
self.faction = faction
self.goods = goods
self.needgroups = needgroups
self.needs = needs
self.recipes = recipes
self.toolgroups = toolgroups
# TODO Handle ToolGroupChildrenSpec
self.toolgroups_by_group = dict_group_by_id(toolgroups.values(), 'ParentToolGroupSpec.ParentIds')
# TODO Handle ParentToolGroupSpec and ToolGroupChildrenSpec
self.tools_by_group = dict_group_by_id(tools.values(), 'ToolSpec.GroupId')
self.templates = {template['Id'].lower(): template for template in templates.values() if 'TemplateSpec' in template}
self.natural_resources: list[TemplateBlueprint] = sorted(
[p for p in self.templates.values() if 'NaturalResourceSpec' in p],
key=lambda p: ('CropSpec' not in p, p['NaturalResourceSpec']['Order'])
)
self.plantable_by_group = dict_group_by_id(self.natural_resources, 'PlantableSpec.ResourceGroup')
self.planter_building_by_group = dict_group_by_id(self.templates.values(), 'PlanterBuildingSpec.PlantableResourceGroup')
cuttable_by_group = dict_group_by_id(self.natural_resources, 'CuttableSpec.Yielder.ResourceGroup')
gatherable_by_group = dict_group_by_id(self.natural_resources, 'GatherableSpec.Yielder.ResourceGroup')
scavengable_by_group = dict_group_by_id(self.templates.values(), 'RuinSpec.Yielder.ResourceGroup')
self.yieldable_by_group: dict[
str,
tuple[typing.Literal['CuttableSpec'], list[TemplateBlueprint]] |
tuple[typing.Literal['GatherableSpec'], list[TemplateBlueprint]] |
tuple[typing.Literal['RuinSpec'], list[TemplateBlueprint]]
] = {}
self.yieldable_by_group.update({k: ('CuttableSpec', v) for k, v in cuttable_by_group.items()})
self.yieldable_by_group.update({k: ('GatherableSpec', v) for k, v in gatherable_by_group.items()})
self.yieldable_by_group.update({k: ('RuinSpec', v) for k, v in scavengable_by_group.items()})
def RenderFaction(self, faction: FactionBlueprint):
self.RenderNaturalResources(self.natural_resources)
for b in self.toolgroups_by_group['']:
if b['BlockObjectToolGroupSpec'].get('Type') != 'PlantingModeToolGroup':
self.RenderToolGroup(b)
def RenderNaturalResources(self, resources: list[TemplateBlueprint]):
for b in self.toolgroups_by_group['']:
if b['BlockObjectToolGroupSpec'].get('Type') == 'PlantingModeToolGroup':
self.RenderToolGroup(b)
def RenderToolGroup(self, toolgroup: BlockObjectToolGroupBlueprint):
items: list[tuple[int, typing.Literal[True], BlockObjectToolGroupBlueprint] | tuple[int, typing.Literal[False], ToolBlueprint]] = []
for tool in self.tools_by_group.get(toolgroup['BlockObjectToolGroupSpec']['Id'].lower(), []):
items.append((tool['ToolSpec']['Order'], False, tool))
for tg in self.toolgroups_by_group.get(toolgroup['BlockObjectToolGroupSpec']['Id'].lower(), []):
items.append((tg['BlockObjectToolGroupSpec']['Order'], True, tg))
for _, is_group, item in sorted(items, key=lambda x: (x[0], x[1])):
if is_group:
toolgroup = typing.cast(BlockObjectToolGroupBlueprint, item)
self.RenderToolGroup(toolgroup)
else:
tool = typing.cast(ToolBlueprint, item)
if tool['ToolSpec'].get('DevMode'):
logging.debug(f'Skipping DevMode Tool {tool['ToolSpec']['Id']}')
continue
template = self.templates[tool['ToolSpec']['Id'].lower()]
if 'PlantableSpec' in template:
self.RenderNaturalResource(template)
if 'PlaceableBlockObjectSpec' in template:
self.RenderBuilding(template)
def RenderBuilding(self, building: TemplateBlueprint):
for r in building.get('ManufactorySpec', {}).get('ProductionRecipeIds', []):
if r.lower() not in self.recipes:
logging.warning(f'Skipping missing recipe: {r}')
continue
self.RenderRecipe(self.recipes[r.lower()])
def RenderNaturalResource(self, resource: TemplateBlueprint): ...
def RenderRecipe(self, recipe: RecipeBlueprint): ...
def Write(self, filename): ...
class GraphGenerator(Generator):
FONTSIZE = 28
def dottext(self, message):
message = self.gettext(message)
message = re.sub(r'<color=(\w+)>(.*?)</color>', r'<font color="\1">\2</font>', message, flags=re.S)
if message.startswith('<') and message.endswith('>'):
message = f'<{message}>'
return message
def RenderFaction(self, faction: FactionBlueprint, templates: typing.Collection[TemplateBlueprint], toolgroups: dict[str, BlockObjectToolGroupBlueprint] ):
_ = self.dottext
self.graph.set_name(faction['FactionSpec']['Id'])
self.graph.set_label(_(faction['FactionSpec']['DisplayNameLocKey'])) # type: ignore
self.graph.add_node(pydot.Node(
'SciencePoints',
label=_('Science.SciencePoints'),
# image='sprites/bottombar/buildinggroups/Science.png',
))
for building in templates:
if building.get('PlaceableBlockObjectSpec', {}).get('ToolGroupId', '').lower() not in toolgroups:
continue
toolgroup = toolgroups[building['PlaceableBlockObjectSpec']['ToolGroupId'].lower()]
building_goods = set()
for c in building.get('BuildingSpec', {}).get('BuildingCost', []):
building_goods.add(c['Id'].lower())
recipes = building.get('ManufactorySpec', {}).get('ProductionRecipeIds', [])
for r in recipes:
sg = pydot.Subgraph(
building['Id'] + ('.' + r if len(recipes) > self.args.graph_grouping_threshold else ''),
cluster=True,
label=f'[{_(toolgroup['BlockObjectToolGroupSpec']['NameLocKey'])}]\n{_(building['LabeledEntitySpec']['DisplayNameLocKey'])}',
fontsize=self.FONTSIZE,
)
self.graph.add_subgraph(sg)
if r.lower() not in self.recipes:
logging.warning(f'Skipping missing recipe: {r}')
continue
self.RenderRecipe(sg, building, building_goods, self.recipes[r.lower()])
def RenderRecipe(self, sg, building, building_goods, recipe: RecipeBlueprint):
_ = self.dottext
sg.add_node(pydot.Node(
building['Id'] + '.' + recipe['RecipeSpec']['Id'],
label=f'{_('Unit.Hour.NumberAndUnit').format(recipe['RecipeSpec']['CycleDurationInHours'])}',
tooltip=_(recipe['RecipeSpec']['DisplayLocKey']),
))
if recipe['RecipeSpec']['Fuel']:
good = self.goods[recipe['RecipeSpec']['Fuel'].lower()]
amount = round(1 / recipe['RecipeSpec']['CyclesFuelLasts'], 3)
self.graph.add_edge(pydot.Edge(
good['GoodSpec']['Id'],
building['Id'] + '.' + recipe['RecipeSpec']['Id'],
label=amount,
labeltooltip=f'{_(good['GoodSpec']['DisplayNameLocKey' if amount == 1 else 'PluralDisplayNameLocKey'])} --> {_(recipe['RecipeSpec']['DisplayLocKey'])}',
style='dashed' if good['GoodSpec']['Id'].lower() in building_goods else 'solid',
color='#b30000',
))
for x in recipe['RecipeSpec']['Ingredients']:
if x['Id'].lower() not in self.goods:
continue
good = self.goods[x['Id'].lower()]
#if good['Id'].lower() in building_goods:
# continue
self.graph.add_node(pydot.Node(
good['GoodSpec']['Id'],
label=_(good['GoodSpec']['DisplayNameLocKey']),
# image=f'sprites/goods/{good['Good']['Id']}Icon.png',
))
self.graph.add_edge(pydot.Edge(
good['GoodSpec']['Id'],
building['Id'] + '.' + recipe['RecipeSpec']['Id'],
label=x['Amount'],
labeltooltip=f'{_(good['GoodSpec']['DisplayNameLocKey' if x['Amount'] == 1 else 'PluralDisplayNameLocKey'])} --> {_(recipe['RecipeSpec']['DisplayLocKey'])}',
style='dashed' if good['GoodSpec']['Id'].lower() in building_goods else 'solid',
color='#b30000',
))
for x in recipe['RecipeSpec']['Products']:
if x['Id'].lower() not in self.goods:
continue
good = self.goods[x['Id'].lower()]
self.graph.add_node(pydot.Node(
good['GoodSpec']['Id'],
label=_(good['GoodSpec']['DisplayNameLocKey']),
# image=f'sprites/goods/{good['Good']['Id']}Icon.png',
))
self.graph.add_edge(pydot.Edge(
building['Id'] + '.' + recipe['RecipeSpec']['Id'],
good['GoodSpec']['Id'],
label=x['Amount'],
color='#008000',
))
if recipe['RecipeSpec']['ProducedSciencePoints'] > 0:
self.graph.add_edge(pydot.Edge(
building['Id'] + '.' + recipe['RecipeSpec']['Id'],
'SciencePoints',
label=recipe['RecipeSpec']['ProducedSciencePoints'],
color='#008000',
))
def Write(self, filename):
self.graph = g = pydot.Dot(
graph_type='digraph',
tooltip=' ',
labelloc='t',
fontsize=self.FONTSIZE * 1.5,
rankdir='LR',
# ratio=9 / 16,
penwidth=2,
bgcolor='#1d2c38',
color='#a99262',
fontcolor='white',
style='filled',
fillcolor='#322227',
# clusterrank='none',
# newrank=True,
# concentrate=True,
)
g.set_node_defaults(
tooltip=' ',
fontsize=self.FONTSIZE,
penwidth=2,
color='#a99262',
fontcolor='white',
fillcolor='#22362a',
style='filled',
)
g.set_edge_defaults(
tooltip=' ',
labeltooltip=' ',