Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

feat(3d): add model gallery, custom models, and GeoJSON input (#3779)

Igor Dykhta7441968c4b4f
diff --git a/src/components/src/side-panel/layer-panel/layer-configurator.tsx b/src/components/src/side-panel/layer-panel/layer-configurator.tsx
index 67b6f234e..cbe527cd5 100644
--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx
+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx
@@ -3,18 +3,11 @@
/* eslint-disable complexity */
import {FormattedMessage} from '@kepler.gl/localization';
-import React, {Component, Fragment, useCallback, useRef, useState} from 'react';
+import React, {Component, useCallback, useRef, useState} from 'react';
import styled from 'styled-components';
import ItemSelector from '../../common/item-selector/item-selector';
-import InfoHelperFactory from '../../common/info-helper';
-import {
- Input,
- InputLight,
- PanelLabel,
- PanelLabelWrapper,
- SidePanelSection
-} from '../../common/styled-components';
+import {InputLight, PanelLabel, SidePanelSection} from '../../common/styled-components';
import SourceDataSelectorFactory from '../common/source-data-selector';
import AggrScaleSelectorFactory from './aggr-scale-selector';
@@ -33,7 +26,7 @@ import TextLabelPanelFactory from './text-label-panel';
import VisConfigSliderFactory from './vis-config-slider';
import VisConfigSwitchFactory from './vis-config-switch';
import ScenegraphModelSelectorFactory, {
- ScenegraphCustomModelUrlInput
+ SCENEGRAPH_3D_MODEL_OPTIONS
} from './scenegraph-model-selector';
import RasterTileLayerConfiguratorFactory from './raster-tile-layer-configurator';
@@ -44,7 +37,6 @@ import {ActionHandler, toggleModal, updateDatasetProps} from '@kepler.gl/actions
import {
AGGREGATION_TYPE_OPTIONS,
LAYER_TYPES,
- CUSTOM_SCENEGRAPH_MODEL_ID,
BitmapDatasetMetadata,
Tile3DDatasetMetadata
} from '@kepler.gl/constants';
@@ -424,8 +416,7 @@ LayerConfiguratorFactory.deps = [
AggrScaleSelectorFactory,
VectorTileLayerConfiguratorFactory,
RasterTileLayerConfiguratorFactory,
- ScenegraphModelSelectorFactory,
- InfoHelperFactory
+ ScenegraphModelSelectorFactory
];
export default function LayerConfiguratorFactory(
@@ -443,8 +434,7 @@ export default function LayerConfiguratorFactory(
AggrScaleSelector: ReturnType<typeof AggrScaleSelectorFactory>,
VectorTileLayerConfigurator: ReturnType<typeof VectorTileLayerConfiguratorFactory>,
RasterTileLayerConfigurator: ReturnType<typeof RasterTileLayerConfiguratorFactory>,
- ScenegraphModelSelector: ReturnType<typeof ScenegraphModelSelectorFactory>,
- InfoHelper: ReturnType<typeof InfoHelperFactory>
+ ScenegraphModelSelector: ReturnType<typeof ScenegraphModelSelectorFactory>
): React.ComponentType<LayerConfiguratorProps> {
class LayerConfigurator extends Component<LayerConfiguratorProps> {
_renderPointLayerConfig(props) {
@@ -1075,36 +1065,13 @@ export default function LayerConfiguratorFactory(
>
<ScenegraphModelSelector
selected={layer.config.visConfig.scenegraph}
+ customModelUrl={layer.config.visConfig.scenegraphCustomModelUrl}
disabled={!layer.config.visConfig.scenegraphEnabled}
- onSelect={(scenegraph: {id: string}) =>
- visConfiguratorProps.onChange({scenegraph: scenegraph.id})
- }
+ onChange={visConfiguratorProps.onChange}
/>
{layer.config.visConfig.scenegraphEnabled ? (
<>
<ConfigGroupCollapsibleContent>
- {layer.config.visConfig.scenegraph === CUSTOM_SCENEGRAPH_MODEL_ID ? (
- <SidePanelSection>
- <PanelLabelWrapper>
- <PanelLabel>
- <FormattedMessage id="layer.3DModelURL" />
- </PanelLabel>
- <InfoHelper
- id={`${layer.id}-scenegraphCustomModelUrl`}
- description="layer.3DModelURLDescription"
- property="scenegraphCustomModelUrl"
- />
- </PanelLabelWrapper>
- <ScenegraphCustomModelUrlInput
- customModelUrl={layer.config.visConfig.scenegraphCustomModelUrl}
- onChange={url =>
- visConfiguratorProps.onChange({
- scenegraphCustomModelUrl: url
- })
- }
- />
- </SidePanelSection>
- ) : null}
<VisConfigSwitch
{...layer.visConfigSettings.scenegraphColorEnabled}
{...visConfiguratorProps}
@@ -1395,20 +1362,25 @@ export default function LayerConfiguratorFactory(
_render3DLayerConfig({layer, visConfiguratorProps}) {
return (
- <Fragment>
+ <StyledLayerVisualConfigurator>
<LayerConfigGroup label={'layer.3DModel'} collapsible>
- <Input
- type="file"
- accept=".glb,.gltf"
- onChange={e => {
- if (e.target.files && e.target.files[0]) {
- const url = URL.createObjectURL(e.target.files[0]);
- visConfiguratorProps.onChange({scenegraph: url});
- }
- }}
+ <ScenegraphModelSelector
+ options={SCENEGRAPH_3D_MODEL_OPTIONS}
+ selected={layer.config.visConfig.scenegraph}
+ customModelUrl={layer.config.visConfig.scenegraphCustomModelUrl}
+ onChange={visConfiguratorProps.onChange}
/>
- </LayerConfigGroup>
- <LayerConfigGroup label={'layer.3DModelOptions'} collapsible>
+ <VisConfigSwitch
+ {...layer.visConfigSettings.scenegraphColorEnabled}
+ {...visConfiguratorProps}
+ />
+ {layer.config.visConfig.scenegraphColorEnabled ? (
+ <LayerColorSelector
+ {...visConfiguratorProps}
+ selectedColor={layer.config.visConfig.scenegraphColor}
+ property="scenegraphColor"
+ />
+ ) : null}
<VisConfigSlider
{...layer.visConfigSettings.sizeScale}
{...visConfiguratorProps}
@@ -1430,7 +1402,7 @@ export default function LayerConfiguratorFactory(
disabled={false}
/>
</LayerConfigGroup>
- </Fragment>
+ </StyledLayerVisualConfigurator>
);
}
diff --git a/src/components/src/side-panel/layer-panel/scenegraph-model-selector.tsx b/src/components/src/side-panel/layer-panel/scenegraph-model-selector.tsx
index a43428a23..57f073642 100644
--- a/src/components/src/side-panel/layer-panel/scenegraph-model-selector.tsx
+++ b/src/components/src/side-panel/layer-panel/scenegraph-model-selector.tsx
@@ -1,15 +1,24 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {useMemo, useState} from 'react';
+import React, {useMemo, useRef, useState} from 'react';
import styled, {withTheme} from 'styled-components';
-import {TRIP_LAYER_SCENEGRAPH_MODELS} from '@kepler.gl/constants';
+import {
+ CUSTOM_SCENEGRAPH_MODEL_ID,
+ DEFAULT_SCENEGRAPH_MODEL_ID,
+ SCENEGRAPH_LAYER_MODELS,
+ TRIP_LAYER_SCENEGRAPH_MODELS
+} from '@kepler.gl/constants';
+import type {ScenegraphModel} from '@kepler.gl/constants';
+import {ScenegraphLayerIcon} from '@kepler.gl/layers';
+import {FormattedMessage} from '@kepler.gl/localization';
import LayerTypeDropdownListFactory from './layer-type-dropdown-list';
import LayerTypeListItemFactory from './layer-type-list-item';
import ItemSelector from '../../common/item-selector/item-selector';
-import {Input, SidePanelSection} from '../../common/styled-components';
+import Checkbox from '../../common/checkbox';
+import {Button, Input, SidePanelSection} from '../../common/styled-components';
import {LayerTypeOption} from './layer-type-dropdown-list';
import AirplaneModelIcon from '../../common/icons/3d-models/airplane';
@@ -27,6 +36,7 @@ import ScooterModelIcon from '../../common/icons/3d-models/scooter';
const EmptyIcon = () => <></>;
const ICON_MAP: Record<string, React.ComponentType<any>> = {
+ 'default-model': ScenegraphLayerIcon,
airplane: AirplaneModelIcon,
boeing777: BoeingModelIcon,
'uber-evtol': EvtolModelIcon,
@@ -40,23 +50,28 @@ const ICON_MAP: Record<string, React.ComponentType<any>> = {
cargoship: CargoshipModelIcon
};
-const SCENEGRAPH_MODEL_OPTIONS = TRIP_LAYER_SCENEGRAPH_MODELS.map(m => ({
- ...m,
- icon: ICON_MAP[m.id] || EmptyIcon
-}));
+export function getScenegraphModelOptions(
+ models: ScenegraphModel[] = TRIP_LAYER_SCENEGRAPH_MODELS
+) {
+ return models.map(model => ({
+ ...model,
+ icon: ICON_MAP[model.id] || EmptyIcon
+ }));
+}
-const StyledScenegraphModelSelector = styled.div`
- .item-selector .item-selector__dropdown {
- padding: 4px 10px 4px 10px;
- }
-`;
+const SCENEGRAPH_MODEL_OPTIONS = getScenegraphModelOptions();
+
+export const SCENEGRAPH_3D_MODEL_OPTIONS = getScenegraphModelOptions(SCENEGRAPH_LAYER_MODELS);
const getDisplayOption = op => op.label;
const getOptionValue = op => op.id;
+type ModelSource = 'model' | 'url' | 'file';
+
export type ScenegraphModelSelectorProps = {
selected: string;
- onSelect: (scenegraph: {id: string; angles: number[]}) => void;
+ customModelUrl?: string;
+ onChange: (visConfig: {scenegraph: string; scenegraphCustomModelUrl?: string}) => void;
options?: LayerTypeOption[];
disabled?: boolean;
theme: any;
@@ -64,43 +79,193 @@ export type ScenegraphModelSelectorProps = {
ScenegraphModelSelectorFactory.deps = [LayerTypeListItemFactory, LayerTypeDropdownListFactory];
+function isLocalModelUrl(url: string): boolean {
+ return url.startsWith('blob:') || url.startsWith('data:');
+}
+
+function initialGalleryId(options: LayerTypeOption[], selected: string): string {
+ if (options.some(option => option.id === selected)) {
+ return selected;
+ }
+ if (options.some(option => option.id === DEFAULT_SCENEGRAPH_MODEL_ID)) {
+ return DEFAULT_SCENEGRAPH_MODEL_ID;
+ }
+ return options[0]?.id || '';
+}
+
function ScenegraphModelSelectorFactory(
LayerTypeListItem: ReturnType<typeof LayerTypeListItemFactory>,
LayerTypeDropdownList: ReturnType<typeof LayerTypeDropdownListFactory>
) {
const ScenegraphModelSelector: React.FC<ScenegraphModelSelectorProps> = ({
selected,
+ customModelUrl = '',
options = SCENEGRAPH_MODEL_OPTIONS,
disabled,
- onSelect
+ onChange
}) => {
- const selectedItems = useMemo(
- () => options.find(op => op.id === selected),
- [options, selected]
+ const galleryOptions = useMemo(
+ () => options.filter(option => option.id !== CUSTOM_SCENEGRAPH_MODEL_ID),
+ [options]
+ );
+ const isGallerySelection = galleryOptions.some(option => option.id === selected);
+ const [source, setSource] = useState<ModelSource>(
+ isGallerySelection ? 'model' : isLocalModelUrl(customModelUrl) ? 'file' : 'url'
+ );
+ const [galleryId, setGalleryId] = useState(() => initialGalleryId(galleryOptions, selected));
+ const [url, setUrl] = useState(isLocalModelUrl(customModelUrl) ? '' : customModelUrl);
+ const [fileName, setFileName] = useState('');
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const objectUrlRef = useRef<string | null>(
+ isLocalModelUrl(customModelUrl) ? customModelUrl : null
);
+ const activeGalleryId = isGallerySelection ? selected : galleryId;
+ const selectedItems = galleryOptions.find(option => option.id === activeGalleryId);
+
+ const selectSource = (next: ModelSource) => {
+ if (disabled || next === source) {
+ return;
+ }
+ setSource(next);
+ if (next === 'model') {
+ onChange({scenegraph: activeGalleryId});
+ return;
+ }
+ onChange({
+ scenegraph: CUSTOM_SCENEGRAPH_MODEL_ID,
+ scenegraphCustomModelUrl: next === 'file' ? objectUrlRef.current || '' : url
+ });
+ };
+
+ const onFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ event.target.value = '';
+ if (!file) {
+ return;
+ }
+ if (objectUrlRef.current?.startsWith('blob:')) {
+ URL.revokeObjectURL(objectUrlRef.current);
+ }
+ const objectUrl = URL.createObjectURL(file);
+ objectUrlRef.current = objectUrl;
+ setFileName(file.name);
+ setSource('file');
+ onChange({
+ scenegraph: CUSTOM_SCENEGRAPH_MODEL_ID,
+ scenegraphCustomModelUrl: objectUrl
+ });
+ };
+
return (
- <SidePanelSection>
- <StyledScenegraphModelSelector className="layer-config__type">
- <ItemSelector
- selectedItems={selectedItems}
- options={options}
- disabled={disabled}
- multiSelect={false}
- placeholder="placeholder.selectType"
- onChange={id => {
- const scenegraph = SCENEGRAPH_MODEL_OPTIONS.find(d => d.id === id);
- if (scenegraph) {
- onSelect(scenegraph);
+ <SidePanelSection disabled={disabled}>
+ <SourceList>
+ <Checkbox
+ type="radio"
+ name="scenegraph-model-source"
+ id="scenegraph-model-source-model"
+ checked={source === 'model'}
+ label={<FormattedMessage id="layer.3DModelSourceModel" />}
+ onChange={() => selectSource('model')}
+ />
+ <ModelDropdown
+ className="layer-config__type"
+ $active={source === 'model'}
+ onMouseDown={() => {
+ if (source !== 'model') {
+ selectSource('model');
}
}}
- getOptionValue={getOptionValue}
- filterOption="label"
- displayOption={getDisplayOption}
- DropDownLineItemRenderComponent={LayerTypeListItem}
- DropDownRenderComponent={LayerTypeDropdownList}
+ >
+ <ItemSelector
+ selectedItems={selectedItems}
+ options={galleryOptions}
+ disabled={disabled}
+ multiSelect={false}
+ placeholder="placeholder.selectType"
+ onChange={id => {
+ const scenegraph = galleryOptions.find(option => option.id === id);
+ if (!scenegraph) {
+ return;
+ }
+ setGalleryId(scenegraph.id);
+ setSource('model');
+ onChange({scenegraph: scenegraph.id});
+ }}
+ getOptionValue={getOptionValue}
+ filterOption="label"
+ displayOption={getDisplayOption}
+ DropDownLineItemRenderComponent={LayerTypeListItem}
+ DropDownRenderComponent={LayerTypeDropdownList}
+ DropDownWrapperComponent={ModelMenuFrame}
+ />
+ </ModelDropdown>
+ <Checkbox
+ type="radio"
+ name="scenegraph-model-source"
+ id="scenegraph-model-source-url"
+ checked={source === 'url'}
+ label={<FormattedMessage id="layer.3DModelSourceUrl" />}
+ onChange={() => selectSource('url')}
+ />
+ <SourceControl>
+ <SourceInput
+ type="text"
+ value={url}
+ $active={source === 'url'}
+ onMouseDown={() => {
+ if (source !== 'url') {
+ selectSource('url');
+ }
+ }}
+ onChange={({target: {value}}) => setUrl(value)}
+ onBlur={event => {
+ if (source === 'url') {
+ onChange({
+ scenegraph: CUSTOM_SCENEGRAPH_MODEL_ID,
+ scenegraphCustomModelUrl: event.target.value
+ });
+ }
+ }}
+ placeholder={'http://...'}
+ />
+ </SourceControl>
+ <Checkbox
+ type="radio"
+ name="scenegraph-model-source"
+ id="scenegraph-model-source-file"
+ checked={source === 'file'}
+ label={<FormattedMessage id="layer.3DModelSourceFile" />}
+ onChange={() => selectSource('file')}
/>
- </StyledScenegraphModelSelector>
+ <SourceControl>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".glb,.gltf,model/gltf-binary,model/gltf+json"
+ style={{display: 'none'}}
+ onChange={onFileChange}
+ />
+ <FileButton
+ type="button"
+ secondary
+ small
+ $active={source === 'file'}
+ title={fileName || undefined}
+ onClick={() => {
+ if (source !== 'file') {
+ selectSource('file');
+ return;
+ }
+ fileInputRef.current?.click();
+ }}
+ >
+ <FileButtonLabel>
+ {fileName ? fileName : <FormattedMessage id="layer.3DModelFile" />}
+ </FileButtonLabel>
+ </FileButton>
+ </SourceControl>
+ </SourceList>
</SidePanelSection>
);
};
@@ -110,25 +275,65 @@ function ScenegraphModelSelectorFactory(
>;
}
-type ScenegraphCustomModelUrlInputProps = {
- customModelUrl: string;
- onChange: (url: string) => void;
-};
+const SourceList = styled.div`
+ display: grid;
+ grid-template-columns: max-content minmax(0, 1fr);
+ column-gap: 10px;
+ row-gap: 8px;
+ align-items: center;
+`;
-export const ScenegraphCustomModelUrlInput: React.FC<ScenegraphCustomModelUrlInputProps> = ({
- customModelUrl,
- onChange
-}: ScenegraphCustomModelUrlInputProps) => {
- const [url, setUrl] = useState(customModelUrl || '');
- return (
- <Input
- type="text"
- value={url}
- onChange={({target: {value}}) => setUrl(value)}
- onBlur={() => onChange(url)}
- placeholder={'http://...'}
- />
- );
-};
+const ModelDropdown = styled.div<{$active?: boolean}>`
+ min-width: 0;
+ opacity: ${props => (props.$active ? 1 : 0.5)};
+ cursor: pointer;
+
+ .item-selector .item-selector__dropdown {
+ padding: 4px 10px 4px 10px;
+ }
+`;
+
+const ModelMenuFrame = styled.div<{width?: number}>`
+ border: 0;
+ z-index: ${props => props.theme.dropdownWrapperZ};
+ width: ${props => (props.width || 0) + 10}px;
+`;
+
+const SourceControl = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+`;
+
+const SourceInput = styled(Input)<{$active?: boolean}>`
+ && {
+ opacity: ${props => (props.$active ? 1 : 0.5)};
+ cursor: ${props => (props.$active ? 'text' : 'pointer')};
+ }
+`;
+
+const FileButton = styled(Button)<{$active?: boolean}>`
+ && {
+ width: 100%;
+ height: ${props => props.theme.inputBoxHeight};
+ box-sizing: border-box;
+ overflow: hidden;
+ padding-top: 0;
+ padding-bottom: 0;
+ opacity: ${props => (props.$active ? 1 : 0.4)};
+ cursor: pointer;
+ pointer-events: auto;
+ }
+`;
+
+const FileButtonLabel = styled.span`
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+ max-width: 100%;
+`;
export default ScenegraphModelSelectorFactory;
diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.ts
index 2a095c171..00dc61e2f 100644
--- a/src/constants/src/default-settings.ts
+++ b/src/constants/src/default-settings.ts
@@ -1918,17 +1918,24 @@ export const getLoaderOptions = () => {
};
export const CUSTOM_SCENEGRAPH_MODEL_ID = 'custom';
+export const DEFAULT_SCENEGRAPH_MODEL_ID = 'default-model';
+export const LEGACY_DEFAULT_SCENEGRAPH_URL =
+ 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb';
const MODELS_BASE_URL =
'https://studio-public-data.foursquare.com/statics/keplergl/3d-models.2022-06-13';
-export const TRIP_LAYER_SCENEGRAPH_MODELS: {
+export type ScenegraphModel = {
id: string;
label: string;
icon: any;
url: string | null;
+ /** [roll, pitch, yaw] added to the layer angle sliders */
angles: [number, number, number];
scale: number;
-}[] = [
+};
+
+/** Gallery shared by the trip layer and the point 3D layer. */
+const SCENEGRAPH_GALLERY_MODELS: ScenegraphModel[] = [
{
id: 'airplane',
label: 'Airplane',
@@ -2016,13 +2023,36 @@ export const TRIP_LAYER_SCENEGRAPH_MODELS: {
url: `${MODELS_BASE_URL}/Cargoship.glb`,
angles: [0, 0, 0],
scale: 1.0
- },
- {
- id: CUSTOM_SCENEGRAPH_MODEL_ID,
- label: 'Custom',
- icon: null,
- url: null,
- angles: [0, 0, 0],
- scale: 1.0
}
];
+
+const CUSTOM_SCENEGRAPH_MODEL: ScenegraphModel = {
+ id: CUSTOM_SCENEGRAPH_MODEL_ID,
+ label: 'Custom',
+ icon: null,
+ url: null,
+ angles: [0, 0, 0],
+ scale: 1.0
+};
+
+/** Duck used by the point 3D layer. Yaw lives on the model so angle Z can default to 0. */
+export const DEFAULT_SCENEGRAPH_MODEL: ScenegraphModel = {
+ id: DEFAULT_SCENEGRAPH_MODEL_ID,
+ label: 'Ducky',
+ icon: null,
+ url: `${MODELS_BASE_URL}/Duck-Kepler-3D-Layer.glb`,
+ angles: [0, 0, 90],
+ scale: 150
+};
+
+export const TRIP_LAYER_SCENEGRAPH_MODELS: ScenegraphModel[] = [
+ ...SCENEGRAPH_GALLERY_MODELS,
+ CUSTOM_SCENEGRAPH_MODEL
+];
+
+/** Same gallery as trips, plus Ducky and a custom URL. */
+export const SCENEGRAPH_LAYER_MODELS: ScenegraphModel[] = [
+ ...SCENEGRAPH_GALLERY_MODELS,
+ DEFAULT_SCENEGRAPH_MODEL,
+ CUSTOM_SCENEGRAPH_MODEL
+];
diff --git a/src/layers/src/index.ts b/src/layers/src/index.ts
index 1dc76f1e2..b990f4ba6 100644
--- a/src/layers/src/index.ts
+++ b/src/layers/src/index.ts
@@ -181,7 +181,9 @@ export {formatCircleRadiusLabel, formatLineLengthLabel} from './editor-layer/edi
export {
default as ScenegraphLayer,
- scenegraphVisConfigs
+ scenegraphVisConfigs,
+ toCorsSafeGcsUrl,
+ migrateLegacyScenegraphVisConfig
} from './scenegraph-layer/scenegraph-layer';
export {default as ScenegraphLayerIcon} from './scenegraph-layer/scenegraph-layer-icon';
diff --git a/src/layers/src/scenegraph-layer/scenegraph-info-modal.tsx b/src/layers/src/scenegraph-layer/scenegraph-info-modal.tsx
index 59167af74..aa1a02d88 100644
--- a/src/layers/src/scenegraph-layer/scenegraph-info-modal.tsx
+++ b/src/layers/src/scenegraph-layer/scenegraph-info-modal.tsx
@@ -57,20 +57,22 @@ const ScenegraphInfoModalFactory = () => {
<div className="scenegraph-info-modal">
<div className="scenegraph-info-modal__description">
<span>
- In your csv you can specify points with optional altitude. The models will show at each
- point you specify. You can use a sample model or upload one in{' '}
+ In your csv you can specify points with optional altitude. A model is placed at each
+ point. A GeoJSON geometry column places one model at each feature centroid. Pick one from
+ the gallery, or provide a URL to a{' '}
</span>
<code>glTF (GLB or Embedded)</code>
- <span> format.</span>
+ <span> file.</span>
</div>
<div className="scenegraph-info-modal__example">
<StyledTitle>Example:</StyledTitle>
<ExampleTable />
</div>
<div className="scenegraph-info-modal__icons">
- <StyledTitle>Sample Models</StyledTitle>
- <div>Duck</div>
- <div>Use your own model</div>
+ <StyledTitle>Models</StyledTitle>
+ <div>Airplane, car, ship, and the rest of the gallery</div>
+ <div>Ducky</div>
+ <div>Custom model URL</div>
</div>
</div>
);
diff --git a/src/layers/src/scenegraph-layer/scenegraph-layer.ts b/src/layers/src/scenegraph-layer/scenegraph-layer.ts
index dee33da65..b6928b4f8 100644
--- a/src/layers/src/scenegraph-layer/scenegraph-layer.ts
+++ b/src/layers/src/scenegraph-layer/scenegraph-layer.ts
@@ -8,16 +8,38 @@ import {GLTFLoader, postProcessGLTF} from '@loaders.gl/gltf';
import Layer, {LayerBaseConfig} from '../base-layer';
import ScenegraphLayerIcon from './scenegraph-layer-icon';
import ScenegraphInfoModalFactory from './scenegraph-info-modal';
-import {LAYER_VIS_CONFIGS} from '@kepler.gl/constants';
+import {
+ CUSTOM_SCENEGRAPH_MODEL_ID,
+ DEFAULT_SCENEGRAPH_MODEL,
+ DEFAULT_SCENEGRAPH_MODEL_ID,
+ LEGACY_DEFAULT_SCENEGRAPH_URL,
+ GEOARROW_METADATA_KEY,
+ GEOJSON_FIELDS,
+ LAYER_VIS_CONFIGS,
+ SCENEGRAPH_LAYER_MODELS
+} from '@kepler.gl/constants';
+import type {ScenegraphModel} from '@kepler.gl/constants';
import {
ColorRange,
Merge,
+ RGBColor,
+ VisConfigBoolean,
VisConfigColorRange,
+ VisConfigColorSelect,
+ VisConfigInput,
VisConfigNumber,
LayerColumn
} from '@kepler.gl/types';
import {default as KeplerTable} from '@kepler.gl/table';
import {DataContainerInterface} from '@kepler.gl/utils';
+import {DATA_TYPES} from 'type-analyzer';
+
+import {FindDefaultLayerPropsReturnValue} from '../layer-utils';
+import {
+ getAllPositions,
+ getCentroidFromGeometry,
+ parseGeoJsonRawFeature
+} from '../geojson-layer/geojson-utils';
export type ScenegraphLayerVisConfigSettings = {
opacity: VisConfigNumber;
@@ -26,12 +48,17 @@ export type ScenegraphLayerVisConfigSettings = {
angleX: VisConfigNumber;
angleY: VisConfigNumber;
angleZ: VisConfigNumber;
+ scenegraph: VisConfigInput;
+ scenegraphColorEnabled: VisConfigBoolean;
+ scenegraphColor: VisConfigColorSelect;
+ scenegraphCustomModelUrl: VisConfigInput;
};
export type ScenegraphLayerColumnsConfig = {
lat: LayerColumn;
lng: LayerColumn;
altitude?: LayerColumn;
+ geojson?: LayerColumn;
};
export type ScenegraphLayerVisConfig = {
@@ -41,7 +68,10 @@ export type ScenegraphLayerVisConfig = {
angleX: number;
angleY: number;
angleZ: number;
- scenegraph: string;
+ scenegraph: string | null;
+ scenegraphColorEnabled: boolean;
+ scenegraphColor: RGBColor | null;
+ scenegraphCustomModelUrl: string;
};
export type ScenegraphLayerConfig = Merge<
@@ -53,15 +83,89 @@ export type ScenegraphLayerData = {position: number[]; index: number};
export const scenegraphRequiredColumns: ['lat', 'lng'] = ['lat', 'lng'];
export const scenegraphOptionalColumns: ['altitude'] = ['altitude'];
+export const scenegraphGeojsonRequiredColumns: ['geojson'] = ['geojson'];
+
+export const COLUMN_MODE_POINTS = 'points';
+export const COLUMN_MODE_GEOJSON = 'geojson';
+
+const SUPPORTED_ANALYZER_TYPES = {
+ [DATA_TYPES.GEOMETRY]: true,
+ [DATA_TYPES.GEOMETRY_FROM_STRING]: true,
+ [DATA_TYPES.PAIR_GEOMETRY_FROM_STRING]: true
+};
+
+const SUPPORTED_COLUMN_MODES = [
+ {
+ key: COLUMN_MODE_POINTS,
+ label: 'Point Columns',
+ requiredColumns: scenegraphRequiredColumns,
+ optionalColumns: scenegraphOptionalColumns
+ },
+ {
+ key: COLUMN_MODE_GEOJSON,
+ label: 'GeoJSON',
+ requiredColumns: scenegraphGeojsonRequiredColumns
+ }
+];
+const DEFAULT_COLUMN_MODE = COLUMN_MODE_POINTS;
+
+/**
+ * Public GCS object URLs do not send Access-Control-Allow-Origin.
+ * The JSON API download of the same object does, and echoes the page origin.
+ * Signed URLs keep their query string; rewriting them drops the signature.
+ */
+export function toCorsSafeGcsUrl(url: string): string {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return url;
+ }
+ if (parsed.protocol !== 'https:' || parsed.search) {
+ return url;
+ }
+
+ let bucket: string | undefined;
+ let objectName: string | undefined;
+ if (parsed.hostname === 'storage.googleapis.com') {
+ if (
+ parsed.pathname.startsWith('/storage/v1/') ||
+ parsed.pathname.startsWith('/download/storage/')
+ ) {
+ return url;
+ }
+ const segments = parsed.pathname.split('/').filter(Boolean);
+ if (segments.length < 2) {
+ return url;
+ }
+ bucket = decodeURIComponent(segments[0]);
+ objectName = decodeURIComponent(segments.slice(1).join('/'));
+ } else if (parsed.hostname.endsWith('.storage.googleapis.com')) {
+ bucket = parsed.hostname.slice(0, -'.storage.googleapis.com'.length);
+ objectName = decodeURIComponent(parsed.pathname.replace(/^\//, ''));
+ }
+
+ if (!bucket || !objectName) {
+ return url;
+ }
+ return `https://storage.googleapis.com/storage/v1/b/${encodeURIComponent(
+ bucket
+ )}/o/${encodeURIComponent(objectName)}?alt=media`;
+}
+
+function fetchModel(url: string, init?: RequestInit): Promise<Response> {
+ return fetch(toCorsSafeGcsUrl(url), init);
+}
export function fetchGltf(url, {propName, layer}: {propName?: string; layer?: any} = {}) {
if (propName === 'scenegraph') {
- return load(url, GLTFLoader, layer.getLoadOptions()).then(gltfWithBuffers =>
+ const loadOptions = layer.getLoadOptions() || {};
+ return load(url, GLTFLoader, {...loadOptions, fetch: fetchModel}).then(gltfWithBuffers =>
postProcessGLTF(gltfWithBuffers)
);
}
- return fetchGltf(url).then(response => response.json());
+ return fetch(toCorsSafeGcsUrl(url)).then(response => response.json());
}
export const scenegraphPosAccessor =
@@ -74,19 +178,31 @@ export const scenegraphPosAccessor =
altitude && altitude.fieldIdx > -1 ? dc.valueAt(d.index, altitude.fieldIdx) : 0
];
+export const scenegraphGeojsonAccessor =
+ ({geojson}: ScenegraphLayerColumnsConfig) =>
+ (dc: DataContainerInterface) =>
+ (d: {index: number}) =>
+ geojson ? dc.valueAt(d.index, geojson.fieldIdx) : null;
+
export const scenegraphVisConfigs: {
opacity: 'opacity';
colorRange: 'colorRange';
- //
- sizeScale: 'sizeScale';
+ sizeScale: VisConfigNumber;
angleX: VisConfigNumber;
angleY: VisConfigNumber;
angleZ: VisConfigNumber;
+ scenegraph: VisConfigInput;
+ scenegraphColorEnabled: 'scenegraphColorEnabled';
+ scenegraphColor: 'scenegraphColor';
+ scenegraphCustomModelUrl: 'scenegraphCustomModelUrl';
} = {
opacity: 'opacity',
colorRange: 'colorRange',
- //
- sizeScale: 'sizeScale',
+ sizeScale: {
+ ...LAYER_VIS_CONFIGS.sizeScale,
+ range: [0, 10000],
+ step: 0.01
+ },
angleX: {
...LAYER_VIS_CONFIGS.angle,
property: 'angleX',
@@ -100,29 +216,72 @@ export const scenegraphVisConfigs: {
angleZ: {
...LAYER_VIS_CONFIGS.angle,
property: 'angleZ',
- defaultValue: 90,
+ defaultValue: 0,
label: 'angle Z'
- }
+ },
+ scenegraph: {
+ ...LAYER_VIS_CONFIGS.scenegraph,
+ defaultValue: DEFAULT_SCENEGRAPH_MODEL_ID
+ },
+ scenegraphColorEnabled: 'scenegraphColorEnabled',
+ scenegraphColor: 'scenegraphColor',
+ scenegraphCustomModelUrl: 'scenegraphCustomModelUrl'
};
-const DEFAULT_MODEL =
- 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Duck/glTF-Binary/Duck.glb';
const DEFAULT_TRANSITION: [0, 0, 0] = [0, 0, 0];
const DEFAULT_SCALE: [1, 1, 1] = [1, 1, 1];
-const DEFAULT_COLOR: [255, 255, 255, 255] = [255, 255, 255, 255];
+const DEFAULT_COLOR: RGBColor = [255, 255, 255];
+// https://deck.gl/docs/api-reference/mesh-layers/scenegraph-layer#_animations
+const DEFAULT_ANIMATIONS = {
+ '*': {speed: 5}
+};
+
+function isScenegraphAssetUrl(value: unknown): value is string {
+ return typeof value === 'string' && value.includes('/');
+}
+
+/**
+ * Saved 3D layers stored `scenegraph: null` and rendered the Khronos duck at
+ * `sizeScale` with yaw taken only from angle Z (default 90). Leaving null lets
+ * the new Ducky default add another 90° and multiply size by the model scale.
+ */
+export function migrateLegacyScenegraphVisConfig<T extends {scenegraph?: string | null}>(
+ visConfig: T | null | undefined
+): T | null | undefined {
+ if (!visConfig || visConfig.scenegraph != null) {
+ return visConfig;
+ }
+ const hasScenegraphKey = Object.prototype.hasOwnProperty.call(visConfig, 'scenegraph');
+ const looksLikeLegacyScenegraph =
+ hasScenegraphKey ||
+ Object.prototype.hasOwnProperty.call(visConfig, 'angleZ') ||
+ Object.prototype.hasOwnProperty.call(visConfig, 'angleX');
+ if (!looksLikeLegacyScenegraph) {
+ return visConfig;
+ }
+ return {...visConfig, scenegraph: LEGACY_DEFAULT_SCENEGRAPH_URL};
+}
export default class ScenegraphLayer extends Layer {
declare visConfigSettings: ScenegraphLayerVisConfigSettings;
declare config: ScenegraphLayerConfig;
_layerInfoModal: () => JSX.Element;
+ dataToFeature: any[] = [];
+ centroids: Array<number[] | null> = [];
+ private _geojsonFieldIdx = -1;
+ private _geojsonBounds: [number, number, number, number] | null = null;
constructor(props) {
super(props);
this.registerVisConfig(scenegraphVisConfigs);
- this.getPositionAccessor = (dataContainer: DataContainerInterface) =>
- scenegraphPosAccessor(this.config.columns)(dataContainer);
+ this.getPositionAccessor = (dataContainer: DataContainerInterface) => {
+ if (this.config.columnMode === COLUMN_MODE_GEOJSON) {
+ return scenegraphGeojsonAccessor(this.config.columns)(dataContainer);
+ }
+ return scenegraphPosAccessor(this.config.columns)(dataContainer);
+ };
// prepare layer info modal
this._layerInfoModal = ScenegraphInfoModalFactory();
@@ -132,12 +291,8 @@ export default class ScenegraphLayer extends Layer {
return '3D';
}
- get requiredLayerColumns() {
- return scenegraphRequiredColumns;
- }
-
- get optionalColumns() {
- return scenegraphOptionalColumns;
+ get supportedColumnModes() {
+ return SUPPORTED_COLUMN_MODES;
}
get columnPairs() {
@@ -154,16 +309,67 @@ export default class ScenegraphLayer extends Layer {
}
get layerInfoModal() {
- return {
+ const modal = {
id: 'scenegraphInfo',
template: this._layerInfoModal,
modalProps: {
title: 'How to use Scenegraph'
}
};
+ return {
+ [COLUMN_MODE_POINTS]: modal,
+ [COLUMN_MODE_GEOJSON]: modal
+ };
+ }
+
+ getDefaultLayerConfig(props) {
+ return {
+ ...super.getDefaultLayerConfig(props),
+ columnMode: props?.columnMode ?? DEFAULT_COLUMN_MODE
+ };
+ }
+
+ static findDefaultLayerProps(dataset: KeplerTable): FindDefaultLayerPropsReturnValue {
+ const geojsonColumns = dataset.fields
+ .filter(
+ f =>
+ (f.type === 'geojson' || f.type === 'geoarrow') &&
+ f.analyzerType &&
+ SUPPORTED_ANALYZER_TYPES[f.analyzerType]
+ )
+ .map(f => f.name);
+
+ const defaultColumns = {
+ geojson: [...(GEOJSON_FIELDS.geojson || []), ...geojsonColumns]
+ };
+ const foundColumns = this.findDefaultColumnField(defaultColumns, dataset.fields);
+ const altProps = foundColumns?.length
+ ? foundColumns.map(columns => ({
+ label:
+ (typeof dataset.label === 'string' && dataset.label.replace(/\.[^/.]+$/, '')) || '3D',
+ columns,
+ columnMode: COLUMN_MODE_GEOJSON
+ }))
+ : [];
+
+ return {props: [], altProps};
+ }
+
+ getDataUpdateTriggers(dataset: KeplerTable): any {
+ const triggers = super.getDataUpdateTriggers(dataset);
+ const {columnMode} = this.config;
+ return {
+ ...triggers,
+ getData: {...triggers.getData, columnMode},
+ getMeta: {...triggers.getMeta, columnMode}
+ };
}
calculateDataAttribute({filteredIndex}: KeplerTable, getPosition) {
+ if (this.config.columnMode === COLUMN_MODE_GEOJSON) {
+ return this._calculateGeojsonDataAttribute(filteredIndex);
+ }
+
const data: ScenegraphLayerData[] = [];
for (let i = 0; i < filteredIndex.length; i++) {
@@ -182,13 +388,41 @@ export default class ScenegraphLayer extends Layer {
return data;
}
+ /**
+ * Place one model per GeoJSON feature at its centroid.
+ * Points use their coordinate; lines and polygons use the vertex average.
+ */
+ private _calculateGeojsonDataAttribute(filteredIndex: number[]) {
+ const data: ScenegraphLayerData[] = [];
+
+ for (let i = 0; i < filteredIndex.length; i++) {
+ const index = filteredIndex[i];
+ const centroid =
+ this.centroids[index] ||
+ (this.dataToFeature[index]?.geometry
+ ? getCentroidFromGeometry(this.dataToFeature[index].geometry)
+ : null);
+ if (centroid && Number.isFinite(centroid[0]) && Number.isFinite(centroid[1])) {
+ data.push({
+ position: [centroid[0], centroid[1], 0],
+ index
+ });
+ }
+ }
+
+ return data;
+ }
+
formatLayerData(datasets, oldLayerData) {
if (this.config.dataId === null) {
return {};
}
const {gpuFilter, dataContainer} = datasets[this.config.dataId];
const {data} = this.updateData(datasets, oldLayerData);
- const getPosition = this.getPositionAccessor(dataContainer);
+ const isGeojsonMode = this.config.columnMode === COLUMN_MODE_GEOJSON;
+ const getPosition = isGeojsonMode
+ ? (d: {position: number[]}) => d.position
+ : this.getPositionAccessor(dataContainer);
return {
data,
getPosition,
@@ -198,18 +432,120 @@ export default class ScenegraphLayer extends Layer {
updateLayerMeta(dataset: KeplerTable, getPosition) {
const {dataContainer} = dataset;
+
+ if (this.config.columnMode === COLUMN_MODE_GEOJSON) {
+ const getFeature = this.getPositionAccessor(dataContainer);
+ const geoField = dataset.fields?.[this.config.columns.geojson?.fieldIdx ?? -1];
+ const encoding =
+ geoField?.metadata && typeof (geoField.metadata as Map<string, string>).get === 'function'
+ ? (geoField.metadata as Map<string, string>).get(GEOARROW_METADATA_KEY)
+ : (geoField?.metadata as Record<string, string> | undefined)?.[GEOARROW_METADATA_KEY];
+ this._buildGeojsonDataToFeature(dataContainer, getFeature, encoding);
+ this.updateMeta({bounds: this._geojsonBounds});
+ return;
+ }
+
+ this.dataToFeature = [];
+ this.centroids = [];
const bounds = this.getPointsBounds(dataContainer, getPosition);
this.updateMeta({bounds});
}
- renderLayer(opts) {
- const {data, gpuFilter, mapState} = opts;
+ private _buildGeojsonDataToFeature(
+ dataContainer: DataContainerInterface,
+ getFeature: (d: {index: number}) => unknown,
+ geoArrowEncoding?: string | null
+ ) {
+ const fieldIdx = this.config.columns.geojson?.fieldIdx ?? -1;
+ if (
+ this.dataToFeature.length === dataContainer.numRows() &&
+ this._geojsonFieldIdx === fieldIdx
+ ) {
+ return;
+ }
+ this._geojsonFieldIdx = fieldIdx;
+ this.dataToFeature = [];
+ this.centroids = [];
+
+ let minLng = Infinity;
+ let maxLng = -Infinity;
+ let minLat = Infinity;
+ let maxLat = -Infinity;
+ let hasValid = false;
+
+ for (let i = 0; i < dataContainer.numRows(); i++) {
+ const feature = parseGeoJsonRawFeature(getFeature({index: i}), geoArrowEncoding);
+ this.dataToFeature[i] = feature;
+ this.centroids[i] = feature?.geometry ? getCentroidFromGeometry(feature.geometry) : null;
+
+ if (feature?.geometry) {
+ const positions = getAllPositions(feature.geometry);
+ for (const pos of positions) {
+ const lng = pos[0];
+ const lat = pos[1];
+ if (Number.isFinite(lng) && Number.isFinite(lat)) {
+ hasValid = true;
+ if (lng < minLng) minLng = lng;
+ if (lng > maxLng) maxLng = lng;
+ if (lat < minLat) minLat = lat;
+ if (lat > maxLat) maxLat = lat;
+ }
+ }
+ }
+ }
- const {
- visConfig: {sizeScale = 1, angleX = 0, angleY = 0, angleZ = 90}
- } = this.config;
+ this._geojsonBounds = hasValid ? [minLng, minLat, maxLng, maxLat] : null;
+ }
- const adjustedAngleY = angleY + (mapState?.globe?.enabled ? 180 : 0);
+ getScenegraph(): ScenegraphModel {
+ const {visConfig} = this.config;
+ const scenegraph = SCENEGRAPH_LAYER_MODELS.find(model => model.id === visConfig.scenegraph);
+ if (scenegraph?.id === CUSTOM_SCENEGRAPH_MODEL_ID) {
+ return {...scenegraph, url: visConfig.scenegraphCustomModelUrl || null};
+ }
+ if (scenegraph) {
+ return scenegraph;
+ }
+ // Older maps stored a glTF URL from the file picker in visConfig.scenegraph.
+ if (isScenegraphAssetUrl(visConfig.scenegraph)) {
+ return {
+ id: visConfig.scenegraph,
+ label: 'Custom',
+ icon: null,
+ url: visConfig.scenegraph,
+ angles: [0, 0, 0],
+ scale: 1
+ };
+ }
+ return DEFAULT_SCENEGRAPH_MODEL;
+ }
+
+ getOrientation(scenegraph: ScenegraphModel, globeMode: boolean): [number, number, number] {
+ const {angleX = 0, angleY = 0, angleZ = 0} = this.config.visConfig;
+ const adjustedAngleY = angleY + (globeMode ? 180 : 0);
+ return [
+ angleX + scenegraph.angles[0],
+ adjustedAngleY + scenegraph.angles[1],
+ angleZ + scenegraph.angles[2]
+ ];
+ }
+
+ getColor(): RGBColor {
+ const {scenegraphColorEnabled, scenegraphColor} = this.config.visConfig;
+ return scenegraphColorEnabled && scenegraphColor ? scenegraphColor : DEFAULT_COLOR;
+ }
+
+ renderLayer(opts) {
+ const scenegraph = this.getScenegraph();
+ if (!scenegraph.url) {
+ return [];
+ }
+
+ const {data, gpuFilter, mapState} = opts;
+ const {sizeScale = 1} = this.config.visConfig;
+ const globeMode = Boolean(mapState?.globe?.enabled);
+ const orientation = this.getOrientation(scenegraph, globeMode);
+ const color = this.getColor();
return [
new DeckScenegraphLayer({
@@ -218,19 +554,22 @@ export default class ScenegraphLayer extends Layer {
extensions: [],
...data,
fetch: fetchGltf,
- scenegraph: this.config.visConfig.scenegraph || DEFAULT_MODEL,
- sizeScale,
+ scenegraph: scenegraph.url,
+ sizeScale: sizeScale * scenegraph.scale,
getTranslation: DEFAULT_TRANSITION,
getScale: DEFAULT_SCALE,
- getOrientation: [angleX, adjustedAngleY, angleZ],
- getColor: DEFAULT_COLOR,
+ getOrientation: orientation,
+ getColor: color,
+ _lighting: 'pbr',
+ _animations: DEFAULT_ANIMATIONS,
// parameters
parameters: {depthTest: true, blend: false, ...(mapState?.layerParameters ?? {})},
// update triggers
updateTriggers: {
- getOrientation: {angleX, adjustedAngleY, angleZ},
- getPosition: this.config.columns,
- getFilterValue: gpuFilter.filterValueUpdateTriggers
+ getOrientation: orientation.join(','),
+ getPosition: {columns: this.config.columns, columnMode: this.config.columnMode},
+ getFilterValue: gpuFilter.filterValueUpdateTriggers,
+ getColor: color
}
})
];
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index fbf8f90bf..9af73a673 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -112,6 +112,10 @@ export default {
'3DModel': '3D Model',
'3DModelURL': 'Custom 3D Model URL',
'3DModelURLDescription': 'URL of a .glb or .glTF file with the 3D model.',
+ '3DModelSourceModel': 'Model',
+ '3DModelSourceUrl': 'URL',
+ '3DModelSourceFile': 'Local file',
+ '3DModelFile': 'Choose file',
'3DModelOptions': '3D Model Options',
service: 'Service',
layer: 'Layer',
diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.ts
index 8e4875bea..b548c6621 100644
--- a/src/reducers/src/vis-state-merger.ts
+++ b/src/reducers/src/vis-state-merger.ts
@@ -16,7 +16,7 @@ import {
isPlainObject
} from '@kepler.gl/utils';
-import {Layer} from '@kepler.gl/layers';
+import {Layer, migrateLegacyScenegraphVisConfig} from '@kepler.gl/layers';
import {createEffect} from '@kepler.gl/effects';
import {notNullorUndefined} from '@kepler.gl/common-utils';
import {
@@ -1289,9 +1289,13 @@ export function validateLayerWithData(
: newLayer.config.textLabel;
// copy visConfig over to emptyLayer to make sure it has all the props
+ const savedVisConfig =
+ savedLayer.type === '3D'
+ ? migrateLegacyScenegraphVisConfig(savedLayer.config.visConfig)
+ : savedLayer.config.visConfig;
const copiedVisConfig = newLayer.copyLayerConfig(
newLayer.config.visConfig,
- savedLayer.config.visConfig || {},
+ savedVisConfig || {},
{
shallowCopy: ['colorRange', 'strokeColorRange']
}
diff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.ts
index c749d7a75..1e93222e6 100644
--- a/src/schemas/src/vis-state-schema.ts
+++ b/src/schemas/src/vis-state-schema.ts
@@ -4,6 +4,7 @@
import pick from 'es-toolkit/compat/pick';
import {VERSIONS} from './versions';
import {LAYER_VIS_CONFIGS, FILTER_VIEW_TYPES} from '@kepler.gl/constants';
+import {migrateLegacyScenegraphVisConfig} from '@kepler.gl/layers';
import {
colorRangeBackwardCompatibility,
isFilterValidToSave,
@@ -54,6 +55,7 @@ export type modifiedType = {
strokeColorRange?: any;
filled?: boolean;
stroked?: boolean;
+ scenegraph?: string;
};
export interface VisState {
@@ -525,6 +527,13 @@ const visConfigModificationV1 = {
}
return modified;
+ },
+ '3D': visConfig => {
+ const migrated = migrateLegacyScenegraphVisConfig(visConfig);
+ if (!migrated || migrated.scenegraph === visConfig?.scenegraph) {
+ return {};
+ }
+ return {scenegraph: migrated.scenegraph};
}
};
diff --git a/test/browser/layer-tests/scenegraph-layer-specs.js b/test/browser/layer-tests/scenegraph-layer-specs.js
index c3215040c..c2dad7705 100644
--- a/test/browser/layer-tests/scenegraph-layer-specs.js
+++ b/test/browser/layer-tests/scenegraph-layer-specs.js
@@ -18,7 +18,13 @@ import {
pointLayerMeta,
preparedFilterDomain0
} from 'test/helpers/layer-utils';
-import {KeplerGlLayers} from '@kepler.gl/layers';
+import {
+ DEFAULT_SCENEGRAPH_MODEL,
+ CUSTOM_SCENEGRAPH_MODEL_ID,
+ LEGACY_DEFAULT_SCENEGRAPH_URL
+} from '@kepler.gl/constants';
+import {KeplerGlLayers, toCorsSafeGcsUrl} from '@kepler.gl/layers';
+import SchemaManager, {CURRENT_VERSION} from '@kepler.gl/schemas';
const {ScenegraphLayer} = KeplerGlLayers;
const columns = {lat: 'lat', lng: 'lng'};
@@ -37,6 +43,17 @@ test('#ScenegraphLayer -> constructor', t => {
t.ok(layer.isAggregated === false, 'ScenegraphLayer is not aggregated');
t.ok(layer.config.label === 'test 3d layer', 'label should be correct');
t.ok(Object.keys(layer.columnPairs).length, 'should have columnPairs');
+ t.equal(
+ layer.config.visConfig.scenegraph,
+ DEFAULT_SCENEGRAPH_MODEL.id,
+ 'should default to the gallery duck'
+ );
+ t.equal(
+ layer.config.visConfig.angleZ,
+ 0,
+ 'angle Z default lets the duck model supply yaw'
+ );
+ t.equal(layer.config.visConfig.scenegraphColorEnabled, false, 'tint starts off');
t.deepEqual(
layer.getLegendVisualChannels(),
{},
@@ -160,16 +177,180 @@ test('#ScenegraphLayer -> renderLayer', t => {
assert: (deckLayers, layer) => {
t.equal(deckLayers.length, 1, 'Should create 1 deck.gl layer');
const {props} = deckLayers[0];
+ const {sizeScale, angleX, angleY, angleZ} = layer.config.visConfig;
+ t.equal(
+ layer.getScenegraph().url,
+ DEFAULT_SCENEGRAPH_MODEL.url,
+ 'should load the duck model'
+ );
const expectedProps = {
opacity: layer.config.visConfig.opacity,
- sizeScale: layer.config.visConfig.sizeScale,
- filterRange: preparedDataset.gpuFilter.filterRange
+ sizeScale: sizeScale * DEFAULT_SCENEGRAPH_MODEL.scale,
+ filterRange: preparedDataset.gpuFilter.filterRange,
+ getOrientation: [
+ angleX + DEFAULT_SCENEGRAPH_MODEL.angles[0],
+ angleY + DEFAULT_SCENEGRAPH_MODEL.angles[1],
+ angleZ + DEFAULT_SCENEGRAPH_MODEL.angles[2]
+ ],
+ getColor: [255, 255, 255],
+ _lighting: 'pbr'
};
Object.keys(expectedProps).forEach(key => {
- t.equal(props[key], expectedProps[key], `should have correct props.${key}`);
+ t.deepEqual(props[key], expectedProps[key], `should have correct props.${key}`);
});
}
+ },
+ {
+ name: 'Scenegraph gallery model',
+ layer: {
+ type: '3D',
+ id: 'test_layer_airplane',
+ config: {
+ dataId,
+ label: 'gps 3d',
+ columns,
+ visConfig: {
+ scenegraph: 'airplane'
+ }
+ }
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex
+ }
+ },
+ assert: (deckLayers, layer) => {
+ const model = layer.getScenegraph();
+ t.equal(deckLayers.length, 1, 'should render a gallery model');
+ t.equal(model.id, 'airplane');
+ t.ok(model.url.endsWith('/Plane.glb'), 'should load the airplane model');
+ t.equal(
+ deckLayers[0].props.sizeScale,
+ layer.config.visConfig.sizeScale * model.scale,
+ 'gallery models use a scale of 1'
+ );
+ }
+ },
+ {
+ name: 'Scenegraph custom url and tint',
+ layer: {
+ type: '3D',
+ id: 'test_layer_custom',
+ config: {
+ dataId,
+ label: 'gps 3d',
+ columns,
+ visConfig: {
+ scenegraph: CUSTOM_SCENEGRAPH_MODEL_ID,
+ scenegraphCustomModelUrl: 'https://example.com/model.glb',
+ scenegraphColorEnabled: true,
+ scenegraphColor: [10, 20, 30]
+ }
+ }
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex
+ }
+ },
+ assert: (deckLayers, layer) => {
+ t.equal(layer.getScenegraph().url, 'https://example.com/model.glb');
+ t.deepEqual(deckLayers[0].props.getColor, [10, 20, 30], 'should tint the model');
+ }
+ },
+ {
+ name: 'Scenegraph custom url missing',
+ layer: {
+ type: '3D',
+ id: 'test_layer_custom_empty',
+ config: {
+ dataId,
+ label: 'gps 3d',
+ columns,
+ visConfig: {
+ scenegraph: CUSTOM_SCENEGRAPH_MODEL_ID,
+ scenegraphCustomModelUrl: ''
+ }
+ }
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex
+ }
+ },
+ assert: deckLayers => {
+ t.equal(deckLayers.length, 0, 'should not render until a custom URL is set');
+ }
+ },
+ {
+ name: 'Scenegraph legacy file url',
+ layer: {
+ type: '3D',
+ id: 'test_layer_legacy',
+ config: {
+ dataId,
+ label: 'gps 3d',
+ columns,
+ visConfig: {
+ scenegraph: 'blob:http://localhost/model.glb',
+ angleZ: 90,
+ sizeScale: 10
+ }
+ }
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex
+ }
+ },
+ assert: (deckLayers, layer) => {
+ const {props} = deckLayers[0];
+ t.equal(layer.getScenegraph().url, 'blob:http://localhost/model.glb');
+ t.equal(props.sizeScale, 10, 'legacy urls keep the saved size');
+ t.deepEqual(props.getOrientation, [0, 0, 90], 'legacy urls do not add model angles');
+ }
+ },
+ {
+ name: 'Scenegraph legacy default duck',
+ layer: {
+ type: '3D',
+ id: 'test_layer_legacy_default',
+ config: {
+ dataId,
+ label: 'gps 3d',
+ columns,
+ visConfig: {
+ scenegraph: null,
+ angleZ: 90,
+ sizeScale: 10
+ }
+ }
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex
+ }
+ },
+ assert: (deckLayers, layer) => {
+ const {props} = deckLayers[0];
+ t.equal(
+ layer.config.visConfig.scenegraph,
+ LEGACY_DEFAULT_SCENEGRAPH_URL,
+ 'null scenegraph keeps the pre-gallery duck'
+ );
+ t.equal(props.sizeScale, 10, 'legacy default duck keeps the saved size');
+ t.deepEqual(
+ props.getOrientation,
+ [0, 0, 90],
+ 'legacy default duck does not add the gallery model yaw'
+ );
+ }
}
];
@@ -178,3 +359,115 @@ test('#ScenegraphLayer -> renderLayer', t => {
stubedFetch.restore();
t.end();
});
+
+test('#ScenegraphLayer -> geojson centroid', t => {
+ const layer = new ScenegraphLayer({
+ id: 'scenegraph-geojson',
+ dataId: 'geo',
+ columnMode: 'geojson',
+ columns: {
+ geojson: {value: 'geom', fieldIdx: 0}
+ }
+ });
+ const rows = [
+ [{type: 'Point', coordinates: [-122.4, 37.8]}],
+ [
+ {
+ type: 'LineString',
+ coordinates: [
+ [0, 0],
+ [2, 2]
+ ]
+ }
+ ],
+ [null]
+ ];
+ const dataset = {
+ dataContainer: {
+ numRows: () => rows.length,
+ valueAt: (index, fieldIdx) => rows[index][fieldIdx]
+ },
+ fields: [{name: 'geom', fieldIdx: 0, type: 'geojson'}],
+ filteredIndex: [0, 1, 2]
+ };
+
+ layer.updateLayerMeta(dataset);
+ const data = layer.calculateDataAttribute(dataset, () => null);
+
+ t.equal(layer.config.columnMode, 'geojson', 'geojson column mode is selected');
+ t.equal(data.length, 2, 'skips features without geometry');
+ t.deepEqual(data[0].position, [-122.4, 37.8, 0], 'point features keep their coordinate');
+ t.deepEqual(data[1].position, [1, 1, 0], 'lines and polygons use the vertex centroid');
+ t.end();
+});
+
+test('#ScenegraphLayer -> GCS model URL', t => {
+ t.equal(
+ toCorsSafeGcsUrl('https://storage.googleapis.com/kepler-examples/duck.glb'),
+ 'https://storage.googleapis.com/storage/v1/b/kepler-examples/o/duck.glb?alt=media',
+ 'rewrites public GCS object URLs to the CORS-enabled download API'
+ );
+ const signed =
+ 'https://storage.googleapis.com/kepler-examples/duck.glb?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Signature=abc';
+ t.equal(toCorsSafeGcsUrl(signed), signed, 'leaves signed GCS URLs unchanged');
+ const signedVirtualHost =
+ 'https://kepler-examples.storage.googleapis.com/duck.glb?GoogleAccessId=test&Expires=1&Signature=abc';
+ t.equal(
+ toCorsSafeGcsUrl(signedVirtualHost),
+ signedVirtualHost,
+ 'leaves virtual-hosted signed GCS URLs unchanged'
+ );
+ t.equal(
+ toCorsSafeGcsUrl('https://studio-public-data.foursquare.com/statics/keplergl/Duck.glb'),
+ 'https://studio-public-data.foursquare.com/statics/keplergl/Duck.glb',
+ 'leaves non-GCS URLs unchanged'
+ );
+ t.equal(
+ toCorsSafeGcsUrl('blob:http://localhost/model.glb'),
+ 'blob:http://localhost/model.glb',
+ 'leaves local file URLs unchanged'
+ );
+ t.end();
+});
+
+test('#ScenegraphLayer -> saved map without a model', t => {
+ const saved = {
+ version: CURRENT_VERSION,
+ config: {
+ visState: {
+ layers: [
+ {
+ id: 'legacy-3d',
+ type: '3D',
+ config: {
+ dataId: 'd',
+ label: 'old duck',
+ visConfig: {scenegraph: null, angleZ: 90, sizeScale: 10}
+ }
+ },
+ {
+ id: 'trip-0',
+ type: 'trip',
+ config: {
+ dataId: 'd',
+ label: 'trip',
+ visConfig: {scenegraph: null, scenegraphEnabled: false}
+ }
+ }
+ ]
+ }
+ }
+ };
+ const layers = SchemaManager.parseSavedConfig(saved).visState.layers;
+ const duck = layers.find(layer => layer.type === '3D');
+ const trip = layers.find(layer => layer.type === 'trip');
+
+ t.equal(
+ duck.config.visConfig.scenegraph,
+ LEGACY_DEFAULT_SCENEGRAPH_URL,
+ 'saved 3D layers with a null model keep the pre-gallery duck'
+ );
+ t.equal(duck.config.visConfig.angleZ, 90, 'saved angle Z is preserved');
+ t.equal(trip.config.visConfig.scenegraph, null, 'trip layers keep an empty model');
+ t.end();
+});