#!/usr/bin/env python3
"""Generate the figures of part 2 of the book, From files to the game (docs/files/).

One figure per file page follows a format from its bytes to the game: the
parts of the file in order, the steps the game applies to it, what it becomes
in memory and the systems that use it. Another figure groups the files by the
moment they are read, and four more open the images, dungeon graphics, sound
and texts family pages. Every value transcribes the file pages, which give the
evidence; the program reads no game file and reproduces no game graphics.

Usage:
    python3 scripts/files/make_file_figures.py

Each figure is written to the img/ folder of its family, docs/files/<family>/img/.
"""
import sys
import textwrap
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
sys.path[:0] = [str(Path(__file__).resolve().parent), str(ROOT / 'scripts/common')]
from svgkit import frame, write, arrow, box, text, INK, INK2, GRID, BLUE, LIGHT, DARK, PALE, SHADE, SURF, ORANGE, GREEN  # noqa: E402

FILES = ROOT / 'docs/files'

# name: (family, title, parts [(part, size)], steps, memory, users)
SPECS = {
    'CPS': ('containers', 'CPS containers',
            [('Header', '10 bytes'), ('Palette', 'two images only'), ('Compressed data', 'rest of the file')],
            ['Read the header', 'Read or skip the palette', 'Unpack: stored, LCW or run lengths'],
            'A 320 × 200 page of one byte per pixel, or the unpacked INF or VCN data',
            ['Pictures and scenes', 'Level loading (INF)', 'Tile sets (VCN)']),
    'INF': ('level-data', 'LEVELn.INF',
            [('Header word', '2 bytes'), ('Sublevel records', 'one or two'), ('Level-state section', 'monsters, scripts'),
             ('Cell bindings', 'counted list')],
            ['Unpack the CPS container', 'Follow the link to the sublevel record', 'Load the named files, types and mappings',
             'Copy the scripts, bind the cells'],
            'Monster types and slots, wall properties, script buffer, block bindings, timers',
            ['Monsters', 'Walls and doors', 'Scripts', 'The view']),
    'MAZ': ('level-data', 'LEVELn.MAZ',
            [('Header', '6 bytes'), ('Cells', '1,024 × 4 bytes')],
            ['Read 6 + 4,096 bytes', 'Copy the cells into the block table, unless the level has a record'],
            'The wall references of the 1,024 blocks',
            ['Moving', 'The view', 'Doors and scripts']),
    'VCN': ('dungeon-graphics', 'Tile sets (VCN)',
            [('Block count', '2 bytes'), ('Backdrop colours', '16 bytes'), ('Wall colours', '16 bytes'),
             ('Blocks', '32 bytes each')],
            ['Unpack the CPS container', 'Keep at most 1,484 blocks', 'EGA: colour each block once'],
            'Tile blocks and their two colour tables',
            ['Drawing the walls, floor and ceiling']),
    'VMP': ('dungeon-graphics', 'Wall layouts (VMP)',
            [('Count', '2 bytes'), ('Backdrop', '330 entries'), ('Wall groups', '431 entries each')],
            ['Read the entries', 'Select a group per wall through the level’s wall table'],
            'The entries of the backdrop and of each wall graphic',
            ['The backdrop and wall layers of the view']),
    'DEC': ('dungeon-graphics', 'Wall decorations (DEC)',
            [('Decorations', 'count, 52 bytes each'), ('Rectangles', 'count, 8 bytes each')],
            ['Copy each chain per wall mapping, at most 60 per sublevel', 'Cut the rectangles out of the decoration image'],
            'The decoration table and its shapes',
            ['Wall decorations in the view']),
    'DCR': ('dungeon-graphics', 'Monster decorations (DCR)',
            [('Group count', '2 bytes'), ('Groups', 'six entries of six bytes')],
            ['Load with the monster image, when a level asks for decorations',
             'Cut each rectangle out of the image page, up to 16 colours'],
            'Monster decoration shapes (MonsterDecorationRuntime)',
            ['Monsters in the view']),
    'PAL': ('images', 'Palettes (PAL, EGA, COL)',
            [('Colours 0 to 255', '3 bytes each, 768 in all')],
            ['Read the palette, or the .EGA file in EGA mode', 'The display driver sets the 256 colours'],
            'The working palette',
            ['Every screen', 'The darkening table of the view']),
    'FADING_DAT': ('images', 'FADING.DAT',
                   [('Seven tables', '256 bytes each')],
                   ['Read when the introduction starts', 'When missing, build the tables and write the file'],
                   'The display driver’s colour table, one table at a time',
                   ['Fades of the introduction, VGA mode']),
    'FNT': ('images', 'Fonts (FNT)',
            [('Size', '2 bytes'), ('Offsets', '128 × 2 bytes'), ('Height, width', '2 bytes'), ('Glyphs', 'rest')],
            ['Allocate the stored size and read the file at start-up'],
            'Two fonts: FONT8 and FONT6',
            ['Start menu and questions (FONT8)', 'Play screen (FONT6)']),
    'ITEM_DAT': ('items', 'ITEM.DAT',
                 [('Items', 'count, 14 bytes each'), ('Names', 'count, 35 bytes each')],
                 ['Copy the records into the item table', 'Read the names'],
                 'The item table of 600 entries (ItemRuntime) and the item names',
                 ['Inventory and floors', 'Scripts', 'Item names']),
    'ITEMTYPE_DAT': ('items', 'ITEMTYPE.DAT',
                     [('Count', '2 bytes'), ('Types', '16 bytes each')],
                     ['Copy the records into memory'],
                     'The item types (ItemTypeRuntime), which can change in play',
                     ['Inventory slots', 'Hands and classes', 'Use, damage and defense']),
    'TEXT_DAT': ('texts', 'TEXT.DAT',
                 [('Offsets', '16-bit, one per text'), ('Texts', 'zero-terminated')],
                 ['Read up to 32,000 bytes when a dialogue opens or a parchment is read'],
                 'The text buffer',
                 ['The dialogue screen', 'Parchments']),
    'ADL': ('sound', 'AdLib files (ADL)',
            [('Sound-effect table', '120 bytes'), ('Program pointers', '250 × 2'), ('Instrument pointers', '250 × 2'),
             ('Programs', 'variable'), ('Instruments', '11 bytes each')],
            ['At level load, keep the first 120 bytes', 'Copy the rest, at most 15,120 bytes, to the driver'],
            'The sound-effect table and the driver’s buffer',
            ['Music and sound effects, AdLib']),
    'SND': ('sound', 'Speaker and Tandy files (SND)',
            [('Sound-effect table', '120 bytes'), ('Program pointers', '250 × 2'), ('Unused pointers', '250 × 2'),
             ('Programs', 'variable')],
            ['At level load, keep the first 120 bytes', 'Copy the rest, at most 15,120 bytes, to the buffer'],
            'The sound-effect table and the sound buffer',
            ['Sounds through the PC speaker or the Tandy chip']),
    'SAV': ('saves', 'Saved games (SAV)',
            [('Description', '20 bytes'), ('Characters', '6 × 345 bytes'), ('Party and world', '92 bytes'),
             ('Items', '600 × 14 bytes'), ('Level records', '17 × 2,130 bytes'), ('Options', '3 bytes'),
             ('Item types', '6 × 16 bytes')],
            ['Read the whole file and check the size of each part', 'Settle the level, then restore each part'],
            'Characters, party variables, items, LEVELS.TMP, options and conjured-weapon types',
            ['The whole game']),
    'LEVELS_TMP': ('saves', 'LEVELS.TMP',
                   [('Walls', 'up to 1,200 bytes'), ('Monsters', '900 bytes'), ('Temporary walls', '30 bytes'),
                    ('× 17 records', '2,130 bytes each')],
                   ['Write a level’s record when the party leaves it', 'Read it back when the party returns',
                    'Copied whole into saved games'],
                   'The walls, monster slots and temporary walls of the level',
                   ['Level changes', 'Saved games']),
    'EOSPREFS_DAT': ('saves', 'EOSPREFS.DAT',
                     [('Display mode', 'word'), ('Sound driver', 'word'), ('Mouse', 'word')],
                     ['Read once at start-up; without it, the game returns to DOS'],
                     'The display mode, sound driver and control mode',
                     ['Display driver', 'ADL or SND files', 'Mouse or keyboard control']),
}


def wrap(s, width):
    return textwrap.wrap(s, width) or ['']


def file_figure(name, spec):
    family, title, parts, steps, memory, users = spec
    W = 700
    cols = [(20, 150), (190, 170), (380, 150), (550, 130)]
    heads = ['The file', 'What the game does', 'In memory', 'Used by']
    rows = max(len(parts) * 44, sum(len(wrap(s, 24)) * 15 + 14 for s in steps), len(wrap(memory, 22)) * 15 + 20,
               len(users) * 40)
    H = 90 + rows + 30
    desc = (f'From the file {title} to the game. The file holds, in order: ' +
            '; '.join(f'{p} ({s})' for p, s in parts) + '. The game: ' + '; '.join(steps) + '. In memory: ' + memory +
            '. Used by: ' + ', '.join(users) + '.')
    out = frame(W, H, f'{title}: from the file to the game', desc,
                'The parts of the file, what the game does with them, what they become and who uses them.')
    for (x, w), h in zip(cols, heads):
        out.append(text(x, 74, h, 11.5, INK2, True))
    y0 = 86
    x, w = cols[0]
    for k, (p, s) in enumerate(parts):
        y = y0 + k * 44
        out.append(f'<rect x="{x}" y="{y}" width="{w}" height="40" fill="{PALE}" stroke="{BLUE}"/>')
        out.append(text(x + 8, y + 14, p, 11, INK, True))
        out.append(text(x + 8, y + 29, s, 10, INK2))
    x, w = cols[1]
    y = y0
    for k, s in enumerate(steps):
        ls = wrap(s, 26)
        h = len(ls) * 15 + 10
        out.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="6" fill="{SURF}" stroke="{INK2}"/>')
        for j, l in enumerate(ls):
            out.append(text(x + 8, y + 12 + j * 15, l, 10.5, INK))
        if k < len(steps) - 1:
            arrow(out, f'M{x + w / 2},{y + h} L{x + w / 2},{y + h + 12}')
        y += h + 14
    x, w = cols[2]
    ls = wrap(memory, 23)
    h = len(ls) * 15 + 14
    out.append(f'<rect x="{x}" y="{y0}" width="{w}" height="{h}" rx="6" fill="{BLUE}"/>')
    for j, l in enumerate(ls):
        out.append(text(x + 8, y0 + 14 + j * 15, l, 10.5, '#ffffff'))
    x, w = cols[3]
    for k, u in enumerate(users):
        y = y0 + k * 40
        ls = wrap(u, 21)
        out.append(f'<rect x="{x}" y="{y}" width="{w}" height="34" rx="6" fill="{SHADE}" stroke="{GRID}"/>')
        for j, l in enumerate(ls[:2]):
            out.append(text(x + 8, y + 17 + (j - (min(len(ls), 2) - 1) / 2) * 13, l, 10, INK))
    arrow(out, f'M{cols[0][0] + cols[0][1] + 2},{y0 + 20} L{cols[1][0] - 3},{y0 + 20}')
    arrow(out, f'M{cols[1][0] + cols[1][1] + 2},{y0 + 20} L{cols[2][0] - 3},{y0 + 20}')
    arrow(out, f'M{cols[2][0] + cols[2][1] + 2},{y0 + 20} L{cols[3][0] - 3},{y0 + 20}')
    write(FILES / family / 'img', f'file-{name.lower().replace("_", "-")}.svg', out)


def when_read():
    groups = [('At start-up', ['EOSPREFS.DAT: the settings', 'PALETTE.COL', 'The fonts: FONT6, FONT8',
                               'The introduction, FADING.DAT', 'MENU.CPS: the start menu']),
              ('At each level load', ['LEVELn.INF', 'The map: LEVELn.MAZ', 'Dungeon style: VCN, VMP, PAL',
                                      'Decoration images and DEC', 'Door and monster images, DCR', 'Sound: ADL or SND',
                                      'The level record, LEVELS.TMP']),
              ('When needed', ['TEXT.DAT: dialogues, parchments', 'Dialogue and scene pictures',
                               'EOBDATA<n>.SAV: save, load', 'FINAL.SAV, the ending, CREDITS.TXT'])]
    W, H = 700, 340
    desc = ('When the game reads its files. At start-up: EOSPREFS.DAT, PALETTE.COL, the two fonts, the introduction '
            'with its pictures, palettes and FADING.DAT, and the start menu picture. At each level load: the level’s '
            'INF file, its MAZ map, the VCN, VMP and PAL files of its dungeon style, its decoration images and DEC '
            'file, its door and monster images with their DCR files, its ADL or SND file, and its record in '
            'LEVELS.TMP. When needed: TEXT.DAT for dialogues and parchments, the dialogue and scene pictures, the '
            'saved games, and at the end FINAL.SAV, the ending and CREDITS.TXT.')
    out = frame(W, H, 'When the game reads its files', desc,
                'Most files are read when a level is loaded; a few at start-up, the rest when they are needed.')
    for k, (head, items) in enumerate(groups):
        x = 20 + k * 225
        out.append(f'<rect x="{x}" y="70" width="210" height="{H - 90}" rx="8" fill="{SURF}" stroke="{GRID}"/>')
        out.append(text(x + 12, 90, head, 12.5, DARK, True))
        for j, it in enumerate(items):
            y = 108 + j * 28
            ls = wrap(it, 34)
            out.append(f'<rect x="{x + 10}" y="{y}" width="190" height="24" rx="4" fill="{PALE}"/>')
            assert len(ls) == 1, it
            out.append(text(x + 18, y + 12, it, 10, INK))
    write(FILES / 'img', 'files-when-read.svg', out)


def sound_family():
    W, H = 700, 350
    desc = ('How a sound reaches the card. A level\u2019s INF file, or the sequence being played, names one of ten '
            'sound names; the sound driver of EOSPREFS.DAT chooses the .ADL file of that name for the AdLib card, '
            'or the .SND file for the PC speaker or the Tandy chip. One file is loaded at a time. When the game '
            'plays a sound number from 0 to 119, the sound-effect table of the loaded file gives the program to '
            'start, and the driver plays it.')
    out = frame(W, H, 'Sound and music: from a name to a program', desc,
                'One file is loaded at a time; its table turns the game\u2019s sound numbers into programs.')
    out.append(text(20, 76, 'Loading', 11.5, INK2, True))
    box(out, 20, 108, 170, 52, 'LEVELn.INF or the\nsequence: a sound name')
    box(out, 240, 88, 160, 40, 'NAME.ADL\nAdLib card', 'state', 10.5)
    box(out, 240, 140, 160, 40, 'NAME.SND\nPC speaker or Tandy', 'state', 10.5)
    arrow(out, 'M190,134 L214,134 L214,108 L238,108')
    arrow(out, 'M214,134 L214,160 L238,160')
    box(out, 240, 196, 160, 34, 'EOSPREFS.DAT: sound driver', 'end', 10)
    arrow(out, 'M320,196 L320,182', dash=True)
    out.append(text(408, 214, 'chooses one of the two', 10.5, INK2))
    box(out, 450, 100, 230, 64, 'Sound-effect table (120 entries)\nand programs, in memory', 'strong', 11)
    arrow(out, 'M400,108 L448,120')
    arrow(out, 'M400,160 L448,146')
    out.append(text(20, 250, 'Playing', 11.5, INK2, True))
    steps = [('Sound number\n0 to 119', 'step'), ('Entry of the\ntable', 'state'), ('Program', 'state'),
             ('The driver\nplays it', 'end')]
    x = 20
    for k, (label, kind) in enumerate(steps):
        box(out, x, 262, 140, 52, label, kind, 11)
        if k < len(steps) - 1:
            arrow(out, f'M{x + 140},288 L{x + 178},288')
        x += 180
    out.append(text(20, 332, '255 in a table plays nothing; the .SND files hold no music.', 10.5, INK2))
    write(FILES / 'sound' / 'img', 'sound-family.svg', out)


def dungeon_graphics_family():
    W, H = 700, 330
    rows = [('Dungeon style: tile set (.VCN),\nwall layouts (.VMP), palette (.PAL)', 'Walls, floor and ceiling'),
            ('Decoration images and\ntheir .DEC list', 'Wall decorations'),
            ('Door image', 'Doors'),
            ('Up to two monster images,\nsome with a .DCR list', 'Monsters and their decorations')]
    desc = ('What a level draws with. Each sublevel record of the level\u2019s INF file names its graphics: a dungeon '
            'style, whose tile set (.VCN), wall layouts (.VMP) and palette (.PAL) draw the walls, floor and ceiling '
            'of the view; decoration images with their .DEC list, for the wall decorations; a door image; and up to '
            'two monster images, some with a .DCR list of monster decorations. Everything is drawn with the '
            'level\u2019s palette.')
    out = frame(W, H, 'Dungeon graphics: what a level draws with', desc,
                'The INF file names the graphics; the view draws them with the level\u2019s palette.')
    for x, head in ((20, 'Named by'), (190, 'Files'), (480, 'In the view')):
        out.append(text(x, 76, head, 11.5, INK2, True))
    box(out, 20, 88, 140, 222, 'LEVELn.INF,\neach sublevel\nrecord')
    for k, (files, use) in enumerate(rows):
        y = 88 + k * 58
        box(out, 190, y, 250, 48, files, 'state', 10.5)
        box(out, 480, y, 200, 48, use, 'end', 11)
        arrow(out, f'M160,{y + 24} L188,{y + 24}')
        arrow(out, f'M440,{y + 24} L478,{y + 24}')
    write(FILES / 'dungeon-graphics' / 'img', 'dungeon-graphics-family.svg', out)


def images_family():
    uses = [('Monster images', 29, 'level'), ('Dialogue pictures', 24, 'script'), ('Introduction', 13, 'seq'),
            ('Ending', 13, 'seq'), ('Wall decoration images', 12, 'level'), ('Portraits and interface', 12, 'ui'),
            ('Scenes and screens', 7, 'seq'), ('Named nowhere', 4, 'none'), ('Door images', 2, 'level')]
    assert sum(n for _, n, _ in uses) == 116
    colours = {'level': BLUE, 'script': LIGHT, 'seq': ORANGE, 'ui': GREEN, 'none': '#b9b8b3'}
    keys = [('level', 'Loaded with a level'), ('script', 'Shown by a script'), ('seq', 'Sequences and scenes'),
            ('ui', 'Menus, play screen'), ('none', 'Not used')]
    W, H = 700, 120 + len(uses) * 26
    desc = ('The 116 .CPS pictures of the game by use: ' +
            '; '.join(f'{u}, {n}' for u, n, _ in uses) + '. The monster, decoration and door images are loaded with a level; '
            'the dialogue pictures are shown by the level scripts; the introduction, ending and scene pictures by the sequences; the portraits and '
            'interface by the menus and the play screen; four pictures are named nowhere.')
    out = frame(W, H, 'The 116 pictures, by use', desc, 'Every picture is a .CPS file that unpacks to 320 × 200 pixels.')
    x0, scale, y = 190, 15, 82
    x = 20
    for key, label in keys:
        out.append(f'<rect x="{x}" y="{y - 6}" width="12" height="12" rx="2" fill="{colours[key]}"/>')
        out.append(text(x + 18, y, label, 10.5, INK2))
        x += 18 + len(label) * 5.6 + 22
    y = 108
    for use, n, key in uses:
        out.append(text(x0 - 10, y + 9, use, 11, INK, None, 'end'))
        out.append(f'<rect x="{x0}" y="{y}" width="{n * scale}" height="18" rx="3" fill="{colours[key]}"/>')
        out.append(text(x0 + n * scale + 6, y + 9, str(n), 11, INK2))
        y += 26
    write(FILES / 'images' / 'img', 'images-family.svg', out)


def texts_family():
    rows = [('TEXT.DAT', '122 texts: conversations, scenes,\nparchments', 'The dialogue screen and\nthe parchment reader'),
            ('LEVELn.INF', '456 strings: messages, prompts\nand answers of the scripts', 'The scripts of each level'),
            ('ITEM.DAT', '123 item names, before and\nafter identification', 'Inventory, character sheet,\nmessages'),
            ('START.EXE', 'About 590 strings: captions,\ncredits, menus, names', 'The game\u2019s own routines')]
    desc = ('Where the game\u2019s texts are and what shows them. TEXT.DAT holds 122 texts, conversations, scenes '
            'and parchments, shown by the dialogue screen and the parchment reader. The 16 level files hold 456 '
            'strings, the messages, prompts and answers of their scripts. ITEM.DAT holds 123 item names, before and '
            'after identification, shown by the inventory, the character sheet and the messages. The executable '
            'holds about 590 strings, used by the game\u2019s own routines.')
    W, H = 700, 330
    out = frame(W, H, 'Texts: where they are and what shows them', desc,
                'Four places hold every text the player can see; this book counts them and quotes none.')
    for x, head in ((20, 'File'), (170, 'What it holds'), (470, 'Shown by')):
        out.append(text(x, 76, head, 11.5, INK2, True))
    for k, (name, held, shown) in enumerate(rows):
        y = 88 + k * 58
        box(out, 20, y, 120, 48, name, 'strong', 11)
        box(out, 170, y, 260, 48, held, 'state', 10.5)
        box(out, 470, y, 210, 48, shown, 'end', 10.5)
        arrow(out, f'M140,{y + 24} L168,{y + 24}')
        arrow(out, f'M430,{y + 24} L468,{y + 24}')
    write(FILES / 'texts' / 'img', 'texts-family.svg', out)


if __name__ == '__main__':
    for n, s in SPECS.items():
        file_figure(n, s)
    when_read()
    sound_family()
    dungeon_graphics_family()
    images_family()
    texts_family()
