From c32bf3177d5c182bea4271ad135b7aa901319b5b Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 8 Nov 2026 13:50:38 -0800 Subject: [PATCH] Add hillshade surface shading and draw it on the Cesium globe The globe port takes the globe's material only when it is free, follows a terrain change, lets go of a material someone replaced, and takes it again once it comes free; idle ticks ask for no frame. --- docs/RENDERER-CONTRACT.md | 5 ++ src/render/cesium/globe.js | 113 +++++++++++++++++++++++++ src/render/cesium/globe.test.mjs | 58 +++++++++++++ src/render/cesium/harness.js | 1 + src/render/cesium/ports.js | 1 + src/render/cesium/ports.test.mjs | 1 + src/render/conformance/checks/ports.js | 32 +++++++ src/render/contract/globe.d.ts | 25 ++++-- 8 files changed, 227 insertions(+), 9 deletions(-) diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index e9c426229..3fd1941ec 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -48,6 +48,11 @@ optional, so a renderer written before it still conforms: otherwise (not on camera moves or tile loads), so the application can key cached heights by it. `isSettled('surface')` says whether that surface has loaded what is in view; a renderer without it answers `surface` as `base`. +- `SurfaceShading` has a `hillshade` kind: view-lit shading of the drawn + terrain's own relief (the ellipsoid's curvature where terrain has no + normals) that only darkens, at most `strength` opacity. The Cesium port + draws it as a globe material it takes only while no one else holds the + globe's material; it has no `relief` kind. - `camera.on('changed', cb, { threshold })` measures each listener by its own threshold under the capability `cameraChangeThreshold`; a renderer without it fires every `changed` listener at 0.5. diff --git a/src/render/cesium/globe.js b/src/render/cesium/globe.js index 12f7cf31b..9d5a2c79f 100644 --- a/src/render/cesium/globe.js +++ b/src/render/cesium/globe.js @@ -114,6 +114,34 @@ async function terrainProvider(spec, { worldDataToken }) { throw new TypeError(`Unknown terrain kind: ${spec.kind}`); } +/** + * `hillshade` surface shading: view-directed display lighting over the + * terrain's own normals, or the ellipsoid's curvature where the terrain + * has none (Cesium leaves normal-dependent materials out without them). It + * darkens only, up to `strength` opacity; it stands for no sun, changes no + * geometry and asks for no data. + * @param {boolean} terrainNormals + */ +function hillshadeSource(terrainNormals) { + const normal = terrainNormals + ? 'vec3 normal = normalize(materialInput.normalEC);' + : `vec3 worldPosition = (czm_inverseView * vec4(-materialInput.positionToEyeEC, 1.0)).xyz; + vec3 geodeticNormal = normalize(worldPosition * czm_ellipsoidInverseRadii * czm_ellipsoidInverseRadii); + vec3 normal = normalize(czm_viewRotation * geodeticNormal);`; + return ` +czm_material czm_getMaterial(czm_materialInput materialInput) +{ + czm_material material = czm_getDefaultMaterial(materialInput); + ${normal} + vec3 displayLight = normalize(vec3(-0.45, 0.55, 0.8)); + float shade = clamp((1.0 - dot(normal, displayLight)) * strength * (0.32 / 0.28), 0.0, strength); + material.diffuse = vec3(0.0); + material.alpha = shade; + return material; +} +`; +} + /** The last `surfaceVersion` any globe port handed out. */ let surfaceVersions = 0; @@ -456,6 +484,10 @@ export function createCesiumGlobe( scene.preUpdate.addEventListener(() => { // A throw here would stop the widget's render loop. try { + if (shadingStale()) { + applyShading(); + requestRender('base'); + } if (imagery.list().length) imagery.sync(); if (progressListeners.size === 0) return; const base = drawnBase(); @@ -467,6 +499,84 @@ export function createCesiumGlobe( }), ); + // --- Surface shading -------------------------------------------------- + + // `setSurfaceShading`: the globe material this port owns, while it shades. + // It takes the globe's material only when no one else holds it, and gives + // it back on null. On the tick after a change it follows the terrain + // (with normals or without), lets go of a material someone replaced, and + // takes the globe's material once it comes free. + let shading = null; + let shadingMaterial = null; + let shadingNormals = null; + // The terrain's normals when shading was last applied, owned or not, so + // an idle tick never applies it again. + let shadingSeen = null; + // A material that could not be made is not retried until the terrain or + // the shading changes. + let shadingBroken = false; + const shadingNormalsNow = () => + scene.globe?.terrainProvider?.hasVertexNormals === true; + // Whether a tick should apply the shading again: the terrain's normals + // changed, someone took our material, or the globe's material came free. + function shadingStale() { + const globe = scene.globe; + if (!shading || !globe) return false; + if (shadingSeen !== shadingNormalsNow()) return true; + if (shadingMaterial) return globe.material !== shadingMaterial; + return globe.material == null && !shadingBroken; + } + function dropShadingMaterial() { + if (!shadingMaterial) return; + if (scene.globe && scene.globe.material === shadingMaterial) + scene.globe.material = undefined; + if (!shadingMaterial.isDestroyed?.()) shadingMaterial.destroy?.(); + shadingMaterial = null; + shadingNormals = null; + } + function applyShading() { + const globe = scene.globe; + const normals = shadingNormalsNow(); + if (normals !== shadingSeen) shadingBroken = false; + shadingSeen = normals; + if (!shading || !globe) return dropShadingMaterial(); + if (shadingMaterial && globe.material !== shadingMaterial) { + // Someone else took the globe's material: theirs it stays, and ours, + // no longer drawn, goes. + if (!shadingMaterial.isDestroyed?.()) shadingMaterial.destroy?.(); + shadingMaterial = null; + shadingNormals = null; + } + if (shadingMaterial && shadingNormals === normals) { + shadingMaterial.uniforms.strength = shading.strength; + return; + } + if (!shadingMaterial && globe.material != null) return; + dropShadingMaterial(); + shadingBroken = true; + shadingMaterial = new Cesium.Material({ + fabric: { + type: normals ? 'GEVHillshadeTerrain' : 'GEVHillshadeCurvature', + uniforms: { strength: shading.strength }, + source: hillshadeSource(normals), + }, + translucent: true, + }); + shadingBroken = false; + shadingNormals = normals; + globe.material = shadingMaterial; + } + function setSurfaceShading(next) { + if (next && next.kind !== 'hillshade') + throw new TypeError(`This renderer has no ${next.kind} shading`); + shading = next + ? { strength: Math.min(1, Math.max(0, Number(next.strength) || 0)) } + : null; + shadingBroken = false; + applyShading(); + requestRender('base'); + } + // --- Port ------------------------------------------------------------------ const port = { @@ -493,6 +603,7 @@ export function createCesiumGlobe( if (can('globeVisibility')) port.isGlobeVisible = () => scene.globe?.show === true; if (can('surfaceIdentity')) port.surfaceVersion = readSurfaceVersion; + if (can('surfaceShading')) port.setSurfaceShading = setSurfaceShading; if (can('splitSwipe')) { // Cesium's split starts at the canvas's left edge, as the scene was // made: a `left` layer shows once the split moves. @@ -511,6 +622,8 @@ export function createCesiumGlobe( photorealGen += 1; terrainGen += 1; for (const off of removers) off(); + shading = null; + dropShadingMaterial(); progressListeners.clear(); for (const done of [...settleWaits]) done(); imagery.dispose(); diff --git a/src/render/cesium/globe.test.mjs b/src/render/cesium/globe.test.mjs index c4c67fc70..b5b1bd062 100644 --- a/src/render/cesium/globe.test.mjs +++ b/src/render/cesium/globe.test.mjs @@ -629,3 +629,61 @@ test('surfaceVersion follows what heights answer against; surface settles on it' plain.scene.globe.show = false; assert.equal(plain.port.isSettled('surface'), plain.port.isSettled('base')); }); + +test('hillshade shading owns a free globe material, follows the terrain, gives it back', () => { + const { scene, port, tick, dispose, renders } = setup( + new Set([...ALL, 'surfaceShading']), + ); + assert.throws( + () => + port.setSurfaceShading({ + kind: 'relief', + values: new Float32Array(1), + width: 1, + height: 1, + rectangle: { west: 0, south: 0, east: 1, north: 1 }, + strength: 1, + }), + /no relief shading/, + ); + port.setSurfaceShading({ kind: 'hillshade', strength: 0.28 }); + const curvature = scene.globe.material; + assert.ok(curvature instanceof Cesium.Material); + assert.equal(curvature.type, 'GEVHillshadeCurvature'); + assert.equal(curvature.uniforms.strength, 0.28); + port.setSurfaceShading({ kind: 'hillshade', strength: 0.5 }); + assert.equal(scene.globe.material, curvature, 'restrengthened in place'); + assert.equal(curvature.uniforms.strength, 0.5); + // Terrain with normals: the next tick shades its relief instead. + scene.globe.terrainProvider = { hasVertexNormals: true }; + tick(); + assert.equal(scene.globe.material.type, 'GEVHillshadeTerrain'); + assert.ok(curvature.isDestroyed()); + port.setSurfaceShading(null); + assert.equal(scene.globe.material, undefined, 'given back'); + // A material someone else holds stays theirs. + const theirs = { isDestroyed: () => false }; + scene.globe.material = theirs; + port.setSurfaceShading({ kind: 'hillshade', strength: 0.28 }); + assert.equal(scene.globe.material, theirs); + renders.length = 0; + tick(); + tick(); + assert.deepEqual(renders, [], 'idle ticks ask for no frame'); + // Once theirs is let go, the next tick takes the free material. + scene.globe.material = undefined; + tick(); + const ours = scene.globe.material; + assert.equal(ours.type, 'GEVHillshadeTerrain', 'taken once free'); + // Replaced while ours: let go of, and destroyed, on the next tick. + scene.globe.material = theirs; + tick(); + assert.equal(scene.globe.material, theirs); + assert.ok(ours.isDestroyed()); + renders.length = 0; + tick(); + assert.deepEqual(renders, [], 'and idle again'); + port.setSurfaceShading(null); + assert.equal(scene.globe.material, theirs); + dispose(); +}); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 9dde08480..d6af0ab17 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -76,6 +76,7 @@ export const CESIUM_CHECKS = new Set([ 'globe.imagery', 'globe.sky', 'globe.split', + 'globe.surfaceShading', 'globe.surfaceVersion', 'globe.visible', 'globe.withoutImageHooks', diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 8c5da2761..e91b3ef44 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -45,6 +45,7 @@ const GLOBE_CAPABILITIES = [ 'splitSwipe', 'imageHooks', 'surfaceIdentity', + 'surfaceShading', 'globeVisibility', ]; diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index a56173d23..b3a6f954a 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -24,6 +24,7 @@ test('capabilities follow what the scene supports', () => { 'splitSwipe', 'imageHooks', 'surfaceIdentity', + 'surfaceShading', ]; const globe = { show: true }; const draw = ['models', 'quads', 'meshes']; diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index 62b8c8eaf..b7bacfe75 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -3086,6 +3086,38 @@ export function portChecks() { }, { capability: 'surfaceIdentity' }, ), + check( + 'globe.surfaceShading', + 'hillshade shading is set, restrengthened and cleared, drawing each time', + async (h, r) => { + await overAustin(h, r, 20000); + const errors = []; + const off = r.on('error', (e) => errors.push(e)); + const draws = []; + const offDraw = r.frame.on('postRender', () => draws.push(1)); + try { + for (const shading of [ + { kind: 'hillshade', strength: 0.28 }, + { kind: 'hillshade', strength: 0.5 }, + null, + ]) { + const before = draws.length; + r.globe.setSurfaceShading(shading); + await h.frame(r); + await h.frame(r); + ok( + draws.length > before, + `drawn after ${shading?.strength ?? 'clearing'}`, + ); + } + deepEqual(errors, [], 'no errors'); + } finally { + off(); + offDraw(); + } + }, + { capability: 'surfaceShading' }, + ), check( 'globe.sky', 'sky settings round-trip and keep unchanged keys', diff --git a/src/render/contract/globe.d.ts b/src/render/contract/globe.d.ts index 31c10bdd0..2e1562f11 100644 --- a/src/render/contract/globe.d.ts +++ b/src/render/contract/globe.d.ts @@ -232,15 +232,22 @@ export interface SkySettings { lighting: boolean; } -export interface SurfaceShading { - kind: 'relief'; - /** Elevation-like field to shade, row-major, `width × height`. */ - values: Float32Array; - width: number; - height: number; - rectangle: GeoRect; - strength: number; -} +export type SurfaceShading = + | { + kind: 'relief'; + /** Elevation-like field to shade, row-major, `width × height`. */ + values: Float32Array; + width: number; + height: number; + rectangle: GeoRect; + strength: number; + } + /** + * View-lit shading of the drawn terrain's own relief (the ellipsoid's + * curvature where terrain has no normals); darkens only, at most + * `strength` opacity. + */ + | { kind: 'hillshade'; strength: number }; export interface LoadProgress { tilesPending: number;