feat(globe): dynamic lines on both engines

engine.lines.createLine({ id, widthPx, color, depthFailAlpha, dash
({ lengthPx, gapPx } | 'tactical'), arc ('none'|'geodesic'), modelMatrix,
pickId }) → a Line: setPositions (Cartesian3[] or a flat Float64Array),
setColor, setModelMatrix, show, destroy; lines.list() for QA. Options,
flat positions, geodesic densification (great circles of the geodetic
normals, height interpolated, one step per degree) and the registry are
engine-neutral (src/globe/lines.js); the fake engine keeps every line.

- Cesium: a Primitive of a PolylineGeometry (synchronous, rebuilt when
  the positions change) with a PolylineMaterialAppearance in an
  engine-owned collection; depthFailAlpha is depthFailAppearance with the
  alpha scaled; pixel dashes are PolylineDash (16-bit pattern); the
  tactical dash is the launches' selected-orbit shader under its own type
  (launches keep theirs until Task 15a moves them onto engine.lines).
- Navara: a public MeshDesc (transparent pass, unlit) holding a ribbon
  of one quad per segment, widened to CSS pixels in the vertex shader;
  a second copy drawn with GreaterDepth and the alpha scaled is the
  depth-fail part; dashes are cut in the fragment shader (pixels along
  the screen direction, or the tactical pattern over the fraction along
  the line); positions relative to the first point, the model matrix on
  the group. Geodesic arcs are densified on the CPU. Not pickable yet.
- The contract suite draws a three-point line on both engines: magenta
  along both segments, nothing off it, 1° east once turned by its model
  matrix, gone when hidden; a line 30 km under the ground shows only its
  depth-fail copy, dimmer than the line.

Main chunk 2,867,499 bytes (+7,197, +0.25 %: the Cesium lines).
This commit is contained in:
German Khokhlov committed 2026-10-16 17:24:36 +04:00
1 parent 0109097440
commit 86aa0bc9ba
16 files changed
+1380 -2

No files matched your search

+11 -1
View File
@@ -30,6 +30,12 @@ const NO_MOVERS = Object.freeze({
},
list: () => [],
});
const NO_LINES = Object.freeze({
createLine() {
throw new Error("Navara lines need the view's three runtime (lines/)");
},
list: () => [],
});
// Navara's drawn camera (view.camera.raw, a three PerspectiveCamera in
// Earth-fixed metres): matrixWorld columns are right, up, back, position.
@@ -84,7 +90,8 @@ function rayRaisedEllipsoid({ origin, direction }, height) {
* it the engine only keeps the state) and the engine destroys it;
* `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) and the engine destroys it;
* without it createSet throws), `lines` engine.lines (lines/index.js;
* likewise), both destroyed with the engine;
* `fetch` and `clock` (the camera model's timers) are test seams.
* @returns {import('../contract.js').GlobeEngine}
*/
@@ -97,6 +104,7 @@ export function createNavaraEngine(
clock,
appClock,
movers: moversPort = null,
lines: linesPort = null,
sharpen: sharpenPort = null,
} = {},
) {
@@ -246,6 +254,7 @@ export function createNavaraEngine(
maps: maps.maps,
clock: engineClock.clock,
movers: moversPort?.movers ?? NO_MOVERS,
lines: linesPort?.lines ?? NO_LINES,
destroy() {
if (destroyed) return;
destroyed = true;
@@ -257,6 +266,7 @@ export function createNavaraEngine(
maps.destroy();
sharpenPort?.destroy();
moversPort?.destroy();
linesPort?.destroy();
},
isDestroyed: () => destroyed,
// Navara only, not contract: the ground the floor last sampled under
+2
View File
@@ -10,6 +10,7 @@ import { forEachLuminanceUniform, navaraHooks } from './internals.js';
import { buildNavaraLook } from './look.js';
import { createNavaraSharpen } from './sharpen.js';
import { createNavaraMovers } from './movers/index.js';
import { createNavaraLines } from './lines/index.js';
import {
NAVARA_CONTEXT_ATTRIBUTES,
navaraScenePlan,
@@ -117,6 +118,7 @@ export async function createNavaraGlobe({
...(appClock ? { appClock } : {}),
sharpen: createNavaraSharpen(view),
movers: createNavaraMovers(view),
lines: createNavaraLines(view),
});
const camera = engine.camera;
let ground = Number.NaN;
+81
View File
@@ -0,0 +1,81 @@
// engine.lines on Navara: each line is one Navara mesh descriptor (public
// MeshDesc API, the transparent pass, unlit) holding its ribbon
// (lineMesh.js). Geodesic arcs are densified on the CPU (src/globe/lines.js)
// since the ribbon draws straight segments. Every change asks for one frame;
// nothing animates on its own, so an idle view stays idle. Lines are not
// pickable on Navara yet (trails never take a click; see phase 3 Task 4).
import { MeshDesc } from '@navaramap/three';
import { createLineRegistry, densifyGeodesic } from '../../lines.js';
import { createLineMesh } from './lineMesh.js';
const DESC_NAME = 'gevLine';
const registered = new WeakSet();
class GevLineDesc extends MeshDesc {
constructor(view, ctx, config) {
super(view, ctx, config);
this.gev = config[DESC_NAME];
}
getPassKey() {
return 'transparent';
}
createMesh() {
return this.gev.line.group;
}
update() {
const canvas = this.ctx.getRenderer().domElement;
this.gev.line.update(canvas.clientWidth, canvas.clientHeight);
}
onDestroy() {
this.gev.line.dispose();
super.onDestroy();
}
}
/**
* @param {object} view an initialised Navara ThreeView
* @returns {{ lines: import('../../contract.js').GlobeLines, destroy: () => void }}
*/
export function createNavaraLines(view) {
if (!registered.has(view)) {
view.registerMesh(DESC_NAME, GevLineDesc);
registered.add(view);
}
const request = () => view.forceUpdate();
const registry = createLineRegistry((options) => {
const line = createLineMesh(options);
const canvas = view.canvas;
if (canvas) line.update(canvas.clientWidth || 1, canvas.clientHeight || 1);
const handle = view.addMesh({ lit: false, [DESC_NAME]: { line } });
return {
setPositions(flat) {
line.setPositions(
options.arc === 'geodesic' ? densifyGeodesic(flat) : flat,
);
request();
},
setColor(rgba) {
line.setColor(rgba);
request();
},
setModelMatrix(matrix) {
line.setModelMatrix(matrix);
request();
},
show(visible) {
line.show(visible);
request();
},
destroy() {
handle.delete();
request();
},
};
});
return { lines: registry.lines, destroy: () => registry.destroyAll() };
}
+259
View File
@@ -0,0 +1,259 @@
// The three side of a Navara line: a ribbon of one quad per segment whose
// vertices are pushed apart in the vertex shader to the line's width in CSS
// pixels (projected ends, the screen-space normal), so the width holds at any
// distance. A second copy of the ribbon, drawn only where the scene hides it
// (depthFunc GreaterDepth) with the alpha scaled, is depthFailAlpha. Dashes
// in pixels are cut in the fragment shader along the segment's screen
// direction (as Cesium's PolylineDash); the tactical dash is the launches'
// pattern over the fraction along the whole line. Positions are relative to
// the first point (the group sits there, in doubles), the model matrix
// multiplies the group's transform (an orbit ring turned by GMST).
import {
BufferAttribute,
BufferGeometry,
DoubleSide,
GreaterDepth,
Group,
LessEqualDepth,
Matrix4,
Mesh,
MeshBasicMaterial,
} from 'three';
const VERTEX_HEAD = /* glsl */ `
attribute vec3 gevEnd;
attribute vec2 gevSide;
attribute float gevS;
uniform vec2 uGevViewport;
uniform float uGevWidthPx;
varying float vGevS;
varying float vGevT;
varying vec2 vGevDirection;
`;
const VERTEX_PROJECT = /* glsl */ `
vec4 gevA = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
vec4 gevB = projectionMatrix * modelViewMatrix * vec4(gevEnd, 1.0);
// Ends behind the camera move along the segment to just in front of it.
const float GEV_NEAR_W = 1e-3;
if (gevA.w < GEV_NEAR_W) gevA = mix(gevA, gevB, (GEV_NEAR_W - gevA.w) / (gevB.w - gevA.w));
if (gevB.w < GEV_NEAR_W) gevB = mix(gevB, gevA, (GEV_NEAR_W - gevB.w) / (gevA.w - gevB.w));
vec2 gevScreenA = gevA.xy / gevA.w * 0.5 * uGevViewport;
vec2 gevScreenB = gevB.xy / gevB.w * 0.5 * uGevViewport;
vec2 gevDirection = gevScreenB - gevScreenA;
gevDirection = length(gevDirection) > 1e-6 ? normalize(gevDirection) : vec2(1.0, 0.0);
vec2 gevNormal = vec2(-gevDirection.y, gevDirection.x);
gl_Position = gevSide.x < 0.5 ? gevA : gevB;
gl_Position.xy += gevNormal * gevSide.y * uGevWidthPx / uGevViewport * gl_Position.w;
vec4 mvPosition = modelViewMatrix * vec4(gevSide.x < 0.5 ? position : gevEnd, 1.0);
vGevS = gevS;
vGevT = gevSide.y * 0.5 + 0.5;
vGevDirection = gevDirection;
`;
const FRAGMENT_HEAD = /* glsl */ `
uniform vec4 uGevColor;
uniform float uGevAlphaScale;
uniform float uGevDash;
uniform vec2 uGevDashPx;
uniform vec2 uGevTactical;
varying float vGevS;
varying float vGevT;
varying vec2 vGevDirection;
float gevTactical() {
float groupPosition = fract(vGevS * uGevTactical.x);
float markPosition = groupPosition * (uGevTactical.y + 1.0);
float markIndex = floor(markPosition);
float localPosition = fract(markPosition);
float centerDistance = abs(localPosition - 0.5);
float edge = max(fwidth(localPosition) * 1.35, 0.012);
float dashAlong = 1.0 - smoothstep(0.27 - edge, 0.27 + edge, centerDistance);
float dashAcross = 1.0 - smoothstep(0.12, 0.24, abs(vGevT - 0.5));
float dotAlong = (localPosition - 0.5) / 0.32;
float dotAcross = (vGevT - 0.5) / 0.5;
float dot = 1.0 - smoothstep(0.78, 1.0, length(vec2(dotAlong, dotAcross)));
float isDot = 1.0 - step(0.5, markIndex);
return mix(dashAlong * dashAcross, dot, isDot) * mix(0.58, 1.0, isDot);
}
`;
const FRAGMENT_COLOR = /* glsl */ `
#include <color_fragment>
diffuseColor = uGevColor;
diffuseColor.a *= uGevAlphaScale;
if (uGevDash > 1.5) {
diffuseColor.a *= gevTactical();
} else if (uGevDash > 0.5) {
float gevAlong = dot(gl_FragCoord.xy, vGevDirection);
if (mod(gevAlong, uGevDashPx.x + uGevDashPx.y) > uGevDashPx.x) discard;
}
`;
/** Patches three's MeshBasicMaterial shaders into the pixel-width ribbon. */
export function patchLineShader(shader, uniforms) {
Object.assign(shader.uniforms, uniforms);
const replace = (source, from, to) => {
if (!source.includes(from))
throw new Error(`Line shader: three has no ${from}`);
return source.replace(from, to);
};
shader.vertexShader = replace(
replace(
shader.vertexShader,
'void main() {',
`${VERTEX_HEAD}\nvoid main() {`,
),
'#include <project_vertex>',
VERTEX_PROJECT,
);
shader.fragmentShader = replace(
replace(
shader.fragmentShader,
'void main() {',
`${FRAGMENT_HEAD}\nvoid main() {`,
),
'#include <color_fragment>',
FRAGMENT_COLOR,
);
return shader;
}
/**
* The ribbon geometry of a flat position list, relative to `origin`: per
* segment 4 vertices (start/end × side) and 2 triangles; `gevS` is the
* fraction of the line's length at the vertex's end.
*/
export function buildRibbon(flat, origin) {
const points = flat.length / 3;
const segments = Math.max(0, points - 1);
const start = new Float32Array(segments * 12);
const end = new Float32Array(segments * 12);
const side = new Float32Array(segments * 8);
const along = new Float32Array(segments * 4);
const index = new Uint32Array(segments * 6);
const cumulative = new Float64Array(points);
for (let p = 1; p < points; p++)
cumulative[p] =
cumulative[p - 1] +
Math.hypot(
flat[p * 3] - flat[p * 3 - 3],
flat[p * 3 + 1] - flat[p * 3 - 2],
flat[p * 3 + 2] - flat[p * 3 - 1],
);
const total = cumulative[points - 1] || 1;
for (let s = 0; s < segments; s++) {
const a = s * 3;
const b = a + 3;
for (let v = 0; v < 4; v++) {
const vertex = s * 4 + v;
for (let k = 0; k < 3; k++) {
start[vertex * 3 + k] = flat[a + k] - origin[k];
end[vertex * 3 + k] = flat[b + k] - origin[k];
}
const atEnd = v >= 2 ? 1 : 0;
side[vertex * 2] = atEnd;
side[vertex * 2 + 1] = v % 2 === 0 ? 1 : -1;
along[vertex] = cumulative[s + atEnd] / total;
}
index.set(
[s * 4, s * 4 + 1, s * 4 + 2, s * 4 + 2, s * 4 + 1, s * 4 + 3],
s * 6,
);
}
const geometry = new BufferGeometry();
geometry.setAttribute('position', new BufferAttribute(start, 3));
geometry.setAttribute('gevEnd', new BufferAttribute(end, 3));
geometry.setAttribute('gevSide', new BufferAttribute(side, 2));
geometry.setAttribute('gevS', new BufferAttribute(along, 1));
geometry.setIndex(new BufferAttribute(index, 1));
return geometry;
}
/** @param {ReturnType<import('../../lines.js').normalizeLineOptions>} options */
export function createLineMesh(options) {
const dash = options.dash;
const shared = {
uGevViewport: { value: [1, 1] },
uGevWidthPx: { value: options.widthPx },
uGevColor: { value: [...options.color] },
uGevDash: { value: dash?.kind === 'tactical' ? 2 : dash ? 1 : 0 },
uGevDashPx: {
value: dash?.kind === 'pixels' ? [dash.lengthPx, dash.gapPx] : [1, 0],
},
uGevTactical: {
value: dash?.kind === 'tactical' ? [dash.groups, dash.dashes] : [1, 1],
},
};
const material = (alphaScale, depthFunc) => {
const value = new MeshBasicMaterial({
transparent: true,
depthWrite: false,
depthFunc,
side: DoubleSide,
});
const uniforms = { ...shared, uGevAlphaScale: { value: alphaScale } };
value.onBeforeCompile = (shader) => patchLineShader(shader, uniforms);
value.customProgramCacheKey = () => 'gev-line';
return value;
};
const group = new Group();
group.matrixAutoUpdate = false;
group.frustumCulled = false;
const main = new Mesh(new BufferGeometry(), material(1, LessEqualDepth));
main.frustumCulled = false;
main.renderOrder = options.order;
group.add(main);
let behind = null;
if (options.depthFailAlpha > 0) {
behind = new Mesh(
main.geometry,
material(options.depthFailAlpha, GreaterDepth),
);
behind.frustumCulled = false;
behind.renderOrder = options.order;
group.add(behind);
}
let origin = [0, 0, 0];
const model = new Matrix4();
if (options.modelMatrix) model.fromArray(options.modelMatrix);
const place = () => {
group.matrix
.copy(model)
.multiply(new Matrix4().makeTranslation(origin[0], origin[1], origin[2]));
group.matrixWorldNeedsUpdate = true;
};
place();
return {
group,
uniforms: shared,
meshes: () => (behind ? [main, behind] : [main]),
setPositions(flat) {
const previous = main.geometry;
origin = flat.length >= 3 ? [flat[0], flat[1], flat[2]] : [0, 0, 0];
const geometry = buildRibbon(flat, origin);
main.geometry = geometry;
if (behind) behind.geometry = geometry;
previous.dispose();
place();
},
setColor(rgba) {
shared.uGevColor.value = [...rgba];
},
setModelMatrix(matrix) {
model.fromArray(matrix);
place();
},
show(visible) {
group.visible = visible;
},
/** Each drawn frame: the viewport the pixel width is measured in. */
update(width, height) {
shared.uGevViewport.value = [width, height];
},
dispose() {
main.geometry.dispose();
for (const mesh of [main, behind]) mesh?.material.dispose();
},
};
}
+79
View File
@@ -0,0 +1,79 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
GreaterDepth,
Matrix4,
ShaderLib,
UniformsUtils,
Vector3,
} from 'three';
import { normalizeLineOptions } from '../../lines.js';
import { buildRibbon, createLineMesh, patchLineShader } from './lineMesh.js';
const flat = new Float64Array([
6_378_137, 0, 0, 6_378_137, 300, 0, 6_378_137, 300, 400,
]);
test('the ribbon has a quad per segment relative to the first point', () => {
const geometry = buildRibbon(flat, [6_378_137, 0, 0]);
assert.equal(geometry.getAttribute('position').count, 8);
assert.equal(geometry.index.count, 12);
assert.deepEqual(
[...geometry.getAttribute('gevEnd').array.subarray(0, 3)],
[0, 300, 0],
);
// The fraction along the line: 0 at the start, 300/700 at the joint, 1 at the end.
const s = geometry.getAttribute('gevS').array;
assert.deepEqual([s[0], s[2]], [0, 300 / 700].map(Math.fround));
assert.equal(s[7], 1);
const side = geometry.getAttribute('gevSide').array;
assert.deepEqual([...side.subarray(0, 8)], [0, 1, 0, -1, 1, 1, 1, -1]);
});
test('the shader patch widens the ribbon in pixels and cuts dashes', () => {
const shader = patchLineShader(
{
uniforms: UniformsUtils.clone(ShaderLib.basic.uniforms),
vertexShader: ShaderLib.basic.vertexShader,
fragmentShader: ShaderLib.basic.fragmentShader,
},
{ uGevWidthPx: { value: 3 } },
);
assert.match(
shader.vertexShader,
/uGevWidthPx \/ uGevViewport \* gl_Position\.w/,
);
assert.match(
shader.fragmentShader,
/mod\(gevAlong, uGevDashPx\.x \+ uGevDashPx\.y\)/,
);
assert.match(shader.fragmentShader, /float gevTactical\(\)/);
});
test('a line places its group at the first point under its model matrix', () => {
const turn = new Matrix4().makeRotationZ(Math.PI / 2);
const line = createLineMesh(
normalizeLineOptions({
id: 'orbit',
widthPx: 3,
color: [0, 1, 1, 1],
depthFailAlpha: 0.3,
dash: 'tactical',
modelMatrix: turn.toArray(),
}),
);
line.setPositions(flat);
const origin = new Vector3().setFromMatrixPosition(line.group.matrix);
// (6378137, 0, 0) turned 90° about z.
assert.ok(Math.abs(origin.x) < 1e-6 && Math.abs(origin.y - 6_378_137) < 1e-6);
const [main, behind] = line.meshes();
assert.equal(behind.material.depthFunc, GreaterDepth);
assert.equal(main.geometry, behind.geometry);
assert.equal(line.uniforms.uGevDash.value, 2);
assert.deepEqual(line.uniforms.uGevTactical.value, [4, 100]);
line.setColor([1, 0, 0, 0.5]);
assert.deepEqual(line.uniforms.uGevColor.value, [1, 0, 0, 0.5]);
line.show(false);
assert.equal(line.group.visible, false);
line.dispose();
});