Skip to content

Commit

Permalink
Fixed TileId.toTileId() on dart2js platforms.
Browse files Browse the repository at this point in the history
  • Loading branch information
bramp committed Feb 1, 2024
1 parent a6d30c5 commit 0996741
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
22 changes: 18 additions & 4 deletions packages/pmtiles/lib/src/zxy.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:math';

import 'package:meta/meta.dart';

/// Convert from Tile ID to ZXY and back.
Expand Down Expand Up @@ -52,10 +54,22 @@ class ZXY {
}

int toTileId() {
// https://oeis.org/A002450 for the formula, but it's basically
// for (int i = 0; i < z; i++) { tilesOnPreviousLayers += 1 << (i * 2); }
final tilesOnPreviousLayers =
((1 << (z * 2)) - 1) ~/ 3; // (pow(4, z) - 1) ~/ 3;
// The tile ID is effectively the sum of all possible tiles on previous
// layers, and the value of the tile on this layer (as mapped by a Hilbert
// curve). e.g
//
// for (int i = 0; i < z; i++) {
// tilesOnPreviousLayers += 1 << (i * 2);
// }
//
// However that loop can be removed by using the following formula from
// https://oeis.org/A002450.
final tilesOnPreviousLayers = (pow(4, z) - 1) ~/ 3;

// We could also replace the `pow(4, z)` with `1 << (z * 2)` but bit
// operations are truncated to 32 bits in dart2js.
// See https://github.com/dart-lang/sdk/issues/8298

return tilesOnPreviousLayers + _Hilbert.inverse(1 << z, x, y);
}

Expand Down
5 changes: 3 additions & 2 deletions packages/pmtiles/test/zxy_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,15 @@ void main() {
test('fromTileId', () {
for (final entry in tests.entries) {
final zxy = ZXY.fromTileId(entry.value);
expect(zxy, equals(entry.key));
expect(zxy, equals(entry.key),
reason: "ZXY.fromTileId(${entry.value})");
}
});

test('toTileId', () {
for (final entry in tests.entries) {
final tileId = entry.key.toTileId();
expect(tileId, equals(entry.value));
expect(tileId, equals(entry.value), reason: "${entry.key}.toTileId()");
}
});
});
Expand Down

0 comments on commit 0996741

Please sign in to comment.