From 8b2859e501c6a462828e256df21a38b1cc2582f5 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Fri, 6 Nov 2026 18:21:20 -0800 Subject: [PATCH] Draw clamped points, draped lines and ground fills through the Cesium draw port Clamped items now follow the ground the way Cesium's own entities do: a clamped point is a billboard of a drawn dot, a draped line a ground polyline, and a clamped fill a ground primitive, packed so no two fills in one overlap. A rebuilt set keeps its old ground primitives until the new ones are ready and swaps them in one frame, and whenSettled waits for them. Sets with horizonCull hide their points and icons past the horizon before each frame, and a change to what a set clamps to rebuilds it. --- src/render/cesium/draw.js | 414 +++++++++++++++++++++++++++++--- src/render/cesium/draw.test.mjs | 254 ++++++++++++++++++++ src/render/cesium/ports.js | 7 +- 3 files changed, 644 insertions(+), 31 deletions(-) diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 66df419a9..697e686f5 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -6,6 +6,15 @@ * item carries a pick id `{set, id, meta, lodGroup}`, which the query port * (`ports.js`) reads picks back through. * + * Clamped items follow the ground as Cesium's own entities do: a clamped + * point is a billboard of a drawn dot, a draped line a ground polyline, a + * clamped fill a ground primitive (packed so no two fills in one overlap, + * so overlapping translucent fills blend as they did). A rebuilt set keeps + * drawing its last ground primitives until the new ones are ready, so a + * refresh never blinks. `horizonCull` hides a set's points and icons past + * the ellipsoid's horizon, each frame before it draws, tested at the + * position each was given (not where clamping put it). + * * Built over a scene by `createCesiumPorts`, and on its own over a Cesium * viewer with no renderer bound, when code first asks * `findDraw` for one (`rendererOf.js`). @@ -37,6 +46,30 @@ export function toImage(image) { throw new Error('the Cesium renderer takes URL, SVG and canvas images only'); } +/** Cesium's height reference for an item's `height` and `clampTo`. */ +export function heightReferenceOf(height, clampTo = 'both') { + const H = Cesium.HeightReference; + if (height === 'clampGround') + return ( + { terrain: H.CLAMP_TO_TERRAIN, tiles: H.CLAMP_TO_3D_TILE }[clampTo] ?? + H.CLAMP_TO_GROUND + ); + if (height === 'relativeGround') + return ( + { terrain: H.RELATIVE_TO_TERRAIN, tiles: H.RELATIVE_TO_3D_TILE }[ + clampTo + ] ?? H.RELATIVE_TO_GROUND + ); + return H.NONE; +} + +/** Cesium's classification for what clamped lines and fills drape onto. */ +const classificationOf = (clampTo = 'both') => + ({ + terrain: Cesium.ClassificationType.TERRAIN, + tiles: Cesium.ClassificationType.CESIUM_3D_TILE, + })[clampTo] ?? Cesium.ClassificationType.BOTH; + const ANCHORS = { center: Cesium.VerticalOrigin.CENTER, bottom: Cesium.VerticalOrigin.BOTTOM, @@ -64,11 +97,27 @@ export function createCesiumDraw({ scene, report }) { if (sets.has(spec.id)) throw new Error(`a set with id ${spec.id} is live`); const items = new Map(); const listeners = { ready: listenerList(report) }; - const record = { kind, spec, items, listeners, host: null, pickIds: [] }; + const record = { + kind, + spec, + items, + listeners, + host: null, + pickIds: [], + // What it drew before its ground primitives were ready, still shown. + retiring: null, + pending: null, + // The host's ground primitives, and the collection beside them. + ground: null, + own: null, + // Each point or icon at its position, for the horizon cull. + placed: [], + }; // Each build records its items' pick ids, for height queries to see // through. const rebuild = () => { record.pickIds = []; + record.placed = []; build(record); setsVersion += 1; }; @@ -97,9 +146,15 @@ export function createCesiumDraw({ scene, report }) { requestRender(); }, setOptions(options) { + const culled = spec.horizonCull; + const clampTo = spec.clampTo; Object.assign(spec, options); + // What clamped items clamp to is built into them. + if (spec.clampTo !== clampTo) rebuild(); setsVersion += 1; - if (record.host) record.host.show = spec.show !== false; + showHosts(record); + // No longer culled: what the cull hid comes back. + if (culled && !spec.horizonCull) uncull(record); requestRender(); }, size: () => items.size, @@ -108,7 +163,7 @@ export function createCesiumDraw({ scene, report }) { }, set show(value) { spec.show = value; - if (record.host) record.host.show = value; + showHosts(record); requestRender(); }, on(event, cb) { @@ -118,6 +173,7 @@ export function createCesiumDraw({ scene, report }) { if (record.host && !record.host.isDestroyed?.() && live()) scene.primitives.remove(record.host); record.host = null; + retire(record); // A newer set under the same id is not this handle's to remove. if (sets.get(spec.id) === record) sets.delete(spec.id); setsVersion += 1; @@ -140,11 +196,98 @@ export function createCesiumDraw({ scene, report }) { return id; } - function replaceHost(record, host) { - if (record.host) scene.primitives.remove(record.host); + /** + * Draw `host` for the set in place of what it drew. With `ground` (its + * ground primitives), the new host's ground primitives stay hidden and + * the old host keeps drawing until every one is ready, then they swap in + * one frame, as the entities' ground batches do; a host still waiting + * when the next one comes is dropped. + */ + function replaceHost(record, host, ground = null, own = null) { + const old = record.host; + const waiting = ground?.length ? ground : null; + // Only old ground primitives wait for the new ones: the rest of the old + // host goes now, as the new host's own parts draw at once. + if ( + old && + waiting && + !record.retiring && + !record.pending && + record.ground + ) { + record.retiring = old; + if (record.own) old.remove(record.own); + } else if (old) scene.primitives.remove(old); + if (!waiting) retire(record); + // Hidden one by one: a hidden collection would not build them. + if (waiting) for (const primitive of waiting) primitive.show = false; + record.pending = waiting; + record.ground = waiting; + record.own = waiting ? own : null; record.host = host; - host.show = record.spec.show !== false; scene.primitives.add(host); + showHosts(record); + } + + function showHosts(record) { + const show = record.spec.show !== false; + if (record.host) record.host.show = show; + if (record.retiring) record.retiring.show = show; + } + + function retire(record) { + if (record.retiring && !record.retiring.isDestroyed?.() && live()) + scene.primitives.remove(record.retiring); + record.retiring = null; + } + + /** + * After a draw: a set whose ground primitives are all ready shows them, + * and lets go of what drew in their place. + */ + function swapReady() { + for (const record of sets.values()) { + const ground = record.pending; + if (!ground || ground.some((p) => !p.isDestroyed() && !p.ready)) continue; + for (const primitive of ground) primitive.show = true; + record.pending = null; + retire(record); + requestRender(); + } + } + + // The horizon cull: a point or icon past the ellipsoid's horizon from the + // eye is hidden, as layers drawn without depth test used to do themselves. + let occluder = null; + function cullHorizon() { + for (const record of sets.values()) { + if (!record.spec.horizonCull || !record.placed.length) continue; + const eye = scene.camera?.positionWC; + // The eye is ECEF in 3D only. + if ( + !eye || + (scene.mode ?? Cesium.SceneMode.SCENE3D) !== Cesium.SceneMode.SCENE3D + ) + return; + occluder ??= new Cesium.EllipsoidalOccluder( + scene.globe?.ellipsoid ?? Cesium.Ellipsoid.WGS84, + eye, + ); + occluder.cameraPosition = eye; + for (const placed of record.placed) { + const show = placed.shown && occluder.isPointVisible(placed.position); + if (placed.primitive.show !== show) placed.primitive.show = show; + } + } + } + + function uncull(record) { + for (const placed of record.placed) placed.primitive.show = placed.shown; + } + + /** Remember a drawn point or icon for the horizon cull. */ + function place(record, primitive, position, shown) { + record.placed.push({ primitive, position, shown }); } // Atlases icons name images from, by id: `{atlas, slot}` reads the slot @@ -180,6 +323,7 @@ export function createCesiumDraw({ scene, report }) { color: toColor(item.color, item.alpha ?? 1), verticalOrigin: ANCHORS[item.anchor ?? 'center'], disableDepthTestDistance: item.disableDepthTest ?? 0, + heightReference: heightReferenceOf(item.height, record.spec.clampTo), show: item.show !== false, id: pickId(record, item), }; @@ -195,26 +339,90 @@ export function createCesiumDraw({ scene, report }) { } const billboard = host.add(options); if (keyed) billboard.setImage(image.key, image.canvas); + place(record, billboard, position, options.show); } replaceHost(record, host); } function buildPoints(record) { - const host = new Cesium.PointPrimitiveCollection(); - for (const item of record.items.values()) - host.add({ - position: toCartesian(item.pos), - pixelSize: item.pixelSize, - color: toColor(item.color), - outlineColor: toColor(item.outlineColor ?? [0, 0, 0, 0]), - outlineWidth: item.outlineWidth ?? 0, - disableDepthTestDistance: item.disableDepthTest ?? 0, - show: item.show !== false, - id: pickId(record, item), - }); + let points = null; + let dots = null; + for (const item of record.items.values()) { + const position = toCartesian(item.pos); + const show = item.show !== false; + const heightReference = heightReferenceOf( + item.height, + record.spec.clampTo, + ); + let primitive; + if (heightReference === Cesium.HeightReference.NONE) { + points ??= new Cesium.PointPrimitiveCollection(); + primitive = points.add({ + position, + pixelSize: item.pixelSize, + color: toColor(item.color), + outlineColor: toColor(item.outlineColor ?? [0, 0, 0, 0]), + outlineWidth: item.outlineWidth ?? 0, + disableDepthTestDistance: item.disableDepthTest ?? 0, + show, + id: pickId(record, item), + }); + } else { + // Point primitives cannot follow the ground. + dots ??= new Cesium.BillboardCollection({ scene }); + primitive = addDot(dots, item, { + position, + heightReference, + show, + id: pickId(record, item), + }); + } + place(record, primitive, position, show); + } + let host = points ?? dots ?? new Cesium.PointPrimitiveCollection(); + if (points && dots) { + host = new Cesium.PrimitiveCollection(); + host.add(points); + host.add(dots); + } replaceHost(record, host); } + /** + * A clamped point as Cesium's entity points draw one: a billboard of a + * dot drawn at its pixel size, one texture per look. + */ + function addDot(collection, item, options) { + const color = toColor(item.color); + const outlineColor = toColor(item.outlineColor ?? [0, 0, 0, 0]); + const outlineWidth = Math.round(item.outlineWidth ?? 0); + let pixelSize = Math.max(1, Math.round(item.pixelSize)); + let scale = 1; + if (outlineWidth <= 0) { + // Drawn large and scaled down, as the entity points are. + scale = pixelSize / 50; + pixelSize = 50; + } + const css = color.toCssColorString(); + const cssOutline = outlineColor.toCssColorString(); + const billboard = collection.add({ + ...options, + scale, + disableDepthTestDistance: item.disableDepthTest ?? 0, + }); + billboard.setImage( + JSON.stringify([css, pixelSize, cssOutline, outlineWidth]), + Cesium.createBillboardPointCallback( + color.alpha, + css, + cssOutline, + outlineWidth, + pixelSize, + ), + ); + return billboard; + } + function lineMaterial(style) { switch (style.kind) { case 'solid': @@ -283,9 +491,33 @@ export function createCesiumDraw({ scene, report }) { function buildLines(record) { const host = new Cesium.PolylineCollection(); + const draped = new Map(); for (const item of record.items.values()) { - if (item.mode === 'draped') - throw new Error('the Cesium renderer has no draped lines'); + if (item.mode === 'draped') { + if (item.style.kind !== 'solid') + throw new Error('the Cesium renderer drapes solid lines only'); + const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; + if (!draped.has(clampTo)) draped.set(clampTo, []); + draped.get(clampTo).push( + new Cesium.GeometryInstance({ + geometry: new Cesium.GroundPolylineGeometry({ + positions: linePositions(item), + width: item.widthPx, + arcType: Cesium.ArcType.GEODESIC, + }), + attributes: { + color: Cesium.ColorGeometryInstanceAttribute.fromColor( + toColor(item.style.color), + ), + show: new Cesium.ShowGeometryInstanceAttribute( + item.show !== false, + ), + }, + id: pickId(record, item), + }), + ); + continue; + } host.add({ positions: linePositions(item), width: item.widthPx, @@ -294,7 +526,25 @@ export function createCesiumDraw({ scene, report }) { id: pickId(record, item), }); } - replaceHost(record, host); + if (!draped.size) return replaceHost(record, host); + // Draped lines drape as the entities' clamped polylines do. + const ground = [...draped].map( + ([clampTo, geometryInstances]) => + new Cesium.GroundPolylinePrimitive({ + geometryInstances, + appearance: new Cesium.PolylineColorAppearance(), + classificationType: classificationOf(clampTo), + }), + ); + replaceHost(record, collect(host, ground), ground, host); + } + + /** One host for a set's own collection and its ground primitives. */ + function collect(own, ground) { + const host = new Cesium.PrimitiveCollection(); + if (own) host.add(own); + for (const primitive of ground) host.add(primitive); + return host; } const heightOf = (pos) => @@ -362,11 +612,101 @@ export function createCesiumDraw({ scene, report }) { } } + /** A clamped shape's fill geometry, on the ellipsoid for draping. */ + function groundGeometry(item) { + const g = item.geometry; + switch (g.kind) { + case 'polygon': { + const [outer, ...holes] = g.rings.map((ring) => ring.map(toCartesian)); + return new Cesium.PolygonGeometry({ + polygonHierarchy: new Cesium.PolygonHierarchy( + outer, + holes.map((h) => new Cesium.PolygonHierarchy(h)), + ), + }); + } + case 'ellipse': + if (typeof g.semiMajor !== 'number' || typeof g.semiMinor !== 'number') + throw new Error('the Cesium renderer takes fixed ellipse radii only'); + return new Cesium.EllipseGeometry({ + center: toCartesian(g.center), + semiMajorAxis: g.semiMajor, + semiMinorAxis: g.semiMinor, + rotation: g.rotation ?? 0, + }); + case 'rectangle': + return new Cesium.RectangleGeometry({ + rectangle: Cesium.Rectangle.fromDegrees( + g.rect.west, + g.rect.south, + g.rect.east, + g.rect.north, + ), + }); + default: + throw new Error(`the Cesium renderer cannot clamp ${g.kind} shapes`); + } + } + + /** + * A set's clamped fills as ground primitives, packed as the entities' + * ground batches are: a fill goes in the first batch it overlaps nothing + * in, so overlapping translucent fills blend over each other. + */ + function groundFills(record, items) { + const batches = []; + for (const item of items) { + if (item.outline) + throw new Error('the Cesium renderer has no clamped outlines yet'); + if (!item.fill || item.outlineOnly) continue; + if (typeof item.fill === 'object' && !Array.isArray(item.fill)) + throw new Error('the Cesium renderer fills shapes with colours only'); + if (item.extrudeHeight !== undefined) + throw new Error('the Cesium renderer cannot clamp extruded shapes'); + const instance = new Cesium.GeometryInstance({ + geometry: groundGeometry(item), + attributes: { + color: Cesium.ColorGeometryInstanceAttribute.fromColor( + toColor(item.fill), + ), + }, + id: pickId(record, item), + }); + const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; + const rectangle = instance.geometry.rectangle; + let batch = batches.find( + (b) => b.clampTo === clampTo && !b.rectangles.collides(rectangle), + ); + if (!batch) { + batch = { + clampTo, + instances: [], + rectangles: new Cesium.RectangleCollisionChecker(), + }; + batches.push(batch); + } + batch.rectangles.insert(String(batch.instances.length), rectangle); + batch.instances.push(instance); + } + return batches.map( + (batch) => + new Cesium.GroundPrimitive({ + geometryInstances: batch.instances, + classificationType: classificationOf(batch.clampTo), + }), + ); + } + function buildShapes(record) { const host = new Cesium.PrimitiveCollection(); const outlines = new Cesium.PolylineCollection(); + const clamped = []; for (const item of record.items.values()) { if (item.show === false) continue; + if (item.height === 'clampGround') { + clamped.push(item); + continue; + } if ( item.fill && typeof item.fill === 'object' && @@ -410,7 +750,9 @@ export function createCesiumDraw({ scene, report }) { }); } host.add(outlines); - replaceHost(record, host); + const ground = groundFills(record, clamped); + if (!ground.length) return replaceHost(record, host); + replaceHost(record, collect(host, ground), ground, host); } function buildModels(record) { @@ -520,7 +862,15 @@ export function createCesiumDraw({ scene, report }) { sets, version: () => setsVersion, tilesets, - watchClamp, + /** Whether a set's ground primitives are still being built. */ + building: () => [...sets.values()].some((record) => record.pending), + /** Each frame, before it draws: the horizon cull. */ + beforeRender: cullHorizon, + /** Each frame, after it drew: clamp state, and ground swaps. */ + afterRender() { + watchClamp(); + swapReady(); + }, /** * Let go of the sets; with `removeHosts`, take what they draw out of * the scene too (a scene the port does not own outlives it). @@ -529,8 +879,10 @@ export function createCesiumDraw({ scene, report }) { clampListeners.clear(); // Late model loads find no host and destroy themselves. for (const record of sets.values()) { - if (removeHosts && record.host && !scene.isDestroyed?.()) - scene.primitives.remove(record.host); + if (removeHosts && !scene.isDestroyed?.()) { + if (record.host) scene.primitives.remove(record.host); + retire(record); + } record.host = null; } sets.clear(); @@ -553,15 +905,19 @@ provideUnboundDraw((viewer) => { ) return null; const part = createCesiumDraw({ scene, report: uncaught }); - const off = scene.postRender.addEventListener(() => part.watchClamp()); + const offs = [ + scene.preRender?.addEventListener?.(() => part.beforeRender()), + scene.postRender.addEventListener(() => part.afterRender()), + ]; + const off = () => offs.splice(0).forEach((remove) => remove?.()); return { port: part.port, dispose() { off(); part.dispose({ removeHosts: true }); }, - release() { - off(); - }, + // Released, its sets still draw, culled and swapped as before; the + // hooks go with the scene. + release() {}, }; }); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 4f62dde25..12bc5cd13 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -4,6 +4,10 @@ import test from 'node:test'; import { bindRenderer, drawOf, findDraw } from '../rendererOf.js'; import './draw.js'; +// Node has no WebGL context to report line-width limits. +Cesium.ContextLimits._minimumAliasedLineWidth = 1; +Cesium.ContextLimits._maximumAliasedLineWidth = 10; + /** A scene with what the draw port touches: primitives and its events. */ function fakeScene() { const added = []; @@ -14,6 +18,14 @@ function fakeScene() { postRender, preRender, camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) }, + frameState: { mode: Cesium.SceneMode.SCENE3D }, + // Clamped billboards ask the scene to follow the ground. + clamped: [], + updateHeight(position, update, heightReference) { + this.clamped.push(heightReference); + return () => {}; + }, + getHeight: () => undefined, primitives: { add: (primitive) => (added.push(primitive), primitive), remove: (primitive) => { @@ -68,3 +80,245 @@ test('nothing to draw into, no port', () => { assert.equal(findDraw({ scene: {} }), null); assert.throws(() => drawOf({}), /no renderer to draw with/); }); + +/** A draw port over a fake scene, with its frame hooks. */ +function drawOver(scene = fakeScene()) { + const viewer = { scene }; + const draw = drawOf(viewer); + return { + scene, + draw, + frame() { + scene.preRender.raiseEvent(); + scene.postRender.raiseEvent(); + }, + }; +} + +test('a clamped point is a billboard dot that follows the ground; others stay points', () => { + const { scene, draw } = drawOver(); + const set = draw.points({ id: 'dots', clampTo: 'both' }); + set.set([ + { + id: 'ground', + pos: { lon: 10, lat: 20 }, + height: 'clampGround', + pixelSize: 9, + color: '#7fe6ed', + outlineColor: '#000', + outlineWidth: 2, + disableDepthTest: Infinity, + }, + { id: 'free', pos: { lon: 0, lat: 0 }, pixelSize: 4, color: '#fff' }, + ]); + const host = scene.added[0]; + assert.ok(host instanceof Cesium.PrimitiveCollection, 'both kinds'); + const points = host.get(0); + const dots = host.get(1); + assert.ok(points instanceof Cesium.PointPrimitiveCollection); + assert.ok(dots instanceof Cesium.BillboardCollection); + const dot = dots.get(0); + assert.equal(dot.heightReference, Cesium.HeightReference.CLAMP_TO_GROUND); + assert.equal(dot.disableDepthTestDistance, Infinity); + assert.equal(dot.scale, 1, 'an outlined dot is drawn at its size'); + assert.deepEqual(scene.clamped, [Cesium.HeightReference.CLAMP_TO_GROUND]); + assert.deepEqual(dot.id, { + set: 'dots', + id: 'ground', + meta: undefined, + lodGroup: undefined, + }); + set.dispose(); +}); + +test('horizonCull hides points past the horizon each frame, and shows them again', () => { + const { scene, draw, frame } = drawOver(); + const set = draw.points({ id: 'cull', horizonCull: true }); + const near = { lon: 0, lat: 0 }; + const far = { lon: 180, lat: 0 }; + set.set([ + { id: 'near', pos: near, pixelSize: 4, color: '#fff' }, + { id: 'far', pos: far, pixelSize: 4, color: '#fff' }, + { id: 'hidden', pos: near, pixelSize: 4, color: '#fff', show: false }, + ]); + const host = scene.added[0]; + frame(); + assert.deepEqual( + [0, 1, 2].map((i) => host.get(i).show), + [true, false, false], + ); + scene.camera.positionWC = new Cesium.Cartesian3(-2e7, 0, 0); + frame(); + assert.deepEqual( + [0, 1, 2].map((i) => host.get(i).show), + [false, true, false], + 'the eye moved round', + ); + set.setOptions({ horizonCull: false }); + assert.deepEqual( + [0, 1, 2].map((i) => host.get(i).show), + [true, true, false], + 'uncull shows what the cull hid, not what was hidden', + ); + set.dispose(); +}); + +test('draped lines are ground polylines; a rebuild keeps the old ones until the new are ready', () => { + const { scene, draw, frame } = drawOver(); + const set = draw.lines({ id: 'tracks' }); + const line = (id) => ({ + id, + positions: [ + { lon: 0, lat: 0 }, + { lon: 1, lat: 1 }, + ], + widthPx: 2.5, + mode: 'draped', + style: { kind: 'solid', color: '#7fe6ed' }, + }); + set.set([line('a')]); + const first = scene.added[0]; + const ground = first.get(1); + assert.ok(ground instanceof Cesium.GroundPolylinePrimitive); + assert.equal(ground.classificationType, Cesium.ClassificationType.BOTH); + assert.equal(ground.geometryInstances[0].geometry.width, 2.5); + assert.deepEqual(ground.geometryInstances[0].id.id, 'a'); + + // Still not ready: the first build is all there is. + set.set([line('a'), line('b')]); + assert.deepEqual(scene.added.length, 1, 'an unready host is dropped'); + const second = scene.added[0]; + Object.defineProperty(second.get(1), 'ready', { value: true }); + frame(); + assert.equal(second.get(1).show, true, 'shown once ready'); + set.set([line('c')]); + assert.equal(scene.added.length, 2, 'the ready one stays until…'); + const third = scene.added[1].get(1); + assert.equal(third.show, false, 'the new one hidden while it builds'); + frame(); + assert.equal(scene.added.length, 2); + Object.defineProperty(third, 'ready', { value: true }); + frame(); + assert.equal(scene.added.length, 1, '…the new one is ready'); + assert.equal(third.show, true, 'and they swap in one frame'); + set.dispose(); + assert.equal(scene.added.length, 0); +}); + +test('clamped fills are ground primitives packed so none overlap within one', () => { + const { scene, draw } = drawOver(); + const set = draw.shapes({ id: 'discs' }); + const disc = (id, lon, fill = [1, 0, 0, 0.3]) => ({ + id, + geometry: { + kind: 'ellipse', + center: { lon, lat: 0 }, + semiMajor: 100_000, + semiMinor: 100_000, + }, + fill, + height: 'clampGround', + }); + set.set([disc('a', 0), disc('b', 0.5), disc('c', 30, '#ff0'), disc('x', 60)]); + const host = scene.added[0]; + const grounds = []; + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) + grounds.push(host.get(i)); + assert.deepEqual( + grounds.map((g) => g.geometryInstances.map((instance) => instance.id.id)), + [['a', 'c', 'x'], ['b']], + ); + assert.throws( + () => set.set([{ ...disc('o', 0), outline: '#fff' }]), + /no clamped outlines/, + ); + set.dispose(); +}); + +test('changing what a set clamps to rebuilds its items', () => { + const { scene, draw } = drawOver(); + const set = draw.points({ id: 'reclamp', clampTo: 'terrain' }); + set.set([ + { + id: 'p', + pos: { lon: 0, lat: 0 }, + height: 'clampGround', + pixelSize: 4, + color: '#fff', + }, + ]); + assert.equal( + scene.added[0].get(0).heightReference, + Cesium.HeightReference.CLAMP_TO_TERRAIN, + ); + set.setOptions({ clampTo: 'tiles' }); + assert.equal( + scene.added[0].get(0).heightReference, + Cesium.HeightReference.CLAMP_TO_3D_TILE, + ); + set.dispose(); +}); + +test('while a rebuild builds, only the old ground waits: the rest goes at once', () => { + const { scene, draw, frame } = drawOver(); + const set = draw.shapes({ id: 'mixed' }); + const disc = (id, height) => ({ + id, + geometry: { + kind: 'ellipse', + center: { lon: 0, lat: 0 }, + semiMajor: 1000, + semiMinor: 1000, + }, + fill: '#fff', + ...(height ? { height } : {}), + }); + const items = [disc('ground', 'clampGround'), disc('raised')]; + set.set(items); + const first = scene.added[0]; + const ground = first.get(1); + assert.ok(ground instanceof Cesium.GroundPrimitive); + Object.defineProperty(ground, 'ready', { value: true }); + frame(); + set.set(items); + assert.equal(scene.added.length, 2); + assert.equal(first.length, 1, 'the old raised fill is gone'); + assert.equal(first.get(0), ground, 'its ground fill waits'); + set.dispose(); + assert.equal(scene.added.length, 0); +}); + +test('clamped shapes refuse what they cannot draw', () => { + const { draw } = drawOver(); + const set = draw.shapes({ id: 'refuse' }); + const disc = { + id: 'a', + geometry: { + kind: 'ellipse', + center: { lon: 0, lat: 0 }, + semiMajor: 1000, + semiMinor: 1000, + }, + fill: '#fff', + height: 'clampGround', + }; + assert.throws( + () => set.set([{ ...disc, fill: { preset: 'radialRim' } }]), + /colours only/, + ); + assert.throws( + () => + set.set([ + { + ...disc, + geometry: { + ...disc.geometry, + semiMajor: { byCameraHeight: { factor: 1, min: 1, max: 2 } }, + }, + }, + ]), + /fixed ellipse radii/, + ); + set.dispose(); +}); diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 4d8555f61..14ebfdfbe 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -215,7 +215,8 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) { scene.preRender.addEventListener(onPhase('preRender')), scene.postRender.addEventListener(drew), scene.postRender.addEventListener(onPhase('postRender')), - scene.postRender.addEventListener(() => watchClamp()), + scene.preRender.addEventListener(() => drawPart.beforeRender()), + scene.postRender.addEventListener(() => drawPart.afterRender()), scene.postRender.addEventListener(() => trimGlobeAfterDraw()), ]; @@ -356,7 +357,7 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) { // --- Draw ------------------------------------------------------------------ const drawPart = createCesiumDraw({ scene, report }); - const { port: draw, sets, tilesets, watchClamp } = drawPart; + const { port: draw, sets, tilesets } = drawPart; const cameraPart = createCesiumCamera({ scene, camera, report, widget }); const cameraPort = cameraPart.port; @@ -898,6 +899,7 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) { if (!tilesLoaded()) blockers.push('tiles'); if (modelSets().some((r) => r.host.loading > 0)) blockers.push('models'); if (iconState() !== 'settled') blockers.push('icons'); + if (drawPart.building()) blockers.push('draw'); if (busy) blockers.push('redraw'); if (performance.now() - lastTick >= STALL_MS) blockers.push('frames'); return { state: 'timeout', blockers }; @@ -913,6 +915,7 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) { globeLoaded() && tilesLoaded() && icons === 'settled' && + !drawPart.building() && !modelSets().some((r) => r.host.loading > 0 || r.host.failed > 0) ); }