Population and thematic rasters

RasterHeightSurfaceStyle, CategoricalRasterStyle and BivariateRasterStyle are exported from forge3d and forge3d.style. They use the existing native GIS normalization/classification API. Their apply() results include a true-valid mask, display-sRGB RGBA8 cells and legend data. Population results also contain float32 heights; thematic results contain class indices (0 means nodata).

import numpy as np
import forge3d as f3d

population = np.array([[0, 10, 20], [20, 10, 0]], dtype=np.float32)
height_style = f3d.RasterHeightSurfaceStyle(
    height_scale=2, source_units="people/km²", height_units="m", nodata=-9999,
)
terrain = f3d.TerrainSource(
    data=population, style=height_style, crs="EPSG:3857",
    metadata={"source_id": "local-population"},
)
scene = f3d.MapScene(
    terrain=terrain, lighting=f3d.LightingPreset(name="daylight"),
    output=f3d.OutputSpec(width=192, height=192),
)
scene.render("population.png")

Height is source value × height_scale. The scale is in declared height units per source unit; use metres for metric terrain coordinates. Values must be nonnegative outside nodata, and the output must fit finite float32. Units are labels carried into parameters and legends, never inferred or converted. Shade interpolates the low/high colors with gis.normalize_raster minmax values; a constant raster uses the low color. NaN/nonfinite source cells, declared nodata, and false valid_mask cells are excluded. An all-invalid input diagnoses empty_raster. Invalid scales/domains diagnose invalid_argument.

For land cover, supply a CategoricalRasterStyle(palette={class_id: rgba}, labels={class_id: label}, nodata=...) to RasterOverlay(style=..., data=...). Class IDs must be integers and every valid source ID must appear in the palette. Zero is a valid source ID unless explicitly declared nodata. RGBA colors are four integer bytes; class legend rows retain original IDs in ascending order. Native classifier output indices are numbered from 1; 0 is reserved for nodata.

For the starting bivariate slice, supply two increasing finite boundaries per axis and a 3×3 palette to BivariateRasterStyle(x_bins, y_bins, palette, x_label, y_label, ...). Use RasterOverlay(data=x, secondary_data=y, style=...). palette[y_bin][x_bin] has low-to-high y rows and x columns. right=False preserves classifier intervals [-∞, b0), [b0, b1), [b1, ∞); right=True gives (-∞, b0], (b0, b1], (b1, ∞). The two masks intersect. Results expose both axis indices, combined indices 1–9, palette cells and labelled axis legends with units and boundary closure.

MapScene accepts inline arrays or local .npy/GeoTIFF sources (path and secondary_path). GeoTIFF nodata masks are retained. Styled sources must share the terrain grid and CRS; pre-align them using the existing GIS/alignment APIs. The native terrain pass has one thematic color source. Multiple styled overlays diagnose explicitly. A thematic overlay can color a population height surface; it then supplies the color palette while the population style supplies height. Ordinary unstyled raster overlays keep their existing compositor and 3D block.

Nearest-cell native sampling is the default. A single categorical raster in a one-shot MapScene render can opt into CategoricalRasterStyle(palette=palette, display_sampling="area_majority"). Default alignment uses nearest-neighbour sampling. For area-majority sampling, each level counts valid coverage from the original categorical grid over successively doubled terrain footprints, clipped at the right and bottom bounds. Exact affine overlap applies when the CRS operation leaves horizontal coordinates unchanged, converts projected units, or changes a matching projection’s false origin. This includes shifted, rotated and sheared grids and equivalent CRS descriptions with different axis metadata. Comparing distinct CRS descriptions uses PROJ from the raster extra. Rotated Web Mercator terrain over an axis-aligned WGS84 source grid uses numerical source-area integration within the longitude wrap, including equivalent frames with different units or false origins. Other smooth CRS transformations refine and clip each footprint in the original grid, unwrapping geographic longitude or easting in Web Mercator, Mercator, Equidistant Cylindrical and Lambert Cylindrical Equal Area where a footprint crosses the projection seam. For these cylindrical sources, wide geographic footprints preserve their authored direction, including a full turn. The alignment closes geographic outlines that enclose a pole and preserves both longitude limits where a polar stereographic edge touches a pole. When cylindrical source data and geographic terrain share a geodetic CRS, terrain extending beyond a pole can be clipped to the source raster’s finite latitude range before voting. When source and terrain share a geodetic CRS, EPSG:9840 orthographic footprints are clipped at the visible horizon before voting. Azimuthal equidistant footprints on spheres or centred at an ellipsoidal pole, and Lambert azimuthal equal-area footprints on spheres and ellipsoids, are split along the central meridian. This preserves the poles and coverage at the antipodal rim. When both grids share a geodetic CRS, nonpolar azimuthal equidistant footprints on oblate ellipsoids with second eccentricity squared below one are clipped to the reach of shortest geodesics along each bearing. The orthographic and azimuthal alignments also measure coverage directly on supported Mercator, Equidistant Cylindrical, and Lambert Cylindrical Equal Area source grids when they share the geodetic CRS. Areas from overlapping longitude copies cancel their opposite-signed closure regions before contributing to the vote. A geographic source with another datum can use these horizon and rim calculations if PROJ selects a single identity operation whose published area contains the complete source extent. Geographic and Transverse Mercator sources can also use these calculations when the footprint stays in a continuous chart within the published area of use and one regional datum operation agrees with PROJ’s default at all sampled points. For regional geographic sources expressed in Greenwich degrees, the reducer partitions supported datum operations by their published bounds and, for forward shifts on local horizontal GeoTIFF grids, by the grid and subgrid boundaries. It clips each contribution in the original source coordinates before combining class areas and applying the priority rule. Ellipsoidal azimuthal equidistant footprints wholly beyond the half-meridian have no coverage. Other discontinuous footprints use GDAL’s area-weighted warp for each class and level. On already aligned grids, each cell contributes one vote. The class with the most coverage wins, with the lowest source ID breaking ties. A footprint with no valid coverage is nodata.

Use priority_classes with priority_min_coverage to give selected palette classes precedence in this reduction. The fraction is between zero and one and is measured against valid covered area. The first listed class that is present and meets the minimum wins. The certificate records the list and the minimum fraction.

For a standalone render, the terrain shader chooses one level from the screen-pixel footprint and loads one integer class index. It looks up that index in the palette and co-writes it to the class-ID attachment when capturing AOVs. An opaque layer and palette retain their palette colours in the unlit view. The policy is recorded in the render metadata and in a requested render certificate, with hashes of the normalized source indices and the signed class-to-colour palette. The source hash includes the source grid and incorporates nodata through the reserved ID.

Include "class_id" in OutputSpec.aovs to export <image-stem>_aov-class_id.npz. Its class_id array holds the original signed 64-bit class IDs, and its boolean valid array identifies pixels with a class. The class-ID attachment shares the one-shot integer output slot with VT source IDs, so select one of those capture modes per frame.

For an ordered camera sequence, call scene.render(path, categorical_history=True) on the same MapScene as its camera moves. The footprint level still determines which pixels have a class. Within that coverage, the shader can retain the previous class at the same screen pixel when the previous frame’s base cell had data and that class still wins at an eligible mip level. The eligible levels run from the finest minifying level to the footprint level. With no eligible history, the shader uses the finest covered level over valid base cells and the footprint level over source gaps. Palette colour and exported ID come from the same selection.

History is available for live, one-shot resident area-majority renders. Starting a standalone render or changing the aligned pyramid, palette, viewport or device resets retention. A requested certificate records the history rule and the digest of any supplied prior history texture.

To stream a categorical overlay, set RasterOverlay.metadata to {"categorical_storage": "streamed"} and configure the terrain’s metadata["virtual_texture"] with the albedo family. The renderer derives the virtual size and level count from the aligned grid unless they are explicitly configured. It pages integer class IDs into an R32Uint atlas and uses the same resident sample for the palette and class-ID export. When the full pyramid fits the residency and upload budgets, every level is available for the first draw. When a requested page is missing, the shader uses a resident coarser page from the same pyramid. The coarsest page is required before the pass is drawn. A cold render needs enough upload budget for that page. This configuration uses one categorical albedo source. Material VT sources, packed stores, and water reflections require a different render configuration.

The interactive viewer accepts a .categoria.json overlay file containing source, the path to a one-band integer TIFF including signed 64-bit samples, and style, the dictionary from CategoricalRasterStyle.to_dict(). Load it with viewer.load_overlay() and set preserve_colors=True for the unlit palette. The viewer supports one raster overlay in this mode and uses its usual registration rules for GeoTIFF drapes. For a categorical GeoTIFF snapshot, the companion <image-stem>_aov-class_id.tif has source IDs in band 1 and validity in band 2. It writes signed 64-bit samples when the visible IDs require them.

Use categorical_albedo=(class_grid, style) in hybrid_render_terrain_reference() to render a DEM-aligned categorical albedo. It selects the mip from the center ray’s footprint and shares the sample between terrain albedo and the class_id and class_valid outputs. Set categorical_unlit=True to display the opaque palette directly. The traced render certificate records the priority rule and palette and source hashes.

The Swiss camera fixture records the oblique and near-nadir tracks and their controlled aliasing comparison. The flyover record includes frame hashes, switch counts and per-class area shares. Run each side with its own staged extension and the same --track. The comparison records whether the continuous PNG files are byte-identical in comparison.json and exits with an error if a gate fails.

python tests/test_categoria_gpu.py before artifacts/categoria/baseline --track oblique
python tests/test_categoria_gpu.py after artifacts/categoria/candidate --track oblique
python tests/test_categoria_gpu.py compare artifacts/categoria/candidate --baseline artifacts/categoria/baseline

Cells with zero alpha, including nodata, discard terrain fragments. Other alpha values and overlay opacity blend the palette into terrain albedo before native lighting. Lighting and tone mapping can change displayed RGB; apply().rgba is the exact palette reference. Legends are structured data, ready for a consumer; this slice does not compose a legend into a map plate.

Style parameters and inline source cells survive MapScene.save_bundle() / load_bundle() without a schema-version change. Nonfinite source cells encode as null holes and negative zero normalizes to zero. Invalid nonfinite style parameters are rejected. Existing unstyled recipe serialization is unchanged. Styled inline terrain with shape (1, H, W) normalizes to (H, W) at construction, so the data summary and stored values use the same single-band grid. Local file paths remain references; keep those sources available for replay.

Run the complete public example on a physical terrain-capable GPU:

python examples/mapscene_thematic_rasters.py --output artifacts/thematic

It renders all three styles, saves/reloads each bundle, compares PNG bytes and writes render metadata and hashes. The scope excludes spikes, contours, data fetching, alignment redesign and plate composition. No cross-backend or hosted acceptance is established by a single local adapter run.