Cotton code
268 lines · 13.5 KB · PythonRaw
#!/usr/bin/env python3"""Put the music's painted materials into the Loom package's catalogue.    python3 scripts/import-music-materials.py <object> [<materials directory>]    python3 scripts/import-music-materials.py all [<materials directory>]    python3 scripts/import-music-materials.py party <music12-faces directory>    python3 scripts/import-music-materials.py amp <music12-faces directory>    python3 scripts/import-music-materials.py tray <music21-tray directory>    python3 scripts/import-music-materials.py doors [<doors15 directory>]The layers were painted with Codex (4 Nov 2026, Round 11, after the dark-roompictures the owner chose, `music10-darkroom`) and cut out of wordless masters;the directory (`music11-materials`) holds them with `layout.json`, whichplaces each in its object's box, in its pixels. No word, numeral or figure ison any of them: the faces draw those live. One function per object, so eachMusic face job imports the objects it draws and a layer two faces share (thesleeve, under the album and leaning over the hi-fi) is imported once.    sleeve   the 12-inch sleeve (CottonFaces' `Cotton/SongHifiFace.swift`             leans it over the deck; the album's face lays it whole)        sleeve-front    the worn frame, its cover's aperture cut through it        sleeve-blank    the black stock with its cream double rule, laid in                        the aperture where the album has no cover        sleeve-back     the wordless back, two cream rules        sleeve-shadow   its shadow, larger than the sleeve    ground   the dark room every Music face stands in (`FaceGround.tolex`,             laid by `FaceGroundSurface`)        tolex           the black pebbled tolex, a seamless tile (JPEG)        lamp-glow       the warm pool the one lamp casts, laid once upper left    hifi     the black hi-fi deck (`Cotton/SongHifiFace.swift`)        hifi-plate      the brushed plate, its meters' windows cut through it        hifi-meter      one wordless cream meter card, laid twice        hifi-needle     one meter needle, upright, its pivot at its foot        hifi-knob       the brass time knob, its mark at twelve        hifi-ticks      the cream tick ring round it        hifi-jewel-on   the red jewel, lit (playing)        hifi-jewel-off  the same jewel, dark (paused)        hifi-shadow     the deck's shadow, larger than the plate    single   the 7-inch in its paper sleeve (`Cotton/SongSingleFace.swift`)        single-sleeve-cream  the cream paper sleeve, its round window cut                        through it        single-sleeve-blue   the same sleeve in blue paper, the same window        single-record   the seven-inch record, its label's round cut out        single-label-blank   the cream label, its spindle hole cut out        single-shadow   the sleeve's shadow, larger than the sleeve    divider  the artist's divider in its crate (`Cotton/ArtistDividerFace.swift`)        crate           the empty black crate, front and inside        divider         the black fibre divider card and its raised tab        spine-blank     one album's spine, blank stock the face tints        divider-shadow  the divider's shadow, larger than the card    turntable  the record turning on its slipmat (`Cotton/SongTurntableFace.swift`;             its jewel is the hi-fi's, `tt-jewel-on`/`-off` being the same             files, so they are not imported twice)        slipmat         the black felt mat, top view        record          the twelve-inch record, its label's round cut out        label-blank     the cream label, its spindle hole cut out        spindle         the brass spindle        tonearm         the brass arm at the outer groove, its pivot upper right        tonearm-shadow  the arm's shadow, larger than the arm    party    the turntable on a dance floor under party lights             (`Cotton/SongPartyFace.swift`; Round 12, `music12-faces`, so             `all` does not import it: name its directory; the record, mat,             arm, spindle and jewel are the turntable's)        floor           the dark wood dance floor, a seamless tile (JPEG),                        `FaceGround.partyFloor`'s surface        party-lights    the warm bokeh discs, laid over the floor and drifted        party-glow      the one warm reflection streak over the record, still        party-label-blank  the black label with its red and cream rings, its                        spindle hole cut out    amp      the guitar-amp head (`Cotton/SongAmpFace.swift`; Round 12,             `music12-faces`, so `all` does not import it: name its             directory; behind its grille the turntable's record and label)        amp-frame       the tolex cabinet, its panel's and grille's                        apertures cut through it        amp-panel       the cream enamel panel and its black strip, wordless        amp-ticks       the dark tick arc over the big knob        amp-knob-big    the big brass knob, its mark at twelve (the clock)        amp-knob-small  the small brass knob, laid twice (volume, tone)        amp-grille      the woven cloth, its gaps alpha, the record behind it        amp-jewel-on    the orange pilot lamp, lit (playing), held to                        `AMP_JEWEL` pixels        amp-jewel-off   the same lamp, dark (paused)        amp-shadow      the cabinet's shadow, larger than the frame    tray     the clear acrylic tray a record rests on, its short square-cut             arm and the cover's strip along its foot (`Cotton/AlbumTrayFace.swift`:             `album.tray`, `song.tray`; Round 23, `music23-acrylic-tray`, Round             21's placements with the tray, rail and arm repainted, so `all` does             not import it: name its directory; the strip's blank is Round 21's,             `music21-tray`, which Round 23's layout names; the record, label,             spindle, jewel, 7-inch and its label are Round 11's). Sizes as             painted, 4x the tray's 300 x 400 point phone box:        tray            the acrylic slab round an inset satin base, its faint                        round well and rail; its lip partly clear, so the                        ground shows through it (1200 x 1600)        tray-shadow     its shadow, the tray's silhouette blurred                        (1344 x 1744, laid from -72, -72)        tray-ledge      the clear rail at the tray's foot, laid over the                        strip's lower edge (1024 x 26)        strip-blank     the strip's black card and its thin cream rule, the                        cover and the cream panel laid in it live (1096 x 256)        tray-arm        the satin square-section arm on its square pivot                        block, at the outer groove (263 x 843)        tray-arm-shadow the arm's shadow, its silhouette blurred (311 x 891)Each is at least 3x the most it is drawn at on a phone, declared 3x (2x onthe Mac) as the card paper is; the faces set the frame they draw each at.The places the faces read off `layout.json` and off the paint (the meters'marks, the knob's sweep, the divider's tab and the crate's lip, the arm'spivot and grooves, the amp's ticks) are their knobs (`SongHifiFaceKnobs`,`SongSingleFaceKnobs`, `ArtistDividerFaceKnobs`, `SongTurntableFaceKnobs`,`SongPartyFaceKnobs`, `SongAmpFaceKnobs`, `AlbumTrayFaceKnobs`): a repainted layer owes new ones."""import jsonimport pathlibimport subprocessimport sysHERE = pathlib.Path(__file__).resolve().parentCATALOGUE = HERE.parent / 'apps/loom/Sources/CottonPaper/Media.xcassets'DEFAULT = pathlib.Path.home() / 'lanes/_refs/music/music11-materials'# The amp's jewels are painted 1024 pixels square for a lamp drawn some 21# points wide: held to 256, still twelve times that.AMP_JEWEL = 256def imageset(name, extension):    folder = CATALOGUE / f'{name}.imageset'    folder.mkdir(exist_ok=True)    for old in folder.iterdir():        old.unlink()    contents = {        'images': [            {'filename': f'{name}.{extension}', 'idiom': 'universal', 'scale': '3x'},            {'filename': f'{name}.{extension}', 'idiom': 'mac', 'scale': '2x'},        ],        'info': {'author': 'xcode', 'version': 1},        'properties': {'preserves-vector-representation': False},    }    (folder / 'Contents.json').write_text(json.dumps(contents, indent=2) + '\n')    return folder / f'{name}.{extension}'def put(source, names, widest=None):    """Each of `names`, the one picture of that name in `source`, into the catalogue; its size.    `widest` holds a name to that many pixels on its longer side (macOS's    `sips`), for a layer painted far larger than it is ever drawn."""    total = 0    widest = widest or {}    for name in names:        found = [source / f'{name}.{extension}' for extension in ('png', 'jpg') if (source / f'{name}.{extension}').exists()]        if len(found) != 1:            sys.exit(f'{source} holds {len(found)} pictures named {name}, not one')        picture = found[0]        target = imageset(name, picture.suffix[1:])        if name in widest:            subprocess.run(['sips', '-Z', str(widest[name]), str(picture), '--out', str(target)], check=True, capture_output=True)        else:            target.write_bytes(picture.read_bytes())        total += target.stat().st_size        print(f'{picture.name} -> {name}')    return totaldef ground(source):    return put(source, ['tolex', 'lamp-glow'])def sleeve(source):    return put(source, ['sleeve-front', 'sleeve-blank', 'sleeve-back', 'sleeve-shadow'])def hifi(source):    return put(source, [        'hifi-plate', 'hifi-meter', 'hifi-needle', 'hifi-knob', 'hifi-ticks', 'hifi-jewel-on', 'hifi-jewel-off',        'hifi-shadow',    ])def single(source):    return put(source, ['single-sleeve-cream', 'single-sleeve-blue', 'single-record', 'single-label-blank', 'single-shadow'])def divider(source):    return put(source, ['crate', 'divider', 'spine-blank', 'divider-shadow'])def turntable(source):    return put(source, ['slipmat', 'record', 'label-blank', 'spindle', 'tonearm', 'tonearm-shadow'])def party(source):    return put(source, ['floor', 'party-lights', 'party-glow', 'party-label-blank'])def amp(source):    return put(source, [        'amp-frame', 'amp-panel', 'amp-ticks', 'amp-knob-big', 'amp-knob-small', 'amp-grille', 'amp-jewel-on',        'amp-jewel-off', 'amp-shadow',    ], widest={'amp-jewel-on': AMP_JEWEL, 'amp-jewel-off': AMP_JEWEL})def tray(source):    """Round 23's clear acrylic tray, rail and square-cut arm, and the strip's blank its layout reuses from Round 21."""    total = put(source, ['tray', 'tray-shadow', 'tray-ledge', 'tray-arm', 'tray-arm-shadow'])    strip = json.loads((source / 'layout.json').read_text())['layers']['strip-blank.png'].get('file')    return total + put((source / strip).parent if strip else source, ['strip-blank'])# THE MUSIC DOORS' PICTURES (Round 15, 4 Nov 2026): Plus's two doors on the# Music decks, painted wordless: an edge-on stack of 7-inch singles in their# paper sleeves (Add files) and a small empty black record crate (Add a# folder). Each is laid over its own separate shadow (`<name>-shadow.png`,# `layout.json`'s shadowOffset) and kept once as an act picture# (`act-<object>`, one of the core's ACT_OBJECTS) at the act objects' size,# exactly as Books' doors are (`import-books-materials.py doors`). Requires# Pillow.DOORS = {'music-files': 'singles', 'music-folder': 'crate'}ACT_SIDE = 360DOORS_DEFAULT = '/Volumes/Cotton SSD/lanes/features/out/doors15'def doors(source):    from PIL import Image    source = pathlib.Path(source)    layout = json.loads((source / 'layout.json').read_text())['layers']    for painted, object_name in DOORS.items():        name = f'act-{object_name}'        if (CATALOGUE / f'{name}.imageset').exists():            sys.exit(f'{name} is in the catalogue already: nothing is imported twice')        shadowed = layout[f'{painted}-shadow.png']        dx, dy = (-offset for offset in shadowed['shadowOffset'])        with Image.open(source / f'{painted}-shadow.png') as shadow, Image.open(source / f'{painted}.png') as picture:            laid = shadow.convert('RGBA')            picture = picture.convert('RGBA')            if picture.getchannel('A').getextrema()[0] != 0:                sys.exit(f'{painted}: requires a transparent background')            laid.alpha_composite(picture, (dx, dy))        laid.thumbnail((ACT_SIDE, ACT_SIDE), Image.Resampling.LANCZOS)        target = imageset(name, 'png')        laid.save(target, optimize=True)        print(f'{painted} over its shadow -> {name} {laid.size[0]}x{laid.size[1]}')OBJECTS = {'ground': ground, 'sleeve': sleeve, 'hifi': hifi, 'single': single, 'divider': divider, 'turntable': turntable}# Round 12's and Round 21's objects, in their own directories: named one at a# time, never `all`.LATER = {'party': party, 'amp': amp, 'tray': tray}def main(argv):    if argv and argv[0] == 'doors':        return doors(argv[1] if len(argv) > 1 else DOORS_DEFAULT)    named = {**OBJECTS, **LATER}    if not argv or argv[0] not in [*named, 'all']:        sys.exit(f'import-music-materials: name an object ({", ".join(named)}) or all')    if argv[0] in LATER and len(argv) < 2:        sys.exit(f'import-music-materials: {argv[0]} is a later round\'s: name its directory (music12-faces, music23-acrylic-tray)')    source = pathlib.Path(argv[1]) if len(argv) > 1 else DEFAULT    chosen = OBJECTS.values() if argv[0] == 'all' else [named[argv[0]]]    total = sum(object_(source) for object_ in chosen)    print(f'{total // 1024} KB in all')if __name__ == '__main__':    main(sys.argv[1:])