diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 4b54e2670..08a5326bf 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -3236,7 +3236,6 @@ "src/hudLayouts.js", "src/hudLayoutPolicy.js", "src/ui/radioPanelPlacement.js", - "src/cyberSonarGpu.js", "src/render/cesium/iconSetPrimitive.js", "src/data/iconSet.js", "src/data/iconSegment.js", diff --git a/src/app/embed.js b/src/app/embed.js index 6cf272584..bd46485ba 100644 --- a/src/app/embed.js +++ b/src/app/embed.js @@ -18,6 +18,9 @@ import { cameraOf } from '../render/cesium/camera.js'; // panel, Import and others): a viewer with no renderer bound gets its globe // port from here, as it gets its camera. import '../render/cesium/globe.js'; +// The application's data reaches `findEffects` (the cyber contact sweep): +// such a viewer gets its effects port from here too. +import '../render/cesium/effects.js'; import { annotationsFromParams, createView } from '../view/index.js'; const EMBED_VIEW_MESSAGE = 'gev:view'; diff --git a/src/cyberSonarGpu.js b/src/cyberSonarGpu.js deleted file mode 100644 index 70e7e6908..000000000 --- a/src/cyberSonarGpu.js +++ /dev/null @@ -1,304 +0,0 @@ -import * as Cesium from 'cesium'; -import { IconSetPrimitive } from './render/cesium/iconSetPrimitive.js'; - -// Narrow, version-tested engine adapter. Cesium has no public custom shader -// option for native point/billboard collections. Do not patch its prototypes or -// access EntityCluster's private collections. An engine upgrade must revalidate -// this adapter; unsupported versions keep the original commands unchanged. -export const CYBER_SONAR_CESIUM_VERSION = '1.138.0'; - -// Follow every public DrawCommand setter, including pick/shadow/culling flags. -// Copying native.dirty would keep derived pipelines dirty forever: the scene -// consumes our command, so it never clears that flag on the native command. -const commandProperties = Object.entries( - Object.getOwnPropertyDescriptors(Cesium.DrawCommand.prototype), -) - .filter( - ([key, descriptor]) => - descriptor.set && key !== 'shaderProgram' && key !== 'uniformMap', - ) - .map(([key]) => key); - -export function syncCyberSonarCommand( - native, - record, - program, - uniforms, - labelBackground, -) { - if (!record.command) { - record.command = new Cesium.DrawCommand(); - record.uniformMap = { - ...uniforms, - u_gevSonarLabelBackground: () => record.labelBackground, - }; - } - const command = record.command; - record.labelBackground = labelBackground; - // Uniform values (angle/viewport/etc.) change through stable callbacks, not - // new maps/functions. Owner callback replacement and removal still propagate. - for (const key in record.uniformMap) { - if ( - !(key in uniforms) && - key !== 'u_gevSonarLabelBackground' && - !(key in native.uniformMap) - ) { - delete record.uniformMap[key]; - command.dirty = true; - } - } - for (const key in native.uniformMap) { - if (record.uniformMap[key] !== native.uniformMap[key]) { - record.uniformMap[key] = native.uniformMap[key]; - command.dirty = true; - } - } - for (const key of commandProperties) command[key] = native[key]; - command.shaderProgram = program; - command.uniformMap = record.uniformMap; - return command; -} - -export function sonarVertexSource(source, kind) { - const text = source.sources.join('\n'); - const attribute = - kind === 'point' ? 'positionHighAndSize' : 'positionHighAndScale'; - const lowAttribute = - kind === 'point' ? 'positionLowAndOutline' : 'positionLowAndRotation'; - // Icon sets move rows on the GPU, so their shader publishes the anchor itself. - const anchorSource = - kind === 'icon' - ? 'iconAnchorClip' - : `czm_modelViewProjectionRelativeToEye * czm_translateRelativeToEye(${attribute}.xyz, ${lowAttribute}.xyz)`; - if ( - (kind === 'icon' - ? !text.includes('iconAnchorClip') - : !text.includes(attribute) || !text.includes(lowAttribute)) || - !text.includes('v_color') || - !/void\s+main\s*\(\s*\)/.test(text) - ) - return null; - const next = source.clone(); - next.sources = [ - text.replace(/void\s+main\s*\(\s*\)/, 'void gev_sonar_main()'), - ` -uniform vec4 u_gevSonar; // angle, radius, opacity floor, sweep enabled -uniform vec2 u_gevSonarViewport; -uniform float u_gevSonarSector; -uniform float u_gevSonarLabelBackground; -void main() { - gev_sonar_main(); - // All corners/glyphs share the contact anchor, before native screen offsets. - // Leave gl_Position untouched so appearance never changes geometry or picks. - vec4 anchor = ${anchorSource}; - if (anchor.w <= 0.0) return; - vec2 pixel = anchor.xy / anchor.w * u_gevSonarViewport * 0.5; - float floorValue = u_gevSonar.z; - float factor = floorValue + (1.0 - floorValue) * 0.46; - if (u_gevSonar.w > 0.5) { - float distanceSquared = dot(pixel, pixel); - float radiusSquared = u_gevSonar.y * u_gevSonar.y; - float delta = mod(degrees(atan(pixel.x, pixel.y)) - u_gevSonar.x + 360.0, 360.0); - if (delta > 359.9999) delta = 0.0; - factor = floorValue; - if (distanceSquared < radiusSquared * 0.000625) factor = 1.0; - else if (distanceSquared <= radiusSquared && delta <= u_gevSonarSector) - factor += (1.0 - floorValue) * min(1.0, (u_gevSonarSector - delta) / min(10.0, u_gevSonarSector * 0.42)); - } - #ifdef SDF - factor = (1.0 + factor) * 0.5; - #else - if (u_gevSonarLabelBackground > 0.5) factor = (1.0 + factor) * 0.5; - #endif - float coverage = floorValue >= 0.9999 ? 1.0 : clamp((factor - floorValue) / (1.0 - floorValue), 0.0, 1.0); - if (u_gevSonarLabelBackground < 0.5) - v_color.rgb = v_color.rgb * 0.28 + (vec3(0.62, 0.68, 0.72) + vec3(0.38, 0.16, 0.12) * coverage) * 0.72; - // Apply before native fragment pass classification, never after main(). - v_color.a *= factor; - ${kind === 'point' ? 'v_outlineColor.a *= factor;' : kind === 'icon' ? '' : '#ifdef SDF\n v_outlineColor.a *= factor;\n #endif'} -} -`, - ]; - return next; -} - -// Use native batch bounds, never individual contacts, for idle render demand. -// Like Cesium's frustum builder, exclude the far plane (it fits multiple frusta). -export function isCyberSonarCommandVisible(command, frameState, culling) { - const bounds = command.boundingVolume; - if (!bounds || !command.cull) return true; - culling ??= new Cesium.CullingVolume( - frameState.cullingVolume.planes.slice(0, 5), - ); - if (culling.computeVisibility(bounds) === Cesium.Intersect.OUTSIDE) - return false; - return !( - frameState.mode === Cesium.SceneMode.SCENE3D && - frameState.occluder && - command.occlude && - bounds.isOccluded(frameState.occluder) - ); -} - -/** Work scales with draw commands, not the number of contacts in a collection. - * Source programs, colors, pick IDs, render states and other scenes stay owned - * by Cesium. Only this scene's rendered command slice receives derived shaders. - */ -export function createCyberSonarGpu(scene, readFrame) { - const root = scene.primitives; - const original = root.update; - const programs = new Map(); - let commands = new WeakMap(); - let disposed = false; - const stats = { - commands: 0, - visibleCommands: 0, - programs: 0, - supported: Cesium.VERSION === CYBER_SONAR_CESIUM_VERSION, - error: null, - }; - const uniforms = new Cesium.Cartesian4(); - const viewport = new Cesium.Cartesian2(); - let sector = 24; - const sonarUniforms = { - u_gevSonar: () => uniforms, - u_gevSonarViewport: () => viewport, - u_gevSonarSector: () => sector, - }; - const culling = new Cesium.CullingVolume(); - const used = new Set(); - const replaced = []; - const release = () => { - for (const { program } of programs.values()) - if (!program.isDestroyed()) program.destroy(); - programs.clear(); - commands = new WeakMap(); - used.clear(); - replaced.length = 0; - stats.programs = 0; - }; - const wrapped = function (frameState) { - const start = frameState.commandList.length; - original.call(this, frameState); - stats.commands = 0; - stats.visibleCommands = 0; - if ( - disposed || - !stats.supported || - !frameState.passes.render || - frameState.passes.pick - ) - return; - const frame = readFrame(); - if (!frame.enabled) { - if (programs.size) release(); - return; - } - viewport.x = scene.drawingBufferWidth; - viewport.y = scene.drawingBufferHeight; - uniforms.x = frame.angle; - uniforms.y = - (Math.min(viewport.x * 0.4, viewport.y * 0.52) * frame.range) / 100; - uniforms.z = frame.opacity / 100; - uniforms.w = frame.active ? 1 : 0; - sector = frame.sector; - used.clear(); - replaced.length = 0; - if (frameState.cullingVolume) - for (let i = 0; i < 5; i++) - culling.planes[i] = frameState.cullingVolume.planes[i]; - try { - for (let i = start; i < frameState.commandList.length; i++) { - const native = frameState.commandList[i]; - const kind = - native.owner instanceof Cesium.PointPrimitiveCollection - ? 'point' - : native.owner instanceof Cesium.BillboardCollection - ? 'billboard' - : native.owner instanceof IconSetPrimitive - ? 'icon' - : null; - if (!kind || !native.shaderProgram || !native.uniformMap) continue; - const source = native.shaderProgram; - // Label backgrounds are non-SDF billboard batches. The version-tested - // engine pick association distinguishes them without enumerating labels - // or reaching into EntityCluster. One representative per draw batch; - // Cesium's label glyph/background collections are homogeneous. - const labelBackground = - kind === 'billboard' && - !source.vertexShaderSource.defines.includes('SDF') && - native.owner.length > 0 && - native.owner.get(0).pickPrimitive instanceof Cesium.Label - ? 1 - : 0; - let entry = programs.get(source); - if (!entry) { - const vertex = sonarVertexSource(source.vertexShaderSource, kind); - if (!vertex) throw new Error('Unsupported native contact shader'); - const attributes = Object.fromEntries( - Object.entries(source.vertexAttributes).map(([name, value]) => [ - name, - value.index, - ]), - ); - const program = Cesium.ShaderProgram.fromCache({ - context: frameState.context, - vertexShaderSource: vertex, - fragmentShaderSource: source.fragmentShaderSource, - attributeLocations: attributes, - }); - // Compile while errors can still leave the whole native command slice - // intact, rather than stopping the viewer's render loop at draw time. - try { - void program.allUniforms; - } catch (error) { - program.destroy(); - throw error; - } - programs.set(source, (entry = { program })); - } - used.add(source); - let record = commands.get(native); - if (!record) commands.set(native, (record = {})); - const derived = syncCyberSonarCommand( - native, - record, - entry.program, - sonarUniforms, - labelBackground, - ); - replaced.push(i, native); - frameState.commandList[i] = derived; - stats.commands++; - if (isCyberSonarCommandVisible(native, frameState, culling)) - stats.visibleCommands++; - } - for (const [source, entry] of programs) - if (!used.has(source)) { - if (!entry.program.isDestroyed()) entry.program.destroy(); - programs.delete(source); - } - stats.programs = programs.size; - } catch (error) { - // Recover the original commands already replaced in this slice. - for (let i = 0; i < replaced.length; i += 2) - frameState.commandList[replaced[i]] = replaced[i + 1]; - stats.supported = false; - stats.commands = 0; - stats.visibleCommands = 0; - stats.error = String(error?.message || error); - release(); - } - }; - root.update = wrapped; - return { - stats, - destroy() { - if (disposed) return; - disposed = true; - if (root.update === wrapped && !root.isDestroyed?.()) - root.update = original; - release(); - }, - }; -} diff --git a/src/cyberSonarGpu.test.mjs b/src/cyberSonarGpu.test.mjs deleted file mode 100644 index 8507620ba..000000000 --- a/src/cyberSonarGpu.test.mjs +++ /dev/null @@ -1,354 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; -import { - createCyberSonarGpu, - sonarVertexSource, - CYBER_SONAR_CESIUM_VERSION, - isCyberSonarCommandVisible, - syncCyberSonarCommand, -} from './cyberSonarGpu.js'; - -test('stable commands reuse uniforms and derived pipelines while all native fields remain live', () => { - const native = new Cesium.DrawCommand({ - count: 6, - uniformMap: { value: () => 1 }, - }); - const record = {}, - program = {}, - uniforms = { u_gevSonar: () => 42 }; - const derived = syncCyberSonarCommand(native, record, program, uniforms, 0); - const map = derived.uniformMap; - derived.dirty = false; - derived.lastDirtyTime = 7; - assert.equal(native.dirty, true); - assert.equal( - syncCyberSonarCommand(native, record, program, uniforms, 1), - derived, - ); - assert.equal( - derived.dirty, - false, - 'stale native dirty flag must not rebuild pipelines', - ); - assert.equal(derived.lastDirtyTime, 7); - assert.equal(derived.uniformMap, map); - assert.equal(map.u_gevSonarLabelBackground(), 1); - for (const [key, value] of Object.entries({ - count: 12, - offset: 2, - instanceCount: 3, - pickId: 'pick', - pass: Cesium.Pass.TRANSLUCENT, - cull: false, - occlude: false, - castShadows: true, - receiveShadows: true, - pickOnly: true, - renderState: {}, - vertexArray: {}, - modelMatrix: Cesium.Matrix4.IDENTITY, - framebuffer: {}, - })) { - derived.dirty = false; - native[key] = value; - syncCyberSonarCommand(native, record, program, uniforms, 0); - assert.equal(derived[key], value, key); - assert.equal(derived.dirty, true, key); - } - native.uniformMap.value = () => 2; - syncCyberSonarCommand(native, record, program, uniforms, 0); - assert.equal(map.value(), 2); - native.uniformMap = { replacement: () => 3 }; - syncCyberSonarCommand(native, record, program, uniforms, 0); - assert.equal(map.value, undefined); - assert.equal(map.replacement(), 3); - assert.equal(map.u_gevSonar(), 42); - const nextProgram = {}; - syncCyberSonarCommand(native, record, nextProgram, uniforms, 0); - assert.equal(derived.shaderProgram, nextProgram); - assert.equal(native.shaderProgram, undefined); -}); - -test('GPU shader transform is isolated, settings-driven, and precedes native fragment classification', () => { - assert.equal( - Cesium.VERSION, - CYBER_SONAR_CESIUM_VERSION, - 'engine upgrades require GPU revalidation', - ); - for (const [kind, attr, low] of [ - ['point', 'positionHighAndSize', 'positionLowAndOutline'], - ['billboard', 'positionHighAndScale', 'positionLowAndRotation'], - ]) { - const source = new Cesium.ShaderSource({ - defines: ['SDF'], - sources: [ - `in vec4 ${attr}; in vec4 ${low}; out vec4 v_color; void main() { v_color=vec4(1.); }`, - ], - }); - const original = source.sources[0]; - const next = sonarVertexSource(source, kind); - assert.equal(source.sources[0], original); - assert.notEqual(next, source); - assert.deepEqual(next.defines, ['SDF']); - assert.match(next.sources[0], /void gev_sonar_main/); - assert.match(next.sources[1], /v_color.a \*= factor/); - assert.match(next.sources[1], /u_gevSonarSector/); - assert.match(next.sources[1], /floorValue \+ \(1.0 - floorValue\) \* 0.46/); - assert.ok( - next.sources[1].includes( - `czm_translateRelativeToEye(${attr}.xyz, ${low}.xyz)`, - ), - ); - assert.match(next.sources[1], /anchor.xy \/ anchor.w/); - assert.doesNotMatch(next.sources[1], /gl_Position\s*[=\/]/); - } - assert.equal( - sonarVertexSource( - new Cesium.ShaderSource({ sources: ['void main() {}'] }), - 'point', - ), - null, - ); -}); - -test('render demand follows batch bounds, including horizon culling, without far-plane rejection', () => { - const planes = Array.from( - { length: 6 }, - (_, i) => new Cesium.Cartesian4(1, 0, 0, i), - ); - const frame = { - cullingVolume: { planes }, - mode: Cesium.SceneMode.SCENE3D, - occluder: {}, - }; - let intersections = 0; - let occluded = false; - const command = { - cull: true, - occlude: true, - boundingVolume: { - intersectPlane(plane) { - intersections++; - return plane.distance === 5 - ? Cesium.Intersect.OUTSIDE - : Cesium.Intersect.INSIDE; - }, - isOccluded() { - return occluded; - }, - }, - }; - assert.equal(isCyberSonarCommandVisible(command, frame), true); - assert.equal(intersections, 5); - occluded = true; - assert.equal(isCyberSonarCommandVisible(command, frame), false); - frame.mode = Cesium.SceneMode.SCENE2D; - assert.equal(isCyberSonarCommandVisible(command, frame), true); - command.boundingVolume.intersectPlane = () => Cesium.Intersect.OUTSIDE; - assert.equal(isCyberSonarCommandVisible(command, frame), false); - command.cull = false; - assert.equal(isCyberSonarCommandVisible(command, frame), true); - assert.equal(isCyberSonarCommandVisible({}, frame), true); -}); - -test('adapter never walks contacts, touches other scenes, or transforms pick-only passes', () => { - let calls = 0; - const original = function (fs) { - assert.equal(this, root); - calls++; - fs.commandList.push({ owner: {}, id: 'terrain' }); - }; - const root = { update: original }; - const other = { update: original }; - const adapter = createCyberSonarGpu({ primitives: root }, () => ({ - enabled: false, - })); - const frame = { commandList: [], passes: { render: true, pick: false } }; - root.update(frame); - assert.equal(calls, 1); - assert.equal(frame.commandList[0].id, 'terrain'); - assert.equal(other.update, original); - root.update({ commandList: [], passes: { render: false, pick: true } }); - assert.equal(calls, 2); - adapter.destroy(); - adapter.destroy(); - assert.equal(root.update, original); -}); - -test('unknown native shaders fail closed without losing native commands', () => { - const points = new Cesium.PointPrimitiveCollection(); - const command = { - owner: points, - uniformMap: {}, - shaderProgram: { - vertexShaderSource: new Cesium.ShaderSource({ - sources: ['void main() {}'], - }), - }, - }; - const root = { - update(fs) { - fs.commandList.push(command); - }, - }; - const adapter = createCyberSonarGpu( - { primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 }, - () => ({ - enabled: true, - active: true, - angle: 0, - range: 100, - opacity: 84, - sector: 24, - }), - ); - const frame = { commandList: [], passes: { render: true } }; - root.update(frame); - assert.equal(frame.commandList[0], command); - assert.equal(adapter.stats.supported, false); - assert.match(adapter.stats.error, /Unsupported native contact shader/); - assert.equal(adapter.stats.programs, 0); - adapter.destroy(); - points.destroy(); -}); - -test('program swaps, layer removal and late shader failure release only adapter resources', () => { - const points = new Cesium.PointPrimitiveCollection(); - const source = () => ({ - vertexShaderSource: new Cesium.ShaderSource({ - sources: [ - 'in vec4 positionHighAndSize; in vec4 positionLowAndOutline; out vec4 v_color; void main() {}', - ], - }), - vertexAttributes: {}, - fragmentShaderSource: new Cesium.ShaderSource({ - sources: ['void main() {}'], - }), - }); - const native = new Cesium.DrawCommand({ - owner: points, - uniformMap: {}, - shaderProgram: source(), - cull: false, - vertexArray: { generation: 1 }, - pickId: 'native-pick', - }); - const unknown = new Cesium.DrawCommand({ - owner: points, - uniformMap: {}, - shaderProgram: { - vertexShaderSource: new Cesium.ShaderSource({ - sources: ['void main() {}'], - }), - }, - }); - let nativeCommands = [native]; - let enabled = true; - const root = { - update(frame) { - frame.commandList.push(...nativeCommands); - }, - }; - const fromCache = Cesium.ShaderProgram.fromCache; - const created = []; - Cesium.ShaderProgram.fromCache = () => { - const program = { - allUniforms: {}, - destroyed: false, - isDestroyed() { - return this.destroyed; - }, - destroy() { - assert.equal(this.destroyed, false); - this.destroyed = true; - }, - }; - created.push(program); - return program; - }; - const adapter = createCyberSonarGpu( - { primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 }, - () => ({ - enabled, - active: true, - angle: 0, - range: 100, - opacity: 84, - sector: 24, - }), - ); - const draw = () => { - const frame = { commandList: [], passes: { render: true } }; - root.update(frame); - return frame.commandList; - }; - try { - const first = draw()[0]; - assert.notEqual(first, native); - first.dirty = false; - assert.equal(draw()[0], first); - assert.equal(first.dirty, false); - assert.equal(created.length, 1, 'stable draws reuse the program'); - const buffer = { generation: 2 }; - native.vertexArray = buffer; - native.shaderProgram = source(); - const swapped = draw()[0]; - assert.equal(swapped, first); - assert.equal(swapped.vertexArray, buffer); - assert.equal(swapped.pickId, 'native-pick'); - assert.equal(swapped.shaderProgram, created[1]); - assert.equal(created[0].destroyed, true); - assert.equal(adapter.stats.programs, 1); - nativeCommands = []; - draw(); - assert.equal(created[1].destroyed, true); - assert.equal( - adapter.stats.programs, - 0, - 'disabled layers retain no adapter program', - ); - nativeCommands = [native]; - draw(); - enabled = false; - assert.equal(draw()[0], native); - assert.equal( - created[2].destroyed, - true, - 'theme/cockpit exit releases the derived program', - ); - enabled = true; - nativeCommands = [native, unknown]; - assert.deepEqual( - draw(), - nativeCommands, - 'a later failure rolls back earlier replacements in the same slice', - ); - assert.equal(created[3].destroyed, true); - assert.equal(adapter.stats.supported, false); - assert.equal(adapter.stats.programs, 0); - assert.equal(adapter.stats.commands, 0); - assert.equal(adapter.stats.visibleCommands, 0); - assert.deepEqual(draw(), nativeCommands); - assert.equal( - created.length, - 4, - 'unsupported draws do not retry compilation', - ); - } finally { - adapter.destroy(); - Cesium.ShaderProgram.fromCache = fromCache; - points.destroy(); - } -}); - -test('disposal does not overwrite a successor update owner', () => { - const root = { update() {} }; - const adapter = createCyberSonarGpu({ primitives: root }, () => ({ - enabled: false, - })); - const successor = () => {}; - root.update = successor; - adapter.destroy(); - assert.equal(root.update, successor); -}); diff --git a/src/cyberSonarScene.js b/src/cyberSonarScene.js index f07159cbf..68a80f997 100644 --- a/src/cyberSonarScene.js +++ b/src/cyberSonarScene.js @@ -1,211 +1,153 @@ -import * as Cesium from 'cesium'; -import { createCyberSonarGpu } from './cyberSonarGpu.js'; +/** + * The Cyber contact sweep on the map's markers, through the renderer's + * `effects.screenModulation` (`src/render/contract/effects.d.ts`). This + * keeps the sweep's clock and settings; the renderer shades the markers. + * + * Each tick, before the renderer decides whether to draw: a change of the + * theme, the sweep, its settings or the map's size sets the sector at once; + * while sweeping, the sector moves to the current angle on every tick that + * draws anyway, and at least at the renderer's `sonarCadenceHz` (which then + * asks for a frame). Out of the theme the sector is cleared. + * + * A renderer without the capability, or one that does not list the pass + * once a sector is set, leaves markers as they are: the document's + * `cyberSonarGpu` says `unsupported`, so the HUD overlays skip their own + * sweep too, and the sonar status says so. + * + * The frame and effects ports are looked up once, when the scene is made: + * bind the renderer to the viewer before creating it. + */ import { - applyCyberSonarPrimitive, - createCyberSonarSampler, - isCyberContactThemeActive, - isCyberContactSonarActive, + CYBER_SONAR_RENDER_INTERVAL_MS, + cyberSonarSector, + isCyberMapThemeActive, isCyberSonarActive, readCyberSonarSettings, - cyberSonarAngleDeg, syncCyberSonarAnimation, - CYBER_SONAR_RENDER_INTERVAL_MS, } from './cyberSonar.js'; +import { + canvasOf, + findEffects, + findFrame, + rendererOf, +} from './render/rendererOf.js'; -const alive = (value) => value && !value.isDestroyed?.(); -const diagnostics = new WeakMap(); -export const getCyberSonarSceneDiagnostics = (viewer) => ({ - ...diagnostics.get(viewer), -}); +/** Sweep updates per second when the renderer's quality has no setting. */ +export const CYBER_SONAR_DEFAULT_CADENCE_HZ = + 1000 / CYBER_SONAR_RENDER_INTERVAL_MS; +const UNSUPPORTED_MESSAGE = + 'Contact GPU unavailable. Native contacts remain visible.'; -export function visitCyberSonarModels(primitive, visit, visible = true) { - if (!alive(primitive)) return; - visible = visible && primitive.show !== false; - if (primitive instanceof Cesium.PrimitiveCollection) { - for (let i = 0; i < primitive.length; i++) - visitCyberSonarModels(primitive.get(i), visit, visible); - } else if (primitive instanceof Cesium.Model) { - visit(primitive, primitive, 'model', visible && primitive.ready); - } -} - -/** Native dots, icons and glyphs use GPU draw-command treatment. Models retain - * their existing reversible CPU color treatment without walking native records. +/** + * @param {object} viewer The scene object the renderer is bound to. + * @param {{subscribe?: Function}} [manager] Layer visibility changes ask + * for a frame, so markers shown or hidden draw with the sweep. + * @returns {() => void} Clears the sector and lets go. */ export function createCyberSonarScene(viewer, manager) { - const scene = viewer?.scene; - if ( - !scene?.postUpdate?.addEventListener || - !scene?.preRender?.addEventListener - ) - return () => {}; - const tracked = new Map(); - const matrix = new Cesium.Matrix4(); - const position = new Cesium.Cartesian3(); - let epoch = 0, - timer = null, - disposed = false; - let sampler, width, height, active, count; - const stats = { contacts: 0, updateMs: 0, frames: 0 }; - const root = globalThis.document?.documentElement; - const gpu = createCyberSonarGpu(scene, () => ({ - ...readCyberSonarSettings(), - enabled: isCyberContactThemeActive(), - active: isCyberContactSonarActive(), - angle: cyberSonarAngleDeg(performance.now()), - })); - stats.gpu = gpu.stats; - let gpuSupported = gpu.stats.supported; - diagnostics.set(viewer, stats); - const restore = (visual, state) => { - if (!alive(state.owner)) return; - for (const key of state.keys) - applyCyberSonarPrimitive(visual, 1, false, undefined, key); + const frame = findFrame(viewer); + if (!frame) return () => {}; + const effects = findEffects(viewer); + const doc = globalThis.document; + const root = doc?.documentElement; + let failed = typeof effects?.screenModulation !== 'function'; + let current = null; + let key = null; + let lastSetAt = Number.NEGATIVE_INFINITY; + let interval = CYBER_SONAR_RENDER_INTERVAL_MS; + let disposed = false; + + const readCadence = () => { + const hz = Number(rendererOf(viewer)?.quality?.get?.()?.sonarCadenceHz); + interval = 1000 / (hz > 0 ? hz : CYBER_SONAR_DEFAULT_CADENCE_HZ); }; - const visit = (visual, owner, kind, visible) => { - let state = tracked.get(visual); - if (!visible) { - if (state) { - restore(visual, state); - tracked.delete(visual); - } - return; - } - let p = visual.position; - if (kind === 'model') - p = Cesium.Matrix4.getTranslation(visual.modelMatrix, position); - else if ( - p && - owner.modelMatrix && - !Cesium.Matrix4.equals(owner.modelMatrix, Cesium.Matrix4.IDENTITY) - ) - p = Cesium.Matrix4.multiplyByPoint(owner.modelMatrix, p, position); - if (!p) return; - const w = matrix[3] * p.x + matrix[7] * p.y + matrix[11] * p.z + matrix[15]; - const x = - (matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12]) / w; - const y = - (matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13]) / w; - if (w <= 0 || Math.abs(x) > 1.1 || Math.abs(y) > 1.1) return; - if (!state) { - state = { - owner, - keys: - kind === 'label' - ? ['fillColor', 'outlineColor', 'backgroundColor'] - : kind === 'marker' && visual.outlineColor - ? ['color', 'outlineColor'] - : ['color'], - epoch, - }; - tracked.set(visual, state); - } - state.epoch = epoch; - const factor = active - ? sampler.at((x + 1) * width * 0.5, (1 - y) * height * 0.5) - : sampler.neutral; - for (const key of state.keys) { - if (key === 'outlineColor' && visual.outlineWidth === 0) continue; - if (key === 'backgroundColor' && !visual.showBackground) continue; - applyCyberSonarPrimitive( - visual, - kind === 'label' ? sampler.label(factor) : factor, - true, - sampler, - key, - kind === 'model', - ); - } - count++; - }; - const update = () => { - if (disposed) return; - if (timer !== null) { - clearTimeout(timer); - timer = null; - } - if (!isCyberContactThemeActive()) { - for (const [visual, state] of tracked) restore(visual, state); - tracked.clear(); - stats.contacts = 0; - stats.updateMs = 0; - return; - } - const started = performance.now(); - width = scene.canvas.clientWidth; - height = scene.canvas.clientHeight; - sampler = createCyberSonarSampler(width, height, started); - active = isCyberContactSonarActive(); - Cesium.Matrix4.multiply( - scene.camera.frustum.projectionMatrix, - scene.camera.viewMatrix, - matrix, - ); - epoch++; - count = 0; - visitCyberSonarModels(scene.primitives, visit); - for (const [visual, state] of tracked) - if (state.epoch !== epoch) { - restore(visual, state); - tracked.delete(visual); - } - stats.contacts = count; - stats.updateMs = performance.now() - started; - stats.frames++; - // No contacts, no scanner-owned render demand. In continuous scenes the - // next rendered frame cancels this timer; parked scenes refresh at fleet - // cadence. Idle update-only ticks must not continually postpone the timer. - }; - let removeRender; - // Aircraft fleet writers run in preRender, while tracked models and entity - // visualizers update earlier. Compose AFTER all those owners and BEFORE - // Cesium uploads primitive attributes for this draw. Requeue at postUpdate - // so writers installed later (enable/re-enable/track) cannot overwrite sonar. - // This only reorders one callback; the contact walk runs once per actual draw. - const removeUpdate = scene.postUpdate.addEventListener(() => { - if (isCyberSonarActive()) syncCyberSonarAnimation(); - const supportChanged = gpuSupported !== gpu.stats.supported; - gpuSupported = gpu.stats.supported; - const support = gpu.stats.supported ? 'supported' : 'unsupported'; + + const publish = () => { + const support = failed ? 'unsupported' : 'supported'; if (root?.dataset && root.dataset.cyberSonarGpu !== support) root.dataset.cyberSonarGpu = support; - // Shader setup runs after preRender's model tint. If it fails while the - // scene is parked (including Sonar OFF/reduced motion), draw once more so - // the now-unsupported contact path restores models before becoming idle. - if (supportChanged) scene.requestRender(); - const status = globalThis.document?.getElementById?.('cyber-sonar-status'); - const message = gpu.stats.supported - ? '' - : 'Contact GPU unavailable. Native contacts remain visible.'; + const status = doc?.getElementById?.('cyber-sonar-status'); + const message = failed ? UNSUPPORTED_MESSAGE : ''; if (status && status.textContent !== message) status.textContent = message; - removeRender?.(); - removeRender = scene.preRender.addEventListener(update); - }); - const removePostRender = scene.postRender?.addEventListener(() => { - if (timer !== null) clearTimeout(timer); - timer = null; - if (isCyberContactSonarActive() && (count || gpu.stats.visibleCommands)) - timer = setTimeout(() => { - timer = null; - if (!disposed && isCyberContactSonarActive()) scene.requestRender(); - }, CYBER_SONAR_RENDER_INTERVAL_MS); + }; + + /** The renderer cannot draw the pass: markers stay as they are. */ + const fail = () => { + if (failed) return; + failed = true; + const had = current; + current = null; + key = null; + if (had) effects.screenModulation(null); + publish(); + }; + + const set = (sector, at) => { + const had = current; + // Before the call: its change listeners read `current`. + current = sector; + lastSetAt = at; + effects.screenModulation(sector); + // A first sector set but not listed is unsupported; a pass that stops + // later is caught by the change listener. + if ( + sector && + !had && + !effects.diagnostics().passes.includes('screenModulation') + ) + fail(); + }; + + const offTick = frame.on('preUpdate', (t) => { + if (disposed) return; + // The HUD's own sweep keeps its clock whether or not markers are shaded. + const active = isCyberSonarActive(); + if (active) syncCyberSonarAnimation(); + if (failed) return; + const theme = isCyberMapThemeActive(); + const sweeping = theme && active; + if (!theme) { + if (current) set(null, lastSetAt); + key = null; + return; + } + const canvas = canvasOf(viewer); + // The sector is in CSS pixels. + const width = canvas?.clientWidth ?? 0; + const height = canvas?.clientHeight ?? 0; + const settings = readCyberSonarSettings(root); + const next = `${sweeping}|${settings.range}|${settings.opacity}|${settings.sector}|${width}|${height}`; + const now = performance.now(); + if ( + next === key && + !(sweeping && (now - lastSetAt >= interval || t.rendering)) + ) + return; + key = next; + readCadence(); + set(cyberSonarSector(width, height, now, { sweeping, root }), now); }); + + const offChange = failed + ? null + : effects.on('change', (diagnostics) => { + if (current && !diagnostics.passes.includes('screenModulation')) fail(); + }); + const unsubscribe = manager?.subscribe?.((change) => { - if (change.type !== 'visibility') return; - scene.requestRender(); + if (change.type === 'visibility') frame.requestRender('cyber-sonar'); }); + + publish(); return () => { if (disposed) return; disposed = true; - removeUpdate(); - removeRender?.(); - removePostRender?.(); - gpu.destroy(); - if (root?.dataset) delete root.dataset.cyberSonarGpu; + offTick(); + offChange?.(); unsubscribe?.(); - if (timer !== null) clearTimeout(timer); - for (const [visual, state] of tracked) restore(visual, state); - tracked.clear(); - diagnostics.delete(viewer); + const had = current; + current = null; + if (had) effects.screenModulation(null); + if (root?.dataset) delete root.dataset.cyberSonarGpu; }; } diff --git a/src/cyberSonarScene.test.mjs b/src/cyberSonarScene.test.mjs index 7d0db8551..38b2da3f3 100644 --- a/src/cyberSonarScene.test.mjs +++ b/src/cyberSonarScene.test.mjs @@ -1,19 +1,16 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; import { + CYBER_SONAR_RENDER_INTERVAL_MS, + applyCyberSonarSettings, createCyberSonarSampler, cyberSonarIntensityAtScreenPoint, - applyCyberSonarPrimitive, - applyCyberSonarSettings, + cyberSonarSector, isCyberContactSonarActive, isCyberSonarActive, } from './cyberSonar.js'; -import { - createCyberSonarScene, - visitCyberSonarModels, - getCyberSonarSceneDiagnostics, -} from './cyberSonarScene.js'; +import { createCyberSonarScene } from './cyberSonarScene.js'; +import { bindRenderer } from './render/rendererOf.js'; test('frame sampler matches reference without per-contact settings access', () => { let reads = 0; @@ -47,44 +44,7 @@ test('frame sampler matches reference without per-contact settings access', () = ); }); -test('model walk never enumerates native contact or EntityCluster records', () => { - const root = new Cesium.PrimitiveCollection(); - const points = root.add(new Cesium.PointPrimitiveCollection()); - points.add(); - points.get = () => { - throw new Error('must not enumerate contacts'); - }; - const cluster = root.add(new Cesium.EntityCluster()); - Object.defineProperty(cluster, '_billboardCollection', { - get() { - throw new Error('must not access cluster internals'); - }, - configurable: true, - }); - const seen = []; - visitCyberSonarModels(root, (...v) => seen.push(v)); - assert.equal(seen.length, 0); - delete cluster._billboardCollection; - root.destroy(); -}); - -test('models retain render-pass alpha and owner refresh survives teardown', () => { - const frame = createCyberSonarSampler(1000, 800, 0); - const model = { color: new Cesium.Color(1, 0.5, 0.2, 1) }; - applyCyberSonarPrimitive(model, 0.5, true, frame, 'color', true); - assert.equal(model.color.alpha, 1); - assert.ok(model.color.red < 1); - const owner = new Cesium.Color(0.2, 0.3, 0.4, 0.7); - model.color = owner; - applyCyberSonarPrimitive(model, 1, false); - assert.equal(model.color, owner); - const unset = {}; - applyCyberSonarPrimitive(unset, 0.5, true, frame, 'color', true); - applyCyberSonarPrimitive(unset, 1, false); - assert.equal(unset.color, undefined); -}); - -test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail closed', () => { +test('removed CSS mode cannot disable GPU contacts; unsupported renderers fail closed', () => { const root = { dataset: { uiTheme: 'cyber' }, style: { setProperty() {} } }; const options = { root, @@ -106,209 +66,291 @@ test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail cl assert.equal(isCyberContactSonarActive(options), false); }); -test('native owner colors remain untouched and scene teardown releases listeners', () => { - const previous = globalThis.document; +test('the sector is the sweep the HUD shows, in CSS pixels and radians', () => { + const root = { + dataset: { + cyberSonarOpacity: '62', + cyberSonarSector: '40', + cyberSonarRange: '110', + }, + }; + const s = cyberSonarSector(1000, 800, 1300, { root }); + assert.deepEqual(s.center, { x: 500, y: 400 }); + assert.ok(Math.abs(s.angle - Math.PI / 2) < 1e-9, 'a quarter period'); + assert.ok(Math.abs(s.width - (40 * Math.PI) / 180) < 1e-12); + assert.ok(Math.abs(s.radius - 440) < 1e-9); + assert.equal(s.floor, 0.62); + assert.equal(s.strength, 0.72); + assert.equal(s.color, '#ffd6d6'); + const rest = cyberSonarSector(1000, 800, 1300, { root, sweeping: false }); + assert.equal(rest.radius, 0); + assert.ok(Math.abs(rest.floor - (0.62 + 0.38 * 0.46)) < 1e-12); +}); + +/** + * A document with the Cyber HUD shown, and a renderer fake bound to a + * viewer: its frame's preUpdate is ticked by hand and its effects record + * each sector. + */ +function fixture({ modulation = true, lists = true, cadenceHz } = {}) { + const previous = { + document: globalThis.document, + matchMedia: globalThis.matchMedia, + }; const root = { dataset: { uiTheme: 'cyber', cyberSonar: 'on' } }; - let cockpit = false; + const status = { textContent: '' }; + const state = { cockpit: false, reducedMotion: false }; globalThis.document = { documentElement: root, - body: { classList: { contains: () => cockpit } }, - getElementById: () => ({ classList: { contains: () => true } }), + body: { classList: { contains: () => state.cockpit } }, + getElementById: (id) => + id === 'cyber-sonar-status' + ? status + : { classList: { contains: () => true } }, }; - const primitives = new Cesium.PrimitiveCollection(); - const points = primitives.add(new Cesium.PointPrimitiveCollection()); - const point = points.add({ color: new Cesium.Color(0.3, 0.7, 0.5, 0.8) }); - const original = primitives.update; - const scene = { - primitives, - postUpdate: new Cesium.Event(), - preRender: new Cesium.Event(), - postRender: new Cesium.Event(), - canvas: { clientWidth: 1000, clientHeight: 800 }, - camera: { - frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY }, - viewMatrix: Cesium.Matrix4.IDENTITY, + globalThis.matchMedia = () => ({ matches: state.reducedMotion }); + const ticks = new Set(); + const changes = new Set(); + const sets = []; + const requests = []; + let drawing = null; + const effects = { + diagnostics: () => ({ + style: null, + passes: drawing && lists ? ['screenModulation'] : [], + }), + on(event, cb) { + changes.add(cb); + return () => changes.delete(cb); }, - requestRender() {}, }; - const viewer = { scene }; - const dispose = createCyberSonarScene(viewer); - try { - for (const enabled of ['on', 'off', 'on']) { - root.dataset.cyberSonar = enabled; - for (const opacity of [35, 84, 100]) { - root.dataset.cyberSonarOpacity = String(opacity); - point.color = new Cesium.Color(0.6, 0.4, 0.2, 0.7); - scene.postUpdate.raiseEvent(); - scene.preRender.raiseEvent(); - assert.equal(point.color.alpha, 0.7); - assert.equal(point.color.red, 0.6); - } - } - const previousTimeout = globalThis.setTimeout; - const previousClear = globalThis.clearTimeout; - let timers = 0; - globalThis.setTimeout = () => { - timers++; - return 1; + if (modulation) + effects.screenModulation = (sector) => { + const was = effects.diagnostics().passes.length; + drawing = sector; + sets.push(sector); + if (effects.diagnostics().passes.length !== was) + for (const cb of [...changes]) cb(effects.diagnostics()); }; - globalThis.clearTimeout = () => {}; - try { - const gpu = getCyberSonarSceneDiagnostics(viewer).gpu; - gpu.commands = 6; - gpu.visibleCommands = 0; - scene.postRender.raiseEvent(); - assert.equal(timers, 0, 'culled batches must not schedule a sonar draw'); - gpu.visibleCommands = 1; - scene.postRender.raiseEvent(); - assert.equal(timers, 1, 'a visible batch keeps the sweep moving'); - root.dataset.cyberSonar = 'off'; - scene.postRender.raiseEvent(); - assert.equal(timers, 1, 'OFF does not schedule contact draws'); - } finally { - globalThis.setTimeout = previousTimeout; - globalThis.clearTimeout = previousClear; - } - cockpit = true; - scene.postUpdate.raiseEvent(); - scene.preRender.raiseEvent(); - root.dataset.uiTheme = 'tactical'; - scene.postUpdate.raiseEvent(); - scene.preRender.raiseEvent(); + const canvas = { clientWidth: 1000, clientHeight: 800 }; + const viewer = {}; + const unbind = bindRenderer(viewer, { + canvas, + effects, + quality: { get: () => (cadenceHz ? { sonarCadenceHz: cadenceHz } : {}) }, + frame: { + on(phase, cb) { + assert.equal(phase, 'preUpdate'); + ticks.add(cb); + return () => ticks.delete(cb); + }, + requestRender: (reason) => requests.push(reason), + }, + }); + return { + root, + status, + state, + sets, + requests, + canvas, + viewer, + ticks, + changes, + effects, + tick(rendering = false) { + for (const cb of [...ticks]) cb({ rendering }); + }, + restore() { + unbind(); + globalThis.document = previous.document; + globalThis.matchMedia = previous.matchMedia; + }, + }; +} + +test('a renderer without the capability leaves markers alone and says so', () => { + const f = fixture({ modulation: false }); + try { + const dispose = createCyberSonarScene(f.viewer); + assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported'); + assert.match(f.status.textContent, /Native contacts remain visible/); + f.tick(true); + assert.equal(f.changes.size, 0); dispose(); - dispose(); - assert.equal(primitives.update, original); - assert.equal(scene.postUpdate.numberOfListeners, 0); - assert.equal(scene.preRender.numberOfListeners, 0); - assert.equal(scene.postRender.numberOfListeners, 0); - assert.equal(root.dataset.cyberSonarGpu, undefined); + assert.equal(f.ticks.size, 0); + assert.equal(f.root.dataset.cyberSonarGpu, undefined); } finally { - dispose(); - primitives.destroy(); - globalThis.document = previous; + f.restore(); } }); -for (const reducedMotion of [false, true]) { - test(`shader failure requests one parked restoration draw with ${reducedMotion ? 'reduced motion' : 'Sonar OFF'}`, () => { - const previousDocument = globalThis.document; - const previousMatchMedia = globalThis.matchMedia; - const previousTimeout = globalThis.setTimeout; - const previousClear = globalThis.clearTimeout; - const root = { - dataset: { uiTheme: 'cyber', cyberSonar: reducedMotion ? 'on' : 'off' }, - }; - const status = { textContent: '' }; - globalThis.document = { - documentElement: root, - body: { classList: { contains: () => false } }, - getElementById: (id) => - id === 'cyber-sonar-status' - ? status - : { classList: { contains: () => true } }, - }; - globalThis.matchMedia = () => ({ matches: reducedMotion }); - let scheduled = 0; - globalThis.setTimeout = () => { - scheduled++; - return 1; - }; - globalThis.clearTimeout = () => {}; - // A model-shaped fixture exercises the actual scene walk without loading a - // glTF or allocating a WebGL context. Rendering remains the browser gate. - const nativeColor = new Cesium.Color(0.2, 0.4, 0.8, 1); - const model = Object.create(Cesium.Model.prototype, { - ready: { value: true }, - show: { value: true }, - color: { value: nativeColor.clone(), writable: true }, - modelMatrix: { value: Cesium.Matrix4.IDENTITY }, - }); - const primitives = new Cesium.PrimitiveCollection({ - destroyPrimitives: false, - }); - primitives.add(model); - const points = new Cesium.PointPrimitiveCollection(); - const nativeCommand = { - owner: points, - uniformMap: {}, - shaderProgram: { - vertexShaderSource: new Cesium.ShaderSource({ - sources: ['void main() {}'], - }), - }, - }; - primitives.update = (frame) => frame.commandList.push(nativeCommand); - let requests = 0; - const scene = { - primitives, - postUpdate: new Cesium.Event(), - preRender: new Cesium.Event(), - postRender: new Cesium.Event(), - canvas: { clientWidth: 1000, clientHeight: 800 }, - drawingBufferWidth: 1000, - drawingBufferHeight: 800, - camera: { - frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY }, - viewMatrix: Cesium.Matrix4.IDENTITY, - }, - requestRender() { - requests++; - }, - }; - const viewer = { scene }; - const dispose = createCyberSonarScene(viewer); - try { - scene.postUpdate.raiseEvent(); - scene.preRender.raiseEvent(); - assert.notDeepEqual( - model.color, - nativeColor, - 'Cyber neutral treatment precedes shader compilation', - ); - const frame = { commandList: [], passes: { render: true } }; - primitives.update(frame); - assert.equal(getCyberSonarSceneDiagnostics(viewer).gpu.supported, false); - assert.equal(frame.commandList[0], nativeCommand); - scene.postRender.raiseEvent(); - assert.equal( - scheduled, - 0, - 'inactive sweep has no timer to perform recovery', - ); - scene.postUpdate.raiseEvent(); - assert.equal(root.dataset.cyberSonarGpu, 'unsupported'); - assert.match(status.textContent, /Native contacts remain visible/); - assert.equal( - requests, - 1, - 'support loss explicitly wakes the parked scene', - ); - scene.preRender.raiseEvent(); - assert.deepEqual( - model.color, - nativeColor, - 'the requested draw restores native model color', - ); - assert.equal(getCyberSonarSceneDiagnostics(viewer).contacts, 0); - scene.postRender.raiseEvent(); - for (let i = 0; i < 3; i++) scene.postUpdate.raiseEvent(); - assert.equal( - requests, - 1, - 'unsupported idle ticks do not create a render loop', - ); - assert.equal(scheduled, 0); - dispose(); - scene.postUpdate.raiseEvent(); - assert.equal(requests, 1, 'disposed callbacks cannot wake the scene'); - } finally { - dispose(); - points.destroy(); - primitives.destroy(); - globalThis.document = previousDocument; - globalThis.matchMedia = previousMatchMedia; - globalThis.setTimeout = previousTimeout; - globalThis.clearTimeout = previousClear; - } - }); -} +test('the HUD sweep keeps its clock while markers cannot be shaded', () => { + const f = fixture({ modulation: false }); + const animation = { + animationName: 'cyber-sonar-sweep', + playState: 'running', + startTime: 500, + effect: { updateTiming() {} }, + }; + f.root.querySelector = (selector) => + selector === '.hud-sonar' + ? { isConnected: true, getAnimations: () => [animation] } + : null; + try { + const dispose = createCyberSonarScene(f.viewer); + f.tick(false); + assert.equal(animation.startTime, 0); + assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported'); + dispose(); + } finally { + f.restore(); + } +}); + +test('the sweep sets its sector on drawing ticks and at the cadence, and changes at once', () => { + const f = fixture(); + const now = performance.now; + let clock = 1000; + performance.now = () => clock; + try { + const dispose = createCyberSonarScene(f.viewer); + assert.equal(f.root.dataset.cyberSonarGpu, 'supported'); + assert.equal(f.status.textContent, ''); + f.tick(); + assert.equal(f.sets.length, 1, 'the theme sets a sector'); + assert.deepEqual(f.sets[0], cyberSonarSector(1000, 800, 1000)); + clock += 10; + f.tick(false); + assert.equal(f.sets.length, 1, 'an idle tick before the cadence sets none'); + f.tick(true); + assert.equal(f.sets.length, 2, 'a tick that draws moves the angle'); + assert.deepEqual(f.sets[1], cyberSonarSector(1000, 800, 1010)); + clock += CYBER_SONAR_RENDER_INTERVAL_MS; + f.tick(false); + assert.equal(f.sets.length, 3, 'the cadence moves it on an idle tick'); + f.canvas.clientWidth = 600; + f.tick(false); + assert.equal(f.sets.length, 4, 'a resize sets it at once'); + assert.deepEqual(f.sets[3].center, { x: 300, y: 400 }); + f.root.dataset.cyberSonar = 'off'; + f.tick(false); + assert.equal(f.sets[4].radius, 0, 'Sonar OFF rests every contact'); + clock += 1000; + f.tick(true); + f.tick(false); + assert.equal(f.sets.length, 5, 'at rest only changes set it'); + f.root.dataset.cyberSonarOpacity = '50'; + f.tick(false); + assert.equal(f.sets.length, 6); + assert.equal(f.sets[5].floor, 0.5 + 0.5 * 0.46); + f.state.cockpit = true; + f.tick(false); + assert.equal(f.sets[6], null, 'out of the map theme it clears'); + f.tick(true); + assert.equal(f.sets.length, 7, 'cleared once'); + f.state.cockpit = false; + f.root.dataset.cyberSonar = 'on'; + f.state.reducedMotion = true; + f.tick(false); + assert.equal(f.sets[7].radius, 0, 'reduced motion rests the sweep'); + f.state.reducedMotion = false; + f.root.dataset.uiTheme = 'tactical'; + f.tick(false); + assert.equal(f.sets[8], null, 'another HUD style clears it'); + f.tick(true); + assert.equal(f.sets.length, 9); + f.root.dataset.uiTheme = 'cyber'; + f.tick(false); + assert.ok(f.sets[9]?.radius > 0, 'back in Cyber it sweeps at once'); + assert.deepEqual(f.requests, [], 'the scene itself never asks for frames'); + dispose(); + assert.equal(f.sets[10], null, 'disposal clears it'); + assert.equal(f.ticks.size, 0); + assert.equal(f.changes.size, 0); + assert.equal(f.root.dataset.cyberSonarGpu, undefined); + dispose(); + assert.equal(f.sets.length, 11); + } finally { + performance.now = now; + f.restore(); + } +}); + +test('the renderer cadence paces the idle sweep', () => { + const f = fixture({ cadenceHz: 4 }); + const now = performance.now; + let clock = 0; + performance.now = () => clock; + try { + const dispose = createCyberSonarScene(f.viewer); + f.tick(); + clock += CYBER_SONAR_RENDER_INTERVAL_MS; + f.tick(); + assert.equal(f.sets.length, 1, '4 Hz waits 250 ms'); + clock += 250 - CYBER_SONAR_RENDER_INTERVAL_MS; + f.tick(); + assert.equal(f.sets.length, 2); + dispose(); + } finally { + performance.now = now; + f.restore(); + } +}); + +test('a sector the renderer does not list is unsupported: cleared, and the sweep stops', () => { + const f = fixture({ lists: false }); + try { + const dispose = createCyberSonarScene(f.viewer); + f.tick(true); + assert.equal(f.sets.length, 2); + assert.equal(f.sets[1], null, 'cleared again'); + assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported'); + assert.match(f.status.textContent, /Native contacts remain visible/); + f.tick(true); + assert.equal(f.sets.length, 2, 'never set again'); + dispose(); + assert.equal(f.sets.length, 2); + } finally { + f.restore(); + } +}); + +test('a pass the renderer stops drawing on its own stops the sweep', () => { + const f = fixture(); + try { + const dispose = createCyberSonarScene(f.viewer); + f.tick(true); + assert.equal(f.sets.length, 1); + for (const cb of [...f.changes]) cb({ style: null, passes: [] }); + assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported'); + assert.equal(f.sets.at(-1), null); + const count = f.sets.length; + f.tick(true); + assert.equal(f.sets.length, count); + dispose(); + } finally { + f.restore(); + } +}); + +test('layer visibility changes ask for a frame', () => { + const f = fixture(); + let listener = null; + const manager = { + subscribe(cb) { + listener = cb; + return () => (listener = null); + }, + }; + try { + const dispose = createCyberSonarScene(f.viewer, manager); + listener({ type: 'visibility' }); + listener({ type: 'data' }); + assert.deepEqual(f.requests, ['cyber-sonar']); + dispose(); + assert.equal(listener, null); + } finally { + f.restore(); + } +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 958491cd8..6198d24d7 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -4,8 +4,6 @@ "src/app/embed.js", "src/app/scene.js", "src/app/viewer.js", - "src/cyberSonarGpu.js", - "src/cyberSonarScene.js", "src/data/geoImportPins.js", "src/layers/weather/shellRendering.js", "src/layers/wind/gpuRendering.js",