@metoceanapi/wxtiles-common 0.0.6 → 0.0.7

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,1099 @@
1
+ import { __colorSchemes_default_preset } from "../defaults/colorschemes";
2
+ import { __colorStyles_default_preset } from "../defaults/styles";
3
+ import { __units_default_preset } from "../defaults/uconv";
4
+
5
+ /** x,y,z */
6
+ export interface XYZ {
7
+ x: number;
8
+ y: number;
9
+ z: number;
10
+ }
11
+
12
+ /** type for unit converter */
13
+ export type WxUnitTuple = [string, number, number?];
14
+
15
+ /** Type of an Object with all unit convertion tupels */
16
+ export interface WxUnits {
17
+ [unit: string]: WxUnitTuple | undefined;
18
+ }
19
+
20
+ /**
21
+ * Type of an Object with all color schemes,
22
+ * each color scheme is an array of colors evenly distributed between min and max values in a {@link WxLegend} and {@link RawCLUT}*/
23
+ export interface WxColorSchemes {
24
+ [name: string]: string[] | undefined;
25
+ }
26
+
27
+ /** A [level,color] tuple */
28
+ export type colorMapTuple = [number, string];
29
+
30
+ /** Weak color style (may not have all fields of {@link WxColorStyleStrict}) */
31
+ export interface WxColorStyleWeak extends Partial<WxColorStyleStrict> {}
32
+
33
+ /** interface of an object with all mixed color styles */
34
+ export interface WxColorStylesWeakMixed {
35
+ [name: string]: WxColorStyleWeak | WxColorStyleWeak[] | undefined;
36
+ }
37
+
38
+ /** interface of an object with all weak color styles */
39
+ export interface ColorStylesIncomplete {
40
+ [name: string]: WxColorStyleWeak | undefined;
41
+ }
42
+
43
+ /** Strict style interface */
44
+ export interface WxColorStyleStrict {
45
+ /** Name of the style */
46
+ name: string;
47
+
48
+ /** Name of a parent style to inherit from */
49
+ parent?: string;
50
+
51
+ /** Tile filling schema.
52
+ * - **'none'** means no fill, leave the tile transparent
53
+ * - **'solid'** means solid fill, no gradient between levels.
54
+ * - **'gradient'** means gradient fill.
55
+ * */
56
+ fill: "none" | "gradient" | "solid";
57
+
58
+ /**
59
+ * Color of isolines.
60
+ * - **'none'** do not render.
61
+ * - **'fill'** using value of {@link fill} in each pixel.
62
+ * - **'inverted'** using *inverted* value of {@link fill} in each pixel.
63
+ * - **'#RGB'** or '**#RRGGBB**' or '**#RRGGBBAA**' - using this WEB-color.
64
+ * */
65
+ isolineColor: "none" | "inverted" | "fill" | `#${string}`;
66
+
67
+ /** if true then render isoline text values */
68
+ isolineText: boolean;
69
+
70
+ /** Font size of isoline text values in ems */
71
+ isolineTextSizeEm: number;
72
+
73
+ /** if true then render a solid background behind isoline text values */
74
+ isolineTextBackground: boolean;
75
+
76
+ /**
77
+ * Representation of the wind/current field.
78
+ * - **'none'** do not render vectors.
79
+ * - **'arrows'** use arrows to represent winds/currents.
80
+ * - **'barbs'** use barbs.
81
+ * */
82
+ vectorType: "none" | "arrows" | "barbs";
83
+
84
+ /**
85
+ * Color of vectors.
86
+ * - **'none'** do not render vectors.
87
+ * - **'fill'** using value of {@link fill} in each pixel.
88
+ * - **'inverted'** using *inverted* value of {@link fill} in each pixel.
89
+ * - **'#RGB'** or '**#RRGGBB**' or '**#RRGGBBAA**' - using this WEB-color.
90
+ * */
91
+ vectorColor: "none" | "inverted" | "fill" | `#${string}`;
92
+
93
+ /** Factor for vectors length */
94
+ vectorFactor: number;
95
+
96
+ /**
97
+ * Draw streamlines:
98
+ * - **'none'** means no streamlines.
99
+ * - **'fill'** using value of {@link fill} in each pixel.
100
+ * - **'inverted'** using *inverted* value of {@link fill} in each pixel.
101
+ * - **'#RGB'** or '**#RRGGBB**' or '**#RRGGBBAA**' - using this WEB-color.
102
+ * */
103
+ streamLineColor: "none" | "inverted" | "fill" | `#${string}`;
104
+
105
+ /** factor to scale streamlines length */
106
+ streamLineSpeedFactor: number;
107
+
108
+ /**
109
+ * Step to seed streamlines. Streamlines spread both ways from seed point.
110
+ * less value means more streamlines.
111
+ * */
112
+ streamLineGridStep?: number;
113
+
114
+ /** steps in each streamline */
115
+ streamLineSteps?: number;
116
+
117
+ /**
118
+ * - if true then render streamlines as static lines.
119
+ * - if false then render streamlines as animated lines.
120
+ * */
121
+ streamLineStatic: boolean;
122
+
123
+ /** If true then fill values below style's minimum. */
124
+ showBelowMin: boolean;
125
+
126
+ /** If true then fill values above style's maximum. */
127
+ showAboveMax: boolean;
128
+
129
+ /** Color scheme name from the default set. May be extended in {@link WxAPI}*/
130
+ colorScheme: string;
131
+
132
+ /** Used if presented instead of colorScheme */
133
+ colors?: string[];
134
+
135
+ /**
136
+ * Used if presented instead of levels, colors, colorScheme.
137
+ * Array of [level,color] tuples. Colors are WEB-colors.
138
+ */
139
+ colorMap?: [number, string][];
140
+
141
+ /** Levels to build legend. Used if presented, otherwise 10 levels are calculated evenly on given data */
142
+ levels?: number[];
143
+
144
+ /** radius for the BOX filter */
145
+ blurRadius: number;
146
+
147
+ /** Additional rotation of all wind or current's vectors or directions by angle in degrees.*/
148
+ addDegrees: number;
149
+
150
+ /** Units of the style (from the default set)*/
151
+ units: string;
152
+
153
+ /**
154
+ * Additional extend of default {@link units}.
155
+ * @see {@link WxUnits}
156
+ * */
157
+ extraUnits?: WxUnits;
158
+
159
+ /**
160
+ * masking:
161
+ * - **'none'** - no masking.
162
+ * - **'sea'** - make sea transparent.
163
+ * - **'land'** - make land transparent.
164
+ * */
165
+ mask?: "land" | "sea" | "none";
166
+
167
+ /** If exists then try to use WebGL to render tiles */
168
+ gl?: {
169
+ animationSpeed?: number;
170
+ noiseTexturePow?: number;
171
+ vectorFieldFactor?: number;
172
+ animationIntensity?: number;
173
+ wavesCount?: number;
174
+ };
175
+ }
176
+
177
+ /**
178
+ * @typedef {Object} WxColorStylesStrict
179
+ * @property {string} name - name of the style
180
+ */
181
+ export interface WxColorStylesStrict {
182
+ base: WxColorStyleStrict;
183
+ [name: string]: WxColorStyleStrict | undefined;
184
+ }
185
+
186
+ let _units: WxUnits;
187
+ let _colorSchemes: WxColorSchemes;
188
+ let _colorStylesUnrolled: WxColorStylesStrict;
189
+
190
+ /** Options for the wxtiles library */
191
+ export interface WxTilesLibOptions {
192
+ /** Additional Color styles to use for the library */
193
+ colorStyles?: WxColorStylesWeakMixed;
194
+
195
+ /** Additional color schemes to use for the library */
196
+ colorSchemes?: WxColorSchemes;
197
+
198
+ /** Additional units to use for the library */
199
+ units?: WxUnits;
200
+ }
201
+
202
+ /**
203
+ * Initialize the wxtiles library
204
+ * @param options - options {@link WxTilesLibOptions} to initialize the library
205
+ */
206
+ export function WxTilesLibSetup({
207
+ colorStyles = {},
208
+ units = {},
209
+ colorSchemes = {},
210
+ }: WxTilesLibOptions = {}): void {
211
+ WXLOG("WxTile lib setup: start");
212
+ _units = Object.assign({}, __units_default_preset, units);
213
+ _colorSchemes = Object.assign(
214
+ {},
215
+ colorSchemes,
216
+ __colorSchemes_default_preset,
217
+ );
218
+ const toUnroll = Object.assign({}, colorStyles, __colorStyles_default_preset);
219
+ _colorStylesUnrolled = unrollStylesParent(toUnroll);
220
+ WXLOG("WxTile lib setup: styles unrolled");
221
+
222
+ // Make sure fonts are loaded & ready!
223
+ (async () => {
224
+ try {
225
+ await document.fonts.load("32px barbs");
226
+ await document.fonts.load("32px arrows");
227
+ } catch (e) {
228
+ WXLOG("WxTile lib setup: fonts not loaded");
229
+ }
230
+ })();
231
+
232
+ WXLOG("WxTile lib setup is done.");
233
+ }
234
+
235
+ /**
236
+ * Get all {@link WxColorStylesStrict} used by the library
237
+ * */
238
+ export function WxGetColorStyles(): WxColorStylesStrict {
239
+ return _colorStylesUnrolled;
240
+ }
241
+
242
+ /**
243
+ * Get all {@link WxColorSchemes} used by the library
244
+ * */
245
+ export function WxGetColorSchemes(): WxColorSchemes {
246
+ return _colorSchemes;
247
+ }
248
+
249
+ /** A function type with extra properties. */
250
+ export interface Converter {
251
+ /** interface of a function - unit cinverter*/
252
+ (x: number): number;
253
+ /** true if the converter is a trivial one */
254
+ trivial?: boolean;
255
+ }
256
+
257
+ /**
258
+ * Convert a value from one unit to another
259
+ * @param from - the unit to convert from
260
+ * @param to - the unit to convert to
261
+ * @param customUnits - custom units to use if needed
262
+ * @returns a function that converts a value from one unit to another
263
+ * @example
264
+ * ```ts
265
+ * const convert = makeConverter('m/s', 'km/h');
266
+ * const speed = convert(10); // speed is now 36
267
+ * ```
268
+ * */
269
+ export function makeConverter(
270
+ from: string,
271
+ to: string,
272
+ customUnits?: WxUnits,
273
+ ): Converter {
274
+ WXLOG("makeConverter: From=", from, " To=", to);
275
+ const c = (x: number) => x;
276
+ c.trivial = true;
277
+ if (from === to) {
278
+ WXLOG("Trivial converter");
279
+ return c; // trivial
280
+ }
281
+
282
+ const localUnitsCopy = Object.assign({}, _units, customUnits);
283
+ const fromUnit = localUnitsCopy[from];
284
+ const toUnit = localUnitsCopy[to];
285
+ if (!fromUnit || !toUnit) {
286
+ WXLOG("Inconvertible units. Trivial converter");
287
+ return c; // Inconvertible
288
+ }
289
+
290
+ const [fromUnitBase, fromFactor, fromOffset] = fromUnit;
291
+ const [toUnitBase, toFactor, toOffset] = toUnit;
292
+
293
+ if (fromUnitBase !== toUnitBase || !fromFactor || !toFactor) {
294
+ WXLOG("Inconvertible units. Trivial converter");
295
+ return c; // trivial
296
+ }
297
+
298
+ const a = fromFactor / toFactor;
299
+ const b = ((fromOffset || 0) - (toOffset || 0)) / toFactor;
300
+ return b ? (x: number) => a * x + b : (x: number) => a * x;
301
+ }
302
+
303
+ /**
304
+ * Unroll color styles with parent references
305
+ * @param stylesArrInc - array of styles, some of them may be incomplete, with inheritence
306
+ * @returns Strict styles array
307
+ */
308
+ function unrollStylesParent(
309
+ stylesArrInc: WxColorStylesWeakMixed,
310
+ ): WxColorStylesStrict {
311
+ const stylesInc: ColorStylesIncomplete = Object.assign(
312
+ {},
313
+ __colorStyles_default_preset,
314
+ );
315
+ for (const name in stylesArrInc) {
316
+ const styleA = stylesArrInc[name];
317
+ if (Array.isArray(styleA)) {
318
+ for (let i = 0; i < styleA.length; ++i) {
319
+ stylesInc[`${name}[${i}]`] = Object.assign({}, styleA[i]); // deep copy
320
+ }
321
+ } else {
322
+ stylesInc[name] = Object.assign({}, styleA); // deep copy
323
+ }
324
+ }
325
+
326
+ const baseStyleCopy = Object.assign({}, __colorStyles_default_preset.base);
327
+ // recursive function to apply inheritance
328
+ const inherit = (
329
+ stylesInc: ColorStylesIncomplete,
330
+ name: string,
331
+ ): WxColorStyleStrict => {
332
+ if (name === "base") return baseStyleCopy; // nothing to inherit
333
+ const style = stylesInc[name]; // there are no arrays by this point
334
+ if (!style) return baseStyleCopy; // nothing to inherit
335
+ if (!style.parent || !(style.parent in stylesInc)) style.parent = "base";
336
+ const parent = inherit(stylesInc, style.parent); // After inheritance it is FULL ColorStyle
337
+ return Object.assign(
338
+ style,
339
+ Object.assign({}, parent, style, { parent: "base" }),
340
+ ); // this ugly construction changes style 'in place' so it is a soft-copy. huray!
341
+ };
342
+
343
+ const styles: WxColorStylesStrict = { base: baseStyleCopy };
344
+ for (const name in stylesInc) {
345
+ styles[name] = inherit(stylesInc, name);
346
+ }
347
+
348
+ return styles;
349
+ }
350
+
351
+ /** Function type to load image from URL, with additional properties */
352
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
353
+ type UriLoaderPromiseFunc<T> = (url: string, ...props: any[]) => Promise<T>;
354
+
355
+ export interface CachedUriLoaderPromiseFunc<T> extends UriLoaderPromiseFunc<T> {
356
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
357
+ (url: string, ...props: any): Promise<T>;
358
+ clearCache: () => void;
359
+ }
360
+
361
+ /** Makes a cachable function that loads image from URL, with additional properties */
362
+ export function cacheUriPromise<T>(
363
+ fn: UriLoaderPromiseFunc<T>,
364
+ ): CachedUriLoaderPromiseFunc<T> {
365
+ const cache = new Map<string, Promise<T>>();
366
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
367
+ const cachedFunc = (url: string, ...props: any[]): Promise<T> => {
368
+ const cached = cache.get(url);
369
+ if (cached) return cached;
370
+ const promise = fn(url, ...props);
371
+ // cache any result (even falures)
372
+ cache.set(url, promise);
373
+ // except aborted (images), so they could be reloaded
374
+ promise.catch((e) => e.name === "AbortError" && cache.delete(url));
375
+ return promise;
376
+ };
377
+
378
+ cachedFunc.clearCache = () => cache.clear();
379
+ return cachedFunc;
380
+ }
381
+
382
+ /**
383
+ * abortable 'loadImage'
384
+ * @param url - image url
385
+ * @param requestInit - fetch requestInit
386
+ * */
387
+ export async function loadImage(
388
+ url: string,
389
+ requestInit?: RequestInit,
390
+ ): Promise<ImageBitmap> {
391
+ //// Method 0
392
+ const f = await fetch(url, requestInit);
393
+ if (f.status !== 200 && f.status !== 304) {
394
+ throw {
395
+ name: "Tile loading failed",
396
+ reason: f.headers.get("x-reason"),
397
+ status: f.status,
398
+ };
399
+ }
400
+
401
+ return await createImageBitmap(await f.blob(), { premultiplyAlpha: "none" });
402
+
403
+ // //// Method 000
404
+ // const img = new Image();
405
+ // img.src = URL.createObjectURL(await (await fetch(url, requestInit)).blob());
406
+ // await img.decode();
407
+ // URL.revokeObjectURL(img.src);
408
+ // return img;
409
+
410
+ // const img = new Image();
411
+ // img.crossOrigin = 'anonymous'; // essential
412
+ // const abortFunc = () => (img.src = ''); // stop loading
413
+ // signal.addEventListener('abort', abortFunc);
414
+
415
+ // //// Method 1
416
+ // img.src = url;
417
+ // await img.decode();
418
+ // signal.removeEventListener('abort', abortFunc);
419
+ // return img;
420
+
421
+ //// Method 2
422
+ // return new Promise((resolve, reject) => {
423
+ // img.onerror = (e) => {
424
+ // signal.removeEventListener('abort', abortFunc);
425
+ // reject(e);
426
+ // };
427
+ // img.onload = () => {
428
+ // signal.removeEventListener('abort', abortFunc);
429
+ // resolve(img);
430
+ // };
431
+ // img.src = url; // should be after .onload
432
+ // });
433
+ }
434
+
435
+ /** integral pare for fast box blur algorithm */
436
+ export interface IntegralPare {
437
+ /** Integral image */
438
+ integral: Uint32Array;
439
+ /** Integral image of ZEROs */
440
+ integralNZ: Uint32Array | null;
441
+ }
442
+
443
+ /** interface of a data read from a PNG tile */
444
+ export interface DataPicture {
445
+ raw: Uint16Array;
446
+ dmin: number;
447
+ dmax: number;
448
+ dmul: number;
449
+ }
450
+
451
+ /** One (scalar) or three (vector components + length component) {@link DataPictures} */
452
+ export type DataPictures =
453
+ | [DataPicture]
454
+ | [DataPicture, DataPicture, DataPicture];
455
+
456
+ /**
457
+ * class implements {@link DataPictures} with lazy calculation of {@link IntegralPare} for fast box blur algorithm
458
+ * */
459
+ export class DataIntegral implements DataPicture {
460
+ protected integral_?: IntegralPare;
461
+ radius = 0;
462
+ constructor(
463
+ public raw: Uint16Array,
464
+ public dmin: number,
465
+ public dmax: number,
466
+ public dmul: number,
467
+ ) {}
468
+ get integral(): IntegralPare {
469
+ if (!this.integral_) {
470
+ this.integral_ = buildIntegralPare(this.raw);
471
+ }
472
+ return this.integral_;
473
+ }
474
+ }
475
+
476
+ /** One (scalar) or two (vector) {@link DataIntegral} */
477
+ export type DataIntegrals = [DataIntegral] | [DataIntegral, DataIntegral];
478
+
479
+ /**
480
+ * Helper function to create a 2D canvas context
481
+ * @param width - width of the context
482
+ * @param height - height of the context
483
+ * @param willReadFrequently - if true, the context will be read frequently (browser will optimize it)
484
+ * @returns canvas context
485
+ */
486
+ export function create2DContext(
487
+ width: number,
488
+ height: number,
489
+ willReadFrequently = true,
490
+ ): CanvasRenderingContext2D {
491
+ const context = Object.assign(document.createElement("canvas"), {
492
+ width,
493
+ height,
494
+ imageSmoothingEnabled: false,
495
+ }).getContext("2d", {
496
+ willReadFrequently,
497
+ });
498
+ if (!context) throw new Error("Cannot get canvas context");
499
+ return context;
500
+ }
501
+
502
+ /** Converts an ImageBitmap to ImageData */
503
+ function imageToData(image: ImageBitmap): ImageData {
504
+ const { width, height } = image;
505
+ const context = create2DContext(width, height);
506
+ context.drawImage(image, 0, 0);
507
+ return context.getImageData(0, 0, width, height);
508
+ }
509
+
510
+ /**
511
+ * Load ImageData to from URL with RequestInit
512
+ * @param url - image url
513
+ * @param requestInit - fetch requestInit
514
+ * @returns Promise of ImageData
515
+ */
516
+ export async function loadImageData(
517
+ url: string,
518
+ requestInit?: RequestInit,
519
+ ): Promise<ImageData> {
520
+ return imageToData(await loadImage(url, requestInit));
521
+ }
522
+
523
+ /**
524
+ * Calculates integral image of the image
525
+ * @param image - ImageData to calculate integral image of
526
+ * @returns integral image {@link DataIntegral}
527
+ * */
528
+ function dataToIntegral(imData: ImageData): DataIntegral {
529
+ if (imData.data[34] < 1) {
530
+ WXLOG(
531
+ "Warning: image is in too old format. Check the version of the Splitter.",
532
+ );
533
+ }
534
+
535
+ // picTile contains bytes RGBARGBARGBA ...
536
+ // we need RG and don't need BA, so output is a 16 byte array picData with every second value dropped.
537
+ const imbuf = new Uint16Array(imData.data.buffer);
538
+ const raw = new Uint16Array(imbuf.length / 2);
539
+ for (let i = 0; i < raw.length; i++) {
540
+ raw[i] = imbuf[i * 2];
541
+ }
542
+
543
+ // Min and Max values of the data are encoded as two floats saved in the first 8 pixels in Blue channel
544
+ const minmaxbuf = new Uint8Array(8);
545
+ for (let i = 0; i < 8; ++i) {
546
+ minmaxbuf[i] = imData.data[i * 4 + 2];
547
+ }
548
+
549
+ const view = new DataView(minmaxbuf.buffer);
550
+ const dmin = view.getFloat32(0, true);
551
+ const dmax = view.getFloat32(4, true);
552
+ const dmul = (dmax - dmin) / 65535;
553
+ // const integral = buildIntegralPare(raw);
554
+ // return new DataIntegral({ raw, dmin, dmax, dmul }, 0);
555
+ return new DataIntegral(raw, dmin, dmax, dmul);
556
+ }
557
+
558
+ /**
559
+ * Load {@link DataIntegral} from URL with RequestInit
560
+ * @param url - image url
561
+ * @param requestInit - fetch requestInit
562
+ * @returns Promise of {@link DataIntegral}
563
+ * */
564
+ export async function loadDataIntegral(
565
+ url: string,
566
+ requestInit?: RequestInit,
567
+ ): Promise<DataIntegral> {
568
+ return dataToIntegral(await loadImageData(url, requestInit));
569
+ }
570
+
571
+ /**
572
+ * Calculaates {@link IntegralPare} from raw data Uint16Array.
573
+ * Used for fast box-blur algo
574
+ * Integarl image: https://en.wikipedia.org/wiki/Summed-area_table.
575
+ * @param raw - raw data
576
+ * @returns IntegralPare
577
+ * */
578
+ export function buildIntegralPare(raw: Uint16Array): IntegralPare {
579
+ const integral = new Uint32Array(258 * 258);
580
+ // The main Idea of integralNZ is to calculate the amount of Non Zero values,
581
+ // so in the Blur algorithm it can be used for 'averaging' instead of actual area of a BoxBlur frame
582
+ const integralNZ = new Uint32Array(258 * 258);
583
+
584
+ integral[0] = raw[0]; // upper left value
585
+ integralNZ[0] = raw[0] ? 1 : 0; // upper left value
586
+
587
+ // boundaries
588
+ for (let i = 1; i < 258; ++i) {
589
+ integral[i] = raw[i] + integral[i - 1]; // uper boundary
590
+ integralNZ[i] = (raw[i] ? 1 : 0) + integralNZ[i - 1]; // uper boundary
591
+ const yi = 258 * i;
592
+ integral[yi] = raw[yi] + integral[yi - 258]; // left boundary
593
+ integralNZ[yi] = (raw[yi] ? 1 : 0) + integralNZ[yi - 258]; // left boundary
594
+ }
595
+
596
+ // the rest picture
597
+ for (let y = 1; y < 258; ++y) {
598
+ for (let x = 1; x < 258; ++x) {
599
+ const i = 258 * y + x;
600
+ integral[i] =
601
+ raw[i] + integral[i - 258] + integral[i - 1] - integral[i - 259];
602
+ integralNZ[i] =
603
+ (raw[i] ? 1 : 0) +
604
+ integralNZ[i - 258] +
605
+ integralNZ[i - 1] -
606
+ integralNZ[i - 259];
607
+ }
608
+ }
609
+
610
+ // 66564 is the maximum posible value of the integralNZ image, so if all values are not 0, then no need to use it
611
+ return {
612
+ integral,
613
+ integralNZ: integralNZ[66563] === 66564 ? null : integralNZ,
614
+ };
615
+ }
616
+
617
+ // restore raw data from integral using zero radius
618
+ function restoreRawFromIntegral(im: DataIntegral): DataIntegral {
619
+ // TESTED - works
620
+ /*
621
+ \ 012345
622
+ 0 -AB---
623
+ 1 -CD--- - (2,1) r=0
624
+ 2 ------
625
+ */
626
+ const { integral: I } = im.integral;
627
+ im.raw[0] = I[0]; // upper left value
628
+ // the rest picture
629
+ for (let y = 1; y < 258; y++) {
630
+ im.raw[y] = I[y] - I[y - 1]; // uper boundary
631
+ im.raw[258 * y] = I[258 * y] - I[258 * (y - 1)]; // left boundary
632
+ for (let x = 1; x < 258; x++) {
633
+ const i = 258 * y + x;
634
+ im.raw[i] = I[i - 259] + I[i] - I[i - 258] - I[i - 1];
635
+ }
636
+ }
637
+
638
+ return im;
639
+ }
640
+
641
+ /**
642
+ * BoxBlur implementation based on integral image {@link DataIntegral}.
643
+ * Adaptaion of using in 'tiling' mode. Uses only one boudary line for each tile.
644
+ * Gives decent visual results, but not as good as bluring over the whole image.
645
+ * Sometimes distortion of the image is noticable on the edges of the tiles.
646
+ * Also it doesn't change/blur corners of the tiles.
647
+ * @param data - {@link DataIntegral}
648
+ * @param radius - radius for the box-blur algorithm
649
+ * */
650
+ export function blurData(im: DataIntegral, radius: number): DataIntegral {
651
+ const adjustedRadius = radius < 0 ? 0 : radius;
652
+ if (adjustedRadius === im.radius) return im;
653
+ im.radius = adjustedRadius;
654
+ if (!adjustedRadius) return restoreRawFromIntegral(im); // radius === 0
655
+
656
+ const { integral, integralNZ } = im.integral;
657
+
658
+ // process picture excluding two lines of boundaries
659
+ for (let y = 2; y < 256; y++) {
660
+ for (let x = 2; x < 256; x++) {
661
+ const i = 258 * y + x;
662
+ if (!im.raw[i]) {
663
+ continue;
664
+ }
665
+
666
+ /* |
667
+ 012345
668
+ 0 A--B--
669
+ 1 -+++--
670
+ 2 -+o+-- - (2,2) r=1
671
+ 3 C++D--
672
+ 4 ------
673
+
674
+ |
675
+ (25)34567
676
+ 253 -A--B-
677
+ 254 --+++-
678
+ 255 --+o+- - (255,255) r=1
679
+ 256 -C++D-
680
+ 257 ------
681
+
682
+ */
683
+
684
+ const rx = Math.min(adjustedRadius, x - 1, 256 - x);
685
+ const ry = Math.min(adjustedRadius, y - 1, 256 - y);
686
+
687
+ const i1 = 258 * (y - ry - 1) + x;
688
+ const i2 = 258 * (y + ry) + x;
689
+ let sumNZ: number;
690
+ if (integralNZ) {
691
+ const ANZ = integralNZ[i1 - rx - 1];
692
+ const BNZ = integralNZ[i1 + rx];
693
+ const CNZ = integralNZ[i2 - rx - 1];
694
+ const DNZ = integralNZ[i2 + rx];
695
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
696
+ } else {
697
+ sumNZ = (2 * rx + 1) * (2 * ry + 1); // all values are non Zero
698
+ }
699
+
700
+ const A = integral[i1 - rx - 1];
701
+ const B = integral[i1 + rx];
702
+ const C = integral[i2 - rx - 1];
703
+ const D = integral[i2 + rx];
704
+ const sum = A + D - B - C;
705
+
706
+ im.raw[i] = sum / sumNZ;
707
+ }
708
+ }
709
+
710
+ // process boundaries
711
+ // Copy the first line from the boundary to the second line, to make life easier
712
+ for (let k = 2; k < 256; k++) {
713
+ // top two lines
714
+ const ti = 258 + k; // start with (2,1)
715
+ if (im.raw[ti]) {
716
+ /*
717
+ |
718
+ 012345
719
+ A B
720
+ 0 -+++--
721
+ 1 C+oD-- - (2,1) rx=1, A=B=0
722
+ 2 ------
723
+
724
+ |
725
+ (25)4567
726
+ A B
727
+ 0 ---+++
728
+ 1 --C+oD - (256,1) rx=1, A=B=0
729
+ 2 ------
730
+
731
+ |
732
+ 012345
733
+ A B
734
+ 0 -+++++--
735
+ 1 C++o+D-- - (3,1) rx=2, A=B=0
736
+ 2 --------
737
+
738
+ |
739
+ (25)234567
740
+ A B
741
+ 0 -+++++
742
+ 1 C++o+D - (255,1) rx=2, A=B=0
743
+ 2 ------
744
+ */
745
+
746
+ const x = k;
747
+ const rx = Math.min(adjustedRadius, x - 1, 256 - x);
748
+
749
+ const i2 = 258 + x;
750
+ let sumNZ: number;
751
+ if (integralNZ) {
752
+ const ANZ = 0;
753
+ const BNZ = 0;
754
+ const CNZ = integralNZ[i2 - rx - 1];
755
+ const DNZ = integralNZ[i2 + rx];
756
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
757
+ } else {
758
+ sumNZ = (2 * rx + 1) * 2; // all values are non Zero
759
+ }
760
+
761
+ const A = 0;
762
+ const B = 0;
763
+ const C = integral[i2 - rx - 1];
764
+ const D = integral[i2 + rx];
765
+ const sum = A + D - B - C;
766
+
767
+ const s = sum / sumNZ;
768
+
769
+ im.raw[ti - 258] = s; // 0 line
770
+ im.raw[ti] = s; // 1 line
771
+ } // top
772
+
773
+ // bottom two lines
774
+ const bi = 258 * 256 + k;
775
+ if (im.raw[bi]) {
776
+ /*
777
+ |
778
+ 012345
779
+ 254 ------
780
+ 255 A--B--
781
+ 256 -+o+-- - (2,256) ry=1
782
+ 257 C++D--
783
+
784
+ |
785
+ 012345
786
+ 254 --------
787
+ 255 A----B--
788
+ 256 -++o++-- - (3,256) ry=2
789
+ 257 C++++D--
790
+ */
791
+ const x = k;
792
+ const rx = Math.min(adjustedRadius, x - 1, 256 - x);
793
+ const i1 = 258 * 255 + x;
794
+ const i2 = 258 * 257 + x;
795
+ const A = integral[i1 - rx - 1];
796
+ const B = integral[i1 + rx];
797
+ const C = integral[i2 - rx - 1];
798
+ const D = integral[i2 + rx];
799
+ const sum = A + D - B - C;
800
+
801
+ let sumNZ: number;
802
+ if (integralNZ) {
803
+ const ANZ = integralNZ[i1 - rx - 1];
804
+ const BNZ = integralNZ[i1 + rx];
805
+ const CNZ = integralNZ[i2 - rx - 1];
806
+ const DNZ = integralNZ[i2 + rx];
807
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
808
+ } else {
809
+ sumNZ = (2 * rx + 1) * 2; // all values are non Zero
810
+ }
811
+
812
+ const s = sum / sumNZ;
813
+ im.raw[bi] = s; // 256 row
814
+ im.raw[bi + 258] = s; // 257 row
815
+ } // bottom
816
+
817
+ // left two lines
818
+ const li = 258 * k + 1;
819
+ if (im.raw[li]) {
820
+ const y = k;
821
+ const ry = Math.min(adjustedRadius, y - 1, 256 - y);
822
+ const i1 = 258 * (y - ry - 1) + 1;
823
+ const i2 = 258 * (y + ry) + 1;
824
+
825
+ let sumNZ: number;
826
+ if (integralNZ) {
827
+ const ANZ = 0;
828
+ const BNZ = integralNZ[i1];
829
+ const CNZ = 0;
830
+ const DNZ = integralNZ[i2];
831
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
832
+ } else {
833
+ sumNZ = (2 * ry + 1) * 2; // all values are non Zero
834
+ }
835
+
836
+ const A = 0;
837
+ const B = integral[i1];
838
+ const C = 0;
839
+ const D = integral[i2];
840
+ const sum = A + D - B - C;
841
+
842
+ const s = sum / sumNZ;
843
+ im.raw[li - 1] = s; // 0 column
844
+ im.raw[li] = s; // 1 column
845
+ } // left
846
+
847
+ // right two lines
848
+ const ri = 258 * k + 256;
849
+ if (im.raw[ri]) {
850
+ const y = k;
851
+ const ry = Math.min(adjustedRadius, y - 1, 256 - y);
852
+ const i1 = 258 * (y - ry - 1) + 256;
853
+ const i2 = 258 * (y + ry) + 256;
854
+
855
+ let sumNZ: number;
856
+ if (integralNZ) {
857
+ const ANZ = integralNZ[i1 - 1];
858
+ const BNZ = integralNZ[i1 + 1];
859
+ const CNZ = integralNZ[i2 - 1];
860
+ const DNZ = integralNZ[i2 + 1];
861
+ sumNZ = ANZ + DNZ - BNZ - CNZ; // amount of non Zero values
862
+ } else {
863
+ sumNZ = 2 * (2 * ry + 1); // all values are non Zero
864
+ }
865
+
866
+ const A = integral[i1 - 1];
867
+ const B = integral[i1 + 1];
868
+ const C = integral[i2 - 1];
869
+ const D = integral[i2 + 1];
870
+ const sum = A + D - B - C;
871
+
872
+ const s = sum / sumNZ;
873
+ im.raw[ri] = s; // 256 column
874
+ im.raw[ri + 1] = s; // 257 column
875
+ } // right
876
+ } // for k
877
+
878
+ return im;
879
+ }
880
+
881
+ /**
882
+ * Convert Uin32 RGB color to web color
883
+ * @param color - Uin32 color
884
+ * @returns web color in format '#RRGGBB'
885
+ * */
886
+ export function RGBtoHEX(rgb: number): string {
887
+ const r = (rgb >> 0) & 255;
888
+ const g = (rgb >> 8) & 255;
889
+ const b = (rgb >> 16) & 255;
890
+ let rs = r.toString(16);
891
+ let gs = g.toString(16);
892
+ let bs = b.toString(16);
893
+ rs = rs.length === 2 ? rs : `0${rs}`;
894
+ gs = gs.length === 2 ? gs : `0${gs}`;
895
+ bs = bs.length === 2 ? bs : `0${bs}`;
896
+ return `#${rs}${gs}${bs}`;
897
+ }
898
+
899
+ /**
900
+ * Convert Uin32 RGBA color to web color
901
+ * @param color - Uin32 color
902
+ * @returns web color in format '#RRGGBBAA'
903
+ * */
904
+ export function RGBAtoHEX(rgba: number): string {
905
+ const r = (rgba >> 0) & 255;
906
+ const g = (rgba >> 8) & 255;
907
+ const b = (rgba >> 16) & 255;
908
+ const a = (rgba >> 24) & 255;
909
+ let rs = r.toString(16);
910
+ let gs = g.toString(16);
911
+ let bs = b.toString(16);
912
+ let as = a.toString(16);
913
+ rs = rs.length === 2 ? rs : `0${rs}`;
914
+ gs = gs.length === 2 ? gs : `0${gs}`;
915
+ bs = bs.length === 2 ? bs : `0${bs}`;
916
+ as = as.length === 2 ? as : `0${as}`;
917
+ return `#${rs}${gs}${bs}${as}`;
918
+ }
919
+
920
+ /**
921
+ * Convert web color to Uin32 RGB color
922
+ * @param color - web color in format '#RGB' or '#RRGGBB' or '#RRGGBBAA'
923
+ * @returns Uin32 color
924
+ * */
925
+ export function HEXtoRGBA(c: string): number {
926
+ if (c[0] === "#") {
927
+ if (c.length === 4)
928
+ return +(`0xff${c[3]}${c[3]}${c[2]}${c[2]}${c[1]}${c[1]}`);
929
+ if (c.length === 7)
930
+ return +(`0xff${c[5]}${c[6]}${c[3]}${c[4]}${c[1]}${c[2]}`);
931
+ if (c.length === 9)
932
+ return +(`0x${c[7]}${c[8]}${c[5]}${c[6]}${c[3]}${c[4]}${c[1]}${c[2]}`);
933
+ }
934
+
935
+ WXLOG("wrong color format", c);
936
+
937
+ return 0;
938
+ }
939
+
940
+ /**
941
+ * json loader helper
942
+ * @template {any} T - type of the object to load
943
+ * @param url - url to json file
944
+ * @param requestInit - requestInit for fetch
945
+ * @returns json object
946
+ * */
947
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
948
+ export async function fetchJson<T = any>(
949
+ url: RequestInfo,
950
+ requestInit?: RequestInit,
951
+ ): Promise<T> {
952
+ const response = await fetch(url, requestInit);
953
+ if (!response.ok) {
954
+ throw new Error(`error:${url} - ${response.statusText}`);
955
+ }
956
+
957
+ return response.json();
958
+ }
959
+
960
+ /**
961
+ * Create element helper
962
+ * @param tag - tag name
963
+ * @param className - class name
964
+ * @param container - container to append element
965
+ * @returns created element
966
+ * */
967
+ export function createEl(
968
+ tagName: string,
969
+ className = "",
970
+ container?: HTMLElement,
971
+ ): HTMLElement {
972
+ const el = document.createElement(tagName); // Object.assign(document.createElement(tagName), { className });
973
+ el.className = className;
974
+ container?.appendChild(el);
975
+ return el;
976
+ }
977
+
978
+ /**
979
+ * Color linear mixer
980
+ * @param color1 - color1 Uin32 RGBA
981
+ * @param color2 - color2 Uin32 RGBA
982
+ * @param k - koefficient
983
+ * @returns mixed color Uin32 RGBA
984
+ * */
985
+ export function mixColor(c1: number, c2: number, t: number): number {
986
+ const r1 = (c1 >> 0) & 255;
987
+ const g1 = (c1 >> 8) & 255;
988
+ const b1 = (c1 >> 16) & 255;
989
+ const a1 = c1 >>> 24;
990
+
991
+ const r2 = (c2 >> 0) & 255;
992
+ const g2 = (c2 >> 8) & 255;
993
+ const b2 = (c2 >> 16) & 255;
994
+ const a2 = c2 >>> 24;
995
+
996
+ const r = r1 + t * (r2 - r1);
997
+ const g = g1 + t * (g2 - g1);
998
+ const b = b1 + t * (b2 - b1);
999
+ const a = a1 + t * (a2 - a1);
1000
+ return r | (g << 8) | (b << 16) | (a << 24);
1001
+ }
1002
+
1003
+ /**
1004
+ * Helper to create array of levels for a style
1005
+ * @param min - min value
1006
+ * @param max - max value
1007
+ * @param n - number of levels
1008
+ * @returns array of levels
1009
+ * */
1010
+ export function createLevels(min: number, max: number, n: number): number[] {
1011
+ // create 10 levels from min to max
1012
+ const levels: number[] = [];
1013
+ for (let i = 0; i < n; ++i) {
1014
+ levels.push((i * (max - min)) / (n - 1) + min);
1015
+ }
1016
+ return levels;
1017
+ }
1018
+
1019
+ /**
1020
+ * Get closest existing time in array. If time is Date, strings will be converted to number to find closest time
1021
+ * @param times - array of times
1022
+ * @param time - time to find
1023
+ * @returns closest time a value from array
1024
+ * */
1025
+ export function getClosestTimeString(
1026
+ times: string[],
1027
+ time: Date | string | number,
1028
+ ): string {
1029
+ const unixTime: number =
1030
+ typeof time === "number"
1031
+ ? time
1032
+ : typeof time === "string"
1033
+ ? new Date(time).getTime()
1034
+ : time.getTime();
1035
+ // Take the next times[]'s after unixTime OR the last
1036
+ return (
1037
+ times.find((stime) => new Date(stime).getTime() >= unixTime) ||
1038
+ times[times.length - 1]
1039
+ );
1040
+ }
1041
+
1042
+ let wxlogging = false;
1043
+ /**
1044
+ * Logging helper
1045
+ * */
1046
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
1047
+ export let WXLOG = (...args: any[]) => {};
1048
+
1049
+ /**
1050
+ * Set logging on/off
1051
+ * @param logging - true to turn on logging
1052
+ * @example
1053
+ * WxTilesLogging(true); // turn on logging to console
1054
+ *
1055
+ * WxTilesLogging(false); // turn off logging
1056
+ *
1057
+ * WxTilesLogging(console.trace); // set logging using console.trace
1058
+ * */
1059
+ // biome-ignore lint/suspicious/noExplicitAny: Suppressing for specific use case
1060
+ export function WxTilesLogging(on?: boolean | ((...args: any[]) => void)) {
1061
+ wxlogging = !!on;
1062
+ console.log("WXLOGing", wxlogging);
1063
+ WXLOG = typeof on === "function" ? on : wxlogging ? console.log : () => {};
1064
+ }
1065
+
1066
+ /**
1067
+ * Helper to convert short form of web color from '#RGB' to '#RRGGBB'
1068
+ * @param color - web color in format '#RGB' or '#RRGGBB' or '#RRGGBBAA'
1069
+ * @returns web color in format '#RRGGBB'
1070
+ * */
1071
+ export function refineColor(c: string): string {
1072
+ // convert short form of color into long #25f => #2255ff
1073
+ return c[0] === "#" && c.length === 4
1074
+ ? `#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}`
1075
+ : c;
1076
+ }
1077
+
1078
+ /**
1079
+ * Helper to fill URI template with values
1080
+ * @param uri - URI template
1081
+ * @param values - {@link XYZ} values to fill template
1082
+ * @returns URI with values filled
1083
+ * */
1084
+ export function uriXYZ(uri: string, { x, y, z }: XYZ): string {
1085
+ return uri
1086
+ .replace("{x}", `${x}`)
1087
+ .replace("{y}", `${y}`)
1088
+ .replace("{z}", `${z}`);
1089
+ // return uri.replace('{x}', x.toString()).replace('{y}', y.toString()).replace('{z}', z.toString());
1090
+ }
1091
+
1092
+ /**
1093
+ * Calculate hash of {@link XYZ}
1094
+ * @param xyz - {@link XYZ} to calculate hash
1095
+ * @returns string hash
1096
+ * */
1097
+ export function HashXYZ({ x, y, z }: XYZ): string {
1098
+ return `${z}-${x}-${y}`;
1099
+ }