-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathbitmap-layer.ts
More file actions
566 lines (509 loc) · 16.4 KB
/
Copy pathbitmap-layer.ts
File metadata and controls
566 lines (509 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
import {BitmapLayer as DeckBitmapLayer, PathLayer, ScatterplotLayer} from '@deck.gl/layers';
import {
EditableGeoJsonLayer,
ModifyMode,
TranslateMode,
CompositeMode,
GeoJsonEditMode
} from '@deck.gl-community/editable-layers';
import Layer from '../base-layer';
import BitmapLayerIcon from './bitmap-layer-icon';
import {FindDefaultLayerPropsReturnValue} from '../layer-utils';
import {
LAYER_VIS_CONFIGS,
LAYER_TYPES,
DatasetType,
BitmapDatasetMetadata,
BitmapBounds
} from '@kepler.gl/constants';
import {KeplerTable as KeplerDataset, Datasets as KeplerDatasets} from '@kepler.gl/table';
import {VisConfigNumber, VisConfigBoolean} from '@kepler.gl/types';
const EDIT_MODE = new CompositeMode([
new TranslateMode() as unknown as GeoJsonEditMode,
new ModifyMode() as unknown as GeoJsonEditMode
]);
export type BitmapLayerVisConfigSettings = {
opacity: VisConfigNumber;
showBounds: VisConfigBoolean;
editBounds: VisConfigBoolean;
alignMode: VisConfigBoolean;
boundsWest: VisConfigNumber;
boundsSouth: VisConfigNumber;
boundsEast: VisConfigNumber;
boundsNorth: VisConfigNumber;
};
export const bitmapVisConfigs = {
opacity: {
...LAYER_VIS_CONFIGS.opacity,
defaultValue: 1,
property: 'opacity'
} as VisConfigNumber,
showBounds: {
type: 'boolean',
defaultValue: true,
label: 'layerVisConfigs.showBounds',
group: 'display',
property: 'showBounds'
} as VisConfigBoolean,
editBounds: {
type: 'boolean',
defaultValue: false,
label: 'layerVisConfigs.editBounds',
group: 'display',
property: 'editBounds'
} as VisConfigBoolean,
alignMode: {
type: 'boolean',
defaultValue: false,
label: 'layerVisConfigs.alignMode',
group: 'display',
property: 'alignMode'
} as VisConfigBoolean,
boundsWest: {
type: 'number',
defaultValue: 0,
label: 'layerVisConfigs.boundsWest',
isRanged: false,
range: [-180, 180],
step: 0.0001,
group: 'display',
property: 'boundsWest'
} as VisConfigNumber,
boundsSouth: {
type: 'number',
defaultValue: 0,
label: 'layerVisConfigs.boundsSouth',
isRanged: false,
range: [-90, 90],
step: 0.0001,
group: 'display',
property: 'boundsSouth'
} as VisConfigNumber,
boundsEast: {
type: 'number',
defaultValue: 0,
label: 'layerVisConfigs.boundsEast',
isRanged: false,
range: [-180, 180],
step: 0.0001,
group: 'display',
property: 'boundsEast'
} as VisConfigNumber,
boundsNorth: {
type: 'number',
defaultValue: 0,
label: 'layerVisConfigs.boundsNorth',
isRanged: false,
range: [-90, 90],
step: 0.0001,
group: 'display',
property: 'boundsNorth'
} as VisConfigNumber
};
export type AlignControlPoint = {
uv: [number, number]; // normalized image coordinates (0-1)
geo: [number, number]; // [lng, lat]
};
export default class BitmapOverlayLayer extends Layer {
declare visConfigSettings: BitmapLayerVisConfigSettings;
private _editFeatureCollection: any = null;
private _prevDataBoundsKey: string = '';
private _onRedrawNeeded: (() => void) | undefined;
private _rafId: number | undefined;
// Alignment mode state
alignControlPoints: AlignControlPoint[] = [];
alignWaitingForMap: boolean = false;
private _pendingUV: [number, number] | null = null;
constructor(props: {dataId: string; visConfig?: Record<string, any>} & Record<string, any>) {
super(props);
this.registerVisConfig(bitmapVisConfigs);
// Apply visConfig from findDefaultLayerProps (e.g. bounds seeded from metadata)
if (props.visConfig) {
this.updateLayerVisConfig(props.visConfig);
}
this.meta = {};
}
// --- Alignment mode methods ---
onAlignImageClick(uv: [number, number]): void {
this._pendingUV = uv;
this.alignWaitingForMap = true;
}
onAlignMapClick(lngLat: [number, number]): void {
if (!this._pendingUV) return;
this.alignControlPoints = [
...this.alignControlPoints,
{uv: this._pendingUV, geo: lngLat}
];
this._pendingUV = null;
this.alignWaitingForMap = false;
if (this.alignControlPoints.length >= 2) {
this._computeBoundsFromControlPoints();
}
}
resetAlignControlPoints(): void {
this.alignControlPoints = [];
this.alignWaitingForMap = false;
this._pendingUV = null;
}
private _computeBoundsFromControlPoints(): void {
const pts = this.alignControlPoints;
if (pts.length < 2) return;
// Solve affine: lng = a * u + b, lat = c * v + d
// From 2+ points, use least squares (for 2 points, exact solution)
const n = pts.length;
let sumU = 0, sumLng = 0, sumUU = 0, sumULng = 0;
let sumV = 0, sumLat = 0, sumVV = 0, sumVLat = 0;
for (const p of pts) {
const [u, v] = p.uv;
const [lng, lat] = p.geo;
sumU += u; sumLng += lng; sumUU += u * u; sumULng += u * lng;
sumV += v; sumLat += lat; sumVV += v * v; sumVLat += v * lat;
}
// lng = a*u + b (solve for a, b)
const detU = n * sumUU - sumU * sumU;
if (Math.abs(detU) < 1e-12) return;
const a = (n * sumULng - sumU * sumLng) / detU;
const b = (sumLng - a * sumU) / n;
// lat = 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;
// Bounds: image corners are (0,0), (1,0), (1,1), (0,1)
// UV origin (0,0) = top-left of image, (1,1) = bottom-right
const west = b; // u=0
const east = a + b; // u=1
const north = d; // v=0 (top of image)
const south = c + d; // v=1 (bottom of image)
this.updateLayerVisConfig({
boundsWest: Math.min(west, east),
boundsEast: Math.max(west, east),
boundsSouth: Math.min(south, north),
boundsNorth: Math.max(south, north)
});
this._onRedrawNeeded?.();
}
updateLayerVisConfig(newVisConfig: Record<string, any>): this {
if ('alignMode' in newVisConfig && !newVisConfig.alignMode) {
this.resetAlignControlPoints();
}
// Make alignMode and editBounds mutually exclusive
if (newVisConfig.alignMode && this.config.visConfig.editBounds) {
newVisConfig.editBounds = false;
}
if (newVisConfig.editBounds && this.config.visConfig.alignMode) {
newVisConfig.alignMode = false;
this.resetAlignControlPoints();
}
super.updateLayerVisConfig(newVisConfig);
return this;
}
static findDefaultLayerProps(dataset: KeplerDataset): FindDefaultLayerPropsReturnValue {
if (dataset.type !== DatasetType.BITMAP) {
return {props: []};
}
const metadata = (dataset.metadata || {}) as BitmapDatasetMetadata;
const visConfig: Record<string, any> = {};
if (metadata.bounds) {
const metaBounds = metadata.bounds;
if (Array.isArray(metaBounds) && typeof metaBounds[0] === 'number') {
const [w, s, e, n] = metaBounds as [number, number, number, number];
visConfig.boundsWest = w;
visConfig.boundsSouth = s;
visConfig.boundsEast = e;
visConfig.boundsNorth = n;
} else if (Array.isArray(metaBounds) && Array.isArray(metaBounds[0])) {
const corners = metaBounds as [
[number, number],
[number, number],
[number, number],
[number, number]
];
const lngs = corners.map(c => c[0]);
const lats = corners.map(c => c[1]);
visConfig.boundsWest = Math.min(...lngs);
visConfig.boundsSouth = Math.min(...lats);
visConfig.boundsEast = Math.max(...lngs);
visConfig.boundsNorth = Math.max(...lats);
}
}
return {
props: [
{
label: dataset.label || 'Bitmap',
isVisible: true,
visConfig
}
]
};
}
get type(): string {
return LAYER_TYPES.bitmap;
}
get name(): string {
return 'Bitmap';
}
get requireData(): boolean {
return false;
}
get requiredLayerColumns(): string[] {
return [];
}
get layerIcon(): typeof BitmapLayerIcon {
return BitmapLayerIcon;
}
get supportedDatasetTypes(): DatasetType[] {
return [DatasetType.BITMAP];
}
get visualChannels() {
return {};
}
shouldRenderLayer(): boolean {
return Boolean(this.type && this.config.isVisible);
}
getHoverData(): any {
return null;
}
formatLayerData(datasets: KeplerDatasets): Record<string, any> {
const {dataId} = this.config;
if (!dataId || !datasets[dataId]) {
return {};
}
const dataset = datasets[dataId];
const metadata = (dataset.metadata || {}) as BitmapDatasetMetadata;
const {visConfig} = this.config;
const bounds: BitmapBounds = [
visConfig.boundsWest,
visConfig.boundsSouth,
visConfig.boundsEast,
visConfig.boundsNorth
];
this.updateMeta({bounds});
return {
imageUrl: metadata.imageUrl,
bounds
};
}
updateLayerMeta(_dataset: KeplerDataset): void {
// bounds are managed through visConfig, meta.bounds is set in formatLayerData
}
renderLayer(opts: any) {
const {data, layerCallbacks} = opts;
const {imageUrl, bounds} = data || {};
if (!imageUrl || !bounds) {
return [];
}
this._onRedrawNeeded = layerCallbacks?.onRedrawNeeded;
const {visConfig} = this.config;
const {visible} = this.getDefaultDeckLayerProps(opts);
// Use live visConfig bounds (handles direct mutations from alignment mode)
// rather than the potentially stale cached data.bounds from formatLayerData
const west = visConfig.boundsWest ?? bounds[0];
const south = visConfig.boundsSouth ?? bounds[1];
const east = visConfig.boundsEast ?? bounds[2];
const north = visConfig.boundsNorth ?? bounds[3];
const dataBoundsKey = `${west},${south},${east},${north}`;
// Rebuild the editable feature collection only when data.bounds changes
// (i.e., formatLayerData was re-run due to slider change or other external update).
// During editing, data.bounds stays stale (cached), so this won't trigger.
if (dataBoundsKey !== this._prevDataBoundsKey) {
this._prevDataBoundsKey = dataBoundsKey;
this._editFeatureCollection = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [
[
[west, north],
[east, north],
[east, south],
[west, south],
[west, north]
]
]
},
properties: {shape: 'Rectangle'}
}
]
};
}
// Read current bounds from the edit feature collection (source of truth during editing)
const editCoords =
this._editFeatureCollection?.features?.[0]?.geometry?.coordinates?.[0];
let activeBounds: [number, number, number, number];
if (editCoords && editCoords.length >= 4) {
// Use all vertices (excluding closing point which duplicates the first)
const pts = editCoords.slice(0, -1);
const lngs = pts.map((c: number[]) => c[0]);
const lats = pts.map((c: number[]) => c[1]);
activeBounds = [
Math.min(...lngs),
Math.min(...lats),
Math.max(...lngs),
Math.max(...lats)
];
} else {
activeBounds = [west, south, east, north];
}
const isAligning = visConfig.alignMode;
const layers: any[] = [
new DeckBitmapLayer({
id: this.id,
image: imageUrl,
bounds: activeBounds,
opacity: visConfig.opacity ?? 1,
pickable: isAligning,
visible,
onClick: isAligning
? (info: any) => {
if (this.alignWaitingForMap) {
// Second click: use the geo coordinate under the cursor
if (info.coordinate) {
this.onAlignMapClick(info.coordinate as [number, number]);
this._onRedrawNeeded?.();
}
} else {
// First click: capture the UV position on the image
if (info.bitmap?.uv) {
this.onAlignImageClick(info.bitmap.uv as [number, number]);
this._onRedrawNeeded?.();
}
}
return true;
}
: undefined
})
];
// Visualize alignment control points
if (visConfig.alignMode && this.alignControlPoints.length > 0) {
layers.push(
new ScatterplotLayer({
id: `${this.id}-align-pts`,
data: this.alignControlPoints,
getPosition: (d: AlignControlPoint) => d.geo,
getFillColor: [255, 100, 100, 220],
getRadius: 6,
radiusUnits: 'pixels',
pickable: false,
visible,
updateTriggers: {
getPosition: this.alignControlPoints.length
}
})
);
}
// 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);
layers.push(
new ScatterplotLayer({
id: `${this.id}-align-pending`,
data: [{position: [pendingLng, pendingLat]}],
getPosition: (d: any) => d.position,
getFillColor: [100, 200, 255, 220],
getLineColor: [255, 255, 255, 255],
getRadius: 8,
radiusUnits: 'pixels',
stroked: true,
lineWidthMinPixels: 2,
pickable: false,
visible
})
);
}
if (visConfig.showBounds && !visConfig.editBounds) {
// Static boundary outline (no interaction)
const [aW, aS, aE, aN] = activeBounds;
layers.push(
new PathLayer({
id: `${this.id}-bounds`,
data: [
[
[aW, aN],
[aE, aN],
[aE, aS],
[aW, aS],
[aW, aN]
]
],
getPath: (d: any) => d,
getColor: [255, 255, 255, 200],
getWidth: 2,
widthUnits: 'pixels',
pickable: false,
visible
})
);
}
if (visConfig.editBounds) {
// @ts-ignore - EditableGeoJsonLayer types are loose
layers.push(
new EditableGeoJsonLayer({
id: `${this.id}-edit`,
// @ts-ignore
data: this._editFeatureCollection,
mode: EDIT_MODE,
selectedFeatureIndexes: [0],
pickable: true,
pickingRadius: 12,
visible,
modeConfig: {
lockRectangles: true
},
filled: false,
stroked: true,
getLineColor: [255, 255, 255, 200],
getLineWidth: 2,
lineWidthUnits: 'pixels',
getEditHandlePointColor: [255, 200, 0, 255],
getEditHandlePointRadius: 6,
editHandlePointRadiusUnits: 'pixels',
onEdit: ({updatedData, editType}) => {
this._editFeatureCollection = updatedData;
const isFinal =
editType === 'finishMovePosition' ||
editType === 'translated' ||
editType === 'addPosition';
if (isFinal) {
// Sync sliders on gesture end
const geom = updatedData?.features?.[0]?.geometry;
const coords =
geom && 'coordinates' in geom ? (geom as any).coordinates[0] : null;
if (coords && coords.length >= 5) {
const pts = coords.slice(0, -1);
const lngs = pts.map((c: number[]) => c[0]);
const lats = pts.map((c: number[]) => c[1]);
this.updateLayerVisConfig({
boundsWest: Math.min(...lngs),
boundsSouth: Math.min(...lats),
boundsEast: Math.max(...lngs),
boundsNorth: Math.max(...lats)
});
}
if (this._rafId) {
cancelAnimationFrame(this._rafId);
this._rafId = undefined;
}
this._onRedrawNeeded?.();
} else if (!this._rafId) {
// Throttle live redraws to animation frame rate
this._rafId = requestAnimationFrame(() => {
this._rafId = undefined;
this._onRedrawNeeded?.();
});
}
}
})
);
}
return layers;
}
}