tools/data/npc_yaml.py (2407B)
1 import collections 2 import copy 3 4 import ruamel.yaml.tokens 5 6 7 def has_comment(value): 8 if isinstance(value, ruamel.yaml.tokens.CommentToken): 9 return '#' in value.value 10 if isinstance(value, (list, tuple)): 11 return any(has_comment(token) for token in value) 12 return False 13 14 15 def keyed_nodes(nodes, section): 16 # Repeated fixed spawns share a code; their occurrence distinguishes each row. 17 result = {} 18 counts = collections.Counter() 19 for node in nodes: 20 if section == 'playfields': 21 key = node['id'] 22 elif section == 'districts': 23 key = node['name'] 24 else: 25 key = (node['template_code'], node['placement_status']) 26 counts[key] += 1 27 result[key, counts[key]] = node 28 return result 29 30 31 def merge_population(generated, baseline, edited): 32 # Keep handwritten fields/comments; update only values unchanged from the baseline. 33 result = copy.deepcopy(edited) 34 for field, value in generated.items(): 35 if field not in baseline: 36 result[field] = copy.deepcopy(value) 37 elif field not in edited: 38 continue 39 elif isinstance(value, dict): 40 result[field] = merge_population(value, baseline[field], edited[field]) 41 elif field in ['playfields', 'districts', 'groups']: 42 new_nodes = keyed_nodes(value, field) 43 old_nodes = keyed_nodes(baseline[field], field) 44 edited_nodes = keyed_nodes(edited[field], field) 45 result[field].clear() 46 for key, node in new_nodes.items(): 47 if key in old_nodes and key not in edited_nodes: 48 continue 49 if key in edited_nodes and key in old_nodes: 50 node = merge_population(node, old_nodes[key], edited_nodes[key]) 51 result[field].append(copy.deepcopy(node)) 52 for key, node in edited_nodes.items(): 53 if key not in new_nodes and (key not in old_nodes or node != old_nodes[key] 54 or has_comment(node.ca.comment) 55 or any(has_comment(value) for value in node.ca.items.values())): 56 result[field].append(copy.deepcopy(node)) 57 elif value != baseline[field] and edited[field] == baseline[field]: 58 result[field] = copy.deepcopy(value) 59 return result