-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathh3core.js
1835 lines (1727 loc) · 61.8 KB
/
h3core.js
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2018-2019, 2022 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @module h3
*/
import C from '../out/libh3';
import BINDINGS from './bindings';
import {
throwIfError,
H3LibraryError,
JSBindingError,
E_RES_DOMAIN,
E_UNKNOWN_UNIT,
E_ARRAY_LENGTH,
E_NULL_INDEX,
E_CELL_INVALID,
E_OPTION_INVALID
} from './errors';
/**
* Map of C-defined functions
* @type {any}
* @private
*/
const H3 = {};
// Create the bound functions themselves
BINDINGS.forEach(function bind(def) {
H3[def[0]] = C.cwrap(...def);
});
// Alias the hexidecimal base for legibility
const BASE_16 = 16;
// Alias unused bits for legibility
const UNUSED_UPPER_32_BITS = 0;
// ----------------------------------------------------------------------------
// Byte size imports
const SZ_INT = 4;
const SZ_PTR = 4;
const SZ_DBL = 8;
const SZ_INT64 = 8;
const SZ_H3INDEX = H3.sizeOfH3Index();
const SZ_LATLNG = H3.sizeOfLatLng();
const SZ_CELLBOUNDARY = H3.sizeOfCellBoundary();
const SZ_GEOPOLYGON = H3.sizeOfGeoPolygon();
const SZ_GEOLOOP = H3.sizeOfGeoLoop();
const SZ_LINKED_GEOPOLYGON = H3.sizeOfLinkedGeoPolygon();
const SZ_COORDIJ = H3.sizeOfCoordIJ();
// ----------------------------------------------------------------------------
// Custom types
/**
* 64-bit hexidecimal string representation of an H3 index
* @static
* @typedef {string} H3Index
*/
/**
* 64-bit hexidecimal string representation of an H3 index,
* or two 32-bit integers in little endian order in an array.
* @static
* @typedef {string | number[]} H3IndexInput
*/
/**
* Coordinates as an `{i, j}` pair
* @static
* @typedef CoordIJ
* @property {number} i
* @property {number} j
*/
/**
* Custom JS Error instance with an attached error code. Error codes come from the
* core H3 library and can be found [in the H3 docs](https://h3geo.org/docs/library/errors#table-of-error-codes).
* @static
* @typedef H3Error
* @property {string} message
* @property {number} code
*/
/**
* Pair of lat,lng coordinates (or lng,lat if GeoJSON output is specified)
* @static
* @typedef {number[]} CoordPair
*/
/**
* Pair of lower,upper 32-bit ints representing a 64-bit value
* @static
* @typedef {number[]} SplitLong
*/
// ----------------------------------------------------------------------------
// Unit constants
/**
* Length/Area units
* @static
* @property {string} m
* @property {string} m2
* @property {string} km
* @property {string} km2
* @property {string} rads
* @property {string} rads2
*/
export const UNITS = {
m: 'm',
m2: 'm2',
km: 'km',
km2: 'km2',
rads: 'rads',
rads2: 'rads2'
};
// ----------------------------------------------------------------------------
// Flags
/**
* Mode flags for polygonToCells
* @static
* @property {string} containmentCenter
* @property {string} containmentFull
* @property {string} containmentOverlapping
* @property {string} containmentOverlappingBbox
*/
export const POLYGON_TO_CELLS_FLAGS = {
containmentCenter: 'containmentCenter',
containmentFull: 'containmentFull',
containmentOverlapping: 'containmentOverlapping',
containmentOverlappingBbox: 'containmentOverlappingBbox'
};
// ----------------------------------------------------------------------------
// Utilities and helpers
/**
* @private
* @param {string} flags Value from POLYGON_TO_CELLS_FLAGS
* @returns {number} Flag value
* @throws {H3Error} If invalid
*/
function polygonToCellsFlagsToNumber(flags) {
switch (flags) {
case POLYGON_TO_CELLS_FLAGS.containmentCenter:
return 0;
case POLYGON_TO_CELLS_FLAGS.containmentFull:
return 1;
case POLYGON_TO_CELLS_FLAGS.containmentOverlapping:
return 2;
case POLYGON_TO_CELLS_FLAGS.containmentOverlappingBbox:
return 3;
default:
throw JSBindingError(E_OPTION_INVALID, flags);
}
}
/**
* Validate a resolution, throwing an error if invalid
* @private
* @param {unknown} res Value to validate
* @return {number} Valid res
* @throws {H3Error} If invalid
*/
function validateRes(res) {
if (typeof res !== 'number' || res < 0 || res > 15 || Math.floor(res) !== res) {
throw H3LibraryError(E_RES_DOMAIN, res);
}
return res;
}
/**
* Assert H3 index output, throwing an error if null
* @private
* @param {H3Index | null} h3Index Index to validate
* @return {H3Index}
* @throws {H3Error} If invalid
*/
function validateH3Index(h3Index) {
if (!h3Index) throw JSBindingError(E_NULL_INDEX);
return h3Index;
}
const MAX_JS_ARRAY_LENGTH = Math.pow(2, 32) - 1;
/**
* Validate an array length. JS will throw its own error if you try
* to create an array larger than 2^32 - 1, but validating beforehand
* allows us to exit early before we try to process large amounts
* of data that won't even fit in an output array
* @private
* @param {number} length Length to validate
* @return {number} Valid array length
* @throws {H3Error} If invalid
*/
function validateArrayLength(length) {
if (length > MAX_JS_ARRAY_LENGTH) {
throw JSBindingError(E_ARRAY_LENGTH, length);
}
return length;
}
const INVALID_HEXIDECIMAL_CHAR = /[^0-9a-fA-F]/;
/**
* Convert an H3 index (64-bit hexidecimal string) into a "split long" - a pair of 32-bit ints
* @param {H3IndexInput} h3Index H3 index to check
* @return {SplitLong} A two-element array with 32 lower bits and 32 upper bits
*/
export function h3IndexToSplitLong(h3Index) {
if (
Array.isArray(h3Index) &&
h3Index.length === 2 &&
Number.isInteger(h3Index[0]) &&
Number.isInteger(h3Index[1])
) {
return h3Index;
}
if (typeof h3Index !== 'string' || INVALID_HEXIDECIMAL_CHAR.test(h3Index)) {
return [0, 0];
}
const upper = parseInt(h3Index.substring(0, h3Index.length - 8), BASE_16);
const lower = parseInt(h3Index.substring(h3Index.length - 8), BASE_16);
return [lower, upper];
}
/**
* Convert a 32-bit int to a hexdecimal string
* @private
* @param {number} num Integer to convert
* @return {H3Index} Hexidecimal string
*/
function hexFrom32Bit(num) {
if (num >= 0) {
return num.toString(BASE_16);
}
// Handle negative numbers
num = num & 0x7fffffff;
let tempStr = zeroPad(8, num.toString(BASE_16));
const topNum = (parseInt(tempStr[0], BASE_16) + 8).toString(BASE_16);
tempStr = topNum + tempStr.substring(1);
return tempStr;
}
/**
* Get a H3 index string from a split long (pair of 32-bit ints)
* @param {number} lower Lower 32 bits
* @param {number} upper Upper 32 bits
* @return {H3Index} H3 index
*/
export function splitLongToH3Index(lower, upper) {
return hexFrom32Bit(upper) + zeroPad(8, hexFrom32Bit(lower));
}
/**
* Zero-pad a string to a given length
* @private
* @param {number} fullLen Target length
* @param {string} numStr String to zero-pad
* @return {string} Zero-padded string
*/
function zeroPad(fullLen, numStr) {
const numZeroes = fullLen - numStr.length;
let outStr = '';
for (let i = 0; i < numZeroes; i++) {
outStr += '0';
}
outStr = outStr + numStr;
return outStr;
}
// One more than the max size of an unsigned 32-bit int.
// Dividing by this number is equivalent to num >>> 32
const UPPER_BIT_DIVISOR = Math.pow(2, 32);
/**
* Convert a JS double-precision floating point number to a split long
* @private
* @param {number} num Number to convert
* @return {SplitLong} A two-element array with 32 lower bits and 32 upper bits
*/
function numberToSplitLong(num) {
if (typeof num !== 'number') {
return [0, 0];
}
return [num | 0, (num / UPPER_BIT_DIVISOR) | 0];
}
/**
* Populate a C-appropriate GeoLoop struct from a polygon array
* @private
* @param {number[][]} polygonArray Polygon, as an array of coordinate pairs
* @param {number} geoLoop C pointer to a GeoLoop struct
* @param {boolean} isGeoJson Whether coordinates are in [lng, lat] order per GeoJSON spec
* @return {number} C pointer to populated GeoLoop struct
*/
function polygonArrayToGeoLoop(polygonArray, geoLoop, isGeoJson) {
const numVerts = polygonArray.length;
const geoCoordArray = C._calloc(numVerts, SZ_LATLNG);
// Support [lng, lat] pairs if GeoJSON is specified
const latIndex = isGeoJson ? 1 : 0;
const lngIndex = isGeoJson ? 0 : 1;
for (let i = 0; i < numVerts * 2; i += 2) {
C.HEAPF64.set(
[polygonArray[i / 2][latIndex], polygonArray[i / 2][lngIndex]].map(degsToRads),
geoCoordArray / SZ_DBL + i
);
}
C.HEAPU32.set([numVerts, geoCoordArray], geoLoop / SZ_INT);
return geoLoop;
}
/**
* Create a C-appropriate GeoPolygon struct from an array of polygons
* @private
* @param {number[][][]} coordinates Array of polygons, each an array of coordinate pairs
* @param {boolean} isGeoJson Whether coordinates are in [lng, lat] order per GeoJSON spec
* @return {number} C pointer to populated GeoPolygon struct
*/
function coordinatesToGeoPolygon(coordinates, isGeoJson) {
// Any loops beyond the first loop are holes
const numHoles = coordinates.length - 1;
const geoPolygon = C._calloc(SZ_GEOPOLYGON);
// Byte positions within the struct
const geoLoopOffset = 0;
const numHolesOffset = geoLoopOffset + SZ_GEOLOOP;
const holesOffset = numHolesOffset + SZ_INT;
// geoLoop is first part of struct
polygonArrayToGeoLoop(coordinates[0], geoPolygon + geoLoopOffset, isGeoJson);
let holes;
if (numHoles > 0) {
holes = C._calloc(numHoles, SZ_GEOLOOP);
for (let i = 0; i < numHoles; i++) {
polygonArrayToGeoLoop(coordinates[i + 1], holes + SZ_GEOLOOP * i, isGeoJson);
}
}
C.setValue(geoPolygon + numHolesOffset, numHoles, 'i32');
C.setValue(geoPolygon + holesOffset, holes, 'i32');
return geoPolygon;
}
/**
* Free memory allocated for a GeoPolygon struct. It is an error to access the struct
* after passing it to this method.
* @private
* @param {number} geoPolygon C pointer to GeoPolygon struct
* @return {void}
*/
function destroyGeoPolygon(geoPolygon) {
// Byte positions within the struct
const geoLoopOffset = 0;
const numHolesOffset = geoLoopOffset + SZ_GEOLOOP;
const holesOffset = numHolesOffset + SZ_INT;
// Offset of the geoLoop vertex array pointer within the GeoLoop struct
const geoLoopArrayOffset = SZ_INT;
// Free the outer vertex array
C._free(C.getValue(geoPolygon + geoLoopOffset + geoLoopArrayOffset, 'i8*'));
// Free the vertex array for the holes, if any
const numHoles = C.getValue(geoPolygon + numHolesOffset, 'i32');
if (numHoles > 0) {
const holes = C.getValue(geoPolygon + holesOffset, 'i32');
for (let i = 0; i < numHoles; i++) {
C._free(C.getValue(holes + SZ_GEOLOOP * i + geoLoopArrayOffset, 'i8*'));
}
C._free(holes);
}
C._free(geoPolygon);
}
/**
* Read an H3 index from a pointer to C memory.
* @private
* @param {number} cAddress Pointer to allocated C memory
* @param {number} offset Offset, in number of H3 indexes, in case we're
* reading an array
* @return {H3Index | null} H3 index, or null if index was invalid
*/
function readH3IndexFromPointer(cAddress, offset = 0) {
const lower = C.getValue(cAddress + SZ_H3INDEX * offset, 'i32');
const upper = C.getValue(cAddress + SZ_H3INDEX * offset + SZ_INT, 'i32');
// The lower bits are allowed to be 0s, but if the upper bits are 0
// this represents an invalid H3 index
return upper ? splitLongToH3Index(lower, upper) : null;
}
/**
* Read a boolean (32 bit) from a pointer to C memory.
* @private
* @param {number} cAddress Pointer to allocated C memory
* @param {number} offset Offset, in number of booleans, in case we're
* reading an array
* @return {Boolean} Boolean value
*/
function readBooleanFromPointer(cAddress, offset = 0) {
const val = C.getValue(cAddress + SZ_INT * offset, 'i32');
return Boolean(val);
}
/**
* Read a double from a pointer to C memory.
* @private
* @param {number} cAddress Pointer to allocated C memory
* @param {number} offset Offset, in number of doubles, in case we're
* reading an array
* @return {number} Double value
*/
function readDoubleFromPointer(cAddress, offset = 0) {
return C.getValue(cAddress + SZ_DBL * offset, 'double');
}
/**
* Read a 64-bit int from a pointer to C memory into a JS 64-bit float.
* Note that this may lose precision if larger than MAX_SAFE_INTEGER
* @private
* @param {number} cAddress Pointer to allocated C memory
* @return {number} Double value
*/
function readInt64AsDoubleFromPointer(cAddress) {
return H3.readInt64AsDoubleFromPointer(cAddress);
}
/**
* Store an H3 index in C memory. Primarily used as an efficient way to
* write sets of hexagons.
* @private
* @param {H3IndexInput} h3Index H3 index to store
* @param {number} cAddress Pointer to allocated C memory
* @param {number} offset Offset, in number of H3 indexes from beginning
* of the current array
*/
function storeH3Index(h3Index, cAddress, offset) {
// HEAPU32 is a typed array projection on the index space
// as unsigned 32-bit integers. This means the index needs
// to be divided by SZ_INT (4) to access correctly. Also,
// the H3 index is 64 bits, so we skip by twos as we're writing
// to 32-bit integers in the proper order.
C.HEAPU32.set(h3IndexToSplitLong(h3Index), cAddress / SZ_INT + 2 * offset);
}
/**
* Read an array of 64-bit H3 indexes from C and convert to a JS array of
* H3 index strings
* @private
* @param {number} cAddress Pointer to C ouput array
* @param {number} maxCount Max number of hexagons in array. Hexagons with
* the value 0 will be skipped, so this isn't
* necessarily the length of the output array.
* @return {H3Index[]} Array of H3 indexes
*/
function readArrayOfH3Indexes(cAddress, maxCount) {
const out = [];
for (let i = 0; i < maxCount; i++) {
const h3Index = readH3IndexFromPointer(cAddress, i);
if (h3Index !== null) {
out.push(h3Index);
}
}
return out;
}
/**
* Store an array of H3 index strings as a C array of 64-bit integers.
* @private
* @param {number} cAddress Pointer to C input array
* @param {H3IndexInput[]} hexagons H3 indexes to pass to the C lib
*/
function storeArrayOfH3Indexes(cAddress, hexagons) {
// Assuming the cAddress points to an already appropriately
// allocated space
const count = hexagons.length;
for (let i = 0; i < count; i++) {
storeH3Index(hexagons[i], cAddress, i);
}
}
/**
* Populate a C-appropriate LatLng struct from a [lat, lng] array
* @private
* @param {number} lat Coordinate latitude
* @param {number} lng Coordinate longitude
* @return {number} C pointer to populated LatLng struct
*/
function storeLatLng(lat, lng) {
const geoCoord = C._calloc(1, SZ_LATLNG);
C.HEAPF64.set([lat, lng].map(degsToRads), geoCoord / SZ_DBL);
return geoCoord;
}
/**
* Read a single lat or lng value
* @private
* @param {number} cAddress Pointer to C value
* @return {number}
*/
function readSingleCoord(cAddress) {
return radsToDegs(C.getValue(cAddress, 'double'));
}
/**
* Read a LatLng from C and return a [lat, lng] pair.
* @private
* @param {number} cAddress Pointer to C struct
* @return {CoordPair} [lat, lng] pair
*/
function readLatLng(cAddress) {
return [readSingleCoord(cAddress), readSingleCoord(cAddress + SZ_DBL)];
}
/**
* Read a LatLng from C and return a GeoJSON-style [lng, lat] pair.
* @private
* @param {number} cAddress Pointer to C struct
* @return {CoordPair} [lng, lat] pair
*/
function readLatLngGeoJson(cAddress) {
return [readSingleCoord(cAddress + SZ_DBL), readSingleCoord(cAddress)];
}
/**
* Read the CellBoundary structure into a list of geo coordinate pairs
* @private
* @param {number} cellBoundary C pointer to CellBoundary struct
* @param {boolean} [geoJsonCoords] Whether to provide GeoJSON coordinate order: [lng, lat]
* @param {boolean} [closedLoop] Whether to close the loop
* @return {CoordPair[]} Array of geo coordinate pairs
*/
function readCellBoundary(cellBoundary, geoJsonCoords, closedLoop) {
const numVerts = C.getValue(cellBoundary, 'i32');
// Note that though numVerts is an int, the coordinate doubles have to be
// aligned to 8 bytes, hence the 8-byte offset here
const vertsPos = cellBoundary + SZ_DBL;
const out = [];
// Support [lng, lat] pairs if GeoJSON is specified
const readCoord = geoJsonCoords ? readLatLngGeoJson : readLatLng;
for (let i = 0; i < numVerts * 2; i += 2) {
out.push(readCoord(vertsPos + SZ_DBL * i));
}
if (closedLoop) {
// Close loop if GeoJSON is specified
out.push(out[0]);
}
return out;
}
/**
* Read the LinkedGeoPolygon structure into a nested array of MultiPolygon coordinates
* @private
* @param {number} polygon C pointer to LinkedGeoPolygon struct
* @param {boolean} [formatAsGeoJson] Whether to provide GeoJSON output: [lng, lat], closed loops
* @return {CoordPair[][][]} MultiPolygon-style output.
*/
function readMultiPolygon(polygon, formatAsGeoJson) {
const output = [];
const readCoord = formatAsGeoJson ? readLatLngGeoJson : readLatLng;
let loops;
let loop;
let coords;
let coord;
// Loop through the linked structure, building the output
while (polygon) {
output.push((loops = []));
// Follow ->first pointer
loop = C.getValue(polygon, 'i8*');
while (loop) {
loops.push((coords = []));
// Follow ->first pointer
coord = C.getValue(loop, 'i8*');
while (coord) {
coords.push(readCoord(coord));
// Follow ->next pointer
coord = C.getValue(coord + SZ_DBL * 2, 'i8*');
}
if (formatAsGeoJson) {
// Close loop if GeoJSON is requested
coords.push(coords[0]);
}
// Follow ->next pointer
loop = C.getValue(loop + SZ_PTR * 2, 'i8*');
}
// Follow ->next pointer
polygon = C.getValue(polygon + SZ_PTR * 2, 'i8*');
}
return output;
}
/**
* Read a CoordIJ from C and return an {i, j} pair.
* @private
* @param {number} cAddress Pointer to C struct
* @return {CoordIJ} {i, j} pair
*/
function readCoordIJ(cAddress) {
return {
i: C.getValue(cAddress, 'i32'),
j: C.getValue(cAddress + SZ_INT, 'i32')
};
}
/**
* Store an {i, j} pair to a C CoordIJ struct.
* @private
* @param {number} cAddress Pointer to C memory
* @param {CoordIJ} ij {i,j} pair to store
* @return {void}
*/
function storeCoordIJ(cAddress, {i, j}) {
C.setValue(cAddress, i, 'i32');
C.setValue(cAddress + SZ_INT, j, 'i32');
}
/**
* Read an array of positive integers array from C. Negative
* values are considered invalid and ignored in output.
* @private
* @param {number} cAddress Pointer to C array
* @param {number} count Length of C array
* @return {number[]} Javascript integer array
*/
function readArrayOfPositiveIntegers(cAddress, count) {
const out = [];
for (let i = 0; i < count; i++) {
const int = C.getValue(cAddress + SZ_INT * i, 'i32');
if (int >= 0) {
out.push(int);
}
}
return out;
}
// ----------------------------------------------------------------------------
// Public API functions: Core
/**
* Whether a given string represents a valid H3 index
* @static
* @param {H3IndexInput} h3Index H3 index to check
* @return {boolean} Whether the index is valid
*/
export function isValidCell(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
return Boolean(H3.isValidCell(lower, upper));
}
/**
* Whether the given H3 index is a pentagon
* @static
* @param {H3IndexInput} h3Index H3 index to check
* @return {boolean} isPentagon
*/
export function isPentagon(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
return Boolean(H3.isPentagon(lower, upper));
}
/**
* Whether the given H3 index is in a Class III resolution (rotated versus
* the icosahedron and subject to shape distortion adding extra points on
* icosahedron edges, making them not true hexagons).
* @static
* @param {H3IndexInput} h3Index H3 index to check
* @return {boolean} isResClassIII
*/
export function isResClassIII(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
return Boolean(H3.isResClassIII(lower, upper));
}
/**
* Get the number of the base cell for a given H3 index
* @static
* @param {H3IndexInput} h3Index H3 index to get the base cell for
* @return {number} Index of the base cell (0-121)
*/
export function getBaseCellNumber(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
return H3.getBaseCellNumber(lower, upper);
}
/**
* Get the indices of all icosahedron faces intersected by a given H3 index
* @static
* @param {H3IndexInput} h3Index H3 index to get faces for
* @return {number[]} Indices (0-19) of all intersected faces
* @throws {H3Error} If input is invalid
*/
export function getIcosahedronFaces(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const countPtr = C._malloc(SZ_INT);
try {
throwIfError(H3.maxFaceCount(lower, upper, countPtr));
const count = C.getValue(countPtr, 'i32');
const faces = C._malloc(SZ_INT * count);
try {
throwIfError(H3.getIcosahedronFaces(lower, upper, faces));
return readArrayOfPositiveIntegers(faces, count);
} finally {
C._free(faces);
}
} finally {
C._free(countPtr);
}
}
/**
* Returns the resolution of an H3 index
* @static
* @param {H3IndexInput} h3Index H3 index to get resolution
* @return {number} The number (0-15) resolution, or -1 if invalid
*/
export function getResolution(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
if (!H3.isValidCell(lower, upper)) {
// Compatability with stated API
return -1;
}
return H3.getResolution(lower, upper);
}
/**
* Get the hexagon containing a lat,lon point
* @static
* @param {number} lat Latitude of point
* @param {number} lng Longtitude of point
* @param {number} res Resolution of hexagons to return
* @return {H3Index} H3 index
* @throws {H3Error} If input is invalid
*/
export function latLngToCell(lat, lng, res) {
const latLng = C._malloc(SZ_LATLNG);
// Slightly more efficient way to set the memory
C.HEAPF64.set([lat, lng].map(degsToRads), latLng / SZ_DBL);
// Read value as a split long
const h3Index = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.latLngToCell(latLng, res, h3Index));
return validateH3Index(readH3IndexFromPointer(h3Index));
} finally {
C._free(h3Index);
C._free(latLng);
}
}
/**
* Get the lat,lon center of a given hexagon
* @static
* @param {H3IndexInput} h3Index H3 index
* @return {CoordPair} Point as a [lat, lng] pair
* @throws {H3Error} If input is invalid
*/
export function cellToLatLng(h3Index) {
const latLng = C._malloc(SZ_LATLNG);
const [lower, upper] = h3IndexToSplitLong(h3Index);
try {
throwIfError(H3.cellToLatLng(lower, upper, latLng));
return readLatLng(latLng);
} finally {
C._free(latLng);
}
}
/**
* Get the vertices of a given hexagon (or pentagon), as an array of [lat, lng]
* points. For pentagons and hexagons on the edge of an icosahedron face, this
* function may return up to 10 vertices.
* @static
* @param {H3IndexInput} h3Index H3 index
* @param {boolean} [formatAsGeoJson] Whether to provide GeoJSON output: [lng, lat], closed loops
* @return {CoordPair[]} Array of [lat, lng] pairs
* @throws {H3Error} If input is invalid
*/
export function cellToBoundary(h3Index, formatAsGeoJson) {
const cellBoundary = C._malloc(SZ_CELLBOUNDARY);
const [lower, upper] = h3IndexToSplitLong(h3Index);
try {
throwIfError(H3.cellToBoundary(lower, upper, cellBoundary));
return readCellBoundary(cellBoundary, formatAsGeoJson, formatAsGeoJson);
} finally {
C._free(cellBoundary);
}
}
// ----------------------------------------------------------------------------
// Public API functions: Algorithms
/**
* Get the parent of the given hexagon at a particular resolution
* @static
* @param {H3IndexInput} h3Index H3 index to get parent for
* @param {number} res Resolution of hexagon to return
* @return {H3Index} H3 index of parent, or null for invalid input
* @throws {H3Error} If input is invalid
*/
export function cellToParent(h3Index, res) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const parent = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.cellToParent(lower, upper, res, parent));
return validateH3Index(readH3IndexFromPointer(parent));
} finally {
C._free(parent);
}
}
/**
* Get the children/descendents of the given hexagon at a particular resolution
* @static
* @param {H3IndexInput} h3Index H3 index to get children for
* @param {number} res Resolution of hexagons to return
* @return {H3Index[]} H3 indexes of children, or empty array for invalid input
* @throws {H3Error} If resolution is invalid or output is too large for JS
*/
export function cellToChildren(h3Index, res) {
// Bad input in this case can potentially result in high computation volume
// using the current C algorithm. Validate and return an empty array on failure.
if (!isValidCell(h3Index)) {
return [];
}
const [lower, upper] = h3IndexToSplitLong(h3Index);
const count = validateArrayLength(cellToChildrenSize(h3Index, res));
const hexagons = C._calloc(count, SZ_H3INDEX);
try {
throwIfError(H3.cellToChildren(lower, upper, res, hexagons));
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
}
/**
* Get the number of children for a cell at a given resolution
* @static
* @param {H3IndexInput} h3Index H3 index to get child count for
* @param {number} res Child resolution
* @return {number} Number of children at res for the given cell
* @throws {H3Error} If cell or parentRes are invalid
*/
export function cellToChildrenSize(h3Index, res) {
if (!isValidCell(h3Index)) {
throw H3LibraryError(E_CELL_INVALID);
}
const [lower, upper] = h3IndexToSplitLong(h3Index);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.cellToChildrenSize(lower, upper, res, countPtr));
return readInt64AsDoubleFromPointer(countPtr);
} finally {
C._free(countPtr);
}
}
/**
* Get the center child of the given hexagon at a particular resolution
* @static
* @param {H3IndexInput} h3Index H3 index to get center child for
* @param {number} res Resolution of cell to return
* @return {H3Index} H3 index of child, or null for invalid input
* @throws {H3Error} If resolution is invalid
*/
export function cellToCenterChild(h3Index, res) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const centerChild = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.cellToCenterChild(lower, upper, res, centerChild));
return validateH3Index(readH3IndexFromPointer(centerChild));
} finally {
C._free(centerChild);
}
}
/**
* Get the position of the cell within an ordered list of all children of the
* cell's parent at the specified resolution.
* @static
* @param {H3IndexInput} h3Index H3 index to get child pos for
* @param {number} parentRes Resolution of reference parent
* @return {number} Position of child within parent at parentRes
* @throws {H3Error} If cell or parentRes are invalid
*/
export function cellToChildPos(h3Index, parentRes) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const childPos = C._malloc(SZ_INT64);
try {
throwIfError(H3.cellToChildPos(lower, upper, parentRes, childPos));
return readInt64AsDoubleFromPointer(childPos);
} finally {
C._free(childPos);
}
}
/**
* Get the child cell at a given position within an ordered list of all children
* at the specified resolution
* @static
* @param {number} childPos Position of the child cell to get
* @param {H3IndexInput} h3Index H3 index of the parent cell
* @param {number} childRes Resolution of child cell to return
* @return {H3Index} H3 index of child
* @throws {H3Error} If input is invalid
*/
export function childPosToCell(childPos, h3Index, childRes) {
const [cpLower, cpUpper] = numberToSplitLong(childPos);
const [lower, upper] = h3IndexToSplitLong(h3Index);
const child = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.childPosToCell(cpLower, cpUpper, lower, upper, childRes, child));
return validateH3Index(readH3IndexFromPointer(child));
} finally {
C._free(child);
}
}
/**
* Get all hexagons in a k-ring around a given center. The order of the hexagons is undefined.
* @static
* @param {H3IndexInput} h3Index H3 index of center hexagon
* @param {number} ringSize Radius of k-ring
* @return {H3Index[]} H3 indexes for all hexagons in ring
* @throws {H3Error} If input is invalid or output is too large for JS
*/
export function gridDisk(h3Index, ringSize) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.maxGridDiskSize(ringSize, countPtr));
const count = validateArrayLength(readInt64AsDoubleFromPointer(countPtr));
const hexagons = C._calloc(count, SZ_H3INDEX);
try {
throwIfError(H3.gridDisk(lower, upper, ringSize, hexagons));
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
} finally {
C._free(countPtr);
}
}
/**
* Get all hexagons in a k-ring around a given center, in an array of arrays
* ordered by distance from the origin. The order of the hexagons within each ring is undefined.
* @static
* @param {H3IndexInput} h3Index H3 index of center hexagon
* @param {number} ringSize Radius of k-ring
* @return {H3Index[][]} Array of arrays with H3 indexes for all hexagons each ring
* @throws {H3Error} If input is invalid or output is too large for JS
*/
export function gridDiskDistances(h3Index, ringSize) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.maxGridDiskSize(ringSize, countPtr));
const count = validateArrayLength(readInt64AsDoubleFromPointer(countPtr));
const kRings = C._calloc(count, SZ_H3INDEX);
const distances = C._calloc(count, SZ_INT);
try {
throwIfError(H3.gridDiskDistances(lower, upper, ringSize, kRings, distances));
/**
* An array of empty arrays to hold the output
* @type {string[][]}
* @private
*/
const out = [];
for (let i = 0; i < ringSize + 1; i++) {
out.push([]);
}
// Read the array of hexagons, putting them into the appropriate rings
for (let i = 0; i < count; i++) {
const cell = readH3IndexFromPointer(kRings, i);
const index = C.getValue(distances + SZ_INT * i, 'i32');
// eslint-disable-next-line max-depth
if (cell !== null) {
out[index].push(cell);
}
}
return out;
} finally {
C._free(kRings);
C._free(distances);
}
} finally {