ridge-bake: the ground under the near clip is the place's own DEM from 1 m, drawn by card 0 inside the clip silhouette (baker_version 7)
near_march / join_near / the near flag in cards; cut_ring and bake_place join it; pack leaves near pixels out of distance_m and the nearest-terrain table. Rulings ridge-near-ground-outline, ridge-skirt-needs-real-ground. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f17ed57d5b
commit
406b197a6c
7 changed files with 161 additions and 66 deletions
|
|
@ -7,7 +7,7 @@ The live noise ridge is nearly invisible on a phone (about 1.35:1 against the da
|
|||
|
||||
## Ends
|
||||
- One owner per decision: the baker owns ridge geometry and shading; the runtime owns only the ring's residency, the camera's pose against its heading, blending and compositing. No ridge geometry is computed in the browser.
|
||||
- The near ground is a skirt under an authored 500 m near clip (the march starts there; nothing nearer is baked as terrain), `r_max` is where the linear slide holds for the nearest solid terrain each card draws in each tile (at or beyond the clip; a tile of skirt only binds nothing), and every bake keeps 150 rows under the horizon so the plane reaches the bottom of every viewport.
|
||||
- The ground under the authored 500 m near clip is the place's own DEM from 1 m, drawn by card 0 inside the silhouette of the terrain at the clip and riding card 0's slide; everything that bounds the view reads terrain at or beyond the clip: `r_max` is where the linear slide holds for the nearest solid terrain each card draws in each tile (a tile of near ground only binds nothing), and every bake keeps 150 rows under the horizon so the plane reaches the bottom of every viewport.
|
||||
- Nothing from the scene paints above app content: the scene is one stacking context at the back of the app, and nothing it creates has its own z-index or lives outside it.
|
||||
- Phone cost is bounded: no per-frame script for the ridge, decoded size and fetched size gated in CI.
|
||||
- The ring is the bake and the heading is unbounded: the whole 360 degrees ships as azimuth tiles, the client holds only the arc it is about to need and fetches more as the view turns, and nothing caps the heading: it is unwrapped within a stretch of motion and `ridge/heading.ts` `normalize` brings it into [0, 360) before each one, so no angle or pixel position grows with uptime, while `ridge/ring.ts` is the one place that reasons about the wrap at 0 / 360.
|
||||
|
|
|
|||
|
|
@ -33,9 +33,9 @@ Files are `Copernicus_DSM_COG_10_<N|S>dd_00_<E|W>ddd_00_DEM.tif`; the list below
|
|||
2. **Low-pass.** `prefilter` blurs the sampled heights with a Gaussian of `prefilter_m` metres along each ray and across rays at equal distance (sigma = `prefilter_m` / (distance x column width) columns), then recomputes the angles. Roofs go, hills stay.
|
||||
3. **View.** `set_view` maps angle to row linearly: the highest skyline angle of the whole ring sits at 4% of the frame height, the lowest at 66%, and the horizon keeps `GROUND_ROWS_MIN` = 150 rows under it (the runtime's `groundRowsNeeded`: (1 - 0.85) x 600 / 0.6, so the plane reaches the bottom of every viewport at rest). The scale is the lesser of the two fits, clamped to 0.5x to 10x vertical exaggeration (rulings `ridge-ring-vertical-anchors`, `ridge-ground-rows-below-horizon`: every azimuth sits inside one frame; a place whose whole-ring relief leaves too few ground rows is flattened below 1x); a skyline that cannot hold the rows even at 0.5x is refused naming `sky_deg` and the floor. `export.validate_manifest` refuses a plane with fewer than 150 rows under the horizon and `manifest.ts` refuses it at load.
|
||||
4. **Seams.** `coverage` counts the visible rows of the opaque view per log-distance bin and column. `seams` finds one seam per authored split per column by dynamic programming (seam carving, forward energy): it sits in a gap between depths, moving it costs 2 per bin plus the visible rows it sweeps (so it never hops across a ridge between two columns and splits it side by side), a seam inside visible terrain is cheap to cross-fade, the authored depth only breaks ties. Seam k stays 0.4 nat beyond seam k-1. The DP runs over the ring three times side by side and keeps the middle lap, so a seam is continuous across the wrap (column 6399 to 0) and a tile boundary is only a crop.
|
||||
5. **Cards.** `cards` runs per tile, on that tile's columns and the matching normals (it is column-independent: a tile is a crop of per-column results, so no seam appears at a tile boundary). It makes card i from the first visible hit at or beyond seam i-1 (layered depth: a farther card keeps the terrain a nearer ridge hides), alpha 1 minus a smoothstep over seam i in log-distance (the cross-fade), crest rows with fractional coverage, distance and normal interpolated between samples by angle, albedo from a small height and slope material, cropped to the rows where alpha is not zero. The rows of card i > 0 below the angle of its first sample (hit and first sample of the card) are its **wall**: the extruded face of the ridge the card starts at, which keeps that sample's distance, wears the ground material at its height with the face up, and is flagged `wall`. Card 0's wall is the **skirt**: the march starts at the authored near clip `NEAR_CLIP_M` = 500 m and nothing nearer is baked as terrain, so the rows under card 0's first sample are the near ground drawn as the extruded face of the clip, coloured from the sample-0 height blurred round the ring (Gaussian, `SKIRT_BLUR_DEG` = 4 degrees, tuned by eye) so that no colour edge narrower than the blur runs down the rows; the runtime lights it with the wall code like any wall. The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a tile that differs by more than 0.02.
|
||||
5. **Cards.** `cards` runs per tile, on that tile's columns and the matching normals (it is column-independent: a tile is a crop of per-column results, so no seam appears at a tile boundary). It makes card i from the first visible hit at or beyond seam i-1 (layered depth: a farther card keeps the terrain a nearer ridge hides), alpha 1 minus a smoothstep over seam i in log-distance (the cross-fade), crest rows with fractional coverage, distance and normal interpolated between samples by angle, albedo from a small height and slope material, cropped to the rows where alpha is not zero. The rows of card i > 0 below the angle of its first sample (hit and first sample of the card) are its **wall**: the extruded face of the ridge the card starts at, which keeps that sample's distance, wears the ground material at its height with the face up, and is flagged `wall`. Card 0 also draws the **near march** (ruling `ridge-near-ground-outline`): the place's own DEM from `NEAR_START_M` = 1 m to the near clip `NEAR_CLIP_M` = 500 m (`near_march`: float64 bilinear samples every max(1 m, 0.02 d) up to 10 m, about 170 per column, low-passed with the place's own `prefilter_m`), joined to the far march by `join_near` on the whole ring before the tile cut, its angles capped per column at the angle of the clip sample so the near ground draws inside the silhouette of the terrain at the clip (a near hill above that edge is cut along it). Its rows are ordinary terrain with their own normal and the albedo of their own height and n_up, flagged `near` in memory; `cards` refuses a march that starts at the clip. The runtime reads them as ground at the clip distance (they decode at `log_d_min`) and lights them like any card pixel. The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a tile that differs by more than 0.02.
|
||||
6. **Tiles.** The ring is absolute compass, column 0 = north, column c at azimuth (c + 0.5) / 6400 x 360; `places.json`'s `az_deg` / `look_at` is only the rest azimuth (`view.look_az_deg`). Tile t owns columns [200 t, 200 t + 200) (11.25 degrees) and its files hold [200 t - 2, 200 t + 202): two columns of real neighbour data each side (the client's ink pass and lighting read one texel each way; the client crops it), taken periodically by `ridge.ring_cols`. Per card and tile the file is cropped to the rows where that tile's 8-bit alpha is not zero (`top`, `h`); a card that holds nothing in a tile is `null` there (the client interpolates its distance from the neighbours); a card with no solid pixel in any tile is refused.
|
||||
7. **Distance and the offset range.** The bake holds no camera (ruling `ridge-camera-full-ring`). `pack` gives each card tile `distance_m` = exp(median ln d) over the tile's solid pixels that are not wall (its interior 200 columns); the client derives each card's slide from that and the viewer's offset r and heading. `camera.r_max_m` is the largest |r| (never above half the nearest terrain's distance) at which, for every tile, card and phi (24 steps of the camera's angle on the circle against its heading; the offset-only rotation mode moves phi round the whole circle), the least-squares line `a + s beta` fitted to the exact view angle `atan2(R sin beta - r sin phi, R cos beta - r cos phi)` over the widest viewport (`HFOV_MAX_DEG` = 72 / 1.1) errs by at most `FIT_PX_MAX` = 24 card px (the continuous error: the line by quadrature over the viewport, the worst error looked for on 513 points, so a handful of samples cannot undercount it); the distance d is that of the NEAREST solid (alpha >= 0.5, not wall) pixel the card draws in the tile's interior columns, which is where the slide errs most (the line is fitted for the tile's `distance_m`, the median, but the bound is held for the nearest terrain: a tile whose terrain spans 600 to 2000 m is bound at 600 m); a tile that draws only skirt rows has no such pixel and binds nothing; and the resident gate (below) must hold at r_max_m too. `camera.r_max_forward_m` is the same search at phi = 0 alone (same `FIT_PX_MAX`, the same half-distance cap, the same resident gate): the camera pushed forward along its heading, which is where the offset stays when the view direction turns with it (the modes 'still' and 'both'), so it is at least `r_max_m`; the client takes `r_max_m` for the offset-only mode and for a backward offset, `r_max_forward_m` for a forward one in the other modes (`view.ts` `offsetRange`). `FIT_PX_MAX` is provisional, tuned by eye (ruling `ridge-offset-range-fit`). A bake whose `r_max_m` is below `R_MAX_FLOOR_M` = 25 m is refused, naming the card and tile. `distance_m` excludes the skirt, so card 0's distances are never nearer than the near clip (`write_bake` refuses one that is), and `r_max_m` and `r_max_forward_m` hold for the nearest solid terrain each card draws in each tile, at or beyond 500 m, skirt-only tiles excluded: not a measurement of the ground nearer than that, which is only the skirt.
|
||||
7. **Distance and the offset range.** The bake holds no camera (ruling `ridge-camera-full-ring`). `pack` gives each card tile `distance_m` = exp(median ln d) over the tile's solid pixels that are neither wall nor near ground (its interior 200 columns); the client derives each card's slide from that and the viewer's offset r and heading. `camera.r_max_m` is the largest |r| (never above half the nearest terrain's distance) at which, for every tile, card and phi (24 steps of the camera's angle on the circle against its heading; the offset-only rotation mode moves phi round the whole circle), the least-squares line `a + s beta` fitted to the exact view angle `atan2(R sin beta - r sin phi, R cos beta - r cos phi)` over the widest viewport (`HFOV_MAX_DEG` = 72 / 1.1) errs by at most `FIT_PX_MAX` = 24 card px (the continuous error: the line by quadrature over the viewport, the worst error looked for on 513 points, so a handful of samples cannot undercount it); the distance d is that of the NEAREST solid (alpha >= 0.5, neither wall nor near ground) pixel the card draws in the tile's interior columns, which is where the slide errs most (the line is fitted for the tile's `distance_m`, the median, but the bound is held for the nearest terrain: a tile whose terrain spans 600 to 2000 m is bound at 600 m); a tile whose card 0 draws only near ground (under the clip) has no such pixel and binds nothing; and the resident gate (below) must hold at r_max_m too. `camera.r_max_forward_m` is the same search at phi = 0 alone (same `FIT_PX_MAX`, the same half-distance cap, the same resident gate): the camera pushed forward along its heading, which is where the offset stays when the view direction turns with it (the modes 'still' and 'both'), so it is at least `r_max_m`; the client takes `r_max_m` for the offset-only mode and for a backward offset, `r_max_forward_m` for a forward one in the other modes (`view.ts` `offsetRange`). `FIT_PX_MAX` is provisional, tuned by eye (ruling `ridge-offset-range-fit`). A bake whose `r_max_m` is below `R_MAX_FLOOR_M` = 25 m is refused, naming the card and tile. `distance_m` and the nearest-terrain table exclude the near ground (a tile with nothing outside it gets `distance_m` = 500 m), so card 0's distances are never nearer than the near clip (`write_bake` refuses one that is), and `r_max_m` and `r_max_forward_m` hold for the nearest solid terrain each card draws in each tile, at or beyond 500 m, near-only tiles excluded: the ground nearer than that rides card 0's slide and is not measured.
|
||||
8. **Normals.** `normals` takes the along-ray slope and the across-ray slope at equal distance (neighbouring columns, same sample), both times the vertical exaggeration.
|
||||
|
||||
Files per card `i` and tile `t`: `card-<i>-t<tt>-colour.webp` (lossy RGB albedo, lossless straight alpha) and `card-<i>-t<tt>-geometry.webp` (lossless: R, G = (n + 1) / 2 for the normal's along and across components, B = log-distance normalised between `encoding.log_d_min` and `log_d_max`; wall pixels write R = G = 255, a code outside the unit disc that no real normal reaches), each 204 columns wide. The manifest lists the cards nearest first (`near_m`, `far_m`: the median seam depths over the ring) and `tiles[t][i]` = `{ top, h, distance_m, colour, geometry }` or `null`; the runtime paints the cards last to first. The `bake_id` is the sha256 of the files, tile-major, then card, colour then geometry.
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
|
||||
The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour
|
||||
columns each side; the bake holds no camera: it ships each card tile's distance_m and camera.r_max_m, the largest offset the per-card linear slide can take (ruling ridge-offset-range-fit); the client lights the cards itself (ruling ridge-cards-runtime-lit).
|
||||
The pure parts (budget, bake_id, index, schema check) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work), and so do validate_manifest and write_bake, which read ridge's NEAR_CLIP_M and GROUND_ROWS_MIN."""
|
||||
The pure parts (budget, bake_id, index, schema check) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work), and so do pack, validate_manifest and write_bake, which read ridge's NEAR_CLIP_M and GROUND_ROWS_MIN."""
|
||||
import os, sys, json, math, shutil, hashlib, argparse, tempfile
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
|
@ -13,7 +13,7 @@ HERE = Path(__file__).resolve().parent
|
|||
sys.path.insert(0, str(HERE))
|
||||
import numpy as np, imagecodecs
|
||||
|
||||
BAKER_VERSION = 6
|
||||
BAKER_VERSION = 7
|
||||
RING_W = 6400 # the ring's columns (ridge.W, asserted in bake_place): column c is at azimuth (c + 0.5) / RING_W x 360, column 0 = north
|
||||
TILES = 32 # azimuth tiles of the ring, each card cut into TILES files per kind (ruling ridge-camera-full-ring: the client loads the arc near its heading)
|
||||
TILE_W = RING_W // TILES # 200 columns = 11.25 degrees owned by a tile
|
||||
|
|
@ -51,11 +51,11 @@ SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'r
|
|||
view=_obj(look_az_deg=_num, ring_w={'const': RING_W}, tile_w={'const': TILE_W}, tiles={'const': TILES}, apron={'const': APRON}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num),
|
||||
curvature=_obj(r_earth_m=_num, k_ref=_num),
|
||||
encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}),
|
||||
camera=dict(_obj(r_max_m=_num, r_max_forward_m=_num), description="r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile that draws only skirt rows (wall) has no such terrain and binds nothing. Nothing nearer than the clip is baked as terrain, so they are no measure of the ground under it."),
|
||||
camera=dict(_obj(r_max_m=_num, r_max_forward_m=_num), description="r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) has no such terrain and binds nothing. The ground under the clip is drawn by card 0 from the near march and is not measured, so they are no measure of it."),
|
||||
cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _obj(near_m=_numnull, far_m=_numnull),
|
||||
'description': "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."},
|
||||
tiles={'type': 'array', 'minItems': TILES, 'maxItems': TILES, 'items': {'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _objnull(top=_int, h=_int, distance_m=_num, colour=_file, geometry=_file)},
|
||||
'description': "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are not wall (the interior tile_w columns)."},
|
||||
'description': "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance."},
|
||||
bytes=_int,
|
||||
attribution=_obj(credit_line=_str, licence=_str, dem_source=_str, url=_str)),
|
||||
'index': _obj(schema={'const': 1}, default=_str, places={'type': 'object', 'additionalProperties': _str})}}
|
||||
|
|
@ -104,7 +104,7 @@ def encode_colour(albedo, alpha):
|
|||
"""Lossy RGB albedo with lossless alpha coverage, straight (not premultiplied); the colour under a zero alpha is zeroed."""
|
||||
a = u8(alpha); rgb = u8(albedo) * (a[..., None] > 0); return bytes(imagecodecs.webp_encode(np.dstack([rgb, a]), level=WEBP_QUALITY, lossless=False))
|
||||
def encode_geometry(n_r, n_t, logd, enc, wall=None):
|
||||
"""Lossless, opaque RGB: R, G = (n_r + 1) / 2, (n_t + 1) / 2 ('rt8'), B = the log-distance normalised between enc log_d_min and log_d_max. Wall pixels (the extruded face under a ridge; wall (h, w) bool) write R = G = 255: a code outside the unit disc
|
||||
"""Lossless, opaque RGB: R, G = (n_r + 1) / 2, (n_t + 1) / 2 ('rt8'), B = the log-distance normalised between enc log_d_min and log_d_max (a log-distance under log_d_min, the near ground under the clip, encodes as 0: the clip distance). Wall pixels (the extruded face under a ridge; wall (h, w) bool) write R = G = 255: a code outside the unit disc
|
||||
that no real normal reaches (real r2 + t2 peaks at 0.998), which the runtime reads as 'normal up, no crease'."""
|
||||
b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min']); r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)
|
||||
if wall is not None: m = np.asarray(wall, bool); r, t = np.where(m, 255, r).astype(np.uint8), np.where(m, 255, t).astype(np.uint8)
|
||||
|
|
@ -205,7 +205,7 @@ def write_bake(out, place, view, meta, packed, opaque, default=None):
|
|||
if opaque[t].shape != (h, w): raise ValueError(f'tile {t}: the opaque view is {opaque[t].shape}, the frame {(h, w)}')
|
||||
import ridge
|
||||
rmin = min(row[0]['distance_m'] for row in tiles if row[0]) # distance_m is exp of a float32 log: it lands a few parts in 1e7 off the clip, so the compare keeps 1e-5 of slack
|
||||
if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise ValueError(f'card 0 stands {rmin:.1f} m away, nearer than the near clip {ridge.NEAR_CLIP_M:g} m: nothing nearer is baked as terrain')
|
||||
if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise ValueError(f'card 0 stands {rmin:.1f} m away, nearer than the near clip {ridge.NEAR_CLIP_M:g} m: the distance of card 0 is measured at or beyond the clip (the near ground under it is not measured)')
|
||||
if camera['r_max_forward_m'] < camera['r_max_m']: raise ValueError(f"r_max_forward_m {camera['r_max_forward_m']:g} is below r_max_m {camera['r_max_m']:g}: phi = 0 is one of the angles r_max_m holds for")
|
||||
for r in (camera['r_max_m'], camera['r_max_forward_m']): check_budget(k, tile_bytes, bands, r, rmin)
|
||||
for t, (row, drow) in enumerate(zip(tiles, dec)):
|
||||
|
|
@ -232,28 +232,29 @@ def write_bake(out, place, view, meta, packed, opaque, default=None):
|
|||
return dest
|
||||
|
||||
# ------------------------------------------------------------------------------------ the bake
|
||||
def cut_ring(d, a, h, splits_km):
|
||||
"""The ring cut of a prefiltered march (set_view done): normals, coverage, the periodic seams on all RING_W columns, then ridge.cards per tile on its TILE_W + 2 APRON columns with the matching normals. Returns dict(cards [TILES][cards] (ridge.cards arrays),
|
||||
def cut_ring(d, a, h, splits_km, near):
|
||||
"""The ring cut of a prefiltered march (set_view done) and its near march (ridge.near_march): coverage, the periodic seams and the opaque view on the far march (d, a), the join of the near ground and the normals on all RING_W columns (ridge.join_near), then ridge.cards per tile on its TILE_W + 2 APRON columns of the joined march. Returns dict(cards [TILES][cards] (ridge.cards arrays),
|
||||
splits_km, seams (K, ring) in m, cov (bins, ring), opaque [TILES] (rows, TILE_W + 2 APRON) coverage, edges)."""
|
||||
import ridge
|
||||
nrm = ridge.normals(d, h); cov = ridge.coverage(d, a); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], d); op = ridge.opaque(a); cols = lambda x, t: ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON); tiles = []
|
||||
for t in range(TILES): tiles.append(ridge.cards(d, cols(a, t), cols(h, t), cols(sm, t), tuple(cols(x, t) for x in nrm))); print(f'tile {t + 1}/{TILES}', file=sys.stderr, flush=True)
|
||||
cov = ridge.coverage(d, a); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], d); op = ridge.opaque(a); D, A, Hc, nrm = ridge.join_near(d, a, h, near); cols = lambda x, t: ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON); tiles = []
|
||||
for t in range(TILES): tiles.append(ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm))); print(f'tile {t + 1}/{TILES}', file=sys.stderr, flush=True)
|
||||
return dict(cards=tiles, splits_km=list(splits_km), seams=sm, cov=cov, opaque=[cols(op, t) for t in range(TILES)], edges=ridge.log_edges(d))
|
||||
|
||||
def bake_place(pid):
|
||||
"""stage 0, prefilter, set_view on the whole ring, cut_ring: dict(place, view, meta, v, and cut_ring's cards, splits_km, seams, cov, opaque, edges). Needs RIDGE_TILES / RIDGE_WORK."""
|
||||
import ridge
|
||||
assert ridge.W == RING_W and ridge.H > 0
|
||||
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0)); ring = cut_ring(d, a, h, p['card_split_km'])
|
||||
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0)); ring = cut_ring(d, a, h, p['card_split_km'], ridge.near_march(p.get('prefilter_m', 0) or 0))
|
||||
place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m'], tz=p['tz'])
|
||||
view = dict(look_az_deg=p['az_center'], plane_h=ridge.H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * ridge.H, near_row=v['near_row'] * ridge.H)
|
||||
meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])))
|
||||
return dict(place=place, view=view, meta=meta, v=v, **ring)
|
||||
|
||||
def pack(bake):
|
||||
"""The tiles of a bake as bytes plus their manifest facts. Per card tile: distance_m = exp(median ln d) over the solid (alpha >= 0.5) pixels that are not wall of the interior TILE_W columns (a tile with none falls back to its non-wall, then any, lit pixels);
|
||||
a card with no rows in a tile is null there. Per card: the median seam depths over the ring. camera.r_max_m: solve_r_max over the NEAREST solid non-wall pixel of each card tile (not its median distance_m; a tile that draws only wall, the skirt, has none and binds nothing) and every camera angle on its circle (the offset-only rotation mode), camera.r_max_forward_m: the same at phi = 0 alone (the modes where the offset turns with the view). Refuses a card empty in every tile (naming the splits) and a card with
|
||||
"""The tiles of a bake as bytes plus their manifest facts. Per card tile: distance_m = exp(median ln d) over the solid (alpha >= 0.5) pixels that are neither wall nor near ground (under the clip) of the interior TILE_W columns (a tile with none falls back to its non-wall, then any, lit pixels, near ground never; a tile with nothing outside the near ground gets ridge.NEAR_CLIP_M: the near ground binds nothing and is not measured);
|
||||
a card with no rows in a tile is null there. Per card: the median seam depths over the ring. camera.r_max_m: solve_r_max over the NEAREST solid non-wall pixel of each card tile (not its median distance_m; a tile whose card 0 draws only near ground, under the clip, has none and binds nothing) and every camera angle on its circle (the offset-only rotation mode), camera.r_max_forward_m: the same at phi = 0 alone (the modes where the offset turns with the view). Refuses a card empty in every tile (naming the splits) and a card with
|
||||
no solid terrain apart from its wall in any tile. Returns dict(cards, tiles, camera, report) (report is printed, not written)."""
|
||||
import ridge
|
||||
sm = bake['seams']; sp = bake['splits_km']; k = len(sp) + 1; ppd = bake['view']['px_per_deg_h']; inner = slice(APRON, APRON + TILE_W); enc = bake['meta']['encoding']
|
||||
for i in range(k):
|
||||
if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise ValueError(f"card {i} is empty: it lies between the splits {' and '.join(f'{sp[j]:g} km' for j in (i - 1, i) if 0 <= j < len(sp))} (card_split_km {sp}) and holds no terrain nothing nearer hides; move or remove a split")
|
||||
|
|
@ -262,9 +263,9 @@ def pack(bake):
|
|||
row, drow, nrow, brow = [], [], [], []
|
||||
for i, c in enumerate(tile):
|
||||
if c['alpha'].shape[0] == 0: row.append(None); drow.append(None); nrow.append(None); continue
|
||||
al, wl, ld = c['alpha'][:, inner], c['wall'][:, inner], c['logd'][:, inner]; solid = (al >= 0.5) & ~wl; any_solid[i] |= bool(solid.any())
|
||||
pool = next((m, l) for m, l in ((solid, ld), ((al > 0) & ~wl, ld), (al > 0, ld), (c['alpha'] > 0, c['logd'])) if m.any())
|
||||
dm = float(np.exp(np.median(pool[1][pool[0]]))); nrow.append(float(np.exp(ld[solid].min())) if solid.any() else None) # the nearest solid terrain the card draws in this tile: None where it draws only wall (the skirt), which binds nothing
|
||||
al, wl, ld, nr = c['alpha'][:, inner], c['wall'][:, inner], c['logd'][:, inner], c['near'][:, inner]; solid = (al >= 0.5) & ~wl & ~nr; any_solid[i] |= bool(solid.any())
|
||||
pool = next(((m, l) for m, l in ((solid, ld), ((al > 0) & ~wl & ~nr, ld), ((al > 0) & ~nr, ld), ((c['alpha'] > 0) & ~c['near'], c['logd'])) if m.any()), None)
|
||||
dm = float(np.exp(np.median(pool[1][pool[0]]))) if pool else ridge.NEAR_CLIP_M; nrow.append(float(np.exp(ld[solid].min())) if solid.any() else None) # the nearest solid terrain the card draws in this tile: None where it draws only near ground, which binds nothing
|
||||
row.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc, c['wall']), distance_m=dm)); drow.append(dm); brow.append(c['alpha'].shape[0])
|
||||
tiles.append(row); dist.append(drow); near.append(nrow); bands.append(brow)
|
||||
for i in range(k):
|
||||
|
|
|
|||
|
|
@ -173,7 +173,7 @@
|
|||
"type": "number"
|
||||
}
|
||||
},
|
||||
"description": "r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile that draws only skirt rows (wall) has no such terrain and binds nothing. Nothing nearer than the clip is baked as terrain, so they are no measure of the ground under it."
|
||||
"description": "r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) has no such terrain and binds nothing. The ground under the clip is drawn by card 0 from the near march and is not measured, so they are no measure of it."
|
||||
},
|
||||
"cards": {
|
||||
"type": "array",
|
||||
|
|
@ -269,7 +269,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"description": "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are not wall (the interior tile_w columns)."
|
||||
"description": "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance."
|
||||
},
|
||||
"bytes": {
|
||||
"type": "integer"
|
||||
|
|
|
|||
|
|
@ -117,7 +117,7 @@ def detail_height(E, N, dist):
|
|||
return cfg['amp_m'] * fade * (s / nrm - 0.3)
|
||||
|
||||
# ====================================================================== stage 0: march
|
||||
NEAR_CLIP_M = 500.0 # authored: the march's first sample. Nothing nearer is baked as terrain; the ground under it is card 0's skirt (cards)
|
||||
NEAR_CLIP_M = 500.0 # authored: the far march's first sample and the boundary of parallax authority: coverage, seams, the encoding range, distance_m and r_max read terrain at or beyond it. The ground under it is the near march (near_march), drawn by card 0 only
|
||||
def schedule(detail):
|
||||
d = [NEAR_CLIP_M]
|
||||
while d[-1] < P['rmax_km'] * 1000:
|
||||
|
|
@ -150,6 +150,24 @@ def stage0(detail=False, force=False):
|
|||
t0 = time.time(); mosaic(P); t1 = time.time(); d, A, Hh = march(detail); t2 = time.time(); np.savez(c, d=d, ang=A, h=Hh)
|
||||
return d, A, Hh, dict(mosaic=t1 - t0, march=t2 - t1, samples=len(d))
|
||||
|
||||
# ====================================================================== the near march: the ground under the near clip
|
||||
NEAR_START_M = 1.0 # authored: the ray of the frame bottom meets flat ground from a 1.6 m eye farther out than this; a 5 m start leaves a wall at grandcanyon h100, where the ground at 5 m stands 8 degrees up
|
||||
def near_schedule():
|
||||
"""Sample distances (m) of the near march: NEAR_START_M, then steps of max(1 m, 0.02 d) capped at 10 m, every sample below NEAR_CLIP_M (about 170)."""
|
||||
d = [NEAR_START_M]
|
||||
while d[-1] + min(10.0, max(1.0, 0.02 * d[-1])) < NEAR_CLIP_M: d.append(d[-1] + min(10.0, max(1.0, 0.02 * d[-1])))
|
||||
return np.array(d)
|
||||
def near_march(sigma_m=0.0):
|
||||
"""(d, a, h) of the ground under the near clip: the place's own DEM, bilinear, sampled along near_schedule() on all W columns in float64 (no cache: one pass is about 170 x 6400 samples), low-passed with the place's own prefilter (sigma_m = prefilter_m) like the far march."""
|
||||
m, lt, ll = mosaic(P); az = np.radians((np.arange(W) + 0.5) / W * 360.0); d = near_schedule(); cosl = math.cos(math.radians(P['lat'])); sa, ca = np.sin(az), np.cos(az)
|
||||
h = np.stack([np.asarray(bil(m, lt, ll, P['lat'] + dk * ca / 111320.0, P['lon'] + dk * sa / (111320.0 * cosl)), np.float64) for dk in d]); a, h = prefilter(d, h, sigma_m)
|
||||
return d, a, h
|
||||
def join_near(d, a, h, near):
|
||||
"""The one join of the near march to the far march (d, a, h: (K, W), set_view done): returns (D, A, Hc, nrm) for cards, near samples first. The near angles are capped per column at the angle of the far march's first sample, a[0]: the near ground draws inside the silhouette of the terrain at the clip
|
||||
and no near hill rises above it (ruling ridge-near-ground-outline). The normals of the two marches are computed apart and concatenated, so the far normals are those of the far march alone. Needs the whole ring (the cap and the lateral normal read ring columns): cut the tiles from the result."""
|
||||
dn, an, hn = near; a = np.asarray(a); an = np.minimum(an, a[0][None, :]); nn, nf = normals(dn, hn), normals(d, h)
|
||||
return np.concatenate([dn, d]), np.concatenate([an, a]), np.concatenate([hn, h]), tuple(np.concatenate([x, y]) for x, y in zip(nn, nf))
|
||||
|
||||
# ====================================================================== periodic helpers
|
||||
|
||||
# ====================================================================== prefilter: the march is a heightfield of roofs and hills; the cards want the hills
|
||||
|
|
@ -247,11 +265,12 @@ def cards(d, a, h, seams, nrm=None):
|
|||
log-distance of the hit; card 0 owns the rows below the first sample, the last card has no far edge. Alphas are then made nested so the alpha-over composite of all cards is exactly the opaque coverage (a row two
|
||||
cards both hold partly is not counted twice). Distance and normal are interpolated between sample k-1 and k by angle. Each card is cropped to the rows where its 8-bit alpha is not zero.
|
||||
nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for columns cut from the ring: the lateral slope reads the neighbouring columns). Rows of any card below the angle of its first sample (hit and idx == 0) are its wall: they keep that sample's distance, their albedo is the ground material at their height with the face up (n_up = 1),
|
||||
and `wall` flags them. Each card: dict(top, alpha (h,n), albedo (h,n,3), n_r, n_t, logd (ln metres) (h,n), wall (h,n) bool)."""
|
||||
and `wall` flags them (card 0's first sample is the near march's NEAR_START_M, so no row of it is wall under a real frame). Card 0 draws the near march (join_near; the samples nearer than NEAR_CLIP_M) under the silhouette of the terrain at the clip as ordinary terrain: its own normal, the albedo of its own height and n_up; `near` (h, n) bool flags the pixels whose hit lies on the near side of the clip sample (the rows that were card 0's wall), whose distance is then never above the clip. Each card: dict(top, alpha (h,n), albedo (h,n,3), n_r, n_t, logd (ln metres) (h,n), wall (h,n) bool, near (h,n) bool)."""
|
||||
d = np.asarray(d, np.float64); a = np.asarray(a, np.float64); h = np.asarray(h, np.float64); seams = np.asarray(seams, np.float64); nk, n = a.shape; nc = len(seams) + 1
|
||||
n_r, n_t, n_u = nrm if nrm is not None else normals(d, h); ld = np.broadcast_to(np.log(d)[:, None], (nk, n)); p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p
|
||||
if d[0] >= NEAR_CLIP_M: raise ValueError(f"card 0 draws the ground under the near clip from the near march, but the first sample is at {d[0]:g} m (the clip is {NEAR_CLIP_M:g} m): pass join_near")
|
||||
n_r, n_t, n_u = nrm if nrm is not None else normals(d, h); ld = np.broadcast_to(np.log(d)[:, None], (nk, n)); p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p; kn = int(np.searchsorted(d, NEAR_CLIP_M)) # kn: the samples nearer than the clip
|
||||
ks0 = [np.searchsorted(d, seams[i - 1] * math.exp(-XF)) for i in range(1, nc)]; ks1 = [np.searchsorted(d, seams[i] * math.exp(XF)) for i in range(nc - 1)]
|
||||
F = np.zeros((nc, H, n)); X = np.ones((nc, H, n)); G = np.zeros((nc, 5, H, n)); Wl = np.zeros((nc, H, n), bool) # coverage, far fade, then (logd, h, n_r, n_t, n_u); wall rows
|
||||
F = np.zeros((nc, H, n)); X = np.ones((nc, H, n)); G = np.zeros((nc, 5, H, n)); Wl = np.zeros((nc, H, n), bool); Nr = np.zeros((nc, H, n), bool) # coverage, far fade, then (logd, h, n_r, n_t, n_u); wall rows; near rows (the ground under the clip)
|
||||
for x in range(n):
|
||||
for i in range(nc):
|
||||
k0 = 0 if i == 0 else int(ks0[i - 1][x]); k1 = nk if i == nc - 1 else int(ks1[i][x])
|
||||
|
|
@ -262,13 +281,13 @@ def cards(d, a, h, seams, nrm=None):
|
|||
t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0); mix = lambda arr: arr[kp, x] + t * (arr[kk, x] - arr[kp, x])
|
||||
F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0); lh = mix(ld)
|
||||
G[i, :, :, x] = np.where(hit, np.stack([lh, mix(h), mix(n_r), mix(n_t), mix(n_u)]), 0)
|
||||
Wl[i, :, x] = hit & (idx == 0) # rows below the card's first sample: the extruded wall
|
||||
Wl[i, :, x] = hit & (idx == 0); Nr[i, :, x] = hit & (kp < kn) # rows below the card's first sample: the extruded wall; hits on the near side of the clip sample (below it, or between the last near sample and it): the near ground (only card 0 reaches it)
|
||||
if i < nc - 1: s = np.clip((lh - (math.log(seams[i, x]) - XF)) / (2 * XF), 0, 1); X[i, :, x] = 1 - s * s * (3 - 2 * s)
|
||||
out = []; A = np.zeros((H, n))
|
||||
for i in range(nc):
|
||||
part = np.where(F[i] < 1, np.clip((np.maximum(A, F[i]) - A) / np.maximum(1 - A, 1e-6), 0, 1), F[i]); al = np.where(np.rint(X[i] * part * 255) > 0, X[i] * part, 0.0); A = 1 - (1 - A) * (1 - al)
|
||||
rows = np.flatnonzero(al.max(1) > 0)
|
||||
if not len(rows): out.append(dict(top=0, alpha=np.zeros((0, n), np.float32), albedo=np.zeros((0, n, 3), np.float32), n_r=np.zeros((0, n), np.float32), n_t=np.zeros((0, n), np.float32), logd=np.zeros((0, n), np.float32), wall=np.zeros((0, n), bool))); continue
|
||||
if not len(rows): out.append(dict(top=0, alpha=np.zeros((0, n), np.float32), albedo=np.zeros((0, n, 3), np.float32), n_r=np.zeros((0, n), np.float32), n_t=np.zeros((0, n), np.float32), logd=np.zeros((0, n), np.float32), wall=np.zeros((0, n), bool), near=np.zeros((0, n), bool))); continue
|
||||
sl = slice(int(rows[0]), int(rows[-1]) + 1); g = G[i, :, sl]; nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12
|
||||
out.append(dict(top=int(rows[0]), alpha=al[sl].astype(np.float32), albedo=albedo(g[1], np.where(Wl[i, sl], 1.0, g[4] / nz)).astype(np.float32), n_r=(g[2] / nz).astype(np.float32), n_t=(g[3] / nz).astype(np.float32), logd=g[0].astype(np.float32), wall=Wl[i, sl].copy()))
|
||||
out.append(dict(top=int(rows[0]), alpha=al[sl].astype(np.float32), albedo=albedo(g[1], np.where(Wl[i, sl], 1.0, g[4] / nz)).astype(np.float32), n_r=(g[2] / nz).astype(np.float32), n_t=(g[3] / nz).astype(np.float32), logd=g[0].astype(np.float32), wall=Wl[i, sl].copy(), near=Nr[i, sl].copy()))
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -15,11 +15,17 @@ D = ridge.schedule(False)
|
|||
def az_of(x): return (x + 0.5) / W * 360.0
|
||||
def col_of(az): return int(round(az / 360.0 * W - 0.5)) % W
|
||||
|
||||
def rays(hfun):
|
||||
def rays(hfun, eye=EYE):
|
||||
az = (np.arange(W) + 0.5) / W * 360.0; A = np.zeros((len(D), W), np.float32); Hh = np.zeros_like(A)
|
||||
for k, dk in enumerate(D):
|
||||
h = hfun(dk, az); Hh[k] = h; A[k] = np.degrees(np.arctan2(h - EYE - dk * dk / (2 * ridge.R_EARTH) * (1 - ridge.KREF), dk))
|
||||
h = hfun(dk, az); Hh[k] = h; A[k] = np.degrees(np.arctan2(h - eye - dk * dk / (2 * ridge.R_EARTH) * (1 - ridge.KREF), dk))
|
||||
return A, Hh
|
||||
def near_rays(hfun, sigma=0.0):
|
||||
"""The near march of a synthetic terrain: hfun over ridge.near_schedule() on all W columns, float64, prefiltered like the far march (angles from ridge.P['eye_m']): (d, a, h) as ridge.near_march returns it."""
|
||||
dn = ridge.near_schedule(); az = (np.arange(W) + 0.5) / W * 360.0; hn = np.stack([np.broadcast_to(np.asarray(hfun(dk, az), np.float64), az.shape) for dk in dn]); a, h = ridge.prefilter(dn, hn, sigma); return dn, a, h
|
||||
def _join(hfun, A, Hh, sigma=0.0):
|
||||
"""ridge.join_near of raw far rays (K, W) and the near march of the same terrain, cut to the window 0..NW: (D, a, h, nrm) as ridge.cards reads them."""
|
||||
d, a, h, nrm = ridge.join_near(D, A, Hh, near_rays(hfun, sigma)); return d, _w(a), _w(h), tuple(_w(x) for x in nrm)
|
||||
def theta(h, d): return math.degrees(math.atan2(h - EYE - d * d / (2 * ridge.R_EARTH) * (1 - ridge.KREF), d))
|
||||
def in_arc(az, a0, a1): return ((az - a0) % 360.0) <= ((a1 - a0) % 360.0)
|
||||
def block(a0, a1, d0, d1, h): return lambda dk, az: np.where(in_arc(az, a0, a1) & (dk >= d0) & (dk < d1), h, 0.0)
|
||||
|
|
@ -49,17 +55,18 @@ def test_paths_come_from_the_environment_with_no_default():
|
|||
|
||||
# ---------------------------------------------------------------------------------------- synthetic bakes: the shared steps of export.bake_place on rays the fixtures make
|
||||
def _bake(hfun, splits_km, sigma=0.0, fixed_m=None):
|
||||
"""prefilter, whole-ring set_view, coverage and the periodic seams on the whole ring (or fixed_m, one seam depth in m for every column), then the window columns 0..NW (azimuth 0..72) of them and the cards on those, of synthetic rays: the pieces of the bake a fixture can look at cheaply."""
|
||||
A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0))
|
||||
nrm = tuple(_w(x) for x in ridge.normals(D, h)); aw, hw = _w(a), _w(h); cov_ring = ridge.coverage(D, a); cov = _w(cov_ring); sm = _w(ridge.seams(cov_ring, [k * 1000.0 for k in splits_km], D)) if fixed_m is None else np.array([np.full(NW, float(v)) for v in fixed_m])
|
||||
return dict(cards=ridge.cards(D, aw, hw, sm, nrm), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(D), a=aw, h=hw, nrm=nrm, v=v)
|
||||
"""prefilter, whole-ring set_view, coverage and the periodic seams on the whole ring (or fixed_m, one seam depth in m for every column), the join of the near march on the whole ring, then the window columns 0..NW (azimuth 0..72) of them and the cards on those, of synthetic rays: the pieces of the bake a fixture can look at cheaply.
|
||||
D, a, h, nrm of the result are the JOINED march's window (the near samples first); opaque and edges are the far march's."""
|
||||
A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0)); cov_ring = ridge.coverage(D, a); cov = _w(cov_ring)
|
||||
sm = _w(ridge.seams(cov_ring, [k * 1000.0 for k in splits_km], D)) if fixed_m is None else np.array([np.full(NW, float(v)) for v in fixed_m])
|
||||
Dj, aj, hj, nj = ridge.join_near(D, a, h, near_rays(hfun, sigma)); aw, hw, nrm = _w(aj), _w(hj), tuple(_w(x) for x in nj)
|
||||
return dict(cards=ridge.cards(Dj, aw, hw, sm, nrm), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(_w(a)), edges=ridge.log_edges(D), D=Dj, a=aw, h=hw, nrm=nrm, v=v)
|
||||
def _canvas(card, key='alpha'):
|
||||
out = np.zeros((H, NW) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out
|
||||
def _row(deg): return int(np.argmin(np.abs(ridge.rowang - deg)))
|
||||
THREE = terrain(block(0, 359.99, 3000, 3600, 350), block(0, 359.99, 20000, 21500, 1800), block(0, 359.99, 70000, 72000, 7000)) # ridges at 3, 20 and 70 km, each taller in angle than the one before
|
||||
WIDE3 = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 40000, 2000), block(0, 359.99, 70000, 72000, 3000)) # low near hills, then ridges at 39 and 71 km: the frame reaches below the ground at the seams (so cards have wall rows) and the horizon is inside it
|
||||
WALLED = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 40000, 2000))
|
||||
NEARHILL = terrain(block(0, 359.99, 0, 4000, 150), block(0, 359.99, 38000, 40000, 2000)) # ground above the eye from the first sample on: every row of card 0 lies below its first sample
|
||||
def _ramp(dk, az): return np.maximum(GROUND, np.where(dk > 12000, (dk - 12000) * 0.045 + 50.0, 0.0)) # a slope the first sample of card 1 stands on: n_up about 0.9, so the material would be rock if the face counted
|
||||
|
||||
def test_the_vertical_anchors_read_the_whole_ring():
|
||||
|
|
@ -105,8 +112,8 @@ def test_far_card_keeps_terrain_hidden_behind_a_nearer_ridge():
|
|||
r = _row(0.5 * (theta(350, 3000) + theta(2400, 20000))); assert c0[r, 900] < 0.01 and a1[r, 900] > 0.99 and abs(math.exp(ld1[r, 900]) - 20000) < 1500, (c0[r, 900], a1[r, 900])
|
||||
def test_crossfade_is_complementary():
|
||||
"""A ridge across the seam (seam fixed at 6 km, the ridge's front face at 5.9 km inside the cross-fade): the nearer card is partly transparent over the window, the farther card is opaque on the ridge, and the composite stays at coverage 1 below the crest."""
|
||||
A, Hh = rays(terrain(block(0, 359.99, 5900, 6100, 900))); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = _w(A), _w(Hh)
|
||||
cs = ridge.cards(D, aw, hw, np.full((1, NW), 6000.0)); c0, c1 = _canvas(cs[0]), _canvas(cs[1]); crest = int(np.argmax(ridge.opaque(aw)[:, 500] > 0.5)); r = crest + 6
|
||||
hf = terrain(block(0, 359.99, 5900, 6100, 900)); A, Hh = rays(hf); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw = _w(A); Dj, aj, hj, nj = _join(hf, A, Hh)
|
||||
cs = ridge.cards(Dj, aj, hj, np.full((1, NW), 6000.0), nj); c0, c1 = _canvas(cs[0]), _canvas(cs[1]); crest = int(np.argmax(ridge.opaque(aw)[:, 500] > 0.5)); r = crest + 6
|
||||
assert 0.2 < c0[r, 500] < 0.8, ('the near card does not fade over the window', c0[r, 500]); assert c1[r, 500] > 0.99, 'the far card is not opaque on the ridge'
|
||||
comp = 1 - (1 - c0) * (1 - c1); assert (comp[crest + 3:, :] > 0.999).all(), 'the composite dips below coverage 1 under the crest'
|
||||
def test_normals_of_a_tilted_plane():
|
||||
|
|
@ -136,7 +143,7 @@ def test_prefilter_flattens_roofs_and_keeps_hills():
|
|||
assert np.allclose(ridge.prefilter(D, Hh, 0.0)[1], Hh), 'sigma 0 changed the heights'
|
||||
def test_crest_rows_have_fractional_coverage():
|
||||
"""The top row of a card's run has alpha equal to the share of its angular span under the running maximum, and the rows below it are 1 (a lower ridge in columns 0..640 so its crest is not at the frame's top edge)."""
|
||||
A, Hh = rays(terrain(block(0, 36, 5000, 5600, 500), block(36, 359.99, 5000, 5600, 560))); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = _w(A), _w(Hh); c = ridge.cards(D, aw, hw, np.zeros((0, NW)))[0]
|
||||
hf = terrain(block(0, 36, 5000, 5600, 500), block(36, 359.99, 5000, 5600, 560)); A, Hh = rays(hf); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw = _w(A); Dj, aj, hj, nj = _join(hf, A, Hh); c = ridge.cards(Dj, aj, hj, np.zeros((0, NW)), nj)[0]
|
||||
cv = _canvas(c)[:, 300]; r = int(np.argmax(cv > 0)); top = float(aw.max(0)[300]); p = 1.0 / ridge.PXDEG_V; want = (top - (ridge.rowang[r] - 0.5 * p)) / p
|
||||
assert 0.0 < want < 1.0 and abs(cv[r] - want) < 0.01, (cv[r], want, r); assert (cv[r + 1:] > 0.999).all()
|
||||
def test_cards_composite_to_the_opaque_view():
|
||||
|
|
@ -146,14 +153,14 @@ def test_cards_composite_to_the_opaque_view():
|
|||
rm = np.maximum.accumulate(b['a'], axis=0); col = 640; r = _row(float(b['a'][:, col].max()) - 0.5); k = int(np.searchsorted(rm[:, col], ridge.rowang[r], 'left')); first = None
|
||||
for c in b['cards']:
|
||||
if _canvas(c)[r, col] > 0.99: first = math.exp(_canvas(c, 'logd')[r, col]); break
|
||||
assert first is not None and abs(first - D[k]) < 0.1 * D[k] + 60, (first, D[k])
|
||||
assert first is not None and abs(first - b['D'][k]) < 0.1 * b['D'][k] + 60, (first, b['D'][k])
|
||||
|
||||
# ---------------------------------------------------------------------------------------- the ring: tiles are crops of per-column results, the wrap is periodic
|
||||
_RING = {}
|
||||
def _ring(key, hfun, splits_km):
|
||||
"""export.cut_ring on synthetic rays (prefilter, whole-ring set_view, then the ring cut), cached by key: dict(bake = what export.bake_place returns, minus the place)."""
|
||||
if key not in _RING:
|
||||
A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, 0.0); v = ridge.set_view(a.max(0)); r = export.cut_ring(D, a, h, splits_km)
|
||||
A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, 0.0); v = ridge.set_view(a.max(0)); r = export.cut_ring(D, a, h, splits_km, near_rays(hfun))
|
||||
_RING[key] = dict(r, op_ring=ridge.opaque(a), place=dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE, tz='Europe/Vienna'), v=v,
|
||||
view=dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * H, near_row=v['near_row'] * H),
|
||||
meta=dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1]))))
|
||||
|
|
@ -190,10 +197,10 @@ def test_every_tile_is_cut_at_its_own_seam():
|
|||
def test_tile_is_a_crop_of_the_columns():
|
||||
"""ridge.cards on a tile's columns (the 200 it owns and the apron) equals the same columns of ridge.cards on a wider run of columns, pixel for pixel, for fixed seams: the tile cut changes no pixel and adds no seam."""
|
||||
b = _bake(terrain(_receding, block(0, 359.99, 3000, 3600, 350)), [6]); x0 = 500; n = export.TILE_W + 2 * export.APRON; sl = slice(x0, x0 + n)
|
||||
tile = ridge.cards(D, b['a'][:, sl], b['h'][:, sl], b['seams'][:, sl], tuple(x[:, sl] for x in b['nrm']))
|
||||
tile = ridge.cards(b['D'], b['a'][:, sl], b['h'][:, sl], b['seams'][:, sl], tuple(x[:, sl] for x in b['nrm']))
|
||||
for c, w in zip(tile, b['cards']):
|
||||
assert np.array_equal(_canvas(w)[:, sl], _tile_canvas(c)), 'a tile is not a crop of the columns'; seen = _tile_canvas(c) > 0
|
||||
for key in ('albedo', 'n_r', 'n_t', 'logd', 'wall'): assert np.array_equal(_canvas(w, key)[:, sl][seen], _tile_canvas(c, key)[seen]), ('a tile is not a crop of the columns', key)
|
||||
for key in ('albedo', 'n_r', 'n_t', 'logd', 'wall', 'near'): assert np.array_equal(_canvas(w, key)[:, sl][seen], _tile_canvas(c, key)[seen]), ('a tile is not a crop of the columns', key)
|
||||
|
||||
# ---------------------------------------------------------------------------------------- toy bakes: tile data made by hand, for the packer and the writer
|
||||
def _toy(dists=(3000.0, 15000.0, 50000.0), bands=(300, 400, 500), tops=(300, 150, 60), amp=0.01):
|
||||
|
|
@ -201,7 +208,7 @@ def _toy(dists=(3000.0, 15000.0, 50000.0), bands=(300, 400, 500), tops=(300, 150
|
|||
n = export.TILE_W + 2 * export.APRON; x = np.arange(n); tile = []; k = len(dists)
|
||||
for i in range(k):
|
||||
ld = np.log(dists[i] * (1 + amp * np.sin(x * 0.3)))[None, :].repeat(bands[i], 0).astype(np.float32)
|
||||
tile.append(dict(top=tops[i], alpha=np.ones((bands[i], n), np.float32), albedo=np.full((bands[i], n, 3), 0.4, np.float32), n_r=np.full((bands[i], n), 0.1, np.float32), n_t=np.full((bands[i], n), -0.1, np.float32), logd=ld, wall=np.zeros((bands[i], n), bool)))
|
||||
tile.append(dict(top=tops[i], alpha=np.ones((bands[i], n), np.float32), albedo=np.full((bands[i], n, 3), 0.4, np.float32), n_r=np.full((bands[i], n), 0.1, np.float32), n_t=np.full((bands[i], n), -0.1, np.float32), logd=ld, wall=np.zeros((bands[i], n), bool), near=np.zeros((bands[i], n), bool)))
|
||||
comp = export.composite_alpha([(c['top'], c['alpha']) for c in tile], H, n)
|
||||
return dict(cards=[[dict(c) for c in tile] for _ in range(export.TILES)], splits_km=[6.0 * (j + 1) for j in range(k - 1)], seams=np.tile(np.array(dists[:-1])[:, None] * 0.5, (1, W)), opaque=[comp.copy() for _ in range(export.TILES)],
|
||||
view=dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=100.0, exaggeration=5.0, horizon_row=60.0, sky_row=24.0, near_row=396.0), meta=dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(500.0), log_d_max=math.log(100000.0))),
|
||||
|
|
@ -213,7 +220,7 @@ def _refuses(out, b, packed, why, **kw):
|
|||
except ValueError: assert not os.path.exists(out), ('a refused bake left files', why)
|
||||
else: assert False, why
|
||||
def _pins():
|
||||
assert (export.RING_W, export.TILES, export.TILE_W, export.APRON, export.MAX_CARDS, export.BAKER_VERSION) == (6400, 32, 200, 2, 6, 6), 'the ring layout is pinned'
|
||||
assert (export.RING_W, export.TILES, export.TILE_W, export.APRON, export.MAX_CARDS, export.BAKER_VERSION) == (6400, 32, 200, 2, 6, 7), 'the ring layout is pinned'
|
||||
assert (export.TILE_BYTES_MAX, export.PLACE_BYTES_MAX, export.RESIDENT_BYTES_MAX, export.FIT_PX_MAX, export.R_MAX_FLOOR_M, export.PHI_STEPS) == (235_000, 7_500_000, 20_000_000, 24.0, 25.0, 24), 'the budgets and the fit bound are pinned'
|
||||
assert abs(export.HFOV_MAX_DEG - 72 / 1.1) < 1e-12
|
||||
|
||||
|
|
@ -222,7 +229,7 @@ def test_schema3():
|
|||
_pins(); d = tempfile.mkdtemp()
|
||||
try:
|
||||
b = _toy(); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); mk = lambda: json.loads(json.dumps(m))
|
||||
assert m['schema'] == 3 and m['baker_version'] == 6 and set(m['view']) >= {'ring_w', 'tile_w', 'tiles', 'apron'} and 'rows_above' not in m['view'] and m['camera'] == dict(r_max_m=pk['camera']['r_max_m'], r_max_forward_m=pk['camera']['r_max_forward_m']) and m['camera']['r_max_forward_m'] >= m['camera']['r_max_m'] and len(m['tiles']) == 32 and 'w' not in m and 'h' not in m
|
||||
assert m['schema'] == 3 and m['baker_version'] == 7 and set(m['view']) >= {'ring_w', 'tile_w', 'tiles', 'apron'} and 'rows_above' not in m['view'] and m['camera'] == dict(r_max_m=pk['camera']['r_max_m'], r_max_forward_m=pk['camera']['r_max_forward_m']) and m['camera']['r_max_forward_m'] >= m['camera']['r_max_m'] and len(m['tiles']) == 32 and 'w' not in m and 'h' not in m
|
||||
def bad(f, why):
|
||||
x = mk(); f(x)
|
||||
try: export.validate_manifest(x)
|
||||
|
|
@ -428,9 +435,9 @@ def _vienna_ring(splits, tiles):
|
|||
"""Vienna's whole-ring march and seams for the given splits, cards on only the given tiles: (d, seams, {t: cards}, {t: opaque})."""
|
||||
saved = ridge.P
|
||||
try:
|
||||
p = ridge.configure(dict(ridge.load_preset('vienna'), card_split_km=splits)); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p['prefilter_m']); ridge.set_view(a.max(0)); nrm = ridge.normals(d, h); sm = ridge.seams(ridge.coverage(d, a), [k * 1000.0 for k in splits], d); op = ridge.opaque(a)
|
||||
p = ridge.configure(dict(ridge.load_preset('vienna'), card_split_km=splits)); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p['prefilter_m']); ridge.set_view(a.max(0)); sm = ridge.seams(ridge.coverage(d, a), [k * 1000.0 for k in splits], d); op = ridge.opaque(a); D_, A_, H_, nrm = ridge.join_near(d, a, h, ridge.near_march(p['prefilter_m']))
|
||||
cols = lambda x, t: ridge.ring_cols(x, t * export.TILE_W - export.APRON, export.TILE_W + 2 * export.APRON)
|
||||
return d, sm, {t: ridge.cards(d, cols(a, t), cols(h, t), cols(sm, t), tuple(cols(x, t) for x in nrm)) for t in tiles}, {t: cols(op, t) for t in tiles}
|
||||
return d, sm, {t: ridge.cards(D_, cols(A_, t), cols(H_, t), cols(sm, t), tuple(cols(x, t) for x in nrm)) for t in tiles}, {t: cols(op, t) for t in tiles}
|
||||
finally: ridge.P = saved
|
||||
def test_vienna_k1_k2_k3():
|
||||
"""Vienna with card_split_km [6], [6, 40] and [6, 20, 40]: 2, 3 and 4 cards, seams ordered in every column of the ring, each composite of a tile (the rest azimuth's, the north's and the last one) equals the opaque view within 0.02; the cross-fade column count is printed."""
|
||||
|
|
@ -466,26 +473,26 @@ def test_written_cards_decode_to_the_cards_in_memory():
|
|||
range, within quantisation."""
|
||||
b = _vienna_bake(); d = tempfile.mkdtemp()
|
||||
try:
|
||||
dest = _write(d, b, export.pack(b)); m = json.load(open(dest / 'manifest.json')); enc = m['encoding']; span = enc['log_d_max'] - enc['log_d_min']; partial_seen = 0
|
||||
dest = _write(d, b, export.pack(b)); m = json.load(open(dest / 'manifest.json')); enc = m['encoding']; span = enc['log_d_max'] - enc['log_d_min']; partial_seen = near_seen = 0
|
||||
for t in (0, 19, 31):
|
||||
for c, rec in zip(b['cards'][t], m['tiles'][t]):
|
||||
col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; wall = c['wall']; solid = (al > 0) & ~wall; part = (al > 0.05) & (al < 0.95) & ~wall; partial_seen += int(part.sum())
|
||||
col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; wall = c['wall']; nr = c['near']; solid = (al > 0) & ~wall & ~nr; part = (al > 0.05) & (al < 0.95) & ~wall & ~nr; partial_seen += int(part.sum()); near_seen += int((nr & (al > 0)).sum())
|
||||
assert (col[..., 3] == np.rint(al * 255)).all(), 'alpha is not exact'; e = np.abs(col[..., :3] / 255.0 - c['albedo']).max(-1)
|
||||
assert e[solid].mean() < 0.021 and np.percentile(e[solid], 99) < 0.081, ('albedo is off', e[solid].mean(), np.percentile(e[solid], 99)); assert part.sum() == 0 or e[part].mean() < 0.1, ('albedo at partial alpha is off: premultiplied?', e[part].mean())
|
||||
assert (geo[..., 3] == 255).all(); q = 1.0 / 255 + 1e-6; assert (((geo[..., 0] == 255) & (geo[..., 1] == 255)) == wall).all(), 'the wall code is not R = G = 255 on exactly the wall pixels'
|
||||
assert np.abs(geo[..., 0] / 255.0 * 2 - 1 - c['n_r'])[solid].max() < 2 * q and np.abs(geo[..., 1] / 255.0 * 2 - 1 - c['n_t'])[solid].max() < 2 * q, 'a normal channel is off or swapped'
|
||||
assert np.abs(enc['log_d_min'] + geo[..., 2] / 255.0 * span - c['logd'])[solid].max() < span * q, 'the log-distance is off or not over the encoding range'
|
||||
assert np.abs(c['n_r'][solid]).mean() > 0.05 and np.abs(c['n_t'][solid]).mean() > 0.01 and np.abs(c['n_r'][solid].mean() - c['n_t'][solid].mean()) > 0.0, 'the fixture does not tell the channels apart'
|
||||
assert col[..., :3][solid].mean() > 20, 'albedo is zeroed'
|
||||
assert partial_seen > 0, 'the fixture has no partial alpha'
|
||||
assert col[..., :3][solid].mean() > 20, 'albedo is zeroed'; assert (geo[..., 2][nr & (al > 0)] == 0).all(), 'a near pixel is not at the clip distance (B = 0)'
|
||||
assert partial_seen > 0, 'the fixture has no partial alpha'; assert near_seen > 1000, 'the fixture has no near ground'
|
||||
finally: shutil.rmtree(d)
|
||||
|
||||
# ---------------------------------------------------------------------------------------- wall rows
|
||||
def _first_sample_angle(b, i):
|
||||
"""Per column, the angle of the first sample card i reads: the first sample at or beyond its near seam, less the cross-fade half-width (card 0: sample 0, the near clip)."""
|
||||
k0 = np.zeros(NW, int) if i == 0 else np.array([np.searchsorted(D, b['seams'][i - 1][x] * math.exp(-ridge.XF)) for x in range(NW)]); return k0, b['a'][k0, np.arange(NW)]
|
||||
"""Per column, the angle of the first sample card i reads: the first sample at or beyond its near seam, less the cross-fade half-width (card 0: sample 0 of the joined march, the near start)."""
|
||||
k0 = np.zeros(NW, int) if i == 0 else np.array([np.searchsorted(b['D'], b['seams'][i - 1][x] * math.exp(-ridge.XF)) for x in range(NW)]); return k0, b['a'][k0, np.arange(NW)]
|
||||
def test_wall_rows_flagged():
|
||||
"""Every card, card 0 included, flags as wall exactly the rows below the angle of its first sample (the extruded face of the ridge it starts at); the wall carries R = G = 255 in the geometry file and no other pixel has r2 + t2 above 1.02; wall pixels keep that sample's
|
||||
"""Every card, card 0 included, flags as wall exactly the rows below the angle of its first sample (the extruded face of the ridge it starts at; card 0's first sample is the near march's, under the frame, so it has none); the wall carries R = G = 255 in the geometry file and no other pixel has r2 + t2 above 1.02; wall pixels keep that sample's
|
||||
distance and their albedo is the ground material of the sample's height with the face up (so a steep face is not rock), constant down the column."""
|
||||
steep = 0
|
||||
for make in (lambda: _bake(WALLED, [20]), lambda: _bake(WIDE3, [20, 55]), lambda: _bake(_receding, [6]), lambda: _bake(_ramp, [20], fixed_m=[20000.0])): # the ramp's seam is fixed: the wall must stand on the slope, below the height where every material is rock or snow
|
||||
|
|
@ -495,7 +502,7 @@ def test_wall_rows_flagged():
|
|||
geo = export.decode(export.encode_geometry(c['n_r'], c['n_t'], c['logd'], dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), c['wall'])); r, t = geo[..., 0] / 255.0 * 2 - 1, geo[..., 1] / 255.0 * 2 - 1; code = (geo[..., 0] == 255) & (geo[..., 1] == 255)
|
||||
assert (code == c['wall']).all() and (r[~code] ** 2 + t[~code] ** 2 <= 1.02).all(), 'the wall code is not on exactly the wall pixels, or a real normal reaches it'
|
||||
for x in np.flatnonzero(c['wall'].any(0)):
|
||||
rows = np.flatnonzero(c['wall'][:, x]); ld = c['logd'][rows, x]; assert np.ptp(ld) < 1e-5 and abs(math.exp(ld[0]) - D[k0[x]]) < 1e-3 * D[k0[x]] + 60, ('a wall keeps its sample distance', x)
|
||||
rows = np.flatnonzero(c['wall'][:, x]); ld = c['logd'][rows, x]; assert np.ptp(ld) < 1e-5 and abs(math.exp(ld[0]) - b['D'][k0[x]]) < 1e-3 * b['D'][k0[x]] + 60, ('a wall keeps its sample distance', x)
|
||||
want_alb = ridge.albedo(np.array([b['h'][k0[x], x]]), np.array([1.0]))[0]; assert np.abs(c['albedo'][rows, x] - want_alb).max() < 1e-5, ('wall albedo is not the ground material with the face up', x)
|
||||
assert seen > 1000, 'the fixture has no wall'
|
||||
for i in range(1, len(b['cards'])):
|
||||
|
|
@ -508,26 +515,26 @@ def test_the_sheet_lights_a_wall_with_the_face_up():
|
|||
assert np.allclose(rgb[:, :2], up) and np.allclose(rgb[:, 2:], tilted) and abs(up - tilted) > 0.05, (rgb[0, 0], rgb[0, 3])
|
||||
# ---------------------------------------------------------------------------------------- the near clip, the ground rows
|
||||
def _nearest_solid(c):
|
||||
"""The nearest solid (alpha >= 0.5) non-wall pixel of a card tile's interior columns, metres; None where there is none (computed here from the arrays, not by pack)."""
|
||||
ld, al, wl = (c[k][:, 2:-2] for k in ('logd', 'alpha', 'wall')); m = (al >= 0.5) & ~wl; return float(np.exp(np.float64(ld[m].min()))) if m.any() else None
|
||||
def test_r_max_holds_for_the_nearest_terrain_of_every_tile_and_skirt_only_tiles_do_not_bind():
|
||||
"""The nearest solid (alpha >= 0.5) pixel that is neither wall nor near ground of a card tile's interior columns, metres; None where there is none (computed here from the arrays, not by pack)."""
|
||||
ld, al, wl, nr = (c[k][:, 2:-2] for k in ('logd', 'alpha', 'wall', 'near')); m = (al >= 0.5) & ~wl & ~nr; return float(np.exp(np.float64(ld[m].min()))) if m.any() else None
|
||||
def test_r_max_holds_for_the_nearest_terrain_of_every_tile_and_near_only_tiles_do_not_bind():
|
||||
"""The offset range is where the linear map holds for the NEAREST solid terrain each card draws in each tile (ruling ridge-offset-range-fit), not its median: a tile whose card 0 spans 600 to 2000 m has its median near 1200 m, and at the r_max the median would give the 600 m pixels err past FIT_PX_MAX.
|
||||
So the fit at every tile's nearest solid pixel is within the bound at r_max_m (over the circle) and at r_max_forward_m (phi 0), and the bound is reached: a little more offset breaks it at the binding tile. A tile whose card 0 draws only wall (the skirt, at the near clip) has no terrain and binds nothing."""
|
||||
So the fit at every tile's nearest solid pixel is within the bound at r_max_m (over the circle) and at r_max_forward_m (phi 0), and the bound is reached: a little more offset breaks it at the binding tile. A tile whose card 0 draws only near ground (under the clip) has no terrain and binds nothing."""
|
||||
b = _toy(); cs = [[dict(c) for c in tile] for tile in b['cards']]; c = dict(cs[7][0]); n = c['alpha'].shape[1]
|
||||
ld = np.log(np.linspace(600.0, 2000.0, n))[None, :].repeat(c['alpha'].shape[0], 0).astype(np.float32); cs[7][0] = dict(c, logd=ld)
|
||||
bad = dict(cs[5][0]); cs[5][0] = dict(bad, wall=np.ones_like(bad['wall']), logd=np.full_like(bad['logd'], math.log(500.0))) # tile 5: card 0 is all skirt
|
||||
bad = dict(cs[5][0]); cs[5][0] = dict(bad, near=np.ones_like(bad['near']), logd=np.full_like(bad['logd'], math.log(300.0))) # tile 5: card 0 is all near ground
|
||||
pk = export.pack(dict(b, cards=cs)); r, rf = pk['camera']['r_max_m'], pk['camera']['r_max_forward_m']; ppd = ridge.HPX_DEG; worst = worst_f = 0.0; seen = 0
|
||||
for t, tile in enumerate(cs):
|
||||
for i, card in enumerate(tile):
|
||||
d = _nearest_solid(card)
|
||||
if d is None: assert (t, i) == (5, 0), ('a tile has no solid terrain but was not made all skirt', t, i); continue
|
||||
if d is None: assert (t, i) == (5, 0), ('a tile has no solid terrain but was not made all near ground', t, i); continue
|
||||
seen += 1; assert export.fit_px(d, r, ppd) <= export.FIT_PX_MAX + 1e-6 and export.fit_px(d, rf, ppd, 1) <= export.FIT_PX_MAX + 1e-6, ('the nearest terrain of a tile is outside the fit bound', t, i, d, r, rf)
|
||||
worst, worst_f = max(worst, export.fit_px(d, r + 0.5, ppd)), max(worst_f, export.fit_px(d, rf + 0.5, ppd, 1))
|
||||
assert seen == 32 * 3 - 1 and worst > export.FIT_PX_MAX and worst_f > export.FIT_PX_MAX, ('the range stops short of the bound of the nearest terrain', worst, worst_f)
|
||||
assert abs(pk['tiles'][7][0]['distance_m'] - float(np.exp(np.median(np.log(np.linspace(600.0, 2000.0, n)))))) < 1.0, 'the manifest distance is still the median'
|
||||
assert r < export.solve_r_max([[1200.0 if (t, i) == (7, 0) else None for i in range(3)] for t in range(32)], [[100] * 3 for _ in range(32)], ppd) - 5, 'the range is the median model'
|
||||
skirt_free = export.pack(_toy()); assert pk['camera']['r_max_m'] < skirt_free['camera']['r_max_m'], 'the 600 m pixels do not bind'
|
||||
only = export.pack(dict(b, cards=[[dict(cs[t][i]) if (t, i) != (7, 0) else dict(b['cards'][7][0]) for i in range(3)] for t in range(32)])); assert only['camera'] == skirt_free['camera'], ('a skirt-only tile binds r_max', only['camera'], skirt_free['camera'])
|
||||
near_free = export.pack(_toy()); assert pk['camera']['r_max_m'] < near_free['camera']['r_max_m'], 'the 600 m pixels do not bind'
|
||||
only = export.pack(dict(b, cards=[[dict(cs[t][i]) if (t, i) != (7, 0) else dict(b['cards'][7][0]) for i in range(3)] for t in range(32)])); assert only['camera'] == near_free['camera'], ('a near-only tile binds r_max', only['camera'], near_free['camera'])
|
||||
def test_the_near_clip_compare_does_not_depend_on_float32_rounding():
|
||||
"""A card 0 exactly at the near clip is accepted whatever the clip's value: exp of a float32 ln 700 is 699.99994, which a strict compare against a 700 m clip refuses; one 1.5 per mille under the clip is still refused."""
|
||||
saved = ridge.NEAR_CLIP_M; d = tempfile.mkdtemp()
|
||||
|
|
@ -566,6 +573,74 @@ def test_the_near_clip_and_the_ground_rows_are_refused_at_the_writer():
|
|||
except ValueError as e: assert 'GROUND_ROWS_MIN' in str(e), str(e)
|
||||
else: assert False, 'validate_manifest accepted a short plane'
|
||||
finally: shutil.rmtree(d)
|
||||
# ---------------------------------------------------------------------------------------- the near ground: the place's own terrain under the clip, drawn by card 0 inside the clip's silhouette
|
||||
def _blend(L, ld, arr, x):
|
||||
"""arr (K, n) read at hits of log-distance ld (between the samples of log-distance L), blended by the fraction between the two samples: what ridge.cards does for a normal."""
|
||||
kk = np.searchsorted(L, ld, 'left'); kp = np.maximum(kk - 1, 0); t = np.clip((ld - L[kp]) / np.maximum(L[kk] - L[kp], 1e-12), 0, 1); return arr[kp, x] + t * (arr[kk, x] - arr[kp, x])
|
||||
def test_near_ground_draws_inside_the_clip_silhouette():
|
||||
"""Eye 1.6 m over flat ground, a ramp hill at 150-300 m rising to 60 m (its crest stands far above the angle of the clip sample) and a far ridge in half the ring: card 0 composites to the opaque view of the FAR march (the hill above the clip line is not drawn; without the cap it stands above the far ridge),
|
||||
its rows are near ground, not wall, and their normals are normals(dn, hn) of the near march blended at the hit (the ramp's, not the far sample 0's)."""
|
||||
saved = ridge.P.get('eye_m'); ridge.P.update(eye_m=1.6)
|
||||
try:
|
||||
far = block(36, 359.99, 20000, 21500, 1500); hf = lambda dk, az: np.maximum(np.where((dk >= 150) & (dk < 300), 0.4 * (dk - 150), 0.0), np.asarray(far(dk, az), float))
|
||||
A, Hh = rays(hf, eye=1.6); a, h = ridge.prefilter(D, Hh, 0.0); ridge.set_view(a.max(0)); near = near_rays(hf); Dj, Aj, Hj, Nj = ridge.join_near(D, a, h, near); aw, hw, nj = _w(Aj), _w(Hj), tuple(_w(x) for x in Nj)
|
||||
c = ridge.cards(Dj, aw, hw, np.zeros((0, NW)), nj)[0]; comp = _canvas(c); opq = ridge.opaque(_w(a)); err = np.abs(comp - opq).max(); assert err < export.COVER_TOL, ('card 0 draws outside the silhouette of the terrain at the clip', err)
|
||||
free = ridge.cards(Dj, _w(np.concatenate([near[1], a])), hw, np.zeros((0, NW)), nj)[0]; assert np.abs(_canvas(free) - opq).max() > 5 * export.COVER_TOL, 'the fixture cannot tell a hill above the clip line (the cap is not tested)'
|
||||
x = 300; al, nrr, wl, ld = c['alpha'][:, x], c['near'][:, x], c['wall'], c['logd'][:, x]; sel = (al > 0.99) & nrr; assert sel.sum() > 20 and not wl.any(), ('card 0 has wall rows', int(wl.sum()), int(sel.sum())); assert nrr[al > 0.5].mean() > 0.9, 'the rows under the clip are not flagged near'
|
||||
L = np.log(Dj); q = ld[sel].astype(np.float64); want = np.stack([_blend(L, q, nj[0], x), _blend(L, q, nj[1], x), _blend(L, q, nj[2], x)]); m = np.sqrt((want ** 2).sum(0))
|
||||
assert np.abs(c['n_r'][sel, x] - want[0] / m).max() < 2e-3 and np.abs(c['n_t'][sel, x] - want[1] / m).max() < 2e-3, 'a near row has not its own normal'; assert (np.abs(c['n_r'][sel, x]) > 0.5).sum() > 5, 'the fixture has no ramp rows'
|
||||
finally: ridge.P.update(eye_m=saved)
|
||||
def test_near_ground_has_the_material_and_relief_of_its_own_heights():
|
||||
"""Near heights stepping in blocks of 20 columns across the grass, forest and rock thresholds (100, 1000, 2100 m, the forest block a 45 degree hill) while the far march stands at 1000 m everywhere: every near row carries albedo(its own height, its own n_up), so the blocks differ where the ground does, and the hill face is steep (n_up < 0.93) and rock."""
|
||||
dn = ridge.near_schedule(); K, Kn = len(D), len(dn); a = np.tile(np.linspace(5.0, 12.0, K)[:, None], (1, W)); h = np.full((K, W), 1000.0); blk = (np.arange(W) // 20) % 3; base = np.array([100.0, 1000.0, 2100.0])[blk]
|
||||
hn = np.broadcast_to(base[None, :], (Kn, W)).copy(); hn[:, blk == 1] += dn[:, None]; an = np.tile(np.linspace(-8.0, 5.0, Kn)[:, None], (1, W)); ridge.P.update(eye_m=EYE); ridge.set_view(a.max(0))
|
||||
Dj, Aj, Hj, Nj = ridge.join_near(D, a, h, (dn, an, hn)); assert all(np.array_equal(u[Kn:], w) for u, w in zip(Nj, ridge.normals(D, h))), 'the far normals are not those of the far march alone'
|
||||
c = ridge.cards(Dj, _w(Aj), _w(Hj), np.zeros((0, NW)), tuple(_w(x) for x in Nj))[0]; up = np.sqrt(np.clip(1 - c['n_r'] ** 2 - c['n_t'] ** 2, 0, 1)); got = {}
|
||||
for x in range(NW):
|
||||
if not 3 <= x % 20 <= 16: continue
|
||||
sel = (c['alpha'][:, x] > 0.99) & c['near'][:, x] & (c['logd'][:, x] < math.log(ridge.NEAR_CLIP_M) - 1e-6); assert sel.sum() > 50, ('no near rows', x) # the crest row that meets the clip sample itself is not under the clip
|
||||
if blk[x] == 1: assert up[sel, x].max() < 0.93 and np.abs(c['albedo'][sel, x] - np.asarray(ridge.ROCK)).max() < 1e-4, ('the hill face is not steep rock', x, float(up[sel, x].max()))
|
||||
else: assert np.abs(c['albedo'][sel, x] - ridge.albedo(np.full(int(sel.sum()), base[x]), up[sel, x])).max() < 1e-5, ('a near row has not the material of its own height', x)
|
||||
got[blk[x]] = c['albedo'][sel, x].mean(0)
|
||||
assert np.abs(got[0] - got[1]).max() > 0.05 and np.abs(got[1] - got[2]).max() > 0.05 and np.abs(got[0] - got[2]).max() > 0.05, ('the blocks do not differ where the ground does', got)
|
||||
def test_near_pixels_are_not_measured():
|
||||
"""pack of a bake with near rows (card 0, one tile: its lower third is near ground at 150 m) equals in every distance_m and in the camera pack of the same bake with those pixels cut out; a tile whose card 0 is near only gets distance_m == NEAR_CLIP_M and binds nothing, and write_bake accepts it."""
|
||||
b = _toy(dists=(520.0, 15000.0, 50000.0)); base = export.pack(b); cs = [[dict(c) for c in tile] for tile in b['cards']]; c = cs[3][0]; n = c['alpha'].shape[0]; near = np.zeros_like(c['near']); near[n * 2 // 3:] = True
|
||||
cs[3][0] = dict(c, near=near, logd=np.where(near, math.log(150.0), c['logd']).astype(np.float32)); a = export.pack(dict(b, cards=cs))
|
||||
cs[3][0] = dict(c, alpha=np.where(near, 0.0, c['alpha']).astype(np.float32)); cut = export.pack(dict(b, cards=cs)); dists = lambda pk: [[e and e['distance_m'] for e in row] for row in pk['tiles']]
|
||||
assert dists(a) == dists(cut) == dists(base) and a['camera'] == cut['camera'] == base['camera'], ('near pixels were measured', a['camera'], cut['camera'])
|
||||
cs[3][0] = c; only = dict(cs[9][0]); cs[9][0] = dict(only, near=np.ones_like(only['near']), logd=np.full_like(only['logd'], math.log(300.0))); ob = dict(b, cards=cs); pk = export.pack(ob); d = tempfile.mkdtemp()
|
||||
try:
|
||||
assert pk['tiles'][9][0]['distance_m'] == ridge.NEAR_CLIP_M and pk['camera'] == base['camera'] and pk['tiles'][8][0]['distance_m'] == base['tiles'][8][0]['distance_m'], ('a near-only tile', pk['tiles'][9][0]['distance_m'], pk['camera'])
|
||||
assert _write(d + '/ok', ob, pk).exists(), 'a bake with a near-only tile was refused'
|
||||
finally: shutil.rmtree(d)
|
||||
def test_cards_refuses_a_march_without_the_near_ground():
|
||||
"""ridge.cards on a march whose first sample is the near clip (not joined to the near march) raises, naming join_near: card 0 can never extrude the clip sample again."""
|
||||
A, Hh = rays(THREE); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0))
|
||||
try: ridge.cards(D, _w(A), _w(Hh), np.zeros((0, NW)))
|
||||
except ValueError as e: assert 'join_near' in str(e), str(e)
|
||||
else: assert False, 'cards drew a march that starts at the near clip'
|
||||
def test_near_march_starts_at_your_feet():
|
||||
"""The near march starts at NEAR_START_M = 1 m, strictly increasing in steps of max(1 m, 0.02 d) up to 10 m, its last sample under the clip; over flat ground with a 1.6 m eye and a frame bottom below -8 degrees (the ray of the frame bottom meets the ground 11 m out) card 0 has no wall row and draws the ground to the bottom row."""
|
||||
dn = ridge.near_schedule(); st = np.diff(dn); assert dn[0] == ridge.NEAR_START_M == 1.0 and (st > 0).all() and dn[-1] < ridge.NEAR_CLIP_M and dn[-1] + 10.0 >= ridge.NEAR_CLIP_M and 150 < len(dn) < 190, (dn[0], len(dn))
|
||||
assert np.allclose(st, np.clip(0.02 * dn[:-1], 1.0, 10.0)), 'the steps are not max(1 m, 0.02 d) capped at 10 m'
|
||||
saved = ridge.P.get('eye_m'); ridge.P.update(eye_m=1.6)
|
||||
try:
|
||||
hf = lambda dk, az: np.zeros_like(az); A, Hh = rays(hf, eye=1.6); a, h = ridge.prefilter(D, Hh, 0.0); sk = np.full(W, -5.0); sk[::2] = 2.0; ridge.set_view(sk); assert ridge.BOTTOM_DEG < -8.0, ridge.BOTTOM_DEG
|
||||
Dj, Aj, Hj, Nj = ridge.join_near(D, a, h, near_rays(hf)); c = ridge.cards(Dj, _w(Aj), _w(Hj), np.zeros((0, NW)), tuple(_w(x) for x in Nj))[0]
|
||||
assert not c['wall'].any() and c['near'].any(), ('card 0 has wall under the frame bottom', int(c['wall'].sum())); assert _canvas(c)[H - 1, 300] > 0.99 and c['near'][H - 1 - c['top'], 300], 'the bottom row is not near ground'
|
||||
finally: ridge.P.update(eye_m=saved)
|
||||
def test_near_march_is_float64_and_prefiltered():
|
||||
"""near_march over an injected 64 x 64 mosaic: a plane tilted 5% at 3000 m gives adjacent-column near normals within 1e-3 of each other (heights in float32 would jump by 0.1 at a metre's distance); 30 m roof blocks under sigma 100 leave near heights within 2 m of each other, and without the prefilter they do not."""
|
||||
saved = (ridge.P, ridge.PXDEG_V); lat, lon = 47.0, 11.0; n = 64; ridge.P = dict(id='nearmos', lat=lat, lon=lon, rmax_km=1, eye_m=3001.6); key = (ridge.P['id'], ridge.mosaic_key(ridge.P)); ridge.PXDEG_V = 100.0
|
||||
x = np.arange(n)[None, :] * (111320.0 * math.cos(math.radians(lat)) / 3600.0); y = np.arange(n)[:, None]
|
||||
try:
|
||||
ridge._mos[key] = ((3000.0 + 0.05 * x + 0 * y).astype(np.float32), lat + 32 / 3600.0, lon - 32 / 3600.0); dn, an, hn = ridge.near_march(0.0); nn = ridge.normals(dn, hn)
|
||||
assert hn.dtype == np.float64 and an.dtype == np.float64 and hn.shape == (len(ridge.near_schedule()), W) and (dn == ridge.near_schedule()).all(), (hn.dtype, hn.shape)
|
||||
assert max(np.abs(np.diff(nn[0], axis=1)).max(), np.abs(np.diff(nn[1], axis=1)).max()) < 1e-3, ('the near normals jump between adjacent columns', float(np.abs(np.diff(nn[1], axis=1)).max()))
|
||||
ridge._mos[key] = ((3000.0 + 30.0 * ((np.arange(n)[None, :] + y) % 2)).astype(np.float32), lat + 32 / 3600.0, lon - 32 / 3600.0); raw = np.ptp(ridge.near_march(0.0)[2]); flat = np.ptp(ridge.near_march(100.0)[2])
|
||||
assert raw > 20.0 and flat < 2.0, ('sigma is not applied to the near heights', raw, flat)
|
||||
finally: ridge.P, ridge.PXDEG_V = saved; ridge._mos.pop(key, None)
|
||||
# ---------------------------------------------------------------------------------------- rules that no other test touched
|
||||
def test_seams_keep_their_separation():
|
||||
"""Two authored targets closer than SEAM_SEP (6 and 7 km, 0.15 nat): the seams still sit at least 0.4 nat apart in every column."""
|
||||
|
|
@ -584,9 +659,9 @@ def test_coverage_counts_every_visible_row_including_the_foreground():
|
|||
def test_cards_interpolate_between_samples_and_renormalise():
|
||||
"""On a ramp face every card pixel sits between two samples: its log-distance lies strictly between theirs (not on the nearer sample), and its normal is the normalised blend of theirs by that same fraction (the samples carry alternating normals, so a blend
|
||||
that is not renormalised, or a hit that is not interpolated, differs)."""
|
||||
A, Hh = rays(terrain(lambda dk, az: np.where(dk >= 4000, GROUND + 0.5 * (dk - 4000), 0.0) + 0 * az)); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = _w(A), _w(Hh); k = np.arange(len(D))[:, None]
|
||||
hf = terrain(lambda dk, az: np.where(dk >= 4000, GROUND + 0.5 * (dk - 4000), 0.0) + 0 * az); A, Hh = rays(hf); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); Dj, aw, hw, _ = _join(hf, A, Hh); k = np.arange(len(Dj))[:, None]
|
||||
nr = np.broadcast_to(np.where(k % 2 == 0, -0.8, 0.8), aw.shape).astype(float); nt = np.broadcast_to(np.where(k % 3 == 0, 0.3, -0.3), aw.shape).astype(float); nu = np.sqrt(1 - nr ** 2 - nt ** 2) * 0 + 0.5
|
||||
c = ridge.cards(D, aw, hw, np.zeros((0, NW)), nrm=(nr, nt, nu))[0]; x = 300; sel = np.flatnonzero(c['alpha'][:, x] > 0.999); ld = c['logd'][sel, x].astype(np.float64); L = np.log(D); kk = np.searchsorted(L, ld, 'left'); kp = kk - 1; ok = kp >= 0
|
||||
c = ridge.cards(Dj, aw, hw, np.zeros((0, NW)), nrm=(nr, nt, nu))[0]; x = 300; sel = np.flatnonzero(c['alpha'][:, x] > 0.999); ld = c['logd'][sel, x].astype(np.float64); L = np.log(Dj); kk = np.searchsorted(L, ld, 'left'); kp = kk - 1; ok = kp >= 0
|
||||
t = (ld - L[np.maximum(kp, 0)]) / (L[kk] - L[np.maximum(kp, 0)]); inner = ok & (t > 0.02) & (t < 0.98); assert inner.sum() > 0.3 * len(sel), ('hits sit on samples, not between them', int(inner.sum()), len(sel))
|
||||
mix = lambda arr: arr[np.maximum(kp, 0), x] + t * (arr[kk, x] - arr[np.maximum(kp, 0), x]); m = np.sqrt(mix(nr) ** 2 + mix(nt) ** 2 + mix(nu) ** 2); er = np.abs(c['n_r'][sel, x] - mix(nr) / m)[inner]; et = np.abs(c['n_t'][sel, x] - mix(nt) / m)[inner]
|
||||
assert er.max() < 1e-3 and et.max() < 1e-3, ('the normal is not the normalised blend of the two samples', er.max(), et.max())
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import { groundRowsNeeded, HFOV_MAX_DEG } from './view';
|
|||
export const TILE_BYTES_MAX = 235_000;
|
||||
export const PLACE_BYTES_MAX = 7_500_000;
|
||||
export const RESIDENT_BYTES_MAX = 20_000_000;
|
||||
/** As ridge.py NEAR_CLIP_M: the march's first sample, so no terrain is nearer. */
|
||||
/** As ridge.py NEAR_CLIP_M: the far march's first sample; card 0's distance_m is measured at or beyond it (the near ground under it is not measured). */
|
||||
export const NEAR_CLIP_M = 500;
|
||||
|
||||
interface WireFile {
|
||||
|
|
|
|||
Loading…
Reference in a new issue