Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
fix: align bitmap control points in Mercator coordinates (#3945)
Igor Dykhtaa3f77a359932
diff --git a/src/layers/src/bitmap-layer/bitmap-layer.ts b/src/layers/src/bitmap-layer/bitmap-layer.tsindex bb63a706a..37d468c14 100644--- a/src/layers/src/bitmap-layer/bitmap-layer.ts+++ b/src/layers/src/bitmap-layer/bitmap-layer.ts@@ -8,6 +8,7 @@ import {ScatterplotLayer} from '@deck.gl/layers';import {EditableGeoJsonLayer} from '@deck.gl-community/editable-layers';+import {lngLatToWorld, worldToLngLat} from '@math.gl/web-mercator';import Layer from '../base-layer';import BitmapLayerIcon from './bitmap-layer-icon';@@ -23,6 +24,9 @@ import {import {KeplerTable as KeplerDataset, Datasets as KeplerDatasets} from '@kepler.gl/table';import {VisConfigNumber, VisConfigBoolean} from '@kepler.gl/types';+// deck.gl's Mercator shader clamps latitudes outside this range.+const MAX_BITMAP_LATITUDE = 89.9;+const CORNER_HANDLE_COLOR: [number, number, number, number] = [255, 200, 0, 255];const MOVE_HANDLE_COLOR: [number, number, number, number] = [38, 181, 242, 255];const MOVE_HANDLE_RADIUS = 10;@@ -179,7 +183,8 @@ export default class BitmapOverlayLayer extends Layer {const pts = this.alignControlPoints;if (pts.length < 2) return;- // Solve affine: lng = a * u + b, lat = c * v + d+ // The bitmap interpolates UVs in Mercator space, so fit projected Y, not latitude.+ // Solve affine: lng = a * u + b, mercatorY = c * v + d// From 2+ points, use least squares (for 2 points, exact solution)const n = pts.length;let sumU = 0,@@ -187,20 +192,22 @@ export default class BitmapOverlayLayer extends Layer {sumUU = 0,sumULng = 0;let sumV = 0,- sumLat = 0,+ sumY = 0,sumVV = 0,- sumVLat = 0;+ sumVY = 0;for (const p of pts) {const [u, v] = p.uv;const [lng, lat] = p.geo;+ if (![u, v, lng, lat].every(Number.isFinite) || Math.abs(lat) > MAX_BITMAP_LATITUDE) return;+ const y = lngLatToWorld([lng, lat])[1];sumU += u;sumLng += lng;sumUU += u * u;sumULng += u * lng;sumV += v;- sumLat += lat;+ sumY += y;sumVV += v * v;- sumVLat += v * lat;+ sumVY += v * y;}// lng = a*u + b (solve for a, b)@@ -209,18 +216,25 @@ export default class BitmapOverlayLayer extends Layer {const a = (n * sumULng - sumU * sumLng) / detU;const b = (sumLng - a * sumU) / n;- // lat = c*v + d (solve for c, d)+ // mercatorY = c*v + d (solve for c, d)const detV = n * sumVV - sumV * sumV;if (Math.abs(detV) < 1e-12) return;- const c = (n * sumVLat - sumV * sumLat) / detV;- const d = (sumLat - c * sumV) / n;+ const c = (n * sumVY - sumV * sumY) / detV;+ const d = (sumY - c * sumV) / n;// Bounds: image corners are (0,0), (1,0), (1,1), (0,1)// UV origin (0,0) = top-left of image, (1,1) = bottom-rightconst west = b; // u=0const east = a + b; // u=1- const north = d; // v=0 (top of image)- const south = c + d; // v=1 (bottom of image)+ const north = worldToLngLat([0, d])[1]; // v=0 (top of image)+ const south = worldToLngLat([0, c + d])[1]; // v=1 (bottom of image)++ if (+ ![west, east, north, south].every(Number.isFinite) ||+ Math.abs(north) > MAX_BITMAP_LATITUDE ||+ Math.abs(south) > MAX_BITMAP_LATITUDE+ )+ return;this.updateLayerVisConfig({boundsWest: Math.min(west, east),@@ -418,12 +432,23 @@ export default class BitmapOverlayLayer extends Layer {}const isAligning = visConfig.alignMode;+ // Saved/imported bounds may include the poles. Match deck's projection clamp+ // before it computes Mercator texture bounds, without changing the saved bounds.+ const bitmapBounds: [number, number, number, number] = [+ activeBounds[0],+ Math.max(-MAX_BITMAP_LATITUDE, Math.min(MAX_BITMAP_LATITUDE, activeBounds[1])),+ activeBounds[2],+ Math.max(-MAX_BITMAP_LATITUDE, Math.min(MAX_BITMAP_LATITUDE, activeBounds[3]))+ ];const layers: any[] = [new DeckBitmapLayer({- id: this.id,+ // BitmapLayer caches its mesh and texture uniforms across viewport changes.+ id: `${this.id}${opts.mapState?.globe?.enabled ? '-globe' : ''}`,image: imageUrl,- bounds: activeBounds,+ // Keep the texture in the alignment solver's Mercator plane, including on a globe.+ _imageCoordinateSystem: 'cartesian',+ bounds: bitmapBounds,opacity: visConfig.opacity ?? 1,pickable: isAligning,visible,@@ -462,13 +487,14 @@ export default class BitmapOverlayLayer extends Layer {// Visualize pending point (waiting for map click)if (visConfig.alignMode && this._pendingUV) {const [u, v] = this._pendingUV;- const [aW, aS, aE, aN] = activeBounds;- const pendingLng = aW + u * (aE - aW);- const pendingLat = aN + v * (aS - aN);+ const [aW, aS, aE, aN] = bitmapBounds;+ const nw = lngLatToWorld([aW, aN]);+ const se = lngLatToWorld([aE, aS]);+ const position = worldToLngLat([nw[0] + u * (se[0] - nw[0]), nw[1] + v * (se[1] - nw[1])]);layers.push(new ScatterplotLayer({id: `${this.id}-align-pending`,- data: [{position: [pendingLng, pendingLat]}],+ data: [{position}],getPosition: (d: any) => d.position,getFillColor: [100, 200, 255, 220],getLineColor: [255, 255, 255, 255],diff --git a/test/browser/layer-tests/bitmap-layer-specs.js b/test/browser/layer-tests/bitmap-layer-specs.jsindex 445e9f2ca..87a07d0b5 100644--- a/test/browser/layer-tests/bitmap-layer-specs.js+++ b/test/browser/layer-tests/bitmap-layer-specs.js@@ -4,6 +4,8 @@import test from 'tape-catch';import {KeplerGlLayers} from '@kepler.gl/layers';import {DatasetType} from '@kepler.gl/constants';+import {WebMercatorViewport, _GlobeViewport as GlobeViewport} from '@deck.gl/core';+import {lngLatToWorld, worldToLngLat} from '@math.gl/web-mercator';import {testCreateCases} from 'test/helpers/layer-utils';import {BitmapBoundsEditMode,@@ -600,3 +602,280 @@ test('#BitmapOverlayLayer -> layer properties', t => {t.end();});++test('#BitmapOverlayLayer -> aligns control points in the rendered Mercator plane', t => {+ const cases = [+ [+ {uv: [0.25, 0.25], geo: [10, 60]},+ {uv: [0.75, 0.75], geo: [20, 30]}+ ],+ [+ {uv: [0, 0], geo: [0, 0]},+ {uv: [1, 1], geo: [20, -70]}+ ],+ [+ {uv: [0, 0], geo: [-30, 80]},+ {uv: [1, 1], geo: [30, 40]},+ {+ uv: [0.5, 0.5],+ geo: worldToLngLat([+ lngLatToWorld([0, 0])[0],+ (lngLatToWorld([0, 80])[1] + lngLatToWorld([0, 40])[1]) / 2+ ])+ }+ ]+ ];+ for (const points of cases) {+ const layer = createBitmapLayer();+ for (const point of points) {+ layer.onAlignImageClick(point.uv);+ layer.onAlignMapClick(point.geo);+ }+ const {boundsWest, boundsEast, boundsNorth, boundsSouth} = layer.config.visConfig;+ t.ok(+ [boundsWest, boundsEast, boundsNorth, boundsSouth].every(Number.isFinite),+ 'finite bounds'+ );+ t.ok(boundsWest < boundsEast && boundsSouth < boundsNorth, 'ordered bounds');+ t.ok(boundsSouth > -90 && boundsNorth < 90, 'latitude bounds stay valid');+ const nw = lngLatToWorld([boundsWest, boundsNorth]);+ const se = lngLatToWorld([boundsEast, boundsSouth]);+ for (const {uv, geo} of points) {+ // deck's bitmap interpolates texture coordinates across projected corners.+ const rendered = worldToLngLat([+ nw[0] + uv[0] * (se[0] - nw[0]),+ nw[1] + uv[1] * (se[1] - nw[1])+ ]);+ t.ok(Math.abs(rendered[0] - geo[0]) < 1e-8, 'control point longitude matches');+ t.ok(Math.abs(rendered[1] - geo[1]) < 1e-8, 'control point latitude matches');+ }+ }+ t.end();+});++test('#BitmapOverlayLayer -> ignores degenerate or nonprojectable alignment', t => {+ for (const points of [+ [+ {uv: [0.5, 0.2], geo: [10, 60]},+ {uv: [0.5, 0.8], geo: [20, 30]}+ ],+ [+ {uv: [0.2, 0.5], geo: [10, 60]},+ {uv: [0.8, 0.5], geo: [20, 30]}+ ],+ [+ {uv: [0, 0], geo: [10, 89.95]},+ {uv: [1, 1], geo: [20, 30]}+ ],+ [+ {uv: [0, 0], geo: [NaN, 60]},+ {uv: [1, 1], geo: [20, 30]}+ ],+ [+ {uv: [Infinity, 0], geo: [10, 60]},+ {uv: [1, 1], geo: [20, 30]}+ ],+ [+ {uv: [0, 0.499], geo: [10, 80]},+ {uv: [1, 0.501], geo: [20, 79]}+ ]+ ]) {+ const layer = createBitmapLayer();+ const before = {...layer.config.visConfig};+ for (const {uv, geo} of points) {+ layer.onAlignImageClick(uv);+ layer.onAlignMapClick(geo);+ }+ t.deepEqual(layer.config.visConfig, before, 'preserves bounds when no valid fit exists');+ }+ t.end();+});++// Evaluate deck's chosen texture-coordinate conversion at a geographic point.+// The default mesh is latitude-linear on GlobeViewport and Mercator-linear on WebMercatorViewport.+function bitmapUVAtLocation(bitmap, viewport, geo) {+ bitmap.context = {viewport};+ const {coordinateConversion, bounds} = bitmap._getCoordinateUniforms();+ let position;+ let textureBounds;+ if (coordinateConversion === 1) {+ position = lngLatToWorld(geo);+ textureBounds = bounds;+ } else if (coordinateConversion === -1 || viewport.resolution) {+ position = geo;+ textureBounds = coordinateConversion === -1 ? bounds : bitmap.props.bounds;+ } else {+ position = lngLatToWorld(geo);+ textureBounds = [+ ...lngLatToWorld(bitmap.props.bounds.slice(0, 2)),+ ...lngLatToWorld(bitmap.props.bounds.slice(2, 4))+ ];+ }+ return [+ (position[0] - textureBounds[0]) / (textureBounds[2] - textureBounds[0]),+ (position[1] - textureBounds[3]) / (textureBounds[1] - textureBounds[3])+ ];+}++test('#BitmapOverlayLayer -> aligned texture points stay fixed when switching flat and globe', t => {+ const points = [+ {uv: [0, 0], geo: [10, 60]},+ {uv: [1, 0.5], geo: [20, 40]}+ ];+ const layer = createBitmapLayer();+ for (const {uv, geo} of points) {+ layer.onAlignImageClick(uv);+ layer.onAlignMapClick(geo);+ }+ layer.updateLayerVisConfig({alignMode: true});+ layer.onAlignImageClick([1, 0.5]);+ const originalBounds = {...layer.config.visConfig};+ let previousBitmap;+ for (const globe of [false, true, false]) {+ const viewport = new (globe ? GlobeViewport : WebMercatorViewport)({+ width: 800,+ height: 600,+ latitude: 40,+ longitude: 15,+ zoom: 3,+ resolution: 5+ });+ const renderedLayers = layer.renderLayer({+ data: layer.formatLayerData(MOCK_DATASETS),+ mapState: {globe: {enabled: globe}},+ visible: true,+ layerCallbacks: {}+ });+ const bitmap = renderedLayers[0];+ if (previousBitmap) {+ // deck transfers state by id; viewport changes alone do not update BitmapLayer.+ bitmap.internalState = {+ changeFlags: {+ dataChanged: false,+ propsChanged: false,+ updateTriggersChanged: false,+ viewportChanged: true,+ stateChanged: false,+ extensionsChanged: false+ }+ };+ bitmap._diffProps(bitmap.props, previousBitmap.props);+ t.ok(+ bitmap.id !== previousBitmap.id ||+ bitmap.shouldUpdateState({changeFlags: bitmap.internalState.changeFlags}),+ 'projection switch creates a new bitmap or invalidates its cached mesh and uniforms'+ );+ }+ previousBitmap = bitmap;+ const pending = renderedLayers.find(l => l.id === `${layer.id}-align-pending`);+ const position = pending.props.getPosition(pending.props.data[0]);+ t.ok(+ Math.abs(position[0] - 20) < 1e-8 && Math.abs(position[1] - 40) < 1e-8,+ 'pending marker matches the selected image point'+ );+ for (const {uv, geo} of points) {+ const actual = bitmapUVAtLocation(bitmap, viewport, geo);+ t.ok(+ Math.abs(actual[0] - uv[0]) < 1e-8,+ `longitude maps to image U in ${globe ? 'globe' : 'flat'}`+ );+ t.ok(+ Math.abs(actual[1] - uv[1]) < 1e-8,+ `latitude maps to image V in ${globe ? 'globe' : 'flat'}`+ );+ }+ t.deepEqual(layer.config.visConfig, originalBounds, 'projection changes preserve saved bounds');+ }+ t.end();+});++test('#BitmapOverlayLayer -> accepts finite fits beyond the square Mercator tile boundary', t => {+ for (const points of [+ [+ {uv: [0.25, 0.25], geo: [10, 84]},+ {uv: [0.75, 0.75], geo: [20, 80]}+ ],+ [+ {uv: [0, 0], geo: [10, 88]},+ {uv: [1, 1], geo: [20, 86]}+ ]+ ]) {+ const layer = createBitmapLayer();+ for (const {uv, geo} of points) {+ layer.onAlignImageClick(uv);+ layer.onAlignMapClick(geo);+ }+ const [bitmap] = layer.renderLayer({+ data: layer.formatLayerData(MOCK_DATASETS),+ mapState: {},+ visible: true,+ layerCallbacks: {}+ });+ const viewport = new WebMercatorViewport({+ width: 800,+ height: 600,+ latitude: 80,+ longitude: 15,+ zoom: 3+ });+ t.ok(+ bitmap.props.bounds[3] > 85.051129,+ 'retains renderable northern bounds beyond 85 degrees'+ );+ for (const {uv, geo} of points) {+ const actual = bitmapUVAtLocation(bitmap, viewport, geo);+ t.ok(+ Math.abs(actual[0] - uv[0]) < 1e-8 && Math.abs(actual[1] - uv[1]) < 1e-8,+ 'high-latitude control points map to their image location'+ );+ }+ if (points[0].geo[1] === 84)+ t.ok(+ Math.abs(bitmap.props.bounds[3] - 85.354501) < 1e-6,+ 'keeps the fitted 85.354501 degree bound'+ );+ }+ t.end();+});++test('#BitmapOverlayLayer -> renders saved polar bounds with finite Mercator texture coordinates', t => {+ const layer = createBitmapLayer({+ visConfig: {boundsWest: -180, boundsSouth: -90, boundsEast: 180, boundsNorth: 90}+ });+ const savedBounds = {...layer.config.visConfig};+ for (const globe of [false, true]) {+ const viewport = new (globe ? GlobeViewport : WebMercatorViewport)({+ width: 800,+ height: 600,+ latitude: 0,+ longitude: 0,+ zoom: 1,+ resolution: 5+ });+ const [bitmap] = layer.renderLayer({+ data: layer.formatLayerData(MOCK_DATASETS),+ mapState: {globe: {enabled: globe}},+ visible: true,+ layerCallbacks: {}+ });+ bitmap.context = {viewport};+ t.ok(+ bitmap._getCoordinateUniforms().bounds.every(Number.isFinite),+ 'texture bounds are finite at the poles'+ );+ for (const latitude of [-89.9, 0, 89.9]) {+ const uv = bitmapUVAtLocation(bitmap, viewport, [0, latitude]);+ t.ok(+ uv.every(value => Number.isFinite(value) && value >= 0 && value <= 1),+ 'polar and equatorial texture coordinates stay within the image'+ );+ const expectedV = latitude === 0 ? 0.5 : latitude < 0 ? 1 : 0;+ t.ok(+ Math.abs(uv[1] - expectedV) < 1e-8,+ 'the poles map to opposite image edges and the equator to its center'+ );+ }+ t.deepEqual(layer.config.visConfig, savedBounds, 'rendering preserves saved polar bounds');+ }+ t.end();+});