Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

4.0 KB
Raw Blame
#!/usr/bin/env python3
"""Generate every shared Tux mood and its immutable per-cell colours."""
import argparse
import json
import math
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT.parent / 'prototype/habitat/assets/tux/moods.json'
OUTPUT = ROOT / 'main/ui/habitat/tux_moods.inc'
MOODS = ('idle', 'working', 'attention', 'done', 'offline', 'asleep', 'booped', 'listening')


def rgb(value):
    return [int(value[i:i + 2], 16) for i in (1, 3, 5)]


def mix(a, b, weight):
    # Math.round, as used by daemons/tools/bake.mjs individualColor.
    return [math.floor(x + (y - x) * weight + 0.5) for x, y in zip(a, b)]


def color(asset, row, rows, ch, mat):
    bg = rgb(asset['background'])
    if ch == ' ':
        value = bg
    else:
        assert mat in '.mae', 'Unknown material in Tux source'
        base = rgb(asset['material_colors'][mat]) if mat != '.' else mix(
            *map(rgb, asset['gradient']), row / (rows - 1) if rows > 1 else 0)
        level = asset['ink'][ch]
        value = mix(base, [255] * 3, level - 1) if level > 1 else mix(bg, base, level)
    r, g, b = value
    return ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)


def generate():
    a = json.loads(SOURCE.read_text())
    frames, starts, counts = [], [], []
    for mood in MOODS:
        starts.append(len(frames)); counts.append(len(a['moods'][mood]))
        frames.extend(a['moods'][mood])
    rows = len(frames[0]['rows'].splitlines())
    cols = len(frames[0]['rows'].splitlines()[0])
    assert 1 <= rows <= 24 and 7 <= cols <= 54
    eye = mix(rgb(a['gradient'][0]), [255] * 3, .35)
    face_ink = ((eye[0] >> 3) << 11) | ((eye[1] >> 2) << 5) | (eye[2] >> 3)
    out = [
        '// Generated by gen_tux_moods.py from the pinned Tux model; all eight Habitat moods.',
        f'// Seed {a["traits"]["seed"]}: {a["flags"]}.',
        f'enum {{ TUX_ROWS = {rows}, TUX_COLS = {cols}, TUX_FRAMES = {len(frames)} }};',
        f'enum {{ TUX_FACE_INK = 0x{face_ink:04x} }};',
        'static const char tux_rows[TUX_FRAMES][TUX_ROWS][TUX_COLS + 1] = {',
    ]
    colors, landmarks = [], []
    for f in frames:
        lines, mats = f['rows'].splitlines(), f['mats'].splitlines()
        assert len(lines) == len(mats) == rows
        palette = []
        out.append('    {')
        for r, (line, mat) in enumerate(zip(lines, mats)):
            assert len(line) == len(mat) == cols
            assert all(32 <= ord(c) <= 126 for c in line)
            out.append('        ' + json.dumps(line) + ',')
            palette.append([color(a, r, rows, c, m) for c, m in zip(line, mat)])
        out.append('    },'); colors.append(palette)
        points = [*f['eyes'], f['beak']]
        assert all(3 <= x < cols - 3 and 0 <= y < rows for x, y in points)
        landmarks.append([n for p in points for n in p])
    out += ['};', 'static const uint16_t tux_colors[TUX_FRAMES][TUX_ROWS][TUX_COLS] = {']
    for f in colors:
        out.append('    {')
        out.extend('        {' + ','.join(f'0x{c:04x}' for c in row) + '},' for row in f)
        out.append('    },')
    out += ['};', 'static const uint8_t tux_landmarks[TUX_FRAMES][6] = {']
    out.extend('    {' + ','.join(map(str, v)) + '},' for v in landmarks)
    out += ['};', 'static const uint8_t tux_starts[HT_CHARACTER_MOODS] = {' + ','.join(map(str, starts)) + '};',
            'static const uint16_t tux_ends[] = {' + ','.join(str((i + 1) * a['frame_ms']) for i in range(max(counts))) + '};',
            'static const ht_character_animation_t tux_animations[HT_CHARACTER_MOODS] = {']
    out.extend(f'    {{{n}, {n * a["frame_ms"]}, tux_ends}},' for n in counts)
    return '\n'.join(out + ['};', ''])


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('--check', action='store_true')
    args = parser.parse_args(); result = generate()
    if args.check:
        if not OUTPUT.exists() or OUTPUT.read_text() != result: raise SystemExit('Tux moods are stale')
    else: OUTPUT.write_text(result)
    print('Tux: all eight shared moods, 36 frames, registered eyes/beak and RGB565 colours')