Skip to content

TexturedGlobe#

Drape a pyramids raster — or a whole-world tile basemap — over a 3-D sphere on a matplotlib Axes3D.

TexturedGlobe wraps cleopatra's TexturedGlobeGlyph, which is deliberately geometry-only: it paints an equirectangular array onto a tilted, spinnable sphere and knows nothing about rasters, CRSes or nodata. This class owns the geospatial half of that seam — building the texture from geodata, and mapping lon/lat back onto the drawn surface so vector overlays land where they belong at any spin.

digitalearth.static.globe.textured_globe.TexturedGlobe #

Bases: WatermarkMixin

A 3-D textured globe built from geospatial data.

Inherits cleopatra's WatermarkMixin, whose surface comes with it as-is: :meth:stamp below is this package's documented spelling for the logo stamp, and stamp_watermark(text) is available unchanged from upstream, documented there rather than here.

Wraps cleopatra.glyphs.globe.TexturedGlobeGlyph: this class owns the data → texture conversion and the lon/lat overlay maths, the glyph owns the sphere, the tilt, the lighting and the render.

Parameters:

Name Type Description Default
texture ndarray

An equirectangular (H, W, 3) or (H, W, 4) array — row 0 at +90 degrees, column 0 at -180 degrees. Use :meth:from_dataset or :meth:from_provider to build one from geodata.

required
**kwargs Any

Forwarded to TexturedGlobeGlyph — tilt_deg (default Earth's 23.44), n_lon / n_lat (mesh resolution, the render-cost driver), brightness, sun (a world-space direction that shades a day/night terminator), ambient, fig and ax.

{}

Attributes:

Name Type Description
glyph

The underlying cleopatra TexturedGlobeGlyph.

fig Any

The matplotlib figure, once :meth:draw, :meth:spin or :meth:animate has run (None before).

ax Any

The matplotlib Axes3D, once :meth:draw, :meth:spin or :meth:animate has run (None before).

Examples:

  • Build a globe from a two-tone synthetic texture and draw it:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> texture = np.zeros((90, 180, 3), dtype=np.uint8)
    >>> texture[:45] = (40, 90, 180)
    >>> texture[45:] = (180, 120, 40)
    >>> globe = TexturedGlobe(texture, n_lon=36, n_lat=18)
    >>> fig, ax = globe.draw(spin=45.0)
    >>> ax.name
    '3d'
    
  • The north pole sits on the tilted polar axis, not straight up:
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> texture = np.zeros((8, 16, 3), dtype=np.uint8)
    >>> globe = TexturedGlobe(texture, tilt_deg=0.0, n_lon=8, n_lat=4)
    >>> np.round(globe.project(0.0, 90.0), 6)
    array([[0., 0., 1.]])
    
Source code in src/digitalearth/static/globe/textured_globe.py
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
class TexturedGlobe(WatermarkMixin):
    """A 3-D textured globe built from geospatial data.

    Inherits cleopatra's ``WatermarkMixin``, whose surface comes with it as-is: :meth:`stamp` below is this
    package's documented spelling for the logo stamp, and ``stamp_watermark(text)`` is available unchanged
    from upstream, documented there rather than here.

    Wraps ``cleopatra.glyphs.globe.TexturedGlobeGlyph``: this class owns the data → texture conversion and
    the lon/lat overlay maths, the glyph owns the sphere, the tilt, the lighting and the render.

    Args:
        texture: An equirectangular ``(H, W, 3)`` or ``(H, W, 4)`` array — row 0 at +90 degrees, column 0 at
            -180 degrees. Use :meth:`from_dataset` or :meth:`from_provider` to build one from geodata.
        **kwargs: Forwarded to ``TexturedGlobeGlyph`` — ``tilt_deg`` (default Earth's 23.44), ``n_lon`` /
            ``n_lat`` (mesh resolution, the render-cost driver), ``brightness``, ``sun`` (a world-space
            direction that shades a day/night terminator), ``ambient``, ``fig`` and ``ax``.

    Attributes:
        glyph: The underlying cleopatra ``TexturedGlobeGlyph``.
        fig: The matplotlib figure, once :meth:`draw`, :meth:`spin` or :meth:`animate` has run (``None`` before).
        ax: The matplotlib ``Axes3D``, once :meth:`draw`, :meth:`spin` or :meth:`animate` has run (``None`` before).

    Examples:
        - Build a globe from a two-tone synthetic texture and draw it:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> texture = np.zeros((90, 180, 3), dtype=np.uint8)
            >>> texture[:45] = (40, 90, 180)
            >>> texture[45:] = (180, 120, 40)
            >>> globe = TexturedGlobe(texture, n_lon=36, n_lat=18)
            >>> fig, ax = globe.draw(spin=45.0)
            >>> ax.name
            '3d'

            ```
        - The north pole sits on the tilted polar axis, not straight up:
            ```python
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> texture = np.zeros((8, 16, 3), dtype=np.uint8)
            >>> globe = TexturedGlobe(texture, tilt_deg=0.0, n_lon=8, n_lat=4)
            >>> np.round(globe.project(0.0, 90.0), 6)
            array([[0., 0., 1.]])

            ```
    """

    def __init__(self, texture: np.ndarray, **kwargs: Any):
        """Wrap an equirectangular texture in a cleopatra globe glyph.

        Args:
            texture: An equirectangular ``(H, W, 3)`` or ``(H, W, 4)`` array — row 0 at +90 degrees, column
                0 at -180 degrees.
            **kwargs: Forwarded to ``TexturedGlobeGlyph`` (``tilt_deg``, ``n_lon``, ``n_lat``,
                ``brightness``, ``sun``, ``ambient``, ``fig``, ``ax``).

        Raises:
            ValueError: If ``texture`` is not a 3-channel or 4-channel 2-D image, or if a lighting argument
                is out of contract (a zero-length ``sun``, an ``ambient`` outside ``[0, 1]``).
        """
        self.glyph = TexturedGlobeGlyph(texture, **kwargs)
        #: The glyph options, so a frame of :meth:`animate` can rebuild the glyph around a new texture and
        #: be identical in every other respect. cleopatra's ``texture`` is a read-only property, so a
        #: stack is stepped by constructing a glyph per frame rather than by assigning to the one we hold;
        #: ``fig``/``ax`` are dropped because a frame draws on the axes the animation already owns.
        self._glyph_kwargs: dict[str, Any] = {
            key: value for key, value in kwargs.items() if key not in ("fig", "ax")
        }
        #: A glyph of the same tilt carrying no texture, whose ``transform`` places the overlays. They
        #: cannot hold the drawing glyph's own method: that keeps its texture alive for as long as the
        #: artist lives, and drags it into anything the figure is pickled or copied into — one marker took
        #: a saved figure from about 1 MB to 134 MB. The rotation depends on the tilt and nothing else, so
        #: this places points exactly as the real glyph does.
        self._placer = TexturedGlobeGlyph(
            np.zeros((2, 4, 3), dtype=np.uint8),
            tilt_deg=kwargs.get("tilt_deg", EARTH_TILT_DEG),
            n_lon=4,
            n_lat=2,
        )
        self.fig: Any = None
        self.ax: Any = None
        # Declared up front rather than sprung into existence by animate(), so every reader can see the
        # instance's full state and the accessors need no getattr() guards.
        self._animation: FuncAnimation | None = None
        self._animation_fps: float | None = None
        #: A fig/ax handed to the constructor is the caller's too — the glyph stores it and draws on it even
        #: when no later call passes one, so ownership has to be settled here, not only at draw time.
        self._caller_supplied_axes: bool = (
            kwargs.get("ax") is not None or kwargs.get("fig") is not None
        )
        #: The spin the globe was last drawn at, so an overlay defaults to the surface it can see.
        self._spin: float = 0.0
        #: The overlays that follow the globe, each still on the axes it was drawn on. A draw or animation
        #: frame turns the ones on its own axes (see :meth:`_turn_overlays`).
        self._overlays: list[Any] = []
        #: Whether :attr:`fig` is ours to close. A caller-supplied axes belongs to the caller.
        self._owns_fig: bool = False
        #: The axes the constructor was given, if any. animate() falls back to it so a globe built around a
        #: caller's axes keeps drawing there instead of opening a figure of its own.
        self._ctor_ax: Any = kwargs.get("ax")

    def _is_ours(self, axes: Any) -> bool:
        """Whether ``axes`` sits on the figure this globe made and still owns.

        Args:
            axes: The axes about to be drawn on.

        Returns:
            True when drawing there is the globe drawing on its own figure.
        """
        return (
            self._owns_fig
            and self.fig is not None
            and axes is not None
            and axes.get_figure() is self.fig
        )

    def _reuse_own_axes(self, ax: Any, kwargs: dict) -> Any:
        """Fall back to the axes this globe already owns, resizing its figure if asked.

        A globe that is drawn, decorated and then drawn (or animated) again should carry on where it is.
        Opening a fresh figure each time would leave its overlays behind on a figure about to be closed —
        which is exactly what made a plain ``animate()`` after ``coastlines()`` come out bare.

        Args:
            ax: The axes the caller asked for, or ``None``.
            kwargs: The render options; ``figsize`` is consumed here when the axes is reused.

        Returns:
            The axes to draw on, which may still be ``None`` when this globe owns nothing yet.
        """
        if ax is not None or self._caller_supplied_axes or not self._is_ours(self.ax):
            return ax
        figsize = kwargs.pop("figsize", None)
        if figsize is not None:
            self.fig.set_size_inches(figsize)
        return self.ax

    def _turn_overlays(self, axes: Any, spin: float) -> None:
        """Turn the overlays drawn on ``axes`` to ``spin``, and forget the ones no longer drawn anywhere.

        Scoped to one axes on purpose. A globe drawn into several panels — a contact sheet of spins — keeps
        each panel's overlays at that panel's spin, so turning one panel must not move, strip or duplicate
        another's. An overlay that has left its axes — removed by the caller, or wiped by ``ax.clear()`` — is
        dropped here, so it is never brought back and a hand-written redraw loop cannot pile copies up.

        Args:
            axes: The axes the globe has just been drawn on.
            spin: The spin, in degrees, it was drawn at.
        """
        kept = []
        for overlay in self._overlays:
            if overlay.axes is None:
                continue
            if overlay.axes is axes:
                overlay._spin = float(spin)
                overlay.stale = True
            kept.append(overlay)
        self._overlays = kept

    @staticmethod
    def _to_body(lon: Any, lat: Any, altitude: float) -> np.ndarray:
        """Turn lon/lat degrees into body-frame points lifted ``altitude`` above the unit surface.

        Args:
            lon: Longitude(s) in degrees.
            lat: Latitude(s) in degrees, the same shape as ``lon``.
            altitude: Radial offset from the unit surface.

        Returns:
            An ``(N, 3)`` array of body-frame points.

        Raises:
            ValueError: if ``lon`` and ``lat`` do not have the same shape.
        """
        lon_arr = np.atleast_1d(np.asarray(lon, dtype=float))
        lat_arr = np.atleast_1d(np.asarray(lat, dtype=float))
        if lon_arr.shape != lat_arr.shape:
            raise ValueError(
                f"lon and lat must have the same shape, got {lon_arr.shape} and {lat_arr.shape}"
            )
        return _lonlat_to_body(lon_arr.ravel(), lat_arr.ravel()) * (
            1.0 + float(altitude)
        )

    # ------------------------------------------------------------------ constructors

    @classmethod
    def _global_values(
        cls,
        dataset: Any,
        *,
        band: int = DEFAULT_BAND,
        shape: tuple[int, int] = DEFAULT_TEXTURE_SHAPE,
        resampling: str = "nearest",
    ) -> np.ndarray:
        """Read one band onto the global EPSG:4326 texture grid, nodata masked to ``NaN``.

        The step :meth:`from_dataset` and :meth:`animate` share: pyramids aligns the raster onto the
        template, which reprojects it, resamples it and settles the longitude frame in one call, and the band
        is then read with nodata masked. Factored out so a stack's frames are placed exactly as a single
        raster is — a frame measured on one grid and drawn on another is the drift worth not having.

        Args:
            dataset: A pyramids ``Dataset`` carrying a CRS.
            band: 1-based index of the band to read.
            shape: The ``(rows, cols)`` of the global grid to align onto.
            resampling: The pyramids resampling method for the align.

        Returns:
            The ``(rows, cols)`` float array of that band on the global grid, nodata as ``NaN``.

        Raises:
            ValueError: If ``shape`` is not a coercible ``(rows, columns)`` pair of at least
                ``(2, 2)``, if ``dataset`` has no CRS, or if ``band`` is outside its band count.
                Validating here rather than in each caller is what lets :meth:`animate` inherit the
                same refusals.
        """
        try:
            rows, cols = (int(v) for v in shape)
        except (TypeError, ValueError) as exc:
            raise ValueError(
                f"shape must be a (rows, columns) pair of integers, got {shape!r}"
            ) from exc
        if rows < 2 or cols < 2:
            raise ValueError(f"shape must be at least (2, 2), got {shape!r}")
        # `epsg` is None both for a raster with no CRS and for one whose CRS carries no EPSG authority code
        # (geostationary, Mollweide, a bare ESRI code). Only the first is unplaceable; the second reprojects
        # fine, so the presence of a CRS — not of a code — is what decides. Read the attribute rather than
        # resolving the code: source_epsg() parses the CRS, which raises on one stored as a bare string.
        epsg = getattr(dataset, "epsg", None)
        if epsg is None and not getattr(dataset, "crs", None):
            raise ValueError(
                "a dataset needs a CRS to be placed on the globe; this one has none. "
                "Set dataset.crs / dataset.epsg first."
            )
        if not 1 <= band <= dataset.band_count:
            raise ValueError(
                f"band index {band} is out of range for a {dataset.band_count}-band dataset "
                f"(valid 1..{dataset.band_count})."
            )
        source = dataset.select_bands([band]) if dataset.band_count > 1 else dataset
        aligned = source.align(cls._global_template(rows, cols), method=resampling)
        return read_masked_band(aligned, band=1)

    @classmethod
    def from_dataset(
        cls,
        dataset: Any,
        *,
        band: int = DEFAULT_BAND,
        cmap: Any = "viridis",
        vmin: float | None = None,
        vmax: float | None = None,
        shape: tuple[int, int] = DEFAULT_TEXTURE_SHAPE,
        resampling: str = "nearest",
        **kwargs: Any,
    ) -> "TexturedGlobe":
        """Build a globe from a pyramids ``Dataset``, draped at the raster's true lon/lat position.

        **pyramids** does the geospatial work: the raster is aligned onto a global EPSG:4326 grid, which
        reprojects it and resamples it in one step, and settles the longitude frame along the way. Its band is
        then read with nodata masked to ``NaN`` and colour-mapped through cleopatra's colormap resolver. Cells
        the raster does not cover — and its nodata cells — stay fully transparent, so a regional dataset shows
        as a patch on the globe rather than being smeared over it.

        Args:
            dataset: A pyramids ``Dataset``. Must carry a CRS.
            band: 1-based band index to draw.
            cmap: Colormap name or ``Colormap``, resolved by ``cleopatra.styling.colors.resolve_colormap``.
            vmin: Lower bound of the colour scale; defaults to the band's finite minimum.
            vmax: Upper bound of the colour scale; defaults to the band's finite maximum.
            shape: ``(rows, columns)`` of the global canvas. Larger is sharper and slower to build.
            resampling: How pyramids resamples the raster onto that grid — ``"nearest"`` (the default, which
                preserves categorical values), ``"bilinear"``, ``"cubic"``, ``"average"``, ``"mode"``, and
                the rest of ``Dataset.align``'s methods.
            **kwargs: Forwarded to :class:`TexturedGlobe` (and on to the glyph).

        Returns:
            TexturedGlobe: a globe whose texture carries the dataset.

        Raises:
            ValueError: if ``dataset`` has no resolvable CRS (there is then no way to place it on the
                sphere), if ``shape`` is not two positive integers, if ``band`` is out of range, or if the
                colour bounds are non-finite or leave no range.

        Warns:
            RuntimeWarning: If nothing survives the resample onto the texture, or if what does is finer than
                the sphere mesh and so would not be drawn — see :meth:`_warn_if_finer_than_the_mesh`.

        Examples:
            - Drape a whole-globe raster and inspect the texture it produced:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> from pyramids.dataset import Dataset, GeoReference
                >>> arr = np.arange(8, dtype="float32").reshape(2, 4)
                >>> ds = Dataset.from_array(
                ...     arr=arr, geo_ref=GeoReference(geo=(-180.0, 90.0, 0.0, 90.0, 0.0, -90.0), epsg=4326))
                >>> globe = TexturedGlobe.from_dataset(ds, shape=(90, 180))
                >>> globe.glyph.texture.shape
                (90, 180, 4)
                >>> bool((globe.glyph.texture[..., 3] > 0).mean() > 0.98)
                True

                ```
            - A raster covering only part of the world leaves the rest transparent:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> from pyramids.dataset import Dataset, GeoReference
                >>> arr = np.ones((2, 2), dtype="float32")
                >>> ds = Dataset.from_array(
                ...     arr=arr, geo_ref=GeoReference(geo=(0.0, 10.0, 0.0, 20.0, 0.0, -10.0), epsg=4326))
                >>> globe = TexturedGlobe.from_dataset(ds, shape=(90, 180))
                >>> opaque = globe.glyph.texture[..., 3] > 0
                >>> bool(opaque.any()), bool(opaque.all())
                (True, False)

                ```
        """
        # pyramids owns the regrid and _global_values owns the call — including validating `shape` and the
        # CRS, so animate() inherits the same refusals. The grid comes back off the result rather than being
        # coerced again here: coercing in one place and passing the raw pair on is what silently dropped the
        # int() and broke shape=(h / 2, w / 2).
        values = cls._global_values(
            dataset, band=band, shape=shape, resampling=resampling
        )
        rows, cols = values.shape
        rgba = cls._colorize(values, cmap=cmap, vmin=vmin, vmax=vmax)
        texture = _as_byte_texture(rgba)
        if not (texture[..., 3] > 0).any():
            warnings.warn(
                f"nothing was draped onto the {rows}x{cols} globe texture, so it will render blank. Either "
                "the raster is finer than one texture cell — pass a finer shape=, e.g. shape=(2880, 5760) — "
                "or it does not overlap the globe at all, which usually means its CRS or geotransform is "
                "wrong.",
                RuntimeWarning,
                stacklevel=2,
            )
        globe = cls(texture, **kwargs)
        globe._warn_if_finer_than_the_mesh(texture)
        return globe

    def _warn_if_finer_than_the_mesh(self, texture: np.ndarray) -> None:
        """Warn when the draped data is too small to survive the sphere mesh.

        A fine texture is not enough to make small data visible. The glyph point-samples the texture down to
        its ``n_lon`` x ``n_lat`` mesh, so detail narrower than one mesh face falls between the samples and
        disappears — however many texture cells it covers. The default mesh is 180x90, roughly 2-degree faces,
        while the default texture is 0.125 degrees, so a raster can occupy hundreds of texture cells and still
        paint nothing.

        Checking the mesh is the only check that predicts what a reader will actually see; the texture-grid
        check alone reports success on a globe that renders blank.

        Args:
            texture: The global RGBA canvas about to be handed to the glyph.

        Warns:
            RuntimeWarning: If the opaque part of ``texture`` covers no mesh sample.
        """
        opaque = texture[..., 3] > 0
        if not opaque.any():
            return  # from_dataset has already warned that nothing was draped at all
        rows, cols = _mesh_sample_indices(
            texture.shape[:2], self.glyph.n_lon, self.glyph.n_lat
        )
        if not opaque[np.ix_(rows, cols)].any():
            warnings.warn(
                f"the draped data is finer than the {self.glyph.n_lon}x{self.glyph.n_lat} sphere mesh, so it "
                "falls between the mesh samples and the globe will render without it. Raise the mesh "
                "(n_lon=/n_lat=) until a mesh face fits inside the data's footprint.",
                RuntimeWarning,
                stacklevel=3,
            )

    @classmethod
    def from_provider(
        cls, provider: Any = "Esri.WorldImagery", **kwargs: Any
    ) -> "TexturedGlobe":
        """Build a globe from a whole-world XYZ tile basemap (delegates to ``cleopatra``'s ``world_texture``).

        Args:
            provider: An ``xyzservices`` provider name or resolved ``TileProvider``. Defaults to
                ``"Esri.WorldImagery"`` — a bulk-permitting imagery provider. Do **not** point this at
                OpenStreetMap's tiles: a whole-world fetch pulls thousands of tiles, which its usage policy
                prohibits.
            **kwargs: The fetch options ``zoom``, ``cache``, ``max_workers``, ``timeout``, ``retries`` and
                ``user_agent`` go to ``world_texture``; ``texture_n_lon`` / ``texture_n_lat`` size the
                fetched texture grid. Everything else — ``n_lon``, ``n_lat``, ``tilt_deg``, ``sun``,
                ``ambient`` — is forwarded to the glyph, exactly as in the other constructors.

        Returns:
            TexturedGlobe: a globe textured with the provider's imagery.

        Note:
            ``n_lon`` / ``n_lat`` always mean the **sphere mesh**, here as everywhere else in this class.
            The texture grid — which ``world_texture`` also calls ``n_lon`` / ``n_lat`` — is set with
            ``texture_n_lon`` / ``texture_n_lat``, so the same keyword never means two different things.

        Raises:
            ValueError: if ``provider`` is not a known ``xyzservices`` provider.
            OSError: if the tiles cannot be fetched — the whole-world grid is pulled over the network on
                first use, so a connection failure or an unreachable provider surfaces here.

        Examples:
            - Build a photographic Earth and spin it (needs the network on first use; the texture is then
              cached on disk):
                ```python
                >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
                >>> globe = TexturedGlobe.from_provider("Esri.WorldImagery", zoom=3)   # doctest: +SKIP
                >>> globe.glyph.texture.shape                             # doctest: +SKIP
                (1440, 2880, 4)
                >>> fig, ax = globe.draw(spin=30.0, sun=(1.0, 0.3, 0.2))  # doctest: +SKIP

                ```
            - Size the fetched texture and the sphere mesh independently:
                ```python
                >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
                >>> globe = TexturedGlobe.from_provider(                  # doctest: +SKIP
                ...     "Esri.WorldImagery", zoom=2, texture_n_lon=720, texture_n_lat=360,
                ...     n_lon=60, n_lat=30,
                ... )
                >>> globe.glyph.n_lon, globe.glyph.n_lat                  # doctest: +SKIP
                (60, 30)

                ```
        """
        texture_keys = (
            "zoom",
            "cache",
            "max_workers",
            "timeout",
            "retries",
            "user_agent",
        )
        texture_kwargs = {k: kwargs.pop(k) for k in texture_keys if k in kwargs}
        for shape_key, fetch_key in (
            ("texture_n_lon", "n_lon"),
            ("texture_n_lat", "n_lat"),
        ):
            if shape_key in kwargs:
                texture_kwargs[fetch_key] = kwargs.pop(shape_key)
        return cls(world_texture(provider, **texture_kwargs), **kwargs)

    # ------------------------------------------------------------------ texture building

    @staticmethod
    def _validate_colour_bounds(
        good: np.ndarray, vmin: float | None, vmax: float | None
    ) -> None:
        """Reject bound combinations that leave nothing to colour.

        Separated from resolving the bounds because it answers a different question: not "what scale do we
        use" but "is what the caller asked for coherent at all". Quietly substituting a workable range
        instead would return a plausible image drawn from a scale nobody chose.

        Args:
            good: The band's finite values, already stripped of nodata. May be empty.
            vmin: Lower bound, or ``None``.
            vmax: Upper bound, or ``None``.

        Raises:
            ValueError: If either bound is not finite, if both are given and ``vmax <= vmin``, or if a
                single given bound sits outside the data on the wrong side.
        """
        for name, bound in (("vmin", vmin), ("vmax", vmax)):
            if bound is not None and not np.isfinite(float(bound)):
                raise ValueError(f"{name} must be a finite number, got {bound!r}")
        if vmin is not None and vmax is not None and float(vmax) <= float(vmin):
            raise ValueError(
                f"vmax must be greater than vmin, got vmin={vmin!r}, vmax={vmax!r}"
            )
        if not good.size:
            return
        if vmax is None and vmin is not None and float(vmin) >= float(good.max()):
            raise ValueError(
                f"vmin={vmin!r} is at or above the band's maximum ({float(good.max())!r}), so there is no "
                "range to colour. Lower vmin, or pass vmax as well."
            )
        if vmin is None and vmax is not None and float(vmax) <= float(good.min()):
            raise ValueError(
                f"vmax={vmax!r} is at or below the band's minimum ({float(good.min())!r}), so there is no "
                "range to colour. Raise vmax, or pass vmin as well."
            )

    @classmethod
    def _resolve_colour_bounds(
        cls, good: np.ndarray, vmin: float | None, vmax: float | None
    ) -> tuple[float, float]:
        """Settle the colour scale's ``(lo, hi)`` from the caller's bounds and the band's finite values.

        A bound the caller gives always wins; a bound they leave out comes from the data, or from a unit
        fallback when there is no finite data to take it from.

        Args:
            good: The band's finite values, already stripped of nodata. May be empty.
            vmin: Lower bound, or ``None`` to take the band's minimum.
            vmax: Upper bound, or ``None`` to take the band's maximum.

        Returns:
            The ``(lo, hi)`` pair to normalise against, with ``hi > lo`` guaranteed.

        Raises:
            ValueError: If the bounds leave no range — see :meth:`_validate_colour_bounds`.
        """
        cls._validate_colour_bounds(good, vmin, vmax)
        # `good` is already the finite subset, so from_finite skips the second pass and the ~75 MB copy
        # from_values would make of a global canvas. A unit range remains the fallback for an empty one.
        return Scale.from_finite(good, vmin=vmin, vmax=vmax).as_limits()

    @classmethod
    def _colorize(
        cls,
        values: np.ndarray,
        *,
        cmap: Any,
        vmin: float | None,
        vmax: float | None,
    ) -> np.ndarray:
        """Colour-map a NaN-masked 2-D band to an ``(H, W, 4)`` float RGBA array, NaN cells transparent.

        Args:
            values: The band, with nodata already masked to ``NaN``.
            cmap: Colormap name or ``Colormap``, resolved by cleopatra; ``None`` falls back to viridis.
            vmin: Lower bound of the colour scale, or ``None`` to take the band's finite minimum.
            vmax: Upper bound of the colour scale, or ``None`` to take the band's finite maximum.

        Returns:
            An ``(H, W, 4)`` float RGBA array in ``[0, 1]``, with alpha ``0`` wherever ``values`` is not
            finite.

        Raises:
            ValueError: If the colour bounds leave no range — see :meth:`_resolve_colour_bounds`.

        Warns:
            RuntimeWarning: If no cell of the band is finite, so the result is entirely transparent.
        """
        good = finite(values)
        if not good.size:
            warnings.warn(
                "every cell of this band is nodata or non-finite, so the globe will be fully transparent.",
                RuntimeWarning,
                stacklevel=3,
            )
        lo, hi = cls._resolve_colour_bounds(good, vmin, vmax)
        colormap = resolve_colormap(cmap)
        if colormap is None:  # resolve_colormap returns None only for cmap=None
            colormap = resolve_colormap("viridis")
        rgba = np.asarray(
            colormap(Normalize(vmin=lo, vmax=hi)(np.asarray(values, dtype=float))),
            dtype=float,
        ).copy()
        rgba[..., 3] = np.where(np.isfinite(values), rgba[..., 3], 0.0)
        return rgba

    @staticmethod
    def _global_template(rows: int, cols: int) -> Dataset:
        """Build the empty global EPSG:4326 raster that a dataset is aligned onto.

        The grid is chosen so its **cell centres** land exactly on the latitudes and longitudes the glyph
        samples — ``linspace(90, -90, rows)`` and ``linspace(-180, 180, cols)`` — rather than on the
        half-cell-offset grid a naive ``(-180, 90)`` corner would give. Without that the whole texture sits
        half a cell off what is drawn.

        Args:
            rows: Number of texture rows.
            cols: Number of texture columns.

        Returns:
            Dataset: an empty raster carrying only the target grid; ``align`` reads its spatial properties.
        """
        d_lat, d_lon = 180.0 / (rows - 1), 360.0 / (cols - 1)
        # Pull the outermost centres a hair inside the globe. Sitting exactly on +/-90 / +/-180 puts them on
        # the *boundary* of a whole-world source rather than inside it, and the warp returns nothing there —
        # which showed as a hole at the pole and a seam down the antimeridian. The offset is a millionth of a
        # cell, far below anything the texture can express, so nothing moves visibly.
        inset_lat, inset_lon = d_lat * _EDGE_INSET, d_lon * _EDGE_INSET
        return Dataset.from_array(
            arr=np.zeros((rows, cols), dtype="float32"),
            geo_ref=GeoReference(
                geo=(
                    -180.0 + inset_lon - d_lon / 2,
                    d_lon * (1.0 - 2.0 * _EDGE_INSET / (cols - 1)),
                    0.0,
                    90.0 - inset_lat + d_lat / 2,
                    0.0,
                    -d_lat * (1.0 - 2.0 * _EDGE_INSET / (rows - 1)),
                ),
                epsg=_TEXTURE_EPSG,
            ),
        )

    # ------------------------------------------------------------------ geometry

    def project(
        self, lon: Any, lat: Any, *, spin: float | None = None, altitude: float = 0.0
    ) -> np.ndarray:
        """Map lon/lat degrees onto the drawn sphere, returning world-space ``(N, 3)`` coordinates.

        Pushes the points through the glyph's own ``transform``, so they carry the same spin **and axial
        tilt** as the rendered surface — the reason this is exact rather than an approximation.

        Args:
            lon: Longitude(s) in degrees (scalar or array-like).
            lat: Latitude(s) in degrees, same shape as ``lon``.
            spin: The spin, in degrees, to place the points at. Defaults to the spin the globe was last
                drawn at, so an overlay lands on the surface the reader can actually see.
            altitude: Radial offset from the unit surface. A small positive value (e.g. ``0.01``) lifts an
                overlay clear of the surface so matplotlib does not z-fight it.

        Returns:
            np.ndarray: an ``(N, 3)`` array of world-space coordinates.

        Raises:
            ValueError: if ``lon`` and ``lat`` do not have the same shape.

        Examples:
            - With no tilt the body frame is the world frame, so the cardinal points are exact:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
                ...                       n_lon=8, n_lat=4)
                >>> np.round(globe.project(0.0, 0.0), 6)
                array([[1., 0., 0.]])
                >>> np.round(globe.project(90.0, 0.0), 6)
                array([[0., 1., 0.]])
                >>> np.round(globe.project(0.0, 90.0), 6)
                array([[0., 0., 1.]])

                ```
            - Points land on the unit sphere; ``altitude`` lifts an overlay clear of the surface:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> world = globe.project([0.0, 45.0], [10.0, -20.0], spin=30.0)
                >>> world.shape
                (2, 3)
                >>> [round(float(r), 6) for r in np.linalg.norm(world, axis=1)]
                [1.0, 1.0]
                >>> round(float(np.linalg.norm(globe.project(0.0, 0.0, altitude=0.05))), 6)
                1.05

                ```
        """
        spin = self._spin if spin is None else spin
        body = self._to_body(lon, lat, altitude)
        return np.atleast_2d(self.glyph.transform(body, spin=spin))

    def visible(self, world_xyz: np.ndarray) -> np.ndarray:
        """Boolean mask of which world-space points face the camera (i.e. are on the near side).

        A point on a unit sphere is its own outward normal, so it is visible exactly when it points toward
        the camera. Uses the axes' current ``elev``/``azim``, so call it after :meth:`draw`.

        A point sitting exactly on the limb is a tie, and floating point decides it: at ``lon=90`` with the
        camera at ``azim=0``, ``cos(90°)`` evaluates to ``6.1e-17`` rather than ``0``, so the point reads as
        (barely) visible. Do not rely on the classification of points within rounding distance of the limb.

        Args:
            world_xyz: An ``(N, 3)`` array of world-space points, as returned by :meth:`project`.

        Returns:
            np.ndarray: an ``(N,)`` boolean mask, ``True`` for the near-side points.

        Raises:
            RuntimeError: if the globe has not been drawn yet (there is no camera to test against).

        Examples:
            - The hemisphere facing the camera is visible; the one behind it is not:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
                ...                       n_lon=8, n_lat=4)
                >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
                >>> globe.visible(globe.project(0.0, 0.0)).tolist()
                [True]
                >>> globe.visible(globe.project(180.0, 0.0)).tolist()
                [False]

                ```
            - Use it to label only the points a reader can actually see:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
                ...                       n_lon=8, n_lat=4)
                >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
                >>> lon, lat = [0.0, 45.0, 180.0, 225.0], [0.0, 0.0, 0.0, 0.0]
                >>> int(globe.visible(globe.project(lon, lat)).sum())
                2

                ```
        """
        if self.ax is None:
            raise RuntimeError(
                "draw() the globe before asking which points are visible"
            )
        view = _view_vector(self.ax.elev, self.ax.azim)
        points = np.atleast_2d(np.asarray(world_xyz, dtype=float))
        return np.asarray(points @ view > 0.0, dtype=bool).ravel()

    # ------------------------------------------------------------------ rendering

    def _bind(self, ax: Any, *, owns: bool) -> None:
        """Adopt ``ax`` as the render target, releasing a figure we own and are leaving behind.

        The single rule for figure ownership: we close a figure only if we created it *and* we are no longer
        drawing on it. Rebinding to a different axes releases the old one so nothing is orphaned beyond
        ``close()``'s reach; rebinding to another axes on the *same* figure closes nothing, because that
        figure is still in use.

        Args:
            ax: The axes now being drawn on.
            owns: Whether the figure behind ``ax`` was created by this globe.
        """
        figure = ax.get_figure()
        if self._owns_fig and self.fig is not None and self.fig is not figure:
            closing = self.fig
            plt.close(closing)
            # the overlays on that figure go with it; keeping them registered would only pin a dead figure
            self._overlays = [
                overlay
                for overlay in self._overlays
                if overlay.axes is not None and overlay.axes.get_figure() is not closing
            ]
        self.ax, self.fig = ax, figure
        self._owns_fig = owns

    def draw(
        self, ax: Any = None, *, spin: float = 0.0, **kwargs: Any
    ) -> tuple[Any, Any]:
        """Draw the globe, returning the matplotlib ``(fig, ax)`` and recording them on the instance.

        A globe keeps drawing where it already is: called without an ``ax``, this reuses the axes it owns, so
        overlays added since the last draw — :meth:`points`, :meth:`coastlines`, :meth:`borders`,
        :meth:`land` without a ``spin=`` — turn to the new ``spin`` and stay. ``figsize`` resizes that
        figure. Pass an ``ax`` to draw somewhere else instead; overlays stay behind with the axes they
        were drawn on, and a figure this globe owned and is leaving is closed.

        Args:
            ax: An existing ``Axes3D`` to draw on, accepted positionally to match :meth:`animate`. A figure
                the caller supplies is never closed by :meth:`close`.
            spin: Rotation about the polar axis, in degrees.
            **kwargs: Forwarded to the glyph's ``draw`` (``sun``, ``ambient``, ``figsize``, ``elev``,
                ``azim``, ``background``).

        Returns:
            The ``(Figure, Axes3D)`` the globe was drawn on.

        Examples:
            - Draw the globe and keep the axes for further decoration:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> fig, ax = globe.draw(spin=45.0)
                >>> ax.name
                '3d'
                >>> globe.ax is ax
                True

                ```
            - Draw several spins onto axes you own, to build a contact sheet:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> import matplotlib.pyplot as plt
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> fig, axes = plt.subplots(1, 3, subplot_kw={"projection": "3d"})
                >>> for spin, sub in zip([0.0, 120.0, 240.0], axes):
                ...     _ = globe.draw(ax=sub, spin=spin)
                >>> len(fig.axes)
                3

                ```
        """
        ax = self._reuse_own_axes(ax, kwargs)
        if ax is not None:
            kwargs["ax"] = ax
        supplied = not (ax is None or self._is_ours(ax)) or self._caller_supplied_axes
        _, drawn_ax = self.glyph.draw(spin=spin, **kwargs)
        self._bind(drawn_ax, owns=not supplied)
        self._spin = float(spin)
        self._turn_overlays(drawn_ax, self._spin)
        return self.fig, self.ax

    def points(
        self,
        data: Any,
        *,
        lat: Any = None,
        spin: float | None = None,
        altitude: float = 0.01,
        hide_far_side: bool = True,
        **kwargs: Any,
    ) -> Any:
        """Scatter lon/lat points onto the globe's surface.

        Accepts either a pyramids ``FeatureCollection`` / geopandas ``GeoDataFrame`` of points (its geometry
        is reprojected to lon/lat when needed) or a pair of ``lon``/``lat`` array-likes.

        Args:
            data: A point ``FeatureCollection``/``GeoDataFrame``, or the longitudes when ``lat`` is given.
            lat: Latitudes, when ``data`` holds longitudes.
            spin: Pin the points to this spin, in degrees. Omitted (the default), they follow the globe:
                they are drawn at the spin it was last drawn at, and redrawn at each animation frame's
                spin so they turn with the surface. Giving a value opts out of that and fixes them there.
            altitude: Radial lift above the surface, to avoid z-fighting with it.
            hide_far_side: When True (default), hide the markers on the hemisphere facing away from the
                camera, which matplotlib would otherwise draw straight through the sphere. Decided at each
                draw, against the camera as it is then, so a camera move re-decides it. With False every
                marker is drawn and the collection is depth-sorted like any other artist, so markers near
                the limb can be painted over by the sphere.
            **kwargs: Forwarded to ``Axes3D.scatter`` (e.g. ``c``, ``s``, ``marker``, ``color``).

        Returns:
            The scatter collection on the axes. It stays there as the globe turns — re-placed at each draw,
            never replaced — so restyling it, removing it, or keying a colorbar to it keeps working.

            It holds **every** point, which is a change: a hidden marker is drawn at size zero rather than
            left out of the collection. That is what keeps each per-point value with its own point and fits
            the colour scale to all of them, and it means ``len(scatter.get_offsets())`` counts the points
            given rather than the ones on show — ask :meth:`visible` which of those face the camera.

        Raises:
            RuntimeError: if the globe has not been drawn yet.
            ValueError: if ``data`` is neither a feature collection nor a pair of lon/lat arrays, or is a
                feature collection carrying no CRS.

        Note:
            Non-point geometry (polygons, lines) is reduced to its centroids rather than rejected, so a
            polygon layer can be marked on the globe without converting it first.

        Examples:
            - Scatter lon/lat points; the ones behind the globe are drawn at size zero:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
                ...                       n_lon=8, n_lat=4)
                >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
                >>> scatter = globe.points([0.0, 180.0], lat=[0.0, 0.0])
                >>> len(scatter.get_offsets())
                2
                >>> globe.visible(globe.project([0.0, 180.0], [0.0, 0.0])).tolist()
                [True, False]

                ```
            - Keep the far side when you want the full set drawn:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
                ...                       n_lon=8, n_lat=4)
                >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
                >>> scatter = globe.points([0.0, 180.0], lat=[0.0, 0.0], hide_far_side=False)
                >>> fig.canvas.draw()
                >>> len(scatter.get_offsets())
                2

                ```
            - Points follow the globe unless pinned; turning it half-way takes the follower out of sight:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import matplotlib.pyplot as plt
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
                ...                       n_lon=8, n_lat=4)
                >>> ax = plt.figure().add_subplot(projection="3d")
                >>> _ = globe.draw(ax, elev=0.0, azim=0.0)
                >>> follower = globe.points([0.0], lat=[0.0])
                >>> pinned = globe.points([0.0], lat=[0.0], spin=0.0)
                >>> _ = globe.draw(ax, elev=0.0, azim=0.0, spin=180.0)
                >>> bool(globe.visible(globe.project([0.0], [0.0]))[0])
                False
                >>> bool(globe.visible(globe.project([0.0], [0.0], spin=0.0))[0])
                True
                >>> follower in ax.collections
                True

                ```
        """
        if self.ax is None:
            raise RuntimeError("draw() the globe before adding points to it")
        lon_vals, lat_vals = self._as_lonlat(data, lat)
        body = self._to_body(lon_vals, lat_vals, altitude)
        at = self._spin if spin is None else float(spin)
        world = np.atleast_2d(self.glyph.transform(body, spin=at))
        scatter = self.ax.scatter(world[:, 0], world[:, 1], world[:, 2], **kwargs)
        scatter.__class__ = _SpherePoints
        scatter._adopt_points(self._placer.transform, body, at, cull=hide_far_side)
        if spin is None:
            self._overlays.append(scatter)
        return scatter

    # ------------------------------------------------------------------ reference geography

    def _reference_layer(
        self,
        layer: str,
        resolution: str,
        defaults: dict,
        *,
        spin: float | None,
        altitude: float,
        fill: bool,
        **kwargs: Any,
    ) -> Any:
        """Add a Natural-Earth layer to the globe as one overlay collection.

        Args:
            layer: The Natural-Earth layer name (``"coastline"``, ``"borders"``, ``"land"``).
            resolution: Natural-Earth resolution (``"110m"`` / ``"50m"`` / ``"10m"``).
            defaults: The layer's base style, overridden by the caller's (see :func:`_overlay_style`).
            spin: Pin the layer to this spin, or ``None`` to follow the globe.
            altitude: Radial lift above the surface.
            fill: Whether the parts are closed rings to fill rather than lines to stroke.

        Returns:
            The ``Line3DCollection`` (lines) or ``PolyCollection`` (fill) now on the axes.

        Raises:
            RuntimeError: if the globe has not been drawn yet, so there is no axes to add the layer to.
        """
        if self.ax is None:
            raise RuntimeError(
                f"draw() the globe before adding the {layer!r} layer to it"
            )
        parts = [
            part
            for part in (
                np.asarray(raw, dtype=float) for raw in natural_earth(layer, resolution)
            )
            if part.ndim == 2 and len(part) >= 2
        ]
        bodies = [self._to_body(part[:, 0], part[:, 1], altitude) for part in parts]
        style = _overlay_style(defaults, kwargs, fill)
        at = self._spin if spin is None else float(spin)
        overlay: Any
        if fill:
            overlay = _SphereFill([], **style)
            overlay._adopt_rings(
                self._placer.transform,
                bodies,
                at,
                [_interior_is_left(p) for p in parts],
            )
        else:
            overlay = _SphereLines([], **style)
            overlay._adopt_parts(self._placer.transform, bodies, at)
        # add_collection, not add_collection3d: the overlay is already 3-D, starts empty (it is placed at
        # draw time), and add_collection3d's autolim would try to size the view from that empty geometry
        self.ax.add_collection(overlay, autolim=False)
        if spin is None:
            self._overlays.append(overlay)
        return overlay

    def coastlines(
        self,
        resolution: str = "110m",
        *,
        spin: float | None = None,
        altitude: float = 0.002,
        **kwargs: Any,
    ) -> Any:
        """Draw Natural-Earth coastlines on the globe, split at the visible limb.

        Named and styled to match :meth:`~digitalearth.static.Map.coastlines` on the 2-D globe, so the two
        tiers read alike. Each coastline is placed on the sphere and broken into the arcs that face the
        camera, each carried out to the horizon; without that split every line crossing the limb would be
        drawn as a chord through the planet. The split is redone at every draw, for the spin and the camera
        of that moment.

        Args:
            resolution: Natural-Earth resolution — ``"110m"`` (default), ``"50m"`` or ``"10m"``.
            spin: Pin the coastlines to this spin, in degrees. Omitted, they follow the globe and are
                redrawn at each animation frame's spin.
            altitude: Radial lift above the surface, so the lines are not z-fought by it.
            **kwargs: Line styling forwarded to matplotlib (``color``, ``linewidth``, ``linestyle``,
                ``alpha``), in any spelling it accepts (``c``, ``lw``, ``ls``, ``linewidths``). ``zorder``
                is taken for parity with :class:`~digitalearth.static.Map` but cannot move the layer: a
                3-D axes orders its collections by depth, which always puts a layer in front of the sphere
                and behind the markers.

        Returns:
            The ``Line3DCollection`` holding every near-side arc. It stays on the axes as the globe turns.
            The arcs are worked out when the figure is drawn, so ``get_segments()`` is empty until then.

        Raises:
            RuntimeError: if the globe has not been drawn yet.

        Examples:
            - Coastlines land on the sphere as a set of near-side arcs. The vectors are fetched (and
              cached) by ``cleopatra``, so this needs a network on first use:
                ```python
                >>> import matplotlib                                      # doctest: +SKIP
                >>> matplotlib.use("Agg")                                  # doctest: +SKIP
                >>> import numpy as np                                     # doctest: +SKIP
                >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
                >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
                >>> lines = globe.coastlines()                             # doctest: +SKIP
                >>> globe.fig.canvas.draw()                                # doctest: +SKIP
                >>> len(lines.get_segments())                              # doctest: +SKIP
                57

                ```
            - Restyle them like any matplotlib line, and pin them to one spin so they stay put while the
              globe turns:
                ```python
                >>> import matplotlib                                      # doctest: +SKIP
                >>> matplotlib.use("Agg")                                  # doctest: +SKIP
                >>> import numpy as np                                     # doctest: +SKIP
                >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
                >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
                >>> lines = globe.coastlines(color="white", lw=1.2, spin=0.0)  # doctest: +SKIP
                >>> float(lines.get_linewidth()[0])                            # doctest: +SKIP
                1.2

                ```
            - Asking before the globe is drawn is refused — there is no camera yet to clip against:
                ```python
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8)).coastlines()
                Traceback (most recent call last):
                    ...
                RuntimeError: draw() the globe before adding the 'coastline' layer to it

                ```
        """
        return self._reference_layer(
            "coastline",
            resolution,
            {"color": "black", "linewidth": 0.5},
            spin=spin,
            altitude=altitude,
            fill=False,
            **kwargs,
        )

    def borders(
        self,
        resolution: str = "110m",
        *,
        spin: float | None = None,
        altitude: float = 0.002,
        **kwargs: Any,
    ) -> Any:
        """Draw Natural-Earth country borders on the globe, split at the visible limb.

        The counterpart of :meth:`~digitalearth.static.Map.borders`, same spelling and same default
        styling, so a globe and a flat map can be given the same reference geography.

        Args:
            resolution: Natural-Earth resolution — ``"110m"`` (default), ``"50m"`` or ``"10m"``.
            spin: Pin the borders to this spin, in degrees. Omitted, they follow the globe.
            altitude: Radial lift above the surface.
            **kwargs: Line styling forwarded to matplotlib, as for :meth:`coastlines`, including what
                ``zorder`` can and cannot do there.

        Returns:
            The ``Line3DCollection`` holding every near-side arc. It stays on the axes as the globe turns.

        Raises:
            RuntimeError: if the globe has not been drawn yet.

        Examples:
            - Borders draw in their own default grey, thinner than the coastlines. The vectors are
              fetched (and cached) by ``cleopatra``, so this needs a network on first use:
                ```python
                >>> import matplotlib                                      # doctest: +SKIP
                >>> matplotlib.use("Agg")                                  # doctest: +SKIP
                >>> import numpy as np                                     # doctest: +SKIP
                >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
                >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
                >>> float(globe.borders().get_linewidth()[0])              # doctest: +SKIP
                0.4

                ```
            - Ask for the finer cut when the globe is drawn large:
                ```python
                >>> import matplotlib                                      # doctest: +SKIP
                >>> matplotlib.use("Agg")                                  # doctest: +SKIP
                >>> import numpy as np                                     # doctest: +SKIP
                >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
                >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
                >>> fine, coarse = globe.borders("50m"), globe.borders("110m")  # doctest: +SKIP
                >>> globe.fig.canvas.draw()                                     # doctest: +SKIP
                >>> len(fine.get_segments()) > len(coarse.get_segments())       # doctest: +SKIP
                True

                ```
            - Asking before the globe is drawn is refused — there is no camera yet to clip against:
                ```python
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8)).borders()
                Traceback (most recent call last):
                    ...
                RuntimeError: draw() the globe before adding the 'borders' layer to it

                ```
        """
        return self._reference_layer(
            "borders",
            resolution,
            {"color": "gray", "linewidth": 0.4},
            spin=spin,
            altitude=altitude,
            fill=False,
            **kwargs,
        )

    def land(
        self,
        resolution: str = "110m",
        *,
        spin: float | None = None,
        altitude: float = 0.001,
        **kwargs: Any,
    ) -> Any:
        """Fill Natural-Earth land polygons on the globe.

        The counterpart of :meth:`~digitalearth.static.Map.land`. Each land ring is clipped to the
        hemisphere facing the camera and re-closed along the limb, so a continent running off the edge is
        filled to the horizon instead of having a chord cut across the disc. This is what turns an ocean
        product — SST, sea ice, chlorophyll — from a ball of colour with white holes into a readable map.

        Interior rings (holes) are dropped, as they are on the 2-D globe. A ring that runs off the near
        side is closed along the horizon the way its own winding leads, so a landmass reaching past the
        horizon in several places fills each of its visible pieces and not the sea between them, however
        far round the horizon that takes.

        Args:
            resolution: Natural-Earth resolution — ``"110m"`` (default), ``"50m"`` or ``"10m"``.
            spin: Pin the fill to this spin, in degrees. Omitted, it follows the globe.
            altitude: Radial lift above the surface. The fill sorts under the line layers by the depth
                it reports rather than by its radius, so this only has to clear the sphere itself.
            **kwargs: Patch styling forwarded to matplotlib (``color``, ``alpha``, ``edgecolor``, ...),
                in any spelling it accepts (``fc``, ``ec``, ``lw``). As for :meth:`coastlines`, ``zorder``
                is accepted but the axes' depth sort decides the order.

        Returns:
            The ``PolyCollection`` holding the fill. It stays on the axes as the globe turns, re-clipped and
            re-projected at each draw; at a camera that shows no land it simply has no faces, and the faces
            are worked out when the figure is drawn, so ``get_paths()`` is empty until then.

        Raises:
            RuntimeError: if the globe has not been drawn yet.

        Examples:
            - The fill arrives as one collection holding every visible land ring. The vectors are fetched
              (and cached) by ``cleopatra``, so this needs a network on first use:
                ```python
                >>> import matplotlib                                      # doctest: +SKIP
                >>> matplotlib.use("Agg")                                  # doctest: +SKIP
                >>> import numpy as np                                     # doctest: +SKIP
                >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
                >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
                >>> patch = globe.land()                                   # doctest: +SKIP
                >>> patch in globe.ax.collections                          # doctest: +SKIP
                True

                ```
            - Colour it like any patch — a translucent fill still lets the texture read through:
                ```python
                >>> import matplotlib                                      # doctest: +SKIP
                >>> matplotlib.use("Agg")                                  # doctest: +SKIP
                >>> import numpy as np                                     # doctest: +SKIP
                >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
                >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
                >>> patch = globe.land(color="0.4", alpha=0.5)             # doctest: +SKIP
                >>> round(float(patch.get_facecolor()[0][3]), 2)           # doctest: +SKIP
                0.5

                ```
            - Asking before the globe is drawn is refused — there is no camera yet to clip against:
                ```python
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8)).land()
                Traceback (most recent call last):
                    ...
                RuntimeError: draw() the globe before adding the 'land' layer to it

                ```
        """
        return self._reference_layer(
            "land",
            resolution,
            {"color": "#efefdb", "edgecolor": "none"},
            spin=spin,
            altitude=altitude,
            fill=True,
            **kwargs,
        )

    @staticmethod
    def _as_lonlat(data: Any, lat: Any) -> tuple[np.ndarray, np.ndarray]:
        """Resolve ``points``' input into lon/lat degree arrays, reprojecting a feature collection if needed.

        Args:
            data: A point ``FeatureCollection`` / ``GeoDataFrame``, or the longitudes when ``lat`` is given.
            lat: Latitudes, when ``data`` holds longitudes; ``None`` to read the geometry from ``data``.

        Returns:
            A ``(lon, lat)`` pair of 1-D degree arrays.

        Raises:
            ValueError: If ``data`` has no geometry and no ``lat`` was given, or if a feature collection
                carries no CRS (its coordinates then cannot be placed on the sphere).
        """
        if lat is not None:
            return np.atleast_1d(np.asarray(data, dtype=float)), np.atleast_1d(
                np.asarray(lat, dtype=float)
            )
        geometry = getattr(data, "geometry", None)
        if geometry is None:
            raise ValueError(
                "points needs a FeatureCollection/GeoDataFrame, or both lon and lat"
            )
        # As on the raster path, a missing EPSG code is not the same as a missing CRS: a projection with no
        # authority code still reprojects, so test the CRS itself.
        epsg = source_epsg(data)
        if epsg is None and getattr(data, "crs", None) is None:
            raise ValueError(
                "the feature collection has no CRS, so its points cannot be placed on the globe"
            )
        # Reduce to centroids *before* reprojecting: a centroid taken on lon/lat degrees is not the centroid
        # of the shape on the ground, and geopandas warns about exactly that.
        if not (geometry.geom_type == "Point").all():
            geometry = geometry.centroid
        if epsg != _TEXTURE_EPSG:
            geometry = geometry.to_crs(_TEXTURE_EPSG)
        return geometry.x.to_numpy(), geometry.y.to_numpy()

    def _animate_frames(
        self, stack: Any, titles: Sequence[Any] | None, interval: float
    ) -> tuple[list[Any], float]:
        """Materialise the stack and validate the per-call arguments shared by every frame.

        Args:
            stack: The rasters to step.
            titles: One title per frame, or ``None``.
            interval: Milliseconds between frames, before coercion.

        Returns:
            The stack as a list and the interval coerced to ``float``.

        Raises:
            ValueError: If ``stack`` is empty, ``titles`` is a string or the wrong length, or ``interval``
                is not a positive number of milliseconds.
        """
        frames = list(stack)
        if not frames:
            raise ValueError(
                "animate needs at least one raster to step; the stack yielded none. Pass a sequence of "
                "pyramids Datasets, or use spin() to turn the camera around the texture already drawn."
            )
        if isinstance(titles, str):
            # A bare string is iterable, so len() "works" and the per-frame indexing would hand each frame
            # one character. Refuse it rather than silently captioning a two-frame stack "a", "b".
            raise ValueError(
                f"titles must be one title per frame, not a single string; got {titles!r}"
            )
        if titles is not None and len(titles) != len(frames):
            raise ValueError(
                f"titles must have one entry per frame; got {len(titles)} for {len(frames)} frames."
            )
        try:
            interval_ms = float(
                interval
            )  # coerce first, so a non-number hits the one message below
        except (TypeError, ValueError):
            interval_ms = (
                0.0  # fall through rather than surface float()'s generic message
            )
        if interval_ms <= 0:
            raise ValueError(
                f"interval must be a positive number of milliseconds, got {interval!r}"
            )
        return frames, interval_ms

    def _animate_scale(
        self,
        frames: Sequence[Any],
        *,
        vmin: float | None,
        vmax: float | None,
        band: int,
        shape: tuple[int, int],
        resampling: str,
    ) -> tuple[float, float]:
        """Settle the ``(low, high)`` colour scale shared across the whole stack.

        Measured from a bounded, evenly-spread sample rather than from all of it: a 624-band series would
        otherwise read every band into memory just to find its limits. The sample is released here; the
        frames are read one at a time as each is drawn, so the whole stack is never held at once.

        Args:
            frames: The stack to measure across.
            vmin: Low end, or ``None`` to measure it.
            vmax: High end, or ``None`` to measure it.
            band: 1-based band index read from each frame.
            shape: The ``(rows, cols)`` global grid each frame is aligned onto.
            resampling: The pyramids resampling method for that align.

        Returns:
            The ``(low, high)`` limits: the caller's bounds where given, measured ends otherwise.

        Raises:
            ValueError: If the caller's bounds leave nothing to colour (see :meth:`_validate_colour_bounds`).
        """
        if vmin is None or vmax is None:
            sample = [
                self._global_values(
                    frame, band=band, shape=shape, resampling=resampling
                )
                for frame in sample_evenly(frames, cap=DEFAULT_CLIM_SCAN_CAP)
            ]
            # Validate the caller's ORIGINAL bounds against the sampled data, before substituting the
            # measured ends. A one-sided vmin/vmax must raise the same "nothing to colour" message
            # from_dataset gives — not the "vmax must be greater than vmin" that resolving both forces.
            self._validate_colour_bounds(
                np.concatenate([finite(v) for v in sample])
                if sample
                else np.array([], dtype=float),
                vmin,
                vmax,
            )
            measured = stack_scale(sample).as_limits()
        else:
            self._validate_colour_bounds(np.array([], dtype=float), vmin, vmax)
            measured = (0.0, 1.0)
        low = measured[0] if vmin is None else float(vmin)
        high = measured[1] if vmax is None else float(vmax)
        return low, high

    def _animate_axes(self, ax: Any, kwargs: dict[str, Any]) -> tuple[Any, bool]:
        """Resolve the axes to animate on, and whether the caller supplied it.

        Args:
            ax: The axes the caller passed, or ``None``.
            kwargs: The forwarded draw options; ``figsize`` is consumed here if a new figure is made.

        Returns:
            The resolved ``Axes3D`` and a flag that is ``True`` when the caller owns it.
        """
        supplied = not (ax is None or self._is_ours(ax)) or self._caller_supplied_axes
        if ax is None:
            ax = self._ctor_ax
        ax = self._reuse_own_axes(ax, kwargs)
        if ax is None:
            figsize = kwargs.pop(
                "figsize", self.glyph.default_options.get("figsize", (6, 6))
            )
            ax = plt.figure(figsize=figsize).add_subplot(projection="3d")
        return ax, supplied

    def animate(
        self,
        stack: Any,
        *,
        ax: Any = None,
        band: int = DEFAULT_BAND,
        cmap: Any = "viridis",
        vmin: float | None = None,
        vmax: float | None = None,
        shape: tuple[int, int] = DEFAULT_TEXTURE_SHAPE,
        resampling: str = "nearest",
        titles: Sequence[Any] | None = None,
        spin: float | None = None,
        interval: float = _DEFAULT_INTERVAL_MS,
        **kwargs: Any,
    ) -> FuncAnimation:
        """Step a series of rasters across the globe, returning a matplotlib ``FuncAnimation``.

        The globe counterpart of :meth:`~digitalearth.static.builders.animation.AnimationMixin.animate` on the
        2-D tier: the camera holds still and the **data** changes, which is what a time series of a global
        field — sea-surface temperature, sea ice, an anomaly field — wants. To turn the viewpoint around one
        fixed texture instead, use :meth:`spin`.

        **One colour scale across the whole stack.** The scale is settled before any frame is drawn and they
        all share it, so a change on screen is a change in the data. Per-frame normalisation would make a
        constant field shimmer and an outlier frame rescale the rest; pass ``vmin``/``vmax`` to pin the scale
        yourself, and either one alone fixes that end and measures the other. The scale is measured from an
        evenly-spread sample of at most ``DEFAULT_CLIM_SCAN_CAP`` (24) frames, as the 2-D tier measures its
        own — a long series does not read every frame into memory just to find its limits.

        **Memory is bounded by one frame, not the stack.** Frames are read and colourised one at a time, as
        each is drawn, never all held at once; a 624-band series animates in roughly the footprint of a
        single frame. The default ``shape`` is a 1440x2880 texture (~17 MB each), so a coarser ``shape=`` is
        worth passing when the output is small.

        **Overlays come along.** Anything added with :meth:`points`, :meth:`coastlines`, :meth:`borders` or
        :meth:`land` is re-placed on every frame, so a coastline stays registered to the ground while the
        field beneath it changes. That is the whole reason this is a method rather than something a caller
        assembles: stepping the texture by hand means rebuilding the globe per frame, and clearing the axes
        to do so throws the overlays away.

        Each frame is read through :meth:`_global_values`, the same path :meth:`from_dataset` takes, so a
        frame is placed exactly as a single raster would be. cleopatra's ``texture`` is a read-only property,
        so each frame builds a glyph around its own texture from the options this globe was constructed with.

        Args:
            stack: The rasters to step, one per frame — a sequence of pyramids ``Dataset`` objects, or
                anything iterable that yields them (a ``DatasetCollection`` indexes the same way).
            ax: An existing ``Axes3D`` to animate on. When omitted, the constructor's axes is used if one was
                given, and only otherwise is a new figure created.
            band: 1-based index of the band to read from every frame.
            cmap: Colormap name or object, resolved by cleopatra for all frames alike.
            vmin: Low end of the shared colour scale; ``None`` (default) measures it across the stack.
            vmax: High end of the shared colour scale; ``None`` (default) measures it across the stack.
            shape: The ``(rows, cols)`` global texture grid every frame is aligned onto.
            resampling: The pyramids resampling method for that align.
            titles: One title per frame, set on the axes as it is drawn; ``None`` (default) leaves the title
                alone.
            spin: The spin to hold the camera at, in degrees — the same ``spin=`` that :meth:`draw` and the
                glyph take, named to match them rather than the :meth:`spin` method. ``None`` (default) keeps
                the globe where it
                already is, so a decorated globe animates from the view it was drawn at.
            interval: Milliseconds between frames.
            **kwargs: Forwarded to the glyph's ``draw`` on every frame (``sun``, ``ambient``, and the render
                options). ``figsize`` sizes the figure created here, or resizes the one the globe already
                owns, and is ignored when ``ax`` is given.

        Returns:
            The ``FuncAnimation`` over the stack. It is also kept on ``self._animation`` so it is not
            garbage-collected before you save or display it.

        Raises:
            ValueError: If ``stack`` yields no frames, ``titles`` does not have one entry per frame,
                ``interval`` is not a positive number of milliseconds, a frame has no CRS or too few bands,
                or a render option or lighting argument is out of contract.

        Examples:
            - Step a two-frame stack; the colour scale is measured across both, so the second frame being
                warmer is visible rather than normalised away:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from pyramids.dataset import Dataset, GeoReference
                >>> from digitalearth.static import TexturedGlobe
                >>> ref = GeoReference(geo=(-180.0, 2.0, 0.0, 90.0, 0.0, -2.0), epsg=4326)
                >>> cool = Dataset.from_array(np.zeros((90, 180), "float32"), geo_ref=ref)
                >>> warm = Dataset.from_array(np.ones((90, 180), "float32"), geo_ref=ref)
                >>> globe = TexturedGlobe.from_dataset(cool, shape=(90, 180), n_lon=16, n_lat=8)
                >>> anim = globe.animate([cool, warm], shape=(90, 180), interval=100)
                >>> len(list(anim.new_frame_seq()))
                2

                ```
            - A stack with a title per frame:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from pyramids.dataset import Dataset, GeoReference
                >>> from digitalearth.static import TexturedGlobe
                >>> ref = GeoReference(geo=(-180.0, 2.0, 0.0, 90.0, 0.0, -2.0), epsg=4326)
                >>> frames = [
                ...     Dataset.from_array(np.full((90, 180), v, "float32"), geo_ref=ref)
                ...     for v in (1.0, 2.0)
                ... ]
                >>> globe = TexturedGlobe.from_dataset(frames[0], shape=(90, 180), n_lon=16, n_lat=8)
                >>> _ = globe.animate(frames, shape=(90, 180), titles=["Jan", "Feb"], interval=100)
                >>> globe.ax.get_title()
                'Jan'

                ```
        """
        frames, interval = self._animate_frames(stack, titles, interval)
        low, high = self._animate_scale(
            frames, vmin=vmin, vmax=vmax, band=band, shape=shape, resampling=resampling
        )
        at_spin = self._spin if spin is None else float(spin)
        ax, supplied = self._animate_axes(ax, kwargs)
        if titles is not None and ax.get_title():
            # The globe's counterpart of the 2-D tier's titles-vs-set_title warning: a per-frame caption
            # paints over whatever heading the axes already carries, so the two would disagree for the clip.
            warnings.warn(
                f"titles= captions each frame, painting over the title already on the axes "
                f"({ax.get_title()!r}); drop one of the two.",
                RuntimeWarning,
                stacklevel=2,
            )

        def _texture(index: int) -> np.ndarray:
            """Read one frame onto the global grid and colourise it against the settled scale.

            Reading here, as the frame is drawn, is the other half of keeping a long stack out of memory:
            only the frame on screen is alive, never the whole series. It costs one align per draw, which
            is what the 2-D tier's in-place animation does too.
            """
            grid = self._global_values(
                frames[index], band=band, shape=shape, resampling=resampling
            )
            return _as_byte_texture(
                self._colorize(grid, cmap=cmap, vmin=low, vmax=high)
            )

        def _show(index: int, texture: np.ndarray | None = None) -> None:
            """Draw one frame: its own texture, the held spin, and the overlays turned to match."""
            self.glyph = TexturedGlobeGlyph(
                _texture(index) if texture is None else texture, **self._glyph_kwargs
            )
            self.glyph.draw(ax, spin=at_spin, **kwargs)
            self._spin = at_spin
            self._turn_overlays(ax, at_spin)
            if titles is not None:
                ax.set_title(str(titles[index]))

        # The first frame is drawn now, as spin() does it: a bad render option is refused at this call
        # rather than from inside the frame loop. Its texture is read once here and reused for the draw.
        first_texture = _texture(0)
        _show(0, first_texture)
        self._bind(ax, owns=not supplied)
        self._warn_if_finer_than_the_mesh(first_texture)

        def _frame(index: int) -> tuple[Any, ...]:
            _show(index)
            return (self.glyph.surface,)

        anim = FuncAnimation(
            _root_figure(ax),
            _frame,
            frames=len(frames),
            interval=interval,
            blit=False,
        )
        self._animation = (
            anim  # keep a strong reference so it survives until save/display
        )
        self._animation_fps = 1000.0 / interval
        return anim

    def spin(self, ax: Any = None, **kwargs: Any) -> FuncAnimation:
        """Animate a full rotation of the camera, returning a matplotlib ``FuncAnimation``.

        This turns the **viewpoint** around one fixed texture. To step a **series of rasters** instead,
        holding the camera still, use :meth:`animate` — the two are deliberately separate, because
        spinning while stepping time conflates them and a viewer cannot tell whether a change on screen
        is the data or the vantage point.

        When no ``ax`` is given the 3-D axes is created here rather than inside the glyph, so :attr:`fig` and
        :attr:`ax` are known without reaching into the animation's internals — which is what lets
        :meth:`save_animation` and :meth:`stamp` work on an animated globe.

        Overlays turn with the sphere. Anything added with :meth:`points`, :meth:`coastlines`,
        :meth:`borders` or :meth:`land` is turned to each frame's spin, so markers and coastlines stay
        attached to the ground; pass ``spin=`` to one of those to pin it in place instead. Called without
        an ``ax``, this animates on the axes the globe already owns, so a globe that was drawn and
        decorated keeps its overlays.

        The rotation is swept here rather than by the glyph's own ``animate``, which is how each frame's
        spin is known; it sweeps the same one, ``start_spin`` plus ``revolutions`` whole turns spread over
        ``n_frames`` frames. The first frame is drawn by this call, so a bad render option is refused here
        rather than from inside the frame loop — at the cost of one render, about half a second on the
        default mesh, before the animation comes back.

        Args:
            ax: An existing ``Axes3D`` to animate on. When omitted, the constructor's axes is used if one
                was given, and only otherwise is a new figure created.
            **kwargs: ``n_frames``, ``revolutions``, ``start_spin`` and ``interval`` shape the rotation and
                are read here; the rest (``sun``, ``ambient``, and the render options) goes to the glyph's
                ``draw`` on every frame. ``figsize`` sizes the figure created here, or resizes the one the
                globe already owns, and is ignored when ``ax`` is given.

        Returns:
            The ``FuncAnimation`` over the rotation. It is also kept on ``self._animation`` so it is not
            garbage-collected before you save or display it.

        Raises:
            ValueError: If ``interval`` is not a positive number of milliseconds, ``n_frames`` is below 1,
                or a render option or lighting argument is out of contract.

        Examples:
            - Animate a rotation; the figure and axes are recorded for saving or stamping afterwards:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> anim = globe.spin(n_frames=4, interval=100)
                >>> globe.ax.name
                '3d'
                >>> globe.fig is globe.ax.get_figure()
                True

                ```
            - Animate onto an axes you already own:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> import matplotlib.pyplot as plt
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> ax = plt.figure().add_subplot(projection="3d")
                >>> anim = globe.spin(ax, n_frames=2, interval=200)
                >>> globe.ax is ax
                True

                ```
        """
        interval = float(kwargs.pop("interval", _DEFAULT_INTERVAL_MS))
        if interval <= 0:
            raise ValueError(
                f"interval must be a positive number of milliseconds, got {interval!r}"
            )
        n_frames = int(kwargs.pop("n_frames", _DEFAULT_N_FRAMES))
        if n_frames < 1:
            raise ValueError(f"n_frames must be at least 1, got {n_frames}")
        spins = float(kwargs.pop("start_spin", 0.0)) + np.linspace(
            0.0,
            360.0 * float(kwargs.pop("revolutions", _DEFAULT_REVOLUTIONS)),
            n_frames,
            endpoint=False,
        )
        supplied = not (ax is None or self._is_ours(ax)) or self._caller_supplied_axes
        if ax is None:
            ax = (
                self._ctor_ax
            )  # a globe built around the caller's axes keeps animating there
        ax = self._reuse_own_axes(ax, kwargs)
        if ax is None:
            figsize = kwargs.pop(
                "figsize", self.glyph.default_options.get("figsize", (6, 6))
            )
            ax = plt.figure(figsize=figsize).add_subplot(projection="3d")
        # The rotation is swept here rather than by the glyph's own animate, so each frame's spin is known
        # without reaching into the glyph. The first frame is drawn now: a bad render option or lighting
        # argument is refused at this call, as the glyph's animate would, and not from inside the frame loop.
        self.glyph.draw(ax, spin=float(spins[0]), **kwargs)
        self._bind(ax, owns=not supplied)
        self._spin = float(spins[0])
        self._turn_overlays(ax, self._spin)

        def _frame(index: int) -> tuple[Any, ...]:
            spin = float(spins[index])
            self.glyph.draw(ax, spin=spin, **kwargs)
            self._spin = spin
            self._turn_overlays(ax, spin)
            return (self.glyph.surface,)

        anim = FuncAnimation(
            _root_figure(ax), _frame, frames=n_frames, interval=interval, blit=False
        )
        self._animation = (
            anim  # keep a strong reference so it survives until save/display
        )
        self._animation_fps = 1000.0 / interval
        return anim

    def save(self, path: str | os.PathLike[str], **kwargs: Any) -> Path:
        """Save the drawn figure to ``path``.

        Args:
            path: Destination file path.
            **kwargs: Forwarded to ``Figure.savefig``.

        Returns:
            The path that was written, as a :class:`pathlib.Path` — the same contract as every other
            backend's ``save``.

        Raises:
            RuntimeError: if the globe has not been drawn yet.

        Examples:
            - Draw, then write the figure to disk:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> import tempfile
                >>> from pathlib import Path
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> fig, ax = globe.draw()
                >>> out = Path(tempfile.mkdtemp()) / "globe.png"
                >>> written = globe.save(str(out))
                >>> written == out
                True
                >>> out.exists() and out.stat().st_size > 0
                True

                ```
            - Saving before drawing is refused, rather than writing an empty figure:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> globe.save("globe.png")
                Traceback (most recent call last):
                    ...
                RuntimeError: draw() the globe before saving it

                ```
        """
        if self.fig is None:
            raise RuntimeError("draw() the globe before saving it")
        self.fig.savefig(path, **kwargs)
        return Path(path)

    def save_animation(
        self,
        path: str,
        *,
        fps: float | None = None,
        gif: str | None = None,
        **kwargs: Any,
    ) -> Any:
        """Save the animation built by :meth:`spin` or :meth:`animate`, optionally also deriving a GIF.

        A textured globe is exactly the case the derive-a-GIF path exists for: every frame is a full 3-D
        surface redraw, so encoding twice off one render is far cheaper than rendering twice.

        Args:
            path: Output path; the extension picks the format.
            fps: Frames per second. Defaults to the animation's own interval.
            gif: Optional second path to derive a GIF at. Requires ``path`` to be a video.
            **kwargs: Forwarded to :func:`digitalearth.static.render.animation.save_animation`.

        Returns:
            The written path, or a ``(video, gif)`` pair when ``gif`` was requested.

        Raises:
            RuntimeError: if no animation has been built yet — call :meth:`spin` or :meth:`animate` first.

        Examples:
            - Animate, then write the rotation straight to a GIF:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> import tempfile
                >>> from pathlib import Path
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> anim = globe.spin(n_frames=2, interval=200)
                >>> out = Path(tempfile.mkdtemp()) / "globe.gif"
                >>> written = globe.save_animation(str(out))
                >>> Path(written).exists()
                True

                ```
            - Render once and deliver both a video and a GIF derived from it:
                ```python
                >>> video, gif = globe.save_animation("globe.mp4", gif="globe.gif")  # doctest: +SKIP

                ```
        """
        if self._animation is None:
            raise RuntimeError("no animation to save; call spin() or animate() first")
        anim = self._animation
        rate = fps if fps is not None else self._animation_fps
        return save_animation(anim, path, fps=rate, gif=gif, **kwargs)

    def close(self) -> None:
        """Close the globe's figure, drop the animation reference, and forget the overlays.

        Every :meth:`draw`, :meth:`spin` or :meth:`animate` that is not handed an existing axes creates a pyplot figure,
        and pyplot keeps a reference to it forever. A loop that builds many globes therefore grows without
        bound and eventually trips matplotlib's open-figure warning. Closing releases both the figure and the
        retained animation.

        Only a figure this globe created is closed. An axes handed in by the caller — to ``__init__``,
        ``draw(ax=...)`` or ``animate(ax=...)`` — belongs to the caller, who may well have other subplots on
        it, so its figure is left alone.

        The overlays are forgotten either way, so a later draw — on any axes — starts without them rather
        than turning markers that belong to a figure the caller has finished with.

        Safe to call more than once, and on a globe that was never drawn.

        Examples:
            - Close a drawn globe and see the figure released:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import matplotlib.pyplot as plt
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> plt.close("all")
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> fig, ax = globe.draw()
                >>> len(plt.get_fignums())
                1
                >>> globe.close()
                >>> len(plt.get_fignums())
                0

                ```
        """
        if self.fig is not None and self._owns_fig:
            plt.close(self.fig)
        self._owns_fig = False
        self.fig = None
        self.ax = None
        self._animation = None
        self._animation_fps = None
        self._overlays = []

    def __enter__(self) -> "TexturedGlobe":
        """Enter the runtime context, returning the globe so ``with TexturedGlobe(...) as g:`` binds it.

        Returns:
            This globe.
        """
        return self

    def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> bool:
        """Close the figure on exit so a long run of globes stays memory-bounded.

        Mirrors :class:`~digitalearth.static.core.scene.Scene`: the figure is closed whether or not the body
        raised, and any exception propagates (``__exit__`` returns ``False``), so ``with`` never swallows an
        error.

        Args:
            exc_type: Exception class raised in the body, if any.
            exc: The exception instance, if any.
            tb: The traceback, if any.

        Returns:
            ``False``, so an exception raised inside the block is re-raised.
        """
        self.close()
        return False

    def stamp(self, mark: Any, **kwargs: Any) -> Any:
        """Stamp a logo / watermark onto the globe's figure.

        The same figure-level mark as :meth:`digitalearth.static.core.scene.Scene.stamp`, and it carries the same
        two caveats: stamp **last**, because the mark is baked from the figure's current size, and note that
        a ``bbox_inches="tight"`` save crops surrounding whitespace and so shifts the mark's margin.

        Args:
            mark: The mark image — a file path or an ``(H, W, 3)`` / ``(H, W, 4)`` array.
            **kwargs: Forwarded to cleopatra's ``WatermarkMixin.stamp_mark``.

        Returns:
            The frameless inset ``Axes`` the mark was drawn on.

        Raises:
            RuntimeError: if the globe has not been drawn yet.

        Examples:
            - Stamp a mark onto the drawn globe; it arrives as an extra axes on the figure:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> fig, ax = globe.draw()
                >>> mark = np.full((8, 16, 4), 255, dtype=np.uint8)
                >>> mark_ax = globe.stamp(mark, frac=0.2, shadow=False)
                >>> len(fig.axes)
                2
                >>> round(float(mark_ax.get_position().bounds[2]), 3)
                0.2

                ```
            - Stamping before drawing is refused:
                ```python
                >>> import matplotlib
                >>> matplotlib.use("Agg")
                >>> import numpy as np
                >>> from digitalearth.static import TexturedGlobe
                >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
                >>> globe.stamp(np.full((8, 16, 4), 255, dtype=np.uint8))
                Traceback (most recent call last):
                    ...
                RuntimeError: draw() the globe before stamping it

                ```
        """
        if self.fig is None:
            raise RuntimeError("draw() the globe before stamping it")
        return self.stamp_mark(mark, **kwargs)

__enter__() #

Enter the runtime context, returning the globe so with TexturedGlobe(...) as g: binds it.

Returns:

Type Description
TexturedGlobe

This globe.

Source code in src/digitalearth/static/globe/textured_globe.py
def __enter__(self) -> "TexturedGlobe":
    """Enter the runtime context, returning the globe so ``with TexturedGlobe(...) as g:`` binds it.

    Returns:
        This globe.
    """
    return self

__exit__(exc_type, exc, tb) #

Close the figure on exit so a long run of globes stays memory-bounded.

Mirrors :class:~digitalearth.static.core.scene.Scene: the figure is closed whether or not the body raised, and any exception propagates (__exit__ returns False), so with never swallows an error.

Parameters:

Name Type Description Default
exc_type Any

Exception class raised in the body, if any.

required
exc Any

The exception instance, if any.

required
tb Any

The traceback, if any.

required

Returns:

Type Description
bool

False, so an exception raised inside the block is re-raised.

Source code in src/digitalearth/static/globe/textured_globe.py
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> bool:
    """Close the figure on exit so a long run of globes stays memory-bounded.

    Mirrors :class:`~digitalearth.static.core.scene.Scene`: the figure is closed whether or not the body
    raised, and any exception propagates (``__exit__`` returns ``False``), so ``with`` never swallows an
    error.

    Args:
        exc_type: Exception class raised in the body, if any.
        exc: The exception instance, if any.
        tb: The traceback, if any.

    Returns:
        ``False``, so an exception raised inside the block is re-raised.
    """
    self.close()
    return False

__init__(texture, **kwargs) #

Wrap an equirectangular texture in a cleopatra globe glyph.

Parameters:

Name Type Description Default
texture ndarray

An equirectangular (H, W, 3) or (H, W, 4) array — row 0 at +90 degrees, column 0 at -180 degrees.

required
**kwargs Any

Forwarded to TexturedGlobeGlyph (tilt_deg, n_lon, n_lat, brightness, sun, ambient, fig, ax).

{}

Raises:

Type Description
ValueError

If texture is not a 3-channel or 4-channel 2-D image, or if a lighting argument is out of contract (a zero-length sun, an ambient outside [0, 1]).

Source code in src/digitalearth/static/globe/textured_globe.py
def __init__(self, texture: np.ndarray, **kwargs: Any):
    """Wrap an equirectangular texture in a cleopatra globe glyph.

    Args:
        texture: An equirectangular ``(H, W, 3)`` or ``(H, W, 4)`` array — row 0 at +90 degrees, column
            0 at -180 degrees.
        **kwargs: Forwarded to ``TexturedGlobeGlyph`` (``tilt_deg``, ``n_lon``, ``n_lat``,
            ``brightness``, ``sun``, ``ambient``, ``fig``, ``ax``).

    Raises:
        ValueError: If ``texture`` is not a 3-channel or 4-channel 2-D image, or if a lighting argument
            is out of contract (a zero-length ``sun``, an ``ambient`` outside ``[0, 1]``).
    """
    self.glyph = TexturedGlobeGlyph(texture, **kwargs)
    #: The glyph options, so a frame of :meth:`animate` can rebuild the glyph around a new texture and
    #: be identical in every other respect. cleopatra's ``texture`` is a read-only property, so a
    #: stack is stepped by constructing a glyph per frame rather than by assigning to the one we hold;
    #: ``fig``/``ax`` are dropped because a frame draws on the axes the animation already owns.
    self._glyph_kwargs: dict[str, Any] = {
        key: value for key, value in kwargs.items() if key not in ("fig", "ax")
    }
    #: A glyph of the same tilt carrying no texture, whose ``transform`` places the overlays. They
    #: cannot hold the drawing glyph's own method: that keeps its texture alive for as long as the
    #: artist lives, and drags it into anything the figure is pickled or copied into — one marker took
    #: a saved figure from about 1 MB to 134 MB. The rotation depends on the tilt and nothing else, so
    #: this places points exactly as the real glyph does.
    self._placer = TexturedGlobeGlyph(
        np.zeros((2, 4, 3), dtype=np.uint8),
        tilt_deg=kwargs.get("tilt_deg", EARTH_TILT_DEG),
        n_lon=4,
        n_lat=2,
    )
    self.fig: Any = None
    self.ax: Any = None
    # Declared up front rather than sprung into existence by animate(), so every reader can see the
    # instance's full state and the accessors need no getattr() guards.
    self._animation: FuncAnimation | None = None
    self._animation_fps: float | None = None
    #: A fig/ax handed to the constructor is the caller's too — the glyph stores it and draws on it even
    #: when no later call passes one, so ownership has to be settled here, not only at draw time.
    self._caller_supplied_axes: bool = (
        kwargs.get("ax") is not None or kwargs.get("fig") is not None
    )
    #: The spin the globe was last drawn at, so an overlay defaults to the surface it can see.
    self._spin: float = 0.0
    #: The overlays that follow the globe, each still on the axes it was drawn on. A draw or animation
    #: frame turns the ones on its own axes (see :meth:`_turn_overlays`).
    self._overlays: list[Any] = []
    #: Whether :attr:`fig` is ours to close. A caller-supplied axes belongs to the caller.
    self._owns_fig: bool = False
    #: The axes the constructor was given, if any. animate() falls back to it so a globe built around a
    #: caller's axes keeps drawing there instead of opening a figure of its own.
    self._ctor_ax: Any = kwargs.get("ax")

animate(stack, *, ax=None, band=DEFAULT_BAND, cmap='viridis', vmin=None, vmax=None, shape=DEFAULT_TEXTURE_SHAPE, resampling='nearest', titles=None, spin=None, interval=_DEFAULT_INTERVAL_MS, **kwargs) #

Step a series of rasters across the globe, returning a matplotlib FuncAnimation.

The globe counterpart of :meth:~digitalearth.static.builders.animation.AnimationMixin.animate on the 2-D tier: the camera holds still and the data changes, which is what a time series of a global field — sea-surface temperature, sea ice, an anomaly field — wants. To turn the viewpoint around one fixed texture instead, use :meth:spin.

One colour scale across the whole stack. The scale is settled before any frame is drawn and they all share it, so a change on screen is a change in the data. Per-frame normalisation would make a constant field shimmer and an outlier frame rescale the rest; pass vmin/vmax to pin the scale yourself, and either one alone fixes that end and measures the other. The scale is measured from an evenly-spread sample of at most DEFAULT_CLIM_SCAN_CAP (24) frames, as the 2-D tier measures its own — a long series does not read every frame into memory just to find its limits.

Memory is bounded by one frame, not the stack. Frames are read and colourised one at a time, as each is drawn, never all held at once; a 624-band series animates in roughly the footprint of a single frame. The default shape is a 1440x2880 texture (~17 MB each), so a coarser shape= is worth passing when the output is small.

Overlays come along. Anything added with :meth:points, :meth:coastlines, :meth:borders or :meth:land is re-placed on every frame, so a coastline stays registered to the ground while the field beneath it changes. That is the whole reason this is a method rather than something a caller assembles: stepping the texture by hand means rebuilding the globe per frame, and clearing the axes to do so throws the overlays away.

Each frame is read through :meth:_global_values, the same path :meth:from_dataset takes, so a frame is placed exactly as a single raster would be. cleopatra's texture is a read-only property, so each frame builds a glyph around its own texture from the options this globe was constructed with.

Parameters:

Name Type Description Default
stack Any

The rasters to step, one per frame — a sequence of pyramids Dataset objects, or anything iterable that yields them (a DatasetCollection indexes the same way).

required
ax Any

An existing Axes3D to animate on. When omitted, the constructor's axes is used if one was given, and only otherwise is a new figure created.

None
band int

1-based index of the band to read from every frame.

DEFAULT_BAND
cmap Any

Colormap name or object, resolved by cleopatra for all frames alike.

'viridis'
vmin float | None

Low end of the shared colour scale; None (default) measures it across the stack.

None
vmax float | None

High end of the shared colour scale; None (default) measures it across the stack.

None
shape tuple[int, int]

The (rows, cols) global texture grid every frame is aligned onto.

DEFAULT_TEXTURE_SHAPE
resampling str

The pyramids resampling method for that align.

'nearest'
titles Sequence[Any] | None

One title per frame, set on the axes as it is drawn; None (default) leaves the title alone.

None
spin float | None

The spin to hold the camera at, in degrees — the same spin= that :meth:draw and the glyph take, named to match them rather than the :meth:spin method. None (default) keeps the globe where it already is, so a decorated globe animates from the view it was drawn at.

None
interval float

Milliseconds between frames.

_DEFAULT_INTERVAL_MS
**kwargs Any

Forwarded to the glyph's draw on every frame (sun, ambient, and the render options). figsize sizes the figure created here, or resizes the one the globe already owns, and is ignored when ax is given.

{}

Returns:

Type Description
FuncAnimation

The FuncAnimation over the stack. It is also kept on self._animation so it is not

FuncAnimation

garbage-collected before you save or display it.

Raises:

Type Description
ValueError

If stack yields no frames, titles does not have one entry per frame, interval is not a positive number of milliseconds, a frame has no CRS or too few bands, or a render option or lighting argument is out of contract.

Examples:

  • Step a two-frame stack; the colour scale is measured across both, so the second frame being warmer is visible rather than normalised away:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import TexturedGlobe
    >>> ref = GeoReference(geo=(-180.0, 2.0, 0.0, 90.0, 0.0, -2.0), epsg=4326)
    >>> cool = Dataset.from_array(np.zeros((90, 180), "float32"), geo_ref=ref)
    >>> warm = Dataset.from_array(np.ones((90, 180), "float32"), geo_ref=ref)
    >>> globe = TexturedGlobe.from_dataset(cool, shape=(90, 180), n_lon=16, n_lat=8)
    >>> anim = globe.animate([cool, warm], shape=(90, 180), interval=100)
    >>> len(list(anim.new_frame_seq()))
    2
    
  • A stack with a title per frame:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from digitalearth.static import TexturedGlobe
    >>> ref = GeoReference(geo=(-180.0, 2.0, 0.0, 90.0, 0.0, -2.0), epsg=4326)
    >>> frames = [
    ...     Dataset.from_array(np.full((90, 180), v, "float32"), geo_ref=ref)
    ...     for v in (1.0, 2.0)
    ... ]
    >>> globe = TexturedGlobe.from_dataset(frames[0], shape=(90, 180), n_lon=16, n_lat=8)
    >>> _ = globe.animate(frames, shape=(90, 180), titles=["Jan", "Feb"], interval=100)
    >>> globe.ax.get_title()
    'Jan'
    
Source code in src/digitalearth/static/globe/textured_globe.py
def animate(
    self,
    stack: Any,
    *,
    ax: Any = None,
    band: int = DEFAULT_BAND,
    cmap: Any = "viridis",
    vmin: float | None = None,
    vmax: float | None = None,
    shape: tuple[int, int] = DEFAULT_TEXTURE_SHAPE,
    resampling: str = "nearest",
    titles: Sequence[Any] | None = None,
    spin: float | None = None,
    interval: float = _DEFAULT_INTERVAL_MS,
    **kwargs: Any,
) -> FuncAnimation:
    """Step a series of rasters across the globe, returning a matplotlib ``FuncAnimation``.

    The globe counterpart of :meth:`~digitalearth.static.builders.animation.AnimationMixin.animate` on the
    2-D tier: the camera holds still and the **data** changes, which is what a time series of a global
    field — sea-surface temperature, sea ice, an anomaly field — wants. To turn the viewpoint around one
    fixed texture instead, use :meth:`spin`.

    **One colour scale across the whole stack.** The scale is settled before any frame is drawn and they
    all share it, so a change on screen is a change in the data. Per-frame normalisation would make a
    constant field shimmer and an outlier frame rescale the rest; pass ``vmin``/``vmax`` to pin the scale
    yourself, and either one alone fixes that end and measures the other. The scale is measured from an
    evenly-spread sample of at most ``DEFAULT_CLIM_SCAN_CAP`` (24) frames, as the 2-D tier measures its
    own — a long series does not read every frame into memory just to find its limits.

    **Memory is bounded by one frame, not the stack.** Frames are read and colourised one at a time, as
    each is drawn, never all held at once; a 624-band series animates in roughly the footprint of a
    single frame. The default ``shape`` is a 1440x2880 texture (~17 MB each), so a coarser ``shape=`` is
    worth passing when the output is small.

    **Overlays come along.** Anything added with :meth:`points`, :meth:`coastlines`, :meth:`borders` or
    :meth:`land` is re-placed on every frame, so a coastline stays registered to the ground while the
    field beneath it changes. That is the whole reason this is a method rather than something a caller
    assembles: stepping the texture by hand means rebuilding the globe per frame, and clearing the axes
    to do so throws the overlays away.

    Each frame is read through :meth:`_global_values`, the same path :meth:`from_dataset` takes, so a
    frame is placed exactly as a single raster would be. cleopatra's ``texture`` is a read-only property,
    so each frame builds a glyph around its own texture from the options this globe was constructed with.

    Args:
        stack: The rasters to step, one per frame — a sequence of pyramids ``Dataset`` objects, or
            anything iterable that yields them (a ``DatasetCollection`` indexes the same way).
        ax: An existing ``Axes3D`` to animate on. When omitted, the constructor's axes is used if one was
            given, and only otherwise is a new figure created.
        band: 1-based index of the band to read from every frame.
        cmap: Colormap name or object, resolved by cleopatra for all frames alike.
        vmin: Low end of the shared colour scale; ``None`` (default) measures it across the stack.
        vmax: High end of the shared colour scale; ``None`` (default) measures it across the stack.
        shape: The ``(rows, cols)`` global texture grid every frame is aligned onto.
        resampling: The pyramids resampling method for that align.
        titles: One title per frame, set on the axes as it is drawn; ``None`` (default) leaves the title
            alone.
        spin: The spin to hold the camera at, in degrees — the same ``spin=`` that :meth:`draw` and the
            glyph take, named to match them rather than the :meth:`spin` method. ``None`` (default) keeps
            the globe where it
            already is, so a decorated globe animates from the view it was drawn at.
        interval: Milliseconds between frames.
        **kwargs: Forwarded to the glyph's ``draw`` on every frame (``sun``, ``ambient``, and the render
            options). ``figsize`` sizes the figure created here, or resizes the one the globe already
            owns, and is ignored when ``ax`` is given.

    Returns:
        The ``FuncAnimation`` over the stack. It is also kept on ``self._animation`` so it is not
        garbage-collected before you save or display it.

    Raises:
        ValueError: If ``stack`` yields no frames, ``titles`` does not have one entry per frame,
            ``interval`` is not a positive number of milliseconds, a frame has no CRS or too few bands,
            or a render option or lighting argument is out of contract.

    Examples:
        - Step a two-frame stack; the colour scale is measured across both, so the second frame being
            warmer is visible rather than normalised away:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import TexturedGlobe
            >>> ref = GeoReference(geo=(-180.0, 2.0, 0.0, 90.0, 0.0, -2.0), epsg=4326)
            >>> cool = Dataset.from_array(np.zeros((90, 180), "float32"), geo_ref=ref)
            >>> warm = Dataset.from_array(np.ones((90, 180), "float32"), geo_ref=ref)
            >>> globe = TexturedGlobe.from_dataset(cool, shape=(90, 180), n_lon=16, n_lat=8)
            >>> anim = globe.animate([cool, warm], shape=(90, 180), interval=100)
            >>> len(list(anim.new_frame_seq()))
            2

            ```
        - A stack with a title per frame:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from digitalearth.static import TexturedGlobe
            >>> ref = GeoReference(geo=(-180.0, 2.0, 0.0, 90.0, 0.0, -2.0), epsg=4326)
            >>> frames = [
            ...     Dataset.from_array(np.full((90, 180), v, "float32"), geo_ref=ref)
            ...     for v in (1.0, 2.0)
            ... ]
            >>> globe = TexturedGlobe.from_dataset(frames[0], shape=(90, 180), n_lon=16, n_lat=8)
            >>> _ = globe.animate(frames, shape=(90, 180), titles=["Jan", "Feb"], interval=100)
            >>> globe.ax.get_title()
            'Jan'

            ```
    """
    frames, interval = self._animate_frames(stack, titles, interval)
    low, high = self._animate_scale(
        frames, vmin=vmin, vmax=vmax, band=band, shape=shape, resampling=resampling
    )
    at_spin = self._spin if spin is None else float(spin)
    ax, supplied = self._animate_axes(ax, kwargs)
    if titles is not None and ax.get_title():
        # The globe's counterpart of the 2-D tier's titles-vs-set_title warning: a per-frame caption
        # paints over whatever heading the axes already carries, so the two would disagree for the clip.
        warnings.warn(
            f"titles= captions each frame, painting over the title already on the axes "
            f"({ax.get_title()!r}); drop one of the two.",
            RuntimeWarning,
            stacklevel=2,
        )

    def _texture(index: int) -> np.ndarray:
        """Read one frame onto the global grid and colourise it against the settled scale.

        Reading here, as the frame is drawn, is the other half of keeping a long stack out of memory:
        only the frame on screen is alive, never the whole series. It costs one align per draw, which
        is what the 2-D tier's in-place animation does too.
        """
        grid = self._global_values(
            frames[index], band=band, shape=shape, resampling=resampling
        )
        return _as_byte_texture(
            self._colorize(grid, cmap=cmap, vmin=low, vmax=high)
        )

    def _show(index: int, texture: np.ndarray | None = None) -> None:
        """Draw one frame: its own texture, the held spin, and the overlays turned to match."""
        self.glyph = TexturedGlobeGlyph(
            _texture(index) if texture is None else texture, **self._glyph_kwargs
        )
        self.glyph.draw(ax, spin=at_spin, **kwargs)
        self._spin = at_spin
        self._turn_overlays(ax, at_spin)
        if titles is not None:
            ax.set_title(str(titles[index]))

    # The first frame is drawn now, as spin() does it: a bad render option is refused at this call
    # rather than from inside the frame loop. Its texture is read once here and reused for the draw.
    first_texture = _texture(0)
    _show(0, first_texture)
    self._bind(ax, owns=not supplied)
    self._warn_if_finer_than_the_mesh(first_texture)

    def _frame(index: int) -> tuple[Any, ...]:
        _show(index)
        return (self.glyph.surface,)

    anim = FuncAnimation(
        _root_figure(ax),
        _frame,
        frames=len(frames),
        interval=interval,
        blit=False,
    )
    self._animation = (
        anim  # keep a strong reference so it survives until save/display
    )
    self._animation_fps = 1000.0 / interval
    return anim

borders(resolution='110m', *, spin=None, altitude=0.002, **kwargs) #

Draw Natural-Earth country borders on the globe, split at the visible limb.

The counterpart of :meth:~digitalearth.static.Map.borders, same spelling and same default styling, so a globe and a flat map can be given the same reference geography.

Parameters:

Name Type Description Default
resolution str

Natural-Earth resolution — "110m" (default), "50m" or "10m".

'110m'
spin float | None

Pin the borders to this spin, in degrees. Omitted, they follow the globe.

None
altitude float

Radial lift above the surface.

0.002
**kwargs Any

Line styling forwarded to matplotlib, as for :meth:coastlines, including what zorder can and cannot do there.

{}

Returns:

Type Description
Any

The Line3DCollection holding every near-side arc. It stays on the axes as the globe turns.

Raises:

Type Description
RuntimeError

if the globe has not been drawn yet.

Examples:

  • Borders draw in their own default grey, thinner than the coastlines. The vectors are fetched (and cached) by cleopatra, so this needs a network on first use:
    >>> import matplotlib                                      # doctest: +SKIP
    >>> matplotlib.use("Agg")                                  # doctest: +SKIP
    >>> import numpy as np                                     # doctest: +SKIP
    >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
    >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
    >>> float(globe.borders().get_linewidth()[0])              # doctest: +SKIP
    0.4
    
  • Ask for the finer cut when the globe is drawn large:
    >>> import matplotlib                                      # doctest: +SKIP
    >>> matplotlib.use("Agg")                                  # doctest: +SKIP
    >>> import numpy as np                                     # doctest: +SKIP
    >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
    >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
    >>> fine, coarse = globe.borders("50m"), globe.borders("110m")  # doctest: +SKIP
    >>> globe.fig.canvas.draw()                                     # doctest: +SKIP
    >>> len(fine.get_segments()) > len(coarse.get_segments())       # doctest: +SKIP
    True
    
  • Asking before the globe is drawn is refused — there is no camera yet to clip against:
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8)).borders()
    Traceback (most recent call last):
        ...
    RuntimeError: draw() the globe before adding the 'borders' layer to it
    
Source code in src/digitalearth/static/globe/textured_globe.py
def borders(
    self,
    resolution: str = "110m",
    *,
    spin: float | None = None,
    altitude: float = 0.002,
    **kwargs: Any,
) -> Any:
    """Draw Natural-Earth country borders on the globe, split at the visible limb.

    The counterpart of :meth:`~digitalearth.static.Map.borders`, same spelling and same default
    styling, so a globe and a flat map can be given the same reference geography.

    Args:
        resolution: Natural-Earth resolution — ``"110m"`` (default), ``"50m"`` or ``"10m"``.
        spin: Pin the borders to this spin, in degrees. Omitted, they follow the globe.
        altitude: Radial lift above the surface.
        **kwargs: Line styling forwarded to matplotlib, as for :meth:`coastlines`, including what
            ``zorder`` can and cannot do there.

    Returns:
        The ``Line3DCollection`` holding every near-side arc. It stays on the axes as the globe turns.

    Raises:
        RuntimeError: if the globe has not been drawn yet.

    Examples:
        - Borders draw in their own default grey, thinner than the coastlines. The vectors are
          fetched (and cached) by ``cleopatra``, so this needs a network on first use:
            ```python
            >>> import matplotlib                                      # doctest: +SKIP
            >>> matplotlib.use("Agg")                                  # doctest: +SKIP
            >>> import numpy as np                                     # doctest: +SKIP
            >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
            >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
            >>> float(globe.borders().get_linewidth()[0])              # doctest: +SKIP
            0.4

            ```
        - Ask for the finer cut when the globe is drawn large:
            ```python
            >>> import matplotlib                                      # doctest: +SKIP
            >>> matplotlib.use("Agg")                                  # doctest: +SKIP
            >>> import numpy as np                                     # doctest: +SKIP
            >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
            >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
            >>> fine, coarse = globe.borders("50m"), globe.borders("110m")  # doctest: +SKIP
            >>> globe.fig.canvas.draw()                                     # doctest: +SKIP
            >>> len(fine.get_segments()) > len(coarse.get_segments())       # doctest: +SKIP
            True

            ```
        - Asking before the globe is drawn is refused — there is no camera yet to clip against:
            ```python
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8)).borders()
            Traceback (most recent call last):
                ...
            RuntimeError: draw() the globe before adding the 'borders' layer to it

            ```
    """
    return self._reference_layer(
        "borders",
        resolution,
        {"color": "gray", "linewidth": 0.4},
        spin=spin,
        altitude=altitude,
        fill=False,
        **kwargs,
    )

close() #

Close the globe's figure, drop the animation reference, and forget the overlays.

Every :meth:draw, :meth:spin or :meth:animate that is not handed an existing axes creates a pyplot figure, and pyplot keeps a reference to it forever. A loop that builds many globes therefore grows without bound and eventually trips matplotlib's open-figure warning. Closing releases both the figure and the retained animation.

Only a figure this globe created is closed. An axes handed in by the caller — to __init__, draw(ax=...) or animate(ax=...) — belongs to the caller, who may well have other subplots on it, so its figure is left alone.

The overlays are forgotten either way, so a later draw — on any axes — starts without them rather than turning markers that belong to a figure the caller has finished with.

Safe to call more than once, and on a globe that was never drawn.

Examples:

  • Close a drawn globe and see the figure released:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> plt.close("all")
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> fig, ax = globe.draw()
    >>> len(plt.get_fignums())
    1
    >>> globe.close()
    >>> len(plt.get_fignums())
    0
    
Source code in src/digitalearth/static/globe/textured_globe.py
def close(self) -> None:
    """Close the globe's figure, drop the animation reference, and forget the overlays.

    Every :meth:`draw`, :meth:`spin` or :meth:`animate` that is not handed an existing axes creates a pyplot figure,
    and pyplot keeps a reference to it forever. A loop that builds many globes therefore grows without
    bound and eventually trips matplotlib's open-figure warning. Closing releases both the figure and the
    retained animation.

    Only a figure this globe created is closed. An axes handed in by the caller — to ``__init__``,
    ``draw(ax=...)`` or ``animate(ax=...)`` — belongs to the caller, who may well have other subplots on
    it, so its figure is left alone.

    The overlays are forgotten either way, so a later draw — on any axes — starts without them rather
    than turning markers that belong to a figure the caller has finished with.

    Safe to call more than once, and on a globe that was never drawn.

    Examples:
        - Close a drawn globe and see the figure released:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> plt.close("all")
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> fig, ax = globe.draw()
            >>> len(plt.get_fignums())
            1
            >>> globe.close()
            >>> len(plt.get_fignums())
            0

            ```
    """
    if self.fig is not None and self._owns_fig:
        plt.close(self.fig)
    self._owns_fig = False
    self.fig = None
    self.ax = None
    self._animation = None
    self._animation_fps = None
    self._overlays = []

coastlines(resolution='110m', *, spin=None, altitude=0.002, **kwargs) #

Draw Natural-Earth coastlines on the globe, split at the visible limb.

Named and styled to match :meth:~digitalearth.static.Map.coastlines on the 2-D globe, so the two tiers read alike. Each coastline is placed on the sphere and broken into the arcs that face the camera, each carried out to the horizon; without that split every line crossing the limb would be drawn as a chord through the planet. The split is redone at every draw, for the spin and the camera of that moment.

Parameters:

Name Type Description Default
resolution str

Natural-Earth resolution — "110m" (default), "50m" or "10m".

'110m'
spin float | None

Pin the coastlines to this spin, in degrees. Omitted, they follow the globe and are redrawn at each animation frame's spin.

None
altitude float

Radial lift above the surface, so the lines are not z-fought by it.

0.002
**kwargs Any

Line styling forwarded to matplotlib (color, linewidth, linestyle, alpha), in any spelling it accepts (c, lw, ls, linewidths). zorder is taken for parity with :class:~digitalearth.static.Map but cannot move the layer: a 3-D axes orders its collections by depth, which always puts a layer in front of the sphere and behind the markers.

{}

Returns:

Type Description
Any

The Line3DCollection holding every near-side arc. It stays on the axes as the globe turns.

Any

The arcs are worked out when the figure is drawn, so get_segments() is empty until then.

Raises:

Type Description
RuntimeError

if the globe has not been drawn yet.

Examples:

  • Coastlines land on the sphere as a set of near-side arcs. The vectors are fetched (and cached) by cleopatra, so this needs a network on first use:
    >>> import matplotlib                                      # doctest: +SKIP
    >>> matplotlib.use("Agg")                                  # doctest: +SKIP
    >>> import numpy as np                                     # doctest: +SKIP
    >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
    >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
    >>> lines = globe.coastlines()                             # doctest: +SKIP
    >>> globe.fig.canvas.draw()                                # doctest: +SKIP
    >>> len(lines.get_segments())                              # doctest: +SKIP
    57
    
  • Restyle them like any matplotlib line, and pin them to one spin so they stay put while the globe turns:
    >>> import matplotlib                                      # doctest: +SKIP
    >>> matplotlib.use("Agg")                                  # doctest: +SKIP
    >>> import numpy as np                                     # doctest: +SKIP
    >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
    >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
    >>> lines = globe.coastlines(color="white", lw=1.2, spin=0.0)  # doctest: +SKIP
    >>> float(lines.get_linewidth()[0])                            # doctest: +SKIP
    1.2
    
  • Asking before the globe is drawn is refused — there is no camera yet to clip against:
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8)).coastlines()
    Traceback (most recent call last):
        ...
    RuntimeError: draw() the globe before adding the 'coastline' layer to it
    
Source code in src/digitalearth/static/globe/textured_globe.py
def coastlines(
    self,
    resolution: str = "110m",
    *,
    spin: float | None = None,
    altitude: float = 0.002,
    **kwargs: Any,
) -> Any:
    """Draw Natural-Earth coastlines on the globe, split at the visible limb.

    Named and styled to match :meth:`~digitalearth.static.Map.coastlines` on the 2-D globe, so the two
    tiers read alike. Each coastline is placed on the sphere and broken into the arcs that face the
    camera, each carried out to the horizon; without that split every line crossing the limb would be
    drawn as a chord through the planet. The split is redone at every draw, for the spin and the camera
    of that moment.

    Args:
        resolution: Natural-Earth resolution — ``"110m"`` (default), ``"50m"`` or ``"10m"``.
        spin: Pin the coastlines to this spin, in degrees. Omitted, they follow the globe and are
            redrawn at each animation frame's spin.
        altitude: Radial lift above the surface, so the lines are not z-fought by it.
        **kwargs: Line styling forwarded to matplotlib (``color``, ``linewidth``, ``linestyle``,
            ``alpha``), in any spelling it accepts (``c``, ``lw``, ``ls``, ``linewidths``). ``zorder``
            is taken for parity with :class:`~digitalearth.static.Map` but cannot move the layer: a
            3-D axes orders its collections by depth, which always puts a layer in front of the sphere
            and behind the markers.

    Returns:
        The ``Line3DCollection`` holding every near-side arc. It stays on the axes as the globe turns.
        The arcs are worked out when the figure is drawn, so ``get_segments()`` is empty until then.

    Raises:
        RuntimeError: if the globe has not been drawn yet.

    Examples:
        - Coastlines land on the sphere as a set of near-side arcs. The vectors are fetched (and
          cached) by ``cleopatra``, so this needs a network on first use:
            ```python
            >>> import matplotlib                                      # doctest: +SKIP
            >>> matplotlib.use("Agg")                                  # doctest: +SKIP
            >>> import numpy as np                                     # doctest: +SKIP
            >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
            >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
            >>> lines = globe.coastlines()                             # doctest: +SKIP
            >>> globe.fig.canvas.draw()                                # doctest: +SKIP
            >>> len(lines.get_segments())                              # doctest: +SKIP
            57

            ```
        - Restyle them like any matplotlib line, and pin them to one spin so they stay put while the
          globe turns:
            ```python
            >>> import matplotlib                                      # doctest: +SKIP
            >>> matplotlib.use("Agg")                                  # doctest: +SKIP
            >>> import numpy as np                                     # doctest: +SKIP
            >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
            >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
            >>> lines = globe.coastlines(color="white", lw=1.2, spin=0.0)  # doctest: +SKIP
            >>> float(lines.get_linewidth()[0])                            # doctest: +SKIP
            1.2

            ```
        - Asking before the globe is drawn is refused — there is no camera yet to clip against:
            ```python
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8)).coastlines()
            Traceback (most recent call last):
                ...
            RuntimeError: draw() the globe before adding the 'coastline' layer to it

            ```
    """
    return self._reference_layer(
        "coastline",
        resolution,
        {"color": "black", "linewidth": 0.5},
        spin=spin,
        altitude=altitude,
        fill=False,
        **kwargs,
    )

draw(ax=None, *, spin=0.0, **kwargs) #

Draw the globe, returning the matplotlib (fig, ax) and recording them on the instance.

A globe keeps drawing where it already is: called without an ax, this reuses the axes it owns, so overlays added since the last draw — :meth:points, :meth:coastlines, :meth:borders, :meth:land without a spin= — turn to the new spin and stay. figsize resizes that figure. Pass an ax to draw somewhere else instead; overlays stay behind with the axes they were drawn on, and a figure this globe owned and is leaving is closed.

Parameters:

Name Type Description Default
ax Any

An existing Axes3D to draw on, accepted positionally to match :meth:animate. A figure the caller supplies is never closed by :meth:close.

None
spin float

Rotation about the polar axis, in degrees.

0.0
**kwargs Any

Forwarded to the glyph's draw (sun, ambient, figsize, elev, azim, background).

{}

Returns:

Type Description
tuple[Any, Any]

The (Figure, Axes3D) the globe was drawn on.

Examples:

  • Draw the globe and keep the axes for further decoration:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> fig, ax = globe.draw(spin=45.0)
    >>> ax.name
    '3d'
    >>> globe.ax is ax
    True
    
  • Draw several spins onto axes you own, to build a contact sheet:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> import matplotlib.pyplot as plt
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> fig, axes = plt.subplots(1, 3, subplot_kw={"projection": "3d"})
    >>> for spin, sub in zip([0.0, 120.0, 240.0], axes):
    ...     _ = globe.draw(ax=sub, spin=spin)
    >>> len(fig.axes)
    3
    
Source code in src/digitalearth/static/globe/textured_globe.py
def draw(
    self, ax: Any = None, *, spin: float = 0.0, **kwargs: Any
) -> tuple[Any, Any]:
    """Draw the globe, returning the matplotlib ``(fig, ax)`` and recording them on the instance.

    A globe keeps drawing where it already is: called without an ``ax``, this reuses the axes it owns, so
    overlays added since the last draw — :meth:`points`, :meth:`coastlines`, :meth:`borders`,
    :meth:`land` without a ``spin=`` — turn to the new ``spin`` and stay. ``figsize`` resizes that
    figure. Pass an ``ax`` to draw somewhere else instead; overlays stay behind with the axes they
    were drawn on, and a figure this globe owned and is leaving is closed.

    Args:
        ax: An existing ``Axes3D`` to draw on, accepted positionally to match :meth:`animate`. A figure
            the caller supplies is never closed by :meth:`close`.
        spin: Rotation about the polar axis, in degrees.
        **kwargs: Forwarded to the glyph's ``draw`` (``sun``, ``ambient``, ``figsize``, ``elev``,
            ``azim``, ``background``).

    Returns:
        The ``(Figure, Axes3D)`` the globe was drawn on.

    Examples:
        - Draw the globe and keep the axes for further decoration:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> fig, ax = globe.draw(spin=45.0)
            >>> ax.name
            '3d'
            >>> globe.ax is ax
            True

            ```
        - Draw several spins onto axes you own, to build a contact sheet:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> import matplotlib.pyplot as plt
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> fig, axes = plt.subplots(1, 3, subplot_kw={"projection": "3d"})
            >>> for spin, sub in zip([0.0, 120.0, 240.0], axes):
            ...     _ = globe.draw(ax=sub, spin=spin)
            >>> len(fig.axes)
            3

            ```
    """
    ax = self._reuse_own_axes(ax, kwargs)
    if ax is not None:
        kwargs["ax"] = ax
    supplied = not (ax is None or self._is_ours(ax)) or self._caller_supplied_axes
    _, drawn_ax = self.glyph.draw(spin=spin, **kwargs)
    self._bind(drawn_ax, owns=not supplied)
    self._spin = float(spin)
    self._turn_overlays(drawn_ax, self._spin)
    return self.fig, self.ax

from_dataset(dataset, *, band=DEFAULT_BAND, cmap='viridis', vmin=None, vmax=None, shape=DEFAULT_TEXTURE_SHAPE, resampling='nearest', **kwargs) classmethod #

Build a globe from a pyramids Dataset, draped at the raster's true lon/lat position.

pyramids does the geospatial work: the raster is aligned onto a global EPSG:4326 grid, which reprojects it and resamples it in one step, and settles the longitude frame along the way. Its band is then read with nodata masked to NaN and colour-mapped through cleopatra's colormap resolver. Cells the raster does not cover — and its nodata cells — stay fully transparent, so a regional dataset shows as a patch on the globe rather than being smeared over it.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset. Must carry a CRS.

required
band int

1-based band index to draw.

DEFAULT_BAND
cmap Any

Colormap name or Colormap, resolved by cleopatra.styling.colors.resolve_colormap.

'viridis'
vmin float | None

Lower bound of the colour scale; defaults to the band's finite minimum.

None
vmax float | None

Upper bound of the colour scale; defaults to the band's finite maximum.

None
shape tuple[int, int]

(rows, columns) of the global canvas. Larger is sharper and slower to build.

DEFAULT_TEXTURE_SHAPE
resampling str

How pyramids resamples the raster onto that grid — "nearest" (the default, which preserves categorical values), "bilinear", "cubic", "average", "mode", and the rest of Dataset.align's methods.

'nearest'
**kwargs Any

Forwarded to :class:TexturedGlobe (and on to the glyph).

{}

Returns:

Name Type Description
TexturedGlobe TexturedGlobe

a globe whose texture carries the dataset.

Raises:

Type Description
ValueError

if dataset has no resolvable CRS (there is then no way to place it on the sphere), if shape is not two positive integers, if band is out of range, or if the colour bounds are non-finite or leave no range.

Warns:

Type Description
RuntimeWarning

If nothing survives the resample onto the texture, or if what does is finer than the sphere mesh and so would not be drawn — see :meth:_warn_if_finer_than_the_mesh.

Examples:

  • Drape a whole-globe raster and inspect the texture it produced:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> arr = np.arange(8, dtype="float32").reshape(2, 4)
    >>> ds = Dataset.from_array(
    ...     arr=arr, geo_ref=GeoReference(geo=(-180.0, 90.0, 0.0, 90.0, 0.0, -90.0), epsg=4326))
    >>> globe = TexturedGlobe.from_dataset(ds, shape=(90, 180))
    >>> globe.glyph.texture.shape
    (90, 180, 4)
    >>> bool((globe.glyph.texture[..., 3] > 0).mean() > 0.98)
    True
    
  • A raster covering only part of the world leaves the rest transparent:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> arr = np.ones((2, 2), dtype="float32")
    >>> ds = Dataset.from_array(
    ...     arr=arr, geo_ref=GeoReference(geo=(0.0, 10.0, 0.0, 20.0, 0.0, -10.0), epsg=4326))
    >>> globe = TexturedGlobe.from_dataset(ds, shape=(90, 180))
    >>> opaque = globe.glyph.texture[..., 3] > 0
    >>> bool(opaque.any()), bool(opaque.all())
    (True, False)
    
Source code in src/digitalearth/static/globe/textured_globe.py
@classmethod
def from_dataset(
    cls,
    dataset: Any,
    *,
    band: int = DEFAULT_BAND,
    cmap: Any = "viridis",
    vmin: float | None = None,
    vmax: float | None = None,
    shape: tuple[int, int] = DEFAULT_TEXTURE_SHAPE,
    resampling: str = "nearest",
    **kwargs: Any,
) -> "TexturedGlobe":
    """Build a globe from a pyramids ``Dataset``, draped at the raster's true lon/lat position.

    **pyramids** does the geospatial work: the raster is aligned onto a global EPSG:4326 grid, which
    reprojects it and resamples it in one step, and settles the longitude frame along the way. Its band is
    then read with nodata masked to ``NaN`` and colour-mapped through cleopatra's colormap resolver. Cells
    the raster does not cover — and its nodata cells — stay fully transparent, so a regional dataset shows
    as a patch on the globe rather than being smeared over it.

    Args:
        dataset: A pyramids ``Dataset``. Must carry a CRS.
        band: 1-based band index to draw.
        cmap: Colormap name or ``Colormap``, resolved by ``cleopatra.styling.colors.resolve_colormap``.
        vmin: Lower bound of the colour scale; defaults to the band's finite minimum.
        vmax: Upper bound of the colour scale; defaults to the band's finite maximum.
        shape: ``(rows, columns)`` of the global canvas. Larger is sharper and slower to build.
        resampling: How pyramids resamples the raster onto that grid — ``"nearest"`` (the default, which
            preserves categorical values), ``"bilinear"``, ``"cubic"``, ``"average"``, ``"mode"``, and
            the rest of ``Dataset.align``'s methods.
        **kwargs: Forwarded to :class:`TexturedGlobe` (and on to the glyph).

    Returns:
        TexturedGlobe: a globe whose texture carries the dataset.

    Raises:
        ValueError: if ``dataset`` has no resolvable CRS (there is then no way to place it on the
            sphere), if ``shape`` is not two positive integers, if ``band`` is out of range, or if the
            colour bounds are non-finite or leave no range.

    Warns:
        RuntimeWarning: If nothing survives the resample onto the texture, or if what does is finer than
            the sphere mesh and so would not be drawn — see :meth:`_warn_if_finer_than_the_mesh`.

    Examples:
        - Drape a whole-globe raster and inspect the texture it produced:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> arr = np.arange(8, dtype="float32").reshape(2, 4)
            >>> ds = Dataset.from_array(
            ...     arr=arr, geo_ref=GeoReference(geo=(-180.0, 90.0, 0.0, 90.0, 0.0, -90.0), epsg=4326))
            >>> globe = TexturedGlobe.from_dataset(ds, shape=(90, 180))
            >>> globe.glyph.texture.shape
            (90, 180, 4)
            >>> bool((globe.glyph.texture[..., 3] > 0).mean() > 0.98)
            True

            ```
        - A raster covering only part of the world leaves the rest transparent:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> arr = np.ones((2, 2), dtype="float32")
            >>> ds = Dataset.from_array(
            ...     arr=arr, geo_ref=GeoReference(geo=(0.0, 10.0, 0.0, 20.0, 0.0, -10.0), epsg=4326))
            >>> globe = TexturedGlobe.from_dataset(ds, shape=(90, 180))
            >>> opaque = globe.glyph.texture[..., 3] > 0
            >>> bool(opaque.any()), bool(opaque.all())
            (True, False)

            ```
    """
    # pyramids owns the regrid and _global_values owns the call — including validating `shape` and the
    # CRS, so animate() inherits the same refusals. The grid comes back off the result rather than being
    # coerced again here: coercing in one place and passing the raw pair on is what silently dropped the
    # int() and broke shape=(h / 2, w / 2).
    values = cls._global_values(
        dataset, band=band, shape=shape, resampling=resampling
    )
    rows, cols = values.shape
    rgba = cls._colorize(values, cmap=cmap, vmin=vmin, vmax=vmax)
    texture = _as_byte_texture(rgba)
    if not (texture[..., 3] > 0).any():
        warnings.warn(
            f"nothing was draped onto the {rows}x{cols} globe texture, so it will render blank. Either "
            "the raster is finer than one texture cell — pass a finer shape=, e.g. shape=(2880, 5760) — "
            "or it does not overlap the globe at all, which usually means its CRS or geotransform is "
            "wrong.",
            RuntimeWarning,
            stacklevel=2,
        )
    globe = cls(texture, **kwargs)
    globe._warn_if_finer_than_the_mesh(texture)
    return globe

from_provider(provider='Esri.WorldImagery', **kwargs) classmethod #

Build a globe from a whole-world XYZ tile basemap (delegates to cleopatra's world_texture).

Parameters:

Name Type Description Default
provider Any

An xyzservices provider name or resolved TileProvider. Defaults to "Esri.WorldImagery" — a bulk-permitting imagery provider. Do not point this at OpenStreetMap's tiles: a whole-world fetch pulls thousands of tiles, which its usage policy prohibits.

'Esri.WorldImagery'
**kwargs Any

The fetch options zoom, cache, max_workers, timeout, retries and user_agent go to world_texture; texture_n_lon / texture_n_lat size the fetched texture grid. Everything else — n_lon, n_lat, tilt_deg, sun, ambient — is forwarded to the glyph, exactly as in the other constructors.

{}

Returns:

Name Type Description
TexturedGlobe TexturedGlobe

a globe textured with the provider's imagery.

Note

n_lon / n_lat always mean the sphere mesh, here as everywhere else in this class. The texture grid — which world_texture also calls n_lon / n_lat — is set with texture_n_lon / texture_n_lat, so the same keyword never means two different things.

Raises:

Type Description
ValueError

if provider is not a known xyzservices provider.

OSError

if the tiles cannot be fetched — the whole-world grid is pulled over the network on first use, so a connection failure or an unreachable provider surfaces here.

Examples:

  • Build a photographic Earth and spin it (needs the network on first use; the texture is then cached on disk):
    >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
    >>> globe = TexturedGlobe.from_provider("Esri.WorldImagery", zoom=3)   # doctest: +SKIP
    >>> globe.glyph.texture.shape                             # doctest: +SKIP
    (1440, 2880, 4)
    >>> fig, ax = globe.draw(spin=30.0, sun=(1.0, 0.3, 0.2))  # doctest: +SKIP
    
  • Size the fetched texture and the sphere mesh independently:
    >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
    >>> globe = TexturedGlobe.from_provider(                  # doctest: +SKIP
    ...     "Esri.WorldImagery", zoom=2, texture_n_lon=720, texture_n_lat=360,
    ...     n_lon=60, n_lat=30,
    ... )
    >>> globe.glyph.n_lon, globe.glyph.n_lat                  # doctest: +SKIP
    (60, 30)
    
Source code in src/digitalearth/static/globe/textured_globe.py
@classmethod
def from_provider(
    cls, provider: Any = "Esri.WorldImagery", **kwargs: Any
) -> "TexturedGlobe":
    """Build a globe from a whole-world XYZ tile basemap (delegates to ``cleopatra``'s ``world_texture``).

    Args:
        provider: An ``xyzservices`` provider name or resolved ``TileProvider``. Defaults to
            ``"Esri.WorldImagery"`` — a bulk-permitting imagery provider. Do **not** point this at
            OpenStreetMap's tiles: a whole-world fetch pulls thousands of tiles, which its usage policy
            prohibits.
        **kwargs: The fetch options ``zoom``, ``cache``, ``max_workers``, ``timeout``, ``retries`` and
            ``user_agent`` go to ``world_texture``; ``texture_n_lon`` / ``texture_n_lat`` size the
            fetched texture grid. Everything else — ``n_lon``, ``n_lat``, ``tilt_deg``, ``sun``,
            ``ambient`` — is forwarded to the glyph, exactly as in the other constructors.

    Returns:
        TexturedGlobe: a globe textured with the provider's imagery.

    Note:
        ``n_lon`` / ``n_lat`` always mean the **sphere mesh**, here as everywhere else in this class.
        The texture grid — which ``world_texture`` also calls ``n_lon`` / ``n_lat`` — is set with
        ``texture_n_lon`` / ``texture_n_lat``, so the same keyword never means two different things.

    Raises:
        ValueError: if ``provider`` is not a known ``xyzservices`` provider.
        OSError: if the tiles cannot be fetched — the whole-world grid is pulled over the network on
            first use, so a connection failure or an unreachable provider surfaces here.

    Examples:
        - Build a photographic Earth and spin it (needs the network on first use; the texture is then
          cached on disk):
            ```python
            >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
            >>> globe = TexturedGlobe.from_provider("Esri.WorldImagery", zoom=3)   # doctest: +SKIP
            >>> globe.glyph.texture.shape                             # doctest: +SKIP
            (1440, 2880, 4)
            >>> fig, ax = globe.draw(spin=30.0, sun=(1.0, 0.3, 0.2))  # doctest: +SKIP

            ```
        - Size the fetched texture and the sphere mesh independently:
            ```python
            >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
            >>> globe = TexturedGlobe.from_provider(                  # doctest: +SKIP
            ...     "Esri.WorldImagery", zoom=2, texture_n_lon=720, texture_n_lat=360,
            ...     n_lon=60, n_lat=30,
            ... )
            >>> globe.glyph.n_lon, globe.glyph.n_lat                  # doctest: +SKIP
            (60, 30)

            ```
    """
    texture_keys = (
        "zoom",
        "cache",
        "max_workers",
        "timeout",
        "retries",
        "user_agent",
    )
    texture_kwargs = {k: kwargs.pop(k) for k in texture_keys if k in kwargs}
    for shape_key, fetch_key in (
        ("texture_n_lon", "n_lon"),
        ("texture_n_lat", "n_lat"),
    ):
        if shape_key in kwargs:
            texture_kwargs[fetch_key] = kwargs.pop(shape_key)
    return cls(world_texture(provider, **texture_kwargs), **kwargs)

land(resolution='110m', *, spin=None, altitude=0.001, **kwargs) #

Fill Natural-Earth land polygons on the globe.

The counterpart of :meth:~digitalearth.static.Map.land. Each land ring is clipped to the hemisphere facing the camera and re-closed along the limb, so a continent running off the edge is filled to the horizon instead of having a chord cut across the disc. This is what turns an ocean product — SST, sea ice, chlorophyll — from a ball of colour with white holes into a readable map.

Interior rings (holes) are dropped, as they are on the 2-D globe. A ring that runs off the near side is closed along the horizon the way its own winding leads, so a landmass reaching past the horizon in several places fills each of its visible pieces and not the sea between them, however far round the horizon that takes.

Parameters:

Name Type Description Default
resolution str

Natural-Earth resolution — "110m" (default), "50m" or "10m".

'110m'
spin float | None

Pin the fill to this spin, in degrees. Omitted, it follows the globe.

None
altitude float

Radial lift above the surface. The fill sorts under the line layers by the depth it reports rather than by its radius, so this only has to clear the sphere itself.

0.001
**kwargs Any

Patch styling forwarded to matplotlib (color, alpha, edgecolor, ...), in any spelling it accepts (fc, ec, lw). As for :meth:coastlines, zorder is accepted but the axes' depth sort decides the order.

{}

Returns:

Type Description
Any

The PolyCollection holding the fill. It stays on the axes as the globe turns, re-clipped and

Any

re-projected at each draw; at a camera that shows no land it simply has no faces, and the faces

Any

are worked out when the figure is drawn, so get_paths() is empty until then.

Raises:

Type Description
RuntimeError

if the globe has not been drawn yet.

Examples:

  • The fill arrives as one collection holding every visible land ring. The vectors are fetched (and cached) by cleopatra, so this needs a network on first use:
    >>> import matplotlib                                      # doctest: +SKIP
    >>> matplotlib.use("Agg")                                  # doctest: +SKIP
    >>> import numpy as np                                     # doctest: +SKIP
    >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
    >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
    >>> patch = globe.land()                                   # doctest: +SKIP
    >>> patch in globe.ax.collections                          # doctest: +SKIP
    True
    
  • Colour it like any patch — a translucent fill still lets the texture read through:
    >>> import matplotlib                                      # doctest: +SKIP
    >>> matplotlib.use("Agg")                                  # doctest: +SKIP
    >>> import numpy as np                                     # doctest: +SKIP
    >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
    >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
    >>> patch = globe.land(color="0.4", alpha=0.5)             # doctest: +SKIP
    >>> round(float(patch.get_facecolor()[0][3]), 2)           # doctest: +SKIP
    0.5
    
  • Asking before the globe is drawn is refused — there is no camera yet to clip against:
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8)).land()
    Traceback (most recent call last):
        ...
    RuntimeError: draw() the globe before adding the 'land' layer to it
    
Source code in src/digitalearth/static/globe/textured_globe.py
def land(
    self,
    resolution: str = "110m",
    *,
    spin: float | None = None,
    altitude: float = 0.001,
    **kwargs: Any,
) -> Any:
    """Fill Natural-Earth land polygons on the globe.

    The counterpart of :meth:`~digitalearth.static.Map.land`. Each land ring is clipped to the
    hemisphere facing the camera and re-closed along the limb, so a continent running off the edge is
    filled to the horizon instead of having a chord cut across the disc. This is what turns an ocean
    product — SST, sea ice, chlorophyll — from a ball of colour with white holes into a readable map.

    Interior rings (holes) are dropped, as they are on the 2-D globe. A ring that runs off the near
    side is closed along the horizon the way its own winding leads, so a landmass reaching past the
    horizon in several places fills each of its visible pieces and not the sea between them, however
    far round the horizon that takes.

    Args:
        resolution: Natural-Earth resolution — ``"110m"`` (default), ``"50m"`` or ``"10m"``.
        spin: Pin the fill to this spin, in degrees. Omitted, it follows the globe.
        altitude: Radial lift above the surface. The fill sorts under the line layers by the depth
            it reports rather than by its radius, so this only has to clear the sphere itself.
        **kwargs: Patch styling forwarded to matplotlib (``color``, ``alpha``, ``edgecolor``, ...),
            in any spelling it accepts (``fc``, ``ec``, ``lw``). As for :meth:`coastlines`, ``zorder``
            is accepted but the axes' depth sort decides the order.

    Returns:
        The ``PolyCollection`` holding the fill. It stays on the axes as the globe turns, re-clipped and
        re-projected at each draw; at a camera that shows no land it simply has no faces, and the faces
        are worked out when the figure is drawn, so ``get_paths()`` is empty until then.

    Raises:
        RuntimeError: if the globe has not been drawn yet.

    Examples:
        - The fill arrives as one collection holding every visible land ring. The vectors are fetched
          (and cached) by ``cleopatra``, so this needs a network on first use:
            ```python
            >>> import matplotlib                                      # doctest: +SKIP
            >>> matplotlib.use("Agg")                                  # doctest: +SKIP
            >>> import numpy as np                                     # doctest: +SKIP
            >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
            >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
            >>> patch = globe.land()                                   # doctest: +SKIP
            >>> patch in globe.ax.collections                          # doctest: +SKIP
            True

            ```
        - Colour it like any patch — a translucent fill still lets the texture read through:
            ```python
            >>> import matplotlib                                      # doctest: +SKIP
            >>> matplotlib.use("Agg")                                  # doctest: +SKIP
            >>> import numpy as np                                     # doctest: +SKIP
            >>> from digitalearth.static import TexturedGlobe          # doctest: +SKIP
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), np.uint8))  # doctest: +SKIP
            >>> _ = globe.draw(elev=0.0, azim=0.0)                     # doctest: +SKIP
            >>> patch = globe.land(color="0.4", alpha=0.5)             # doctest: +SKIP
            >>> round(float(patch.get_facecolor()[0][3]), 2)           # doctest: +SKIP
            0.5

            ```
        - Asking before the globe is drawn is refused — there is no camera yet to clip against:
            ```python
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8)).land()
            Traceback (most recent call last):
                ...
            RuntimeError: draw() the globe before adding the 'land' layer to it

            ```
    """
    return self._reference_layer(
        "land",
        resolution,
        {"color": "#efefdb", "edgecolor": "none"},
        spin=spin,
        altitude=altitude,
        fill=True,
        **kwargs,
    )

points(data, *, lat=None, spin=None, altitude=0.01, hide_far_side=True, **kwargs) #

Scatter lon/lat points onto the globe's surface.

Accepts either a pyramids FeatureCollection / geopandas GeoDataFrame of points (its geometry is reprojected to lon/lat when needed) or a pair of lon/lat array-likes.

Parameters:

Name Type Description Default
data Any

A point FeatureCollection/GeoDataFrame, or the longitudes when lat is given.

required
lat Any

Latitudes, when data holds longitudes.

None
spin float | None

Pin the points to this spin, in degrees. Omitted (the default), they follow the globe: they are drawn at the spin it was last drawn at, and redrawn at each animation frame's spin so they turn with the surface. Giving a value opts out of that and fixes them there.

None
altitude float

Radial lift above the surface, to avoid z-fighting with it.

0.01
hide_far_side bool

When True (default), hide the markers on the hemisphere facing away from the camera, which matplotlib would otherwise draw straight through the sphere. Decided at each draw, against the camera as it is then, so a camera move re-decides it. With False every marker is drawn and the collection is depth-sorted like any other artist, so markers near the limb can be painted over by the sphere.

True
**kwargs Any

Forwarded to Axes3D.scatter (e.g. c, s, marker, color).

{}

Returns:

Type Description
Any

The scatter collection on the axes. It stays there as the globe turns — re-placed at each draw,

Any

never replaced — so restyling it, removing it, or keying a colorbar to it keeps working.

Any

It holds every point, which is a change: a hidden marker is drawn at size zero rather than

Any

left out of the collection. That is what keeps each per-point value with its own point and fits

Any

the colour scale to all of them, and it means len(scatter.get_offsets()) counts the points

Any

given rather than the ones on show — ask :meth:visible which of those face the camera.

Raises:

Type Description
RuntimeError

if the globe has not been drawn yet.

ValueError

if data is neither a feature collection nor a pair of lon/lat arrays, or is a feature collection carrying no CRS.

Note

Non-point geometry (polygons, lines) is reduced to its centroids rather than rejected, so a polygon layer can be marked on the globe without converting it first.

Examples:

  • Scatter lon/lat points; the ones behind the globe are drawn at size zero:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
    ...                       n_lon=8, n_lat=4)
    >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
    >>> scatter = globe.points([0.0, 180.0], lat=[0.0, 0.0])
    >>> len(scatter.get_offsets())
    2
    >>> globe.visible(globe.project([0.0, 180.0], [0.0, 0.0])).tolist()
    [True, False]
    
  • Keep the far side when you want the full set drawn:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
    ...                       n_lon=8, n_lat=4)
    >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
    >>> scatter = globe.points([0.0, 180.0], lat=[0.0, 0.0], hide_far_side=False)
    >>> fig.canvas.draw()
    >>> len(scatter.get_offsets())
    2
    
  • Points follow the globe unless pinned; turning it half-way takes the follower out of sight:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
    ...                       n_lon=8, n_lat=4)
    >>> ax = plt.figure().add_subplot(projection="3d")
    >>> _ = globe.draw(ax, elev=0.0, azim=0.0)
    >>> follower = globe.points([0.0], lat=[0.0])
    >>> pinned = globe.points([0.0], lat=[0.0], spin=0.0)
    >>> _ = globe.draw(ax, elev=0.0, azim=0.0, spin=180.0)
    >>> bool(globe.visible(globe.project([0.0], [0.0]))[0])
    False
    >>> bool(globe.visible(globe.project([0.0], [0.0], spin=0.0))[0])
    True
    >>> follower in ax.collections
    True
    
Source code in src/digitalearth/static/globe/textured_globe.py
def points(
    self,
    data: Any,
    *,
    lat: Any = None,
    spin: float | None = None,
    altitude: float = 0.01,
    hide_far_side: bool = True,
    **kwargs: Any,
) -> Any:
    """Scatter lon/lat points onto the globe's surface.

    Accepts either a pyramids ``FeatureCollection`` / geopandas ``GeoDataFrame`` of points (its geometry
    is reprojected to lon/lat when needed) or a pair of ``lon``/``lat`` array-likes.

    Args:
        data: A point ``FeatureCollection``/``GeoDataFrame``, or the longitudes when ``lat`` is given.
        lat: Latitudes, when ``data`` holds longitudes.
        spin: Pin the points to this spin, in degrees. Omitted (the default), they follow the globe:
            they are drawn at the spin it was last drawn at, and redrawn at each animation frame's
            spin so they turn with the surface. Giving a value opts out of that and fixes them there.
        altitude: Radial lift above the surface, to avoid z-fighting with it.
        hide_far_side: When True (default), hide the markers on the hemisphere facing away from the
            camera, which matplotlib would otherwise draw straight through the sphere. Decided at each
            draw, against the camera as it is then, so a camera move re-decides it. With False every
            marker is drawn and the collection is depth-sorted like any other artist, so markers near
            the limb can be painted over by the sphere.
        **kwargs: Forwarded to ``Axes3D.scatter`` (e.g. ``c``, ``s``, ``marker``, ``color``).

    Returns:
        The scatter collection on the axes. It stays there as the globe turns — re-placed at each draw,
        never replaced — so restyling it, removing it, or keying a colorbar to it keeps working.

        It holds **every** point, which is a change: a hidden marker is drawn at size zero rather than
        left out of the collection. That is what keeps each per-point value with its own point and fits
        the colour scale to all of them, and it means ``len(scatter.get_offsets())`` counts the points
        given rather than the ones on show — ask :meth:`visible` which of those face the camera.

    Raises:
        RuntimeError: if the globe has not been drawn yet.
        ValueError: if ``data`` is neither a feature collection nor a pair of lon/lat arrays, or is a
            feature collection carrying no CRS.

    Note:
        Non-point geometry (polygons, lines) is reduced to its centroids rather than rejected, so a
        polygon layer can be marked on the globe without converting it first.

    Examples:
        - Scatter lon/lat points; the ones behind the globe are drawn at size zero:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
            ...                       n_lon=8, n_lat=4)
            >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
            >>> scatter = globe.points([0.0, 180.0], lat=[0.0, 0.0])
            >>> len(scatter.get_offsets())
            2
            >>> globe.visible(globe.project([0.0, 180.0], [0.0, 0.0])).tolist()
            [True, False]

            ```
        - Keep the far side when you want the full set drawn:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
            ...                       n_lon=8, n_lat=4)
            >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
            >>> scatter = globe.points([0.0, 180.0], lat=[0.0, 0.0], hide_far_side=False)
            >>> fig.canvas.draw()
            >>> len(scatter.get_offsets())
            2

            ```
        - Points follow the globe unless pinned; turning it half-way takes the follower out of sight:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import matplotlib.pyplot as plt
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
            ...                       n_lon=8, n_lat=4)
            >>> ax = plt.figure().add_subplot(projection="3d")
            >>> _ = globe.draw(ax, elev=0.0, azim=0.0)
            >>> follower = globe.points([0.0], lat=[0.0])
            >>> pinned = globe.points([0.0], lat=[0.0], spin=0.0)
            >>> _ = globe.draw(ax, elev=0.0, azim=0.0, spin=180.0)
            >>> bool(globe.visible(globe.project([0.0], [0.0]))[0])
            False
            >>> bool(globe.visible(globe.project([0.0], [0.0], spin=0.0))[0])
            True
            >>> follower in ax.collections
            True

            ```
    """
    if self.ax is None:
        raise RuntimeError("draw() the globe before adding points to it")
    lon_vals, lat_vals = self._as_lonlat(data, lat)
    body = self._to_body(lon_vals, lat_vals, altitude)
    at = self._spin if spin is None else float(spin)
    world = np.atleast_2d(self.glyph.transform(body, spin=at))
    scatter = self.ax.scatter(world[:, 0], world[:, 1], world[:, 2], **kwargs)
    scatter.__class__ = _SpherePoints
    scatter._adopt_points(self._placer.transform, body, at, cull=hide_far_side)
    if spin is None:
        self._overlays.append(scatter)
    return scatter

project(lon, lat, *, spin=None, altitude=0.0) #

Map lon/lat degrees onto the drawn sphere, returning world-space (N, 3) coordinates.

Pushes the points through the glyph's own transform, so they carry the same spin and axial tilt as the rendered surface — the reason this is exact rather than an approximation.

Parameters:

Name Type Description Default
lon Any

Longitude(s) in degrees (scalar or array-like).

required
lat Any

Latitude(s) in degrees, same shape as lon.

required
spin float | None

The spin, in degrees, to place the points at. Defaults to the spin the globe was last drawn at, so an overlay lands on the surface the reader can actually see.

None
altitude float

Radial offset from the unit surface. A small positive value (e.g. 0.01) lifts an overlay clear of the surface so matplotlib does not z-fight it.

0.0

Returns:

Type Description
ndarray

np.ndarray: an (N, 3) array of world-space coordinates.

Raises:

Type Description
ValueError

if lon and lat do not have the same shape.

Examples:

  • With no tilt the body frame is the world frame, so the cardinal points are exact:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
    ...                       n_lon=8, n_lat=4)
    >>> np.round(globe.project(0.0, 0.0), 6)
    array([[1., 0., 0.]])
    >>> np.round(globe.project(90.0, 0.0), 6)
    array([[0., 1., 0.]])
    >>> np.round(globe.project(0.0, 90.0), 6)
    array([[0., 0., 1.]])
    
  • Points land on the unit sphere; altitude lifts an overlay clear of the surface:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> world = globe.project([0.0, 45.0], [10.0, -20.0], spin=30.0)
    >>> world.shape
    (2, 3)
    >>> [round(float(r), 6) for r in np.linalg.norm(world, axis=1)]
    [1.0, 1.0]
    >>> round(float(np.linalg.norm(globe.project(0.0, 0.0, altitude=0.05))), 6)
    1.05
    
Source code in src/digitalearth/static/globe/textured_globe.py
def project(
    self, lon: Any, lat: Any, *, spin: float | None = None, altitude: float = 0.0
) -> np.ndarray:
    """Map lon/lat degrees onto the drawn sphere, returning world-space ``(N, 3)`` coordinates.

    Pushes the points through the glyph's own ``transform``, so they carry the same spin **and axial
    tilt** as the rendered surface — the reason this is exact rather than an approximation.

    Args:
        lon: Longitude(s) in degrees (scalar or array-like).
        lat: Latitude(s) in degrees, same shape as ``lon``.
        spin: The spin, in degrees, to place the points at. Defaults to the spin the globe was last
            drawn at, so an overlay lands on the surface the reader can actually see.
        altitude: Radial offset from the unit surface. A small positive value (e.g. ``0.01``) lifts an
            overlay clear of the surface so matplotlib does not z-fight it.

    Returns:
        np.ndarray: an ``(N, 3)`` array of world-space coordinates.

    Raises:
        ValueError: if ``lon`` and ``lat`` do not have the same shape.

    Examples:
        - With no tilt the body frame is the world frame, so the cardinal points are exact:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
            ...                       n_lon=8, n_lat=4)
            >>> np.round(globe.project(0.0, 0.0), 6)
            array([[1., 0., 0.]])
            >>> np.round(globe.project(90.0, 0.0), 6)
            array([[0., 1., 0.]])
            >>> np.round(globe.project(0.0, 90.0), 6)
            array([[0., 0., 1.]])

            ```
        - Points land on the unit sphere; ``altitude`` lifts an overlay clear of the surface:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> world = globe.project([0.0, 45.0], [10.0, -20.0], spin=30.0)
            >>> world.shape
            (2, 3)
            >>> [round(float(r), 6) for r in np.linalg.norm(world, axis=1)]
            [1.0, 1.0]
            >>> round(float(np.linalg.norm(globe.project(0.0, 0.0, altitude=0.05))), 6)
            1.05

            ```
    """
    spin = self._spin if spin is None else spin
    body = self._to_body(lon, lat, altitude)
    return np.atleast_2d(self.glyph.transform(body, spin=spin))

save(path, **kwargs) #

Save the drawn figure to path.

Parameters:

Name Type Description Default
path str | PathLike[str]

Destination file path.

required
**kwargs Any

Forwarded to Figure.savefig.

{}

Returns:

Type Description
Path

The path that was written, as a :class:pathlib.Path — the same contract as every other

Path

backend's save.

Raises:

Type Description
RuntimeError

if the globe has not been drawn yet.

Examples:

  • Draw, then write the figure to disk:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> import tempfile
    >>> from pathlib import Path
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> fig, ax = globe.draw()
    >>> out = Path(tempfile.mkdtemp()) / "globe.png"
    >>> written = globe.save(str(out))
    >>> written == out
    True
    >>> out.exists() and out.stat().st_size > 0
    True
    
  • Saving before drawing is refused, rather than writing an empty figure:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> globe.save("globe.png")
    Traceback (most recent call last):
        ...
    RuntimeError: draw() the globe before saving it
    
Source code in src/digitalearth/static/globe/textured_globe.py
def save(self, path: str | os.PathLike[str], **kwargs: Any) -> Path:
    """Save the drawn figure to ``path``.

    Args:
        path: Destination file path.
        **kwargs: Forwarded to ``Figure.savefig``.

    Returns:
        The path that was written, as a :class:`pathlib.Path` — the same contract as every other
        backend's ``save``.

    Raises:
        RuntimeError: if the globe has not been drawn yet.

    Examples:
        - Draw, then write the figure to disk:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> import tempfile
            >>> from pathlib import Path
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> fig, ax = globe.draw()
            >>> out = Path(tempfile.mkdtemp()) / "globe.png"
            >>> written = globe.save(str(out))
            >>> written == out
            True
            >>> out.exists() and out.stat().st_size > 0
            True

            ```
        - Saving before drawing is refused, rather than writing an empty figure:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> globe.save("globe.png")
            Traceback (most recent call last):
                ...
            RuntimeError: draw() the globe before saving it

            ```
    """
    if self.fig is None:
        raise RuntimeError("draw() the globe before saving it")
    self.fig.savefig(path, **kwargs)
    return Path(path)

save_animation(path, *, fps=None, gif=None, **kwargs) #

Save the animation built by :meth:spin or :meth:animate, optionally also deriving a GIF.

A textured globe is exactly the case the derive-a-GIF path exists for: every frame is a full 3-D surface redraw, so encoding twice off one render is far cheaper than rendering twice.

Parameters:

Name Type Description Default
path str

Output path; the extension picks the format.

required
fps float | None

Frames per second. Defaults to the animation's own interval.

None
gif str | None

Optional second path to derive a GIF at. Requires path to be a video.

None
**kwargs Any

Forwarded to :func:digitalearth.static.render.animation.save_animation.

{}

Returns:

Type Description
Any

The written path, or a (video, gif) pair when gif was requested.

Raises:

Type Description
RuntimeError

if no animation has been built yet — call :meth:spin or :meth:animate first.

Examples:

  • Animate, then write the rotation straight to a GIF:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> import tempfile
    >>> from pathlib import Path
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> anim = globe.spin(n_frames=2, interval=200)
    >>> out = Path(tempfile.mkdtemp()) / "globe.gif"
    >>> written = globe.save_animation(str(out))
    >>> Path(written).exists()
    True
    
  • Render once and deliver both a video and a GIF derived from it:
    >>> video, gif = globe.save_animation("globe.mp4", gif="globe.gif")  # doctest: +SKIP
    
Source code in src/digitalearth/static/globe/textured_globe.py
def save_animation(
    self,
    path: str,
    *,
    fps: float | None = None,
    gif: str | None = None,
    **kwargs: Any,
) -> Any:
    """Save the animation built by :meth:`spin` or :meth:`animate`, optionally also deriving a GIF.

    A textured globe is exactly the case the derive-a-GIF path exists for: every frame is a full 3-D
    surface redraw, so encoding twice off one render is far cheaper than rendering twice.

    Args:
        path: Output path; the extension picks the format.
        fps: Frames per second. Defaults to the animation's own interval.
        gif: Optional second path to derive a GIF at. Requires ``path`` to be a video.
        **kwargs: Forwarded to :func:`digitalearth.static.render.animation.save_animation`.

    Returns:
        The written path, or a ``(video, gif)`` pair when ``gif`` was requested.

    Raises:
        RuntimeError: if no animation has been built yet — call :meth:`spin` or :meth:`animate` first.

    Examples:
        - Animate, then write the rotation straight to a GIF:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> import tempfile
            >>> from pathlib import Path
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> anim = globe.spin(n_frames=2, interval=200)
            >>> out = Path(tempfile.mkdtemp()) / "globe.gif"
            >>> written = globe.save_animation(str(out))
            >>> Path(written).exists()
            True

            ```
        - Render once and deliver both a video and a GIF derived from it:
            ```python
            >>> video, gif = globe.save_animation("globe.mp4", gif="globe.gif")  # doctest: +SKIP

            ```
    """
    if self._animation is None:
        raise RuntimeError("no animation to save; call spin() or animate() first")
    anim = self._animation
    rate = fps if fps is not None else self._animation_fps
    return save_animation(anim, path, fps=rate, gif=gif, **kwargs)

spin(ax=None, **kwargs) #

Animate a full rotation of the camera, returning a matplotlib FuncAnimation.

This turns the viewpoint around one fixed texture. To step a series of rasters instead, holding the camera still, use :meth:animate — the two are deliberately separate, because spinning while stepping time conflates them and a viewer cannot tell whether a change on screen is the data or the vantage point.

When no ax is given the 3-D axes is created here rather than inside the glyph, so :attr:fig and :attr:ax are known without reaching into the animation's internals — which is what lets :meth:save_animation and :meth:stamp work on an animated globe.

Overlays turn with the sphere. Anything added with :meth:points, :meth:coastlines, :meth:borders or :meth:land is turned to each frame's spin, so markers and coastlines stay attached to the ground; pass spin= to one of those to pin it in place instead. Called without an ax, this animates on the axes the globe already owns, so a globe that was drawn and decorated keeps its overlays.

The rotation is swept here rather than by the glyph's own animate, which is how each frame's spin is known; it sweeps the same one, start_spin plus revolutions whole turns spread over n_frames frames. The first frame is drawn by this call, so a bad render option is refused here rather than from inside the frame loop — at the cost of one render, about half a second on the default mesh, before the animation comes back.

Parameters:

Name Type Description Default
ax Any

An existing Axes3D to animate on. When omitted, the constructor's axes is used if one was given, and only otherwise is a new figure created.

None
**kwargs Any

n_frames, revolutions, start_spin and interval shape the rotation and are read here; the rest (sun, ambient, and the render options) goes to the glyph's draw on every frame. figsize sizes the figure created here, or resizes the one the globe already owns, and is ignored when ax is given.

{}

Returns:

Type Description
FuncAnimation

The FuncAnimation over the rotation. It is also kept on self._animation so it is not

FuncAnimation

garbage-collected before you save or display it.

Raises:

Type Description
ValueError

If interval is not a positive number of milliseconds, n_frames is below 1, or a render option or lighting argument is out of contract.

Examples:

  • Animate a rotation; the figure and axes are recorded for saving or stamping afterwards:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> anim = globe.spin(n_frames=4, interval=100)
    >>> globe.ax.name
    '3d'
    >>> globe.fig is globe.ax.get_figure()
    True
    
  • Animate onto an axes you already own:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> import matplotlib.pyplot as plt
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> ax = plt.figure().add_subplot(projection="3d")
    >>> anim = globe.spin(ax, n_frames=2, interval=200)
    >>> globe.ax is ax
    True
    
Source code in src/digitalearth/static/globe/textured_globe.py
def spin(self, ax: Any = None, **kwargs: Any) -> FuncAnimation:
    """Animate a full rotation of the camera, returning a matplotlib ``FuncAnimation``.

    This turns the **viewpoint** around one fixed texture. To step a **series of rasters** instead,
    holding the camera still, use :meth:`animate` — the two are deliberately separate, because
    spinning while stepping time conflates them and a viewer cannot tell whether a change on screen
    is the data or the vantage point.

    When no ``ax`` is given the 3-D axes is created here rather than inside the glyph, so :attr:`fig` and
    :attr:`ax` are known without reaching into the animation's internals — which is what lets
    :meth:`save_animation` and :meth:`stamp` work on an animated globe.

    Overlays turn with the sphere. Anything added with :meth:`points`, :meth:`coastlines`,
    :meth:`borders` or :meth:`land` is turned to each frame's spin, so markers and coastlines stay
    attached to the ground; pass ``spin=`` to one of those to pin it in place instead. Called without
    an ``ax``, this animates on the axes the globe already owns, so a globe that was drawn and
    decorated keeps its overlays.

    The rotation is swept here rather than by the glyph's own ``animate``, which is how each frame's
    spin is known; it sweeps the same one, ``start_spin`` plus ``revolutions`` whole turns spread over
    ``n_frames`` frames. The first frame is drawn by this call, so a bad render option is refused here
    rather than from inside the frame loop — at the cost of one render, about half a second on the
    default mesh, before the animation comes back.

    Args:
        ax: An existing ``Axes3D`` to animate on. When omitted, the constructor's axes is used if one
            was given, and only otherwise is a new figure created.
        **kwargs: ``n_frames``, ``revolutions``, ``start_spin`` and ``interval`` shape the rotation and
            are read here; the rest (``sun``, ``ambient``, and the render options) goes to the glyph's
            ``draw`` on every frame. ``figsize`` sizes the figure created here, or resizes the one the
            globe already owns, and is ignored when ``ax`` is given.

    Returns:
        The ``FuncAnimation`` over the rotation. It is also kept on ``self._animation`` so it is not
        garbage-collected before you save or display it.

    Raises:
        ValueError: If ``interval`` is not a positive number of milliseconds, ``n_frames`` is below 1,
            or a render option or lighting argument is out of contract.

    Examples:
        - Animate a rotation; the figure and axes are recorded for saving or stamping afterwards:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> anim = globe.spin(n_frames=4, interval=100)
            >>> globe.ax.name
            '3d'
            >>> globe.fig is globe.ax.get_figure()
            True

            ```
        - Animate onto an axes you already own:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> import matplotlib.pyplot as plt
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> ax = plt.figure().add_subplot(projection="3d")
            >>> anim = globe.spin(ax, n_frames=2, interval=200)
            >>> globe.ax is ax
            True

            ```
    """
    interval = float(kwargs.pop("interval", _DEFAULT_INTERVAL_MS))
    if interval <= 0:
        raise ValueError(
            f"interval must be a positive number of milliseconds, got {interval!r}"
        )
    n_frames = int(kwargs.pop("n_frames", _DEFAULT_N_FRAMES))
    if n_frames < 1:
        raise ValueError(f"n_frames must be at least 1, got {n_frames}")
    spins = float(kwargs.pop("start_spin", 0.0)) + np.linspace(
        0.0,
        360.0 * float(kwargs.pop("revolutions", _DEFAULT_REVOLUTIONS)),
        n_frames,
        endpoint=False,
    )
    supplied = not (ax is None or self._is_ours(ax)) or self._caller_supplied_axes
    if ax is None:
        ax = (
            self._ctor_ax
        )  # a globe built around the caller's axes keeps animating there
    ax = self._reuse_own_axes(ax, kwargs)
    if ax is None:
        figsize = kwargs.pop(
            "figsize", self.glyph.default_options.get("figsize", (6, 6))
        )
        ax = plt.figure(figsize=figsize).add_subplot(projection="3d")
    # The rotation is swept here rather than by the glyph's own animate, so each frame's spin is known
    # without reaching into the glyph. The first frame is drawn now: a bad render option or lighting
    # argument is refused at this call, as the glyph's animate would, and not from inside the frame loop.
    self.glyph.draw(ax, spin=float(spins[0]), **kwargs)
    self._bind(ax, owns=not supplied)
    self._spin = float(spins[0])
    self._turn_overlays(ax, self._spin)

    def _frame(index: int) -> tuple[Any, ...]:
        spin = float(spins[index])
        self.glyph.draw(ax, spin=spin, **kwargs)
        self._spin = spin
        self._turn_overlays(ax, spin)
        return (self.glyph.surface,)

    anim = FuncAnimation(
        _root_figure(ax), _frame, frames=n_frames, interval=interval, blit=False
    )
    self._animation = (
        anim  # keep a strong reference so it survives until save/display
    )
    self._animation_fps = 1000.0 / interval
    return anim

stamp(mark, **kwargs) #

Stamp a logo / watermark onto the globe's figure.

The same figure-level mark as :meth:digitalearth.static.core.scene.Scene.stamp, and it carries the same two caveats: stamp last, because the mark is baked from the figure's current size, and note that a bbox_inches="tight" save crops surrounding whitespace and so shifts the mark's margin.

Parameters:

Name Type Description Default
mark Any

The mark image — a file path or an (H, W, 3) / (H, W, 4) array.

required
**kwargs Any

Forwarded to cleopatra's WatermarkMixin.stamp_mark.

{}

Returns:

Type Description
Any

The frameless inset Axes the mark was drawn on.

Raises:

Type Description
RuntimeError

if the globe has not been drawn yet.

Examples:

  • Stamp a mark onto the drawn globe; it arrives as an extra axes on the figure:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> fig, ax = globe.draw()
    >>> mark = np.full((8, 16, 4), 255, dtype=np.uint8)
    >>> mark_ax = globe.stamp(mark, frac=0.2, shadow=False)
    >>> len(fig.axes)
    2
    >>> round(float(mark_ax.get_position().bounds[2]), 3)
    0.2
    
  • Stamping before drawing is refused:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
    >>> globe.stamp(np.full((8, 16, 4), 255, dtype=np.uint8))
    Traceback (most recent call last):
        ...
    RuntimeError: draw() the globe before stamping it
    
Source code in src/digitalearth/static/globe/textured_globe.py
def stamp(self, mark: Any, **kwargs: Any) -> Any:
    """Stamp a logo / watermark onto the globe's figure.

    The same figure-level mark as :meth:`digitalearth.static.core.scene.Scene.stamp`, and it carries the same
    two caveats: stamp **last**, because the mark is baked from the figure's current size, and note that
    a ``bbox_inches="tight"`` save crops surrounding whitespace and so shifts the mark's margin.

    Args:
        mark: The mark image — a file path or an ``(H, W, 3)`` / ``(H, W, 4)`` array.
        **kwargs: Forwarded to cleopatra's ``WatermarkMixin.stamp_mark``.

    Returns:
        The frameless inset ``Axes`` the mark was drawn on.

    Raises:
        RuntimeError: if the globe has not been drawn yet.

    Examples:
        - Stamp a mark onto the drawn globe; it arrives as an extra axes on the figure:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> fig, ax = globe.draw()
            >>> mark = np.full((8, 16, 4), 255, dtype=np.uint8)
            >>> mark_ax = globe.stamp(mark, frac=0.2, shadow=False)
            >>> len(fig.axes)
            2
            >>> round(float(mark_ax.get_position().bounds[2]), 3)
            0.2

            ```
        - Stamping before drawing is refused:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), n_lon=8, n_lat=4)
            >>> globe.stamp(np.full((8, 16, 4), 255, dtype=np.uint8))
            Traceback (most recent call last):
                ...
            RuntimeError: draw() the globe before stamping it

            ```
    """
    if self.fig is None:
        raise RuntimeError("draw() the globe before stamping it")
    return self.stamp_mark(mark, **kwargs)

visible(world_xyz) #

Boolean mask of which world-space points face the camera (i.e. are on the near side).

A point on a unit sphere is its own outward normal, so it is visible exactly when it points toward the camera. Uses the axes' current elev/azim, so call it after :meth:draw.

A point sitting exactly on the limb is a tie, and floating point decides it: at lon=90 with the camera at azim=0, cos(90°) evaluates to 6.1e-17 rather than 0, so the point reads as (barely) visible. Do not rely on the classification of points within rounding distance of the limb.

Parameters:

Name Type Description Default
world_xyz ndarray

An (N, 3) array of world-space points, as returned by :meth:project.

required

Returns:

Type Description
ndarray

np.ndarray: an (N,) boolean mask, True for the near-side points.

Raises:

Type Description
RuntimeError

if the globe has not been drawn yet (there is no camera to test against).

Examples:

  • The hemisphere facing the camera is visible; the one behind it is not:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
    ...                       n_lon=8, n_lat=4)
    >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
    >>> globe.visible(globe.project(0.0, 0.0)).tolist()
    [True]
    >>> globe.visible(globe.project(180.0, 0.0)).tolist()
    [False]
    
  • Use it to label only the points a reader can actually see:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> from digitalearth.static import TexturedGlobe
    >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
    ...                       n_lon=8, n_lat=4)
    >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
    >>> lon, lat = [0.0, 45.0, 180.0, 225.0], [0.0, 0.0, 0.0, 0.0]
    >>> int(globe.visible(globe.project(lon, lat)).sum())
    2
    
Source code in src/digitalearth/static/globe/textured_globe.py
def visible(self, world_xyz: np.ndarray) -> np.ndarray:
    """Boolean mask of which world-space points face the camera (i.e. are on the near side).

    A point on a unit sphere is its own outward normal, so it is visible exactly when it points toward
    the camera. Uses the axes' current ``elev``/``azim``, so call it after :meth:`draw`.

    A point sitting exactly on the limb is a tie, and floating point decides it: at ``lon=90`` with the
    camera at ``azim=0``, ``cos(90°)`` evaluates to ``6.1e-17`` rather than ``0``, so the point reads as
    (barely) visible. Do not rely on the classification of points within rounding distance of the limb.

    Args:
        world_xyz: An ``(N, 3)`` array of world-space points, as returned by :meth:`project`.

    Returns:
        np.ndarray: an ``(N,)`` boolean mask, ``True`` for the near-side points.

    Raises:
        RuntimeError: if the globe has not been drawn yet (there is no camera to test against).

    Examples:
        - The hemisphere facing the camera is visible; the one behind it is not:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
            ...                       n_lon=8, n_lat=4)
            >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
            >>> globe.visible(globe.project(0.0, 0.0)).tolist()
            [True]
            >>> globe.visible(globe.project(180.0, 0.0)).tolist()
            [False]

            ```
        - Use it to label only the points a reader can actually see:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> from digitalearth.static import TexturedGlobe
            >>> globe = TexturedGlobe(np.zeros((8, 16, 3), dtype=np.uint8), tilt_deg=0.0,
            ...                       n_lon=8, n_lat=4)
            >>> fig, ax = globe.draw(elev=0.0, azim=0.0)
            >>> lon, lat = [0.0, 45.0, 180.0, 225.0], [0.0, 0.0, 0.0, 0.0]
            >>> int(globe.visible(globe.project(lon, lat)).sum())
            2

            ```
    """
    if self.ax is None:
        raise RuntimeError(
            "draw() the globe before asking which points are visible"
        )
    view = _view_vector(self.ax.elev, self.ax.azim)
    points = np.atleast_2d(np.asarray(world_xyz, dtype=float))
    return np.asarray(points @ view > 0.0, dtype=bool).ravel()