#!/usr/bin/env python3
"""Convert published planetary mosaics into the maps app's bundled raster sets.
Same offline pipeline as the Moon pair (NASA SVS 4720, converted by the
earlier `analysis/convert_moon.py`): every body ships as raw equirectangular
assets under `maps/src/main/assets/
/` —
_color_.rgba RGBA8 colour, lon -180..180 / lat 90..-90
_dem_.rg RG8 packed uint16 DEM (rocky bodies only):
R = high byte, G = low byte of
packed = metres / 0.5 + 20000 (clamped 0..65535)
_ring_1024.rgba 1024x1 RGBA radial ring strip (ringed giants only),
u = 0 at the ring inner radius, 1 at the outer
*.json sidecar pinning dimensions/format/source
Sources, exact URLs, sizes and licences: see DATASETS.md in this directory.
Nothing here runs at app runtime; the app is offline-first and only reads
the converted assets.
Usage:
python3 convert_planets.py --raw ~/planet-data/raw --all
Requires: numpy, Pillow, tifffile (build-time only).
"""
import argparse
import json
import pathlib
import numpy as np
from PIL import Image
ASSETS = pathlib.Path(__file__).resolve().parent.parent / "src" / "main" / "assets"
DEM_OFFSET = 20000.0
DEM_UNIT = 0.5 # metres per packed unit
def write_sidecar(path: pathlib.Path, **fields):
path.write_text(json.dumps(fields, indent=2) + "\n")
def save_rgba(img: Image.Image, out: pathlib.Path, source: str, w: int, h: int):
img = img.convert("RGBA")
if img.size != (w, h):
img = img.resize((w, h), Image.LANCZOS)
img.save(out.with_suffix(".tmp.png")) # placeholder replaced below
out.with_suffix(".tmp.png").unlink()
out.write_bytes(img.tobytes())
write_sidecar(
out.with_suffix(".json"),
width=w, height=h, format="RGBA8", projection="equirectangular",
lon_range=[-180, 180], lat_range=[-90, 90], source=source,
)
print(f"{out.name}: {w}x{h} {out.stat().st_size / 1e6:.1f} MB")
def save_dem(metres: np.ndarray, out: pathlib.Path, source: str, radius_km: float):
h, w = metres.shape
packed = np.clip(metres / DEM_UNIT + DEM_OFFSET, 0, 65535).round().astype(np.uint16)
rg = np.empty((h, w, 2), dtype=np.uint8)
rg[..., 0] = (packed >> 8).astype(np.uint8)
rg[..., 1] = (packed & 0xFF).astype(np.uint8)
out.write_bytes(rg.tobytes())
write_sidecar(
out.with_suffix(".json"),
width=w, height=h, format="RG8 packed uint16",
units="half-metres + 20000 (i.e. metres = (v - 20000) / 2)",
radius_km=radius_km, projection="equirectangular",
lon_range=[-180, 180], lat_range=[-90, 90], source=source,
)
print(f"{out.name}: {w}x{h} {out.stat().st_size / 1e6:.1f} MB "
f"(elev {metres.min():.0f}..{metres.max():.0f} m)")
def block_mean(arr: np.ndarray, out_w: int, out_h: int) -> np.ndarray:
"""Box-downsample a 2D float array to (out_h, out_w) ignoring NaNs."""
in_h, in_w = arr.shape
fy, fx = in_h // out_h, in_w // out_w
cropped = arr[: fy * out_h, : fx * out_w]
blocks = cropped.reshape(out_h, fy, out_w, fx)
return np.nanmean(blocks, axis=(1, 3))
def load_dem_tif(path: pathlib.Path, out_w: int, out_h: int) -> np.ndarray:
import tifffile
with tifffile.TiffFile(path) as tif:
arr = tif.asarray().astype(np.float32)
arr[arr == -32768] = np.nan # GDAL_NODATA
metres = block_mean(arr, out_w, out_h)
# Fill any residual no-data holes (polar gaps) with the global mean so
# the relief shading never sees a cliff at a data boundary.
holes = ~np.isfinite(metres)
if holes.any():
metres[holes] = np.nanmean(metres)
return metres
def load_colour_tif(path: pathlib.Path, w: int, h: int) -> Image.Image:
import tifffile
with tifffile.TiffFile(path) as tif:
arr = tif.asarray() # (3, H, W) uint8, planar
rgb = np.moveaxis(arr, 0, -1)
return Image.fromarray(rgb, "RGB").resize((w, h), Image.LANCZOS)
def load_colour_jpg(path: pathlib.Path, w: int, h: int) -> Image.Image:
return Image.open(path).convert("RGB").resize((w, h), Image.LANCZOS)
def save_ring_strip(strip_rgba: np.ndarray, out: pathlib.Path, source: str,
inner: float, outer: float):
assert strip_rgba.shape == (1, 1024, 4) and strip_rgba.dtype == np.uint8
out.write_bytes(strip_rgba.tobytes())
write_sidecar(
out.with_suffix(".json"),
width=1024, height=1, format="RGBA8 radial strip",
ring_inner_radii=inner, ring_outer_radii=outer,
note="u = (radius - inner) / (outer - inner) in planetary radii",
source=source,
)
print(f"{out.name}: 1024x1 {out.stat().st_size} B")
def saturn_ring(raw: pathlib.Path) -> np.ndarray:
"""Collapse the Solar System Scope ring texture to a 1024x1 strip."""
img = Image.open(raw / "2k_saturn_ring_alpha.png").convert("RGBA")
arr = np.asarray(img).astype(np.float32)
alpha = arr[..., 3:4] / 255.0
rgb = (arr[..., :3] * alpha).sum(axis=0) / np.maximum(alpha.sum(axis=0), 1e-6)
a = arr[..., 3].mean(axis=0)
strip = np.zeros((1, 2048, 4), dtype=np.uint8)
strip[0, :, :3] = np.clip(rgb, 0, 255).astype(np.uint8)
strip[0, :, 3] = np.clip(a, 0, 255).astype(np.uint8)
# Box-downsample 2048 -> 1024.
return strip.reshape(1, 1024, 2, 4).mean(axis=2).round().astype(np.uint8)
def procedural_ring(bands, rgb) -> np.ndarray:
"""Thin-ring strip: gaussian bands at (centre_u, width_u, peak_alpha)."""
u = np.linspace(0.0, 1.0, 1024)
alpha = np.zeros(1024, dtype=np.float32)
for centre, width, peak in bands:
alpha += peak * np.exp(-0.5 * ((u - centre) / width) ** 2)
strip = np.zeros((1, 1024, 4), dtype=np.uint8)
strip[0, :, 0], strip[0, :, 1], strip[0, :, 2] = rgb
strip[0, :, 3] = np.clip(alpha, 0, 255).astype(np.uint8)
return strip
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--raw", required=True, help="directory with downloaded source files")
ap.add_argument("--all", action="store_true")
args = ap.parse_args()
raw = pathlib.Path(args.raw)
# Mercury: USGS MESSENGER MDIS enhanced-colour mosaic + USGS DEM (MLA +
# stereo), public domain (USGS/NASA). Colour 4096 wide like the Moon.
mercury = ASSETS / "mercury"
mercury.mkdir(parents=True, exist_ok=True)
save_rgba(
load_colour_tif(raw / "Mercury_MESSENGER_MDIS_Basemap_EnhancedColor_Mosaic_Global_665m.tif", 4096, 2048),
mercury / "mercury_color_4096.rgba",
"USGS MESSENGER MDIS Basemap EnhancedColor Mosaic Global 665m (PDS/ASC S3)", 4096, 2048)
save_dem(
load_dem_tif(raw / "Mercury_Messenger_USGS_DEM_Global_665m_v2.tif", 2048, 1024),
mercury / "mercury_dem_2048.rg",
"USGS Mercury MESSENGER DEM Global 665m v2 (MLA + stereo, rel 2439.4 km sphere)", 2439.4)
# Mars: USGS Viking colour mosaic + MGS MOLA DEM, public domain.
mars = ASSETS / "mars"
mars.mkdir(parents=True, exist_ok=True)
save_rgba(
load_colour_tif(raw / "Mars_Viking_ClrMosaic_global_925m.tif", 4096, 2048),
mars / "mars_color_4096.rgba",
"USGS Mars Viking ClrMosaic global 925m (PDS/ASC S3)", 4096, 2048)
save_dem(
load_dem_tif(raw / "Mars_MGS_MOLA_DEM_mosaic_global_463m.tif", 2048, 1024),
mars / "mars_dem_2048.rg",
"USGS Mars MGS MOLA DEM mosaic global 463m (rel areoid)", 3396.0)
# Gas/ice giants + Venus: colour spheres only (thick atmospheres, no
# usable global topography). Solar System Scope textures (CC BY 4.0,
# derived from NASA imagery), already 2048x1024.
for body, jpg, source in [
("venus", "2k_venus_atmosphere.jpg", "Solar System Scope 2k Venus atmosphere (CC BY 4.0; NASA-based)"),
("jupiter", "2k_jupiter.jpg", "Solar System Scope 2k Jupiter (CC BY 4.0; NASA-based)"),
("saturn", "2k_saturn.jpg", "Solar System Scope 2k Saturn (CC BY 4.0; NASA-based)"),
("uranus", "2k_uranus.jpg", "Solar System Scope 2k Uranus (CC BY 4.0; NASA-based)"),
("neptune", "2k_neptune.jpg", "Solar System Scope 2k Neptune (CC BY 4.0; NASA-based)"),
]:
dest = ASSETS / body
dest.mkdir(parents=True, exist_ok=True)
save_rgba(load_colour_jpg(raw / jpg, 2048, 1024), dest / f"{body}_color_2048.rgba", source, 2048, 1024)
# Rings. Saturn: real radial profile from the SSS ring texture, mapped
# onto 1.24..2.27 radii (C ring inner edge to A ring outer edge).
save_ring_strip(saturn_ring(raw), ASSETS / "saturn" / "saturn_ring_1024.rgba",
"Solar System Scope Saturn ring texture (CC BY 4.0), row-collapsed radial profile",
1.24, 2.27)
# Uranus: narrow dark rings (Voyager 2 / HST radii), procedural strip —
# no published global ring texture exists at usable licence/resolution.
save_ring_strip(
procedural_ring(
[(0.19, 0.004, 60), (0.36, 0.004, 70), (0.43, 0.004, 80), (0.51, 0.005, 90),
(0.66, 0.005, 80), (0.83, 0.006, 100), (0.94, 0.008, 160)],
(178, 196, 200)),
ASSETS / "uranus" / "uranus_ring_1024.rgba",
"Procedural: Voyager 2/HST Uranus ring radii (zeta..epsilon), faint narrow bands",
1.55, 2.02)
# Neptune: Galle/LeVerrier/Lassell/Adams rings, procedural strip.
save_ring_strip(
procedural_ring(
[(0.12, 0.05, 36), (0.47, 0.006, 90), (0.73, 0.03, 44), (0.92, 0.008, 110)],
(168, 186, 214)),
ASSETS / "neptune" / "neptune_ring_1024.rgba",
"Procedural: Voyager 2 Neptune ring radii (Galle, LeVerrier, Lassell, Adams)",
1.68, 2.32)
if __name__ == "__main__":
main()