Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
fix(layers): show layer text labels in globe mode (#3730)
Igor Dykhta9c95180f2469
diff --git a/src/deckgl-arrow-layers/src/layers/geo-arrow-text-layer.ts b/src/deckgl-arrow-layers/src/layers/geo-arrow-text-layer.tsindex b6c2fe1a9..a5fbb3e41 100644--- a/src/deckgl-arrow-layers/src/layers/geo-arrow-text-layer.ts+++ b/src/deckgl-arrow-layers/src/layers/geo-arrow-text-layer.ts@@ -244,8 +244,12 @@ export class GeoArrowTextLayer<ExtraProps extends object = object> extends CompodataComparator: (d1: {data: unknown}, d2: {data: unknown}) => {return d1.data === d2.data;},+ // Keep any `_subLayerProps` the caller passed in (e.g. a globe-aware+ // `characters` sublayer class) instead of replacing them wholesale._subLayerProps: {+ ...(this.props._subLayerProps as Record<string, any> | undefined),characters: {+ ...(this.props._subLayerProps as Record<string, any> | undefined)?.characters,dataComparator: (d1: {data: unknown}, d2: {data: unknown}) => {return d1.data === d2.data;}diff --git a/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.ts b/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.tsindex c7fa921de..8f64896ae 100644--- a/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.ts+++ b/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.ts@@ -4,57 +4,12 @@// @ts-ignore _MultiIconLayer is an experimental, underscore-prefixed deck.gl export whose named type binding isn't reliably resolvable through the package barrel under this project's module resolution. Access it off the namespace with a loose type.import {_MultiIconLayer as MultiIconLayer} from '@deck.gl/layers';-// Back-face culling for globe-mode text labels.-//-// deck.gl's TextLayer uses a MultiIconLayer to render glyphs; on a globe, labels-// anchored on the far hemisphere would otherwise be drawn "through" the planet.-// This subclass injects a small GLSL-// snippet into the icon vertex shader that degenerates (collapses) glyph vertices-// whose anchor is facing away from the camera, so back-side labels disappear.-//-// The test uses the true sphere-horizon condition rather than a fixed dot-product-// cutoff. In deck.gl common space the globe is a sphere centered at the origin, so:-// - the label anchor position doubles as its outward surface normal, and-// - a surface point is visible from the camera exactly when the angle between its-// normal and the camera direction is within the horizon half-angle, i.e.-// dot(normalize(anchor), normalize(cameraPos)) > R / d-// where R is the sphere radius (= |anchor|) and d = |cameraPos| is the camera-// distance from the globe center.-// This is zoom-independent: the visible cap automatically shrinks as you zoom in and-// grows as you pull back, so labels don't pop in/out at the limb while zooming.-const BACKFACE_CULL_INJECT = /* glsl */ `- // Only cull on the globe; leave web-mercator / flat views untouched.- if (project.projectionMode == PROJECTION_MODE_GLOBE) {- vec3 anchorCommon = geometry.position.xyz;- float radius = length(anchorCommon);- float camDist = length(project.cameraPosition);- // Guard against degenerate anchors / camera at the center.- if (radius > 0.0 && camDist > radius) {- float cosSurface = dot(anchorCommon / radius, project.cameraPosition / camDist);- // Cosine of the horizon half-angle. Add a tiny margin so labels are hidden just- // before they wrap exactly onto the limb (avoids glyphs smeared along the edge).- float cosHorizon = radius / camDist + 0.02;- if (cosSurface < cosHorizon) {- // Push the vertex outside clip space so this glyph is discarded. The hook- // exposes the clip-space position as \`position\`, not \`gl_Position\`.- position = vec4(0.0, 0.0, 2.0, 1.0);- }- }- }-`;+import {injectGlobeBackfaceCull} from './globe-backface-cull';export default class EnhancedMultiIconLayer extends (MultiIconLayer as any) {static layerName = 'EnhancedMultiIconLayer';getShaders() {- const shaders = super.getShaders();- const existing = shaders.inject?.['vs:DECKGL_FILTER_GL_POSITION'] || '';- return {- ...shaders,- inject: {- ...(shaders.inject || {}),- 'vs:DECKGL_FILTER_GL_POSITION': `${existing}\n${BACKFACE_CULL_INJECT}`- }- };+ return injectGlobeBackfaceCull(super.getShaders());}}diff --git a/src/deckgl-layers/src/globe/enhanced-text-background-layer.ts b/src/deckgl-layers/src/globe/enhanced-text-background-layer.tsnew file mode 100644index 000000000..8efb2cf37--- /dev/null+++ b/src/deckgl-layers/src/globe/enhanced-text-background-layer.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// Copy of EnhancedMultiIconLayer for deck.gl's text-background sublayer. Same inject,+// different base class, so far-side label backgrounds are culled with the glyphs.+// @ts-ignore _TextBackgroundLayer is an experimental, underscore-prefixed deck.gl export whose named type binding isn't reliably resolvable through the package barrel under this project's module resolution. Access it off the namespace with a loose type.+import {_TextBackgroundLayer as TextBackgroundLayer} from '@deck.gl/layers';++import {injectGlobeBackfaceCull} from './globe-backface-cull';++export default class EnhancedTextBackgroundLayer extends (TextBackgroundLayer as any) {+ static layerName = 'EnhancedTextBackgroundLayer';++ getShaders() {+ return injectGlobeBackfaceCull(super.getShaders());+ }+}diff --git a/src/deckgl-layers/src/globe/globe-backface-cull.spec.ts b/src/deckgl-layers/src/globe/globe-backface-cull.spec.tsnew file mode 100644index 000000000..6c9ed6cc1--- /dev/null+++ b/src/deckgl-layers/src/globe/globe-backface-cull.spec.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {injectGlobeBackfaceCull} from './globe-backface-cull';++const HOOK = 'vs:DECKGL_FILTER_GL_POSITION';++describe('globe-backface-cull', () => {+ test('appends to the position hook without dropping existing injects', () => {+ const shaders = injectGlobeBackfaceCull({+ vs: 'void main() {}',+ inject: {[HOOK]: 'existing_inject();', 'vs:DECKGL_FILTER_SIZE': 'size_inject();'}+ });++ expect(shaders.vs).toBe('void main() {}');+ expect(shaders.inject[HOOK]).toContain('existing_inject();');+ expect(shaders.inject[HOOK]).toContain('PROJECTION_MODE_GLOBE');+ expect(shaders.inject['vs:DECKGL_FILTER_SIZE']).toBe('size_inject();');+ });++ test('handles a base layer with no injects', () => {+ const shaders = injectGlobeBackfaceCull({vs: 'void main() {}'});+ expect(shaders.inject[HOOK]).toContain('PROJECTION_MODE_GLOBE');+ });++ test('only culls under the globe projection', () => {+ const glsl = injectGlobeBackfaceCull({}).inject[HOOK];+ expect(glsl).toMatch(/if\s*\(project\.projectionMode\s*==\s*PROJECTION_MODE_GLOBE\)/);+ });++ test('keeps the original EnhancedMultiIconLayer horizon formula', () => {+ const glsl = injectGlobeBackfaceCull({}).inject[HOOK];+ expect(glsl).toContain('radius / camDist + 0.02');+ expect(glsl).not.toContain('mix(');+ });+});diff --git a/src/deckgl-layers/src/globe/globe-backface-cull.ts b/src/deckgl-layers/src/globe/globe-backface-cull.tsnew file mode 100644index 000000000..21840c031--- /dev/null+++ b/src/deckgl-layers/src/globe/globe-backface-cull.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// Back-face culling for globe-mode text labels.+//+// Extracted unchanged from EnhancedMultiIconLayer so the same inject can be reused by+// the glyph sublayer and the text-background sublayer. The GLSL is a copy of the+// original snippet; do not change the horizon formula here without treating it as a+// behavior change for every globe label that already uses EnhancedMultiIconLayer+// (including MVTLabelLayer basemap place names).+//+// deck.gl's TextLayer uses a MultiIconLayer to render glyphs; on a globe, labels+// anchored on the far hemisphere would otherwise be drawn "through" the planet.+// This injects a small GLSL snippet into the vertex shader that degenerates+// (collapses) glyph vertices whose anchor is facing away from the camera, so+// back-side labels disappear.+//+// The test uses the true sphere-horizon condition rather than a fixed dot-product+// cutoff. In deck.gl common space the globe is a sphere centered at the origin, so:+// - the label anchor position doubles as its outward surface normal, and+// - a surface point is visible from the camera exactly when the angle between its+// normal and the camera direction is within the horizon half-angle, i.e.+// dot(normalize(anchor), normalize(cameraPos)) > R / d+// where R is the sphere radius (= |anchor|) and d = |cameraPos| is the camera+// distance from the globe center.+// This is zoom-independent: the visible cap automatically shrinks as you zoom in and+// grows as you pull back, so labels don't pop in/out at the limb while zooming.+const BACKFACE_CULL_INJECT = /* glsl */ `+ // Only cull on the globe; leave web-mercator / flat views untouched.+ if (project.projectionMode == PROJECTION_MODE_GLOBE) {+ vec3 anchorCommon = geometry.position.xyz;+ float radius = length(anchorCommon);+ float camDist = length(project.cameraPosition);+ // Guard against degenerate anchors / camera at the center.+ if (radius > 0.0 && camDist > radius) {+ float cosSurface = dot(anchorCommon / radius, project.cameraPosition / camDist);+ // Cosine of the horizon half-angle. Add a tiny margin so labels are hidden just+ // before they wrap exactly onto the limb (avoids glyphs smeared along the edge).+ float cosHorizon = radius / camDist + 0.02;+ if (cosSurface < cosHorizon) {+ // Push the vertex outside clip space so this glyph is discarded. The hook+ // exposes the clip-space position as \`position\`, not \`gl_Position\`.+ position = vec4(0.0, 0.0, 2.0, 1.0);+ }+ }+ }+`;++/**+ * Appends the globe back-face cull snippet to a layer's vertex position hook,+ * preserving anything the base layer already injected there.+ * Copied from EnhancedMultiIconLayer.getShaders().+ */+export function injectGlobeBackfaceCull(shaders: any): any {+ const existing = shaders.inject?.['vs:DECKGL_FILTER_GL_POSITION'] || '';+ return {+ ...shaders,+ inject: {+ ...(shaders.inject || {}),+ 'vs:DECKGL_FILTER_GL_POSITION': `${existing}\n${BACKFACE_CULL_INJECT}`+ }+ };+}diff --git a/src/deckgl-layers/src/globe/index.ts b/src/deckgl-layers/src/globe/index.tsindex a6c01eb93..5cf549743 100644--- a/src/deckgl-layers/src/globe/index.ts+++ b/src/deckgl-layers/src/globe/index.ts@@ -13,8 +13,10 @@// lng/lat and onto the sphere.// - Text/Label rendering with back-face culling: MVTLabelLayer renders place labels via a// TextLayer whose glyph sublayer is EnhancedMultiIconLayer, which degenerates glyph-// vertices on the far side of the globe (dot(surfaceNormal, toCamera) < 0.1) so labels-// don't show through the planet. Implemented as a GLSL inject.+// vertices on the far side of the globe so labels don't show through the planet.+// User layer text labels reuse the same inject (see globe-backface-cull) and, when a+// background is enabled, EnhancedTextBackgroundLayer — a copy of EnhancedMultiIconLayer+// for the background sublayer. The GLSL itself is unchanged from EnhancedMultiIconLayer.export {AtmosphereLayerRealistic,@@ -38,5 +40,6 @@ export {export type {GlobeBasemapProvider, GlobeAttribution} from './globe-layers';export {MVTLabelLayer} from './mvt-label-layer';export {default as EnhancedMultiIconLayer} from './enhanced-multi-icon-layer';+export {default as EnhancedTextBackgroundLayer} from './enhanced-text-background-layer';export {KeplerGlobeView} from './globe-view';export {getStarsBackgroundImage, drawStarsBackground} from './globe-stars-layer';diff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.tsindex 01a4a1794..7cc1b5934 100644--- a/src/layers/src/base-layer.ts+++ b/src/layers/src/base-layer.ts@@ -3,6 +3,7 @@import {COORDINATE_SYSTEM} from '@deck.gl/core';import {GeoArrowTextLayer} from '@kepler.gl/deckgl-arrow-layers';+import {EnhancedMultiIconLayer, EnhancedTextBackgroundLayer} from '@kepler.gl/deckgl-layers';import {DataFilterExtension} from '@deck.gl/extensions';import {TextLayer} from '@deck.gl/layers';import {console as Console} from 'global/window';@@ -1627,6 +1628,7 @@ class Layer implements KeplerLayer {const visible = this.config.isVisible && visibleInMap;const TextLayerClass = isArrowTable(data.data) ? GeoArrowTextLayer : TextLayer;+ const isGlobeMode = Boolean(mapState?.globe?.enabled);return data.textLabels.reduce((accu, d, i) => {if (d.getText) {@@ -1664,6 +1666,10 @@ class Layer implements KeplerLayer {parameters: {// text will always show on top of all layersdepthTest: false,+ // Globe mode sets a global `cull: true` to backface-cull the sphere+ // surface. That also culls the glyph quads, hiding every label, so+ // disable culling for the label layer (see mvt-label-layer.ts).+ ...(isGlobeMode ? {cull: false} : null),...(mapState?.layerParameters ?? {})},@@ -1685,9 +1691,14 @@ class Layer implements KeplerLayer {getColor: textLabel[i].color},_subLayerProps: {+ // Labels anchored on the far hemisphere would otherwise be drawn+ // through the planet, since depthTest is off. Both the glyphs and the+ // label background need it, or a far-side label leaves an empty box.+ ...(isGlobeMode ? {characters: {type: EnhancedMultiIconLayer}} : null),...(background? {background: {+ ...(isGlobeMode ? {type: EnhancedTextBackgroundLayer} : null),parameters: {cull: false,...(mapState?.layerParameters ?? {})diff --git a/test/browser/layer-tests/point-layer-specs.js b/test/browser/layer-tests/point-layer-specs.jsindex 25cf52a2f..acc572d3f 100644--- a/test/browser/layer-tests/point-layer-specs.js+++ b/test/browser/layer-tests/point-layer-specs.js@@ -8,6 +8,7 @@ import {scaleQuantize} from 'd3-scale';import cloneDeep from 'es-toolkit/compat/cloneDeep';import {DEFAULT_TEXT_LABEL, PROJECTED_PIXEL_SIZE_MULTIPLIER} from '@kepler.gl/constants';+import {EnhancedMultiIconLayer, EnhancedTextBackgroundLayer} from '@kepler.gl/deckgl-layers';import {KeplerGlLayers} from '@kepler.gl/layers';import {processGeojson} from '@kepler.gl/processors';import {INITIAL_MAP_STATE, INITIAL_VIS_STATE, renderDeckGlLayer} from '@kepler.gl/reducers';@@ -850,6 +851,76 @@ test('#PointLayer -> renderLayer split map label visibility', t => {t.end();});+test('#PointLayer -> renderLayer globe mode text labels', t => {+ const tc = {+ layer: {+ config: {+ dataId,+ label: 'gps point',+ columns: {+ lat: 'lat',+ lng: 'lng',+ altitude: 'id'+ },+ textLabel: [+ {+ field: {+ name: 'types',+ type: 'string'+ },+ background: true+ }+ ]+ },+ type: 'point',+ id: 'test_layer_1'+ },+ datasets: {+ [dataId]: preparedDataset+ }+ };++ const layer = testCreateLayerFromConfig(t, tc, {point: PointLayer});+ const data = testFormatLayerData(t, layer, tc.datasets);++ const renderWithMapState = mapState =>+ renderDeckGlLayer(+ {+ datasets: tc.datasets,+ layer,+ layerIndex: 0,+ data,+ mapState,+ interactionConfig: INITIAL_VIS_STATE.interactionConfig+ },+ {}+ ).find(l => String(l.id).includes('-label-'));++ const flatLabel = renderWithMapState(INITIAL_MAP_STATE);+ t.ok(flatLabel, 'should create a text label layer in flat mode');+ t.notOk('cull' in flatLabel.props.parameters, 'should not touch culling outside globe mode');+ t.notOk(+ flatLabel.props._subLayerProps.characters,+ 'should not override the glyph sublayer outside globe mode'+ );++ // globe mode sets a global `cull: true`, which would otherwise discard the glyph quads+ const globeLabel = renderWithMapState({...INITIAL_MAP_STATE, globe: {enabled: true}});+ t.equal(globeLabel.props.parameters.cull, false, 'should disable culling in globe mode');+ t.equal(+ globeLabel.props._subLayerProps.characters.type,+ EnhancedMultiIconLayer,+ 'should render glyphs with the globe back-face culling sublayer'+ );+ t.equal(+ globeLabel.props._subLayerProps.background.type,+ EnhancedTextBackgroundLayer,+ 'should render the label background with the globe back-face culling sublayer'+ );++ t.end();+});+test('#PointLayer -> updateLayer', t => {const layerConfig = {id: 'test1',