Spaces:
Running

File size: 2,885 Bytes
cd932f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python3
"""
Rasterize Natural Earth 110m land polygons into a compact equirectangular
land mask usable by the Space's world view with zero runtime network calls.

Output: geo/landmask.json  -> {"w":360,"h":180,"b64":"..."}
  1 bit per cell, row-major from lat +90 (top) to -90 (bottom), lon -180..+180.

Usage:
  python scripts/rasterize_land.py --geojson geo/ne_110m_land.geojson \
                                   --out geo/landmask.json --w 360 --h 180
"""
import argparse
import base64
import json


def rings(geom):
    """Yield every linear ring (list of [lon,lat]) from a Polygon/MultiPolygon."""
    t = geom.get("type")
    if t == "Polygon":
        for r in geom["coordinates"]:
            yield r
    elif t == "MultiPolygon":
        for poly in geom["coordinates"]:
            for r in poly:
                yield r


def point_in_ring(x, y, ring):
    inside = False
    n = len(ring)
    j = n - 1
    for i in range(n):
        xi, yi = ring[i][0], ring[i][1]
        xj, yj = ring[j][0], ring[j][1]
        if ((yi > y) != (yj > y)) and (x < (xj - xi) * (y - yi) / ((yj - yi) or 1e-12) + xi):
            inside = not inside
        j = i
    return inside


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--geojson", default="geo/ne_110m_land.geojson")
    ap.add_argument("--out", default="geo/landmask.json")
    ap.add_argument("--w", type=int, default=360)
    ap.add_argument("--h", type=int, default=180)
    args = ap.parse_args()

    gj = json.load(open(args.geojson, encoding="utf-8"))
    polys = []
    for f in gj["features"]:
        for r in rings(f["geometry"]):
            if len(r) >= 4:
                polys.append((r, min(p[0] for p in r), max(p[0] for p in r),
                      min(p[1] for p in r), max(p[1] for p in r)))
    print("land rings:", len(polys))

    W, H = args.w, args.h
    bits = bytearray((W * H + 7) // 8)
    land = 0
    for row in range(H):
        lat = 90.0 - (row + 0.5) * (180.0 / H)
        for col in range(W):
            lon = -180.0 + (col + 0.5) * (360.0 / W)
            hit = False
            for ring, x0, x1, y0, y1 in polys:
                if lon < x0 or lon > x1 or lat < y0 or lat > y1:
                    continue
                if point_in_ring(lon, lat, ring):
                    hit = True
                    break
            if hit:
                land += 1
                k = row * W + col
                bits[k >> 3] |= 1 << (7 - (k & 7))
    out = {"w": W, "h": H, "b64": base64.b64encode(bytes(bits)).decode("ascii"),
           "source": "Natural Earth 110m land (ne_110m_land.geojson), public domain"}
    with open(args.out, "w") as f:
        json.dump(out, f, separators=(",", ":"))
    print("land cells: %d / %d (%.1f%%)" % (land, W * H, 100.0 * land / (W * H)))
    print("wrote", args.out)


if __name__ == "__main__":
    main()