Treat contacts with the Cyber sonar sweep on Navara behind an optional render.setContactSonar capability

The sprite and point mover shaders rate each contact by its anchor against the sweep with the cyberSonar.js sampler maths; the engine sonar scene feeds the theme, settings and shared sweep angle each drawn frame and keeps the fleet cadence only while the sweep runs over contacts.
This commit is contained in:
German Khokhlov committed 2026-11-03 21:49:56 +04:00
1 parent c2d7a6dbb0
commit 1a3f6f2486
16 files changed
+1040 -6

No files matched your search

+30 -1
View File
@@ -10,11 +10,13 @@ import * as geo from '../../geo/index.js';
import {
BLOOM_INITIAL,
CLOUD_COVER_INITIAL,
CONTACT_SONAR_INITIAL,
SHARPEN_INITIAL,
STYLE_INITIAL,
createEngineEvent,
mergeBloom,
mergeCloudCover,
mergeContactSonar,
mergeSharpen,
mergeStyle,
} from '../contract.js';
@@ -96,6 +98,7 @@ function rayRaisedEllipsoid({ origin, direction }, height) {
* sharpen?: { set: (state: { enabled: boolean, amount: number }) => void, destroy: () => void },
* bloom?: { set: (state: { enabled: boolean, strength: number }) => void, destroy: () => void },
* clouds?: { set: (state: { coverage: number | null }) => void, destroy: () => void },
* sonar?: { set: (state: import('../contract.js').ContactSonar) => void, destroy: () => void },
* styles?: { names: readonly string[], uniformNames: (name: string) => string[], defaults: (name: string) => Record<string, number>, set: (name: string, state: { intensity: number, uniforms: Record<string, number> }) => void, destroy: () => void },
* }} options `hooks` are internals.js; `container` defaults to the
* canvas's parent; `sharpen` draws render.setSharpen (sharpen.js; without
@@ -105,7 +108,9 @@ function rayRaisedEllipsoid({ origin, direction }, height) {
* draws render.setBloom (bloom.js; without it no bloom capability), also
* destroyed with the engine; `clouds` draws render.setCloudCover
* (cockpitClouds.js; without it, as on a look without clouds, no
* cloudCover capability), destroyed with the engine;
* cloudCover capability), destroyed with the engine; `sonar` draws
* render.setContactSonar (sonar.js; without it no contactSonar
* capability), destroyed with the engine;
* `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;
@@ -127,6 +132,7 @@ export function createNavaraEngine(
styles: stylesPort = null,
bloom: bloomPort = null,
clouds: cloudsPort = null,
sonar: sonarPort = null,
} = {},
) {
if (!view?.camera?.raw)
@@ -185,12 +191,16 @@ export function createNavaraEngine(
});
// Defined below, with the surface and input it needs.
let groundFloor = null;
// Between the view's preRender and postRender: a change made then shows
// in the frame being drawn and asks for no other.
let drawing = false;
const handlers = {
preUpdate: (time) => {
engineClock.beginFrame();
frames.preUpdate.raiseEvent(time);
},
preRender: (time) => {
drawing = true;
model.sync();
// After the user's camera is read, before anything draws.
followStep.raiseEvent();
@@ -198,6 +208,7 @@ export function createNavaraEngine(
frames.preRender.raiseEvent(time);
},
postRender: (time) => {
drawing = false;
model.afterFrame();
frames.postRender.raiseEvent(time);
},
@@ -351,6 +362,22 @@ export function createNavaraEngine(
cloudCover: () => ({ ...cloudCover }),
}
: {};
let contactSonar = { ...CONTACT_SONAR_INITIAL };
const sonarRender = sonarPort
? {
setContactSonar(options) {
const next = mergeContactSonar(contactSonar, options);
const changed = Object.keys(next).some(
(key) => next[key] !== contactSonar[key],
);
contactSonar = next;
if (!changed || destroyed) return;
sonarPort.set({ ...next });
if (!drawing) view.forceUpdate();
},
contactSonar: () => ({ ...contactSonar }),
}
: {};
return {
kind: 'navara',
host: { container: container ?? canvas.parentElement, canvas, size },
@@ -382,6 +409,7 @@ export function createNavaraEngine(
...styleRender,
...bloomRender,
...cloudRender,
...sonarRender,
},
surface,
input: input.input,
@@ -405,6 +433,7 @@ export function createNavaraEngine(
stylesPort?.destroy();
bloomPort?.destroy();
cloudsPort?.destroy();
sonarPort?.destroy();
moversPort?.destroy();
linesPort?.destroy();
},
@@ -314,11 +314,46 @@ test('setCloudCover hands changed covers to the clouds port and draws a frame',
assert.equal(destroyed, 1);
});
test('setContactSonar hands changes to the sonar port, asking a frame only outside one', () => {
const view = fakeView();
const shown = [];
let destroyed = 0;
const engine = createNavaraEngine(view, {
hooks,
sonar: { set: (state) => shown.push(state), destroy: () => destroyed++ },
});
assertGlobeEngine(engine);
assert.equal(engineCapabilities(engine).contactSonar, true);
assert.equal(engine.render.contactSonar().enabled, false);
engine.render.setContactSonar({ enabled: true, active: true });
assert.deepEqual(view.calls.at(-1), ['forceUpdate']);
assert.equal(shown.length, 1);
// Inside a drawn frame the change shows in that frame: no other frame.
engine.frames.preRender.addEventListener(() =>
engine.render.setContactSonar({ angleDeg: 45 }),
);
const calls = view.calls.length;
view.emit('preRender', 1);
view.emit('postRender', 2);
assert.equal(shown.at(-1).angleDeg, 45);
assert.equal(
view.calls.slice(calls).filter(([name]) => name === 'forceUpdate').length,
0,
);
assert.throws(
() => engine.render.setContactSonar({ opacity: 120 }),
TypeError,
);
engine.destroy();
assert.equal(destroyed, 1);
});
test('without a styles port the engine has no visualStyles capability', () => {
const { engine } = setup();
assert.equal(engineCapabilities(engine).visualStyles, false);
assert.equal(engineCapabilities(engine).bloom, false);
assert.equal(engineCapabilities(engine).cloudCover, false);
assert.equal(engineCapabilities(engine).contactSonar, false);
assert.equal(engine.render.setStyle, undefined);
assert.equal(engine.render.setBloom, undefined);
});
+2
View File
@@ -25,6 +25,7 @@ import { createNavaraSharpen } from './sharpen.js';
import { createNavaraStyles } from './stylePasses.js';
import { createNavaraBloom } from './bloom.js';
import { createNavaraCloudCover } from './cockpitClouds.js';
import { createNavaraSonar } from './sonar.js';
import { retroShader } from '../../styles/retro.js';
import { nightVisionShader } from '../../styles/surveillance.js';
import { thermalShader } from '../../styles/thermal.js';
@@ -161,6 +162,7 @@ export async function createNavaraGlobe({
sharpen: createNavaraSharpen(view),
bloom: createNavaraBloom(view),
clouds: createNavaraCloudCover(look),
sonar: createNavaraSonar(view),
styles: createNavaraStyles(view, {
shaders: STYLE_SHADERS,
onStarsDimmed: (amount) => look.setStarsDimmed(amount),
+17 -2
View File
@@ -30,6 +30,7 @@ import {
OVERLAY_DEPTH_MODES,
OVERLAY_DEPTH_VERTEX,
} from '../overlayDepth.js';
import { DETACHED_SONAR, SONAR_VERTEX } from '../sonar.js';
const VERTEX_HEAD = /* glsl */ `
attribute vec4 gevStyle;
@@ -48,7 +49,10 @@ varying vec2 vGevLocal;
varying float vGevOutline;
varying float vGevPixelDistance;
varying float vGevTranslucency;
varying float vGevSonarFactor;
uniform vec2 uGevResolution;
${OVERLAY_DEPTH_VERTEX}
${SONAR_VERTEX}
`;
const VERTEX_PROJECT = /* glsl */ `
@@ -96,7 +100,10 @@ vec2 gevTurned = vec2(
vec4 mvPosition = mvCenter;
mvPosition.xy += gevTurned * gevSizePx * uGevFootprint * max(-mvCenter.z, 0.0);
gl_Position = projectionMatrix * mvPosition;
vGevColor = gevColor;
// The Cyber sonar (sonar.js): by the anchor's place on screen, never the
// corner's, so a contact is treated whole; the position stays as it is.
vGevSonarFactor = gevSonarFactor(projectionMatrix * mvCenter, uGevResolution);
vGevColor = gevSonarColor(gevColor, vGevSonarFactor);
vGevLocal = gevCorner;
#ifndef GEV_ALWAYS_VISIBLE
vGevDepthFree = gevDistance < uGevDisableWithinM ? 1.0 : 0.0;
@@ -117,6 +124,7 @@ varying vec2 vGevLocal;
varying float vGevOutline;
varying float vGevPixelDistance;
varying float vGevTranslucency;
varying float vGevSonarFactor;
${OVERLAY_DEPTH_FRAGMENT}
`;
@@ -135,7 +143,8 @@ float gevDistanceToCenter = gevRadius * 0.5;
float gevWholeAlpha = 1.0 - smoothstep(gevMaxDistance, 0.5, gevDistanceToCenter);
float gevInner = 1.0 - vGevOutline;
float gevInnerAlpha = 1.0 - smoothstep(gevMaxDistance * gevInner, 0.5 * gevInner, gevDistanceToCenter);
diffuseColor *= sRGBTransferEOTF(mix(uGevOutlineColor, vGevColor, gevInnerAlpha));
vec4 gevOutline = vec4(uGevOutlineColor.rgb, uGevOutlineColor.a * vGevSonarFactor);
diffuseColor *= sRGBTransferEOTF(mix(gevOutline, vGevColor, gevInnerAlpha));
diffuseColor.a *= gevWholeAlpha * vGevTranslucency;
if (diffuseColor.a < 0.005) discard;
`
@@ -290,6 +299,12 @@ export function createMoverMesh(
uGevResolution: overlayUniforms.uGevResolution,
uGevDisplayBlend:
overlayUniforms.uGevDisplayBlend ?? DETACHED_OVERLAY.uGevDisplayBlend,
// Shared by every overlay of the view: the Cyber sonar (sonar.js).
uGevSonar: overlayUniforms.uGevSonar ?? DETACHED_SONAR.uGevSonar,
uGevSonarSector:
overlayUniforms.uGevSonarSector ?? DETACHED_SONAR.uGevSonarSector,
uGevSonarEnabled:
overlayUniforms.uGevSonarEnabled ?? DETACHED_SONAR.uGevSonarEnabled,
};
// A canvas atlas is there at once; a URL one once its image loads.
let textureReady = point || Boolean(options.sprite.atlas.canvas);
+3
View File
@@ -15,6 +15,7 @@
import { withFrameUpdates } from './frameDescriptor.js';
import { EffectDesc, Pass as NavaraPass } from '@navaramap/three';
import { GevOverlayPass } from './overlayPass.js';
import { sonarUniformsFor } from './sonar.js';
import { RGBADepthPacking, Scene } from 'three';
export const OVERLAY_EFFECT_KEY = 'gevOverlay';
@@ -110,6 +111,8 @@ export function createNavaraOverlay(view, { beforeSharpen = false } = {}) {
uGevDisplayBlend: { value: 0 },
tGevSceneDepth: { value: null },
uGevResolution: { value: [0, 0] },
// The Cyber sonar's, shared by the view's overlays (sonar.js).
...sonarUniformsFor(view),
},
attach(context) {
ctx = context;
+129
View File
@@ -0,0 +1,129 @@
// The Cyber HUD's contact sonar on Navara (render.setContactSonar): the
// sweep's treatment of contacts, drawn by the sprite and point movers'
// shaders (movers/moverMesh.js) from uniforms every overlay of a view
// shares. The rings and the sweep itself are the HUD's own (CSS,
// src/cyberSonar.js); this is the contact side, the counterpart of the
// Cesium command adapter (src/cyberSonarGpu.js), with the same maths: each
// contact's factor from its anchor's place on screen against the sweep (the
// sampler of src/cyberSonar.js createCyberSonarSampler), its colour pulled
// toward the scanner tint by that factor and its alpha scaled by it.
// Positions, picks and the instance data stay as the layers set them.
// Models keep their colours (Cesium tints them on the CPU).
const views = new WeakMap();
/**
* The sonar uniforms of a view, one object for all its overlays (overlay.js
* spreads them into each overlay's uniforms):
* - uGevSonar: angle (deg, clockwise from screen up), range (fraction of
* the keyhole radius min(0.4 width, 0.52 height)), opacity floor (0..1),
* sweep on (1) or off (0);
* - uGevSonarSector: the sector's width (deg);
* - uGevSonarEnabled: 1 while the Cyber contact treatment applies.
*/
export function sonarUniformsFor(view) {
let uniforms = views.get(view);
if (!uniforms) {
uniforms = {
uGevSonar: { value: [0, 1, 0.84, 0] },
uGevSonarSector: { value: 24 },
uGevSonarEnabled: { value: 0 },
};
views.set(view, uniforms);
}
return uniforms;
}
/** Sonar uniforms of a mesh drawn outside an overlay (tests): off. */
export const DETACHED_SONAR = Object.freeze({
uGevSonar: { value: [0, 1, 0.84, 0] },
uGevSonarSector: { value: 24 },
uGevSonarEnabled: { value: 0 },
});
/**
* Vertex declarations and gevSonarFactor(anchor, resolution): the factor of
* a contact whose anchor is at clip position `anchor`, in a target of
* `resolution` pixels; 1 when the treatment is off.
*/
export const SONAR_VERTEX = /* glsl */ `
uniform vec4 uGevSonar;
uniform float uGevSonarSector;
uniform float uGevSonarEnabled;
float gevSonarFactor(vec4 anchor, vec2 resolution) {
if (uGevSonarEnabled < 0.5) return 1.0;
float floorValue = uGevSonar.z;
if (uGevSonar.w < 0.5) return floorValue + (1.0 - floorValue) * 0.46;
// Invalid projections fail open, as the CPU sampler does.
if (anchor.w <= 0.0 || resolution.x < 1.0 || resolution.y < 1.0) return 1.0;
vec2 pixel = anchor.xy / anchor.w * resolution * 0.5;
float radius = min(resolution.x * 0.4, resolution.y * 0.52) * uGevSonar.y;
float distanceSquared = dot(pixel, pixel);
float radiusSquared = radius * radius;
if (distanceSquared > radiusSquared) return floorValue;
if (distanceSquared < radiusSquared * 0.000625) return 1.0;
float delta = mod(degrees(atan(pixel.x, pixel.y)) - uGevSonar.x + 360.0, 360.0);
if (delta > 359.9999) delta = 0.0;
if (delta > uGevSonarSector) return floorValue;
float feather = min(10.0, uGevSonarSector * 0.42);
return floorValue + (1.0 - floorValue) * min(1.0, (uGevSonarSector - delta) / feather);
}
vec4 gevSonarColor(vec4 color, float factor) {
if (uGevSonarEnabled < 0.5) return color;
float floorValue = uGevSonar.z;
float coverage = floorValue >= 0.9999 ? 1.0 : clamp((factor - floorValue) / (1.0 - floorValue), 0.0, 1.0);
vec3 tint = color.rgb * 0.28 + (vec3(0.62, 0.68, 0.72) + vec3(0.38, 0.16, 0.12) * coverage) * 0.72;
return vec4(tint, color.a * factor);
}
`;
/**
* gevSonarFactor in JS, line for line (tests hold it to the CPU sampler of
* src/cyberSonar.js): `x`, `y` CSS pixels from the top-left of a
* `width` × `height` view; `state` as render.setContactSonar takes it.
*/
export function sonarFactorAt(x, y, width, height, state) {
if (!state.enabled) return 1;
const floor = state.opacity / 100;
if (!state.active) return floor + (1 - floor) * 0.46;
if (![x, y].every(Number.isFinite) || width < 1 || height < 1) return 1;
// Screen up is +y here, as in clip space.
const px = x - width / 2;
const py = height / 2 - y;
const radius = (Math.min(width * 0.4, height * 0.52) * state.range) / 100;
const distanceSquared = px * px + py * py;
const radiusSquared = radius * radius;
if (distanceSquared > radiusSquared) return floor;
if (distanceSquared < radiusSquared * 0.000625) return 1;
let delta =
((((Math.atan2(px, py) * 180) / Math.PI - state.angleDeg + 360) % 360) +
360) %
360;
if (delta > 359.9999) delta = 0;
if (delta > state.sector) return floor;
const feather = Math.min(10, state.sector * 0.42);
return floor + (1 - floor) * Math.min(1, (state.sector - delta) / feather);
}
/**
* The sonar port createNavaraEngine takes: `set(state)` (already checked)
* writes the view's sonar uniforms; `destroy()` turns the treatment off.
* @param {object} view an initialised ThreeView
*/
export function createNavaraSonar(view) {
const uniforms = sonarUniformsFor(view);
return {
set({ enabled, active, angleDeg, range, opacity, sector }) {
const sonar = uniforms.uGevSonar.value;
sonar[0] = angleDeg;
sonar[1] = range / 100;
sonar[2] = opacity / 100;
sonar[3] = active ? 1 : 0;
uniforms.uGevSonarSector.value = sector;
uniforms.uGevSonarEnabled.value = enabled ? 1 : 0;
},
destroy() {
uniforms.uGevSonarEnabled.value = 0;
},
};
}
+134
View File
@@ -0,0 +1,134 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createCyberSonarSampler } from '../../cyberSonar.js';
import { patchMoverShader } from './movers/moverMesh.js';
import {
DETACHED_SONAR,
SONAR_VERTEX,
createNavaraSonar,
sonarFactorAt,
sonarUniformsFor,
} from './sonar.js';
// A document root carrying the Cyber sonar settings, as the HUD writes them.
const rootWith = ({ range, opacity, sector }) => ({
dataset: {
cyberSonarRange: String(range),
cyberSonarOpacity: String(opacity),
cyberSonarSector: String(sector),
},
});
test('the shader factor is the CPU sampler of cyberSonar.js', () => {
const settings = [
{ range: 100, opacity: 84, sector: 24 },
{ range: 60, opacity: 35, sector: 8 },
{ range: 120, opacity: 50, sector: 60 },
];
for (const { width, height } of [
{ width: 1280, height: 800 },
{ width: 390, height: 844 },
])
for (const setting of settings)
for (const nowMs of [0, 700, 2600, 4100, 5199]) {
const sampler = createCyberSonarSampler(
width,
height,
nowMs,
rootWith(setting),
);
const angleDeg = ((((nowMs % 5200) + 5200) % 5200) / 5200) * 360;
const state = { enabled: true, active: true, angleDeg, ...setting };
for (let y = 0; y <= height; y += height / 16)
for (let x = 0; x <= width; x += width / 16) {
const expected = sampler.at(x, y);
const actual = sonarFactorAt(x, y, width, height, state);
assert.ok(
Math.abs(actual - expected) < 1e-9,
`${width}x${height} ${JSON.stringify(setting)} t=${nowMs} (${x}, ${y}): ${actual} vs ${expected}`,
);
}
// The sweep off: the sampler's neutral factor everywhere.
assert.ok(
Math.abs(
sonarFactorAt(10, 10, width, height, { ...state, active: false }) -
sampler.neutral,
) < 1e-12,
);
}
// Off: contacts unchanged.
assert.equal(
sonarFactorAt(5, 5, 100, 100, { enabled: false, active: true }),
1,
);
});
test('the GLSL carries the same rule as its JS twin', () => {
for (const term of [
'radiusSquared * 0.000625',
'min(resolution.x * 0.4, resolution.y * 0.52) * uGevSonar.y',
'floorValue + (1.0 - floorValue) * 0.46',
'min(10.0, uGevSonarSector * 0.42)',
'degrees(atan(pixel.x, pixel.y)) - uGevSonar.x + 360.0',
'color.rgb * 0.28 + (vec3(0.62, 0.68, 0.72) + vec3(0.38, 0.16, 0.12) * coverage) * 0.72',
'color.a * factor',
])
assert.ok(SONAR_VERTEX.includes(term), term);
});
test('the mover shaders treat contacts by their anchor and keep their position', () => {
for (const point of [false, true]) {
const shader = patchMoverShader(
{
uniforms: {},
vertexShader:
'void main() {\n#include <uv_vertex>\n#include <project_vertex>\n}',
fragmentShader:
'void main() {\n#include <color_fragment>\n#include <colorspace_fragment>\n}',
},
{},
{ point },
);
assert.match(
shader.vertexShader,
/vGevSonarFactor = gevSonarFactor\(projectionMatrix \* mvCenter, uGevResolution\);/,
);
assert.match(
shader.vertexShader,
/vGevColor = gevSonarColor\(gevColor, vGevSonarFactor\);/,
);
// gl_Position comes from the corner before the sonar runs.
assert.ok(
shader.vertexShader.indexOf(
'gl_Position = projectionMatrix * mvPosition',
) < shader.vertexShader.indexOf('gevSonarFactor(projectionMatrix'),
);
if (point)
assert.match(
shader.fragmentShader,
/uGevOutlineColor\.a \* vGevSonarFactor/,
);
}
});
test('one set of sonar uniforms per view, written by the port', () => {
const view = {};
const uniforms = sonarUniformsFor(view);
assert.equal(sonarUniformsFor(view), uniforms, 'shared by its overlays');
assert.notEqual(sonarUniformsFor({}), uniforms);
assert.equal(DETACHED_SONAR.uGevSonarEnabled.value, 0);
const port = createNavaraSonar(view);
port.set({
enabled: true,
active: true,
angleDeg: 120,
range: 80,
opacity: 50,
sector: 30,
});
assert.deepEqual(uniforms.uGevSonar.value, [120, 0.8, 0.5, 1]);
assert.equal(uniforms.uGevSonarSector.value, 30);
assert.equal(uniforms.uGevSonarEnabled.value, 1);
port.destroy();
assert.equal(uniforms.uGevSonarEnabled.value, 0);
});