Add ground fills to the globe contract

engine.ground draws sets of polygons (with holes), discs, cells and
corridors draped on the surface, with fill and outline colours, order and
picks, written in bulk and committed. Every engine implements it:

- Cesium batches each set into one GroundPrimitive for fills and one
  GroundPolylinePrimitive for outlines and pixel corridors, classified
  against terrain and 3D tiles; sets that are not pickable stay out of the
  pick pass.
- Navara draws them in one screen pass after tone mapping that finds each
  pixel's ground from the scene depth and tests the items in its screen
  cell; long rings are split into edge bins. Measured at Dubai against
  SDK vector layers, the pass matched Cesium's frame time up to 10,000
  polygons with a few megabytes instead of 70 to 146, drew exact colours
  and outlines, and hid reliably across an engine switch, where vector
  layers hidden with update({ show: false }) never hid. Dense corridors
  remain its limit (10,000 cost 135 ms a frame).
- The fake engine keeps the same registry and CPU picks.

The contract suite checks it on both engines (Cesium 66/66, Navara 69/69).
Earthquakes and fire perimeters have unwired ground prototypes whose
drawing matches today's Cesium one (0.998 on Cesium, 0.976 on Navara).
docs/GLOBE-PRIMITIVES.md describes the primitives and when to use each.
This commit is contained in:
German Khokhlov committed 2026-11-07 05:14:42 +04:00
1 parent 6dc643182e
commit 974a0b6361
27 files changed
+5256 -685

No files matched your search

+25 -1
View File
@@ -27,6 +27,7 @@ import { createNavaraCredits } from './credits.js';
import { createNavaraInput } from './input.js';
import { createNavaraPicking } from './picking.js';
import { createFollowController } from '../follow.js';
import { createGroundPicks } from '../ground.js';
import { navaraFollowGestures } from './followGestures.js';
import { createNavaraMaps } from './maps.js';
import { createNavaraSurface } from './surface.js';
@@ -47,6 +48,12 @@ const NO_LINES = Object.freeze({
},
list: () => [],
});
const NO_GROUND = Object.freeze({
createSet() {
throw new Error("Navara ground needs the view's three runtime (ground/)");
},
list: () => [],
});
// Navara's drawn camera (view.camera.raw, a three PerspectiveCamera in
// Earth-fixed metres): matrixWorld columns are right, up, back, position.
@@ -89,7 +96,8 @@ function readCamera(raw) {
* `appClock` (the engine clock's time) defaults to the page's app clock;
* `movers` is engine.movers on the view's three runtime (movers/index.js;
* without it createSet throws), `lines` engine.lines (lines/index.js;
* likewise), both destroyed with the engine;
* likewise), `ground` engine.ground (ground/index.js; likewise), all
* destroyed with the engine;
* `fetch` and `clock` (the camera model's timers) are test seams.
* @returns {import('../contract.js').GlobeEngine}
*/
@@ -103,6 +111,7 @@ export function createNavaraEngine(
appClock,
movers: moversPort = null,
lines: linesPort = null,
ground: groundPort = null,
sharpen: sharpenPort = null,
styles: stylesPort = null,
bloom: bloomPort = null,
@@ -228,6 +237,16 @@ export function createNavaraEngine(
...(clock ? { now: () => clock.now() } : {}),
});
// Ground items are picked on the CPU at the globe under the pointer
// (src/globe/ground.js), under every mover and line.
const removeGroundPicks = picking.registerMeshPicker(
createGroundPicks({
pickGlobe: (screen) => picker.pickGlobe(screen),
camera: model.camera,
size,
sets: () => groundPort?.pickables?.() ?? [],
}),
);
const picker = {
// Navara mesh owners supply exact triangle hits for sync/hover/click picks.
registerMeshPicker: (pick) => picking.registerMeshPicker(pick),
@@ -394,6 +413,7 @@ export function createNavaraEngine(
clock: engineClock.clock,
movers: moversPort?.movers ?? NO_MOVERS,
lines: linesPort?.lines ?? NO_LINES,
ground: groundPort?.ground ?? NO_GROUND,
destroy() {
if (destroyed) return;
destroyed = true;
@@ -402,6 +422,7 @@ export function createNavaraEngine(
follow.destroy();
model.destroy();
input.destroy();
removeGroundPicks();
picking.destroy();
credits.destroy();
maps.destroy();
@@ -412,6 +433,7 @@ export function createNavaraEngine(
sonarPort?.destroy();
moversPort?.destroy();
linesPort?.destroy();
groundPort?.destroy();
},
isDestroyed: () => destroyed,
// Navara only, not contract: the post pipeline as QA reads it (the
@@ -426,6 +448,8 @@ export function createNavaraEngine(
passes: styles?.passes ?? glow?.passes ?? null,
};
},
// Navara only, not contract: what the ground pass holds (QA reads it).
groundDiagnostics: () => groundPort?.diagnostics?.() ?? null,
// Navara only, not contract: the ground the floor last sampled under
// the camera and the margin it keeps above it (QA measures against it).
groundFloor: {
+107
View File
@@ -0,0 +1,107 @@
// engine.ground on Navara: every shown set in one screen pass (pass.js),
// classified on the scene depth, so fills drape on terrain and 3D tiles
// alike. A commit packs the set's items once (pack.js), with the terrain
// heights under them that bound each item's screen box; a set packed before
// its terrain loaded is packed again a few times, further apart each time,
// until it has them. A show, hide or commit composes the shown sets in draw
// order (set order, then creation) and asks for one frame. Nothing animates
// on its own. Picks are CPU picks at the globe under the pointer
// (src/globe/ground.js), wired by the engine.
import { createGroundRegistry } from '../../ground.js';
import { composeGround, packSet } from './pack.js';
// Frames before the first new try at a set's missing terrain heights; each
// later try waits twice as long, up to RETRIES tries.
const RETRY_FRAMES = 30;
const RETRIES = 6;
/**
* @param {object} view an initialised Navara ThreeView
* @param {{ createPass: (view: object) => ReturnType<typeof import('./pass.js').createGroundPass> }} options
* `createPass` makes the pass (pass.js createGroundPass; the view's three
* runtime, which Node tests replace).
* @returns {{ ground: import('../../contract.js').GlobeGround,
* pickables: () => object[], diagnostics: () => object, destroy: () => void }}
*/
export function createNavaraGround(view, { createPass }) {
const pass = createPass(view);
const entries = new Set();
const terrainHeight = (lon, lat) => {
const height = view.sampleTerrainHeight?.({ lat, lng: lon });
return Number.isFinite(height) ? height : undefined;
};
const pack = (entry) => {
entry.pack = packSet(entry.options.kind, entry.items, { terrainHeight });
entry.wait = entry.pack.heights.some(Number.isNaN) ? RETRY_FRAMES : 0;
};
const compose = () => {
const drawn = [...entries]
.filter((entry) => entry.shown && entry.pack?.count)
.sort((a, b) => a.options.order - b.options.order);
pass.set(
drawn.length ? composeGround(drawn.map(({ pack }) => pack)) : null,
);
view.forceUpdate();
};
const retry = () => {
let changed = false;
for (const entry of entries) {
if (!entry.wait || !entry.shown || --entry.wait > 0) continue;
const tries = entry.tries + 1;
pack(entry);
entry.tries = tries;
if (entry.wait)
entry.wait = tries < RETRIES ? RETRY_FRAMES * 2 ** tries : 0;
changed = true;
}
if (changed) compose();
};
view.on('postRender', retry);
const registry = createGroundRegistry((options) => {
const entry = {
options,
shown: true,
items: [],
pack: null,
tries: 0,
wait: 0,
};
entries.add(entry);
return {
commit(items) {
entry.items = items;
entry.tries = 0;
pack(entry);
compose();
},
show(visible) {
if (entry.shown === visible) return;
entry.shown = visible;
compose();
},
destroy() {
entries.delete(entry);
// A set object still held keeps no packed data.
entry.items = [];
entry.pack = null;
compose();
},
};
});
return {
ground: registry.ground,
/** Every live set's state ({ options, items, shown }) for CPU picks. */
pickables: () => [...registry.live.values()],
/** Not contract: what the pass holds (QA measures it). */
diagnostics: () => ({
items: pass.owner.state?.count ?? 0,
textureBytes: pass.textureBytes(),
}),
destroy() {
view.off('postRender', retry);
registry.destroyAll();
pass.destroy();
},
};
}
+89
View File
@@ -0,0 +1,89 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createNavaraGround } from './index.js';
function fakeView({ height = () => 12 } = {}) {
const listeners = new Map();
return {
frames: 0,
on: (name, listener) => listeners.set(name, listener),
off: (name) => listeners.delete(name),
forceUpdate() {
this.frames++;
},
sampleTerrainHeight: ({ lat, lng }) => height(lng, lat),
postRender: () => listeners.get('postRender')?.(),
listening: () => listeners.size,
};
}
function fakePass() {
const states = [];
return {
states,
owner: { state: null },
set(state) {
states.push(state);
this.owner.state = state;
},
textureBytes: () => 0,
destroyed: false,
destroy() {
this.destroyed = true;
},
};
}
const square = (lon) => ({
rings: [
[
[lon, 0],
[lon + 1, 0],
[lon + 1, 1],
],
],
fill: [1, 0, 0, 1],
});
test('shown sets compose in order into one pass; hiding all hides it', () => {
const view = fakeView();
const pass = fakePass();
const ground = createNavaraGround(view, { createPass: () => pass });
const top = ground.ground.createSet({ id: 'top', kind: 'polygon', order: 1 });
const bottom = ground.ground.createSet({ id: 'bottom', kind: 'polygon' });
top.replace([square(0)]);
top.commit();
bottom.replace([square(2), square(4)]);
bottom.commit();
const state = pass.states.at(-1);
assert.equal(state.count, 3);
assert.ok(view.frames >= 2, 'each change asks for a frame');
top.show(false);
bottom.show(false);
assert.equal(pass.states.at(-1), null);
bottom.show(true);
assert.equal(pass.states.at(-1).count, 2);
assert.equal(ground.pickables().length, 2);
ground.destroy();
assert.equal(pass.destroyed, true);
assert.equal(view.listening(), 0);
});
test('a set packed before its terrain loaded is packed again later', () => {
let loaded = false;
const view = fakeView({ height: () => (loaded ? 30 : undefined) });
const pass = fakePass();
const ground = createNavaraGround(view, { createPass: () => pass });
const set = ground.ground.createSet({ id: 'zones', kind: 'polygon' });
set.replace([square(0)]);
set.commit();
const before = pass.states.length;
for (let frame = 0; frame < 29; frame++) view.postRender();
assert.equal(pass.states.length, before, 'not before 30 frames');
loaded = true;
view.postRender();
assert.equal(pass.states.length, before + 1, 'packed again with heights');
for (let frame = 0; frame < 500; frame++) view.postRender();
assert.equal(pass.states.length, before + 1, 'no more once it has them');
ground.destroy();
});
+616
View File
@@ -0,0 +1,616 @@
// The data of Navara's ground pass (pass.js), without three: each item in a
// gnomonic frame of its own (the tangent plane at its centre, reached along
// rays from the Earth's centre, where great-circle edges are straight
// lines), its boundary as segments in that plane, in float64 until the
// numbers are small; per camera change the frames in view space, each
// item's conservative screen box and a screen grid of candidate items,
// kept in draw order.
import * as geo from '../../../geo/index.js';
import { cellRing } from '../../ground.js';
const { cartesian3 } = geo;
/** Item kinds as the shader reads them. */
export const KIND = Object.freeze({
area: 0,
disc: 1,
corridorPx: 2,
corridorM: 3,
});
export const GRID_COLS = 64;
export const GRID_ROWS = 40;
/** RGBA32F texels per pass item in the frame texture. */
export const TEXELS = 4;
/** RGBA32F texels per pass item in the style texture. */
export const STYLE_TEXELS = 6;
/** An area of more segments than this gets a grid of bins (binArea). */
export const BIN_THRESHOLD = 32;
const MAX_BINS = 32;
/** Segments of a corridor drawn as one pass item. */
export const CORRIDOR_CHUNK = 4;
/** Texture rows hold this many texels. */
export const ROW = 1024;
// Highest ground above the ellipsoid a fill reaches (the item's volume).
const CEILING_M = 9000;
// Lowest: Navara's globe mesh can lie well under the ellipsoid at orbital
// detail (−26 km measured over Alaska); Cesium's GroundPrimitive floor.
const FLOOR_M = -100000;
// The floor of an item's screen box: as deep as the terrain's level of
// detail can put the ground at that distance (a kilometre plus 5 % of the
// distance), down to FLOOR_M. A box to −100 km for a near item streaks
// across the screen and makes it a candidate of cells it never covers.
const nearFloor = (distance) => -Math.min(-FLOOR_M, 1000 + 0.05 * distance);
// Where the terrain under an item was sampled, its box spans the sampled
// heights, less the error of the terrain's level of detail at that distance
// (100 m plus 2 %) below, and above that error plus room for 3D tiles'
// buildings over the terrain.
// Terrain is sampled on a grid of 0.005° (about 500 m), and the box
// widened by 350 m each way for the slopes between samples.
const SAMPLE_STEP_DEG = 0.005;
const lodMargin = (distance) => 450 + 0.02 * distance;
const TILE_HEADROOM_M = 900;
/** Terrain samples per pass item. */
const SAMPLES = 9;
const CELL_STEP_DEG = 0.25;
function frameAt(lon, lat) {
const center = cartesian3.fromDegrees(lon, lat);
const radius = cartesian3.magnitude(center);
const up = cartesian3.divideByScalar(center, radius, cartesian3.create());
const east = cartesian3.normalize(
cartesian3.create(-center.y, center.x, 0),
cartesian3.create(),
);
if (!Number.isFinite(east.x)) Object.assign(east, { x: 1, y: 0, z: 0 });
const north = cartesian3.cross(up, east, cartesian3.create());
const scratch = cartesian3.create();
// A ground position in the frame's gnomonic plane, metres.
const project = (lonDeg, latDeg) => {
cartesian3.fromDegrees(lonDeg, latDeg, 0, undefined, scratch);
const dx = scratch.x - center.x;
const dy = scratch.y - center.y;
const dz = scratch.z - center.z;
const scale = radius / (radius + dx * up.x + dy * up.y + dz * up.z);
return [
(dx * east.x + dy * east.y + dz * east.z) * scale,
(dx * north.x + dy * north.y + dz * north.z) * scale,
];
};
return { center, radius, up, east, north, project };
}
// A path's points in a frame's plane.
const planePoints = (flat, project) => {
const points = [];
for (let index = 0; index < flat.length; index += 2)
points.push(project(flat[index], flat[index + 1]));
return points;
};
/**
* A grid of square bins over an area's segments (flat [ax, ay, bx, by, …]
* in its plane) when it has more than BIN_THRESHOLD: the grid covers the
* segments' bounds and half a bin round them; each bin lists the segments
* that reach within half a bin of it and whether its centre is inside the
* area (even-odd). A pixel then tests only its bin's segments: the nearest
* one, and the crossings between it and the bin's centre. Null for a
* smaller area.
*/
export function binArea(list) {
const count = list.length / 4;
if (count <= BIN_THRESHOLD) return null;
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (let index = 0; index < list.length; index += 2) {
minX = Math.min(minX, list[index]);
maxX = Math.max(maxX, list[index]);
minY = Math.min(minY, list[index + 1]);
maxY = Math.max(maxY, list[index + 1]);
}
const across = Math.min(
MAX_BINS,
Math.max(2, Math.ceil(Math.sqrt(count / 4))),
);
const size = Math.max(maxX - minX, maxY - minY, 1e-3) / across;
const x = minX - size / 2;
const y = minY - size / 2;
const columns = Math.ceil((maxX - minX + size) / size) || 1;
const rows = Math.ceil((maxY - minY + size) / size) || 1;
const cells = Array.from({ length: columns * rows }, () => []);
const clampTo = (value, max) => Math.min(max - 1, Math.max(0, value));
for (let index = 0; index < count; index++) {
const [ax, ay, bx, by] = list.slice(index * 4, index * 4 + 4);
const x0 = clampTo(
Math.floor((Math.min(ax, bx) - x) / size - 0.5),
columns,
);
const x1 = clampTo(
Math.floor((Math.max(ax, bx) - x) / size + 0.5),
columns,
);
const y0 = clampTo(Math.floor((Math.min(ay, by) - y) / size - 0.5), rows);
const y1 = clampTo(Math.floor((Math.max(ay, by) - y) / size + 0.5), rows);
for (let row = y0; row <= y1; row++)
for (let column = x0; column <= x1; column++)
cells[row * columns + column].push(index);
}
const insideAt = (px, py) => {
let inside = false;
for (let index = 0; index < list.length; index += 4) {
const ay = list[index + 1];
const by = list[index + 3];
if (
ay > py !== by > py &&
px <
((list[index + 2] - list[index]) * (py - ay)) / (by - ay) +
list[index]
)
inside = !inside;
}
return inside;
};
return {
x,
y,
size,
columns,
rows,
bins: cells.map((indices, cell) => ({
count: indices.length,
inside: insideAt(
x + ((cell % columns) + 0.5) * size,
y + (Math.floor(cell / columns) + 0.5) * size,
)
? 1
: 0,
list: indices.flatMap((index) => list.slice(index * 4, index * 4 + 4)),
})),
};
}
/**
* One set's items packed for the pass as pass items: float64 frames, the
* terrain heights under each (`terrainHeight(lon, lat)`, undefined where
* not loaded: that item keeps the deep default box), the
* style texels (segment starts relative to the set's own segments) and the
* segments. A corridor longer than CORRIDOR_CHUNK segments becomes one pass
* item per chunk, each in its own plane with its own screen box; a chunk
* also holds its neighbours' end segments and draws only where its own
* segments are the nearest, so joints blend once.
*/
export function packSet(kind, items, { terrainHeight = null } = {}) {
const frames = [];
const styles = [];
const volumes = [];
const heights = [];
const segments = [];
const bins = [];
// Terrain heights on a grid of SAMPLE_STEP_DEG, each sampled once.
const sampled = new Map();
const heightAt = (lon, lat) => {
const x = Math.round(lon / SAMPLE_STEP_DEG);
const y = Math.round(lat / SAMPLE_STEP_DEG);
const key = x * 1e6 + y;
if (!sampled.has(key))
sampled.set(
key,
terrainHeight?.(x * SAMPLE_STEP_DEG, y * SAMPLE_STEP_DEG),
);
return sampled.get(key);
};
// The lowest and highest terrain under a pass item's sample positions
// (flat [lon, lat, …], at most SAMPLES of them), NaN when unknown.
const sampleHeights = (flat) => {
if (!terrainHeight) return [Number.NaN, Number.NaN];
let low = Infinity;
let high = -Infinity;
const count = flat.length / 2;
const step = Math.max(1, Math.ceil(count / SAMPLES));
for (let index = 0; index < count; index += step) {
const height = heightAt(flat[index * 2], flat[index * 2 + 1]);
if (!Number.isFinite(height)) return [Number.NaN, Number.NaN];
low = Math.min(low, height);
high = Math.max(high, height);
}
return [low, high];
};
const emit = (frame, style, extent, padPx, list, samples, extra = null) => {
heights.push(...sampleHeights(samples));
const start = segments.length / 4;
segments.push(...list);
if (extra) {
// The bins' own segment lists follow the item's, relative to its start.
style.bins[3] = bins.length / 4;
for (const bin of extra.bins) {
bins.push(segments.length / 4 - start, bin.count, bin.inside, 0);
segments.push(...bin.list);
}
}
const radius = extent * (1 + 101000 / frame.radius) + 1;
const floor = FLOOR_M - ((radius * radius) / (2 * frame.radius)) * 1.1;
frames.push(
frame.center.x,
frame.center.y,
frame.center.z,
frame.east.x,
frame.east.y,
frame.east.z,
frame.north.x,
frame.north.y,
frame.north.z,
frame.up.x,
frame.up.y,
frame.up.z,
frame.radius,
);
volumes.push(radius, floor, CEILING_M, padPx + 2);
styles.push(
...style.fill,
...style.line,
...style.shape,
floor,
CEILING_M,
start,
list.length / 4,
...style.bins,
...style.origin,
);
};
const segmentsOf = (points, closed) => {
const list = [];
const last = closed ? points.length : points.length - 1;
for (let index = 0; index < last; index++) {
const a = points[index];
const b = points[(index + 1) % points.length];
list.push(a[0], a[1], b[0], b[1]);
}
return list;
};
const reach = (points) =>
points.reduce((most, [x, y]) => Math.max(most, Math.hypot(x, y)), 0);
for (const item of items) {
const none = [0, 0, 0, 0];
if (kind === 'corridor') {
const code = item.widthM ? KIND.corridorM : KIND.corridorPx;
const segmentCount = item.path.length / 2 - 1;
for (let first = 0; first < segmentCount; first += CORRIDOR_CHUNK) {
const own = Math.min(CORRIDOR_CHUNK, segmentCount - first);
const from = Math.max(0, first - 1);
const to = Math.min(segmentCount, first + own + 1);
const part = item.path.subarray(from * 2, (to + 1) * 2);
let west = Infinity;
let east = -Infinity;
let south = Infinity;
let north = -Infinity;
for (let at = 0; at < part.length; at += 2) {
west = Math.min(west, part[at]);
east = Math.max(east, part[at]);
south = Math.min(south, part[at + 1]);
north = Math.max(north, part[at + 1]);
}
const frame = frameAt((west + east) / 2, (south + north) / 2);
const points = planePoints(part, frame.project);
emit(
frame,
{
fill: item.fill,
line: none,
shape: [code, 0, item.widthPx ?? 0, item.widthM ?? 0],
bins: [first - from, own, 0, 0],
origin: [0, 0, 0, 0],
},
reach(points) + (item.widthM ?? 0) / 2,
(item.widthPx ?? 0) / 2,
segmentsOf(points, false),
part,
);
}
continue;
}
const style = {
fill: item.fill ?? none,
line: item.outline?.color ?? none,
shape: [KIND.area, item.outline?.widthPx ?? 0, 0, 0],
bins: [0, 0, 0, 0],
origin: [0, 0, 0, 0],
};
const padPx = (item.outline?.widthPx ?? 0) / 2;
if (kind === 'disc') {
const frame = frameAt(item.center[0], item.center[1]);
const radius = frame.radius * Math.tan(item.radiusM / frame.radius);
style.shape = [KIND.disc, item.outline?.widthPx ?? 0, 0, radius];
emit(
frame,
style,
radius,
padPx,
[],
Float64Array.of(
...item.center,
item.bounds.west,
item.center[1],
item.bounds.east,
item.center[1],
item.center[0],
item.bounds.south,
item.center[0],
item.bounds.north,
),
);
continue;
}
const { bounds } = item;
const frame = frameAt(
(bounds.west + bounds.east) / 2,
(bounds.south + bounds.north) / 2,
);
const rings = (
kind === 'cell' ? [cellRing(item, CELL_STEP_DEG)] : item.rings
).map((ring) => planePoints(ring, frame.project));
const list = rings.flatMap((ring) => segmentsOf(ring, true));
const binned = binArea(list);
if (binned) {
style.bins = [binned.columns, binned.rows, binned.size, 0];
style.origin = [binned.x, binned.y, 0, 0];
}
emit(
frame,
style,
Math.max(...rings.map(reach)),
padPx,
list,
Float64Array.of(
(bounds.west + bounds.east) / 2,
(bounds.south + bounds.north) / 2,
...(kind === 'cell' ? cellRing(item, CELL_STEP_DEG) : item.rings[0]),
),
binned,
);
}
return {
count: volumes.length / 4,
bins: Float32Array.from(bins),
heights: Float64Array.from(heights),
frames: Float64Array.from(frames),
styles: Float32Array.from(styles),
volumes: Float64Array.from(volumes),
segments: Float32Array.from(segments),
};
}
/** Storage for `texels` RGBA texels in rows of ROW. */
export function texelStorage(texels) {
const width = Math.min(ROW, Math.max(1, texels));
const height = Math.max(1, Math.ceil(texels / width));
return { width, height, data: new Float32Array(width * height * 4) };
}
/** Conservative clip box of an item's volume in view space, or 2s off screen. */
export function clipBounds(view, radius, floor, ceiling, projection, out) {
const p = projection;
let x0 = Infinity;
let y0 = Infinity;
let x1 = -Infinity;
let y1 = -Infinity;
let front = 0;
let behind = 0;
for (let corner = 0; corner < 8; corner++) {
const x = (corner & 1 ? 1 : -1) * radius;
const y = (corner & 2 ? 1 : -1) * radius;
const z = corner & 4 ? ceiling : floor;
const vx = view[0] + view[3] * x + view[6] * y + view[9] * z;
const vy = view[1] + view[4] * x + view[7] * y + view[10] * z;
const vz = view[2] + view[5] * x + view[8] * y + view[11] * z;
const w = p[3] * vx + p[7] * vy + p[11] * vz + p[15];
if (w <= 0) {
behind++;
continue;
}
front++;
const cx = (p[0] * vx + p[4] * vy + p[8] * vz + p[12]) / w;
const cy = (p[1] * vx + p[5] * vy + p[9] * vz + p[13]) / w;
x0 = Math.min(x0, cx);
y0 = Math.min(y0, cy);
x1 = Math.max(x1, cx);
y1 = Math.max(y1, cy);
}
if (front && behind) {
x0 = -1;
y0 = -1;
x1 = 1;
y1 = 1;
}
if (!front || x1 < -1 || y1 < -1 || x0 > 1 || y0 > 1) out.fill(2);
else {
out[0] = Math.max(-1, x0);
out[1] = Math.max(-1, y0);
out[2] = Math.min(1, x1);
out[3] = Math.min(1, y1);
}
return out;
}
/**
* The drawn sets (packSet results, in draw order) as one pass state:
* static textures data (styles, segments) and update(view, projection,
* width, height), which refreshes the frames in view space and the grid
* of candidates when the camera or the viewport changed (true then).
*/
export function composeGround(packs) {
const count = packs.reduce((total, pack) => total + pack.count, 0);
const segmentCount = packs.reduce(
(total, pack) => total + pack.segments.length / 4,
0,
);
const frames64 = new Float64Array(count * 13);
const volumes = new Float64Array(count * 4);
const heights = new Float64Array(count * 2);
const styles = texelStorage(count * STYLE_TEXELS);
const segments = texelStorage(segmentCount);
const bins = texelStorage(
packs.reduce((total, pack) => total + pack.bins.length / 4, 0),
);
let item = 0;
let segment = 0;
let bin = 0;
for (const pack of packs) {
frames64.set(pack.frames, item * 13);
volumes.set(pack.volumes, item * 4);
heights.set(pack.heights, item * 2);
styles.data.set(pack.styles, item * STYLE_TEXELS * 4);
for (let index = 0; index < pack.count; index++) {
const at = (item + index) * STYLE_TEXELS * 4;
styles.data[at + 14] += segment;
// A binned area's first bin.
if (styles.data[at + 8] === KIND.area && styles.data[at + 16] > 0)
styles.data[at + 19] += bin;
}
segments.data.set(pack.segments, segment * 4);
bins.data.set(pack.bins, bin * 4);
item += pack.count;
segment += pack.segments.length / 4;
bin += pack.bins.length / 4;
}
const frames = texelStorage(count * TEXELS);
const grid = {
width: GRID_COLS,
height: GRID_ROWS,
data: new Float32Array(GRID_COLS * GRID_ROWS * 4),
};
let candidates = texelStorage(1);
const counts = new Uint32Array(GRID_COLS * GRID_ROWS);
const offsets = new Uint32Array(counts.length);
const cursor = new Uint32Array(counts.length);
const ranges = new Int32Array(count * 4);
const viewFrame = new Float64Array(12);
const box = new Float64Array(4);
const lastView = new Float64Array(16).fill(Number.NaN);
const lastProjection = new Float64Array(16).fill(Number.NaN);
let lastWidth = 0;
let lastHeight = 0;
const clampTo = (value, max) => Math.min(max - 1, Math.max(0, value));
return {
count,
styles,
segments,
bins,
frames,
grid,
get candidates() {
return candidates;
},
/** True when the frames, grid or candidates changed (upload them). */
update(view, projection, width, height) {
let changed = width !== lastWidth || height !== lastHeight;
for (let index = 0; index < 16 && !changed; index++)
changed =
view[index] !== lastView[index] ||
projection[index] !== lastProjection[index];
if (!changed) return false;
lastView.set(view);
lastProjection.set(projection);
lastWidth = width;
lastHeight = height;
const m = view;
counts.fill(0);
for (let index = 0; index < count; index++) {
const f = index * 13;
// Centre with the translation, axes without; float64 until here.
for (let axis = 0; axis < 4; axis++) {
const x = frames64[f + axis * 3];
const y = frames64[f + axis * 3 + 1];
const z = frames64[f + axis * 3 + 2];
const translate = axis === 0 ? 1 : 0;
viewFrame[axis * 3] =
m[0] * x + m[4] * y + m[8] * z + translate * m[12];
viewFrame[axis * 3 + 1] =
m[1] * x + m[5] * y + m[9] * z + translate * m[13];
viewFrame[axis * 3 + 2] =
m[2] * x + m[6] * y + m[10] * z + translate * m[14];
}
const t = index * TEXELS * 4;
frames.data.set(viewFrame.subarray(0, 3), t);
frames.data[t + 3] = frames64[f + 12];
frames.data.set(viewFrame.subarray(3, 6), t + 4);
frames.data.set(viewFrame.subarray(6, 9), t + 8);
frames.data.set(viewFrame.subarray(9, 12), t + 12);
const v = index * 4;
// The item's extent in its plane and its padding in pixels, for
// the shader's early rejection.
frames.data[t + 7] = volumes[v];
frames.data[t + 11] = volumes[v + 3];
const distance = Math.hypot(viewFrame[0], viewFrame[1], viewFrame[2]);
// Heights relative to the plane's origin on the ellipsoid; the
// plane dips under the curve by r²/2R at the item's edge.
const low = heights[index * 2];
const known = Number.isFinite(low);
const dip = (volumes[v] * volumes[v]) / (2 * frames64[f + 12]);
clipBounds(
viewFrame,
volumes[v],
known
? low - lodMargin(distance) - dip * 1.1
: Math.max(volumes[v + 1], nearFloor(distance)),
known
? heights[index * 2 + 1] + TILE_HEADROOM_M + lodMargin(distance)
: volumes[v + 2],
projection,
box,
);
const r = index * 4;
const valid = box[0] <= 1;
if (!valid) {
ranges[r] = -1;
continue;
}
const padX = (2 * volumes[v + 3]) / Math.max(1, width);
const padY = (2 * volumes[v + 3]) / Math.max(1, height);
ranges[r] = clampTo(
Math.floor(((box[0] - padX) * 0.5 + 0.5) * GRID_COLS),
GRID_COLS,
);
ranges[r + 1] = clampTo(
Math.floor(((box[1] - padY) * 0.5 + 0.5) * GRID_ROWS),
GRID_ROWS,
);
ranges[r + 2] = clampTo(
Math.floor(((box[2] + padX) * 0.5 + 0.5) * GRID_COLS),
GRID_COLS,
);
ranges[r + 3] = clampTo(
Math.floor(((box[3] + padY) * 0.5 + 0.5) * GRID_ROWS),
GRID_ROWS,
);
for (let y = ranges[r + 1]; y <= ranges[r + 3]; y++)
for (let x = ranges[r]; x <= ranges[r + 2]; x++)
counts[y * GRID_COLS + x]++;
}
let total = 0;
for (let cell = 0; cell < counts.length; cell++) {
offsets[cell] = total;
cursor[cell] = total;
total += counts[cell];
grid.data[cell * 4] = offsets[cell];
grid.data[cell * 4 + 1] = counts[cell];
}
if (candidates.data.length / 4 < total)
candidates = texelStorage(
Math.max(total, (candidates.data.length / 4) * 2),
);
// Items enter each cell in draw order.
for (let index = 0; index < count; index++) {
const r = index * 4;
if (ranges[r] < 0) continue;
for (let y = ranges[r + 1]; y <= ranges[r + 3]; y++)
for (let x = ranges[r]; x <= ranges[r + 2]; x++)
candidates.data[cursor[y * GRID_COLS + x]++ * 4] = index;
}
return true;
},
};
}
+273
View File
@@ -0,0 +1,273 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as geo from '../../../geo/index.js';
import { normalizeGroundItem } from '../../ground.js';
import {
BIN_THRESHOLD,
binArea,
composeGround,
CORRIDOR_CHUNK,
GRID_COLS,
KIND,
packSet,
STYLE_TEXELS,
} from './pack.js';
const items = (kind, list) =>
list.map((item, index) => normalizeGroundItem(kind, item, index));
test('a set packs its frames, styles and segments', () => {
const pack = packSet(
'polygon',
items('polygon', [
{
rings: [
[
[55, 25],
[55.1, 25],
[55.1, 25.1],
],
[
[55.05, 25.02],
[55.08, 25.02],
[55.08, 25.05],
],
],
fill: [1, 0, 0, 0.5],
outline: { color: [0, 0, 1, 1], widthPx: 3 },
},
]),
);
assert.equal(pack.count, 1);
assert.equal(pack.segments.length / 4, 6, 'three segments per ring');
const style = pack.styles;
assert.deepEqual([...style.slice(0, 4)], [1, 0, 0, 0.5]);
assert.deepEqual([...style.slice(4, 8)], [0, 0, 1, 1]);
assert.equal(style[8], KIND.area);
assert.equal(style[9], 3);
assert.equal(style[14], 0);
assert.equal(style[15], 6);
// The plane's origin is on the ellipsoid at the bounds' centre.
const centre = geo.cartesian3.fromDegrees(55.05, 25.05);
assert.ok(Math.abs(pack.frames[0] - centre.x) < 1e-6);
assert.equal(pack.volumes[3], 3 / 2 + 2, 'half the outline + 2 px pad');
});
test('gnomonic segments keep a great-circle edge straight and distances right', () => {
const [disc] = items('disc', [{ center: [0, 0], radiusM: 100_000 }]);
const pack = packSet('disc', [disc]);
const radius = pack.frames[12];
assert.ok(
Math.abs(pack.styles[11] - radius * Math.tan(100_000 / radius)) < 0.01,
);
assert.equal(pack.styles[8], KIND.disc);
const corridor = packSet(
'corridor',
items('corridor', [
{
positions: [
[-1, 0],
[1, 0],
],
color: [1, 1, 1, 1],
widthPx: 4,
},
]),
);
const [ax, ay, bx, by] = corridor.segments;
assert.ok(Math.abs(ay) < 1e-6 && Math.abs(by) < 1e-6, 'on the equator');
assert.ok(Math.abs(ax + bx) < 1e-6);
assert.equal(corridor.styles[8], KIND.corridorPx);
assert.equal(corridor.styles[10], 4);
});
test('composed sets keep draw order and offset their segments', () => {
const square = (lon) => ({
rings: [
[
[lon, 0],
[lon + 1, 0],
[lon + 1, 1],
[lon, 1],
],
],
fill: [1, 1, 1, 1],
});
const first = packSet('polygon', items('polygon', [square(0)]));
const second = packSet('polygon', items('polygon', [square(0.5)]));
const state = composeGround([first, second]);
assert.equal(state.count, 2);
assert.equal(
state.styles.data[STYLE_TEXELS * 4 + 14],
4,
'second set after four',
);
// A camera 2000 km over (0.75, 0.5) looking straight down.
const eye = geo.cartesian3.fromDegrees(0.75, 0.5, 2e6);
const target = geo.cartesian3.fromDegrees(0.75, 0.5);
const up = geo.cartesian3.create(0, 0, 1);
const zAxis = geo.cartesian3.normalize(
geo.cartesian3.subtract(eye, target, geo.cartesian3.create()),
geo.cartesian3.create(),
);
const xAxis = geo.cartesian3.normalize(
geo.cartesian3.cross(up, zAxis, geo.cartesian3.create()),
geo.cartesian3.create(),
);
const yAxis = geo.cartesian3.cross(zAxis, xAxis, geo.cartesian3.create());
const view = [
xAxis.x,
yAxis.x,
zAxis.x,
0,
xAxis.y,
yAxis.y,
zAxis.y,
0,
xAxis.z,
yAxis.z,
zAxis.z,
0,
-geo.cartesian3.dot(xAxis, eye),
-geo.cartesian3.dot(yAxis, eye),
-geo.cartesian3.dot(zAxis, eye),
1,
];
const f = 1 / Math.tan(Math.PI / 6);
const near = 1;
const far = 1e8;
const projection = [
f,
0,
0,
0,
0,
f,
0,
0,
0,
0,
-(far + near) / (far - near),
-1,
0,
0,
(-2 * far * near) / (far - near),
0,
];
assert.equal(state.update(view, projection, 800, 800), true);
assert.equal(state.update(view, projection, 800, 800), false, 'unchanged');
// The middle cell holds both, first set first.
const cell = (GRID_COLS * 40) / 2 + GRID_COLS / 2;
const [offset, count] = state.grid.data.slice(cell * 4, cell * 4 + 2);
assert.equal(count, 2);
assert.deepEqual(
[
state.candidates.data[offset * 4],
state.candidates.data[(offset + 1) * 4],
],
[0, 1],
);
// The first frame's centre in view space is in front of the camera.
assert.ok(state.frames.data[2] < -1.9e6);
});
test('a long corridor packs as chunks that own their own segments', () => {
const positions = Array.from({ length: 41 }, (_, index) => [index * 0.01, 0]);
const pack = packSet(
'corridor',
items('corridor', [{ positions, color: [1, 1, 1, 1], widthM: 10 }]),
);
assert.equal(pack.count, Math.ceil(40 / CORRIDOR_CHUNK));
const owned = (index) => [
...pack.styles.slice(
index * STYLE_TEXELS * 4 + 16,
index * STYLE_TEXELS * 4 + 18,
),
];
const counts = (index) => pack.styles[index * STYLE_TEXELS * 4 + 15];
// The first chunk has no segment before it, the others one each side.
assert.deepEqual(owned(0), [0, CORRIDOR_CHUNK]);
assert.equal(counts(0), CORRIDOR_CHUNK + 1);
assert.deepEqual(owned(1), [1, CORRIDOR_CHUNK]);
assert.equal(counts(1), CORRIDOR_CHUNK + 2);
const last = pack.count - 1;
const rest = 40 - last * CORRIDOR_CHUNK;
assert.deepEqual(owned(last), [1, rest]);
assert.equal(counts(last), rest + 1);
assert.equal(pack.styles[8], KIND.corridorM);
assert.equal(pack.styles[11], 10);
});
test('sampled terrain heights bound the screen box; unknown ones keep it deep', () => {
const square = items('polygon', [
{
rings: [
[
[55, 25],
[55.01, 25],
[55.01, 25.01],
[55, 25.01],
],
],
fill: [1, 1, 1, 1],
},
]);
const sampled = packSet('polygon', square, { terrainHeight: () => 40 });
assert.deepEqual([...sampled.heights], [40, 40]);
const unknown = packSet('polygon', square, {
terrainHeight: (lon) => (lon > 55.005 ? undefined : 10),
});
assert.ok(unknown.heights.every(Number.isNaN));
assert.ok(packSet('polygon', square).heights.every(Number.isNaN));
});
test('a large area bins its segments; each bin knows its centre', () => {
// A ring of 200 segments round a 10 km circle.
const list = [];
for (let index = 0; index < 200; index++) {
const a = (index / 200) * 2 * Math.PI;
const b = ((index + 1) / 200) * 2 * Math.PI;
list.push(
5000 * Math.cos(a),
5000 * Math.sin(a),
5000 * Math.cos(b),
5000 * Math.sin(b),
);
}
assert.equal(binArea(list.slice(0, 4 * BIN_THRESHOLD)), null);
const grid = binArea(list);
assert.equal(grid.columns, grid.rows);
const at = (x, y) =>
grid.bins[
Math.floor((y - grid.y) / grid.size) * grid.columns +
Math.floor((x - grid.x) / grid.size)
];
assert.equal(at(0, 0).inside, 1, 'the middle is inside');
assert.equal(at(0, 0).count, 0, 'and far from every edge');
assert.equal(at(grid.x + 1, grid.y + 1).inside, 0, 'a corner is outside');
assert.ok(at(5000, 0).count > 0, 'the rim bins hold its edges');
// A ring through a pixel's neighbourhood is in its bin's list.
const total = grid.bins.reduce((sum, bin) => sum + bin.count, 0);
assert.ok(total >= 200 && total < 200 * 6, `${total} entries`);
});
test('each bin of a packed area points at its own segments', () => {
const ring = Array.from({ length: 80 }, (_, index) => {
const angle = (index / 80) * 2 * Math.PI;
return [55 + 0.2 * Math.cos(angle), 25 + 0.2 * Math.sin(angle)];
});
const pack = packSet(
'polygon',
items('polygon', [{ rings: [ring], fill: [1, 1, 1, 1] }]),
);
const columns = pack.styles[16];
const rows = pack.styles[17];
assert.ok(columns * rows > 1);
assert.equal(pack.bins.length / 4, columns * rows);
let expected = 80;
for (let bin = 0; bin < columns * rows; bin++) {
assert.equal(pack.bins[bin * 4], expected, `bin ${bin} start`);
expected += pack.bins[bin * 4 + 1];
}
assert.equal(pack.segments.length / 4, expected);
});
+350
View File
@@ -0,0 +1,350 @@
// engine.ground's screen pass on Navara: one public EffectDesc after tone
// mapping, before the sharpening, anti-aliasing and gev's overlays. Each
// pixel's world position comes from Navara's packed scene depth (terrain,
// 3D tiles); where that is the ground (not a mesh in front of it), the
// candidates of its screen cell (pack.js) are tested in their own gnomonic
// planes: a disc against its radius, an area against its segments (even-odd
// inside, distance to the nearest edge), a corridor against its distance to
// the line. Fills and outlines are anti-aliased over one pixel across the
// boundary and blended in display space, in draw order, as Cesium blends
// translucent ground primitives. Costs nothing while no item is drawn
// (the effect is hidden).
import { EffectDesc, Effect as NavaraEffect } from '@navaramap/three';
import { Effect, EffectAttribute } from 'postprocessing';
import {
DataTexture,
FloatType,
Matrix4,
NearestFilter,
RGBADepthPacking,
RGBAFormat,
Uniform,
} from 'three';
import { withFrameUpdates, withPassDisposal } from '../frameDescriptor.js';
import { GRID_COLS, GRID_ROWS, KIND, STYLE_TEXELS, TEXELS } from './pack.js';
export const GROUND_EFFECT_KEY = 'gevGround';
const fragmentShader = /* glsl */ `
uniform sampler2D tAllDepth;
uniform sampler2D tSurfaceDepth;
uniform highp sampler2D tFrames;
uniform highp sampler2D tStyles;
uniform highp sampler2D tSegments;
uniform highp sampler2D tBins;
uniform highp sampler2D tGrid;
uniform highp sampler2D tCandidates;
uniform mat4 uInverseProjection;
uniform float uLogDepthFC;
vec4 atSlot(highp sampler2D image, int slot) {
int width = textureSize(image, 0).x;
return texelFetch(image, ivec2(slot % width, slot / width), 0);
}
vec3 toDisplay(vec3 c) {
return mix(12.92*c,1.055*pow(max(c,vec3(0.0)),vec3(1.0/2.4))-0.055,step(vec3(0.0031308),c));
}
vec3 toLinear(vec3 c) {
return mix(c/12.92,pow(max((c+0.055)/1.055,vec3(0.0)),vec3(2.4)),step(vec3(0.04045),c));
}
void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
outputColor = inputColor;
float depth = unpackRGBAToDepth(texture2D(tAllDepth, uv));
float distance = exp2(2.0 * depth / uLogDepthFC) - 1.0;
vec4 ray = uInverseProjection * vec4(uv * 2.0 - 1.0, -1.0, 1.0);
vec3 point = ray.xyz * (distance / -ray.z);
// Derivatives before any divergent branch: neighbours test other items.
vec3 pointDx = dFdx(point);
vec3 pointDy = dFdy(point);
// A quad across the sky has no surface derivative.
float onSurface = 1.0 - step(1.0, depth);
float derivativeMask = 1.0 - step(0.5, abs(dFdx(onSurface)) + abs(dFdy(onSurface)));
pointDx *= derivativeMask;
pointDy *= derivativeMask;
if (depth >= 1.0) return;
ivec2 tile = clamp(ivec2(floor(uv * vec2(${GRID_COLS}.0, ${GRID_ROWS}.0))), ivec2(0), ivec2(${GRID_COLS - 1}, ${GRID_ROWS - 1}));
vec2 range = texelFetch(tGrid, tile, 0).xy;
if (range.y < 0.5) return;
float surface = texture2D(tSurfaceDepth, uv).r;
// The packed depth also holds forward meshes, which are not ground.
if (depth < surface - 2e-7) return;
vec3 color = toDisplay(inputColor.rgb);
int first = int(range.x);
int candidates = int(range.y);
for (int k = 0; k < candidates; k++) {
int id = int(atSlot(tCandidates, first + k).x);
vec4 origin = atSlot(tFrames, id * ${TEXELS});
vec4 east = atSlot(tFrames, id * ${TEXELS} + 1);
vec4 north = atSlot(tFrames, id * ${TEXELS} + 2);
vec3 up = atSlot(tFrames, id * ${TEXELS} + 3).xyz;
vec4 span = atSlot(tStyles, id * ${STYLE_TEXELS} + 3);
vec3 delta = point - origin.xyz;
float height = dot(delta, up);
if (height < span.x || height > span.y) continue;
vec4 fillColor = atSlot(tStyles, id * ${STYLE_TEXELS});
vec4 lineColor = atSlot(tStyles, id * ${STYLE_TEXELS} + 1);
vec4 shape = atSlot(tStyles, id * ${STYLE_TEXELS} + 2);
// Along the ray from the Earth's centre onto the item's plane.
float scale = origin.w / (origin.w + height);
vec2 local = vec2(dot(delta, east.xyz), dot(delta, north.xyz)) * scale;
vec2 localDx = vec2(dot(pointDx, east.xyz), dot(pointDx, north.xyz)) * scale;
vec2 localDy = vec2(dot(pointDy, east.xyz), dot(pointDy, north.xyz)) * scale;
// Beyond the item's extent and its padding in pixels: not this item.
float reach = east.w + north.w * (length(localDx) + length(localDy));
if (dot(local, local) > reach * reach) continue;
int kind = int(shape.x + 0.5);
float nearest = 1e30;
int nearestSegment = 0;
vec2 normal = vec2(1.0, 0.0);
bool inside = false;
if (kind == ${KIND.disc}) {
float r = length(local);
if (r > 0.0) normal = local / r;
nearest = abs(r - shape.w);
inside = r < shape.w;
} else {
int start = int(span.z);
int count = int(span.w);
// A large area: only the segments of the pixel's bin, while its
// reach (half the outline and the anti-aliasing) stays inside the
// half bin the bin's list covers; inside-ness from the bin's centre.
bool binned = false;
bool centreInside = false;
vec2 centre = vec2(0.0);
if (kind == ${KIND.area}) {
vec4 grid = atSlot(tStyles, id * ${STYLE_TEXELS} + 4);
if (grid.x > 0.5 &&
(length(localDx) + length(localDy)) * (shape.y * 0.5 + 1.5) <= grid.z * 0.5) {
vec2 origin = atSlot(tStyles, id * ${STYLE_TEXELS} + 5).xy;
ivec2 cell = ivec2(floor((local - origin) / grid.z));
// Off the grid: outside the area, beyond any edge's reach.
if (cell.x < 0 || cell.y < 0 || cell.x >= int(grid.x) || cell.y >= int(grid.y)) continue;
vec4 bin = atSlot(tBins, int(grid.w) + cell.y * int(grid.x) + cell.x);
start += int(bin.x);
count = int(bin.y);
centreInside = bin.z > 0.5;
centre = origin + (vec2(cell) + 0.5) * grid.z;
binned = true;
}
}
for (int s = 0; s < count; s++) {
vec4 segment = atSlot(tSegments, start + s);
vec2 a = segment.xy;
vec2 ab = segment.zw - a;
vec2 ap = local - a;
float t = clamp(dot(ap, ab) / max(dot(ab, ab), 1e-12), 0.0, 1.0);
vec2 off = ap - ab * t;
float d = length(off);
if (d < nearest) {
nearest = d;
nearestSegment = s;
if (d > 0.0) normal = off / d;
}
if (binned) {
// The segment from the bin's centre to the pixel crosses it.
vec2 cp = local - centre;
float d1 = ab.x * (centre.y - a.y) - ab.y * (centre.x - a.x);
float d2 = ab.x * (local.y - a.y) - ab.y * (local.x - a.x);
float d3 = cp.x * (a.y - centre.y) - cp.y * (a.x - centre.x);
float d4 = cp.x * (segment.w - centre.y) - cp.y * (segment.z - centre.x);
if (d1 * d2 < 0.0 && d3 * d4 < 0.0) inside = !inside;
} else if ((a.y > local.y) != (segment.w > local.y) &&
local.x < ab.x * (local.y - a.y) / ab.y + a.x)
inside = !inside;
}
if (binned) inside = inside != centreInside;
}
// Metres one pixel spans across the boundary.
float pixel = max(abs(dot(normal, localDx)) + abs(dot(normal, localDy)), 1e-4);
if (kind == ${KIND.corridorPx} || kind == ${KIND.corridorM}) {
// A chunk of a long corridor draws where its own segments are nearest.
vec2 owned = atSlot(tStyles, id * ${STYLE_TEXELS} + 4).xy;
if (float(nearestSegment) < owned.x - 0.5 ||
float(nearestSegment) > owned.x + owned.y - 0.5) continue;
float halfWidth = kind == ${KIND.corridorPx} ? shape.z * 0.5 * pixel : shape.w * 0.5;
float cover = clamp((halfWidth - nearest) / pixel + 0.5, 0.0, 1.0);
color = mix(color, fillColor.rgb, fillColor.a * cover);
continue;
}
float inward = inside ? nearest : -nearest;
if (fillColor.a > 0.0)
color = mix(color, fillColor.rgb, fillColor.a * clamp(inward / pixel + 0.5, 0.0, 1.0));
if (lineColor.a > 0.0 && shape.y > 0.0)
color = mix(color, lineColor.rgb, lineColor.a * clamp(shape.y * 0.5 - nearest / pixel + 0.5, 0.0, 1.0));
}
outputColor = vec4(toLinear(color), inputColor.a);
}
`;
function dataTexture({ data, width, height }) {
const texture = new DataTexture(data, width, height, RGBAFormat, FloatType);
texture.minFilter = NearestFilter;
texture.magFilter = NearestFilter;
texture.needsUpdate = true;
return texture;
}
/** A composed state (pack.js composeGround) with its GPU textures. */
function texturesFor(state) {
const textures = {
styles: dataTexture(state.styles),
segments: dataTexture(state.segments),
bins: dataTexture(state.bins),
frames: dataTexture(state.frames),
grid: dataTexture(state.grid),
candidates: dataTexture(state.candidates),
candidateData: state.candidates.data,
dispose() {
for (const key of [
'styles',
'segments',
'bins',
'frames',
'grid',
'candidates',
])
textures[key].dispose();
},
};
return textures;
}
/** Bytes the pass's data textures hold on the GPU. */
export const textureBytes = (state) =>
state
? [
state.styles,
state.segments,
state.bins,
state.frames,
state.grid,
state.candidates,
].reduce((total, { data }) => total + data.byteLength, 0)
: 0;
class GroundEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
static key = GROUND_EFFECT_KEY;
// Navara takes the first anchor that exists: the latest first.
static insertAfter = [
'gevFirmsGround',
'gevEarthquakeGround',
'gevObservedWeather',
'gevNepalEvent',
'gevRecentImagery',
'toneMapping',
];
static insertBefore = [
'gevPreSharpenOverlay',
'gevSharpen',
'smaa',
'fxaa',
'gevOverlay',
'final',
];
constructor(view, ctx, config) {
super(view, ctx, config);
this.owner = config[GROUND_EFFECT_KEY].owner;
}
createPass() {
const camera = this.view.camera.raw;
if (!camera) throw new Error('Camera not available for the ground pass');
this.effect = new Effect('GevGround', fragmentShader, {
// Its own pass: inputColor is the tone-mapped frame.
attributes: EffectAttribute.CONVOLUTION,
uniforms: new Map([
['tAllDepth', new Uniform(null)],
['tSurfaceDepth', new Uniform(null)],
['tFrames', new Uniform(null)],
['tStyles', new Uniform(null)],
['tSegments', new Uniform(null)],
['tBins', new Uniform(null)],
['tGrid', new Uniform(null)],
['tCandidates', new Uniform(null)],
['uInverseProjection', new Uniform(new Matrix4())],
['uLogDepthFC', new Uniform(1)],
]),
});
return new NavaraEffect(camera, this.effect);
}
updateFrame() {
const camera = this.view.camera.raw;
const owner = this.owner;
if (!this.effect || !camera || !owner.state) return;
const mrt = this.find('mrt');
if (mrt?.depthBufferPacking !== RGBADepthPacking)
throw new Error('The ground pass needs packed scene depth');
const input = this.ctx.getInputBuffer();
const { state } = owner;
if (
state.update(
camera.matrixWorldInverse.elements,
camera.projectionMatrix.elements,
input.width,
input.height,
)
) {
const textures = owner.textures;
if (textures.candidateData !== state.candidates.data) {
textures.candidates.dispose();
textures.candidates = dataTexture(state.candidates);
textures.candidateData = state.candidates.data;
}
textures.frames.needsUpdate = true;
textures.grid.needsUpdate = true;
textures.candidates.needsUpdate = true;
}
const u = this.effect.uniforms;
u.get('tAllDepth').value = mrt.depthBuffer;
u.get('tSurfaceDepth').value = this.ctx.getRenderTarget().depthTexture;
u.get('uInverseProjection').value.copy(camera.projectionMatrixInverse);
u.get('uLogDepthFC').value = 2 / Math.log2(camera.far + 1);
u.get('tFrames').value = owner.textures.frames;
u.get('tStyles').value = owner.textures.styles;
u.get('tSegments').value = owner.textures.segments;
u.get('tBins').value = owner.textures.bins;
u.get('tGrid').value = owner.textures.grid;
u.get('tCandidates').value = owner.textures.candidates;
}
}
const registered = new WeakSet();
/**
* The pass of one view: set(state) shows a composed state (null: nothing,
* the effect hidden) and disposes the one before.
*/
export function createGroundPass(view) {
if (!registered.has(view)) {
view.registerEffect(GROUND_EFFECT_KEY, GroundEffectDesc);
registered.add(view);
}
const owner = { state: null, textures: null };
let handle = null;
return {
owner,
set(state) {
const previous = owner.textures;
owner.state = state && state.count ? state : null;
owner.textures = owner.state ? texturesFor(owner.state) : null;
const visible = owner.state !== null;
if (visible && !handle)
handle = view.addEffect({
[GROUND_EFFECT_KEY]: { owner },
visible: true,
});
else handle?.update({ visible });
previous?.dispose();
},
textureBytes: () => textureBytes(owner.state),
destroy() {
handle?.delete();
handle = null;
owner.textures?.dispose();
owner.state = null;
owner.textures = null;
},
};
}
+147
View File
@@ -0,0 +1,147 @@
// A prototype of engine.ground on Navara's own vector layers, kept to
// measure against the screen pass (pass.js) and not used by the engine:
// each set's items grouped by style into one GeoJSON source and one
// clamped vector layer per group (discs and cells as polygons, pixel
// corridors as polylines; metre corridors are not drawn). `hide` picks how a
// hidden set goes: 'delete' (its layers deleted, rebuilt when shown) or
// 'update' (layer.update with show false).
import { areaRings, createGroundRegistry } from '../../ground.js';
const toHex = (rgba) =>
(Math.round(rgba[0] * 255) << 16) |
(Math.round(rgba[1] * 255) << 8) |
Math.round(rgba[2] * 255);
function ringCoordinates(flat) {
const ring = [];
for (let index = 0; index < flat.length; index += 2)
ring.push([flat[index], flat[index + 1]]);
ring.push(ring[0]);
return ring;
}
// Features grouped by their layer style: Map<key, { style, features }>.
export function vectorGroups(kind, items) {
const groups = new Map();
const add = (key, style, feature) => {
if (!groups.has(key)) groups.set(key, { style, features: [] });
groups.get(key).features.push(feature);
};
items.forEach((item, index) => {
if (kind === 'corridor') {
if (!item.widthPx) return;
const coordinates = [];
for (let at = 0; at < item.path.length; at += 2)
coordinates.push([item.path[at], item.path[at + 1]]);
add(
`line:${item.fill.join()}:${item.widthPx}`,
{
polyline: {
color: toHex(item.fill),
width: item.widthPx,
opacity: item.fill[3],
transparent: item.fill[3] < 1,
clampToGround: true,
},
},
{
type: 'Feature',
id: index,
properties: {},
geometry: { type: 'LineString', coordinates },
},
);
return;
}
const rings = areaRings(kind, item).map(ringCoordinates);
const fill = item.fill ?? [0, 0, 0, 0];
const outline = item.outline;
add(
`area:${fill.join()}:${outline ? `${outline.color.join()}:${outline.widthPx}` : ''}`,
{
polygon: {
color: toHex(fill),
opacity: fill[3],
transparent: true,
clampToGround: true,
...(outline
? {
outline: true,
outlineShow: true,
outlineColor: toHex(outline.color),
outlineWidth: outline.widthPx,
}
: {}),
},
},
{
type: 'Feature',
id: index,
properties: {},
geometry: { type: 'Polygon', coordinates: rings },
},
);
});
return groups;
}
/**
* @param {object} view an initialised Navara ThreeView
* @param {{ hide?: 'delete'|'update' }} [options]
*/
export function createNavaraVectorGround(view, { hide = 'delete' } = {}) {
const registry = createGroundRegistry((options) => {
let groups = new Map();
let batches = [];
let shown = true;
const release = () => {
for (const { layer, source } of batches) {
layer.delete();
source.delete();
}
batches = [];
};
const build = () => {
release();
for (const { style, features } of groups.values()) {
const source = view.addSource({
type: 'geojson',
data: { type: 'FeatureCollection', features },
});
const config = { type: 'vector', source, ...style };
batches.push({ source, config, layer: view.addLayer(config) });
}
};
return {
commit(items) {
groups = vectorGroups(options.kind, items);
if (shown || hide === 'update') build();
if (!shown && hide === 'update')
for (const batch of batches)
batch.layer.update({ ...batch.config, show: false });
view.forceUpdate();
},
show(visible) {
if (visible === shown) return;
shown = visible;
if (hide === 'delete') {
if (visible) build();
else release();
} else
for (const batch of batches)
batch.layer.update({ ...batch.config, show: visible });
view.forceUpdate();
},
destroy() {
release();
view.forceUpdate();
},
};
});
return {
ground: registry.ground,
pickables: () => [...registry.live.values()],
destroy: () => registry.destroyAll(),
};
}
+3
View File
@@ -34,6 +34,8 @@ import { animeShader } from '../../styles/anime.js';
import { noirShader } from '../../styles/noir.js';
import { createNavaraMovers } from './movers/index.js';
import { createNavaraLines } from './lines/index.js';
import { createNavaraGround } from './ground/index.js';
import { createGroundPass } from './ground/pass.js';
import { createNavaraOverlay } from './overlay.js';
import { createPostSampling } from './postSampling.js';
import {
@@ -170,6 +172,7 @@ export async function createNavaraGlobe({ container, search, hd = false }) {
),
}),
lines: createNavaraLines(view, { overlay }),
ground: createNavaraGround(view, { createPass: createGroundPass }),
});
const camera = engine.camera;
let ground = Number.NaN;