#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """Compile the approved SVG artwork to cropped native PDF layers. Requires Python 3 and Homebrew librsvg, only when editing artwork; Xcode uses committed PDFs. --author-master rebuilds the production master from approved sources. Ordinary invocations compile the editable production master as-is. """ from pathlib import Path import copy, ctypes as C, ctypes.util, json, re, subprocess, argparse import xml.etree.ElementTree as E ROOT=Path(__file__).resolve().parents[3] MEDIA=ROOT/'docs/media'; OUT=ROOT/'platforms/macos/Resources/Hardware' S='http://www.w3.org/2000/svg'; E.register_namespace('',S) def tag(n): return '{'+S+'}'+n def get(r,id): return next(e for e in r.iter() if e.get('id')==id) def clone(e): return copy.deepcopy(e) def group(id,**attrs): return E.Element(tag('g'),{'id':id,**attrs}) def remove(r,e): for p in r.iter(): if e in list(p): p.remove(e);return def author(): proposal=E.parse(MEDIA/'proposal/stacked-system.svg').getroot() scene=next(e for e in proposal if any(c.get('id')=='system-cassette-installed' for c in e)) xml=E.tostring(scene,encoding='unicode').replace('system-','') scene=E.fromstring(xml);scene.attrib={} r=E.Element(tag('svg'),{'viewBox':'-120 0 960 457','width':'960','height':'457'}) r.extend(list(scene)) defs=r.find(tag('defs')) original=E.parse(MEDIA/'tandy-color-computer-3-full-system.svg').getroot() # Namespaced source controllers provide actual projected geometry at all depths. originals=E.fromstring(E.tostring(original,encoding='unicode').replace('id="','id="source-').replace('url(#','url(#source-')) defs.extend(clone(originals.find(tag('defs')))) virt=E.parse(MEDIA/'tandy-color-computer-3-virtual-system.svg').getroot() # Remove all static sample pixels. Screen aperture is occupied by live Metal. remove(r,get(r,'basic-startup-screen')) for e in get(r,'monitor'): if e.get('fill')=='#00ff00':e.set('fill','#000000') for e in get(r,'glass-edge'):e.set('stop-color','#07100a') get(r,'monitor').set('data-runtime-part','monitor') get(r,'multi-pak-installed').set('data-runtime-when','mpi=on') get(r,'mpi-slot-population').set('data-runtime-when','mpi=on') get(r,'mpi-slot-population').attrib.pop('data-max-drive-controllers',None) for id,key in [('computer-ram-options','ram'),('computer-processor-badges','cpu'),('mpi-selector-positions','startup')]: for e in get(r,id): if e.tag!=tag('g'):continue suffix=e.get('id').removeprefix('computer-ram-') if key=='ram' else ('6309' if 'hitachi' in e.get('id') else '6809') if key=='cpu' else e.get('data-slot') e.set('data-runtime-when',key+'='+suffix);e.set('style','display:none') for e in list(r.iter()): if e.get('data-ui-role')=='media-state': parent=next(p for p in r.iter() if e in list(p)) id=parent.get('id'); key='tape' if id=='cassette-media' else id.removeprefix('vds-').removesuffix('-media') e.set('data-runtime-when',key+'='+e.get('data-state'));e.set('style','display:none') if e.get('data-ui-role')=='activity-led': key=e.get('id').replace('cassette','tape').removeprefix('vds-').removesuffix('-activity-led')+'Activity' for c in e: if c.get('data-state'): c.set('data-runtime-when',key+'='+c.get('data-state'));c.set('style','display:none') for id,key in [('stack-hard','hardCase'),('stack-floppy-low','floppyCase'),('stack-floppy-high','floppyCase')]:get(r,id).set('data-runtime-when',key+'=on') # Both controllers have their own occupancy choice, in every physical slot. # Front labels are affine mapped between projected front faces; bodies use # the original per-slot geometry rather than a flat vertical translation. def labelRect(e): p=next(c for c in e if c.tag==tag('path')) nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',p.get('d')))) return (min(nums[::2]),min(nums[1::2]),max(nums[::2])-min(nums[::2]),max(nums[1::2])-min(nums[1::2])) labels={kind:clone(get(r,f'proposal-slot{n}-fd501-controller-label-artwork')) for kind,n in [('floppy',4),('hard',3)]} for n in range(1,5): parent=get(r,f'mpi-slot-{n}-population');parent.clear();parent.set('id',f'mpi-slot-{n}-population') rom=clone(get(virt,f'mpi-slot-{n}-rom'));rom.set('style','display:none');rom.set('data-runtime-when',f'slot{n}=rom');parent.append(rom) for kind in ['floppy','hard']: card=clone(get(originals,f'source-fd501-controller-slot-{n}')) card.set('id',f'mpi-slot-{n}-{kind}');card.set('style','display:none');card.set('data-runtime-when',f'slot{n}={kind}') old=get(card,f'source-fd501-controller-label-artwork-slot-{n}') a=labelRect(labels[kind]);b=labelRect(old) label=clone(labels[kind]);label.set('transform',f'translate({b[0]} {b[1]}) scale({b[2]/a[2]} {b[3]/a[3]}) translate({-a[0]} {-a[1]})') # Unique identifiers for all cloned descendants and referenced gradients. for e in card.iter(): if e.get('id') and e is not card:e.set('id',f'{kind}-{n}-'+e.get('id')) remove(card,old) for e in label.iter(): if e.get('id'):e.set('id',f'{kind}-{n}-'+e.get('id')) card.append(label);parent.append(card) # Original proposal routes consist of 17 paths each. Warp only the near # endpoint to each real slot, holding the far stack endpoint fixed. ribbons=get(r,'proposal-controller-ribbons');paths=list(ribbons);ribbons.clear();ribbons.set('id','controller-routes') coords={1:(421.0,238.0),2:(414.9,220.0),3:(408.0,204.0),4:(401.0,189.0)} for kind,base,start in [('hard',3,0),('floppy',4,17)]: for n in range(1,5): g=group(f'{kind}-route-{n}',**{'data-runtime-when':f'slot{n}={kind}'}) dx,dy=coords[n][0]-coords[base][0],coords[n][1]-coords[base][1] for path in paths[start:start+17]: p=clone(path) def warp(m): x,y=float(m[1]),float(m[2]);w=max(0,min(1,(570-x)/160)) return f'{x+dx*w:.4f} {y+dy*w:.4f}' p.set('d',re.sub(r'(-?\d+\.\d+)[ ,](-?\d+\.\d+)',warp,p.get('d')));g.append(p) ribbons.append(g) # Complete hardware is blank until the adapter applies every state. get(r,'cassette-installed').set('data-runtime-when','scene=on') get(r,'joystick-installed').set('data-runtime-when','scene=on') for e in r.iter(): for k in list(e.attrib): if k.startswith('{http://www.inkscape'):del e.attrib[k] # Catch accidental duplicate definitions before compiling any assets. ids=[e.get('id') for e in r.iter() if e.get('id')] assert len(ids)==len(set(ids)), 'Duplicate SVG IDs' E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True) def orchestra(): # Keep the approved per-slot shell/perspective; replace only its front label. r=E.parse(MEDIA/'runtime-system.svg').getroot() master=E.parse(MEDIA/'orchestra-90-label.svg').getroot() defs=r.find(tag('defs')) for e in list(defs): if e.get('id')=='orchestra-silver':defs.remove(e) defs.extend(clone(master.find(tag('defs')))) for n in range(1,5): parent=get(r,f'mpi-slot-{n}-population') for e in list(parent): if e.get('data-runtime-when')==f'slot{n}=orchestra':parent.remove(e) card=clone(get(r,f'mpi-slot-{n}-floppy')) card.set('data-runtime-when',f'slot{n}=orchestra');card.set('data-cartridge','orchestra') housing=next(e for e in card if 'controller-housing-slot' in e.get('id','')) for e in housing.iter(): fill=e.get('fill','') if fill.startswith('url(#source-fd501-controller-'): e.set('fill',{'url(#source-fd501-controller-side)':'#b9ad97','url(#source-fd501-controller-top)':'#f3ead8','url(#source-fd501-controller-front)':'#e2d5bd'}.get(fill,'#d1c4ab')) if e.get('stroke'):e.set('stroke','#b2a48b') # Replace the controller's top recess with the two real RCA sockets. # Project the entire socket into the top plane, including its circular rings. # The rear edge shifts left, following the housing's receding side edge. top=list(housing)[2] nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',top.get('d')))) tx,ty=min(nums[::2]),min(nums[1::2]);tw,th=max(nums[::2])-tx,max(nums[1::2])-ty side=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',list(housing)[1].get('d')))) slope=(side[0]-side[2])/(side[7]-side[5]) for e in list(housing): if e.get('fill') in ['#0c181c','#4f5958']:housing.remove(e) sockets=E.SubElement(housing,tag('g'),{'id':f'rca-sockets-{n}','aria-label':'Left and right RCA audio sockets'}) for fraction in [.43,.64]: cx,cy=tx+tw*fraction,ty+th*.5 width,depth=tw*.13,th*.48 socket=E.SubElement(sockets,tag('g'),{'transform':f'matrix({width} 0 {depth*slope} {depth} {cx} {cy})'}) E.SubElement(socket,tag('rect'),{'x':'-.5','y':'-.5','width':'1','height':'1','rx':'.06','fill':'#483d2a'}) E.SubElement(socket,tag('circle'),{'r':'.36','fill':'#c7a75f','stroke':'#826c3e','stroke-width':'.035'}) E.SubElement(socket,tag('circle'),{'r':'.22','fill':'#171b1c'}) label=next(e for e in card if e.get('id','').endswith('controller-label-artwork')) paths=[e for e in label if e.tag==tag('path')] paper=paths[2] nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',paper.get('d')))) x,y=min(nums[::2]),min(nums[1::2]);w,h=max(nums[::2])-x,max(nums[1::2])-y frames=[clone(e) for e in paths[:2]] transform=label.get('transform','') label.clear();label.set('id',f'controller-slot-{n}-label');label.set('transform',transform);label.extend(frames) artwork=E.SubElement(label,tag('g'),{'transform':f'translate({x} {y}) scale({w/480} {h/280})'}) artwork.extend(clone(e) for e in master if e.tag not in [tag('defs'),tag('title'),tag('desc')]) for e in card.iter(): if e.get('id'):e.set('id','orchestra-'+e.get('id')) if e.tag==tag('title'):e.text='Orchestra-90 stereo music cartridge' parent.insert(1,card) ids=[e.get('id') for e in r.iter() if e.get('id')] assert len(ids)==len(set(ids)), 'Duplicate SVG IDs' E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True) def speech(): # Service-manual shell/label derivative, using the same scene perspective. r=E.parse(MEDIA/'runtime-system.svg').getroot() master=E.parse(MEDIA/'speech-sound-label.svg').getroot() for n in range(1,5): parent=get(r,f'mpi-slot-{n}-population') for e in list(parent): if e.get('data-runtime-when')==f'slot{n}=speech':parent.remove(e) card=clone(next(e for e in parent if e.get('data-runtime-when')==f'slot{n}=orchestra')) card.set('data-runtime-when',f'slot{n}=speech');card.set('data-cartridge','speech') for e in card.iter(): for child in list(e): if 'rca-sockets-' in child.get('id',''):e.remove(child) if e.get('fill') in ['#b9ad97','#f3ead8','#e2d5bd']: e.set('fill',{'#b9ad97':'#aaa99c','#f3ead8':'#e6e5d8','#e2d5bd':'#d5d4c7'}[e.get('fill')]) label=next(e for e in card if e.get('id','').endswith(f'controller-slot-{n}-label')) artwork=next(e for e in label if e.tag==tag('g')) for e in list(artwork):artwork.remove(e) artwork.extend(clone(e) for e in master if e.tag not in [tag('defs'),tag('title'),tag('desc')]) for e in card.iter(): if e.get('id'):e.set('id',e.get('id').replace('orchestra-','speech-')) if e.tag==tag('title'):e.text='Speech/Sound Cartridge' parent.insert(2,card) ids=[e.get('id') for e in r.iter() if e.get('id')] assert len(ids)==len(set(ids)), 'Duplicate SVG IDs' E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True) def sdc(): # Compact smooth shell seated at each existing ROM socket's projected depth. # A separate small lens changes with transfer state; the shell is cached. r=E.parse(MEDIA/'runtime-system.svg').getroot() master=E.parse(MEDIA/'coco-sdc-label.svg').getroot() for n in range(1,5): parent=get(r,f'mpi-slot-{n}-population') for e in list(parent): if e.get('data-runtime-when')==f'slot{n}=sdc':parent.remove(e) rom=get(parent,f'rom-cartridge-slot-{n}-shell') front=next(e for e in rom if e.get('fill')=='url(#rom-shell-front)') nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',front.get('d')))) x,y=min(nums[::2]),min(nums[1::2]);w,h=max(nums[::2])-x,max(nums[1::2])-y bottom=y+h;h*=1.12;y=bottom-h # Receding top edge follows the same slot-dependent depth as the ROM shell. top=next(e for e in rom if e.get('fill')=='url(#rom-shell-top)') nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',top.get('d')))) dx=x-min(nums[::2]);dy=min(float(v) for v in nums[1::2]) originalY=bottom-h/1.12;depth=originalY-dy card=group(f'mpi-slot-{n}-sdc',style='display:none',**{'data-runtime-when':f'slot{n}=sdc','data-cartridge':'sdc','data-slot':str(n)}) E.SubElement(card,tag('title')).text='CoCo SDC SD card cartridge' def path(d,fill,**attrs):return E.SubElement(card,tag('path'),{'d':d,'fill':fill,**attrs}) path(f'M{x} {y+2} L{x-dx} {y-depth+2} L{x-dx} {bottom-depth} L{x} {bottom}Z','url(#rom-shell-side)') path(f'M{x} {y+2} Q{x} {y} {x+2} {y} H{x+w-2} Q{x+w} {y} {x+w-1} {y-2} L{x+w-dx-2} {y-depth} H{x-dx+2} Q{x-dx} {y-depth} {x-dx} {y-depth+2}Z','url(#rom-shell-top)') E.SubElement(card,tag('rect'),{'x':str(x),'y':str(y),'width':str(w),'height':str(h),'rx':'1.8','fill':'url(#rom-shell-front)','stroke':'#11191b','stroke-width':'.5'}) path(f'M{x+2} {y+1} H{x+w-2}','none',stroke='#65706f',**{'stroke-width':'.4'}) path(f'M{x+1.2} {bottom-3} H{x+w-1.2}','none',stroke='#0b1113',**{'stroke-width':'.6'}) label=E.SubElement(card,tag('g'),{'transform':f'translate({x+5} {y+5}) scale({(w-10)/480} {(h*.68)/280})'}) label.extend(clone(e) for e in master if e.tag not in [tag('title'),tag('desc')]) # SD slot visible on the receding top surface. It is decorative, not a picker. slot=E.SubElement(card,tag('g'),{'transform':f'matrix(1 0 {dx/depth} 1 {x} {y})'}) E.SubElement(slot,tag('rect'),{'x':str(w*.32),'y':str(-depth*.68),'width':str(w*.36),'height':str(depth*.28),'rx':'.5','fill':'#090f11','stroke':'#56605e','stroke-width':'.3'}) cx,cy=x+w-8,bottom-7 E.SubElement(card,tag('circle'),{'cx':str(cx),'cy':str(cy),'r':'2','fill':'#0b1114','stroke':'#626967','stroke-width':'.4'}) for state,color in [('empty','#484c50'),('loaded','#2ac65c'),('read','#f49b24'),('write','#e63c36')]: led=E.SubElement(card,tag('g'),{'id':f'sdc-slot-{n}-{state}','data-runtime-when':f'sdcActivity={state}','style':'display:none'}) E.SubElement(led,tag('circle'),{'cx':str(cx),'cy':str(cy),'r':'1.45','fill':color}) E.SubElement(led,tag('ellipse'),{'cx':str(cx-.3),'cy':str(cy-.5),'rx':'.65','ry':'.35','fill':'#ffffff','opacity':'.45'}) parent.append(card) ids=[e.get('id') for e in r.iter() if e.get('id')] assert len(ids)==len(set(ids)), 'Duplicate SVG IDs' E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True) def printer(): # Add the standalone thermal printer last: existing layer indices and scene # coordinates remain unchanged. The editable SVG is the production master; # make-tp10-printer.py assembles its committed shaded shell and state overlays. r=E.parse(MEDIA/'runtime-system.svg').getroot() master=E.parse(MEDIA/'tandy-tp-10-printer.svg').getroot() defs=r.find(tag('defs')) for e in list(defs): if e.get('id','').startswith('tp10-'):defs.remove(e) for e in list(r): if e.get('id')=='tp10-printer':r.remove(e) defs.extend(clone(master.find(tag('defs')))) r.append(clone(get(master,'tp10-printer'))) ids=[e.get('id') for e in r.iter() if e.get('id')] assert len(ids)==len(set(ids)), 'Duplicate SVG IDs' E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True) class Rect(C.Structure):_fields_=[(x,C.c_double) for x in ['x','y','width','height']] def compile_art(): lib=C.CDLL('/opt/homebrew/lib/librsvg-2.dylib' if Path('/opt/homebrew/lib/librsvg-2.dylib').exists() else C.util.find_library('rsvg-2')) lib.rsvg_handle_new_from_data.argtypes=[C.c_char_p,C.c_size_t,C.c_void_p];lib.rsvg_handle_new_from_data.restype=C.c_void_p lib.rsvg_handle_render_document.argtypes=[C.c_void_p,C.c_void_p,C.POINTER(Rect),C.c_void_p] obj=C.CDLL(C.util.find_library('gobject-2.0'));obj.g_object_unref.argtypes=[C.c_void_p] cairo=C.CDLL(C.util.find_library('cairo')) cairo.cairo_image_surface_create.argtypes=[C.c_int,C.c_int,C.c_int];cairo.cairo_image_surface_create.restype=C.c_void_p cairo.cairo_create.argtypes=[C.c_void_p];cairo.cairo_create.restype=C.c_void_p cairo.cairo_image_surface_get_data.argtypes=[C.c_void_p];cairo.cairo_image_surface_get_data.restype=C.c_void_p for method in ['cairo_destroy','cairo_surface_destroy','cairo_surface_flush']:getattr(cairo,method).argtypes=[C.c_void_p] def visible_bounds(handle): # Ink geometry includes zero-area outlined space glyphs and ignores clipping. # Measure actual alpha at 2x solely to crop layers, never as runtime art. width,height=1920,914 surface=cairo.cairo_image_surface_create(0,width,height);context=cairo.cairo_create(surface) assert lib.rsvg_handle_render_document(handle,context,C.byref(Rect(0,0,width,height)),None) cairo.cairo_surface_flush(surface) pixels=C.string_at(cairo.cairo_image_surface_get_data(surface),width*height*4) left,top,right,bottom=width,height,0,0 for y in range(height): row=pixels[(y*width*4)+3:(y+1)*width*4:4] if row.strip(b'\0'): left=min(left,width-len(row.lstrip(b'\0')));right=max(right,len(row.rstrip(b'\0'))) top=min(top,y);bottom=y+1 cairo.cairo_destroy(context);cairo.cairo_surface_destroy(surface) return (left/2-120-.5,top/2-.5,(right-left)/2+1,(bottom-top)/2+1) if right>left else None OUT.mkdir(parents=True,exist_ok=True) source=E.parse(MEDIA/'runtime-system.svg').getroot();defs=source.find(tag('defs')) layers=[] def emit(nodes,ancestors,conditions,part): r=E.Element(tag('svg'),{'viewBox':'-120 0 960 457','width':'960','height':'457'});r.append(clone(defs));p=r for ancestor in ancestors: a=E.Element(tag('g'),{k:v for k,v in ancestor.attrib.items() if k not in ['id','style','data-runtime-when','data-runtime-part']});p.append(a);p=a p.extend(clone(e) for e in nodes) data=E.tostring(r);handle=lib.rsvg_handle_new_from_data(data,len(data),None) bounds=visible_bounds(handle);obj.g_object_unref(handle) if not bounds:return x,y,w,h=bounds r.set('viewBox',f'{x} {y} {w} {h}');r.set('width',str(w));r.set('height',str(h)) filename=f'layer-{len(layers):03d}.pdf' subprocess.run(['rsvg-convert','-f','pdf','-o',str(OUT/filename)],input=E.tostring(r),check=True) layers.append({'file':filename,'bounds':[x,y,w,h],'when':conditions,'part':part}) def walk(e,ancestors,conditions,part): conditions=dict(conditions) if e.get('data-runtime-when'): k,v=e.get('data-runtime-when').split('=');conditions[k]=v part=e.get('data-runtime-part',part) e=clone(e) if e.get('data-runtime-when'):e.set('style','display:inline') dynamic=any(c is not e and (c.get('data-runtime-when') or c.get('data-runtime-part')) for c in e.iter()) if not dynamic:emit([e],ancestors,conditions,part);return batch=[] for c in e: if c.tag in [tag('title'),tag('desc'),tag('metadata')]:continue if any(d.get('data-runtime-when') or d.get('data-runtime-part') for d in c.iter()): if batch:emit(batch,ancestors+[e],conditions,part);batch=[] walk(c,ancestors+[e],conditions,part) else:batch.append(c) if batch:emit(batch,ancestors+[e],conditions,part) for c in source: if c.tag==tag('g'):walk(c,[],{},'scene') (OUT/'layers.json').write_text(json.dumps(layers,indent=2)+'\n') # Freestanding desk reference control, composed separately from emulated hardware. subprocess.run(['rsvg-convert','-f','pdf','-o',str(OUT/'manual-help.pdf'),str(MEDIA/'manual-help.svg')],check=True) # Standalone, unskewed badges. Native semantic text accompanies these outlines. badges={'motorola':'motorola-inside-badge','hitachi':'hitachi-inside-badge','mpi':'tandy-multi-pak-interface-badge','floppy':'tandy-fd-502-disk-drive-badge','hard':'tandy-virtual-drive-system-badge','cassette':'tandy-computer-cassette-recorder-badge','joystick':'tandy-deluxe-joystick-badge','printer':'tandy-thermal-printer-tp-10-badge'} for key,name in badges.items():subprocess.run(['rsvg-convert','-f','pdf','-o',str(OUT/(key+'.pdf')),str(MEDIA/(name+'.svg'))],check=True) for ram in ['128kb','512kb','2mb','8mb']: r=E.parse(MEDIA/'tandy-128k-color-computer-3-badge.svg').getroot() for e in get(r,'computer-ram-options'): if e.tag==tag('g'):e.set('style','display:inline' if e.get('id')=='computer-ram-'+ram else 'display:none') subprocess.run(['rsvg-convert','-f','pdf','-o',str(OUT/('coco-'+ram+'.pdf'))],input=E.tostring(r),check=True) print(f'Compiled {len(layers)} cropped layers and {len(badges)+4} badges') if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--author-master',action='store_true');p.add_argument('--orchestra',action='store_true');p.add_argument('--speech',action='store_true');p.add_argument('--printer',action='store_true');p.add_argument('--sdc',action='store_true');args=p.parse_args() if args.author_master:author() if args.author_master or args.orchestra or args.speech:orchestra() if args.author_master or args.speech:speech() if args.author_master or args.printer:printer() if args.author_master or args.sdc:sdc() compile_art()