gen-skyline.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. #!/usr/bin/env python3
  2. """Generate Mount Rainier's skyline as seen from Kerry Park, Seattle.
  3. Casts rays over Terrarium elevation tiles from the AWS Open Data "Terrain
  4. Tiles" bucket (with earth curvature and atmospheric refraction), keeps the
  5. highest apparent angle per bearing, and writes SVG paths for the far massif,
  6. its snowfield, and the nearer foothills to components/cards/rainier-skyline.ts.
  7. Depends on numpy and Pillow. Run with: python3 scripts/gen-skyline.py
  8. Set TOPO_CACHE to a directory to reuse downloaded tiles.
  9. """
  10. import io
  11. import math
  12. import os
  13. import urllib.request
  14. import numpy as np
  15. from PIL import Image
  16. VIEWER = (47.6295, -122.3599) # Kerry Park, Queen Anne Hill
  17. EYE = 2.0 # metres above the ground
  18. SUMMIT = (46.8523, -121.7603) # Columbia Crest
  19. ZOOM = 11
  20. FOV = 24.0 # degrees of bearing across the widget
  21. SUMMIT_AT = 0.64 # where the summit sits across the width (0..1)
  22. STEP_AZ = 0.02 # degrees between rays
  23. STEP_D = 40.0 # metres between samples along a ray
  24. MAX_D = 125_000.0
  25. FAR_FROM = 72_000.0 # samples beyond this belong to the Rainier massif
  26. MID_FROM = 22_000.0 # foothills between here and FAR_FROM; Seattle's hills nearer
  27. SNOWLINE = 1900.0 # metres; early autumn snow
  28. EARTH_R = 6_371_000.0
  29. K_REFRACTION = 0.13
  30. VIEW_W = 200.0
  31. EXAGGERATION = 1.8
  32. SCALE = 5 # output units per view unit, so coordinates can be integers
  33. TOLERANCE = 0.8 # RDP tolerance in output units
  34. TILE_URL = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
  35. OUT = os.path.join(os.path.dirname(__file__), "..", "components", "cards", "rainier-skyline.ts")
  36. def fetch_tile(x, y, z):
  37. cache = os.environ.get("TOPO_CACHE")
  38. path = cache and os.path.join(cache, f"{z}-{x}-{y}.png")
  39. if path and os.path.exists(path):
  40. data = open(path, "rb").read()
  41. else:
  42. with urllib.request.urlopen(TILE_URL.format(z=z, x=x, y=y), timeout=60) as r:
  43. data = r.read()
  44. if path:
  45. os.makedirs(cache, exist_ok=True)
  46. open(path, "wb").write(data)
  47. rgb = np.asarray(Image.open(io.BytesIO(data)).convert("RGB"), dtype=np.float64)
  48. return rgb[:, :, 0] * 256 + rgb[:, :, 1] + rgb[:, :, 2] / 256 - 32768
  49. def global_px(lat, lon, z):
  50. n = 256 * (1 << z)
  51. x = (lon + 180.0) / 360.0 * n
  52. r = np.radians(lat)
  53. y = (1.0 - np.log(np.tan(r) + 1.0 / np.cos(r)) / math.pi) / 2.0 * n
  54. return x, y
  55. def destination(lat, lon, bearing, d):
  56. """Points d metres from (lat, lon) along each bearing (degrees), on a sphere."""
  57. p1, l1, b = math.radians(lat), math.radians(lon), np.radians(bearing)
  58. a = d / EARTH_R
  59. p2 = np.arcsin(math.sin(p1) * np.cos(a) + math.cos(p1) * np.sin(a) * np.cos(b))
  60. l2 = l1 + np.arctan2(np.sin(b) * np.sin(a) * math.cos(p1), np.cos(a) - math.sin(p1) * np.sin(p2))
  61. return np.degrees(p2), np.degrees(l2)
  62. def bearing_to(a, b):
  63. p1, p2 = math.radians(a[0]), math.radians(b[0])
  64. dl = math.radians(b[1] - a[1])
  65. y = math.sin(dl) * math.cos(p2)
  66. x = math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl)
  67. return (math.degrees(math.atan2(y, x)) + 360) % 360
  68. def rdp(points, eps):
  69. if len(points) < 3:
  70. return points
  71. a, b = points[0], points[-1]
  72. ab = b - a
  73. norm = np.hypot(*ab)
  74. d = np.abs(ab[0] * (points[:, 1] - a[1]) - ab[1] * (points[:, 0] - a[0])) / max(norm, 1e-9)
  75. i = int(np.argmax(d))
  76. if d[i] > eps:
  77. return np.vstack([rdp(points[: i + 1], eps)[:-1], rdp(points[i:], eps)])
  78. return np.array([a, b])
  79. def path(points):
  80. """A compact closed SVG path in SCALE units, with relative segments.
  81. The ring is split at its farthest point so RDP keeps its shape."""
  82. ring = np.asarray(points, dtype=float) * SCALE
  83. far = int(np.argmax(np.hypot(*(ring - ring[0]).T)))
  84. pts = np.vstack([rdp(ring[: far + 1], TOLERANCE)[:-1], rdp(ring[far:], TOLERANCE)])
  85. pts = np.round(pts).astype(int)
  86. out = [f"M{pts[0][0]} {pts[0][1]}"]
  87. for (x0, y0), (x1, y1) in zip(pts[:-1], pts[1:]):
  88. if (x1, y1) != (x0, y0):
  89. out.append(f"l{x1 - x0}{'' if y1 - y0 < 0 else ' '}{y1 - y0}")
  90. return "".join(out) + "z"
  91. def main():
  92. az0 = bearing_to(VIEWER, SUMMIT)
  93. left = az0 - FOV * SUMMIT_AT
  94. bearings = np.arange(left, left + FOV + STEP_AZ / 2, STEP_AZ)
  95. dists = np.arange(300.0, MAX_D, STEP_D)
  96. lat, lon = destination(VIEWER[0], VIEWER[1], bearings[:, None], dists[None, :])
  97. gx, gy = global_px(lat, lon, ZOOM)
  98. tx0, ty0 = int(gx.min() // 256), int(gy.min() // 256)
  99. tx1, ty1 = int(gx.max() // 256), int(gy.max() // 256)
  100. dem = np.zeros(((ty1 - ty0 + 1) * 256, (tx1 - tx0 + 1) * 256))
  101. for ty in range(ty0, ty1 + 1):
  102. for tx in range(tx0, tx1 + 1):
  103. dem[(ty - ty0) * 256 : (ty - ty0 + 1) * 256, (tx - tx0) * 256 : (tx - tx0 + 1) * 256] = fetch_tile(tx, ty, ZOOM)
  104. # Bilinear sample.
  105. fx, fy = gx - tx0 * 256, gy - ty0 * 256
  106. x0, y0 = np.floor(fx).astype(int), np.floor(fy).astype(int)
  107. ax, ay = fx - x0, fy - y0
  108. h = (
  109. dem[y0, x0] * (1 - ax) * (1 - ay)
  110. + dem[y0, x0 + 1] * ax * (1 - ay)
  111. + dem[y0 + 1, x0] * (1 - ax) * ay
  112. + dem[y0 + 1, x0 + 1] * ax * ay
  113. )
  114. gx0, gy0 = global_px(np.array(VIEWER[0]), np.array(VIEWER[1]), ZOOM)
  115. eye = dem[int(gy0 - ty0 * 256), int(gx0 - tx0 * 256)] + EYE
  116. r_eff = EARTH_R / (1 - K_REFRACTION)
  117. angle = np.degrees(np.arctan2(h - eye - dists**2 / (2 * r_eff), dists))
  118. far = dists >= FAR_FROM
  119. mid = (dists >= MID_FROM) & ~far
  120. near = dists < MID_FROM
  121. far_sky = angle[:, far].max(axis=1)
  122. mid_sky = angle[:, mid].max(axis=1)
  123. near_sky = angle[:, near].max(axis=1)
  124. front_sky = np.maximum(mid_sky, near_sky)
  125. # Snow: visible far-field points above the snowline. A point is visible when
  126. # nothing nearer along the ray rises above it.
  127. running = np.maximum.accumulate(angle, axis=1)
  128. visible = angle >= running - 1e-9
  129. snowy = visible & far[None, :] & (h >= SNOWLINE)
  130. snow_low = np.where(snowy, angle, np.inf).min(axis=1)
  131. summit_angle = far_sky.max()
  132. scale = (VIEW_W / FOV) * EXAGGERATION # units per degree, vertically
  133. top = 6.0 # leave headroom above the summit
  134. horizon = top + summit_angle * scale
  135. def y(a):
  136. return horizon - a * scale
  137. xs = (bearings - left) / FOV * VIEW_W
  138. view_h = math.ceil(y(min(near_sky.min(), mid_sky.min())) + 4)
  139. def layer(sky):
  140. return path([(0, view_h)] + [(x, y(a)) for x, a in zip(xs, sky)] + [(VIEW_W, view_h)])
  141. # Snowfield polygons over contiguous runs where snow is visible above the foothills.
  142. snow_paths = []
  143. has = np.isfinite(snow_low) & (far_sky > front_sky)
  144. i = 0
  145. while i < len(xs):
  146. if not has[i]:
  147. i += 1
  148. continue
  149. j = i
  150. while j + 1 < len(xs) and has[j + 1]:
  151. j += 1
  152. if j - i >= 3:
  153. low = np.maximum(snow_low[i : j + 1], front_sky[i : j + 1])
  154. top_pts = [(xs[k], y(far_sky[k])) for k in range(i, j + 1)]
  155. bottom_pts = [(xs[k], y(low[k - i])) for k in range(j, i - 1, -1)]
  156. snow_paths.append(path(top_pts + bottom_pts))
  157. i = j + 1
  158. with open(OUT, "w") as f:
  159. f.write(
  160. "// Generated by scripts/gen-skyline.py: Mount Rainier from Kerry Park, Seattle,\n"
  161. "// ray-cast over AWS Terrain Tiles (USGS 3DEP). Vertical scale exaggerated "
  162. f"{EXAGGERATION}x.\n\n"
  163. f"export const SKYLINE_SIZE = [{VIEW_W * SCALE:.0f}, {view_h * SCALE}] as const;\n\n"
  164. f"export const RAINIER = \"{layer(far_sky)}\";\n\n"
  165. f"export const RAINIER_SNOW = \"{''.join(snow_paths)}\";\n\n"
  166. f"export const FOOTHILLS = \"{layer(mid_sky)}\";\n\n"
  167. f"export const SEATTLE_HILLS = \"{layer(near_sky)}\";\n"
  168. )
  169. print(
  170. f"bearing {az0:.2f}°, summit {summit_angle:.2f}° above horizon, "
  171. f"eye {eye:.0f} m, tiles {(tx1 - tx0 + 1) * (ty1 - ty0 + 1)}, horizon y {horizon:.1f}, height {view_h}"
  172. )
  173. if __name__ == "__main__":
  174. main()