@tangram.gl/basemap-layers 0.0.0 → 10.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +12 -7
  2. package/THIRD-PARTY-NOTICES.md +7 -5
  3. package/dist/geojson-task-worker.js +3166 -0
  4. package/dist/geojson-task-worker.js.map +6 -0
  5. package/dist/geojson-worker.js +1089 -7
  6. package/dist/geojson-worker.js.map +3 -3
  7. package/dist/index.cjs +9588 -2093
  8. package/dist/index.cjs.map +3 -3
  9. package/dist/index.js +9599 -2090
  10. package/dist/index.js.map +3 -3
  11. package/dist/map-style.cjs +456 -20
  12. package/dist/map-style.cjs.map +3 -3
  13. package/dist/map-style.js +456 -19
  14. package/dist/map-style.js.map +2 -2
  15. package/dist/types/basemap-error.d.ts +52 -0
  16. package/dist/types/basemap-layer.d.ts +378 -25
  17. package/dist/types/basemap-protocol.d.ts +91 -0
  18. package/dist/types/basemap-request.d.ts +73 -0
  19. package/dist/types/circle-layer.d.ts +65 -8
  20. package/dist/types/color-relief-layer.d.ts +184 -0
  21. package/dist/types/dem-pixels.d.ts +40 -0
  22. package/dist/types/feature-state.d.ts +55 -0
  23. package/dist/types/fill-extrusion-lighting-extension.d.ts +1 -2
  24. package/dist/types/fill-outline-extension.d.ts +2 -3
  25. package/dist/types/fill-pattern.d.ts +35 -3
  26. package/dist/types/fill-style-extensions.d.ts +11 -59
  27. package/dist/types/geojson-resource.d.ts +18 -0
  28. package/dist/types/geojson-source.d.ts +13 -2
  29. package/dist/types/geojson-task-handler.d.ts +2 -0
  30. package/dist/types/geojson-task.d.ts +26 -0
  31. package/dist/types/geojson-tiler.d.ts +29 -2
  32. package/dist/types/geojson-worker.d.ts +5 -1
  33. package/dist/types/globe-horizon-extension.d.ts +2 -45
  34. package/dist/types/globe-layers.d.ts +141 -45
  35. package/dist/types/globe-line-angle-extension.d.ts +20 -17
  36. package/dist/types/glyph-store.d.ts +10 -1
  37. package/dist/types/heatmap-layer.d.ts +99 -0
  38. package/dist/types/hillshade-layer.d.ts +159 -27
  39. package/dist/types/icon-text-fit.d.ts +92 -0
  40. package/dist/types/image-source-layer.d.ts +142 -0
  41. package/dist/types/index.d.ts +25 -1
  42. package/dist/types/line-blur-extension.d.ts +3 -11
  43. package/dist/types/line-dash-extension.d.ts +53 -0
  44. package/dist/types/line-gradient-extension.d.ts +69 -0
  45. package/dist/types/line-metrics.d.ts +24 -0
  46. package/dist/types/line-pattern-extension.d.ts +50 -0
  47. package/dist/types/line-shape-extension.d.ts +76 -0
  48. package/dist/types/map-style-loader.d.ts +1 -1
  49. package/dist/types/map-style.d.ts +2 -2
  50. package/dist/types/mvt-label-layer.d.ts +111 -20
  51. package/dist/types/pmtiles-source.d.ts +38 -0
  52. package/dist/types/projected-background-layer.d.ts +63 -0
  53. package/dist/types/projected-bitmap-layer.d.ts +58 -0
  54. package/dist/types/projected-tile-data.d.ts +16 -0
  55. package/dist/types/projected-tile-selection.d.ts +72 -0
  56. package/dist/types/projected-tileset.d.ts +92 -0
  57. package/dist/types/projected-viewport.d.ts +76 -0
  58. package/dist/types/raster-color-extension.d.ts +4 -7
  59. package/dist/types/raster-fade.d.ts +155 -0
  60. package/dist/types/raster-tile-fingerprint.d.ts +11 -0
  61. package/dist/types/raster-tile-loader.d.ts +80 -0
  62. package/dist/types/shader-injection-plugin.d.ts +8 -0
  63. package/dist/types/source-features.d.ts +58 -0
  64. package/dist/types/source-tiles.d.ts +32 -0
  65. package/dist/types/sprite.d.ts +37 -3
  66. package/dist/types/stretch-icon-layer.d.ts +28 -0
  67. package/dist/types/style-accessor.d.ts +50 -12
  68. package/dist/types/style-expression.d.ts +22 -2
  69. package/dist/types/style-resolver.d.ts +47 -2
  70. package/dist/types/terrain-query.d.ts +39 -0
  71. package/dist/types/zoom-load-gate.d.ts +22 -0
  72. package/dist/types/zoom-paint-extension.d.ts +80 -11
  73. package/package.json +24 -21
  74. package/src/basemap-error.ts +82 -0
  75. package/src/basemap-layer.ts +1289 -101
  76. package/src/basemap-protocol.ts +353 -0
  77. package/src/basemap-request.ts +212 -0
  78. package/src/circle-layer.ts +430 -54
  79. package/src/color-relief-layer.ts +572 -0
  80. package/src/dem-pixels.ts +174 -0
  81. package/src/feature-state.ts +164 -0
  82. package/src/fill-extrusion-lighting-extension.ts +126 -9
  83. package/src/fill-outline-extension.ts +4 -4
  84. package/src/fill-pattern.ts +87 -9
  85. package/src/fill-style-extensions.ts +114 -44
  86. package/src/geojson-resource.ts +58 -0
  87. package/src/geojson-source.ts +106 -85
  88. package/src/geojson-task-handler.ts +11 -0
  89. package/src/geojson-task-worker.ts +8 -0
  90. package/src/geojson-task.ts +34 -0
  91. package/src/geojson-tiler.ts +270 -4
  92. package/src/geojson-worker.ts +36 -6
  93. package/src/globe-horizon-extension.ts +14 -4
  94. package/src/globe-layers.ts +1905 -406
  95. package/src/globe-line-angle-extension.ts +183 -23
  96. package/src/glyph-store.ts +28 -6
  97. package/src/heatmap-layer.ts +591 -0
  98. package/src/hillshade-layer.ts +309 -88
  99. package/src/icon-text-fit.ts +358 -0
  100. package/src/image-source-layer.ts +380 -0
  101. package/src/index.ts +58 -1
  102. package/src/line-blur-extension.ts +14 -12
  103. package/src/line-dash-extension.ts +303 -0
  104. package/src/line-gradient-extension.ts +191 -0
  105. package/src/line-metrics.ts +90 -0
  106. package/src/line-pattern-extension.ts +173 -0
  107. package/src/line-shape-extension.ts +272 -0
  108. package/src/map-style-loader.ts +5 -4
  109. package/src/map-style.ts +2 -1
  110. package/src/mvt-label-layer.ts +568 -144
  111. package/src/pmtiles-source.ts +276 -0
  112. package/src/projected-background-layer.ts +202 -0
  113. package/src/projected-bitmap-layer.ts +262 -0
  114. package/src/projected-tile-data.ts +132 -0
  115. package/src/projected-tile-selection.ts +605 -0
  116. package/src/projected-tileset.ts +183 -0
  117. package/src/projected-viewport.ts +254 -0
  118. package/src/raster-color-extension.ts +43 -18
  119. package/src/raster-fade.ts +319 -0
  120. package/src/raster-tile-fingerprint.ts +31 -0
  121. package/src/raster-tile-loader.ts +211 -0
  122. package/src/shader-injection-plugin.ts +25 -0
  123. package/src/source-features.ts +170 -0
  124. package/src/source-tiles.ts +102 -0
  125. package/src/sprite.ts +122 -15
  126. package/src/stretch-icon-layer.ts +87 -0
  127. package/src/style-accessor.ts +105 -17
  128. package/src/style-expression.ts +80 -3
  129. package/src/style-resolver.ts +200 -22
  130. package/src/terrain-query.ts +86 -0
  131. package/src/text-layout.ts +2 -3
  132. package/src/zoom-load-gate.ts +57 -0
  133. package/src/zoom-paint-extension.ts +245 -47
  134. package/dist/types/arabic-shaping.d.ts +0 -7
  135. package/dist/types/bidi.d.ts +0 -8
  136. package/dist/types/polylabel.d.ts +0 -17
  137. package/src/arabic-shaping.ts +0 -366
  138. package/src/bidi.ts +0 -199
  139. package/src/polylabel.ts +0 -312
@@ -0,0 +1,303 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {LayerExtension, log} from '@deck.gl/core';
6
+ import type {Accessor, CompositeLayer, Layer} from '@deck.gl/core';
7
+ import type {Device, Texture} from '@luma.gl/core';
8
+ import {createShaderInjectionPlugin} from './shader-injection-plugin';
9
+
10
+ /** The most dash intervals a pattern can store before it falls back to one dash and gap. */
11
+ export const MAX_DASH_INTERVALS = 32;
12
+ const MAX_DASH_ROWS = 4096;
13
+ const TEXTURE_WIDTH = 1 + MAX_DASH_INTERVALS / 2;
14
+
15
+ type DashArray = readonly [number, number];
16
+ type DashPattern = {
17
+ intervals: readonly DashArray[];
18
+ period: number;
19
+ dashLength: number;
20
+ merged: DashArray;
21
+ };
22
+
23
+ const patternRows = new Map<string, number>();
24
+ const patterns: DashPattern[] = [];
25
+ const patternTextures = new WeakMap<Device, {texture: Texture; rows: number}>();
26
+ let warnedAboutFullAtlas = false;
27
+
28
+ /**
29
+ * Registers normalized lengths in line widths and returns their stable row, or -1 if the
30
+ * pattern exceeds the atlas limits. Intervals use half widths to match PathLayer's coordinates.
31
+ */
32
+ export function getDashPatternRow(pattern: number[]): number {
33
+ if (Math.ceil(pattern.length / 2) > MAX_DASH_INTERVALS) {
34
+ return -1;
35
+ }
36
+ const key = pattern.join(',');
37
+ const existing = patternRows.get(key);
38
+ if (existing !== undefined) {
39
+ return existing;
40
+ }
41
+ if (patterns.length >= MAX_DASH_ROWS) {
42
+ if (!warnedAboutFullAtlas) {
43
+ warnedAboutFullAtlas = true;
44
+ log.warn(
45
+ `[BasemapLayer] The dash atlas holds ${MAX_DASH_ROWS} patterns. New line-dasharray patterns draw as one dash and one gap per period.`
46
+ )();
47
+ }
48
+ return -1;
49
+ }
50
+
51
+ const intervals: DashArray[] = [];
52
+ let period = 0;
53
+ let dashLength = 0;
54
+ let gapLength = 0;
55
+ for (const [index, length] of pattern.entries()) {
56
+ const end = period + 2 * length;
57
+ if (index % 2 === 0) {
58
+ intervals.push([period, end]);
59
+ dashLength += 2 * length;
60
+ } else {
61
+ gapLength += 2 * length;
62
+ }
63
+ period = end;
64
+ }
65
+ const row = patterns.length;
66
+ patterns.push({intervals, period, dashLength, merged: [dashLength, gapLength]});
67
+ patternRows.set(key, row);
68
+ return row;
69
+ }
70
+
71
+ /** The pattern stored in an atlas row, in half line widths. */
72
+ export function getDashPattern(row: number): DashPattern | undefined {
73
+ return patterns[row];
74
+ }
75
+
76
+ function decodeDashArray(array: DashArray): DashArray {
77
+ const [period, marker] = array;
78
+ const pattern = marker < 0 ? getDashPattern(-marker - 1) : undefined;
79
+ if (!pattern) {
80
+ return array;
81
+ }
82
+ const scale = period / pattern.period;
83
+ return [pattern.merged[0] * scale, pattern.merged[1] * scale];
84
+ }
85
+
86
+ function getPatternTexture(device: Device): Texture {
87
+ const previous = patternTextures.get(device);
88
+ const rows = patterns.length;
89
+ if (previous?.rows === rows) {
90
+ return previous.texture;
91
+ }
92
+
93
+ const height = 2 ** Math.ceil(Math.log2(Math.max(rows, 1)));
94
+ const data = new Float32Array(TEXTURE_WIDTH * height * 4);
95
+ patterns.forEach(({intervals, period, dashLength}, row) => {
96
+ const start = row * TEXTURE_WIDTH * 4;
97
+ data.set([intervals.length, period, dashLength, 0], start);
98
+ intervals.forEach((interval, index) => data.set(interval, start + 4 + index * 2));
99
+ });
100
+ const texture = device.createTexture({
101
+ format: 'rgba32float',
102
+ width: TEXTURE_WIDTH,
103
+ height,
104
+ mipLevels: 1,
105
+ sampler: {minFilter: 'nearest', magFilter: 'nearest'}
106
+ });
107
+ texture.writeData(data);
108
+ previous?.texture.destroy();
109
+ patternTextures.set(device, {texture, rows});
110
+ return texture;
111
+ }
112
+
113
+ const LINE_DASH_PLUGIN = createShaderInjectionPlugin({
114
+ name: 'lineDash',
115
+ vs: /* glsl */ `
116
+ #ifdef DASH_MODE_PATH
117
+ flat out float lineDash_row;
118
+ flat out float lineDash_period;
119
+ flat out float lineDash_offset;
120
+ #endif
121
+ `,
122
+ fs: /* glsl */ `
123
+ #ifdef DASH_MODE_PATH
124
+ uniform highp sampler2D lineDash_patterns;
125
+ flat in float lineDash_row;
126
+ flat in float lineDash_period;
127
+ flat in float lineDash_offset;
128
+ #endif
129
+ `,
130
+ inject: {
131
+ 'vs:#main-end': {
132
+ order: 1,
133
+ injection: /* glsl */ `
134
+ #ifdef DASH_MODE_PATH
135
+ // Deck has converted the period into path coordinates and LineBlurExtension has rescaled it.
136
+ lineDash_row = instanceDashArrays.y < 0.0 ? -instanceDashArrays.y - 1.0 : -1.0;
137
+ lineDash_period = pathStyle_dashArray.x;
138
+ lineDash_offset = lineDash_period > 0.0 ? mod(dashOffsetAndLength.x, lineDash_period) : 0.0;
139
+ #endif
140
+ `
141
+ },
142
+ 'fs:#main-start': {
143
+ order: 1,
144
+ injection: /* glsl */ `
145
+ #ifdef DASH_MODE_PATH
146
+ float lineDash_coverage = 1.0;
147
+ bool lineDash_discard = false;
148
+ bool lineDash_valid = lineDash_row >= 0.0 && lineDash_period > 0.0;
149
+ // Use the vertex phase on the geometry outside the segment's endpoints, including caps.
150
+ float lineDash_along = clamp(vDashSegment.x, 0.0, vDashSegment.y) + lineDash_offset;
151
+ float lineDash_filterWidth = max(fwidth(lineDash_along), 1e-4);
152
+ bool lineDash_round = path.capType > 0.5;
153
+ float lineDash_nearest = 0.0;
154
+ float lineDash_duty = 1.0;
155
+ float lineDash_subPixelBlend = 0.0;
156
+ if (lineDash_valid) {
157
+ int row = int(lineDash_row);
158
+ vec3 header = texelFetch(lineDash_patterns, ivec2(0, row), 0).xyz;
159
+ float scale = lineDash_period / header.y;
160
+ float position = mod(lineDash_along, lineDash_period);
161
+ float low = position - 0.5 * lineDash_filterWidth;
162
+ float high = position + 0.5 * lineDash_filterWidth;
163
+ float lowCycle = floor(low / lineDash_period);
164
+ float highCycle = floor(high / lineDash_period);
165
+ low = mod(low, lineDash_period);
166
+ high = mod(high, lineDash_period);
167
+ // F(x) counts complete periods plus the covered length inside the current period.
168
+ // Evaluate F(high) - F(low) in one loop, with the filter centered in the first period.
169
+ float covered = (highCycle - lowCycle) * header.z * scale;
170
+ bool inDash = false;
171
+ lineDash_nearest = lineDash_period;
172
+ float capSpan = 2.0 * sqrt(max(1.0 - vPathPosition.x * vPathPosition.x, 0.0));
173
+ float previousEnd = 0.0;
174
+ float capLength = 0.0;
175
+ for (int i = 0; i < ${MAX_DASH_INTERVALS}; i++) {
176
+ if (i >= int(header.x)) {
177
+ break;
178
+ }
179
+ vec4 pair = texelFetch(lineDash_patterns, ivec2(1 + i / 2, row), 0);
180
+ vec2 interval = (i % 2 == 0 ? pair.xy : pair.zw) * scale;
181
+ float intervalLength = interval.y - interval.x;
182
+ if (lineDash_round) {
183
+ // The nearest interval can be across the seam of the period, including a zero-length dot.
184
+ float forward = interval.x - position;
185
+ float backward = position - interval.y;
186
+ float distanceAlong = max(max(forward, backward), 0.0);
187
+ distanceAlong = min(distanceAlong, min(forward + lineDash_period, backward + lineDash_period));
188
+ lineDash_nearest = min(lineDash_nearest, distanceAlong);
189
+ capLength += min(interval.x - previousEnd, capSpan);
190
+ previousEnd = interval.y;
191
+ } else {
192
+ covered += clamp(high - interval.x, 0.0, intervalLength) -
193
+ clamp(low - interval.x, 0.0, intervalLength);
194
+ inDash = inDash || (intervalLength > 0.0 && position >= interval.x && position <= interval.y);
195
+ }
196
+ }
197
+ if (lineDash_round) {
198
+ capLength += min(max(lineDash_period - previousEnd, 0.0), capSpan);
199
+ lineDash_duty = clamp((header.z * scale + capLength) / lineDash_period, 0.0, 1.0);
200
+ } else if (bool(picking.isActive)) {
201
+ lineDash_discard = !inDash;
202
+ } else {
203
+ lineDash_coverage = clamp(covered / lineDash_filterWidth, 0.0, 1.0);
204
+ }
205
+ }
206
+
207
+ // Evaluate the derivative before PathLayer or a neighboring fragment can discard.
208
+ float lineDash_distance = length(vec2(lineDash_nearest, vPathPosition.x));
209
+ float lineDash_edgePixels = (1.0 - lineDash_distance) / max(fwidth(lineDash_distance), 1e-6);
210
+ if (lineDash_valid && lineDash_round) {
211
+ if (bool(picking.isActive)) {
212
+ lineDash_discard = lineDash_distance > 1.0;
213
+ } else {
214
+ lineDash_coverage = lineDash_nearest > 0.0 ? smoothedge(0.0, lineDash_edgePixels) : 1.0;
215
+ lineDash_subPixelBlend = smoothstep(lineDash_period, 2.0 * lineDash_period, lineDash_filterWidth);
216
+ }
217
+ }
218
+ #endif
219
+ `
220
+ },
221
+ 'fs:#main-end': {
222
+ order: 1,
223
+ injection: /* glsl */ `
224
+ #ifdef DASH_MODE_PATH
225
+ if (lineDash_valid) {
226
+ if (lineDash_round && !bool(picking.isActive)) {
227
+ #ifdef ANTIALIASING
228
+ // The resolved cap and stroke bound the same silhouette. Replace the stroke's coverage
229
+ // with their intersection while preserving the line's opacity and color.
230
+ float strokeCoverage = smoothedge(0.0, edgePixels);
231
+ #ifdef LINE_BLUR_ENABLED
232
+ strokeCoverage = lineBlur_fade;
233
+ #endif
234
+ if (strokeCoverage > 0.0) {
235
+ lineDash_coverage = min(strokeCoverage, lineDash_coverage) / strokeCoverage;
236
+ }
237
+ #endif
238
+ // Unresolved periods still scale the stroke by the dash duty cycle.
239
+ lineDash_coverage = mix(lineDash_coverage, lineDash_duty, lineDash_subPixelBlend);
240
+ }
241
+ if (lineDash_discard || lineDash_coverage <= 0.0) {
242
+ discard;
243
+ }
244
+ fragColor.a *= lineDash_coverage;
245
+ }
246
+ #endif
247
+ `
248
+ }
249
+ }
250
+ });
251
+
252
+ /**
253
+ * Draws every dash and gap of a `line-dasharray`, as MapLibre GL JS does, on the `PathLayer`s of
254
+ * a layer that also has `PathStyleExtension({dash: true, dashMode: 'path'})`, listed after it.
255
+ * `getDashArray` returns `[period, -(row + 1)]` (see `getDashPatternRow`): it takes no vertex
256
+ * attribute of its own, as a dashed path with offsets has none left. The negative gap turns
257
+ * deck.gl's own dash test off; the pattern's dashes come from a data texture shared by the
258
+ * device's layers. Dashes are box-filtered along the path, and end in semicircles with round
259
+ * caps, so a zero-length dash draws a dot. A gap of 0 or more is drawn by deck.gl as before. WebGL
260
+ * only: on WebGPU, `getDashArray` is replaced by the pattern's total dash and gap lengths.
261
+ */
262
+ export class LineDashExtension extends LayerExtension {
263
+ static extensionName = 'LineDashExtension';
264
+ static defaultProps = {
265
+ getDashArray: {type: 'accessor', value: [0, 0]}
266
+ };
267
+
268
+ /** Whether this layer can run the pattern shader. */
269
+ isEnabled(layer: Layer): boolean {
270
+ return layer.context.device.type === 'webgl' && 'pathTesselator' in (layer.state || {});
271
+ }
272
+
273
+ /** On WebGPU, forward the merged dash and gap to PathStyleExtension. */
274
+ getSubLayerProps(this: CompositeLayer, extension: this) {
275
+ const props: {
276
+ getDashArray?: Accessor<unknown, DashArray>;
277
+ updateTriggers: Record<string, unknown>;
278
+ } = LayerExtension.prototype.getSubLayerProps.call(this, extension);
279
+ const {getDashArray} = props;
280
+ if (this.context.device.type !== 'webgpu' || !getDashArray) {
281
+ return props;
282
+ }
283
+ const decoded: Accessor<unknown, DashArray> =
284
+ typeof getDashArray === 'function'
285
+ ? (object, info) => decodeDashArray(getDashArray(object, info))
286
+ : decodeDashArray(getDashArray);
287
+ return {...props, getDashArray: decoded};
288
+ }
289
+
290
+ /** Bind the current device atlas, including rows registered since the last draw. */
291
+ draw(this: Layer, params: unknown, extension: this) {
292
+ if (extension.isEnabled(this)) {
293
+ this.setShaderModuleProps({
294
+ lineDash: {lineDash_patterns: getPatternTexture(this.context.device)}
295
+ });
296
+ }
297
+ }
298
+
299
+ /** Install the ordered dash calculations on supported PathLayers. */
300
+ getShaders(this: Layer, extension: this) {
301
+ return extension.isEnabled(this) ? {plugins: [LINE_DASH_PLUGIN]} : {};
302
+ }
303
+ }
@@ -0,0 +1,191 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {LayerExtension} from '@deck.gl/core';
6
+ import type {CompositeLayer, Layer} from '@deck.gl/core';
7
+ import {createSegmentAttributeUpdate} from './line-metrics';
8
+ import {createShaderInjectionPlugin} from './shader-injection-plugin';
9
+ import {getCompiledStyleProperty} from './style-expression';
10
+
11
+ /** `geojson-vt`'s properties for a line's part in a tile, with `lineMetrics`. */
12
+ export const LINE_CLIP_START = 'geojsonvt_clip_start';
13
+ export const LINE_CLIP_END = 'geojsonvt_clip_end';
14
+
15
+ /** The ramp's width for an interpolated gradient, as MapLibre GL JS draws it. */
16
+ const RAMP_WIDTH = 256;
17
+ /**
18
+ * The ramp's width for a `step` gradient, drawn without filtering. MapLibre widens it with the
19
+ * longest line in the tile, up to the device's texture size; this width is that of a line about
20
+ * as long as the tile is wide, near the source's highest zoom.
21
+ */
22
+ const STEP_RAMP_WIDTH = 2048;
23
+
24
+ /** A `line-gradient` ramp, and the sampler parameters to draw it with. */
25
+ export type LineGradientRamp = {
26
+ image: ImageData | {data: Uint8ClampedArray; width: number; height: number};
27
+ textureParameters: Record<string, string>;
28
+ };
29
+
30
+ const rampCache = new WeakMap<object, {value: unknown; ramp: LineGradientRamp | null}>();
31
+
32
+ /**
33
+ * The `line-gradient` of a style layer as a one-row RGBA ramp, from `line-progress` 0 at its first
34
+ * pixel to 1 at its last, unpremultiplied, as MapLibre GL JS renders it (`renderColorRamp`). A
35
+ * `step` gradient is sampled with the nearest pixel, as MapLibre does, the others linearly. Null
36
+ * without a valid `line-gradient`. Cached per style layer while its value is unchanged.
37
+ */
38
+ export function getLineGradientRamp(styleLayer: {
39
+ paint?: Record<string, unknown>;
40
+ }): LineGradientRamp | null {
41
+ const value = styleLayer.paint?.['line-gradient'];
42
+ const cached = rampCache.get(styleLayer);
43
+ if (cached && cached.value === value) {
44
+ return cached.ramp;
45
+ }
46
+ const property =
47
+ value === undefined ? null : getCompiledStyleProperty(styleLayer, 'line-gradient');
48
+ let ramp: LineGradientRamp | null = null;
49
+ if (property) {
50
+ const step = Array.isArray(value) && value[0] === 'step';
51
+ const width = step ? STEP_RAMP_WIDTH : RAMP_WIDTH;
52
+ const data = new Uint8ClampedArray(width * 4);
53
+ for (let i = 0; i < width; i++) {
54
+ const color = property.evaluateWithGlobals({zoom: 0, lineProgress: i / (width - 1)}) as
55
+ | number[]
56
+ | null;
57
+ if (color) {
58
+ data.set([color[0], color[1], color[2], Math.round(color[3] * 255)], i * 4);
59
+ }
60
+ }
61
+ ramp = {
62
+ image:
63
+ typeof ImageData === 'undefined'
64
+ ? {data, width, height: 1}
65
+ : new ImageData(data, width, 1),
66
+ textureParameters: {
67
+ minFilter: step ? 'nearest' : 'linear',
68
+ magFilter: step ? 'nearest' : 'linear',
69
+ mipmapFilter: 'none'
70
+ }
71
+ };
72
+ }
73
+ rampCache.set(styleLayer, {value, ramp});
74
+ return ramp;
75
+ }
76
+
77
+ /** A tiled line's part of its whole line, `[start, end]`, from its `lineMetrics` properties. */
78
+ export function getLineClip(feature: {properties?: Record<string, unknown>}): [number, number] {
79
+ const properties = feature?.properties;
80
+ const start = Number(properties?.[LINE_CLIP_START]);
81
+ const end = Number(properties?.[LINE_CLIP_END]);
82
+ return Number.isFinite(start) && Number.isFinite(end) ? [start, end] : [0, 1];
83
+ }
84
+
85
+ const SHADER_MODULE_NAME = 'lineGradient';
86
+
87
+ const VS = `\
88
+ in vec2 instanceLineProgress;
89
+ out float lineGradient_progress;
90
+ `;
91
+
92
+ const FS = `\
93
+ uniform sampler2D lineGradient_texture;
94
+ in float lineGradient_progress;
95
+ `;
96
+
97
+ /**
98
+ * Adds `line-gradient` to the `PathLayer`s of a layer: each fragment takes the color of
99
+ * `lineGradientImage`, a ramp of `line-gradient` from progress 0 at its left edge to 1 at its
100
+ * right, at the fragment's `line-progress`, times the stroke's own color, as MapLibre GL JS
101
+ * multiplies the ramp by `line-opacity`. The stroke color should be white with the opacity.
102
+ *
103
+ * `getLineClip` gives a path's part of its whole line, `[start, end]` in 0 to 1, as geojson-vt
104
+ * records it for a source with `lineMetrics` (`geojsonvt_clip_start`, `geojsonvt_clip_end`). The
105
+ * progress runs from `start` to `end` along the path, by distance, as in MapLibre. WebGL only:
106
+ * on WebGPU the paths draw `getLineGradientFallbackColor`, the line-color.
107
+ */
108
+ export class LineGradientExtension extends LayerExtension {
109
+ static extensionName = 'LineGradientExtension';
110
+ static defaultProps = {
111
+ lineGradientImage: {type: 'image', value: null, async: true},
112
+ getLineClip: {type: 'accessor', value: [0, 1]},
113
+ getLineGradientFallbackColor: {type: 'accessor', value: [0, 0, 0, 255]}
114
+ };
115
+
116
+ isEnabled(layer: Layer): boolean {
117
+ return layer.context.device.type !== 'webgpu' && 'pathTesselator' in (layer.state || {});
118
+ }
119
+
120
+ initializeState(this: Layer, context: unknown, extension: this) {
121
+ if (!extension.isEnabled(this)) {
122
+ return;
123
+ }
124
+ const getProgress = (distance: number, length: number, [start, end]: number[]) =>
125
+ start + (end - start) * (length > 0 ? distance / length : 0);
126
+ this.getAttributeManager()?.addInstanced({
127
+ // The `line-progress` at each segment's start and end.
128
+ instanceLineProgress: {
129
+ size: 2,
130
+ accessor: ['getPath', 'getLineClip'],
131
+ update: createSegmentAttributeUpdate(({start, end, length}, object, objectInfo) => {
132
+ const clip = (this.props as any).getLineClip;
133
+ const lineClip = typeof clip === 'function' ? clip(object, objectInfo) : clip;
134
+ return [getProgress(start, length, lineClip), getProgress(end, length, lineClip)];
135
+ }),
136
+ noAlloc: false
137
+ }
138
+ });
139
+ }
140
+
141
+ /**
142
+ * On WebGPU, where the ramp shader does not run, the paths draw `getLineGradientFallbackColor`
143
+ * in place of the white stroke color that the ramp multiplies.
144
+ */
145
+ getSubLayerProps(this: CompositeLayer, extension: this): any {
146
+ const props = LayerExtension.prototype.getSubLayerProps.call(this, extension);
147
+ if (this.context.device.type !== 'webgpu') {
148
+ return props;
149
+ }
150
+ return {
151
+ ...props,
152
+ getColor: props.getLineGradientFallbackColor,
153
+ updateTriggers: {...props.updateTriggers, getColor: props.updateTriggers.getLineGradientFallbackColor}
154
+ };
155
+ }
156
+
157
+ draw(this: Layer<any>, params: unknown, extension: this) {
158
+ if (!extension.isEnabled(this) || !this.props.lineGradientImage) {
159
+ return;
160
+ }
161
+ this.setShaderModuleProps({
162
+ [SHADER_MODULE_NAME]: {lineGradient_texture: this.props.lineGradientImage}
163
+ });
164
+ }
165
+
166
+ getShaders(this: Layer, extension: this) {
167
+ if (!extension.isEnabled(this)) {
168
+ return {};
169
+ }
170
+ const plugin = createShaderInjectionPlugin({
171
+ name: SHADER_MODULE_NAME,
172
+ vs: VS,
173
+ fs: FS,
174
+ inject: {
175
+ // The progress at this vertex: along its segment, from the segment's start, as PathLayer
176
+ // measures `vPathPosition.y` in the segment's widths. Vertices of joins and caps lie
177
+ // before or after the segment: the ramp's edge pixels color them.
178
+ 'vs:#main-end': `
179
+ float lineGradient_along = vPathLength > 0.0 ? vPathPosition.y / vPathLength : 0.0;
180
+ lineGradient_progress = mix(instanceLineProgress.x, instanceLineProgress.y, lineGradient_along);
181
+ `,
182
+ 'fs:DECKGL_FILTER_COLOR': `
183
+ if (!bool(picking.isActive)) {
184
+ color *= texture(lineGradient_texture, vec2(lineGradient_progress, 0.5));
185
+ }
186
+ `
187
+ }
188
+ });
189
+ return {plugins: [plugin]};
190
+ }
191
+ }
@@ -0,0 +1,90 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {createIterable} from '@deck.gl/core';
6
+ import type {Attribute, Layer} from '@deck.gl/core';
7
+
8
+ /** The distances of one rendered segment of a path, in common units. */
9
+ export type SegmentDistances = {
10
+ /** From the start of the path to the segment's start. */
11
+ start: number;
12
+ /** From the start of the path to the segment's end. */
13
+ end: number;
14
+ /** The path's length. */
15
+ length: number;
16
+ };
17
+
18
+ /**
19
+ * An attribute `update` for a `PathLayer` that writes `size` values per rendered segment, from
20
+ * `getValues` given the segment's distances and its path's object. The distances are measured
21
+ * between the positions as deck.gl projects them, in the order the path runs, from 0 at each
22
+ * path's start: as MapLibre GL JS measures a line's distance from the start of the line within its
23
+ * tile. Padding and joint vertices get 0.
24
+ *
25
+ * WebGL2 guarantees 16 vertex attributes, and a `PathLayer` with dashes and offsets uses all of
26
+ * them: each value of a segment that a layer can compute on the CPU goes in one such attribute.
27
+ */
28
+ export function createSegmentAttributeUpdate(
29
+ getValues: (distances: SegmentDistances, object: any, objectInfo: any) => number[]
30
+ ) {
31
+ return function update(
32
+ this: Layer,
33
+ attribute: Attribute,
34
+ {startRow, endRow}: {startRow: number; endRow: number}
35
+ ): void {
36
+ const tesselator = (this.state as any)?.pathTesselator;
37
+ const vertexStarts = tesselator?.vertexStarts as number[] | undefined;
38
+ const positions = tesselator?.get?.('positions') as ArrayLike<number> | null | undefined;
39
+ const output = attribute.value as Float32Array;
40
+ const {size} = attribute;
41
+ if (!vertexStarts || !positions || typeof tesselator.getPathSegmentIndices !== 'function') {
42
+ return;
43
+ }
44
+ attribute.startIndices = vertexStarts;
45
+ const firstRow = Math.max(0, startRow);
46
+ const lastRow = Math.min(endRow, vertexStarts.length);
47
+ const first = vertexStarts[firstRow] ?? 0;
48
+ const last = vertexStarts[lastRow] ?? output.length / size;
49
+ output.fill(0, first * size, last * size);
50
+
51
+ const project = (index: number) =>
52
+ this.projectPosition(
53
+ [positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2] || 0],
54
+ {autoOffset: false}
55
+ );
56
+ const starts: number[] = [];
57
+ const ends: number[] = [];
58
+ const {iterable, objectInfo} = createIterable(this.props.data, firstRow, lastRow);
59
+ let row = firstRow;
60
+ for (const object of iterable) {
61
+ objectInfo.index++;
62
+ const segments: number[] = tesselator.getPathSegmentIndices(row++);
63
+ starts.length = 0;
64
+ ends.length = 0;
65
+ let distance = 0;
66
+ let previous = -2;
67
+ let previousEnd: number[] | null = null;
68
+ for (const segment of segments) {
69
+ const a = segment === previous + 1 && previousEnd ? previousEnd : project(segment);
70
+ const b = project(segment + 1);
71
+ starts.push(distance);
72
+ distance += Math.hypot(b[0] - a[0], b[1] - a[1], (b[2] || 0) - (a[2] || 0));
73
+ ends.push(distance);
74
+ previous = segment;
75
+ previousEnd = b;
76
+ }
77
+ segments.forEach((segment, index) => {
78
+ const values = getValues(
79
+ {start: starts[index], end: ends[index], length: distance},
80
+ object,
81
+ objectInfo
82
+ );
83
+ output.set(values, segment * size);
84
+ });
85
+ if (row >= lastRow) {
86
+ break;
87
+ }
88
+ }
89
+ };
90
+ }