18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-20 10:24:58 +01:00

Merge branch 'master' into feat/renderers-cleanup

This commit is contained in:
2026-11-16 21:44:48 +01:00
264 changed files with 41203 additions and 10041 deletions

View File

@@ -0,0 +1,179 @@
#!/usr/bin/env python3
"""Writes //$e descriptions into the indicators of the signals in scenery/pkp/wskazniki, and makes there, as copies, the
indicators which so far came only built into the signal templates: W1 of the warning discs and of the block signals, W18 of
the block signals and the I, II and III plates of the repeaters. The templates keep theirs: one of these put on the template
it was copied from shows twice. The editor puts them on a signal it places.
usage: indicator_headers.py <data root> [--write] [--sidecar]
without --write it only reports what it would write; --sidecar writes the descriptions of the lit ones beside the data, in
editor/templates, the files of the game left as they are. The ones made are new files either way, a replaced one is kept in
editor_backup first
"""
import os
import re
import sys
import tarfile
import time
from editor_headers import LINEMARK, decode, load, sidecar, write
FOLDER = 'pkp/wskazniki'
PARAMS = [
'params:',
' - {id: 1, role: link, label: Signal}',
' - {id: 2, role: pos.x}',
' - {id: 3, role: pos.y}',
' - {id: 4, role: pos.z}',
' - {id: 5, role: rot.y}',
' - {id: 6, role: rot.x, default: 0}',
' - {id: 7, role: rot.z, default: 0}',
]
# the lit indicators under the head of the signal: the file, the sign, the name and what it says
LIT = [
('w19led.inc', 'W19', 'W19 ledowy', 'Wskaźnik W19 ledowy, na maszcie semafora pod komorami.'),
('w20led.inc', 'W20', 'W20 ledowy', 'Wskaźnik W20 ledowy (jazda po torze lewym), na maszcie semafora pod komorami.'),
('w21xled.inc', 'W21', 'W21 ledowy jednocyfrowy', 'Wskaźnik W21 ledowy jednocyfrowy (50-90 km/h), na maszcie semafora pod komorami. Każda jego prędkość wpisuje się do komórki semafora, (p1) to nazwa semafora.'),
('w21xyled.inc', 'W21', 'W21 ledowy dwucyfrowy', 'Wskaźnik W21 ledowy dwucyfrowy, na maszcie semafora pod komorami. Każda jego prędkość wpisuje się do komórki semafora, (p1) to nazwa semafora.'),
('w24led.inc', 'W24', 'W24 ledowy', 'Wskaźnik W24 ledowy (kierunku), na maszcie semafora pod komorami.'),
('w26led.inc', 'W26', 'W26 ledowy', 'Wskaźnik W26 ledowy (P albo D), na maszcie semafora pod komorami.'),
]
# how far the plates fixed flat to the mast go ahead of where their models put them: their back is 5 cm from the axis of the
# mast, the mast is 6.1 cm thick and its clamp under them 8.3 cm, so they went through the plate, in the templates too
AHEAD = '0.04'
# the indicators taken out of the signal templates: the model has its place by the foot of the signal built in.
# the file made, the sign, the name, the template it comes from, the model with its offset and textures, the node name suffix
MADE = [
('w1_nowy.inc', 'W1', 'W1 nowy, tarcza', 'ts1pi.inc', 'model 0 0 0.1 0 sem/wskazniki/w1new_d.t3d sem/slupy endmodel', 'w1',
'Wskaźnik W1 nowego typu na maszcie tarczy ostrzegawczej.'),
('w1_nowy_mz.inc', 'W1', 'W1 nowy, tarcza z pasem', 'ts1py+1sp.inc', 'model 0 0 0 0 sem/wskazniki/w1new_mz.t3d sem/slupy endmodel', 'w1',
'Wskaźnik W1 nowego typu na maszcie tarczy ostrzegawczej z pasem świetlnym, niżej niż zwykły.'),
('w1_stary.inc', 'W1', 'W1 stary, tarcza', 'ts1py+2sp.inc', 'model 0 0 0.1 0 sem/wskazniki/w1old_d.t3d sem/slupy endmodel', 'w1',
'Wskaźnik W1 starego typu na maszcie tarczy ostrzegawczej.'),
('w1_sbl.inc', 'W1', 'W1 na SBL', 'sbl4pw1.inc', 'model 0 0 0.1 0 pkp/w1_sbl.t3d pkp/w1 endmodel', 'w1',
'Wskaźnik W1 na maszcie semafora SBL, przedostatniego przed wjazdowym.'),
('w18.inc', 'W18', 'W18 na SBL', 'sbl3w18.inc', 'model 0 0 %s 0 sem/wskazniki/w18new.t3d sem/slupy endmodel' % AHEAD, 'w18',
'Wskaźnik W18 nowego typu na maszcie semafora SBL, ostatniego przed wjazdowym.'),
('w18_stary.inc', 'W18', 'W18 stary na SBL', 'sbl3yw18u.inc', 'model 0 0 %s 0 sem/wskazniki/w18old.t3d sem/slupy endmodel' % AHEAD, 'w18',
'Wskaźnik W18 starego typu na maszcie semafora SBL, ostatniego przed wjazdowym.'),
('wsk_i.inc', 'I', 'Tablica I', 'ps2pbi.inc', 'model 0 0 %s 0 sem/wskazniki/isp.t3d sem/slupy endmodel' % AHEAD, 'i',
'Tablica I na maszcie powtarzacza, pierwszego od semafora.'),
('wsk_ii.inc', 'II', 'Tablica II', 'ps2pbii.inc', 'model 0 0 %s 0 sem/wskazniki/iisp.t3d sem/slupy endmodel' % AHEAD, 'ii',
'Tablica II na maszcie powtarzacza, drugiego od semafora.'),
('wsk_iii.inc', 'III', 'Tablica III', 'ps2pbiii.inc', 'model 0 0 %s 0 sem/wskazniki/iiisp.t3d sem/slupy endmodel' % AHEAD, 'iii',
'Tablica III na maszcie powtarzacza, trzeciego od semafora.'),
]
EVENT = re.compile(r'^\s*event\s+\(p1\)_(\S+)\s+(\S+)', re.I | re.M)
def quoted(text):
return '"' + text.replace('\\', '\\\\').replace('"', '\\"') + '"'
def lit_events(text):
"""the events the indicator is shown by, by name: on, off, a letter or a speed; the parts of a multiple one left out"""
events = {}
for name, kind in EVENT.findall(text):
low = name.lower()
if low.endswith('_off') or low.endswith('off'):
events['off'] = name
elif kind.lower() == 'multiple' and re.search(r'_(\d+)$', low):
events[re.search(r'_(\d+)$', low).group(1)] = name
elif kind.lower() == 'lights' and re.search(r'_([a-z])$', low) and not re.search(r'_w\d+$', low):
events[low[-1].upper()] = name
elif kind.lower() == 'lights' and re.search(r'^w\d+$', low):
events['on'] = name
# shown first, then the letters and the speeds from the lowest, the one putting it out last
order = lambda key: (0, 0, '') if key == 'on' else (3, 0, '') if key == 'off' else (2, int(key), '') if key.isdigit() else (1, 0, key)
return {key: events[key] for key in sorted(events, key=order)}
def header(sign, name, description, place, events=None):
lines = ['version: 1', 'name: ' + name, 'category: indicator', 'description: ' + quoted(description)]
entry = '{sign: %s, place: %s' % (sign, place)
if events:
entry += ', events: {' + ', '.join('%s: %s' % (key, value) for key, value in events.items()) + '}'
lines.append('indicator: ' + entry + '}')
return lines + PARAMS
def made_text(entry, eol):
file, sign, name, source, model, suffix, description = entry
body = [
'//-- %s skopiowany z %s przez tools/editor/indicator_headers.py: model ma swoje położenie względem stopy semafora' % (name, source),
'//-- p1=nazwa semafora, p2,p3,p4=położenie jak semafora, p5=obrót jak semafora, p6,p7=pochylenie (0)',
'origin (p2) (p3) (p4)',
'rotate (p6) (p5) (p7)',
'node 400 0 (p1)_%s %s' % (suffix, model),
'rotate 0 0 0',
'endorigin',
]
block = [LINEMARK + ' ' + line for line in header(sign, name, description + ' Bez eventów, model stawia edytor przy semaforze.', 'foot')]
return eol.join(block + body) + eol
def main():
if len(sys.argv) < 2:
print(__doc__)
return 1
root = os.path.join(sys.argv[1], 'scenery', FOLDER)
writing = '--write' in sys.argv
described = []
for file, sign, name, description in LIT:
path = os.path.join(root, file)
if not os.path.isfile(path):
print('SKIP %-18s missing' % file)
continue
raw = load(path)
text, encoding = decode(raw)
events = lit_events(text)
if 'off' not in events or len(events) < 2:
print('SKIP %-18s events not found: %s' % (file, events))
continue
lines = header(sign, name, description + ' Gaszony eventem (p1)_%s.' % events['off'], 'head', events)
described.append((file, {'raw': raw, 'text': text, 'encoding': encoding, 'header': lines}))
print('%-18s %-4s head %s' % (file, sign, ', '.join('%s=%s' % item for item in events.items())))
made = []
for entry in MADE:
path = os.path.join(root, entry[0])
content = made_text(entry, '\r\n').encode('cp1250')
state = 'new' if not os.path.isfile(path) else ('same' if load(path) == content else 'changed')
made.append((entry[0], content, state))
print('%-18s %-4s foot %s (%s)' % (entry[0], entry[1], entry[4].split()[5], state))
print('described: %d, made: %d' % (len(described), len([m for m in made if m[2] != 'same'])))
if '--sidecar' in sys.argv:
sidecar(sys.argv[1], os.path.join('scenery', FOLDER), described)
elif writing and described:
write(sys.argv[1], os.path.join('scenery', FOLDER), 'indicators', described)
if writing or '--sidecar' in sys.argv:
write_made(sys.argv[1], root, made)
return 0
def write_made(data, root, made):
"""the indicators made, the ones there with other content kept in editor_backup first"""
replaced = [file for file, _, state in made if state == 'changed']
if replaced:
backup = os.path.join(data, 'editor_backup')
os.makedirs(backup, exist_ok=True) # NOSONAR
archive = os.path.join(backup, time.strftime('indicators_made_%Y%m%d_%H%M%S.tar'))
with tarfile.open(archive, 'w') as tar: # NOSONAR
for file in replaced:
tar.add(os.path.join(root, file), arcname=FOLDER + '/' + file) # NOSONAR
print('replaced ones kept in', archive)
for file, content, state in made:
if state == 'same':
continue
if state == 'changed':
print('REPLACED', file)
with open(os.path.join(root, file), 'wb') as out: # NOSONAR
out.write(content)
if __name__ == '__main__':
sys.exit(main())

View File

@@ -10,7 +10,7 @@ import os
import re
import sys
from editor_headers import body_lines, decode, load, sidecar, write
from editor_headers import LINEMARK, body_lines, decode, load, sidecar, write
FAMILIES = [
(re.compile(r'^ss[dow]?\d'), 'main'),
@@ -48,9 +48,56 @@ def statements(words, keyword):
return out
GUESSED = ('kind', 'mount', 'lamps', 'lean', 'read')
def flow_items(inner):
"""The key: value pieces of a YAML flow map written on one line, its nested maps and quoted strings kept whole."""
items, depth, quote, start = [], 0, '', 0
for idx, char in enumerate(inner):
if quote:
if char == quote and inner[idx - 1] != '\\':
quote = ''
elif char in '"\'':
quote = char
elif char in '{[':
depth += 1
elif char in '}]':
depth -= 1
elif char == ',' and depth == 0:
items.append(inner[start:idx].strip())
start = idx + 1
if inner[start:].strip():
items.append(inner[start:].strip())
return items
def kept_of(text, file=''):
"""What a description written before has that the guesses mustn't replace: the keys of its signal map other than the guessed
ones (arms, aspects, repeats...), its description, its parameters from 6 on, by id. Only a signal map written on one line is
kept; one written as a block is told of, its keys are lost"""
lines = [line[len(LINEMARK):].strip() for line in text.splitlines() if line.startswith(LINEMARK)]
signal, description, params = [], None, {}
for line in lines:
if line.startswith('signal:'):
inner = line[len('signal:'):].strip()
if inner.startswith('{') and inner.endswith('}'):
signal = [item for item in flow_items(inner[1:-1]) if item.split(':', 1)[0].strip() not in GUESSED]
else:
print('WARNING %s: its signal map isn\'t written on one line as {...}, its keys written by hand aren\'t kept' % (file or '?'), file=sys.stderr)
elif line.startswith('description:'):
description = line[len('description:'):].strip()
elif line.startswith('- {id:'):
found = re.match(r'- \{id:\s*(\d+)', line)
if found and int(found.group(1)) >= 6:
params[int(found.group(1))] = line[2:]
return signal, description, params
def examine(path, file):
raw = load(path)
text, encoding = decode(raw, 'utf-8')
kept_signal, kept_description, kept_params = kept_of(text, file)
lines = body_lines(text)
body = '\n'.join(lines)
words = tokens(body)
@@ -145,10 +192,10 @@ def examine(path, file):
"{id: 5, role: rot.y}",
]
if count >= 6:
params.append("{id: 6, role: texture, label: Plate, default: 0_nothing}" if 'tabl/(p6)' in body.lower() else "{id: 6, role: text, label: Symbol, default: none}")
params.append(kept_params.get(6) or ("{id: 6, role: texture, label: Plate, default: 0_nothing}" if 'tabl/(p6)' in body.lower() else "{id: 6, role: text, label: Symbol, default: none}"))
for id in range(7, count + 1):
label = 'Linked signal' if id == 7 else 'Parameter %d' % id
params.append("{id: %d, role: text, label: %s, default: none}" % (id, label))
params.append(kept_params.get(id) or "{id: %d, role: text, label: %s, default: none}" % (id, label))
signal = ['kind: ' + kind, 'mount: ' + mount]
if lamps:
@@ -157,12 +204,16 @@ def examine(path, file):
signal.append('lean: ' + lean)
if read:
signal.append('read: "' + read + '"')
# the keys written by hand stay: the arms, the aspects, the events a disc repeats
signal += kept_signal
header = [
'version: 1',
'name: ' + file[:-4],
'category: signal',
]
if description:
if kept_description:
header.append('description: ' + kept_description)
elif description:
header.append('description: "' + description.replace('\\', '\\\\').replace('"', '\\"') + '"')
header.append('signal: {' + ', '.join(signal) + '}')
header.append('params:')

View File

@@ -56,12 +56,20 @@ def kind_of(path, text):
return None
def described(data, file):
template = os.path.join(data, 'scenery', file)
beside = os.path.join(data, 'editor', 'templates', file)
def under(root, *parts):
"""the path of the parts under the root; a name out of a table which leads out of it, by .. or as a path of its own,
raises ValueError"""
base = os.path.realpath(root)
path = os.path.realpath(os.path.join(base, *parts))
if os.path.commonpath([base, path]) != base:
raise ValueError('%s is out of %s' % (path, base))
return path
def described(template, beside):
if os.path.exists(beside):
# a description this script wrote may be written again
with open(beside, encoding='utf-8', errors='replace') as source: # NOSONAR: a developer tool reading the data root it is given on its command line
with open(beside, encoding='utf-8', errors='replace') as source: # NOSONAR: under() kept the path in the data folder
return 'usage: {' not in source.read()
try:
text, _ = decode(load(template))
@@ -74,7 +82,8 @@ def read_tables(tables):
uses = {}
for table in tables:
scenery = os.path.basename(table).replace('use_', '').replace('.tsv', '')
with open(table, encoding='utf-8') as source: # NOSONAR: a developer tool reading the tables it is given on its command line
# a table named on the command line by whoever runs the tool, read as asked
with open(table, encoding='utf-8') as source: # NOSONAR
next(source)
for row in source:
cells = row.rstrip('\n').split('\t')
@@ -121,10 +130,18 @@ def main(argv):
unknown = []
for key, entry in sorted(uses.items(), key=lambda item: -len(item[1]['offsets'])):
file = entry['file']
if len(entry['offsets']) < least or described(data, file):
if len(entry['offsets']) < least:
continue
try:
text, _ = decode(load(os.path.join(data, 'scenery', file)))
template = under(data, 'scenery', file)
beside = under(data, 'editor', 'templates', file)
except ValueError as error:
print('left out:', error)
continue
if described(template, beside):
continue
try:
text, _ = decode(load(template))
except OSError:
continue
kind = kind_of(file, text)
@@ -135,9 +152,8 @@ def main(argv):
counts[kind] = counts.get(kind, 0) + 1
lines = header(entry, kind, name)
if write:
target = os.path.join(data, 'editor', 'templates', file)
os.makedirs(os.path.dirname(target), exist_ok=True) # NOSONAR
with open(target, 'w', encoding='utf-8', newline='\n') as out: # NOSONAR
os.makedirs(os.path.dirname(beside), exist_ok=True) # NOSONAR
with open(beside, 'w', encoding='utf-8', newline='\n') as out: # NOSONAR
out.write('\n'.join(lines) + '\n')
written += 1
else: