#!/usr/bin/env python3
"""Build the tokenised BASIC application, native sprite and RISC OS ZIP.
Python 3 standard library only. Run this script from any directory.
The lexer deliberately supports this source's uppercase keywords and lowercase
identifiers; it is not a general-purpose BBC BASIC tokeniser.
"""
from pathlib import Path
import datetime
import math
import re
import struct
import zipfile

ROOT = Path(__file__).resolve().parent
APP = ROOT / '!Tracks'
# BBC BASIC V token bytes (BBC BASIC Reference Manual, Appendix B).
# ELSE is contextual: 8B in a single-line IF, CC on its own line.
TOKENS = {
 'OTHERWISE':'7f','ABS':'94','ASC':'97','RND':'b3','OPENIN':'8e','CLOSE':'d9','READ':'f3','DATA':'dc','AND':'80','DIV':'81','EOR':'82','MOD':'83','OR':'84','ERROR':'85',
 'STEP':'88','THEN':'8c','COS':'9b','ERL':'9e','ERR':'9f','FALSE':'a3',
 'FN':'a4','INT':'a8','LEN':'a9','NOT':'ac','PI':'af','SIN':'b5',
 'TO':'b8','TRUE':'b9','VAL':'bb','CHR$':'bd','LEFT$(':'c0',
 'MID$(':'c1','RIGHT$(':'c2','STR$':'c3','CASE':'c88e',
 'CIRCLE':'c88f','FILL':'c890','RECTANGLE':'c893','WHILE':'c895',
 'QUIT':'c898','SYS':'c899','WHEN':'c9','OF':'ca','ENDCASE':'cb',
 'ENDIF':'cd','ENDWHILE':'ce','DEF':'dd','DIM':'de','DRAW':'df',
 'END':'e0','ENDPROC':'e1','FOR':'e3','IF':'e7','LOCAL':'ea',
 'MOVE':'ec','NEXT':'ed','ON':'ee','VDU':'ef','PLOT':'f0',
 'PRINT':'f1','PROC':'f2','REM':'f4','REPEAT':'f5','REPORT$':'f624',
 'REPORT':'f6','RETURN':'f8','UNTIL':'fd','OFF':'87'
}
TOKENS = {k:bytes.fromhex(v) for k,v in TOKENS.items()}
KEYWORDS = sorted(TOKENS, key=len, reverse=True)


def tokenise_line(line):
    result = bytearray()
    i = 0
    while i < len(line):
        if line[i] == '"':
            # Preserve quoted text, including doubled quote sequences.
            j = i + 1
            while j < len(line):
                if line[j] == '"':
                    if j+1 < len(line) and line[j+1] == '"':
                        j += 2
                        continue
                    j += 1
                    break
                j += 1
            else:
                raise ValueError('Unterminated string: '+line)
            result.extend(line[i:j].encode('ascii'))
            i = j
        elif line[i] == '&':
            m = re.match(r'&[0-9A-Fa-f]+',line[i:])
            if not m:
                raise ValueError('Bad hexadecimal literal: '+line)
            result.extend(m[0].encode('ascii'))
            i += len(m[0])
        elif line.startswith('ELSE',i):
            result.append(0xcc if line.strip()=='ELSE' else 0x8b)
            i += 4
        elif line[i].isupper():
            for k in KEYWORDS:
                if line.startswith(k,i):
                    result.extend(TOKENS[k])
                    i += len(k)
                    if k in ('REM','DATA'):
                        result.extend(line[i:].encode('ascii'))
                        i = len(line)
                    break
            else:
                raise ValueError('Unknown uppercase keyword: '+line[i:])
        else:
            result.append(ord(line[i]))
            i += 1
    return bytes(result)


def build_basic():
    out = bytearray()
    lines = (APP/'Source').read_text(encoding='ascii').splitlines()
    for number,line in enumerate(lines,1):
        tokenised = tokenise_line(line)
        length = 4+len(tokenised)
        if length > 255:
            raise ValueError(f'BASIC line {number*10} too long')
        out.extend(bytes((13, (number*10)>>8, (number*10)&255, length)))
        out.extend(tokenised)
    out.extend(b'\r\xff')
    (APP/'!RunImage').write_bytes(out)
    return len(lines)



import array
import random
import sys
import json

def soundcode():
    # ARM-state ARMv4-compatible, position independent, 32-bit return.
    # Context: start,end,position,fraction,loop,step at offsets 0..20.
    # SharedSound's helper routines handle mixing, volume and resampling.
    ops=[];labels={};fix=[];listing=[]
    def label(s): labels[s]=len(ops)*4; listing.append(s+':')
    def emit(op,s): ops.append(op);listing.append('    '+s)
    def branch(cond,target):
        fix.append((len(ops),target));emit((cond<<28)|0x0a000000,'B'+{14:'',3:'LO',0:'EQ',2:'HS'}[cond]+' '+target)
    emit(0xe92d5ff7,'STMFD sp!, {r0-r2,r4-r12,lr}')
    emit(0xe1a0c000,'MOV r12,r0')
    emit(0xe59c4008,'LDR r4,[r12,#8]')
    emit(0xe59c5004,'LDR r5,[r12,#4]')
    emit(0xe59c900c,'LDR r9,[r12,#12]')
    emit(0xe59c6014,'LDR r6,[r12,#20]')
    label('loop')
    emit(0xe1540005,'CMP r4,r5');branch(3,'data')
    emit(0xe59ca010,'LDR r10,[r12,#16]')
    emit(0xe35a0000,'CMP r10,#0');branch(0,'silence')
    emit(0xe59c4000,'LDR r4,[r12,#0]')
    emit(0xe3a09000,'MOV r9,#0')
    emit(0xe1540005,'CMP r4,r5');branch(2,'silence')
    label('data')
    emit(0xe1a0e00f,'MOV lr,pc')
    emit(0xe598f008,'LDR pc,[r8,#8]')
    emit(0xe1510002,'CMP r1,r2');branch(3,'loop');branch(14,'finish')
    label('silence')
    emit(0xe1a0e00f,'MOV lr,pc')
    emit(0xe598f004,'LDR pc,[r8,#4]')
    emit(0xe59c4004,'LDR r4,[r12,#4]')
    label('finish')
    emit(0xe58c4008,'STR r4,[r12,#8]')
    emit(0xe58c900c,'STR r9,[r12,#12]')
    emit(0xe1a03000,'MOV r3,r0')
    emit(0xe8bd9ff7,'LDMFD sp!, {r0-r2,r4-r12,pc}')
    for i,target in fix:
        ops[i]|=((labels[target]-(i*4+8))//4)&0xffffff
    (APP/'SoundCode').write_bytes(struct.pack('<'+'I'*len(ops),*ops))
    (ROOT/'SoundARM').write_text('; SharedSound fill callback, assembled by Build\n'+'\n'.join(listing)+'\n')

# Appended to Build by the development step; the delivered Build is standalone.
PALETTE = [(16,26,34),(42,53,67),(89,104,120),(142,158,173),
           (227,235,236),(184,214,225),(68,117,141),(24,63,56),
           (40,104,85),(179,72,53),(244,202,103),(41,84,136),
           (62,132,188),(184,196,204),(240,244,238),(204,114,46)]
TW,TH=244,36

class Canvas:
    def __init__(self,w,h):self.w=w;self.h=h;self.p=[[None]*w for _ in range(h)]
    def dot(self,x,y,c):
        if 0<=x<self.w and 0<=y<self.h:self.p[y][x]=c
    def rect(self,x0,y0,x1,y1,c):
        for y in range(y0,y1):
            for x in range(x0,x1):self.dot(x,y,c)
    def line(self,x0,y0,x1,y1,c):
        n=max(abs(x1-x0),abs(y1-y0),1)
        for i in range(n+1):self.dot(round(x0+(x1-x0)*i/n),round(y0+(y1-y0)*i/n),c)
    def ellipse(self,x0,y0,x1,y1,c):
        for y in range(y0,y1):
            for x in range(x0,x1):
                if ((x+.5-(x0+x1)/2)/((x1-x0)/2))**2+((y+.5-(y0+y1)/2)/((y1-y0)/2))**2<=1:self.dot(x,y,c)
    def poly(self,points,c):
        for y in range(min(p[1] for p in points),max(p[1] for p in points)+1):
            for x in range(min(p[0] for p in points),max(p[0] for p in points)+1):
                inside=False;j=len(points)-1
                for i in range(len(points)):
                    a,b=points[i],points[j]
                    if (a[1]>y+.5)!=(b[1]>y+.5) and x+.5<(b[0]-a[0])*(y+.5-a[1])/(b[1]-a[1])+a[0]:inside=not inside
                    j=i
                if inside:self.dot(x,y,c)
    def flip(self):
        o=Canvas(self.w,self.h);o.p=[row[::-1] for row in self.p];return o

def wheel(c,x,y,r,f,steam=False):
    c.ellipse(x-r,y-r,x+r+1,y+r+1,0)
    c.ellipse(x-r+1,y-r+1,x+r,y+r,2 if not steam else 9)
    a=f*math.pi/2
    c.line(x-round((r-1)*math.cos(a)),y-round((r-1)*math.sin(a)),
           x+round((r-1)*math.cos(a)),y+round((r-1)*math.sin(a)),13)
    c.dot(x,y,4)

def train(kind,frame):
    c=Canvas(TW,TH)
    for x in (2,60,118):
        roof=1 if kind==0 else 2 if kind==1 else 13
        body=9 if kind==0 else 11 if kind==1 else 14
        c.rect(x+2,10,x+52,12,roof);c.rect(x,12,x+54,15,roof)
        c.rect(x+1,15,x+53,29,body)
        c.rect(x+1,28,x+53,31,0);c.rect(x+3,27,x+51,28,10 if kind==0 else 12)
        if kind==0:
            c.rect(x+2,15,x+52,16,10)
            for wx in range(x+5,x+49,9):
                c.rect(wx,17,wx+6,24,10);c.rect(wx+1,18,wx+5,23,5)
                c.line(wx+1,18,wx+3,18,14)
            c.rect(x+3,24,x+51,25,15)
        elif kind==1:
            c.rect(x+2,15,x+52,25,13)
            for wx in range(x+5,x+49,9):
                c.rect(wx,17,wx+6,23,0);c.rect(wx+1,18,wx+5,22,6)
                c.dot(wx+1,18,5)
        else:
            c.rect(x+3,16,x+51,23,1)
            for wx in range(x+5,x+49,9):
                c.rect(wx,17,wx+6,21,6);c.rect(wx,17,wx+4,18,5)
            c.rect(x+1,25,x+53,27,8)
            c.rect(x+3,15,x+5,27,3);c.rect(x+48,15,x+50,27,3)
        c.rect(x+53,27,x+59,29,2)
        wheel(c,x+11,32,3,frame);wheel(c,x+43,32,3,frame)
    x=178
    if kind==0:
        c.rect(x,8,x+21,11,0);c.rect(x+2,11,x+20,28,7)
        c.rect(x+3,12,x+19,13,10)
        c.rect(x+5,14,x+17,22,10);c.rect(x+6,15,x+16,21,6)
        c.rect(x+7,15,x+12,17,5)
        c.rect(x+19,15,x+54,27,7);c.rect(x+20,15,x+53,18,8)
        c.rect(x+22,18,x+54,20,8);c.rect(x+53,15,x+58,27,0)
        c.rect(x+29,11,x+34,16,10);c.rect(x+28,11,x+35,13,15)
        c.rect(x+45,3,x+51,17,0);c.rect(x+43,1,x+53,4,1)
        c.rect(x+46,5,x+48,14,2)
        c.rect(x+20,14,x+23,27,10);c.rect(x+39,15,x+41,27,10)
        c.rect(x,27,x+61,30,9);c.rect(x+59,26,x+64,28,2)
        c.rect(x+8,29,x+47,33,0)
        c.poly([(x+57,29),(x+64,32),(x+57,32)],0)
        for wx in (x+10,x+27,x+44):wheel(c,wx,30,5,frame,True)
        dy=[0,2,0,-2][frame];dx=[2,0,-2,0][frame]
        c.line(x+10+dx,30+dy,x+44+dx,30+dy,13)
        c.rect(x+5,24,x+14,26,10);c.rect(x+6,24,x+13,25,15)
        c.ellipse(x+56,20,x+60,24,10)
    elif kind==1:
        c.poly([(x+3,7),(x+50,7),(x+61,14),(x+63,28),(x,28),(x,12)],11)
        c.rect(x+5,7,x+49,9,3);c.rect(x+4,9,x+49,11,2)
        c.poly([(x+49,11),(x+58,15),(x+61,25),(x+61,28),(x+48,28)],10)
        c.poly([(x+48,12),(x+56,15),(x+58,20),(x+48,20)],0)
        c.rect(x+49,13,x+53,18,6);c.line(x+50,13,x+54,15,5)
        c.rect(x+4,13,x+13,21,0);c.rect(x+5,14,x+12,20,6)
        for gx in range(x+18,x+44,3):c.rect(gx,14,gx+1,24,0)
        c.rect(x+1,25,x+48,27,13);c.rect(x,28,x+64,31,0)
        c.rect(x+54,23,x+57,25,14);c.rect(x+60,26,x+64,28,2)
        c.rect(x+16,26,x+27,27,4)
        for wx in (x+9,x+18,x+44,x+53):wheel(c,wx,32,3,frame)
    else:
        c.poly([(x+1,10),(x+35,10),(x+47,13),(x+58,22),(x+64,28),(x+60,31),(x,31)],14)
        c.rect(x+3,10,x+32,12,13)
        c.poly([(x+8,15),(x+37,15),(x+46,19),(x+51,23),(x+8,23)],1)
        c.rect(x+10,16,x+29,20,6);c.rect(x+10,16,x+28,17,5)
        c.poly([(x+32,16),(x+37,16),(x+44,19),(x+47,22),(x+32,22)],6)
        c.poly([(x,25),(x+45,25),(x+60,28),(x+51,29),(x,28)],8)
        c.line(x+5,8,x+12,3,2);c.line(x+12,3,x+23,8,2)
        c.line(x+7,2,x+19,2,0);c.rect(x+4,8,x+25,10,2)
        c.rect(x+3,15,x+5,27,3);c.rect(x+11,29,x+46,32,0)
        c.rect(x+53,25,x+57,26,10)
        for wx in (x+10,x+20,x+38,x+48):wheel(c,wx,32,3,frame)
    return c

def tunnel(frame):
    # A taller mouth clears the steam chimney and the electric pantograph.
    # This is a background layer: the train remains in front until it reaches
    # the vanishing plane at x=40 (x=10 in the mirrored left-hand portal).
    c=Canvas(50,52)
    c.ellipse(0,0,74,72,2);c.rect(0,32,50,52,2)
    c.ellipse(7,7,67,67,1);c.rect(7,33,50,52,1)
    c.ellipse(13,12,61,66,0);c.rect(13,33,50,52,0)
    # Warm stone joints on the arched rim.
    for y in range(6,52,7):
        for x in range(0,50,11):
            if c.p[y][x]==2:c.rect(x,y,min(x+9,50),y+1,3)
        for x in range((y//7%2)*5,50,11):
            for yy in range(max(0,y-5),y):
                if c.p[yy][x]==2:c.dot(x,yy,1)
    if frame:
        # Rolling shutter descends into the entrance in four steps.
        stop=12+frame*10
        for y in range(12,min(stop,52)):
            for x in range(13,50):
                if c.p[y][x]==0:c.dot(x,y,1 if y%4==0 else 7 if y%4==3 else 8)
        c.rect(34,min(stop,51)-1,44,min(stop,51),10)
    return c

def rectangles(c):
    # Exact disjoint rectangle partition of opaque pixels. This lets ordinary
    # Wimp windows follow the silhouette without saving desktop screenshots.
    active={};out=[]
    for y,row in enumerate(c.p+[[]]):
        runs=[];x=0
        while x<len(row):
            if row[x] is None:x+=1;continue
            start=x
            while x<len(row) and row[x] is not None:x+=1
            runs.append((start,x))
        for span in list(active):
            if span not in runs:out.append((*span,active.pop(span),y))
        for span in runs:active.setdefault(span,y)
    return [(x0,y0,x1,y1) for x0,x1,y0,y1 in out]

def sprite_bytes(name,c):
    stride=((c.w*4+31)//32)*4
    image=bytearray(stride*c.h);mask=bytearray(stride*c.h)
    for y,row in enumerate(c.p):
        for x,col in enumerate(row):
            if col is not None:
                off=y*stride+x//2;shift=x%2*4
                image[off]|=col<<shift;mask[off]|=15<<shift
    pal=b''.join(struct.pack('<II',r<<8|g<<16|b<<24,r<<8|g<<16|b<<24) for r,g,b in PALETTE)
    img=44+len(pal);msk=img+len(image);size=msk+len(mask)
    header=struct.pack('<I12s7I',size,name.encode(),stride//4-1,c.h-1,0,(c.w*4-1)%32,img,msk,27)
    return header+pal+image+mask

def area(path,items):
    raw=b''.join(sprite_bytes(name,c) for name,c in items)
    path.write_bytes(struct.pack('<III',len(items),16,16+len(raw))+raw)

def assets():
    items=[];shapes=[]
    for kind in range(3):
        base=train(kind,0);rects=rectangles(base);shapes.append(rects)
        for direction in range(2):
            for frame in range(4):
                c=train(kind,frame)
                assert [[p is not None for p in r] for r in c.p]==[[p is not None for p in r] for r in base.p]
                items.append((f't{kind}{direction}{frame}',c if direction==0 else c.flip()))
    shapes.append(rectangles(tunnel(0)))
    for direction in range(2):
        for frame in range(5):items.append((f'p{direction}{frame}',tunnel(frame) if direction==0 else tunnel(frame).flip()))
    area(APP/'Trains',items)
    icon=Canvas(34,34)
    # A readable front-three-quarter steam locomotive at the standard icon size.
    icon.rect(3,27,31,29,2);icon.rect(5,29,30,30,0)
    icon.rect(4,11,15,24,7);icon.rect(3,9,16,12,0)
    icon.rect(6,13,12,19,10);icon.rect(7,14,11,18,5)
    icon.rect(13,17,27,25,8);icon.rect(14,17,26,19,10)
    icon.ellipse(22,16,32,27,0);icon.ellipse(24,18,30,25,1)
    icon.rect(23,8,28,18,0);icon.rect(22,6,29,9,2)
    icon.rect(5,25,32,28,9)
    for x in (9,19,28):wheel(icon,x,28,3,0,True)
    icon.line(9,28,28,28,13);icon.dot(28,21,10)
    icon.ellipse(20,2,26,5,13);icon.ellipse(14,0,21,4,3)
    area(APP/'!Sprites',[('!tracks',icon)])
    # Readable/generated BASIC geometry and sprite pointer table.
    base=(APP/'Source').read_text().split('REM Generated sprite geometry')[0]
    tail=['REM Generated sprite geometry - rebuilt by Build.','DEF PROCassets',
          f'DIM sprite%({len(items)-1}),count%(3),rx%(3,127),ry%(3,127),rr%(3,127),rb%(3,127)',
          'LOCAL i%,j%,k%,name$','FOR i%=0 TO '+str(len(items)-1),'  READ name$',
          '  SYS "OS_SpriteOp",&118,sprites%,name$ TO ,,sprite%(i%)','NEXT',
          'FOR k%=0 TO 3','  READ count%(k%)','  FOR j%=0 TO count%(k%)-1',
          '    READ rx%(k%,j%),ry%(k%,j%),rr%(k%,j%),rb%(k%,j%)','  NEXT','NEXT','ENDPROC',':']
    tail.extend('DATA "'+name+'"' for name,c in items)
    for rs in shapes:
        assert len(rs)<=128
        tail.append('DATA '+str(len(rs)))
        tail.extend('DATA '+','.join(map(str,r)) for r in rs)
    (APP/'Source').write_text(base+'\n'.join(tail)+'\n')
    (ROOT/'Geometry').write_text(json.dumps(shapes,indent=2)+'\n')
    # Lossless developer preview of the actual pixel art, not an artist impression.
    preview=Canvas(540,224);preview.rect(0,0,540,224,4)
    for k in range(3):
        t=train(k,0)
        for y,row in enumerate(t.p):
            for x,col in enumerate(row):
                if col is not None:preview.rect(18+2*x,12+k*67+2*y,20+2*x,14+k*67+2*y,col)
    rgb=bytes(v for row in preview.p for col in row for v in PALETTE[col])
    (ROOT.parent/'Tracks-preview.ppm').write_bytes(b'P6\n540 224\n255\n'+rgb)
    print('Silhouette rectangles:',[len(r) for r in shapes])

def audio():
    sr=11025
    def write(name,samples):
        data=array.array('h')
        for i,s in enumerate(samples):
            v=int(max(-.94,min(.94,s))*24000)
            data.extend((v,v))
        if sys.byteorder!='little':data.byteswap()
        (APP/name).write_bytes(data.tobytes())
    for kind,name in enumerate(('Steam','Diesel','Electric')):
        rng=random.Random(700+kind);samples=[];lp=0.
        # Six-second loops; all tonal components have an integer cycle count.
        n=sr*6
        for i in range(n):
            t=i/sr;noise=rng.uniform(-1,1);lp=.85*lp+.15*noise
            if kind==0:
                phase=(t*5)%1;env=math.exp(-phase*9)*(1-math.exp(-phase*55))
                s=.56*env*(.75*noise+lp)+.065*math.sin(2*math.pi*55*t)
            elif kind==1:
                pulse=.72+.28*math.cos(2*math.pi*20*t)
                s=(.15*math.sin(2*math.pi*55*t)+.09*math.sin(2*math.pi*110*t)+.055*math.sin(2*math.pi*165*t))*pulse+.07*lp
            else:
                s=.07*math.sin(2*math.pi*330*t)+.035*math.sin(2*math.pi*660*t)+.06*lp
            samples.append(s)
        # Tiny seam crossfade on the noise component; keeps looping unobtrusive.
        fade=220
        for j in range(fade):
            a=j/fade;samples[j]=samples[-fade+j]*(1-a)+samples[j]*a
        write(name,samples)
    for kind,name in enumerate(('Whistle','Horn','Chime')):
        rng=random.Random(999+kind);samples=[];n=int(sr*1.65)
        freqs=((523.25,659.25,783.99),(220,277.18),(440,554.37))[kind]
        for i in range(n):
            t=i/sr;env=min(1,t/.14)*min(1,(1.65-t)/.32)
            vibrato=1.4*math.sin(2*math.pi*4.5*t) if kind==0 else 0
            s=sum(math.sin(2*math.pi*f*t+vibrato)*(.20/len(freqs)) for f in freqs)
            if kind==0:s+=rng.uniform(-.028,.028)
            samples.append(s*env)
        write(name,samples)

def make_zip():
    target=ROOT.parent/'Tracks-riscos5.zip'
    stamp=int((datetime.datetime.now(datetime.timezone.utc)-datetime.datetime(1900,1,1,tzinfo=datetime.timezone.utc)).total_seconds()*100)
    types={'OakLogo':0xff9,'!Run':0xfeb,'!Boot':0xfeb,'!RunImage':0xffb,'!Sprites':0xff9,'Trains':0xff9,
           'SoundCode':0xffd,'Steam':0xffd,'Diesel':0xffd,'Electric':0xffd,'Whistle':0xffd,'Horn':0xffd,'Chime':0xffd}
    with zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED) as z:
        for p in sorted(ROOT.rglob('*')):
            if not p.is_file():continue
            zi=zipfile.ZipInfo(p.relative_to(ROOT).as_posix(),datetime.datetime.now().timetuple()[:6])
            zi.create_system=13;zi.compress_type=zipfile.ZIP_DEFLATED
            load=0xfff00000|(types.get(p.name,0xfff)<<8)|((stamp>>32)&255)
            metadata=struct.pack('<4sIIII',b'ARC0',load,stamp&0xffffffff,0x33,0)
            zi.extra=struct.pack('<HH',0x4341,len(metadata))+metadata
            z.writestr(zi,p.read_bytes())
    return target

if __name__=='__main__':
    assets();soundcode();audio();lines=build_basic()
    print(f'{make_zip()}: {lines} BASIC lines; native sprites and synthesised sound')
