diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 7afc09214..6cf1247a2 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -45,6 +45,11 @@ optional, so a renderer written before it still conforms: - A line item's `depthFailDash` (`{ length, pattern16? }`) dashes the parts behind the surface in `depthFailColor`, as the Draw tool's rubber band is. A renderer that predates it draws those parts solid. +- A rectangle shape's `rotation` (radians counter-clockwise) turns it about + its centre in longitude and latitude, as a KML ground overlay turns, and + its image fill turns with it. The Cesium port drapes image fills too, each + on a ground primitive of its own. A renderer that predates it draws the + rectangle unturned. The renderer itself (`renderer.d.ts`) adds capture, pixel reads, settling, resize, context loss and `destroy`. `common.d.ts` holds the shared shapes diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 34f2d086e..c96aa5c65 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -1854,6 +1854,9 @@ export function createCesiumDraw({ ), height: g.height ?? 0, extrudedHeight, + // An image fill turns with the rectangle, as a KML overlay's does. + rotation: g.rotation ?? 0, + stRotation: g.rotation ?? 0, }), }; case 'box': { @@ -1902,6 +1905,8 @@ export function createCesiumDraw({ g.rect.east, g.rect.north, ), + rotation: g.rotation ?? 0, + stRotation: g.rotation ?? 0, }); default: throw new Error(`the Cesium renderer cannot clamp ${g.kind} shapes`); @@ -1926,13 +1931,24 @@ export function createCesiumDraw({ parts.set(item.id, { look: lookOf(item), id: null, ground: null }); continue; } - if (typeof item.fill === 'object' && !Array.isArray(item.fill)) + const imageFill = + typeof item.fill === 'object' && !Array.isArray(item.fill) + ? item.fill + : null; + if (imageFill && !imageFill.image) 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'); - // Hidden ones are built too, hidden, so showing them is a change of - // their show, not a rebuild of every fill; a hidden one it cannot - // build stays out, as before, and showing it rebuilds. + // Draping a material needs depth textures (WebGL 2 always has them). + if (imageFill && scene.context?.depthTexture === false) + throw new Error('the Cesium renderer cannot drape images here'); + // Refused before anything is made, so nothing is left half built. + const image = imageFill ? toImage(imageFill.image) : null; + // Hidden colour fills are built too, hidden, so showing them is a + // change of their show, not a rebuild of every fill; a hidden one it + // cannot build stays out, as before, and showing it rebuilds. Hidden + // image fills are not passed in (`hiddenFillBuilds`): their textures + // load when they show. let geometry; try { geometry = groundGeometry(item); @@ -1946,20 +1962,41 @@ export function createCesiumDraw({ ground: null, }; parts.set(item.id, part); + const show = new Cesium.ShowGeometryInstanceAttribute( + item.show !== false, + ); const instance = new Cesium.GeometryInstance({ geometry, - attributes: { - color: Cesium.ColorGeometryInstanceAttribute.fromColor( - toColor(item.fill), - ), - show: new Cesium.ShowGeometryInstanceAttribute(item.show !== false), - }, + attributes: imageFill + ? { show } + : { + color: Cesium.ColorGeometryInstanceAttribute.fromColor( + toColor(item.fill), + ), + show, + }, id: part.id, }); const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; + if (imageFill) { + // An image fill is a ground primitive of its own, with its material. + // (Cesium turns its texture wrongly across the antimeridian: its + // rotation points are taken against a centre wrapped to ±180°.) + batches.push({ + clampTo, + instances: [instance], + parts: [part], + image, + imageFill, + }); + continue; + } const rectangle = instance.geometry.rectangle; let batch = batches.find( - (b) => b.clampTo === clampTo && !b.rectangles.collides(rectangle), + (b) => + b.rectangles && + b.clampTo === clampTo && + !b.rectangles.collides(rectangle), ); if (!batch) { batch = { @@ -1979,11 +2016,40 @@ export function createCesiumDraw({ ? Cesium.GroundPrimitive : UnpickableGroundPrimitive; const grounds = batches.map((batch) => { + const material = batch.imageFill + ? Cesium.Material.fromType('Image', { + image: batch.image, + repeat: new Cesium.Cartesian2( + ...(batch.imageFill.repeat ?? [1, 1]), + ), + }) + : null; const ground = new Ground({ geometryInstances: batch.instances, classificationType: classificationOf(batch.clampTo), allowPicking: pickable, + ...(material + ? { + appearance: new Cesium.MaterialAppearance({ + material, + materialSupport: + Cesium.MaterialAppearance.MaterialSupport.TEXTURED, + translucent: true, + flat: true, + }), + } + : {}), }); + // Its material holds the texture, which the primitive leaves alone: + // it goes with the primitive, which may outlive the host that built it + // while a rebuild's ground primitives get ready. + if (material) { + const destroyGround = ground.destroy.bind(ground); + ground.destroy = () => { + if (!material.isDestroyed()) material.destroy(); + return destroyGround(); + }; + } for (const part of batch.parts) part.ground = ground; return ground; }); @@ -2096,7 +2162,7 @@ export function createCesiumDraw({ }; for (const item of record.items.values()) { // Clamped ones are built hidden as well (`groundFills`), when they - // are a fill it can draw: others hidden stay out, as before. + // are a colour fill it can draw: others hidden stay out, as before. if ( item.height === 'clampGround' && (item.show !== false || hiddenFillBuilds(item)) diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 363f3c54d..22582a3df 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -2590,6 +2590,101 @@ test('an unclamped shape filled with an image draws a textured primitive and fre ); })); +test('a draped rectangle turns, its image fill with it, on a ground primitive that owns its material', () => + withImageClasses(() => { + const scene = fakeScene(); + const draw = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }).port; + const set = draw.shapes({ id: 'overlays' }); + const overlay = (extra = {}) => ({ + id: 'overlay', + geometry: { + kind: 'rectangle', + rect: { west: 2, south: 1, east: 2.1, north: 1.1 }, + rotation: 0.4, + }, + fill: { image: 'overlay.png' }, + height: 'clampGround', + ...extra, + }); + const tinted = { + id: 'tinted', + geometry: { + kind: 'rectangle', + rect: { west: 2, south: 1, east: 2.1, north: 1.1 }, + rotation: -0.2, + }, + fill: [1, 0, 0, 0.5], + height: 'clampGround', + }; + set.set([overlay(), tinted]); + const grounds = () => { + const host = scene.added[0]; + const out = []; + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) + out.push(host.get(i)); + return out; + }; + const [image, colour] = grounds(); + assert.equal( + grounds().length, + 2, + 'the image on a ground primitive of its own', + ); + const { appearance, geometryInstances } = image; + assert.ok(appearance instanceof Cesium.MaterialAppearance); + assert.equal(appearance.material.type, 'Image'); + assert.equal(appearance.material.uniforms.image, 'overlay.png'); + const [instance] = geometryInstances; + assert.equal(instance.id.id, 'overlay'); + assert.equal(instance.geometry._rotation, 0.4); + assert.equal(instance.geometry._stRotation, 0.4, 'the image turns with it'); + assert.equal(instance.attributes.color, undefined); + assert.equal(colour.geometryInstances[0].geometry._rotation, -0.2); + // Hiding it is a change of its show, not a rebuild. + const host = scene.added[0]; + set.upsert([overlay({ show: false })]); + assert.equal(scene.added[0], host, 'not rebuilt'); + const material = appearance.material; + scene.primitives.remove = (primitive) => { + const at = scene.added.indexOf(primitive); + if (at >= 0) scene.added.splice(at, 1); + primitive.destroy(); + return at >= 0; + }; + set.dispose(); + assert.equal(material.isDestroyed(), true, 'its material goes with it'); + // Not rotated, it is as before. + const plain = draw.shapes({ id: 'plain' }); + plain.set([ + overlay({ + geometry: { + kind: 'rectangle', + rect: { west: 2, south: 1, east: 2.1, north: 1.1 }, + }, + }), + ]); + const [flat] = grounds(); + assert.equal(flat.geometryInstances[0].geometry._rotation, 0); + plain.dispose(); + // An image it cannot take is refused before anything is built. + const made = scene.added.length; + assert.throws( + () => + draw + .shapes({ id: 'atlas' }) + .set([ + overlay(), + overlay({ id: 'b', fill: { image: { atlas: 'a', slot: 's' } } }), + ]), + /URL, SVG and canvas images only/, + ); + assert.equal(scene.added.length, made, 'nothing drawn'); + })); + test('scene data packs draw their geometry and media marker through the Cesium draw port on a viewer of its own', async (t) => { const names = [ 'HTMLCanvasElement', diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index f34b8cd21..3cc462010 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -59,6 +59,7 @@ export const CESIUM_CHECKS = new Set([ 'draw.points.update', 'draw.lodGroup', 'draw.sets', + 'draw.shapes.drapedRotation', 'effects.crossfade', 'effects.defineStyle', 'effects.styles', diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index 6f83e8ae9..a69b17257 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -1378,6 +1378,70 @@ export function portChecks() { lines.dispose(); }, ), + check( + 'draw.shapes.drapedRotation', + 'a draped rectangle with an image fill draws turned by its rotation, picks there, and hides in place', + async (h, r) => { + await overAustin(h, r); + const at = (dLon, dLat = 0) => + h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat }); + const shapes = r.draw.shapes({ id: 'conf:overlay' }); + const mine = (pos) => { + const s = r.query.project(pos); + return Boolean( + s && + r.query + .drillPick(s.x, s.y) + .some( + (hit) => hit.set === 'conf:overlay' && hit.id === 'overlay', + ), + ); + }; + // Wide east to west; a quarter turn stands it north to south. + const overlay = (rotation, extra = {}) => ({ + id: 'overlay', + geometry: { + kind: 'rectangle', + rect: { + west: AUSTIN.lon - 0.004, + south: AUSTIN.lat - 0.001, + east: AUSTIN.lon + 0.004, + north: AUSTIN.lat + 0.001, + }, + ...(rotation === undefined ? {} : { rotation }), + }, + fill: { image: PIXEL_PNG }, + height: 'clampGround', + ...extra, + }); + const until = async (test) => { + for (let i = 0; i < 300; i++) { + await drawn(h, r, 1); + if (test()) return true; + } + return false; + }; + shapes.set([overlay(undefined)]); + ok(await until(() => mine(at(0))), 'unturned, it draws'); + ok(mine(at(0.003)), 'unturned, it is wide'); + ok(!mine(at(0, 0.003)), 'unturned, it is not tall'); + shapes.set([overlay(Math.PI / 2)]); + ok( + await until(() => mine(at(0, 0.003)) && !mine(at(0.003))), + 'a quarter turn stands it north to south', + ); + ok(mine(at(0)), 'turned about its centre'); + shapes.upsert([overlay(Math.PI / 2, { show: false })]); + await drawn(h, r); + ok(!mine(at(0)), 'hidden'); + shapes.upsert([overlay(Math.PI / 2)]); + ok(await until(() => mine(at(0, 0.003))), 'shown again'); + equal(shapes.size(), 1, 'held'); + shapes.dispose(); + await drawn(h, r); + ok(!mine(at(0)), 'gone with its set'); + }, + ), check( 'draw.lines.styles', 'flow lines draw draped and in space, and a line with a depth-fail colour moves every frame, without stopping the frame or picks', diff --git a/src/render/contract/contract.test.mjs b/src/render/contract/contract.test.mjs index 12e7e09e1..e0b9f5bb5 100644 --- a/src/render/contract/contract.test.mjs +++ b/src/render/contract/contract.test.mjs @@ -184,6 +184,11 @@ test('members added to version 0 later are optional, each behind its capability' members(checker.getTypeAtLocation(declared(shape).name)), )[field]; assert.equal(optional('LineItem', 'depthFailDash'), true); + // And on one kind of a union: the rectangle's rotation. + const rectangle = checker + .getTypeAtLocation(declared('ShapeGeometry').name) + .types.find((kind) => checker.getPropertyOfType(kind, 'rect')); + assert.equal(Object.fromEntries(members(rectangle)).rotation, true); }); test('the shape check names what is missing and what a capability does not allow', () => { diff --git a/src/render/contract/draw.d.ts b/src/render/contract/draw.d.ts index 9aa52e5bb..bcc94ad5b 100644 --- a/src/render/contract/draw.d.ts +++ b/src/render/contract/draw.d.ts @@ -281,8 +281,13 @@ export type ShapeGeometry = /** Only part of the ellipse, radians from north. */ arc?: { start: number; end: number }; } - /** `height`: metres above the ellipsoid, for a rectangle not clamped. */ - | { kind: 'rectangle'; rect: GeoRect; height?: number } + /** + * `height`: metres above the ellipsoid, for a rectangle not clamped. + * `rotation`: radians counter-clockwise, turning the rectangle about its + * centre in longitude and latitude (as a KML ground overlay turns); an + * image fill turns with it. + */ + | { kind: 'rectangle'; rect: GeoRect; height?: number; rotation?: number } | { kind: 'box'; center: Position; diff --git a/src/render/stub/index.js b/src/render/stub/index.js index b5676490e..e0821c47c 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -656,6 +656,25 @@ export function createStubRenderer(options = {}) { return set && item ? itemPosition(set, item, aheadMs) : null; } + /** + * Whether `lon`, `lat` (degrees) is in a rectangle geometry, turned by its + * `rotation` about its centre in longitude and latitude. + */ + function inRectangle({ rect, rotation = 0 }, lon, lat) { + // A rectangle across the antimeridian runs east past 180°. + const span = rect.east - rect.west; + const width = span >= 360 ? 360 : ((span % 360) + 360) % 360; + const wrap = (d) => ((((d + 180) % 360) + 360) % 360) - 180; + const dLon = wrap(lon - (rect.west + width / 2)); + const dLat = lat - (rect.south + rect.north) / 2; + const cos = Math.cos(rotation); + const sin = Math.sin(rotation); + return ( + Math.abs(cos * dLon + sin * dLat) <= width / 2 && + Math.abs(-sin * dLon + cos * dLat) <= (rect.north - rect.south) / 2 + ); + } + function hitsAt(x, y, win = {}) { if (scriptedPicks) return scriptedPicks(x, y, win) ?? []; const halfW = (win.width ?? 3) / 2; @@ -681,6 +700,30 @@ export function createStubRenderer(options = {}) { } continue; } + if (set.kind === 'shapes') { + // Draped rectangles are picked where they cover the ellipsoid, turned + // as the default renderer turns them; other shapes are not picked. + const ground = rayEllipsoid(pickRay(x, y)); + const at = ground && toCartographicRadians(ground); + if (!at) continue; + for (const item of set.items.values()) { + if (item.show === false || item.pickable === false) continue; + if (!item.fill || item.outlineOnly) continue; + if (item.height !== 'clampGround') continue; + if (item.geometry?.kind !== 'rectangle') continue; + if (!inRectangle(item.geometry, toDegrees(at.lon), toDegrees(at.lat))) + continue; + hits.push({ + set: setId, + id: item.id, + meta: item.meta, + surface: false, + position: ground, + depth: magnitude(sub(ground, eye().position)), + }); + } + continue; + } if ( set.kind !== 'icons' && set.kind !== 'points' && diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index 8f5eee824..28e78c2e9 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import { createStubRenderer } from './index.js'; import { createStubHarness } from './harness.js'; import { runConformance } from '../conformance/index.js'; +import { toEcef } from './math.js'; test('the stub passes the conformance suite', async () => { const report = await runConformance(createStubHarness()); @@ -97,3 +98,35 @@ test('a model load is told once, even when a listener loads it again', () => { set.upsert([model('a', 'good.glb')]); assert.deepEqual(told.slice(2), ['ready a']); }); + +test('a draped rectangle across the antimeridian picks on both sides of it, turned too', () => { + const r = createStubRenderer(); + r.camera.setView({ + destination: { lon: 180, lat: 0, height: 400_000 }, + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + const shapes = r.draw.shapes({ id: 'dateline' }); + const rect = (rotation) => ({ + id: 'r', + geometry: { + kind: 'rectangle', + rect: { west: 179, south: -0.25, east: -179, north: 0.25 }, + rotation, + }, + fill: '#f00', + height: 'clampGround', + }); + const picked = (lon, lat) => { + const s = r.query.project(toEcef({ lon, lat, height: 0 })); + return r.query.drillPick(s.x, s.y).some((hit) => hit.set === 'dateline'); + }; + shapes.set([rect(0)]); + for (const lon of [179.5, 180, -179.5]) + assert.ok(picked(lon, 0), `at ${lon}`); + assert.ok(!picked(178.5, 0) && !picked(-178.5, 0), 'not past its ends'); + assert.ok(!picked(180, 0.5), 'not past its north'); + shapes.set([rect(Math.PI / 2)]); + assert.ok(picked(180, 0.75), 'a quarter turn stands it north to south'); + assert.ok(!picked(179.5, 0), 'and narrows it'); + r.destroy(); +});