diff --git a/include/tile_coordinates_set.h b/include/tile_coordinates_set.h index 3d45c50e..76285ae2 100644 --- a/include/tile_coordinates_set.h +++ b/include/tile_coordinates_set.h @@ -50,6 +50,7 @@ class LossyTileCoordinatesSet : public TileCoordinatesSet { size_t size() const override; size_t zoom() const override; void set(TileCoordinate x, TileCoordinate y) override; + void forEachSet(const std::function& f) const override; private: unsigned int zoom_; diff --git a/src/tile_coordinates_set.cpp b/src/tile_coordinates_set.cpp index e6d6e78e..8f8c69ac 100644 --- a/src/tile_coordinates_set.cpp +++ b/src/tile_coordinates_set.cpp @@ -134,3 +134,24 @@ void LossyTileCoordinatesSet::set(TileCoordinate x, TileCoordinate y) { throw std::logic_error("LossyTileCoordinatesSet::set() is not implemented; LossyTileCoordinatesSet is read-only"); } +void LossyTileCoordinatesSet::forEachSet(const std::function& f) const { + // Expand the underlying set instead of testing all 4^zoom tiles (2^34 at z17). + // Its tiles arrive x-major, y-minor; one column of them becomes `scale` + // columns here, which keeps this set's order x-major, y-minor too. + std::vector column; + TileCoordinate columnX = 0; + auto flush = [&]() { + for (TileCoordinate dx = 0; dx < scale; dx++) + for (TileCoordinate y : column) + for (TileCoordinate dy = 0; dy < scale; dy++) + f(columnX * scale + dx, y * scale + dy); + column.clear(); + }; + tiles.forEachSet([&](TileCoordinate x, TileCoordinate y) { + if (!column.empty() && x != columnX) flush(); + columnX = x; + column.push_back(y); + }); + if (!column.empty()) flush(); +} + diff --git a/test/tile_coordinates_set.test.cpp b/test/tile_coordinates_set.test.cpp index 87a054b8..d0a00338 100644 --- a/test/tile_coordinates_set.test.cpp +++ b/test/tile_coordinates_set.test.cpp @@ -45,6 +45,22 @@ MU_TEST(test_tile_coordinates_set) { mu_check(z2.test(1, 1) == true); mu_check(z2.test(2, 2) == false); } + + // forEachSet on a wrapped set visits the same tiles as a full scan, in x-major, y-minor order + { + PreciseTileCoordinatesSet z3(3); + z3.set(0, 0); z3.set(0, 5); z3.set(2, 1); z3.set(2, 7); z3.set(7, 3); + LossyTileCoordinatesSet z5(5, z3); + + std::vector> expected, visited; + for (TileCoordinate x = 0; x < 32; x++) + for (TileCoordinate y = 0; y < 32; y++) + if (z5.test(x, y)) expected.push_back({x, y}); + z5.forEachSet([&](TileCoordinate x, TileCoordinate y) { visited.push_back({x, y}); }); + + mu_check(expected.size() == 5 * 16); + mu_check(visited == expected); + } } MU_TEST_SUITE(test_suite_tile_coordinates_set) {