"""Render the 1881 Törefors sketch from a hand-traced municipal plan (Pillow).
Plan coordinates below refer to fig. 1 on page 9 of Töre utvecklingsplan,
rasterised at 1.7 px/PDF point. The 300 m scale spans 246 source pixels.
Elevations are illustrative; present-day façade features follow BD 28, p. 3.
"""
import math
import os
import random
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

W, H, SS = 1680, 1150, 2
PAPER, INK, SOFT = '#f6f2e7', '#25372f', '#566354'
image = Image.new('RGB', (W*SS,H*SS), PAPER)
draw = ImageDraw.Draw(image)
rng = random.Random(1881)

def pix(p):
    return tuple(round(v*SS) for v in p)

def line(points, color, width=1):
    draw.line([pix(p) for p in points], fill=color, width=max(1,round(width*SS)), joint='curve')

def area(points, color, stroke=None, width=1):
    xy = [pix(p) for p in points]
    draw.polygon(xy,fill=color)
    if stroke:
        line([*points,points[0]],stroke,width)

def dot(x,y,r,color):
    draw.ellipse([pix((x-r,y-r)),pix((x+r,y+r))],fill=color)

def text(p,words,size,color=INK,bold=False,serif=False,anchor='la'):
    name = ('georgiab' if bold else 'georgia') if serif else ('segoeuib' if bold else 'segoeui')
    path = Path(os.environ.get('WINDIR','C:/Windows'))/'Fonts'/f'{name}.ttf'
    font = ImageFont.truetype(str(path),int(size*SS))
    draw.text(pix(p), words, font=font,fill=color,anchor=anchor)

def mix(col, target, amount):
    values=[tuple(bytes.fromhex(c[1:])) for c in (col,target)]
    return '#'+''.join(f'{int(a+(b-a)*amount):02x}' for a,b in zip(*values))

# Oblique orthographic projection with south towards the viewer.
def site(x,y,z=0):
    return (35 + (x-680 + .22*(y-182))*3.35, 177 + (y-168)*2.12 - 2.58*z)

def route(path, color, width):
    line([site(*p) for p in path],color,width)

def ground(path, color, outline=None):
    area([site(*p) for p in path],color,outline)

def curve(points,n=8):
    """Catmull-Rom interpolation of digitised bends."""
    result=[]
    q=[points[0],*points,points[-1]]
    for i in range(1,len(q)-2):
        a,b,c,d=q[i-1:i+3]
        for j in range(n):
            t=j/n
            result.append(tuple(.5*(2*B +(-A+C)*t+(2*A-5*B+4*C-D)*t*t+(-A+3*B-3*C+D)*t**3) for A,B,C,D in zip(a,b,c,d)))
    return result+[points[-1]]

def building(project,cx,cy,length,width,wall,peak,angle,kind):
    ca,sa=math.cos(math.radians(angle)),math.sin(math.radians(angle))
    def P(u,v,h):
        return project(cx+u*ca-v*sa,cy+u*sa+v*ca,h)
    def face(vertices,color,stroke=None):
        area([P(*p) for p in vertices],color,stroke,.55)
    def wire(vertices,color,sw=.6):
        line([P(*p) for p in vertices],color,sw)
    a,b=length/2,width/2
    red=kind=='workers'
    pale=kind=='master'
    roof='#778783' if (red or pale) else '#68675e'
    body='#974b3d' if red else '#dedbc8' if pale else '#7c796f' if kind=='mill' else '#8b7b62'
    trim='#f3ead6'
    corners=[(-a,-b),(a,-b),(a,b),(-a,b)]
    shifted=[project(cx+u*ca-v*sa+3,cy+u*sa+v*ca+3,0) for u,v in corners]
    area(shifted,'#adab8d')
    for i in range(4):
        (u1,v1),(u2,v2)=corners[i],corners[(i+1)%4]
        p0,p1,p2=P(u1,v1,0),P(u2,v2,0),P(u1,v1,wall)
        if (p1[0]-p0[0])*(p2[1]-p0[1])-(p1[1]-p0[1])*(p2[0]-p0[0])<0:
            continue
        def coord(t,h):
            return (u1+(u2-u1)*t,v1+(v2-v1)*t,h)
        shade=body if i in (0,2) else mix(body,'#332d24',.17)
        face([coord(0,0),coord(1,0),coord(1,wall),coord(0,wall)],shade,'#655f50')
        face([coord(0,0),coord(1,0),coord(1,.48),coord(0,.48)],'#777768')
        slots=max(8,int(math.dist((u1,v1),(u2,v2))/.72))
        for k in range(1,slots):
            wire([coord(k/slots,.5),coord(k/slots,wall)],mix(shade,'#42392e',.16),.4)
        longface=i in (0,2)
        count=7 if red and longface else 4 if pale and longface else 2 if pale or red else max(2,round(math.dist((u1,v1),(u2,v2))/5))
        levels=2 if pale or kind=='mill' else 1
        for lev in range(levels):
            for j in range(count):
                t=(j+.5)/count
                lo=(.85+lev*(wall/levels)); hi=min(wall-.35,lo+(wall/levels)*.48)
                frac=min(.13, .22/count)
                if i==2 and red and j in [0,2,3,6]:continue
                if kind in ('shed','store') and j%2==0:continue
                frame=[coord(t-frac,lo),coord(t+frac,lo),coord(t+frac,hi),coord(t-frac,hi)]
                face(frame,trim if red or pale else '#b3ab8d')
                face([coord(t-frac*.72,lo+.14),coord(t+frac*.72,lo+.14),coord(t+frac*.72,hi-.14),coord(t-frac*.72,hi-.14)],'#526462')
                wire([coord(t,lo),coord(t,hi)],trim,.6)
                wire([coord(t-frac,(hi+lo)/2),coord(t+frac,(hi+lo)/2)],trim,.55)
        if red or pale:
            for t in (0,.985):
                face([coord(t,0),coord(t+.015,0),coord(t+.015,wall),coord(t,wall)],trim)
    # Roof strips run the full length. Paint far slopes before near ones.
    cross=[(-b,wall),(-b*.65,wall+peak*.68),(0,wall+peak),(b*.65,wall+peak*.68),(b,wall)] if red else [(-b,wall),(0,wall+peak),(b,wall)]
    for sign in (-1,1):
        u=sign*a
        face([(u,v,z) for v,z in cross],mix(body,'#514b3c',.16), '#68675b')
    for k,((v1,z1),(v2,z2)) in enumerate(zip(cross,cross[1:])):
        surf=[(-a-.35,v1,z1),(a+.35,v1,z1),(a+.35,v2,z2),(-a-.35,v2,z2)]
        face(surf,mix(roof,'#dcdac7',.18 if k<len(cross)//2 else .02),'#5f655c')
        for seam in range(1,max(1,int(length/1.35))):
            u=-a+seam*1.35
            wire([(u,v1,z1),(u,v2,z2)],mix(roof,'#e1decd',.24),.4)
    if red or pale:
        for u in (-a*.42,a*.43) if red else (-a*.30,):
            h=wall+peak
            face([(u,-.28,h),(u+.8,-.28,h),(u+.8,-.28,h+1.4),(u,-.28,h+1.4)],'#6a5a4a')
            face([(u,.36,h),(u+.8,.36,h),(u+.8,.36,h+1.4),(u,.36,h+1.4)],'#51544c')
        # Front roofs and door surrounds. Placement echoes present façades.
        for u in ([-a*.88,-a*.24,a*.02,a*.82] if red else [a*.34]):
            w=1.5 if red else 1.9
            h=wall*.75 if red else wall*.47
            face([(u-w*.5,b,.3),(u+w*.5,b,.3),(u+w*.5,b,h),(u-w*.5,b,h)],'#693f32')
            for pos in (-w,w):
                wire([(u+pos,b+1.1,.3),(u+pos,b+1.1,h)],trim,1)
            face([(u-w,b+1.4,h),(u+w,b+1.4,h),(u,b+1.4,h+.9)],body,trim)
            face([(u,b,h+.9),(u,b+1.4,h+.9),(u+w,b+1.4,h),(u+w,b,h)],roof,trim)
            if pale:
                face([(u-w*1.22,b+.16,h),(u+w*1.22,b+.16,h),(u+w*1.22,b+.16,wall),(u,b+.16,wall+peak),(u-w*1.22,b+.16,wall)],body,'#858374')
                face([(u-.5,b+.18,h+.65),(u+.5,b+.18,h+.65),(u+.5,b+.18,wall-.35),(u-.5,b+.18,wall-.35)],'#50605e')
            wire([(u-w,b+1.8,.18),(u+w,b+1.8,.18)],'#aa9c83',1.2)

def furnace():
    def block(cx,cy,z0,z1,a,b,ap,bp,col):
        lo=[(cx-a,cy-b,z0),(cx+a,cy-b,z0),(cx+a,cy+b,z0),(cx-a,cy+b,z0)]
        hi=[(cx-ap,cy-bp,z1),(cx+ap,cy-bp,z1),(cx+ap,cy+bp,z1),(cx-ap,cy+bp,z1)]
        for i,k in ((3,.77),(2,.97)):
            pts=[lo[i],lo[(i+1)%4],hi[(i+1)%4],hi[i]]
            area([site(*p) for p in pts],mix(col,'#342f28',1-k),'#64594e',.7)
            for n in range(1,max(1,round((z1-z0)/1.1))):
                t=n/max(1,round((z1-z0)/1.1))
                p=tuple(v+(w-v)*t for v,w in zip(lo[i],hi[i]));q=tuple(v+(w-v)*t for v,w in zip(lo[(i+1)%4],hi[(i+1)%4]))
                line([site(*p),site(*q)],mix(col,'#473c32',.28),.5)
        area([site(*p) for p in hi],mix(col,'#e5d8bd',.22),'#64594e',.55)
    block(808,317,0,6.4,6.2,5.6,5.6,5.2,'#787f72')
    block(808,317,6.4,12.4,4.7,4.4,3.8,3.6,'#a38565')
    block(808,317,12.4,14,2.4,2.4,2,2,'#946c4f')
    block(799,316,0,7.8,3,3,2.2,2.2,'#8e775f')
    aperture=[(805,322.65,0),(805,322.65,2),(806,322.65,3.2),(807.2,322.65,3.6),(808.4,322.65,3.2),(809.4,322.65,2),(809.4,322.65,0)]
    area([site(*p) for p in aperture],'#443d34')
    for post in (805,810.5):
        line([site(post,319,11.8),site(post,319,15.2)],'#574b3e',1)
    area([site(*p) for p in [(804.3,315.2,15),(808,313.7,16.3),(812,315.2,15),(812,319.2,15),(804.3,319.2,15)]],'#625449')

# Heading
text((65,30),'TÖREFORS   /   ПРОМЫШЛЕННЫЙ ЛАНДШАФТ',16,SOFT,True)
text((62,54),'Hyttgården в 1881 году',51,INK,False,True)
text((66,128),'Вид с юга. Положение построек и русла перенесено со схемы коммуны Kalix.',21,SOFT)
line([(65,165),(1615,165)],'#b9bb9e')
heading=image.crop((*pix((0,0)),*pix((W,169))))
# Landscape is composed within its own clipped panel.
panel=(42,185,1190,743)
terrain=[(550,100),(1130,100),(1130,500),(550,500)]
ground(terrain,'#d9d8b8')
for i in range(9400):
    gx=rng.uniform(615,1080);gy=rng.uniform(135,459)
    start=site(gx,gy)
    line([start,(start[0]+rng.uniform(.5,2.4),start[1]-.6)],rng.choice(['#d0d1b1','#d4d5b5','#dfdec4']),.68)
left=[(885,127),(876,145),(869,164),(869,177),(879,197),(877,209),(883,226),(910,232),(933,251),(947,274),(946,298),(932,314),(913,325),(908,338),(902,354),(885,374),(869,392),(851,413),(825,429),(800,427),(777,414),(755,386),(728,383),(706,390),(690,412),(673,449),(639,475)]
right=[(921,122),(916,145),(911,165),(914,193),(912,203),(925,213),(941,235),(953,252),(975,275),(975,299),(963,322),(950,341),(940,365),(940,380),(929,398),(937,422),(935,443),(908,475)]
water=curve(left)+curve(right[::-1])
ground(water,'#93b7b4','#778c7c')
# Fine horizontal ripples clipped visually by the water polygon.

water_mask=Image.new('1',image.size,0)
ImageDraw.Draw(water_mask).polygon([pix(site(*p)) for p in water],fill=1)
ripples=image.copy()
rd=ImageDraw.Draw(ripples)
for i in range(4900):
    x=rng.randint(0,1280);y=rng.randint(175,800);length=rng.uniform(3,14)
    rd.line([pix((x,y)),pix((x+length,y))],fill=rng.choice(['#a5c1bb','#90afab']),width=SS)
image.paste(ripples,mask=water_mask)
# Contour of the foreground, kept in plan coordinates.
road=curve([(653,193),(680,205),(713,213),(756,215),(782,217),(807,227),(831,243),(851,257),(875,268),(899,266),(931,257),(955,251),(977,246),(996,254),(1023,268),(1054,281)])
rail=curve([(658,433),(683,381),(710,322),(731,271),(750,235),(764,217)])
canal=[(884,194),(872,207),(857,227),(842,247),(831,267),(815,283),(805,296),(794,310),(783,326),(770,348),(751,382)]
route(road,'#a69b7c',12);route(road,'#dfc99e',8)
route(rail,'#ad9474',4);route(rail,'#666959',1.5)
for u,v in zip(rail[::4],rail[1::4]):
    dx,dy=v[0]-u[0],v[1]-u[1];l=math.hypot(dx,dy)
    if l:route([(u[0]-dy/l*1.3,u[1]+dx/l*1.3),(u[0]+dy/l*1.3,u[1]-dx/l*1.3)],'#796c56',1.2)
route(canal,'#8d947a',8);route(canal,'#83a9a2',5)
# Wooden road bridge spanning the main stream.
bridge=[(933,257),(956,251)]
route(bridge,'#7f705c',13);route(bridge,'#be9c74',9)
for i in range(1,16):
    t=i/16;x=933+23*t;y=257-6*t
    route([(x-.5,y-1.6),(x+.5,y+1.6)],'#8d7b62',.9)

assets=[
    (752,278,33,16,5.4,3.1,28,'store'),(847,342,36,13,5.2,3.2,-46,'store'),
    (879,289,15,9,6.0,2.9,37,'master'),(913,288,22,9.5,4.2,3.7,-56,'workers'),
    (791,310,13,8,5.2,2.8,29,'mill'),(912,343,9,7,4,2.5,18,'mill'),
    (876,246,14,11,4.5,3,-47,'shed'),(843,220,10,7,4,2.5,-50,'shed'),
    (897,304,9,7,3.3,1.9,-51,'shed'),(861,197,7,5,3.5,2.1,35,'shed')
]
for item in sorted(assets+[('furnace',317)],key=lambda p:p[1]):
    if item[0]=='furnace':furnace()
    else:building(site,*item)
# Clip to map viewport and place the editorial frame over its edges.
background=Image.new('RGB',image.size,PAPER)
background.paste(heading,pix((0,0)))
background.paste(image.crop((*pix(panel[:2]),*pix(panel[2:]))),pix(panel[:2]))
image=background
draw=ImageDraw.Draw(image)
def badge(x,y,s,r=13):
    dot(x,y,r+2,'#f4eddd');dot(x,y,r,'#314e42');text((x,y-1),s,17,'#fffff5',True,anchor='mm')
def pin(x,y,dx,dy,s):
    a=site(x,y);b=(a[0]+dx,a[1]+dy)
    line([a,b],'#475247',1.3);badge(*b,s)
pin(913,288,38,-42,'1');pin(879,289,-47,27,'2');pin(808,317,40,33,'3')
pin(791,310,-22,37,'4');pin(912,343,26,27,'5');pin(847,342,-13,36,'6')
x,y=site(736,193);text((x,y-10),'Дорога',17,'#605e4b',True)
x,y=site(964,317);text((x-15,y),'Töreälven',23,'#385d5b',False,True)
x,y=site(945,254)
line([(x,y-3),(x+18,y-30),(x+32,y-30)],'#475247',1.3)
text((x+38,y-44),'Мост',17,'#485a4c',True)
x,y=site(826,269);text((x-55,y-22),'Канал',17,'#49685c')
x,y=site(704,335);text((x-99,y+21),'Конный путь',17,'#625f50')
x,y=site(749,272);text((x-56,y-51),'Угольный склад',16,'#625f50')
# North indicator and east–west ground scale in the horizontal projection.
line([(82,252),(74,217)],INK,2);area([(74,213),(72,225),(79,221)],INK)
text((72,200),'С',14,INK,True,anchor='ma')
base=(73,708);scale=50*246/300*3.35
line([base,(base[0]+scale,base[1])],INK,3)
for sx in (base[0],base[0]+scale):line([(sx,base[1]-4),(sx,base[1]+4)],INK,2)
text((base[0],base[1]-25),'50 м  ·  запад — восток',15,INK)
# Key
text((1230,197),'На плане',36,INK,False,True)
rows=[
    ('1','Hyttgården¹','Жильё рабочих'),('2','Masmästarn¹','Дом мастера и контора'),
    ('3','Доменный комплекс','Плавильная и обжиговая печи'),('4','Nykvarn','Новая мельница у домны'),
    ('5','Kvarn','Мельница у русла'),('6','Старый угольный склад','Gammalt kolhus')]
for i,(n,title,descr) in enumerate(rows):
    y=277+i*65
    badge(1245,y+1,n)
    text((1272,y-14),title,21,INK,True);text((1272,y+14),descr,17,SOFT)
text((1230,675),'¹ Сопоставление двух контуров',17,SOFT)
text((1230,700),'с нынешними домами предварительное.',17,SOFT)
line([(65,769),(1615,769)],'#b9bb9e')
text((65,789),'Как узнать дома сегодня',31,INK,False,True)
# Two more detailed studies use the same generated geometry, at a larger scale.
def closeup(sx,sy,scale):
    return lambda x,y,z=0:(sx+(x+.27*y)*scale,sy+(.45*y-.9*z)*scale)
building(closeup(325,997,11.5),0,0,22,9.5,4.2,3.7,-7,'workers')
building(closeup(998,1001,11.5),0,0,15,9,6,2.9,-9,'master')
badge(99,894,'1');text((117,1038),'Hyttgården',25,INK,True)
text((117,1071),'Ломаная крыша, четыре крыльца.',18,SOFT)
badge(777,894,'2');text((797,1038),'Masmästarn',25,INK,True)
text((797,1071),'Два этажа, светлая обшивка, фронтон у входа.',18,SOFT)
line([(65,1116),(1615,1116)],'#c6c6b0')
text((65,1123),'Планировка по Töre utvecklingsplan, рис. 1. Фасады по фотографиям Länsstyrelsen, BD 28. Высоты, материалы и детали в исторической сцене условны.',15,SOFT)
image.resize((W,H),Image.Resampling.LANCZOS).save(Path(__file__).with_name('yard-1881.png'),optimize=True)

