#!/usr/bin/env python3
"""figures.py: the map, the drawings and the cover for "The Huns".
Usage: figures.py --cache DIR [--out DIR]
Needs: Pillow, rsvg-convert, the Noto fonts (Serif, Sans Old Hungarian, Serif Devanagari and CJK)
The map and the banquet hall are written as SVG fragments that the huns-map and attila-hall shortcodes
inline into the page, so that they follow the light and dark theme: they carry class names only, the
colours are in assets/css/widgets.css and huns.css. The cover is cropped from a scene of paint.sh.
"""
from __future__ import annotations
import argparse
import base64
import io
import json
import math
import subprocess
from pathlib import Path
from PIL import Image, ImageEnhance
HERE = Path(__file__).resolve().parent
INK = "#f8f0e8"
MUTED = "#b6a091"
FAINT = "#6b5148"
NIGHT = "#120c0c"
ROSE = "#f45ba4"
VIOLET = "#a78bfa"
BLUE = "#60a5fa"
GOLD = "#f2c45a"
TEAL = "#5eead4"
FONT = "Noto Serif"
RUNES = "Noto Sans Old Hungarian"
def escape(content: str) -> str:
return content.replace("&", "&").replace("<", "<").replace('"', """)
# --------------------------------------------------------------------------------------
# SVG helpers (after content/posts/the-goths/figures.py)
# --------------------------------------------------------------------------------------
class Svg:
def __init__(self, width: int, height: int):
self.width, self.height = width, height
self.parts = [
f'")
subprocess.run(
["rsvg-convert", "--unlimited", "-o", str(path)], input="".join(self.parts).encode(), check=True
)
print(f" {path.name}")
# --------------------------------------------------------------------------------------
# The map: a Lambert conformal conic of Eurasia, from Natural Earth (public domain)
# --------------------------------------------------------------------------------------
MAP_W, MAP_H = 1200, 640
WEST, EAST, SOUTH, NORTH = -20.0, 145.0, 4.0, 74.0 # clipping box, wider than the picture
LON0, LAT0, PHI1, PHI2 = 58.0, 42.0, 30.0, 52.0
RIVERS = {"Danube", "Donau", "Dnipro", "Dnepre", "Dniester", "Don", "Volga", "Ural", "Ertix", "Irtysh", "Tobol",
"Ob", "Yenisey", "Verkhniy Yenisey", "Malyy Yenisey", "Selenge (Selenga)", "Amu Darya", "Syr Darya",
"Huang", "Nile", "Rhine", "Rhein", "Rhne", "Loire", "Po", "Indus", "Ganges", "Euphrates", "Tigris", "Tisza"} # fmt: skip
def _conic(lon: float, lat: float) -> tuple[float, float]:
n = math.log(math.cos(math.radians(PHI1)) / math.cos(math.radians(PHI2))) / math.log(
math.tan(math.pi / 4 + math.radians(PHI2) / 2) / math.tan(math.pi / 4 + math.radians(PHI1) / 2)
)
f = math.cos(math.radians(PHI1)) * math.tan(math.pi / 4 + math.radians(PHI1) / 2) ** n / n
rho = f / math.tan(math.pi / 4 + math.radians(lat) / 2) ** n
rho0 = f / math.tan(math.pi / 4 + math.radians(LAT0) / 2) ** n
theta = n * math.radians(lon - LON0)
return rho * math.sin(theta), rho0 - rho * math.cos(theta)
def _frame():
"""Scale and offset that fit the area the story covers into the picture."""
points = [_conic(lon, lat) for lon, lat in ((-4.5, 44), (0, 51), (36, 31), (79, 22.5), (121, 38), (110, 50), (56, 55))]
xs, ys = [p[0] for p in points], [p[1] for p in points]
scale = min((MAP_W - 40) / (max(xs) - min(xs)), (MAP_H - 30) / (max(ys) - min(ys)))
return scale, MAP_W / 2 - scale * (max(xs) + min(xs)) / 2, MAP_H / 2 + scale * (max(ys) + min(ys)) / 2
SCALE, DX, DY = _frame()
def project(lon: float, lat: float) -> tuple[float, float]:
x, y = _conic(lon, lat)
return DX + SCALE * x, DY - SCALE * y
def clip_ring(ring: list) -> list:
"""Sutherland-Hodgman against the longitude and latitude box."""
for axis, limit, keep_above in ((0, WEST, True), (0, EAST, False), (1, SOUTH, True), (1, NORTH, False)):
inside = (lambda p: p[axis] >= limit) if keep_above else (lambda p: p[axis] <= limit)
out = []
for a, b in zip(ring[-1:] + ring[:-1], ring):
if inside(a) != inside(b):
t = (limit - a[axis]) / (b[axis] - a[axis])
out.append((a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])))
if inside(b):
out.append((b[0], b[1]))
ring = out
if not ring:
break
return ring
def thin(points: list, step: float) -> list:
kept = points[:1]
for p in points[1:-1]:
if math.dist(p, kept[-1]) >= step:
kept.append(p)
return kept + points[-1:]
def polyline(points: list) -> str:
return "M" + "L".join(f"{x:.1f} {y:.1f}" for x, y in points)
def smooth(points: list) -> str:
"""A Catmull-Rom curve through the waypoints."""
d = f"M{points[0][0]:.1f} {points[0][1]:.1f}"
for i in range(len(points) - 1):
p0, p1, p2 = points[max(i - 1, 0)], points[i], points[i + 1]
p3 = points[min(i + 2, len(points) - 1)]
c1 = (p1[0] + (p2[0] - p0[0]) / 6, p1[1] + (p2[1] - p0[1]) / 6)
c2 = (p2[0] - (p3[0] - p1[0]) / 6, p2[1] - (p3[1] - p1[1]) / 6)
d += f"C{c1[0]:.1f} {c1[1]:.1f} {c2[0]:.1f} {c2[1]:.1f} {p2[0]:.1f} {p2[1]:.1f}"
return d
def arrow_head(points: list, size=17.0) -> str:
(x0, y0), (x1, y1) = points[-2], points[-1]
angle = math.atan2(y1 - y0, x1 - x0)
left = (x1 - size * math.cos(angle - 0.45), y1 - size * math.sin(angle - 0.45))
right = (x1 - size * math.cos(angle + 0.45), y1 - size * math.sin(angle + 0.45))
return polyline([(x1, y1), left, right]) + "Z"
def polygons(geometry: dict) -> list:
if geometry["type"] == "Polygon":
return [geometry["coordinates"]]
return geometry["coordinates"]
def land_path(cache: Path, name: str) -> str:
d = []
for feature in json.loads((cache / name).read_text())["features"]:
for polygon in polygons(feature["geometry"]):
for ring in polygon:
ring = clip_ring([tuple(p[:2]) for p in ring])
if len(ring) < 4:
continue
points = thin([project(*p) for p in ring], 1.6)
xs, ys = [p[0] for p in points], [p[1] for p in points]
if len(points) > 3 and (max(xs) - min(xs)) * (max(ys) - min(ys)) > 12:
d.append(polyline(points) + "Z")
return "".join(d)
def river_path(cache: Path) -> str:
d = []
for feature in json.loads((cache / "rivers.geojson").read_text())["features"]:
if feature["properties"].get("name") not in RIVERS:
continue
geometry = feature["geometry"]
lines = [geometry["coordinates"]] if geometry["type"] == "LineString" else geometry["coordinates"]
for line in lines:
# "Don" and "Po" also name rivers far outside the map
if all(WEST < p[0] < EAST and SOUTH < p[1] < NORTH for p in line):
d.append(polyline(thin([project(*p[:2]) for p in line], 2.0)))
return "".join(d)
BADGE_SPOTS = [(0, 22), (0, -24), (32, 4), (-32, 4), (30, 34), (-30, 34), (30, -30), (-30, -30), (0, 56), (0, -58),
(64, 4), (-64, 4)] # fmt: skip
def fig_map(cache: Path, steps: list, out: Path) -> None:
parts = [
f'")
(out / "huns-map.svg").write_text("\n".join(parts) + "\n")
print(" huns-map.svg")
# --------------------------------------------------------------------------------------
# Attila's banquet hall, seen from above: Attila faces the door, so his right is on our left
# --------------------------------------------------------------------------------------
def fig_hall(parts_data: list, out: Path) -> None:
number = {part["id"]: i for i, part in enumerate(parts_data, 1)}
def part(name: str, body: str, bx: float, by: float) -> str:
return (
f'{body}'
f''
f'{number[name]}'
)
def chair(x: float, y: float, kind: str = "guest") -> str:
return (
f''
f''
)
table = lambda x, y, w=74, h=52: (
f''
f''
)
pieces = [
'",
]
(out / "huns-hall.svg").write_text("\n".join(pieces) + "\n")
print(" huns-hall.svg")
# --------------------------------------------------------------------------------------
# Charts
# --------------------------------------------------------------------------------------
def fig_timeline(out: Path) -> None:
"""Who rode when: bars on a common scale of years."""
svg = Svg(1200, 640)
svg.text(600, 56, "Eleven centuries, one famous name", 40)
svg.text(600, 92, "the peoples of this story, 209 BC to AD 900", 22, MUTED)
first, last, left, right = -300, 900, 60, 1140
at = lambda year: left + (year - first) / (last - first) * (right - left)
for year in range(-300, 901, 150):
svg.path(f"M{at(year):.0f} 126V574", FAINT, 1, "3 8")
label = f"{-year} BC" if year < 0 else ("AD 1" if year == 0 else str(year))
svg.text(at(year), 606, label, 19, MUTED)
rows = [
("Xiongnu empire", -209, 48, GOLD, "209 BC – AD 48, then split"),
("Southern and northern Xiongnu", 48, 155, GOLD, "48 – c. 150"),
("Huns in Europe", 370, 469, ROSE, "c. 370 – 469"),
("Attila", 434, 453, ROSE, "434 – 453"),
("Kidarites", 380, 467, BLUE, "late 4th century – 467"),
("Alchon Huns", 430, 600, BLUE, "c. 430 – c. 600"),
("Magyars in the Carpathian Basin", 895, 900, TEAL, "from 895"),
("Hunor and Magor written down", 1282, 1285, TEAL, "c. 1282, far off this chart"),
]
for i, (name, start, end, colour, years) in enumerate(rows):
y = 130 + i * 55
off = start > last
x0, x1 = (right - 14, right) if off else (at(start), max(at(end), at(start) + 8))
if off:
svg.add(f'')
else:
svg.rect(x0, y + 24, x1 - x0, 20, fill=colour, radius=6)
late = start > 250
svg.text(x1 if late else x0, y + 15, f"{name} {years}", 20, INK, "end" if late else "start")
svg.save(out / "huns-timeline.png")
def fig_names(out: Path) -> None:
"""The forms of the name, as the German article on the Huns lists them, and the Chinese one behind them."""
svg = Svg(1200, 700)
svg.text(600, 56, "One name, many tongues", 40)
svg.text(600, 92, "how the sources write “Hun”, and the older Chinese name often compared with it", 22, MUTED)
cards = [
(220, 130, "Οὖννοι", "Noto Serif", "Ounnoi", "Greek", ROSE),
(600, 130, "Hunni", "Noto Serif", "Hunni", "Latin", ROSE),
(980, 130, "Xwn", "Noto Serif", "Xwn", "Sogdian, transcribed", ROSE),
(220, 390, "हूण", "Noto Serif Devanagari", "Huna", "Sanskrit", ROSE),
(600, 390, "Χοῦνοι", "Noto Serif", "Chounoi", "Ptolemy, 2nd century: same people?", VIOLET),
(980, 390, "匈奴", "Noto Serif CJK TC", "Xiongnu", "Chinese: same people?", GOLD),
]
for cx, y, word, family, latin, note, colour in cards:
svg.rect(cx - 170, y, 340, 226, fill="#1f1414", stroke=colour, width=2)
svg.text(cx, y + 106, word, 72, INK, family=family)
svg.text(cx, y + 160, latin, 30, colour)
svg.text(cx, y + 198, note, 18, MUTED)
svg.text(600, 668, "Solid history: the first four. The links to Ptolemy and the Xiongnu are debated.", 20, MUTED)
svg.save(out / "huns-names.png")
def fig_alphabet(letters: list, out: Path) -> None:
columns, w, h = 7, 160, 150
rows = math.ceil(len(letters) / columns)
svg = Svg(1200, 126 + rows * (h + 12) + 40)
svg.text(600, 56, "The Old Hungarian letters", 40)
svg.text(600, 92, "rovás, modern spelling; written from right to left", 22, MUTED)
for i, item in enumerate(letters):
col, row = i % columns, i // columns
# right to left, like the script itself
x, y = 1200 - 22 - w - col * (w + 6), 126 + row * (h + 12)
svg.rect(x, y, w, h, fill="#1f1414", stroke=FAINT)
svg.text(x + w / 2, y + 82, item["rune"], 62, GOLD, family=RUNES)
svg.text(x + w / 2, y + 130, item["latin"], 30, INK)
svg.text(600, svg.height - 20, "Read the rows from the right.", 20, MUTED)
svg.save(out / "huns-alphabet.png")
def fig_cover(out: Path) -> None:
"""The painted riders of paint.sh, cropped to the shape of a preview image."""
source = out / "huns-scene-riders.jpg"
if not source.exists():
print(" huns-cover.png: skipped, run paint.sh first")
return
painting = Image.open(source).convert("RGB")
w, h = painting.size
height = round(w * 630 / 1200)
top = round((h - height) * 0.5)
painting = painting.crop((0, top, w, top + height)).resize((1200, 630), Image.LANCZOS)
painting = ImageEnhance.Color(painting).enhance(1.08)
svg = Svg(1200, 630)
svg.image(painting, 0, 0, 1200, 630)
svg.save(out / "huns-cover.png")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--cache", type=Path, required=True, help="folder with the downloads of build.sh")
parser.add_argument("--out", type=Path, default=HERE)
args = parser.parse_args()
load = lambda name: json.loads((HERE / name).read_text())
args.out.mkdir(parents=True, exist_ok=True)
fig_map(args.cache, load("huns-map.json"), args.out)
fig_hall(load("hall.json"), args.out)
fig_timeline(args.out)
fig_names(args.out)
fig_alphabet(load("rovas.json"), args.out)
fig_cover(args.out)
if __name__ == "__main__":
main()