Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: hide overlapping text labels (#3707)
Igor Dykhta52a769e27914
diff --git a/src/components/src/side-panel/layer-panel/text-label-panel.tsx b/src/components/src/side-panel/layer-panel/text-label-panel.tsxindex 7123d9e13..0b68c6ab6 100644--- a/src/components/src/side-panel/layer-panel/text-label-panel.tsx+++ b/src/components/src/side-panel/layer-panel/text-label-panel.tsx@@ -70,6 +70,20 @@ function TextLabelPanelFactory(/></ConfigGroupCollapsibleHeader><ConfigGroupCollapsibleContent>+ <SidePanelSection>+ <SwitchWrapper>+ <PanelLabel>+ <FormattedMessage id="panel.text.collisionEnabled" />+ </PanelLabel>+ <Switch+ checked={Boolean(textLabel[0]?.collisionEnabled)}+ id={`${this.props.id}-textCollisionEnabled`}+ onChange={() =>+ updateLayerTextLabel('all', 'collisionEnabled', !textLabel[0]?.collisionEnabled)+ }+ />+ </SwitchWrapper>+ </SidePanelSection>{textLabel.map((tl, idx) => (<div key={tl.field ? tl.field.name : `null-${idx}`}><PanelLabel>diff --git a/src/constants/src/layers.ts b/src/constants/src/layers.tsindex e12057bb4..f0c3917c9 100644--- a/src/constants/src/layers.ts+++ b/src/constants/src/layers.ts@@ -51,7 +51,8 @@ export const DEFAULT_TEXT_LABEL: LayerTextLabel = {outlineWidth: 0,outlineColor: [255, 0, 0, 255],background: false,- backgroundColor: [0, 0, 200, 255]+ backgroundColor: [0, 0, 200, 255],+ collisionEnabled: false};const DEFAULT_COLOR_PALETTE = KEPLER_COLOR_PALETTES.find(diff --git a/src/deckgl-layers/src/globe/globe-backface-cull.spec.ts b/src/deckgl-layers/src/globe/globe-backface-cull.spec.tsindex 6c9ed6cc1..283a2ada0 100644--- a/src/deckgl-layers/src/globe/globe-backface-cull.spec.ts+++ b/src/deckgl-layers/src/globe/globe-backface-cull.spec.ts@@ -28,6 +28,15 @@ describe('globe-backface-cull', () => {expect(glsl).toMatch(/if\s*\(project\.projectionMode\s*==\s*PROJECTION_MODE_GLOBE\)/);});+ test('appends to an object-form position hook without stringifying it', () => {+ const shaders = injectGlobeBackfaceCull({+ inject: {[HOOK]: {order: 1, injection: 'existing_inject();'}}+ });+ expect(shaders.inject[HOOK]).toContain('existing_inject();');+ expect(shaders.inject[HOOK]).toContain('PROJECTION_MODE_GLOBE');+ expect(shaders.inject[HOOK]).not.toContain('[object Object]');+ });+test('keeps the original EnhancedMultiIconLayer horizon formula', () => {const glsl = injectGlobeBackfaceCull({}).inject[HOOK];expect(glsl).toContain('radius / camDist + 0.02');diff --git a/src/deckgl-layers/src/globe/globe-backface-cull.ts b/src/deckgl-layers/src/globe/globe-backface-cull.tsindex 21840c031..10623e0b4 100644--- a/src/deckgl-layers/src/globe/globe-backface-cull.ts+++ b/src/deckgl-layers/src/globe/globe-backface-cull.ts@@ -52,7 +52,8 @@ const BACKFACE_CULL_INJECT = /* glsl */ `* Copied from EnhancedMultiIconLayer.getShaders().*/export function injectGlobeBackfaceCull(shaders: any): any {- const existing = shaders.inject?.['vs:DECKGL_FILTER_GL_POSITION'] || '';+ const existingRaw = shaders.inject?.['vs:DECKGL_FILTER_GL_POSITION'] || '';+ const existing = typeof existingRaw === 'string' ? existingRaw : existingRaw.injection || '';return {...shaders,inject: {diff --git a/src/deckgl-types.d.ts b/src/deckgl-types.d.tsindex f7c6ac35b..7dc51aa56 100644--- a/src/deckgl-types.d.ts+++ b/src/deckgl-types.d.ts@@ -58,6 +58,7 @@ declare module '@deck.gl/core' {export type {CoordinateSystem} from '@deck.gl/core/dist/lib/constants';export type {ChangeFlags} from '@deck.gl/core/dist/lib/layer-state';export type {MapViewState} from '@deck.gl/core/dist/views/map-view';+ export type {FilterContext} from '@deck.gl/core/dist/passes/layers-pass';export type {Effect, PreRenderOptions, PostRenderOptions} from '@deck.gl/core/dist/lib/effect';export type {ControllerProps} from '@deck.gl/core/dist/controllers/controller';export type {BinaryAttribute} from '@deck.gl/core/dist/lib/attribute/attribute';@@ -78,6 +79,7 @@ declare module '@deck.gl/layers' {export {default as PolygonLayer} from '@deck.gl/layers/dist/polygon-layer/polygon-layer';export {default as GeoJsonLayer} from '@deck.gl/layers/dist/geojson-layer/geojson-layer';export {default as TextLayer} from '@deck.gl/layers/dist/text-layer/text-layer';+ export {default as _TextBackgroundLayer} from '@deck.gl/layers/dist/text-layer/text-background-layer/text-background-layer';export {default as SolidPolygonLayer} from '@deck.gl/layers/dist/solid-polygon-layer/solid-polygon-layer';export {default as PointCloudLayer} from '@deck.gl/layers/dist/point-cloud-layer/point-cloud-layer';diff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.tsindex 3a34879ed..30e71ffef 100644--- a/src/layers/src/base-layer.ts+++ b/src/layers/src/base-layer.ts@@ -4,8 +4,13 @@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 {CollisionFilterExtension, DataFilterExtension} from '@deck.gl/extensions';import {TextLayer} from '@deck.gl/layers';+import CollisionTextLayer from './collision-text-layer';+import {+ installCollisionFilterEffectAlignment,+ snapCollisionModuleFade+} from './collision-filter-effect';import {console as Console} from 'global/window';import keymirror from 'keymirror';import React from 'react';@@ -164,6 +169,39 @@ const dataFilterExtension = new DataFilterExtension({countItems: getApplicationConfig().useOnFilteredItemsChange ?? false});+/**+ * CollisionFilterExtension registers CollisionFilterEffect only in+ * initializeState. Toggling the extension onto an already-matched TextLayer+ * skips that hook, so luma.gl never gets collision_texture and aborts the+ * draw (all labels vanish). Re-run initializeState from updateState when the+ * collision attribute is missing.+ */+class KeplerCollisionFilterExtension extends CollisionFilterExtension {+ static extensionName = 'CollisionFilterExtension';++ getShaders(this: any) {+ const base = CollisionFilterExtension.prototype.getShaders.call(this) || {};+ return snapCollisionModuleFade(base);+ }++ initializeState(this: any, context: any, extension: this) {+ // Align CollisionFilterEffect to the live drawing buffer before deck.gl+ // registers it. Video export scales the GL canvas above CSS size; without+ // this the collision map only covers the top-left of the frame.+ installCollisionFilterEffectAlignment(this.context?.deck || context?.deck);+ CollisionFilterExtension.prototype.initializeState.call(this, context, extension);+ }++ updateState(this: any, _params: unknown, extension: this) {+ const attributeManager = this.getAttributeManager();+ if (attributeManager && !attributeManager.attributes.collisionPriorities) {+ KeplerCollisionFilterExtension.prototype.initializeState.call(this, this.context, extension);+ }+ }+}++const collisionFilterExtension = new KeplerCollisionFilterExtension();+// eslint-disable-next-line @typescript-eslint/no-unused-varsconst defaultDataAccessor = dc => d => d;const identity = d => d;@@ -1627,19 +1665,38 @@ class Layer implements KeplerLayer {// labels should be visible and, if splitMap, shown in one of the panelsconst visible = this.config.isVisible && visibleInMap;- const TextLayerClass = isArrowTable(data.data) ? GeoArrowTextLayer : TextLayer;+ const isArrow = isArrowTable(data.data);const isGlobeMode = Boolean(mapState?.globe?.enabled);return data.textLabels.reduce((accu, d, i) => {if (d.getText) {- const background = textLabel[i].background || backgroundProps?.background;+ const userBackground = Boolean(textLabel[i].background || backgroundProps?.background);+ // GeoArrowTextLayer cannot draw a collision hit-area background, so GPU+ // collision would sample the geographic anchor and cull offset labels.+ // Leave Arrow labels unfiltered until that path exists.+ const collisionEnabled = Boolean(textLabel[i].collisionEnabled) && !isArrow;+ // CollisionTextLayer draws an expanded background in the collision pass so+ // the GPU hit-test still covers the geographic anchor after pixelOffset.+ const TextLayerClass = collisionEnabled+ ? CollisionTextLayer+ : isArrow+ ? GeoArrowTextLayer+ : TextLayer;const getText = animationConfig ? f => d.getText(f, animationConfig) : d.getText;+ const background = userBackground || collisionEnabled;+ // Distinct id when collision is on so deck.gl does not rematch the+ // previous TextLayer. Matching would keep a stale collisionPriorities+ // attribute after the extension is removed, and skip initializeState+ // (no collision_texture) when it is added.+ const labelId = `${this.id}-label-${textLabel[i].field?.name}${+ collisionEnabled ? '-collision' : ''+ }`;accu.push(// @ts-expect-errornew TextLayerClass({...sharedProps,- id: `${this.id}-label-${textLabel[i].field?.name}`,+ id: labelId,data: data.data,visible,getText,@@ -1682,6 +1739,15 @@ class Layer implements KeplerLayer {}),...(mapState?.layerParameters ?? {})},+ ...(collisionEnabled+ ? {+ extensions: [...(sharedProps.extensions || []), collisionFilterExtension],+ collisionEnabled: true,+ collisionGroup: `${this.id}-text-label-${i}`,+ getCollisionPriority: 0,+ collisionShowBackground: userBackground+ }+ : {}),getFilterValue: data.getFilterValue,updateTriggers: {@@ -1698,7 +1764,8 @@ class Layer implements KeplerLayer {},getTextAnchor: textLabel[i].anchor,getAlignmentBaseline: textLabel[i].alignment,- getColor: textLabel[i].color+ getColor: textLabel[i].color,+ collisionEnabled},_subLayerProps: {// Labels anchored on the far hemisphere would otherwise be drawndiff --git a/src/layers/src/collision-filter-effect.spec.ts b/src/layers/src/collision-filter-effect.spec.tsnew file mode 100644index 000000000..62dc82b3a--- /dev/null+++ b/src/layers/src/collision-filter-effect.spec.ts@@ -0,0 +1,160 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {+ alignCollisionFilterEffect,+ installCollisionFilterEffectAlignment,+ snapCollisionModuleFade,+ type DeckLike+} from './collision-filter-effect';++describe('alignCollisionFilterEffect', () => {+ function createEffect() {+ const canvasContext = {+ getPixelSize: jest.fn((_opts?: unknown): [number, number] => [1080, 608]),+ getDevicePixelRatio: jest.fn((_opts?: unknown) => 3.555),+ getDrawingBufferSize: jest.fn((): [number, number] => [1080, 608]),+ cssToDeviceRatio: jest.fn(() => 2)+ };+ const gl = {+ drawingBufferWidth: 1920,+ drawingBufferHeight: 1080+ };+ const effect = {+ id: 'collision-filter-effect',+ lastViewport: {id: 'stale'} as unknown,+ context: {device: {gl, canvasContext}},+ preRender: jest.fn((_opts?: unknown) => ({+ pixelSize: canvasContext.getPixelSize(),+ devicePixelRatio: canvasContext.getDevicePixelRatio(),+ lastViewport: effect.lastViewport+ }))+ };+ return {effect, canvasContext};+ }++ test('sizes the collision FBO from the live GL buffer and CSS viewport', () => {+ const {effect, canvasContext} = createEffect();+ const originalGetPixelSize = canvasContext.getPixelSize;+ const originalGetDevicePixelRatio = canvasContext.getDevicePixelRatio;+ alignCollisionFilterEffect(effect);++ expect(effect.preRender({viewports: [{width: 540}]})).toEqual({+ pixelSize: [1920, 1080],+ devicePixelRatio: 1920 / 540,+ lastViewport: undefined+ });+ expect(canvasContext.getPixelSize).toBe(originalGetPixelSize);+ expect(canvasContext.getDevicePixelRatio).toBe(originalGetDevicePixelRatio);+ expect(canvasContext.getPixelSize()).toEqual([1080, 608]);+ expect(canvasContext.getDevicePixelRatio()).toBe(3.555);+ });++ test('falls back to luma drawing-buffer size when GL sizes are missing', () => {+ const canvasContext = {+ getPixelSize: jest.fn((_opts?: unknown): [number, number] => [800, 600]),+ getDevicePixelRatio: jest.fn((_opts?: unknown) => 2),+ getDrawingBufferSize: jest.fn((): [number, number] => [1600, 1200]),+ cssToDeviceRatio: jest.fn(() => 2)+ };+ const effect = {+ context: {device: {canvasContext}},+ preRender: jest.fn((_opts?: unknown) => ({+ pixelSize: canvasContext.getPixelSize(),+ devicePixelRatio: canvasContext.getDevicePixelRatio()+ }))+ };+ alignCollisionFilterEffect(effect);++ expect(effect.preRender({viewports: [{width: 800}]})).toEqual({+ pixelSize: [1600, 1200],+ devicePixelRatio: 2+ });+ });++ test('only invalidates lastViewport when the drawing buffer size changes', () => {+ const {effect} = createEffect();+ alignCollisionFilterEffect(effect);++ effect.preRender({viewports: [{width: 540}]});+ effect.lastViewport = {id: 'current'};+ expect(effect.preRender({viewports: [{width: 540}]})).toMatchObject({+ lastViewport: {id: 'current'}+ });+ });+});++describe('installCollisionFilterEffectAlignment', () => {+ test('wraps CollisionFilterEffect before Deck adds it as a default effect', () => {+ const added: unknown[] = [];+ const addDefaultEffect = jest.fn(+ (effect: {id?: string; preRender?: (opts?: unknown) => unknown}) => {+ added.push(effect.preRender?.());+ }+ );+ const deck: DeckLike = {+ _addDefaultEffect: addDefaultEffect+ };+ installCollisionFilterEffectAlignment(deck);++ const canvasContext = {+ getPixelSize: () => [100, 100] as [number, number],+ getDevicePixelRatio: () => 1,+ getDrawingBufferSize: () => [200, 200] as [number, number],+ cssToDeviceRatio: () => 2+ };+ const effect = {+ id: 'collision-filter-effect',+ context: {device: {canvasContext}},+ preRender: (_opts?: unknown) => String(canvasContext.getPixelSize())+ };++ deck._addDefaultEffect?.(effect);+ expect(added).toEqual(['200,200']);+ expect(deck.__keplerCollisionFilterAligned).toBe(true);++ installCollisionFilterEffectAlignment(deck);+ expect(addDefaultEffect).toHaveBeenCalledTimes(1);+ });++ test('does not wrap unrelated default effects', () => {+ const lighting = {id: 'lighting', preRender: jest.fn()};+ const deck: DeckLike = {+ _addDefaultEffect: jest.fn()+ };+ installCollisionFilterEffectAlignment(deck);+ deck._addDefaultEffect?.(lighting);+ expect(lighting.preRender.mock.calls.length).toBe(0);+ });+});++describe('snapCollisionModuleFade', () => {+ const positionHook = 'vs:DECKGL_FILTER_GL_POSITION';++ test('appends binary fade snapping to the collision module inject', () => {+ const shaders = snapCollisionModuleFade({+ modules: [+ {+ name: 'collision',+ inject: {[positionHook]: 'collision_fade = collision_isVisible(tex, color);'}+ }+ ]+ });+ const collision = shaders.modules?.find(+ (module: {name: string}) => module.name === 'collision'+ );+ expect(collision.inject[positionHook]).toContain('collision_isVisible');+ expect(collision.inject[positionHook]).toContain('collision_fade < 0.5');+ expect(shaders.inject).toBeUndefined();+ });++ test('does not produce an object inject that deck.gl would stringify as [object Object]', () => {+ const shaders = snapCollisionModuleFade({+ modules: [{name: 'collision', inject: {[positionHook]: 'base();'}}]+ });+ const globeInject = 'if (project.projectionMode == PROJECTION_MODE_GLOBE) {}';+ const merged = (globeInject || '') + (shaders.inject?.[positionHook] || '');+ expect(merged).not.toContain('[object Object]');+ expect(merged).toContain('PROJECTION_MODE_GLOBE');+ });+});diff --git a/src/layers/src/collision-filter-effect.ts b/src/layers/src/collision-filter-effect.tsnew file mode 100644index 000000000..ab9b0cd0d--- /dev/null+++ b/src/layers/src/collision-filter-effect.ts@@ -0,0 +1,162 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++/**+ * Video export (hubble) mutates window.devicePixelRatio so MapLibre/deck draw+ * at the output resolution into a small CSS preview. CollisionFilterEffect+ * still sizes its FBO from luma's CSS pixel size and projects with+ * window.devicePixelRatio, so the collision pass only fills the top-left of+ * the texture and every other label is culled.+ *+ * Same class of mismatch as alignExportShadowPass: size the collision map+ * from the live GL buffer and project with drawingBuffer / viewport CSS.+ */++/**+ * Append binary fade snapping to the collision shader *module* inject.+ *+ * Do not put an `{order, injection}` object on the extension's own `inject` map.+ * deck.gl mergeShaders concatenates injects with `+`, so an object becomes+ * `[object Object]` in GLSL (`'[' : syntax error`) when another layer (globe+ * back-face cull) already injected a string at the same hook.+ */+export function snapCollisionModuleFade(shaders: {modules?: any[]; inject?: any} = {}): {+ modules?: any[];+ inject?: any;+} {+ const positionHook = 'vs:DECKGL_FILTER_GL_POSITION';+ const modules = (shaders.modules || []).map((module: any) => {+ if (module?.name !== 'collision') {+ return module;+ }+ const baseInject = module.inject?.[positionHook];+ const baseInjectCode =+ typeof baseInject === 'string' ? baseInject : baseInject?.injection || '';+ return {+ ...module,+ inject: {+ ...module.inject,+ [positionHook]: `${baseInjectCode}+ if (collision.enabled) {+ if (collision_fade < 0.5) {+ collision_fade = 0.0;+ position = vec4(0.0, 0.0, 2.0, 1.0);+ } else {+ collision_fade = 1.0;+ }+ }`+ }+ };+ });+ return {...shaders, modules};+}++export type CollisionFilterEffectLike = {+ id?: string;+ preRender?: (opts?: unknown) => unknown;+ lastViewport?: unknown;+ context?: {device?: CanvasDevice};+ collisionFilterPass?: {device?: CanvasDevice};+};++type CanvasDevice = {+ gl?: {+ drawingBufferWidth?: number;+ drawingBufferHeight?: number;+ };+ canvasContext?: {+ getPixelSize?: () => [number, number];+ getDevicePixelRatio?: () => number;+ getDrawingBufferSize?: () => [number, number];+ cssToDeviceRatio?: () => number;+ };+};++export type DeckLike = {+ __keplerCollisionFilterAligned?: boolean;+ _addDefaultEffect?: (effect: CollisionFilterEffectLike) => void;+};++function getCanvasDevice(effect: CollisionFilterEffectLike): CanvasDevice | undefined {+ return effect.context?.device || effect.collisionFilterPass?.device;+}++/**+ * Wrap CollisionFilterEffect.preRender so the collision FBO matches the color+ * pass during high-DPI / video-export canvas scaling.+ */+export function alignCollisionFilterEffect(effect: CollisionFilterEffectLike): void {+ const preRender = effect.preRender?.bind(effect);+ if (!preRender) {+ return;+ }++ let lastBufferKey = '';++ effect.preRender = function alignedCollisionPreRender(+ this: CollisionFilterEffectLike,+ opts: any+ ) {+ const device = getCanvasDevice(this);+ const canvasContext = device?.canvasContext;+ if (!canvasContext) {+ return preRender(opts);+ }++ const gl = device?.gl;+ const drawingBuffer = canvasContext.getDrawingBufferSize?.();+ const width = gl?.drawingBufferWidth || drawingBuffer?.[0];+ const height = gl?.drawingBufferHeight || drawingBuffer?.[1];+ const viewportWidth = opts?.viewports?.[0]?.width;++ const prevGetPixelSize = canvasContext.getPixelSize;+ const prevGetDevicePixelRatio = canvasContext.getDevicePixelRatio;++ if (width && height) {+ canvasContext.getPixelSize = () => [width, height];+ canvasContext.getDevicePixelRatio = () =>+ viewportWidth ? width / viewportWidth : canvasContext.cssToDeviceRatio?.() ?? 1;+ } else {+ canvasContext.getPixelSize = () => canvasContext.getDrawingBufferSize?.() ?? [1, 1];+ canvasContext.getDevicePixelRatio = () => canvasContext.cssToDeviceRatio?.() ?? 1;+ }++ const bufferKey = `${width || 0}x${height || 0}`;+ if (bufferKey !== lastBufferKey) {+ lastBufferKey = bufferKey;+ // CollisionFilterEffect skips redraw when only the FBO size changes+ // (visgl/deck.gl#10333). Force a new collision pass after resize.+ this.lastViewport = undefined;+ }++ try {+ return preRender(opts);+ } finally {+ canvasContext.getPixelSize = prevGetPixelSize;+ canvasContext.getDevicePixelRatio = prevGetDevicePixelRatio;+ }+ };+}++/**+ * CollisionFilterExtension adds CollisionFilterEffect via Deck._addDefaultEffect.+ * Wrap that once per Deck so the instance is aligned before setup().+ */+export function installCollisionFilterEffectAlignment(deck?: DeckLike | null): void {+ if (+ !deck ||+ deck.__keplerCollisionFilterAligned ||+ typeof deck._addDefaultEffect !== 'function'+ ) {+ return;+ }++ deck.__keplerCollisionFilterAligned = true;+ const addDefaultEffect = deck._addDefaultEffect.bind(deck);+ deck._addDefaultEffect = (effect: CollisionFilterEffectLike) => {+ if (effect?.id === 'collision-filter-effect') {+ alignCollisionFilterEffect(effect);+ }+ return addDefaultEffect(effect);+ };+}diff --git a/src/layers/src/collision-text-layer.spec.ts b/src/layers/src/collision-text-layer.spec.tsnew file mode 100644index 000000000..da4109964--- /dev/null+++ b/src/layers/src/collision-text-layer.spec.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import type {FilterContext} from '@deck.gl/core';++import CollisionTextLayer from './collision-text-layer';++describe('CollisionTextLayer.filterSubLayer', () => {+ const filter = CollisionTextLayer.prototype.filterSubLayer;+ const ctx = (id: string, renderPass: string): FilterContext =>+ ({layer: {id}, renderPass} as FilterContext);++ test('collision pass draws only the background hit area', () => {+ const layer = {props: {collisionShowBackground: false}};+ expect(filter.call(layer, ctx('label-types-background', 'collision'))).toBe(true);+ expect(filter.call(layer, ctx('label-types-characters', 'collision'))).toBe(false);+ });++ test('color pass hides the forced collision background', () => {+ const layer = {props: {collisionShowBackground: false}};+ expect(filter.call(layer, ctx('label-types-background', 'screen'))).toBe(false);+ expect(filter.call(layer, ctx('label-types-characters', 'screen'))).toBe(true);+ });++ test('color pass keeps a user-configured background', () => {+ const layer = {props: {collisionShowBackground: true}};+ expect(filter.call(layer, ctx('label-types-background', 'screen'))).toBe(true);+ expect(filter.call(layer, ctx('label-types-characters', 'screen'))).toBe(true);+ });++ test('does not treat a label field named background as the hit-area sublayer', () => {+ const layer = {props: {collisionShowBackground: false}};+ expect(filter.call(layer, ctx('point-label-background-characters', 'screen'))).toBe(true);+ expect(filter.call(layer, ctx('point-label-background-characters', 'collision'))).toBe(false);+ });+});diff --git a/src/layers/src/collision-text-layer.ts b/src/layers/src/collision-text-layer.tsnew file mode 100644index 000000000..5fc68095c--- /dev/null+++ b/src/layers/src/collision-text-layer.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {console as Console} from 'global/window';+import {EnhancedTextBackgroundLayer} from '@kepler.gl/deckgl-layers';+import {TextLayer} from '@deck.gl/layers';+import type {FilterContext} from '@deck.gl/core';++type CollisionTextLayerProps = {+ collisionShowBackground?: boolean;+};++/**+ * CollisionFilterExtension samples geometry.worldPosition (the geographic+ * anchor). Kepler's labels are shifted with getPixelOffset / non-centered+ * anchors, so that sample misses the glyphs and every label is culled.+ *+ * PointLabelLayer's approach: draw an expanded text background in the+ * collision pass so the hit area still covers the anchor. In the color pass+ * the expanded padding is skipped so a user-configured background keeps its+ * normal size.+ */+class CollisionTextBackgroundLayer extends EnhancedTextBackgroundLayer {+ static layerName = 'CollisionTextBackgroundLayer';++ getShaders() {+ const shaders = super.getShaders();+ let vs = shaders.vs as string;+ if (!vs.includes('textBackground.padding.') || !vs.includes('void main(void) {')) {+ Console.error('Cannot edit text-background-layer shader for collision');+ return shaders;+ }+ vs = vs.split('textBackground.padding.').join('_padding.');+ vs = vs.replace(+ 'void main(void) {',+ `void main(void) {+ // collision.sort is true only while drawing the collision map. Expand toward+ // the geographic origin (so pixelOffset still covers the sample point) and+ // add extra padding so the 5x5 collision sample sits inside the hit box.+ // Color/picking keep the configured background size.+ vec4 _padding = textBackground.padding;+ if (collision.sort) {+ _padding += instancePixelOffsets.xyxy * vec4(1.0, 1.0, -1.0, -1.0) + vec4(16.0);+ }`+ );+ return {...shaders, vs};+ }+}++export default class CollisionTextLayer<DataT = any> extends TextLayer<DataT> {+ static layerName = 'CollisionTextLayer';+ // Kepler-only prop; TextLayer.defaultProps is typed as DefaultProps<TextLayerProps>+ // so an extra key cannot be declared on the static side.+ static defaultProps = {+ ...(TextLayer.defaultProps as object),+ collisionShowBackground: false+ } as typeof TextLayer.defaultProps;++ getSubLayerClass(subLayerId: string, DefaultLayerClass: any): any {+ if (subLayerId === 'background') {+ // Prefer CollisionTextBackgroundLayer over _subLayerProps.background.type+ // (EnhancedTextBackgroundLayer). This subclass already injects globe+ // back-face culling via EnhancedTextBackgroundLayer.+ return CollisionTextBackgroundLayer;+ }+ return super.getSubLayerClass(subLayerId, DefaultLayerClass);+ }++ filterSubLayer({layer, renderPass}: FilterContext): boolean {+ // TextLayer names the hit-area sublayer `${parentId}-background`. Match the+ // suffix so a label field named "background" is not treated as that sublayer.+ const isBackground = layer.id.endsWith('-background');+ if (renderPass === 'collision') {+ return isBackground;+ }+ if (isBackground) {+ return Boolean((this.props as CollisionTextLayerProps).collisionShowBackground);+ }+ return true;+ }+}diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.tsindex b5c1769d4..f1977cd49 100644--- a/src/localization/src/translations/ca.ts+++ b/src/localization/src/translations/ca.ts@@ -61,7 +61,8 @@ export default {alignment: 'Alineació',addMoreLabel: 'Afegeix més etiquetes',outlineWidth: 'Amplada del contorn',- outlineColor: 'Color del contorn'+ outlineColor: 'Color del contorn',+ collisionEnabled: 'Amaga les etiquetes superposades'}},sidebar: {diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.tsindex 3e0b9370d..101c32073 100644--- a/src/localization/src/translations/cn.ts+++ b/src/localization/src/translations/cn.ts@@ -61,7 +61,8 @@ export default {alignment: '对齐方式',addMoreLabel: '添加更多标签',outlineWidth: '轮廓宽度',- outlineColor: '轮廓颜色'+ outlineColor: '轮廓颜色',+ collisionEnabled: '隐藏重叠标签'}},sidebar: {diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex e7569f7ce..23b790ae7 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -71,7 +71,8 @@ export default {alignment: 'Alignment',addMoreLabel: 'Add More Label',outlineWidth: 'Outline width',- outlineColor: 'Outline color'+ outlineColor: 'Outline color',+ collisionEnabled: 'Hide overlapping labels'}},sidebar: {diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.tsindex be2c0e809..1f2c92f3c 100644--- a/src/localization/src/translations/es.ts+++ b/src/localization/src/translations/es.ts@@ -61,7 +61,8 @@ export default {alignment: 'Alineación',addMoreLabel: 'Añadir más etiquetas',outlineWidth: 'Ancho del contorno',- outlineColor: 'Color del contorno'+ outlineColor: 'Color del contorno',+ collisionEnabled: 'Ocultar etiquetas superpuestas'}},sidebar: {diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.tsindex 0c0a653c7..2490489cf 100644--- a/src/localization/src/translations/fi.ts+++ b/src/localization/src/translations/fi.ts@@ -60,7 +60,8 @@ export default {alignment: 'Sijoittelu',addMoreLabel: 'Lisää uusia nimiöitä',outlineWidth: 'Ääriviivan leveys',- outlineColor: 'Ääriviivan väri'+ outlineColor: 'Ääriviivan väri',+ collisionEnabled: 'Piilota päällekkäiset nimiöt'}},sidebar: {diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.tsindex 2c38ddba6..76f160a7f 100644--- a/src/localization/src/translations/ja.ts+++ b/src/localization/src/translations/ja.ts@@ -61,7 +61,8 @@ export default {addMoreLabel: 'ラベルを追加',backgroundColor: '背景色',outlineWidth: '輪郭線の幅',- outlineColor: '輪郭線の色'+ outlineColor: '輪郭線の色',+ collisionEnabled: '重なったラベルを非表示'}},sidebar: {diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.tsindex 7351df22c..d6f8c05b7 100644--- a/src/localization/src/translations/pt.ts+++ b/src/localization/src/translations/pt.ts@@ -61,7 +61,8 @@ export default {addMoreLabel: 'Adicionar mais Rótulos',backgroundColor: 'Cor de fundo',outlineWidth: 'Largura do contorno',- outlineColor: 'Cor do contorno'+ outlineColor: 'Cor do contorno',+ collisionEnabled: 'Ocultar rótulos sobrepostos'}},sidebar: {diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.tsindex 75b54d847..4e04a0aa1 100644--- a/src/localization/src/translations/ru.ts+++ b/src/localization/src/translations/ru.ts@@ -61,7 +61,8 @@ export default {alignment: 'Положение',addMoreLabel: 'Добавить еще ярлык',outlineWidth: 'Ширина контура',- outlineColor: 'Цвет контура'+ outlineColor: 'Цвет контура',+ collisionEnabled: 'Скрывать пересекающиеся подписи'}},sidebar: {diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex 57722ccff..1ea47ee9e 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -791,7 +791,11 @@ function addOrRemoveTextLabels(newFields, textLabel, defaultTextLabel = DEFAULT_...newTextLabel.filter(tl => tl.field),...addFields.map(af => ({...defaultTextLabel,- field: af+ field: af,+ collisionEnabled: Boolean(+ textLabel.find(tl => tl.collisionEnabled)?.collisionEnabled ??+ defaultTextLabel.collisionEnabled+ )}))];@@ -835,11 +839,19 @@ export function layerTextLabelChangeUpdater(let newTextLabel = textLabel.slice();if (!textLabel[idx] && idx === textLabel.length) {// if idx is set to length, add empty text label- newTextLabel = [...textLabel, defaultTextLabel];+ newTextLabel = [+ ...textLabel,+ {+ ...defaultTextLabel,+ collisionEnabled: Boolean(textLabel[0]?.collisionEnabled)+ }+ ];}if (idx === 'all' && prop === 'fields') {newTextLabel = addOrRemoveTextLabels(value, textLabel, defaultTextLabel);+ } else if (idx === 'all' && prop) {+ newTextLabel = textLabel.map(tl => ({...tl, [prop]: value}));} else {newTextLabel = updateTextLabelPropAndValue(idx, prop, value, newTextLabel);}diff --git a/src/types/layers.d.ts b/src/types/layers.d.tsindex de1c6b0ca..161bfbc52 100644--- a/src/types/layers.d.ts+++ b/src/types/layers.d.ts@@ -171,6 +171,8 @@ export type LayerTextLabel = {outlineWidth: number;outlineColor: RGBAColor;backgroundColor: RGBAColor | null;+ /** Hide labels that overlap other labels of the same field (GPU collision filter). */+ collisionEnabled?: boolean;};export type ColorRangeConfig = {diff --git a/test/browser/layer-tests/h3-hexagon-layer-specs.js b/test/browser/layer-tests/h3-hexagon-layer-specs.jsindex 358b6d469..acb95236f 100644--- a/test/browser/layer-tests/h3-hexagon-layer-specs.js+++ b/test/browser/layer-tests/h3-hexagon-layer-specs.js@@ -323,7 +323,8 @@ test('#H3Layer -> renderLayer', t => {outlineWidth: 0,outlineColor: [255, 0, 0, 255],background: false,- backgroundColor: [0, 0, 200, 255]+ backgroundColor: [0, 0, 200, 255],+ collisionEnabled: false}];diff --git a/test/browser/layer-tests/point-layer-specs.js b/test/browser/layer-tests/point-layer-specs.jsindex a87110c4c..4427fa60b 100644--- a/test/browser/layer-tests/point-layer-specs.js+++ b/test/browser/layer-tests/point-layer-specs.js@@ -699,6 +699,115 @@ test('#PointLayer -> renderLayer', t => {[Number.MIN_SAFE_INTEGER, 0, 0, 0],'Should calculate correct instancePixelOffset');+ t.notOk(+ (deckLayers[1].props.extensions || []).some(+ ext => ext.constructor.extensionName === 'CollisionFilterExtension'+ ),+ 'Should not add CollisionFilterExtension when collision is off'+ );+ t.notOk(+ deckLayers[1].props.collisionEnabled,+ 'Should leave collision filtering disabled by default'+ );+ }+ },+ {+ name: 'Point gps point.1 with text labels and collision filtering',+ layer: {+ config: {+ dataId,+ label: 'gps point',+ columns: {+ lat: 'lat',+ lng: 'lng',+ altitude: 'id'+ },+ textLabel: [+ {+ field: {+ name: 'types',+ type: 'string'+ },+ collisionEnabled: true+ }+ ]+ },+ type: 'point',+ id: 'test_layer_1'+ },+ datasets: {+ [dataId]: copyTableAndUpdate(preparedDataset, {filteredIndex})+ },+ assert: deckLayers => {+ const labelLayer = deckLayers.find(l => l.id === 'test_layer_1-label-types-collision');+ t.ok(labelLayer, 'Should create a text label layer');+ t.ok(+ labelLayer.props.extensions.some(+ ext => ext.constructor.extensionName === 'CollisionFilterExtension'+ ),+ 'Should add CollisionFilterExtension to the text label layer'+ );+ t.equal(labelLayer.props.collisionEnabled, true, 'Should enable collision filtering');+ t.equal(+ labelLayer.props.collisionGroup,+ 'test_layer_1-text-label-0',+ 'Should use a per-label collision group'+ );+ t.equal(+ labelLayer.constructor.layerName,+ 'CollisionTextLayer',+ 'Should use CollisionTextLayer so the hit area covers the anchor'+ );+ t.equal(labelLayer.props.background, true, 'Should enable a collision background');+ t.equal(+ labelLayer.props.collisionShowBackground,+ false,+ 'Should hide the collision-only background in the color pass'+ );+ }+ },+ {+ name: 'Point gps point.1 with text labels, collision filtering and visible background',+ layer: {+ config: {+ dataId,+ label: 'gps point',+ columns: {+ lat: 'lat',+ lng: 'lng',+ altitude: 'id'+ },+ textLabel: [+ {+ field: {+ name: 'types',+ type: 'string'+ },+ background: true,+ collisionEnabled: true+ }+ ]+ },+ type: 'point',+ id: 'test_layer_1'+ },+ datasets: {+ [dataId]: copyTableAndUpdate(preparedDataset, {filteredIndex})+ },+ assert: deckLayers => {+ const labelLayer = deckLayers.find(l => l.id === 'test_layer_1-label-types-collision');+ t.ok(labelLayer, 'Should create a text label layer');+ t.equal(+ labelLayer.constructor.layerName,+ 'CollisionTextLayer',+ 'Should use CollisionTextLayer so the hit area covers the anchor'+ );+ t.equal(labelLayer.props.background, true, 'Should keep the user background enabled');+ t.equal(+ labelLayer.props.collisionShowBackground,+ true,+ 'Should still draw the user background in the color pass'+ );}},{diff --git a/test/fixtures/state-saved-v1-4.js b/test/fixtures/state-saved-v1-4.jsindex 9615675b2..f69e69f76 100644--- a/test/fixtures/state-saved-v1-4.js+++ b/test/fixtures/state-saved-v1-4.js@@ -226,7 +226,8 @@ mergedLayer0.config = {outlineWidth: 0,outlineColor: [255, 0, 0, 255],background: false,- backgroundColor: [0, 0, 200, 255]+ backgroundColor: [0, 0, 200, 255],+ collisionEnabled: false}],colorUI: {diff --git a/test/fixtures/test-hex-id-data.js b/test/fixtures/test-hex-id-data.jsindex 822fb4db1..7b14715ae 100644--- a/test/fixtures/test-hex-id-data.js+++ b/test/fixtures/test-hex-id-data.js@@ -308,7 +308,8 @@ mergedH3Layer.config = {outlineWidth: 0,outlineColor: [255, 0, 0, 255],background: false,- backgroundColor: [0, 0, 200, 255]+ backgroundColor: [0, 0, 200, 255],+ collisionEnabled: false}],colorUI: {diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.jsindex 0e9cbe89f..93e5561cf 100644--- a/test/node/reducers/vis-state-test.js+++ b/test/node/reducers/vis-state-test.js@@ -1186,6 +1186,17 @@ test('#visStateReducer -> LAYER_TEXT_LABEL_CHANGE', t => {const expected8 = [{...DEFAULT_TEXT_LABEL, field: {name: 'blue', valueAccessor}}];t.deepEqual(nextState8.layers[0].config.textLabel, expected8, 'should remove text label blue');+ // enable GPU collision filtering for all labels+ const nextState9 = reducer(+ nextState8,+ VisStateActions.layerTextLabelChange(nextState8.layers[0], 'all', 'collisionEnabled', true)+ );+ t.equal(+ nextState9.layers[0].config.textLabel[0].collisionEnabled,+ true,+ 'should enable collision filtering on all text labels'+ );+t.end();});