Cesium shapes: clamped outlines, clamped extrusions and walls, image fills without draping

Clamped outlines were refused; they are now draped lines, a ground polyline
a ring (a polygon's rings, an ellipse cut in 64, a rectangle's turned
corners) under the shape's pick id. Clamped extruded shapes, clamped walls,
and clamped image fills where the scene has no depth textures were refused;
they now stand on the surface unclamped, the surface height read when the
set is built (an extrusion from the lowest point under it, a wall's foot
under each position). The new conformance check draw.shapes.clamped draws
each kind; Cesium runs it.
This commit is contained in:
Sameh Khamis committed 2026-11-11 16:17:28 -08:00
1 parent 19055b2b8b
commit d497435b61
5 files changed
+443 -12

No files matched your search

+10
View File
@@ -146,6 +146,16 @@ one. The stub's is a frame along the ground track, so an autodetect
pins what both share (the range kept, north-up when still, the frame on the pins what both share (the range kept, north-up when still, the frame on the
target standing up). target standing up).
The Cesium port draws clamped shapes of every kind. A clamped outline is a
draped line (a ground polyline a ring, under the shape's pick id; an outlined
clamped shape is rebuilt on any change, and its outline does not pulse). What
a ground primitive cannot drape stands on the surface unclamped, the surface
read when the set is built: an extruded shape from the lowest surface height
under it up to its `extrudeHeight`, a wall with its foot on the surface under
each position and its heights above it, and an image fill where the scene
cannot drape materials (no depth textures). The check `draw.shapes.clamped`
draws each.
The Cesium port takes every kind of `ImageRef` wherever an image is drawn The Cesium port takes every kind of `ImageRef` wherever an image is drawn
(icons on billboards and on the GPU, line patterns, shape fills, quads and (icons on billboards and on the GPU, line patterns, shape fills, quads and
raster shells): a URL, SVG, a blob (by an object URL made once per blob), a raster shells): a URL, SVG, a blob (by an object URL made once per blob), a
+200 -9
View File
@@ -3623,6 +3623,164 @@ export function createCesiumDraw({
} }
} }
/** The surface's height under a position now, metres; 0 where unknown. */
function surfaceHeight(cartesian, clampTo) {
const at = Cesium.Cartographic.fromCartesian(cartesian);
if (!at) return 0;
const globe = scene.globe;
if (clampTo !== 'tiles' && globe?.show !== false) {
const h = globe?.getHeight?.(at);
if (Number.isFinite(h)) return h;
}
if (clampTo !== 'terrain' && scene.sampleHeightSupported) {
try {
const h = scene.sampleHeight(at);
if (Number.isFinite(h)) return h;
} catch {
// No depth to sample in this scene: the ellipsoid.
}
}
return 0;
}
/**
* A clamped shape a ground primitive cannot drape, as one standing on the
* surface, unclamped: an extruded one (its base at the lowest surface
* height under it, up to its `extrudeHeight`), a wall (its foot on the
* surface under each position, its heights above it), and an image fill
* where the scene cannot drape materials (on the surface under it). The
* surface is read when the set is built. Any other item is itself.
*/
function standing(record, item) {
if (item.height !== 'clampGround') return item;
const g = item.geometry;
const imageFill =
item.fill && typeof item.fill === 'object' && !Array.isArray(item.fill);
if (
item.extrudeHeight === undefined &&
g.kind !== 'wall' &&
!(imageFill && scene.context?.depthTexture === false)
)
return item;
const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both';
const at = (cartesian, height) => {
const c = Cesium.Cartographic.fromCartesian(cartesian);
return {
lon: Cesium.Math.toDegrees(c.longitude),
lat: Cesium.Math.toDegrees(c.latitude),
height,
};
};
const lowest = (points) =>
Math.min(...points.map((p) => surfaceHeight(p, clampTo)));
let geometry;
switch (g.kind) {
case 'polygon': {
const rings = g.rings.map((ring) => ring.map(toCartesian));
const base = lowest(rings.flat());
geometry = {
kind: 'polygon',
rings: rings.map((ring) => ring.map((p) => at(p, base))),
};
break;
}
case 'ellipse': {
const center = toCartesian(g.center);
geometry = { ...g, center: at(center, lowest([center])) };
break;
}
case 'rectangle': {
const r = g.rect;
const corners = [
[r.west, r.south],
[r.east, r.south],
[r.east, r.north],
[r.west, r.north],
[(r.west + r.east) / 2, (r.south + r.north) / 2],
].map(([lon, lat]) => Cesium.Cartesian3.fromDegrees(lon, lat));
geometry = { ...g, height: lowest(corners) };
break;
}
case 'wall': {
const points = g.positions.map(toCartesian);
const feet = points.map((p) => surfaceHeight(p, clampTo));
geometry = {
kind: 'wall',
positions: points.map((p, i) => at(p, feet[i])),
minimumHeights: feet.map((h, i) => h + (g.minimumHeights?.[i] ?? 0)),
maximumHeights: feet.map(
(h, i) => h + (g.maximumHeights?.[i] ?? heightOf(g.positions[i])),
),
};
break;
}
default:
return item;
}
return { ...item, geometry, height: 'absolute' };
}
/**
* A clamped shape's outline as rings on the surface, each closed: a
* polygon's rings, an ellipse cut in 64, a rectangle's turned corners.
*/
function outlineRings(item) {
const g = item.geometry;
const closed = (ring) =>
ring.length && !Cesium.Cartesian3.equals(ring[0], ring.at(-1))
? [...ring, ring[0]]
: ring;
switch (g.kind) {
case 'polygon':
return g.rings.map((ring) => closed(ring.map(toCartesian)));
case 'ellipse': {
const center = toCartesian(g.center);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(center);
const turn = g.rotation ?? 0;
const ring = [];
for (let k = 0; k < 64; k++) {
const a = (k / 64) * 2 * Math.PI;
// Along the semi-major axis at `rotation` counter-clockwise from north.
const major = g.semiMajor * Math.cos(a);
const minor = g.semiMinor * Math.sin(a);
const east = -major * Math.sin(turn) + minor * Math.cos(turn);
const north = major * Math.cos(turn) + minor * Math.sin(turn);
ring.push(
Cesium.Matrix4.multiplyByPoint(
enu,
new Cesium.Cartesian3(east, north, 0),
new Cesium.Cartesian3(),
),
);
}
return [closed(ring)];
}
case 'rectangle': {
const r = g.rect;
const cx = (r.west + r.east) / 2;
const cy = (r.south + r.north) / 2;
const c = Math.cos(g.rotation ?? 0);
const sn = Math.sin(g.rotation ?? 0);
const ring = [
[r.west, r.south],
[r.east, r.south],
[r.east, r.north],
[r.west, r.north],
].map(([lon, lat]) => {
const dx = lon - cx;
const dy = lat - cy;
return Cesium.Cartesian3.fromDegrees(
cx + dx * c - dy * sn,
cy + dx * sn + dy * c,
);
});
return [closed(ring)];
}
default:
return [];
}
}
/** /**
* A set's clamped fills as ground primitives, packed as the entities' * 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 * ground batches are: a fill goes in the first batch it overlaps nothing
@@ -3637,9 +3795,10 @@ export function createCesiumDraw({
// still draws; a host already retiring keeps its own. // still draws; a host already retiring keeps its own.
if (!record.retiring) record.retiringShapeParts = record.shapeParts ?? null; if (!record.retiring) record.retiringShapeParts = record.shapeParts ?? null;
record.shapeParts = null; record.shapeParts = null;
// Clamped outlines, drawn as draped lines: a ground polyline each.
const outlines = [];
for (const item of items) { for (const item of items) {
if (item.outline) if (item.outline) outlines.push(item);
throw new Error('the Cesium renderer has no clamped outlines yet');
if (!item.fill || item.outlineOnly) { if (!item.fill || item.outlineOnly) {
parts.set(item.id, { look: lookOf(item), id: null, ground: null }); parts.set(item.id, { look: lookOf(item), id: null, ground: null });
continue; continue;
@@ -3651,11 +3810,6 @@ export function createCesiumDraw({
const imageFill = objectFill; const imageFill = objectFill;
if (imageFill && !imageFill.image) if (imageFill && !imageFill.image)
throw new Error('the Cesium renderer fills shapes with colours only'); 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');
// 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. // Refused before anything is made, so nothing is left half built.
const image = imageFill ? imageAt(imageFill.image) : null; const image = imageFill ? imageAt(imageFill.image) : null;
// Hidden colour fills are built too, hidden, so showing them is a // Hidden colour fills are built too, hidden, so showing them is a
@@ -3764,6 +3918,42 @@ export function createCesiumDraw({
for (const part of batch.parts) part.ground = ground; for (const part of batch.parts) part.ground = ground;
return ground; return ground;
}); });
for (const item of outlines) {
const rings = outlineRings(item).filter((ring) => ring.length >= 2);
if (!rings.length) continue;
const part = parts.get(item.id);
// Picked as its shape.
part.id ??= pickId(record, item);
const outline = new Cesium.GroundPolylinePrimitive({
geometryInstances: rings.map(
(positions) =>
new Cesium.GeometryInstance({
geometry: new Cesium.GroundPolylineGeometry({
positions,
width: item.outlineWidth ?? 1,
arcType: Cesium.ArcType.GEODESIC,
}),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
toColor(item.outline),
),
show: new Cesium.ShowGeometryInstanceAttribute(
item.show !== false,
),
},
id: part.id,
}),
),
appearance: new Cesium.PolylineColorAppearance(),
classificationType: classificationOf(
item.clampTo ?? record.spec.clampTo ?? 'both',
),
allowPicking: pickable,
});
// Any change to an outlined clamped shape rebuilds the set.
part.outlineGround = outline;
grounds.push(outline);
}
record.shapeParts = parts; record.shapeParts = parts;
return grounds; return grounds;
} }
@@ -3841,7 +4031,7 @@ export function createCesiumDraw({
continue; continue;
} }
const was = parts?.get(item.id); const was = parts?.get(item.id);
if (!was) return false; if (!was || was.outlineGround) return false;
if (was.ground?.isDestroyed() || was.batch?.isDestroyed()) return false; if (was.ground?.isDestroyed() || was.batch?.isDestroyed()) return false;
if (sameLook(was, item)) { if (sameLook(was, item)) {
moves.push(false); moves.push(false);
@@ -4323,7 +4513,8 @@ export function createCesiumDraw({
materials.push(material); materials.push(material);
return material; return material;
}; };
for (const item of record.items.values()) { for (const given of record.items.values()) {
const item = standing(record, given);
// Clamped ones are built hidden as well (`groundFills`), when they // Clamped ones are built hidden as well (`groundFills`), when they
// are a colour fill it can draw: others hidden stay out, as before. // are a colour fill it can draw: others hidden stay out, as before.
if ( if (
+148 -3
View File
@@ -271,10 +271,155 @@ test('clamped fills are ground primitives packed so none overlap within one', ()
grounds.map((g) => g.geometryInstances.map((instance) => instance.id.id)), grounds.map((g) => g.geometryInstances.map((instance) => instance.id.id)),
[['a', 'c', 'x'], ['b']], [['a', 'c', 'x'], ['b']],
); );
assert.throws( set.dispose();
() => set.set([{ ...disc('o', 0), outline: '#fff' }]), });
/no clamped outlines/,
test('a clamped outline is a draped line under its shape’s pick id, a ring each', () => {
const { scene, draw } = drawOver();
const set = draw.shapes({ id: 'outlined' });
set.set([
{
id: 'o',
geometry: {
kind: 'polygon',
rings: [
[
{ lon: 0, lat: 0 },
{ lon: 1, lat: 0 },
{ lon: 1, lat: 1 },
],
[
{ lon: 0.5, lat: 0.2 },
{ lon: 0.7, lat: 0.2 },
{ lon: 0.7, lat: 0.4 },
],
],
},
fill: [1, 0, 0, 0.3],
outline: '#fff',
outlineWidth: 3,
height: 'clampGround',
},
{
id: 'r',
geometry: {
kind: 'rectangle',
rect: { west: 2, south: 0, east: 3, north: 1 },
},
outline: '#0f0',
outlineOnly: true,
height: 'clampGround',
},
]);
const host = scene.added[0];
const lines = [];
for (let i = 0; i < host.length; i++)
if (host.get(i) instanceof Cesium.GroundPolylinePrimitive)
lines.push(host.get(i));
assert.deepEqual(
lines.map((l) =>
l.geometryInstances.map((g) => [g.id.id, g.geometry._positions.length]),
),
[
[
['o', 4],
['o', 4],
],
[['r', 5]],
],
'closed rings',
); );
assert.equal(lines[0].geometryInstances[0].geometry.width, 3);
set.dispose();
});
test('where the scene cannot drape materials, a clamped image fill lies on the surface', () =>
withImageClasses(() => {
const scene = fakeScene();
scene.context = { depthTexture: false };
const { draw } = drawOver(scene);
const set = draw.shapes({ id: 'flat-image' });
set.set([
{
id: 'pic',
geometry: {
kind: 'rectangle',
rect: { west: 0, south: 0, east: 0.01, north: 0.01 },
},
fill: { image: 'pic.png' },
height: 'clampGround',
},
]);
const found = [];
const walk = (primitive) => {
if (primitive instanceof Cesium.PrimitiveCollection)
for (let i = 0; i < primitive.length; i++) walk(primitive.get(i));
else found.push(primitive);
};
scene.added.forEach(walk);
const fill = found.find((p) => p instanceof Cesium.Primitive);
assert.ok(fill, 'an unclamped primitive');
assert.ok(!found.some((p) => p instanceof Cesium.GroundPrimitive));
assert.equal(fill.appearance.material.type, 'Image');
set.dispose();
}));
test('clamped extruded shapes and walls stand on the surface, unclamped', () => {
const scene = fakeScene();
scene.globe = { show: true, getHeight: () => 120 };
const { draw } = drawOver(scene);
const set = draw.shapes({ id: 'standing' });
set.set([
{
id: 'block',
geometry: {
kind: 'polygon',
rings: [
[
{ lon: 0, lat: 0 },
{ lon: 0.01, lat: 0 },
{ lon: 0.01, lat: 0.01 },
],
],
},
fill: '#f00',
extrudeHeight: 400,
height: 'clampGround',
},
{
id: 'fence',
geometry: {
kind: 'wall',
positions: [
{ lon: 0, lat: 0, height: 10 },
{ lon: 0.01, lat: 0, height: 20 },
],
},
fill: '#00f',
height: 'clampGround',
},
]);
const geometries = new Map();
const walk = (primitive) => {
if (!primitive) return;
if (primitive instanceof Cesium.PrimitiveCollection)
for (let i = 0; i < primitive.length; i++) walk(primitive.get(i));
assert.ok(!(primitive instanceof Cesium.GroundPrimitive), 'not draped');
for (const instance of [primitive.geometryInstances ?? []].flat())
geometries.set(instance.id?.id, instance.geometry);
};
scene.added.forEach(walk);
const block = geometries.get('block');
assert.ok(block instanceof Cesium.PolygonGeometry);
assert.deepEqual(
[block._height, block._extrudedHeight].sort((a, b) => a - b),
[120, 400],
'from the surface up to its extruded height',
);
const fence = geometries.get('fence');
assert.ok(fence instanceof Cesium.WallGeometry);
assert.deepEqual(fence._minimumHeights, [120, 120], 'its foot on it');
assert.deepEqual(fence._maximumHeights, [130, 140], 'its heights above it');
set.dispose(); set.dispose();
}); });
+1
View File
@@ -69,6 +69,7 @@ export const CESIUM_CHECKS = new Set([
'draw.points.population', 'draw.points.population',
'draw.displayRange', 'draw.displayRange',
'draw.sets', 'draw.sets',
'draw.shapes.clamped',
'draw.shapes.drapedRotation', 'draw.shapes.drapedRotation',
'draw.shapes.resize', 'draw.shapes.resize',
'effects.crossfade', 'effects.crossfade',
+84
View File
@@ -1973,6 +1973,90 @@ export function portChecks() {
ok(!mine(at(0)), 'gone with its set'); ok(!mine(at(0)), 'gone with its set');
}, },
), ),
check(
'draw.shapes.clamped',
'clamped shapes of every kind draw: outlined, outline only, extruded and walls, and the filled ones are picked',
async (h, r) => {
await overAustin(h, r, 3000);
const shapes = r.draw.shapes({ id: 'conf:clamped-shapes' });
const box = (dLon, dLat, d = 0.0012) => ({
west: AUSTIN.lon + dLon - d,
south: AUSTIN.lat + dLat - d,
east: AUSTIN.lon + dLon + d,
north: AUSTIN.lat + dLat + d,
});
shapes.set([
{
id: 'outlined',
geometry: { kind: 'rectangle', rect: box(-0.004, 0.002) },
fill: [1, 0, 0, 0.6],
outline: '#ffffff',
outlineWidth: 3,
height: 'clampGround',
},
{
id: 'rim',
geometry: { kind: 'rectangle', rect: box(0.004, 0.002) },
outline: '#00ff00',
outlineWidth: 3,
outlineOnly: true,
height: 'clampGround',
},
{
id: 'tower',
geometry: {
kind: 'ellipse',
center: { lon: AUSTIN.lon - 0.004, lat: AUSTIN.lat - 0.003 },
semiMajor: 120,
semiMinor: 120,
},
fill: '#0000ff',
outline: '#ffffff',
extrudeHeight: 300,
height: 'clampGround',
},
{
id: 'fence',
geometry: {
kind: 'wall',
positions: [
{
lon: AUSTIN.lon + 0.003,
lat: AUSTIN.lat - 0.003,
height: 40,
},
{
lon: AUSTIN.lon + 0.005,
lat: AUSTIN.lat - 0.003,
height: 40,
},
],
},
fill: '#ffff00',
height: 'clampGround',
},
]);
equal(shapes.size(), 4, 'every kind is taken');
await settled(r);
await drawn(h, r);
for (const [id, lon, lat, height] of [
['outlined', AUSTIN.lon - 0.004, AUSTIN.lat + 0.002, 0],
['tower', AUSTIN.lon - 0.004, AUSTIN.lat - 0.003, 300],
]) {
const s = r.query.project(h.toEcef({ lon, lat, height }));
ok(s, `${id} projects`);
ok(
r.query
.drillPick(s.x, s.y)
.some(
(hit) => hit.set === 'conf:clamped-shapes' && hit.id === id,
),
`${id} drawn and picked`,
);
}
shapes.dispose();
},
),
check( check(
'draw.shapes.resize', 'draw.shapes.resize',
'a clamped ellipse whose radius alone is upserted draws at the new radius, growing and shrinking', 'a clamped ellipse whose radius alone is upserted draws at the new radius, growing and shrinking',