Skip to content

An AI skill that turns books into animated, narrated, interactive web experiences

feat(maps kit): paper map and night globe for shorts and documentaries, geo.py builder, sample page

yzrdc50464aa0f4
diff --git a/.claude/skills/papermorph/assets/templates/maps/lib/globe.js b/.claude/skills/papermorph/assets/templates/maps/lib/globe.js
new file mode 100644
index 0000000..a601d5d
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/maps/lib/globe.js
@@ -0,0 +1,115 @@
+/* globe.js: the map kit's night globe (three.js, lib/vendor/ from geo.py --globe), on the beat clock, for the engine's
+ stage either way up (SW x SH). One WebGL canvas for the whole film, moved into each beat's panel through a
+ foreignObject, so beats never pile up contexts. The camera is orthographic: a globe of radius 1 seen at H shows the
+ Earth's radius as 450 / H stage px (half the short side of the stage), and the paper map (map.js paperMap, the same
+ orthographic view in lon/lat) takes the very same view object: a shot hands over from globe to map without a jump.
+ The texture is ../img/night.webp (NASA Black Marble). Loaded by loadGlobe() (map.js), used through globeShot();
+ window.Globe = { canvas, draw, mount, dot, arc, vec, clearMarks }.
+ Console: Chromium logs "GPU stall due to ReadPixels" (preserveDrawingBuffer, which the export's screenshots need):
+ harmless. */
+import * as THREE from './vendor/three.module.js';
+
+const W = SW, Hpx = SH, R0 = Math.min(SW, SH) / 2, DEG = Math.PI / 180;
+const canvas = document.createElement('canvas');
+canvas.width = W; canvas.height = Hpx;
+canvas.style.cssText = `width:${W}px;height:${Hpx}px;display:block`;
+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true });
+renderer.setPixelRatio(1);
+renderer.outputColorSpace = THREE.SRGBColorSpace;
+const scene = new THREE.Scene();
+const cam = new THREE.OrthographicCamera(-1, 1, 1, -1, .01, 100);
+
+// lon/lat (degrees) to a point on the unit sphere, matching SphereGeometry's UVs (u = 0 at lon -180, north up)
+const vec = (lon, lat, r = 1) => new THREE.Vector3(
+ r * Math.cos(lat * DEG) * Math.cos(lon * DEG), r * Math.sin(lat * DEG), -r * Math.cos(lat * DEG) * Math.sin(lon * DEG));
+
+const loader = new THREE.TextureLoader();
+const night = loader.load(new URL('../img/night.webp', import.meta.url).href, () => window.GLOBE_READY = true, undefined,
+ () => { console.error('globe.js: no ../img/night.webp (geo.py --globe makes it)'); window.GLOBE_READY = true; });
+night.colorSpace = THREE.SRGBColorSpace;
+night.anisotropy = renderer.capabilities.getMaxAnisotropy();
+
+const earth = new THREE.Mesh(new THREE.SphereGeometry(1, 160, 120), new THREE.ShaderMaterial({
+ uniforms: { map: { value: night }, gain: { value: 1.6 }, tint: { value: new THREE.Color('#ffcf8a') }, sea: { value: new THREE.Color('#06101c') } },
+ // every varying is read by the fragment shader: an unread one is a warning in Firefox's console on every globe beat
+ vertexShader: `varying vec2 vUv; varying vec3 vN;
+ void main() { vUv = uv; vN = normalize(normalMatrix * normal); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.); }`,
+ fragmentShader: `uniform sampler2D map; uniform float gain; uniform vec3 tint, sea; varying vec2 vUv; varying vec3 vN;
+ void main() { vec3 c = texture2D(map, vUv).rgb; float l = max(c.r, max(c.g, c.b));
+ vec3 lights = tint * pow(l, 1.4) * gain;
+ float rim = pow(1. - max(dot(vN, vec3(0., 0., 1.)), 0.), 3.);
+ vec3 col = sea + c * .35 + lights + vec3(.15, .35, .7) * rim * .35;
+ gl_FragColor = vec4(col, 1.);
+ #include <colorspace_fragment>
+ }`,
+}));
+scene.add(earth);
+
+// atmosphere: a soft glow behind the disc, brightest at the limb and gone by 1.22 radii (a camera-facing sprite)
+const air = (() => {
+ const c = document.createElement('canvas'); c.width = c.height = 512; const x = c.getContext('2d');
+ const g = x.createRadialGradient(256, 256, 0, 256, 256, 256), r0 = 1 / 1.22;
+ g.addColorStop(0, 'rgba(90,150,255,0)'); g.addColorStop(r0 * .96, 'rgba(90,150,255,.0)'); g.addColorStop(r0, 'rgba(110,170,255,.55)');
+ g.addColorStop(r0 + (1 - r0) * .3, 'rgba(80,140,255,.18)'); g.addColorStop(1, 'rgba(60,120,255,0)');
+ x.fillStyle = g; x.fillRect(0, 0, 512, 512);
+ const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), transparent: true, depthWrite: false, depthTest: false, blending: THREE.AdditiveBlending }));
+ s.scale.setScalar(2.44); s.renderOrder = -1; return s;
+})();
+scene.add(air);
+
+// stars: fixed points far behind, on their own seed
+const stars = (() => {
+ let s = 7; const R = () => (s = (s * 16807) % 2147483647) / 2147483647;
+ const p = [];
+ for (let i = 0; i < 2500; i++) { const u = R() * 2 - 1, a = R() * Math.PI * 2, r = 40; p.push(r * Math.sqrt(1 - u * u) * Math.cos(a), r * u, r * Math.sqrt(1 - u * u) * Math.sin(a)); }
+ const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(p, 3));
+ return new THREE.Points(g, new THREE.PointsMaterial({ color: 0xc8d8ff, size: 1.6, sizeAttenuation: false, transparent: true, opacity: .7 }));
+})();
+scene.add(stars);
+
+// glowing points (cities with cases) and arcs (where the virus travelled): built once, shown by draw()
+const dots = new THREE.Group(); scene.add(dots);
+const dotTex = (() => { const c = document.createElement('canvas'); c.width = c.height = 64; const x = c.getContext('2d');
+ const g = x.createRadialGradient(32, 32, 0, 32, 32, 32); g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(.25, 'rgba(255,90,70,.95)'); g.addColorStop(1, 'rgba(255,40,30,0)');
+ x.fillStyle = g; x.fillRect(0, 0, 64, 64); return new THREE.CanvasTexture(c); })();
+function dot(lon, lat) {
+ const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: dotTex, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }));
+ s.position.copy(vec(lon, lat, 1.002)); s.visible = false; dots.add(s); return s;
+}
+const arcs = new THREE.Group(); scene.add(arcs);
+function arc(a, b, lift = .25, color = 0xff6a50) {
+ const A = vec(...a), B = vec(...b), n = 96, pts = [];
+ for (let i = 0; i <= n; i++) {
+ const q = i / n, p = A.clone().lerp(B, q).normalize(), ang = A.angleTo(B);
+ pts.push(p.multiplyScalar(1 + lift * ang / Math.PI * 2 * Math.sin(Math.PI * q) + .003));
+ }
+ const g = new THREE.BufferGeometry().setFromPoints(pts);
+ const l = new THREE.Line(g, new THREE.LineBasicMaterial({ color, transparent: true, opacity: .95, blending: THREE.AdditiveBlending }));
+ l.geometry.setDrawRange(0, 0); l._n = n + 1; arcs.add(l); return l;
+}
+
+/* draw a view: lon/lat the point at the screen centre (north up), H the half-height of the view in globe radii
+ (1.15 shows the whole Earth across the frame), dx/dy shift the frame in screen px, roll in degrees, opacity of the canvas,
+ lights gain; dotsOn(i) → 0..1 per dot, arcsOn(i) → 0..1 drawn fraction per arc. */
+function draw({ lon = 0, lat = 0, H = 1.15, dx = 0, dy = 0, roll = 0, gain = 1.6, dotScale = .03 } = {}, dotsOn, arcsOn) {
+ const k = R0 / H; // stage px per globe radius
+ cam.left = (-W / 2 - dx) / k; cam.right = (W / 2 - dx) / k; cam.top = (Hpx / 2 + dy) / k; cam.bottom = (-Hpx / 2 + dy) / k;
+ cam.updateProjectionMatrix();
+ cam.position.copy(vec(lon, lat, 10)); cam.up.set(0, 1, 0); cam.lookAt(0, 0, 0);
+ if (roll) cam.rotateZ(roll * DEG);
+ earth.material.uniforms.gain.value = gain;
+ dots.children.forEach((s, i) => { const v = dotsOn ? dotsOn(i) : 0; s.visible = v > 0; s.material.opacity = v; s.scale.setScalar(dotScale * H * (.6 + .4 * v)); });
+ arcs.children.forEach((l, i) => { const v = arcsOn ? arcsOn(i) : 0; l.visible = v > 0; l.geometry.setDrawRange(0, Math.round(l._n * v)); });
+ stars.material.opacity = Math.min(.7, .7 * (H - .3) / .8);
+ renderer.render(scene, cam);
+}
+
+// put the canvas into a panel: returns the foreignObject (fade it like any element)
+function mount(p) {
+ const fo = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
+ fo.setAttribute('x', 0); fo.setAttribute('y', 0); fo.setAttribute('width', W); fo.setAttribute('height', Hpx);
+ const g = G(p, {}); g.appendChild(fo); fo.appendChild(canvas);
+ return g;
+}
+
+window.Globe = { canvas, draw, mount, dot, arc, vec, clearMarks: () => { dots.clear(); arcs.clear(); } };
diff --git a/.claude/skills/papermorph/assets/templates/maps/lib/map.js b/.claude/skills/papermorph/assets/templates/maps/lib/map.js
new file mode 100644
index 0000000..69fee04
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/maps/lib/map.js
@@ -0,0 +1,309 @@
+/* map.js: the map kit, a paper map and a night globe on one view, for an upright short (900 x 1600) and a landscape
+ documentary (1600 x 900) alike: the stage is the engine's SW x SH. Pure functions of the beat clock, like the kits.
+ Loaded after engine.js and ../img/geo-lite.js (geo.py), before the chapter; the globe (lib/globe.js, three.js in
+ lib/vendor/ and img/night.webp, also from geo.py --globe) loads with loadGlobe(). Works beside shorts.js or film.js;
+ it uses only the engine's helpers and its own colours.
+
+ A view is { lon, lat, H, dx, dy, roll }: the point at the stage centre, the Earth's radius as 450 / H stage px (1.15
+ the whole world, .42 China, .1 a country like Italy, .02 a province, .003 a city), the frame shifted by dx, dy px,
+ turned clockwise by roll degrees. The globe and the paper map take the same view(t), so a shot hands over from one to
+ the other without a jump: put both in the shot, fade the map's group in over a few tenths, and give each an `on`.
+
+ paperMap(p, D, view, opts) -> M the paper map in this panel; opts, all optional:
+ lit(iso, t) -> 0..1 a country lit (iso as in geo-lite.js: ISO 3166 alpha-3, 'CHN', 'ITA', 'ATA')
+ litFill: MAP_COL.hot the fill of lit and region: a colour, or (key) => colour to mix several
+ region(name, t, iso) -> 0..1 a region lit ('Hubei', 'Lombardia': geo.py --regions CHN,ITA:region)
+ regions: true | ['CHN'] draw the borders of every region in the data (true) or of these countries'
+ hatch(key, t) -> 0..1 ink hatching over a country (iso) or a region (name): an order, a lockdown, what
+ is not the colour of the film's subject
+ areas: [[shape, at, style]] an area of your own: shape an iso ('ITA'), 'ITA/Lombardia', or rings of
+ [lon, lat] (mapCircle(ll, km) is one); at a time (shown over .35 s) or (t) -> 0..1;
+ style { fill: 'hatch' | colour | null, line: MAP_COL.ink | null, width: 3 }
+ detail: 'Wuhan' | true rivers, lakes and built-up areas of a place cut by geo.py --detail, faded in as
+ the view closes in (H .22 to .06) and drawn under the marks
+ dots: [[lon, lat, t0, r = 7]] dots in MAP_COL.hot popping in at t0, r px
+ routes: [[[lon, lat], [lon, lat], t0, dur = .8]] an arc drawn from a to b; a dot lands at b when it arrives
+ cities: [[name, t0, side]] an ink dot and a label (CITIES; side 'l' or 'r', default 'r'); labels keep
+ inside the safe box and hide when their city is off it
+ labelSize: 36 · safe: [x0, y0, x1, y1] (the shorts' 50,150,810,1290 upright; 60,60,SW-60,SH-230 landscape)
+ on: [t0, t1] drawn only then. Default: the shot's window when p is a shorts shot(), else the
+ whole beat. A layer that is covered (the globe after the hand-over, a map under
+ a later shot) must not be drawn: Firefox pays for every drawn canvas
+ bg: MAP_COL.night | null the ground around the disc (null: transparent) · px: 1 canvas px per stage px
+ M = { g, view(t), xy(ll, t) -> [x, y] stage px or null behind the globe }: draw your own marks above M.g with M.xy.
+ The map redraws only when something on it changes: a view that holds still with nothing popping costs nothing a
+ frame, and its projected shapes are kept while the view holds. Labels, dots and routes may start at any time.
+ Move a map through its view(t), never by scaling a group above it: Gecko re-rasters a canvas under a scaled parent.
+
+ globeShot(p, D, view, dotsOn, arcsOn, { on }) the night globe here (one WebGL canvas for the whole film, moved into
+ each beat); marks from Globe.clearMarks() / Globe.dot(lon, lat) / Globe.arc(a, b);
+ dotsOn(i, t), arcsOn(i, t) -> 0..1; the view may add gain (city lights, 1.6) and
+ dotScale. on as for paperMap
+ loadGlobe() -> Promise loads lib/globe.js and its texture: loadGlobe().then(startShorts) (or boot)
+ mapXY(ll, v) -> [x, y] | null a lon/lat to stage px for a view (globe and map alike), null on the far side
+ mapKeys([[t, lon, lat, H, dx, dy]...], ease = io) -> view(t) a camera through keys, eased between them, the first
+ held from 0 and the last after; lon takes the short way round, H changes evenly
+ mapRings(key) -> [[lon, lat]...][] a country's ('ITA') or region's ('ITA/Lombardia') outline, for areas or SVG
+ mapCircle([lon, lat], km) -> ring a circle on the ground, for areas
+ CITIES {name: [lon, lat]} from geo-lite.js (capitals, big cities, geo.py --cities)
+ MAP_COL land, sea, ink, line, night, hot (marks; book.css --red), mark, urban, river:
+ each from book.css --map-<name> when set (--map-land: #ece3cd) */
+'use strict';
+const { paperMap, globeShot, loadGlobe, mapXY, mapKeys, mapRings, mapCircle, CITIES, MAP_COL } = (() => {
+ const DEG = Math.PI / 180, R0 = Math.min(SW, SH) / 2; // the Earth's radius at H = 1, in stage px
+ const X = document.createElement('canvas').getContext('2d');
+ const css = (k, d) => { X.fillStyle = d; X.fillStyle = bookSetting(k) || d; return X.fillStyle; };
+ const MAP_COL = { land: css('--map-land', '#ece3cd'), sea: css('--map-sea', '#bfcac6'), ink: css('--map-ink', '#2b2520'),
+ line: css('--map-line', '#9a8a70'), night: css('--map-night', '#04060a'), hot: css('--map-hot', css('--red', '#c8281e')),
+ mark: css('--map-mark', css('--mark', '#f4c430')), urban: css('--map-urban', '#cdb995'), river: css('--map-river', '#8fa9ad') };
+ const FONT = bookSetting('--map-font') || '"Oswald", "Arial Narrow", sans-serif';
+ const PORTRAIT = SH > SW, SAFE = PORTRAIT ? [50, 150, 810, 1290] : [60, 60, SW - 60, SH - 230];
+ const clamp01 = v => Math.min(1, Math.max(0, v)), ramp = (t, a, b) => clamp01((t - a) / (b - a));
+ const within = (t, on) => !on || (t >= on[0] && t <= on[1]);
+ // a shorts shot() records its window on its group: the default `on` of a map or globe inside it
+ const shotOn = p => { for (let e = p; e && e.nodeType === 1; e = e.parentNode) if (e._on) return e._on; };
+
+ /* ---------- data ---------- */
+ const unpack = (rs, q = 100) => rs.map(r => { // delta integers -> {lam, cphi, sphi, c: centre unit vector, rad}
+ const n = r.length / 2, lam = new Float32Array(n), cphi = new Float32Array(n), sphi = new Float32Array(n);
+ let x = 0, y = 0, cx = 0, cy = 0, cz = 0;
+ for (let i = 0; i < n; i++) {
+ x += r[2 * i]; y += r[2 * i + 1];
+ lam[i] = x / q * DEG; const f = y / q * DEG; cphi[i] = Math.cos(f); sphi[i] = Math.sin(f);
+ cx += cphi[i] * Math.cos(lam[i]); cy += cphi[i] * Math.sin(lam[i]); cz += sphi[i];
+ }
+ const l = Math.hypot(cx, cy, cz) || 1; cx /= l; cy /= l; cz /= l;
+ let rad = 0;
+ for (let i = 0; i < n; i++) rad = Math.max(rad, Math.acos(Math.min(1, cphi[i] * Math.cos(lam[i]) * cx + cphi[i] * Math.sin(lam[i]) * cy + sphi[i] * cz)));
+ return { n, lam, cphi, sphi, c: [cx, cy, cz], rad };
+ });
+ const GL = window.GEO_LITE || { lod: [{}, {}], cities: {} };
+ if (!window.GEO_LITE) console.error('map.js: no GEO_LITE; load ../img/geo-lite.js (made by geo.py) before map.js');
+ const each = (o, f) => Object.fromEntries(Object.entries(o || {}).map(([k, v]) => [k, f(v)]));
+ let DATA;
+ const data = () => DATA || (DATA = {
+ lod: GL.lod.map(L => each(L, rs => unpack(rs))),
+ regions: each(GL.regions, R => each(R, rs => unpack(rs))),
+ detail: each(GL.detail, d => ({ lakes: unpack(d.lakes, 1e4), urban: unpack(d.urban, 1e4), rivers: unpack(d.rivers, 1e4) })),
+ });
+ const decode = (rs, q = 100) => rs.map(r => { const o = []; let x = 0, y = 0; for (let i = 0; i < r.length; i += 2) { x += r[i]; y += r[i + 1]; o.push([x / q, y / q]); } return o; });
+ const rawShape = key => { const [c, n] = key.split('/'); return n ? GL.regions?.[c]?.[n] : GL.lod[1][c] || GL.lod[0][c]; };
+ function mapRings(key) {
+ const rs = rawShape(key);
+ if (!rs) throw new Error(`mapRings: no ${key} in geo-lite.js`);
+ return decode(rs);
+ }
+ const mapCircle = ([lon, lat], km) => [...Array(48)].map((_, i) => { const a = i / 48 * 2 * Math.PI; return [lon + km / 111.2 / Math.cos(lat * DEG) * Math.cos(a), lat + km / 111.2 * Math.sin(a)]; });
+ // lon/lat rings given by hand, packed like the data so they project the same way
+ const pack = rings => unpack((typeof rings[0][0] === 'number' ? [rings] : rings).map(r => {
+ const o = []; let px = 0, py = 0; for (const [x, y] of r) { const qx = Math.round(x * 1e4), qy = Math.round(y * 1e4); o.push(qx - px, qy - py); px = qx; py = qy; } return o; }), 1e4);
+
+ /* ---------- views ---------- */
+ function mapXY([lon, lat], v) {
+ const k = R0 / v.H, dl = (lon - v.lon) * DEG, f = lat * DEG, f0 = v.lat * DEG;
+ if (Math.sin(f0) * Math.sin(f) + Math.cos(f0) * Math.cos(f) * Math.cos(dl) < 0) return null;
+ let x = Math.cos(f) * Math.sin(dl), y = Math.cos(f0) * Math.sin(f) - Math.sin(f0) * Math.cos(f) * Math.cos(dl);
+ if (v.roll) { const c = Math.cos(v.roll * DEG), s = Math.sin(v.roll * DEG); [x, y] = [x * c + y * s, y * c - x * s]; }
+ return [SW / 2 + (v.dx || 0) + k * x, SH / 2 + (v.dy || 0) - k * y];
+ }
+ function mapKeys(K, ease = io) {
+ return t => {
+ let i = 0; while (i < K.length - 2 && t > K[i + 1][0]) i++;
+ const [t0, l0, f0, h0, x0 = 0, y0 = 0] = K[i], [t1, l1, f1, h1, x1 = 0, y1 = 0] = K[Math.min(i + 1, K.length - 1)];
+ const q = t1 > t0 ? ease(ramp(t, t0, t1)) : 1, dl = ((l1 - l0) % 360 + 540) % 360 - 180; // the short way round
+ return { lon: l0 + dl * q, lat: f0 + (f1 - f0) * q, H: h0 * (h1 / h0) ** q, dx: x0 + (x1 - x0) * q, dy: y0 + (y1 - y0) * q };
+ };
+ }
+
+ /* ---------- the paper map ---------- */
+ // a colour with a paper grain multiplied in, as a pattern fixed to the canvas: baked once, free every frame (a grain
+ // blended over the whole canvas each frame cost Firefox 7 ms)
+ const GRAIN = {};
+ let NOISE;
+ function grained(ctx, colour) {
+ if (!NOISE) {
+ NOISE = document.createElement('canvas'); NOISE.width = NOISE.height = 256;
+ const x = NOISE.getContext('2d'), im = x.createImageData(256, 256);
+ let s = 11; const R = () => (s = (s * 16807) % 2147483647) / 2147483647;
+ for (let i = 0; i < im.data.length; i += 4) { const v = 255 - R() * R() * 70; im.data[i] = im.data[i + 1] = im.data[i + 2] = v; im.data[i + 3] = 255; }
+ x.putImageData(im, 0, 0);
+ }
+ if (!GRAIN[colour]) {
+ const c = document.createElement('canvas'); c.width = c.height = 256;
+ const x = c.getContext('2d'); x.fillStyle = colour; x.fillRect(0, 0, 256, 256);
+ x.globalCompositeOperation = 'multiply'; x.globalAlpha = .5; x.drawImage(NOISE, 0, 0);
+ GRAIN[colour] = c;
+ }
+ return ctx.createPattern(GRAIN[colour], 'repeat');
+ }
+ function hatchPattern(ctx) {
+ const tile = document.createElement('canvas'); tile.width = tile.height = 12;
+ const tc = tile.getContext('2d'); tc.strokeStyle = MAP_COL.ink; tc.lineWidth = 2.6;
+ tc.beginPath(); tc.moveTo(-3, 15); tc.lineTo(15, -3); tc.moveTo(-3, 3); tc.lineTo(3, -3); tc.moveTo(9, 15); tc.lineTo(15, 9); tc.stroke();
+ return ctx.createPattern(tile, 'repeat');
+ }
+ const measure = (str, size) => { X.font = `600 ${size}px ${FONT}`; return X.measureText(str).width; };
+ const backEase = typeof back === 'function' ? back : out;
+
+ function paperMap(p, D, view, { lit, litFill, region, regions = false, hatch, areas = [], detail, dots = [], routes = [],
+ cities = [], labelSize = 36, safe = SAFE, on = shotOn(p), bg = MAP_COL.night, px = 1 } = {}) {
+ const fillOf = typeof litFill === 'function' ? litFill : () => litFill || MAP_COL.hot;
+ const geo = data();
+ const g = G(p, {}), fo = mk('foreignObject', { x: 0, y: 0, width: SW, height: SH }, g);
+ const cv = document.createElement('canvas'); cv.width = SW * px; cv.height = SH * px;
+ cv.style.cssText = `width:${SW}px;height:${SH}px;display:block`;
+ fo.appendChild(cv);
+ const ctx = cv.getContext('2d'), land = grained(ctx, MAP_COL.land), sea = grained(ctx, MAP_COL.sea), hatchFill = hatchPattern(ctx);
+ const lab = G(g, {});
+ const labels = cities.map(([name, t0, side = 'r']) => {
+ if (!CITIES[name]) throw new Error(`paperMap: no city ${name} in geo-lite.js (geo.py --cities)`);
+ const e = G(lab, { o: 0 }), w = measure(name.toUpperCase(), labelSize);
+ const tx = T(e, name.toUpperCase(), { x: 0, y: 0, size: labelSize, fill: MAP_COL.ink, font: FONT, weight: 600, anchor: 'start' });
+ tx.setAttribute('stroke', MAP_COL.land); tx.setAttribute('stroke-width', labelSize / 5); tx.setAttribute('paint-order', 'stroke'); tx.setAttribute('stroke-linejoin', 'round');
+ return { e, ll: CITIES[name], t0, side, w };
+ });
+ const rkeys = regions === true ? Object.keys(geo.regions) : regions || [];
+ const regionSets = Object.entries(geo.regions).flatMap(([c, R]) => Object.entries(R).map(([n, rs]) => ({ c, n, rs })));
+ const AREAS = areas.map(([shape, at, style = {}]) => {
+ const rs = typeof shape === 'string'
+ ? (shape.includes('/') ? geo.regions[shape.split('/')[0]]?.[shape.split('/')[1]] : geo.lod[1][shape] || geo.lod[0][shape]) : pack(shape);
+ if (!rs) throw new Error(`paperMap: no area ${shape} in geo-lite.js`);
+ return { rs, a: typeof at === 'function' ? at : t => ramp(t, at, at + .35), fill: 'fill' in style ? style.fill : 'hatch',
+ line: 'line' in style ? style.line : MAP_COL.ink, width: style.width ?? 3 };
+ });
+ const details = detail === true ? Object.values(geo.detail) : detail ? [geo.detail[detail]] : [];
+ if (details.some(d => !d)) throw new Error(`paperMap: no detail ${detail} in geo-lite.js (geo.py --detail)`);
+ const vf = t => ({ lon: 0, lat: 0, H: 1.15, ...view(t) });
+
+ // project rings into a Path2D for view v; open: a river, not closed
+ function addRing(P, r, v, open) {
+ const { l0, sf0, cf0, k, cx, cy } = v;
+ let lx = 1e9, ly = 1e9;
+ for (let i = 0; i < r.n; i++) {
+ const dl = r.lam[i] - l0, cdl = Math.cos(dl), cp = r.cphi[i], sp = r.sphi[i];
+ let x = cp * Math.sin(dl), y = cf0 * sp - sf0 * cp * cdl;
+ if (sf0 * sp + cf0 * cp * cdl < 0) { const l = Math.hypot(x, y) || 1; x /= l; y /= l; } // far side: onto the rim
+ const Xp = cx + k * x, Yp = cy - k * y;
+ if (!i) { P.moveTo(Xp, Yp); lx = Xp; ly = Yp; }
+ else if (Math.abs(Xp - lx) + Math.abs(Yp - ly) > 1 || i === r.n - 1) { P.lineTo(Xp, Yp); lx = Xp; ly = Yp; } // under a pixel: dropped
+ }
+ if (!open) P.closePath();
+ }
+ const visible = (r, v) => {
+ const d = Math.acos(Math.max(-1, Math.min(1, r.c[0] * v.ex + r.c[1] * v.ey + r.c[2] * v.ez)));
+ return d - r.rad < v.reach && r.rad * v.k > .6;
+ };
+ // projected shapes are cached while the view holds: a lit country fading in costs a fill, not a projection
+ let cacheSig, cache;
+ const shape = (id, rs, v, open) => {
+ if (!cache.has(id)) { const P = new Path2D(); for (const r of rs || []) if (visible(r, v)) addRing(P, r, v, open); cache.set(id, P); }
+ return cache.get(id);
+ };
+
+ let drawn = null; // the signature of what is on the canvas: nothing changed, nothing drawn
+ clockRun(t => {
+ if (!within(t, on)) return;
+ const s = vf(t), k = R0 / s.H;
+ const L = k > 900 ? geo.lod[1] : geo.lod[0], keys = Object.keys(L);
+ const pop = (t0, d = .25) => { const q = ramp(t, t0, t0 + d); return q && backEase(q); };
+ const vals = {
+ lit: lit ? keys.map(c => clamp01(lit(c, t))) : [],
+ reg: region ? regionSets.map(R => clamp01(region(R.n, t, R.c))) : [],
+ hat: hatch ? [...keys, ...regionSets.map(R => R.n)].map(c => clamp01(hatch(c, t))) : [],
+ area: AREAS.map(A => clamp01(A.a(t))),
+ det: details.length ? ramp(k, R0 / .22, R0 / .06) : 0,
+ route: routes.map(([, , t0, dur = .8]) => ramp(t, t0, t0 + dur) + pop(t0 + dur)),
+ dot: dots.map(d => pop(d[2])),
+ lab: labels.map(l => ramp(t, l.t0, l.t0 + .3)),
+ };
+ const vsig = [s.lon, s.lat, s.H, s.dx || 0, s.dy || 0, s.roll || 0].map(n => n.toFixed(5)).join();
+ const sig = vsig + JSON.stringify(vals);
+ if (sig === drawn) return;
+ drawn = sig;
+ const l0 = s.lon * DEG, f0 = s.lat * DEG;
+ const v = { l0, sf0: Math.sin(f0), cf0: Math.cos(f0), k, cx: SW / 2 + (s.dx || 0), cy: SH / 2 + (s.dy || 0),
+ ex: Math.cos(f0) * Math.cos(l0), ey: Math.cos(f0) * Math.sin(l0), ez: Math.sin(f0) };
+ const diag = Math.hypot(SW / 2 + Math.abs(s.dx || 0), SH / 2 + Math.abs(s.dy || 0));
+ v.reach = diag >= k ? Math.PI / 2 : Math.asin(diag / k);
+ if (vsig !== cacheSig) { cacheSig = vsig; cache = new Map(); }
+ ctx.setTransform(px, 0, 0, px, 0, 0);
+ if (bg) { ctx.fillStyle = bg; ctx.fillRect(0, 0, SW, SH); } else ctx.clearRect(0, 0, SW, SH);
+ // roll: clockwise, as the globe's camera and mapXY turn it
+ if (s.roll) { ctx.translate(v.cx, v.cy); ctx.rotate(s.roll * DEG); ctx.translate(-v.cx, -v.cy); }
+ const disc = new Path2D(); disc.arc(v.cx, v.cy, k, 0, 2 * Math.PI);
+ ctx.fillStyle = sea; ctx.fill(disc);
+ ctx.save(); ctx.clip(disc);
+ const all = shape('all', keys.flatMap(c => L[c]), v);
+ ctx.fillStyle = land; ctx.fill(all);
+ ctx.strokeStyle = MAP_COL.line; ctx.lineWidth = 1; ctx.lineJoin = 'bevel'; ctx.stroke(all); // round joins: most of a 10 ms stroke
+ const fillA = (P, a, f) => { if (a > 0) { ctx.globalAlpha = a * .85; ctx.fillStyle = f; ctx.fill(P); ctx.globalAlpha = 1; } };
+ keys.forEach((c, i) => vals.lit[i] && fillA(shape('c' + c, L[c], v), vals.lit[i], fillOf(c)));
+ regionSets.forEach((R, i) => vals.reg[i] && fillA(shape('r' + R.c + R.n, R.rs, v), vals.reg[i], fillOf(R.n)));
+ if (rkeys.length) {
+ const P = shape('borders', regionSets.filter(R => rkeys.includes(R.c)).flatMap(R => R.rs), v);
+ ctx.setLineDash([4, 3]); ctx.lineWidth = .9; ctx.strokeStyle = MAP_COL.line; ctx.stroke(P); ctx.setLineDash([]);
+ }
+ if (vals.det) for (const [j, d] of details.entries()) {
+ ctx.globalAlpha = .8 * vals.det; ctx.fillStyle = MAP_COL.urban; ctx.fill(shape('du' + j, d.urban, v));
+ ctx.globalAlpha = vals.det; ctx.fillStyle = sea; const lk = shape('dl' + j, d.lakes, v); ctx.fill(lk);
+ ctx.strokeStyle = MAP_COL.river; ctx.lineJoin = 'round'; ctx.lineWidth = 1; ctx.stroke(lk);
+ ctx.lineWidth = Math.min(5, k / 4000); ctx.lineCap = 'round'; ctx.stroke(shape('dr' + j, d.rivers, v, true));
+ ctx.globalAlpha = 1; ctx.lineJoin = 'bevel';
+ }
+ const hatchA = (P, a) => { if (a > 0) { ctx.globalAlpha = a * .7; ctx.fillStyle = hatchFill; ctx.fill(P); ctx.globalAlpha = a * .12; ctx.fillStyle = MAP_COL.ink; ctx.fill(P); ctx.globalAlpha = 1; } };
+ if (hatch) {
+ keys.forEach((c, i) => vals.hat[i] && hatchA(shape('c' + c, L[c], v), vals.hat[i]));
+ regionSets.forEach((R, i) => vals.hat[keys.length + i] && hatchA(shape('r' + R.c + R.n, R.rs, v), vals.hat[keys.length + i]));
+ }
+ AREAS.forEach((A, i) => {
+ const a = vals.area[i]; if (!a) return;
+ const P = shape('a' + i, A.rs, v);
+ if (A.fill === 'hatch') hatchA(P, a); else if (A.fill) fillA(P, a / .85, A.fill);
+ if (A.line) { ctx.globalAlpha = a; ctx.strokeStyle = A.line; ctx.lineWidth = A.width; ctx.lineJoin = 'round'; ctx.stroke(P); ctx.globalAlpha = 1; ctx.lineJoin = 'bevel'; }
+ });
+ ctx.restore();
+ // marks in stage px, so they keep their size at every zoom
+ const xy = ll => mapXY(ll, { ...s, roll: 0 });
+ ctx.save(); ctx.clip(disc); // arcs over the rim would float in space
+ ctx.strokeStyle = MAP_COL.hot; ctx.lineWidth = 3.5; ctx.lineCap = 'round';
+ routes.forEach(([a, b, t0, dur = .8]) => {
+ const q = ramp(t, t0, t0 + dur), A = xy(a), B = xy(b);
+ if (!q || !A || !B) return;
+ const lift = Math.hypot(B[0] - A[0], B[1] - A[1]) * .25, mx = (A[0] + B[0]) / 2, my = (A[1] + B[1]) / 2 - lift;
+ ctx.beginPath(); ctx.moveTo(...A);
+ for (let i = 1; i <= 24 * q; i++) { const u = i / 24; ctx.lineTo((1 - u) ** 2 * A[0] + 2 * u * (1 - u) * mx + u * u * B[0], (1 - u) ** 2 * A[1] + 2 * u * (1 - u) * my + u * u * B[1]); }
+ ctx.stroke();
+ if (q >= 1) dotAt(B, 7 * pop(t0 + dur));
+ });
+ ctx.restore();
+ dots.forEach(([lon, lat, , r = 7], i) => { const P = xy([lon, lat]); if (P) dotAt(P, r * vals.dot[i]); });
+ ctx.fillStyle = MAP_COL.ink;
+ labels.forEach((l, i) => {
+ const P = xy(l.ll), a = vals.lab[i];
+ if (P && a) { ctx.globalAlpha = a; ctx.beginPath(); ctx.arc(P[0], P[1], 5, 0, 2 * Math.PI); ctx.fill(); ctx.globalAlpha = 1; }
+ const Q = s.roll ? mapXY(l.ll, s) : P; // the canvas is turned by the roll, the SVG labels are not
+ if (!Q || Q[0] < safe[0] || Q[0] > safe[2] || Q[1] < safe[1] || Q[1] > safe[3]) return put(l.e, { o: 0 });
+ let x = l.side === 'l' ? Q[0] - 14 - l.w : Q[0] + 14;
+ if (x + l.w > safe[2]) x = Q[0] - 14 - l.w; if (x < safe[0]) x = Q[0] + 14;
+ put(l.e, { x: Math.max(safe[0], Math.min(safe[2] - l.w, x)), y: Math.max(safe[1] + labelSize * .8, Math.min(safe[3], Q[1] + labelSize * .3)), o: a });
+ });
+ }, D, { tail: true });
+ function dotAt([x, y], r) {
+ if (r <= 0) return;
+ ctx.fillStyle = MAP_COL.hot; ctx.beginPath(); ctx.arc(x, y, r, 0, 2 * Math.PI); ctx.fill();
+ ctx.globalAlpha = .25; ctx.beginPath(); ctx.arc(x, y, r * 2.2, 0, 2 * Math.PI); ctx.fill(); ctx.globalAlpha = 1;
+ }
+ return { g, view: vf, xy: (ll, t) => mapXY(ll, vf(t)) };
+ }
+
+ /* ---------- the globe ---------- */
+ function globeShot(p, D, view, dotsOn, arcsOn, { on = shotOn(p) } = {}) {
+ if (!window.Globe) throw new Error('globeShot: the globe is not loaded; start the chapter with loadGlobe().then(...)');
+ const g = Globe.mount(p);
+ clockRun(t => within(t, on) && Globe.draw({ H: 1.15, ...view(t) }, dotsOn && (i => dotsOn(i, t)), arcsOn && (i => arcsOn(i, t))), D, { tail: true });
+ return g;
+ }
+ const loadGlobe = () => import('./globe.js').then(() => new Promise(r => { (function w() { window.GLOBE_READY ? r() : setTimeout(w, 30); })(); }));
+
+ return { paperMap, globeShot, loadGlobe, mapXY, mapKeys, mapRings, mapCircle, CITIES: GL.cities, MAP_COL };
+})();
diff --git a/.claude/skills/papermorph/assets/templates/maps/sample.html b/.claude/skills/papermorph/assets/templates/maps/sample.html
new file mode 100644
index 0000000..0fc67db
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/maps/sample.html
@@ -0,0 +1,91 @@
+<!doctype html>
+<html lang="en" data-stage="portrait">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Map kit · sample</title>
+<link rel="stylesheet" href="../lib/engine.css">
+<link rel="expect" href="#bar" blocking="render">
+</head>
+<body>
+<!-- The map kit's sample, upright; ?wide plays it on the landscape stage. Four beats prove the pieces: the globe handing
+ over to the paper map, a lit country, a region, routes and labels; hatching and an area; a city's detail; a map that
+ holds still. Not a chapter: it has no narration, so its beats are given lengths below and their clips are silence.
+ To play it, in site/<book>/ after engine.py (and the shorts or documentary kit's lib/, for book.css and the fonts):
+ cp assets/templates/maps/lib/* site/<book>/lib/ && mkdir -p site/<book>/maps && cp assets/templates/maps/sample.html site/<book>/maps/index.html
+ uv run --with pillow --with shapely python3 scripts/geo.py site/<book>/img --regions CHN,ITA:region \
+ --detail Wuhan=114.27,30.58,1.2 --cities Codogno=9.705,45.16,Bergamo,Milan,Wuhan --globe site/<book>/lib
+ mkdir -p site/<book>/maps/audio/en && for b in globe orders wuhan still; do
+ ffmpeg -v error -f lavfi -i anullsrc=r=44100:cl=mono -t 7 -q:a 9 site/<book>/maps/audio/en/$b.mp3; done -->
+<script>if (new URLSearchParams(location.search).has('wide')) document.documentElement.dataset.stage = 'landscape';</script>
+<script src="../lib/engine.js"></script>
+<script>window.TIMINGS = Object.fromEntries(['globe', 'orders', 'wuhan', 'still'].map(id => [id, { dur: 6.4, marks: {}, cues: [] }]));</script>
+<script src="../img/geo-lite.js"></script>
+<script src="../lib/map.js"></script>
+<script>
+'use strict';
+const CHAPTER = { number: 0, title: 'Map kit', minutes: 1, language: 'en', lead: false };
+function say(p, str, t0, y = SH > SW ? 250 : 110) {
+ const e = T(p, str.toUpperCase(), { x: SW / 2, y, size: SH > SW ? 80 : 64, fill: MAP_COL.land, font: '"Oswald", sans-serif', weight: 600, anchor: 'middle', o: 0 });
+ e.setAttribute('stroke', MAP_COL.ink); e.setAttribute('stroke-width', 8); e.setAttribute('paint-order', 'stroke'); e.setAttribute('stroke-linejoin', 'round');
+ show(e, t0, .3);
+}
+const ramp01 = (t, a, b) => Math.min(1, Math.max(0, (t - a) / (b - a)));
+const MILAN = CITIES.Milan, WUHAN = CITIES.Wuhan;
+
+const BEATS = [
+ // the globe turns to Italy and hands over to the paper map at 1.8 s: the same view, so nothing jumps; Lombardy lit,
+ // routes out of Milan, labels
+ ['globe', 'Globe to map', (m, D) => {
+ const p = panel(0), tH = 1.8;
+ mk('rect', { x: 0, y: 0, width: SW, height: SH, fill: MAP_COL.night }, p);
+ const view = mapKeys([[0, 60, 20, 1.1], [tH + .2, 10, 44, .16], [D, 4, 42, .3]]);
+ Globe.clearMarks(); Globe.dot(...MILAN);
+ globeShot(p, D, view, () => 1, null, { on: [0, tH + .4] });
+ const mp = G(p, { o: 0 });
+ show(mp, tH, .4, lin);
+ paperMap(mp, D, view, {
+ lit: (c, t) => c === 'ITA' ? .35 * ramp01(t, tH + .3, tH + .6) : 0,
+ region: (n, t) => n === 'Lombardia' ? ramp01(t, tH + .5, tH + .8) : 0,
+ routes: ['Paris', 'London', 'Madrid', 'Berlin'].map((n, i) => [MILAN, CITIES[n], tH + 1.4 + i * .3, .7]),
+ cities: [['Milan', tH + .6, 'l'], ['Paris', tH + 2.1], ['London', tH + 2.4]],
+ on: [tH - .05, D + 1],
+ });
+ say(p, 'Globe to paper', .2);
+ }],
+ // the paper map alone: countries hatched one by one (an order), an area of 15 km hatched and outlined, a lit country
+ ['orders', 'Hatching and an area', (m, D) => {
+ const p = panel(0);
+ const order = ['ITA', 'ESP', 'FRA', 'DEU', 'GBR', 'AUT', 'CHE', 'BEL', 'NLD', 'PRT'];
+ const view = mapKeys([[0, 8, 47, .2], [3, 8, 47, .2], [4.6, 9.7, 45.2, .012]]);
+ paperMap(p, D, view, {
+ hatch: (c, t) => ramp01(t, .3 + order.indexOf(c) * .2, .5 + order.indexOf(c) * .2) * (order.includes(c) ? 1 : 0),
+ lit: (c, t) => c === 'SWE' ? .5 * ramp01(t, 2.6, 2.9) : 0, litFill: MAP_COL.mark,
+ areas: [[[mapCircle(CITIES.Codogno, 15)], 4.4, { fill: MAP_COL.hot, line: MAP_COL.ink }], ['ITA/Lombardia', 3.4, { fill: null, width: 4 }]],
+ cities: [['Codogno', 4.6], ['Bergamo', 4.8]],
+ });
+ say(p, 'Orders, an area', .2);
+ }],
+ // closing in on one city: rivers, lakes and the built-up area fade in as the view closes (geo.py --detail)
+ ['wuhan', 'A city up close', (m, D) => {
+ const p = panel(0);
+ const view = mapKeys([[0, 112, 31, .42], [D - .6, ...WUHAN, .006]]);
+ paperMap(p, D, view, { regions: ['CHN'], region: (n, t) => n === 'Hubei' ? .3 * ramp01(t, .5, 1) * (1 - ramp01(t, 2.5, 3.5)) : 0, detail: 'Wuhan',
+ dots: [[...WUHAN, 4.5, 10]], cities: [['Wuhan', 1]] });
+ say(p, 'A city up close', .2);
+ }],
+ // a view that holds still: drawn while its marks pop, then never again (perf: ~0 ms a frame after 3 s)
+ ['still', 'A still map', (m, D) => {
+ const p = panel(0);
+ paperMap(p, D, () => ({ lon: 15, lat: 30, H: 1.15 }), {
+ dots: Object.keys(CITIES).slice(0, 40).map((n, i) => [...CITIES[n], .3 + i * .06, 5]),
+ cities: [['Tokyo', 1.5], ['Lagos', 1.7], ['London', 1.9, 'l']],
+ });
+ say(p, 'A still map', .2);
+ }],
+].map(([id, title, run, extra]) => ({ id, title, run, ...extra }));
+
+loadGlobe().then(() => document.fonts.load('600 40px Oswald')).then(boot);
+</script>
+</body>
+</html>
diff --git a/.claude/skills/papermorph/scripts/geo.py b/.claude/skills/papermorph/scripts/geo.py
new file mode 100644
index 0000000..2409666
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/geo.py
@@ -0,0 +1,220 @@
+#!/usr/bin/env python3
+"""The map kit's data: countries, regions, cities and a city's detail in lon/lat, from Natural Earth (public domain).
+
+ python3 geo.py site/<book>/img # img/geo-lite.js: the world, capitals and big cities
+ python3 geo.py site/<book>/img --regions CHN,ITA:region # + China's provinces, Italy's regions
+ python3 geo.py site/<book>/img --detail Wuhan=114.27,30.58,1.5 # + rivers, lakes and built-up areas 1.5 deg around
+ python3 geo.py site/<book>/img --cities Codogno=9.705,45.16,Bergamo # + named places (a name, or name=lon,lat)
+ uv run --with pillow python3 geo.py site/<book>/img --globe site/<book>/lib # + the globe: three.js and night.webp
+
+Writes window.GEO_LITE for assets/templates/maps/lib/map.js (paperMap, globeShot): lod[0] 110m countries for wide views,
+lod[1] 50m thinned to 0.02 deg for close ones, both keyed by ISO 3166 alpha-3 ('CHN', 'FRA', 'ATA' Antarctica included);
+regions[ISO][name] admin-1 at 0.02 deg, by English name ('Hubei'), or merged by another Natural Earth field after a colon
+(ITA:region gives Italy's 20 regions, 'Lombardia', instead of its 110 provinces: with shapely installed, uv run --with
+shapely, each is dissolved into one outline, else its provinces' borders show inside it); cities {name: [lon, lat]};
+detail[name] {c: centre, lakes, urban, rivers} at 10m. Rings are
+delta-encoded integers (hundredths of a degree, detail ten-thousandths). Only outer rings: holes are lakes, the sea shows.
+The world alone is about 400 KB; each region set and detail cut adds to it, so ask for the ones the film shows.
+
+Natural Earth's GeoJSON is downloaded once from github.com/nvkelso/natural-earth-vector into ~/.cache/papermorph/ne
+(the 10m regions file is 39 MB, the detail files 40 MB), or read from --ne DIR when you already have the files.
+--globe also writes LIB/vendor/three.module.js, three.core.js and three.LICENSE (three.js r186, MIT) and
+IMG/night.webp from NASA's Black Marble 2016 (public domain; --night-width 8192 px, the film's; 4096 is lighter); that
+step needs Pillow (the uv line above). Credit the picture in the film's sources: "Black Marble 2016, NASA Earth
+Observatory, public domain"; the map: "Natural Earth, public domain".
+"""
+import argparse, json, pathlib, sys, urllib.request
+
+NE = 'https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/'
+THREE = 'https://cdn.jsdelivr.net/npm/[email protected]/'
+NIGHT = 'https://eoimages.gsfc.nasa.gov/images/imagerecords/144000/144898/BlackMarble_2016_3km.jpg'
+CACHE = pathlib.Path.home() / '.cache/papermorph/ne'
+
+
+def get(url, dst):
+ if not dst.exists():
+ print('downloading', url, file=sys.stderr)
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ tmp = dst.with_suffix('.part')
+ with urllib.request.urlopen(url, timeout=120) as r, open(tmp, 'wb') as fh:
+ while b := r.read(1 << 20):
+ fh.write(b)
+ tmp.rename(dst)
+ return dst
+
+
+def features(a, name):
+ f = pathlib.Path(a.ne) / f'ne_{name}.geojson' if a.ne else get(NE + f'ne_{name}.geojson', CACHE / f'ne_{name}.geojson')
+ return json.loads(f.read_text(encoding='utf-8'))['features']
+
+
+def iso(p): # France and Norway have ISO_A3 -99 in Natural Earth; their _EH code is right
+ for k in ('ISO_A3', 'ISO_A3_EH', 'ADM0_A3', 'adm0_a3'):
+ if p.get(k) and p[k] != '-99':
+ return p[k]
+
+
+def dp(pts, tol): # Douglas-Peucker on [(lon, lat)]
+ if tol <= 0 or len(pts) < 4:
+ return pts
+ if pts[0] == pts[-1]: # a closed ring: split at its farthest point, or every point lies on a zero-length chord
+ x0, y0 = pts[0]
+ m = max(range(len(pts)), key=lambda i: (pts[i][0] - x0) ** 2 + (pts[i][1] - y0) ** 2)
+ return dp(pts[:m + 1], tol) + dp(pts[m:], tol)[1:]
+ keep, stack = {0, len(pts) - 1}, [(0, len(pts) - 1)]
+ while stack:
+ a, b = stack.pop()
+ (ax, ay), (bx, by) = pts[a], pts[b]
+ dx, dy, best, bi = bx - ax, by - ay, -1, -1
+ L = (dx * dx + dy * dy) ** .5 or 1e-12
+ for i in range(a + 1, b):
+ x, y = pts[i]
+ d = abs(dy * (x - ax) - dx * (y - ay)) / L
+ if d > best:
+ best, bi = d, i
+ if best > tol:
+ keep.add(bi); stack += [(a, bi), (bi, b)]
+ return [pts[i] for i in sorted(keep)]
+
+
+def enc(line, tol, q=100, least=4):
+ # Antarctica's ring runs along the pole between lon 180 and -180: drop those points, or the border draws a seam
+ pts = dp([tuple(p[:2]) for p in line if p[1] > -89.99], tol)
+ out, px, py = [], 0, 0
+ for x, y in pts:
+ qx, qy = round(x * q), round(y * q)
+ if out and qx == px and qy == py:
+ continue
+ out += [qx - px, qy - py]; px, py = qx, qy
+ return out if len(out) >= 2 * least else None
+
+
+def outer(geom):
+ if not geom:
+ return []
+ return [p[0] for p in (geom['coordinates'] if geom['type'] == 'MultiPolygon' else [geom['coordinates']])]
+
+
+def layer(feats, tol, key, keep=lambda p: True):
+ out = {}
+ for f in feats:
+ p = f['properties']
+ if keep(p):
+ out.setdefault(key(p), []).extend(r for r in (enc(r, tol) for r in outer(f['geometry'])) if r)
+ return out
+
+
+def detail(a, lon, lat, deg):
+ box = lambda x, y: abs(x - lon) <= deg and abs(y - lat) <= deg
+ near = lambda r: any(box(x, y) for x, y, *_ in r)
+ rings = lambda name: [r for f in features(a, name) for o in outer(f['geometry']) if near(o)
+ for r in [enc(o, .0005, 10000)] if r]
+ rivers = []
+ for f in features(a, '10m_rivers_lake_centerlines'):
+ g = f['geometry']
+ if not g:
+ continue
+ for ln in (g['coordinates'] if g['type'] == 'MultiLineString' else [g['coordinates']]):
+ run = [] # the stretches inside the box, each with one point past its edge so it reaches the frame
+ for i, p in enumerate(ln):
+ if box(*p[:2]):
+ if not run and i:
+ run.append(ln[i - 1])
+ run.append(p)
+ elif run:
+ run.append(p); rivers.append(run); run = []
+ if run:
+ rivers.append(run)
+ return {'lakes': rings('10m_lakes'), 'urban': rings('10m_urban_areas'),
+ 'rivers': [r for r in (enc(r, .0005, 10000, 2) for r in rivers) if r]}
+
+
+def globe(lib, img, width):
+ from PIL import Image
+ # the minified builds, under the names the module imports (three.module.min.js imports ./three.core.js)
+ for f, name in (('build/three.module.min.js', 'three.module.js'), ('build/three.core.min.js', 'three.core.js'), ('LICENSE', 'three.LICENSE')):
+ get(THREE + f, lib / 'vendor' / name)
+ jpg = get(NIGHT, CACHE.parent / 'BlackMarble_2016_3km.jpg')
+ Image.MAX_IMAGE_PIXELS = None
+ im = Image.open(jpg).convert('RGB').resize((width, width // 2), Image.LANCZOS)
+ im.save(img / 'night.webp', quality=82, method=5)
+ print(lib / 'vendor', 'three.js r186;', img / 'night.webp', im.size)
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__.split('\n')[0], epilog=__doc__.split('\n', 2)[2],
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('img', help="the book's img/ folder: geo-lite.js is written there")
+ ap.add_argument('--regions', default='', help='ISO codes whose admin-1 regions to add (CHN,ITA:region,USA)')
+ ap.add_argument('--detail', action='append', default=[], metavar='NAME=LON,LAT,DEG',
+ help='rivers, lakes and built-up areas within DEG degrees of a point (repeatable)')
+ ap.add_argument('--cities', default='', help='more places: names from Natural Earth, or name=lon,lat')
+ ap.add_argument('--min-pop', type=float, default=5e6, help='cities this big are in besides capitals (default 5e6)')
+ ap.add_argument('--ne', help='a folder holding the Natural Earth GeoJSON files instead of downloading them')
+ ap.add_argument('--globe', metavar='LIB', help="the book's lib/: also fetch three.js and make img/night.webp")
+ ap.add_argument('--night-width', type=int, default=8192)
+ a = ap.parse_args()
+ img = pathlib.Path(a.img)
+ img.mkdir(parents=True, exist_ok=True)
+
+ geo = {'lod': [layer(features(a, '110m_admin_0_countries'), 0, iso), layer(features(a, '50m_admin_0_countries'), .02, iso)]}
+ want = dict((c.split(':') + [''])[:2] for c in a.regions.split(',') if c) # ISO -> the field to merge by
+ if want:
+ geo['regions'], parts = {}, {}
+ for f in features(a, '10m_admin_1_states_provinces'):
+ p = f['properties']
+ if p.get('adm0_a3') in want and f['geometry']:
+ key = p.get(want[p['adm0_a3']]) or p.get('name_en') or p['name']
+ parts.setdefault(p['adm0_a3'], {}).setdefault(key, []).append(f['geometry'])
+ try:
+ from shapely.geometry import mapping, shape
+ from shapely.ops import unary_union
+ union = lambda gs: [mapping(unary_union([shape(g).buffer(0) for g in gs]))] if len(gs) > 1 else gs
+ except ImportError:
+ union = lambda gs: gs
+ if any(want.values()):
+ print('shapely is not installed: merged regions keep their inner borders', file=sys.stderr)
+ for c, keys in parts.items():
+ geo['regions'][c] = {k: [r for g in union(gs) for r in (enc(r, .02) for r in outer(g)) if r] for k, gs in keys.items()}
+ if miss := [c for c in want if c not in geo['regions']]:
+ sys.exit(f'no regions for {miss}: use the adm0_a3 code (CHN, ITA, USA)')
+
+ # names, or name=lon,lat (split by the same commas: "Codogno=9.705" + "45.16" rejoin)
+ names, parts, raw = {}, [s.strip() for s in a.cities.split(',') if s.strip()], []
+ i = 0
+ while i < len(parts):
+ n, eq, v = parts[i].partition('=')
+ if eq and i + 1 < len(parts):
+ names[n] = [float(v), float(parts[i + 1])]; i += 2
+ else:
+ raw.append(parts[i]); i += 1
+ best = {}
+ for f in features(a, '10m_populated_places_simple'):
+ p = f['properties']
+ n = p['nameascii'] if p['nameascii'] in raw else p['name'] if p['name'] in raw else None
+ n = n or (p['nameascii'] if p.get('adm0cap') or p['pop_max'] >= a.min_pop else None)
+ if n and p['pop_max'] > best.get(n, (-1,))[0]:
+ best[n] = (p['pop_max'], round(p['longitude'], 3), round(p['latitude'], 3))
+ geo['cities'] = {n: [v[1], v[2]] for n, v in sorted(best.items())} | names
+ if miss := [n for n in raw if n not in best]:
+ print('not in Natural Earth (give them as name=lon,lat):', ', '.join(miss), file=sys.stderr)
+
+ for d in a.detail:
+ n, _, v = d.partition('=')
+ lon, lat, deg = (float(x) for x in v.split(','))
+ geo.setdefault('detail', {})[n] = {'c': [lon, lat], **detail(a, lon, lat, deg)}
+
+ out = img / 'geo-lite.js'
+ out.write_text('// made by geo.py from Natural Earth (public domain): lon/lat rings, delta-encoded integers (1/100 deg,\n'
+ '// detail 1/10000); lod[0] 110m, lod[1] 50m at 0.02 deg, regions admin-1, cities [lon, lat]\n'
+ 'window.GEO_LITE = ' + json.dumps(geo, separators=(',', ':')) + ';\n')
+ pts = lambda L: sum(len(r) // 2 for rs in L.values() for r in rs)
+ print(out, f'{out.stat().st_size // 1024} KB:', 'points 110m', pts(geo['lod'][0]), '50m', pts(geo['lod'][1]),
+ *(f'{c} {len(v)} regions' for c, v in geo.get('regions', {}).items()), 'cities', len(geo['cities']),
+ *(f'detail {n}' for n in geo.get('detail', {})))
+ if a.globe:
+ globe(pathlib.Path(a.globe), img, a.night_width)
+
+
+if __name__ == '__main__':
+ main()