Files
forge-invar/src/forge_invar/tools/sentences.py
T
2026-11-05 22:57:14 +01:00

81 lines
2.1 KiB
Python

import logging
import re
from ..constants import PROJECT_PATH
TARGET_FILE = PROJECT_PATH / "project" / "inc_sentences.glsl"
CP437_FILE = PROJECT_PATH / "project" / "inc_cp437.glsl"
SENTENCES_FILE = PROJECT_PATH / "sentences.txt"
BACKUP_SENTENCES_FILE = PROJECT_PATH / "sentences.example.txt"
FILE_CONTENT = """
#ifndef INC_SENTENCES
#define INC_SENTENCES
#define SENTENCE_COUNT {0}
#define SENTENCE_MAX_LENGTH {1}
const int sentences[] = int[SENTENCE_COUNT * SENTENCE_MAX_LENGTH](
{2}
);
const int lengths[] = int[SENTENCE_COUNT](
{3}
);
#endif
"""
log = logging.getLogger(__name__)
def read_mapping() -> dict[str, str]:
mapping = {' ': '0x20'}
with CP437_FILE.open() as cp437:
for line in cp437:
if (match := re.match(r'.*// (0x\w\w), (.)$', line)):
mapping[match.group(2)] = match.group(1)
return mapping
def read_sentences() -> list[str]:
if SENTENCES_FILE.exists():
return SENTENCES_FILE.read_text().splitlines()
log.warning("sentences.txt not found, using backup")
return BACKUP_SENTENCES_FILE.read_text().splitlines()
def convert(sentence: str, mapping: dict[str, str], max_len: int) -> str:
out = []
for i in range(max_len):
if i >= len(sentence):
out += ["0x00"]
elif sentence[i] not in mapping:
log.warning(f"Char '{sentence[i]}' not in CP437")
out += ["0x20"]
else:
out += [mapping[sentence[i]]]
return ", ".join(out)
def main():
mapping = read_mapping()
sentences = read_sentences()
max_len = max(len(sentence) for sentence in sentences)
TARGET_FILE.write_text(
FILE_CONTENT.format(
len(sentences),
max_len,
"".join(
" " + convert(sentence, mapping, max_len) + ("," if i < len(sentences) - 1 else " ") + f" // {sentence}\n"
for i, sentence in enumerate(sentences)
),
" " + ", ".join(str(len(sentence)) for sentence in sentences) + "\n"
)
)
log.info(f"Wrote {len(sentences)} sentences to {TARGET_FILE}")
if __name__ == "__main__":
main()