#!/usr/bin/env python3 """figures.py: the map, the drawings and the cover for "The Turks". Usage: figures.py --cache DIR [--out DIR] Needs: Pillow, rsvg-convert, the Noto fonts (Serif and Sans Old Turkic) The map and the yurt are written as SVG fragments that the turk-map and yurt-explorer 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 turks.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 = "#f6eff8" MUTED = "#a99ab4" FAINT = "#5b4d6b" NIGHT = "#0f0c17" ROSE = "#f45ba4" VIOLET = "#a78bfa" BLUE = "#60a5fa" GOLD = "#f2c45a" TEAL = "#5eead4" FONT = "Noto Serif" RUNES = "Noto Sans Old Turkic" 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'' '' f'' "" '' ] def add(self, markup: str) -> None: self.parts.append(markup) def rect(self, x, y, w, h, fill="none", stroke="none", width=1.5, radius=14, opacity=1.0) -> None: self.add( f'' ) def path(self, d, stroke=FAINT, width=2.0, dash="") -> None: extra = f' stroke-dasharray="{dash}"' if dash else "" self.add(f'') def text(self, x, y, content, size=24, fill=INK, anchor="middle", family=FONT, extra="") -> None: self.add( f'{escape(content)}' ) def image(self, picture: Image.Image, x, y, w, h, opacity=1.0) -> None: buffer = io.BytesIO() picture.save(buffer, "JPEG", quality=92) data = base64.b64encode(buffer.getvalue()).decode() self.add( f'' ) def save(self, path: Path) -> None: self.add("") 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 = -15.0, 150.0, 8.0, 74.0 # clipping box, wider than the picture LON0, LAT0, PHI1, PHI2 = 64.0, 45.0, 35.0, 55.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"} # 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 ((9, 45.4), (31, 29.4), (117, 46), (112, 31), (64, 57), (19, 52), (104, 53))] 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'', f'', f'', f'', f'', ] dots = [project(*p["at"]) for step in steps for p in step["places"] if not p.get("label_only")] badges = [] for number, step in enumerate(steps, 1): parts.append(f'') for kind, key in (("own", "routes"), ("foe", "foes")): for route in step.get(key, []): points = [project(*p) for p in route] length = ' pathLength="1"' if kind == "own" else "" parts.append(f'') parts.append(f'') for place in step["places"]: x, y = project(*place["at"]) flip = place.get("left", False) or x > MAP_W - 230 if place.get("label_only"): parts.append(f'{escape(place["name"])}') continue parts.append(f'') anchor = ' text-anchor="end"' if flip else "" parts.append( f'' f"{escape(place['name'])}" ) # the step's number, at the end of its first path: this is what links map and list without JavaScript first = (step.get("routes") or step.get("foes"))[0] x, y = project(*first[-1]) # several steps end close together: take the first spot that keeps clear of the numbers already placed dx, dy = next( ( spot for spot in BADGE_SPOTS if all(math.dist((x + spot[0], y + spot[1]), other) >= 33 for other in badges) and all(math.dist((x + spot[0], y + spot[1]), dot) >= 21 for dot in dots) ), BADGE_SPOTS[0], ) badges.append((x + dx, y + dy)) parts.append( f'' f'{number}' ) parts.append("") (out / "turks-map.svg").write_text("\n".join(parts) + "\n") print(" turks-map.svg") # -------------------------------------------------------------------------------------- # The yurt: a cutaway seen from the back of the tent towards the door, so east is on the left # -------------------------------------------------------------------------------------- def fig_yurt(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]}' ) # the shell: walls from x 110 to 890, the roof rising to the crown shell = "M110 600V395L405 150H595L890 395V600Z" felt = "M84 600V386L398 124H602L916 386V600H890V395L595 150H405L110 395V600Z" lattice = [] for side in ((110, 330), (670, 890)): x0, x1 = side for x in range(x0 - 160, x1 + 1, 44): for lean in (1, -1): a, b = (x, x + 160) if lean > 0 else (x + 160, x) # clip each lath to its section of the wall t0 = max(0.0, min((x0 - a) / (b - a), (x1 - a) / (b - a))) t1 = min(1.0, max((x0 - a) / (b - a), (x1 - a) / (b - a))) if t0 < t1: lattice.append( f"M{a + (b - a) * t0:.0f} {600 - 200 * t0:.0f}L{a + (b - a) * t1:.0f} {600 - 200 * t1:.0f}" ) poles = "".join( f"M{x0} {y0}L{x1} {y1}" for x0, y0, x1, y1 in ( (110, 395, 408, 152), (190, 398, 424, 160), (270, 400, 444, 164), (350, 401, 466, 168), (890, 395, 592, 152), (810, 398, 576, 160), (730, 400, 556, 164), (650, 401, 534, 168), ) # fmt: skip ) rug = lambda x, y, w: f'' chest = lambda x: ( f'' f'' ) pieces = [ f'', '', '', f'', part("felt", f'', 84, 470), part("lattice", f'', 118, 372), part("poles", f'', 262, 268), part( "door", '' '' '', 610, 420, ), part("east", rug(150, 586, 190) + chest(170) + '', 150, 486), part( "west", rug(660, 586, 190) + chest(714) + '', 850, 486, ), part( "smoke", '' '', 556, 300, ), part( "crown", '' '', 626, 120, ), part( "hearth", '' '' '', 606, 636, ), 'EASTWEST', "", ] (out / "turks-yurt.svg").write_text("\n".join(pieces) + "\n") print(" turks-yurt.svg") # -------------------------------------------------------------------------------------- # Charts # -------------------------------------------------------------------------------------- def box(svg: Svg, cx, y, name, note="", colour=VIOLET, w=190, h=62) -> None: svg.rect(cx - w / 2, y, w, h, fill="#1a1426", stroke=colour, width=2) svg.text(cx, y + (27 if note else 39), name, 22) if note: svg.text(cx, y + 49, note, 15, MUTED) def fig_timeline(out: Path) -> None: """Who ruled, and when: bars on a common scale of years.""" svg = Svg(1200, 640) svg.text(600, 56, "Eight centuries of the steppe", 40) svg.text(600, 92, "the powers of this story, AD 500 to 1400", 22, MUTED) first, last, left, right = 500, 1400, 60, 1140 at = lambda year: left + (year - first) / (last - first) * (right - left) for year in range(first, last + 1, 100): svg.path(f"M{at(year):.0f} 126V574", FAINT, 1, "3 8") svg.text(at(year), 606, str(year), 19, MUTED) rows = [ ("First Turkic Khaganate", 552, 603, ROSE), ("Eastern khaganate", 603, 630, ROSE), ("Western khaganate", 603, 659, ROSE), ("Second Turkic Khaganate", 682, 744, ROSE), ("Kimek–Kipchak khaganate", 880, 1050, GOLD), ("Cumans and Kipchaks in the west", 1054, 1241, GOLD), ("Golden Horde, the “Kipchak Khanate”", 1241, 1400, VIOLET), ("Mamluk Egypt (to 1517)", 1250, 1400, BLUE), ] for i, (name, start, end, colour) in enumerate(rows): y = 130 + i * 55 svg.rect(at(start), y + 24, at(end) - at(start), 20, fill=colour, radius=6) late = at(start) > 760 x = at(end) if late else at(start) svg.text(x, y + 15, f"{name} {start}–{end}" if end < 1400 else name, 20, INK, "end" if late else "start") svg.save(out / "turks-timeline.png") def fig_words(out: Path) -> None: """Words of the Lord's Prayer in the Codex Cumanicus and in Crimean Tatar today.""" svg = Svg(1200, 800) svg.text(600, 56, "Seven hundred years apart", 40) svg.text(600, 92, "words from the Lord’s Prayer: Codex Cumanicus and Crimean Tatar", 22, MUTED) for x, title, colour in ((250, "Codex Cumanicus", GOLD), (660, "Crimean Tatar", ROSE), (1000, "Meaning", MUTED)): svg.text(x, 148, title, 28, colour) rows = [ ("atamız", "atamız", "our father"), ("köktä", "kökte", "in heaven"), ("atıñ", "adıñ", "your name"), ("yerdä", "yerde", "on earth"), ("ötmäkimizni", "ötmegimizni", "our bread"), ("bugün", "bugün", "today"), ("yaman", "yaman", "evil"), ("qutxarğıl", "qurtar", "deliver us"), ] for i, (old, new, meaning) in enumerate(rows): y = 172 + i * 70 svg.rect(60, y, 1080, 58, fill="#1a1426", stroke=FAINT) svg.text(250, y + 39, old, 30) svg.text(660, y + 39, new, 30) svg.text(1000, y + 38, meaning, 24, MUTED) svg.text(600, 764, "As printed in the English Wikipedia articles on the codex and the Cuman language.", 18, MUTED) svg.save(out / "turks-words.png") def fig_runes(letters: list, out: Path) -> None: svg = Svg(1200, 860) svg.text(600, 56, "The Orkhon runes", 40) svg.text(600, 92, "many consonants have two shapes: one for back vowels, one for front vowels", 22, MUTED) for i, item in enumerate(letters): col, row = i % 6, i // 6 x, y = 40 + col * 190, 126 + row * 176 pair = item["back"] != item["front"] svg.rect(x, y, 170, 156, fill="#1a1426", stroke=VIOLET if pair else FAINT) if pair: svg.text(x + 50, y + 82, item["back"], 66, GOLD, family=RUNES) svg.text(x + 120, y + 82, item["front"], 66, ROSE, family=RUNES) else: svg.text(x + 85, y + 82, item["back"], 66, INK, family=RUNES) svg.text(x + 85, y + 134, item["latin"], 30, INK) for x, colour, text in ((330, GOLD, "with a, ı, o, u"), (650, ROSE, "with e, i, ö, ü"), (930, INK, "one shape")): svg.rect(x - 90, 838 - 17, 20, 20, fill=colour, radius=5) svg.text(x - 58, 838, text, 20, MUTED, "start") svg.save(out / "turks-alphabet.png") def fig_cover(out: Path) -> None: """The painted riders of paint.sh, cropped to the shape of a preview image.""" source = out / "turks-scene-riders.jpg" if not source.exists(): print(" turks-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 / "turks-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("turks-map.json"), args.out) fig_yurt(load("yurt.json"), args.out) fig_timeline(args.out) fig_words(args.out) fig_runes(load("turkic-runes.json"), args.out) fig_cover(args.out) if __name__ == "__main__": main()