mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-14 23:32:20 +00:00
Draw by hand on Navara: clicks, moves and the double click from the engine input, a dashed engine line and vertex dots as the preview, and depth picks at the camera treated as misses
This commit is contained in:
1 parent
d8ef366ab1
commit
6ba67d01af
8 files changed
+915
-170
No files matched your search
@@ -0,0 +1,163 @@
|
||||
// UTILITIES ▸ Draw on a globe engine without a Cesium viewer (Navara): the
|
||||
// draw surface src/annotations/drawTool.js runs on. Clicks, moves and the
|
||||
// double click come from engine.input (the pointer claim the tool holds
|
||||
// makes every layer's own click yield, as on Cesium); the open shape shows
|
||||
// as a dashed engine line (the rubber band) and a dot per vertex, at the
|
||||
// height each click landed on. No Cesium, no three.
|
||||
|
||||
import * as geo from '../geo/index.js';
|
||||
import { pickWorldFromScreen } from './annotationResolver.js';
|
||||
import { DRAW_COLOR_CSS } from './drawMarks.js';
|
||||
import { MAX_VERTICES } from './drawMode.js';
|
||||
|
||||
const LINE_ID = 'gev-draw-preview';
|
||||
const DOTS_ID = 'gev-draw-vertices';
|
||||
|
||||
/** '#rrggbb' → rgba in 0..1. */
|
||||
export function cssRgba(css, alpha = 1) {
|
||||
const hex = Number.parseInt(String(css).slice(1), 16);
|
||||
return [
|
||||
((hex >> 16) & 255) / 255,
|
||||
((hex >> 8) & 255) / 255,
|
||||
(hex & 255) / 255,
|
||||
alpha,
|
||||
];
|
||||
}
|
||||
|
||||
const world = (v) => geo.cartesian3.fromDegrees(v.lon, v.lat, v.height || 0);
|
||||
|
||||
/**
|
||||
* The draw surface factory for `engine`: `surface({ session, cursor })`
|
||||
* (the open shape and the rubber band's end, as live getters) returns the
|
||||
* input and preview initDrawTool runs on.
|
||||
* @param {import('../globe/contract.js').GlobeEngine} engine
|
||||
*/
|
||||
export function navaraDrawSurface(engine) {
|
||||
return (live) => {
|
||||
let line = null;
|
||||
let dots = null;
|
||||
let removers = null;
|
||||
let color = 'primary';
|
||||
let destroyed = false;
|
||||
|
||||
const ensurePreview = () => {
|
||||
line ??= engine.lines.createLine({
|
||||
id: LINE_ID,
|
||||
widthPx: 3,
|
||||
color: cssRgba(DRAW_COLOR_CSS.primary, 0.9),
|
||||
// Cesium's depth-fail dash at 0.35 of the colour, 0.9 in front.
|
||||
depthFailAlpha: 0.35 / 0.9,
|
||||
dash: { lengthPx: 8, gapPx: 8 },
|
||||
});
|
||||
dots ??= engine.movers.createSet({
|
||||
id: DOTS_ID,
|
||||
kind: 'point',
|
||||
capacity: MAX_VERTICES,
|
||||
order: 10,
|
||||
depthTest: 'always',
|
||||
pickable: false,
|
||||
point: { sizePx: 8, outlinePx: 2, outlineColor: [0, 0, 0, 0.6] },
|
||||
});
|
||||
};
|
||||
/** The rubber band through the vertices, the pointer and back (areas). */
|
||||
const drawLine = () => {
|
||||
const session = live.session();
|
||||
if (!line) return;
|
||||
if (!session || session.shape === 'pin') {
|
||||
line.show(false);
|
||||
return;
|
||||
}
|
||||
const points = session.vertices.map(world);
|
||||
const cursor = live.cursor();
|
||||
if (cursor) points.push(world(cursor));
|
||||
if (session.shape === 'area' && points.length >= 3)
|
||||
points.push(points[0]);
|
||||
if (points.length < 2) {
|
||||
line.show(false);
|
||||
return;
|
||||
}
|
||||
line.setPositions(points);
|
||||
line.show(true);
|
||||
};
|
||||
|
||||
return {
|
||||
canvas: engine.host.canvas,
|
||||
pick(position) {
|
||||
const { width, height } = engine.host.size();
|
||||
return pickWorldFromScreen(
|
||||
engine,
|
||||
position.x / (width || 1),
|
||||
position.y / (height || 1),
|
||||
);
|
||||
},
|
||||
sync(session, nextColor) {
|
||||
if (destroyed) return;
|
||||
color = nextColor;
|
||||
if (!session) {
|
||||
line?.show(false);
|
||||
if (dots) {
|
||||
dots.setCount(0);
|
||||
dots.commit();
|
||||
}
|
||||
engine.render.request('draw');
|
||||
return;
|
||||
}
|
||||
ensurePreview();
|
||||
const css = DRAW_COLOR_CSS[color] || DRAW_COLOR_CSS.primary;
|
||||
line.setColor(cssRgba(css, 0.9));
|
||||
const stroke = cssRgba(css, 1);
|
||||
session.vertices.forEach((v, index) =>
|
||||
dots.set(index, { position: world(v), color: stroke, show: true }),
|
||||
);
|
||||
dots.setCount(session.vertices.length);
|
||||
dots.commit();
|
||||
drawLine();
|
||||
engine.render.request('draw');
|
||||
},
|
||||
moved() {
|
||||
if (destroyed) return;
|
||||
drawLine();
|
||||
engine.render.request('draw');
|
||||
},
|
||||
bound: () => Boolean(removers),
|
||||
bind({ click, move, doubleClick }) {
|
||||
if (removers || destroyed) return;
|
||||
removers = [
|
||||
engine.input.on('click', click),
|
||||
engine.input.on('move', move),
|
||||
engine.input.on('doubleClick', doubleClick),
|
||||
];
|
||||
},
|
||||
unbind() {
|
||||
for (const remove of removers ?? []) remove();
|
||||
removers = null;
|
||||
},
|
||||
diagnostics: ({ destroyed: toolDestroyed }) => ({
|
||||
sceneHandler: Boolean(removers),
|
||||
// Navara draws no Cesium data source; its preview is one line and
|
||||
// one dot per vertex.
|
||||
previewDataSources: 0,
|
||||
previewEntities: toolDestroyed
|
||||
? 0
|
||||
: (line ? 1 : 0) + (dots ? dots.count() : 0),
|
||||
previewLines: engine.lines.list().filter(({ id }) => id === LINE_ID)
|
||||
.length,
|
||||
stockSingleClick: false,
|
||||
stockDoubleClick: false,
|
||||
}),
|
||||
settled: () => Promise.resolve(),
|
||||
destroy() {
|
||||
if (!destroyed) {
|
||||
destroyed = true;
|
||||
for (const remove of removers ?? []) remove();
|
||||
removers = null;
|
||||
line?.destroy();
|
||||
dots?.destroy();
|
||||
line = dots = null;
|
||||
engine.render.request('draw');
|
||||
}
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
|
||||
import {
|
||||
isPointerFree,
|
||||
pointerOwner,
|
||||
resetPointerOwnership,
|
||||
} from '../data/inputOwnership.js';
|
||||
import { createSessionDrawTool } from './drawTool.js';
|
||||
import { navaraDrawSurface } from './drawInputNavara.js';
|
||||
import * as geo from '../geo/index.js';
|
||||
|
||||
/** The board double the tool draws on (its calls are what Draw sends). */
|
||||
function fakeAnnotations() {
|
||||
const calls = { annotate: [], frame: [] };
|
||||
return {
|
||||
calls,
|
||||
async annotate(specs, options) {
|
||||
calls.annotate.push({ specs, options });
|
||||
return { drawn: specs.length };
|
||||
},
|
||||
clear() {},
|
||||
list: () => [],
|
||||
onChange: () => () => {},
|
||||
frame: (id) => calls.frame.push(id),
|
||||
};
|
||||
}
|
||||
|
||||
function harness(t) {
|
||||
resetPointerOwnership();
|
||||
document.body.replaceChildren();
|
||||
const toggle = document.createElement('button');
|
||||
toggle.id = 'draw-toggle';
|
||||
document.body.append(toggle);
|
||||
// Over (0, 0): the canvas centre is the ellipsoid under the camera.
|
||||
const engine = createFakeEngine({ kind: 'navara', altitude: 20000 });
|
||||
const annotations = fakeAnnotations();
|
||||
let actions = null;
|
||||
const tool = createSessionDrawTool({
|
||||
annotations,
|
||||
connect: (next) => {
|
||||
actions = next;
|
||||
return () => (actions = null);
|
||||
},
|
||||
});
|
||||
t.after(() => {
|
||||
tool.destroy();
|
||||
resetPointerOwnership();
|
||||
});
|
||||
const attach = () => tool.attachScene({ surface: navaraDrawSurface(engine) });
|
||||
attach();
|
||||
const click = (x, y) => engine.fake.input('click', { position: { x, y } });
|
||||
const key = (name) =>
|
||||
document.body.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: name, bubbles: true }),
|
||||
);
|
||||
return {
|
||||
engine,
|
||||
tool,
|
||||
annotations,
|
||||
attach,
|
||||
click,
|
||||
key,
|
||||
act: (name, ...args) => actions?.[name]?.(...args),
|
||||
line: () => engine.fake.line('gev-draw-preview'),
|
||||
dots: () => engine.fake.moverSet('gev-draw-vertices'),
|
||||
};
|
||||
}
|
||||
|
||||
test('on Navara a click is a vertex, the rubber band follows the pointer and a double click finishes', async (t) => {
|
||||
const h = harness(t);
|
||||
h.act('toggleDraw');
|
||||
assert.equal(pointerOwner(), 'draw', 'the session holds the pointer');
|
||||
assert.equal(h.tool.diagnostics().sceneHandler, true);
|
||||
h.tool.setShape('area');
|
||||
h.click(500, 380);
|
||||
h.click(540, 380);
|
||||
h.click(540, 420);
|
||||
assert.equal(h.tool.session.vertices.length, 3);
|
||||
assert.equal(
|
||||
h.engine.movers.list().find(({ id }) => id === 'gev-draw-vertices').count,
|
||||
3,
|
||||
);
|
||||
// The band: three vertices, the pointer and the closing vertex.
|
||||
h.engine.fake.input('move', {
|
||||
startPosition: { x: 540, y: 420 },
|
||||
endPosition: { x: 500, y: 420 },
|
||||
});
|
||||
const band = h.line();
|
||||
assert.equal(band.shown, true);
|
||||
assert.equal(band.positions.length, 5 * 3);
|
||||
assert.equal(band.options.dash.lengthPx, 8);
|
||||
assert.equal(band.options.dash.gapPx, 8);
|
||||
// The vertex hangs where the click landed (the ellipsoid here).
|
||||
const first = geo.cartographic.fromCartesian({
|
||||
x: band.positions[0],
|
||||
y: band.positions[1],
|
||||
z: band.positions[2],
|
||||
});
|
||||
assert.ok(Math.abs(first.height) < 1);
|
||||
h.engine.fake.input('doubleClick', { position: { x: 500, y: 420 } });
|
||||
await Promise.resolve();
|
||||
assert.equal(h.annotations.calls.annotate.length, 1);
|
||||
const [spec] = h.annotations.calls.annotate[0].specs;
|
||||
assert.equal(spec.type, 'area');
|
||||
assert.equal(spec.manual, true);
|
||||
assert.ok(spec.ring.length >= 3);
|
||||
assert.equal(h.tool.session.vertices.length, 0, 'a fresh shape is open');
|
||||
});
|
||||
|
||||
test('Escape cancels the open shape, then leaves Draw and frees the pointer', (t) => {
|
||||
const h = harness(t);
|
||||
h.act('toggleDraw');
|
||||
h.tool.setShape('line');
|
||||
h.click(500, 380);
|
||||
h.click(560, 380);
|
||||
assert.equal(h.tool.session.vertices.length, 2);
|
||||
h.key('Escape');
|
||||
assert.equal(h.tool.session.vertices.length, 0, 'the sketch is cancelled');
|
||||
assert.equal(h.tool.active, true);
|
||||
h.key('Escape');
|
||||
assert.equal(h.tool.active, false);
|
||||
assert.equal(isPointerFree(), true);
|
||||
assert.equal(h.tool.diagnostics().sceneHandler, false);
|
||||
});
|
||||
|
||||
test('a switch mid-sketch ends the sketch, takes the preview off the engine and keeps shape and colour', (t) => {
|
||||
const h = harness(t);
|
||||
h.act('toggleDraw');
|
||||
h.tool.setShape('line');
|
||||
h.tool.setColor('amber');
|
||||
h.click(500, 380);
|
||||
h.click(560, 380);
|
||||
assert.ok(h.line());
|
||||
h.tool.detachScene();
|
||||
assert.equal(h.tool.active, false);
|
||||
assert.equal(isPointerFree(), true, 'the pointer is free after the switch');
|
||||
assert.equal(h.line(), undefined, 'the band left the engine');
|
||||
assert.equal(h.dots(), undefined);
|
||||
// A click on the old engine does nothing now.
|
||||
h.click(520, 400);
|
||||
assert.equal(h.tool.session, null);
|
||||
h.attach();
|
||||
assert.equal(h.tool.shape, 'line');
|
||||
assert.equal(h.tool.color, 'amber');
|
||||
h.act('toggleDraw');
|
||||
h.click(500, 380);
|
||||
assert.equal(h.tool.session.vertices.length, 1);
|
||||
});
|
||||
+229
-162
@@ -67,11 +67,16 @@ const PREVIEW = DRAW_COLOR_CSS;
|
||||
* through the actions it gives `connect`, which returns their disconnect.
|
||||
* A row's fly-to is an immediate navigation through `navigation`, like
|
||||
* Import's, so Cockpit can refuse it and a running orbit or follow lets go.
|
||||
* @param {{viewer: Cesium.Viewer, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function}} deps
|
||||
* The globe it draws on is a Cesium `viewer` or a draw `surface` factory
|
||||
* (`surface({ session, cursor })`: the input and preview of a globe without
|
||||
* a viewer, src/annotations/drawInputNavara.js), which gets the open shape
|
||||
* and the rubber band's end as live getters.
|
||||
* @param {{viewer?: Cesium.Viewer, surface?: Function, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function}} deps
|
||||
* @returns {{destroy: Function}|null}
|
||||
*/
|
||||
export function initDrawTool({
|
||||
viewer,
|
||||
viewer = null,
|
||||
surface: makeSurface = null,
|
||||
annotations,
|
||||
navigation = null,
|
||||
publish = () => {},
|
||||
@@ -81,7 +86,11 @@ export function initDrawTool({
|
||||
}) {
|
||||
// A page without the Draw controls (the Display controls view omitted) has
|
||||
// no draw tool.
|
||||
if (!viewer || !annotations || !document.getElementById('draw-toggle'))
|
||||
if (
|
||||
(!viewer && !makeSurface) ||
|
||||
!annotations ||
|
||||
!document.getElementById('draw-toggle')
|
||||
)
|
||||
return null;
|
||||
|
||||
let active = false;
|
||||
@@ -90,16 +99,14 @@ export function initDrawTool({
|
||||
let shape = normalizeShape(initialShape);
|
||||
let color = DRAW_COLORS.includes(initialColor) ? initialColor : 'primary';
|
||||
let hint = '';
|
||||
let handler = null;
|
||||
let lease = null;
|
||||
let savedDoubleClick = null;
|
||||
let savedSingleClick = null;
|
||||
let cursor = null; // last mouse position on the canvas, for the rubber band
|
||||
// The last pointer position on the globe ({ lon, lat, height }), for the
|
||||
// rubber band.
|
||||
let cursor = null;
|
||||
// Bumped by anything that supersedes an in-flight finish: cancelling, clearing
|
||||
// the board, leaving draw mode, teardown. An `annotate()` that resolves after
|
||||
// one of those must not write its outcome over the newer state.
|
||||
let generation = 0;
|
||||
const previewEntities = [];
|
||||
// Every DOM listener this tool adds (the session's keydown), so teardown is
|
||||
// one loop rather than a list that can fall out of step with the bindings.
|
||||
const domListeners = [];
|
||||
@@ -108,14 +115,11 @@ export function initDrawTool({
|
||||
domListeners.push([target, type, listener, options]);
|
||||
};
|
||||
|
||||
const dataSource = new Cesium.CustomDataSource(PREVIEW_DATA_SOURCE_NAME);
|
||||
// `add()` resolves on the NEXT tick, so an init-then-immediate-destroy would
|
||||
// remove a source that had not been attached yet and leave the attachment to
|
||||
// land afterwards — a preview data source nobody owns. Chain the removal onto
|
||||
// the attachment instead of racing it.
|
||||
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
|
||||
() => null,
|
||||
);
|
||||
// The globe's input and preview: Cesium's here, or the surface's.
|
||||
const live = { session: () => session, cursor: () => cursor };
|
||||
const surface = makeSurface
|
||||
? makeSurface(live)
|
||||
: cesiumDrawSurface(viewer, live);
|
||||
|
||||
const present = () =>
|
||||
publish({
|
||||
@@ -138,75 +142,14 @@ export function initDrawTool({
|
||||
});
|
||||
|
||||
// ---- preview ---------------------------------------------------------
|
||||
const vertexPositions = () =>
|
||||
session.vertices.map((v) =>
|
||||
Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
|
||||
);
|
||||
const previewLine = dataSource.entities.add({
|
||||
show: false,
|
||||
polyline: {
|
||||
positions: new Cesium.CallbackProperty(() => {
|
||||
if (!session) return [];
|
||||
const pts = vertexPositions();
|
||||
if (cursor && session.shape !== 'pin') pts.push(cursor);
|
||||
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
|
||||
return pts;
|
||||
}, false),
|
||||
width: 3,
|
||||
material: new Cesium.PolylineDashMaterialProperty({
|
||||
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.9),
|
||||
dashLength: 16,
|
||||
}),
|
||||
depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
|
||||
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.35),
|
||||
dashLength: 16,
|
||||
}),
|
||||
clampToGround: false,
|
||||
},
|
||||
});
|
||||
const syncPreview = () => {
|
||||
if (destroyed) return;
|
||||
previewEntities.forEach((e) => dataSource.entities.remove(e));
|
||||
previewEntities.length = 0;
|
||||
if (!session) {
|
||||
previewLine.show = false;
|
||||
setHint(() => drawHint(null));
|
||||
viewer.scene.requestRender();
|
||||
return;
|
||||
}
|
||||
const stroke = Cesium.Color.fromCssColorString(
|
||||
PREVIEW[color] || PREVIEW.primary,
|
||||
);
|
||||
previewLine.polyline.material = new Cesium.PolylineDashMaterialProperty({
|
||||
color: stroke.withAlpha(0.9),
|
||||
dashLength: 16,
|
||||
});
|
||||
previewLine.show = session.shape !== 'pin';
|
||||
for (const v of session.vertices) {
|
||||
previewEntities.push(
|
||||
dataSource.entities.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0),
|
||||
point: {
|
||||
pixelSize: 8,
|
||||
color: stroke,
|
||||
outlineColor: Cesium.Color.BLACK.withAlpha(0.6),
|
||||
outlineWidth: 2,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
surface.sync(session, color);
|
||||
setHint(() => drawHint(session));
|
||||
viewer.scene.requestRender();
|
||||
};
|
||||
|
||||
// ---- vertices from clicks --------------------------------------------
|
||||
const worldAt = (position) => {
|
||||
const canvas = viewer.scene.canvas;
|
||||
const w = canvas.clientWidth || canvas.width || 1;
|
||||
const h = canvas.clientHeight || canvas.height || 1;
|
||||
return pickWorldFromScreen(viewer, position.x / w, position.y / h);
|
||||
};
|
||||
const worldAt = (position) => surface.pick(position);
|
||||
const onClick = (event) => {
|
||||
if (!session || destroyed) return;
|
||||
const p = worldAt(event.position);
|
||||
@@ -231,10 +174,8 @@ export function initDrawTool({
|
||||
const onMove = (event) => {
|
||||
if (!session || session.shape === 'pin' || destroyed) return;
|
||||
const p = worldAt(event.endPosition);
|
||||
cursor = p
|
||||
? Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height || 0)
|
||||
: null;
|
||||
viewer.scene.requestRender();
|
||||
cursor = p ? { lon: p.lon, lat: p.lat, height: p.height || 0 } : null;
|
||||
surface.moved();
|
||||
};
|
||||
|
||||
// ---- finish / cancel -------------------------------------------------
|
||||
@@ -315,7 +256,7 @@ export function initDrawTool({
|
||||
)
|
||||
return false;
|
||||
return (
|
||||
t === document.body || t === viewer.scene.canvas || t.tagName === 'CANVAS'
|
||||
t === document.body || t === surface.canvas || t.tagName === 'CANVAS'
|
||||
);
|
||||
};
|
||||
const onKey = (event) => {
|
||||
@@ -386,49 +327,19 @@ export function initDrawTool({
|
||||
}
|
||||
|
||||
function bindSceneHandler() {
|
||||
if (handler) return;
|
||||
handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
|
||||
handler.setInputAction(onClick, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
handler.setInputAction(onMove, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||||
handler.setInputAction(() => {
|
||||
void finish();
|
||||
}, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
|
||||
// Cesium's Viewer binds BOTH stock click actions on its own handler: the
|
||||
// single click picks an entity into `viewer.selectedEntity`, the double
|
||||
// click tracks it. Neither goes through a layer, so neither can be fixed by
|
||||
// the shared pointer claim — they have to be borrowed outright for the
|
||||
// session and given back on the way out. Borrowing the single click is what
|
||||
// stops a vertex placed on a contact from also selecting it.
|
||||
const stock = viewer.screenSpaceEventHandler;
|
||||
savedSingleClick =
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null;
|
||||
savedDoubleClick =
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
|
||||
null;
|
||||
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
|
||||
if (surface.bound()) return;
|
||||
surface.bind({
|
||||
click: onClick,
|
||||
move: onMove,
|
||||
doubleClick: () => {
|
||||
void finish();
|
||||
},
|
||||
});
|
||||
listen(document, 'keydown', onKey, true);
|
||||
}
|
||||
|
||||
function releaseSceneHandler() {
|
||||
if (handler) {
|
||||
handler.destroy();
|
||||
handler = null;
|
||||
}
|
||||
if (savedSingleClick) {
|
||||
viewer.screenSpaceEventHandler.setInputAction(
|
||||
savedSingleClick,
|
||||
Cesium.ScreenSpaceEventType.LEFT_CLICK,
|
||||
);
|
||||
savedSingleClick = null;
|
||||
}
|
||||
if (savedDoubleClick) {
|
||||
viewer.screenSpaceEventHandler.setInputAction(
|
||||
savedDoubleClick,
|
||||
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
|
||||
);
|
||||
savedDoubleClick = null;
|
||||
}
|
||||
surface.unbind();
|
||||
// Drop the keydown listener bound alongside this handler.
|
||||
for (let i = domListeners.length - 1; i >= 0; i -= 1) {
|
||||
const [target, type, listener, options] = domListeners[i];
|
||||
@@ -528,34 +439,19 @@ export function initDrawTool({
|
||||
return {
|
||||
active,
|
||||
destroyed,
|
||||
sceneHandler: Boolean(handler),
|
||||
domListeners: domListeners.length,
|
||||
previewDataSources: countPreviewDataSources(viewer),
|
||||
previewEntities: destroyed ? 0 : dataSource.entities.values.length,
|
||||
pointerOwner: pointerOwner(),
|
||||
// The viewer's OWN click actions. While a session is open both are
|
||||
// borrowed (absent here); after it closes both are back. A harness can
|
||||
// compare the restored functions by identity with what it captured
|
||||
// before, which is the only way to prove they were given back rather
|
||||
// than replaced.
|
||||
stockSingleClick: Boolean(
|
||||
viewer.screenSpaceEventHandler?.getInputAction?.(
|
||||
Cesium.ScreenSpaceEventType.LEFT_CLICK,
|
||||
),
|
||||
),
|
||||
stockDoubleClick: Boolean(
|
||||
viewer.screenSpaceEventHandler?.getInputAction?.(
|
||||
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
|
||||
),
|
||||
),
|
||||
// The globe's handler, preview and (Cesium) the viewer's OWN click
|
||||
// actions: see the surface's diagnostics.
|
||||
...surface.diagnostics({ destroyed }),
|
||||
};
|
||||
},
|
||||
/** Resolves once every deferred teardown step has run. */
|
||||
whenSettled() {
|
||||
return attaching;
|
||||
return surface.settled();
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return attaching;
|
||||
if (destroyed) return surface.settled();
|
||||
// Supersede any finish still in flight before anything is torn down.
|
||||
generation += 1;
|
||||
if (active) setActive(false);
|
||||
@@ -569,37 +465,203 @@ export function initDrawTool({
|
||||
for (const [target, type, listener, options] of domListeners.splice(0)) {
|
||||
target.removeEventListener(type, listener, options);
|
||||
}
|
||||
previewEntities.length = 0;
|
||||
dataSource.entities.removeAll();
|
||||
// Wait for the pending add() before removing: a destroy() in the same
|
||||
// tick as init would otherwise remove nothing and let the attachment land
|
||||
// behind it.
|
||||
attaching = attaching.then(() => {
|
||||
try {
|
||||
viewer.dataSources.remove(dataSource, true);
|
||||
} catch {
|
||||
/* viewer already disposed — nothing to detach from */
|
||||
}
|
||||
});
|
||||
// The preview leaves once the globe's pending attachment has landed.
|
||||
const settled = surface.destroy();
|
||||
document.body.classList.remove('gev-drawing');
|
||||
hint = '';
|
||||
present();
|
||||
if (window.__gevDrawTool === api) delete window.__gevDrawTool;
|
||||
return attaching;
|
||||
return settled;
|
||||
},
|
||||
};
|
||||
window.__gevDrawTool = api;
|
||||
return api;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Draw tool's input and preview on a Cesium viewer: a dashed rubber band
|
||||
* and a dot per vertex in a preview data source, and a ScreenSpaceEventHandler
|
||||
* for clicks, moves and the double click. Cesium's Viewer binds BOTH stock
|
||||
* click actions on its own handler (select, track); they are borrowed while a
|
||||
* sketch is open and given back on the way out.
|
||||
*/
|
||||
function cesiumDrawSurface(viewer, live) {
|
||||
const previewEntities = [];
|
||||
const dataSource = new Cesium.CustomDataSource(PREVIEW_DATA_SOURCE_NAME);
|
||||
// `add()` resolves on the NEXT tick, so an init-then-immediate-destroy would
|
||||
// remove a source that had not been attached yet and leave the attachment to
|
||||
// land afterwards — a preview data source nobody owns. Chain the removal onto
|
||||
// the attachment instead of racing it.
|
||||
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
|
||||
() => null,
|
||||
);
|
||||
let handler = null;
|
||||
let savedSingleClick = null;
|
||||
let savedDoubleClick = null;
|
||||
const toCartesian = (v) =>
|
||||
Cesium.Cartesian3.fromDegrees(v.lon, v.lat, v.height || 0);
|
||||
const previewLine = dataSource.entities.add({
|
||||
show: false,
|
||||
polyline: {
|
||||
positions: new Cesium.CallbackProperty(() => {
|
||||
const session = live.session();
|
||||
if (!session) return [];
|
||||
const pts = session.vertices.map(toCartesian);
|
||||
const cursor = live.cursor();
|
||||
if (cursor && session.shape !== 'pin') pts.push(toCartesian(cursor));
|
||||
if (session.shape === 'area' && pts.length >= 3) pts.push(pts[0]);
|
||||
return pts;
|
||||
}, false),
|
||||
width: 3,
|
||||
material: new Cesium.PolylineDashMaterialProperty({
|
||||
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.9),
|
||||
dashLength: 16,
|
||||
}),
|
||||
depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
|
||||
color: Cesium.Color.fromCssColorString(PREVIEW.primary).withAlpha(0.35),
|
||||
dashLength: 16,
|
||||
}),
|
||||
clampToGround: false,
|
||||
},
|
||||
});
|
||||
return {
|
||||
canvas: viewer.scene.canvas,
|
||||
/** The world point under a canvas position, or null. */
|
||||
pick(position) {
|
||||
const canvas = viewer.scene.canvas;
|
||||
const w = canvas.clientWidth || canvas.width || 1;
|
||||
const h = canvas.clientHeight || canvas.height || 1;
|
||||
return pickWorldFromScreen(viewer, position.x / w, position.y / h);
|
||||
},
|
||||
/** Show the open shape (null: none) in `color`. */
|
||||
sync(session, color) {
|
||||
previewEntities.forEach((e) => dataSource.entities.remove(e));
|
||||
previewEntities.length = 0;
|
||||
if (!session) {
|
||||
previewLine.show = false;
|
||||
viewer.scene.requestRender();
|
||||
return;
|
||||
}
|
||||
const stroke = Cesium.Color.fromCssColorString(
|
||||
PREVIEW[color] || PREVIEW.primary,
|
||||
);
|
||||
previewLine.polyline.material = new Cesium.PolylineDashMaterialProperty({
|
||||
color: stroke.withAlpha(0.9),
|
||||
dashLength: 16,
|
||||
});
|
||||
previewLine.show = session.shape !== 'pin';
|
||||
for (const v of session.vertices) {
|
||||
previewEntities.push(
|
||||
dataSource.entities.add({
|
||||
position: toCartesian(v),
|
||||
point: {
|
||||
pixelSize: 8,
|
||||
color: stroke,
|
||||
outlineColor: Cesium.Color.BLACK.withAlpha(0.6),
|
||||
outlineWidth: 2,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
viewer.scene.requestRender();
|
||||
},
|
||||
/** The rubber band's end moved (read live by the preview line). */
|
||||
moved() {
|
||||
viewer.scene.requestRender();
|
||||
},
|
||||
bound: () => Boolean(handler),
|
||||
bind({ click, move, doubleClick }) {
|
||||
if (handler) return;
|
||||
handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
|
||||
handler.setInputAction(click, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
handler.setInputAction(move, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||||
handler.setInputAction(
|
||||
doubleClick,
|
||||
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
|
||||
);
|
||||
// Neither stock action goes through a layer, so neither can be fixed by
|
||||
// the shared pointer claim — they are borrowed outright for the session.
|
||||
// Borrowing the single click is what stops a vertex placed on a contact
|
||||
// from also selecting it.
|
||||
const stock = viewer.screenSpaceEventHandler;
|
||||
savedSingleClick =
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) || null;
|
||||
savedDoubleClick =
|
||||
stock.getInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
|
||||
null;
|
||||
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
stock.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
|
||||
},
|
||||
unbind() {
|
||||
if (handler) {
|
||||
handler.destroy();
|
||||
handler = null;
|
||||
}
|
||||
if (savedSingleClick) {
|
||||
viewer.screenSpaceEventHandler.setInputAction(
|
||||
savedSingleClick,
|
||||
Cesium.ScreenSpaceEventType.LEFT_CLICK,
|
||||
);
|
||||
savedSingleClick = null;
|
||||
}
|
||||
if (savedDoubleClick) {
|
||||
viewer.screenSpaceEventHandler.setInputAction(
|
||||
savedDoubleClick,
|
||||
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
|
||||
);
|
||||
savedDoubleClick = null;
|
||||
}
|
||||
},
|
||||
diagnostics: ({ destroyed }) => ({
|
||||
sceneHandler: Boolean(handler),
|
||||
previewDataSources: countPreviewDataSources(viewer),
|
||||
previewEntities: destroyed ? 0 : dataSource.entities.values.length,
|
||||
// The viewer's OWN click actions. While a session is open both are
|
||||
// borrowed (absent here); after it closes both are back. A harness can
|
||||
// compare the restored functions by identity with what it captured
|
||||
// before, which is the only way to prove they were given back rather
|
||||
// than replaced.
|
||||
stockSingleClick: Boolean(
|
||||
viewer.screenSpaceEventHandler?.getInputAction?.(
|
||||
Cesium.ScreenSpaceEventType.LEFT_CLICK,
|
||||
),
|
||||
),
|
||||
stockDoubleClick: Boolean(
|
||||
viewer.screenSpaceEventHandler?.getInputAction?.(
|
||||
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
|
||||
),
|
||||
),
|
||||
}),
|
||||
/** Resolves once every deferred teardown step has run. */
|
||||
settled: () => attaching,
|
||||
destroy() {
|
||||
previewEntities.length = 0;
|
||||
dataSource.entities.removeAll();
|
||||
// Wait for the pending add() before removing: a destroy() in the same
|
||||
// tick as init would otherwise remove nothing and let the attachment
|
||||
// land behind it.
|
||||
attaching = attaching.then(() => {
|
||||
try {
|
||||
viewer.dataSources.remove(dataSource, true);
|
||||
} catch {
|
||||
/* viewer already disposed — nothing to detach from */
|
||||
}
|
||||
});
|
||||
return attaching;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The Draw control for the page session. The marks live on the annotation
|
||||
* board and the chosen shape and colour here; the drawing tool itself (its
|
||||
* preview, click handler and Escape/Enter keys) belongs to the attached
|
||||
* Cesium viewer. `attachScene({ viewer, navigation })` starts the tool on a
|
||||
* viewer with the shape and colour last chosen; `detachScene()` ends it, an
|
||||
* open shape included. Without a viewer the controls answer nothing, as on
|
||||
* an engine without Draw. Same handle as initDrawTool's
|
||||
* globe. `attachScene({ viewer, navigation })` starts the tool on a Cesium
|
||||
* viewer, `attachScene({ surface, navigation })` on a globe without one
|
||||
* (Navara: src/annotations/drawInputNavara.js), with the shape and colour
|
||||
* last chosen; `detachScene()` ends it, an open shape included. Without a
|
||||
* globe the controls answer nothing. Same handle as initDrawTool's
|
||||
* (`window.__gevDrawTool`), kept across switches.
|
||||
*/
|
||||
export function createSessionDrawTool({
|
||||
@@ -667,13 +729,18 @@ export function createSessionDrawTool({
|
||||
pointerOwner: pointerOwner(),
|
||||
},
|
||||
whenSettled: () => inner?.whenSettled() ?? settled,
|
||||
attachScene({ viewer = null, navigation: next = navigation } = {}) {
|
||||
attachScene({
|
||||
viewer = null,
|
||||
surface = null,
|
||||
navigation: next = navigation,
|
||||
} = {}) {
|
||||
if (destroyed) return;
|
||||
detachScene();
|
||||
navigation = next;
|
||||
if (!viewer) return;
|
||||
if (!viewer && !surface) return;
|
||||
inner = initDrawTool({
|
||||
viewer,
|
||||
surface,
|
||||
annotations,
|
||||
navigation,
|
||||
publish,
|
||||
|
||||
@@ -2294,6 +2294,19 @@ export function createAnnotationResolver({
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a depth pick landed on the camera itself: something drawn into
|
||||
* the depth buffer at the near plane (Navara's screen-space preview lines
|
||||
* and sprites) reads back as a point a metre or so from the camera. Such a
|
||||
* pick is a miss; the ray's globe hit answers instead.
|
||||
*/
|
||||
function depthAtCamera(engine, screen, hit) {
|
||||
const camera = engine.camera.livePosition;
|
||||
const ground = engine.camera.pickEllipsoid(screen);
|
||||
const reference = ground ? geo.cartesian3.distance(ground, camera) : 0;
|
||||
return geo.cartesian3.distance(hit, camera) < Math.max(2, 0.01 * reference);
|
||||
}
|
||||
|
||||
/** pickWorldFromScreen through a globe engine: the same cascade. */
|
||||
function enginePickWorldFromScreen(engine, nx, ny) {
|
||||
const { width: w, height: h } = engine.host.size();
|
||||
@@ -2303,10 +2316,11 @@ export function createAnnotationResolver({
|
||||
y: Math.max(0, Math.min(1, ny)) * h,
|
||||
};
|
||||
const stages = [
|
||||
() =>
|
||||
engine.picker.pickPositionSupported
|
||||
? engine.picker.pickPosition(screen)
|
||||
: undefined,
|
||||
() => {
|
||||
if (!engine.picker.pickPositionSupported) return undefined;
|
||||
const hit = engine.picker.pickPosition(screen);
|
||||
return hit && !depthAtCamera(engine, screen, hit) ? hit : undefined;
|
||||
},
|
||||
() => engine.camera.pickEllipsoid(screen),
|
||||
() => engine.picker.pickGlobe(screen),
|
||||
];
|
||||
|
||||
@@ -68,6 +68,27 @@ test('pickWorldFromScreen tries the depth pick, then the ellipsoid, then the glo
|
||||
assert.equal(resolver.pickWorldFromScreen(engine, 0.5, 0.5), null);
|
||||
});
|
||||
|
||||
test('a depth pick at the camera itself (an overlay at the near plane) is a miss', () => {
|
||||
const engine = lookingDownAt(-97.7431, 30.2672);
|
||||
// Navara reads a screen-space preview line at the near plane: a point a
|
||||
// metre from the camera, 20 km above the ground.
|
||||
engine.fake.script(
|
||||
'pickPosition',
|
||||
geo.cartesian3.fromDegrees(-97.7431, 30.2672, 19999),
|
||||
);
|
||||
const picked = resolver.pickWorldFromScreen(engine, 0.5, 0.5);
|
||||
assert.ok(Math.abs(picked.height) < 1e-3, 'the ellipsoid answers instead');
|
||||
// A roof well below the camera is kept.
|
||||
engine.fake.script(
|
||||
'pickPosition',
|
||||
geo.cartesian3.fromDegrees(-97.7431, 30.2672, 400),
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(resolver.pickWorldFromScreen(engine, 0.5, 0.5).height - 400) <
|
||||
1e-6,
|
||||
);
|
||||
});
|
||||
|
||||
test('near-view recovery centres on the engine camera when nothing is picked', async () => {
|
||||
const engine = lookingDownAt(2.35, 48.85, 10000);
|
||||
for (const name of ['pickPosition', 'pickEllipsoid', 'pickGlobe'])
|
||||
|
||||
+30
-4
@@ -3,7 +3,12 @@
|
||||
// with src/app/navaraMode.js, so the Cesium-mode bundle carries none of it.
|
||||
|
||||
import { createNavaraAnnotationRenderer } from '../annotations/navaraAnnotationRenderer.js';
|
||||
import { sessionAnnotations, sessionGeoImport } from './sessionTools.js';
|
||||
import { navaraDrawSurface } from '../annotations/drawInputNavara.js';
|
||||
import {
|
||||
sessionAnnotations,
|
||||
sessionDrawTool,
|
||||
sessionGeoImport,
|
||||
} from './sessionTools.js';
|
||||
|
||||
/**
|
||||
* The annotation board drawn on this Navara scene: draped areas and routes
|
||||
@@ -33,9 +38,30 @@ export function attachNavaraAnnotations(
|
||||
return annotations;
|
||||
}
|
||||
|
||||
/** UTILITIES ▸ Draw on this Navara scene; null while it has none. */
|
||||
export function attachNavaraDraw() {
|
||||
return null;
|
||||
/**
|
||||
* UTILITIES ▸ Draw on this Navara scene: the session's tool on the engine's
|
||||
* input and preview (src/annotations/drawInputNavara.js). A switch ends an
|
||||
* open sketch and keeps the chosen shape and colour. Returns the tool (null
|
||||
* on a page without it or without the board).
|
||||
*/
|
||||
export function attachNavaraDraw(
|
||||
{ engine },
|
||||
{ layerSession, annotations, styleManager },
|
||||
{ defer },
|
||||
) {
|
||||
if (!annotations) return null;
|
||||
const drawTool = sessionDrawTool({
|
||||
layerSession,
|
||||
annotations,
|
||||
styleManager,
|
||||
defer,
|
||||
});
|
||||
drawTool?.attachScene({
|
||||
surface: navaraDrawSurface(engine),
|
||||
navigation: styleManager,
|
||||
});
|
||||
defer(() => drawTool?.detachScene());
|
||||
return drawTool;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user