-
Notifications
You must be signed in to change notification settings - Fork 0
/
baro-data.py
1983 lines (1503 loc) · 59.6 KB
/
baro-data.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
"""
python 3.11+ script; depends on Pillow and lxml.
"""
import json
import os
import re
import sys
from base64 import b64encode
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from copy import copy
from dataclasses import dataclass, is_dataclass, fields, asdict
from graphlib import TopologicalSorter
from io import BytesIO, StringIO
from itertools import count, chain
from lxml import etree
from operator import ior
from pathlib import Path
from functools import partial, reduce
from threading import Lock
from typing import (
Union,
NewType,
TypeAlias,
Callable,
Iterable,
Iterator,
overload,
TypeVar,
Literal,
TYPE_CHECKING,
)
from time import monotonic_ns
if TYPE_CHECKING:
import PIL
_CHECK_SPRITE_DUPE = False
_CHECK_L10N_MISSING = False
PACKAGE_ORIGIN_KEY = "__package-origin"
TYPES_TS = """\
export type Identifier = string;
export type Money = "$";
export type Part = {
what: Identifier | Money
amount: number
condition?: [number | null, number | null]
}
export type WeightedRandomWithReplacement = {
weighted_random_with_replacement: Part[];
amount: number;
}
export type Process = {
// id: string,
uses: (Part | WeightedRandomWithReplacement)[],
skills: Record<Identifier, number>,
stations: Identifier[],
time: number
needs_recipe?: boolean
description?: string
}
export type Entity = {
identifier: Identifier,
tags: Identifier[],
package?: string,
}
export type Package = {
name: string,
version: string | null,
steamworkshopid: string | null,
}
export type Dictionary = Record<string, string>
export type Bundle = {
name: string,
load_order: Package[],
entities: Entity[],
processes: Process[],
i18n: Record<string, Dictionary>,
}
// export type LoadableDictionary = {
// url: string,
// localized_name?: string,
// }
export type LoadableBundle = {
name: string,
load_order: Package[],
url: string, // url to Bundle
sprites: string, // url to CSS sprite sheet
// dictionaries: Record<string, LoadableDictionary>
}
"""
class ansi:
"""256-color mode https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit"""
class Color(object):
# this stupid fucking text editor's indentation breaks from the
# unmatched left bracket in strings ...
reset = "\x1b[0m" # ]
def __init__(self, n):
self.fg = f"\x1b[38;5;{n}m" # ]
if sys.stderr.isatty() and "NOCOLOR" not in os.environ:
def __call__(self, str):
return f"{self.fg}{str}{self.reset}"
else:
def __call__(self, str):
return str
blue = Color(12)
magenta = Color(13)
_LAST_TIME = None
def logtime(message):
global _LAST_TIME
if _LAST_TIME is None:
d = 0.0
else:
d = (monotonic_ns() - _LAST_TIME) / 1e6
prefix = ansi.blue(f"{d: 8.3f}ms")
print(f"{prefix} » {message}", file=sys.stderr)
_LAST_TIME = monotonic_ns()
class Error(Exception):
def __init__(self, **kwargs):
super().__init__(kwargs)
def as_warning(self) -> Warning:
raise NotImplementedError
class MissingAttribute(Error):
def as_warning(self) -> Warning:
(args,) = self.args
return warn_missing_attribute(**args)
class BadValue(Error):
def as_warning(self) -> Warning:
(args,) = self.args
return warn_bad_value(**args)
class Warning(object):
def __init__(self, message="", **kwargs):
self.message = message
self.kwargs = kwargs
def with_path(self, path):
self.kwargs["path"] = path
return self
def warn_missing_attribute(*, element: etree._Element, attribute):
return Warning(
"required attribute missing from element", attribute=attribute, element=element
)
def warn_unexpected_element(*, unexpected):
return Warning("unexpected element", unexpected=unexpected)
def warn_bad_value(*, error, attribute, element):
return Warning(
"bad attribute value", error=error, attribute=attribute, element=element
)
def log_warnings(it, *, path=None):
for item in it:
if isinstance(item, Warning):
if path:
item = item.with_path(path)
log_warning(item.message, **item.kwargs)
else:
yield item
def log_warning(message, **kwargs):
print(ansi.magenta(message), file=sys.stderr)
for key, value in kwargs.items():
prefix = f"\t» {ansi.blue(key)} "
value = format_log_value(value, path=kwargs.get("path"))
if "\n" in value:
print(f"{prefix}...\n{value}", file=sys.stderr)
else:
print(f"{prefix}{value}", file=sys.stderr)
def format_log_value(v, path=None):
if isinstance(v, etree._Element):
# etree.tostringlist does nothing interesting?
lines = etree.tostring(v).decode().strip().splitlines(keepends=True)
if not lines:
return ""
if v.sourceline is None or path is None:
return "".join(lines)
[head, *tail] = lines
lines = [head] + _dedent_strings(tail)
width = len(str(v.sourceline + len(lines) - 1))
return "".join(
f"{path}:{no:{width}} {line}"
for no, line in zip(count(v.sourceline), lines)
)
elif is_dataclass(v):
return repr(v)
elif isinstance(v, Exception):
return repr(v)
else:
return str(v)
def _dedent_strings(strings):
if not strings:
return []
indent = min(re.match(" *", s).end() for s in strings)
return [s[indent:] for s in strings]
Identifier = NewType("Identifier", str)
Money: TypeAlias = Literal["$"]
MONEY: Money = "$"
RequiredSkill: TypeAlias = dict[Identifier, float]
IDENTIFIER_PATTERN = re.compile(r"[a-z0-9\._-]+", flags=re.IGNORECASE)
def coerce_to_identifier(value: str) -> str:
"""
>>> coerce_to_identifier("Cat Mod")
'catmod'
>>> coerce_to_identifier("%()fun_B4N4N4 ")
'fun_b4n4n4'
"""
return "".join(IDENTIFIER_PATTERN.findall(value.strip().lower()))
def make_identifier(value: str) -> Identifier:
"""
>>> make_identifier("guitar-ceta")
'guitar-ceta'
"""
# the game seems to use a lot of case insensitive stuff in Identifier.cs so
# lowercase these to normalize values
value = value.strip().lower()
if IDENTIFIER_PATTERN.fullmatch(value) is None:
raise ValueError(value)
return Identifier(value)
def split_identifier_list(value: str) -> list[Identifier]:
return [make_identifier(s) for s in value.split(",") if s]
def split_ltwh(value: str) -> tuple[int, int, int, int]:
(a, s, d, f) = [int(v.strip()) for v in value.split(",", maxsplit=4)]
return (a, s, d, f)
def split_int_pair(value: str) -> tuple[int, int]:
(a, s) = [int(v.strip()) for v in value.split(",", maxsplit=2)]
return (a, s)
def xmlbool(value: str) -> bool:
if value.lower() == "true":
return True
elif value.lower() == "false":
return False
else:
raise ValueError(value)
def serialize_dataclass(value):
if is_dataclass(value):
return dataclass_to_dict_without_defaults(value)
else:
raise TypeError(value)
def dataclass_to_dict_without_defaults(value):
return {
field.name: getattr(value, field.name)
for field in fields(value)
if field.default != getattr(value, field.name)
}
@dataclass
class Part(object):
"""RequiredItem or any item output of Fabricate or money"""
what: Union[Identifier, Money]
# positive if fabrication produces this item, negative if it consumes it
amount: int
# condition (like health or quality) required to be consumed or to be
# yielded? (CopyCondition and OutCondition{Min,Max} is used to specify
# condition of outputs/yielded items)
condition: tuple[float | None, float | None] = (None, None)
@property
def is_created(self):
return self.amount > 0
@property
def is_consumed(self):
return self.amount < 0
def can_combine(self, other: "Part") -> bool:
"""combine amounts for the same part in the same direction"""
return (
self.what == other.what
and self.condition == other.condition
and sign(self.amount) == sign(other.amount)
)
def combine_in_place(self, other: "Part"):
self.amount += other.amount
@dataclass
class RandomChoices(object):
"""barotrauma seems to do weighted random with replacement ..."""
weighted_random_with_replacement: list[Part]
amount: int
@dataclass
class Process(object):
"""Fabricate / Deconstruct / Price"""
id: str
uses: list[Part | RandomChoices]
stations: list[Identifier]
skills: dict[Identifier, float]
time: float = 0.0
# see fabricatorrequiresrecipe in localization strings
needs_recipe: bool = False
# see displayname.{description} in localization strings?
description: str | None = None
def iter_parts(self) -> Iterator[Part]:
for uses in self.uses:
if isinstance(uses, RandomChoices):
yield from uses.weighted_random_with_replacement
else:
yield uses
@dataclass
class Sprite(object):
element: etree._Element
package_name: str
texture: str
ltwh: tuple[int, int, int, int]
@dataclass
class BaroItem(object):
element: etree._Element
identifier: Identifier
nameidentifier: str | None
tags: list[Identifier]
def extract_BaroItem(element) -> Iterator[BaroItem | Warning]:
# there are a lot of attributes on this, we don't care to explicitly ignore
# them so don't yield from attrs.warnings() since that warns us about
# unused attributes
attrs = Attribs.from_element(element)
try:
yield BaroItem(
element=element,
identifier=attrs.use("identifier", convert=make_identifier),
nameidentifier=attrs.or_none("nameidentifier"),
tags=attrs.use("tags", convert=split_identifier_list, default=[]),
)
except Error as err:
yield err.as_warning()
def extract_Sprite_under(el):
for child in skip_comments(el):
if child.tag.lower() in ("inventoryicon", "sprite"):
yield from extract_Sprite(child)
def extract_Sprite(el) -> Iterator[Sprite | Warning]:
attrs = Attribs.from_element(el)
try:
# fmt: off
if (sheetindex := attrs.or_none("sheetindex", convert=split_int_pair)) \
and (sheetelementsize := attrs.or_none("sheetelementsize", convert=split_int_pair)):
(col, row) = sheetindex
(w, h) = sheetelementsize
ltwh = (w * col, row * h, w, h)
else:
ltwh = attrs.or_none("sourcerect", convert=split_ltwh) \
or attrs.use("source", convert=split_ltwh)
# fmt: on
yield Sprite(
element=el,
texture=attrs.use("texture"),
ltwh=ltwh,
package_name=attrs.use(PACKAGE_ORIGIN_KEY),
)
except Error as err:
yield err.as_warning()
VOWEL_PATTERN = re.compile(r"[aeiou]", flags=re.IGNORECASE)
def make_process_id(identifier: Identifier, tag: str, index: int):
# try not to use identifier characters for a separator
prefix = identifier[0] + VOWEL_PATTERN.sub("", identifier[1:])
return f"{prefix}/{tag[0]}{index:x}"
def extract_Item(item) -> Iterator[Process | Warning]:
identifier = extract_item_identifier(item)
counts = defaultdict(count) # type: ignore
for el in skip_comments(item):
tag = el.tag.lower()
try:
if tag == "fabricate":
id = make_process_id(identifier, tag, next(counts[tag]))
yield from extract_Fabricate(el, id=id)
elif tag == "deconstruct":
id = make_process_id(identifier, tag, next(counts[tag]))
yield from extract_Deconstruct(el, id=id)
elif tag == "price":
id = make_process_id(identifier, tag, next(counts[tag]))
yield from extract_Price(el, id=id)
except Error as err:
yield err.as_warning()
def extract_item_identifier(el) -> Identifier:
identifier = el.get("identifier")
if not identifier:
raise MissingAttribute(attribute="identifier", element=el)
return make_identifier(identifier)
def extract_Fabricate(el, **kwargs) -> Iterator[Process | Warning]:
# <Fabricate> is a child of <Item> or whatever. Our model is upside down
# compared to Barotrauma. Our Fabricate has the item it outs output as a
# child in `uses`.
attrs = Attribs.from_element(el)
attrs.ignore(
"fabricationlimitmin",
"fabricationlimitmax",
"quality",
"outcondition",
"hidefornontraitors",
)
res = Process(
**kwargs,
uses=[
Part(
what=extract_item_identifier(el.getparent()),
amount=attrs.use("amount", convert=int, default=1),
)
],
skills={},
stations=attrs.use("suitablefabricators", convert=split_identifier_list),
time=attrs.use("requiredtime", convert=float, default=1.0),
needs_recipe=attrs.use("requiresrecipe", default=False, convert=xmlbool),
description=attrs.opt("displayname"),
)
requiredmoney = attrs.opt("requiredmoney", convert=int)
if requiredmoney: # probably buying from a vending machine
res.uses.append(Part(what=MONEY, amount=-requiredmoney))
yield from attrs.warnings()
for child in el.xpath("*"):
try:
for item in extract_Fabricate_Item(child):
if isinstance(item, Part):
res.uses.append(item)
elif isinstance(item, dict): # RequiredSkill ...
res.skills.update(item)
else:
yield item
except Error as err:
yield err.as_warning()
yield res
def extract_Fabricate_Item(el) -> Iterator[RequiredSkill | Part | Warning]:
attrs = Attribs.from_element(el)
if el.tag.lower() == "requiredskill":
skill_identifier = attrs.use("identifier", convert=make_identifier)
skill_level = attrs.use("level", convert=float)
yield {skill_identifier: skill_level}
elif el.tag.lower() in ("requireditem", "item"):
attrs.ignore("usecondition", "header", "defaultitem")
what = attrs.or_none("identifier", convert=make_identifier)
if what is None:
what = attrs.or_none("tag", convert=make_identifier)
if what is None:
raise MissingAttribute(attribute=("identifier", "tag"), element=el)
# this is an ingredient/required item. it is consumed
# during fabrication, so the amount is negative
amount = -(
attrs.or_none("amount", convert=int)
or attrs.use("count", convert=int, default=1)
)
yield Part(
what=what,
amount=amount,
condition=(
attrs.or_none("mincondition", convert=float),
attrs.or_none("maxcondition", convert=float),
),
# description=attrs.or_none("description"),
)
else:
yield warn_unexpected_element(unexpected=el)
for child in el.xpath("*"):
yield warn_unexpected_element(unexpected=child)
def extract_Deconstruct(el, **kwargs) -> Iterator[Process | Warning]:
attrs = Attribs.from_element(el)
fab = Process(
**kwargs,
uses=[Part(what=extract_item_identifier(el.getparent()), amount=-1)],
skills={},
time=attrs.use("time", convert=float, default=1.0),
stations=attrs.use(
"requireddeconstructor",
default=[make_identifier("deconstructor")],
convert=split_identifier_list,
),
)
if attrs.use("chooserandom", convert=xmlbool, default=False):
# Weird special case for genetics detailed in extract_Deconstruct_Item() ...
#
# I don't want to model identifying unidentified genetic material the
# way barotrauma does it because their way doesn't map to how players
# understand it.
#
# So this peeks if all children under chooserandom have the same
# requiredotheritem and "moves" it up in that case.
children = iter(el.xpath("*"))
if (
(head := next(children, None)) is not None
and (req := head.get("requiredotheritem")) is not None
and all(req == sibling.get("requiredotheritem") for sibling in children)
):
for item in extract_Deconstruct_Item(head):
if isinstance(item, Part) and item.is_consumed:
break
else:
raise Exception("did not find requiredotheritem")
for child in el.xpath("*"):
child.attrib.pop("requiredotheritem")
fab.uses.append(item)
choose = RandomChoices(
weighted_random_with_replacement=[],
amount=attrs.use("amount", convert=int, default=1),
)
fab.uses.append(choose)
else:
choose = None
for child in el.xpath("*"):
try:
for item in extract_Deconstruct_Item(child):
if isinstance(item, Part):
if item.is_created:
if choose is None:
fab.uses.append(item)
else:
choose.weighted_random_with_replacement.append(item)
elif item.is_consumed:
if choose is None:
fab.uses.append(item)
else:
yield Warning(
"requiredotheritem with chooserandom not handled ",
element=el,
)
return # skip this Deconstruct entirely
else:
yield Warning("item has no amount", item=item, element=child)
else:
yield item
except Error as err:
yield err.as_warning()
yield fab
yield from attrs.warnings()
def extract_Deconstruct_Item(el) -> Iterator[Part | Warning]:
attrs = Attribs.from_element(el)
attrs.ignore(
"commonness",
"copycondition",
# useful but confusing to display vs the condition the input is
# required to be at for this part to be produced Items/ItemPrefab.cs:62
"outcondition",
"outconditionmin",
"outconditionmax",
"activatebuttontext",
"infotext",
"infotextonotheritemmissing",
# saw multiplier once Items/Genetic/genetic.xml:224 dunno what it means
# <Item name="" identifier="geneticmaterialhusk" variantof="geneticmaterialcrawler" nameidentifier="geneticmaterial">
# <Deconstruct>
# <Item identifier="geneticmaterialhusk" multiplier="5" />
"multiplier",
)
if el.tag.lower() in (
"requireditem", # not to be confused with requiredotheritem lulz
"item",
):
# Deconstruction Items are yields, so positive amounts
# mincondition maxcondition constrain whether that item qualifies to be
# yielded as an output,
yield Part(
what=attrs.use("identifier", convert=make_identifier),
amount=attrs.use("amount", convert=int, default=1),
condition=(
attrs.or_none("mincondition", convert=float),
attrs.or_none("maxcondition", convert=float),
),
# description=attrs.or_none("description"),
)
# This is super fucking stupid.
#
# The game models identifying genetic material as _deconstructing_
# unidentified genetic material into into usable genetic material. But
# it also wants to consume saline in the process. But deconstruction
# doesn't consume more than one item -- that's what fabrication is for.
#
# Instead, there's this requiredotheritem attribute on the <Item> in a
# <Deconstruct> that makes that deconstruction recipe require another
# input to consume.
#
# Also, all the recipes for identifying genetic material require the
# same item; stabilozine. But, instead of doing something like...
#
# <Deconstruct>
# <RequiredOtherItem identifier="stabilozine">
# <RandomChoice>
# <Item identifier="geneticmaterialcrawler" commonness="3" outconditionmin="0.1" ... />
# <Item identifier="geneticmaterialcrawler" commonness="2" outconditionmin="0.2" ... />
# <Item identifier="geneticmaterialcrawler" commonness="1" outconditionmin="0.4" ... />
# <Item identifier="geneticmaterialmudraptor" commonness="3" outconditionmin="0.1" ... />
# <Item identifier="geneticmaterialmudraptor" commonness="2" outconditionmin="0.2" ... />
# <Item identifier="geneticmaterialmudraptor" commonness="1" outconditionmin="0.4" ... />
# ...
# </RandomChoice>
# </Deconstruct>
#
# ... the RandomChoice is a property of the entire deconstruct and each
# item has to specify the stabilozine as a requiredotheritem.
#
# <Deconstruct chooserandom="true">
# <Item identifier="geneticmaterialcrawler" commonness="3" requiredotheritem="stabilozine" outconditionmin="0.1" ... />
# <Item identifier="geneticmaterialcrawler" commonness="2" requiredotheritem="stabilozine" outconditionmin="0.2" ... />
# <Item identifier="geneticmaterialcrawler" commonness="1" requiredotheritem="stabilozine" outconditionmin="0.4" ... />
# <Item identifier="geneticmaterialmudraptor" commonness="3" requiredotheritem="stabilozine" outconditionmin="0.1" ... />
# <Item identifier="geneticmaterialmudraptor" commonness="2" requiredotheritem="stabilozine" outconditionmin="0.2" ... />
# <Item identifier="geneticmaterialmudraptor" commonness="1" requiredotheritem="stabilozine" outconditionmin="0.4" ... />
# ...
# </Deconstruct>
#
# But this isn't how people think about it. Like a possible yield
# conditional on an extra input. That doesn't make sense here because
# they all take the same input.
#
# Combining genetics is also a Deconstruct with requiredotheritem. But
# less fucky since chooserandom is not involved.
other = attrs.or_none("requiredotheritem")
if other is not None:
yield Part(what=make_identifier(other), amount=-1)
else:
yield warn_unexpected_element(unexpected=el)
yield from attrs.warnings()
def extract_Price(el, **kwargs) -> Iterator[Process | Warning]:
attrs = Attribs.from_element(el)
# canbespecial is for discounts or in demand i guess? could be interesting
# requiresunlock not sure how to display this but would be useful
attrs.ignore(
"minleveldifficulty",
"minavailable",
"maxavailable",
"canbespecial",
"displaynonempty",
"requiresunlock",
)
# these are probably important if showing/guessing prices
attrs.ignore("baseprice", "buyingpricemodifier", "multiplier")
# price = attrs.use("baseprice", convert=float, default=0.0)
# multiplier = attrs.use("multiplier", convert=float, default=1.0)
is_sold_by_stores_generally = attrs.use("sold", convert=xmlbool, default=None)
if is_sold_by_stores_generally is None:
is_sold_by_stores_generally = attrs.use(
"soldbydefault", convert=xmlbool, default=True
)
yield from attrs.warnings()
price = Process(
**kwargs,
stations=[],
uses=[
Part(what=MONEY, amount=-1),
Part(what=extract_item_identifier(el.getparent()), amount=1),
],
skills={},
)
for child in el.xpath("*"):
if child.tag.lower() != "price":
yield warn_unexpected_element(unexpected=child)
continue
attrs = Attribs.from_element(child)
attrs.ignore(
"multiplier",
"minavailable",
"maxavailable",
"mindifficulty",
"minleveldifficulty",
)
try:
locationtype = attrs.opt("locationtype", convert=make_identifier)
if locationtype:
stations_fallback = dict(default=[f"merchant{locationtype}"])
else:
stations_fallback = dict()
stations = attrs.use(
"storeidentifier", convert=split_identifier_list, **stations_fallback
)
if attrs.use("sold", convert=xmlbool, default=is_sold_by_stores_generally):
price.stations.extend(stations)
except Error as err:
yield err.as_warning()
yield from attrs.warnings()
if price.stations:
yield price
@dataclass
class ContentPackageHeader(object):
name: str
iscorepackage: bool
gameversion: str
modversion: str
steamworkshopid: str
@dataclass
class ContentPackage(object):
path: Path
xmlpath: Path
element: etree._Element
name: str
iscorepackage: bool
gameversion: str
modversion: str
steamworkshopid: str
@dataclass
class PreItem(object):
"""variant_of not applied"""
package: ContentPackage
xmlpath: Path
element: etree._Element
identifier: Identifier
variant_of: Identifier | None
def find_ContentPackage_element(xmlpath: Path, peek=512) -> etree._Element | None:
with xmlpath.open("rb") as file:
if peek:
if b"<contentpackage" not in file.read(peek).lower():
return None
file.seek(0)
for _, element in etree.iterparse(file, events=("start",)):
if element.tag.lower() == "contentpackage":
return element
else:
break # only check the root element
return None
def extract_ContentPackageHeader(element) -> Iterator[ContentPackageHeader | Warning]:
attrs = Attribs.from_element(element)
attrs.ignore("altnames", "expectedhash")
yield ContentPackageHeader(
name=attrs.use("name"),
iscorepackage=attrs.use("corepackage", convert=xmlbool, default=False),
gameversion=attrs.use("gameversion"),
modversion=attrs.use("modversion", default=None),
steamworkshopid=attrs.use("steamworkshopid", default=None),
)
yield from attrs.warnings()
@dataclass
class ContentPath(object):
kind: Literal["item"] | Literal["text"]
path: Path
def extract_ContentPath(element, convert_path) -> Iterator[ContentPath | Warning]:
for child in element:
tag = child.tag.lower()
if tag not in ("item", "text"):
continue
a = Attribs.from_element(child)
try:
path = a.use("file", convert=convert_path)
except Error as err:
yield err.as_warning()
else:
yield ContentPath(kind=tag, path=path)
yield from a.warnings()
def apply_variants(
preitems: dict[Identifier, PreItem]
) -> Iterator[tuple[Identifier, etree._Element] | Warning]:
graph: dict[Identifier, set[Identifier]] = {}
for identifier, preitem in preitems.items():
if preitem.variant_of is None:
yield identifier, preitem.element
elif preitem.variant_of not in preitems:
yield Warning(
"element's variant_of not not found",
element=preitem.element,
variant_of=preitem.variant_of,
path=preitem.xmlpath,
)
else:
graph[identifier] = {preitem.variant_of}
# topological sort so that identifiers for variants of an item are iterated
# _after_ the identifiers of the item they are a variant of ...
#
# so B =variant_of=> A yields A before B
applied: dict[Identifier, etree._Element] = {}
for identifier in TopologicalSorter(graph).static_order():
# anything that isn't a variant was already yielded in the earlier loop
if (variation := preitems[identifier]).variant_of is None:
continue
# fmt: off
base_element = applied.get(variation.variant_of) \
or preitems[variation.variant_of].element
# fmt: on
applied_element = applied[identifier] = apply_variant(
base_element,
variation.element,
only_tags=("fabricate", "deconstruct", "price", "inventoryicon", "sprite"),
)
yield identifier, applied_element
def apply_variant(
base: etree._Element, variant: etree._Element, only_tags=()
) -> etree._Element:
"""Given <variant variantof=base>, apply variant over top of base, returning a new element.
variantof is some sort of "inheritance" or reuse gimick where some element
can be a variant of another and that element's definition is merged over
that of the thing it's a variant of.
mostly, the game copies the referenced element and then adds or replaces
existing attributes from the variant; working recursively by pairing child
elements by their tag name
some uh ... "features":
- some element attribute values are numbers prefixed with * or +, those are
added or multiplied with the existing value i guess but i don't think
this feature is used? so I'm ignoring it
- if an element in a variant has no children or attributes, it removes the
element instead of merging???