Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: Globe view mode (#3486)
Igor Dykhta263c19190e99
diff --git a/docs/user-guides/README.md b/docs/user-guides/README.mdindex 340ffda41..df8e66665 100644--- a/docs/user-guides/README.md+++ b/docs/user-guides/README.md@@ -59,6 +59,7 @@ This guide will teach you how to perform data analysis in Kepler.gl by adding da#### [Map Settings](./m-map-settings.md)* [View maps in 3d](./m-map-settings.md#view-maps-in-3d)+* [Globe view](./m-map-settings.md#globe-view)* [Display legend](./m-map-settings.md#display-legend)* [Split maps](./m-map-settings.md#split-maps)diff --git a/docs/user-guides/effects.md b/docs/user-guides/effects.mdindex 3f0d53715..8a7673288 100644--- a/docs/user-guides/effects.md+++ b/docs/user-guides/effects.md@@ -6,6 +6,15 @@ You can add an effect from the **Effects** panel in the side bar. Multiple effec> **Limitation:** Only one Light & Shadow effect and one fog effect (either Distance Fog or Surface Fog) can be active at a time.+> **Combining effects with globe, swipe, and video export:** Effects work with the+> flat map, [globe view](./m-map-settings.md#globe-view),+> [split/swipe maps](./m-map-settings.md#split-maps), and+> [video export](./k-save-and-export.md#export-video) individually, but using+> several of these together (for example effects on a globe while recording a+> video in swipe mode) has **limited support** and may not render or export+> exactly as expected. If you run into problems, disable one of the features+> (start by turning off effects) and try again.+---## Table of contents@@ -35,6 +44,8 @@ You can add an effect from the **Effects** panel in the side bar. Multiple effecSimulates realistic sun lighting and shadow casting based on time of day and geographic location. Useful for visualizing how sunlight and shadows interact with 3D buildings or extruded layers throughout the day.+> **Not supported in [globe view](./m-map-settings.md#globe-view).** The Light & Shadow effect only applies to the flat (web-mercator) map.+| Parameter | Type | Range | Default | Description || --- | --- | --- | --- | --- || timestamp | number | 0 – MAX | — | The point in time used to compute sun position. Controlled via the date/time picker and timezone selector in the UI. |@@ -215,6 +226,8 @@ Replaces the image with a grid of hexagonal tiles, each filled with the averageFades distant objects into a fog color based on their depth from the camera. Enhances the perception of depth and distance, and can be used to de-emphasize background layers or create atmospheric haze. Requires a 3D view (pitch > 0).+> **Not supported in [globe view](./m-map-settings.md#globe-view).** Distance Fog only applies to the flat (web-mercator) map.+| Parameter | Type | Range | Default | Description || --- | --- | --- | --- | --- || density | number | 0 – 1 | 0.5 | Overall opacity of the fog. `0` is invisible; `1` is fully opaque at maximum distance. |@@ -228,6 +241,8 @@ Fades distant objects into a fog color based on their depth from the camera. EnhRenders a fog layer at a specific elevation above the terrain surface. Unlike distance fog, surface fog stays at a fixed altitude and is visible from all camera angles. Useful for simulating low-lying clouds, ground mist, or valley fog. Requires a 3D view (pitch > 0).+> **Not supported in [globe view](./m-map-settings.md#globe-view).** Surface Fog only applies to the flat (web-mercator) map.+| Parameter | Type | Range | Default | Description || --- | --- | --- | --- | --- || density | number | 0 – 1 | 0.6 | Overall opacity of the fog. `0` is fully transparent; `1` is fully opaque. |diff --git a/docs/user-guides/k-save-and-export.md b/docs/user-guides/k-save-and-export.mdindex 486e031f0..9b79cc6ae 100644--- a/docs/user-guides/k-save-and-export.md+++ b/docs/user-guides/k-save-and-export.md@@ -112,6 +112,16 @@ If your map has time-range filters in the *enlarged* (time-slider) view or filte- Position your camera in the preview *before* clicking Render. If you selected a camera preset like *Orbit (360°)*, the orbit starts from whatever position you set.- All active [effects](./effects.md) (post-processing filters, fog, lighting) are included in the recording.+> **Limited support for feature combinations:** [Globe view](./m-map-settings.md#globe-view),+> [swipe/split comparison](./m-map-settings.md#split-maps), video export, and+> post-processing [effects](./effects.md) each work on their own, but combining+> several at once (for example recording a video of a globe in swipe mode with+> effects active) has **limited support** and may not preview or export exactly+> as expected. If the preview looks wrong or the export fails, disable one of the+> features (turn off effects, exit swipe mode, or switch back to the flat map)+> and record again. Support for these combinations is expected to improve over+> time.+## <a href="#export-dropbox">Share Public URL (Dropbox) </a>diff --git a/docs/user-guides/m-map-settings.md b/docs/user-guides/m-map-settings.mdindex 09647d424..895ea5a38 100644--- a/docs/user-guides/m-map-settings.md+++ b/docs/user-guides/m-map-settings.md@@ -3,6 +3,7 @@<!-- TOC -->- [Split Maps](#split-maps)- [View Maps in 3D](#view-maps-in-3d)+ - [Globe View](#globe-view)- [Display Legend](#display-legend)<!-- /TOC -->@@ -39,6 +40,147 @@ View your map in 3D by clicking the 3D icon in the top right corner of your map+## Globe View++Switch from the flat (web-mercator) map to a 3D globe projection to view your+data wrapped onto a sphere. Toggle Globe view from the map view mode control in+the top right corner of the map.++- __drag__: rotate the globe+- __scroll / pinch__: zoom in and out++Globe view is well suited to global-scale datasets and flows, and to+presentation-style maps. It is built on deck.gl's globe projection and is still+evolving, so a number of layers and interactions behave differently than in the+flat map.++### Enabling globe view++The globe view option is enabled by default. Application developers can hide the+globe entry in the map view mode control (leaving only Top/3D) by setting+`enableGlobeView: false` in the application configuration:++```js+import KeplerGl from '@kepler.gl/components';+import {initApplicationConfig} from '@kepler.gl/utils';++initApplicationConfig({enableGlobeView: false});+```++### Camera and zoom constraints++To keep the basemap and interactions coherent, globe view applies a few+constraints that do not exist in the flat map:++- __Zoom range is limited__ (roughly zoom `2`–`12`). You can pull the globe+ further back than the flat map so the whole planet fits on screen, but+ __zooming in past zoom level `12` is currently disabled.__ This cap is in place+ because, past that level in the current deck.gl 9.x globe projection, the+ vector basemap tileset (Mapbox Streets vector tiles) stops loading and renders+ as empty rectangles, and the camera becomes unstable — it drifts while panning+ and zooming, and zoom-to-cursor becomes inaccurate. Capping the zoom keeps the+ basemap and interactions coherent until the underlying tile/controller issue is+ resolved upstream. Satellite/raster basemaps hold up better at closer zoom, so+ the cap may be relaxed as globe support matures.+- __The camera can't be centered on the poles.__ The center latitude is+ constrained to a band around the equator (about ±75°) so you can't stare+ straight down at a pole.+- __Reset bearing/pitch__ recenters the view toward the equator.++### Supported layers++The following layers render correctly in globe view:++- Point+- Arc+- Line+- Grid+- Hexbin (Hexagon)+- H3 (Hexagon ID)+- Cluster+- Icon+- GeoJSON / Polygon+- 3D / Point (elevation)+- Trip+- Vector Tile+- Raster Tile+- Hex Tile+- Heatmap (see caveat below)++> **Heatmap in globe view.** The heatmap layer is supported in globe view, but+> works differently than on the flat map. Because a heatmap cannot be draped+> directly onto the sphere, the density is computed offscreen for the current+> data/view bounds and projected back onto the globe. As a result the effective+> radius adapts with zoom, and very large `Radius` values or extreme zoom levels+> can look different than on the flat map.++### Unsupported layers++These layers are hidden or disabled in globe view because their geometry does+not project onto the sphere correctly:++- __Flow__ — flow arrows are flat quads in the equatorial plane and collapse to+ nothing when viewed edge-on on the globe.+- __S2__+- __3D Tiles__ (Tile3D)++If a layer is unsupported, kepler.gl will indicate that it is not available in+globe view and keep it hidden until you return to the flat map.++### Globe appearance settings++When globe view is enabled, the __Base map__ side panel shows a set of+globe-specific appearance controls (in addition to the usual base map style+picker). Each row has a visibility toggle, and some rows add a color swatch or a+slider:++- __Atmosphere__ — the glowing halo rendered around the globe. Turning it off+ also hides its sub-settings:+ - __Day/Night (terminator)__ — shades the night side of the globe. The slider+ controls the shading opacity.+ - __Sun azimuth__ — direction of the sun used for the day/night shading. The+ slider sets the angle (0–360°).+- __Base map__ — the reference basemap draped on the sphere. Turning it off also+ hides its sub-layers:+ - __Labels__ — place/road labels, with a color picker.+ - __Admin borders__ — administrative boundary lines, with a color picker.+ - __Water__ — water fill, with a color picker.+- __Surface__ — the color of the globe's land surface.+- __Background__ — the color of the empty space rendered around the globe. This+ color is also used as the background in image and video export.++### Known issues and limitations++- __Basemap breakdown at high zoom.__ At high globe zoom the mapbox vector+ basemap tileset can stop loading and render as empty rectangles. Zoom is capped+ to avoid this. Satellite/raster basemaps generally hold up better at closer+ zoom.+- __Panning/zoom drift at high zoom.__ Near the zoom cap the camera may drift+ while interacting. This is the primary reason for the zoom cap.+- __Zoom-to-cursor behaves differently for zoom-in vs zoom-out.__ Zooming in+ keeps the point under the cursor fixed. Zooming out does not anchor to the+ cursor (exact anchoring is unstable near the globe's edge and tends to drift+ toward the poles); instead it zooms out while gently recentering toward the+ cursor location.+- __Arcs and lines on the far side.__ Depending on depth handling, geometry on+ the back of the globe may be partially visible through the sphere.+- __Basemap differences.__ Mapbox and MapLibre basemaps can look different in+ globe mode; some basemap styles are better tuned for the sphere than others.++> **Combining globe with swipe, video export, and effects:** Globe view,+> [swipe/split comparison](#split-maps), [video export](./k-save-and-export.md#export-video),+> and post-processing [effects](./effects.md) each work on their own, but their+> combinations (for example globe + swipe + video recording with effects active+> at the same time) have **limited support** and may not render or export+> exactly as expected. When you hit an issue, try disabling one of the features+> (e.g. turn off effects, exit swipe mode, or switch back to the flat map)+> before recording. Support for these combinations is expected to improve as+> globe support matures.++These limitations stem from the underlying deck.gl globe projection and are+expected to improve as that support matures.++## Display LegendDisplay a legend for visible layers on the map.diff --git a/examples/demo-app/esbuild.config.mjs b/examples/demo-app/esbuild.config.mjsindex 9530c789f..be2c699e2 100644--- a/examples/demo-app/esbuild.config.mjs+++ b/examples/demo-app/esbuild.config.mjs@@ -88,6 +88,9 @@ const config = {platform: 'browser',format: 'iife',logLevel: 'info',+ logOverride: {+ 'unsupported-jsx-comment': 'silent'+ },inject: ['src/react19-shim.js'],loader: {'.js': 'jsx',diff --git a/jest.config.js b/jest.config.jsindex c5a321258..c86a75140 100644--- a/jest.config.js+++ b/jest.config.js@@ -22,7 +22,7 @@ const config = {// Some libraries (even if transitive) are transitioning to ESM and need additional transpilation. Relevant issues:// - tiny-sdf: https://github.com/visgl/deck.gl/issues/7735transformIgnorePatterns: [- '/node_modules\\/(?!(.*@mapbox\\/tiny-sdf\\.*|@loaders\\.gl|@deck\\.gl|@deck\\.gl-community|@luma\\.gl|@hubble\\.gl|@flowmap\\.gl|@math\\.gl|d3-.*|kdbush|preact|maplibregl-mapbox-request-transformer))',+ '/node_modules\\/(?!(.*@mapbox\\/tiny-sdf\\.*|@loaders\\.gl|@deck\\.gl|@deck\\.gl-community|@luma\\.gl|@hubble\\.gl|@flowmap\\.gl|@math\\.gl|d3-.*|kdbush|preact|maplibregl-mapbox-request-transformer|react-date-picker|react-time-picker|react-calendar|react-clock|react-fit|@wojtekmaj\\/date-utils|get-user-locale|make-event-props|update-input-width|detect-element-overflow|memoize|mimic-function))','\\.pnp\\.[^\\/]+$']};diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.tsindex 85fc70228..fd033a1aa 100644--- a/src/actions/src/action-types.ts+++ b/src/actions/src/action-types.ts@@ -131,6 +131,8 @@ export const ActionTypes = {TOGGLE_FULLSCREEN: `${ACTION_PREFIX}TOGGLE_FULLSCREEN`,TOGGLE_SPLIT_MAP: `${ACTION_PREFIX}TOGGLE_SPLIT_MAP`,TOGGLE_SPLIT_MAP_VIEWPORT: `${ACTION_PREFIX}TOGGLE_SPLIT_MAP_VIEWPORT`,+ SET_MAP_VIEW_MODE: `${ACTION_PREFIX}SET_MAP_VIEW_MODE`,+ GLOBE_CONFIG_CHANGE: `${ACTION_PREFIX}GLOBE_CONFIG_CHANGE`,SET_MAP_SPLIT_MODE: `${ACTION_PREFIX}SET_MAP_SPLIT_MODE`,SET_SWIPE_COMPARE_PERCENTAGE: `${ACTION_PREFIX}SET_SWIPE_COMPARE_PERCENTAGE`,diff --git a/src/actions/src/map-state-actions.ts b/src/actions/src/map-state-actions.tsindex daf932ce3..64b7bc76b 100644--- a/src/actions/src/map-state-actions.ts+++ b/src/actions/src/map-state-actions.ts@@ -4,7 +4,7 @@import {createAction} from '@reduxjs/toolkit';import {default as ActionTypes} from './action-types';import {Bounds, Merge, Viewport} from '@kepler.gl/types';-import {MapSplitMode} from '@kepler.gl/constants';+import {MapSplitMode, MapViewMode, GlobeConfig} from '@kepler.gl/constants';export type TogglePerspectiveUpdaterAction = void;/**@@ -115,6 +115,33 @@ export const toggleSplitMapViewport: (payload: {(syncInfo: ToggleSplitMapViewportUpdaterAction['payload']) => ({payload: syncInfo}));+export type SetMapViewModeUpdaterAction = {payload: {mapViewMode: MapViewMode}};+/**+ * Set map view mode (2D, 3D, or Globe)+ * @memberof mapStateActions+ * @param mapViewMode - One of MapViewMode values+ * @public+ */+export const setMapViewMode: (+ mapViewMode: MapViewMode+) => Merge<SetMapViewModeUpdaterAction, {type: typeof ActionTypes.SET_MAP_VIEW_MODE}> = createAction(+ ActionTypes.SET_MAP_VIEW_MODE,+ (mapViewMode: MapViewMode) => ({payload: {mapViewMode}})+);++export type GlobeConfigChangeUpdaterAction = {payload: Partial<GlobeConfig>};+/**+ * Update globe configuration+ * @memberof mapStateActions+ * @param config - Partial globe config to merge+ * @public+ */+export const globeConfigChange: (+ config: Partial<GlobeConfig>+) => Merge<GlobeConfigChangeUpdaterAction, {type: typeof ActionTypes.GLOBE_CONFIG_CHANGE}> =+ createAction(ActionTypes.GLOBE_CONFIG_CHANGE, (config: Partial<GlobeConfig>) => ({+ payload: config+ }));export type SetMapSplitModeUpdaterAction = {payload: {mapSplitMode: MapSplitMode;diff --git a/src/components/package.json b/src/components/package.jsonindex 91f5a3760..388698c36 100644--- a/src/components/package.json+++ b/src/components/package.json@@ -46,6 +46,7 @@"@kepler.gl/cloud-providers": "3.3.0-alpha.3","@kepler.gl/common-utils": "3.3.0-alpha.3","@kepler.gl/constants": "3.3.0-alpha.3",+ "@kepler.gl/deckgl-layers": "3.3.0-alpha.3","@kepler.gl/effects": "3.3.0-alpha.3","@kepler.gl/layers": "3.3.0-alpha.3","@kepler.gl/localization": "3.3.0-alpha.3",@@ -107,14 +108,14 @@"react": "^19.0.0","react-color": "^2.19.3","react-copy-to-clipboard": "^5.1.1",- "react-date-picker": "^11.0.0",+ "react-date-picker": "^12.0.2","react-dom": "^19.0.0","react-intl": "^7.0.0","react-json-pretty": "^2.2.0","react-map-gl": "^8.1.1","react-modal": "^3.16.3","react-redux": "^9.1.0",- "react-time-picker": "^7.0.0",+ "react-time-picker": "^8.0.0","react-tooltip": "^4.2.17","react-virtualized": "9.22.6","redux": "^5.0.0",diff --git a/src/components/src/effects/effect-time-configurator.tsx b/src/components/src/effects/effect-time-configurator.tsxindex 85af3993f..ac0b98ce0 100644--- a/src/components/src/effects/effect-time-configurator.tsx+++ b/src/components/src/effects/effect-time-configurator.tsx@@ -150,8 +150,15 @@ const TextBlock = styled.div<TextBlockProps>`* @returns Timestamp or null if case of bad inputs.*/const getTimestamp = (dateStr: string, timeStr: string, timezone: string): number | null => {+ // Bail out early on malformed inputs (e.g. partially edited date/time fields+ // that produce values like "NaN:NaN"). Otherwise moment falls back to+ // `new Date()` and logs a deprecation warning while still returning invalid.+ if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr) || !/^\d{2}:\d{2}$/.test(timeStr)) {+ return null;+ }+let timestamp: number | null = null;- const curr = moment.tz(`${dateStr}T${timeStr}:00`, timezone);+ const curr = moment.tz(`${dateStr}T${timeStr}:00`, 'YYYY-MM-DDTHH:mm:ss', true, timezone);if (curr.isValid()) {timestamp = curr.utc().valueOf();}@@ -192,7 +199,10 @@ export default function EffectTimeConfiguratorFactory(const [datePickerDate, fullDate, formattedTime, formattedDate, dayTimeProgress] =useMemo(() => {- const currentMoment = moment.tz(timestamp, timezone);+ // Guard against an invalid stored timestamp so we never build an+ // "Invalid Date" for the date picker (react-date-picker throws on it).+ const safeTimestamp = Number.isFinite(timestamp) ? timestamp : Date.now();+ const currentMoment = moment.tz(safeTimestamp, timezone);// Slider value from 0 to 1const dayProgress = getDayRatio(currentMoment);@@ -327,7 +337,8 @@ export default function EffectTimeConfiguratorFactory(<DatePickervalue={datePickerDate}onChange={setDate}- {...({minDetail: 'month', formatShortWeekday} as any)}+ maxDetail="month"+ {...({calendarProps: {minDetail: 'month', formatShortWeekday}} as any)}/></StyledDatePicker><StyledExtraIcon>diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsxindex 0721de129..27cba1998 100644--- a/src/components/src/kepler-gl.tsx+++ b/src/components/src/kepler-gl.tsx@@ -212,6 +212,7 @@ export const sidePanelSelector = (props: KeplerGLProps, availableProviders, filtversion: props.version ? props.version : DEFAULT_KEPLER_GL_PROPS.version,appWebsite: props.appWebsite,mapStyle: props.mapStyle,+ mapState: props.mapState,onSaveMap: props.onSaveMap,uiState: props.uiState,mapStyleActions: props.mapStyleActions,diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex 22de5399e..c0c3d850a 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -78,9 +78,21 @@ import {NO_MAP_ID,EMPTY_MAPBOX_STYLE,MAPBOX_MAX_PITCH,- MAP_LIB_OPTIONS+ MAP_LIB_OPTIONS,+ GLOBE_MIN_ZOOM,+ GLOBE_MAX_ZOOM} from '@kepler.gl/constants';+import {+ getGlobeBaseLayers,+ getGlobeTopLayers,+ getGlobeClearColor,+ getGlobeBasemapAttributions,+ resolveGlobeBasemapProvider,+ KeplerGlobeView+} from '@kepler.gl/deckgl-layers';+import type {GlobeAttribution} from '@kepler.gl/deckgl-layers';+import {DROPPABLE_MAP_CONTAINER_TYPE} from './common/dnd-layer-items';// Contextsimport {MapViewStateContext} from './map-view-state-context';@@ -241,17 +253,32 @@ type AttributionProps = {showOsmBasemapAttribution: boolean;datasetAttributions: DatasetAttribution[];baseMapLibraryConfig: BaseMapLibraryConfig;+ globeAttributions?: GlobeAttribution[];};export const Attribution: React.FC<AttributionProps> = ({showBaseMapLibLogo = true,showOsmBasemapAttribution = false,datasetAttributions,- baseMapLibraryConfig+ baseMapLibraryConfig,+ globeAttributions = []}: AttributionProps) => {const isPalm = hasMobileWidth(breakPointValues);const memoizedComponents = useMemo(() => {+ const globeAttributionNodes = globeAttributions.length ? (+ <>+ {globeAttributions.map(attr => (+ <React.Fragment key={attr.label}>+ <span className="pipe-separator">|</span>+ <a href={attr.href} target="_blank" rel="noopener noreferrer">+ {attr.label}+ </a>+ </React.Fragment>+ ))}+ </>+ ) : null;+if (!showBaseMapLibLogo) {return (<StyledAttribution@@ -262,9 +289,17 @@ export const Attribution: React.FC<AttributionProps> = ({<DatasetAttributions datasetAttributions={datasetAttributions} isPalm={isPalm} /><div className="attrition-link">{datasetAttributions?.length ? <span className="pipe-separator">|</span> : null}+ {globeAttributions.length && isPalm ? (+ <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} />+ ) : null}<a href="https://kepler.gl/policy/" target="_blank" rel="noopener noreferrer">© kepler.gl</a>+ {globeAttributionNodes}+ {globeAttributions.length ? <span className="pipe-separator">|</span> : null}+ {globeAttributions.length && !isPalm ? (+ <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} />+ ) : null}</div></EndHorizontalFlexbox></StyledAttribution>@@ -296,6 +331,7 @@ export const Attribution: React.FC<AttributionProps> = ({</a></>) : null}+ {globeAttributionNodes}<span className="pipe-separator">|</span>{!isPalm ? <MapLibLogo baseMapLibraryConfig={baseMapLibraryConfig} /> : null}</div>@@ -307,7 +343,8 @@ export const Attribution: React.FC<AttributionProps> = ({showOsmBasemapAttribution,datasetAttributions,isPalm,- baseMapLibraryConfig+ baseMapLibraryConfig,+ globeAttributions]);return memoizedComponents;@@ -587,12 +624,28 @@ export default function MapContainerFactory(// used by <StyledMap> inline style propmapStyleTypeSelector = props => props.mapStyle.styleType;mapStyleBackgroundColorSelector = props => props.mapStyle.backgroundColor;+ globeModeSelector = props => Boolean(props.mapState?.globe?.enabled);+ globeBackgroundColorSelector = props => props.mapState?.globe?.config?.backgroundColor;styleSelector = createSelector(this.mapStyleTypeSelector,this.mapStyleBackgroundColorSelector,- (styleType, backgroundColor) => ({+ this.globeModeSelector,+ this.globeBackgroundColorSelector,+ (styleType, backgroundColor, isGlobeMode, globeBackgroundColor) => ({...MAP_STYLE.container,- ...(styleType === NO_MAP_ID ? {backgroundColor: rgbToHex(backgroundColor)} : {})+ ...(styleType === NO_MAP_ID ? {backgroundColor: rgbToHex(backgroundColor)} : {}),+ // In globe mode the deck.gl canvas is transparent (the globe View uses+ // `clearColor: false` to avoid corrupting the picking buffer), so the+ // background around the globe is painted here on the container instead.+ ...(isGlobeMode+ ? {+ // Fall back to the default globe background when none is configured.+ backgroundColor: rgbToHex(+ (globeBackgroundColor as [number, number, number]) ||+ (getGlobeClearColor().slice(0, 3) as [number, number, number])+ )+ }+ : {})}));@@ -781,6 +834,8 @@ export default function MapContainerFactory(_annotationViewportCache: {key: string; viewport: any} | null = null;+ _wasInteracting = false;+_getAnnotationViewport(mapState: any, internalViewState: any) {const longitude = internalViewState?.longitude ?? mapState.longitude;const latitude = internalViewState?.latitude ?? mapState.latitude;@@ -1075,15 +1130,59 @@ export default function MapContainerFactory(? computeDeckEffects({visState, mapState, isExport: this.props.isExport}): [];- const views = deckGlProps?.views ? deckGlProps?.views() : new MapView({farZMultiplier: 1.2});+ const isGlobeMode = mapState.globe?.enabled;++ // Follow the selected basemap style's library so the globe uses the same+ // provider as the flat 2D map (CARTO tiles for MapLibre styles, Mapbox+ // tiles for Mapbox styles).+ const globeBasemapProvider = resolveGlobeBasemapProvider(+ getBaseMapLibrary(mapStyle?.mapStyles?.[mapStyle?.styleType]),+ mapboxApiAccessToken || ''+ );++ // In globe mode, prepend globe base layers and append top layers+ const globeBaseLayers =+ isGlobeMode && mapState.globe+ ? getGlobeBaseLayers({+ mapboxApiAccessToken: mapboxApiAccessToken || '',+ globe: mapState.globe,+ mapStyleType: mapStyle?.styleType,+ basemapProvider: globeBasemapProvider+ })+ : [];+ const globeTopLayers =+ isGlobeMode && mapState.globe ? getGlobeTopLayers({globe: mapState.globe}) : [];+ const finalDeckGlLayers = isGlobeMode+ ? [...globeBaseLayers, ...deckGlLayers, ...globeTopLayers]+ : deckGlLayers;++ const views = deckGlProps?.views+ ? deckGlProps?.views()+ : isGlobeMode+ ? new KeplerGlobeView({+ resolution: 5,+ // The visible background around the globe is painted by the map+ // container's CSS background (see styleSelector), NOT by a per-view+ // color clear. deck.gl applies a View's `clearColor` in *every* pass,+ // including the picking pass, and it forces the cleared alpha to 255+ // (`clearColor[3] || 255`). In the picking buffer the alpha byte encodes+ // the layer index, so a 255 clear makes deck.gl decode every pixel as a+ // non-existent layer ("Picked non-existent layer. Is picking buffer+ // corrupt?") on hover. `clearColor: false` skips the per-view color+ // clear so the picking buffer keeps its 0 alpha; the canvas stays+ // transparent and the CSS background shows through.+ clear: true,+ clearColor: false+ })+ : new MapView({farZMultiplier: 1.2});let allDeckGlProps = {...deckGlProps,pickingRadius: DEFAULT_PICKING_RADIUS,views,- layers: deckGlLayers,+ layers: finalDeckGlLayers,effects,- parameters: getLayerBlendingParameters(visState.layerBlending)+ parameters: isGlobeMode ? {cull: true} : getLayerBlendingParameters(visState.layerBlending)};if (typeof deckRenderCallbacks?.onDeckRender === 'function') {@@ -1120,11 +1219,21 @@ export default function MapContainerFactory(? {doubleClickZoom: !isEditorDrawingMode,dragRotate: this.props.mapState.dragRotate,- maxPitch: this.props.mapState.maxPitch ?? getApplicationConfig().maxPitch+ maxPitch: this.props.mapState.maxPitch ?? getApplicationConfig().maxPitch,+ // In globe mode allow zooming out further than deck.gl's default+ // of 0 so the whole globe can be pulled back on screen. Set on the+ // controller so it stays authoritative regardless of the viewState+ // round-trip through Redux/local context. Cap the max zoom too so+ // the basemap tiles don't break down at high globe zoom.+ ...(isGlobeMode ? {minZoom: GLOBE_MIN_ZOOM, maxZoom: GLOBE_MAX_ZOOM} : {})}: false}- initialViewState={internalViewState}+ viewState={+ isGlobeMode+ ? {...internalViewState, minZoom: GLOBE_MIN_ZOOM, maxZoom: GLOBE_MAX_ZOOM}+ : internalViewState+ }onBeforeRender={this._onBeforeRender}onViewStateChange={isInteractive ? this._onViewportChange : undefined}{...extraDeckParams}@@ -1225,14 +1334,54 @@ export default function MapContainerFactory(}, DEBOUNCE_VIEWPORT_PROPAGATE);_onViewportChange = viewport => {- const {viewState} = viewport;+ const {viewState, interactionState} = viewport;if (this.props.isExport) {// Image export map shouldn't be interactive (otherwise this callback can// lead to inadvertent changes to the state of the main map)return;}const {setInternalViewState} = this.context;- setInternalViewState(viewState, this.props.index);++ // Flat map (2D/3D): keep the original, always-synchronous behavior. The+ // interaction-aware timing below exists purely to fix globe-specific+ // controlled-viewState, so it must not change the main 2D logic.+ if (!this.props.mapState?.globe?.enabled) {+ setInternalViewState(viewState, this.props.index);+ this._wasInteracting = false;+ this._onViewportChangePropagateDebounced();+ return;+ }++ const isUserInteraction =+ interactionState &&+ (interactionState.isZooming ||+ interactionState.isPanning ||+ interactionState.isRotating ||+ interactionState.isDragging ||+ interactionState.inTransition);+ // The emit that ends a gesture (panend/rotateEnd, or a fling transition+ // ending) arrives with all interaction flags false. If we defer it, the+ // controlled `viewState` fed back to deck lags a frame behind the+ // controller's committed state and deck re-seeds from the stale value,+ // making the globe visibly "jump back" to where the drag was released -+ // most noticeable on a throw/fling release. Treat the first all-false emit+ // right after an active gesture as part of that gesture and apply it+ // synchronously too.+ const isInteractionSettle = !isUserInteraction && this._wasInteracting;+ this._wasInteracting = Boolean(isUserInteraction);+ if (isUserInteraction || isInteractionSettle) {+ // For interactive gestures (pan/zoom/rotate) and their end-of-gesture+ // settle, update synchronously so the controlled `viewState` stays in+ // lockstep with the controller and there's no stale re-seed.+ setInternalViewState(viewState, this.props.index);+ } else {+ // deck.gl can fire onViewStateChange synchronously during its own render+ // (e.g. when switching view types like MapView -> GlobeView). Updating React+ // state during render throws a warning, so defer non-interactive updates.+ setTimeout(() => {+ setInternalViewState(viewState, this.props.index);+ }, 0);+ }this._onViewportChangePropagateDebounced();};@@ -1341,7 +1490,11 @@ export default function MapContainerFactory(<ResolvedMapComponentkey={`bottom-${baseMapLibraryName}`}{...mapProps}- mapStyle={mapStyle.bottomMapStyle ?? EMPTY_MAPBOX_STYLE}+ mapStyle={+ mapState.globe?.enabled+ ? EMPTY_MAPBOX_STYLE+ : mapStyle.bottomMapStyle ?? EMPTY_MAPBOX_STYLE+ }{...bottomMapContainerProps}ref={this._setMapRef}/>@@ -1379,6 +1532,8 @@ export default function MapContainerFactory(editor={editor}locale={locale}onTogglePerspective={mapStateActions.togglePerspective}+ onSetMapViewMode={mapStateActions.setMapViewMode}+ mapViewMode={mapState.mapViewMode}onToggleSplitMap={mapStateActions.toggleSplitMap}onMapToggleLayer={this._handleMapToggleLayer}onToggleMapControl={this._toggleMapControl}@@ -1425,7 +1580,7 @@ export default function MapContainerFactory(setSelectedAnnotation={visStateActions.setSelectedAnnotation}/>{this.props.children}- {mapStyle.topMapStyle ? (+ {mapStyle.topMapStyle && !mapState.globe?.enabled ? (<ResolvedMapComponentkey={`top-${baseMapLibraryName}`}viewState={internalViewState}@@ -1470,6 +1625,15 @@ export default function MapContainerFactory(showOsmBasemapAttribution={this.state.showOsmAttribution}datasetAttributions={datasetAttributions}baseMapLibraryConfig={baseMapLibraryConfig}+ globeAttributions={getGlobeBasemapAttributions({+ globe: mapState.globe,+ mapboxApiAccessToken,+ mapStyleType: mapStyle?.styleType,+ basemapProvider: resolveGlobeBasemapProvider(+ baseMapLibraryName,+ mapboxApiAccessToken+ )+ })}/>) : null}{this.props.primary ? (diff --git a/src/components/src/map-view-state-context.tsx b/src/components/src/map-view-state-context.tsxindex fbd96e56d..4c9e9d713 100644--- a/src/components/src/map-view-state-context.tsx+++ b/src/components/src/map-view-state-context.tsx@@ -11,6 +11,8 @@ type MapViewState = {bearing?: number;pitch?: number;maxPitch?: number;+ minZoom?: number;+ maxZoom?: number;};import {pickViewportPropsFromMapState} from '@kepler.gl/reducers';diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsxindex 2e9d4eff9..a9547c3a7 100644--- a/src/components/src/map/map-control.tsx+++ b/src/components/src/map/map-control.tsx@@ -17,6 +17,7 @@ import {Editor, LayerVisConfig, LayerOrder, MapControls, MapState} from '@keplerimport {Datasets} from '@kepler.gl/table';import {MapStateActions, UIStateActions} from '@kepler.gl/actions';import {getApplicationConfig} from '@kepler.gl/utils';+import {MapViewMode} from '@kepler.gl/constants';import AnnotationControlFactory from './annotations/annotation-control';@@ -53,6 +54,8 @@ export type MapControlProps = {mapIndex: number;mapControls: MapControls;onTogglePerspective: () => void;+ onSetMapViewMode?: (mode: MapViewMode) => void;+ mapViewMode?: MapViewMode;onToggleSplitMap: typeof MapStateActions.toggleSplitMap;onSetMapSplitMode?: typeof MapStateActions.setMapSplitMode;onToggleSplitMapViewport: ({diff --git a/src/components/src/map/map-navigation-control.tsx b/src/components/src/map/map-navigation-control.tsxindex 5bb7e145d..8f8adfa72 100644--- a/src/components/src/map/map-navigation-control.tsx+++ b/src/components/src/map/map-navigation-control.tsx@@ -75,6 +75,19 @@ export default function MapNavigationControlFactory() {const handleCompassClick = useCallback(() => {const currentBearing = viewState?.bearing ?? mapState.bearing;const currentPitch = viewState?.pitch ?? mapState.pitch;+ const isGlobe = Boolean(mapState.globe?.enabled);++ // In globe mode bearing/pitch stay at 0, so a compass reset instead recenters+ // the camera target back onto the equator (latitude 0), keeping longitude/zoom.+ if (isGlobe) {+ const currentLatitude = viewState?.latitude ?? mapState.latitude;+ if (currentBearing === 0 && currentPitch === 0 && currentLatitude === 0) {+ return;+ }+ mapStateActions.updateMap({bearing: 0, pitch: 0, latitude: 0}, mapIndex);+ return;+ }+if (currentBearing === 0 && currentPitch === 0) {return;}diff --git a/src/components/src/map/toggle-3d-button.tsx b/src/components/src/map/toggle-3d-button.tsxindex 81e65647c..99abedabb 100644--- a/src/components/src/map/toggle-3d-button.tsx+++ b/src/components/src/map/toggle-3d-button.tsx@@ -3,61 +3,139 @@import React, {ComponentType, useCallback, useMemo} from 'react';import classnames from 'classnames';-import {Cube3d} from '../common/icons';+import {Cube3d, Globe} from '../common/icons';import {MapControlButton} from '../common/styled-components';import MapControlTooltipFactory from './map-control-tooltip';+import MapControlToolbarFactory from './map-control-toolbar';+import ToolbarItem from '../common/toolbar-item';import {MapControls} from '@kepler.gl/types';+import {MapViewMode} from '@kepler.gl/constants';+import {getApplicationConfig} from '@kepler.gl/utils';-Toggle3dButtonFactory.deps = [MapControlTooltipFactory];+Toggle3dButtonFactory.deps = [MapControlTooltipFactory, MapControlToolbarFactory];interface Toggle3dButtonIcons {cube: ComponentType<any>;+ globe: ComponentType<any>;}export type Toggle3dButtonProps = {dragRotate: boolean;+ mapViewMode?: MapViewMode;onTogglePerspective: () => void;+ onSetMapViewMode?: (mode: MapViewMode) => void;+ onToggleMapControl: (control: string) => void;actionIcons: Toggle3dButtonIcons;mapControls: MapControls;};-function Toggle3dButtonFactory(MapControlTooltip) {+const VIEW_MODE_ITEMS = [+ {+ id: MapViewMode.MODE_2D,+ label: 'tooltip.top'+ },+ {+ id: MapViewMode.MODE_3D,+ label: 'tooltip.3DMap'+ },+ {+ id: MapViewMode.MODE_GLOBE,+ label: 'tooltip.globeMap'+ }+];++function Toggle3dButtonFactory(+ MapControlTooltip: ReturnType<typeof MapControlTooltipFactory>,+ MapControlToolbar: ReturnType<typeof MapControlToolbarFactory>+) {const defaultActionIcons = {- cube: props => <Cube3d {...props} height="18px" />+ cube: props => <Cube3d {...props} height="18px" />,+ globe: props => <Globe {...props} height="18px" />};- /** @type {import('./toggle-3d-button').Toggle3dButtonComponent} */+const Toggle3dButton: React.FC<Toggle3dButtonProps> = ({dragRotate,+ mapViewMode,onTogglePerspective,+ onSetMapViewMode,+ onToggleMapControl,actionIcons = defaultActionIcons,mapControls}) => {- const onClick = useCallback(- event => {- event.preventDefault();- onTogglePerspective();+ const currentMode = mapViewMode || (dragRotate ? MapViewMode.MODE_3D : MapViewMode.MODE_2D);++ const onClickButton = useCallback(+ e => {+ e.preventDefault();+ onToggleMapControl('toggle3d');+ },+ [onToggleMapControl]+ );++ const onSelectMode = useCallback(+ (mode: MapViewMode) => {+ if (onSetMapViewMode) {+ onSetMapViewMode(mode);+ } else if (mode === MapViewMode.MODE_3D) {+ if (!dragRotate) onTogglePerspective();+ } else if (mode === MapViewMode.MODE_2D) {+ if (dragRotate) onTogglePerspective();+ }+ onToggleMapControl('toggle3d');},- [onTogglePerspective]+ [onSetMapViewMode, onTogglePerspective, dragRotate, onToggleMapControl]);const isVisible = useMemo(() => {return (mapControls?.toggle3d || {}).show;}, [mapControls]);- return isVisible ? (- <MapControlTooltip- id="action-3d"- message={dragRotate ? 'tooltip.disable3DMap' : 'tooltip.3DMap'}- >- <MapControlButton- onClick={onClick}- active={dragRotate}- className={classnames('map-control-button', 'toggle-3d', {map3d: dragRotate})}+ // Optionally hide the globe view mode option via application config.+ const viewModeItems = useMemo(+ () =>+ getApplicationConfig().enableGlobeView+ ? VIEW_MODE_ITEMS+ : VIEW_MODE_ITEMS.filter(item => item.id !== MapViewMode.MODE_GLOBE),+ []+ );++ if (!isVisible) return null;++ const isActive = mapControls?.toggle3d?.active;+ const isGlobe = currentMode === MapViewMode.MODE_GLOBE;+ const is3d = currentMode === MapViewMode.MODE_3D;++ const ActiveIcon = isGlobe ? actionIcons.globe : actionIcons.cube;++ return (+ <div className="view-mode-controls" style={{position: 'relative'}}>+ {isActive ? (+ <MapControlToolbar $show={isActive}>+ {viewModeItems.map(item => (+ <ToolbarItem+ key={item.id}+ onClick={() => onSelectMode(item.id)}+ label={item.label}+ icon={item.id === MapViewMode.MODE_GLOBE ? actionIcons.globe : actionIcons.cube}+ active={currentMode === item.id}+ />+ ))}+ </MapControlToolbar>+ ) : null}+ <MapControlTooltip+ id="action-3d"+ message="tooltip.viewMode">- <actionIcons.cube height="22px" />- </MapControlButton>- </MapControlTooltip>- ) : null;+ <MapControlButton+ onClick={onClickButton}+ active={is3d || isGlobe}+ className={classnames('map-control-button', 'toggle-3d', {map3d: is3d, mapGlobe: isGlobe})}+ >+ <ActiveIcon height="22px" />+ </MapControlButton>+ </MapControlTooltip>+ </div>+ );};Toggle3dButton.displayName = 'Toggle3dButton';diff --git a/src/components/src/modals/export-video-modal.tsx b/src/components/src/modals/export-video-modal.tsxindex eda6dc8b9..f0eab0e2c 100644--- a/src/components/src/modals/export-video-modal.tsx+++ b/src/components/src/modals/export-video-modal.tsx@@ -4,7 +4,12 @@import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';import styled, {ThemeProvider, useTheme} from 'styled-components';-import {DEFAULT_MAPBOX_API_URL, NO_MAP_ID, EMPTY_MAPBOX_STYLE, MapSplitMode} from '@kepler.gl/constants';+import {+ DEFAULT_MAPBOX_API_URL,+ NO_MAP_ID,+ EMPTY_MAPBOX_STYLE,+ MapSplitMode+} from '@kepler.gl/constants';import {FormattedMessage} from '@kepler.gl/localization';import {Viewport, ExportVideo, Effect} from '@kepler.gl/types';import {@@ -41,6 +46,7 @@ type HubbleModule = {let _hubbleModule: HubbleModule | null = null;let _hubblePromise: Promise<HubbleModule> | null = null;let _swipeContainer: SwipeContainerType | null = null;+let _globeContainer: SwipeContainerType | null = null;function loadHubble(): Promise<HubbleModule> {if (_hubbleModule) return Promise.resolve(_hubbleModule);@@ -54,6 +60,12 @@ function loadHubble(): Promise<HubbleModule> {} catch (_err) {// swipe export unavailable; regular export still works}+ try {+ const globeMod = await import('./globe-export-video-container');+ _globeContainer = globeMod.GlobeExportVideoPanelContainer;+ } catch (_err) {+ // globe export container unavailable; falls back to hubble's container+ }return _hubbleModule;},err => {@@ -324,7 +336,11 @@ const ExportVideoModalFactory = () => {const onUpdateVideoConfiguration = useCallback((values: VideoConfiguration) => {setVideoConfiguration(prev => ({...prev, ...values}));- if (values.swipeStartPct !== undefined || values.swipeEndPct !== undefined || values.swipeEasing !== undefined) {+ if (+ values.swipeStartPct !== undefined ||+ values.swipeEndPct !== undefined ||+ values.swipeEasing !== undefined+ ) {uiStateActions.setExportVideoSetting(values as any);}},@@ -378,6 +394,11 @@ const ExportVideoModalFactory = () => {const isSwipeMode = mapState.mapSplitMode === MapSplitMode.SWIPE_COMPARE && mapState.isSplit;+ // In globe mode the deck.gl GlobeView renders the planet (and basemap tiles)+ // itself; the flat maplibre base map must be disabled so it doesn't render a+ // 2D Mercator map behind/around the globe (mirrors studio's disableStaticMap).+ const isGlobeEnabled = Boolean(mapState?.globe?.enabled);+const onFilterFrameUpdate = useCallback((filterIdx: number, name: string, value: any) => {visStateActions.setFilterAnimationTime(filterIdx, name, value);@@ -423,6 +444,7 @@ const ExportVideoModalFactory = () => {const {ExportVideoPanelContainer, KeplerUIContext} = hubble;const SwipeContainer = _swipeContainer;+ const GlobeContainer = _globeContainer;return (<KeplerUIContext.Provider value={KEPLER_UI}>@@ -439,7 +461,7 @@ const ExportVideoModalFactory = () => {onTripFrameUpdate={onTripFrameUpdate}deckProps={deckPropsWithEffects}mapProps={staticMapProps}- disableBaseMap={false}+ disableBaseMap={isGlobeEnabled}mapboxLayerBeforeId={topLayer?.id}defaultFileName={DEFAULT_FILENAME}animatableFilters={animatableFilters}@@ -448,6 +470,27 @@ const ExportVideoModalFactory = () => {swipeEndPct={exportVideo.swipeEndPct}swipeEasing={exportVideo.swipeEasing}/>+ ) : isGlobeEnabled && GlobeContainer ? (+ // Globe (non-swipe) export uses a dedicated container that drives its+ // own capture loop. hubble's built-in container only advances frames+ // from the mapbox base map's render event, which doesn't fire in+ // globe mode (base map disabled), so its export would hang.+ <GlobeContainer+ ref={hubbleContainerRef}+ initialState={videoConfiguration}+ mapData={keplerState}+ onSettingsChange={onUpdateVideoConfiguration}+ header={false}+ handleClose={onClose}+ exportVideoWidth={exportVideoWidth}+ onFilterFrameUpdate={onFilterFrameUpdate}+ onTripFrameUpdate={onTripFrameUpdate}+ deckProps={deckPropsWithEffects}+ mapProps={staticMapProps}+ defaultFileName={DEFAULT_FILENAME}+ animatableFilters={animatableFilters}+ getTimeRangeFilterKeyframes={getTimeRangeFilterKeyframes}+ />) : (<ExportVideoPanelContainerref={hubbleContainerRef}@@ -461,7 +504,7 @@ const ExportVideoModalFactory = () => {onTripFrameUpdate={onTripFrameUpdate}deckProps={deckPropsWithEffects}mapProps={staticMapProps}- disableBaseMap={false}+ disableBaseMap={isGlobeEnabled}mapboxLayerBeforeId={topLayer?.id}defaultFileName={DEFAULT_FILENAME}animatableFilters={animatableFilters}diff --git a/src/components/src/modals/globe-export-video-container.tsx b/src/components/src/modals/globe-export-video-container.tsxnew file mode 100644index 000000000..508bd41e4--- /dev/null+++ b/src/components/src/modals/globe-export-video-container.tsx@@ -0,0 +1,586 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {Component, createRef} from 'react';+import {easeInOut} from 'popmotion';+import download from 'downloadjs';+import styled from 'styled-components';+import {Button} from '../common';+import {+ DeckAdapter,+ KeplerAnimation,+ WebMEncoder,+ JPEGSequenceEncoder,+ PNGSequenceEncoder,+ GifEncoder,+ FormatConfigs,+ Timecode+} from '@hubble.gl/core';+import type {DeckProps, MapViewState} from '@deck.gl/core';+import {FILTER_VIEW_TYPES} from '@kepler.gl/constants';++import {parseSetCameraType, scaleToVideoExport, getResolutionSetting} from './hubble-utils';+import {GlobeExportVideoPreview} from './globe-export-video-preview';+import SwipeExportSettings from './swipe-export-settings';+import {getGlobeClearColor} from '@kepler.gl/deckgl-layers';++// No-op for the swipe-specific settings callbacks that this single-map globe+// exporter doesn't use (the swipe controls are hidden via `hideSwipe`).+const noop = () => undefined;++const ENCODERS = {+ gif: GifEncoder,+ webm: WebMEncoder,+ jpeg: JPEGSequenceEncoder,+ png: PNGSequenceEncoder+};++export type GlobeExportVideoSettings = {+ mediaType?: string;+ cameraPreset?: string;+ fileName?: string;+ resolution?: string;+ durationMs?: number;+};++type GlobeExportVideoPanelContainerProps = {+ initialState?: Partial<GlobeExportVideoPanelContainerState>;+ glContext?: WebGL2RenderingContext;+ exportVideoWidth: number;+ handleClose: () => void;+ mapData: any;+ header: boolean;+ deckProps?: DeckProps;+ mapProps: Record<string, any>;+ defaultFileName: string;+ animatableFilters: any;+ onTripFrameUpdate: (value: any) => void;+ onFilterFrameUpdate: (filterIdx: number, name: string, value: any) => void;+ getTimeRangeFilterKeyframes: (args: any) => any;+ onSettingsChange: (settings: GlobeExportVideoSettings) => void;+};++type GlobeExportVideoPanelContainerState = {+ adapter?: DeckAdapter;+ durationMs: number;+ mediaType: string;+ cameraPreset: string;+ fileName: string;+ resolution: string;+ viewState?: MapViewState;+ rendering: boolean;+ previewing: boolean;+ saving: boolean;+ currentTimeMs: number;+ memo?: {viewState: MapViewState};+};++const PanelBody = styled.div<{$exportVideoWidth: number}>`+ display: grid;+ grid-template-columns: ${props => props.$exportVideoWidth}px 280px;+ grid-template-rows: auto;+ grid-column-gap: 24px;+`;++const TimelineControls = styled.div`+ position: relative;+ display: flex;+ justify-content: center;+ padding-top: 16px;+`;++const timelinePlayButtonStyle = {+ cursor: 'pointer',+ height: '32px',+ width: '32px',+ fill: '#FFF'+};++const ButtonGroup = styled.div`+ display: flex;+`;++const StatusText = styled.div`+ font-size: 11px;+ color: ${props => props.theme.subtextColorLT || '#6A7485'};+ text-align: center;+ margin-top: 4px;+`;++const PlayIcon: React.FC<{style?: React.CSSProperties; onClick?: () => void}> = ({+ style,+ onClick+}) => (+ <svg className="data-ex-icons-play" viewBox="0 0 24 24" style={style} onClick={onClick}>+ <path fill="none" d="M0 0h24v24H0z" />+ <path d="M19.376 12.416L8.777 19.482A.5.5 0 0 1 8 19.066V4.934a.5.5 0 0 1 .777-.416l10.599 7.066a.5.5 0 0 1 0 .832z" />+ </svg>+);++const StopIcon: React.FC<{style?: React.CSSProperties; onClick?: () => void}> = ({+ style,+ onClick+}) => (+ <svg className="data-ex-icons-stop" viewBox="0 0 24 24" style={style} onClick={onClick}>+ <path fill="none" d="M0 0h24v24H0z" />+ <path d="M6 5h12a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z" />+ </svg>+);++/**+ * Video export container for globe mode.+ *+ * hubble's built-in ExportVideoPanelContainer only drives its frame-capture+ * loop from the mapbox base map's 'render' event; in globe mode the base map is+ * disabled so that loop never fires and the export hangs. This container mirrors+ * the swipe-export approach: it owns a requestAnimationFrame capture loop and+ * reads the globe deck canvas directly, so recording works without a base map.+ */+export class GlobeExportVideoPanelContainer extends Component<+ GlobeExportVideoPanelContainerProps,+ GlobeExportVideoPanelContainerState+> {+ previewRef = createRef<GlobeExportVideoPreview>();+ animationFrameId: number | null = null;+ activeEncoder: any | null = null;+ // Reused across all captured frames to avoid allocating a full-resolution+ // canvas per frame (GC pressure/jank during a multi-second export).+ compositeCanvas: HTMLCanvasElement | null = null;++ constructor(props: GlobeExportVideoPanelContainerProps) {+ super(props);++ const {+ initialState,+ mapData: {mapState},+ glContext+ } = props;++ this.state = {+ mediaType: 'webm',+ cameraPreset: 'None',+ fileName: '',+ resolution: '1280x720',+ durationMs: 1000,+ rendering: false,+ previewing: false,+ saving: false,+ currentTimeMs: 0,+ ...(initialState || {})+ };++ const viewState = scaleToVideoExport(mapState, this._getContainer());+ this.state = {+ ...this.state,+ viewState,+ memo: {viewState},+ adapter: new DeckAdapter({glContext})+ };+ }++ componentDidMount() {+ const {onTripFrameUpdate, onFilterFrameUpdate, getTimeRangeFilterKeyframes} = this.props;+ const animation = new KeplerAnimation({+ ...this.getFilterKeyframes(),+ ...this.getTripKeyframes(),+ cameraKeyframe: this.getCameraKeyframes(),+ onCameraFrameUpdate: this.setViewState as any,+ onTripFrameUpdate,+ onFilterFrameUpdate,+ getTimeRangeFilterKeyframes+ });+ this.state.adapter!.animationManager.attachAnimation(animation);+ }++ componentWillUnmount() {+ this.onStop({abort: true});+ if (this.animationFrameId) {+ cancelAnimationFrame(this.animationFrameId);+ }+ }++ getFileName() {+ const {defaultFileName} = this.props;+ const {fileName} = this.state;+ return fileName || defaultFileName;+ }++ getCanvasSize() {+ const {resolution} = this.state;+ const {width, height} = getResolutionSetting(resolution);+ return {width, height};+ }++ _getContainer() {+ const {width, height} = this.getCanvasSize();+ const {exportVideoWidth} = this.props;+ const aspectRatio = width / height;+ return {height: exportVideoWidth / aspectRatio, width: exportVideoWidth};+ }++ getFormatConfigs(): Partial<FormatConfigs> {+ const {width, height} = this.getCanvasSize();+ return {+ webm: {quality: 0.8},+ jpeg: {quality: 0.8},+ png: {},+ gif: {sampleInterval: 1000, width, height}+ };+ }++ getTimecode(): Timecode {+ const {durationMs} = this.state;+ return {start: 0, end: durationMs, framerate: 30};+ }++ getEncoder() {+ const {mediaType} = this.state;+ return ENCODERS[mediaType];+ }++ getCameraKeyframes() {+ const {viewState, cameraPreset, durationMs} = this.state;+ const {longitude, latitude, zoom, pitch, bearing} = viewState!;+ const {width, height} = this.getCanvasSize();+ return {+ timings: [0, durationMs],+ keyframes: [+ {longitude, latitude, zoom, pitch, bearing},+ parseSetCameraType(cameraPreset, viewState!)+ ],+ easings: [easeInOut],+ width,+ height+ };+ }++ getFilterKeyframes() {+ const {+ mapData: {+ visState: {filters}+ },+ animatableFilters+ } = this.props;++ const filterKeyframes = (+ Array.isArray(animatableFilters) && animatableFilters.length+ ? animatableFilters+ : filters.filter(+ (f: any) => f.type === 'timeRange' && f.view === FILTER_VIEW_TYPES.enlarged+ )+ ).map((f: any) => ({+ id: f.id,+ timings: [0, this.state.durationMs]+ }));++ if (filterKeyframes.length) {+ return {filters, filterKeyframes};+ }+ return {};+ }++ getTripKeyframes() {+ const {+ mapData: {+ visState: {layers, animationConfig}+ }+ } = this.props;++ const animatableLayer = layers.filter(+ (l: any) => l.config.animation && l.config.animation.enabled && l.config.isVisible+ );+ const readyToAnimation =+ Array.isArray(animationConfig.domain) && Number.isFinite(animationConfig.currentTime);+ if (animatableLayer.length && readyToAnimation) {+ return {+ animationConfig,+ tripKeyframe: {timings: [0, this.state.durationMs]}+ };+ }+ return {};+ }++ setViewState = (viewState: MapViewState) => {+ this.setState({viewState});+ };++ /** CSS background color (area the globe doesn't cover), from globe config. */+ getBackgroundColor(): string {+ const bg = this.props.mapData?.mapState?.globe?.config?.backgroundColor;+ const [r, g, b] = getGlobeClearColor(bg);+ return `rgb(${r}, ${g}, ${b})`;+ }++ setStateAndNotify(update: GlobeExportVideoSettings) {+ const {onSettingsChange} = this.props;+ const {mediaType, cameraPreset, fileName, resolution, durationMs} = this.state;+ this.setState({...this.state, ...update} as any);+ if (onSettingsChange) {+ onSettingsChange({mediaType, cameraPreset, fileName, resolution, durationMs, ...update});+ }+ }++ setMediaType = (mediaType: string) => this.setStateAndNotify({mediaType});+ setCameraPreset = (cameraPreset: string) => this.setStateAndNotify({cameraPreset});+ setFileName = (fileName: string) => this.setStateAndNotify({fileName});+ setResolution = (resolution: string) => this.setStateAndNotify({resolution});+ setDuration = (durationMs: number) => this.setStateAndNotify({durationMs});++ /** Preview playback — animate the camera without encoding. */+ onPreviewVideo = () => {+ const {adapter, durationMs} = this.state;+ this.setState({+ previewing: true,+ currentTimeMs: 0,+ memo: {viewState: {...this.state.viewState!}}+ });++ adapter!.animationManager.setKeyframes('kepler', {+ ...this.getFilterKeyframes(),+ ...this.getTripKeyframes(),+ cameraKeyframe: this.getCameraKeyframes()+ });++ const startTime = performance.now();+ const animate = () => {+ const elapsed = performance.now() - startTime;+ const currentTimeMs = Math.min(elapsed, durationMs);++ adapter!.animationManager.timeline.setTime(currentTimeMs);+ adapter!.animationManager.draw();++ this.setState({currentTimeMs});++ if (currentTimeMs >= durationMs) {+ this.setState({+ previewing: false,+ currentTimeMs: 0,+ viewState: {...this.state.memo!.viewState}+ });+ return;+ }+ this.animationFrameId = requestAnimationFrame(animate);+ };+ this.animationFrameId = requestAnimationFrame(animate);+ };++ /**+ * Record — drive our own capture loop (hubble's built-in loop never fires+ * without a base map) and encode the globe deck canvas frame by frame.+ */+ onRenderVideo = () => {+ const {adapter} = this.state;+ const filename = this.getFileName();+ const Encoder = this.getEncoder();+ const formatConfigs = this.getFormatConfigs();+ const timecode = this.getTimecode();+ const {width, height} = this.getCanvasSize();++ this.setState({+ rendering: true,+ saving: false,+ currentTimeMs: 0,+ memo: {viewState: {...this.state.viewState!}}+ });++ adapter!.animationManager.setKeyframes('kepler', {+ ...this.getFilterKeyframes(),+ ...this.getTripKeyframes(),+ cameraKeyframe: this.getCameraKeyframes()+ });++ const encoder = new Encoder({...formatConfigs, framerate: timecode.framerate});+ this.activeEncoder = encoder;+ encoder.start();++ const frameLengthMs = Math.floor(1000 / timecode.framerate);+ let timeMs = timecode.start;+ let retryCount = 0;+ const MAX_RETRIES = 60;++ const captureNextFrame = () => {+ if (!this.state.rendering || this.activeEncoder !== encoder) return;++ adapter!.animationManager.timeline.setTime(timeMs);+ adapter!.animationManager.draw();+ this.setState({currentTimeMs: timeMs});++ // Allow state update → preview re-render → deck redraw before capturing.+ const waitAndCapture = () => {+ requestAnimationFrame(() => {+ if (this.activeEncoder !== encoder) return;+ requestAnimationFrame(() => {+ if (this.activeEncoder !== encoder) return;+ const preview = this.previewRef.current;+ if (!preview) return;++ // Wait for globe base/data layers (tiles included) to finish before+ // the first frame so we don't record a half-loaded planet.+ if (!preview.areLayersLoaded() && retryCount < MAX_RETRIES) {+ retryCount++;+ requestAnimationFrame(waitAndCapture);+ return;+ }+ retryCount = 0;++ const deckCanvas = preview.getCanvas();+ if (!deckCanvas) return;++ // Reuse a single offscreen canvas across frames (resized only when+ // the output dimensions change) instead of allocating one per frame.+ let offscreen = this.compositeCanvas;+ if (!offscreen) {+ offscreen = document.createElement('canvas');+ this.compositeCanvas = offscreen;+ }+ if (offscreen.width !== width || offscreen.height !== height) {+ offscreen.width = width;+ offscreen.height = height;+ }+ const offCtx = offscreen.getContext('2d');+ if (offCtx) {+ // deck's canvas is transparent where the globe isn't drawn+ // (clearColor is disabled to keep picking intact), so fill the+ // configured background first, then composite the deck frame.+ offCtx.fillStyle = this.getBackgroundColor();+ offCtx.fillRect(0, 0, width, height);+ offCtx.drawImage(deckCanvas, 0, 0, width, height);+ }++ encoder.add(offscreen).then(() => {+ if (this.activeEncoder !== encoder) return;+ timeMs += frameLengthMs;+ if (timeMs > timecode.end) {+ this.setState({saving: true});+ encoder.save().then((blob: Blob | null) => {+ if (this.activeEncoder !== encoder) return;+ if (blob) {+ download(blob, filename + encoder.extension, encoder.mimeType);+ }+ this.setState({+ rendering: false,+ saving: false,+ currentTimeMs: 0,+ viewState: {...this.state.memo!.viewState}+ });+ });+ } else {+ captureNextFrame();+ }+ });+ });+ });+ };++ waitAndCapture();+ };++ // Give the deck a moment to mount/draw before the first capture.+ setTimeout(() => captureNextFrame(), 500);+ };++ onStop = ({abort = false}: {abort?: boolean} = {}) => {+ if (this.animationFrameId) {+ cancelAnimationFrame(this.animationFrameId);+ this.animationFrameId = null;+ }+ this.activeEncoder = null;+ if (!abort) {+ this.setState({+ rendering: false,+ previewing: false,+ currentTimeMs: 0,+ viewState: this.state.memo?.viewState || this.state.viewState+ });+ }+ };++ render() {+ const {exportVideoWidth, mapData, deckProps} = this.props;++ const {+ adapter,+ durationMs,+ mediaType,+ cameraPreset,+ fileName,+ resolution,+ viewState,+ rendering,+ previewing,+ saving,+ currentTimeMs+ } = this.state;++ const timecode = this.getTimecode();+ let canvasSize = this.getCanvasSize();+ if (previewing) {+ canvasSize = this._getContainer();+ }++ const isActive = rendering || previewing;++ return (+ <div className="export-video-panel">+ <PanelBody $exportVideoWidth={exportVideoWidth}>+ <GlobeExportVideoPreview+ ref={this.previewRef}+ mapData={mapData}+ adapter={adapter!}+ setViewState={this.setViewState}+ exportVideoWidth={exportVideoWidth}+ resolution={[canvasSize.width, canvasSize.height]}+ viewState={viewState!}+ rendering={rendering}+ saving={saving}+ durationMs={durationMs}+ deckProps={deckProps}+ backgroundColor={this.getBackgroundColor()}+ />+ <SwipeExportSettings+ durationMs={durationMs}+ mediaType={mediaType}+ resolution={resolution}+ fileName={fileName}+ cameraPreset={cameraPreset}+ frameRate={timecode.framerate}+ onChangeDuration={this.setDuration}+ onChangeMediaType={this.setMediaType}+ onChangeResolution={this.setResolution}+ onChangeFileName={this.setFileName}+ onChangeCameraPreset={this.setCameraPreset}+ swipeStartPct={0}+ swipeEndPct={100}+ swipeEasing={'ease-in-out'}+ disabled={isActive}+ onChangeStartPct={noop}+ onChangeEndPct={noop}+ onChangeEasing={noop}+ hideSwipe+ />+ <TimelineControls className="timeline-controls">+ {isActive ? (+ <StopIcon style={timelinePlayButtonStyle} onClick={() => this.onStop({})} />+ ) : (+ <PlayIcon style={timelinePlayButtonStyle} onClick={this.onPreviewVideo} />+ )}+ </TimelineControls>+ {saving && <StatusText>Saving...</StatusText>}+ {rendering && !saving && (+ <StatusText>Rendering... {Math.round((currentTimeMs / durationMs) * 100)}%</StatusText>+ )}+ <ButtonGroup>+ <Button+ style={{marginTop: '16px', width: '100%', height: '32px'}}+ className="export-video-button"+ onClick={this.onRenderVideo}+ disabled={isActive}+ >+ Render+ </Button>+ </ButtonGroup>+ </PanelBody>+ </div>+ );+ }+}diff --git a/src/components/src/modals/globe-export-video-preview.tsx b/src/components/src/modals/globe-export-video-preview.tsxnew file mode 100644index 000000000..43d3d7173--- /dev/null+++ b/src/components/src/modals/globe-export-video-preview.tsx@@ -0,0 +1,111 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {Component, RefObject} from 'react';+import DeckGL from '@deck.gl/react';+import type {Deck, DeckProps, MapViewState} from '@deck.gl/core';+import styled from 'styled-components';++import {DeckAdapter} from '@hubble.gl/core';++const PreviewContainer = styled.div<{$width: number; $height: number; $background: string}>`+ width: ${props => props.$width}px;+ height: ${props => props.$height}px;+ position: relative;+ background: ${props => props.$background};+`;++export type GlobeExportVideoPreviewProps = {+ mapData: any;+ resolution: [number, number];+ exportVideoWidth: number;+ deckProps?: DeckProps;+ viewState: MapViewState;+ adapter: DeckAdapter;+ rendering: boolean;+ saving: boolean;+ setViewState: (viewState: MapViewState) => void;+ durationMs: number;+ /** CSS color string for the area the globe does not cover. */+ backgroundColor: string;+};++/**+ * Single-canvas video export preview for globe mode.+ *+ * hubble's built-in preview cannot be used for globe mode: in its+ * `disableBaseMap` branch it renders a bare <DeckGL> without a viewState and+ * never wires up the frame-capture loop (that loop is driven by the mapbox+ * 'render' event, which does not exist without a base map). This component+ * renders the globe deck directly with a valid, controlled viewState so the+ * GlobeView controller initializes correctly (no MapState/GlobeState assert),+ * stays interactive, and exposes the deck canvas so the parent container can+ * drive its own capture loop (mirrors the swipe export approach).+ */+export class GlobeExportVideoPreview extends Component<GlobeExportVideoPreviewProps> {+ deckRef: RefObject<Deck | null> = React.createRef<Deck | null>();++ _getContainer() {+ const {exportVideoWidth, resolution} = this.props;+ const aspectRatio = resolution[0] / resolution[1];+ return {height: exportVideoWidth / aspectRatio, width: exportVideoWidth};+ }++ /** Expose the deck canvas so the parent container can capture frames. */+ getCanvas(): HTMLCanvasElement | null {+ const deck = this.deckRef.current as any;+ return (deck && deck.getCanvas?.()) || null;+ }++ /** All layers loaded — used to gate the first capture frame. */+ areLayersLoaded(): boolean {+ const deck = this.deckRef.current;+ if (!deck) return false;+ const layers = deck.props.layers || [];+ return layers.length > 0 && layers.every((layer: any) => layer.isLoaded);+ }++ render() {+ const {adapter, deckProps, viewState, setViewState, resolution, exportVideoWidth, backgroundColor} =+ this.props;+ const {width, height} = this._getContainer();+ const deck = this.deckRef.current;++ // adapter.getProps injects `_animate` (and toggles `controller` off while+ // recording) so hubble's KeplerAnimation can drive the camera. Layers,+ // views, controller bounds and initialViewState come from `deckProps`+ // (see getHubbleDeckGlProps). A controlled `viewState` keeps the preview in+ // sync with the animated camera and prevents the GlobeState assert.+ const adapterProps = adapter.getProps({+ deck: deck as any,+ extraProps: deckProps as any+ }) as any;++ // Render the drawing buffer at the true export resolution regardless of the+ // small CSS preview size. deck.gl's MSAA (antialias defaults to true when+ // deck owns the canvas) only smooths edges at the drawing-buffer resolution,+ // so if the buffer were the small preview size the globe silhouette would+ // look pixelated once the captured frame is scaled up to the output size.+ // Passing an explicit numeric `useDevicePixels` sizes the buffer to+ // width * ratio === exportVideoWidth * (resolution / exportVideoWidth) ===+ // resolution, and is far more reliable than mutating window.devicePixelRatio.+ const pixelRatio = Math.max(1, resolution[0] / exportVideoWidth);++ return (+ <PreviewContainer $width={width} $height={height} $background={backgroundColor}>+ <DeckGL+ ref={ref => {+ this.deckRef.current = (ref?.deck as any) || null;+ }}+ deviceProps={{type: 'webgl', webgl: {preserveDrawingBuffer: true}}}+ {...adapterProps}+ viewState={viewState}+ onViewStateChange={({viewState: vs}: any) => setViewState(vs)}+ useDevicePixels={pixelRatio}+ width={width}+ height={height}+ />+ </PreviewContainer>+ );+ }+}diff --git a/src/components/src/modals/hubble-utils.ts b/src/components/src/modals/hubble-utils.tsindex 73d95ed0c..0abc3d224 100644--- a/src/components/src/modals/hubble-utils.ts+++ b/src/components/src/modals/hubble-utils.ts@@ -2,8 +2,17 @@// Copyright contributors to the kepler.gl projectimport {MapView, WebMercatorViewport, type MapViewState} from '@deck.gl/core';-import {DEFAULT_MAPBOX_API_URL, FILTER_VIEW_TYPES, FILTER_TYPES} from '@kepler.gl/constants';+import {+ DEFAULT_MAPBOX_API_URL,+ EMPTY_MAPBOX_STYLE,+ FILTER_VIEW_TYPES,+ FILTER_TYPES,+ GLOBE_MIN_ZOOM,+ GLOBE_MAX_ZOOM+} from '@kepler.gl/constants';import {getLayerBlendingParameters, getBaseMapLibrary} from '@kepler.gl/utils';+import {getGlobeBaseLayers, getGlobeTopLayers, KeplerGlobeView} from '@kepler.gl/deckgl-layers';+import {computeDeckLayers} from '@kepler.gl/reducers';import {isMapboxURL, transformMapboxUrl} from 'maplibregl-mapbox-request-transformer';import {point} from '@turf/helpers';import {transformTranslate} from '@turf/transform-translate';@@ -114,6 +123,7 @@ export function getStaticMapProps(const currentStyle = keplerState.mapStyle?.mapStyles?.[keplerState.mapStyle.styleType];const accessToken = currentStyle?.accessToken || mapboxApiAccessToken;const isMapbox = getBaseMapLibrary(currentStyle) === 'mapbox';+ const isGlobe = Boolean(keplerState.mapState?.globe?.enabled);const mapboxTransformRequest = (url: string, resourceType: string) => {if (isMapboxURL(url)) {@@ -122,15 +132,22 @@ export function getStaticMapProps(return {url};};+ // In globe mode the deck.gl GlobeView renders the planet + basemap tiles as+ // deck layers on a transparent canvas, so the flat maplibre base map must be+ // suppressed (otherwise a 2D Mercator basemap would render behind the globe).+ const bottomMapStyle = isGlobe+ ? EMPTY_MAPBOX_STYLE+ : isMapbox+ ? convertMapboxStyleUrls(keplerState.mapStyle?.bottomMapStyle, accessToken)+ : keplerState.mapStyle?.bottomMapStyle;+return {...keplerState.mapState,preserveDrawingBuffer: true,mapboxApiAccessToken: accessToken,mapboxApiUrl,transformRequest: mapboxTransformRequest,- mapStyle: isMapbox- ? convertMapboxStyleUrls(keplerState.mapStyle?.bottomMapStyle, accessToken)- : keplerState.mapStyle?.bottomMapStyle,+ mapStyle: bottomMapStyle,onViewportChange: onViewChange,mapLib: import('maplibre-gl')};@@ -177,19 +194,123 @@ function getHubbleParameters(keplerState: KeplerState): Record<string, any> {export function getHubbleDeckGlProps(keplerState: KeplerState,- _mapboxApiAccessToken: string,- _mapboxApiUrl: string = DEFAULT_MAPBOX_API_URL+ mapboxApiAccessToken: string,+ mapboxApiUrl: string = DEFAULT_MAPBOX_API_URL): Record<string, any> {+ const globe = keplerState.mapState?.globe;+ const isGlobe = Boolean(globe?.enabled);++ if (!isGlobe) {+ return {+ parameters: getHubbleParameters(keplerState),+ controller: true,+ views: new MapView({+ id: 'mapbox',+ farZMultiplier: 1.2+ })+ };+ }++ // Globe video export: mirror the interactive globe render path in map-container.+ // - Use a GlobeView so the camera/projection curve data around the sphere.+ // - Provide layers explicitly (globe base layers + kepler data layers + globe+ // top layers). When `deckProps.layers` is set, hubble's preview uses them+ // verbatim (skipping its internal 2D-only createKeplerLayers path), and the+ // kepler layers are built from `mapState.globe`, so composite layers (e.g.+ // the heatmap) emit their globe-conforming sublayers.+ const globeBaseLayers = getGlobeBaseLayers({+ mapboxApiAccessToken: mapboxApiAccessToken || '',+ globe,+ mapStyleType: keplerState.mapStyle?.styleType+ });+ const globeTopLayers = getGlobeTopLayers({globe});+ const dataLayers = computeDeckLayers(keplerState, {+ primaryMap: true,+ mapboxApiAccessToken,+ mapboxApiUrl+ });++ // hubble's video-export preview renders a bare <DeckGL> in the disableBaseMap+ // (globe) branch and — unlike its mapbox branch — never forwards a viewState.+ // With `controller: true` deck.gl then constructs a controller state from an+ // empty view state, and GlobeState/MapState assert on the missing+ // latitude/longitude/zoom ("assertion failed at new MapState/GlobeState").+ // That degenerate viewport also leaves tile/MVT base layers permanently+ // "not loaded", so hubble's `layers.every(l => l.isLoaded)` capture gate never+ // fires and the export hangs. Provide an explicit initialViewState (deck.gl+ // uses it to seed the controller when no controlled viewState is supplied) so+ // the globe camera is valid, tiles resolve, and interaction works.+ const {longitude, latitude, zoom, pitch, bearing} = keplerState.mapState || {};+ const initialViewState = {+ longitude,+ latitude,+ zoom,+ pitch: pitch || 0,+ bearing: bearing || 0,+ minZoom: GLOBE_MIN_ZOOM,+ maxZoom: GLOBE_MAX_ZOOM+ };+return {- parameters: getHubbleParameters(keplerState),- controller: true,- views: new MapView({- id: 'mapbox',- farZMultiplier: 1.2- })+ parameters: {+ ...getHubbleParameters(keplerState),+ cull: true+ },+ // Match the interactive globe controller bounds so panning/zoom feels the+ // same in the preview as on the main map.+ controller: {+ minZoom: GLOBE_MIN_ZOOM,+ maxZoom: GLOBE_MAX_ZOOM+ },+ initialViewState,+ views: new KeplerGlobeView({+ resolution: 5,+ // clearColor:false (not a solid color) is deliberate and mirrors the+ // interactive map: deck.gl applies a View's clearColor in EVERY pass+ // including the picking pass, forcing alpha to 255. In the picking buffer+ // the alpha byte encodes the layer index, so a solid clear makes deck.gl+ // decode every pixel as a non-existent layer ("Picked non-existent layer.+ // Is picking buffer corrupt?") whenever the controller picks on hover.+ // Skipping the color clear keeps the picking buffer's 0 alpha intact; the+ // sphere itself stays opaque via the globe-background SolidPolygonLayer.+ clear: true,+ clearColor: false+ }),+ layers: [...globeBaseLayers, ...dataLayers, ...globeTopLayers]};}+/**+ * Build a fresh set of globe layers (base + data + top) for a given split-map+ * index. Used by the swipe export preview, which mounts two independent Deck+ * instances: each side needs its OWN layer instances (deck.gl Layer objects are+ * stateful and bound to a single Deck) and its own `mapIndex` so the split-map+ * layer visibility is respected on each half of the swipe.+ */+export function getGlobeExportLayers(+ keplerState: KeplerState,+ {+ mapIndex,+ mapboxApiAccessToken,+ mapboxApiUrl+ }: {mapIndex: number; mapboxApiAccessToken?: string; mapboxApiUrl?: string}+) {+ const globe = keplerState.mapState?.globe;+ const globeBaseLayers = getGlobeBaseLayers({+ mapboxApiAccessToken: mapboxApiAccessToken || '',+ globe,+ mapStyleType: keplerState.mapStyle?.styleType+ });+ const globeTopLayers = getGlobeTopLayers({globe});+ const dataLayers = computeDeckLayers(keplerState, {+ mapIndex,+ primaryMap: mapIndex === 0,+ mapboxApiAccessToken,+ mapboxApiUrl+ });+ return [...globeBaseLayers, ...dataLayers, ...globeTopLayers];+}+export function getAnimatableFilters(keplerState: KeplerState): TimeRangeFilter[] {const filters = keplerState.visState?.filters || [];return filters.filter(@@ -205,25 +326,37 @@ export function scaleToVideoExport(viewState: MapViewState,container: {width: number; height: number}): MapViewState & {width: number; height: number} {- const viewport = new WebMercatorViewport(viewState);- const nw = viewport.unproject([0, 0]) as [number, number];- const se = viewport.unproject([viewport.width, viewport.height]) as [number, number];- const videoViewport = new WebMercatorViewport({- ...viewState,- width: container.width,- height: container.height- }).fitBounds([nw, se]);- const {height, width, latitude, longitude, zoom, altitude} = videoViewport;- return {- height,- width,- latitude,- longitude,- pitch: viewState.pitch,- zoom,- bearing: viewState.bearing,- altitude- } as any;+ // In globe mode (and at extreme zooms) the WebMercatorViewport used below can+ // produce a non-invertible projection matrix, making `unproject` throw. The+ // Mercator fit-bounds rescaling only makes sense for the flat MapView anyway,+ // so fall back to simply resizing the viewport to the export container.+ try {+ const viewport = new WebMercatorViewport(viewState);+ const nw = viewport.unproject([0, 0]) as [number, number];+ const se = viewport.unproject([viewport.width, viewport.height]) as [number, number];+ const videoViewport = new WebMercatorViewport({+ ...viewState,+ width: container.width,+ height: container.height+ }).fitBounds([nw, se]);+ const {height, width, latitude, longitude, zoom, altitude} = videoViewport;+ return {+ height,+ width,+ latitude,+ longitude,+ pitch: viewState.pitch,+ zoom,+ bearing: viewState.bearing,+ altitude+ } as any;+ } catch (e) {+ return {+ ...viewState,+ width: container.width,+ height: container.height+ } as any;+ }}export function parseSetCameraType(strCameraType: string, viewState: MapViewState): MapViewState {diff --git a/src/components/src/modals/swipe-composite-utils.ts b/src/components/src/modals/swipe-composite-utils.tsindex d28513566..7583996e0 100644--- a/src/components/src/modals/swipe-composite-utils.ts+++ b/src/components/src/modals/swipe-composite-utils.ts@@ -90,7 +90,8 @@ export function compositeSwipeFrame(rightCanvas: HTMLCanvasElement,outputCanvas: HTMLCanvasElement,percentage: number,- showDivider: boolean = true+ showDivider: boolean = true,+ backgroundColor?: string): void {const ctx = outputCanvas.getContext('2d');if (!ctx) return;@@ -101,6 +102,15 @@ export function compositeSwipeFrame(ctx.clearRect(0, 0, w, h);+ // In globe mode the deck canvases are transparent where the globe isn't+ // drawn (clearColor is disabled to keep picking intact), so paint the+ // configured background first. Non-globe swipe passes no color and keeps the+ // previous transparent-clear behavior (the base map is already opaque).+ if (backgroundColor) {+ ctx.fillStyle = backgroundColor;+ ctx.fillRect(0, 0, w, h);+ }+// Draw right (background) canvas fullyctx.drawImage(rightCanvas, 0, 0, w, h);diff --git a/src/components/src/modals/swipe-export-settings.tsx b/src/components/src/modals/swipe-export-settings.tsxindex 5efce8863..2fd874d92 100644--- a/src/components/src/modals/swipe-export-settings.tsx+++ b/src/components/src/modals/swipe-export-settings.tsx@@ -143,6 +143,8 @@ export type SwipeExportSettingsProps = {onChangeStartPct: (value: number) => void;onChangeEndPct: (value: number) => void;onChangeEasing: (value: SwipeEasing) => void;+ // When true, hide the swipe-specific controls (used by single-map globe export).+ hideSwipe?: boolean;};// --- Utilities ---@@ -210,6 +212,7 @@ const AnimationTab: React.FC<{swipeEndPct: number;swipeEasing: SwipeEasing;disabled: boolean;+ hideSwipe?: boolean;onChangeDuration: (value: number) => void;onChangeCameraPreset: (value: string) => void;onChangeStartPct: (value: number) => void;@@ -222,6 +225,7 @@ const AnimationTab: React.FC<{swipeEndPct,swipeEasing,disabled,+ hideSwipe,onChangeDuration,onChangeCameraPreset,onChangeStartPct,@@ -259,44 +263,48 @@ const AnimationTab: React.FC<{/></InputGrid>- <SectionDivider>Swipe</SectionDivider>- <InputGrid>- <StyledLabelCell>Start ({Math.round(swipeStartPct)}%)</StyledLabelCell>- <LightSlider- showValues={false}- isRanged={false}- value1={swipeStartPct}- minValue={0}- maxValue={100}- step={1}- onSlider1Change={(v: number) => { if (!disabled) onChangeStartPct(v); }}- disabled={disabled}- />+ {!hideSwipe && (+ <>+ <SectionDivider>Swipe</SectionDivider>+ <InputGrid>+ <StyledLabelCell>Start ({Math.round(swipeStartPct)}%)</StyledLabelCell>+ <LightSlider+ showValues={false}+ isRanged={false}+ value1={swipeStartPct}+ minValue={0}+ maxValue={100}+ step={1}+ onSlider1Change={(v: number) => { if (!disabled) onChangeStartPct(v); }}+ disabled={disabled}+ />- <StyledLabelCell>End ({Math.round(swipeEndPct)}%)</StyledLabelCell>- <LightSlider- showValues={false}- isRanged={false}- value1={swipeEndPct}- minValue={0}- maxValue={100}- step={1}- onSlider1Change={(v: number) => { if (!disabled) onChangeEndPct(v); }}- disabled={disabled}- />+ <StyledLabelCell>End ({Math.round(swipeEndPct)}%)</StyledLabelCell>+ <LightSlider+ showValues={false}+ isRanged={false}+ value1={swipeEndPct}+ minValue={0}+ maxValue={100}+ step={1}+ onSlider1Change={(v: number) => { if (!disabled) onChangeEndPct(v); }}+ disabled={disabled}+ />- <StyledLabelCell>Easing</StyledLabelCell>- <LightItemSelector- selectedItems={EASING_OPTIONS.find(o => o.id === swipeEasing) || EASING_OPTIONS[0]}- options={EASING_OPTIONS}- multiSelect={false}- searchable={false}- onChange={(val: any) => onChangeEasing(val?.id || val)}- disabled={disabled}- getOptionValue={(o: any) => o.id}- displayOption={(o: any) => o.label}- />- </InputGrid>+ <StyledLabelCell>Easing</StyledLabelCell>+ <LightItemSelector+ selectedItems={EASING_OPTIONS.find(o => o.id === swipeEasing) || EASING_OPTIONS[0]}+ options={EASING_OPTIONS}+ multiSelect={false}+ searchable={false}+ onChange={(val: any) => onChangeEasing(val?.id || val)}+ disabled={disabled}+ getOptionValue={(o: any) => o.id}+ displayOption={(o: any) => o.label}+ />+ </InputGrid>+ </>+ )}</>);@@ -405,7 +413,8 @@ const SwipeExportSettings: React.FC<SwipeExportSettingsProps> = ({disabled,onChangeStartPct,onChangeEndPct,- onChangeEasing+ onChangeEasing,+ hideSwipe}) => {const [activeTab, setActiveTab] = useState<TabId>('animation');@@ -434,6 +443,7 @@ const SwipeExportSettings: React.FC<SwipeExportSettingsProps> = ({swipeEndPct={swipeEndPct}swipeEasing={swipeEasing}disabled={disabled}+ hideSwipe={hideSwipe}onChangeDuration={onChangeDuration}onChangeCameraPreset={onChangeCameraPreset}onChangeStartPct={onChangeStartPct}diff --git a/src/components/src/modals/swipe-export-video-container.tsx b/src/components/src/modals/swipe-export-video-container.tsxindex ae97ab6a6..d521f4340 100644--- a/src/components/src/modals/swipe-export-video-container.tsx+++ b/src/components/src/modals/swipe-export-video-container.tsx@@ -23,6 +23,7 @@ import {parseSetCameraType, scaleToVideoExport, getResolutionSetting} from './huimport {SwipeExportVideoPreview} from './swipe-export-video-preview';import SwipeExportSettings from './swipe-export-settings';import {SwipeEasing} from './swipe-composite-utils';+import {getGlobeClearColor} from '@kepler.gl/deckgl-layers';const ENCODERS = {gif: GifEncoder,@@ -299,6 +300,20 @@ export class SwipeExportVideoPanelContainer extends Component<this.setState({viewState});};+ /**+ * CSS background color for globe swipe (the area the globe doesn't cover).+ * Returns undefined outside globe mode so non-globe swipe keeps its previous+ * transparent-clear compositing (the opaque base map already fills the frame).+ */+ getBackgroundColor(): string | undefined {+ if (!this.props.mapData?.mapState?.globe?.enabled) {+ return undefined;+ }+ const bg = this.props.mapData?.mapState?.globe?.config?.backgroundColor;+ const [r, g, b] = getGlobeClearColor(bg);+ return `rgb(${r}, ${g}, ${b})`;+ }+setStateAndNotify(update: SwipeExportVideoSettings) {const {onSettingsChange} = this.props;const {mediaType, cameraPreset, fileName, resolution, durationMs} = this.state;@@ -548,6 +563,7 @@ export class SwipeExportVideoPanelContainer extends Component<swipeEndPct={swipeEndPct}swipeEasing={swipeEasing}currentTimeMs={currentTimeMs}+ backgroundColor={this.getBackgroundColor()}/><SwipeExportSettingsdurationMs={durationMs}diff --git a/src/components/src/modals/swipe-export-video-preview.tsx b/src/components/src/modals/swipe-export-video-preview.tsxindex b3ac05238..0dc429e9d 100644--- a/src/components/src/modals/swipe-export-video-preview.tsx+++ b/src/components/src/modals/swipe-export-video-preview.tsx@@ -13,6 +13,7 @@ import styled from 'styled-components';import {DeckAdapter} from '@hubble.gl/core';import {createKeplerLayers} from '@hubble.gl/react';import {compositeSwipeFrame, getSwipePercentageAtTime, SwipeEasing} from './swipe-composite-utils';+import {getGlobeExportLayers} from './hubble-utils';function setRef<T>(ref: React.Ref<T> | React.MutableRefObject<T>, value: T) {if (typeof ref === 'function') {@@ -75,6 +76,7 @@ export type SwipeExportVideoPreviewProps = {swipeEndPct: number;swipeEasing: SwipeEasing;currentTimeMs: number;+ backgroundColor?: string;};type SwipeExportVideoPreviewState = {@@ -172,7 +174,14 @@ export class SwipeExportVideoPreview extends Component<if (!leftCanvas || !rightCanvas || !outputCanvas) return;const percentage = this._getCurrentSwipePercentage();- compositeSwipeFrame(leftCanvas, rightCanvas, outputCanvas, percentage, true);+ compositeSwipeFrame(+ leftCanvas,+ rightCanvas,+ outputCanvas,+ percentage,+ true,+ this.props.backgroundColor+ );}/**@@ -208,9 +217,29 @@ export class SwipeExportVideoPreview extends Component<}_createLayers(mapIndex: number, beforeId?: string) {- const {deckProps, mapData, viewState} = this.props;+ const {deckProps, mapData, viewState, disableBaseMap, mapProps} = this.props;++ // Globe swipe: build a fresh set of globe layers per side. Each side is a+ // separate Deck, so it needs its OWN Layer instances (deck.gl Layer objects+ // are stateful and bound to one Deck — sharing them makes the second Deck+ // assert while initializing them). Building per `mapIndex` also respects the+ // split-map layer visibility on each half of the swipe.+ if (disableBaseMap && mapData?.mapState?.globe?.enabled) {+ return getGlobeExportLayers(mapData, {+ mapIndex,+ mapboxApiAccessToken: mapProps?.mapboxApiAccessToken,+ mapboxApiUrl: mapProps?.mapboxApiUrl+ });+ }+if (deckProps && deckProps.layers) {- return deckProps.layers;+ // Non-globe path with explicit layers: clone per side with a unique id so+ // the two Deck instances don't share the same stateful Layer objects.+ return deckProps.layers.map((layer: any) =>+ layer && typeof layer.clone === 'function'+ ? layer.clone({id: `${layer.id}-swipe-${mapIndex}`})+ : layer+ );}return createKeplerLayers(mapData, viewState, mapIndex, beforeId);}@@ -245,6 +274,26 @@ export class SwipeExportVideoPreview extends Component<}}+ // Globe (disableBaseMap) mode has no ReactMapGL and therefore no map 'render'+ // event to drive compositing. Instead each bare <DeckGL> reports when it has+ // drawn via onAfterRender; once both sides have rendered we composite. Without+ // this the composite output canvas is never painted until the user presses+ // play, so the preview shows a blank (white) frame on mount.+ _onDeckRender = (side: 'left' | 'right') => {+ const readyKey = side === 'left' ? 'leftReady' : 'rightReady';+ if (!this.state[readyKey]) {+ this.setState({[readyKey]: true} as any);+ }+ // Composite as soon as both decks exist and have drawn. We check the deck+ // refs directly (not React state, which can be stale right after setState)+ // and intentionally don't gate on layers being fully loaded here (that gate+ // lives in the capture loop): for a live preview we want to show the globe+ // as it streams in rather than a blank frame while tiles load.+ if (this.leftDeckRef.current && this.rightDeckRef.current) {+ this._compositeFrame();+ }+ };+_renderMapCanvas(side: 'left' | 'right',mapIndex: number@@ -258,11 +307,25 @@ export class SwipeExportVideoPreview extends Component<const deck = deckRef.current;if (disableBaseMap) {+ const adapterProps = adapter.getProps({+ deck: deck as any,+ extraProps: {...deckProps, layers: keplerLayers}+ }) as any;+ const adapterOnAfterRender = adapterProps.onAfterRender;return (<MapLayer $width={width} $height={height}><DeckGLref={ref => setRef(deckRef, ref?.deck as any)}- {...(adapter.getProps({deck: deck as any, extraProps: {...deckProps, layers: keplerLayers}}) as any)}+ deviceProps={{type: 'webgl', webgl: {preserveDrawingBuffer: true}}}+ {...adapterProps}+ viewState={viewState}+ onViewStateChange={({viewState: vs}: any) => this.props.setViewState(vs)}+ onAfterRender={(params: any) => {+ if (typeof adapterOnAfterRender === 'function') {+ adapterOnAfterRender(params);+ }+ this._onDeckRender(side);+ }}{...this._getContainer()}/></MapLayer>diff --git a/src/components/src/side-panel.tsx b/src/components/src/side-panel.tsxindex ea616c010..4f3bf3669 100644--- a/src/components/src/side-panel.tsx+++ b/src/components/src/side-panel.tsx@@ -113,6 +113,7 @@ export default function SidePanelFactory(panels = fullPanels,mapInfo = {},mapSaved,+ mapState,mapStateActions,mapStyle,mapStyleActions,@@ -216,6 +217,7 @@ export default function SidePanelFactory(layerBlending={layerBlending}overlayBlending={overlayBlending}mapStyle={mapStyle}+ mapState={mapState}mapStyleActions={mapStyleActions}mapStateActions={mapStateActions}interactionConfig={interactionConfig}diff --git a/src/components/src/side-panel/layer-manager.tsx b/src/components/src/side-panel/layer-manager.tsxindex 0a7ec3983..62d16a5d3 100644--- a/src/components/src/side-panel/layer-manager.tsx+++ b/src/components/src/side-panel/layer-manager.tsx@@ -22,7 +22,7 @@ import {LAYER_BLENDINGS, OVERLAY_BLENDINGS, PANEL_VIEW_TOGGLES} from '@kepler.glimport {Layer, LayerClassesType} from '@kepler.gl/layers';import {UIStateActions, VisStateActions, MapStateActions, ActionHandler} from '@kepler.gl/actions';import {SidePanelItem} from '../types';-import {PanelListView, LayerOrder} from '@kepler.gl/types';+import {MapState, PanelListView, LayerOrder} from '@kepler.gl/types';import {Datasets} from '@kepler.gl/table';import {getApplicationConfig} from '@kepler.gl/utils';import PanelHeaderActionFactory from './panel-header-action';@@ -50,6 +50,7 @@ type LayerManagerProps = {uiStateActions: typeof UIStateActions;visStateActions: typeof VisStateActions;mapStateActions: typeof MapStateActions;+ mapState?: MapState;showAddDataModal: () => void;removeDataset: ActionHandler<typeof UIStateActions.openDeleteModal>;showDatasetTable: ActionHandler<typeof VisStateActions.showDatasetTable>;@@ -176,7 +177,8 @@ function LayerManagerFactory(removeDataset,uiStateActions,visStateActions,- mapStateActions+ mapStateActions,+ mapState}) => {const {addLayer} = visStateActions;const {togglePanelListView} = uiStateActions;@@ -268,6 +270,7 @@ function LayerManagerFactory(uiStateActions={uiStateActions}visStateActions={visStateActions}mapStateActions={mapStateActions}+ mapState={mapState}showDeleteDataset={showDeleteDataset}/>) : (@@ -278,6 +281,7 @@ function LayerManagerFactory(uiStateActions={uiStateActions}visStateActions={visStateActions}mapStateActions={mapStateActions}+ mapState={mapState}layerClasses={filteredLayerClasses}/>)}diff --git a/src/components/src/side-panel/layer-panel/dataset-layer-group.tsx b/src/components/src/side-panel/layer-panel/dataset-layer-group.tsxindex 1dee72136..27d957916 100644--- a/src/components/src/side-panel/layer-panel/dataset-layer-group.tsx+++ b/src/components/src/side-panel/layer-panel/dataset-layer-group.tsx@@ -7,7 +7,7 @@ import DatasetLayerSectionFactory from './dataset-layer-section';import {Layer, LayerClassesType} from '@kepler.gl/layers';import {UIStateActions, VisStateActions, ActionHandler, MapStateActions} from '@kepler.gl/actions';import {KeplerTable, Datasets} from '@kepler.gl/table';-import {LayerOrder} from '@kepler.gl/types';+import {LayerOrder, MapState} from '@kepler.gl/types';type DatasetLayerGroupProps = {datasets: Datasets;@@ -21,6 +21,7 @@ type DatasetLayerGroupProps = {uiStateActions: typeof UIStateActions;visStateActions: typeof VisStateActions;mapStateActions: typeof MapStateActions;+ mapState?: MapState;};DatasetLayerGroupFactory.deps = [DatasetLayerSectionFactory];@@ -40,7 +41,8 @@ function DatasetLayerGroupFactory(layerClasses,uiStateActions,visStateActions,- mapStateActions+ mapStateActions,+ mapState} = props;const datasetLayerSectionData = useMemo(() => {@@ -73,6 +75,7 @@ function DatasetLayerGroupFactory(uiStateActions={uiStateActions}visStateActions={visStateActions}mapStateActions={mapStateActions}+ mapState={mapState}/>))}</>diff --git a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsxindex 62f7737dd..032af2463 100644--- a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx+++ b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx@@ -10,7 +10,7 @@ import {Layer, LayerClassesType} from '@kepler.gl/layers';import {UIStateActions, ActionHandler, VisStateActions, MapStateActions} from '@kepler.gl/actions';import {KeplerTable, Datasets} from '@kepler.gl/table';import {getApplicationConfig} from '@kepler.gl/utils';-import {LayerOrder} from '@kepler.gl/types';+import {LayerOrder, MapState} from '@kepler.gl/types';type DatasetLayerSectionProps = {datasets: Datasets;@@ -25,6 +25,7 @@ type DatasetLayerSectionProps = {uiStateActions: typeof UIStateActions;visStateActions: typeof VisStateActions;mapStateActions: typeof MapStateActions;+ mapState?: MapState;};const DatasetLayerSectionWrapper = styled.div.attrs({@@ -52,7 +53,8 @@ function DatasetLayerSectionFactory(layerClasses,uiStateActions,visStateActions,- mapStateActions+ mapStateActions,+ mapState} = props;const datasetCatalog = useMemo(() => {@@ -103,6 +105,7 @@ function DatasetLayerSectionFactory(uiStateActions={uiStateActions}visStateActions={visStateActions}mapStateActions={mapStateActions}+ mapState={mapState}isSortable={false}/></DatasetLayerSectionWrapper>diff --git a/src/components/src/side-panel/layer-panel/layer-list.tsx b/src/components/src/side-panel/layer-panel/layer-list.tsxindex c0f58f3ae..5bf29653d 100644--- a/src/components/src/side-panel/layer-panel/layer-list.tsx+++ b/src/components/src/side-panel/layer-panel/layer-list.tsx@@ -8,7 +8,7 @@ import classnames from 'classnames';import {Layer, LayerClassesType} from '@kepler.gl/layers';import {Datasets} from '@kepler.gl/table';import {UIStateActions, VisStateActions, MapStateActions} from '@kepler.gl/actions';-import {LayerOrderGroup, LayerOrder, LayerOrderHierarchy} from '@kepler.gl/types';+import {LayerOrderGroup, LayerOrder, LayerOrderHierarchy, MapState} from '@kepler.gl/types';import {useDroppable} from '@dnd-kit/core';import {@@ -39,6 +39,7 @@ export type LayerListProps = {layerClasses: LayerClassesType;isSortable?: boolean;splitMap?: SplitMap;+ mapState?: MapState;uiStateActions: typeof UIStateActions;visStateActions: typeof VisStateActions;mapStateActions: typeof MapStateActions;@@ -315,6 +316,7 @@ function LayerListFactory(uiStateActions,visStateActions,mapStateActions,+ mapState,layerClasses,isSortable = true,splitMap@@ -368,9 +370,10 @@ function LayerListFactory(datasets,openModal,layerTypeOptions,- splitMap+ splitMap,+ mapState}),- [datasets, openModal, layerTypeOptions, splitMap]+ [datasets, openModal, layerTypeOptions, splitMap, mapState]);return (diff --git a/src/components/src/side-panel/layer-panel/layer-panel-header.tsx b/src/components/src/side-panel/layer-panel/layer-panel-header.tsxindex b42ea945b..8789ffba0 100644--- a/src/components/src/side-panel/layer-panel/layer-panel-header.tsx+++ b/src/components/src/side-panel/layer-panel/layer-panel-header.tsx@@ -64,7 +64,7 @@ export type LayerPanelHeaderProps = {layerType?: string | null;allowDuplicate?: boolean;isDragNDropEnabled?: boolean;- warning?: boolean;+ warning?: React.ReactNode;labelRCGColorValues?: RGBColor | null;actionIcons?: {remove: ComponentType<Partial<BaseProps>>;@@ -416,7 +416,7 @@ function LayerPanelHeaderFactory('sort--handle': !isConfigActive})}isValid={isValid}- warning={warning}+ warning={Boolean(warning)}$active={isConfigActive}labelRCGColorValues={labelRCGColorValues}onClick={onToggleEnableConfig}diff --git a/src/components/src/side-panel/layer-panel/layer-panel.tsx b/src/components/src/side-panel/layer-panel/layer-panel.tsxindex b34ee90b1..c4fb0fada 100644--- a/src/components/src/side-panel/layer-panel/layer-panel.tsx+++ b/src/components/src/side-panel/layer-panel/layer-panel.tsx@@ -8,13 +8,14 @@ import React, {MouseEventHandler,TouchEventHandler} from 'react';+import {FormattedMessage} from '@kepler.gl/localization';import styled from 'styled-components';import {ActionHandler, MapStateActions, VisStateActions, toggleModal} from '@kepler.gl/actions';-import {dataTestIds} from '@kepler.gl/constants';+import {dataTestIds, GLOBE_SUPPORTED_LAYERS} from '@kepler.gl/constants';import {Layer, LayerBaseConfig} from '@kepler.gl/layers';import {Datasets} from '@kepler.gl/table';-import {ColorUI, LayerVisConfig, NestedPartial, SplitMap} from '@kepler.gl/types';+import {ColorUI, LayerVisConfig, MapState, NestedPartial, SplitMap} from '@kepler.gl/types';import LayerConfiguratorFactory from './layer-configurator';import LayerPanelHeaderFactory from './layer-panel-header';@@ -33,6 +34,7 @@ type LayerPanelProps = {}[];isDraggable?: boolean;idx: number;+ mapState?: MapState;openModal: ActionHandler<typeof toggleModal>;layerColorUIChange: ActionHandler<typeof VisStateActions.layerColorUIChange>;layerConfigChange: ActionHandler<typeof VisStateActions.layerConfigChange>;@@ -138,13 +140,22 @@ function LayerPanelFactory(};render() {- const {layer, datasets, isDraggable, layerTypeOptions, listeners, splitMap} = this.props;+ const {layer, datasets, isDraggable, layerTypeOptions, listeners, splitMap, mapState} =+ this.props;const {config, isValid} = layer;const {isConfigActive} = config;const allowDuplicate =typeof layer.isValidToSave === 'function' && layer.isValidToSave() && isValid;const layerVisInSplitMap = splitMap?.layers?.[layer.id];+ const isVisible = layerVisInSplitMap ?? config.isVisible;+ const globeWarning =+ mapState?.globe?.enabled &&+ isVisible &&+ GLOBE_SUPPORTED_LAYERS[layer.type ?? ''] === false ? (+ <FormattedMessage id={'layerManager.globeUnsupported'} values={{layerType: layer.type}} />+ ) : undefined;+return (<PanelWrapperclassName={`layer-panel ${this.props.className}`}@@ -156,12 +167,13 @@ function LayerPanelFactory(<LayerPanelHeaderisConfigActive={isConfigActive}layerId={layer.id}- isVisible={layerVisInSplitMap ?? config.isVisible}+ isVisible={isVisible}isValid={isValid}label={config.label}labelRCGColorValues={config.dataId ? datasets[config.dataId].color : null}layerType={layer.type}allowDuplicate={allowDuplicate}+ warning={globeWarning}onToggleEnableConfig={this._toggleEnableConfig}onToggleVisibility={this._toggleVisibility}onResetIsValid={this._resetIsValid}diff --git a/src/components/src/side-panel/map-manager.tsx b/src/components/src/side-panel/map-manager.tsxindex 9bb8818bd..5d5ea87be 100644--- a/src/components/src/side-panel/map-manager.tsx+++ b/src/components/src/side-panel/map-manager.tsx@@ -6,6 +6,7 @@ import React, {useState, useMemo, useCallback} from 'react';import {Button} from '../common/styled-components';import MapStyleSelectorFactory from './map-style-panel/map-style-selector';import LayerGroupSelectorFactory from './map-style-panel/map-layer-selector';+import GlobeConfigPanelFactory from './map-style-panel/globe-config-panel';import PanelTitleFactory from '../side-panel/panel-title';import {Add, Trash} from '../common/icons';@@ -13,10 +14,12 @@ import {PanelMeta} from './common/types';import {injectIntl, WrappedComponentProps} from 'react-intl';import {FormattedMessage} from '@kepler.gl/localization';import {MapStyle} from '@kepler.gl/reducers';-import {MapStyleActions} from '@kepler.gl/actions';+import {MapStyleActions, MapStateActions} from '@kepler.gl/actions';+import {MapState} from '@kepler.gl/types';export type MapManagerProps = {mapStyle: MapStyle;+ mapState?: MapState;mapStyleActions: {mapStyleChange: typeof MapStyleActions.mapStyleChange;mapConfigChange: typeof MapStyleActions.mapConfigChange;@@ -24,21 +27,27 @@ export type MapManagerProps = {setBackgroundColor: typeof MapStyleActions.setBackgroundColor;removeCustomMapStyle: typeof MapStyleActions.removeCustomMapStyle;};+ mapStateActions?: {+ globeConfigChange: typeof MapStateActions.globeConfigChange;+ };showAddMapStyleModal: () => void;panelMetadata: PanelMeta;} & WrappedComponentProps;-MapManagerFactory.deps = [MapStyleSelectorFactory, LayerGroupSelectorFactory, PanelTitleFactory];+MapManagerFactory.deps = [MapStyleSelectorFactory, LayerGroupSelectorFactory, PanelTitleFactory, GlobeConfigPanelFactory];function MapManagerFactory(MapStyleSelector: ReturnType<typeof MapStyleSelectorFactory>,LayerGroupSelector: ReturnType<typeof LayerGroupSelectorFactory>,- PanelTitle: ReturnType<typeof PanelTitleFactory>+ PanelTitle: ReturnType<typeof PanelTitleFactory>,+ GlobeConfigPanel: ReturnType<typeof GlobeConfigPanelFactory>) {const MapManager: React.FC<MapManagerProps> = ({mapStyle,+ mapState,intl,mapStyleActions,+ mapStateActions,showAddMapStyleModal,panelMetadata}) => {@@ -98,7 +107,7 @@ function MapManagerFactory(toggleActive={toggleSelecting}customMapStylesActions={customMapStylesActions}/>- {editableLayers.length ? (+ {editableLayers.length && !mapState?.globe?.enabled ? (<LayerGroupSelectorlayers={mapStyle.visibleLayerGroups}editableLayers={editableLayers}@@ -110,6 +119,12 @@ function MapManagerFactory(onBackgroundColorChange={mapStyleActions.setBackgroundColor}/>) : null}+ {mapState?.globe?.enabled && mapStateActions?.globeConfigChange && (+ <GlobeConfigPanel+ mapState={mapState}+ onGlobeConfigChange={mapStateActions.globeConfigChange}+ />+ )}</div></div>);diff --git a/src/components/src/side-panel/map-style-panel/globe-config-panel.tsx b/src/components/src/side-panel/map-style-panel/globe-config-panel.tsxnew file mode 100644index 000000000..3c0c21183--- /dev/null+++ b/src/components/src/side-panel/map-style-panel/globe-config-panel.tsx@@ -0,0 +1,354 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useCallback} from 'react';+import styled, {css} from 'styled-components';++import {MapState, RGBColor} from '@kepler.gl/types';+import {GlobeConfig} from '@kepler.gl/constants';+import {FormattedMessage} from '@kepler.gl/localization';++import {EyeSeen, EyeUnseen} from '../../common/icons';+import {+ PanelLabel,+ PanelContent,+ PanelLabelBold,+ PanelLabelWrapper+} from '../../common/styled-components';+import PanelHeaderActionFactory from '../panel-header-action';+import RangeSliderFactory from '../../common/range-slider';+import LayerGroupColorPickerFactory from './map-layer-group-color-picker';++const StyledGlobeConfigPanel = styled.div`+ padding-bottom: 6px;+`;++const StyledConfigRow = styled.div`+ margin-bottom: 10px;+ display: flex;+ justify-content: space-between;+ align-items: center;++ &:last-child {+ margin-bottom: 0;+ }++ .layer-group__visibility-toggle {+ margin-right: 12px;+ }+`;++const disableSlider = css`+ opacity: 0.5;+ pointer-events: none;+`;++const SliderWrapper = styled.div<{$enabled?: boolean}>`+ flex-grow: 1;+ margin-left: 4px;+ ${props => (props.$enabled ? '' : disableSlider)}+`;++// Slider rows (Day/Night, Sun Azimuth) put the label and the slider side by side.+// Give the label only the width its (short) text needs so the slider gets the+// rest of the row, matching studio-monorepo's usable slider width. The child+// indent is kept small (~half an eye-icon width) so the sub-row eye icon lines+// up close to the parent (atmosphere) row like it does in studio, rather than+// being pushed ~1.5 icon widths to the right.+const SliderRow = styled(StyledConfigRow)`+ align-items: center;++ .side-panel-panel__label-wrapper {+ flex: 0 0 auto;+ padding-left: 8px;+ white-space: nowrap;+ }+`;++const LayerLabel = styled(PanelLabelBold)<{$active: boolean}>`+ color: ${props => (props.$active ? props.theme.textColor : props.theme.labelColor)};+`;++const ChildRow = styled(StyledConfigRow)`+ .side-panel-panel__label-wrapper {+ padding-left: 8px;+ }+`;++export type GlobeConfigPanelProps = {+ mapState: MapState;+ onGlobeConfigChange: (config: Partial<GlobeConfig>) => void;+};++GlobeConfigPanelFactory.deps = [+ PanelHeaderActionFactory,+ RangeSliderFactory,+ LayerGroupColorPickerFactory+];++function GlobeConfigPanelFactory(+ PanelHeaderAction: ReturnType<typeof PanelHeaderActionFactory>,+ RangeSlider: ReturnType<typeof RangeSliderFactory>,+ LayerGroupColorPicker: ReturnType<typeof LayerGroupColorPickerFactory>+) {+ const GlobeConfigPanel: React.FC<GlobeConfigPanelProps> = ({mapState, onGlobeConfigChange}) => {+ const globeConfig = mapState.globe?.config;++ const onToggle = useCallback(+ (+ key: keyof GlobeConfig,+ childKeys?: (keyof GlobeConfig)[],+ parentKey?: keyof GlobeConfig+ ) => {+ if (!globeConfig) return;+ const newValue = !globeConfig[key];+ const update: Partial<GlobeConfig> = {[key]: newValue};+ if (childKeys) {+ childKeys.forEach(childKey => {+ update[childKey] = newValue as any;+ });+ }+ if (parentKey && newValue === true) {+ update[parentKey] = true as any;+ }+ onGlobeConfigChange(update);+ },+ [globeConfig, onGlobeConfigChange]+ );++ const onSliderChange = useCallback(+ (key: keyof GlobeConfig, value: number[]) => {+ onGlobeConfigChange({[key]: value[1]} as Partial<GlobeConfig>);+ },+ [onGlobeConfigChange]+ );++ const onColorChange = useCallback(+ (key: keyof GlobeConfig, color: RGBColor) => {+ onGlobeConfigChange({[key]: color} as Partial<GlobeConfig>);+ },+ [onGlobeConfigChange]+ );++ if (!mapState.globe?.enabled || !globeConfig) {+ return null;+ }++ return (+ <StyledGlobeConfigPanel>+ <PanelLabel>+ <FormattedMessage id="mapManager.globeLayers" />+ </PanelLabel>+ <PanelContent>+ {/* Atmosphere */}+ <StyledConfigRow>+ <PanelLabelWrapper>+ <PanelHeaderAction+ className="layer-group__visibility-toggle"+ id="globe-atmosphere-toggle"+ tooltip={globeConfig.atmosphere ? 'tooltip.hide' : 'tooltip.show'}+ onClick={() => onToggle('atmosphere', ['terminator', 'azimuth'])}+ IconComponent={globeConfig.atmosphere ? EyeSeen : EyeUnseen}+ active={globeConfig.atmosphere}+ flush+ />+ <LayerLabel $active={globeConfig.atmosphere}>+ <FormattedMessage id="mapLayers.atmosphere" />+ </LayerLabel>+ </PanelLabelWrapper>+ </StyledConfigRow>++ {/* Terminator (child of atmosphere) */}+ <SliderRow>+ <PanelLabelWrapper>+ <PanelHeaderAction+ className="layer-group__visibility-toggle"+ id="globe-terminator-toggle"+ tooltip={globeConfig.terminator ? 'tooltip.hide' : 'tooltip.show'}+ onClick={() => onToggle('terminator', undefined, 'atmosphere')}+ IconComponent={globeConfig.terminator ? EyeSeen : EyeUnseen}+ active={globeConfig.terminator && globeConfig.atmosphere}+ flush+ />+ <LayerLabel $active={globeConfig.terminator && globeConfig.atmosphere}>+ <FormattedMessage id="mapLayers.terminator" />+ </LayerLabel>+ </PanelLabelWrapper>+ <SliderWrapper $enabled={globeConfig.terminator && globeConfig.atmosphere}>+ <RangeSlider+ range={[0, 1]}+ value0={0}+ value1={globeConfig.terminatorOpacity}+ step={0.01}+ isRanged={false}+ onChange={val => onSliderChange('terminatorOpacity', val)}+ inputTheme="secondary"+ showInput+ />+ </SliderWrapper>+ </SliderRow>++ {/* Sun Azimuth (child of atmosphere) */}+ <SliderRow>+ <PanelLabelWrapper>+ <PanelHeaderAction+ className="layer-group__visibility-toggle"+ id="globe-azimuth-toggle"+ tooltip={globeConfig.azimuth ? 'tooltip.hide' : 'tooltip.show'}+ onClick={() => onToggle('azimuth', undefined, 'atmosphere')}+ IconComponent={globeConfig.azimuth ? EyeSeen : EyeUnseen}+ active={globeConfig.azimuth && globeConfig.atmosphere}+ flush+ />+ <LayerLabel $active={globeConfig.azimuth && globeConfig.atmosphere}>+ <FormattedMessage id="mapLayers.sunAzimuth" />+ </LayerLabel>+ </PanelLabelWrapper>+ <SliderWrapper $enabled={globeConfig.azimuth && globeConfig.atmosphere}>+ <RangeSlider+ range={[0, 360]}+ value0={0}+ value1={globeConfig.azimuthAngle}+ step={1}+ isRanged={false}+ onChange={val => onSliderChange('azimuthAngle', val)}+ inputTheme="secondary"+ showInput+ />+ </SliderWrapper>+ </SliderRow>++ {/* Basemap */}+ <StyledConfigRow>+ <PanelLabelWrapper>+ <PanelHeaderAction+ className="layer-group__visibility-toggle"+ id="globe-basemap-toggle"+ tooltip={globeConfig.basemap ? 'tooltip.hide' : 'tooltip.show'}+ onClick={() => onToggle('basemap', ['labels', 'adminLines', 'water'])}+ IconComponent={globeConfig.basemap ? EyeSeen : EyeUnseen}+ active={globeConfig.basemap}+ flush+ />+ <LayerLabel $active={globeConfig.basemap}>+ <FormattedMessage id="mapLayers.basemap" />+ </LayerLabel>+ </PanelLabelWrapper>+ </StyledConfigRow>++ {/* Labels (child of basemap) */}+ <ChildRow>+ <PanelLabelWrapper>+ <PanelHeaderAction+ className="layer-group__visibility-toggle"+ id="globe-labels-toggle"+ tooltip={globeConfig.labels ? 'tooltip.hide' : 'tooltip.show'}+ onClick={() => onToggle('labels', undefined, 'basemap')}+ IconComponent={globeConfig.labels ? EyeSeen : EyeUnseen}+ active={globeConfig.labels && globeConfig.basemap}+ flush+ />+ <LayerLabel $active={globeConfig.labels && globeConfig.basemap}>+ <FormattedMessage id="mapLayers.label" />+ </LayerLabel>+ </PanelLabelWrapper>+ <LayerGroupColorPicker+ slug="globe-labels"+ color={globeConfig.labelsColor}+ onColorChange={(color: RGBColor) => onColorChange('labelsColor', color)}+ extraMarginRight={false}+ disabled={!(globeConfig.labels && globeConfig.basemap)}+ />+ </ChildRow>++ {/* Admin Lines (child of basemap) */}+ <ChildRow>+ <PanelLabelWrapper>+ <PanelHeaderAction+ className="layer-group__visibility-toggle"+ id="globe-admin-toggle"+ tooltip={globeConfig.adminLines ? 'tooltip.hide' : 'tooltip.show'}+ onClick={() => onToggle('adminLines', undefined, 'basemap')}+ IconComponent={globeConfig.adminLines ? EyeSeen : EyeUnseen}+ active={globeConfig.adminLines && globeConfig.basemap}+ flush+ />+ <LayerLabel $active={globeConfig.adminLines && globeConfig.basemap}>+ <FormattedMessage id="mapLayers.adminBorders" />+ </LayerLabel>+ </PanelLabelWrapper>+ <LayerGroupColorPicker+ slug="globe-admin"+ color={globeConfig.adminLinesColor}+ onColorChange={(color: RGBColor) => onColorChange('adminLinesColor', color)}+ extraMarginRight={false}+ disabled={!(globeConfig.adminLines && globeConfig.basemap)}+ />+ </ChildRow>++ {/* Water (child of basemap) */}+ <ChildRow>+ <PanelLabelWrapper>+ <PanelHeaderAction+ className="layer-group__visibility-toggle"+ id="globe-water-toggle"+ tooltip={globeConfig.water ? 'tooltip.hide' : 'tooltip.show'}+ onClick={() => onToggle('water', undefined, 'basemap')}+ IconComponent={globeConfig.water ? EyeSeen : EyeUnseen}+ active={globeConfig.water && globeConfig.basemap}+ flush+ />+ <LayerLabel $active={globeConfig.water && globeConfig.basemap}>+ <FormattedMessage id="mapLayers.water" />+ </LayerLabel>+ </PanelLabelWrapper>+ <LayerGroupColorPicker+ slug="globe-water"+ color={globeConfig.waterColor}+ onColorChange={(color: RGBColor) => onColorChange('waterColor', color)}+ extraMarginRight={false}+ disabled={!(globeConfig.water && globeConfig.basemap)}+ />+ </ChildRow>++ {/* Globe Surface (always visible, only has color) */}+ <StyledConfigRow>+ <PanelLabelWrapper>+ <LayerLabel $active={true} style={{marginLeft: '28px'}}>+ <FormattedMessage id="mapLayers.surface" />+ </LayerLabel>+ </PanelLabelWrapper>+ <LayerGroupColorPicker+ slug="globe-surface"+ color={globeConfig.surfaceColor}+ onColorChange={(color: RGBColor) => onColorChange('surfaceColor', color)}+ extraMarginRight={false}+ disabled={false}+ />+ </StyledConfigRow>++ {/* Background (empty space around the globe, always visible) */}+ <StyledConfigRow>+ <PanelLabelWrapper>+ <LayerLabel $active={true} style={{marginLeft: '28px'}}>+ <FormattedMessage id="mapLayers.background" />+ </LayerLabel>+ </PanelLabelWrapper>+ <LayerGroupColorPicker+ slug="globe-background"+ color={globeConfig.backgroundColor}+ onColorChange={(color: RGBColor) => onColorChange('backgroundColor', color)}+ extraMarginRight={false}+ disabled={false}+ />+ </StyledConfigRow>+ </PanelContent>+ </StyledGlobeConfigPanel>+ );+ };++ GlobeConfigPanel.displayName = 'GlobeConfigPanel';+ return GlobeConfigPanel;+}++export default GlobeConfigPanelFactory;diff --git a/src/components/src/types.ts b/src/components/src/types.tsindex 77c18425c..cf70fc9fd 100644--- a/src/components/src/types.ts+++ b/src/components/src/types.ts@@ -4,7 +4,7 @@import React, {HTMLAttributes, PropsWithChildren} from 'react';import {MapStyle} from '@kepler.gl/reducers';import {Layer, LayerClassesType} from '@kepler.gl/layers';-import {Filter, InteractionConfig, UiState, LayerOrder} from '@kepler.gl/types';+import {Filter, InteractionConfig, MapState, UiState, LayerOrder} from '@kepler.gl/types';import {MapStyleActions,@@ -34,6 +34,7 @@ export type SidePanelProps = {layerClasses: LayerClassesType;layerOrder: LayerOrder;mapStyle: MapStyle;+ mapState?: MapState;mapInfo: {title?: string; description?: string};width: number;datasets: Datasets;diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.tsindex 3d32c2c3d..c799518b4 100644--- a/src/constants/src/default-settings.ts+++ b/src/constants/src/default-settings.ts@@ -1344,6 +1344,104 @@ export const MAP_CONTROLS = keyMirror({aiAssistant: null});+export enum MapViewMode {+ MODE_2D = 'MODE_2D',+ MODE_3D = 'MODE_3D',+ MODE_GLOBE = 'MODE_GLOBE'+}++/**+ * Minimum zoom level allowed in globe mode. Negative values let the user zoom+ * out further than the web-mercator default of 0, so the whole globe can be+ * pulled back to appear smaller on screen.+ */+export const GLOBE_MIN_ZOOM = 2;++/**+ * Maximum zoom in globe mode.+ *+ * TODO: investigate further. Past this level the globe basemap breaks down in+ * deck.gl 9.x: the vector basemap tileset (mapbox-streets vector tiles) stops+ * loading / renders as empty rectangles, and there are interaction issues on+ * zoom in and panning (the camera drifts). Capping zoom here keeps the basemap+ * and interactions coherent until the underlying tile/controller issue is fixed.+ */+export const GLOBE_MAX_ZOOM = 12;++/**+ * Maximum absolute center latitude allowed in globe mode. Constrains the camera+ * target to a band around the equator so the view can't be centered on the+ * poles (deck.gl's default clamps to ~85°, which lets the camera stare straight+ * down at a pole). Applies symmetrically to the northern and southern hemisphere.+ */+export const GLOBE_MAX_LATITUDE = 75;++export type GlobeConfig = {+ atmosphere: boolean;+ azimuth: boolean;+ azimuthAngle: number;+ terminator: boolean;+ terminatorOpacity: number;+ basemap: boolean;+ labels: boolean;+ labelsColor: [number, number, number];+ adminLines: boolean;+ adminLinesColor: [number, number, number];+ water: boolean;+ waterColor: [number, number, number];+ surfaceColor: [number, number, number];+ surface: boolean;+ backgroundColor: [number, number, number];+};++export type Globe = {+ enabled: boolean;+ config: GlobeConfig;+};++export const DEFAULT_GLOBE_CONFIG: GlobeConfig = {+ atmosphere: true,+ azimuth: false,+ azimuthAngle: 45,+ terminator: true,+ terminatorOpacity: 0.35,+ basemap: true,+ labels: false,+ labelsColor: [114.75, 114.75, 114.75],+ adminLines: true,+ adminLinesColor: [40, 63, 93],+ water: true,+ waterColor: [17, 35, 48],+ surface: true,+ surfaceColor: [9, 16, 29],+ // Color of the empty space rendered around the globe (deck.gl clear color).+ // Matches the previous hardcoded clear color [0.015, 0.035, 0.065] in 0-1 space.+ backgroundColor: [4, 9, 17]+};++export const GLOBE_SUPPORTED_LAYERS: Record<string, boolean> = {+ point: true,+ arc: true,+ grid: true,+ hexagon: true,+ geojson: true,+ cluster: true,+ icon: true,+ hexagonId: true,+ '3D': true,+ vectorTile: true,+ hexTile: true,+ line: true,+ trip: true,+ rasterTile: true,+ heatmap: true,+ s2: false,+ tile3d: false,+ // Flow arrows are flat quads in common space (equatorial plane) and collapse when+ // viewed edge-on on the globe, so the flow layer is not supported in Globe mode.+ flow: false+};+export enum MapSplitMode {SINGLE_MAP = 'SINGLE_MAP',DUAL_MAP = 'DUAL_MAP',diff --git a/src/deckgl-layers/package.json b/src/deckgl-layers/package.jsonindex a7914d9af..a659e578c 100644--- a/src/deckgl-layers/package.json+++ b/src/deckgl-layers/package.json@@ -34,6 +34,7 @@"@deck.gl/core": "^9.3.1","@deck.gl/geo-layers": "^9.3.1","@deck.gl/layers": "^9.3.1",+ "@deck.gl/mesh-layers": "^9.3.1","@kepler.gl/constants": "3.3.0-alpha.3","@kepler.gl/types": "3.3.0-alpha.3","@kepler.gl/utils": "3.3.0-alpha.3",@@ -45,6 +46,8 @@"@luma.gl/webgl": "^9.3.2","@mapbox/geo-viewport": "^0.4.1","@mapbox/vector-tile": "^1.3.1",+ "@math.gl/core": "^4.1.0",+ "@math.gl/sun": "^4.1.0","@math.gl/web-mercator": "^4.1.0","@types/d3-array": "^2.8.0","@types/geojson": "^7946.0.8",diff --git a/src/deckgl-layers/src/column-layer/enhanced-column-layer.ts b/src/deckgl-layers/src/column-layer/enhanced-column-layer.tsindex 82e420363..a3bee3f31 100644--- a/src/deckgl-layers/src/column-layer/enhanced-column-layer.ts+++ b/src/deckgl-layers/src/column-layer/enhanced-column-layer.ts@@ -6,6 +6,19 @@ import {UNIT} from '@deck.gl/core';import {editShader} from '../';+// deck.gl 9 / luma 9 sets custom uniforms via UBO-backed shader modules (Model has+// no setUniforms). This module exposes the globe-mode flag to the shader.+const globeModeUniforms = {+ name: 'globeMode',+ vs: `layout(std140) uniform globeModeUniforms {+ float globeMode;+} globeModeProps;+`,+ uniformTypes: {+ globeMode: 'f32'+ }+} as const;+function addInstanceCoverage(vs: string) {const addDecl = editShader(vs,@@ -23,6 +36,16 @@ function addInstanceCoverage(vs: string) {);}+function addGlobeScaling(vs: string) {+ return editShader(+ vs,+ 'hexagon cell vs globe scale mod',+ 'vec2 offset = (rotationMatrix * positions.xy * strokeOffsetRatio + column.offset) * dotRadius;',+ `float radiusGlobeMod = globeModeProps.globeMode > 0.5 ? sin((90.0 - abs(geometry.worldPosition.y)) * PI / 180.0) * PI : 1.0;+ vec2 offset = (rotationMatrix * positions.xy * strokeOffsetRatio + column.offset) * dotRadius * radiusGlobeMod;`+ );+}+type EnhancedColumnLayerProps = ColumnLayerProps<any> & {strokeOpacity: number;};@@ -31,9 +54,12 @@ class EnhancedColumnLayer extends ColumnLayer<any, EnhancedColumnLayerProps> {getShaders() {const shaders = super.getShaders();+ const vs = addGlobeScaling(addInstanceCoverage(shaders.vs));+return {...shaders,- vs: addInstanceCoverage(shaders.vs)+ vs,+ modules: [...(shaders.modules || []), globeModeUniforms]};}@@ -67,6 +93,8 @@ class EnhancedColumnLayer extends ColumnLayer<any, EnhancedColumnLayerProps> {const wireframeModel = this.state.wireframeModel;const {fillVertexCount, edgeDistance} = this.state;+ const globeMode = (this.context.viewport as any).resolution ? 1.0 : 0.0;+const columnProps = {radius,angle: (angle / 180) * Math.PI,@@ -85,14 +113,16 @@ class EnhancedColumnLayer extends ColumnLayer<any, EnhancedColumnLayerProps> {if (extruded && wireframe && wireframeModel) {wireframeModel.shaderInputs.setProps({- column: {...columnProps, isStroke: true}+ column: {...columnProps, isStroke: true},+ globeMode: {globeMode}});wireframeModel.draw(this.context.renderPass);}if (filled && fillModel) {fillModel.setVertexCount(fillVertexCount);fillModel.shaderInputs.setProps({- column: {...columnProps, isStroke: false}+ column: {...columnProps, isStroke: false},+ globeMode: {globeMode}});fillModel.draw(this.context.renderPass);}@@ -100,7 +130,8 @@ class EnhancedColumnLayer extends ColumnLayer<any, EnhancedColumnLayerProps> {fillModel.setVertexCount((fillVertexCount * 2) / 3);fillModel.shaderInputs.setProps({column: {...columnProps, isStroke: true},- layer: {opacity: strokeOpacity ?? this.props.opacity}+ layer: {opacity: strokeOpacity ?? this.props.opacity},+ globeMode: {globeMode}});fillModel.draw(this.context.renderPass);// Restore original vertex count and opacity so subsequent passes are unaffecteddiff --git a/src/deckgl-layers/src/globe/atmosphere-layer.ts b/src/deckgl-layers/src/globe/atmosphere-layer.tsnew file mode 100644index 000000000..627e6976c--- /dev/null+++ b/src/deckgl-layers/src/globe/atmosphere-layer.ts@@ -0,0 +1,333 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// Shaders ported from iTowns, based on Sean O'Neil's approach in GPU Gems 2+// SEE: https://github.com/iTowns/itowns/blob/master/src/Core/Prefab/Globe/Atmosphere.js+// SEE: https://developer.nvidia.com/gpugems/gpugems2/part-ii-shading-lighting-and-shadows/chapter-16-accurate-atmospheric-scattering++import {COORDINATE_SYSTEM} from '@deck.gl/core';+import {SimpleMeshLayer} from '@deck.gl/mesh-layers';+import {SphereGeometry} from '@luma.gl/engine';+import {Vector3} from '@math.gl/core';+import {getSunPosition} from '@math.gl/sun';++import type {GlobeConfig} from '@kepler.gl/constants';++const toRadians = (degrees: number): number => (degrees * Math.PI) / 180;++const angleToVec = (angle: number): [number, number, number] => {+ return [Math.sin(angle), Math.cos(angle), 0];+};++const angleToSunPos = (angle: number): number[] => {+ return new Vector3(angleToVec(angle)).normalize() as unknown as number[];+};++const GLOBE_MESH_INNER = new SphereGeometry({+ radius: 6.4e6,+ nlat: 100,+ nlong: 100+});++const GLOBE_MESH_OUTER = new SphereGeometry({+ radius: 6.7e6,+ nlat: 100,+ nlong: 100+});++const [lon, lat] = [0, 90];+const sunPosNow = getSunPosition(Date.now(), lat, lon);+const v3SunPosNow = angleToSunPos(sunPosNow.azimuth + Math.PI);++const NUM_SAMPLE_RAYS = 3;++const ATMOSPHERE_UNIFORMS = {+ v3SunPos: v3SunPosNow,+ exposure: 2,+ fSamples: 3,+ g: -0.65,+ fKrESun: 0.00025 * 20,+ fKmESun: 0.0001 * 20,+ fKr4PI: 0.00025 * 4 * Math.PI,+ fKm4PI: 0.0001 * 4 * Math.PI,+ fScaleDepth: 0.25,+ fInnerRadius: 258,+ fOuterRadius: 265,+ fTerminatorAttenuateFactor: 0.8,+ fTerminatorOpacityFactor: 1+};++type AtmosphereLayerProps = {+ config: GlobeConfig;+};++export class AtmosphereLayerRealistic extends SimpleMeshLayer<any, AtmosphereLayerProps> {+ static layerName = 'AtmosphereLayerRealistic';++ draw({uniforms}: {uniforms: object}): void {+ const {config} = this.props;+ const model = this.state.model;+ if (model) {+ (model as any).props.uniforms = {+ ...(model as any).props.uniforms,+ ...ATMOSPHERE_UNIFORMS,+ fTerminatorOpacityFactor: config.terminator ? config.terminatorOpacity : 0,+ v3SunPos: config.azimuth ? angleToSunPos(toRadians(config.azimuthAngle)) : v3SunPosNow+ };+ }+ super.draw({uniforms});+ }++ getShaders(): any {+ return {+ ...super.getShaders(),+ inject: {+ 'fs:#decl': `+ uniform vec3 v3SunPos;++ uniform float g;+ uniform float exposure;++ uniform float fSamples;++ uniform float fInnerRadius;+ uniform float fOuterRadius;+ uniform float fKrESun;+ uniform float fKmESun;+ uniform float fKr4PI;+ uniform float fKm4PI;+ uniform float fScaleDepth;++ uniform float fTerminatorAttenuateFactor;+ uniform float fTerminatorOpacityFactor;++ const int nSamples = ${NUM_SAMPLE_RAYS};++ float scale(float fCos) {+ float x = 1.0 - fCos;+ return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.8 + x*5.25))));+ }+ `,+ 'fs:#main-end': `+ vec3 v3CameraPos = cameraPosition;+ vec3 v3Pos = position_commonspace.xyz;++ float g2 = g * g;++ vec3 v3InvWavelength = vec3(1.0 / pow(0.650, 4.0), 1.0 / pow(0.570, 4.0), 1.0 / pow(0.475, 4.0));++ float fInnerRadius2 = fInnerRadius * fInnerRadius;+ float fOuterRadius2 = fOuterRadius * fOuterRadius;+ float fScale = 1.0 / (fOuterRadius - fInnerRadius);+ float fScaleOverScaleDepth = 1.0 / (fOuterRadius - fInnerRadius) / fScaleDepth;++ float cameraHeight2 = length(v3CameraPos) * length(v3CameraPos);++ vec3 v3Ray = v3Pos - v3CameraPos;+ float fFar = length(v3Ray);+ v3Ray /= fFar;++ float B = 2.0 * dot(v3CameraPos, v3Ray);+ float C = cameraHeight2 - fOuterRadius2;+ float fDet = max(0.0, B*B - 4.0 * C);+ float fNear = 0.5 * (-B - sqrt(fDet));++ vec3 v3Start = v3CameraPos + v3Ray * fNear;+ fFar -= fNear;++ float fDepth = exp((fInnerRadius - fOuterRadius) / fScaleDepth);+ float fCameraAngle = dot(-v3Ray, v3Pos) / length(v3Pos);+ float fLightAngle = dot(v3SunPos, v3Pos) / length(v3Pos);+ float fCameraScale = scale(fCameraAngle);+ float fLightScale = scale(fLightAngle);+ float fCameraOffset = fDepth*fCameraScale;+ float fTemp = (fLightScale + fCameraScale);++ float fSampleLength = fFar / fSamples;+ float fScaledLength = fSampleLength * fScale;+ vec3 v3SampleRay = v3Ray * fSampleLength;+ vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5;++ vec3 v3FrontColor = vec3(0.0, 0.0, 0.0);+ vec3 v3Attenuate = vec3(0.0, 0.0, 0.0);+ for(int i=0; i<nSamples; i++)+ {+ float fHeight = length(v3SamplePoint);+ float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fHeight));+ float fScatter = fDepth*fTemp - fCameraOffset;+ v3Attenuate = exp(-fScatter * (v3InvWavelength * fKr4PI + fKm4PI));+ v3FrontColor += v3Attenuate * (fDepth * fScaledLength);+ v3SamplePoint += v3SampleRay;+ }++ vec3 c0 = v3Attenuate;+ vec3 c1 = v3FrontColor * (v3InvWavelength * fKrESun + fKmESun);++ fragColor = vec4(c1, 1.0 - c0 * fTerminatorAttenuateFactor);+ fragColor.a *= fTerminatorOpacityFactor;+ `,+ 'fs:DECKGL_FILTER_COLOR': ``+ }+ };+ }+}++export class AtmosphereSkyLayerRealistic extends SimpleMeshLayer<any, AtmosphereLayerProps> {+ static layerName = 'AtmosphereSkyLayerRealistic';++ draw({uniforms}: {uniforms: object}): void {+ const {config} = this.props;+ const model = this.state.model;+ if (model) {+ (model as any).props.uniforms = {+ ...(model as any).props.uniforms,+ ...ATMOSPHERE_UNIFORMS,+ v3SunPos: config.azimuth ? angleToSunPos(toRadians(config.azimuthAngle)) : v3SunPosNow+ };+ }+ super.draw({uniforms});+ }++ getShaders(): any {+ return {+ ...super.getShaders(),+ inject: {+ 'fs:#decl': `+ uniform vec3 v3SunPos;++ uniform float g;+ uniform float exposure;++ uniform float fSamples;++ uniform float fInnerRadius;+ uniform float fOuterRadius;+ uniform float fKrESun;+ uniform float fKmESun;+ uniform float fKr4PI;+ uniform float fKm4PI;+ uniform float fScaleDepth;++ const int nSamples = ${NUM_SAMPLE_RAYS};++ float scale(float fCos) {+ float x = 1.0 - fCos;+ return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.8 + x*5.25))));+ }++ float getMiePhase(float fCos, float fCos2, float g, float g2) {+ return 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos2) / pow(1.0 + g2 - 2.0 * g * fCos, 1.5);+ }++ float getRayleighPhase(float fCos2) {+ return 0.75 + 0.75 * fCos2;+ }+ `,+ 'fs:#main-end': `+ vec3 v3CameraPos = cameraPosition;+ vec3 v3Pos = position_commonspace.xyz;++ float g2 = g * g;++ vec3 v3InvWavelength = vec3(1.0 / pow(0.650, 4.0), 1.0 / pow(0.570, 4.0), 1.0 / pow(0.475, 4.0));++ float fInnerRadius2 = fInnerRadius * fInnerRadius;+ float fOuterRadius2 = fOuterRadius * fOuterRadius;+ float fScale = 1.0 / (fOuterRadius - fInnerRadius);+ float fScaleOverScaleDepth = 1.0 / (fOuterRadius - fInnerRadius) / fScaleDepth;++ float cameraHeight2 = length(v3CameraPos) * length(v3CameraPos);++ vec3 v3Ray = v3Pos - v3CameraPos;+ float fFar = length(v3Ray);+ v3Ray /= fFar;++ float B = 2.0 * dot(v3CameraPos, v3Ray);+ float C = cameraHeight2 - fOuterRadius2;+ float fDet = max(0.0, B*B - 4.0 * C);+ float fNear = 0.5 * (-B - sqrt(fDet));++ vec3 v3Start = v3CameraPos + v3Ray * fNear;+ fFar -= fNear;+ float fStartAngle = dot(v3Ray, v3Start) / fOuterRadius;+ float fStartDepth = exp(-1.0 / fScaleDepth);+ float fStartOffset = fStartDepth * scale(fStartAngle);++ float fSampleLength = fFar / fSamples;+ float fScaledLength = fSampleLength * fScale;+ vec3 v3SampleRay = v3Ray * fSampleLength;+ vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5;++ vec3 v3FrontColor = vec3(0.0, 0.0, 0.0);+ for(int i=0; i<nSamples; i++)+ {+ float fHeight = length(v3SamplePoint);+ float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fHeight));+ float fLightAngle = dot(v3SunPos, v3SamplePoint) / fHeight;+ float fCameraAngle = dot(v3Ray, v3SamplePoint) / fHeight;+ float fScatter = (fStartOffset + fDepth * (scale(fLightAngle) - scale(fCameraAngle)));+ vec3 v3Attenuate = exp(-fScatter * (v3InvWavelength * fKr4PI + fKm4PI));++ v3FrontColor += v3Attenuate * (fDepth * fScaledLength);+ v3SamplePoint += v3SampleRay;+ }++ vec3 c0 = v3FrontColor * (v3InvWavelength * fKrESun);+ vec3 c1 = v3FrontColor * fKmESun;++ vec3 v3Direction = v3CameraPos - v3Pos;++ float fCos = dot(v3SunPos, v3Direction) / length(v3Direction);+ float fCos2 = fCos * fCos;++ vec3 skyColor = getRayleighPhase(fCos2) * c0 + getMiePhase(fCos, fCos2, g, g2) * c1;++ fragColor = vec4(skyColor, 1.0);+ fragColor.a = fragColor.b;+ `,+ 'fs:DECKGL_FILTER_COLOR': ``+ }+ };+ }+}++const ATMOSPHERE_PARAMETERS = {+ depthTest: false,+ blendFunc: [0x0302, 0x0303, 1, 0x0303], // SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE_MINUS_SRC_ALPHA+ blendEquation: [0x8006, 0x8006] // FUNC_ADD+};++const ATMOSPHERE_SKY_PARAMETERS = {+ cullFace: 0x0404, // GL.FRONT+ depthMask: false,+ blendFunc: [0x0302, 0x0303, 1, 0x0303],+ blendEquation: [0x8006, 0x8006]+};++export const getGlobeAtmosphereLayer = ({config}: {config: GlobeConfig}) => {+ return new AtmosphereLayerRealistic({+ id: 'atmosphere',+ data: [[0, 0, 0]],+ config,+ coordinateOrigin: [0, 0, 0],+ coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,+ getPosition: ((d: number[]) => d) as any,+ getColor: [0, 0, 0],+ mesh: GLOBE_MESH_INNER,+ parameters: ATMOSPHERE_PARAMETERS+ });+};++export const getGlobeAtmosphereSkyLayer = ({config}: {config: GlobeConfig}) => {+ return new AtmosphereSkyLayerRealistic({+ id: 'atmosphere-sky',+ data: [[0, 0, 0]],+ config,+ coordinateOrigin: [0, 0, 0],+ coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,+ getPosition: ((d: number[]) => d) as any,+ getColor: [0, 0, 0],+ mesh: GLOBE_MESH_OUTER,+ parameters: ATMOSPHERE_SKY_PARAMETERS+ });+};diff --git a/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.ts b/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.tsnew file mode 100644index 000000000..4dbb7bdb2--- /dev/null+++ b/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// @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.+//+// Ported from studio-monorepo's EnhancedMultiIconLayer. 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);+ }+ }+ }+`;++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}`+ }+ };+ }+}diff --git a/src/deckgl-layers/src/globe/globe-depth-disk-layer.ts b/src/deckgl-layers/src/globe/globe-depth-disk-layer.tsnew file mode 100644index 000000000..ad23e0481--- /dev/null+++ b/src/deckgl-layers/src/globe/globe-depth-disk-layer.ts@@ -0,0 +1,156 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {COORDINATE_SYSTEM} from '@deck.gl/core';+import {SimpleMeshLayer} from '@deck.gl/mesh-layers';+import {PlaneGeometry} from '@luma.gl/engine';+import {Vector3} from '@math.gl/core';++import {editShader} from '../layer-utils/shader-utils';+import type {RGBColor} from '@kepler.gl/types';++// luma.gl 9's PlaneGeometry ignores `radius`; pass explicit type/xlen/ylen so we+// get a [-1, 1] quad (a `radius: 1` plane would only span [-0.5, 0.5]).+const PLANE_GEOMETRY = new PlaneGeometry({+ type: 'x,y',+ xlen: 2,+ ylen: 2+} as any);++const DEPTH_DISK_PARAMETERS = {+ // Depth writes only happen with depthTest enabled. The disk is opaque-black-ish+ // and used purely to fill the depth buffer so far-side geometry (arcs/lines) is+ // occluded by the planet.+ depthTest: true,+ cull: false+};++// Earth radius in meters. The disk geometry is a [-1, 1] plane; we scale it into+// METERS in the vertex shader (like the atmosphere SphereGeometry, whose radius is+// ~6.4e6 m) and let SimpleMeshLayer's stock projection map it onto the globe —+// exactly the working path the atmosphere mesh layers use.+const DEPTH_DISK_FULL_RADIUS = 6.371e6;++// Globe common space uses GLOBE_RADIUS = 256 units (see deck.gl's project_globe_).+// The disk orientation math is done in that 256-unit common space (matching+// viewport.cameraPosition), then the resulting radius/shift ratios are converted to+// meters for the shader, since the disk geometry is expressed in meters.+const GLOBE_COMMON_RADIUS = 256;++/**+ * Creates a view-oriented disk positioned along the direction from the globe's center to the camera.+ * The disk is a cross-section of the globe between the front (visible) and back side, and it fills+ * the depth buffer so anything on the far side of the globe (e.g. arcs/lines) is depth-culled and+ * hidden behind the planet.+ */+export class GlobeDepthDiskLayer extends SimpleMeshLayer<any> {+ static layerName = 'GlobeDepthDiskLayer';++ getShaders(): any {+ const shaders = super.getShaders();++ // Override the local `pos` computation: reorient the flat [-1,1] plane to face+ // the camera, scale it to meters, and shift it toward the camera along the view+ // axis so it sits at the globe's silhouette cross-section. The stock+ // project_position_to_clipspace call is left untouched so the disk projects onto+ // the globe through the exact same (working) path the atmosphere mesh layers use.+ const vs = editShader(+ shaders.vs,+ 'globe depth disk vs',+ 'vec3 pos = (instanceModelMatrix * positions) * simpleMesh.sizeScale + instanceTranslation;',+ `mat3 u_matDepthDiskOrientation = mat3(+ u_depthDiskOrientCol0,+ u_depthDiskOrientCol1,+ u_depthDiskOrientCol2+ );+ vec3 pos = (u_matDepthDiskOrientation * positions) * u_depthDiskRadius;+ vDepthDiskPos = pos;+ pos = pos + u_directionToCamera * u_depthDiskShift;+ `+ );++ const inject = {+ 'vs:#decl': `+ uniform vec3 u_depthDiskOrientCol0;+ uniform vec3 u_depthDiskOrientCol1;+ uniform vec3 u_depthDiskOrientCol2;+ uniform vec3 u_directionToCamera;+ uniform float u_depthDiskShift;+ uniform float u_depthDiskRadius;+ out vec3 vDepthDiskPos;+ `,+ 'fs:#decl': `+ uniform float u_depthDiskRadius;+ in vec3 vDepthDiskPos;+ `,+ 'fs:#main-start': `+ if (length(vDepthDiskPos) > u_depthDiskRadius) {+ discard;+ }+ `+ };++ return {+ ...shaders,+ vs,+ inject+ };+ }++ draw({uniforms}: {uniforms: object}): void {+ const normalizedRadius = GLOBE_COMMON_RADIUS;++ const camPos = new Vector3((this.context.viewport as any).cameraPosition);+ const camDir = camPos.clone().normalize();+ const topDir = new Vector3(0, 0, 1);+ const sideDir = camDir.clone().cross(topDir);+ const sidePoint = sideDir.clone().scale(normalizedRadius);++ const camToSide = sidePoint.clone().subtract(camPos).normalize();+ const adjustedSidePoint = camToSide.cross(topDir).scale(-normalizedRadius);++ const shiftToCamera = camDir.dot(adjustedSidePoint);+ const adjustedDiskRadius = Math.sqrt(+ normalizedRadius * normalizedRadius - shiftToCamera * shiftToCamera+ );++ // Camera-facing orientation: the plane's local X/Y axes map to world `right`/`up`+ // (both perpendicular to the camera direction), and local Z maps to `forward`.+ // Columns are handed to the shader as vec3s to avoid Matrix3 row/column ambiguity.+ const forward = camDir.clone();+ const right = topDir.clone().cross(forward).normalize();+ const up = forward.clone().cross(right).normalize();++ const model = this.state.model;+ if (model) {+ // Use the same uniform-delivery mechanism as the (working) atmosphere layers:+ // raw `uniform` declarations + assignment to model.props.uniforms.+ (model as any).props.uniforms = {+ ...(model as any).props.uniforms,+ // mat3(col0, col1, col2) in GLSL is column-major; mat3 * (x, y, 0) = x*right + y*up.+ u_depthDiskOrientCol0: [right[0], right[1], right[2]],+ u_depthDiskOrientCol1: [up[0], up[1], up[2]],+ u_depthDiskOrientCol2: [forward[0], forward[1], forward[2]],+ u_directionToCamera: [camDir[0], camDir[1], camDir[2]],+ // Convert the common-space (256-unit) radius/shift to meters, since the disk+ // geometry (and therefore `pos`) is expressed in meters.+ u_depthDiskShift: (shiftToCamera / normalizedRadius) * DEPTH_DISK_FULL_RADIUS,+ u_depthDiskRadius: (adjustedDiskRadius / normalizedRadius) * DEPTH_DISK_FULL_RADIUS+ };+ }+ super.draw({uniforms});+ }+}++export const getGlobeDepthDiskLayer = ({fillColor}: {fillColor?: RGBColor}) => {+ return new GlobeDepthDiskLayer({+ id: 'globe-depth-disk-layer',+ data: [[0, 0, 0]],+ coordinateOrigin: [0, 0, 0],+ coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,+ getPosition: (d: number[]) => d,+ getColor: (fillColor ?? [0, 0, 0]) as any,+ mesh: PLANE_GEOMETRY,+ parameters: DEPTH_DISK_PARAMETERS+ } as any);+};diff --git a/src/deckgl-layers/src/globe/globe-layers.ts b/src/deckgl-layers/src/globe/globe-layers.tsnew file mode 100644index 000000000..ace90bbee--- /dev/null+++ b/src/deckgl-layers/src/globe/globe-layers.ts@@ -0,0 +1,591 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {COORDINATE_SYSTEM, Layer} from '@deck.gl/core';+import {SolidPolygonLayer, BitmapLayer} from '@deck.gl/layers';+import {TileLayer, MVTLayer} from '@deck.gl/geo-layers';++import type {Globe} from '@kepler.gl/constants';+import type {RGBColor} from '@kepler.gl/types';++import {getGlobeAtmosphereLayer, getGlobeAtmosphereSkyLayer} from './atmosphere-layer';+import {getGlobeDepthDiskLayer} from './globe-depth-disk-layer';+import {MVTLabelLayer} from './mvt-label-layer';++type LayerGroup = {slug: string; filter: (layer: any) => boolean};++const devicePixelRatio = Math.min(+ 2,+ (typeof window !== 'undefined' && window.devicePixelRatio) || 1+);++const BACKGROUND_PARAMETERS = {+ depthTest: true,+ cull: true,+ depthMask: false+};++const BASEMAP_RASTER_PARAMETERS = {+ depthMask: false+};++const BACKGROUND_DATA = [+ [+ [-180, 90],+ [0, 90],+ [180, 90],+ [180, -90],+ [0, -90],+ [-180, -90]+ ]+];++const BACKGROUND_NORTH_POLE_DATA = [+ [+ [-180, 90],+ [0, 90],+ [180, 90],+ [180, 85],+ [0, 85],+ [-180, 85]+ ]+];++export const DEFAULT_BASEMAP_COLOR = {+ backgroundFillColor: [9, 16, 29] as RGBColor,+ basemapDefaultFillColor: [255, 255, 255] as RGBColor,+ basemapWaterFillColor: [17, 35, 48] as RGBColor,+ basemapDefaultLineColor: [40, 63, 93] as RGBColor,+ basemapAdminLineColor: [40, 63, 93] as RGBColor,+ basemapLabelColor: [114.75, 114.75, 114.75] as RGBColor+};++function getPaintColor(color: any): string | null {+ if (Array.isArray(color) && color[0] === 'interpolate') {+ return color[4];+ }+ return color;+}++function colorStringToRGB(color: string | null): RGBColor | null {+ if (!color) return null;+ if (typeof color !== 'string') return null;++ // Handle hsl() format+ const hslMatch = color.match(/hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/);+ if (hslMatch) {+ const h = parseInt(hslMatch[1], 10) / 360;+ const s = parseInt(hslMatch[2], 10) / 100;+ const l = parseInt(hslMatch[3], 10) / 100;+ // HSL to RGB conversion+ let r: number, g: number, b: number;+ if (s === 0) {+ r = g = b = l;+ } else {+ const hue2rgb = (p: number, q: number, t: number) => {+ if (t < 0) t += 1;+ if (t > 1) t -= 1;+ if (t < 1 / 6) return p + (q - p) * 6 * t;+ if (t < 1 / 2) return q;+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;+ return p;+ };+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;+ const p = 2 * l - q;+ r = hue2rgb(p, q, h + 1 / 3);+ g = hue2rgb(p, q, h);+ b = hue2rgb(p, q, h - 1 / 3);+ }+ return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)] as RGBColor;+ }++ // Handle rgb() format+ const rgbMatch = color.match(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/);+ if (rgbMatch) {+ return [+ parseInt(rgbMatch[1], 10),+ parseInt(rgbMatch[2], 10),+ parseInt(rgbMatch[3], 10)+ ] as RGBColor;+ }++ // Handle hex format+ const hexMatch = color.match(/^#([0-9a-f]{6})$/i);+ if (hexMatch) {+ const hex = hexMatch[1];+ return [+ parseInt(hex.slice(0, 2), 16),+ parseInt(hex.slice(2, 4), 16),+ parseInt(hex.slice(4, 6), 16)+ ] as RGBColor;+ }++ return null;+}++function findFirstLayerByGroup(layers: any[], layerGroups: LayerGroup[], groupSlug: string) {+ const layerGroup = layerGroups.find(group => group.slug === groupSlug);+ if (!layerGroup) return null;+ return layers.find(layer => layerGroup.filter(layer));+}++function findBackgroundColor(style: any): RGBColor | null {+ let found = style.layers.find((l: any) => l.id === 'background' || l.id === 'land');+ found = found || style.layers.find((l: any) => l.type === 'background');+ return colorStringToRGB(getPaintColor(found?.paint?.['background-color']));+}++function findWaterColor(style: any, layerGroups: LayerGroup[]): RGBColor | null {+ const found =+ style.layers.find((l: any) => l.id === 'water') ||+ findFirstLayerByGroup(style.layers, layerGroups, 'water');+ return colorStringToRGB(found?.paint?.['fill-color']);+}++function findAdminColor(style: any, layerGroups: LayerGroup[]): RGBColor | null {+ const borderLayers =+ style.layers.find((lyr: any) => lyr.id === 'admin-3-4-boundaries') ||+ findFirstLayerByGroup(style.layers, layerGroups, 'border');+ return colorStringToRGB(borderLayers?.paint?.['line-color']);+}++function findLabelColor(style: any, layerGroups: LayerGroup[]): RGBColor | null {+ let labelLayer = style.layers.find(+ (lyr: any) => lyr.id === 'country-label-lg' && lyr.type === 'symbol'+ );+ labelLayer =+ labelLayer ||+ style.layers.find((lyr: any) => lyr.id === 'country-label' && lyr.type === 'symbol');+ labelLayer = labelLayer || findFirstLayerByGroup(style.layers, layerGroups, 'label');+ return colorStringToRGB(labelLayer?.paint?.['text-color']);+}++export const getBasemapColors = (+ mapStyle: Partial<{style: any; layerGroups: LayerGroup[]}>+): {+ backgroundFillColor: RGBColor;+ basemapWaterFillColor: RGBColor;+ basemapAdminLineColor: RGBColor;+ basemapLabelColor: RGBColor;+} => {+ const {style: styleJson = {layers: []}, layerGroups = []} = mapStyle;++ return {+ backgroundFillColor:+ findBackgroundColor(styleJson) ?? DEFAULT_BASEMAP_COLOR.backgroundFillColor,+ basemapWaterFillColor:+ findWaterColor(styleJson, layerGroups) ?? DEFAULT_BASEMAP_COLOR.basemapWaterFillColor,+ basemapAdminLineColor:+ findAdminColor(styleJson, layerGroups) ?? DEFAULT_BASEMAP_COLOR.basemapAdminLineColor,+ basemapLabelColor:+ findLabelColor(styleJson, layerGroups) ?? DEFAULT_BASEMAP_COLOR.basemapLabelColor+ };+};++// Predefined color schemes for well-known basemap styles+const KNOWN_STYLE_COLORS: Record<+ string,+ {+ backgroundFillColor: RGBColor;+ basemapWaterFillColor: RGBColor;+ basemapAdminLineColor: RGBColor;+ basemapLabelColor: RGBColor;+ }+> = {+ dark: {+ backgroundFillColor: [15, 15, 15],+ basemapWaterFillColor: [10, 20, 35],+ basemapAdminLineColor: [60, 60, 80],+ basemapLabelColor: [150, 150, 150]+ },+ 'dark-matter': {+ backgroundFillColor: [18, 18, 18],+ basemapWaterFillColor: [14, 19, 29],+ basemapAdminLineColor: [50, 50, 60],+ basemapLabelColor: [130, 130, 130]+ },+ light: {+ backgroundFillColor: [235, 233, 228],+ basemapWaterFillColor: [170, 211, 223],+ basemapAdminLineColor: [180, 175, 170],+ basemapLabelColor: [80, 80, 80]+ },+ positron: {+ backgroundFillColor: [242, 239, 233],+ basemapWaterFillColor: [174, 209, 220],+ basemapAdminLineColor: [190, 185, 180],+ basemapLabelColor: [90, 90, 90]+ },+ voyager: {+ backgroundFillColor: [234, 229, 220],+ basemapWaterFillColor: [170, 211, 223],+ basemapAdminLineColor: [180, 170, 160],+ basemapLabelColor: [70, 70, 70]+ },+ muted: {+ backgroundFillColor: [225, 225, 218],+ basemapWaterFillColor: [180, 210, 220],+ basemapAdminLineColor: [170, 165, 160],+ basemapLabelColor: [90, 90, 90]+ },+ muted_night: {+ backgroundFillColor: [22, 26, 30],+ basemapWaterFillColor: [15, 25, 40],+ basemapAdminLineColor: [55, 60, 70],+ basemapLabelColor: [140, 140, 140]+ }+};++/**+ * Get basemap colors either from the style JSON or from known style presets.+ * Falls back to default dark colors if style is unknown and no JSON is available.+ */+export const getBasemapColorsForStyle = (+ styleType: string,+ mapStyle?: Partial<{style: any; layerGroups: LayerGroup[]}>+): {+ backgroundFillColor: RGBColor;+ basemapWaterFillColor: RGBColor;+ basemapAdminLineColor: RGBColor;+ basemapLabelColor: RGBColor;+} => {+ // Try to extract from style JSON first+ if (mapStyle?.style?.layers?.length) {+ return getBasemapColors(mapStyle);+ }+ // Fall back to known style presets+ if (KNOWN_STYLE_COLORS[styleType]) {+ return KNOWN_STYLE_COLORS[styleType];+ }+ // Default dark colors+ return {+ backgroundFillColor: DEFAULT_BASEMAP_COLOR.backgroundFillColor,+ basemapWaterFillColor: DEFAULT_BASEMAP_COLOR.basemapWaterFillColor,+ basemapAdminLineColor: DEFAULT_BASEMAP_COLOR.basemapAdminLineColor,+ basemapLabelColor: DEFAULT_BASEMAP_COLOR.basemapLabelColor+ };+};++/**+ * Clear color (background around the globe) for globe mode, in RGBA 0-255 as+ * expected by deck.gl's View `clearColor` prop (deck.gl >= 9 no longer supports+ * the global `parameters.clearColor`; it must be set per-view with `clear: true`).+ */+export function getGlobeClearColor(+ backgroundColor?: [number, number, number] | number[]+): [number, number, number, number] {+ if (backgroundColor) {+ return [backgroundColor[0], backgroundColor[1], backgroundColor[2], 255];+ }+ // Default matches the previous hardcoded clear color [0.015, 0.035, 0.065] in 0-1 space.+ return [4, 9, 17, 255];+}++const INVISIBLE_COLOR: [number, number, number, number] = [0, 0, 0, 0];++const BASEMAP_MVT_PARAMETERS = {+ depthMask: false+};++/**+ * Globe basemap tile provider.+ *+ * - `mapbox` uses Mapbox vector/raster tiles and requires an access token.+ * - `carto` uses CARTO's free OpenMapTiles vector tiles + Esri World Imagery+ * raster, and needs no token. Used as an automatic fallback when no Mapbox+ * token is available (e.g. MapLibre / CARTO basemap setups), so the globe+ * basemap still renders instead of showing a solid-color sphere.+ */+export type GlobeBasemapProvider = 'mapbox' | 'carto';++/**+ * Resolve which globe basemap tile provider to use.+ *+ * The globe should follow the *selected basemap style's* rendering library so+ * it stays consistent with the flat 2D map: a MapLibre/CARTO style uses the+ * free CARTO tiles (even when a Mapbox token is available), and a Mapbox style+ * uses Mapbox tiles. A Mapbox style with no token falls back to CARTO so the+ * globe still renders instead of showing a bare colored sphere.+ *+ * @param baseMapLibrary the selected style's library ('mapbox' | 'maplibre'),+ * e.g. from `getBaseMapLibrary(currentStyle)`.+ */+export const resolveGlobeBasemapProvider = (+ baseMapLibrary: 'mapbox' | 'maplibre' | undefined,+ mapboxApiAccessToken?: string+): GlobeBasemapProvider => {+ if (baseMapLibrary === 'maplibre') {+ return 'carto';+ }+ if (baseMapLibrary === 'mapbox') {+ return mapboxApiAccessToken ? 'mapbox' : 'carto';+ }+ // Unknown library: prefer Mapbox when a token exists, otherwise CARTO.+ return mapboxApiAccessToken ? 'mapbox' : 'carto';+};++// CARTO free vector tiles (OpenMapTiles schema, no API key required).+const CARTO_VECTOR_TILE_URLS = [+ 'https://tiles-a.basemaps.cartocdn.com/vectortiles/carto.streets/v1/{z}/{x}/{y}.mvt',+ 'https://tiles-b.basemaps.cartocdn.com/vectortiles/carto.streets/v1/{z}/{x}/{y}.mvt',+ 'https://tiles-c.basemaps.cartocdn.com/vectortiles/carto.streets/v1/{z}/{x}/{y}.mvt',+ 'https://tiles-d.basemaps.cartocdn.com/vectortiles/carto.streets/v1/{z}/{x}/{y}.mvt'+];++// Free satellite raster fallback (Esri World Imagery, no API key required).+const ESRI_WORLD_IMAGERY_URL =+ 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';++/**+ * Maps a raw MVT source-layer name to a normalized semantic layer kind, so the+ * fill/line/label accessors work across both the Mapbox (`mapbox-streets-v8`)+ * and CARTO/OpenMapTiles schemas.+ *+ * | semantic | mapbox | openmaptiles |+ * | -------- | ------------- | ------------ |+ * | water | `water` | `water` |+ * | admin | `admin` | `boundary` |+ * | label | `place_label` | `place` |+ */+type BasemapLayerKind = 'water' | 'admin' | 'label' | 'other';++function getBasemapLayerKind(layerName?: string): BasemapLayerKind {+ switch (layerName) {+ case 'water':+ return 'water';+ case 'admin':+ case 'boundary':+ return 'admin';+ case 'place_label':+ case 'place':+ return 'label';+ default:+ return 'other';+ }+}++export type GlobeAttribution = {label: string; href: string};++const MAPBOX_ATTRIBUTION: GlobeAttribution = {+ label: '© Mapbox',+ href: 'https://www.mapbox.com/about/maps/'+};+const OSM_ATTRIBUTION: GlobeAttribution = {+ label: '© OpenStreetMap',+ href: 'https://www.openstreetmap.org/copyright'+};+const CARTO_ATTRIBUTION: GlobeAttribution = {+ label: '© CARTO',+ href: 'https://carto.com/attributions'+};+const ESRI_ATTRIBUTION: GlobeAttribution = {+ label: 'Powered by Esri',+ href: 'https://www.esri.com/'+};++/**+ * Resolve the tile-source attribution entries for the globe basemap. deck.gl+ * renders the globe basemap tiles itself (not the base Maplibre/Mapbox map), so+ * the base map's attribution machinery never sees them. This lets the UI credit+ * the actual tile provider(s) in globe mode.+ */+export const getGlobeBasemapAttributions = ({+ globe,+ mapboxApiAccessToken,+ mapStyleType,+ basemapProvider+}: {+ globe?: Globe;+ mapboxApiAccessToken?: string;+ mapStyleType?: string;+ basemapProvider?: GlobeBasemapProvider;+}): GlobeAttribution[] => {+ if (!globe?.enabled || !globe.config?.basemap) {+ return [];+ }++ const provider: GlobeBasemapProvider =+ basemapProvider ?? resolveGlobeBasemapProvider(undefined, mapboxApiAccessToken);++ if (provider === 'mapbox') {+ return mapboxApiAccessToken ? [MAPBOX_ATTRIBUTION, OSM_ATTRIBUTION] : [];+ }++ const isSatellite = mapStyleType === 'satellite' || mapStyleType === 'satellite-street';+ // CARTO vector tiles are OpenStreetMap-derived; Esri imagery is credited separately.+ return isSatellite+ ? [ESRI_ATTRIBUTION, CARTO_ATTRIBUTION, OSM_ATTRIBUTION]+ : [CARTO_ATTRIBUTION, OSM_ATTRIBUTION];+};++// eslint-disable-next-line complexity+export const getGlobeBaseLayers = ({+ mapboxApiAccessToken,+ globe,+ mapStyleType,+ basemapProvider+}: {+ mapboxApiAccessToken: string;+ globe: Globe;+ mapStyleType?: string;+ /**+ * Which tile provider to use for the globe basemap. Defaults to `mapbox` when+ * a token is present, otherwise falls back to the token-free `carto` tiles.+ */+ basemapProvider?: GlobeBasemapProvider;+}): Layer[] => {+ const {config} = globe;++ const isSatellite = mapStyleType === 'satellite';+ const isSatelliteStreet = mapStyleType === 'satellite-street';++ // Fall back to the free CARTO tiles whenever no Mapbox token is available so+ // the globe basemap still renders (matches kepler's default token-free+ // MapLibre/CARTO basemaps). Callers should pass an explicit `basemapProvider`+ // (derived from the selected style) so the globe follows the 2D basemap.+ const provider: GlobeBasemapProvider =+ basemapProvider ?? resolveGlobeBasemapProvider(undefined, mapboxApiAccessToken);+ const useCarto = provider === 'carto';+ const hasTileAccess = useCarto || Boolean(mapboxApiAccessToken);++ return [+ config.atmosphere ? getGlobeAtmosphereSkyLayer({config}) : null,++ // Depth-only cross-section disk: writes depth at the globe's silhouette so+ // far-side geometry (arcs/lines) is occluded by the planet.+ getGlobeDepthDiskLayer({fillColor: config.surfaceColor}),++ // Background surface polygon+ (!config.basemap || (!isSatellite && !isSatelliteStreet)) &&+ new SolidPolygonLayer({+ id: 'globe-background',+ data: BACKGROUND_DATA,+ getPolygon: ((d: number[][]) => d) as any,+ filled: true,+ getFillColor: config.surfaceColor as any,+ parameters: BACKGROUND_PARAMETERS+ }),++ // Fill hole at north pole+ config.basemap &&+ new SolidPolygonLayer({+ id: 'globe-background-north-pole',+ data: BACKGROUND_NORTH_POLE_DATA,+ getPolygon: ((d: number[][]) => d) as any,+ filled: true,+ getFillColor: (config.water ? config.waterColor : config.surfaceColor) as any,+ parameters: BACKGROUND_PARAMETERS+ }),++ // Satellite tiles+ config.basemap &&+ (isSatellite || isSatelliteStreet) &&+ hasTileAccess &&+ new TileLayer({+ id: `globe-satellite-tiles-${provider}`,+ data: useCarto+ ? [ESRI_WORLD_IMAGERY_URL]+ : [+ `https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}@2x.png?access_token=${mapboxApiAccessToken}`+ ],+ minZoom: 0,+ maxZoom: useCarto ? 18 : 19,+ // Esri tiles are 256px; Mapbox @2x tiles are 512px.+ tileSize: useCarto ? 256 : 512 / devicePixelRatio,+ renderSubLayers: (props: any) => {+ const {+ bbox: {west, south, east, north}+ } = props.tile;++ return [+ new BitmapLayer(props, {+ _imageCoordinateSystem: COORDINATE_SYSTEM.CARTESIAN,+ data: undefined,+ image: props.data,+ bounds: [west, south, east, north]+ })+ ];+ },+ parameters: BASEMAP_RASTER_PARAMETERS+ }),++ // Vector basemap (MVT labels/admin/water)+ config.basemap &&+ !isSatellite &&+ hasTileAccess &&+ new MVTLayer({+ // force the layer to update when the style/label/provider config changes+ id: `globe-basemap-mvt-layer-${provider}-${mapStyleType}`,+ data: useCarto+ ? CARTO_VECTOR_TILE_URLS+ : `https://a.tiles.mapbox.com/v4/mapbox.mapbox-streets-v8/{z}/{x}/{y}.vector.pbf?access_token=${mapboxApiAccessToken}`,+ minZoom: 0,+ maxZoom: 23,+ binary: false,+ parameters: BASEMAP_MVT_PARAMETERS,+ loadOptions: useCarto+ ? {+ // OpenMapTiles schema: `boundary` = admin lines, `place` = labels.+ mvt: {+ layers: isSatelliteStreet+ ? ['place', 'boundary']+ : ['place', 'boundary', 'water', 'transportation']+ }+ }+ : {+ mvt: {+ layers: isSatelliteStreet+ ? ['place_label', 'admin']+ : ['place_label', 'admin', 'water', 'road']+ }+ },+ // Render admin/water via GeoJsonLayer and place labels via TextLayer.+ config,+ renderSubLayers: (props: any) => new MVTLabelLayer(props),+ getFillColor: (f: any) => {+ switch (getBasemapLayerKind(f.properties.layerName)) {+ case 'water':+ return config.water ? config.waterColor : INVISIBLE_COLOR;+ default:+ return config.surfaceColor;+ }+ },+ getLineColor: (f: any) => {+ switch (getBasemapLayerKind(f.properties.layerName)) {+ case 'admin':+ return config.adminLines ? config.adminLinesColor : INVISIBLE_COLOR;+ default:+ return config.surfaceColor;+ }+ },+ getLineWidth: (f: any) => {+ switch (getBasemapLayerKind(f.properties.layerName)) {+ case 'admin':+ switch (f.properties.admin_level) {+ case 0:+ case 2:+ return 1;+ default:+ return 0.75;+ }+ default:+ return 0;+ }+ },+ updateTriggers: {+ getFillColor: [config.waterColor, config.surfaceColor, config.water],+ getLineColor: [config.adminLinesColor, config.surfaceColor, config.adminLines]+ },+ lineWidthUnits: 'pixels',+ lineWidthMinPixels: 0,+ lineWidthMaxPixels: 20,+ getPointRadius: 0,+ pointRadiusMinPixels: 0+ } as any)+ ].filter(Boolean) as Layer[];+};++export const getGlobeTopLayers = ({globe}: {globe: Globe}): Layer[] => {+ const {config} = globe;+ return [config.atmosphere ? getGlobeAtmosphereLayer({config}) : null].filter(Boolean) as Layer[];+};diff --git a/src/deckgl-layers/src/globe/globe-view.ts b/src/deckgl-layers/src/globe/globe-view.tsnew file mode 100644index 000000000..cad019c08--- /dev/null+++ b/src/deckgl-layers/src/globe/globe-view.ts@@ -0,0 +1,201 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import * as DeckCore from '@deck.gl/core';+import {clamp} from '@math.gl/core';+import {GLOBE_MAX_LATITUDE} from '@kepler.gl/constants';++// deck.gl exposes GlobeView / GlobeController as experimental, underscore-prefixed+// members. Their named type bindings aren't reliably resolvable through the+// package barrel under this project's module resolution, so we pull them off the+// namespace with a loose type. Runtime behavior is unchanged.+const DeckGlobeView = (DeckCore as any)._GlobeView as any;+const GlobeController = (DeckCore as any)._GlobeController as any;++/**+ * Latitude-based zoom adjustment used by deck.gl's GlobeViewport, replicated+ * here so our custom `_constrainZoom` matches deck.gl's coordinate math.+ * See @deck.gl/core globe-viewport.js `zoomAdjust`.+ */+function zoomAdjust(latitude: number): number {+ return Math.log2(Math.PI * Math.cos((latitude * Math.PI) / 180));+}++/**+ * Custom GlobeController that restores zoom-to-cursor behavior.+ *+ * In deck.gl 9.x, the default GlobeController's GlobeState.zoom() ignores the+ * cursor position and always zooms toward the center. This controller patches+ * that behavior by overriding the ControllerState's zoom method to pan the+ * globe under the cursor while zooming, matching the behavior of deck.gl 8.x+ * and MapController.+ */+class ZoomToCursorGlobeController extends GlobeController {+ constructor(...args: any[]) {+ super(...args);+ const OriginalGlobeState = this.ControllerState;++ // Create patched GlobeState that supports zoom-to-cursor+ this.ControllerState = class PatchedGlobeState extends OriginalGlobeState {+ // Constrain the camera target to a latitude band around the equator so the+ // view can't be centered on the poles. deck.gl's applyConstraints clamps+ // latitude to ~85°, which still lets the camera look straight at a pole.+ applyConstraints(props: any) {+ const result = (super.applyConstraints as any)(props);+ const clampedLatitude = clamp(result.latitude, -GLOBE_MAX_LATITUDE, GLOBE_MAX_LATITUDE);+ if (clampedLatitude !== result.latitude) {+ // deck.gl couples zoom to latitude via zoomAdjust; when we further+ // clamp latitude, re-apply the same delta so zoom stays consistent.+ result.zoom += zoomAdjust(clampedLatitude) - zoomAdjust(result.latitude);+ result.latitude = clampedLatitude;+ }+ return result;+ }++ // deck.gl's GlobeState._constrainZoom derives a minimum zoom from `maxBounds`+ // that forces the globe to fill the viewport. That bounds-based minimum+ // (~3 for a typical window) overrides any configured `minZoom`, so the user+ // can never zoom out far enough to see the whole globe small on screen.+ // Override it to honor only the configured minZoom/maxZoom (plus the same+ // latitude adjustment deck.gl uses), ignoring the bounds-based floor.+ _constrainZoom(zoom: number, props?: any) {+ props = props || (this as any).getViewportProps();+ const {latitude, maxZoom} = props;+ let {minZoom} = props;+ if (minZoom === undefined || minZoom === null) {+ minZoom = 0;+ }+ const ZOOM0 = zoomAdjust(0);+ const zoomAdjustment = zoomAdjust(latitude) - ZOOM0;+ return clamp(zoom, minZoom + zoomAdjustment, maxZoom + zoomAdjustment);+ }++ // Zoom-to-cursor, ported verbatim from deck.gl 8.9.x MapState.zoom() ++ // GlobeViewport.panByPosition(coords, pixel) — which is what studio-monorepo+ // uses and where zoom-to-cursor tracks the cursor accurately over a whole+ // gesture. deck.gl 9.x regressed this in two ways that we avoid here:+ // 1. Its GlobeState.zoom() ignores the cursor and zooms toward the center.+ // 2. Its GlobeViewport.panByPosition became a lossy, *linearized* 3-arg+ // rotation (longitude += (0.25/scale)*(startPixel-pixel), re-derives+ // zoom). Using it per wheel tick accumulates error, so after a long+ // continuous zoom the point ends up noticeably shifted from what was+ // originally under the cursor.+ // The 8.9.x recenter below is an *exact absolute* translation: unproject the+ // cursor pixel in the zoomed viewport to get the geo point currently under it,+ // then shift the center by (anchor - thatPoint). No zoom coupling, no+ // rotationSpeed, and it applies to zoom-in and zoom-out symmetrically, so+ // there is no per-tick accumulated drift.+ zoom({+ pos,+ startPos,+ scale+ }: {+ pos: [number, number];+ startPos?: [number, number];+ scale: number;+ }) {+ let {startZoom, startZoomLngLat} = (this as any).getState();++ if (!startZoomLngLat) {+ // Discrete (wheel) zoom: re-derive the anchor each tick from the current+ // view. For pinch, startZoom/startZoomLngLat are set once by zoomStart and+ // preserved across ticks by _getUpdatedState (which spreads getState()).+ startZoom = (this as any).getViewportProps().zoom;+ startZoomLngLat = (this as any)._unproject(startPos) || (this as any)._unproject(pos);+ }+ if (!startZoomLngLat) {+ return this;+ }++ const currentProps = (this as any).getViewportProps();+ const zoom = (this as any)._constrainZoom(startZoom + Math.log2(scale));++ // Zoom-out (scale < 1): exact cursor anchoring is unstable on a globe (the+ // geo point under an off-center pixel moves non-linearly near the limb and+ // drags the view toward the poles). Instead, gently steer the CENTER toward+ // the geo location under the cursor — the map recenters on the cursor as you+ // zoom out, similar in spirit to zoom-in, but without the pole-ward spin.+ if (scale < 1) {+ const cursorLngLat = startZoomLngLat;+ const cursorValid =+ Array.isArray(cursorLngLat) &&+ Number.isFinite(cursorLngLat[0]) &&+ Number.isFinite(cursorLngLat[1]);+ if (!cursorValid) {+ return (this as any)._getUpdatedState({zoom});+ }++ // Fraction of the way to move the center toward the cursor per tick.+ // Scales with how much we zoomed out this tick so a bigger step moves+ // more. Clamped so a single large tick can't overshoot.+ const RECENTER_STRENGTH = 0.11;+ const t = Math.min(1, (1 - scale) * RECENTER_STRENGTH);++ // Shortest-path longitude interpolation (handle antimeridian wrap).+ let dLng = cursorLngLat[0] - currentProps.longitude;+ if (dLng > 180) dLng -= 360;+ if (dLng < -180) dLng += 360;++ return (this as any)._getUpdatedState({+ zoom,+ longitude: currentProps.longitude + dLng * t,+ latitude: currentProps.latitude + (cursorLngLat[1] - currentProps.latitude) * t+ });+ }++ const zoomedViewport = (this as any).makeViewport({+ ...currentProps,+ zoom+ });++ // 8.9.x GlobeViewport.panByPosition(startZoomLngLat, pos):+ // fromPosition = viewport.unproject(pos) // geo point now under the cursor+ // longitude = startZoomLngLat[0] - fromPosition[0] + viewport.longitude+ // latitude = startZoomLngLat[1] - fromPosition[1] + viewport.latitude+ const fromPosition = zoomedViewport.unproject(pos);++ // Guard: unproject can return NaN/undefined for a pixel off the sphere+ // silhouette; in that case just apply the new zoom about the center.+ const anchorValid =+ Array.isArray(fromPosition) &&+ Number.isFinite(fromPosition[0]) &&+ Number.isFinite(fromPosition[1]);+ if (!anchorValid) {+ return (this as any)._getUpdatedState({zoom});+ }++ return (this as any)._getUpdatedState({+ zoom,+ longitude: startZoomLngLat[0] - fromPosition[0] + zoomedViewport.longitude,+ latitude: startZoomLngLat[1] - fromPosition[1] + zoomedViewport.latitude+ });+ }++ // Clear the persisted pinch anchor at gesture end (matches 8.9.x).+ zoomEnd() {+ return (this as any)._getUpdatedState({+ startZoom: null,+ startZoomLngLat: null+ });+ }+ } as any;+ }+}++/**+ * Custom GlobeView that uses zoom-to-cursor controller behavior.+ */+export class KeplerGlobeView extends DeckGlobeView {+ // Forward constructor props to deck.gl's GlobeView. Declared explicitly because+ // the base class is loosely typed (see DeckGlobeView above), which would+ // otherwise surface a parameterless constructor to callers.+ constructor(props?: any) {+ super(props);+ }++ get ControllerType() {+ return ZoomToCursorGlobeController;+ }+}++KeplerGlobeView.displayName = 'KeplerGlobeView';diff --git a/src/deckgl-layers/src/globe/index.ts b/src/deckgl-layers/src/globe/index.tsnew file mode 100644index 000000000..28ea74251--- /dev/null+++ b/src/deckgl-layers/src/globe/index.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// Globe mode layer adjustments ported from studio-monorepo.+//+// The following globe-specific adjustments from studio-monorepo are NOT ported+// because they are not applicable or feasible in deck.gl 9.x:+//+// 1. Hex tile highPrecision flag:+// Studio-monorepo forced `highPrecision: true` for H3 hexagons at low resolutions+// in globe mode. Kepler.gl doesn't have hex-tile layers in the same form.+//+// 2. MVT clipBounds disabled in globe mode:+// Studio-monorepo's custom MVT layer skipped clipBounds/ClipExtension in globe mode.+// Deck.gl 9.x's MVTLayer handles globe projection natively without this workaround.+//+// Ported adjustments:+// - Grid / Hexagon aggregation cells on the globe: deck.gl 9.x's GridCellLayer /+// HexagonCellLayer position cells in flat mercator common space and draw them with+// project_common_position_to_clipspace, which leaves them on the XY plane through the+// globe center rather than on its surface. ScaleEnhancedGridLayer /+// ScaleEnhancedHexagonLayer swap in a globe-aware cell subclass (see+// layer-utils/globe-cell-utils) that remaps each cell vertex from common space back to+// lng/lat and onto the sphere (equivalent to studio-monorepo's UnfoldedGridCellLayer+// globe offset handling, adapted to deck.gl 9.x's aggregation pipeline).+// - 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 rather than the deck.gl+// 8.x per-vertex hook studio relied on.++export {+ AtmosphereLayerRealistic,+ AtmosphereSkyLayerRealistic,+ getGlobeAtmosphereLayer,+ getGlobeAtmosphereSkyLayer+} from './atmosphere-layer';+export {GlobeDepthDiskLayer, getGlobeDepthDiskLayer} from './globe-depth-disk-layer';+export {+ getGlobeBaseLayers,+ getGlobeTopLayers,+ getGlobeClearColor,+ getGlobeBasemapAttributions,+ resolveGlobeBasemapProvider,+ DEFAULT_BASEMAP_COLOR,+ getBasemapColors,+ getBasemapColorsForStyle+} from './globe-layers';+export type {GlobeBasemapProvider, GlobeAttribution} from './globe-layers';+export {MVTLabelLayer} from './mvt-label-layer';+export {default as EnhancedMultiIconLayer} from './enhanced-multi-icon-layer';+export {KeplerGlobeView} from './globe-view';diff --git a/src/deckgl-layers/src/globe/mvt-label-layer.ts b/src/deckgl-layers/src/globe/mvt-label-layer.tsnew file mode 100644index 000000000..ca8417e12--- /dev/null+++ b/src/deckgl-layers/src/globe/mvt-label-layer.ts@@ -0,0 +1,157 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {CompositeLayer, Color, Layer, UpdateParameters, AccessorFunction} from '@deck.gl/core';+import {GeoJsonLayer, TextLayer} from '@deck.gl/layers';++import type {Globe} from '@kepler.gl/constants';+import type {Feature} from 'geojson';++import EnhancedMultiIconLayer from './enhanced-multi-icon-layer';++// Ported from studio-monorepo (modules/studio/src/components/globe/mvt-label-layer.ts).+//+// This composite is used as the `renderSubLayers` of the globe basemap MVTLayer.+// It renders two things per tile:+// 1. A GeoJsonLayer for admin lines / water fills (same visuals as before).+// 2. A TextLayer for place labels (country names), gated on `config.labels`.+//+// The TextLayer uses a custom `EnhancedMultiIconLayer` as its glyph (characters)+// sublayer, which culls labels on the far side of the globe so they aren't drawn+// through the planet (ported from studio-monorepo).++type MVTLabelLayerProps = {+ data: {features: Feature[]} | Feature[];+ config: Globe['config'];+ labelSizeUnits?: 'meters' | 'common' | 'pixels';+ labelBackground?: Color;+ billboard?: boolean;+};++export class MVTLabelLayer extends CompositeLayer<MVTLabelLayerProps> {+ static layerName = 'MVTLabelLayer';+ static defaultProps = {+ ...GeoJsonLayer.defaultProps,+ billboard: true,+ labelSizeUnits: 'pixels',+ labelBackground: {type: 'color', value: null, optional: true},+ fontFamily: 'Monaco, monospace'+ };++ getLabel(feature: Feature): string {+ const {properties} = feature;++ switch (properties?.layerName) {+ // Mapbox `mapbox-streets-v8` schema.+ case 'place_label':+ switch (properties.class) {+ case 'country':+ return properties.name_en || properties.name || '';+ default:+ return '';+ }+ // CARTO / OpenMapTiles schema.+ case 'place':+ switch (properties.class) {+ case 'country':+ return properties['name:en'] || properties.name_en || properties.name || '';+ default:+ return '';+ }+ default:+ return '';+ }+ }++ getLabelSize(): number {+ return 10;+ }++ getLabelAnchors(feature: Feature): number[][] {+ // @ts-expect-error geometry type is narrowed by the switch below+ const {type, coordinates} = feature.geometry || {};+ switch (type) {+ case 'Point':+ return [coordinates];+ case 'MultiPoint':+ return coordinates;+ default:+ return [];+ }+ }++ updateState({changeFlags}: UpdateParameters<this>): void {+ const {data} = this.props;+ if (changeFlags.dataChanged && data) {+ const features = (data as {features: Feature[]}).features || (data as Feature[]);+ const labelData = (features || []).flatMap((feature, index) => {+ const labelAnchors = this.getLabelAnchors(feature);+ return labelAnchors.map(p => this.getSubLayerRow({position: p}, feature, index));+ });++ this.setState({labelData});+ }+ }++ renderLayers(): Layer[] {+ const {config, labelSizeUnits, labelBackground, billboard} = this.props;+ const layers: Layer[] = [];++ // admin lines and water+ layers.push(+ new GeoJsonLayer(this.props as any, this.getSubLayerProps({id: 'geojson'}), {+ data: this.props.data as any,+ updateTriggers: {+ getFillColor: {+ water: config.water,+ waterColor: config.waterColor+ },+ getLineColor: {+ adminLines: config.adminLines,+ adminLinesColor: config.adminLinesColor+ }+ }+ })+ );++ // labels+ if (config.labels) {+ layers.push(+ new TextLayer(this.getSubLayerProps({id: 'text'}), {+ data: this.state.labelData as any,+ parameters: {+ // Globe mode sets a global `cull: true` (to backface-cull the sphere+ // surface). That also backface-culls the glyph quads, hiding all labels,+ // so explicitly disable culling here. depthTest off keeps labels on top of+ // the globe surface rather than clipping into it.+ cull: false,+ depthTest: false,+ depthMask: false+ },+ billboard,+ sizeUnits: labelSizeUnits,+ // Build the font atlas from the actual labels so accented / non-ASCII+ // characters (ü, ó, etc. in country names) aren't dropped as "missing".+ characterSet: 'auto',+ fontFamily: 'Monaco, monospace',+ background: Boolean(labelBackground),+ getBackgroundColor: () => (labelBackground || [0, 0, 0, 0]) as Color,+ getPosition: (d: any) => d.position,+ getText: this.getSubLayerAccessor(this.getLabel) as AccessorFunction<Feature, string>,+ getSize: this.getSubLayerAccessor(this.getLabelSize),+ getColor: () => config.labelsColor as Color,+ _subLayerProps: {+ characters: {+ type: EnhancedMultiIconLayer+ }+ } as any,+ updateTriggers: {+ getColor: config.labelsColor+ }+ })+ );+ }++ return layers;+ }+}diff --git a/src/deckgl-layers/src/grid-layer/enhanced-cpu-grid-layer.ts b/src/deckgl-layers/src/grid-layer/enhanced-cpu-grid-layer.tsindex 925387173..76fdafa1b 100644--- a/src/deckgl-layers/src/grid-layer/enhanced-cpu-grid-layer.ts+++ b/src/deckgl-layers/src/grid-layer/enhanced-cpu-grid-layer.ts@@ -2,8 +2,12 @@// Copyright contributors to the kepler.gl projectimport {GridLayer, GridLayerPickingInfo} from '@deck.gl/aggregation-layers';-import {GetPickingInfoParams, PickingInfo, Viewport} from '@deck.gl/core';+import {GetPickingInfoParams, Layer, PickingInfo, Viewport} from '@deck.gl/core';import {enrichedAggregationUpdate, enrichedRenderLayers} from '../layer-utils/aggregation-utils';+import {+ makeGlobeCellLayerClass,+ runBinOptionsWithMercatorViewport+} from '../layer-utils/globe-cell-utils';interface GridInternalState {cellOriginCommon?: [number, number];@@ -48,6 +52,31 @@ export default class ScaleEnhancedGridLayer extends GridLayer<any> {return enrichedRenderLayers(this, GridLayer);}+ // In globe mode, run deck.gl's bin/common-space setup under a WebMercatorViewport+ // so binning and the cell shader's flat common space are genuine Web Mercator, which+ // the globe cell subclass then remaps onto the sphere surface. No-op in 2D/3D mode.+ _updateBinOptions() {+ runBinOptionsWithMercatorViewport(this, () =>+ (GridLayer.prototype as any)._updateBinOptions.call(this)+ );+ }++ // deck.gl's GridCellLayer positions cells in flat common space, which lands them+ // on the XY plane through the globe center. Swap in a globe-aware subclass that+ // curves cells onto the sphere surface (no-op in 2D/3D mode).+ getSubLayerClass<T extends Layer>(subLayerId: string, DefaultLayerClass: {new (...args: any[]): T}) {+ const resolved = super.getSubLayerClass(subLayerId, DefaultLayerClass);+ if (subLayerId === 'cells') {+ return makeGlobeCellLayerClass(+ resolved as unknown as {new (...args: any[]): T},+ 'grid'+ ) as unknown as {+ new (...args: any[]): T;+ };+ }+ return resolved;+ }+getPickingInfo(params: GetPickingInfoParams): PickingInfo {const info = super.getPickingInfo(params) as GridLayerPickingInfo<Record<string, unknown>>;if (info.object) {diff --git a/src/deckgl-layers/src/hexagon-layer/enhanced-hexagon-layer.ts b/src/deckgl-layers/src/hexagon-layer/enhanced-hexagon-layer.tsindex 1298e2e92..344519eff 100644--- a/src/deckgl-layers/src/hexagon-layer/enhanced-hexagon-layer.ts+++ b/src/deckgl-layers/src/hexagon-layer/enhanced-hexagon-layer.ts@@ -2,8 +2,12 @@// Copyright contributors to the kepler.gl projectimport {HexagonLayer, HexagonLayerPickingInfo} from '@deck.gl/aggregation-layers';-import {GetPickingInfoParams, PickingInfo, Viewport} from '@deck.gl/core';+import {GetPickingInfoParams, Layer, PickingInfo, Viewport} from '@deck.gl/core';import {enrichedAggregationUpdate, enrichedRenderLayers} from '../layer-utils/aggregation-utils';+import {+ makeGlobeCellLayerClass,+ runBinOptionsWithMercatorViewport+} from '../layer-utils/globe-cell-utils';const THIRD_PI = Math.PI / 3;const HexbinVertices = Array.from({length: 6}, (_, i) => {@@ -59,6 +63,31 @@ export default class ScaleEnhancedHexagonLayer extends HexagonLayer<any> {return enrichedRenderLayers(this, HexagonLayer);}+ // In globe mode, run deck.gl's bin/common-space setup under a WebMercatorViewport+ // so binning and the cell shader's flat common space are genuine Web Mercator, which+ // the globe cell subclass then remaps onto the sphere surface. No-op in 2D/3D mode.+ _updateBinOptions() {+ runBinOptionsWithMercatorViewport(this, () =>+ (HexagonLayer.prototype as any)._updateBinOptions.call(this)+ );+ }++ // deck.gl's HexagonCellLayer positions cells in flat common space, which lands+ // them on the XY plane through the globe center. Swap in a globe-aware subclass+ // that curves cells onto the sphere surface (no-op in 2D/3D mode).+ getSubLayerClass<T extends Layer>(subLayerId: string, DefaultLayerClass: {new (...args: any[]): T}) {+ const resolved = super.getSubLayerClass(subLayerId, DefaultLayerClass);+ if (subLayerId === 'cells') {+ return makeGlobeCellLayerClass(+ resolved as unknown as {new (...args: any[]): T},+ 'hexagon'+ ) as unknown as {+ new (...args: any[]): T;+ };+ }+ return resolved;+ }+getPickingInfo(params: GetPickingInfoParams): PickingInfo {const info = super.getPickingInfo(params) as HexagonLayerPickingInfo<Record<string, unknown>>;if (info.object) {diff --git a/src/deckgl-layers/src/index.ts b/src/deckgl-layers/src/index.tsindex 004cefee0..65af1f44e 100644--- a/src/deckgl-layers/src/index.ts+++ b/src/deckgl-layers/src/index.ts@@ -25,3 +25,5 @@ export * from './layer-utils/aggregation-utils';export * from './3d-building-layer/types';export * from './3d-building-layer/3d-building-utils';++export * from './globe';diff --git a/src/deckgl-layers/src/layer-utils/globe-cell-utils.ts b/src/deckgl-layers/src/layer-utils/globe-cell-utils.tsnew file mode 100644index 000000000..4afd99bc6--- /dev/null+++ b/src/deckgl-layers/src/layer-utils/globe-cell-utils.ts@@ -0,0 +1,184 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {WebMercatorViewport} from '@deck.gl/core';++/**+ * deck.gl's aggregation cell layers (GridCellLayer / HexagonCellLayer) position+ * each cell in flat mercator "common space" (a 2D XY plane) and then draw it with+ * `project_common_position_to_clipspace`, which only multiplies by the+ * view-projection matrix. Under `_GlobeView` this leaves the cells on the flat XY+ * plane that passes through the center of the globe instead of on its surface+ * (the base ColumnLayer works on the globe because it feeds real lng/lat through+ * `project_position` -> `project_globe_`; the aggregation cell shaders skip that).+ *+ * To fix this we remap the already-computed flat common-space vertex position back+ * to lng/lat (inverse Web Mercator) and then onto the sphere with the same math+ * `project_globe_` uses for geographic layers. Because we remap every vertex of the+ * cell footprint (not just the centroid), the flat quad/hexagon naturally curves+ * onto the surface. Elevation (extruded cells, stored in `geometry.position.z` in+ * common units) is added along the radius so columns rise radially off the globe.+ *+ * The remap is gated by a `globeMode` uniform so 2D/3D mercator rendering is+ * byte-for-byte unchanged.+ *+ * `WORLD_SCALE`, `PI`, `GLOBE_RADIUS` and `project.commonOrigin` are all provided+ * by deck.gl's project shader module which these layers include.+ */++// deck.gl 9 / luma 9 sets custom uniforms via UBO-backed shader modules (there is+// no Model.setUniforms). This minimal module exposes the globe-mode flag.+const globeCellUniforms = {+ name: 'globeCell',+ vs: `layout(std140) uniform globeCellUniforms {+ float globeMode;+} globeCellProps;+`,+ uniformTypes: {+ globeMode: 'f32'+ }+} as const;++const GLOBE_CELL_DECL = /* glsl */ `+// Inverse of deck.gl project_mercator_: flat common XY -> lng/lat (degrees).+vec2 kepler_commonToLngLat(vec2 commonXY) {+ float lng = degrees(commonXY.x / WORLD_SCALE - PI);+ float lat = degrees(2.0 * atan(exp(commonXY.y / WORLD_SCALE - PI)) - PI * 0.5);+ return vec2(lng, lat);+}++// Same math as deck.gl project_globe_. elevationCommon is in common units already+// (GLOBE_RADIUS space), matching how project_globe_ scales z off EARTH_RADIUS.+vec3 kepler_lngLatToGlobe(vec2 lngLat, float elevationCommon) {+ float lambda = radians(lngLat.x);+ float phi = radians(lngLat.y);+ float cosPhi = cos(phi);+ float D = GLOBE_RADIUS + elevationCommon;+ return vec3(+ sin(lambda) * cosPhi,+ -cos(lambda) * cosPhi,+ sin(phi)+ ) * D;+}+`;++/**+ * Rewrites a grid/hexagon cell vertex shader so that, in globe mode, the final+ * clip-space position is derived from the sphere surface instead of the flat XY+ * plane. In 2D/3D mode the original path is kept unchanged.+ */+export function addGlobeCellProjection(vs: string, type: string): string {+ const decl = `${GLOBE_CELL_DECL}\nvoid main(void) {`;+ const withDecl = vs.includes('void main(void) {') ? vs.replace('void main(void) {', decl) : vs;++ const target = 'gl_Position = project_common_position_to_clipspace(geometry.position);';+ if (!withDecl.includes(target)) {+ // Shader shape changed in a deck.gl update; leave the original so we don't crash.+ // eslint-disable-next-line no-console+ console.error(`Cannot edit ${type} globe cell shader`);+ return withDecl;+ }++ return withDecl.replace(+ target,+ `if (globeCellProps.globeMode > 0.5) {+ vec2 lngLat = kepler_commonToLngLat(geometry.position.xy + project.commonOrigin.xy);+ vec3 globePos = kepler_lngLatToGlobe(lngLat, geometry.position.z);+ geometry.position = vec4(globePos, 1.0);+ }+ gl_Position = project_common_position_to_clipspace(geometry.position);`+ );+}++/**+ * deck.gl 9's Grid/Hexagon aggregation compute bin positions and the cell layer's+ * "common space" from `this.context.viewport`. Under `_GlobeView` that common space+ * is the globe's 3D-projected space (projectFlat is identity on lng/lat, positions+ * bin off the sphere-projected XY), which both mis-bins data and — combined with the+ * flat cell shader — drops cells onto the plane through the globe center.+ *+ * We sidestep this by running `_updateBinOptions` with a WebMercatorViewport that+ * matches the current globe camera. That makes binning, `cellOriginCommon` /+ * `cellSizeCommon` (or `radiusCommon` / `hexOriginCommon`) and the cell shader's+ * flat position all live in genuine Web Mercator common space, which the cell shader+ * remap (`addGlobeCellProjection`) then curves back onto the sphere. In 2D/3D mode+ * this is a no-op.+ *+ * `callSuper` runs deck.gl's original `_updateBinOptions` while the viewport is+ * temporarily swapped. The swap is synchronous and restored in `finally`.+ */+export function runBinOptionsWithMercatorViewport(layer: any, callSuper: () => void): void {+ const viewport = layer.context?.viewport;+ const isGlobe = Boolean(viewport?.resolution);+ if (!isGlobe) {+ callSuper();+ return;+ }++ const mercatorViewport = new WebMercatorViewport({+ width: viewport.width,+ height: viewport.height,+ longitude: viewport.longitude,+ latitude: viewport.latitude,+ zoom: viewport.zoom+ });++ const originalViewport = layer.context.viewport;+ layer.context.viewport = mercatorViewport;+ try {+ callSuper();+ } finally {+ layer.context.viewport = originalViewport;+ }+}++/**+ * Wraps a deck.gl aggregation cell layer class (GridCellLayer / HexagonCellLayer)+ * with a subclass that injects the globe surface remap into its vertex shader.+ *+ * We create the subclass dynamically from whatever default class deck.gl provides+ * to `getSubLayerClass` so we don't have to import the (non-public) cell layer+ * classes directly. Results are cached per base class so deck.gl sees a stable+ * layer class across renders (layers are recreated every frame) and shader+ * compilation / sublayer diffing stays stable.+ */+const globeCellClassCache = new WeakMap<object, object>();++type LayerConstructor = {new (...args: any[]): any; layerName?: string};++export function makeGlobeCellLayerClass<T extends LayerConstructor>(+ BaseCellLayer: T,+ type: string+): T {+ const cached = globeCellClassCache.get(BaseCellLayer);+ if (cached) {+ return cached as T;+ }++ class GlobeCellLayer extends (BaseCellLayer as {new (...args: any[]): any}) {+ getShaders() {+ const shaders = (super.getShaders as () => any)();+ return {+ ...shaders,+ vs: addGlobeCellProjection(shaders.vs, type),+ modules: [...(shaders.modules || []), globeCellUniforms]+ };+ }++ draw(opts: any) {+ const globeMode = (this.context.viewport as any).resolution ? 1.0 : 0.0;+ // GridCellLayer / HexagonCellLayer render through a single fillModel and set+ // their own module props in draw(); set ours first so it merges (setProps is+ // per-module). deck.gl 9 has no Model.setUniforms — uniforms go through+ // shaderInputs UBO modules.+ const model = (this.state as any).fillModel;+ if (model?.shaderInputs) {+ model.shaderInputs.setProps({globeCell: {globeMode}});+ }+ (super.draw as (o: any) => void)(opts);+ }+ }+ (GlobeCellLayer as unknown as {layerName: string}).layerName = `Globe${type}CellLayer`;+ globeCellClassCache.set(BaseCellLayer, GlobeCellLayer);+ return GlobeCellLayer as unknown as T;+}diff --git a/src/deckgl-layers/src/svg-icon-layer/scatterplot-icon-layer.ts b/src/deckgl-layers/src/svg-icon-layer/scatterplot-icon-layer.tsindex 3108ff447..a5f9e9a3a 100644--- a/src/deckgl-layers/src/svg-icon-layer/scatterplot-icon-layer.ts+++ b/src/deckgl-layers/src/svg-icon-layer/scatterplot-icon-layer.ts@@ -2,32 +2,85 @@// Copyright contributors to the kepler.gl projectimport {ScatterplotLayer, ScatterplotLayerProps} from '@deck.gl/layers';-import {Geometry} from '@luma.gl/engine';+import {Geometry, Model} from '@luma.gl/engine';import {TOPOLOGY} from '@kepler.gl/constants';const DEFAULT_POS = [-1, -1, 0, -1, 1, 0, 1, 1, 0, 1, -1, 0];+const globeModeUniforms = {+ name: 'globeMode',+ vs: `uniform globeModeUniforms {+ float globeModeMod;+} globeModeProps;+`,+ uniformTypes: {+ globeModeMod: 'f32'+ }+};++const iconFragmentShader = /* glsl */ `\+#version 300 es+#define SHADER_NAME scatterplot-icon-layer-fragment-shader+precision highp float;+in vec4 vFillColor;+in vec4 vLineColor;+in vec2 unitPosition;+in float innerUnitRadius;+in float outerRadiusPixels;+out vec4 fragColor;+void main(void) {+ geometry.uv = unitPosition;+ fragColor = vFillColor;+ DECKGL_FILTER_COLOR(fragColor, geometry);+}+`;+export interface ScatterplotIconLayerProps extends ScatterplotLayerProps<any> {iconGeometry: number[];}export default class ScatterplotIconLayer extends ScatterplotLayer<any, ScatterplotIconLayerProps> {+ getShaders() {+ const shaders = super.getShaders();+ return {+ ...shaders,+ fs: iconFragmentShader,+ modules: [...(shaders.modules || []), globeModeUniforms],+ inject: {+ 'vs:DECKGL_FILTER_SIZE': `+ size.xy *= globeModeProps.globeModeMod;`+ }+ };+ }++ draw(opts) {+ const model = this.state.model;+ if (model) {+ model.shaderInputs.setProps({+ globeMode: {+ globeModeMod: (this.context.viewport as any).resolution ? -0.5 : 1+ }+ });+ }+ super.draw(opts);+ }+_getModel() {const {iconGeometry} = this.props;const positions = iconGeometry ? new Float32Array(iconGeometry) : new Float32Array(DEFAULT_POS);- const geometry = new Geometry({- topology: iconGeometry ? TOPOLOGY.TRIANGLE_LIST : TOPOLOGY.TRIANGLE_STRIP,- attributes: {- positions: {size: 3, value: positions}- }+ return new Model(this.context.device, {+ ...this.getShaders(),+ id: this.props.id,+ bufferLayout: this.getAttributeManager()!.getBufferLayouts(),+ geometry: new Geometry({+ topology: iconGeometry ? TOPOLOGY.TRIANGLE_LIST : TOPOLOGY.TRIANGLE_STRIP,+ attributes: {+ positions: {size: 3, value: positions}+ }+ }),+ isInstanced: true});-- const model = super._getModel();- if (model) {- model.setGeometry(geometry);- }- return model;}}diff --git a/src/layers/src/arc-layer/arc-layer.ts b/src/layers/src/arc-layer/arc-layer.tsindex 025265127..ec9443f2e 100644--- a/src/layers/src/arc-layer/arc-layer.ts+++ b/src/layers/src/arc-layer/arc-layer.ts@@ -501,7 +501,7 @@ export default class ArcLayer extends Layer {}renderLayer(opts) {- const {data, gpuFilter, objectHovered, interactionConfig, dataset} = opts;+ const {data, gpuFilter, objectHovered, interactionConfig, dataset, mapState} = opts;const updateTriggers = {getPosition: this.config.columns,getFilterValue: gpuFilter.filterValueUpdateTriggers,@@ -512,6 +512,15 @@ export default class ArcLayer extends Layer {const defaultLayerProps = this.getDefaultDeckLayerProps(opts);const hoveredObject = this.hasHoveredObject(objectHovered);+ // In globe mode deck.gl is configured with a global `cull: true` to backface-+ // cull the globe surface. The arc is drawn as a billboarded triangle-strip+ // ribbon whose back-facing triangles then get culled too, making arcs partly+ // or fully invisible on the globe. Disable culling just for this layer so the+ // whole ribbon renders, without changing the global culling that the globe+ // surface relies on.+ const isGlobeMode = Boolean(mapState?.globe?.enabled);+ const globeParameters = isGlobeMode ? {parameters: {cull: false}} : {};+const useArrowLayer = Boolean(this.geoArrowVector0);let ArcLayerClass: typeof DeckArcLayer | typeof GeoArrowArcLayer = DeckArcLayer;@@ -537,6 +546,7 @@ export default class ArcLayer extends Layer {...this.getBrushingExtensionProps(interactionConfig, 'source_target'),...data,...experimentalPropOverrides,+ ...globeParameters,widthScale,updateTriggers,extensions: [@@ -550,6 +560,7 @@ export default class ArcLayer extends Layer {? [new DeckArcLayer({...this.getDefaultHoverLayerProps(),+ ...globeParameters,visible: defaultLayerProps.visible,data: [hoveredObject],widthScale,diff --git a/src/layers/src/editor-layer/editor-layer.ts b/src/layers/src/editor-layer/editor-layer.tsindex 53d06b6d8..90da24eb8 100644--- a/src/layers/src/editor-layer/editor-layer.ts+++ b/src/layers/src/editor-layer/editor-layer.ts@@ -38,6 +38,7 @@ export type GetEditorLayerProps = {features: Feature[];};selectedFeatureIndexes: number[];+ mapState?: {globe?: {enabled: boolean}};};/**@@ -59,7 +60,8 @@ export function getEditorLayer({onApplyPolygonFilterAll,featureCollection,selectedFeatureIndexes,- viewport+ viewport,+ mapState}: GetEditorLayerProps): DeckLayer<DeckLayerProps> {const {mode: editorMode} = editor;@@ -172,7 +174,10 @@ export function getEditorLayer({getTentativeLineWidth: LINE_STYLE.getTentativeLineWidth,getTentativeFillColor: LINE_STYLE.getTentativeFillColor,- parameters: {},+ // Globe mode needs explicit depth testing so the editor overlay is occluded+ // by the sphere; in flat 2D/3D keep deck.gl's default (empty parameters) so+ // this matches the pre-globe behavior exactly.+ parameters: mapState?.globe?.enabled ? {depthTest: true} : {},shadowEnabled: false,_subLayerProps: {geojson: {shadowEnabled: false},diff --git a/src/layers/src/flow-layer/flow-layer.ts b/src/layers/src/flow-layer/flow-layer.tsindex b2621974c..be4d4db7f 100644--- a/src/layers/src/flow-layer/flow-layer.ts+++ b/src/layers/src/flow-layer/flow-layer.ts@@ -523,9 +523,34 @@ export default class FlowLayer extends Layer {const {visConfig} = this.config;const flowLinesRenderingMode = visConfig.flowLinesRenderingMode || 'straight';++ // In globe mode we still render flows (the layer is flagged unsupported and shows a+ // warning), but we want the flat arrows on the far side of the globe to be occluded+ // by the planet instead of drawing on top of it. The @flowmap.gl flow-line sublayers+ // hardcode `depthTest: false` in their sublayer parameters (see FlowmapLayer.js), so+ // a top-level `parameters` won't reach them — we override via _subLayerProps, which+ // getSubLayerProps applies last. cullMode 'none' keeps both faces (arrows are flat).+ const isGlobeMode = Boolean(opts.mapState?.globe?.enabled);+ const globeSubLayerProps = isGlobeMode+ ? (() => {+ const depthParams = {+ parameters: {cull: false, depthTest: true, depthCompare: 'less-equal', cullMode: 'none'}+ };+ return {+ _subLayerProps: {+ 'flow-lines': depthParams,+ 'curved-flow-lines': depthParams,+ 'animated-flow-lines': depthParams,+ 'flow-highlight': depthParams+ }+ };+ })()+ : {};+return [new FlowmapLayer<LocationDatum, FlowDatum>({...cleanProps,+ ...globeSubLayerProps,dataProvider: this._dataProvider,data: this._dataVersion as any,...flowmapDataAccessors,diff --git a/src/layers/src/heatmap-layer/deck-heatmap-layer.ts b/src/layers/src/heatmap-layer/deck-heatmap-layer.tsindex a33f24b9c..ea63d2387 100644--- a/src/layers/src/heatmap-layer/deck-heatmap-layer.ts+++ b/src/layers/src/heatmap-layer/deck-heatmap-layer.ts@@ -2,6 +2,8 @@// Copyright contributors to the kepler.gl projectimport {HeatmapLayer as DeckGLHeatmapLayer} from '@deck.gl/aggregation-layers';+import {Layer, WebMercatorViewport, project32, COORDINATE_SYSTEM} from '@deck.gl/core';+import {Model} from '@luma.gl/engine';import {editShader, insertBefore} from '@kepler.gl/deckgl-layers';/**@@ -35,8 +37,59 @@ import {editShader, insertBefore} from '@kepler.gl/deckgl-layers';* getShaders, because the legacy AggregationLayer.updateState() calls* getShaders({}) (with no fs) and then passes the raw shader imports to* updateShaders → _createWeightsTransform, bypassing the getShaders patching.+ *+ * # Globe support+ *+ * The stock deck.gl HeatmapLayer only works in a flat WebMercator viewport.+ * It computes the density texture bounds by unprojecting the four screen+ * corners of the *current* viewport, and it renders the final result as a flat+ * 4-vertex quad. Neither of these works on a globe: the screen corners don't+ * unproject to a meaningful lng/lat box, and a flat quad does not conform to+ * the sphere.+ *+ * To support globe mode this layer, when `globeMode` + `densityBounds` are+ * provided:+ *+ * 1. Renders the density texture using a *fixed* WebMercator viewport built+ * from the layer's data bounds (`densityBounds`), instead of the live globe+ * viewport. This makes the offscreen density render behave exactly like the+ * 2D top-down case, but framed around the data rather than the screen.+ *+ * 2. Renders the final texture with a subdivided (tessellated) mesh spanning+ * the same data bounds, so that each vertex is projected onto the globe by+ * deck.gl's `project_position_to_clipspace`. This is the same technique+ * deck.gl's BitmapLayer uses to bend a flat image around the sphere.*/export default class KeplerHeatmapLayer extends DeckGLHeatmapLayer {+ static defaultProps = {+ ...DeckGLHeatmapLayer.defaultProps,+ // kepler.gl extensions to support globe mode+ globeMode: false,+ // [minLng, minLat, maxLng, maxLat] of the data, used to frame the density texture in globe mode+ densityBounds: null+ };++ // Cached fixed density viewport (keyed by bounds) so we don't rebuild it on+ // every update/render. Not stored in layer state to avoid setState-in-render.+ private _densityViewport: WebMercatorViewport | null = null;+ private _densityViewportKey: string | null = null;++ // Cached globe render mesh, so its identity stays stable across frames (only+ // rebuilt when the density bounds or the globe resolution change).+ private _globeMesh: HeatmapMesh | null = null;+ private _globeMeshKey: string | null = null;++ // World bounds [w, s, e, n] the density texture is currently framed to. In+ // globe mode this is normally the data bounds, but when the camera is zoomed+ // in far enough that the visible area sits fully inside the data, we frame the+ // density texture around the *visible* area to improve level-of-detail.+ private _densityBounds: [number, number, number, number] | null = null;+ // Quantized key of `_densityBounds`, so small camera moves don't re-frame.+ private _densityBoundsFrameKey: string | null = null;+ // Cached reference viewport framing the full data bounds (for radius scaling).+ private _referenceViewport: WebMercatorViewport | null = null;+ private _referenceViewportKey: string | null = null;+_createWeightsTransform(shaders: any) {if (shaders.fs?.includes('gaussianKDE')) {let fs = editShader(@@ -73,14 +126,799 @@ export default class KeplerHeatmapLayer extends DeckGLHeatmapLayer {'fragColor.r = 1.0;\n ');if (result.modules) {- result.modules = result.modules.filter(- (m: any) => (m?.name || m) !== 'layer'- );+ result.modules = result.modules.filter((m: any) => (m?.name || m) !== 'layer');}}return result;}++ /**+ * True when the layer should render for a globe: globe mode is enabled and+ * valid data bounds were provided to frame the density texture.+ */+ _isGlobeHeatmap(): boolean {+ const {globeMode, densityBounds} = this.props as any;+ return Boolean(globeMode && densityBounds && this._getDensityViewport());+ }++ /**+ * Decide which world bounds the density texture should be framed to for the+ * current camera.+ *+ * When zoomed out (we can see the whole globe, or the visible area extends+ * past the data), we frame the density texture around the entire data extent+ * so the whole heatmap is covered. When zoomed in far enough that the visible+ * area sits fully inside the data bounds, we frame the density texture around+ * the *visible* area instead — the same fixed-size texture then covers a much+ * smaller region, dramatically improving level-of-detail as the user zooms.+ */+ _computeDensityBounds(globeViewport: any): [number, number, number, number] | null {+ const {densityBounds} = this.props as any;+ if (!densityBounds || densityBounds.length !== 4) {+ return null;+ }+ const [dW, dS, dE, dN] = densityBounds as [number, number, number, number];+ if (![dW, dS, dE, dN].every(Number.isFinite)) {+ return null;+ }+ const dataBounds: [number, number, number, number] = [+ Math.min(dW, dE),+ Math.min(dS, dN),+ Math.max(dW, dE),+ Math.max(dS, dN)+ ];++ const viewBounds = this._getGlobeViewBounds(globeViewport);+ if (viewBounds && this._boundsInside(viewBounds, dataBounds)) {+ // `getBounds()` samples edge-midpoints, so the true visible extent+ // (screen corners) is a bit larger. Pad generously so the heatmap isn't+ // clipped at the corners, and clamp back into the data bounds.+ return this._padBounds(viewBounds, 0.25, dataBounds);+ }++ return dataBounds;+ }++ /**+ * Visible lng/lat bounds of the globe viewport, or null if they can't be+ * determined reliably (e.g. the whole globe is visible / edges miss the+ * sphere / the span is degenerate or wraps around the planet).+ */+ _getGlobeViewBounds(globeViewport: any): [number, number, number, number] | null {+ if (!globeViewport || typeof globeViewport.getBounds !== 'function') {+ return null;+ }+ let bounds: number[];+ try {+ bounds = globeViewport.getBounds();+ } catch (e) {+ return null;+ }+ if (!bounds || bounds.length !== 4 || !bounds.every(Number.isFinite)) {+ return null;+ }+ const [w, s, e, n] = bounds;+ const lngSpan = e - w;+ const latSpan = n - s;+ // Reject degenerate or globe-spanning views: if we see (nearly) the whole+ // planet, framing to the view is pointless and error-prone.+ if (lngSpan <= 0 || latSpan <= 0 || lngSpan >= 350 || latSpan >= 170) {+ return null;+ }+ return [w, s, e, n];+ }++ _boundsInside(+ inner: [number, number, number, number],+ outer: [number, number, number, number]+ ): boolean {+ return (+ inner[0] >= outer[0] && inner[1] >= outer[1] && inner[2] <= outer[2] && inner[3] <= outer[3]+ );+ }++ _padBounds(+ bounds: [number, number, number, number],+ ratio: number,+ clampTo: [number, number, number, number]+ ): [number, number, number, number] {+ const [w, s, e, n] = bounds;+ const padX = (e - w) * ratio;+ const padY = (n - s) * ratio;+ return [+ Math.max(w - padX, clampTo[0]),+ Math.max(s - padY, clampTo[1]),+ Math.min(e + padX, clampTo[2]),+ Math.min(n + padY, clampTo[3])+ ];+ }++ /**+ * Build a plain WebMercator viewport that exactly frames `bounds`+ * ([w, s, e, n]) into a fixed offscreen size. Returns null for invalid bounds.+ */+ _buildMercatorViewport(bounds: [number, number, number, number]): WebMercatorViewport | null {+ const [minLng, minLat, maxLng, maxLat] = bounds;+ if (![minLng, minLat, maxLng, maxLat].every(Number.isFinite)) {+ return null;+ }++ // Clamp latitudes to WebMercator limits so fitBounds stays valid.+ const MAX_LAT = 85.051129;+ const south = Math.max(Math.min(minLat, maxLat), -MAX_LAT);+ const north = Math.min(Math.max(minLat, maxLat), MAX_LAT);+ const west = Math.min(minLng, maxLng);+ const east = Math.max(minLng, maxLng);++ // Use a reasonably large offscreen frame so the density render has enough+ // resolution regardless of the current globe zoom.+ const width = 1024;+ const height = 1024;++ try {+ return new WebMercatorViewport({+ width,+ height,+ longitude: (west + east) / 2,+ latitude: (south + north) / 2,+ zoom: 0+ }).fitBounds(+ [+ [west, south],+ [east, north]+ ],+ {width, height, padding: 0}+ );+ } catch (e) {+ return null;+ }+ }++ /**+ * Build (and cache) the WebMercator viewport that frames `_densityBounds`.+ *+ * This viewport is completely independent of the current globe camera+ * *projection* — it is always a plain WebMercator frame — but the region it+ * covers (`_densityBounds`) follows the camera for level-of-detail (see+ * `_computeDensityBounds`). It drives the offscreen density texture render.+ */+ _getDensityViewport(): WebMercatorViewport | null {+ const bounds = this._densityBounds || (this.props as any).densityBounds;+ if (!bounds || bounds.length !== 4) {+ return null;+ }++ const cacheKey = bounds.join(',');+ if (this._densityViewportKey === cacheKey && this._densityViewport) {+ return this._densityViewport;+ }++ const viewport = this._buildMercatorViewport(bounds as [number, number, number, number]);+ if (!viewport) {+ return null;+ }++ this._densityViewport = viewport;+ this._densityViewportKey = cacheKey;+ return viewport;+ }++ /**+ * Reference WebMercator viewport framing the FULL data bounds. Used to keep+ * the effective heatmap radius constant (in world terms) when the density+ * texture is reframed to a smaller, zoomed-in region: as the frame shrinks the+ * texture resolution increases, so `radiusPixels` must be scaled up by the+ * ratio of viewport scales to avoid a visible jump in blob size / detail.+ */+ _getReferenceViewport(): WebMercatorViewport | null {+ const dataBounds = (this.props as any).densityBounds;+ if (!dataBounds || dataBounds.length !== 4) {+ return null;+ }+ const key = dataBounds.join(',');+ if (this._referenceViewportKey === key && this._referenceViewport) {+ return this._referenceViewport;+ }+ const viewport = this._buildMercatorViewport(dataBounds as [number, number, number, number]);+ this._referenceViewport = viewport;+ this._referenceViewportKey = key;+ return viewport;+ }++ /**+ * Factor to multiply `radiusPixels` by so the heatmap's world-space radius+ * matches what it would be when framed to the full data bounds. Equals the+ * ratio of the current density viewport scale to the reference (data-bounds)+ * viewport scale (scale ∝ 2^zoom, larger for the tighter frame).+ */+ _getRadiusScale(): number {+ const current = this._getDensityViewport();+ const reference = this._getReferenceViewport();+ if (!current || !reference || !reference.scale || !current.scale) {+ return 1;+ }+ const scale = current.scale / reference.scale;+ return Number.isFinite(scale) && scale > 0 ? scale : 1;+ }++ /**+ * Quantize world bounds into a stable string key. Small camera movements+ * should NOT re-frame the density texture (that would thrash the GPU and+ * flicker), so we snap the bounds to a grid proportional to their span.+ */+ _densityBoundsKey(bounds: [number, number, number, number]): string {+ const [w, s, e, n] = bounds;+ const lngSpan = Math.max(1e-6, e - w);+ const latSpan = Math.max(1e-6, n - s);+ // ~12 steps across the current span; re-frame only when the view has moved+ // or zoomed by roughly one twelfth of the frame.+ const stepX = lngSpan / 12;+ const stepY = latSpan / 12;+ const q = (v: number, step: number) => Math.round(v / step) * step;+ return [q(w, stepX), q(s, stepY), q(e, stepX), q(n, stepY)].map(v => v.toFixed(4)).join(',');+ }++ // Tracks whether the previous update ran in globe mode, so we can detect the+ // globe→2D (and 2D→globe) transition and reset stale density framing state.+ private _wasGlobeHeatmap = false;++ updateState(opts: any) {+ const {globeMode, densityBounds} = this.props as any;++ // Detect a transition out of globe mode. In globe mode we frame the density+ // texture to a FIXED WebMercator viewport built from the data bounds and+ // cache the resulting `worldBounds` on the base layer's state. When we+ // switch back to 2D the base layer's `_updateBounds` only recomputes+ // `worldBounds` when the new visible bounds are NOT contained in the cached+ // ones (`boundsContain`). The stale globe frame usually still "contains" the+ // 2D view, so the base layer keeps the globe framing and the heatmap renders+ // in the wrong place (and stays wrong while panning). Clear the cached+ // framing + our globe caches so the 2D path rebuilds from scratch.+ const isGlobeNow = Boolean(globeMode && densityBounds);+ const leftGlobe = this._wasGlobeHeatmap && !isGlobeNow;+ if (leftGlobe) {+ this._resetGlobeState();+ }+ this._wasGlobeHeatmap = isGlobeNow;++ if (!globeMode || !densityBounds) {+ super.updateState(opts);+ // On the globe→2D transition, the base layer's viewport-change detection+ // may not fire (the mode toggle can arrive without a viewport diff in the+ // same cycle). Force a fresh bounds + weightmap computation against the+ // live 2D viewport so the heatmap doesn't keep the stale globe framing.+ if (leftGlobe && this.context?.viewport && !(this.context.viewport as any).resolution) {+ try {+ this._updateBounds(true);+ this._updateTextureRenderingBounds();+ (this.state as any).isWeightMapDirty = true;+ this._updateWeightmap();+ } catch (e) {+ // Defensive: if the live viewport isn't ready this frame, the next+ // regular update will recompute (worldBounds was cleared).+ }+ }+ return;+ }++ // The globe viewport (live camera) is available on the update context. Use+ // it to decide how to frame the density texture (whole data vs. zoomed-in+ // visible area) for level-of-detail. Do this BEFORE swapping the viewport.+ const globeViewport = opts.context?.viewport || this.context.viewport;+ const nextBounds = this._computeDensityBounds(globeViewport);+ if (nextBounds) {+ const nextKey = this._densityBoundsKey(nextBounds);+ if (nextKey !== this._densityBoundsFrameKey) {+ this._densityBounds = nextBounds;+ this._densityBoundsFrameKey = nextKey;+ // Invalidate the cached mercator viewport so it is rebuilt for the new+ // frame, and force the base layer to recompute its density bounds ++ // regenerate the weightmap (it would otherwise keep the old, coarser+ // texture because the new visible bounds are contained in the old ones).+ this._densityViewport = null;+ this._densityViewportKey = null;+ (this.state as any).worldBounds = null;+ }+ }++ if (!this._isGlobeHeatmap()) {+ super.updateState(opts);+ return;+ }++ // In globe mode the density texture is framed by a fixed WebMercator+ // viewport (see `_getDensityViewport`), not the live globe camera. Swap the+ // viewport everywhere the base layer reads it from during update:+ // - `this.context.viewport` and `opts.context.viewport`: used by the+ // density math (`_updateBounds`, `_worldToCommonBounds`) and by change+ // detection (`_getChangeFlags` reads `opts.context.viewport.zoom`).+ // - `this.internalState.viewport`: TAKES PRIORITY in `Layer.projectPosition`+ // (`this.internalState.viewport || this.context.viewport`) and is what+ // deck.gl assigns to `context.viewport` at the start of every update. If+ // we don't swap it too, the data points are projected with the globe+ // viewport and land outside the density texture, producing an empty map.+ const densityViewport = this._getDensityViewport();+ if (!densityViewport) {+ super.updateState(opts);+ return;+ }++ const internalState = this.internalState as any;+ const originalContextViewport = this.context.viewport;+ const originalOptsViewport = opts.context?.viewport;+ const originalInternalViewport = internalState?.viewport;+ (this.context as any).viewport = densityViewport;+ if (opts.context) {+ opts.context.viewport = densityViewport;+ }+ if (internalState) {+ internalState.viewport = densityViewport;+ }++ try {+ // Cancel any pending (2D-style) debounced weightmap update; the density+ // is regenerated synchronously here against the fixed viewport.+ const {updateTimer} = this.state as any;+ if (updateTimer) {+ clearTimeout(updateTimer);+ this.setState({updateTimer: null});+ }+ super.updateState(opts);+ } finally {+ (this.context as any).viewport = originalContextViewport;+ if (opts.context) {+ opts.context.viewport = originalOptsViewport;+ }+ if (internalState) {+ internalState.viewport = originalInternalViewport;+ }+ }+ }++ /**+ * Clear all globe-mode density framing state, both our own caches and the+ * base deck.gl HeatmapLayer's cached bounds, so the next (2D) update recomputes+ * `worldBounds` / `normalizedCommonBounds` from the live viewport instead of+ * reusing the fixed globe frame. Also resets the base layer's cached `zoom` so+ * its viewport-change detection fires, and marks the weight map dirty.+ */+ _resetGlobeState() {+ this._densityViewport = null;+ this._densityViewportKey = null;+ this._densityBounds = null;+ this._densityBoundsFrameKey = null;+ this._referenceViewport = null;+ this._referenceViewportKey = null;+ this._globeMesh = null;+ this._globeMeshKey = null;++ const state = this.state as any;+ if (state) {+ // Force base `_updateBounds` to recompute (it skips when the new visible+ // bounds are contained in the stale globe `worldBounds`).+ state.worldBounds = null;+ state.normalizedCommonBounds = null;+ // Force base `_getChangeFlags` to report a viewport/zoom change so it+ // recomputes bounds and regenerates the weight map on this update.+ state.zoom = null;+ }+ }++ /**+ * When the density texture is reframed to a smaller (zoomed-in) region, its+ * resolution increases, so a fixed `radiusPixels` would suddenly cover a+ * smaller world area — a visible jump in detail. Scale `radiusPixels` by the+ * viewport-scale ratio so the effective world-space radius stays constant as+ * the frame changes. Only applies in globe mode; otherwise defers to super.+ */+ _updateWeightmap() {+ if (!this._isGlobeHeatmap()) {+ super._updateWeightmap();+ return;+ }++ const radiusScale = this._getRadiusScale();+ if (radiusScale === 1) {+ super._updateWeightmap();+ return;+ }++ const originalProps = this.props;+ const scaledRadius = Math.max(1, (originalProps as any).radiusPixels * radiusScale);+ // Shallow-override radiusPixels without mutating the (possibly frozen) props.+ this.props = Object.create(originalProps, {+ radiusPixels: {value: scaledRadius, enumerable: true}+ });+ try {+ super._updateWeightmap();+ } finally {+ this.props = originalProps;+ }+ }++ renderLayers(): any {+ if (!this._isGlobeHeatmap()) {+ return super.renderLayers();+ }++ const {+ weightsTexture,+ maxWeightsTexture,+ colorTexture,+ colorDomain,+ worldBounds,+ normalizedCommonBounds+ } = this.state as any;+ const {updateTriggers, intensity, threshold, aggregation} = this.props as any;++ if (+ !weightsTexture ||+ !colorTexture ||+ !maxWeightsTexture ||+ !worldBounds ||+ !normalizedCommonBounds+ ) {+ return null;+ }++ const densityViewport = this._getDensityViewport();+ if (!densityViewport) {+ return null;+ }++ const AGGREGATION_MODE: Record<string, number> = {SUM: 0, MEAN: 1};++ // Build (and memoize) the tessellated mesh spanning the exact region+ // covered by the density texture (`worldBounds`, already aspect-corrected by+ // the base layer). Texture coordinates are computed the same way deck.gl's+ // flat heatmap does: project each vertex through the density viewport and+ // normalize against `normalizedCommonBounds`. This correctly handles the+ // non-linear Web Mercator latitude mapping of the density texture.+ const resolution = this.context.viewport.resolution;+ const meshKey = `${worldBounds.join(',')}|${resolution}`;+ if (this._globeMeshKey !== meshKey || !this._globeMesh) {+ this._globeMesh = createGlobeHeatmapMesh(+ worldBounds as [number, number, number, number],+ normalizedCommonBounds as [number, number, number, number],+ densityViewport,+ resolution+ );+ this._globeMeshKey = meshKey;+ }+ const mesh = this._globeMesh;++ const GlobeTriangleLayerClass = this.getSubLayerClass(+ 'globe-triangle',+ GlobeHeatmapTriangleLayer+ );++ return new GlobeTriangleLayerClass(+ this.getSubLayerProps({+ id: 'globe-triangle-layer',+ updateTriggers+ }),+ {+ coordinateSystem: COORDINATE_SYSTEM.LNGLAT,+ data: {length: 1},+ mesh,+ maxTexture: maxWeightsTexture,+ colorTexture,+ aggregationMode: AGGREGATION_MODE[aggregation] || 0,+ weightsTexture,+ intensity,+ threshold,+ colorDomain+ }+ );+ }}KeplerHeatmapLayer.layerName = 'HeatmapLayer';++type HeatmapMesh = {+ positions: Float64Array;+ texCoords: Float32Array;+ indices: Uint32Array;+ vertexCount: number;+};++/**+ * Get texture coordinate of a common-space point inside a common bounds box.+ * Mirrors deck.gl's heatmap `getTextureCoordinates`.+ */+function getTextureCoordinate(+ commonPoint: number[],+ commonBounds: [number, number, number, number]+): [number, number] {+ const [xMin, yMin, xMax, yMax] = commonBounds;+ return [(commonPoint[0] - xMin) / (xMax - xMin), (commonPoint[1] - yMin) / (yMax - yMin)];+}++/**+ * Build a mesh covering the world-space rectangle `[minLng, minLat, maxLng,+ * maxLat]` that the density texture spans. When a `resolution` is provided+ * (globe / non-linear viewports set `viewport.resolution`), the quad is+ * subdivided into a grid so it conforms to the sphere.+ *+ * Each vertex's texture coordinate is computed by projecting its world position+ * through the fixed density viewport and normalizing against the density+ * texture's common bounds — identical to how deck.gl's flat heatmap samples the+ * density texture, so the visual result matches 2D top-down mode.+ */+function createGlobeHeatmapMesh(+ worldBounds: [number, number, number, number],+ normalizedCommonBounds: [number, number, number, number],+ densityViewport: WebMercatorViewport,+ resolution?: number+): HeatmapMesh {+ const [minLng, minLat, maxLng, maxLat] = worldBounds;++ const texCoordAt = (lng: number, lat: number): [number, number] =>+ getTextureCoordinate(densityViewport.projectPosition([lng, lat, 0]), normalizedCommonBounds);++ if (!resolution) {+ // corners: [minLng,minLat], [minLng,maxLat], [maxLng,maxLat], [maxLng,minLat]+ const corners = [+ [minLng, minLat],+ [minLng, maxLat],+ [maxLng, maxLat],+ [maxLng, minLat]+ ];+ const positions = new Float64Array(12);+ const texCoords = new Float32Array(8);+ for (let i = 0; i < corners.length; i++) {+ positions[i * 3 + 0] = corners[i][0];+ positions[i * 3 + 1] = corners[i][1];+ positions[i * 3 + 2] = 0;+ const tc = texCoordAt(corners[i][0], corners[i][1]);+ texCoords[i * 2 + 0] = tc[0];+ texCoords[i * 2 + 1] = tc[1];+ }+ return {+ positions,+ texCoords,+ indices: new Uint32Array([0, 2, 1, 0, 3, 2]),+ vertexCount: 6+ };+ }++ const lngSpan = Math.abs(maxLng - minLng);+ const latSpan = Math.abs(maxLat - minLat);+ const uCount = Math.max(2, Math.ceil(lngSpan / resolution) + 1);+ const vCount = Math.max(2, Math.ceil(latSpan / resolution) + 1);++ const vertexCount = (uCount - 1) * (vCount - 1) * 6;+ const indices = new Uint32Array(vertexCount);+ const texCoords = new Float32Array(uCount * vCount * 2);+ const positions = new Float64Array(uCount * vCount * 3);++ let vertex = 0;+ let index = 0;+ for (let u = 0; u < uCount; u++) {+ const ut = u / (uCount - 1);+ for (let v = 0; v < vCount; v++) {+ const vt = v / (vCount - 1);+ const lng = minLng + ut * (maxLng - minLng);+ const lat = minLat + vt * (maxLat - minLat);+ positions[vertex * 3 + 0] = lng;+ positions[vertex * 3 + 1] = lat;+ positions[vertex * 3 + 2] = 0;+ const tc = texCoordAt(lng, lat);+ texCoords[vertex * 2 + 0] = tc[0];+ texCoords[vertex * 2 + 1] = tc[1];+ if (u > 0 && v > 0) {+ indices[index++] = vertex - vCount;+ indices[index++] = vertex - vCount - 1;+ indices[index++] = vertex - 1;+ indices[index++] = vertex - vCount;+ indices[index++] = vertex - 1;+ indices[index++] = vertex;+ }+ vertex++;+ }+ }++ return {positions, texCoords, indices, vertexCount};+}++const globeTriangleVs = `\+#version 300 es+#define SHADER_NAME globe-heatmap-triangle-layer-vertex-shader+uniform sampler2D maxTexture;+in vec3 positions;+in vec3 positions64Low;+in vec2 texCoords;+out vec2 vTexCoords;+out float vIntensityMin;+out float vIntensityMax;+void main(void) {+ gl_Position = project_position_to_clipspace(positions, positions64Low, vec3(0.0));+ vTexCoords = texCoords;+ vec4 maxTexture = texture(maxTexture, vec2(0.5));+ float maxValue = triangle.aggregationMode < 0.5 ? maxTexture.r : maxTexture.g;+ float minValue = maxValue * triangle.threshold;+ if (triangle.colorDomain[1] > 0.) {+ maxValue = triangle.colorDomain[1];+ minValue = triangle.colorDomain[0];+ }+ vIntensityMax = triangle.intensity / maxValue;+ vIntensityMin = triangle.intensity / minValue;+}+`;++const globeTriangleFs = `\+#version 300 es+#define SHADER_NAME globe-heatmap-triangle-layer-fragment-shader+precision highp float;+uniform sampler2D weightsTexture;+uniform sampler2D colorTexture;+in vec2 vTexCoords;+in float vIntensityMin;+in float vIntensityMax;+out vec4 fragColor;+vec4 getLinearColor(float value) {+ float factor = clamp(value * vIntensityMax, 0., 1.);+ vec4 color = texture(colorTexture, vec2(factor, 0.5));+ color.a *= min(value * vIntensityMin, 1.0);+ return color;+}+void main(void) {+ vec4 weights = texture(weightsTexture, vTexCoords);+ float weight = weights.r;+ if (triangle.aggregationMode > 0.5) {+ weight /= max(1.0, weights.a);+ }+ if (weight <= 0.) {+ discard;+ }+ vec4 linearColor = getLinearColor(weight);+ linearColor.a *= layer.opacity;+ fragColor = linearColor;+}+`;++const triangleUniformBlock = `\+layout(std140) uniform triangleUniforms {+ float aggregationMode;+ vec2 colorDomain;+ float intensity;+ float threshold;+} triangle;+`;++const globeTriangleUniforms = {+ name: 'triangle',+ vs: triangleUniformBlock,+ fs: triangleUniformBlock,+ uniformTypes: {+ aggregationMode: 'f32',+ colorDomain: 'vec2<f32>',+ intensity: 'f32',+ threshold: 'f32'+ }+} as any;++/**+ * Renders the heatmap density texture as an (optionally subdivided) mesh that+ * conforms to the globe. It reuses the same density → color-ramp mapping as+ * deck.gl's flat heatmap TriangleLayer, but with an indexed, tessellated mesh+ * whose LNGLAT positions deck.gl projects onto the sphere.+ *+ * The attribute/mesh wiring mirrors deck.gl's BitmapLayer (indexed geometry via+ * the AttributeManager with `noAlloc` update callbacks).+ */+class GlobeHeatmapTriangleLayer extends Layer<any> {+ static layerName = 'GlobeHeatmapTriangleLayer';++ declare state: {+ model?: Model;+ mesh?: HeatmapMesh;+ } & Layer['state'];++ getShaders() {+ return super.getShaders({+ vs: globeTriangleVs,+ fs: globeTriangleFs,+ modules: [project32, globeTriangleUniforms]+ });+ }++ initializeState() {+ const attributeManager = this.getAttributeManager();+ // Not pickable; drop the picking-color attribute the base layer adds.+ attributeManager?.remove(['instancePickingColors']);+ const noAlloc = true;+ attributeManager?.add({+ indices: {+ size: 1,+ isIndexed: true,+ update: attribute => (attribute.value = this.state.mesh?.indices ?? null),+ noAlloc+ },+ positions: {+ size: 3,+ type: 'float64',+ fp64: this.use64bitPositions(),+ update: attribute => (attribute.value = this.state.mesh?.positions ?? null),+ noAlloc+ },+ texCoords: {+ size: 2,+ update: attribute => (attribute.value = this.state.mesh?.texCoords ?? null),+ noAlloc+ }+ });++ this.setState({+ mesh: this.props.mesh,+ model: this._getModel()+ });+ }++ updateState(params: any): void {+ super.updateState(params);+ const {props, oldProps, changeFlags} = params;+ const attributeManager = this.getAttributeManager();++ if (changeFlags.extensionsChanged) {+ this.state.model?.destroy();+ this.setState({model: this._getModel()});+ attributeManager?.invalidateAll();+ }++ // The parent rebuilds the mesh whenever bounds/viewport change and passes+ // it in via the `mesh` prop.+ if (props.mesh !== oldProps.mesh && props.mesh) {+ const oldMesh = this.state.mesh;+ const mesh = props.mesh as HeatmapMesh;+ this.state.model?.setVertexCount(mesh.vertexCount);+ for (const key of Object.keys(mesh) as (keyof HeatmapMesh)[]) {+ if (oldMesh && oldMesh[key] !== mesh[key]) {+ attributeManager?.invalidate(key as string);+ }+ }+ this.setState({mesh});+ }+ }++ _getModel(): Model {+ return new Model(this.context.device, {+ ...this.getShaders(),+ id: this.props.id,+ bufferLayout: this.getAttributeManager()?.getBufferLayouts(),+ topology: 'triangle-list',+ isInstanced: false+ });+ }++ draw(): void {+ const {model} = this.state;+ const {+ aggregationMode,+ colorDomain,+ intensity,+ threshold,+ colorTexture,+ maxTexture,+ weightsTexture+ } = this.props;+ if (!model || !weightsTexture || !colorTexture || !maxTexture) {+ return;+ }+ model.shaderInputs.setProps({+ triangle: {+ aggregationMode,+ colorDomain,+ intensity,+ threshold,+ // Textures are not declared in `uniformTypes`, so they are treated as+ // bindings and bound to the matching sampler uniforms by name.+ colorTexture,+ maxTexture,+ weightsTexture+ }+ });+ model.draw(this.context.renderPass);+ }+}diff --git a/src/layers/src/heatmap-layer/heatmap-layer.ts b/src/layers/src/heatmap-layer/heatmap-layer.tsindex d10aa97c6..427482250 100644--- a/src/layers/src/heatmap-layer/heatmap-layer.ts+++ b/src/layers/src/heatmap-layer/heatmap-layer.ts@@ -596,6 +596,16 @@ class HeatmapLayer extends Layer {visible: boolean;}): KeplerHeatmapLayer[] {const {data, mapState} = opts;++ const globeMode = Boolean(mapState?.globe?.enabled);++ // In globe mode the density texture is framed around the data bounds rather+ // than the visible screen, so we need valid data bounds to render at all.+ const densityBounds = this.meta?.bounds as [number, number, number, number] | undefined;+ if (globeMode && (!densityBounds || densityBounds.length !== 4)) {+ return [];+ }+const {_unfiltered, ...deckData} = data;const defaultLayerProps = this.getDefaultDeckLayerProps(opts);@@ -629,7 +639,10 @@ class HeatmapLayer extends Layer {updateTriggers,colorRange,weightsTextureSize: 512,- debounceTimeout: 0+ debounceTimeout: 0,+ // globe-mode extensions+ globeMode,+ densityBounds: globeMode ? densityBounds : null})];}diff --git a/src/layers/src/line-layer/line-layer.ts b/src/layers/src/line-layer/line-layer.tsindex 921ae4e54..723229711 100644--- a/src/layers/src/line-layer/line-layer.ts+++ b/src/layers/src/line-layer/line-layer.ts@@ -4,6 +4,7 @@import * as arrow from 'apache-arrow';import {BrushingExtension} from '@deck.gl/extensions';+import {ArcLayer as DeckArcLayer} from '@deck.gl/layers';import {GeoArrowArcLayer} from '@kepler.gl/deckgl-arrow-layers';import {FilterArrowExtension} from '@kepler.gl/deckgl-layers';@@ -267,7 +268,7 @@ export default class LineLayer extends ArcLayer {}renderLayer(opts) {- const {data, gpuFilter, objectHovered, interactionConfig, dataset} = opts;+ const {data, gpuFilter, objectHovered, interactionConfig, dataset, mapState} = opts;const layerProps = {widthScale: this.config.visConfig.thickness * PROJECTED_PIXEL_SIZE_MULTIPLIER,@@ -283,6 +284,54 @@ export default class LineLayer extends ArcLayer {const defaultLayerProps = this.getDefaultDeckLayerProps(opts);const hoveredObject = this.hasHoveredObject(objectHovered);+ const globeMode = mapState?.globe?.enabled;++ if (globeMode) {+ const id = `${defaultLayerProps.id}-globe`;+ return [+ new DeckArcLayer({+ ...defaultLayerProps,+ ...this.getBrushingExtensionProps(interactionConfig, 'source_target'),+ ...data,+ ...layerProps,+ id,+ updateTriggers,+ extensions: [...defaultLayerProps.extensions, brushingExtension],+ // On a globe a "line" is drawn as a flat ArcLayer: getHeight 0 keeps the+ // geometry on the sphere surface (no raised paraboloid arc, which would+ // otherwise pop up as spikes sticking out perpendicular to the surface).+ // Match the ArcLayer's globe params exactly (cull:false so the ribbon's+ // back-facing triangles aren't culled by globe mode's global cull, and+ // otherwise deck.gl defaults: depth test on + depth write on, so the+ // depth disk occludes segments on the far side of the globe).+ getHeight: 0,+ parameters: {cull: false},+ // A Kepler line has a single color channel; an ArcLayer interpolates+ // between source and target colors, so feed the same color to both+ // ends (otherwise the target end falls back to deck.gl's default).+ getSourceColor: data.getColor,+ getTargetColor: data.getColor,+ widthUnits: 'pixels' as const+ }),+ ...(hoveredObject+ ? [+ new DeckArcLayer({+ ...this.getDefaultHoverLayerProps(),+ ...layerProps,+ id: `${id}-hovered`,+ data: [hoveredObject],+ getHeight: 0,+ parameters: {cull: false},+ getSourceColor: this.config.highlightColor,+ getTargetColor: this.config.highlightColor,+ getWidth: data.getWidth,+ widthUnits: 'pixels' as const+ })+ ]+ : [])+ ];+ }+const useArrowLayer = Boolean(this.geoArrowVector0);let LineLayerClass: typeof EnhancedLineLayer | typeof GeoArrowArcLayer = EnhancedLineLayer;diff --git a/src/layers/src/s2-geometry-layer/s2-geometry-layer.ts b/src/layers/src/s2-geometry-layer/s2-geometry-layer.tsindex c1fe2d34d..e65d4aea3 100644--- a/src/layers/src/s2-geometry-layer/s2-geometry-layer.ts+++ b/src/layers/src/s2-geometry-layer/s2-geometry-layer.ts@@ -29,7 +29,7 @@ import {LayerColumn} from '@kepler.gl/types';import S2LayerIcon from './s2-layer-icon';-import {getS2Center, validS2Token} from './s2-utils';+import {getS2Center, validS2Token, maybeStripQuotes} from './s2-utils';import {DataContainerInterface, createDataContainer} from '@kepler.gl/utils';export type S2GeometryLayerVisConfigSettings = {@@ -270,7 +270,7 @@ export default class S2GeometryLayer extends Layer {if (validS2Token(token)) {data.push({index,- token+ token: maybeStripQuotes(token)});}}@@ -279,12 +279,14 @@ export default class S2GeometryLayer extends Layer {updateLayerMeta(dataset: KeplerTable, getS2Token) {const {dataContainer} = dataset;- // add safe row flagconst centroids = dataContainer.reduce((acc, entry, index) => {const s2Token = getS2Token({index});if (validS2Token(s2Token)) {- acc.push(getS2Center(s2Token));+ const center = getS2Center(s2Token);+ if (center) {+ acc.push(center);+ }}return acc;diff --git a/src/layers/src/s2-geometry-layer/s2-utils.ts b/src/layers/src/s2-geometry-layer/s2-utils.tsindex 608c270a3..b234a265b 100644--- a/src/layers/src/s2-geometry-layer/s2-utils.ts+++ b/src/layers/src/s2-geometry-layer/s2-utils.ts@@ -9,17 +9,36 @@ const MAXIMUM_TOKEN_LENGTH = 16;/*** Retrieve S2 geometry center* @param s2Token string | number- * @return {*[]}+ * @return {[number, number] | null}*/-export function getS2Center(s2Token) {- const paddedToken = s2Token.toString().padEnd(MAXIMUM_TOKEN_LENGTH, '0');- const s2Id = Long.fromString(paddedToken, MAXIMUM_TOKEN_LENGTH);- const {lat, lng} = S2.idToLatLng(s2Id.toString());- return [lng, lat];+export function getS2Center(s2Token): [number, number] | null {+ const cleaned = maybeStripQuotes(s2Token.toString());+ const paddedToken = cleaned.padEnd(MAXIMUM_TOKEN_LENGTH, '0');+ try {+ const s2Id = Long.fromString(paddedToken, MAXIMUM_TOKEN_LENGTH);+ const {lat, lng} = S2.idToLatLng(s2Id.toString());+ return [lng, lat];+ } catch (e) {+ return null;+ }}-const re = new RegExp('^[0-9a-z]*$', 'g');-// simple test to see if token only contains numbers and letters+const re = /^[0-9a-z]+$/;++export function maybeStripQuotes(token: string): string {+ if (token.length >= 2) {+ const first = token[0];+ const last = token[token.length - 1];+ if ((first === "'" && last === "'") || (first === '"' && last === '"')) {+ return token.slice(1, -1);+ }+ }+ return token;+}++// S2 tokens must be at least 2 hex chars to encode face + level markerexport function validS2Token(token) {- return typeof token === 'string' && Boolean(token.match(re));+ if (typeof token !== 'string') return false;+ const cleaned = maybeStripQuotes(token);+ return cleaned.length >= 2 && re.test(cleaned);}diff --git a/src/layers/src/scenegraph-layer/scenegraph-layer.ts b/src/layers/src/scenegraph-layer/scenegraph-layer.tsindex 5a5d1b6a0..0d69164e2 100644--- a/src/layers/src/scenegraph-layer/scenegraph-layer.ts+++ b/src/layers/src/scenegraph-layer/scenegraph-layer.ts@@ -198,12 +198,14 @@ export default class ScenegraphLayer extends Layer {}renderLayer(opts) {- const {data, gpuFilter} = opts;+ const {data, gpuFilter, mapState} = opts;const {visConfig: {sizeScale = 1, angleX = 0, angleY = 0, angleZ = 90}} = this.config;+ const adjustedAngleY = angleY + (mapState?.globe?.enabled ? 180 : 0);+return [new DeckScenegraphLayer({...this.getDefaultDeckLayerProps(opts),@@ -215,13 +217,13 @@ export default class ScenegraphLayer extends Layer {sizeScale,getTranslation: DEFAULT_TRANSITION,getScale: DEFAULT_SCALE,- getOrientation: [angleX, angleY, angleZ],+ getOrientation: [angleX, adjustedAngleY, angleZ],getColor: DEFAULT_COLOR,// parametersparameters: {depthTest: true, blend: false},// update triggersupdateTriggers: {- getOrientation: {angleX, angleY, angleZ},+ getOrientation: {angleX, adjustedAngleY, angleZ},getPosition: this.config.columns,getFilterValue: gpuFilter.filterValueUpdateTriggers}diff --git a/src/layers/src/vector-tile/mvt-layer.ts b/src/layers/src/vector-tile/mvt-layer.tsindex ba83ed4aa..e709d058a 100644--- a/src/layers/src/vector-tile/mvt-layer.ts+++ b/src/layers/src/vector-tile/mvt-layer.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import {Layer, LayersList} from '@deck.gl/core';+import {Layer, LayersList, LayerExtension} from '@deck.gl/core';import {ClipExtension} from '@deck.gl/extensions';import {MVTLayer as _MVTLayer,@@ -23,6 +23,83 @@ import {incrementVectorTileLoading, decrementVectorTileLoading} from './loading-- loaders.gl & older deck.gl: geojson-table: data = data.features*/+/**+ * Globe-safe rectangular clip.+ *+ * deck.gl's stock `ClipExtension` clips polygon fragments against a min/max box in+ * the layer's *common space*. On a globe viewport, common space is the 3D sphere+ * (projectPosition returns x/y/z on the sphere and the extension only keeps x/y), so+ * a flat rectangle no longer matches the curved tile boundary and slices diagonally+ * through the geometry (visible as diagonal stripes).+ *+ * This extension instead clips against the *world position* (lng/lat), which is the+ * same space the tile `clipBounds` are expressed in. Longitude/latitude are viewport+ * independent, so tile edges are trimmed correctly on the globe (and would match flat+ * too). We only use it in globe mode; 2D keeps the stock ClipExtension.+ */+const globeClipShaderFunction = /* glsl */ `+layout(std140) uniform globeClipUniforms {+ vec4 bounds;+} globeClip;++bool globeClip_isInBounds(vec2 lngLat) {+ return lngLat.x >= globeClip.bounds[0] && lngLat.y >= globeClip.bounds[1] &&+ lngLat.x < globeClip.bounds[2] && lngLat.y < globeClip.bounds[3];+}+`;++const globeClipShaderModule = {+ name: 'globeClip',+ vs: globeClipShaderFunction,+ fs: globeClipShaderFunction,+ uniformTypes: {+ bounds: 'vec4<f32>'+ }+};++const globeClipInjection = {+ 'vs:#decl': /* glsl */ `+out vec2 globeClip_worldPosition;+`,+ 'vs:DECKGL_FILTER_GL_POSITION': /* glsl */ `+ globeClip_worldPosition = geometry.worldPosition.xy;+`,+ 'fs:#decl': /* glsl */ `+in vec2 globeClip_worldPosition;+`,+ 'fs:DECKGL_FILTER_COLOR': /* glsl */ `+ if (!globeClip_isInBounds(globeClip_worldPosition)) discard;+`+};++export class GlobeClipExtension extends LayerExtension {+ static extensionName = 'GlobeClipExtension';++ // Declaring `clipBounds` here is required so that when this extension is attached to+ // a CompositeLayer (GeoJsonLayer), LayerExtension.getSubLayerProps forwards+ // `clipBounds` down to the primitive sublayers (SolidPolygonLayer/PathLayer) where+ // the shader + draw() actually run. Without this the uniform stays [0,0,0,0].+ static defaultProps = {+ clipBounds: [0, 0, 1, 1]+ };++ getShaders(): any {+ return {+ modules: [globeClipShaderModule],+ inject: globeClipInjection+ };+ }++ draw(this: any): void {+ const {clipBounds} = this.props as {clipBounds?: number[]};+ if (!clipBounds) {+ return;+ }+ // clipBounds are [minLng, minLat, maxLng, maxLat] (tile boundingBox in lng/lat).+ this.setShaderModuleProps({globeClip: {bounds: clipBounds}});+ }+}+// @ts-expect-error need to patch private methods because of newer loaders.glexport class MVTLayer<ExtraProps> extends _MVTLayer<ExtraProps> {static layerName = 'MVTLayer';@@ -57,9 +134,19 @@ export class MVTLayer<ExtraProps> extends _MVTLayer<ExtraProps> {props.autoHighlight = true;+ // The globe viewport is identified by having a `resolution` (set by GlobeViewport).+ const isGlobeMode = Boolean((this.context.viewport as any)?.resolution);+if (boundingBox) {props.clipBounds = [...boundingBox[0], ...boundingBox[1]];- props.extensions = [...(props.extensions || []), new ClipExtension()];+ // In globe mode the stock ClipExtension clips in common (sphere) space, which+ // slices diagonally through geometry. Use the lng/lat-based GlobeClipExtension+ // so tile edges are trimmed correctly (prevents doubled/overlapping geometry at+ // tile seams). In 2D keep the stock ClipExtension.+ props.extensions = [+ ...(props.extensions || []),+ isGlobeMode ? new GlobeClipExtension() : new ClipExtension()+ ];}return this.props.renderSubLayers(props);diff --git a/src/layers/src/vector-tile/vector-tile-layer.ts b/src/layers/src/vector-tile/vector-tile-layer.tsindex bf87c6929..4e959239b 100644--- a/src/layers/src/vector-tile/vector-tile-layer.ts+++ b/src/layers/src/vector-tile/vector-tile-layer.ts@@ -44,7 +44,7 @@ import {} from '@kepler.gl/types';import {DataContainerInterface} from '@kepler.gl/utils';-import {MVTLayer as CustomMVTLayer} from './mvt-layer';+import {MVTLayer as CustomMVTLayer, GlobeClipExtension} from './mvt-layer';import VectorTileIcon from './vector-tile-icon';import {default as KeplerLayer,@@ -593,7 +593,11 @@ export default class VectorTileLayer extends AbstractTileLayer<VectorTile, Featuconst perTileOverlays = this._getPerTileOverlays(hoveredObject, {defaultLayerProps,visConfig,- uniqueIdProperty+ uniqueIdProperty,+ // In globe mode use the lng/lat-based GlobeClipExtension for the hover+ // outline (see mvt-layer.ts: the stock common-space clip slices diagonally+ // through the sphere geometry).+ isGlobeMode: Boolean((mapState as any)?.globe?.enabled)});const layers = [@@ -726,7 +730,12 @@ export default class VectorTileLayer extends AbstractTileLayer<VectorTile, Featu*/_getPerTileOverlays(hoveredObject: Feature,- options: {defaultLayerProps: any; visConfig: any; uniqueIdProperty?: string}+ options: {+ defaultLayerProps: any;+ visConfig: any;+ uniqueIdProperty?: string;+ isGlobeMode?: boolean;+ }): DeckLayer[] {let perTileOverlays: DeckLayer[] = [];if (hoveredObject) {@@ -774,7 +783,9 @@ export default class VectorTileLayer extends AbstractTileLayer<VectorTile, Featustroked: true,filled: false,clipBounds: bounds,- extensions: bounds ? [new ClipExtension()] : []+ extensions: bounds+ ? [options.isGlobeMode ? new GlobeClipExtension() : new ClipExtension()]+ : []});});} catch {diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex fe2ec55ad..06ec9fa95 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -46,7 +46,13 @@ export default {water: 'Water',land: 'Land','3dBuilding': '3D Building',- background: 'Background'+ background: 'Background',+ atmosphere: 'Atmosphere',+ basemap: 'Basemap',+ adminBorders: 'Admin Borders',+ terminator: 'Day/Night',+ sunAzimuth: 'Sun Azimuth',+ surface: 'Globe Surface'},panel: {text: {@@ -245,13 +251,15 @@ export default {addData: 'Add Data',addLayer: 'Add Layer',layerBlending: 'Layer Blending',- overlayBlending: 'Overlay Blending'+ overlayBlending: 'Overlay Blending',+ globeUnsupported: '{layerType} layer is not supported in Globe mode'},mapManager: {mapStyle: 'Map style',addMapStyle: 'Add Map Style','3dBuildingColor': '3D Building Color',- backgroundColor: 'Background Color'+ backgroundColor: 'Background Color',+ globeLayers: 'Globe Layers'},effectManager: {effects: 'Effects',@@ -349,6 +357,10 @@ export default {selectSplitMode: 'Select map view mode',showLegend: 'Show legend',disable3DMap: 'Disable 3D Map',+ globeMap: 'Globe Map',+ disableGlobeMap: 'Disable Globe Map',+ viewMode: 'View Mode',+ top: 'Top',DrawOnMap: 'Draw on map',selectLocale: 'Select locale',showAiAssistantPanel: 'Show AI Assistant',diff --git a/src/reducers/src/combined-updaters.ts b/src/reducers/src/combined-updaters.tsindex 70ba7a406..35bde1363 100644--- a/src/reducers/src/combined-updaters.ts+++ b/src/reducers/src/combined-updaters.ts@@ -18,7 +18,8 @@ import {import {receiveMapConfigUpdater as stateMapConfigUpdater,toggleSplitMapUpdater as mapStateToggleSplitMapUpdater,- setMapSplitModeUpdater as mapStateSetMapSplitModeUpdater+ setMapSplitModeUpdater as mapStateSetMapSplitModeUpdater,+ setMapViewModeUpdater} from './map-state-updaters';import {mapStyleChangeUpdater,@@ -41,7 +42,8 @@ import {VisState} from '@kepler.gl/schemas';import {Layer} from '@kepler.gl/layers';import {isPlainObject, computeSplitMapLayers} from '@kepler.gl/utils';import {findMapBounds} from './data-utils';-import {BASE_MAP_COLOR_MODES, OVERLAY_BLENDINGS, MapSplitMode} from '@kepler.gl/constants';+import {BASE_MAP_COLOR_MODES, OVERLAY_BLENDINGS, NO_MAP_ID, MapSplitMode} from '@kepler.gl/constants';+import {getBasemapColorsForStyle, DEFAULT_BASEMAP_COLOR} from '@kepler.gl/deckgl-layers';export type KeplerGlState = {visState: VisState;@@ -302,7 +304,7 @@ export const combinedMapStyleChangeUpdater = (const getColorMode = key => mapStyle.mapStyles[key]?.colorMode;const prevColorMode = getColorMode(mapStyle.styleType);const nextColorMode = getColorMode(payload.styleType);- let {visState} = state;+ let {visState, mapState} = state;if (nextColorMode !== prevColorMode) {switch (nextColorMode) {case BASE_MAP_COLOR_MODES.DARK:@@ -321,13 +323,105 @@ export const combinedMapStyleChangeUpdater = (// do nothing}}++ // Update globe config colors when style changes and globe is enabled+ if (mapState.globe?.enabled) {+ // Switching from "No Basemap" to a basemap - restore basemap sub-toggles+ if (payload.styleType !== NO_MAP_ID && mapStyle.styleType === NO_MAP_ID) {+ mapState = {+ ...mapState,+ globe: {+ ...mapState.globe,+ config: {+ ...mapState.globe.config,+ basemap: true,+ labels: true,+ adminLines: true,+ water: true+ }+ }+ };+ }+ mapState = syncGlobeConfigColorsToStyle(mapState, mapStyle, payload.styleType);+ }+return {...state,visState,+ mapState,mapStyle: mapStyleChangeUpdater(mapStyle, {payload: {...payload}})};};+/**+ * Derive globe basemap colors (surface / water / admin lines) from a map style and+ * return an updated mapState with those colors written into `globe.config`. Used both+ * when the base map style changes and when entering globe mode, so the globe always+ * reflects the currently selected basemap instead of the static DEFAULT_GLOBE_CONFIG.+ */+export function syncGlobeConfigColorsToStyle(+ mapState: MapState,+ mapStyle: MapStyle,+ styleType: string+): MapState {+ if (!mapState.globe?.enabled) {+ return mapState;+ }++ const nextStyleObj = mapStyle.mapStyles[styleType];+ const nextGlobeConfig = {...mapState.globe.config};++ if (styleType === NO_MAP_ID) {+ nextGlobeConfig.basemap = false;+ nextGlobeConfig.labels = false;+ nextGlobeConfig.adminLines = false;+ nextGlobeConfig.water = false;+ nextGlobeConfig.surfaceColor = DEFAULT_BASEMAP_COLOR.backgroundFillColor;+ nextGlobeConfig.waterColor = DEFAULT_BASEMAP_COLOR.basemapWaterFillColor;+ nextGlobeConfig.adminLinesColor = DEFAULT_BASEMAP_COLOR.basemapAdminLineColor;+ } else {+ const basemapColors = nextStyleObj+ ? getBasemapColorsForStyle(styleType, {+ style: nextStyleObj.style,+ layerGroups: nextStyleObj.layerGroups+ })+ : // Style object not yet loaded - use known presets by style type+ getBasemapColorsForStyle(styleType);+ nextGlobeConfig.surfaceColor = basemapColors.backgroundFillColor;+ nextGlobeConfig.waterColor = basemapColors.basemapWaterFillColor;+ nextGlobeConfig.adminLinesColor = basemapColors.basemapAdminLineColor;+ }++ return {+ ...mapState,+ globe: {+ ...mapState.globe,+ config: nextGlobeConfig+ }+ };+}++/**+ * Updater that switches the map view mode (2D / 3D / Globe). Runs the base map-state+ * updater and, when entering globe mode, syncs the globe basemap colors to the+ * currently selected map style so the globe doesn't show stale default colors.+ */+export const combinedSetMapViewModeUpdater = (+ state: KeplerGlState,+ action: MapStateActions.SetMapViewModeUpdaterAction+): KeplerGlState => {+ let mapState = setMapViewModeUpdater(state.mapState, action);++ if (mapState.globe?.enabled) {+ mapState = syncGlobeConfigColorsToStyle(mapState, state.mapStyle, state.mapStyle.styleType);+ }++ return {+ ...state,+ mapState+ };+};+/*** Updater that changes the layer type by calling `layerTypeChangeUpdater` on visState.* In addition to that, if the new layer type has the `darkBaseMapEnabled` configdiff --git a/src/reducers/src/composers.ts b/src/reducers/src/composers.tsindex 7b3c9ec2d..40f53676e 100644--- a/src/reducers/src/composers.ts+++ b/src/reducers/src/composers.ts@@ -11,6 +11,7 @@ import * as combinedUpdaters from './combined-updaters';const actionHandler = {[ActionTypes.ADD_DATA_TO_MAP]: combinedUpdaters.addDataToMapUpdater,[ActionTypes.MAP_STYLE_CHANGE]: combinedUpdaters.combinedMapStyleChangeUpdater,+ [ActionTypes.SET_MAP_VIEW_MODE]: combinedUpdaters.combinedSetMapViewModeUpdater,[ActionTypes.LAYER_TYPE_CHANGE]: combinedUpdaters.combinedLayerTypeChangeUpdater,[ActionTypes.LOAD_FILES_SUCCESS]: combinedUpdaters.loadFilesSuccessUpdater,[ActionTypes.TOGGLE_SPLIT_MAP]: combinedUpdaters.toggleSplitMapUpdater,diff --git a/src/reducers/src/layer-utils.ts b/src/reducers/src/layer-utils.tsindex 004c90e91..a70f42b86 100644--- a/src/reducers/src/layer-utils.ts+++ b/src/reducers/src/layer-utils.ts@@ -607,7 +607,8 @@ export function computeDeckLayers(if (editorInfo) {editorLayer.push(getEditorLayer({- ...editorInfo+ ...editorInfo,+ mapState}));}diff --git a/src/reducers/src/map-state-updaters.ts b/src/reducers/src/map-state-updaters.tsindex 45a4e4c93..7e7f51f46 100644--- a/src/reducers/src/map-state-updaters.ts+++ b/src/reducers/src/map-state-updaters.ts@@ -16,7 +16,7 @@ import {} from '@kepler.gl/utils';import {MapStateActions, ReceiveMapConfigPayload, ActionTypes} from '@kepler.gl/actions';import {MapState, Bounds, Viewport} from '@kepler.gl/types';-import {MapSplitMode} from '@kepler.gl/constants';+import {MapSplitMode, MapViewMode, DEFAULT_GLOBE_CONFIG, GLOBE_MIN_ZOOM, GLOBE_MAX_ZOOM, GLOBE_MAX_LATITUDE} from '@kepler.gl/constants';/*** Updaters for `mapState` reducer. Can be used in your root reducer to directly modify kepler.gl's state.@@ -97,6 +97,11 @@ export const INITIAL_MAP_STATE: MapState = {isViewportSynced: true,isZoomLocked: false,splitMapViewports: [],+ mapViewMode: MapViewMode.MODE_2D,+ globe: {+ enabled: false,+ config: DEFAULT_GLOBE_CONFIG+ },mapSplitMode: MapSplitMode.SINGLE_MAP,swipeComparePercentage: 50};@@ -211,13 +216,24 @@ export const fitBoundsUpdater = (* @public*/export const togglePerspectiveUpdater = (state: MapState): MapState => {+ // Only drop min/maxZoom when we're actually leaving globe mode, where those+ // bounds are set to globe-only values. If globe was never enabled these are+ // the app's own custom bounds and must be preserved.+ const wasGlobeEnabled = Boolean(state.globe?.enabled);+const newState = {...state,...{pitch: state.dragRotate ? 0 : 50,bearing: state.dragRotate ? 0 : 24},- dragRotate: !state.dragRotate+ dragRotate: !state.dragRotate,+ mapViewMode: state.dragRotate ? MapViewMode.MODE_2D : MapViewMode.MODE_3D,+ globe: {...state.globe!, enabled: false},+ // Leaving globe mode: drop globe-only zoom bounds so the flat map (and+ // consumers of mapState such as video export) aren't left clamped. When+ // globe was never on, keep whatever min/maxZoom the app configured.+ ...(wasGlobeEnabled ? {minZoom: undefined, maxZoom: undefined} : {})};// if toggling 3d and 2d while split and unsynced@@ -234,6 +250,101 @@ export const togglePerspectiveUpdater = (state: MapState): MapState => {return newState;};+/**+ * Set map view mode (2D, 3D, Globe)+ * @memberof mapStateUpdaters+ * @public+ */+export const setMapViewModeUpdater = (+ state: MapState,+ action: MapStateActions.SetMapViewModeUpdaterAction+): MapState => {+ const {mapViewMode} = action.payload;+ let nextState: MapState;++ // Only clear min/maxZoom when leaving globe mode (where they hold globe-only+ // bounds). Otherwise preserve the app's custom bounds.+ const wasGlobeEnabled = Boolean(state.globe?.enabled);++ switch (mapViewMode) {+ case MapViewMode.MODE_2D:+ nextState = {+ ...state,+ globe: {...state.globe!, enabled: false},+ pitch: 0,+ bearing: 0,+ dragRotate: false,+ // Clear the globe-only zoom bounds so the flat map (and anything that+ // reads mapState, e.g. video export) is not left with globe's+ // min/maxZoom after leaving globe mode. Only when globe was actually on.+ ...(wasGlobeEnabled ? {minZoom: undefined, maxZoom: undefined} : {}),+ mapViewMode+ };+ break;+ case MapViewMode.MODE_3D:+ nextState = {+ ...state,+ globe: {...state.globe!, enabled: false},+ pitch: 50,+ bearing: 24,+ dragRotate: true,+ ...(wasGlobeEnabled ? {minZoom: undefined, maxZoom: undefined} : {}),+ mapViewMode+ };+ break;+ case MapViewMode.MODE_GLOBE:+ nextState = {+ ...state,+ globe: {...state.globe!, enabled: true},+ dragRotate: true,+ pitch: 0,+ bearing: 0,+ // Allow zooming out further than the default so the whole globe can be+ // pulled back on screen. Cap the max zoom so the basemap tiles stay+ // coherent (they break down at high globe zoom in deck.gl 9.x).+ minZoom: GLOBE_MIN_ZOOM,+ maxZoom: GLOBE_MAX_ZOOM,+ zoom: Math.min(Math.max(state.zoom, GLOBE_MIN_ZOOM), GLOBE_MAX_ZOOM),+ mapViewMode+ };+ break;+ default:+ return state;+ }++ if (nextState.splitMapViewports.length) {+ nextState.splitMapViewports = nextState.splitMapViewports.map(currentViewport => ({+ ...currentViewport,+ pitch: nextState.pitch,+ bearing: nextState.bearing,+ dragRotate: nextState.dragRotate+ }));+ }++ return nextState;+};++/**+ * Update globe config+ * @memberof mapStateUpdaters+ * @public+ */+export const globeConfigChangeUpdater = (+ state: MapState,+ action: MapStateActions.GlobeConfigChangeUpdaterAction+): MapState => {+ return {+ ...state,+ globe: {+ ...state.globe!,+ config: {+ ...state.globe!.config,+ ...action.payload+ }+ }+ };+};+/*** reset mapState to initial State* @memberof mapStateUpdaters@@ -578,13 +689,49 @@ function updateViewport(originalViewport: Viewport, viewportUpdates: Viewport):...(definedProps(viewportUpdates) || {})};- // Make sure zoom level doesn't go bellow minZoom if defined- if (newViewport.minZoom && newViewport.zoom && newViewport.zoom < newViewport.minZoom) {- newViewport.zoom = newViewport.minZoom;- }- // Make sure zoom level doesn't go above maxZoom if defined- if (newViewport.maxZoom && newViewport.zoom && newViewport.zoom > newViewport.maxZoom) {- newViewport.zoom = newViewport.maxZoom;+ // deck.gl's globe controller applies a latitude-dependent adjustment to the+ // zoom range (see KeplerGlobeView._constrainZoom). If we clamp the propagated+ // zoom here against the raw minZoom/maxZoom (without that adjustment), Redux+ // ends up disagreeing with the controller: the controller lets the user pull+ // the globe further out, but this clamp snaps zoom back to `minZoom` when the+ // interaction's inertia transition ends. Apply the same adjustment in globe+ // mode so Redux stays consistent with the controller and there's no snap-back.+ const isGlobe = (newViewport as any).globe?.enabled;++ if (isGlobe) {+ // Keep the camera target within a latitude band around the equator so the+ // stored viewport can't be centered on the poles (matches the globe+ // controller's applyConstraints so geocoder/programmatic updates agree).+ if (typeof newViewport.latitude === 'number') {+ newViewport.latitude = Math.min(+ GLOBE_MAX_LATITUDE,+ Math.max(-GLOBE_MAX_LATITUDE, newViewport.latitude)+ );+ }+ const zoomAdjustment = Math.log2(Math.cos(((newViewport.latitude ?? 0) * Math.PI) / 180));+ if (+ typeof newViewport.minZoom === 'number' &&+ typeof newViewport.zoom === 'number' &&+ newViewport.zoom < newViewport.minZoom + zoomAdjustment+ ) {+ newViewport.zoom = newViewport.minZoom + zoomAdjustment;+ }+ if (+ typeof newViewport.maxZoom === 'number' &&+ typeof newViewport.zoom === 'number' &&+ newViewport.zoom > newViewport.maxZoom + zoomAdjustment+ ) {+ newViewport.zoom = newViewport.maxZoom + zoomAdjustment;+ }+ } else {+ // Make sure zoom level doesn't go bellow minZoom if defined+ if (newViewport.minZoom && newViewport.zoom && newViewport.zoom < newViewport.minZoom) {+ newViewport.zoom = newViewport.minZoom;+ }+ // Make sure zoom level doesn't go above maxZoom if defined+ if (newViewport.maxZoom && newViewport.zoom && newViewport.zoom > newViewport.maxZoom) {+ newViewport.zoom = newViewport.maxZoom;+ }}// Limit viewport update based on maxBoundsif (newViewport.maxBounds && validateBounds(newViewport.maxBounds)) {diff --git a/src/reducers/src/map-state.ts b/src/reducers/src/map-state.tsindex 64090335f..6fc8cba09 100644--- a/src/reducers/src/map-state.ts+++ b/src/reducers/src/map-state.ts@@ -17,6 +17,8 @@ const actionHandler = {[ActionTypes.RESET_MAP_CONFIG]: mapStateUpdaters.resetMapConfigUpdater,[ActionTypes.TOGGLE_SPLIT_MAP]: mapStateUpdaters.toggleSplitMapUpdater,[ActionTypes.TOGGLE_SPLIT_MAP_VIEWPORT]: mapStateUpdaters.toggleSplitMapViewportUpdater,+ [ActionTypes.SET_MAP_VIEW_MODE]: mapStateUpdaters.setMapViewModeUpdater,+ [ActionTypes.GLOBE_CONFIG_CHANGE]: mapStateUpdaters.globeConfigChangeUpdater,[ActionTypes.SET_MAP_SPLIT_MODE]: mapStateUpdaters.setMapSplitModeUpdater,[ActionTypes.SET_SWIPE_COMPARE_PERCENTAGE]: mapStateUpdaters.setSwipeComparePercentageUpdater};diff --git a/src/schemas/src/map-state-schema.ts b/src/schemas/src/map-state-schema.tsindex ea9794b2e..f9e9c4818 100644--- a/src/schemas/src/map-state-schema.ts+++ b/src/schemas/src/map-state-schema.ts@@ -22,7 +22,12 @@ export const propertiesV1 = {splitMapViewports: null,maxPitch: null,mapSplitMode: null,- swipeComparePercentage: null+ swipeComparePercentage: null,+ // Persist the current view mode (2D / 3D / Globe) and the full globe config+ // (colors, toggles, background) so globe maps round-trip through save/load,+ // matching studio-monorepo's persisted map state.+ mapViewMode: null,+ globe: null};const mapStateSchema = {diff --git a/src/schemas/src/schema-manager.ts b/src/schemas/src/schema-manager.tsindex 7ea120d76..2c9d8bd60 100644--- a/src/schemas/src/schema-manager.ts+++ b/src/schemas/src/schema-manager.ts@@ -27,6 +27,27 @@ export type SavedMapState = {isViewportSynced?: true;isZoomLocked?: false;splitMapViewports?: [];+ mapViewMode?: string;+ globe?: {+ enabled: boolean;+ config: {+ atmosphere: boolean;+ azimuth: boolean;+ azimuthAngle: number;+ terminator: boolean;+ terminatorOpacity: number;+ basemap: boolean;+ labels: boolean;+ labelsColor: [number, number, number];+ adminLines: boolean;+ adminLinesColor: [number, number, number];+ water: boolean;+ waterColor: [number, number, number];+ surface: boolean;+ surfaceColor: [number, number, number];+ backgroundColor: [number, number, number];+ };+ };};export type SavedLayerGroups = {diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.tsindex 06e643459..4782e5aa2 100644--- a/src/types/reducers.d.ts+++ b/src/types/reducers.d.ts@@ -2,7 +2,7 @@// Copyright contributors to the kepler.gl projectimport {Field, Millisecond} from './types';-import {MapSplitMode} from '@kepler.gl/constants';+import {MapSplitMode, MapViewMode} from '@kepler.gl/constants';type MapViewState = {latitude: number;longitude: number;@@ -39,6 +39,27 @@ export type MapState = {isZoomLocked: boolean;/** An array of either 0 or 2 Viewport objects (index 0 for left map; index 1 for right map) */splitMapViewports: Viewport[];+ mapViewMode?: MapViewMode;+ globe?: {+ enabled: boolean;+ config: {+ atmosphere: boolean;+ azimuth: boolean;+ azimuthAngle: number;+ terminator: boolean;+ terminatorOpacity: number;+ basemap: boolean;+ labels: boolean;+ labelsColor: [number, number, number];+ adminLines: boolean;+ adminLinesColor: [number, number, number];+ water: boolean;+ waterColor: [number, number, number];+ surfaceColor: [number, number, number];+ surface: boolean;+ backgroundColor: [number, number, number];+ };+ };/** The current split map mode (single, dual, swipe) */mapSplitMode: MapSplitMode;/** Swipe compare divider position as a percentage (0-100) */diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.tsindex 2ce588f09..831da2939 100644--- a/src/utils/src/application-config.ts+++ b/src/utils/src/application-config.ts@@ -128,6 +128,9 @@ export type KeplerApplicationConfig = {/** Whether to enable the swipe compare mode in split map view. Enabled by default. */enableSwipeMode?: boolean;+ /** Whether to show the option to switch to the globe view. Enabled by default. */+ enableGlobeView?: boolean;+/** Whether to enable the layer groups feature. Enabled by default. */enableLayerGroups?: boolean;@@ -240,6 +243,8 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {enableSwipeMode: true,+ enableGlobeView: true,+enableLayerGroups: true,customIcons: [],diff --git a/src/utils/src/effect-utils.ts b/src/utils/src/effect-utils.tsindex de168ebd4..0d66cfa22 100644--- a/src/utils/src/effect-utils.ts+++ b/src/utils/src/effect-utils.ts@@ -42,21 +42,38 @@ export function computeDeckEffects({// TODO: 1) deck effects per deck context 2) preserved between drawslet hasLightingShadow = false;+ // Light & Shadow and both Fog effects are not supported in globe mode:+ // - Fog effects are screen-space post-processing passes that read the flat+ // MapView depth buffer and don't make sense on the sphere.+ // - Shadows are cast on the flat ground plane, not the globe surface.+ // In globe mode we drop the fog effects entirely and force the lighting+ // effect into its shadow-disabled state (kept in the array, like the normal+ // "disabled" path, so the shadow shader module stays registered and layer+ // models don't end up with stale shadow_uShadowMap bindings).+ const isGlobeMode = Boolean(mapState?.globe?.enabled);+const deckEffects = visState.effectOrder.map(effectId => {const effect = findById(effectId)(visState.effects) as Effect | undefined;if (effect?.deckEffect) {+ const isFogEffect = effect.type === SURFACE_FOG_TYPE || effect.type === DISTANCE_FOG_TYPE;+ const isLightingEffect = effect.type === LIGHT_AND_SHADOW_EFFECT.type;++ // Globe mode: skip fog effects, and keep lighting effects only in their+ // shadow-disabled form.+ if (isGlobeMode && isFogEffect) {+ return null;+ }+// Always reset isExportMode so the flag doesn't persist from a// previous export session on reused effect instances.- if (- effect.type === LIGHT_AND_SHADOW_EFFECT.type ||- effect.type === SURFACE_FOG_TYPE ||- effect.type === DISTANCE_FOG_TYPE- ) {+ if (isLightingEffect || isFogEffect) {effect.deckEffect.isExportMode = Boolean(isExport);}- if (effect.isEnabled) {+ const enabledInThisView = effect.isEnabled && !(isGlobeMode && isLightingEffect);++ if (enabledInThisView) {// deck.gl's EffectManager matches effects by id and reuses old// instances (calling oldEffect.setProps(newEffect.props)) instead// of replacing them. When a lighting effect is removed and@@ -84,7 +101,7 @@ export function computeDeckEffects({// Disabling shadow on the lights avoids visual effects.disableLightingEffect(effect);}- if (effect.isEnabled || effect.type === LIGHT_AND_SHADOW_EFFECT.type) {+ if (enabledInThisView || effect.type === LIGHT_AND_SHADOW_EFFECT.type) {if (effect.type === LIGHT_AND_SHADOW_EFFECT.type) {hasLightingShadow = true;if (!isExport) {diff --git a/src/utils/src/map-utils.ts b/src/utils/src/map-utils.tsindex 756b2fcb3..6d8ae85b1 100644--- a/src/utils/src/map-utils.ts+++ b/src/utils/src/map-utils.ts@@ -2,6 +2,8 @@// Copyright contributors to the kepler.gl projectimport WebMercatorViewport from 'viewport-mercator-project';+// @ts-ignore GlobeViewport 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 {_GlobeViewport as GlobeViewport} from '@deck.gl/core';import {TRANSITION_DURATION} from '@kepler.gl/constants';import {SplitMapLayers, SplitMap, Viewport, MapState} from '@kepler.gl/types';@@ -62,13 +64,14 @@ export const getMapLayersFromSplitMaps = (* @returns A viewport.*/export const getViewportFromMapState = (mapState: MapState): Viewport => {- // Make sure we capture error- // e.g. Error message: "Pixel project matrix not invertible"let viewPort;try {- viewPort = new WebMercatorViewport(mapState);+ if (mapState.globe?.enabled) {+ viewPort = new GlobeViewport(mapState);+ } else {+ viewPort = new WebMercatorViewport(mapState);+ }} catch {- // catch error and fallback to default map stateviewPort = new WebMercatorViewport(validateViewPort(mapState));}diff --git a/test/browser/components/effects/effect-time-configurator-test.js b/test/browser/components/effects/effect-time-configurator-test.jsindex 359e83524..7a6261aaa 100644--- a/test/browser/components/effects/effect-time-configurator-test.js+++ b/test/browser/components/effects/effect-time-configurator-test.js@@ -130,7 +130,7 @@ test('Components -> EffectTimeConfigurator -> pick time', t => {.simulate('change', {target: {value: '2022', name: 'year'}});t.deepEqual(- onDateTimeChange.getCall(3).args[0],+ onDateTimeChange.lastCall.args[0],{timestamp: 1643820360000},`Date should be updated`);@@ -148,7 +148,7 @@ test('Components -> EffectTimeConfigurator -> pick time', t => {.simulate('change', {target: {value: '30', name: 'minute'}});t.deepEqual(- onDateTimeChange.getCall(6).args[0],+ onDateTimeChange.lastCall.args[0],{timestamp: 1690317000000},`Time should be updated`);@@ -156,7 +156,7 @@ test('Components -> EffectTimeConfigurator -> pick time', t => {// pick current time buttonwrapper.find('Button').at(0).simulate('click');t.ok(- Math.abs(onDateTimeChange.getCall(7).args[0].timestamp - Date.now()) < 1000,+ Math.abs(onDateTimeChange.lastCall.args[0].timestamp - Date.now()) < 1000,`Should pick current date & time`);@@ -261,7 +261,7 @@ test('Components -> EffectTimeConfigurator -> time with custom timezone update',// Call twice to propagate chagne in date-time-picker.simulate('change', {target: {value: '20', name: 'hour24'}});t.deepEqual(- onDateTimeChange.getCall(1).args[0],+ onDateTimeChange.lastCall.args[0],{timestamp: 1690848180000},`time changed & timezone taken into account`);@@ -301,7 +301,7 @@ test('Components -> EffectTimeConfigurator -> date with custom timezone update',.simulate('change', {target: {value: '10', name: 'day'}});t.deepEqual(- onDateTimeChange.getCall(1).args[0],+ onDateTimeChange.lastCall.args[0],{timestamp: 1689026580000},`date changed & timezone taken into account`);diff --git a/test/browser/components/map/map-control-test.js b/test/browser/components/map/map-control-test.jsindex b7b7f48ac..759dfa5ee 100644--- a/test/browser/components/map/map-control-test.js+++ b/test/browser/components/map/map-control-test.js@@ -202,11 +202,19 @@ test('MapControlFactory - click options', t => {// click split Map - now opens mode menu since enableSwipeMode is truewrapper.find('.map-control-button.split-map').at(0).simulate('click');// onToggleSplitMap is not called directly when mode menu is available- t.notOk(onToggleSplitMap.calledOnce, 'should not call onToggleSplitMap when mode menu is enabled');+ t.notOk(+ onToggleSplitMap.calledOnce,+ 'should not call onToggleSplitMap when mode menu is enabled'+ );- // click toggle3d+ // click toggle3d - now opens the view-mode menu (Top/3D/Globe) instead of+ // toggling perspective directly, mirroring the split-map mode menu above.wrapper.find('.map-control-button.toggle-3d').at(0).simulate('click');- t.ok(onTogglePerspective.calledOnce, 'should call onTogglePerspective');+ // onTogglePerspective is not called directly when the view-mode menu is available+ t.notOk(+ onTogglePerspective.calledOnce,+ 'should not call onTogglePerspective directly when view-mode menu is enabled'+ );// click map legendwrapper.find('.map-control-button.show-legend').at(0).simulate('click');diff --git a/test/node/reducers/map-state-test.js b/test/node/reducers/map-state-test.jsindex 89c0d511c..0f1ca4e2d 100644--- a/test/node/reducers/map-state-test.js+++ b/test/node/reducers/map-state-test.js@@ -11,7 +11,9 @@ import {toggleSplitMapViewport,receiveMapConfig,setMapSplitMode,- setSwipeComparePercentage+ setSwipeComparePercentage,+ setMapViewMode,+ globeConfigChange} from '@kepler.gl/actions';import {@@ -20,6 +22,13 @@ import {INITIAL_MAP_STATE} from '@kepler.gl/reducers';+import {+ MapViewMode,+ GLOBE_MIN_ZOOM,+ GLOBE_MAX_ZOOM,+ DEFAULT_GLOBE_CONFIG+} from '@kepler.gl/constants';+const InitialMapState = reducer(undefined, {});test('#mapStateReducer', t => {const newState = reducer(undefined, {});@@ -739,11 +748,144 @@ test('#mapStateReducer -> toggleSplitMapViewport in SWIPE_COMPARE mode', t => {const stateBeforeToggle = state;state = reducer(state, toggleSplitMapViewport({isViewportSynced: false}));+ t.equal(state, stateBeforeToggle, 'should not allow unsyncing viewports in swipe mode');++ t.end();+});++test('#mapStateReducer -> SET_MAP_VIEW_MODE: enter globe mode', t => {+ const state = reducer(INITIAL_MAP_STATE, setMapViewMode(MapViewMode.MODE_GLOBE));++ t.equal(state.mapViewMode, MapViewMode.MODE_GLOBE, 'should set mapViewMode to globe');+ t.equal(state.globe.enabled, true, 'should enable globe');+ t.equal(state.pitch, 0, 'should reset pitch entering globe');+ t.equal(state.bearing, 0, 'should reset bearing entering globe');+ t.equal(state.dragRotate, true, 'should enable dragRotate in globe');+ t.equal(state.minZoom, GLOBE_MIN_ZOOM, 'should apply globe minZoom');+ t.equal(state.maxZoom, GLOBE_MAX_ZOOM, 'should apply globe maxZoom');++ t.end();+});++test('#mapStateReducer -> SET_MAP_VIEW_MODE: globe clamps zoom into range', t => {+ // zoom above the cap should clamp down to GLOBE_MAX_ZOOM+ let state = reducer(+ {...INITIAL_MAP_STATE, zoom: GLOBE_MAX_ZOOM + 5},+ setMapViewMode(MapViewMode.MODE_GLOBE)+ );+ t.equal(state.zoom, GLOBE_MAX_ZOOM, 'zoom above cap should clamp to GLOBE_MAX_ZOOM');++ // zoom below the floor should clamp up to GLOBE_MIN_ZOOM+ state = reducer(+ {...INITIAL_MAP_STATE, zoom: GLOBE_MIN_ZOOM - 5},+ setMapViewMode(MapViewMode.MODE_GLOBE)+ );+ t.equal(state.zoom, GLOBE_MIN_ZOOM, 'zoom below floor should clamp to GLOBE_MIN_ZOOM');++ // zoom already in range should be preserved+ state = reducer({...INITIAL_MAP_STATE, zoom: 6}, setMapViewMode(MapViewMode.MODE_GLOBE));+ t.equal(state.zoom, 6, 'zoom within range should be preserved');++ t.end();+});++test('#mapStateReducer -> SET_MAP_VIEW_MODE: leaving globe clears globe zoom bounds', t => {+ // enter globe (which sets min/maxZoom to globe bounds)+ const globeState = reducer(INITIAL_MAP_STATE, setMapViewMode(MapViewMode.MODE_GLOBE));+ t.equal(globeState.minZoom, GLOBE_MIN_ZOOM, 'sanity: globe minZoom set');+ t.equal(globeState.maxZoom, GLOBE_MAX_ZOOM, 'sanity: globe maxZoom set');++ // globe -> 2D should clear the globe-only bounds so the flat map isn't clamped+ const to2d = reducer(globeState, setMapViewMode(MapViewMode.MODE_2D));+ t.equal(to2d.globe.enabled, false, '2D should disable globe');+ t.equal(to2d.minZoom, undefined, 'globe -> 2D should clear minZoom');+ t.equal(to2d.maxZoom, undefined, 'globe -> 2D should clear maxZoom');+ t.equal(to2d.pitch, 0, 'globe -> 2D should reset pitch');+ t.equal(to2d.bearing, 0, 'globe -> 2D should reset bearing');++ // globe -> 3D should also clear the globe-only bounds+ const to3d = reducer(globeState, setMapViewMode(MapViewMode.MODE_3D));+ t.equal(to3d.globe.enabled, false, '3D should disable globe');+ t.equal(to3d.minZoom, undefined, 'globe -> 3D should clear minZoom');+ t.equal(to3d.maxZoom, undefined, 'globe -> 3D should clear maxZoom');+ t.equal(to3d.pitch, 50, 'globe -> 3D should set 3D pitch');+ t.equal(to3d.bearing, 24, 'globe -> 3D should set 3D bearing');++ t.end();+});++test('#mapStateReducer -> SET_MAP_VIEW_MODE: preserves custom zoom bounds when globe never enabled', t => {+ // App configured custom bounds and never entered globe: switching 2D/3D must+ // NOT wipe those bounds (only leaving globe clears them).+ const customState = {...INITIAL_MAP_STATE, minZoom: 3, maxZoom: 15};++ const to3d = reducer(customState, setMapViewMode(MapViewMode.MODE_3D));+ t.equal(to3d.minZoom, 3, '2D -> 3D should preserve custom minZoom');+ t.equal(to3d.maxZoom, 15, '2D -> 3D should preserve custom maxZoom');++ const to2d = reducer(+ {...customState, mapViewMode: MapViewMode.MODE_3D},+ setMapViewMode(MapViewMode.MODE_2D)+ );+ t.equal(to2d.minZoom, 3, '3D -> 2D should preserve custom minZoom');+ t.equal(to2d.maxZoom, 15, '3D -> 2D should preserve custom maxZoom');++ t.end();+});++test('#mapStateReducer -> SET_MAP_VIEW_MODE: invalid mode is no-op', t => {+ const state = reducer(INITIAL_MAP_STATE, setMapViewMode('NOT_A_MODE'));+ t.equal(state, INITIAL_MAP_STATE, 'unknown view mode should return same state reference');++ t.end();+});++test('#mapStateReducer -> TOGGLE_PERSPECTIVE: leaving globe clears globe zoom bounds', t => {+ // enter globe first, then toggle perspective (which forces globe off)+ const globeState = reducer(INITIAL_MAP_STATE, setMapViewMode(MapViewMode.MODE_GLOBE));+ const toggled = reducer(globeState, togglePerspective());++ t.equal(toggled.globe.enabled, false, 'togglePerspective should disable globe');+ t.equal(toggled.minZoom, undefined, 'leaving globe via togglePerspective should clear minZoom');+ t.equal(toggled.maxZoom, undefined, 'leaving globe via togglePerspective should clear maxZoom');++ t.end();+});++test('#mapStateReducer -> TOGGLE_PERSPECTIVE: preserves custom zoom bounds when globe never enabled', t => {+ const customState = {...INITIAL_MAP_STATE, minZoom: 4, maxZoom: 14};+ const toggled = reducer(customState, togglePerspective());++ t.equal(toggled.minZoom, 4, 'togglePerspective without globe should preserve custom minZoom');+ t.equal(toggled.maxZoom, 14, 'togglePerspective without globe should preserve custom maxZoom');+ t.equal(toggled.dragRotate, true, 'togglePerspective should still flip dragRotate');++ t.end();+});++test('#mapStateReducer -> GLOBE_CONFIG_CHANGE: merges partial config', t => {+ const globeState = reducer(INITIAL_MAP_STATE, setMapViewMode(MapViewMode.MODE_GLOBE));++ const updated = reducer(+ globeState,+ globeConfigChange({atmosphere: false, backgroundColor: [10, 20, 30]})+ );++ t.equal(updated.globe.config.atmosphere, false, 'should update atmosphere');+ t.deepEqual(updated.globe.config.backgroundColor, [10, 20, 30], 'should update backgroundColor');+ // untouched keys should be preserved from the defaultst.equal(- state,- stateBeforeToggle,- 'should not allow unsyncing viewports in swipe mode'+ updated.globe.config.terminator,+ DEFAULT_GLOBE_CONFIG.terminator,+ 'should preserve unrelated config keys'+ );+ t.equal(+ updated.globe.config.water,+ DEFAULT_GLOBE_CONFIG.water,+ 'should preserve unrelated config keys');+ // changing config must not toggle globe enabled state+ t.equal(updated.globe.enabled, true, 'should not change globe enabled flag');t.end();});diff --git a/test/node/schemas/map-state-schema-test.js b/test/node/schemas/map-state-schema-test.jsindex 5a4cf4cd9..4698ff62c 100644--- a/test/node/schemas/map-state-schema-test.js+++ b/test/node/schemas/map-state-schema-test.js@@ -4,6 +4,7 @@import test from 'tape';import cloneDeep from 'lodash/cloneDeep';import SchemaManager from '@kepler.gl/schemas';+import {DEFAULT_GLOBE_CONFIG, MapViewMode} from '@kepler.gl/constants';import {InitialState} from 'test/helpers/mock-state';test('#mapStateSchema -> v1 -> save load mapState', t => {@@ -29,9 +30,11 @@ test('#mapStateSchema -> v1 -> save load mapState', t => {'splitMapViewports','maxPitch','mapSplitMode',- 'swipeComparePercentage'+ 'swipeComparePercentage',+ 'mapViewMode',+ 'globe'],- 'mapState should have all 12 entries'+ 'mapState should have all entries');const expected = {@@ -47,7 +50,12 @@ test('#mapStateSchema -> v1 -> save load mapState', t => {splitMapViewports: [],maxPitch: undefined,mapSplitMode: 'SINGLE_MAP',- swipeComparePercentage: 50+ swipeComparePercentage: 50,+ mapViewMode: MapViewMode.MODE_2D,+ globe: {+ enabled: false,+ config: DEFAULT_GLOBE_CONFIG+ }};t.deepEqual(msToSave, expected, 'save mapState should be current');@@ -55,3 +63,40 @@ test('#mapStateSchema -> v1 -> save load mapState', t => {t.end();});++test('#mapStateSchema -> v1 -> save load globe-enabled mapState', t => {+ const initialState = cloneDeep(InitialState);+ // Enable globe with a non-default config to verify the full round-trip.+ initialState.mapState.mapViewMode = MapViewMode.MODE_GLOBE;+ initialState.mapState.globe = {+ enabled: true,+ config: {+ ...DEFAULT_GLOBE_CONFIG,+ atmosphere: false,+ terminator: false,+ labels: true,+ basemap: false,+ waterColor: [1, 2, 3],+ backgroundColor: [10, 20, 30]+ }+ };++ const savedState = SchemaManager.getConfigToSave(initialState);+ const msToSave = savedState.config.mapState;+ const msLoaded = SchemaManager.parseSavedConfig(savedState).mapState;++ t.equal(msToSave.mapViewMode, MapViewMode.MODE_GLOBE, 'saved mapViewMode should be globe');+ t.deepEqual(+ msToSave.globe,+ initialState.mapState.globe,+ 'saved globe config should match non-default config'+ );+ t.equal(msLoaded.mapViewMode, MapViewMode.MODE_GLOBE, 'loaded mapViewMode should be globe');+ t.deepEqual(+ msLoaded.globe,+ initialState.mapState.globe,+ 'loaded globe config should round-trip non-default config'+ );++ t.end();+});diff --git a/test/node/utils/effect-utils-test.js b/test/node/utils/effect-utils-test.jsindex b52e2a484..4120cc769 100644--- a/test/node/utils/effect-utils-test.js+++ b/test/node/utils/effect-utils-test.js@@ -11,6 +11,7 @@ import {createEffect} from '@kepler.gl/effects';import {POSTPROCESSING_EFFECTS,LIGHT_AND_SHADOW_EFFECT,+ DISTANCE_FOG_TYPE,DEFAULT_POST_PROCESSING_EFFECT_TYPE} from '@kepler.gl/constants';@@ -57,6 +58,62 @@ test('effectUtils -> computeDeckEffects', t => {t.end();});+test('effectUtils -> computeDeckEffects in globe mode', t => {+ const initialState = InitialState.visState;+ let nextState = visStateReducer(+ initialState,+ VisStateActions.addEffect({id: 'e_ink', type: 'ink'})+ );+ nextState = visStateReducer(+ nextState,+ VisStateActions.addEffect({+ id: 'e_shadow',+ type: LIGHT_AND_SHADOW_EFFECT.type,+ parameters: {timestamp: 1689415852635} // daytime+ })+ );+ // Only one fog effect can exist at a time (enforced by addEffectUpdater), so+ // add just the distance fog effect.+ nextState = visStateReducer(+ nextState,+ VisStateActions.addEffect({id: 'e_distance_fog', type: DISTANCE_FOG_TYPE})+ );++ // Flat mode first: keeps ink + lighting + distance fog = 3 effects. Assert on+ // flat mode before globe mode because both calls share (and mutate) the same+ // lighting deckEffect instance.+ const flatEffects = computeDeckEffects({+ visState: nextState,+ mapState: {latitude: 51.033105, longitude: 0.348512}+ });+ t.equal(flatEffects.length, 3, 'flat mode keeps ink, lighting and the fog effect');+ t.ok(+ flatEffects.some(e => e.id === 'distance-fog-effect'),+ 'flat mode keeps the distance fog effect'+ );++ // Globe mode: drops the fog effect, keeps ink + lighting (shadow disabled).+ const globeEffects = computeDeckEffects({+ visState: nextState,+ mapState: {latitude: 51.033105, longitude: 0.348512, globe: {enabled: true}}+ });+ t.equal(globeEffects.length, 2, 'globe mode drops the fog effect');+ t.notOk(+ globeEffects.some(e => e.id === 'distance-fog-effect'),+ 'globe mode drops the distance fog effect'+ );++ const lightingEffects = globeEffects.filter(e => e instanceof LightingEffect);+ t.equal(lightingEffects.length, 1, 'lighting effect should be kept in globe mode');+ t.equal(+ lightingEffects[0].shadow,+ false,+ 'shadows should be disabled on the lighting effect in globe mode'+ );++ t.end();+});+test('effectUtils -> createEffect', t => {const defaultEffect = createEffect({});const postProcessingEffect = createEffect({diff --git a/yarn.lock b/yarn.lockindex e1c5ee76d..3f0d90894 100644--- a/yarn.lock+++ b/yarn.lock@@ -2853,7 +2853,16 @@ __metadata:languageName: nodelinkType: hard-"@floating-ui/dom@npm:^1.7.5, @floating-ui/dom@npm:^1.7.6":+"@floating-ui/core@npm:^1.8.0":+ version: 1.8.0+ resolution: "@floating-ui/core@npm:1.8.0"+ dependencies:+ "@floating-ui/utils": "npm:^0.2.12"+ checksum: 10c0/cece958f6fab0f8cd7740cd57988c4f8bc5356dca39dd4c093433d44c91952c3a02c7a54d93d7ed6c078b6544d531a29f66621d2839c8bfbb4467dca6aed7df0+ languageName: node+ linkType: hard++"@floating-ui/dom@npm:^1.7.5":version: 1.7.6resolution: "@floating-ui/dom@npm:1.7.6"dependencies:@@ -2863,29 +2872,39 @@ __metadata:languageName: nodelinkType: hard-"@floating-ui/react-dom@npm:^2.1.8":- version: 2.1.8- resolution: "@floating-ui/react-dom@npm:2.1.8"+"@floating-ui/dom@npm:^1.8.0":+ version: 1.8.0+ resolution: "@floating-ui/dom@npm:1.8.0"dependencies:- "@floating-ui/dom": "npm:^1.7.6"+ "@floating-ui/core": "npm:^1.8.0"+ "@floating-ui/utils": "npm:^0.2.12"+ checksum: 10c0/c32b2de7a596b69cfffa909c7028825e14f6319be1b45da529f8943c89fe16b75a49c214e800c87ded3f172353d3b99163d50072f11410488e756961b7b629cc+ languageName: node+ linkType: hard++"@floating-ui/react-dom@npm:^2.1.9":+ version: 2.1.9+ resolution: "@floating-ui/react-dom@npm:2.1.9"+ dependencies:+ "@floating-ui/dom": "npm:^1.8.0"peerDependencies:react: ">=16.8.0"react-dom: ">=16.8.0"- checksum: 10c0/26260ca4bb23b57c73b824062505abf977a008ce6e0463bdacca74f7e49853c4cd1d2bbf1a77c6caa17fa37dfffda2c6c4cd07a8737ebd7474aaff7818401d75+ checksum: 10c0/9fa9851069738cb9591a1ab2da16e257f193eae5fd2d6d48ad0b1e73f3c049929b6805c5ad43d4af3c1da63c60b215b0ee4651a1fe5caeb80e66d9d423744348languageName: nodelinkType: hard"@floating-ui/react@npm:^0.27.0":- version: 0.27.19- resolution: "@floating-ui/react@npm:0.27.19"+ version: 0.27.20+ resolution: "@floating-ui/react@npm:0.27.20"dependencies:- "@floating-ui/react-dom": "npm:^2.1.8"- "@floating-ui/utils": "npm:^0.2.11"+ "@floating-ui/react-dom": "npm:^2.1.9"+ "@floating-ui/utils": "npm:^0.2.12"tabbable: "npm:^6.0.0"peerDependencies:react: ">=17.0.0"react-dom: ">=17.0.0"- checksum: 10c0/2a2cdfd3e67e0606833b63f922ad2a9037974f22b944e1cb8c0991b4c40450f8413d69745c0bbf4646e5ba283747f60d2fdc9a8d289b68b24448e59d81a3a96d+ checksum: 10c0/5ebeb4c877128e9a274692849ceb2103b370441626e97ade38c25db5d94371dd7274292eda05208cc5d1c92c594a59595a1909799c2ac8ff44f9e651a4fe55b3languageName: nodelinkType: hard@@ -2896,6 +2915,13 @@ __metadata:languageName: nodelinkType: hard+"@floating-ui/utils@npm:^0.2.12":+ version: 0.2.12+ resolution: "@floating-ui/utils@npm:0.2.12"+ checksum: 10c0/bb910b90d56991a62011afaf5f8e0c4b7fb6dab69403f4dd17fbd6eb25560b28d533dff9791f270b4f459852e9006a1077b5d73cbedb5e34d9424afc6a828314+ languageName: node+ linkType: hard+"@flowmap.gl/data@npm:^9.2.0":version: 9.2.0resolution: "@flowmap.gl/data@npm:9.2.0"@@ -5255,6 +5281,7 @@ __metadata:"@kepler.gl/cloud-providers": "npm:3.3.0-alpha.3""@kepler.gl/common-utils": "npm:3.3.0-alpha.3""@kepler.gl/constants": "npm:3.3.0-alpha.3"+ "@kepler.gl/deckgl-layers": "npm:3.3.0-alpha.3""@kepler.gl/effects": "npm:3.3.0-alpha.3""@kepler.gl/layers": "npm:3.3.0-alpha.3""@kepler.gl/localization": "npm:3.3.0-alpha.3"@@ -5316,14 +5343,14 @@ __metadata:react: "npm:^19.0.0"react-color: "npm:^2.19.3"react-copy-to-clipboard: "npm:^5.1.1"- react-date-picker: "npm:^11.0.0"+ react-date-picker: "npm:^12.0.2"react-dom: "npm:^19.0.0"react-intl: "npm:^7.0.0"react-json-pretty: "npm:^2.2.0"react-map-gl: "npm:^8.1.1"react-modal: "npm:^3.16.3"react-redux: "npm:^9.1.0"- react-time-picker: "npm:^7.0.0"+ react-time-picker: "npm:^8.0.0"react-tooltip: "npm:^4.2.17"react-virtualized: "npm:9.22.6"redux: "npm:^5.0.0"@@ -5404,6 +5431,7 @@ __metadata:"@deck.gl/core": "npm:^9.3.1""@deck.gl/geo-layers": "npm:^9.3.1""@deck.gl/layers": "npm:^9.3.1"+ "@deck.gl/mesh-layers": "npm:^9.3.1""@kepler.gl/constants": "npm:3.3.0-alpha.3""@kepler.gl/types": "npm:3.3.0-alpha.3""@kepler.gl/utils": "npm:3.3.0-alpha.3"@@ -5415,6 +5443,8 @@ __metadata:"@luma.gl/webgl": "npm:^9.3.2""@mapbox/geo-viewport": "npm:^0.4.1""@mapbox/vector-tile": "npm:^1.3.1"+ "@math.gl/core": "npm:^4.1.0"+ "@math.gl/sun": "npm:^4.1.0""@math.gl/web-mercator": "npm:^4.1.0""@types/d3-array": "npm:^2.8.0""@types/geojson": "npm:^7946.0.8"@@ -11604,10 +11634,10 @@ __metadata:languageName: nodelinkType: hard-"@wojtekmaj/date-utils@npm:^1.1.3, @wojtekmaj/date-utils@npm:^1.5.0":- version: 1.5.1- resolution: "@wojtekmaj/date-utils@npm:1.5.1"- checksum: 10c0/7c213cca5ab6b84ef61b9aea2b9fb8a04bf4c9764b28a97ffc4ee46a3e81560532a74d106a6f8aeef4792e1aaa6ea3dfd3c4a639dddbea560eb3f33cd62b8d7d+"@wojtekmaj/date-utils@npm:^2.0.2":+ version: 2.0.2+ resolution: "@wojtekmaj/date-utils@npm:2.0.2"+ checksum: 10c0/6a55542cf1d5d9477b0267b1df040b1ff2edef36e6622a99e2cbd9c3830f87415f767dc969e796e02bdd722c29a901e4826ba0a3ad123afb4fac8f105d08064flanguageName: nodelinkType: hard@@ -15706,10 +15736,10 @@ __metadata:languageName: nodelinkType: hard-"detect-element-overflow@npm:^1.4.0":- version: 1.4.2- resolution: "detect-element-overflow@npm:1.4.2"- checksum: 10c0/dcc5f6d89c31f6035202cce64b96093338e777752b62c401c672e84908097ef01f833af5864e1c86c6440e4f843658f006d1084fb9090983ea5c438c8ad4a180+"detect-element-overflow@npm:^2.0.0":+ version: 2.0.0+ resolution: "detect-element-overflow@npm:2.0.0"+ checksum: 10c0/43d764fd84a3bd54bca5aca30069cf573036f95380746c6d405c73f36b3cd14f357c5c04684fcbccfee272c60f1f67d5eeb76aa0a08df58f329be4f61a5fdb38languageName: nodelinkType: hard@@ -18460,12 +18490,12 @@ __metadata:languageName: nodelinkType: hard-"get-user-locale@npm:^2.2.1":- version: 2.3.2- resolution: "get-user-locale@npm:2.3.2"+"get-user-locale@npm:^3.0.0":+ version: 3.0.0+ resolution: "get-user-locale@npm:3.0.0"dependencies:- mem: "npm:^8.0.0"- checksum: 10c0/2796b3fc3782b1f4826f31e899642cf72eeb23e296e1cf55280aab5caf7a25f4b906491ee1508a001519d6a410902ccf8fa8edaa895b7aee5dfd422ffe5523b9+ memoize: "npm:^10.0.0"+ checksum: 10c0/71d352b4d1f011cadc2736cb2194f8196e657447448a7eae187ed00f25d83efe1914a44ff22db80fbd1abee8728def436663aff161a4aff09e7044883c0a25ealanguageName: nodelinkType: hard@@ -21361,14 +21391,14 @@ __metadata:linkType: hard"js-yaml@npm:^3.10.0, js-yaml@npm:^3.13.1":- version: 3.15.0- resolution: "js-yaml@npm:3.15.0"+ version: 3.14.2+ resolution: "js-yaml@npm:3.14.2"dependencies:argparse: "npm:^1.0.7"esprima: "npm:^4.0.0"bin:js-yaml: bin/js-yaml.js- checksum: 10c0/ca966bd354ac5b1b7a4694ebdba46526796aa3a6a99529fa540af2abf85918bd155a50ccc0166b413130a00622999973754458ec01e7095bc902177bfdbd5b64+ checksum: 10c0/3261f25912f5dd76605e5993d0a126c2b6c346311885d3c483706cd722efe34f697ea0331f654ce27c00a42b426e524518ec89d65ed02ea47df8ad26dcc8ce69languageName: nodelinkType: hard@@ -22383,10 +22413,10 @@ __metadata:languageName: nodelinkType: hard-"make-event-props@npm:^1.6.0":- version: 1.6.2- resolution: "make-event-props@npm:1.6.2"- checksum: 10c0/ecf0b742e43a392c07e2267baca2397e750d38cc14ef3cb72ef8bfe4a8c8b0fd99a03a2eeab84a26c2b204f7c231da6af31fa26321fbfd413ded43ba1825e867+"make-event-props@npm:^2.0.0":+ version: 2.0.0+ resolution: "make-event-props@npm:2.0.0"+ checksum: 10c0/8c799634839498064dd73c979842af9d1d5a6156fe447edda6144318c948cfa7edbc434b14cebd5898e148e4d52aa37ffa204a82c1e2ee43e5946442f8b2466dlanguageName: nodelinkType: hard@@ -22419,7 +22449,7 @@ __metadata:languageName: nodelinkType: hard-"map-age-cleaner@npm:^0.1.1, map-age-cleaner@npm:^0.1.3":+"map-age-cleaner@npm:^0.1.1":version: 0.1.3resolution: "map-age-cleaner@npm:0.1.3"dependencies:@@ -22985,13 +23015,12 @@ __metadata:languageName: nodelinkType: hard-"mem@npm:^8.0.0":- version: 8.1.1- resolution: "mem@npm:8.1.1"+"memoize@npm:^10.0.0":+ version: 10.2.0+ resolution: "memoize@npm:10.2.0"dependencies:- map-age-cleaner: "npm:^0.1.3"- mimic-fn: "npm:^3.1.0"- checksum: 10c0/5829c404d024c1accaf76ebacbc7eae9b59e5ce5722d184aa24e8387a8097a499f6aa7e181021003c51eb87b2dcdc9a2270050c58753cce761de206643cba91c+ mimic-function: "npm:^5.0.1"+ checksum: 10c0/8a5891f313e8db82bab4bb9694752aab40c11ce3bf9b8cc32228ebaf87e14e8109a23b37ceef32baadbedc09af2c4dd0d361a93e9e591bb0ed9e23f728e1ce9flanguageName: nodelinkType: hard@@ -23510,10 +23539,10 @@ __metadata:languageName: nodelinkType: hard-"mimic-fn@npm:^3.1.0":- version: 3.1.0- resolution: "mimic-fn@npm:3.1.0"- checksum: 10c0/a07cdd8ed6490c2dff5b11f889b245d9556b80f5a653a552a651d17cff5a2d156e632d235106c2369f00cccef4071704589574cf3601bc1b1400a1f620dff067+"mimic-function@npm:^5.0.1":+ version: 5.0.1+ resolution: "mimic-function@npm:5.0.1"+ checksum: 10c0/f3d9464dd1816ecf6bdf2aec6ba32c0728022039d992f178237d8e289b48764fee4131319e72eedd4f7f094e22ded0af836c3187a7edc4595d28dd74368fd81dlanguageName: nodelinkType: hard@@ -26427,13 +26456,13 @@ __metadata:languageName: nodelinkType: hard-"react-calendar@npm:^5.0.0":- version: 5.1.0- resolution: "react-calendar@npm:5.1.0"+"react-calendar@npm:^6.0.0":+ version: 6.0.1+ resolution: "react-calendar@npm:6.0.1"dependencies:- "@wojtekmaj/date-utils": "npm:^1.1.3"+ "@wojtekmaj/date-utils": "npm:^2.0.2"clsx: "npm:^2.0.0"- get-user-locale: "npm:^2.2.1"+ get-user-locale: "npm:^3.0.0"warning: "npm:^4.0.0"peerDependencies:"@types/react": ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0@@ -26442,17 +26471,17 @@ __metadata:peerDependenciesMeta:"@types/react":optional: true- checksum: 10c0/27673f639c5d6296342a2a888436b31a5d602faeaae01be83b2beb98ff568b0a3d1514f5cc50fcacf3ac50b9c0b9d2fb423b0c001a8f5f1a22816671409e2616+ checksum: 10c0/5b7c8e207a62924b9a3c3dc3b826efee739efd3c1af1eb4683b839ac35e64c79e39521639b450bbb71eb9906ab8d6f8dbd5fd3b147914d671eacdb0c631dabf5languageName: nodelinkType: hard-"react-clock@npm:^5.0.0":- version: 5.1.0- resolution: "react-clock@npm:5.1.0"+"react-clock@npm:^6.0.0":+ version: 6.0.0+ resolution: "react-clock@npm:6.0.0"dependencies:- "@wojtekmaj/date-utils": "npm:^1.5.0"+ "@wojtekmaj/date-utils": "npm:^2.0.2"clsx: "npm:^2.0.0"- get-user-locale: "npm:^2.2.1"+ get-user-locale: "npm:^3.0.0"peerDependencies:"@types/react": ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0@@ -26460,7 +26489,7 @@ __metadata:peerDependenciesMeta:"@types/react":optional: true- checksum: 10c0/98a9e29b7e36f56cb49c6fc9f7212b5b54fe06bb5b1a1b25bc31265ed8beaa71b7e74f566cf61290cb1c503b238342d77a86684ebabe37314b12a12e0e630a10+ checksum: 10c0/7d6c67896b78942375433e417dd9dbd2de8ab3b2885084f5ed038cd0db96c449c52b2c1d09a1a990f98417a51b52baca01f897b586c6fc05eae580644700d21clanguageName: nodelinkType: hard@@ -26493,16 +26522,16 @@ __metadata:languageName: nodelinkType: hard-"react-date-picker@npm:^11.0.0":- version: 11.0.0- resolution: "react-date-picker@npm:11.0.0"+"react-date-picker@npm:^12.0.2":+ version: 12.0.2+ resolution: "react-date-picker@npm:12.0.2"dependencies:- "@wojtekmaj/date-utils": "npm:^1.1.3"+ "@wojtekmaj/date-utils": "npm:^2.0.2"clsx: "npm:^2.0.0"- get-user-locale: "npm:^2.2.1"- make-event-props: "npm:^1.6.0"- react-calendar: "npm:^5.0.0"- react-fit: "npm:^2.0.0"+ get-user-locale: "npm:^3.0.0"+ make-event-props: "npm:^2.0.0"+ react-calendar: "npm:^6.0.0"+ react-fit: "npm:^3.0.0"update-input-width: "npm:^1.4.0"peerDependencies:"@types/react": ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0@@ -26511,7 +26540,7 @@ __metadata:peerDependenciesMeta:"@types/react":optional: true- checksum: 10c0/de51915831d16ebcf0f1bb5ff67d41792848c2b36a9a3c8e6e2f652b3a5f2e6751d866095fb234f92e3790ffc1d2557b5f92e839b03b11acead1ecc7d50e2dde+ checksum: 10c0/7f450a3ff3127bcd3aef72174add6f17f90cd03d71a13200bc98fc4604430c96bd29c5e119d9425c059b13b7311165078c64afd92fa9205c53f0951d8cae4ab3languageName: nodelinkType: hard@@ -26551,11 +26580,11 @@ __metadata:languageName: nodelinkType: hard-"react-fit@npm:^2.0.0":- version: 2.0.1- resolution: "react-fit@npm:2.0.1"+"react-fit@npm:^3.0.0":+ version: 3.0.0+ resolution: "react-fit@npm:3.0.0"dependencies:- detect-element-overflow: "npm:^1.4.0"+ detect-element-overflow: "npm:^2.0.0"warning: "npm:^4.0.0"peerDependencies:"@types/react": ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0@@ -26564,9 +26593,7 @@ __metadata:peerDependenciesMeta:"@types/react":optional: true- "@types/react-dom":- optional: true- checksum: 10c0/0202f4e3241bd2e967ec3728c97ab57842353ae48f218ca56d28be14737a7a759e40c3cd05700d9e328ab88e377eccb296f1e33530e6775d3acc05df97084018+ checksum: 10c0/f850183151e80cca474146fd530a1d81a97dd6457341f3bba4366c6d60ae464c60ff0adc0677b9a77b0ba7057b8e3e081870d406d649c3d72b767b666c9f5e8flanguageName: nodelinkType: hard@@ -26862,16 +26889,16 @@ __metadata:languageName: nodelinkType: hard-"react-time-picker@npm:^7.0.0":- version: 7.0.0- resolution: "react-time-picker@npm:7.0.0"+"react-time-picker@npm:^8.0.0":+ version: 8.0.3+ resolution: "react-time-picker@npm:8.0.3"dependencies:- "@wojtekmaj/date-utils": "npm:^1.1.3"+ "@wojtekmaj/date-utils": "npm:^2.0.2"clsx: "npm:^2.0.0"- get-user-locale: "npm:^2.2.1"- make-event-props: "npm:^1.6.0"- react-clock: "npm:^5.0.0"- react-fit: "npm:^2.0.0"+ get-user-locale: "npm:^3.0.0"+ make-event-props: "npm:^2.0.0"+ react-clock: "npm:^6.0.0"+ react-fit: "npm:^3.0.0"update-input-width: "npm:^1.4.0"peerDependencies:"@types/react": ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0@@ -26880,7 +26907,7 @@ __metadata:peerDependenciesMeta:"@types/react":optional: true- checksum: 10c0/538a1964de1ef9021b195f856efedc207019b6da1b9bbdcb6899c876ec6b4eeb02f4f16b77677dc0edb704099ed7f204dde0821573b7a1f1f24909e02ea2aee6+ checksum: 10c0/d40236b01598c89c3e04b1171ce666abc84b79b7ebab96ac56119bec9275502738bed4cf2531d1fdf7f20ddd3798df6d2d78f22f7280326695105b7379b516cblanguageName: nodelinkType: hard@@ -32404,11 +32431,11 @@ __metadata:linkType: hard"ws@npm:^5.2.3":- version: 5.2.5- resolution: "ws@npm:5.2.5"+ version: 5.2.4+ resolution: "ws@npm:5.2.4"dependencies:async-limiter: "npm:~1.0.0"- checksum: 10c0/829b2e57028c65765a01bd240fb05c736050cc1e6836f5d6df04ebc4e78c2950c7d437bbfd01a79345050813e9da2162171be8c5b5301cc4307804932908d9de+ checksum: 10c0/14e84e4209f86ab68b01b9ebf42c88f81f26a64ff4886ef65d27c734c9b90b8d7e84712da3c3f7a922a4ab58bf0b96544d32ae28ebbd620fcda3027dd5bc7604languageName: nodelinkType: hard@@ -32421,7 +32448,22 @@ __metadata:languageName: nodelinkType: hard-"ws@npm:^8.11.0, ws@npm:^8.18.0, ws@npm:^8.19.0":+"ws@npm:^8.11.0, ws@npm:^8.18.0":+ version: 8.18.0+ resolution: "ws@npm:8.18.0"+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: ">=5.0.2"+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true+ checksum: 10c0/25eb33aff17edcb90721ed6b0eb250976328533ad3cd1a28a274bd263682e7296a6591ff1436d6cbc50fa67463158b062f9d1122013b361cec99a05f84680e06+ languageName: node+ linkType: hard++"ws@npm:^8.19.0":version: 8.20.0resolution: "ws@npm:8.20.0"peerDependencies: