-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtunable.py
More file actions
1963 lines (1674 loc) · 165 KB
/
tunable.py
File metadata and controls
1963 lines (1674 loc) · 165 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
from re import template
import collections
import inspect
import random
import types
from sims4.collections import frozendict
from sims4.repr_utils import standard_repr
from sims4.tuning.instances import TunedInstanceMetaclass
from sims4.tuning.merged_tuning_manager import MergedTuningAttr, get_manager, UnavailablePackSafeResourceError
from sims4.tuning.tunable_base import Attributes, TunableBase, tunable_type_mapping, TunableTypeNotSupportedError, BoolWrapper, Tags, RESERVED_KWARGS, get_default_display_name, MalformedTuningSchemaError, LoadingTags, LoadingAttributes
from sims4.utils import classproperty
from singletons import EMPTY_SET, UNSET, DEFAULT
import enum
import paths
import sims4.color
import sims4.log
import sims4.math
import sims4.resources
import sims4.tuning.instance_manager
import sims4.tuning.instances
logger = sims4.log.Logger('Tuning', default_owner='cjiang')
class _TunableHasPackSafeMixin:
__qualname__ = '_TunableHasPackSafeMixin'
__slots__ = ()
def __init__(self, *args, pack_safe=False, **kwargs):
super().__init__(*args, **kwargs)
self.pack_safe = pack_safe
def should_raise_pack_safe_exception(self):
return self.pack_safe
def export_desc(self, *args, **kwargs):
export_dict = super().export_desc(*args, **kwargs)
if self.pack_safe:
export_dict[Attributes.PackSafe] = True
return export_dict
class Tunable(TunableBase):
__qualname__ = 'Tunable'
__slots__ = ('_type', '_default', '_raw_default', '_source_location', '_source_query', '_source_sub_query', '_convert_defined_values')
def __init__(self, tunable_type, default, *, source_location=None, source_query=None, source_sub_query=None, convert_defined_values=True, needs_tuning=DEFAULT, **kwargs):
self._type = tunable_type_mapping.get(tunable_type)
if needs_tuning is DEFAULT:
needs_tuning = self._type is int or self._type is float
super().__init__(needs_tuning=needs_tuning, **kwargs)
self.cache_key = self._type
if self._type is None:
if isinstance(tunable_type, enum.Metaclass):
self._type = tunable_type
else:
raise TunableTypeNotSupportedError(tunable_type)
self._convert_defined_values = convert_defined_values
self._raw_default = default
try:
if self._convert_defined_values:
self._default = self._convert_to_value(default)
else:
self._default = self._type(default) if default is not None else None
self._raw_default = self._convert_from_value(default)
except:
logger.error('Unable to convert default')
self._source_location = '../' + source_location if source_location else None
self._source_query = source_query
self._source_sub_query = source_sub_query
def __repr__(self):
classname = type(self).__name__
if type(self) is Tunable and hasattr(self, '_type'):
typename = self._type.__name__
if len(typename) > 1:
typename = '{}{}'.format(typename[0].capitalize(), typename[1:])
typename = typename.replace('Wrapper', '')
classname = '{}{}'.format(classname, typename)
name = getattr(self, 'name', None)
r = '<{}'.format(classname)
sep = ': '
if name:
r = '{}{}{}'.format(r, sep, name)
sep = '='
r = '{}>'.format(r)
return r
def get_exported_type_name(self):
if hasattr(self._type, 'EXPORT_STRING'):
return self._type.EXPORT_STRING
return self._type.__name__
def export_desc(self):
export_dict = super().export_desc()
export_dict[Attributes.Type] = self.get_exported_type_name()
export_dict[Attributes.Default] = self._export_default(self._raw_default)
if self._source_location is not None:
export_dict[Attributes.SourceLocation] = self._source_location
export_dict[Attributes.SourceQuery] = self._source_query
if self._source_query is not None and self._source_sub_query is not None:
export_dict[Attributes.SourceSubQuery] = self._source_sub_query
return export_dict
def load_etree_node(self, node=None, source=None, expect_error=False):
if node is None:
return self.default
if self.default is None and self._type in (int, float, BoolWrapper):
name = node.get(LoadingAttributes.Name, '<UNKNOWN ITEM>')
logger.error('{}.{}: {} is loading a value of None.', source, name, self._type)
return self.default
try:
content = node.text
if not expect_error:
value = self._convert_to_value(content)
else:
value = self._convert_to_value(content)
except (ValueError, TypeError):
if getattr(self, 'pack_safe', False):
raise UnavailablePackSafeResourceError
name = node.get(LoadingAttributes.Name, '<UNKNOWN ITEM>')
logger_with_no_owner = sims4.log.Logger('Tuning')
logger_with_no_owner.error('Error while parsing tuning in {0}', source)
logger_with_no_owner.error('{0} has an invalid value for {3} specified: {1}. Setting to default value {2}', name, content, self.default, self._type)
return self.default
return value
def _convert_to_value(self, content):
if content is None:
return
return self._type(content)
def _convert_from_value(self, content):
return content
def _to_tunable(t, default=None, **kwargs):
if isinstance(t, TunableBase):
return t
tunable_factory = Tunable
if isinstance(t, enum.Metaclass):
if default is None:
default = t(0)
if t.flags:
tunable_factory = TunableEnumFlags
else:
tunable_factory = TunableEnumEntry
return tunable_factory(t, default, **kwargs)
class TunableTuple(TunableBase):
__qualname__ = 'TunableTuple'
TAGNAME = Tags.Tuple
LOADING_TAG_NAME = LoadingTags.Tuple
INCLUDE_UNTUNED_VALUES = True
__slots__ = ('locked_args', 'tunable_items', '_default', 'export_class_name', '_value_class')
def __init__(self, *args, locked_args=None, _suppress_default_gen=False, export_class_name=None, subclass_args=None, **kwargs):
tunable_items = {}
remaining_kwargs = {}
locked_args = locked_args or {}
for (k, v) in kwargs.items():
if k in RESERVED_KWARGS:
if isinstance(v, TunableBase):
logger.error('TunableTuple {} is using key {} in RESERVED_KWARGS.', self, k)
remaining_kwargs[k] = v
else:
while k not in locked_args:
tunable_items[k] = _to_tunable(v)
keys = [k for k in kwargs if k not in RESERVED_KWARGS]
if subclass_args is not None:
keys = [k for k in keys if k not in subclass_args]
if locked_args is not None:
keys = list(set(keys) | set(locked_args))
self._value_class = sims4.collections.make_immutable_slots_class(keys)
super().__init__(*args, **remaining_kwargs)
self.tunable_items = tunable_items
if locked_args:
self.locked_args = locked_args
else:
self.locked_args = sims4.collections.frozendict()
if not _suppress_default_gen:
default = {}
for (name, template) in tunable_items.items():
template = tunable_items[name]
if not self._has_callback:
pass
default[name] = template.default
self._default = self._create_dict(default, locked_args)
else:
for template in tunable_items.values():
while not self._has_callback:
pass
self.cache_key = id(self)
self.export_class_name = export_class_name
self.needs_deferring = True
def _create_dict(self, items, locked_args):
values = dict(items)
if locked_args:
values.update(locked_args)
return self._value_class(values)
def load_etree_node(self, node=None, source=None, **kwargs):
value = {}
tuned = set()
mtg = get_manager()
if node is not None:
for child_node in node:
name = child_node.get(LoadingAttributes.Name)
if name in self.tunable_items:
template = self.tunable_items.get(name)
if child_node.tag == MergedTuningAttr.Reference:
ref_index = child_node.get(MergedTuningAttr.Index)
tuplevalue = mtg.get_tunable(ref_index, template, source=source)
else:
current_tunable_tag = template.LOADING_TAG_NAME
if current_tunable_tag == Tags.TdescFragTag:
current_tunable_tag = template.FRAG_TAG_NAME
if current_tunable_tag != child_node.tag:
tunable_name = node.get(LoadingAttributes.Name, '<Unnamed>')
logger.error("Incorrectly matched tuning types found in tuning for {0} in {1}. Expected '{2}', got '{3}'", tunable_name, source, current_tunable_tag, child_node.tag)
logger.error('ATTRS 2: {}', node.items())
tuplevalue = template.load_etree_node(node=child_node, source=source)
value[name] = tuplevalue
tuned.add(name)
else:
logger.error('Error in {0}, parsing a {1} tag', source, self.TAGNAME)
if name in self.locked_args:
logger.error("The tag name '{0}' is locked for this tunable and should be removed from the tuning file.", name)
else:
logger.error("The tag name '{0}' was unexpected. Valid tags: {1}", name, ', '.join(self.tunable_items.keys()))
if self.INCLUDE_UNTUNED_VALUES:
leftovers = set(self.tunable_items.keys()) - tuned
for name in leftovers:
template = self.tunable_items[name]
tuplevalue = template.default
value[name] = tuplevalue
constructed_value = self._create_dict(value, self.locked_args)
return constructed_value
def invoke_callback(self, instance_class, tunable_name, source, value):
if not self._has_callback:
return
if self.callback is not None:
self.callback(instance_class, tunable_name, source, **dict(value))
if value is not None and value is not DEFAULT:
for (name, tuple_value) in value.items():
template = self.tunable_items.get(name)
while template is not None:
template.invoke_callback(instance_class, name, source, tuple_value)
def invoke_verify_tunable_callback(self, instance_class, tunable_name, source, value):
if not self._has_verify_tunable_callback:
return
if self.verify_tunable_callback is not None:
self.verify_tunable_callback(instance_class, tunable_name, source, **dict(value))
if value is not None and value is not DEFAULT:
for (name, tuple_value) in value.items():
template = self.tunable_items.get(name)
while template is not None:
template.invoke_verify_tunable_callback(instance_class, name, source, tuple_value)
@property
def export_class(self):
if self.export_class_name is not None:
return self.export_class_name
return self.__class__.__name__
def export_desc(self):
export_dict = super().export_desc()
for (name, val) in self.tunable_items.items():
self.add_member_desc(export_dict, name, val)
return export_dict
@staticmethod
def add_member_desc(export_dict, name, val):
sub_dict = val.export_desc()
sub_dict[Attributes.Name] = name
if val._display_name is not None:
sub_dict[Attributes.DisplayName] = val._display_name
else:
sub_dict[Attributes.DisplayName] = get_default_display_name(name)
if val.TAGNAME in export_dict.keys():
export_dict[val.TAGNAME].append(sub_dict)
else:
export_dict[val.TAGNAME] = [sub_dict]
def function_has_only_optional_arguments(fn):
full_arg_spec = inspect.getfullargspec(fn)
if len(full_arg_spec.args) == len(full_arg_spec.defaults or ()) and len(full_arg_spec.kwonlyargs) == len(full_arg_spec.kwonlydefaults or ()):
return True
return False
class TunableFactory(TunableTuple):
__qualname__ = 'TunableFactory'
FACTORY_TYPE = None
__slots__ = ()
class TunableFactoryWrapper:
__qualname__ = 'TunableFactory.TunableFactoryWrapper'
__slots__ = ('_tuned_values', '_name', 'factory')
def __init__(self, tuned_values, name, factory):
self._tuned_values = tuned_values
self._name = name
self.factory = factory
def __call__(self, *args, **kwargs):
total_kwargs = dict(self._tuned_values, **kwargs)
try:
return self.factory(*args, **total_kwargs)
except:
logger.error('Error invoking {}:', self)
raise
@property
def _factory_name(self):
return self.factory.__name__
def __repr__(self):
return '{}Wrapper.{}'.format(self._name, self._factory_name)
def __getattr__(self, name):
try:
return getattr(self._tuned_values, name)
except AttributeError:
raise AttributeError('{} does not have an attribute named {}'.format(self, name))
def __eq__(self, other):
if not isinstance(other, TunableFactory.TunableFactoryWrapper):
return False
if not self.factory == other.factory:
return False
if not super().__eq__(other):
return False
if not self._tuned_values == other._tuned_values:
return False
return True
def __hash__(self):
return hash(self._tuned_values)
def _create_dict(self, items, locked_args):
new_dict = super()._create_dict(items, locked_args)
tunable_type = type(self)
factory = self.FACTORY_TYPE
if factory is None:
raise NotImplementedError('{} does not specify FACTORY_TYPE.'.format(tunable_type))
if isinstance(factory, types.MethodType) and factory.__self__ is self:
factory_args = inspect.getfullargspec(factory).args
if factory_args and factory_args[0] == 'self':
raise TypeError("{}.FACTORY_TYPE is an instance method. Suggestion: remove the self argument and make '{}' a @staticmethod.".format(tunable_type.__name__, factory.__name__))
raise TypeError('{}.FACTORY_TYPE is a module method. Suggestion: use FACTORY_TYPE = staticmethod({}).'.format(tunable_type.__name__, factory.__name__))
result = TunableFactory.TunableFactoryWrapper(new_dict, tunable_type.__name__, factory)
return result
def invoke_callback(self, instance_class, tunable_name, source, value):
if not self._has_callback:
return
if self.callback is not None:
self.callback(instance_class, tunable_name, source, **dict(value._tuned_values))
for (name, tuple_value) in value._tuned_values.items():
template = self.tunable_items.get(name)
while template is not None:
template.invoke_callback(instance_class, name, source, tuple_value)
def invoke_verify_tunable_callback(self, instance_class, tunable_name, source, value):
if not self._has_verify_tunable_callback:
return
if self.verify_tunable_callback is not None:
self.verify_tunable_callback(instance_class, tunable_name, source, **dict(value._tuned_values))
for (name, tuple_value) in value._tuned_values.items():
template = self.tunable_items.get(name)
while template is not None:
template.invoke_verify_tunable_callback(instance_class, name, source, tuple_value)
@staticmethod
def _process_factory_tunables(factory_type, factory_tunables):
pass
@staticmethod
def factory_option(fn):
fn._factory_option = True
return fn
AUTO_FACTORY_TYPE_NAME_PATTERN = 'Tunable{}'
@staticmethod
def _invoke_callable_tunable(fn, name, all_extra_kwargs, default=UNSET):
if name not in all_extra_kwargs:
if function_has_only_optional_arguments(fn):
return fn()
if default is not UNSET:
return default
return fn()
value = all_extra_kwargs.pop(name)
if isinstance(value, tuple):
return fn(*value)
if isinstance(value, dict):
return fn(**value)
return fn(value)
@classmethod
def create_auto_factory(cls, factory_type, auto_factory_type_name=None, **extra_kwargs):
class auto_factory(cls):
__qualname__ = 'TunableFactory.create_auto_factory.<locals>.auto_factory'
__slots__ = ()
FACTORY_TYPE = factory_type
def __init__(self, *args, **kwargs):
all_extra_kwargs = {}
all_extra_kwargs.update(extra_kwargs)
all_extra_kwargs.update(kwargs)
factory_tunables = {'description': self.FACTORY_TYPE.__doc__}
is_auto_init = False
callable_tunables = {}
mro_getter = getattr(self.FACTORY_TYPE, 'mro', None)
if mro_getter is not None:
parents = mro_getter()
is_auto_init = AutoFactoryInit in parents
for src_cls in reversed(parents):
if 'FACTORY_TUNABLES' in vars(src_cls):
tunables = src_cls.FACTORY_TUNABLES
for (name, value) in tunables.items():
if callable(value):
callable_tunables[name] = value
else:
factory_tunables[name] = value
for (name, value) in vars(src_cls).items():
while getattr(value, '_factory_option', False):
callable_tunables[name] = value
updates = {}
for (name, fn) in callable_tunables.items():
new_tunables = cls._invoke_callable_tunable(fn, name, all_extra_kwargs, {})
if isinstance(new_tunables, dict):
updates.update(new_tunables)
else:
updates[name] = new_tunables
factory_tunables.update(updates)
cls._process_factory_tunables(factory_type, factory_tunables)
if is_auto_init:
factory_type.AUTO_INIT_KWARGS = set(factory_tunables) - RESERVED_KWARGS
factory_tunables.update(all_extra_kwargs)
super().__init__(*args, **factory_tunables)
if auto_factory_type_name is None:
auto_factory_type_name = cls.AUTO_FACTORY_TYPE_NAME_PATTERN.format(factory_type.__name__)
auto_factory.__name__ = auto_factory_type_name
return auto_factory
class HasTunableFactory:
__qualname__ = 'HasTunableFactory'
@classproperty
def TunableFactory(cls):
if '_AUTO_FACTORY' not in vars(cls):
cls._AUTO_FACTORY = TunableFactory.create_auto_factory(cls)
return cls._AUTO_FACTORY
class TunableSingletonFactory(TunableFactory):
__qualname__ = 'TunableSingletonFactory'
__slots__ = ('_origin_value_map',)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._default = self.default()
self._origin_value_map = None
def load_etree_node(self, **kwargs):
value = super().load_etree_node(**kwargs)
if value is not None:
constructed_value = value()
if self._has_callback:
if self._origin_value_map is None:
self._origin_value_map = {}
self._origin_value_map[id(constructed_value)] = value
return constructed_value
def invoke_callback(self, instance_class, tunable_name, source, value):
if not self._has_callback:
return
if self.callback is not None:
self.callback(instance_class, tunable_name, source, value)
if self._origin_value_map is not None:
original_value = self._origin_value_map.get(id(value))
if original_value is not None:
while True:
for (name, tuple_value) in original_value._tuned_values.items():
template = self.tunable_items.get(name)
while template is not None:
template.invoke_callback(instance_class, name, source, tuple_value)
def invoke_verify_tunable_callback(self, instance_class, tunable_name, source, value):
if not self._has_verify_tunable_callback:
return
if self.verify_tunable_callback is not None:
self.verify_tunable_callback(instance_class, tunable_name, source, value)
if self._origin_value_map is not None:
original_value = self._origin_value_map.get(id(value))
if original_value is not None:
while True:
for (name, tuple_value) in original_value._tuned_values.items():
template = self.tunable_items.get(name)
while template is not None:
template.invoke_verify_tunable_callback(instance_class, name, source, tuple_value)
class HasTunableSingletonFactory:
__qualname__ = 'HasTunableSingletonFactory'
__slots__ = ()
@classproperty
def TunableFactory(cls):
if '_AUTO_SINGLETON_FACTORY' not in vars(cls):
cls._AUTO_SINGLETON_FACTORY = TunableSingletonFactory.create_auto_factory(cls)
return cls._AUTO_SINGLETON_FACTORY
class AutoFactoryInit:
__qualname__ = 'AutoFactoryInit'
AUTO_INIT_KWARGS = None
AUTO_INIT_IGNORE_VALUE = 'AUTO_INIT_IGNORE_VALUE'
__slots__ = ()
def __init__(self, *args, **kwargs):
names = self.AUTO_INIT_KWARGS or list(kwargs)
for name in names:
if name in kwargs:
value = kwargs.pop(name)
else:
logger.error('{}: Missing required keyword: {}'.format(type(self).__name__, name))
while value != self.AUTO_INIT_IGNORE_VALUE:
try:
setattr(self, name, value)
except AttributeError:
logger.error("Can't set attribute {}.{} to {}.".format(type(self).__name__, name, value))
try:
super().__init__(*args, **kwargs)
except TypeError:
raise
def __repr__(self):
if not self.AUTO_INIT_KWARGS:
return super().__repr__()
kwargs = {}
for name in self.AUTO_INIT_KWARGS:
value = getattr(self, name)
while value:
kwargs[name] = value
return standard_repr(self, **kwargs)
class TunableReferenceFactory(TunableFactory):
__qualname__ = 'TunableReferenceFactory'
AUTO_FACTORY_TYPE_NAME_PATTERN = 'Tunable{}Reference'
__slots__ = ()
class TunableReferenceFactoryWrapper(TunableFactory.TunableFactoryWrapper):
__qualname__ = 'TunableReferenceFactory.TunableReferenceFactoryWrapper'
__slots__ = ()
def __getattr__(self, name):
try:
return getattr(self._tuned_values, name)
except AttributeError:
pass
return getattr(self.factory, name)
def __call__(self, *args, **kwargs):
total_kwargs = dict(self._tuned_values, **kwargs)
try:
return self.factory(*args, **total_kwargs)
except:
logger.error('Error invoking {}:', self)
raise
@property
def _factory_name(self):
if self.factory is None:
return 'None'
return self.factory.__name__
def __init__(self, manager, class_restrictions=(), reload_dependent=False, allow_none=False, **kwargs):
super().__init__(factory=TunableReference(manager, class_restrictions, reload_dependent=reload_dependent, allow_none=allow_none), subclass_args=('factory',), **kwargs)
if self.default.factory is None:
self._default = None
self.cache_key = '{}_{}'.format(manager.TYPE, id(self))
def load_etree_node(self, **kwargs):
value = super().load_etree_node(**kwargs)
if value is not None and value.factory is not None:
return value
def _create_dict(self, items, locked_args):
factory = items.pop('factory')
new_dict = super(TunableFactory, self)._create_dict(items, locked_args)
tunable_type = type(self)
result = TunableReferenceFactory.TunableReferenceFactoryWrapper(new_dict, tunable_type.__name__, factory)
return result
def invoke_callback(self, instance_class, tunable_name, source, value):
if not self._has_callback:
return
if value is not None:
if self.callback is not None:
self.callback(instance_class, tunable_name, source, factory=value.factory, **dict(value._tuned_values))
for (name, tuple_value) in value._tuned_values.items():
template = self.tunable_items.get(name)
while template is not None:
template.invoke_callback(instance_class, name, source, tuple_value)
def invoke_verify_tunable_callback(self, instance_class, tunable_name, source, value):
if not self._has_verify_tunable_callback:
return
if value is not None:
if self.verify_tunable_callback is not None:
self.verify_tunable_callback(instance_class, tunable_name, source, factory=value.factory, **dict(value._tuned_values))
for (name, tuple_value) in value._tuned_values.items():
template = self.tunable_items.get(name)
while template is not None:
template.invoke_verify_tunable_callback(instance_class, name, source, tuple_value)
@staticmethod
def _process_factory_tunables(factory_type, factory_tunables):
if not issubclass(factory_type, AutoFactoryInit):
return
instance_tunables = TunedInstanceMetaclass.get_tunables(factory_type)
for (name, tunable) in dict(factory_tunables).items():
if tunable is None:
pass
while name in instance_tunables:
tunable = OptionalTunable(disabled_name='use_default', disabled_value=AutoFactoryInit.AUTO_INIT_IGNORE_VALUE, enabled_name='override', tunable=tunable)
factory_tunables[name] = tunable
class TunableVariant(TunableTuple):
__qualname__ = 'TunableVariant'
TAGNAME = Tags.Variant
LOADING_TAG_NAME = LoadingTags.Variant
VARIANTNONE = 'None'
VARIANTNULLTAG = Tags.Tunable
VARIANTNULLCLASS = 'TunableExistance'
VARIANTDEFAULTNONE = 'none'
VARIANTDEFAULT_LOCKED_ARGS = sims4.collections.frozendict({VARIANTDEFAULTNONE: None})
__slots__ = ('_variant', '_variant_default', '_variant_map')
def __init__(self, default=None, *args, **kwargs):
super().__init__(_suppress_default_gen=True, *args, **kwargs)
self._variant_map = None
if default:
self._variant_default = default
try:
if default in self.locked_args:
self._default = self.locked_args[default]
else:
self._default = self.tunable_items[self._variant_default].default
except:
logger.exception('Error while attempting to set a default.')
else:
self._default = None
self._variant_default = self.VARIANTDEFAULTNONE
if not self.locked_args:
self.locked_args = self.VARIANTDEFAULT_LOCKED_ARGS
else:
self.locked_args[self.VARIANTDEFAULTNONE] = None
def export_desc(self):
export_dict = super().export_desc()
export_dict[Attributes.VariantType] = self.VARIANTNONE
if self._variant_default:
export_dict[Attributes.Default] = self._export_default(self._variant_default)
for name in self.locked_args.keys():
sub_dict = {Attributes.Name: name, Attributes.DisplayName: get_default_display_name(name), Attributes.Class: self.VARIANTNULLCLASS}
if self.VARIANTNULLTAG in export_dict.keys():
export_dict[self.VARIANTNULLTAG].append(sub_dict)
else:
export_dict[self.VARIANTNULLTAG] = [sub_dict]
return export_dict
def load_etree_node(self, node=None, source=None, **kwargs):
if node is None:
return
value = None
mtg = get_manager()
variant = node.get(LoadingAttributes.VariantType, self._variant_default)
if variant is not None:
if variant in self.locked_args:
value = self.locked_args[variant]
else:
value = None
template = self.tunable_items.get(variant)
if template is None:
logger.error('Variant is set to a type that does not exist: {}.'.format(variant))
return self._variant_default
node_children = list(node)
if node_children:
child_node = node_children[0]
name = child_node.get(LoadingAttributes.Name)
if child_node.tag == MergedTuningAttr.Reference:
ref_index = child_node.get(MergedTuningAttr.Index)
value = mtg.get_tunable(ref_index, template, source=source)
else:
current_tunable_tag = template.LOADING_TAG_NAME
if current_tunable_tag == Tags.TdescFragTag:
current_tunable_tag = template.FRAG_TAG_NAME
tunable_name = node.get(LoadingAttributes.Name, '<Unnamed>')
logger.error("Incorrectly matched tuning types found in tuning for {0} in {1}. Expected '{2}', got '{3}'".format(tunable_name, source, current_tunable_tag, child_node.tag))
logger.error('ATTRS 3: {}'.format(child_node.items()))
else:
child_node = None
if value is None:
value = template.load_etree_node(node=child_node, source=source)
if value is not None:
if template._has_callback:
if self._variant_map is None:
self._variant_map = {}
self._variant_map[id(value)] = variant
return value
def __getitem__(self, name):
raise RuntimeError('__getitem__ is not valid on an untuned TunableVariant')
def invoke_callback(self, instance_class, tunable_name, source, value):
if not self._has_callback:
return
if self.callback is not None:
self.callback(instance_class, tunable_name, source, **dict(value))
if value is not None and self._variant_map is not None:
variant = self._variant_map.get(id(value))
if variant is not None:
template = self.tunable_items.get(variant)
if template is not None:
template.invoke_callback(instance_class, variant, source, value)
def invoke_verify_tunable_callback(self, instance_class, tunable_name, source, value):
if not self._has_verify_tunable_callback:
return
if self.verify_tunable_callback is not None:
self.verify_tunable_callback(instance_class, tunable_name, source, **dict(value))
if value is not None and self._variant_map is not None:
variant = self._variant_map.get(id(value))
if variant is not None:
template = self.tunable_items.get(variant)
if template is not None:
template.invoke_verify_tunable_callback(instance_class, variant, source, value)
class OptionalTunable(TunableVariant):
__qualname__ = 'OptionalTunable'
__slots__ = ()
def __init__(self, tunable, enabled_by_default=False, disabled_value=None, disabled_name='disabled', enabled_name='enabled', **kwargs):
default = enabled_name if enabled_by_default else disabled_name
kwargs.setdefault('description', getattr(tunable, 'description', None))
kwargs[disabled_name] = disabled_value
kwargs[enabled_name] = tunable
super().__init__(locked_args={disabled_name: disabled_value}, default=default, **kwargs)
class TunableRange(Tunable):
__qualname__ = 'TunableRange'
__slots__ = ('_raw_min', '_raw_max', 'min', 'max')
def __init__(self, tunable_type, default, minimum=None, maximum=None, **kwargs):
super().__init__(tunable_type, default, **kwargs)
if self._convert_defined_values:
self._raw_min = minimum
self._raw_max = maximum
else:
self._raw_min = self._convert_from_value(minimum)
self._raw_max = self._convert_from_value(maximum)
self.min = minimum
self.max = maximum
self.cache_key = (self.min, self.max, self._type)
def load_etree_node(self, node=None, source=None, **kwargs):
value = super().load_etree_node(node=node, source=source, **kwargs)
if self._convert_defined_values:
converted_min = self._convert_to_value(self.min)
converted_max = self._convert_to_value(self.max)
else:
converted_min = self.min
converted_max = self.max
name = '<UNKNOWN ITEM>'
logger_with_no_owner = sims4.log.Logger('Tuning')
if node is not None:
name = node.get(LoadingAttributes.Name, name)
if converted_min is not None and value < converted_min:
logger_with_no_owner.error('Error while parsing tuning in {0}', source)
logger_with_no_owner.error('{0} tuned below min ({1}). Setting to min {2}', name, value, converted_min)
value = converted_min
elif converted_max is not None and value > converted_max:
logger_with_no_owner.error('Error while parsing tuning in {0}', source)
logger_with_no_owner.error('{0} tuned above max ({1}). Setting to max {2}', name, value, converted_max)
value = converted_max
return value
def export_desc(self):
export_dict = super().export_desc()
export_dict[Attributes.Min] = str(self._raw_min)
export_dict[Attributes.Max] = str(self._raw_max)
return export_dict
class TunableList(TunableBase):
__qualname__ = 'TunableList'
TAGNAME = Tags.List
LOADING_TAG_NAME = LoadingTags.List
DEFAULT_LIST = tuple()
__slots__ = ('_template', 'maxlength', '_default', 'allow_none', 'unique_entries', 'set_default_as_first_entry')
def __init__(self, tunable, description=None, maxlength=None, source_location=None, source_query=None, allow_none=False, unique_entries=False, set_default_as_first_entry=False, **kwargs):
super().__init__(description=description, **kwargs)
if source_location:
source_location = '../' + source_location
self._template = _to_tunable(tunable, source_location=source_location, source_query=source_query)
self.maxlength = maxlength
if set_default_as_first_entry:
self._default = (self._template.default,)
else:
self._default = self.DEFAULT_LIST
self.allow_none = allow_none
self.unique_entries = unique_entries
if isinstance(tunable, TunableBase):
self.cache_key = tunable.cache_key
else:
self.cache_key = tunable
self.needs_deferring = True
def load_etree_node(self, node=None, source=None, **kwargs):
if node is None:
return self.default
mtg = get_manager()
if len(node) <= 0:
return self.default
tunable_instance = self._template
tunable_name = node.get(LoadingAttributes.Name, '<Unnamed>')
tunable_list = []
element_index = 0
for child_node in node:
if self.maxlength is not None and len(tunable_list) >= self.maxlength:
logger.error('Error while parsing tuning in {0}'.format(source))
logger.error('TunableList has more elements than allowed ({0}).'.format(self.maxlength))
break
element_index += 1
value = None
try:
if child_node.tag == MergedTuningAttr.Reference:
ref_index = child_node.get(MergedTuningAttr.Index)
value = mtg.get_tunable(ref_index, tunable_instance, source=source)
else:
current_tunable_tag = tunable_instance.LOADING_TAG_NAME
if current_tunable_tag == Tags.TdescFragTag:
current_tunable_tag = tunable_instance.FRAG_TAG_NAME
if current_tunable_tag != child_node.tag:
logger.error("Incorrectly matched tuning types found in tuning for {0} in {1}. Expected '{2}', got '{3}'", tunable_name, source, current_tunable_tag, child_node.tag)
logger.error('ATTRS: {}'.format(child_node.items()))
value = tunable_instance.load_etree_node(node=child_node, source=source)
if not self.allow_none and value is None:
logger.error('None entry found in tunable list in {}.\nName: {}\nIndex: {}\nContent:{}', source, tunable_name, element_index, child_node)
else:
tunable_list.append(value)
except UnavailablePackSafeResourceError:
continue
except:
logger.exception('Error while parsing tuning in {0}:', source)
logger.error('Failed to load element for {0} (index {1}): {2}. Skipping.', tunable_name, element_index, child_node)
return tuple(tunable_list)
def export_desc(self):
result = super().export_desc()
content_export_desc = self._template.export_desc()
content_tag = self._template.TAGNAME
result[content_tag] = content_export_desc
if self.unique_entries:
result[Attributes.UniqueEntries] = 'true'
return result
def invoke_callback(self, instance_class, tunable_name, source, value):
if not self._has_callback:
return
super().invoke_callback(instance_class, tunable_name, source, value)
if value is not None:
for tuned_value in value:
self._template.invoke_callback(instance_class, tunable_name, source, tuned_value)
def invoke_verify_tunable_callback(self, instance_class, tunable_name, source, value):
if not self._has_verify_tunable_callback:
return
super().invoke_verify_tunable_callback(instance_class, tunable_name, source, value)
if value is not None:
for tuned_value in value:
self._template.invoke_verify_tunable_callback(instance_class, tunable_name, source, tuned_value)
class TunableSet(TunableBase):
__qualname__ = 'TunableSet'
__slots__ = ('_template', 'maxlength', '_default', 'allow_none')
TAGNAME = Tags.List
LOADING_TAG_NAME = LoadingTags.List
DEFAULT_LIST = EMPTY_SET
def __init__(self, tunable, description=None, maxlength=None, source_location=None, source_query=None, allow_none=False, **kwargs):
super().__init__(description=description, **kwargs)
if source_location:
source_location = '../' + source_location
self._template = _to_tunable(tunable, source_location=source_location, source_query=source_query)
self.maxlength = maxlength
self._default = self.DEFAULT_LIST
self.allow_none = allow_none
if isinstance(tunable, TunableBase):
self.cache_key = tunable.cache_key
else:
self.cache_key = tunable
self.cache_key = '{}_{}'.format('TunableSet', self.cache_key)
self.needs_deferring = True
def load_etree_node(self, node=None, source=None, **kwargs):
if node is None:
return self.default
mtg = get_manager()
if len(node) <= 0:
return self.default
tunable_instance = self._template
tunable_name = node.get(LoadingAttributes.Name, '<Unnamed>')
tunable_set = set()
element_index = 0
for child_node in node:
if self.maxlength is not None and len(tunable_set) >= self.maxlength:
logger.error('Error while parsing tuning in {0}', source)
logger.error('TunableList has more elements than allowed ({0}).', self.maxlength)
break
element_index += 1
value = None
try:
if child_node.tag == MergedTuningAttr.Reference:
ref_index = child_node.get(MergedTuningAttr.Index)
value = mtg.get_tunable(ref_index, tunable_instance, source=source)
else:
current_tunable_tag = tunable_instance.LOADING_TAG_NAME
if current_tunable_tag == Tags.TdescFragTag:
current_tunable_tag = tunable_instance.FRAG_TAG_NAME
if current_tunable_tag != child_node.tag:
logger.error("Incorrectly matched tuning types found in tuning for {0} in {1}. Expected '{2}', got '{3}'", tunable_name, source, current_tunable_tag, child_node.tag)
logger.error('ATTRS: {}'.format(child_node.items()))
value = tunable_instance.load_etree_node(node=child_node, source=source)
if not self.allow_none and value is None:
logger.error('None entry found in tunable set in {}.\nName: {}\nIndex: {}\nContent:{}', source, tunable_name, element_index, child_node)
else:
tunable_set.add(value)
except UnavailablePackSafeResourceError:
continue
except:
logger.exception('Error while parsing tuning in {0}:', source)
logger.error('Failed to load element for {0} (index {1}): {2}. Skipping.', tunable_name, element_index, child_node)
return frozenset(tunable_set)
def export_desc(self):
export_dict = super().export_desc()
content_export_desc = self._template.export_desc()
content_tag = self._template.TAGNAME
export_dict[content_tag] = content_export_desc
export_dict[Attributes.UniqueEntries] = 'true'
return export_dict
def invoke_callback(self, instance_class, tunable_name, source, value):
if not self._has_callback:
return
super().invoke_callback(instance_class, tunable_name, source, value)
if value is not None:
for tuned_value in value:
self._template.invoke_callback(instance_class, tunable_name, source, tuned_value)
def invoke_verify_tunable_callback(self, instance_class, tunable_name, source, value):
if not self._has_verify_tunable_callback:
return
super().invoke_verify_tunable_callback(instance_class, tunable_name, source, value)
if value is not None:
for tuned_value in value:
self._template.invoke_verify_tunable_callback(instance_class, tunable_name, source, tuned_value)
class TunableMapping(TunableList):
__qualname__ = 'TunableMapping'
DEFAULT_MAPPING = frozendict()
__slots__ = ('_tunable_value', '_key_name', '_value_name', '_tuple_name', '_key_type')
def __init__(self, key_type=str, value_type=str, key_value_type=None, key_name='key', value_name='value', tuple_name=None, **kwargs):
if key_value_type is not None:
(key_name, value_name) = key_value_type.get_tunable_mapping_info()
else:
def key_value_type(**kwargs):
tuple_def = {key_name: _to_tunable(key_type), value_name: _to_tunable(value_type)}
kwargs.update(tuple_def)
return TunableTuple(**kwargs)
tunable_type = key_value_type()
self._key_name = key_name
self._value_name = value_name
self._tuple_name = tuple_name
self._key_type = key_type
super().__init__(tunable_type, **kwargs)
self._default = TunableMapping.DEFAULT_MAPPING
def _process_dict_value(self, value, tunable_name, source):
if value is not None:
if len(value) == 0:
return TunableMapping.DEFAULT_MAPPING
key_name = self._key_name
value_name = self._value_name
if self.allow_none: