@metoceanapi/wxtiles-common 0.0.7 → 0.0.10

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.
@@ -0,0 +1,305 @@
1
+ import { TileType } from "../utils/qtree";
2
+ import {
3
+ type CachedUriLoaderPromiseFunc,
4
+ type DataIntegral,
5
+ type DataIntegrals,
6
+ type DataPictures,
7
+ WXLOG,
8
+ type XYZ,
9
+ blurData,
10
+ cacheUriPromise,
11
+ loadDataIntegral,
12
+ uriXYZ,
13
+ } from "../utils/wxtools";
14
+ import type { WxBoundaryMeta, WxRequestInit, WxURIs, WxData, SLine} from "../types";
15
+ import {
16
+ applyMask,
17
+ makeBox,
18
+ splitCoords,
19
+ subData,
20
+ subDataDegree,
21
+ subMask,
22
+ } from "./loadertools";
23
+ import type { WxLayer } from "./wxlayer";
24
+ import type { BaseDatasetManager } from "../managers/BaseDatasetManager";
25
+
26
+ /**
27
+ * Class to load and preprocess data from PNG tiles.
28
+ * This class is used internally by {@link WxLayer}.
29
+ * Direct usage is not recommended.
30
+ */
31
+ export class Loader<WxDatasetManagerT extends BaseDatasetManager> {
32
+ /** Reference to the associated WxLayer */
33
+ protected readonly _layer: WxLayer<WxDatasetManagerT>;
34
+
35
+ /** Function to load, decode, and cache tile data from a URL */
36
+ protected readonly _loadDataFunc: CachedUriLoaderPromiseFunc<DataIntegral> =
37
+ cacheUriPromise(loadDataIntegral);
38
+
39
+ /**
40
+ * Constructor - Do not use directly.
41
+ * Use WxLayer methods to manage this loader.
42
+ */
43
+ constructor(layer: WxLayer<WxDatasetManagerT>) {
44
+ this._layer = layer;
45
+ }
46
+
47
+ /**
48
+ * Loads and preprocesses data for a single tile.
49
+ * @param tile - Tile coordinates (XYZ).
50
+ * @param requestInit - Optional HTTP request configuration.
51
+ * @returns A promise resolving to the processed tile data or `null` if the tile is invalid.
52
+ */
53
+ async load(tile: XYZ, requestInit?: WxRequestInit): Promise<WxData | null> {
54
+ const preloaded = await this.cacheLoad(
55
+ tile,
56
+ this._layer.tilesURIs,
57
+ requestInit,
58
+ );
59
+ if (!preloaded) return null; // tile is cut by boundaries or mask QTree
60
+ const { rawdata, subCoords, tileType } = preloaded;
61
+ const { units } = this._layer.currentVariableMeta;
62
+ const interpolator = units === "degree" ? subDataDegree : subData;
63
+ const processor = (d: DataIntegral) =>
64
+ interpolator(blurData(d, this._layer.style.blurRadius), subCoords);
65
+ const data = <DataPictures>rawdata.map(processor); // preprocess all loaded data
66
+ this._vectorMagnitudesPrepare(data); // if vector data, prepare magnitudes
67
+ await this._applyMask(
68
+ data,
69
+ tile,
70
+ tileType,
71
+ !subCoords && rawdata.length === 1,
72
+ ); // apply mask if needed
73
+ return { data, slines: this._createStreamLines(data) };
74
+ }
75
+
76
+ /**
77
+ * Loads tile data from the cache or API, ensuring validity against boundaries and masks.
78
+ * @param tile - Tile coordinates (XYZ).
79
+ * @param uris - URIs used to construct tile URLs.
80
+ * @param requestInit - Optional HTTP request configuration.
81
+ * @returns A promise resolving to raw tile data or `null` if the tile is invalid.
82
+ */
83
+ async cacheLoad(
84
+ tile: XYZ,
85
+ uris: WxURIs,
86
+ requestInit?: WxRequestInit,
87
+ ): Promise<{
88
+ rawdata: DataIntegrals;
89
+ subCoords?: XYZ | undefined;
90
+ tileType: TileType;
91
+ } | null> {
92
+ if (!this._checkInsideBoundaries(tile)) return null; // tile is cut by boundaries
93
+
94
+ const tileType = this._checkTypeAndMask(tile);
95
+ if (!tileType) return null; // tile is cut by mask
96
+
97
+ const { upCoords, subCoords } = splitCoords(
98
+ tile,
99
+ this._layer.getCoarseMaxZoom(),
100
+ );
101
+ const URLs = <WxURIs>uris.map((uri) => uriXYZ(uri, upCoords));
102
+ const requestInitCopy = Object.assign(
103
+ {},
104
+ this._layer.wxdatasetManager.wxAPI.requestInit,
105
+ { signal: requestInit?.signal },
106
+ ); // make initCopy, copy only signal
107
+ const rawdata = <DataIntegrals>(
108
+ await Promise.all(
109
+ URLs.map((url: string) => this._loadDataFunc(url, requestInitCopy)),
110
+ )
111
+ );
112
+ return { rawdata, subCoords, tileType };
113
+ // we don't need to process data, as it's for cache preloading only
114
+ }
115
+
116
+ /** Clear cache */
117
+ clearCache(): void {
118
+ this._loadDataFunc.clearCache();
119
+ }
120
+
121
+ /**
122
+ * Applies a mask to the tile data based on the tile type and masking style.
123
+ * @param data - The processed tile data.
124
+ * @param tile - The tile coordinates (XYZ).
125
+ * @param tileType - Type of the tile (e.g., mixed, land, sea).
126
+ * @param needCopy - Whether to create a data copy before masking.
127
+ * @returns A promise resolving once the mask has been applied.
128
+ */
129
+ protected async _applyMask(
130
+ data: DataPictures,
131
+ tile: XYZ,
132
+ tileType: TileType,
133
+ needCopy: boolean,
134
+ ): Promise<void> {
135
+ const { style } = this._layer;
136
+ if (
137
+ (style.mask === "land" || style.mask === "sea") &&
138
+ tileType === TileType.Mixed
139
+ ) {
140
+ if (needCopy) {
141
+ // !!make a copy before masking!! or original data will be spoiled
142
+ // needCopy is false if this is a subTile (already copied from parent)
143
+ const { raw: inRaw, dmin, dmax, dmul } = data[0];
144
+ data[0] = { raw: new Uint16Array(inRaw), dmin, dmax, dmul };
145
+ }
146
+
147
+ let maskImage: ImageData;
148
+ const { wxAPI } = this._layer.wxdatasetManager;
149
+ try {
150
+ const { upCoords, subCoords } = splitCoords(tile, wxAPI.maskDepth);
151
+ maskImage = await wxAPI.loadMaskFunc(upCoords);
152
+ maskImage = subMask(maskImage, subCoords, wxAPI.maskChannel);
153
+ } catch (e) {
154
+ style.mask = undefined;
155
+ WXLOG("Can't load Mask. Masking is disabled");
156
+ return;
157
+ }
158
+
159
+ applyMask(data[0], maskImage, wxAPI.maskChannel, style.mask);
160
+ }
161
+ }
162
+
163
+ /** @no_this @ignore */
164
+ protected _vectorMagnitudesPrepare(data: DataPictures): void {
165
+ if (data.length === 1) return; // no need to process
166
+ data.unshift({
167
+ raw: new Uint16Array(258 * 258),
168
+ dmin: 0,
169
+ dmax: 0,
170
+ dmul: 0,
171
+ });
172
+ const [l, u, v] = data; // length, u, v components
173
+ l.dmax = 1.42 * Math.max(-u.dmin, u.dmax, -v.dmin, v.dmax);
174
+ l.dmul = (l.dmax - l.dmin) / 65535;
175
+ for (let i = 0; i < 258 * 258; ++i) {
176
+ if (!u.raw[i] || !v.raw[i]) {
177
+ // l.raw[i] = 0; // by default it's 0
178
+ continue;
179
+ } // NODATA
180
+ const _u = u.dmin + u.dmul * u.raw[i]; // unpack U data
181
+ const _v = v.dmin + v.dmul * v.raw[i]; // unpack V data
182
+ l.raw[i] = Math.sqrt(_v * _v + _u * _u) / l.dmul; // pack data back to use the original rendering approach
183
+ }
184
+ }
185
+
186
+ /** @ignore */
187
+ protected _checkTypeAndMask(coords: XYZ): TileType | undefined {
188
+ const { mask } = this._layer.style;
189
+ if (mask === "land" || mask === "sea") {
190
+ const tileType = this._layer.wxdatasetManager.wxAPI.qtree.check(coords); // check 'type' of the tile
191
+ return mask === tileType ? undefined /* cut by QTree */ : tileType;
192
+ }
193
+
194
+ return TileType.Mixed;
195
+ }
196
+
197
+ /** @ignore */
198
+ protected _checkInsideBoundaries(coords: XYZ): boolean {
199
+ const boundaries = this._layer.getBoundaries();
200
+ if (boundaries?.boundaries180) {
201
+ const bbox = makeBox(coords);
202
+ const rectIntersect = (b: WxBoundaryMeta) =>
203
+ !(
204
+ bbox.west > b.east ||
205
+ b.west > bbox.east ||
206
+ bbox.south > b.north ||
207
+ b.south > bbox.north
208
+ );
209
+ if (!boundaries.boundaries180.some(rectIntersect)) {
210
+ return false; // cut by boundaries
211
+ }
212
+ }
213
+
214
+ return true;
215
+ }
216
+
217
+ /** @ignore */
218
+ protected _createStreamLines(data: DataPictures): SLine[] {
219
+ if (data.length !== 3) return [];
220
+ const { style } = this._layer;
221
+ if (style.streamLineColor === "none") return [];
222
+ const streamLines: SLine[] = []; // an array of stremllines. Each section of streamline represents a position and size of a particle.
223
+
224
+ // idea is taken from the LIC (linear integral convolution) algorithm and the 'multipartical vector field visualisation'
225
+ // Having the stream lines as precalculated trajectories makes an animation more predictable and (IMHO) representative.
226
+ // Algorithm: use U and V as an increment to build a trajectory. To make trajectory more or less correct the algo
227
+ // does 20 moc steps and stores the point into streamline (sLine).
228
+ // Algo does two passes: forward and backward, to cope boundaries and improve visual effect.
229
+ const [l, u, v] = data;
230
+ const factor = (style.streamLineSpeedFactor || 1) / l.dmax;
231
+ const addDegrees = style.addDegrees
232
+ ? 0.017453292519943 * style.addDegrees
233
+ : 0;
234
+ const gridStep = style.streamLineGridStep || 64;
235
+ const steps = style.streamLineSteps || 300;
236
+ for (let y = 0; y <= 256; y += gridStep) {
237
+ for (let x = 0; x <= 256; x += gridStep) {
238
+ if (!l.raw[1 + x + (1 + y) * 258]) continue; // NODATA
239
+ const sLine: SLine = []; // streamline
240
+ let xforw = x;
241
+ let yforw = y;
242
+ let oldDi = -1; // previous di. The first di will never be -1
243
+ let dx = 0;
244
+ let dy = 0;
245
+ for (
246
+ let i = 0;
247
+ i <= steps &&
248
+ xforw >= 0 &&
249
+ xforw <= 256 &&
250
+ yforw >= 0 &&
251
+ yforw <= 256;
252
+ i++
253
+ ) {
254
+ // forward
255
+ if (!(i % (steps / 10))) sLine.push({ x: ~~xforw, y: ~~yforw }); // push each (steps/10)-th point // 7 points max
256
+ const di = ~~xforw + 1 + (~~yforw + 1) * 258;
257
+ if (di !== oldDi) {
258
+ // calc dx, dy only if di changed
259
+ if (!l.raw[di]) break; // NODATA - stop streamline creation
260
+ oldDi = di; // save old di
261
+ const dl = l.dmin + l.raw[di] * l.dmul;
262
+ const du = u.dmin + u.raw[di] * u.dmul;
263
+ const dv = v.dmin + v.raw[di] * v.dmul;
264
+ const ang = Math.atan2(du, dv) + addDegrees;
265
+ dx = factor * dl * Math.sin(ang);
266
+ dy = factor * dl * Math.cos(ang);
267
+ }
268
+ xforw += dx;
269
+ yforw -= dy; // negative - due to Lat goes up but screen's coordinates go down
270
+ } // for i forward
271
+ let xback = x;
272
+ let yback = y;
273
+ oldDi = -1; // previous di. The first di will never be -1
274
+ for (
275
+ let i = 1;
276
+ i <= steps &&
277
+ xback >= 0 &&
278
+ xback <= 256 &&
279
+ yback >= 0 &&
280
+ yback <= 256;
281
+ i++
282
+ ) {
283
+ // backward // i = 1 because otherwise it produces the same first point hence visual artefact! 2 hours debugging!
284
+ if (!(i % (steps / 10))) sLine.unshift({ x: ~~xback, y: ~~yback }); // push each (steps/10)-th point // 6 points max
285
+ const di = ~~xback + 1 + (~~yback + 1) * 258;
286
+ if (di !== oldDi) {
287
+ // calc dx, dy only if di changed
288
+ if (!l.raw[di]) break; // NODATA - stop streamline creation
289
+ oldDi = di; // save old di
290
+ const dl = l.dmin + l.raw[di] * l.dmul;
291
+ const du = u.dmin + u.raw[di] * u.dmul;
292
+ const dv = v.dmin + v.raw[di] * v.dmul;
293
+ const ang = Math.atan2(du, dv) + addDegrees;
294
+ dx = factor * dl * Math.sin(ang);
295
+ dy = factor * dl * Math.cos(ang);
296
+ }
297
+ xback -= dx;
298
+ yback += dy; // positive - due to Lat goes up but screen's coordinates go down
299
+ } // for i backward
300
+ sLine.length > 2 && streamLines.push(sLine);
301
+ } // for x
302
+ } // for y
303
+ return streamLines;
304
+ } // _createSLines
305
+ }
@@ -0,0 +1,376 @@
1
+ import { PixelsToLonLat, coordToPixel } from "../utils/mercator";
2
+ import type { DataPicture, XYZ } from "../utils/wxtools";
3
+ import type { WxBoundaryMeta } from "../types";
4
+
5
+ /**
6
+ * Convert a degree to a value on a linear scale, wrapping around at 360 degrees.
7
+ * @param start - The starting angle in degrees.
8
+ * @param end - The ending angle in degrees.
9
+ * @param amount - The interpolation amount between the start and end.
10
+ * @returns The interpolated angle, wrapped to the [0, 360) degree range.
11
+ */
12
+ function interpolatorDegreeLinear(
13
+ start: number,
14
+ end: number,
15
+ amount: number,
16
+ ): number {
17
+ const shortestAngle = ((((end - start) % 360) + 540) % 360) - 180;
18
+ return (start + shortestAngle * amount + 360) % 360;
19
+ }
20
+
21
+ type InterpolatorSquare = (
22
+ a: number,
23
+ b: number,
24
+ c: number,
25
+ d: number,
26
+ dxt: number,
27
+ dyt: number,
28
+ dmin: number,
29
+ dmul: number,
30
+ ) => number;
31
+
32
+ /**
33
+ * Interpolator function for square-based bilinear interpolation.
34
+ * This function calculates the interpolated value based on the corners of the square.
35
+ * The interpolation is applied within a 2D grid of values.
36
+ *
37
+ * @param a - Value at the top-left corner of the square.
38
+ * @param b - Value at the top-right corner of the square.
39
+ * @param c - Value at the bottom-left corner of the square.
40
+ * @param d - Value at the bottom-right corner of the square.
41
+ * @param dxt - Interpolation coefficient in the x-direction.
42
+ * @param dyt - Interpolation coefficient in the y-direction.
43
+ * @param dmin - Minimum data value.
44
+ * @param dmul - Multiplication factor for scaling.
45
+ * @returns The interpolated value within the square.
46
+ */
47
+ function interpolatorSquareDegree(
48
+ a: number,
49
+ b: number,
50
+ c: number,
51
+ d: number,
52
+ dxt: number,
53
+ dyt: number,
54
+ dmin: number,
55
+ dmul: number,
56
+ ): number {
57
+ // a----b
58
+ // | |
59
+ // | |
60
+ // c----d
61
+
62
+ // 16 possible variants for a,b,c,d != 0 ( != NaN)
63
+ const sq = (a ? 1 : 0) | (b ? 2 : 0) | (c ? 4 : 0) | (d ? 8 : 0);
64
+ switch (sq) {
65
+ case 0b0000:
66
+ return 0; // NaN
67
+ case 0b0001: // only a != NaN
68
+ return a;
69
+ case 0b0010: // only b != NaN
70
+ return b;
71
+ case 0b0011: // a, b != NaN
72
+ c = a;
73
+ d = b;
74
+ break;
75
+ case 0b0100: // ... etc
76
+ return c;
77
+ case 0b0101:
78
+ b = a;
79
+ d = c;
80
+ break;
81
+ case 0b0110:
82
+ d = (b + c) >> 1;
83
+ a = d;
84
+ break;
85
+ case 0b0111:
86
+ d = (b + c) >> 1;
87
+ break;
88
+ case 0b1000:
89
+ return d;
90
+ case 0b1001:
91
+ b = (a + d) >> 1;
92
+ c = b;
93
+ break;
94
+ case 0b1010:
95
+ a = b;
96
+ c = d;
97
+ break;
98
+ case 0b1011:
99
+ c = (a + d) >> 1;
100
+ break;
101
+ case 0b1100:
102
+ a = c;
103
+ b = d;
104
+ break;
105
+ case 0b1101:
106
+ b = (a + d) >> 1;
107
+ break;
108
+ case 0b1110:
109
+ a = (b + c) >> 1;
110
+ break;
111
+ }
112
+
113
+ // decode Data
114
+ a = dmin + dmul * a;
115
+ b = dmin + dmul * b;
116
+ c = dmin + dmul * c;
117
+ d = dmin + dmul * d;
118
+
119
+ // 2) bilinear
120
+ const u = interpolatorDegreeLinear(a, b, dxt); // upper line
121
+ const l = interpolatorDegreeLinear(c, d, dxt); // lower line
122
+ // Encode Data back before returning
123
+ const ul = (interpolatorDegreeLinear(u, l, dyt) - dmin) / dmul;
124
+ if (ul < 1) return 1; // As 0 is NaN, we don't need NaN here! so return 1 instead of NaN
125
+ return ul;
126
+ }
127
+
128
+ /**
129
+ * Interpolator function for square-based interpolation.
130
+ * This function calculates the interpolated value within a square grid.
131
+ *
132
+ * @param a - Value at the top-left corner of the square.
133
+ * @param b - Value at the top-right corner of the square.
134
+ * @param c - Value at the bottom-left corner of the square.
135
+ * @param d - Value at the bottom-right corner of the square.
136
+ * @param dxt - Interpolation coefficient in the x-direction.
137
+ * @param dyt - Interpolation coefficient in the y-direction.
138
+ * @param dmin - Minimum data value.
139
+ * @param dmul - Multiplication factor for scaling.
140
+ * @returns The interpolated value within the square.
141
+ */
142
+ function interpolatorSquare(
143
+ a: number,
144
+ b: number,
145
+ c: number,
146
+ d: number,
147
+ dxt: number,
148
+ dyt: number,
149
+ dmin: number,
150
+ dmul: number,
151
+ ): number {
152
+ // 0 1
153
+ // a --- b default version a --- b flipped version
154
+ // | / | | \ |
155
+ // | / x | - pyt | \ |
156
+ // c --- d c --- d
157
+ // 2 | 3
158
+ // pxt
159
+ //
160
+ // x - point to interpolate
161
+ // a, b, c, d - corners of the square
162
+ // 16 possible variants for a,b,c,d != 0 ( != NaN)
163
+ const sq = (a ? 1 : 0) | (b ? 2 : 0) | (c ? 4 : 0) | (d ? 8 : 0);
164
+ switch (sq) {
165
+ case 0b0111: // -cba -default version
166
+ return dxt + dyt < 1 ? dxt * (b - a) + dyt * (c - a) + a : 0;
167
+ case 0b1110: // dcb- -default version
168
+ return dxt + dyt < 1 ? 0 : dxt * (d - c) + dyt * (d - b) + b + c - d;
169
+ case 0b1011: // d-ba - flipped version
170
+ return dyt < dxt ? (1 - dxt) * (a - b) + dyt * (d - b) + b : 0;
171
+ case 0b1101: // dc-a - flipped version
172
+ return dyt < dxt ? 0 : (1 - dxt) * (c - d) + dyt * (c - a) + a + d - c;
173
+ case 0b1111: // dcba - default version
174
+ return dxt + dyt < 1
175
+ ? dxt * (b - a) + dyt * (c - a) + a
176
+ : dxt * (d - c) + dyt * (d - b) + b + c - d;
177
+ default:
178
+ return 0;
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Subdivide a data picture using a specified interpolation method.
184
+ * The interpolation is performed to extract a sub-region (subtile) from a larger data picture.
185
+ *
186
+ * @param interpolator - The interpolation function to use.
187
+ * @param inputData - The input data picture from which to extract the subtile.
188
+ * @param subCoords - The coordinates of the subtile within the grid.
189
+ * @returns The subdivided data picture containing the interpolated subtile.
190
+ */
191
+ function subDataPicture(
192
+ interpolator: InterpolatorSquare,
193
+ inputData: DataPicture,
194
+ subCoords: XYZ,
195
+ ): DataPicture {
196
+ const subTileSize = 1 / 2 ** subCoords.z; // a size of a subtile
197
+ const subTileStartX = subCoords.x * 256 * subTileSize - 0.5; // upper left point of a subtile Shifted by 0.5 to get the center of the pixel
198
+ const subTileStartY = subCoords.y * 256 * subTileSize - 0.5;
199
+ const { raw: inRaw, dmin, dmax, dmul } = inputData;
200
+ const subData: DataPicture = {
201
+ raw: new Uint16Array(258 * 258),
202
+ dmin,
203
+ dmax,
204
+ dmul,
205
+ };
206
+ const { raw: outRaw } = subData;
207
+ for (
208
+ let outY = -1,
209
+ outIndex = 0,
210
+ inYf = subTileStartY - subTileSize + 1 /*+1 to shift index */;
211
+ outY <= 256;
212
+ outY++, inYf += subTileSize
213
+ ) {
214
+ const inYi = Math.floor(inYf); // don't use `~~` because of negatives on left and upper borders
215
+ const yt = inYf - inYi; // [0, 1] - `y` interpolati`on coeff
216
+ const inYi258 = inYi * 258;
217
+ for (
218
+ let outX = -1,
219
+ inXf = subTileStartX - subTileSize + 1 /*+1 to shift index */;
220
+ outX <= 256;
221
+ outX++, outIndex++, inXf += subTileSize
222
+ ) {
223
+ const inXi = Math.floor(inXf); // don't use ~~ because of negatives
224
+ const xt = inXf - inXi;
225
+ const inIndex = inXi + inYi258; // data index
226
+ // interpolation inside a rectangular
227
+ const a = inRaw[inIndex]; // upper left corner
228
+ const b = inRaw[inIndex + 1]; // upper right
229
+ const c = inRaw[inIndex + 258]; // lower left
230
+ const d = inRaw[inIndex + 258 + 1]; // lower right
231
+ outRaw[outIndex] = interpolator(a, b, c, d, xt, yt, dmin, dmul);
232
+ } // for x
233
+ } // for y
234
+
235
+ return subData;
236
+ }
237
+
238
+ /**
239
+ * Get sub-tile of a mask via baricemrtric interpolation
240
+ * @param {ImageData} inputData - input data
241
+ * @param {XYZ | undefined} subCoords - subtile coordinates
242
+ * @returns {ImageData} subtile data
243
+ * */
244
+ export function subMask(
245
+ inputData: ImageData,
246
+ subCoords: XYZ | undefined,
247
+ channel: number,
248
+ ): ImageData {
249
+ if (!subCoords) return inputData;
250
+
251
+ const clamp = (v: number) => (v < 0 ? 0 : v > 254 ? 254 : v);
252
+ const subTileSize = 1 / 2 ** subCoords.z; // a size of a subtile
253
+ const subTileStartX = subCoords.x * 256 * subTileSize - 0.5; // upper left point of a subtile Shifted by 0.5 to get the center of the pixel
254
+ const subTileStartY = subCoords.y * 256 * subTileSize - 0.5;
255
+ const { data: inData } = inputData;
256
+ const subData: ImageData = new ImageData(256, 256);
257
+ const { data: outData } = subData;
258
+ for (
259
+ let outY = 0, outIndex = channel, inYf = subTileStartY;
260
+ outY < 256;
261
+ outY++, inYf += subTileSize
262
+ ) {
263
+ const inYi = ~~clamp(inYf);
264
+ const yt = inYf - inYi; // [0, 1] - `y` interpolation coeff
265
+ const inYi256 = inYi * 256;
266
+ for (
267
+ let outX = 0, inXf = subTileStartX;
268
+ outX < 256;
269
+ outX++, outIndex += 4, inXf += subTileSize
270
+ ) {
271
+ const inXi = ~~clamp(inXf);
272
+ const xt = inXf - inXi;
273
+ const inIndex = (inXi + inYi256) * 4 + channel; // data index to pixel/channel used as a mask
274
+ // interpolation inside a rectangular
275
+ const a = inData[inIndex]; // upper left corner
276
+ const b = inData[inIndex + 4]; // upper right
277
+ const c = inData[inIndex + 4 * 256]; // lower left
278
+ const d = inData[inIndex + 4 * 256 + 4]; // lower right
279
+ const r = interpolatorSquare(a, b, c, d, xt, yt, 0, 0);
280
+ // const r = xt + yt < 1 ? xt * (b - a) + yt * (c - a) + a : xt * (d - c) + yt * (d - b) + b + c - d; // barycentric interpolation
281
+ outData[outIndex] = r > 127 ? 255 : 0;
282
+ } // for x
283
+ } // for y
284
+
285
+ return subData;
286
+ }
287
+
288
+ /**
289
+ * Get sub-tile of a regular data via baricemrtric interpolation
290
+ * @param {DataPicture} inputData - input data
291
+ * @param {XYZ | undefined} subCoords - subtile coordinates
292
+ * @returns {DataPicture} subtile data
293
+ * */
294
+ export function subData(inputData: DataPicture, subCoords?: XYZ): DataPicture {
295
+ if (!subCoords) return inputData;
296
+ return subDataPicture(interpolatorSquare, inputData, subCoords);
297
+ }
298
+
299
+ /**
300
+ * Get sub-tile of a degree data tile via bilinear degree interpolation, so middle of 350..10 degree is 0 degree.
301
+ * @param {DataPicture} inputData - input data
302
+ * @param {XYZ | undefined} subCoords - subtile coordinates
303
+ * @returns {DataPicture} subtile data
304
+ * */
305
+ export function subDataDegree(
306
+ inputData: DataPicture,
307
+ subCoords?: XYZ,
308
+ ): DataPicture {
309
+ if (!subCoords) return inputData;
310
+ return subDataPicture(interpolatorSquareDegree, inputData, subCoords);
311
+ }
312
+
313
+ /**
314
+ * Upply sea/land mask to a data tile
315
+ * 0 - for the masks from Sarah (current), 3 - for the masks from Mapbox
316
+ * @param {DataPicture} dataIn - data tile
317
+ * @param {ImageData} mask - sea/land mask
318
+ * @param {number} mc - mask channel of the mask picture to use (0 - Red, 1 - Green, 2 - Blue, 3 - Alpha)
319
+ * @param {'sea' | 'land'} maskType - sea or land masking to apply
320
+ * @returns {DataPicture} - masked data tile
321
+ * */
322
+ export function applyMask(
323
+ dataIn: DataPicture,
324
+ { data }: ImageData,
325
+ mc: number,
326
+ maskType: "land" | "sea",
327
+ ): DataPicture {
328
+ const sea = maskType === "sea";
329
+ const { raw } = dataIn;
330
+ for (let i = mc, j = 259, y = 0; y < 256; j += 2, y++) {
331
+ for (let x = 0; x < 256; x++, j++, i += 4) {
332
+ if (sea === !data[i]) {
333
+ raw[j] = 0; // Perform assignment clearly in the if block
334
+ }
335
+ }
336
+ }
337
+
338
+ return dataIn;
339
+ }
340
+
341
+ /**
342
+ * Create a bounding box for a tile
343
+ * @param coords - tile coordinates
344
+ * @returns {WxBoundaryMeta} [minLon, minLat, maxLon, maxLat]
345
+ * */
346
+ export function makeBox(coords: XYZ): WxBoundaryMeta {
347
+ const [px, py] = coordToPixel(coords.x, coords.y);
348
+ const [west, north] = PixelsToLonLat(px, py, coords.z);
349
+ const [east, south] = PixelsToLonLat(px + 256, py + 256, coords.z);
350
+ return { west, north, east, south };
351
+ }
352
+
353
+ /**
354
+ * Splits tile coordinates into a tile coords at maximum zoom and a subtile coords.
355
+ * If the tile is below maximum zoom, the subtile coords are undefined.
356
+ * @param coords - tile coordinates
357
+ * @param maxZoom - maximum zoom
358
+ * @returns [tile coords, subtile coords (or undefined)]
359
+ * */
360
+ export function splitCoords(
361
+ coords: XYZ,
362
+ maxZoom: number,
363
+ ): { upCoords: XYZ; subCoords?: XYZ } {
364
+ const zDif = coords.z - maxZoom;
365
+ if (zDif <= 0) {
366
+ return { upCoords: coords };
367
+ }
368
+
369
+ const upCoords = { x: coords.x >>> zDif, y: coords.y >>> zDif, z: maxZoom };
370
+ const subCoords = {
371
+ x: coords.x & ((1 << zDif) - 1),
372
+ y: coords.y & ((1 << zDif) - 1),
373
+ z: zDif,
374
+ };
375
+ return { upCoords, subCoords };
376
+ }