From cea3a2edb59407bc59bd289ba3b685621396bde1 Mon Sep 17 00:00:00 2001 From: mwilsnd Date: Fri, 14 Apr 2023 12:14:17 -0500 Subject: [PATCH 01/11] Add clang-format --- .clang-format | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000000..e2b3dd39491 --- /dev/null +++ b/.clang-format @@ -0,0 +1,15 @@ +--- +BasedOnStyle: Chromium +ColumnLimit: '100' +FixNamespaceComments: 'true' +IncludeBlocks: Preserve +IndentWidth: '4' +KeepEmptyLinesAtTheStartOfBlocks: 'false' +Language: Cpp +NamespaceIndentation: None +PointerAlignment: Left +ReflowComments: 'true' +SortIncludes: 'true' +TabWidth: '4' + +... From 26a6dd2e8e4f22cd4f103cf56c604a05827536e2 Mon Sep 17 00:00:00 2001 From: mwilsnd Date: Fri, 14 Apr 2023 12:14:17 -0500 Subject: [PATCH 02/11] Use mapbox's rules --- .clang-format | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/.clang-format b/.clang-format index e2b3dd39491..956884c1b67 100644 --- a/.clang-format +++ b/.clang-format @@ -1,15 +1,11 @@ --- -BasedOnStyle: Chromium -ColumnLimit: '100' -FixNamespaceComments: 'true' -IncludeBlocks: Preserve -IndentWidth: '4' -KeepEmptyLinesAtTheStartOfBlocks: 'false' Language: Cpp -NamespaceIndentation: None -PointerAlignment: Left -ReflowComments: 'true' -SortIncludes: 'true' -TabWidth: '4' - +BasedOnStyle: Google +AccessModifierOffset: -4 +AllowShortFunctionsOnASingleLine: Inline +BinPackArguments: false +BinPackParameters: false +ColumnLimit: 120 +IndentWidth: 4 +SpacesBeforeTrailingComments: 1 ... From 2cdb28b6b6961cedd3ebe31bf4a9aa8895cccf54 Mon Sep 17 00:00:00 2001 From: mwilsnd Date: Fri, 14 Apr 2023 12:14:17 -0500 Subject: [PATCH 03/11] Don't rearrange includes --- .clang-format | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.clang-format b/.clang-format index 956884c1b67..f5b35e58f76 100644 --- a/.clang-format +++ b/.clang-format @@ -7,5 +7,7 @@ BinPackArguments: false BinPackParameters: false ColumnLimit: 120 IndentWidth: 4 +IncludeBlocks: Preserve +SortIncludes: false SpacesBeforeTrailingComments: 1 ... From a9c61a51616551b91e2d71f86fca26fac0e92610 Mon Sep 17 00:00:00 2001 From: Bart Louwers Date: Sat, 22 Apr 2023 21:33:54 +0200 Subject: [PATCH 04/11] Add pre-commit config --- .pre-commit-config.yaml | 7 +++++++ DEVELOPING.md | 15 +++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000000..5887c742e71 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,7 @@ +repos: +- repo: https://github.com/pre-commit/mirrors-clang-format + rev: v14.0.6 + hooks: + - id: clang-format + files: '.*\.(hpp|cpp|h)' + exclude: '(vendor/.*|platform/(ios|darwin)/.*|test/ios/.*|render-test/ios/.*|benchmark/ios/.*)' diff --git a/DEVELOPING.md b/DEVELOPING.md index a92594ba23a..b1cdb2816c5 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -1,5 +1,16 @@ # Developing + +## Pre-commit hooks + +Install [pre-commit](https://pre-commit.com/) and run + +``` +pre-commit install +``` + +to install the pre-commit hooks configured in `.pre-commit-config.yml`. + ## Render Tests To check that the output of the rendering is correct, we compare actual rendered PNGs for simple styles with expected PNGs. The content of the tests is stored in the MapLibre GL JS submodule which means that GL JS and Native are in fact quasi pixel-identical in their rendering. @@ -76,6 +87,7 @@ or any of the platform make files: * iOS developers can use [Xcode](https://developer.apple.com/support/debugging/). See also [Advanced Debugging with Xcode and LLDB](https://developer.apple.com/videos/play/wwdc2018/412/). ## Static Analysis + We use [`clang-tidy`](https://clang.llvm.org/extra/clang-tidy/) for static analysis and run it on CI for each pull request. If you want to run it locally use `-DMLN_WITH_CLANG_TIDY=ON` CMake option and just run regular build. For the list of enabled checks please see: [`.clang-tidy`](.clang-tidy) and [`test/.clang-tidy`](test/.clang-tidy)(for tests we are less strict and use different set of checks). @@ -166,3 +178,6 @@ autoload -Uz compinit && compinit ### Kotlin and Java compatibility We are moving the Android SDK to Kotlin, which is backward compatible with Java, but if you need a Java version of the Android SDK there is a `before-kotlin-port` tag available. + + + From 38d37664ce092dc1d95adf38ba536ec4d141e01d Mon Sep 17 00:00:00 2001 From: Bart Louwers Date: Sun, 23 Apr 2023 00:04:59 +0200 Subject: [PATCH 05/11] Update DEVELOPING.md --- DEVELOPING.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/DEVELOPING.md b/DEVELOPING.md index b1cdb2816c5..9ea6e560c32 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -11,6 +11,10 @@ pre-commit install to install the pre-commit hooks configured in `.pre-commit-config.yml`. +## Static Analysis +We use [`clang-tidy`](https://clang.llvm.org/extra/clang-tidy/) for static analysis and run it on CI for each pull request. If you want to run it locally use `-DMBGL_WITH_CLANG_TIDY=ON` CMake option and just run regular build. For the list of enabled checks please see: + [`.clang-tidy`](.clang-tidy) and [`test/.clang-tidy`](test/.clang-tidy)(for tests we are less strict and use different set of checks). + ## Render Tests To check that the output of the rendering is correct, we compare actual rendered PNGs for simple styles with expected PNGs. The content of the tests is stored in the MapLibre GL JS submodule which means that GL JS and Native are in fact quasi pixel-identical in their rendering. From 6aa2f929459b1fc7d8500895a280de0f04eb1b38 Mon Sep 17 00:00:00 2001 From: Bart Louwers Date: Sat, 29 Apr 2023 15:07:13 +0200 Subject: [PATCH 06/11] Run clang-format with tweaked config --- .clang-format | 10 +- benchmark/api/query.benchmark.cpp | 23 +- benchmark/api/render.benchmark.cpp | 72 +- .../function/camera_function.benchmark.cpp | 24 +- .../function/composite_function.benchmark.cpp | 24 +- .../function/source_function.benchmark.cpp | 22 +- benchmark/parse/filter.benchmark.cpp | 2 +- benchmark/parse/tile_mask.benchmark.cpp | 21 +- benchmark/parse/vector_tile.benchmark.cpp | 3 +- .../benchmark/stub_geometry_tile_feature.hpp | 22 +- .../storage/offline_database.benchmark.cpp | 42 +- benchmark/util/tilecover.benchmark.cpp | 46 +- bin/cache.cpp | 38 +- bin/offline.cpp | 133 +- bin/render.cpp | 37 +- expression-test/expression_test_logger.cpp | 26 +- expression-test/expression_test_logger.hpp | 8 +- expression-test/expression_test_parser.cpp | 86 +- expression-test/expression_test_parser.hpp | 29 +- expression-test/expression_test_runner.cpp | 53 +- expression-test/expression_test_runner.hpp | 6 +- expression-test/main.cpp | 30 +- expression-test/test_runner_common.cpp | 8 +- include/mbgl/actor/actor.hpp | 7 +- include/mbgl/actor/actor_ref.hpp | 9 +- include/mbgl/actor/aspiring_actor.hpp | 25 +- include/mbgl/actor/established_actor.hpp | 39 +- include/mbgl/actor/mailbox.hpp | 5 +- include/mbgl/actor/message.hpp | 35 +- include/mbgl/actor/scheduler.hpp | 13 +- include/mbgl/annotation/annotation.hpp | 36 +- include/mbgl/gfx/backend.hpp | 10 +- include/mbgl/gfx/renderable.hpp | 8 +- include/mbgl/gfx/renderer_backend.hpp | 4 +- include/mbgl/gfx/shader.hpp | 44 +- include/mbgl/gfx/shader_registry.hpp | 237 +-- include/mbgl/gl/custom_layer.hpp | 7 +- include/mbgl/gl/custom_layer_factory.hpp | 4 +- include/mbgl/gl/renderer_backend.hpp | 3 +- include/mbgl/i18n/collator.hpp | 4 +- include/mbgl/i18n/number_format.hpp | 12 +- .../layermanager/background_layer_factory.hpp | 4 +- .../layermanager/circle_layer_factory.hpp | 12 +- .../fill_extrusion_layer_factory.hpp | 8 +- .../mbgl/layermanager/fill_layer_factory.hpp | 8 +- .../layermanager/heatmap_layer_factory.hpp | 7 +- .../layermanager/hillshade_layer_factory.hpp | 4 +- include/mbgl/layermanager/layer_factory.hpp | 20 +- include/mbgl/layermanager/layer_manager.hpp | 37 +- .../mbgl/layermanager/line_layer_factory.hpp | 12 +- .../location_indicator_layer_factory.hpp | 5 +- .../layermanager/raster_layer_factory.hpp | 4 +- .../layermanager/symbol_layer_factory.hpp | 12 +- include/mbgl/map/bound_options.hpp | 17 +- include/mbgl/map/camera.hpp | 38 +- include/mbgl/map/map.hpp | 48 +- include/mbgl/map/map_observer.hpp | 2 +- include/mbgl/map/map_options.hpp | 2 +- include/mbgl/map/mode.hpp | 12 +- include/mbgl/map/projection_mode.hpp | 17 +- include/mbgl/math/log2.hpp | 3 +- include/mbgl/platform/gl_functions.hpp | 511 ++--- include/mbgl/renderer/query.hpp | 12 +- include/mbgl/renderer/renderer.hpp | 53 +- include/mbgl/renderer/renderer_frontend.hpp | 1 - include/mbgl/renderer/renderer_observer.hpp | 2 +- include/mbgl/renderer/renderer_state.hpp | 1 - include/mbgl/shaders/gl/background.hpp | 3 +- .../mbgl/shaders/gl/background_pattern.hpp | 3 +- include/mbgl/shaders/gl/circle.hpp | 3 +- include/mbgl/shaders/gl/clipping_mask.hpp | 3 +- include/mbgl/shaders/gl/collision_box.hpp | 3 +- include/mbgl/shaders/gl/collision_circle.hpp | 3 +- include/mbgl/shaders/gl/debug.hpp | 3 +- include/mbgl/shaders/gl/fill.hpp | 3 +- include/mbgl/shaders/gl/fill_extrusion.hpp | 3 +- .../shaders/gl/fill_extrusion_pattern.hpp | 3 +- include/mbgl/shaders/gl/fill_outline.hpp | 3 +- .../mbgl/shaders/gl/fill_outline_pattern.hpp | 3 +- include/mbgl/shaders/gl/fill_pattern.hpp | 3 +- include/mbgl/shaders/gl/heatmap.hpp | 3 +- include/mbgl/shaders/gl/heatmap_texture.hpp | 3 +- include/mbgl/shaders/gl/hillshade.hpp | 3 +- include/mbgl/shaders/gl/hillshade_prepare.hpp | 3 +- include/mbgl/shaders/gl/line.hpp | 3 +- include/mbgl/shaders/gl/line_gradient.hpp | 3 +- include/mbgl/shaders/gl/line_pattern.hpp | 3 +- include/mbgl/shaders/gl/line_sdf.hpp | 3 +- include/mbgl/shaders/gl/prelude.hpp | 3 +- include/mbgl/shaders/gl/raster.hpp | 3 +- include/mbgl/shaders/gl/symbol_icon.hpp | 3 +- include/mbgl/shaders/gl/symbol_sdf_icon.hpp | 3 +- include/mbgl/shaders/gl/symbol_sdf_text.hpp | 3 +- .../mbgl/shaders/gl/symbol_text_and_icon.hpp | 3 +- include/mbgl/shaders/shader_source.hpp | 6 +- include/mbgl/storage/database_file_source.hpp | 19 +- include/mbgl/storage/file_source.hpp | 2 +- include/mbgl/storage/file_source_manager.hpp | 4 +- include/mbgl/storage/offline.hpp | 12 +- include/mbgl/storage/resource.hpp | 54 +- include/mbgl/storage/resource_options.hpp | 3 +- include/mbgl/storage/response.hpp | 8 +- .../mbgl/style/color_ramp_property_value.hpp | 11 +- include/mbgl/style/conversion.hpp | 5 +- .../conversion/color_ramp_property_value.hpp | 7 +- include/mbgl/style/conversion/coordinate.hpp | 6 +- include/mbgl/style/conversion/function.hpp | 8 +- .../mbgl/style/conversion/property_value.hpp | 19 +- include/mbgl/style/conversion/source.hpp | 3 +- include/mbgl/style/conversion_impl.hpp | 134 +- include/mbgl/style/expression/assertion.hpp | 6 +- include/mbgl/style/expression/at.hpp | 19 +- .../style/expression/boolean_operator.hpp | 20 +- include/mbgl/style/expression/case.hpp | 7 +- include/mbgl/style/expression/coalesce.hpp | 23 +- include/mbgl/style/expression/coercion.hpp | 8 +- include/mbgl/style/expression/collator.hpp | 1 + .../style/expression/collator_expression.hpp | 11 +- include/mbgl/style/expression/comparison.hpp | 10 +- .../style/expression/compound_expression.hpp | 12 +- include/mbgl/style/expression/distance.hpp | 4 +- include/mbgl/style/expression/dsl.hpp | 74 +- include/mbgl/style/expression/error.hpp | 14 +- include/mbgl/style/expression/expression.hpp | 147 +- .../style/expression/format_expression.hpp | 25 +- .../expression/format_section_override.hpp | 58 +- include/mbgl/style/expression/formatted.hpp | 30 +- include/mbgl/style/expression/interpolate.hpp | 37 +- .../mbgl/style/expression/interpolator.hpp | 50 +- include/mbgl/style/expression/let.hpp | 28 +- include/mbgl/style/expression/literal.hpp | 25 +- include/mbgl/style/expression/match.hpp | 13 +- .../mbgl/style/expression/number_format.hpp | 12 +- .../mbgl/style/expression/parsing_context.hpp | 77 +- include/mbgl/style/expression/step.hpp | 8 +- include/mbgl/style/expression/type.hpp | 48 +- include/mbgl/style/expression/value.hpp | 52 +- include/mbgl/style/filter.hpp | 19 +- include/mbgl/style/image.hpp | 33 +- include/mbgl/style/layer.hpp | 46 +- include/mbgl/style/layer_properties.hpp | 7 +- include/mbgl/style/position.hpp | 11 +- include/mbgl/style/property_expression.hpp | 88 +- include/mbgl/style/property_value.hpp | 47 +- include/mbgl/style/rotation.hpp | 3 +- .../style/sources/custom_geometry_source.hpp | 9 +- include/mbgl/style/sources/geojson_source.hpp | 19 +- include/mbgl/style/sources/image_source.hpp | 6 +- include/mbgl/style/sources/raster_source.hpp | 13 +- include/mbgl/style/sources/vector_source.hpp | 14 +- include/mbgl/style/style.hpp | 10 +- include/mbgl/style/style_property.hpp | 11 +- include/mbgl/style/transition_options.hpp | 18 +- include/mbgl/style/types.hpp | 4 +- include/mbgl/style/undefined.hpp | 8 +- include/mbgl/tile/tile_id.hpp | 83 +- include/mbgl/util/bitmask_operations.hpp | 9 +- include/mbgl/util/char_array_buffer.hpp | 26 +- include/mbgl/util/chrono.hpp | 18 +- include/mbgl/util/color.hpp | 22 +- include/mbgl/util/compression.hpp | 7 +- include/mbgl/util/constants.hpp | 8 +- include/mbgl/util/convert.hpp | 7 +- include/mbgl/util/default_style.hpp | 2 +- include/mbgl/util/enum.hpp | 39 +- include/mbgl/util/event.hpp | 4 +- include/mbgl/util/exception.hpp | 36 +- include/mbgl/util/feature.hpp | 28 +- include/mbgl/util/geo.hpp | 84 +- include/mbgl/util/geometry.hpp | 34 +- include/mbgl/util/ignore.hpp | 6 +- include/mbgl/util/image.hpp | 61 +- include/mbgl/util/immutable.hpp | 27 +- include/mbgl/util/indexed_tuple.hpp | 20 +- include/mbgl/util/interpolate.hpp | 61 +- include/mbgl/util/logging.hpp | 51 +- include/mbgl/util/noncopyable.hpp | 13 +- include/mbgl/util/platform.hpp | 2 +- include/mbgl/util/projection.hpp | 41 +- include/mbgl/util/range.hpp | 3 +- include/mbgl/util/run_loop.hpp | 14 +- include/mbgl/util/size.hpp | 23 +- include/mbgl/util/string.hpp | 5 +- include/mbgl/util/thread.hpp | 14 +- include/mbgl/util/tile_server_options.hpp | 559 ++--- include/mbgl/util/tileset.hpp | 30 +- include/mbgl/util/traits.hpp | 27 +- include/mbgl/util/unitbezier.hpp | 49 +- include/mbgl/util/work_task_impl.hpp | 12 +- .../src/cpp/android_renderer_backend.cpp | 11 +- .../src/cpp/android_renderer_backend.hpp | 4 +- .../src/cpp/android_renderer_frontend.cpp | 84 +- .../src/cpp/android_renderer_frontend.hpp | 15 +- .../src/cpp/annotation/marker.hpp | 3 - .../src/cpp/annotation/multi_point.hpp | 24 +- .../src/cpp/annotation/polygon.cpp | 6 +- .../src/cpp/annotation/polygon.hpp | 1 - .../src/cpp/annotation/polyline.cpp | 4 +- .../src/cpp/annotation/polyline.hpp | 1 - .../src/cpp/asset_manager.hpp | 4 +- .../src/cpp/asset_manager_file_source.cpp | 50 +- .../src/cpp/asset_manager_file_source.hpp | 7 +- .../src/cpp/connectivity_listener.cpp | 56 +- .../src/cpp/connectivity_listener.hpp | 2 - .../src/cpp/conversion/collection.cpp | 6 +- .../src/cpp/conversion/collection.hpp | 6 +- .../src/cpp/conversion/color.cpp | 6 +- .../src/cpp/conversion/color.hpp | 2 +- .../src/cpp/conversion/constant.cpp | 45 +- .../src/cpp/conversion/constant.hpp | 2 +- .../src/cpp/conversion/conversion.hpp | 12 +- .../src/cpp/file_source.cpp | 156 +- .../src/cpp/file_source.hpp | 25 +- .../src/cpp/geojson/feature.cpp | 50 +- .../src/cpp/geojson/feature_collection.cpp | 10 +- .../src/cpp/geojson/geometry.cpp | 39 +- .../src/cpp/geojson/geometry_collection.cpp | 16 +- .../src/cpp/geojson/geometry_collection.hpp | 3 +- .../src/cpp/geojson/line_string.cpp | 18 +- .../src/cpp/geojson/line_string.hpp | 3 +- .../src/cpp/geojson/multi_line_string.cpp | 24 +- .../src/cpp/geojson/multi_line_string.hpp | 3 +- .../src/cpp/geojson/multi_point.cpp | 15 +- .../src/cpp/geojson/multi_polygon.cpp | 12 +- .../src/cpp/geojson/point.cpp | 15 +- .../src/cpp/geojson/polygon.cpp | 17 +- .../src/cpp/geojson/polygon.hpp | 10 +- .../src/cpp/geojson/util.hpp | 10 +- .../src/cpp/geometry/lat_lng.hpp | 3 - .../src/cpp/geometry/lat_lng_bounds.cpp | 4 +- .../src/cpp/geometry/lat_lng_bounds.hpp | 2 - .../src/cpp/geometry/lat_lng_quad.cpp | 30 +- .../src/cpp/geometry/lat_lng_quad.hpp | 2 - .../src/cpp/graphics/pointf.hpp | 2 - .../src/cpp/graphics/rectf.hpp | 2 - .../src/cpp/gson/json_array.cpp | 10 +- .../src/cpp/gson/json_element.cpp | 48 +- .../src/cpp/gson/json_object.cpp | 26 +- .../src/cpp/http_file_source.cpp | 86 +- .../src/cpp/i18n/collator.cpp | 49 +- .../src/cpp/i18n/collator_jni.hpp | 4 - .../src/cpp/i18n/number_format.cpp | 42 +- .../MapboxGLAndroidSDK/src/cpp/java/util.hpp | 12 +- .../MapboxGLAndroidSDK/src/cpp/java_types.cpp | 62 +- .../MapboxGLAndroidSDK/src/cpp/java_types.hpp | 70 +- .../MapboxGLAndroidSDK/src/cpp/jni_native.cpp | 4 +- .../MapboxGLAndroidSDK/src/cpp/logger.cpp | 4 +- .../MapboxGLAndroidSDK/src/cpp/logger.hpp | 8 +- .../src/cpp/logging_android.cpp | 4 +- .../src/cpp/map/camera_position.cpp | 41 +- .../MapboxGLAndroidSDK/src/cpp/map/image.cpp | 35 +- .../src/cpp/map_renderer.cpp | 63 +- .../src/cpp/map_renderer.hpp | 15 +- .../src/cpp/map_renderer_runnable.cpp | 15 +- .../src/cpp/map_renderer_runnable.hpp | 5 +- .../src/cpp/native_map_view.cpp | 425 ++-- .../src/cpp/native_map_view.hpp | 81 +- .../src/cpp/offline/offline_manager.cpp | 254 ++- .../src/cpp/offline/offline_manager.hpp | 93 +- .../src/cpp/offline/offline_region.cpp | 266 ++- .../src/cpp/offline/offline_region.hpp | 33 +- .../cpp/offline/offline_region_definition.cpp | 65 +- .../cpp/offline/offline_region_definition.hpp | 16 +- .../src/cpp/offline/offline_region_error.cpp | 9 +- .../src/cpp/offline/offline_region_status.cpp | 11 +- .../src/cpp/snapshotter/map_snapshot.cpp | 51 +- .../src/cpp/snapshotter/map_snapshot.hpp | 21 +- .../src/cpp/snapshotter/map_snapshotter.cpp | 155 +- .../src/cpp/snapshotter/map_snapshotter.hpp | 31 +- .../src/cpp/style/android_conversion.hpp | 35 +- .../src/cpp/style/conversion/filter.cpp | 12 +- .../src/cpp/style/conversion/position.cpp | 17 +- .../src/cpp/style/conversion/position.hpp | 6 +- .../style/conversion/property_expression.hpp | 4 +- .../cpp/style/conversion/property_value.hpp | 6 +- .../style/conversion/transition_options.cpp | 16 +- .../style/conversion/transition_options.hpp | 11 +- .../cpp/style/conversion/url_or_tileset.cpp | 8 +- .../cpp/style/conversion/url_or_tileset.hpp | 2 +- .../src/cpp/style/formatted.cpp | 6 +- .../src/cpp/style/formatted.hpp | 19 +- .../src/cpp/style/layers/background_layer.cpp | 266 +-- .../src/cpp/style/layers/background_layer.hpp | 4 +- .../src/cpp/style/layers/circle_layer.cpp | 525 ++--- .../src/cpp/style/layers/circle_layer.hpp | 4 +- .../src/cpp/style/layers/custom_layer.cpp | 105 +- .../src/cpp/style/layers/custom_layer.hpp | 4 +- .../cpp/style/layers/fill_extrusion_layer.cpp | 422 ++-- .../cpp/style/layers/fill_extrusion_layer.hpp | 4 +- .../src/cpp/style/layers/fill_layer.cpp | 386 ++-- .../src/cpp/style/layers/fill_layer.hpp | 4 +- .../src/cpp/style/layers/heatmap_layer.cpp | 300 +-- .../src/cpp/style/layers/heatmap_layer.hpp | 4 +- .../src/cpp/style/layers/hillshade_layer.cpp | 337 ++-- .../src/cpp/style/layers/hillshade_layer.hpp | 4 +- .../src/cpp/style/layers/layer.cpp | 283 +-- .../src/cpp/style/layers/layer.hpp | 8 +- .../src/cpp/style/layers/layer_manager.cpp | 14 +- .../src/cpp/style/layers/layer_manager.hpp | 8 +- .../src/cpp/style/layers/line_layer.cpp | 602 +++--- .../src/cpp/style/layers/line_layer.hpp | 4 +- .../style/layers/location_indicator_layer.cpp | 521 ++--- .../style/layers/location_indicator_layer.hpp | 5 +- .../src/cpp/style/layers/raster_layer.cpp | 417 ++-- .../src/cpp/style/layers/raster_layer.hpp | 4 +- .../src/cpp/style/layers/symbol_layer.cpp | 1161 +++++------ .../src/cpp/style/layers/symbol_layer.hpp | 4 +- .../src/cpp/style/light.cpp | 84 +- .../src/cpp/style/light.hpp | 2 - .../src/cpp/style/position.cpp | 6 +- .../style/sources/custom_geometry_source.cpp | 326 +-- .../style/sources/custom_geometry_source.hpp | 8 +- .../src/cpp/style/sources/geojson_source.cpp | 357 ++-- .../src/cpp/style/sources/geojson_source.hpp | 18 +- .../src/cpp/style/sources/image_source.cpp | 115 +- .../cpp/style/sources/raster_dem_source.cpp | 87 +- .../src/cpp/style/sources/raster_source.cpp | 85 +- .../src/cpp/style/sources/source.cpp | 328 +-- .../src/cpp/style/sources/source.hpp | 7 +- .../src/cpp/style/sources/unknown_source.cpp | 27 +- .../src/cpp/style/sources/vector_source.cpp | 109 +- .../src/cpp/style/sources/vector_source.hpp | 5 +- .../src/cpp/style/transition_options.cpp | 14 +- .../src/cpp/style/transition_options.hpp | 4 +- .../src/cpp/style/value.cpp | 149 +- .../src/cpp/style/value.hpp | 12 +- .../src/cpp/text/local_glyph_rasterizer.cpp | 43 +- .../src/cpp/util/default_style.cpp | 9 +- .../src/cpp/util/default_style.hpp | 3 - .../src/cpp/util/tile_server_options.cpp | 137 +- .../src/cpp/util/tile_server_options.hpp | 25 +- platform/android/src/async_task.cpp | 11 +- platform/android/src/attach_env.cpp | 16 +- platform/android/src/attach_env.hpp | 13 +- platform/android/src/bitmap.cpp | 56 +- platform/android/src/bitmap.hpp | 5 +- platform/android/src/bitmap_factory.cpp | 9 +- platform/android/src/bitmap_factory.hpp | 5 +- platform/android/src/example_custom_layer.cpp | 52 +- platform/android/src/gl_functions.cpp | 511 ++--- platform/android/src/image.cpp | 5 +- platform/android/src/jni.cpp | 6 +- platform/android/src/run_loop.cpp | 44 +- platform/android/src/run_loop_impl.hpp | 3 +- platform/android/src/string_util.cpp | 4 +- .../android/src/test/benchmark_runner.cpp | 9 +- .../android/src/test/collator_test_stub.cpp | 3 +- .../src/test/http_file_source_test_stub.cpp | 9 +- .../src/test/number_format_test_stub.cpp | 12 +- .../android/src/test/render_test_runner.cpp | 10 +- platform/android/src/test/runtime.cpp | 15 +- platform/android/src/test/test_runner.cpp | 2 +- .../android/src/test/test_runner_common.cpp | 47 +- .../android/src/test/test_runner_common.hpp | 12 +- platform/android/src/timer.cpp | 18 +- .../include/mbgl/gfx/headless_backend.hpp | 13 +- .../include/mbgl/gfx/headless_frontend.hpp | 22 +- .../include/mbgl/gl/headless_backend.hpp | 6 +- .../include/mbgl/map/map_snapshotter.hpp | 20 +- .../include/mbgl/storage/merge_sideloaded.hpp | 87 +- .../include/mbgl/storage/offline_database.hpp | 22 +- .../include/mbgl/storage/offline_download.hpp | 2 +- .../include/mbgl/storage/offline_schema.hpp | 105 +- .../default/include/mbgl/storage/sqlite3.hpp | 21 +- .../default/src/mbgl/gfx/headless_backend.cpp | 3 +- .../src/mbgl/gfx/headless_frontend.cpp | 41 +- .../default/src/mbgl/gl/headless_backend.cpp | 17 +- platform/default/src/mbgl/i18n/collator.cpp | 13 +- .../default/src/mbgl/i18n/number_format.cpp | 12 +- .../src/mbgl/layermanager/layer_manager.cpp | 5 +- .../default/src/mbgl/map/map_snapshotter.cpp | 113 +- .../src/mbgl/storage/asset_file_source.cpp | 25 +- .../src/mbgl/storage/database_file_source.cpp | 110 +- .../src/mbgl/storage/file_source_manager.cpp | 54 +- .../src/mbgl/storage/file_source_request.cpp | 5 +- .../src/mbgl/storage/http_file_source.cpp | 145 +- .../src/mbgl/storage/local_file_request.cpp | 6 +- .../src/mbgl/storage/local_file_source.cpp | 18 +- .../src/mbgl/storage/main_resource_loader.cpp | 76 +- .../src/mbgl/storage/mbtiles_file_source.cpp | 62 +- platform/default/src/mbgl/storage/offline.cpp | 127 +- .../src/mbgl/storage/offline_database.cpp | 214 +- .../src/mbgl/storage/offline_download.cpp | 165 +- .../src/mbgl/storage/online_file_source.cpp | 91 +- platform/default/src/mbgl/storage/sqlite3.cpp | 204 +- platform/default/src/mbgl/text/bidi.cpp | 138 +- .../src/mbgl/text/local_glyph_rasterizer.cpp | 3 +- platform/default/src/mbgl/util/async_task.cpp | 19 +- .../default/src/mbgl/util/compression.cpp | 5 +- .../default/src/mbgl/util/jpeg_reader.cpp | 33 +- platform/default/src/mbgl/util/png_reader.cpp | 62 +- platform/default/src/mbgl/util/png_writer.cpp | 9 +- platform/default/src/mbgl/util/run_loop.cpp | 75 +- .../default/src/mbgl/util/string_stdlib.cpp | 50 +- platform/default/src/mbgl/util/timer.cpp | 28 +- platform/glfw/glfw_gl_backend.cpp | 15 +- platform/glfw/glfw_gl_backend.hpp | 12 +- platform/glfw/glfw_renderer_frontend.cpp | 12 +- platform/glfw/glfw_renderer_frontend.hpp | 4 +- platform/glfw/glfw_view.cpp | 655 +++--- platform/glfw/glfw_view.hpp | 29 +- platform/glfw/main.cpp | 63 +- platform/glfw/settings_json.cpp | 4 +- platform/glfw/test_writer.cpp | 10 +- platform/linux/src/gl_functions.cpp | 511 ++--- platform/linux/src/headless_backend_egl.cpp | 35 +- platform/linux/src/headless_backend_glx.cpp | 18 +- platform/node/src/node_conversion.hpp | 27 +- platform/node/src/node_expression.cpp | 57 +- platform/node/src/node_feature.cpp | 58 +- platform/node/src/node_feature.hpp | 2 +- platform/node/src/node_logging.cpp | 33 +- platform/node/src/node_logging.hpp | 5 +- platform/node/src/node_map.cpp | 358 ++-- platform/node/src/node_map.hpp | 5 +- platform/node/src/node_mapbox_gl_native.cpp | 54 +- platform/node/src/node_request.cpp | 40 +- platform/node/src/node_request.hpp | 2 - platform/node/src/util/async_queue.hpp | 10 +- platform/qt/app/main.cpp | 3 +- platform/qt/app/mapwindow.cpp | 143 +- platform/qt/app/mapwindow.hpp | 3 +- platform/qt/include/QMapLibreGL/export.hpp | 12 +- platform/qt/include/QMapLibreGL/map.hpp | 27 +- platform/qt/include/QMapLibreGL/settings.hpp | 9 +- platform/qt/include/QMapLibreGL/types.hpp | 46 +- platform/qt/src/map.cpp | 567 +++--- platform/qt/src/map_p.hpp | 11 +- platform/qt/src/mbgl/async_task.cpp | 10 +- platform/qt/src/mbgl/async_task_impl.hpp | 3 +- platform/qt/src/mbgl/bidi.cpp | 8 +- platform/qt/src/mbgl/gl_functions.cpp | 515 ++--- platform/qt/src/mbgl/headless_backend_qt.cpp | 8 +- platform/qt/src/mbgl/http_file_source.cpp | 42 +- platform/qt/src/mbgl/http_file_source.hpp | 5 +- platform/qt/src/mbgl/http_request.cpp | 108 +- platform/qt/src/mbgl/http_request.hpp | 7 +- platform/qt/src/mbgl/image.cpp | 15 +- .../qt/src/mbgl/local_glyph_rasterizer.cpp | 11 +- platform/qt/src/mbgl/number_format.cpp | 10 +- platform/qt/src/mbgl/run_loop.cpp | 19 +- platform/qt/src/mbgl/sqlite3.cpp | 141 +- platform/qt/src/mbgl/thread.cpp | 12 +- platform/qt/src/mbgl/thread_local.cpp | 2 +- platform/qt/src/mbgl/timer.cpp | 17 +- platform/qt/src/mbgl/timer_impl.hpp | 2 +- platform/qt/src/settings.cpp | 161 +- platform/qt/src/types.cpp | 14 +- platform/qt/src/utils.cpp | 29 +- platform/qt/src/utils/conversion.hpp | 63 +- platform/qt/src/utils/geojson.cpp | 84 +- platform/qt/src/utils/map_observer.cpp | 46 +- platform/qt/src/utils/map_observer.hpp | 7 +- platform/qt/src/utils/map_renderer.cpp | 26 +- platform/qt/src/utils/map_renderer.hpp | 3 +- platform/qt/src/utils/renderer_backend.cpp | 7 +- platform/qt/src/utils/renderer_backend.hpp | 7 +- platform/qt/src/utils/renderer_observer.hpp | 25 +- platform/qt/src/utils/scheduler.cpp | 10 +- platform/qt/src/utils/scheduler.hpp | 5 +- platform/qt/test/qmaplibregl.test.cpp | 6 +- platform/windows/include/gl_functions_wgl.h | 1768 ++++++++++++---- platform/windows/include/thread.h | 29 +- platform/windows/src/gl_functions.cpp | 511 ++--- platform/windows/src/headless_backend_egl.cpp | 33 +- .../windows/src/headless_backend_osmesa.cpp | 29 +- platform/windows/src/headless_backend_wgl.cpp | 138 +- platform/windows/src/thread.cpp | 15 +- render-test/allocation_index.cpp | 6 +- render-test/allocation_index.hpp | 18 +- render-test/file_source.cpp | 28 +- render-test/file_source.hpp | 2 +- render-test/manifest_parser.cpp | 89 +- render-test/manifest_parser.hpp | 3 +- render-test/metadata.hpp | 32 +- render-test/parser.cpp | 200 +- render-test/render_test.cpp | 91 +- render-test/runner.cpp | 115 +- render-test/runner.hpp | 13 +- src/mbgl/actor/mailbox.cpp | 7 +- src/mbgl/actor/scheduler.cpp | 2 +- src/mbgl/algorithm/update_renderables.hpp | 29 +- src/mbgl/algorithm/update_tile_masks.hpp | 37 +- src/mbgl/annotation/annotation_manager.cpp | 58 +- src/mbgl/annotation/annotation_manager.hpp | 9 +- src/mbgl/annotation/annotation_source.cpp | 6 +- src/mbgl/annotation/annotation_source.hpp | 6 +- src/mbgl/annotation/annotation_tile.cpp | 42 +- src/mbgl/annotation/annotation_tile.hpp | 7 +- src/mbgl/annotation/fill_annotation_impl.cpp | 8 +- src/mbgl/annotation/line_annotation_impl.cpp | 8 +- .../annotation/render_annotation_source.cpp | 29 +- .../annotation/render_annotation_source.hpp | 28 +- src/mbgl/annotation/shape_annotation_impl.cpp | 11 +- src/mbgl/annotation/shape_annotation_impl.hpp | 14 +- .../annotation/symbol_annotation_impl.cpp | 9 +- .../annotation/symbol_annotation_impl.hpp | 46 +- src/mbgl/geometry/anchor.hpp | 4 +- src/mbgl/geometry/debug_font_data.hpp | 520 +++-- src/mbgl/geometry/dem_data.cpp | 43 +- src/mbgl/geometry/dem_data.hpp | 6 +- src/mbgl/geometry/feature_index.cpp | 196 +- src/mbgl/geometry/feature_index.hpp | 111 +- src/mbgl/geometry/line_atlas.cpp | 40 +- src/mbgl/geometry/line_atlas.hpp | 6 +- src/mbgl/gfx/attribute.cpp | 4 +- src/mbgl/gfx/attribute.hpp | 193 +- src/mbgl/gfx/color_mode.hpp | 24 +- src/mbgl/gfx/command_encoder.hpp | 4 +- src/mbgl/gfx/context.hpp | 28 +- src/mbgl/gfx/cull_face_mode.hpp | 8 +- src/mbgl/gfx/debug_group.hpp | 8 +- src/mbgl/gfx/depth_mode.hpp | 4 +- src/mbgl/gfx/draw_mode.hpp | 57 +- src/mbgl/gfx/draw_scope.hpp | 5 +- src/mbgl/gfx/index_buffer.hpp | 5 +- src/mbgl/gfx/index_vector.hpp | 26 +- src/mbgl/gfx/offscreen_texture.hpp | 3 +- src/mbgl/gfx/program.hpp | 39 +- src/mbgl/gfx/render_pass.hpp | 4 +- src/mbgl/gfx/renderbuffer.hpp | 16 +- src/mbgl/gfx/renderer_backend.cpp | 8 +- src/mbgl/gfx/shader_registry.cpp | 26 +- src/mbgl/gfx/stencil_mode.hpp | 26 +- src/mbgl/gfx/texture.hpp | 38 +- src/mbgl/gfx/uniform.hpp | 37 +- src/mbgl/gfx/upload_pass.hpp | 82 +- src/mbgl/gfx/vertex_buffer.hpp | 5 +- src/mbgl/gfx/vertex_vector.hpp | 30 +- src/mbgl/gl/attribute.hpp | 47 +- src/mbgl/gl/command_encoder.cpp | 13 +- src/mbgl/gl/command_encoder.hpp | 4 +- src/mbgl/gl/context.cpp | 242 ++- src/mbgl/gl/context.hpp | 60 +- src/mbgl/gl/custom_layer.cpp | 27 +- src/mbgl/gl/custom_layer_factory.cpp | 3 +- src/mbgl/gl/custom_layer_impl.cpp | 6 +- src/mbgl/gl/custom_layer_impl.hpp | 3 +- src/mbgl/gl/debugging_extension.cpp | 117 +- src/mbgl/gl/debugging_extension.hpp | 158 +- src/mbgl/gl/defines.hpp | 1232 +++++------ src/mbgl/gl/draw_scope_resource.hpp | 4 +- src/mbgl/gl/enum.cpp | 393 ++-- src/mbgl/gl/enum.hpp | 8 +- src/mbgl/gl/extension.hpp | 12 +- src/mbgl/gl/index_buffer_resource.hpp | 4 +- src/mbgl/gl/offscreen_texture.cpp | 17 +- src/mbgl/gl/offscreen_texture.hpp | 6 +- src/mbgl/gl/program.hpp | 79 +- src/mbgl/gl/render_custom_layer.cpp | 5 +- src/mbgl/gl/render_pass.cpp | 12 +- src/mbgl/gl/renderbuffer_resource.hpp | 3 +- src/mbgl/gl/renderer_backend.cpp | 10 +- src/mbgl/gl/state.hpp | 24 +- src/mbgl/gl/texture.cpp | 33 +- src/mbgl/gl/texture.hpp | 19 +- src/mbgl/gl/texture_resource.hpp | 4 +- src/mbgl/gl/uniform.cpp | 38 +- src/mbgl/gl/uniform.hpp | 26 +- src/mbgl/gl/upload_pass.cpp | 103 +- src/mbgl/gl/upload_pass.hpp | 36 +- src/mbgl/gl/value.cpp | 61 +- src/mbgl/gl/value.hpp | 17 +- src/mbgl/gl/vertex_array.cpp | 4 +- src/mbgl/gl/vertex_array.hpp | 6 +- src/mbgl/gl/vertex_buffer_resource.hpp | 4 +- .../layermanager/background_layer_factory.cpp | 4 +- .../layermanager/circle_layer_factory.cpp | 7 +- .../fill_extrusion_layer_factory.cpp | 12 +- src/mbgl/layermanager/fill_layer_factory.cpp | 13 +- .../layermanager/heatmap_layer_factory.cpp | 8 +- .../layermanager/hillshade_layer_factory.cpp | 4 +- src/mbgl/layermanager/layer_factory.cpp | 8 +- src/mbgl/layermanager/layer_manager.cpp | 20 +- src/mbgl/layermanager/line_layer_factory.cpp | 12 +- .../location_indicator_layer_factory.cpp | 12 +- .../layermanager/raster_layer_factory.cpp | 4 +- .../layermanager/symbol_layer_factory.cpp | 12 +- src/mbgl/layout/circle_layout.hpp | 40 +- src/mbgl/layout/clip_lines.cpp | 74 +- src/mbgl/layout/layout.hpp | 14 +- src/mbgl/layout/merge_lines.cpp | 34 +- src/mbgl/layout/merge_lines.hpp | 26 +- src/mbgl/layout/pattern_layout.hpp | 138 +- src/mbgl/layout/symbol_feature.hpp | 4 +- src/mbgl/layout/symbol_instance.cpp | 166 +- src/mbgl/layout/symbol_instance.hpp | 81 +- src/mbgl/layout/symbol_layout.cpp | 813 ++++---- src/mbgl/layout/symbol_layout.hpp | 110 +- src/mbgl/layout/symbol_projection.cpp | 849 ++++---- src/mbgl/layout/symbol_projection.hpp | 118 +- src/mbgl/map/map.cpp | 97 +- src/mbgl/map/map_impl.cpp | 47 +- src/mbgl/map/map_impl.hpp | 11 +- src/mbgl/map/map_options.cpp | 7 +- src/mbgl/map/map_projection.cpp | 7 +- src/mbgl/map/transform.cpp | 114 +- src/mbgl/map/transform.hpp | 20 +- src/mbgl/map/transform_state.cpp | 41 +- src/mbgl/math/log2.cpp | 10 +- src/mbgl/platform/gl_functions.cpp | 8 +- src/mbgl/platform/settings.cpp | 3 +- src/mbgl/programs/attributes.hpp | 6 +- src/mbgl/programs/background_program.cpp | 58 +- src/mbgl/programs/background_program.hpp | 57 +- src/mbgl/programs/circle_program.hpp | 40 +- src/mbgl/programs/clipping_mask_program.cpp | 4 +- src/mbgl/programs/clipping_mask_program.hpp | 20 +- src/mbgl/programs/collision_box_program.hpp | 255 ++- src/mbgl/programs/debug_program.cpp | 4 +- src/mbgl/programs/debug_program.hpp | 19 +- src/mbgl/programs/fill_extrusion_program.cpp | 79 +- src/mbgl/programs/fill_extrusion_program.hpp | 101 +- src/mbgl/programs/fill_program.cpp | 41 +- src/mbgl/programs/fill_program.hpp | 110 +- src/mbgl/programs/heatmap_program.hpp | 31 +- src/mbgl/programs/heatmap_texture_program.hpp | 32 +- .../programs/hillshade_prepare_program.hpp | 40 +- src/mbgl/programs/hillshade_program.hpp | 44 +- src/mbgl/programs/line_program.cpp | 119 +- src/mbgl/programs/line_program.hpp | 240 +-- src/mbgl/programs/program.hpp | 124 +- src/mbgl/programs/program_parameters.cpp | 44 +- src/mbgl/programs/program_parameters.hpp | 90 +- src/mbgl/programs/programs.cpp | 26 +- src/mbgl/programs/raster_program.hpp | 56 +- src/mbgl/programs/segment.hpp | 12 +- src/mbgl/programs/symbol_program.cpp | 189 +- src/mbgl/programs/symbol_program.hpp | 471 +++-- src/mbgl/renderer/backend_scope.cpp | 8 +- src/mbgl/renderer/bucket.hpp | 25 +- src/mbgl/renderer/bucket_parameters.cpp | 4 +- src/mbgl/renderer/bucket_parameters.hpp | 2 +- src/mbgl/renderer/buckets/circle_bucket.cpp | 28 +- src/mbgl/renderer/buckets/circle_bucket.hpp | 6 +- src/mbgl/renderer/buckets/debug_bucket.cpp | 34 +- src/mbgl/renderer/buckets/debug_bucket.hpp | 15 +- src/mbgl/renderer/buckets/fill_bucket.cpp | 68 +- src/mbgl/renderer/buckets/fill_bucket.hpp | 21 +- .../buckets/fill_extrusion_bucket.cpp | 93 +- .../buckets/fill_extrusion_bucket.hpp | 23 +- src/mbgl/renderer/buckets/heatmap_bucket.cpp | 34 +- src/mbgl/renderer/buckets/heatmap_bucket.hpp | 9 +- .../renderer/buckets/hillshade_bucket.cpp | 37 +- .../renderer/buckets/hillshade_bucket.hpp | 13 +- src/mbgl/renderer/buckets/line_bucket.cpp | 259 ++- src/mbgl/renderer/buckets/line_bucket.hpp | 59 +- src/mbgl/renderer/buckets/raster_bucket.cpp | 34 +- src/mbgl/renderer/buckets/raster_bucket.hpp | 2 +- src/mbgl/renderer/buckets/symbol_bucket.cpp | 113 +- src/mbgl/renderer/buckets/symbol_bucket.hpp | 57 +- .../cross_faded_property_evaluator.cpp | 12 +- .../cross_faded_property_evaluator.hpp | 3 +- .../data_driven_property_evaluator.hpp | 25 +- src/mbgl/renderer/image_atlas.cpp | 58 +- src/mbgl/renderer/image_atlas.hpp | 14 +- src/mbgl/renderer/image_manager.cpp | 9 +- src/mbgl/renderer/image_manager.hpp | 4 +- .../layers/render_background_layer.cpp | 111 +- .../renderer/layers/render_circle_layer.cpp | 120 +- .../renderer/layers/render_circle_layer.hpp | 10 +- .../layers/render_fill_extrusion_layer.cpp | 187 +- .../layers/render_fill_extrusion_layer.hpp | 10 +- .../renderer/layers/render_fill_layer.cpp | 223 +- .../renderer/layers/render_fill_layer.hpp | 10 +- .../renderer/layers/render_heatmap_layer.cpp | 81 +- .../renderer/layers/render_heatmap_layer.hpp | 10 +- .../layers/render_hillshade_layer.cpp | 152 +- .../layers/render_hillshade_layer.hpp | 2 +- .../renderer/layers/render_line_layer.cpp | 244 +-- .../renderer/layers/render_line_layer.hpp | 10 +- .../render_location_indicator_layer.cpp | 93 +- .../renderer/layers/render_raster_layer.cpp | 102 +- .../renderer/layers/render_symbol_layer.cpp | 547 +++-- .../renderer/layers/render_symbol_layer.hpp | 38 +- src/mbgl/renderer/paint_parameters.cpp | 176 +- src/mbgl/renderer/paint_parameters.hpp | 13 +- src/mbgl/renderer/paint_property_binder.hpp | 391 ++-- .../renderer/paint_property_statistics.hpp | 8 +- src/mbgl/renderer/pattern_atlas.cpp | 24 +- src/mbgl/renderer/pattern_atlas.hpp | 6 +- .../possibly_evaluated_property_value.hpp | 108 +- .../property_evaluation_parameters.hpp | 14 +- src/mbgl/renderer/render_layer.cpp | 46 +- src/mbgl/renderer/render_layer.hpp | 5 +- src/mbgl/renderer/render_light.cpp | 3 +- src/mbgl/renderer/render_light.hpp | 2 +- src/mbgl/renderer/render_orchestrator.cpp | 266 ++- src/mbgl/renderer/render_orchestrator.hpp | 72 +- src/mbgl/renderer/render_source.cpp | 45 +- src/mbgl/renderer/render_source.hpp | 34 +- src/mbgl/renderer/render_static_data.cpp | 27 +- src/mbgl/renderer/render_tile.cpp | 180 +- src/mbgl/renderer/render_tile.hpp | 24 +- src/mbgl/renderer/render_tree.hpp | 20 +- src/mbgl/renderer/renderer.cpp | 77 +- src/mbgl/renderer/renderer_impl.cpp | 20 +- src/mbgl/renderer/renderer_impl.hpp | 2 +- src/mbgl/renderer/source_state.cpp | 21 +- src/mbgl/renderer/source_state.hpp | 15 +- .../sources/render_custom_geometry_source.cpp | 39 +- .../sources/render_custom_geometry_source.hpp | 10 +- .../sources/render_geojson_source.cpp | 90 +- .../sources/render_geojson_source.hpp | 21 +- .../renderer/sources/render_image_source.cpp | 99 +- .../renderer/sources/render_image_source.hpp | 32 +- .../sources/render_raster_dem_source.cpp | 73 +- .../sources/render_raster_dem_source.hpp | 24 +- .../renderer/sources/render_raster_source.cpp | 28 +- .../renderer/sources/render_raster_source.hpp | 24 +- .../renderer/sources/render_tile_source.cpp | 54 +- .../renderer/sources/render_tile_source.hpp | 36 +- .../renderer/sources/render_vector_source.cpp | 39 +- .../renderer/sources/render_vector_source.hpp | 9 +- src/mbgl/renderer/style_diff.cpp | 38 +- src/mbgl/renderer/style_diff.hpp | 12 +- src/mbgl/renderer/tile_pyramid.cpp | 83 +- src/mbgl/renderer/tile_pyramid.hpp | 30 +- src/mbgl/renderer/tile_render_data.cpp | 3 +- src/mbgl/renderer/tile_render_data.hpp | 6 +- src/mbgl/renderer/update_parameters.hpp | 2 +- src/mbgl/renderer/upload_parameters.hpp | 6 +- src/mbgl/sprite/sprite_loader.cpp | 4 +- src/mbgl/sprite/sprite_parser.cpp | 87 +- src/mbgl/sprite/sprite_parser.hpp | 24 +- src/mbgl/storage/asset_file_source.hpp | 3 +- src/mbgl/storage/file_source_manager.cpp | 15 +- src/mbgl/storage/local_file_source.hpp | 3 +- src/mbgl/storage/mbtiles_file_source.hpp | 5 +- src/mbgl/storage/network_status.cpp | 2 +- src/mbgl/storage/resource.cpp | 119 +- src/mbgl/storage/resource_options.cpp | 21 +- src/mbgl/storage/resource_transform.cpp | 3 +- src/mbgl/storage/response.cpp | 5 +- src/mbgl/style/collection.hpp | 17 +- .../conversion/color_ramp_property_value.cpp | 4 +- src/mbgl/style/conversion/constant.cpp | 56 +- src/mbgl/style/conversion/coordinate.cpp | 8 +- .../custom_geometry_source_options.cpp | 4 +- src/mbgl/style/conversion/filter.cpp | 58 +- src/mbgl/style/conversion/function.cpp | 492 ++--- src/mbgl/style/conversion/geojson_options.cpp | 23 +- src/mbgl/style/conversion/get_json_type.cpp | 8 +- src/mbgl/style/conversion/json.hpp | 6 +- src/mbgl/style/conversion/layer.cpp | 11 +- src/mbgl/style/conversion/light.cpp | 2 +- src/mbgl/style/conversion/property_value.cpp | 139 +- src/mbgl/style/conversion/source.cpp | 50 +- src/mbgl/style/conversion/stringify.hpp | 39 +- src/mbgl/style/conversion/tileset.cpp | 6 +- .../style/conversion/transition_options.cpp | 7 +- src/mbgl/style/custom_tile_loader.cpp | 14 +- src/mbgl/style/expression/assertion.cpp | 34 +- src/mbgl/style/expression/at.cpp | 24 +- .../style/expression/boolean_operator.cpp | 16 +- src/mbgl/style/expression/case.cpp | 8 +- src/mbgl/style/expression/check_subtype.cpp | 18 +- src/mbgl/style/expression/coalesce.cpp | 9 +- src/mbgl/style/expression/coercion.cpp | 72 +- .../style/expression/collator_expression.cpp | 53 +- src/mbgl/style/expression/comparison.cpp | 152 +- .../style/expression/compound_expression.cpp | 651 +++--- src/mbgl/style/expression/distance.cpp | 248 ++- src/mbgl/style/expression/dsl.cpp | 95 +- src/mbgl/style/expression/expression.cpp | 37 +- src/mbgl/style/expression/find_zoom_curve.cpp | 85 +- .../style/expression/format_expression.cpp | 25 +- src/mbgl/style/expression/formatted.cpp | 3 +- .../style/expression/get_covering_stops.cpp | 10 +- src/mbgl/style/expression/image.cpp | 10 +- .../style/expression/image_expression.cpp | 3 +- src/mbgl/style/expression/in.cpp | 30 +- src/mbgl/style/expression/interpolate.cpp | 130 +- src/mbgl/style/expression/is_constant.cpp | 1 - src/mbgl/style/expression/is_expression.cpp | 3 +- src/mbgl/style/expression/length.cpp | 21 +- src/mbgl/style/expression/let.cpp | 19 +- src/mbgl/style/expression/literal.cpp | 60 +- src/mbgl/style/expression/match.cpp | 106 +- src/mbgl/style/expression/number_format.cpp | 47 +- src/mbgl/style/expression/parsing_context.cpp | 84 +- src/mbgl/style/expression/step.cpp | 47 +- src/mbgl/style/expression/util.cpp | 29 +- src/mbgl/style/expression/value.cpp | 262 +-- src/mbgl/style/expression/within.cpp | 88 +- src/mbgl/style/filter.cpp | 3 +- src/mbgl/style/image.cpp | 19 +- src/mbgl/style/image_impl.cpp | 16 +- src/mbgl/style/image_impl.hpp | 16 +- src/mbgl/style/layer.cpp | 42 +- src/mbgl/style/layer_impl.cpp | 3 +- src/mbgl/style/layer_impl.hpp | 8 +- .../layers/fill_extrusion_layer_impl.cpp | 4 +- src/mbgl/style/layers/heatmap_layer_impl.cpp | 4 +- src/mbgl/style/layers/line_layer_impl.cpp | 4 +- src/mbgl/style/layers/symbol_layer_impl.cpp | 17 +- src/mbgl/style/layers/symbol_layer_impl.hpp | 84 +- src/mbgl/style/light.cpp | 52 +- src/mbgl/style/light_impl.cpp | 4 +- src/mbgl/style/light_impl.hpp | 16 +- src/mbgl/style/parser.cpp | 35 +- src/mbgl/style/parser.hpp | 2 +- src/mbgl/style/properties.hpp | 186 +- src/mbgl/style/property_expression.cpp | 12 +- src/mbgl/style/rapidjson_conversion.hpp | 48 +- src/mbgl/style/source.cpp | 3 +- src/mbgl/style/source_impl.cpp | 11 +- .../style/sources/custom_geometry_source.cpp | 6 +- .../sources/custom_geometry_source_impl.cpp | 5 +- src/mbgl/style/sources/geojson_source.cpp | 14 +- .../style/sources/geojson_source_impl.cpp | 37 +- src/mbgl/style/sources/image_source.cpp | 7 +- src/mbgl/style/sources/image_source_impl.cpp | 12 +- src/mbgl/style/sources/image_source_impl.hpp | 1 + src/mbgl/style/sources/raster_source.cpp | 9 +- src/mbgl/style/sources/raster_source_impl.cpp | 6 +- src/mbgl/style/sources/vector_source.cpp | 10 +- src/mbgl/style/sources/vector_source_impl.cpp | 6 +- src/mbgl/style/style_impl.cpp | 15 +- src/mbgl/style/style_impl.hpp | 8 +- src/mbgl/style/types.cpp | 264 +-- src/mbgl/text/bidi.hpp | 2 +- src/mbgl/text/check_max_angle.cpp | 26 +- src/mbgl/text/check_max_angle.hpp | 3 +- src/mbgl/text/collision_feature.cpp | 68 +- src/mbgl/text/collision_feature.hpp | 158 +- src/mbgl/text/collision_index.cpp | 203 +- src/mbgl/text/collision_index.hpp | 64 +- src/mbgl/text/cross_tile_symbol_index.cpp | 68 +- src/mbgl/text/cross_tile_symbol_index.hpp | 17 +- src/mbgl/text/get_anchors.cpp | 86 +- src/mbgl/text/get_anchors.hpp | 40 +- src/mbgl/text/glyph.cpp | 4 +- src/mbgl/text/glyph.hpp | 37 +- src/mbgl/text/glyph_atlas.cpp | 53 +- src/mbgl/text/glyph_manager.cpp | 18 +- src/mbgl/text/glyph_manager.hpp | 12 +- src/mbgl/text/glyph_pbf.cpp | 74 +- src/mbgl/text/glyph_range.hpp | 4 +- src/mbgl/text/language_tag.cpp | 95 +- src/mbgl/text/language_tag.hpp | 4 +- src/mbgl/text/local_glyph_rasterizer.hpp | 7 +- src/mbgl/text/placement.cpp | 984 +++++---- src/mbgl/text/placement.hpp | 65 +- src/mbgl/text/quads.cpp | 126 +- src/mbgl/text/quads.hpp | 47 +- src/mbgl/text/shaping.cpp | 380 ++-- src/mbgl/text/shaping.hpp | 57 +- src/mbgl/text/tagged_string.cpp | 13 +- src/mbgl/text/tagged_string.hpp | 87 +- src/mbgl/tile/custom_geometry_tile.cpp | 32 +- src/mbgl/tile/custom_geometry_tile.hpp | 18 +- src/mbgl/tile/geojson_tile.cpp | 21 +- src/mbgl/tile/geojson_tile.hpp | 9 +- src/mbgl/tile/geojson_tile_data.hpp | 38 +- src/mbgl/tile/geometry_tile.cpp | 127 +- src/mbgl/tile/geometry_tile.hpp | 40 +- src/mbgl/tile/geometry_tile_data.cpp | 34 +- src/mbgl/tile/geometry_tile_data.hpp | 30 +- src/mbgl/tile/geometry_tile_worker.cpp | 239 +-- src/mbgl/tile/geometry_tile_worker.hpp | 43 +- src/mbgl/tile/raster_dem_tile.cpp | 12 +- src/mbgl/tile/raster_dem_tile.hpp | 67 +- src/mbgl/tile/raster_dem_tile_worker.cpp | 6 +- src/mbgl/tile/raster_tile.cpp | 8 +- src/mbgl/tile/raster_tile.hpp | 4 +- src/mbgl/tile/tile.cpp | 34 +- src/mbgl/tile/tile.hpp | 43 +- src/mbgl/tile/tile_cache.cpp | 1 - src/mbgl/tile/tile_cache.hpp | 4 +- src/mbgl/tile/tile_loader.hpp | 5 +- src/mbgl/tile/tile_loader_impl.hpp | 26 +- src/mbgl/tile/vector_tile.cpp | 10 +- src/mbgl/tile/vector_tile.hpp | 5 +- src/mbgl/tile/vector_tile_data.cpp | 36 +- src/mbgl/util/bounding_volumes.cpp | 74 +- src/mbgl/util/camera.cpp | 13 +- src/mbgl/util/chrono.cpp | 19 +- src/mbgl/util/client_options.cpp | 18 +- src/mbgl/util/color.cpp | 61 +- src/mbgl/util/default_style.cpp | 7 +- src/mbgl/util/event.cpp | 60 +- src/mbgl/util/geo.cpp | 29 +- src/mbgl/util/geometry_util.cpp | 32 +- src/mbgl/util/geometry_util.hpp | 20 +- src/mbgl/util/grid_index.cpp | 46 +- src/mbgl/util/grid_index.hpp | 31 +- src/mbgl/util/hash.hpp | 2 +- src/mbgl/util/http_header.cpp | 21 +- src/mbgl/util/http_header.hpp | 5 +- src/mbgl/util/http_timeout.cpp | 5 +- src/mbgl/util/http_timeout.hpp | 6 +- src/mbgl/util/i18n.cpp | 203 +- src/mbgl/util/i18n.hpp | 2 +- src/mbgl/util/intersection_tests.cpp | 21 +- src/mbgl/util/io.cpp | 10 +- src/mbgl/util/io.hpp | 6 +- src/mbgl/util/literal.hpp | 21 +- src/mbgl/util/logging.cpp | 25 +- src/mbgl/util/longest_common_subsequence.hpp | 17 +- src/mbgl/util/mapbox.cpp | 234 +-- src/mbgl/util/mapbox.hpp | 32 +- src/mbgl/util/mat2.cpp | 4 +- src/mbgl/util/mat4.cpp | 67 +- src/mbgl/util/math.hpp | 7 +- src/mbgl/util/premultiply.cpp | 4 +- src/mbgl/util/quaternion.hpp | 12 +- src/mbgl/util/rapidjson.cpp | 4 +- src/mbgl/util/rect.hpp | 8 +- src/mbgl/util/stopwatch.cpp | 20 +- src/mbgl/util/stopwatch.hpp | 15 +- src/mbgl/util/thread_local.hpp | 12 +- src/mbgl/util/tile_coordinate.hpp | 27 +- src/mbgl/util/tile_cover.cpp | 107 +- src/mbgl/util/tile_cover.hpp | 6 +- src/mbgl/util/tile_cover_impl.cpp | 103 +- src/mbgl/util/tile_cover_impl.hpp | 2 +- src/mbgl/util/tile_range.hpp | 22 +- src/mbgl/util/tile_server_options.cpp | 564 +++--- src/mbgl/util/tiny_sdf.cpp | 34 +- src/mbgl/util/tiny_sdf.hpp | 2 +- src/mbgl/util/token.hpp | 5 +- src/mbgl/util/url.cpp | 29 +- src/mbgl/util/work_request.cpp | 3 +- test/actor/actor.test.cpp | 80 +- test/actor/actor_ref.test.cpp | 29 +- test/algorithm/update_renderables.test.cpp | 1793 +++++++++-------- test/algorithm/update_tile_masks.test.cpp | 109 +- test/api/annotations.test.cpp | 208 +- test/api/api_misuse.test.cpp | 14 +- test/api/custom_geometry_source.test.cpp | 30 +- test/api/custom_layer.test.cpp | 37 +- test/api/query.test.cpp | 112 +- test/api/recycle_map.cpp | 20 +- test/geometry/dem_data.test.cpp | 16 +- test/geometry/line_atlas.test.cpp | 4 +- test/gl/bucket.test.cpp | 427 ++-- test/gl/context.test.cpp | 25 +- test/gl/gl_functions.test.cpp | 1 - test/gl/object.test.cpp | 11 +- test/include/mbgl/test/util.hpp | 19 +- test/map/map.test.cpp | 276 +-- test/map/map_snapshotter.test.cpp | 48 +- test/map/prefetch.test.cpp | 23 +- test/map/transform.test.cpp | 181 +- test/platform/settings.test.cpp | 32 +- test/programs/symbol_program.test.cpp | 58 +- test/renderer/backend_scope.test.cpp | 54 +- test/renderer/image_manager.test.cpp | 66 +- test/renderer/pattern_atlas.test.cpp | 12 +- test/renderer/shader_registry.test.cpp | 165 +- test/sprite/sprite_loader.test.cpp | 25 +- test/sprite/sprite_parser.test.cpp | 593 +++--- test/src/mbgl/test/fake_file_source.hpp | 43 +- test/src/mbgl/test/fixture_log_observer.cpp | 23 +- test/src/mbgl/test/fixture_log_observer.hpp | 18 +- test/src/mbgl/test/getrss.cpp | 101 +- test/src/mbgl/test/getrss.hpp | 6 +- test/src/mbgl/test/http_server.cpp | 1 - test/src/mbgl/test/map_adapter.hpp | 10 +- test/src/mbgl/test/mock.hpp | 18 +- test/src/mbgl/test/sqlite3_test_fs.cpp | 4 +- test/src/mbgl/test/sqlite3_test_fs.hpp | 10 +- test/src/mbgl/test/stub_file_source.cpp | 69 +- test/src/mbgl/test/stub_file_source.hpp | 4 +- .../mbgl/test/stub_geometry_tile_feature.hpp | 25 +- test/src/mbgl/test/stub_layer_observer.hpp | 2 +- test/src/mbgl/test/stub_map_observer.hpp | 1 - .../mbgl/test/stub_render_source_observer.hpp | 7 +- test/src/mbgl/test/stub_style_observer.hpp | 10 +- test/src/mbgl/test/stub_tile_observer.hpp | 4 +- test/src/mbgl/test/test.cpp | 2 +- test/src/mbgl/test/util.cpp | 25 +- test/storage/asset_file_source.test.cpp | 26 +- test/storage/database_file_source.test.cpp | 10 +- test/storage/http_file_source.test.cpp | 95 +- test/storage/local_file_source.test.cpp | 35 +- test/storage/main_resource_loader.test.cpp | 116 +- test/storage/mbtiles_file_source.test.cpp | 58 +- test/storage/offline.test.cpp | 9 +- test/storage/offline_database.test.cpp | 480 +++-- test/storage/offline_download.test.cpp | 493 +++-- test/storage/online_file_source.test.cpp | 100 +- test/storage/resource.test.cpp | 8 +- test/storage/sqlite.test.cpp | 20 +- test/storage/sync_file_source.test.cpp | 13 +- .../style/conversion/conversion_impl.test.cpp | 58 +- test/style/conversion/function.test.cpp | 36 +- .../style/conversion/geojson_options.test.cpp | 18 +- test/style/conversion/layer.test.cpp | 6 +- test/style/conversion/light.test.cpp | 32 +- test/style/conversion/stringify.test.cpp | 71 +- test/style/conversion/tileset.test.cpp | 72 +- test/style/expression/expression.test.cpp | 18 +- test/style/filter.test.cpp | 158 +- test/style/properties.test.cpp | 102 +- test/style/property_expression.test.cpp | 383 ++-- test/style/source.test.cpp | 402 ++-- test/style/style.test.cpp | 22 +- test/style/style_image.test.cpp | 18 +- test/style/style_layer.test.cpp | 33 +- test/style/style_parser.test.cpp | 17 +- test/text/bidi.test.cpp | 53 +- test/text/cross_tile_symbol_index.test.cpp | 374 ++-- test/text/get_anchors.test.cpp | 144 +- test/text/glyph_manager.test.cpp | 235 ++- test/text/glyph_pbf.test.cpp | 2 +- test/text/language_tag.test.cpp | 15 +- test/text/local_glyph_rasterizer.test.cpp | 37 +- test/text/quads.test.cpp | 11 +- test/text/shaping.test.cpp | 36 +- test/text/tagged_string.test.cpp | 6 +- test/tile/custom_geometry_tile.test.cpp | 110 +- test/tile/geojson_tile.test.cpp | 46 +- test/tile/geometry_tile_data.test.cpp | 39 +- test/tile/raster_dem_tile.test.cpp | 24 +- test/tile/raster_tile.test.cpp | 23 +- test/tile/tile_cache.test.cpp | 26 +- test/tile/tile_coordinate.test.cpp | 42 +- test/tile/tile_id.test.cpp | 302 +-- test/tile/vector_tile.test.cpp | 31 +- test/util/async_task.test.cpp | 13 +- test/util/bounding_volumes.test.cpp | 24 +- test/util/camera.test.cpp | 9 +- test/util/geo.test.cpp | 57 +- test/util/grid_index.test.cpp | 10 +- test/util/http_timeout.test.cpp | 4 +- test/util/image.test.cpp | 8 +- test/util/mapbox.test.cpp | 580 ++++-- test/util/memory.test.cpp | 54 +- test/util/merge_lines.test.cpp | 94 +- test/util/offscreen_texture.test.cpp | 56 +- test/util/position.test.cpp | 14 +- test/util/projection.test.cpp | 49 +- test/util/run_loop.test.cpp | 10 +- test/util/string.test.cpp | 1 - test/util/text_conversions.test.cpp | 26 +- test/util/thread.test.cpp | 62 +- test/util/thread_local.test.cpp | 20 +- test/util/tile_cover.test.cpp | 482 +++-- test/util/tile_range.test.cpp | 10 +- test/util/tile_server_options.test.cpp | 5 +- test/util/timer.test.cpp | 10 +- test/util/token.test.cpp | 66 +- test/util/url.test.cpp | 413 ++-- 1045 files changed, 34185 insertions(+), 29161 deletions(-) mode change 100755 => 100644 platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp mode change 100755 => 100644 platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp mode change 100755 => 100644 platform/android/src/jni.cpp diff --git a/.clang-format b/.clang-format index f5b35e58f76..22605d6ce92 100644 --- a/.clang-format +++ b/.clang-format @@ -1,13 +1,19 @@ --- -Language: Cpp BasedOnStyle: Google AccessModifierOffset: -4 +AlignAfterOpenBracket: BlockIndent +AllowShortEnumsOnASingleLine: false AllowShortFunctionsOnASingleLine: Inline +AllowShortLambdasOnASingleLine: Inline BinPackArguments: false BinPackParameters: false ColumnLimit: 120 -IndentWidth: 4 IncludeBlocks: Preserve +IndentWidth: 4 +Language: Cpp +PackConstructorInitializers: Never +PenaltyBreakAssignment: 80 SortIncludes: false SpacesBeforeTrailingComments: 1 +Standard: c++17 ... diff --git a/benchmark/api/query.benchmark.cpp b/benchmark/api/query.benchmark.cpp index 1502ca49995..05c3908f3f8 100644 --- a/benchmark/api/query.benchmark.cpp +++ b/benchmark/api/query.benchmark.cpp @@ -21,19 +21,22 @@ class QueryBenchmark { NetworkStatus::Set(NetworkStatus::Status::Offline); map.getStyle().loadJSON(util::read_file("benchmark/fixtures/api/style.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 40.726989, -73.992857 }).withZoom(15.0)); // Manhattan - map.getStyle().addImage(std::make_unique("test-icon", - decodeImage(util::read_file("benchmark/fixtures/api/default_marker.png")), 1.0f)); + map.jumpTo(CameraOptions().withCenter(LatLng{40.726989, -73.992857}).withZoom(15.0)); // Manhattan + map.getStyle().addImage(std::make_unique( + "test-icon", decodeImage(util::read_file("benchmark/fixtures/api/default_marker.png")), 1.0f + )); frontend.render(map); } util::RunLoop loop; - HeadlessFrontend frontend { { 1000, 1000 }, 1 }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), - ResourceOptions().withCachePath("benchmark/fixtures/api/cache.db").withAssetPath(".").withApiKey("foobar") }; - ScreenBox box{{ 0, 0 }, { 1000, 1000 }}; + HeadlessFrontend frontend{{1000, 1000}, 1}; + Map map{ + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), + ResourceOptions().withCachePath("benchmark/fixtures/api/cache.db").withAssetPath(".").withApiKey("foobar")}; + ScreenBox box{{0, 0}, {1000, 1000}}; }; } // end namespace @@ -74,7 +77,7 @@ static void API_queryRenderedFeaturesLayerFromLowDensity(::benchmark::State& sta QueryBenchmark bench; while (state.KeepRunning()) { - bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{ "testlayer" }}, {}}); + bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{"testlayer"}}, {}}); } } @@ -82,7 +85,7 @@ static void API_queryRenderedFeaturesLayerFromHighDensity(::benchmark::State& st QueryBenchmark bench; while (state.KeepRunning()) { - bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{"road-street" }}, {}}); + bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{"road-street"}}, {}}); } } BENCHMARK(API_queryPixelsForLatLngs); diff --git a/benchmark/api/render.benchmark.cpp b/benchmark/api/render.benchmark.cpp index e91376e13ee..cc9e8a8e8d6 100644 --- a/benchmark/api/render.benchmark.cpp +++ b/benchmark/api/render.benchmark.cpp @@ -22,22 +22,20 @@ using namespace mbgl; namespace { -static std::string cachePath { "benchmark/fixtures/api/cache.db" }; -constexpr double pixelRatio { 1.0 }; -constexpr Size size { 1000, 1000 }; +static std::string cachePath{"benchmark/fixtures/api/cache.db"}; +constexpr double pixelRatio{1.0}; +constexpr Size size{1000, 1000}; class RenderBenchmark { public: - RenderBenchmark() { - NetworkStatus::Set(NetworkStatus::Status::Offline); - } + RenderBenchmark() { NetworkStatus::Set(NetworkStatus::Status::Offline); } util::RunLoop loop; }; void prepare(Map& map, std::optional json = std::nullopt) { map.getStyle().loadJSON(json ? *json : util::read_file("benchmark/fixtures/api/style.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 40.726989, -73.992857 }).withZoom(15.0)); // Manhattan + map.jumpTo(CameraOptions().withCenter(LatLng{40.726989, -73.992857}).withZoom(15.0)); // Manhattan auto image = decodeImage(util::read_file("benchmark/fixtures/api/default_marker.png")); map.getStyle().addImage(std::make_unique("test-icon", std::move(image), 1.0f)); @@ -55,10 +53,12 @@ void prepare_map2(Map& map, std::optional json = std::nullopt) { static void API_renderStill_reuse_map(::benchmark::State& state) { RenderBenchmark bench; - HeadlessFrontend frontend { size, pixelRatio }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar") }; + HeadlessFrontend frontend{size, pixelRatio}; + Map map{ + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; prepare(map); for (auto _ : state) { @@ -68,10 +68,12 @@ static void API_renderStill_reuse_map(::benchmark::State& state) { static void API_renderStill_reuse_map_formatted_labels(::benchmark::State& state) { RenderBenchmark bench; - HeadlessFrontend frontend { size, pixelRatio }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar") }; + HeadlessFrontend frontend{size, pixelRatio}; + Map map{ + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; prepare(map, util::read_file("benchmark/fixtures/api/style_formatted_labels.json")); for (auto _ : state) { @@ -81,13 +83,15 @@ static void API_renderStill_reuse_map_formatted_labels(::benchmark::State& state static void API_renderStill_reuse_map_switch_styles(::benchmark::State& state) { RenderBenchmark bench; - HeadlessFrontend frontend { size, pixelRatio }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar") }; + HeadlessFrontend frontend{size, pixelRatio}; + Map map{ + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; for (auto _ : state) { - prepare(map, { "{}" }); + prepare(map, {"{}"}); frontend.render(map); prepare(map); frontend.render(map); @@ -98,10 +102,12 @@ static void API_renderStill_recreate_map(::benchmark::State& state) { RenderBenchmark bench; for (auto _ : state) { - HeadlessFrontend frontend { size, pixelRatio }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar") }; + HeadlessFrontend frontend{size, pixelRatio}; + Map map{ + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; prepare(map); frontend.render(map); } @@ -112,10 +118,11 @@ static void API_renderStill_recreate_map_2(::benchmark::State& state) { for (auto _ : state) { HeadlessFrontend frontend{size, pixelRatio}; - Map map{frontend, - MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; + Map map{ + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; prepare_map2(map); frontend.render(map); } @@ -125,10 +132,11 @@ static void API_renderStill_multiple_sources(::benchmark::State& state) { using namespace mbgl::style; RenderBenchmark bench; HeadlessFrontend frontend{size, pixelRatio}; - Map map{frontend, - MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; + Map map{ + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; prepare(map); auto& style = map.getStyle(); const int kSourcesCount = 50; diff --git a/benchmark/function/camera_function.benchmark.cpp b/benchmark/function/camera_function.benchmark.cpp index d152c516adf..571c36917c4 100644 --- a/benchmark/function/camera_function.benchmark.cpp +++ b/benchmark/function/camera_function.benchmark.cpp @@ -21,13 +21,15 @@ static std::string createFunctionJSON(size_t stopCount) { static void Parse_CameraFunction(benchmark::State& state) { size_t stopCount = state.range(0); - + while (state.KeepRunning()) { conversion::Error error; state.PauseTiming(); auto doc = createFunctionJSON(stopCount); state.ResumeTiming(); - std::optional> result = conversion::convertJSON>(doc, error, false, false); + std::optional> result = conversion::convertJSON>( + doc, error, false, false + ); if (!result) { state.SkipWithError(error.message.c_str()); } @@ -39,23 +41,21 @@ static void Evaluate_CameraFunction(benchmark::State& state) { size_t stopCount = state.range(0); auto doc = createFunctionJSON(stopCount); conversion::Error error; - std::optional> function = conversion::convertJSON>(doc, error, false, false); + std::optional> function = conversion::convertJSON>( + doc, error, false, false + ); if (!function) { state.SkipWithError(error.message.c_str()); } - - while(state.KeepRunning()) { + + while (state.KeepRunning()) { float z = 24.0f * static_cast(rand() % 100) / 100; function->asExpression().evaluate(z); } - + state.SetLabel(std::to_string(stopCount).c_str()); } -BENCHMARK(Parse_CameraFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - -BENCHMARK(Evaluate_CameraFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - +BENCHMARK(Parse_CameraFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); +BENCHMARK(Evaluate_CameraFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); diff --git a/benchmark/function/composite_function.benchmark.cpp b/benchmark/function/composite_function.benchmark.cpp index 4957ae5b4d4..ec6f1203ab6 100644 --- a/benchmark/function/composite_function.benchmark.cpp +++ b/benchmark/function/composite_function.benchmark.cpp @@ -18,7 +18,7 @@ static std::string createFunctionJSON(size_t stopCount) { std::string value = std::to_string(100.0f / stopCount * innerStop); if (stops.size() > 1) stops += ","; - stops += R"([{"zoom":)" + zoom + R"(,"value":)" + value + "}, " + value + "]"; + stops += R"([{"zoom":)" + zoom + R"(,"value":)" + value + "}, " + value + "]"; } } stops += "]"; @@ -33,7 +33,9 @@ static void Parse_CompositeFunction(benchmark::State& state) { state.PauseTiming(); auto doc = createFunctionJSON(stopCount); state.ResumeTiming(); - std::optional> result = conversion::convertJSON>(doc, error, true, false); + std::optional> result = conversion::convertJSON>( + doc, error, true, false + ); if (!result) { state.SkipWithError(error.message.c_str()); } @@ -45,23 +47,23 @@ static void Evaluate_CompositeFunction(benchmark::State& state) { size_t stopCount = state.range(0); auto doc = createFunctionJSON(stopCount); conversion::Error error; - std::optional> function = conversion::convertJSON>(doc, error, true, false); + std::optional> function = conversion::convertJSON>( + doc, error, true, false + ); if (!function) { state.SkipWithError(error.message.c_str()); } - while(state.KeepRunning()) { + while (state.KeepRunning()) { float z = 24.0f * static_cast(rand() % 100) / 100; - function->asExpression().evaluate(z, StubGeometryTileFeature(PropertyMap { { "x", static_cast(rand() % 100) } }), -1.0f); + function->asExpression().evaluate( + z, StubGeometryTileFeature(PropertyMap{{"x", static_cast(rand() % 100)}}), -1.0f + ); } state.SetLabel(std::to_string(stopCount).c_str()); } -BENCHMARK(Parse_CompositeFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - -BENCHMARK(Evaluate_CompositeFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - +BENCHMARK(Parse_CompositeFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); +BENCHMARK(Evaluate_CompositeFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); diff --git a/benchmark/function/source_function.benchmark.cpp b/benchmark/function/source_function.benchmark.cpp index 2056fe706e2..6e75ac1206c 100644 --- a/benchmark/function/source_function.benchmark.cpp +++ b/benchmark/function/source_function.benchmark.cpp @@ -28,7 +28,9 @@ static void Parse_SourceFunction(benchmark::State& state) { state.PauseTiming(); auto doc = createFunctionJSON(stopCount); state.ResumeTiming(); - std::optional> result = conversion::convertJSON>(doc, error, true, false); + std::optional> result = conversion::convertJSON>( + doc, error, true, false + ); if (!result) { state.SkipWithError(error.message.c_str()); } @@ -40,22 +42,22 @@ static void Evaluate_SourceFunction(benchmark::State& state) { size_t stopCount = state.range(0); auto doc = createFunctionJSON(stopCount); conversion::Error error; - std::optional> function = conversion::convertJSON>(doc, error, true, false); + std::optional> function = conversion::convertJSON>( + doc, error, true, false + ); if (!function) { state.SkipWithError(error.message.c_str()); } - while(state.KeepRunning()) { - function->asExpression().evaluate(StubGeometryTileFeature(PropertyMap { { "x", static_cast(rand() % 100) } }), -1.0f); + while (state.KeepRunning()) { + function->asExpression().evaluate( + StubGeometryTileFeature(PropertyMap{{"x", static_cast(rand() % 100)}}), -1.0f + ); } state.SetLabel(std::to_string(stopCount).c_str()); } -BENCHMARK(Parse_SourceFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - -BENCHMARK(Evaluate_SourceFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - +BENCHMARK(Parse_SourceFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); +BENCHMARK(Evaluate_SourceFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); diff --git a/benchmark/parse/filter.benchmark.cpp b/benchmark/parse/filter.benchmark.cpp index 7f94d9d7446..fd19d708ea4 100644 --- a/benchmark/parse/filter.benchmark.cpp +++ b/benchmark/parse/filter.benchmark.cpp @@ -22,7 +22,7 @@ static void Parse_Filter(benchmark::State& state) { static void Parse_EvaluateFilter(benchmark::State& state) { const style::Filter filter = parse(R"FILTER(["==", "foo", "bar"])FILTER"); - const StubGeometryTileFeature feature = { {}, FeatureType::Unknown , {}, {{ "foo", std::string("bar") }} }; + const StubGeometryTileFeature feature = {{}, FeatureType::Unknown, {}, {{"foo", std::string("bar")}}}; const style::expression::EvaluationContext context(&feature); while (state.KeepRunning()) { diff --git a/benchmark/parse/tile_mask.benchmark.cpp b/benchmark/parse/tile_mask.benchmark.cpp index a31e0b5eab6..226b1e0e57c 100644 --- a/benchmark/parse/tile_mask.benchmark.cpp +++ b/benchmark/parse/tile_mask.benchmark.cpp @@ -7,11 +7,8 @@ using namespace mbgl; class FakeTile { public: FakeTile(TileMask mask_) - : mask(std::move(mask_)) { - } - void setMask(TileMask mask_) { - mask = std::move(mask_); - } + : mask(std::move(mask_)) {} + void setMask(TileMask mask_) { mask = std::move(mask_); } const bool usedByRenderedLayers = true; TileMask mask; @@ -19,13 +16,13 @@ class FakeTile { static void TileMaskGeneration(benchmark::State& state) { std::map renderables = { - { UnwrappedTileID{ 12, 1028, 1456 }, TileMask{} }, - { UnwrappedTileID{ 13, 2056, 2912 }, TileMask{} }, - { UnwrappedTileID{ 13, 2056, 2913 }, TileMask{} }, - { UnwrappedTileID{ 14, 4112, 5824 }, TileMask{} }, - { UnwrappedTileID{ 14, 4112, 5827 }, TileMask{} }, - { UnwrappedTileID{ 14, 4114, 5824 }, TileMask{} }, - { UnwrappedTileID{ 14, 4114, 5825 }, TileMask{} }, + {UnwrappedTileID{12, 1028, 1456}, TileMask{}}, + {UnwrappedTileID{13, 2056, 2912}, TileMask{}}, + {UnwrappedTileID{13, 2056, 2913}, TileMask{}}, + {UnwrappedTileID{14, 4112, 5824}, TileMask{}}, + {UnwrappedTileID{14, 4112, 5827}, TileMask{}}, + {UnwrappedTileID{14, 4114, 5824}, TileMask{}}, + {UnwrappedTileID{14, 4114, 5825}, TileMask{}}, }; while (state.KeepRunning()) { diff --git a/benchmark/parse/vector_tile.benchmark.cpp b/benchmark/parse/vector_tile.benchmark.cpp index b87241a2c5a..f2e4b5ecef1 100644 --- a/benchmark/parse/vector_tile.benchmark.cpp +++ b/benchmark/parse/vector_tile.benchmark.cpp @@ -6,7 +6,8 @@ using namespace mbgl; static void Parse_VectorTile(benchmark::State& state) { - auto data = std::make_shared(util::read_file("test/fixtures/api/assets/streets/10-163-395.vector.pbf")); + auto data = std::make_shared(util::read_file("test/fixtures/api/assets/streets/10-163-395.vector.pbf") + ); while (state.KeepRunning()) { std::size_t length = 0; diff --git a/benchmark/src/mbgl/benchmark/stub_geometry_tile_feature.hpp b/benchmark/src/mbgl/benchmark/stub_geometry_tile_feature.hpp index fe19cbb313f..b018313a94c 100644 --- a/benchmark/src/mbgl/benchmark/stub_geometry_tile_feature.hpp +++ b/benchmark/src/mbgl/benchmark/stub_geometry_tile_feature.hpp @@ -8,34 +8,28 @@ using namespace mbgl; class StubGeometryTileFeature : public GeometryTileFeature { public: StubGeometryTileFeature(PropertyMap properties_) - : properties(std::move(properties_)) { - } + : properties(std::move(properties_)) {} - StubGeometryTileFeature(FeatureIdentifier id_, FeatureType type_, GeometryCollection geometry_, PropertyMap properties_) + StubGeometryTileFeature( + FeatureIdentifier id_, FeatureType type_, GeometryCollection geometry_, PropertyMap properties_ + ) : properties(std::move(properties_)), id(std::move(id_)), type(type_), - geometry(std::move(geometry_)) { - } + geometry(std::move(geometry_)) {} PropertyMap properties; FeatureIdentifier id; FeatureType type = FeatureType::Point; GeometryCollection geometry; - FeatureType getType() const override { - return type; - } + FeatureType getType() const override { return type; } - FeatureIdentifier getID() const override { - return id; - } + FeatureIdentifier getID() const override { return id; } std::optional getValue(const std::string& key) const override { return properties.count(key) ? properties.at(key) : std::optional(); } - const GeometryCollection& getGeometries() const override { - return geometry; - } + const GeometryCollection& getGeometries() const override { return geometry; } }; diff --git a/benchmark/storage/offline_database.benchmark.cpp b/benchmark/storage/offline_database.benchmark.cpp index 09da8bcb067..82d8e6cd0b9 100644 --- a/benchmark/storage/offline_database.benchmark.cpp +++ b/benchmark/storage/offline_database.benchmark.cpp @@ -30,7 +30,9 @@ class OfflineDatabase : public benchmark::Fixture { db.clearAmbientCache(); for (unsigned i = 0; i < tileCount; ++i) { - const Resource ambient = Resource::tile("mapbox://tile_ambient" + util::toString(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://tile_ambient" + util::toString(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambient, response); } } @@ -43,14 +45,17 @@ class OfflineDatabase : public benchmark::Fixture { db.deleteRegion(std::move(regions[0])); } - OfflineTilePyramidRegionDefinition definition{ "mapbox://style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "mapbox://style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); regionID = region->getID(); for (unsigned i = 0; i < tileCount; ++i) { - const Resource offline = Resource::tile("mapbox://tile_offline_region" + util::toString(i), 1.0, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource offline = Resource::tile( + "mapbox://tile_offline_region" + util::toString(i), 1.0, 0, 0, 0, Tileset::Scheme::XYZ + ); db.putRegionResource(regionID, offline, response); } } @@ -78,8 +83,9 @@ BENCHMARK_F(OfflineDatabase, InsertTileRegion)(benchmark::State& state) { using namespace mbgl; while (state.KeepRunning()) { - const Resource offline = Resource::tile("mapbox://InsertTileRegion" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource offline = Resource::tile( + "mapbox://InsertTileRegion" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.putRegionResource(regionID, offline, response); } } @@ -99,8 +105,9 @@ BENCHMARK_F(OfflineDatabase, InsertTileCache)(benchmark::State& state) { using namespace mbgl; while (state.KeepRunning()) { - const Resource ambient = Resource::tile("mapbox://InsertTileCache" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://InsertTileCache" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambient, response); } } @@ -112,8 +119,9 @@ BENCHMARK_F(OfflineDatabase, InsertBigTileCache)(benchmark::State& state) { big.data = std::make_shared(util::DEFAULT_MAX_CACHE_SIZE / 100, 0); while (state.KeepRunning()) { - const Resource ambient = Resource::tile("mapbox://InsertTileCache" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://InsertTileCache" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambient, big); } } @@ -126,7 +134,9 @@ BENCHMARK_F(OfflineDatabase, GetTile)(benchmark::State& state) { std::uniform_int_distribution<> dis(0, tileCount - 1); while (state.KeepRunning()) { - auto res = db.get(Resource::tile("mapbox://tile_ambient" + util::toString(dis(gen)), 1, 0, 0, 0, Tileset::Scheme::XYZ)); + auto res = db.get( + Resource::tile("mapbox://tile_ambient" + util::toString(dis(gen)), 1, 0, 0, 0, Tileset::Scheme::XYZ) + ); assert(res != std::nullopt); } } @@ -138,8 +148,9 @@ BENCHMARK_F(OfflineDatabase, AddTilesToFullDatabase)(benchmark::State& state) { db.setMaximumAmbientCacheSize(50 * 1024 * 5); while (state.KeepRunning()) { - const Resource ambient = Resource::tile("mapbox://AddTilesToFullDatabase" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://AddTilesToFullDatabase" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambient, response); } @@ -158,8 +169,9 @@ BENCHMARK_F(OfflineDatabase, AddTilesToDisabledDatabase)(benchmark::State& state db.setMaximumAmbientCacheSize(0); while (state.KeepRunning()) { - const Resource ambient = Resource::tile("mapbox://AddTilesToFullDatabase" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://AddTilesToFullDatabase" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambient, response); } } diff --git a/benchmark/util/tilecover.benchmark.cpp b/benchmark/util/tilecover.benchmark.cpp index dbac201bfd0..b3c63c61e81 100644 --- a/benchmark/util/tilecover.benchmark.cpp +++ b/benchmark/util/tilecover.benchmark.cpp @@ -7,8 +7,7 @@ using namespace mbgl; -static const LatLngBounds sanFrancisco = - LatLngBounds::hull({ 37.6609, -122.5744 }, { 37.8271, -122.3204 }); +static const LatLngBounds sanFrancisco = LatLngBounds::hull({37.6609, -122.5744}, {37.8271, -122.3204}); static void TileCountBounds(benchmark::State& state) { std::size_t length = 0; @@ -21,9 +20,9 @@ static void TileCountBounds(benchmark::State& state) { static void TileCoverPitchedViewport(benchmark::State& state) { Transform transform; - transform.resize({ 512, 512 }); + transform.resize({512, 512}); // slightly offset center so that tile order is better defined - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.1, -0.1 }).withZoom(8.0).withBearing(5.0).withPitch(40.0)); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.1, -0.1}).withZoom(8.0).withBearing(5.0).withPitch(40.0)); std::size_t length = 0; while (state.KeepRunning()) { @@ -43,32 +42,18 @@ static void TileCoverBounds(benchmark::State& state) { } static const auto geomPolygon = Polygon{ - { - {-122.5143814086914,37.779127216982424}, - {-122.50811576843262,37.72721239056709}, - {-122.50313758850099,37.70820178063929}, - {-122.3938751220703,37.707454835665274}, - {-122.37567901611328,37.70663997801684}, - {-122.36297607421874,37.71343018466285}, - {-122.354736328125,37.727280276860036}, - {-122.36469268798828,37.73868429065797}, - {-122.38014221191408,37.75442980295571}, - {-122.38391876220702,37.78753873820529}, - {-122.35919952392578,37.8065289741725}, - {-122.35679626464844,37.820632846207864}, - {-122.3712158203125,37.835276322922695}, - {-122.3818588256836,37.82958198283902}, - {-122.37190246582031,37.80788523279169}, - {-122.38735198974608,37.791337175930686}, - {-122.40966796874999,37.812767557570204}, - {-122.46425628662108,37.807071480609274}, - {-122.46803283691405,37.810326435534755}, - {-122.47901916503906,37.81168262440736}, - {-122.48966217041016,37.78916666399649}, - {-122.50579833984375,37.78781006166096}, - {-122.5143814086914,37.779127216982424} - } -}; + {{-122.5143814086914, 37.779127216982424}, {-122.50811576843262, 37.72721239056709}, + {-122.50313758850099, 37.70820178063929}, {-122.3938751220703, 37.707454835665274}, + {-122.37567901611328, 37.70663997801684}, {-122.36297607421874, 37.71343018466285}, + {-122.354736328125, 37.727280276860036}, {-122.36469268798828, 37.73868429065797}, + {-122.38014221191408, 37.75442980295571}, {-122.38391876220702, 37.78753873820529}, + {-122.35919952392578, 37.8065289741725}, {-122.35679626464844, 37.820632846207864}, + {-122.3712158203125, 37.835276322922695}, {-122.3818588256836, 37.82958198283902}, + {-122.37190246582031, 37.80788523279169}, {-122.38735198974608, 37.791337175930686}, + {-122.40966796874999, 37.812767557570204}, {-122.46425628662108, 37.807071480609274}, + {-122.46803283691405, 37.810326435534755}, {-122.47901916503906, 37.81168262440736}, + {-122.48966217041016, 37.78916666399649}, {-122.50579833984375, 37.78781006166096}, + {-122.5143814086914, 37.779127216982424}}}; static void TileCoverPolygon(benchmark::State& state) { std::size_t length = 0; @@ -95,4 +80,3 @@ BENCHMARK(TileCountPolygon); BENCHMARK(TileCoverPitchedViewport); BENCHMARK(TileCoverBounds); BENCHMARK(TileCoverPolygon); - diff --git a/bin/cache.cpp b/bin/cache.cpp index 179cd9dc8c4..a9d878d4006 100644 --- a/bin/cache.cpp +++ b/bin/cache.cpp @@ -19,20 +19,23 @@ int main(int argc, char* argv[]) { args::ValueFlag urlValue(p, "URL", "Resource URL (required)", {'u'}, args::Options::Required); args::ValueFlag cacheValue( - p, "cache", "Path to the cache database (required)", {'c'}, args::Options::Required); + p, "cache", "Path to the cache database (required)", {'c'}, args::Options::Required + ); args::ValueFlag dataValue( - p, "data", "Path to the resource data (required)", {'d'}, args::Options::Required); + p, "data", "Path to the resource data (required)", {'d'}, args::Options::Required + ); args::ValueFlag etagValue(p, "etag", "Cache eTag, none otherwise", {'t'}); args::ValueFlag expiresValue(p, "expires", "Expires date, will use 'now' otherwise", {'e'}); args::ValueFlag modifiedValue(p, "modified", "Modified date, will use 'now' otherwise", {'m'}); - std::unordered_map typeMap{{"glyphs", mbgl::Resource::Glyphs}, - {"image", mbgl::Resource::Image}, - {"source", mbgl::Resource::Source}, - {"sprite-image", mbgl::Resource::SpriteImage}, - {"sprite-json", mbgl::Resource::SpriteJSON}, - {"style", mbgl::Resource::Style}, - {"tile", mbgl::Resource::Tile}}; + std::unordered_map typeMap{ + {"glyphs", mbgl::Resource::Glyphs}, + {"image", mbgl::Resource::Image}, + {"source", mbgl::Resource::Source}, + {"sprite-image", mbgl::Resource::SpriteImage}, + {"sprite-json", mbgl::Resource::SpriteJSON}, + {"style", mbgl::Resource::Style}, + {"tile", mbgl::Resource::Tile}}; std::string typeHelp("One of the following (required):"); for (auto key : typeMap) { @@ -40,7 +43,8 @@ int main(int argc, char* argv[]) { } args::MapFlag typeFlag( - p, "type", typeHelp, {"type"}, typeMap, args::Options::Required); + p, "type", typeHelp, {"type"}, typeMap, args::Options::Required + ); args::Group tileIdGroup(p, "Coordinates (required for 'tile')", args::Group::Validators::AllOrNone); args::ValueFlag xValueFlag(tileIdGroup, "x", "Tile x coordinate", {'x'}); @@ -82,16 +86,18 @@ int main(int argc, char* argv[]) { exit(1); } - resource.tileData = {{args::get(urlValue), - 1, - args::get(xValueFlag), - args::get(yValueFlag), - static_cast(args::get(zValueFlag))}}; + resource.tileData = { + {args::get(urlValue), + 1, + args::get(xValueFlag), + args::get(yValueFlag), + static_cast(args::get(zValueFlag))}}; } mbgl::util::RunLoop loop; std::shared_ptr dbfs = mbgl::FileSourceManager::get()->getFileSource( - mbgl::FileSourceType::Database, mbgl::ResourceOptions().withCachePath(args::get(cacheValue))); + mbgl::FileSourceType::Database, mbgl::ResourceOptions().withCachePath(args::get(cacheValue)) + ); dbfs->forward(resource, response, [&loop] { loop.stop(); }); loop.run(); return 0; diff --git a/bin/offline.cpp b/bin/offline.cpp index 1025608009b..837505389a2 100644 --- a/bin/offline.cpp +++ b/bin/offline.cpp @@ -24,11 +24,11 @@ std::string readFile(const std::string& fileName) { if (!stream.good()) { throw std::runtime_error("Cannot read file: " + fileName); } - + std::stringstream buffer; buffer << stream.rdbuf(); stream.close(); - + return buffer.str(); } @@ -36,40 +36,37 @@ mapbox::geometry::geometry parseGeometry(const std::string& json) { using namespace mapbox::geojson; auto geojson = parse(json); return geojson.match( - [](const geometry& geom) { - return geom; - }, - [](const feature& feature) { - return feature.geometry; - }, + [](const geometry& geom) { return geom; }, + [](const feature& feature) { return feature.geometry; }, [](const feature_collection& featureCollection) { if (featureCollection.size() < 1) { throw std::runtime_error("No features in feature collection"); } geometry_collection geometries; - + for (auto feature : featureCollection) { geometries.push_back(feature.geometry); } - + return geometries; - }); + } + ); } std::ostream& operator<<(std::ostream& os, mbgl::Response::Error::Reason r) { switch (r) { - case mbgl::Response::Error::Reason::Success: - return os << "Response::Error::Reason::Success"; - case mbgl::Response::Error::Reason::NotFound: - return os << "Response::Error::Reason::NotFound"; - case mbgl::Response::Error::Reason::Server: - return os << "Response::Error::Reason::Server"; - case mbgl::Response::Error::Reason::Connection: - return os << "Response::Error::Reason::Connection"; - case mbgl::Response::Error::Reason::RateLimit: - return os << "Response::Error::Reason::RateLimit"; - case mbgl::Response::Error::Reason::Other: - return os << "Response::Error::Reason::Other"; + case mbgl::Response::Error::Reason::Success: + return os << "Response::Error::Reason::Success"; + case mbgl::Response::Error::Reason::NotFound: + return os << "Response::Error::Reason::NotFound"; + case mbgl::Response::Error::Reason::Server: + return os << "Response::Error::Reason::Server"; + case mbgl::Response::Error::Reason::Connection: + return os << "Response::Error::Reason::Connection"; + case mbgl::Response::Error::Reason::RateLimit: + return os << "Response::Error::Reason::RateLimit"; + case mbgl::Response::Error::Reason::Other: + return os << "Response::Error::Reason::Other"; } // The above switch is exhaustive, but placate GCC nonetheless: @@ -77,7 +74,7 @@ std::ostream& operator<<(std::ostream& os, mbgl::Response::Error::Reason r) { return os; } -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { args::ArgumentParser argumentParser("Mapbox GL offline tool"); args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {'h', "help"}); @@ -85,10 +82,12 @@ int main(int argc, char *argv[]) { args::ValueFlag styleValue(argumentParser, "URL", "Map stylesheet", {'s', "style"}); args::ValueFlag outputValue(argumentParser, "file", "Output database file name", {'o', "output"}); args::ValueFlag apiBaseValue(argumentParser, "URL", "API Base URL", {'a', "apiBaseURL"}); - + args::Group mergeGroup(argumentParser, "Merge databases:", args::Group::Validators::AllOrNone); args::ValueFlag mergePathValue(mergeGroup, "merge", "Database to merge from", {'m', "merge"}); - args::ValueFlag inputValue(mergeGroup, "input", "Database to merge into. Use with --merge option.", {'i', "input"}); + args::ValueFlag inputValue( + mergeGroup, "input", "Database to merge into. Use with --merge option.", {'i', "input"} + ); // LatLngBounds args::Group latLngBoundsGroup(argumentParser, "LatLng bounds:", args::Group::Validators::AllOrNone); @@ -99,12 +98,19 @@ int main(int argc, char *argv[]) { // Geometry args::Group geoJSONGroup(argumentParser, "GeoJson geometry:", args::Group::Validators::AllOrNone); - args::ValueFlag geometryValue(geoJSONGroup, "file", "GeoJSON Feature file containing the region geometry (can't be a FeatureCollection)", {"geojson"}); + args::ValueFlag geometryValue( + geoJSONGroup, + "file", + "GeoJSON Feature file containing the region geometry (can't be a FeatureCollection)", + {"geojson"} + ); args::ValueFlag minZoomValue(argumentParser, "number", "Min zoom level", {"minZoom"}); args::ValueFlag maxZoomValue(argumentParser, "number", "Max zoom level", {"maxZoom"}); args::ValueFlag pixelRatioValue(argumentParser, "number", "Pixel ratio", {"pixelRatio"}); - args::ValueFlag includeIdeographsValue(argumentParser, "boolean", "Include CJK glyphs", {"includeIdeographs"}); + args::ValueFlag includeIdeographsValue( + argumentParser, "boolean", "Include CJK glyphs", {"includeIdeographs"} + ); try { argumentParser.ParseCLI(argc, argv); @@ -122,10 +128,10 @@ int main(int argc, char *argv[]) { } auto mapTilerConfiguration = mbgl::TileServerOptions::MapTilerConfiguration(); - + std::string style = styleValue ? args::get(styleValue) : mapTilerConfiguration.defaultStyles().at(0).getUrl(); std::cout << " Style: " << style << std::endl; - + std::optional mergePath = std::nullopt; if (mergePathValue) mergePath = args::get(mergePathValue); std::optional inputDb = std::nullopt; @@ -136,16 +142,18 @@ int main(int argc, char *argv[]) { const double pixelRatio = pixelRatioValue ? args::get(pixelRatioValue) : 1.0; const bool includeIdeographs = includeIdeographsValue ? args::get(includeIdeographsValue) : false; const std::string output = outputValue ? args::get(outputValue) : "offline.db"; - + using namespace mbgl; - + OfflineRegionDefinition definition = [&]() { if (geometryValue) { try { std::string json = readFile(geometryValue.Get()); auto geometry = parseGeometry(json); - return OfflineRegionDefinition{ OfflineGeometryRegionDefinition(style, geometry, minZoom, maxZoom, static_cast(pixelRatio), includeIdeographs) }; - } catch(const std::runtime_error& e) { + return OfflineRegionDefinition{OfflineGeometryRegionDefinition( + style, geometry, minZoom, maxZoom, static_cast(pixelRatio), includeIdeographs + )}; + } catch (const std::runtime_error& e) { std::cerr << "Could not parse geojson file " << geometryValue.Get() << ": " << e.what() << std::endl; exit(1); } @@ -156,13 +164,15 @@ int main(int argc, char *argv[]) { const double south = southValue ? args::get(southValue) : 38.1; const double east = eastValue ? args::get(eastValue) : -121.7; LatLngBounds boundingBox = LatLngBounds::hull(LatLng(north, west), LatLng(south, east)); - return OfflineRegionDefinition{ OfflineTilePyramidRegionDefinition(style, boundingBox, minZoom, maxZoom, static_cast(pixelRatio), includeIdeographs) }; + return OfflineRegionDefinition{OfflineTilePyramidRegionDefinition( + style, boundingBox, minZoom, maxZoom, static_cast(pixelRatio), includeIdeographs + )}; } }(); const char* apiEnv = getenv("MLN_API_KEY"); const std::string apiKey = tokenValue ? args::get(tokenValue) : (apiEnv ? apiEnv : std::string()); - + if (apiBaseValue) { mapTilerConfiguration.withBaseURL(args::get(apiBaseValue)); } @@ -171,10 +181,10 @@ int main(int argc, char *argv[]) { std::shared_ptr fileSource = std::static_pointer_cast( std::shared_ptr(FileSourceManager::get()->getFileSource( FileSourceType::Database, - ResourceOptions().withApiKey(apiKey) - .withTileServerOptions(mapTilerConfiguration) - .withCachePath(output), - ClientOptions()))); + ResourceOptions().withApiKey(apiKey).withTileServerOptions(mapTilerConfiguration).withCachePath(output), + ClientOptions() + )) + ); std::unique_ptr region; @@ -183,17 +193,19 @@ int main(int argc, char *argv[]) { int retCode = 0; std::cout << "Start Merge" << std::endl; - inputSource.mergeOfflineRegions(*mergePath, [&] (mbgl::expected, std::exception_ptr> result) { - - if (!result) { - std::cerr << "Error merging database: " << util::toString(result.error()) << std::endl; - retCode = 1; - } else { - std::cout << " Added " << result->size() << " Regions" << std::endl; - std::cout << "Finished Merge" << std::endl; + inputSource.mergeOfflineRegions( + *mergePath, + [&](mbgl::expected, std::exception_ptr> result) { + if (!result) { + std::cerr << "Error merging database: " << util::toString(result.error()) << std::endl; + retCode = 1; + } else { + std::cout << " Added " << result->size() << " Regions" << std::endl; + std::cout << "Finished Merge" << std::endl; + } + loop.stop(); } - loop.stop(); - }); + ); loop.run(); return retCode; } @@ -202,10 +214,12 @@ int main(int argc, char *argv[]) { class Observer : public OfflineRegionObserver { public: - Observer(OfflineRegion& region_, - std::shared_ptr fileSource_, - util::RunLoop& loop_, - std::optional mergePath_) + Observer( + OfflineRegion& region_, + std::shared_ptr fileSource_, + util::RunLoop& loop_, + std::optional mergePath_ + ) : region(region_), fileSource(std::move(fileSource_)), loop(loop_), @@ -260,10 +274,10 @@ int main(int argc, char *argv[]) { } }; - std::signal(SIGINT, [] (int) { stop(); }); + std::signal(SIGINT, [](int) { stop(); }); - fileSource->createOfflineRegion( - definition, metadata, [&](mbgl::expected region_) { + fileSource + ->createOfflineRegion(definition, metadata, [&](mbgl::expected region_) { if (!region_) { std::cerr << "Error creating region: " << util::toString(region_.error()) << std::endl; loop.stop(); @@ -271,8 +285,9 @@ int main(int argc, char *argv[]) { } else { assert(region_); region = std::make_unique(std::move(*region_)); - fileSource->setOfflineRegionObserver(*region, - std::make_unique(*region, fileSource, loop, mergePath)); + fileSource->setOfflineRegionObserver( + *region, std::make_unique(*region, fileSource, loop, mergePath) + ); fileSource->setOfflineRegionDownloadState(*region, OfflineRegionDownloadState::Active); } }); diff --git a/bin/render.cpp b/bin/render.cpp index 3f704fe026f..c364225bbcf 100644 --- a/bin/render.cpp +++ b/bin/render.cpp @@ -13,7 +13,7 @@ #include #include -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { args::ArgumentParser argumentParser("Mapbox GL render tool"); args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {"help"}); @@ -22,7 +22,9 @@ int main(int argc, char *argv[]) { args::ValueFlag styleValue(argumentParser, "URL", "Map stylesheet", {'s', "style"}); args::ValueFlag outputValue(argumentParser, "file", "Output file name", {'o', "output"}); args::ValueFlag cacheValue(argumentParser, "file", "Cache database file name", {'c', "cache"}); - args::ValueFlag assetsValue(argumentParser, "file", "Directory to which asset:// URLs will resolve", {'a', "assets"}); + args::ValueFlag assetsValue( + argumentParser, "file", "Directory to which asset:// URLs will resolve", {'a', "assets"} + ); args::Flag debugFlag(argumentParser, "debug", "Debug mode", {"debug"}); @@ -78,31 +80,40 @@ int main(int argc, char *argv[]) { util::RunLoop loop; - HeadlessFrontend frontend({ width, height }, static_cast(pixelRatio)); - Map map(frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()).withPixelRatio(static_cast(pixelRatio)), - ResourceOptions().withCachePath(cache_file).withAssetPath(asset_root).withApiKey(apikey).withTileServerOptions(mapTilerConfiguration)); + HeadlessFrontend frontend({width, height}, static_cast(pixelRatio)); + Map map( + frontend, + MapObserver::nullObserver(), + MapOptions() + .withMapMode(MapMode::Static) + .withSize(frontend.getSize()) + .withPixelRatio(static_cast(pixelRatio)), + ResourceOptions() + .withCachePath(cache_file) + .withAssetPath(asset_root) + .withApiKey(apikey) + .withTileServerOptions(mapTilerConfiguration) + ); if (style.find("://") == std::string::npos) { style = std::string("file://") + style; } map.getStyle().loadURL(style); - map.jumpTo(CameraOptions() - .withCenter(LatLng { lat, lon }) - .withZoom(zoom) - .withBearing(bearing) - .withPitch(pitch)); + map.jumpTo(CameraOptions().withCenter(LatLng{lat, lon}).withZoom(zoom).withBearing(bearing).withPitch(pitch)); if (debug) { - map.setDebug(debug ? mbgl::MapDebugOptions::TileBorders | mbgl::MapDebugOptions::ParseStatus : mbgl::MapDebugOptions::NoDebug); + map.setDebug( + debug ? mbgl::MapDebugOptions::TileBorders | mbgl::MapDebugOptions::ParseStatus + : mbgl::MapDebugOptions::NoDebug + ); } try { std::ofstream out(output, std::ios::binary); out << encodePNG(frontend.render(map).image); out.close(); - } catch(std::exception& e) { + } catch (std::exception& e) { std::cout << "Error: " << e.what() << std::endl; exit(1); } diff --git a/expression-test/expression_test_logger.cpp b/expression-test/expression_test_logger.cpp index 9127a6d7aed..7d2333769e3 100644 --- a/expression-test/expression_test_logger.cpp +++ b/expression-test/expression_test_logger.cpp @@ -60,7 +60,7 @@ document.getElementById('toggle-sequence').addEventListener('click', function (e std::string createResultItem(const TestRunOutput& result, const std::string& status, bool shouldHide) { std::ostringstream html; html << "
\n"; - html << R"(

)" << status << " " << result.id << "

\n"; + html << R"(

)" << status << " " << result.id << "

\n"; html << "

"s << result.expression << "

\n"s; if (result.passed) { @@ -98,11 +98,11 @@ std::string createResultPage(const TestStats& stats, bool shuffle, uint32_t seed // Failed tests if (unsuccessful) { - resultsPage << "

Failed tests:"; + resultsPage << "

Failed tests:"; for (const auto& failed : stats.failed) { resultsPage << failed.id << " "; } - resultsPage << "

Errored tests:"; + resultsPage << "

Errored tests:"; for (const auto& errored : stats.errored) { resultsPage << errored.id << " "; } @@ -127,9 +127,9 @@ std::string createResultPage(const TestStats& stats, bool shuffle, uint32_t seed // Script resultsPage << resultsScript; - // Tests + // Tests resultsPage << "

\n"; - const auto appendResult = [&] (const auto& results, const std::string& status, bool hide = false) { + const auto appendResult = [&](const auto& results, const std::string& status, bool hide = false) { for (const auto& result : results) { resultsPage << createResultItem(result, status, hide); } @@ -153,16 +153,26 @@ void printStats(const TestStats& stats) { printf(ANSI_COLOR_GREEN "%zu passed (%.1lf%%)" ANSI_COLOR_RESET "\n", passedTests, 100.0 * passedTests / count); } if (std::size_t ignorePassedTests = stats.ignorePassed.size()) { - printf(ANSI_COLOR_YELLOW "%zu passed but were ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", ignorePassedTests, 100.0 * ignorePassedTests / count); + printf( + ANSI_COLOR_YELLOW "%zu passed but were ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", + ignorePassedTests, + 100.0 * ignorePassedTests / count + ); } if (std::size_t ignoreFailedTests = stats.ignoreFailed.size()) { - printf(ANSI_COLOR_LIGHT_GRAY "%zu ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", ignoreFailedTests, 100.0 * ignoreFailedTests / count); + printf( + ANSI_COLOR_LIGHT_GRAY "%zu ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", + ignoreFailedTests, + 100.0 * ignoreFailedTests / count + ); } if (std::size_t failedTests = stats.failed.size()) { printf(ANSI_COLOR_RED "%zu failed (%.1lf%%)" ANSI_COLOR_RESET "\n", failedTests, 100.0 * failedTests / count); } if (std::size_t erroredTests = stats.errored.size()) { - printf(ANSI_COLOR_RED "%zu errored (%.1lf%%)" ANSI_COLOR_RESET "\n", erroredTests, 100.0 * erroredTests / count); + printf( + ANSI_COLOR_RED "%zu errored (%.1lf%%)" ANSI_COLOR_RESET "\n", erroredTests, 100.0 * erroredTests / count + ); } } diff --git a/expression-test/expression_test_logger.hpp b/expression-test/expression_test_logger.hpp index ae03476fa3e..e8dabcedf86 100644 --- a/expression-test/expression_test_logger.hpp +++ b/expression-test/expression_test_logger.hpp @@ -3,11 +3,11 @@ #include #include -#define ANSI_COLOR_RED "\x1b[31m" -#define ANSI_COLOR_GREEN "\x1b[32m" -#define ANSI_COLOR_YELLOW "\x1b[33m" +#define ANSI_COLOR_RED "\x1b[31m" +#define ANSI_COLOR_GREEN "\x1b[32m" +#define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_LIGHT_GRAY "\x1b[90m" -#define ANSI_COLOR_RESET "\x1b[0m" +#define ANSI_COLOR_RESET "\x1b[0m" class TestStats; diff --git a/expression-test/expression_test_parser.cpp b/expression-test/expression_test_parser.cpp index ca504a01424..a5622b8898e 100644 --- a/expression-test/expression_test_parser.cpp +++ b/expression-test/expression_test_parser.cpp @@ -29,22 +29,22 @@ namespace { void writeJSON(rapidjson::PrettyWriter& writer, const Value& value) { value.match( - [&] (const NullValue&) { writer.Null(); }, - [&] (bool b) { writer.Bool(b); }, - [&] (uint64_t u) { writer.Uint64(u); }, - [&] (int64_t i) { writer.Int64(i); }, - [&] (double d) { d == std::floor(d) ? writer.Int64(static_cast(d)) : writer.Double(d); }, - [&] (const std::string& s) { writer.String(s); }, - [&] (const std::vector& arr) { + [&](const NullValue&) { writer.Null(); }, + [&](bool b) { writer.Bool(b); }, + [&](uint64_t u) { writer.Uint64(u); }, + [&](int64_t i) { writer.Int64(i); }, + [&](double d) { d == std::floor(d) ? writer.Int64(static_cast(d)) : writer.Double(d); }, + [&](const std::string& s) { writer.String(s); }, + [&](const std::vector& arr) { writer.StartArray(); - for(const auto& item : arr) { + for (const auto& item : arr) { writeJSON(writer, item); } writer.EndArray(); }, - [&] (const std::unordered_map& obj) { + [&](const std::unordered_map& obj) { writer.StartObject(); - for(const auto& entry : obj) { + for (const auto& entry : obj) { writer.Key(entry.first.c_str()); writeJSON(writer, entry.second); } @@ -58,21 +58,21 @@ using JSONReply = variant; JSONReply readJson(const filesystem::path& jsonPath) { auto maybeJSON = util::readFile(jsonPath); if (!maybeJSON) { - return { "Unable to open file "s + jsonPath.string() }; + return {"Unable to open file "s + jsonPath.string()}; } JSDocument document; document.Parse(*maybeJSON); if (document.HasParseError()) { - return { formatJSONParseError(document) }; + return {formatJSONParseError(document)}; } - return { std::move(document) }; + return {std::move(document)}; } std::string toString(const JSValue& value) { assert(value.IsString()); - return { value.GetString(), value.GetStringLength() }; + return {value.GetString(), value.GetStringLength()}; } std::optional toValue(const JSValue& jsvalue) { @@ -269,7 +269,8 @@ bool parseInputs(const JSValue& inputsValue, TestData& data) { assert(canonicalIDObject.HasMember("x") && canonicalIDObject["x"].IsNumber()); assert(canonicalIDObject.HasMember("y") && canonicalIDObject["y"].IsNumber()); canonical = CanonicalTileID( - canonicalIDObject["z"].GetUint(), canonicalIDObject["x"].GetUint(), canonicalIDObject["y"].GetUint()); + canonicalIDObject["z"].GetUint(), canonicalIDObject["x"].GetUint(), canonicalIDObject["y"].GetUint() + ); } // Parse availableImages @@ -300,11 +301,13 @@ bool parseInputs(const JSValue& inputsValue, TestData& data) { feature.id = mapbox::geojson::convert(featureObject["id"]); } - data.inputs.emplace_back(std::move(zoom), - std::move(heatmapDensity), - std::move(canonical), - std::move(availableImages), - std::move(feature)); + data.inputs.emplace_back( + std::move(zoom), + std::move(heatmapDensity), + std::move(canonical), + std::move(availableImages), + std::move(feature) + ); } return true; } @@ -314,10 +317,9 @@ bool parseInputs(const JSValue& inputsValue, TestData& data) { std::tuple, bool, uint32_t> parseArguments(int argc, char** argv) { args::ArgumentParser argumentParser("Mapbox GL Expression Test Runner"); - args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", { 'h', "help" }); + args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {'h', "help"}); args::Flag shuffleFlag(argumentParser, "shuffle", "Toggle shuffling the tests order", {'s', "shuffle"}); - args::ValueFlag seedValue(argumentParser, "seed", "Shuffle seed (default: random)", - { "seed" }); + args::ValueFlag seedValue(argumentParser, "seed", "Shuffle seed (default: random)", {"seed"}); args::PositionalList testNameValues(argumentParser, "URL", "Test name(s)"); args::ValueFlag testFilterValue(argumentParser, "filter", "Test filter regex", {'f', "filter"}); @@ -342,7 +344,7 @@ std::tuple, bool, uint32_t> pars exit(2); } - filesystem::path rootPath {std::string(TEST_RUNNER_ROOT_PATH).append("/metrics/integration/expression-tests")}; + filesystem::path rootPath{std::string(TEST_RUNNER_ROOT_PATH).append("/metrics/integration/expression-tests")}; if (!filesystem::exists(rootPath)) { Log::Error(Event::General, "Test path '" + rootPath.string() + "' does not exist."); exit(3); @@ -377,10 +379,11 @@ std::tuple, bool, uint32_t> pars } } - return Arguments{ std::move(rootPath), - std::move(testPaths), - shuffleFlag ? args::get(shuffleFlag) : false, - seedValue ? args::get(seedValue) : 1u }; + return Arguments{ + std::move(rootPath), + std::move(testPaths), + shuffleFlag ? args::get(shuffleFlag) : false, + seedValue ? args::get(seedValue) : 1u}; } Ignores parseExpressionIgnores() { @@ -392,12 +395,12 @@ Ignores parseExpressionIgnores() { } for (const auto& property : maybeIgnores.get().GetObject()) { - std::string id{ toString(property.name) }; + std::string id{toString(property.name)}; // Keep only expression-test ignores if (id.rfind("expression-tests", 0) != 0) { continue; } - std::string reason{ toString(property.value) }; + std::string reason{toString(property.value)}; ignores.emplace_back(std::move(id), std::move(reason)); } @@ -474,7 +477,8 @@ Value toValue(const Compiled& compiled) { std::optional toValue(const expression::Value& exprValue) { return exprValue.match( [](const Color& c) -> std::optional { - std::vector color { static_cast(c.r), static_cast(c.g), static_cast(c.b), static_cast(c.a) }; + std::vector color{ + static_cast(c.r), static_cast(c.g), static_cast(c.b), static_cast(c.a)}; return {Value{std::move(color)}}; }, [](const expression::Formatted& formatted) -> std::optional { return {formatted.toObject()}; }, @@ -496,18 +500,18 @@ std::optional toValue(const expression::Value& exprValue) { } return {Value{std::move(mbglValueMap)}}; }, - [](const auto& v) { return expression::fromExpressionValue(v); }); + [](const auto& v) { return expression::fromExpressionValue(v); } + ); } -std::unique_ptr parseExpression(const JSValue& value, - std::optional& spec, - TestResult& result) { +std::unique_ptr parseExpression( + const JSValue& value, std::optional& spec, TestResult& result +) { std::optional expected = spec ? toExpressionType(*spec) : std::nullopt; - expression::ParsingContext ctx = expected ? expression::ParsingContext(*expected) : - expression::ParsingContext(); + expression::ParsingContext ctx = expected ? expression::ParsingContext(*expected) : expression::ParsingContext(); Convertible convertible(&value); expression::ParseResult parsed; - if (value.IsObject() && !value.IsArray() && expected){ + if (value.IsObject() && !value.IsArray() && expected) { Error error; parsed = convertFunctionToExpression(*expected, convertible, error, false /*convert tokens*/); if (!parsed) { @@ -538,9 +542,9 @@ std::unique_ptr parseExpression(const JSValue& va return nullptr; } -std::unique_ptr parseExpression(const std::optional& value, - std::optional& spec, - TestResult& result) { +std::unique_ptr parseExpression( + const std::optional& value, std::optional& spec, TestResult& result +) { assert(value); auto document = toDocument(*value); assert(!document.HasParseError()); diff --git a/expression-test/expression_test_parser.hpp b/expression-test/expression_test_parser.hpp index 2c4eaa55a70..2df374522c1 100644 --- a/expression-test/expression_test_parser.hpp +++ b/expression-test/expression_test_parser.hpp @@ -13,11 +13,13 @@ using namespace mbgl; struct Input { - Input(std::optional zoom_, - std::optional heatmapDensity_, - std::optional canonical_, - std::set availableImages_, - Feature feature_) + Input( + std::optional zoom_, + std::optional heatmapDensity_, + std::optional canonical_, + std::set availableImages_, + Feature feature_ + ) : zoom(std::move(zoom_)), heatmapDensity(std::move(heatmapDensity_)), canonical(std::move(canonical_)), @@ -32,10 +34,8 @@ struct Input { struct Compiled { bool operator==(const Compiled& other) const { - bool typeEqual = success == other.success && - isFeatureConstant == other.isFeatureConstant && - isZoomConstant == other.isZoomConstant && - serializedType == other.serializedType && + bool typeEqual = success == other.success && isFeatureConstant == other.isFeatureConstant && + isZoomConstant == other.isZoomConstant && serializedType == other.serializedType && errors == other.errors; return typeEqual; } @@ -93,10 +93,7 @@ JSDocument toDocument(const Value&); Value toValue(const Compiled&); std::optional toValue(const style::expression::Value&); -std::unique_ptr parseExpression(const JSValue&, - std::optional&, - TestResult&); -std::unique_ptr parseExpression(const std::optional&, - std::optional&, - TestResult&); - +std::unique_ptr +parseExpression(const JSValue&, std::optional&, TestResult&); +std::unique_ptr +parseExpression(const std::optional&, std::optional&, TestResult&); diff --git a/expression-test/expression_test_runner.cpp b/expression-test/expression_test_runner.cpp index c0d45116367..68c40e46b4d 100644 --- a/expression-test/expression_test_runner.cpp +++ b/expression-test/expression_test_runner.cpp @@ -18,15 +18,16 @@ using namespace std::literals; namespace { std::string simpleDiff(const Value& result, const Value& expected) { - std::vector resultTokens {tokenize(toJSON(result, 2, true))}; - std::vector expectedTokens {tokenize(toJSON(expected, 2, true))}; + std::vector resultTokens{tokenize(toJSON(result, 2, true))}; + std::vector expectedTokens{tokenize(toJSON(expected, 2, true))}; std::size_t maxLength = std::max(resultTokens.size(), expectedTokens.size()); std::ostringstream diff; - const auto flush = [] (const std::vector& vec, std::size_t pos, std::ostringstream& out, std::string separator) { - for (std::size_t j = pos; j < vec.size(); ++j) { - out << separator << vec[j] << std::endl; - } - }; + const auto flush = + [](const std::vector& vec, std::size_t pos, std::ostringstream& out, std::string separator) { + for (std::size_t j = pos; j < vec.size(); ++j) { + out << separator << vec[j] << std::endl; + } + }; for (std::size_t i = 0; i < maxLength; ++i) { if (resultTokens.size() <= i) { @@ -98,8 +99,9 @@ void writeTestData(const JSDocument& document, const std::string& rootPath, cons TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, const std::string& id) { TestRunOutput output(id); - const auto evaluateExpression = [&data](std::unique_ptr& expression, - TestResult& result) { + const auto evaluateExpression = [&data]( + std::unique_ptr& expression, TestResult& result + ) { assert(expression); std::vector outputs; if (!data.inputs.empty()) { @@ -107,10 +109,12 @@ TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, con mbgl::style::expression::EvaluationResult evaluationResult; if (input.canonical) { evaluationResult = expression->evaluate( - input.zoom, input.feature, input.heatmapDensity, input.availableImages, *input.canonical); + input.zoom, input.feature, input.heatmapDensity, input.availableImages, *input.canonical + ); } else { - evaluationResult = - expression->evaluate(input.zoom, input.feature, input.heatmapDensity, input.availableImages); + evaluationResult = expression->evaluate( + input.zoom, input.feature, input.heatmapDensity, input.availableImages + ); } if (!evaluationResult) { std::unordered_map error{{"error", Value{evaluationResult.error().message}}}; @@ -138,8 +142,7 @@ TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, con auto recompiledExpression = parseExpression(data.result.serialized, data.spec, data.recompiled); if (recompiledExpression) { evaluateExpression(recompiledExpression, data.recompiled); - rewriteRoundtrippedType(data.expected.compiled.serializedType, - data.recompiled.compiled.serializedType); + rewriteRoundtrippedType(data.expected.compiled.serializedType, data.recompiled.compiled.serializedType); } } @@ -159,7 +162,7 @@ TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, con if (data.expected.compiled.success) { serializationOk = compileOk && deepEqual(data.result.serialized, data.expected.serialized); - recompileOk = compileOk && data.recompiled.compiled == data.expected.compiled; + recompileOk = compileOk && data.recompiled.compiled == data.expected.compiled; roundTripOk = recompileOk && deepEqual(data.recompiled.outputs, data.expected.outputs); } @@ -168,36 +171,28 @@ TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, con if (!compileOk) { auto resultValue = toValue(data.result.compiled); auto expectedValue = toValue(data.expected.compiled); - output.text += "Compiled expression difference:\n"s + - simpleDiff(resultValue, expectedValue) + - "\n"s; + output.text += "Compiled expression difference:\n"s + simpleDiff(resultValue, expectedValue) + "\n"s; } if (compileOk && !serializationOk) { - auto diff = simpleDiff(data.expected.serialized.value_or(Value{}), - data.result.serialized.value_or(Value{})); + auto diff = simpleDiff(data.expected.serialized.value_or(Value{}), data.result.serialized.value_or(Value{})); output.text += "Serialized expression difference:\n"s + diff + "\n"s; } if (compileOk && !recompileOk) { auto recompiledValue = toValue(data.recompiled.compiled); auto expectedValue = toValue(data.expected.compiled); - output.text += "Recompiled expression difference:\n"s + - simpleDiff(recompiledValue, expectedValue) + - "\n"s; + output.text += "Recompiled expression difference:\n"s + simpleDiff(recompiledValue, expectedValue) + "\n"s; } if (compileOk && !evalOk) { - auto diff = simpleDiff(data.expected.outputs.value_or(Value{}), - data.result.outputs.value_or(Value{})); + auto diff = simpleDiff(data.expected.outputs.value_or(Value{}), data.result.outputs.value_or(Value{})); output.text += "Expression outputs difference:\n"s + diff + "\n"s; } if (recompileOk && !roundTripOk) { - auto diff = simpleDiff(data.expected.outputs.value_or(Value{}), - data.recompiled.outputs.value_or(Value{})); - output.text += "Roundtripped through serialize expression outputs difference:\n"s + - diff + "\n"s; + auto diff = simpleDiff(data.expected.outputs.value_or(Value{}), data.recompiled.outputs.value_or(Value{})); + output.text += "Roundtripped through serialize expression outputs difference:\n"s + diff + "\n"s; } return output; diff --git a/expression-test/expression_test_runner.hpp b/expression-test/expression_test_runner.hpp index 596d5c11b67..4a868d3ae49 100644 --- a/expression-test/expression_test_runner.hpp +++ b/expression-test/expression_test_runner.hpp @@ -6,7 +6,8 @@ class TestData; struct TestRunOutput { - TestRunOutput(std::string id_) : id(std::move(id_)) {} + TestRunOutput(std::string id_) + : id(std::move(id_)) {} std::string id; bool passed = false; std::string text; @@ -17,8 +18,7 @@ struct TestRunOutput { class TestStats { public: std::size_t testCount() const { - return passed.size() + failed.size() + errored.size() + - ignorePassed.size() + ignoreFailed.size(); + return passed.size() + failed.size() + errored.size() + ignorePassed.size() + ignoreFailed.size(); } std::vector passed; diff --git a/expression-test/main.cpp b/expression-test/main.cpp index e1b2d0d77ec..007143a7194 100644 --- a/expression-test/main.cpp +++ b/expression-test/main.cpp @@ -5,8 +5,7 @@ #include #include -int main(int argc, char** argv) -try { +int main(int argc, char** argv) try { // Parse args std::vector testPaths; mbgl::filesystem::path rootPath; @@ -19,7 +18,7 @@ try { if (shuffle) { printf(ANSI_COLOR_YELLOW "Shuffle seed: %d" ANSI_COLOR_RESET "\n", seed); - std::seed_seq sequence { seed }; + std::seed_seq sequence{seed}; std::mt19937 shuffler(sequence); std::shuffle(testPaths.begin(), testPaths.end(), shuffler); } @@ -28,13 +27,17 @@ try { TestStats stats; for (const auto& path : testPaths) { const auto& expectation = path.parent_path().string(); - std::string id = expectation.substr(rootPath.string().length() + 1, expectation.length() - rootPath.string().length()); + std::string id = expectation.substr( + rootPath.string().length() + 1, expectation.length() - rootPath.string().length() + ); stats.ids.emplace_back(id); bool shouldIgnore = false; std::string ignoreReason; const std::string ignoreName = "expression-tests/" + id; - const auto it = std::find_if(ignores.cbegin(), ignores.cend(), [&ignoreName] (const auto& ignore) { return ignore.id == ignoreName; }); + const auto it = std::find_if(ignores.cbegin(), ignores.cend(), [&ignoreName](const auto& ignore) { + return ignore.id == ignoreName; + }); if (it != ignores.end()) { shouldIgnore = true; ignoreReason = (*it).reason; @@ -54,10 +57,18 @@ try { if (shouldIgnore) { if (testRun->passed) { stats.ignorePassed.emplace_back(std::move(*testRun)); - printf(ANSI_COLOR_YELLOW "* PASSED ignored test %s (%s)" ANSI_COLOR_RESET "\n", id.c_str(), ignoreReason.c_str()); + printf( + ANSI_COLOR_YELLOW "* PASSED ignored test %s (%s)" ANSI_COLOR_RESET "\n", + id.c_str(), + ignoreReason.c_str() + ); } else { stats.ignoreFailed.emplace_back(std::move(*testRun)); - printf(ANSI_COLOR_LIGHT_GRAY "* FAILED ignored test %s (%s)" ANSI_COLOR_RESET "\n", id.c_str(), ignoreReason.c_str()); + printf( + ANSI_COLOR_LIGHT_GRAY "* FAILED ignored test %s (%s)" ANSI_COLOR_RESET "\n", + id.c_str(), + ignoreReason.c_str() + ); } } else { if (testRun->passed) { @@ -72,10 +83,9 @@ try { printStats(stats); writeHTMLResults(stats, rootPath.string(), shuffle, seed); - + return stats.errored.size() + stats.failed.size() == 0 ? 0 : 1; -} -catch (std::exception const& ex) { +} catch (std::exception const& ex) { std::cerr << "Caught an exception while running tests:\n" << ex.what() << '\n'; return 1; } diff --git a/expression-test/test_runner_common.cpp b/expression-test/test_runner_common.cpp index dc84ff1e55b..54caa24d91b 100644 --- a/expression-test/test_runner_common.cpp +++ b/expression-test/test_runner_common.cpp @@ -47,9 +47,11 @@ Value stripPrecision(const Value& value) { std::vector tokenize(std::string str) { std::vector tokens; std::regex re("\n"); - std::copy(std::regex_token_iterator(str.begin(), str.end(), re, -1), - std::regex_token_iterator(), - std::back_inserter(tokens)); + std::copy( + std::regex_token_iterator(str.begin(), str.end(), re, -1), + std::regex_token_iterator(), + std::back_inserter(tokens) + ); return tokens; } diff --git a/include/mbgl/actor/actor.hpp b/include/mbgl/actor/actor.hpp index f56e8ccab78..e873ac70e02 100644 --- a/include/mbgl/actor/actor.hpp +++ b/include/mbgl/actor/actor.hpp @@ -57,13 +57,12 @@ class Actor { template Actor(std::shared_ptr scheduler, Args&&... args) - : retainer(std::move(scheduler)), target(*retainer, parent, std::forward(args)...) {} + : retainer(std::move(scheduler)), + target(*retainer, parent, std::forward(args)...) {} Actor(const Actor&) = delete; - ActorRef> self() { - return parent.self(); - } + ActorRef> self() { return parent.self(); } private: std::shared_ptr retainer; diff --git a/include/mbgl/actor/actor_ref.hpp b/include/mbgl/actor/actor_ref.hpp index d9fefc731d2..b94d5ec7902 100644 --- a/include/mbgl/actor/actor_ref.hpp +++ b/include/mbgl/actor/actor_ref.hpp @@ -24,8 +24,7 @@ class ActorRef { public: ActorRef(Object& object_, std::weak_ptr weakMailbox_) : object(&object_), - weakMailbox(std::move(weakMailbox_)) { - } + weakMailbox(std::move(weakMailbox_)) {} template void invoke(Fn fn, Args&&... args) const { @@ -43,11 +42,7 @@ class ActorRef { auto future = promise.get_future(); if (auto mailbox = weakMailbox.lock()) { - mailbox->push( - actor::makeMessage( - std::move(promise), *object, fn, std::forward(args)... - ) - ); + mailbox->push(actor::makeMessage(std::move(promise), *object, fn, std::forward(args)...)); } else { promise.set_exception(std::make_exception_ptr(std::runtime_error("Actor has gone away"))); } diff --git a/include/mbgl/actor/aspiring_actor.hpp b/include/mbgl/actor/aspiring_actor.hpp index 7d4910a2a43..f76068b240c 100644 --- a/include/mbgl/actor/aspiring_actor.hpp +++ b/include/mbgl/actor/aspiring_actor.hpp @@ -22,37 +22,34 @@ class Actor; the other half being `EstablishedActor`. It is responsible for: - ownership of the actor's `Mailbox` - allocating the memory for (but *not* constructing) the target object `O` - + Using these two pieces--the mailbox and a stable address for `O`--an `AspiringActor` can accept messages for the target object, or provide `ActorRef`s that do so, before the object has actually been constructed by the corresponding `EstablishedActor`. (Such messages are queued in the mailbox until after the object is constructed.) - + This allows for an `AspiringActor` to be created and safely used by a thread other than the one on which the target object will (eventually) live. */ template class AspiringActor { public: - AspiringActor() : mailbox(std::make_shared()) { + AspiringActor() + : mailbox(std::make_shared()) { // mailbox starts closed because the `Object` hasn't yet been constructed assert(!mailbox->isOpen()); } - + AspiringActor(const AspiringActor&) = delete; - - ActorRef> self() { - return ActorRef>(object(), mailbox); - } - + + ActorRef> self() { return ActorRef>(object(), mailbox); } + private: std::shared_ptr mailbox; std::aligned_storage_t objectStorage; - - Object& object() { - return *reinterpret_cast(&objectStorage); - } - + + Object& object() { return *reinterpret_cast(&objectStorage); } + friend class EstablishedActor; friend class Actor; }; diff --git a/include/mbgl/actor/established_actor.hpp b/include/mbgl/actor/established_actor.hpp index 3e52f21e2f7..69a3576a13f 100644 --- a/include/mbgl/actor/established_actor.hpp +++ b/include/mbgl/actor/established_actor.hpp @@ -16,8 +16,8 @@ namespace mbgl { An `EstablishedActor` is one half of the pair of types that comprise an actor (see `Actor`), the other half being `AspiringActor`. It is responsible for managing the lifetime of the target object `O` and the open/closed state of the parent's `mailbox`. - - The `O` object's lifetime is contained by that of its owning `EstablishedActor`: the + + The `O` object's lifetime is contained by that of its owning `EstablishedActor`: the `EstablishedActor` constructor executes the `O` constructor via "placement new", constructing it at the address provided by the parent `AspiringActor`, and the `~EstablishedActor` destructor similarly executes the `~O` destructor (after closing the mailbox). `EstablishedActor` should @@ -27,50 +27,57 @@ template class EstablishedActor { public: // Construct the Object from a parameter pack `args` (i.e. `Object(args...)`) - template || - std::is_constructible_v, Args...> - > * = nullptr> - EstablishedActor(Scheduler& scheduler, AspiringActor& parent_, Args&& ... args) - : parent(parent_) { + template < + typename U = Object, + class... Args, + typename std::enable_if_t< + std::is_constructible_v || std::is_constructible_v, Args...>>* = nullptr> + EstablishedActor(Scheduler& scheduler, AspiringActor& parent_, Args&&... args) + : parent(parent_) { emplaceObject(std::forward(args)...); parent.mailbox->open(scheduler); } - + // Construct the `Object` from a tuple containing the constructor arguments (i.e. // `Object(std::get<0>(args), std::get<1>(args), ...)`) template >::value> EstablishedActor(Scheduler& scheduler, AspiringActor& parent_, ArgsTuple&& args) - : parent(parent_) { + : parent(parent_) { emplaceObject(std::forward(args), std::make_index_sequence{}); parent.mailbox->open(scheduler); } - + EstablishedActor(const EstablishedActor&) = delete; ~EstablishedActor() { parent.mailbox->close(); parent.object().~Object(); } - + private: // Enabled for Objects with a constructor taking ActorRef as the first parameter - template , Args...>> * = nullptr> + template < + typename U = Object, + class... Args, + typename std::enable_if_t, Args...>>* = nullptr> void emplaceObject(Args&&... args_) { new (&parent.objectStorage) Object(parent.self(), std::forward(args_)...); } // Enabled for plain Objects - template > * = nullptr> + template < + typename U = Object, + class... Args, + typename std::enable_if_t>* = nullptr> void emplaceObject(Args&&... args_) { new (&parent.objectStorage) Object(std::forward(args_)...); } - + // Used to expand a tuple holding the constructor arguments template void emplaceObject(ArgsTuple&& args, std::index_sequence) { emplaceObject(std::move(std::get(std::forward(args)))...); - (void) args; // mark args as used: if it's empty tuple, it's not actually used above. + (void)args; // mark args as used: if it's empty tuple, it's not actually used above. } AspiringActor& parent; diff --git a/include/mbgl/actor/mailbox.hpp b/include/mbgl/actor/mailbox.hpp index 37bdf2dca2c..782af736608 100644 --- a/include/mbgl/actor/mailbox.hpp +++ b/include/mbgl/actor/mailbox.hpp @@ -14,13 +14,12 @@ class Message; class Mailbox : public std::enable_shared_from_this { public: - /// Create a "holding" mailbox, messages to which will remain queued, /// unconsumed, until the mailbox is associated with a Scheduler using /// start(). This allows a Mailbox object to be created on one thread and /// later transferred to a different target thread that may not yet exist. Mailbox(); - + Mailbox(Scheduler&); /// Attach the given scheduler to this mailbox and begin processing messages @@ -43,7 +42,7 @@ class Mailbox : public std::enable_shared_from_this { std::recursive_mutex receivingMutex; std::mutex pushingMutex; - bool closed { false }; + bool closed{false}; std::mutex queueMutex; std::queue> queue; diff --git a/include/mbgl/actor/message.hpp b/include/mbgl/actor/message.hpp index 3167a9f252a..2489476980c 100644 --- a/include/mbgl/actor/message.hpp +++ b/include/mbgl/actor/message.hpp @@ -18,14 +18,11 @@ template class MessageImpl : public Message { public: MessageImpl(Object& object_, MemberFn memberFn_, ArgsTuple argsTuple_) - : object(object_), - memberFn(memberFn_), - argsTuple(std::move(argsTuple_)) { - } + : object(object_), + memberFn(memberFn_), + argsTuple(std::move(argsTuple_)) {} - void operator()() override { - invoke(std::make_index_sequence>()); - } + void operator()() override { invoke(std::make_index_sequence>()); } template void invoke(std::index_sequence) { @@ -44,12 +41,9 @@ class AskMessageImpl : public Message { : object(object_), memberFn(memberFn_), argsTuple(std::move(argsTuple_)), - promise(std::move(promise_)) { - } + promise(std::move(promise_)) {} - void operator()() override { - promise.set_value(ask(std::make_index_sequence>())); - } + void operator()() override { promise.set_value(ask(std::make_index_sequence>())); } template ResultType ask(std::index_sequence) { @@ -66,11 +60,10 @@ template class AskMessageImpl : public Message { public: AskMessageImpl(std::promise promise_, Object& object_, MemberFn memberFn_, ArgsTuple argsTuple_) - : object(object_), - memberFn(memberFn_), - argsTuple(std::move(argsTuple_)), - promise(std::move(promise_)) { - } + : object(object_), + memberFn(memberFn_), + argsTuple(std::move(argsTuple_)), + promise(std::move(promise_)) {} void operator()() override { ask(std::make_index_sequence>()); @@ -97,9 +90,13 @@ std::unique_ptr makeMessage(Object& object, MemberFn memberFn, Args&&.. } template -std::unique_ptr makeMessage(std::promise&& promise, Object& object, MemberFn memberFn, Args&&... args) { +std::unique_ptr makeMessage( + std::promise&& promise, Object& object, MemberFn memberFn, Args&&... args +) { auto tuple = std::make_tuple(std::forward(args)...); - return std::make_unique>(std::move(promise), object, memberFn, std::move(tuple)); + return std::make_unique>( + std::move(promise), object, memberFn, std::move(tuple) + ); } } // namespace actor diff --git a/include/mbgl/actor/scheduler.hpp b/include/mbgl/actor/scheduler.hpp index 4525613afea..5dcb1ef5861 100644 --- a/include/mbgl/actor/scheduler.hpp +++ b/include/mbgl/actor/scheduler.hpp @@ -1,6 +1,5 @@ #pragma once - #include #include @@ -87,13 +86,15 @@ class Scheduler { protected: template - void scheduleAndReplyValue(const TaskFn& task, - const ReplyFn& reply, - mapbox::base::WeakPtr replyScheduler) { + void scheduleAndReplyValue( + const TaskFn& task, const ReplyFn& reply, mapbox::base::WeakPtr replyScheduler + ) { auto scheduled = [replyScheduler = std::move(replyScheduler), task, reply] { auto lock = replyScheduler.lock(); if (!replyScheduler) return; - auto scheduledReply = [reply, result = task()] { reply(result); }; + auto scheduledReply = [reply, result = task()] { + reply(result); + }; replyScheduler->schedule(std::move(scheduledReply)); }; @@ -101,4 +102,4 @@ class Scheduler { } }; -} /// namespace mbgl +} // namespace mbgl diff --git a/include/mbgl/annotation/annotation.hpp b/include/mbgl/annotation/annotation.hpp index 0d67e90d78e..3b8ed79999e 100644 --- a/include/mbgl/annotation/annotation.hpp +++ b/include/mbgl/annotation/annotation.hpp @@ -16,24 +16,25 @@ using AnnotationIDs = std::vector; class SymbolAnnotation { public: - SymbolAnnotation(Point geometry_, std::string icon_ = {}) : geometry(geometry_), icon(std::move(icon_)) {} + SymbolAnnotation(Point geometry_, std::string icon_ = {}) + : geometry(geometry_), + icon(std::move(icon_)) {} Point geometry; std::string icon; }; -using ShapeAnnotationGeometry = variant< - LineString, - Polygon, - MultiLineString, - MultiPolygon>; +using ShapeAnnotationGeometry = + variant, Polygon, MultiLineString, MultiPolygon>; class LineAnnotation { public: - LineAnnotation(ShapeAnnotationGeometry geometry_, - style::PropertyValue opacity_ = 1.0f, - style::PropertyValue width_ = 1.0f, - style::PropertyValue color_ = Color::black()) + LineAnnotation( + ShapeAnnotationGeometry geometry_, + style::PropertyValue opacity_ = 1.0f, + style::PropertyValue width_ = 1.0f, + style::PropertyValue color_ = Color::black() + ) : geometry(std::move(geometry_)), opacity(std::move(opacity_)), width(std::move(width_)), @@ -47,10 +48,12 @@ class LineAnnotation { class FillAnnotation { public: - FillAnnotation(ShapeAnnotationGeometry geometry_, - style::PropertyValue opacity_ = 1.0f, - style::PropertyValue color_ = Color::black(), - style::PropertyValue outlineColor_ = {}) + FillAnnotation( + ShapeAnnotationGeometry geometry_, + style::PropertyValue opacity_ = 1.0f, + style::PropertyValue color_ = Color::black(), + style::PropertyValue outlineColor_ = {} + ) : geometry(std::move(geometry_)), opacity(std::move(opacity_)), color(std::move(color_)), @@ -62,9 +65,6 @@ class FillAnnotation { style::PropertyValue outlineColor; }; -using Annotation = variant< - SymbolAnnotation, - LineAnnotation, - FillAnnotation>; +using Annotation = variant; } // namespace mbgl diff --git a/include/mbgl/gfx/backend.hpp b/include/mbgl/gfx/backend.hpp index ef6df989bb1..46d85d51919 100644 --- a/include/mbgl/gfx/backend.hpp +++ b/include/mbgl/gfx/backend.hpp @@ -11,9 +11,9 @@ class Backend { public: /// @brief The active graphics API/backend type. enum class Type : uint8_t { - OpenGL, ///< The OpenGL API backend - TYPE_MAX, ///< Not a valid backend type, used to determine the number - ///< of available backends (ie for array allocation). + OpenGL, ///< The OpenGL API backend + TYPE_MAX, ///< Not a valid backend type, used to determine the number + ///< of available backends (ie for array allocation). }; static constexpr Type DefaultType = Type::OpenGL; @@ -24,9 +24,7 @@ class Backend { } } - static Type GetType() { - return Value(DefaultType); - } + static Type GetType() { return Value(DefaultType); } template static std::unique_ptr Create(Args... args) { diff --git a/include/mbgl/gfx/renderable.hpp b/include/mbgl/gfx/renderable.hpp index 1aca5a789d2..0145614fdd5 100644 --- a/include/mbgl/gfx/renderable.hpp +++ b/include/mbgl/gfx/renderable.hpp @@ -21,14 +21,12 @@ class RenderableResource { class Renderable { protected: Renderable(const Size size_, std::unique_ptr resource_) - : size(size_), resource(std::move(resource_)) { - } + : size(size_), + resource(std::move(resource_)) {} virtual ~Renderable() = default; public: - Size getSize() const { - return size; - } + Size getSize() const { return size; } template T& getResource() const { diff --git a/include/mbgl/gfx/renderer_backend.hpp b/include/mbgl/gfx/renderer_backend.hpp index 5dc70338655..20f04b0221f 100644 --- a/include/mbgl/gfx/renderer_backend.hpp +++ b/include/mbgl/gfx/renderer_backend.hpp @@ -35,9 +35,7 @@ class RendererBackend { return static_cast(getContext()); } - bool contextIsShared() const { - return contextMode == ContextMode::Shared; - } + bool contextIsShared() const { return contextMode == ContextMode::Shared; } /// Returns a reference to the default surface that should be rendered on. virtual Renderable& getDefaultRenderable() = 0; diff --git a/include/mbgl/gfx/shader.hpp b/include/mbgl/gfx/shader.hpp index 2cee56b7803..5241ab0341d 100644 --- a/include/mbgl/gfx/shader.hpp +++ b/include/mbgl/gfx/shader.hpp @@ -13,36 +13,30 @@ class Shader; // * Inherit gfx::Shader // * Declare a public, unique type name (string_view T::Name) // * Be a final class -template -inline constexpr bool is_shader_v = - std::is_base_of_v && - std::is_same_v< - std::remove_cv_t, - std::string_view> && - std::is_final_v; - +template +inline constexpr bool is_shader_v = std::is_base_of_v&& + std::is_same_v, std::string_view>&& std::is_final_v; /// @brief A shader is used as the base class for all programs across any supported /// backend API. Shaders are registered with a `gfx::ShaderRegistry` instance. class Shader { - public: - virtual ~Shader() = default; - - /// @brief Get the type name of this shader - /// @return Shader type name - virtual const std::string_view typeName() const noexcept = 0; - - /// @brief Downcast to a type - /// @tparam T Derived type - /// @return Type or nullptr if type info was not a match - template, bool>* = nullptr> - T* to() noexcept { - if (typeName() != T::Name) { - return nullptr; - } - return static_cast(this); +public: + virtual ~Shader() = default; + + /// @brief Get the type name of this shader + /// @return Shader type name + virtual const std::string_view typeName() const noexcept = 0; + + /// @brief Downcast to a type + /// @tparam T Derived type + /// @return Type or nullptr if type info was not a match + template , bool>* = nullptr> + T* to() noexcept { + if (typeName() != T::Name) { + return nullptr; } + return static_cast(this); + } }; } // namespace gfx diff --git a/include/mbgl/gfx/shader_registry.hpp b/include/mbgl/gfx/shader_registry.hpp index d57ece1db02..ec3716ceb6d 100644 --- a/include/mbgl/gfx/shader_registry.hpp +++ b/include/mbgl/gfx/shader_registry.hpp @@ -14,141 +14,128 @@ namespace gfx { /// Using the registry, shaders may be dynamically registered or replaced /// at runtime. class ShaderRegistry { - public: - explicit ShaderRegistry(); - ShaderRegistry(const ShaderRegistry&) = delete; - ShaderRegistry(ShaderRegistry&&) noexcept = delete; - ShaderRegistry& operator=(const ShaderRegistry&) = delete; - ShaderRegistry& operator=(ShaderRegistry&&) noexcept = delete; - virtual ~ShaderRegistry() = default; - - /// @brief Checks if a shader exists in the registry for the given name. - /// @param shaderName Name of shader - /// @return If a shader is found, true - [[nodiscard]] virtual bool isShader(const std::string& shaderName) - const noexcept; - - /// @brief Get a shader from the registry by name. - /// @param shaderName Name of shader - /// @return A `gfx::Shader` or `nullptr` if no shader is found with the - /// given name - [[nodiscard]] virtual const std::shared_ptr getShader( - const std::string& shaderName) const noexcept; - - /// @brief Replace a matching shader in the registry with the provided - /// instance. Shader type-names must match. - /// @param shader A `gfx::Shader`. The ShaderRegistry will take ownership. - /// @return True if a match was found and the shader was replaced, false - /// otherwise. - [[nodiscard]] virtual bool replaceShader( - std::shared_ptr&& shader) noexcept; - - /// @brief Replace a matching shader in the registry with the provided - /// instance. Shader type-names must match. - /// This variant replaces by explicit name. - /// @param shader A `gfx::Shader`. The ShaderRegistry will take ownership. - /// @param shaderName Unique name to register the shader under. - /// @return True if a match was found and the shader was replaced, false - /// otherwise. - [[nodiscard]] virtual bool replaceShader( - std::shared_ptr&& shader, const std::string& shaderName) noexcept; - - /// @brief Register a new shader with the registry. If a shader is present - /// in the registry with a conflicting name, registration will fail. - /// @param shader A `gfx::Shader` to register. The ShaderRegistry will - /// take ownership. - /// @return True if the shader was registered, false if another shader is - /// already present with a conflicting name. - [[nodiscard]] virtual bool registerShader( - std::shared_ptr&& shader) noexcept; - - /// @brief Register a new shader with the registry. If a shader is present - /// in the registry with a conflicting name, registration will fail. - /// This variant registers using an explicit name. - /// @param shader A `gfx::Shader` to register. The ShaderRegistry will - /// take ownership. - /// @param shaderName Unique name to register the shader under. - /// @return True if the shader was registered, false if another shader is - /// already present with a conflicting name. - [[nodiscard]] virtual bool registerShader( - std::shared_ptr&& shader, const std::string& shaderName) noexcept; - - /// @brief Shorthand helper to quickly get a derived type from the registry. - /// @tparam T Derived type, inheriting `gfx::Shader` - /// @param shaderName The registry name to look up - /// @return T or nullptr if not found in the registry - template, bool>* = nullptr> - std::shared_ptr get(const std::string& shaderName) noexcept { - auto shader = getShader(shaderName); - if (!shader || shader->typeName() != T::Name) { - return nullptr; - } - return std::static_pointer_cast(shader); +public: + explicit ShaderRegistry(); + ShaderRegistry(const ShaderRegistry&) = delete; + ShaderRegistry(ShaderRegistry&&) noexcept = delete; + ShaderRegistry& operator=(const ShaderRegistry&) = delete; + ShaderRegistry& operator=(ShaderRegistry&&) noexcept = delete; + virtual ~ShaderRegistry() = default; + + /// @brief Checks if a shader exists in the registry for the given name. + /// @param shaderName Name of shader + /// @return If a shader is found, true + [[nodiscard]] virtual bool isShader(const std::string& shaderName) const noexcept; + + /// @brief Get a shader from the registry by name. + /// @param shaderName Name of shader + /// @return A `gfx::Shader` or `nullptr` if no shader is found with the + /// given name + [[nodiscard]] virtual const std::shared_ptr getShader(const std::string& shaderName) const noexcept; + + /// @brief Replace a matching shader in the registry with the provided + /// instance. Shader type-names must match. + /// @param shader A `gfx::Shader`. The ShaderRegistry will take ownership. + /// @return True if a match was found and the shader was replaced, false + /// otherwise. + [[nodiscard]] virtual bool replaceShader(std::shared_ptr&& shader) noexcept; + + /// @brief Replace a matching shader in the registry with the provided + /// instance. Shader type-names must match. + /// This variant replaces by explicit name. + /// @param shader A `gfx::Shader`. The ShaderRegistry will take ownership. + /// @param shaderName Unique name to register the shader under. + /// @return True if a match was found and the shader was replaced, false + /// otherwise. + [[nodiscard]] virtual bool replaceShader(std::shared_ptr&& shader, const std::string& shaderName) noexcept; + + /// @brief Register a new shader with the registry. If a shader is present + /// in the registry with a conflicting name, registration will fail. + /// @param shader A `gfx::Shader` to register. The ShaderRegistry will + /// take ownership. + /// @return True if the shader was registered, false if another shader is + /// already present with a conflicting name. + [[nodiscard]] virtual bool registerShader(std::shared_ptr&& shader) noexcept; + + /// @brief Register a new shader with the registry. If a shader is present + /// in the registry with a conflicting name, registration will fail. + /// This variant registers using an explicit name. + /// @param shader A `gfx::Shader` to register. The ShaderRegistry will + /// take ownership. + /// @param shaderName Unique name to register the shader under. + /// @return True if the shader was registered, false if another shader is + /// already present with a conflicting name. + [[nodiscard]] virtual bool registerShader(std::shared_ptr&& shader, const std::string& shaderName) noexcept; + + /// @brief Shorthand helper to quickly get a derived type from the registry. + /// @tparam T Derived type, inheriting `gfx::Shader` + /// @param shaderName The registry name to look up + /// @return T or nullptr if not found in the registry + template , bool>* = nullptr> + std::shared_ptr get(const std::string& shaderName) noexcept { + auto shader = getShader(shaderName); + if (!shader || shader->typeName() != T::Name) { + return nullptr; } + return std::static_pointer_cast(shader); + } - /// @brief Shorthand helper to quickly get a derived type from the registry. - /// This variant looks up shaders only by type name. - /// @tparam T Derived type, inheriting `gfx::Shader` - /// @return T or nullptr if not found in the registry - template, bool>* = nullptr> - std::shared_ptr get() noexcept { - auto shader = getShader(std::string(T::Name)); - if (!shader || shader->typeName() != T::Name) { - return nullptr; - } - return std::static_pointer_cast(shader); + /// @brief Shorthand helper to quickly get a derived type from the registry. + /// This variant looks up shaders only by type name. + /// @tparam T Derived type, inheriting `gfx::Shader` + /// @return T or nullptr if not found in the registry + template , bool>* = nullptr> + std::shared_ptr get() noexcept { + auto shader = getShader(std::string(T::Name)); + if (!shader || shader->typeName() != T::Name) { + return nullptr; } + return std::static_pointer_cast(shader); + } - /// @brief Ensure the destination 'to' is populated with the requested - /// shader. If already non-null, does nothing. - /// @tparam T Derived type, inheriting `gfx::Shader` - /// @param to Location to store the shader - /// @param shaderName The registry name to look up - /// @return True if 'to' has a valid program object, false otherwise. - template, bool>* = nullptr> - bool populate(std::shared_ptr& to, const std::string& shaderName) noexcept { - if (to) { - return true; - } - - auto shader = getShader(shaderName); - if (!shader || shader->typeName() != T::Name) { - return false; - } - to = std::static_pointer_cast(shader); + /// @brief Ensure the destination 'to' is populated with the requested + /// shader. If already non-null, does nothing. + /// @tparam T Derived type, inheriting `gfx::Shader` + /// @param to Location to store the shader + /// @param shaderName The registry name to look up + /// @return True if 'to' has a valid program object, false otherwise. + template , bool>* = nullptr> + bool populate(std::shared_ptr& to, const std::string& shaderName) noexcept { + if (to) { return true; } - /// @brief Ensure the destination 'to' is populated with the requested - /// shader. If already non-null, does nothing. This variant looks up - /// shaders only by type name. - /// @tparam T Derived type, inheriting `gfx::Shader` - /// @param to Location to store the shader - /// @return True if 'to' has a valid program object, false otherwise. - template, bool>* = nullptr> - bool populate(std::shared_ptr& to) noexcept { - if (to) { - return true; - } - - auto shader = getShader(std::string(T::Name)); - if (!shader || shader->typeName() != T::Name) { - return false; - } - to = std::static_pointer_cast(shader); + auto shader = getShader(shaderName); + if (!shader || shader->typeName() != T::Name) { + return false; + } + to = std::static_pointer_cast(shader); + return true; + } + + /// @brief Ensure the destination 'to' is populated with the requested + /// shader. If already non-null, does nothing. This variant looks up + /// shaders only by type name. + /// @tparam T Derived type, inheriting `gfx::Shader` + /// @param to Location to store the shader + /// @return True if 'to' has a valid program object, false otherwise. + template , bool>* = nullptr> + bool populate(std::shared_ptr& to) noexcept { + if (to) { return true; } - private: - std::unordered_map< - std::string, - std::shared_ptr - > programs; - mutable std::shared_mutex programLock; + auto shader = getShader(std::string(T::Name)); + if (!shader || shader->typeName() != T::Name) { + return false; + } + to = std::static_pointer_cast(shader); + return true; + } + +private: + std::unordered_map> programs; + mutable std::shared_mutex programLock; }; } // namespace gfx diff --git a/include/mbgl/gl/custom_layer.hpp b/include/mbgl/gl/custom_layer.hpp index ce12aa6181c..0b4c627335a 100644 --- a/include/mbgl/gl/custom_layer.hpp +++ b/include/mbgl/gl/custom_layer.hpp @@ -63,8 +63,7 @@ class CustomLayerHost { class CustomLayer final : public Layer { public: - CustomLayer(const std::string& id, - std::unique_ptr host); + CustomLayer(const std::string& id, std::unique_ptr host); CustomLayer(const CustomLayer&) = delete; ~CustomLayer() final; @@ -73,8 +72,8 @@ class CustomLayer final : public Layer { Mutable mutableImpl() const; private: - std::optional setPropertyInternal(const std::string& name, - const conversion::Convertible& value) final; + std::optional setPropertyInternal(const std::string& name, const conversion::Convertible& value) + final; StyleProperty getProperty(const std::string&) const final; std::unique_ptr cloneRef(const std::string& id) const final; Mutable mutableBaseImpl() const final; diff --git a/include/mbgl/gl/custom_layer_factory.hpp b/include/mbgl/gl/custom_layer_factory.hpp index 963a3dc2fd9..e4bf0c4c69c 100644 --- a/include/mbgl/gl/custom_layer_factory.hpp +++ b/include/mbgl/gl/custom_layer_factory.hpp @@ -10,7 +10,9 @@ namespace mbgl { class CustomLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/gl/renderer_backend.hpp b/include/mbgl/gl/renderer_backend.hpp index 99191c9596e..fb36c19bbb4 100644 --- a/include/mbgl/gl/renderer_backend.hpp +++ b/include/mbgl/gl/renderer_backend.hpp @@ -31,8 +31,7 @@ class RendererBackend : public gfx::RendererBackend { PremultipliedImage readFramebuffer(const Size&); /// A constant to signal that a framebuffer is bound, but with an unknown ID. - static constexpr const FramebufferID ImplicitFramebufferBinding = - std::numeric_limits::max(); + static constexpr const FramebufferID ImplicitFramebufferBinding = std::numeric_limits::max(); /// Tells the renderer that OpenGL state has already been set by the windowing toolkit. /// It sets the internal assumed state to the supplied values. diff --git a/include/mbgl/i18n/collator.hpp b/include/mbgl/i18n/collator.hpp index b170347d6a9..d0f7ce559d0 100644 --- a/include/mbgl/i18n/collator.hpp +++ b/include/mbgl/i18n/collator.hpp @@ -9,7 +9,9 @@ namespace platform { class Collator { public: - explicit Collator(bool caseSensitive, bool diacriticSensitive, const std::optional& locale = std::nullopt); + explicit Collator( + bool caseSensitive, bool diacriticSensitive, const std::optional& locale = std::nullopt + ); int compare(const std::string& lhs, const std::string& rhs) const; std::string resolvedLocale() const; bool operator==(const Collator& other) const; diff --git a/include/mbgl/i18n/number_format.hpp b/include/mbgl/i18n/number_format.hpp index dceddfe96b1..22da616dd78 100644 --- a/include/mbgl/i18n/number_format.hpp +++ b/include/mbgl/i18n/number_format.hpp @@ -6,11 +6,13 @@ namespace mbgl { namespace platform { -std::string formatNumber(double number, - const std::string& localeId, - const std::string& currency, - uint8_t minFractionDigits, - uint8_t maxFractionDigits); +std::string formatNumber( + double number, + const std::string& localeId, + const std::string& currency, + uint8_t minFractionDigits, + uint8_t maxFractionDigits +); } // namespace platform } // namespace mbgl diff --git a/include/mbgl/layermanager/background_layer_factory.hpp b/include/mbgl/layermanager/background_layer_factory.hpp index f2fa2f7a560..99f2d16b9d2 100644 --- a/include/mbgl/layermanager/background_layer_factory.hpp +++ b/include/mbgl/layermanager/background_layer_factory.hpp @@ -7,7 +7,9 @@ namespace mbgl { class BackgroundLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/circle_layer_factory.hpp b/include/mbgl/layermanager/circle_layer_factory.hpp index aaf5fddfb6a..4fa8e11ae0c 100644 --- a/include/mbgl/layermanager/circle_layer_factory.hpp +++ b/include/mbgl/layermanager/circle_layer_factory.hpp @@ -7,10 +7,14 @@ namespace mbgl { class CircleLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; - std::unique_ptr createLayout(const LayoutParameters& parameters, - std::unique_ptr tileLayer, - const std::vector>& group) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; + std::unique_ptr createLayout( + const LayoutParameters& parameters, + std::unique_ptr tileLayer, + const std::vector>& group + ) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/fill_extrusion_layer_factory.hpp b/include/mbgl/layermanager/fill_extrusion_layer_factory.hpp index fbaa5c12544..846859c01fc 100644 --- a/include/mbgl/layermanager/fill_extrusion_layer_factory.hpp +++ b/include/mbgl/layermanager/fill_extrusion_layer_factory.hpp @@ -7,8 +7,12 @@ namespace mbgl { class FillExtrusionLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; - std::unique_ptr createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; + std::unique_ptr + createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept + final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/fill_layer_factory.hpp b/include/mbgl/layermanager/fill_layer_factory.hpp index 09afb0dc3a1..cf1bce04b0f 100644 --- a/include/mbgl/layermanager/fill_layer_factory.hpp +++ b/include/mbgl/layermanager/fill_layer_factory.hpp @@ -7,8 +7,12 @@ namespace mbgl { class FillLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; - std::unique_ptr createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; + std::unique_ptr + createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept + final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/heatmap_layer_factory.hpp b/include/mbgl/layermanager/heatmap_layer_factory.hpp index 2d0e1a5a027..04cfb341d2f 100644 --- a/include/mbgl/layermanager/heatmap_layer_factory.hpp +++ b/include/mbgl/layermanager/heatmap_layer_factory.hpp @@ -7,8 +7,11 @@ namespace mbgl { class HeatmapLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; - std::unique_ptr createBucket(const BucketParameters&, const std::vector>&) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; + std::unique_ptr + createBucket(const BucketParameters&, const std::vector>&) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/hillshade_layer_factory.hpp b/include/mbgl/layermanager/hillshade_layer_factory.hpp index 25b4f6c2c40..cdd2863d6d5 100644 --- a/include/mbgl/layermanager/hillshade_layer_factory.hpp +++ b/include/mbgl/layermanager/hillshade_layer_factory.hpp @@ -7,7 +7,9 @@ namespace mbgl { class HillshadeLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/layer_factory.hpp b/include/mbgl/layermanager/layer_factory.hpp index 23de124bd69..0e127756643 100644 --- a/include/mbgl/layermanager/layer_factory.hpp +++ b/include/mbgl/layermanager/layer_factory.hpp @@ -8,7 +8,7 @@ namespace mbgl { namespace style { class LayerProperties; -} // namespace style +} // namespace style class Bucket; class BucketParameters; class GeometryTileLayer; @@ -18,7 +18,7 @@ class RenderLayer; /** * @brief The LayerFactory abstract class - * + * * This class is responsible for creation of the layer objects that belong to a concrete layer type. */ class LayerFactory { @@ -26,14 +26,18 @@ class LayerFactory { virtual ~LayerFactory() = default; /// Returns the layer type data. virtual const style::LayerTypeInfo* getTypeInfo() const noexcept = 0; - /// Returns a new Layer instance on success call; returns `nullptr` otherwise. - virtual std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept = 0; + /// Returns a new Layer instance on success call; returns `nullptr` otherwise. + virtual std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept = 0; /// Returns a new RenderLayer instance. virtual std::unique_ptr createRenderLayer(Immutable) noexcept = 0; - /// Returns a new Bucket instance on success call; returns `nullptr` otherwise. - virtual std::unique_ptr createBucket(const BucketParameters&, const std::vector>&) noexcept; - /// Returns a new Layout instance on success call; returns `nullptr` otherwise. - virtual std::unique_ptr createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept; + /// Returns a new Bucket instance on success call; returns `nullptr` otherwise. + virtual std::unique_ptr + createBucket(const BucketParameters&, const std::vector>&) noexcept; + /// Returns a new Layout instance on success call; returns `nullptr` otherwise. + virtual std::unique_ptr + createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept; protected: std::optional getSource(const style::conversion::Convertible& value) const noexcept; diff --git a/include/mbgl/layermanager/layer_manager.hpp b/include/mbgl/layermanager/layer_manager.hpp index c6802dbb495..a963db72804 100644 --- a/include/mbgl/layermanager/layer_manager.hpp +++ b/include/mbgl/layermanager/layer_manager.hpp @@ -7,7 +7,7 @@ namespace mbgl { namespace style { class LayerProperties; -} // namespace style +} // namespace style class GeometryTileLayer; class LayerFactory; class RenderLayer; @@ -18,10 +18,10 @@ class LayoutParameters; /** * @brief A singleton class responsible for creating layer instances. - * + * * The LayerManager has implementation per platform. The LayerManager implementation * defines what layer types are available and it can also disable annotations. - * + * * Linker excludes the unreachable code for the disabled annotations and layers * from the binaries, significantly reducing their size. */ @@ -29,33 +29,38 @@ class LayerManager { public: /** * @brief A singleton getter. - * - * @return LayerManager* + * + * @return LayerManager* */ static LayerManager* get() noexcept; /// Returns a new Layer instance on success call; returns `nullptr` otherwise. - std::unique_ptr createLayer(const std::string& type, const std::string& id, - const style::conversion::Convertible& value, style::conversion::Error& error) noexcept; + std::unique_ptr createLayer( + const std::string& type, + const std::string& id, + const style::conversion::Convertible& value, + style::conversion::Error& error + ) noexcept; /// Returns a new RenderLayer instance on success call; returns `nullptr` otherwise. std::unique_ptr createRenderLayer(Immutable) noexcept; /// Returns a new Bucket instance on success call; returns `nullptr` otherwise. - std::unique_ptr createBucket(const BucketParameters&, const std::vector>&) noexcept; - /// Returns a new Layout instance on success call; returns `nullptr` otherwise. - std::unique_ptr createLayout(const LayoutParameters&, std::unique_ptr, - const std::vector>&) noexcept; + std::unique_ptr + createBucket(const BucketParameters&, const std::vector>&) noexcept; + /// Returns a new Layout instance on success call; returns `nullptr` otherwise. + std::unique_ptr + createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept; /** * @brief a build-time flag to enable/disable annotations in mapbox-gl-native core. - * + * * At the moment, the annotations implementation in core is creating concrete * layer instances apart from LayerManager/LayerFactory code path. - * + * * So, annotations must be disabled if the LayerManager implementation does - * not provide line, fill or symbol layers (those, used by the annotations + * not provide line, fill or symbol layers (those, used by the annotations * implementation). - * - * Note: in future, annotations implemantation will be moved from the core to platform + * + * Note: in future, annotations implemantation will be moved from the core to platform * SDK (see https://github.com/mapbox/mapbox-plugins-android/tree/master/plugin-annotation) * and this flag won't be needed any more. */ diff --git a/include/mbgl/layermanager/line_layer_factory.hpp b/include/mbgl/layermanager/line_layer_factory.hpp index 803f550e57b..4e44dccbe32 100644 --- a/include/mbgl/layermanager/line_layer_factory.hpp +++ b/include/mbgl/layermanager/line_layer_factory.hpp @@ -7,10 +7,14 @@ namespace mbgl { class LineLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; - std::unique_ptr createLayout(const LayoutParameters& parameters, - std::unique_ptr tileLayer, - const std::vector>& group) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; + std::unique_ptr createLayout( + const LayoutParameters& parameters, + std::unique_ptr tileLayer, + const std::vector>& group + ) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/location_indicator_layer_factory.hpp b/include/mbgl/layermanager/location_indicator_layer_factory.hpp index 8d8e3b9a40c..66a44eead77 100644 --- a/include/mbgl/layermanager/location_indicator_layer_factory.hpp +++ b/include/mbgl/layermanager/location_indicator_layer_factory.hpp @@ -7,8 +7,9 @@ namespace mbgl { class LocationIndicatorLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, - const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/raster_layer_factory.hpp b/include/mbgl/layermanager/raster_layer_factory.hpp index d82137ee81f..ccc2dfe5a60 100644 --- a/include/mbgl/layermanager/raster_layer_factory.hpp +++ b/include/mbgl/layermanager/raster_layer_factory.hpp @@ -7,7 +7,9 @@ namespace mbgl { class RasterLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/symbol_layer_factory.hpp b/include/mbgl/layermanager/symbol_layer_factory.hpp index 38f382e96c5..c1384d862ef 100644 --- a/include/mbgl/layermanager/symbol_layer_factory.hpp +++ b/include/mbgl/layermanager/symbol_layer_factory.hpp @@ -7,10 +7,14 @@ namespace mbgl { class SymbolLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; - std::unique_ptr createLayout(const LayoutParameters& parameters, - std::unique_ptr tileLayer, - const std::vector>& group) noexcept final; + std::unique_ptr createLayer( + const std::string& id, const style::conversion::Convertible& value + ) noexcept final; + std::unique_ptr createLayout( + const LayoutParameters& parameters, + std::unique_ptr tileLayer, + const std::vector>& group + ) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/map/bound_options.hpp b/include/mbgl/map/bound_options.hpp index 27cba371ac7..5901a252cfa 100644 --- a/include/mbgl/map/bound_options.hpp +++ b/include/mbgl/map/bound_options.hpp @@ -12,11 +12,20 @@ namespace mbgl { */ struct BoundOptions { /// Sets the latitude and longitude bounds to which the camera center are constrained - BoundOptions& withLatLngBounds(LatLngBounds b) { bounds = b; return *this; } + BoundOptions& withLatLngBounds(LatLngBounds b) { + bounds = b; + return *this; + } /// Sets the minimum zoom level - BoundOptions& withMinZoom(double z) { minZoom = z; return *this; } + BoundOptions& withMinZoom(double z) { + minZoom = z; + return *this; + } /// Sets the maximum zoom level - BoundOptions& withMaxZoom(double z) { maxZoom = z; return *this; } + BoundOptions& withMaxZoom(double z) { + maxZoom = z; + return *this; + } /// Sets the minimum pitch BoundOptions& withMinPitch(double p) { minPitch = p; @@ -44,4 +53,4 @@ struct BoundOptions { std::optional minPitch; }; -} // namespace mbgl +} // namespace mbgl diff --git a/include/mbgl/map/camera.hpp b/include/mbgl/map/camera.hpp index 52f08bb2b12..814249b9097 100644 --- a/include/mbgl/map/camera.hpp +++ b/include/mbgl/map/camera.hpp @@ -17,12 +17,30 @@ namespace mbgl { center point when both are set. */ struct CameraOptions { - CameraOptions& withCenter(const std::optional& o) { center = o; return *this; } - CameraOptions& withPadding(const std::optional& p) { padding = p; return *this; } - CameraOptions& withAnchor(const std::optional& o) { anchor = o; return *this; } - CameraOptions& withZoom(const std::optional& o) { zoom = o; return *this; } - CameraOptions& withBearing(const std::optional& o) { bearing = o; return *this; } - CameraOptions& withPitch(const std::optional& o) { pitch = o; return *this; } + CameraOptions& withCenter(const std::optional& o) { + center = o; + return *this; + } + CameraOptions& withPadding(const std::optional& p) { + padding = p; + return *this; + } + CameraOptions& withAnchor(const std::optional& o) { + anchor = o; + return *this; + } + CameraOptions& withZoom(const std::optional& o) { + zoom = o; + return *this; + } + CameraOptions& withBearing(const std::optional& o) { + bearing = o; + return *this; + } + CameraOptions& withPitch(const std::optional& o) { + pitch = o; + return *this; + } /** Coordinate at the center of the map. */ std::optional center; @@ -48,12 +66,8 @@ struct CameraOptions { }; constexpr bool operator==(const CameraOptions& a, const CameraOptions& b) { - return a.center == b.center - && a.padding == b.padding - && a.anchor == b.anchor - && a.zoom == b.zoom - && a.bearing == b.bearing - && a.pitch == b.pitch; + return a.center == b.center && a.padding == b.padding && a.anchor == b.anchor && a.zoom == b.zoom && + a.bearing == b.bearing && a.pitch == b.pitch; } constexpr bool operator!=(const CameraOptions& a, const CameraOptions& b) { diff --git a/include/mbgl/map/map.hpp b/include/mbgl/map/map.hpp index 2363156378f..3db4c98d691 100644 --- a/include/mbgl/map/map.hpp +++ b/include/mbgl/map/map.hpp @@ -33,23 +33,25 @@ class Style; class Map : private util::noncopyable { public: - explicit Map(RendererFrontend&, - MapObserver&, - const MapOptions&, - const ResourceOptions&, - const ClientOptions& = ClientOptions()); + explicit Map( + RendererFrontend&, + MapObserver&, + const MapOptions&, + const ResourceOptions&, + const ClientOptions& = ClientOptions() + ); ~Map(); /// Register a callback that will get called (on the render thread) when all resources have /// been loaded and a complete render occurs. - using StillImageCallback = std::function; + using StillImageCallback = std::function; void renderStill(StillImageCallback); void renderStill(const CameraOptions&, MapDebugOptions, StillImageCallback); /// Triggers a repaint. void triggerRepaint(); - style::Style& getStyle(); + style::Style& getStyle(); const style::Style& getStyle() const; void setStyle(std::unique_ptr); @@ -71,18 +73,24 @@ class Map : private util::noncopyable { void scaleBy(double scale, const std::optional& anchor, const AnimationOptions& animation = {}); void pitchBy(double pitch, const AnimationOptions& animation = {}); void rotateBy(const ScreenCoordinate& first, const ScreenCoordinate& second, const AnimationOptions& = {}); - CameraOptions cameraForLatLngBounds(const LatLngBounds&, - const EdgeInsets&, - const std::optional& bearing = std::nullopt, - const std::optional& pitch = std::nullopt) const; - CameraOptions cameraForLatLngs(const std::vector&, - const EdgeInsets&, - const std::optional& bearing = std::nullopt, - const std::optional& pitch = std::nullopt) const; - CameraOptions cameraForGeometry(const Geometry&, - const EdgeInsets&, - const std::optional& bearing = std::nullopt, - const std::optional& pitch = std::nullopt) const; + CameraOptions cameraForLatLngBounds( + const LatLngBounds&, + const EdgeInsets&, + const std::optional& bearing = std::nullopt, + const std::optional& pitch = std::nullopt + ) const; + CameraOptions cameraForLatLngs( + const std::vector&, + const EdgeInsets&, + const std::optional& bearing = std::nullopt, + const std::optional& pitch = std::nullopt + ) const; + CameraOptions cameraForGeometry( + const Geometry&, + const EdgeInsets&, + const std::optional& bearing = std::nullopt, + const std::optional& pitch = std::nullopt + ) const; LatLngBounds latLngBoundsForCamera(const CameraOptions&) const; LatLngBounds latLngBoundsForCameraUnwrapped(const CameraOptions&) const; @@ -103,7 +111,7 @@ class Map : private util::noncopyable { void setSize(Size); MapOptions getMapOptions() const; - //Projection Mode + // Projection Mode void setProjectionMode(const ProjectionMode&); ProjectionMode getProjectionMode() const; diff --git a/include/mbgl/map/map_observer.hpp b/include/mbgl/map/map_observer.hpp index 7a400bc749b..675b86c0562 100644 --- a/include/mbgl/map/map_observer.hpp +++ b/include/mbgl/map/map_observer.hpp @@ -63,7 +63,7 @@ class MapObserver { virtual bool onCanRemoveUnusedStyleImage(const std::string&) { return true; } // Observe this event to easily mutate or observe shaders as soon // as the registry becomes available. - virtual void onRegisterShaders(gfx::ShaderRegistry&) {}; + virtual void onRegisterShaders(gfx::ShaderRegistry&){}; }; } // namespace mbgl diff --git a/include/mbgl/map/map_options.hpp b/include/mbgl/map/map_options.hpp index eb5e43a7f3c..12a6b874f9e 100644 --- a/include/mbgl/map/map_options.hpp +++ b/include/mbgl/map/map_options.hpp @@ -138,4 +138,4 @@ class MapOptions final { std::unique_ptr impl_; }; -} // namespace mbgl +} // namespace mbgl diff --git a/include/mbgl/map/mode.hpp b/include/mbgl/map/mode.hpp index a04ad589b80..b16026bd119 100644 --- a/include/mbgl/map/mode.hpp +++ b/include/mbgl/map/mode.hpp @@ -15,8 +15,8 @@ using EnumType = uint32_t; enum class MapMode : EnumType { Continuous, ///< continually updating map - Static, ///< a once-off still image of an arbitrary viewport - Tile ///< a once-off still image of a single tile + Static, ///< a once-off still image of an arbitrary viewport + Tile ///< a once-off still image of a single tile }; /// We can choose to constrain the map both horizontally or vertically, or only @@ -35,12 +35,12 @@ enum class ViewportMode : EnumType { }; enum class MapDebugOptions : EnumType { - NoDebug = 0, + NoDebug = 0, TileBorders = 1 << 1, ParseStatus = 1 << 2, - Timestamps = 1 << 3, - Collision = 1 << 4, - Overdraw = 1 << 5, + Timestamps = 1 << 3, + Collision = 1 << 4, + Overdraw = 1 << 5, StencilClip = 1 << 6, DepthBuffer = 1 << 7, }; diff --git a/include/mbgl/map/projection_mode.hpp b/include/mbgl/map/projection_mode.hpp index ed04fd82d0d..7809605a3ce 100644 --- a/include/mbgl/map/projection_mode.hpp +++ b/include/mbgl/map/projection_mode.hpp @@ -10,9 +10,18 @@ namespace mbgl { * optional. */ struct ProjectionMode { - ProjectionMode& withAxonometric(bool o) { axonometric = o; return *this; } - ProjectionMode& withXSkew(double o) { xSkew = o; return *this; } - ProjectionMode& withYSkew(double o) { ySkew = o; return *this; } + ProjectionMode& withAxonometric(bool o) { + axonometric = o; + return *this; + } + ProjectionMode& withXSkew(double o) { + xSkew = o; + return *this; + } + ProjectionMode& withYSkew(double o) { + ySkew = o; + return *this; + } /** * @brief Set to True to enable axonometric rendering, false otherwise. @@ -30,4 +39,4 @@ struct ProjectionMode { std::optional ySkew; }; -} // namespace mbgl +} // namespace mbgl diff --git a/include/mbgl/math/log2.hpp b/include/mbgl/math/log2.hpp index 694cbdf337d..9bedfc8961d 100644 --- a/include/mbgl/math/log2.hpp +++ b/include/mbgl/math/log2.hpp @@ -30,8 +30,7 @@ T log2(T x) { } // namespace mbgl // log2 is not available on Android before API 18. -#if defined(__ANDROID__) && defined(__GNUC__) && \ - defined(__ANDROID_API__) && __ANDROID_API__ < 18 +#if defined(__ANDROID__) && defined(__GNUC__) && defined(__ANDROID_API__) && __ANDROID_API__ < 18 template typename std::enable_if_t, T> log2(T x) { diff --git a/include/mbgl/platform/gl_functions.hpp b/include/mbgl/platform/gl_functions.hpp index 00a84818d94..5cecdd7159b 100644 --- a/include/mbgl/platform/gl_functions.hpp +++ b/include/mbgl/platform/gl_functions.hpp @@ -7,7 +7,13 @@ // initialized by the platform at linking time. #ifndef NDEBUG -#define MBGL_CHECK_ERROR(cmd) ([&]() { struct __MBGL_CHECK_ERROR { ~__MBGL_CHECK_ERROR() noexcept(false) { mbgl::platform::glCheckError(#cmd, __FILE__, __LINE__); } } __MBGL_CHECK_ERROR; return cmd; }()) +#define MBGL_CHECK_ERROR(cmd) \ + ([&]() { \ + struct __MBGL_CHECK_ERROR { \ + ~__MBGL_CHECK_ERROR() noexcept(false) { mbgl::platform::glCheckError(#cmd, __FILE__, __LINE__); } \ + } __MBGL_CHECK_ERROR; \ + return cmd; \ + }()) #else #define MBGL_CHECK_ERROR(cmd) (cmd) #endif @@ -30,7 +36,7 @@ using GLuint = unsigned int; using GLvoid = void; using GLint64 = int64_t; using GLuint64 = uint64_t; -using GLsync = ::__GLsync *; +using GLsync = ::__GLsync*; #if defined(_WIN32) using GLintptr = long long; @@ -43,505 +49,510 @@ using GLsizeiptr = long; /* OpenGL ES 2.0 */ /// Pointer to glActiveTexture OpenGL function. -extern void (* const glActiveTexture)(GLenum); +extern void (*const glActiveTexture)(GLenum); /// Pointer to glAttachShader OpenGL function. -extern void (* const glAttachShader)(GLuint, GLuint); +extern void (*const glAttachShader)(GLuint, GLuint); /// Pointer to glBindAttribLocation OpenGL function. -extern void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *); +extern void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*); /// Pointer to glBindBuffer OpenGL function. -extern void (* const glBindBuffer)(GLenum, GLuint); +extern void (*const glBindBuffer)(GLenum, GLuint); /// Pointer to glBindFramebuffer OpenGL function. -extern void (* const glBindFramebuffer)(GLenum, GLuint); +extern void (*const glBindFramebuffer)(GLenum, GLuint); /// Pointer to glBindRenderbuffer OpenGL function. -extern void (* const glBindRenderbuffer)(GLenum, GLuint); +extern void (*const glBindRenderbuffer)(GLenum, GLuint); /// Pointer to glBindTexture OpenGL function. -extern void (* const glBindTexture)(GLenum, GLuint); +extern void (*const glBindTexture)(GLenum, GLuint); /// Pointer to glBlendColor OpenGL function. -extern void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat); +extern void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat); /// Pointer to glBlendEquation OpenGL function. -extern void (* const glBlendEquation)(GLenum); +extern void (*const glBlendEquation)(GLenum); /// Pointer to glBlendEquationSeparate OpenGL function. -extern void (* const glBlendEquationSeparate)(GLenum, GLenum); +extern void (*const glBlendEquationSeparate)(GLenum, GLenum); /// Pointer to glBlendFunc OpenGL function. -extern void (* const glBlendFunc)(GLenum, GLenum); +extern void (*const glBlendFunc)(GLenum, GLenum); /// Pointer to glBlendFuncSeparate OpenGL function. -extern void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum); +extern void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum); /// Pointer to glBufferData OpenGL function. -extern void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum); +extern void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum); /// Pointer to glBufferSubData OpenGL function. -extern void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *); +extern void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*); /// Pointer to glCheckFramebufferStatus OpenGL function. -extern GLenum (* const glCheckFramebufferStatus)(GLenum); +extern GLenum (*const glCheckFramebufferStatus)(GLenum); /// Pointer to glClear OpenGL function. -extern void (* const glClear)(GLbitfield); +extern void (*const glClear)(GLbitfield); /// Pointer to glClearColor OpenGL function. -extern void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat); +extern void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat); /// Pointer to glClearDepthf OpenGL function. -extern void (* const glClearDepthf)(GLfloat); +extern void (*const glClearDepthf)(GLfloat); /// Pointer to glClearStencil OpenGL function. -extern void (* const glClearStencil)(GLint); +extern void (*const glClearStencil)(GLint); /// Pointer to glColorMask OpenGL function. -extern void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean); +extern void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean); /// Pointer to glCompileShader OpenGL function. -extern void (* const glCompileShader)(GLuint); +extern void (*const glCompileShader)(GLuint); /// Pointer to glCompressedTexImage2D OpenGL function. -extern void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *); +extern void (*const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*); /// Pointer to glCompressedTexSubImage2D OpenGL function. -extern void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *); +extern void (*const glCompressedTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*); /// Pointer to glCopyTexImage2D OpenGL function. -extern void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint); +extern void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint); /// Pointer to glCopyTexSubImage2D OpenGL function. -extern void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); +extern void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); /// Pointer to glCreateProgram OpenGL function. -extern GLuint (* const glCreateProgram)(); +extern GLuint (*const glCreateProgram)(); /// Pointer to glCreateShader OpenGL function. -extern GLuint (* const glCreateShader)(GLenum); +extern GLuint (*const glCreateShader)(GLenum); /// Pointer to glCullFace OpenGL function. -extern void (* const glCullFace)(GLenum); +extern void (*const glCullFace)(GLenum); /// Pointer to glDeleteBuffers OpenGL function. -extern void (* const glDeleteBuffers)(GLsizei, const GLuint *); +extern void (*const glDeleteBuffers)(GLsizei, const GLuint*); /// Pointer to glDeleteFramebuffers OpenGL function. -extern void (* const glDeleteFramebuffers)(GLsizei, const GLuint *); +extern void (*const glDeleteFramebuffers)(GLsizei, const GLuint*); /// Pointer to glDeleteProgram OpenGL function. -extern void (* const glDeleteProgram)(GLuint); +extern void (*const glDeleteProgram)(GLuint); /// Pointer to glDeleteRenderbuffers OpenGL function. -extern void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *); +extern void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*); /// Pointer to glDeleteShader OpenGL function. -extern void (* const glDeleteShader)(GLuint); +extern void (*const glDeleteShader)(GLuint); /// Pointer to glDeleteTextures OpenGL function. -extern void (* const glDeleteTextures)(GLsizei, const GLuint *); +extern void (*const glDeleteTextures)(GLsizei, const GLuint*); /// Pointer to glDepthFunc OpenGL function. -extern void (* const glDepthFunc)(GLenum); +extern void (*const glDepthFunc)(GLenum); /// Pointer to glDepthMask OpenGL function. -extern void (* const glDepthMask)(GLboolean); +extern void (*const glDepthMask)(GLboolean); /// Pointer to glDepthRangef OpenGL function. -extern void (* const glDepthRangef)(GLfloat, GLfloat); +extern void (*const glDepthRangef)(GLfloat, GLfloat); /// Pointer to glDetachShader OpenGL function. -extern void (* const glDetachShader)(GLuint, GLuint); +extern void (*const glDetachShader)(GLuint, GLuint); /// Pointer to glDisable OpenGL function. -extern void (* const glDisable)(GLenum); +extern void (*const glDisable)(GLenum); /// Pointer to glDisableVertexAttribArray OpenGL function. -extern void (* const glDisableVertexAttribArray)(GLuint); +extern void (*const glDisableVertexAttribArray)(GLuint); /// Pointer to glDrawArrays OpenGL function. -extern void (* const glDrawArrays)(GLenum, GLint, GLsizei); +extern void (*const glDrawArrays)(GLenum, GLint, GLsizei); /// Pointer to glDrawElements OpenGL function. -extern void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *); +extern void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*); /// Pointer to glEnable OpenGL function. -extern void (* const glEnable)(GLenum); +extern void (*const glEnable)(GLenum); /// Pointer to glEnableVertexAttribArray OpenGL function. -extern void (* const glEnableVertexAttribArray)(GLuint); +extern void (*const glEnableVertexAttribArray)(GLuint); /// Pointer to glFinish OpenGL function. -extern void (* const glFinish)(); +extern void (*const glFinish)(); /// Pointer to glFlush OpenGL function. -extern void (* const glFlush)(); +extern void (*const glFlush)(); /// Pointer to glFramebufferRenderbuffer OpenGL function. -extern void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint); +extern void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint); /// Pointer to glFramebufferTexture2D OpenGL function. -extern void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint); +extern void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint); /// Pointer to glFrontFace OpenGL function. -extern void (* const glFrontFace)(GLenum); +extern void (*const glFrontFace)(GLenum); /// Pointer to glGenBuffers OpenGL function. -extern void (* const glGenBuffers)(GLsizei, GLuint *); +extern void (*const glGenBuffers)(GLsizei, GLuint*); /// Pointer to glGenerateMipmap OpenGL function. -extern void (* const glGenerateMipmap)(GLenum); +extern void (*const glGenerateMipmap)(GLenum); /// Pointer to glGenFramebuffers OpenGL function. -extern void (* const glGenFramebuffers)(GLsizei, GLuint *); +extern void (*const glGenFramebuffers)(GLsizei, GLuint*); /// Pointer to glGenRenderbuffers OpenGL function. -extern void (* const glGenRenderbuffers)(GLsizei, GLuint *); +extern void (*const glGenRenderbuffers)(GLsizei, GLuint*); /// Pointer to glGenTextures OpenGL function. -extern void (* const glGenTextures)(GLsizei, GLuint *); +extern void (*const glGenTextures)(GLsizei, GLuint*); /// Pointer to glGetActiveAttrib OpenGL function. -extern void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); +extern void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*); /// Pointer to glGetActiveUniform OpenGL function. -extern void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); +extern void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*); /// Pointer to glGetAttachedShaders OpenGL function. -extern void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *); +extern void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*); /// Pointer to glGetAttribLocation OpenGL function. -extern GLint (* const glGetAttribLocation)(GLuint, const GLchar *); +extern GLint (*const glGetAttribLocation)(GLuint, const GLchar*); /// Pointer to glGetBooleanv OpenGL function. -extern void (* const glGetBooleanv)(GLenum, GLboolean *); +extern void (*const glGetBooleanv)(GLenum, GLboolean*); /// Pointer to glGetBufferParameteriv OpenGL function. -extern void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *); +extern void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*); /// Pointer to glGetError OpenGL function. -extern GLenum (* const glGetError)(); +extern GLenum (*const glGetError)(); /// Pointer to glGetFloatv OpenGL function. -extern void (* const glGetFloatv)(GLenum, GLfloat *); +extern void (*const glGetFloatv)(GLenum, GLfloat*); /// Pointer to glGetFramebufferAttachmentParameteriv OpenGL function. -extern void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *); +extern void (*const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint*); /// Pointer to glGetIntegerv OpenGL function. -extern void (* const glGetIntegerv)(GLenum, GLint *); +extern void (*const glGetIntegerv)(GLenum, GLint*); /// Pointer to glGetProgramInfoLog OpenGL function. -extern void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *); +extern void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*); /// Pointer to glGetProgramiv OpenGL function. -extern void (* const glGetProgramiv)(GLuint, GLenum, GLint *); +extern void (*const glGetProgramiv)(GLuint, GLenum, GLint*); /// Pointer to glGetRenderbufferParameteriv OpenGL function. -extern void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *); +extern void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*); /// Pointer to glGetShaderInfoLog OpenGL function. -extern void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *); +extern void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*); /// Pointer to glGetShaderiv OpenGL function. -extern void (* const glGetShaderiv)(GLuint, GLenum, GLint *); +extern void (*const glGetShaderiv)(GLuint, GLenum, GLint*); /// Pointer to glGetShaderPrecisionFormat OpenGL function. -extern void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *); +extern void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*); /// Pointer to glGetShaderSource OpenGL function. -extern void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *); +extern void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*); /// Pointer to glGetString OpenGL function. -extern const GLubyte *(* const glGetString)(GLenum); +extern const GLubyte* (*const glGetString)(GLenum); /// Pointer to glGetTexParameterfv OpenGL function. -extern void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *); +extern void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*); /// Pointer to glGetTexParameteriv OpenGL function. -extern void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *); +extern void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*); /// Pointer to glGetUniformfv OpenGL function. -extern void (* const glGetUniformfv)(GLuint, GLint, GLfloat *); +extern void (*const glGetUniformfv)(GLuint, GLint, GLfloat*); /// Pointer to glGetUniformiv OpenGL function. -extern void (* const glGetUniformiv)(GLuint, GLint, GLint *); +extern void (*const glGetUniformiv)(GLuint, GLint, GLint*); /// Pointer to glGetUniformLocation OpenGL function. -extern GLint (* const glGetUniformLocation)(GLuint, const GLchar *); +extern GLint (*const glGetUniformLocation)(GLuint, const GLchar*); /// Pointer to glGetVertexAttribfv OpenGL function. -extern void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *); +extern void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*); /// Pointer to glGetVertexAttribiv OpenGL function. -extern void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *); +extern void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*); /// Pointer to glGetVertexAttribPointerv OpenGL function. -extern void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **); +extern void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**); /// Pointer to glHint OpenGL function. -extern void (* const glHint)(GLenum, GLenum); +extern void (*const glHint)(GLenum, GLenum); /// Pointer to glIsBuffer OpenGL function. -extern GLboolean (* const glIsBuffer)(GLuint); +extern GLboolean (*const glIsBuffer)(GLuint); /// Pointer to glIsEnabled OpenGL function. -extern GLboolean (* const glIsEnabled)(GLenum); +extern GLboolean (*const glIsEnabled)(GLenum); /// Pointer to glIsFramebuffer OpenGL function. -extern GLboolean (* const glIsFramebuffer)(GLuint); +extern GLboolean (*const glIsFramebuffer)(GLuint); /// Pointer to glIsProgram OpenGL function. -extern GLboolean (* const glIsProgram)(GLuint); +extern GLboolean (*const glIsProgram)(GLuint); /// Pointer to glIsRenderbuffer OpenGL function. -extern GLboolean (* const glIsRenderbuffer)(GLuint); +extern GLboolean (*const glIsRenderbuffer)(GLuint); /// Pointer to glIsShader OpenGL function. -extern GLboolean (* const glIsShader)(GLuint); +extern GLboolean (*const glIsShader)(GLuint); /// Pointer to glIsTexture OpenGL function. -extern GLboolean (* const glIsTexture)(GLuint); +extern GLboolean (*const glIsTexture)(GLuint); /// Pointer to glLineWidth OpenGL function. -extern void (* const glLineWidth)(GLfloat); +extern void (*const glLineWidth)(GLfloat); /// Pointer to glLinkProgram OpenGL function. -extern void (* const glLinkProgram)(GLuint); +extern void (*const glLinkProgram)(GLuint); /// Pointer to glPixelStorei OpenGL function. -extern void (* const glPixelStorei)(GLenum, GLint); +extern void (*const glPixelStorei)(GLenum, GLint); /// Pointer to glPolygonOffset OpenGL function. -extern void (* const glPolygonOffset)(GLfloat, GLfloat); +extern void (*const glPolygonOffset)(GLfloat, GLfloat); /// Pointer to glReadPixels OpenGL function. -extern void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *); +extern void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*); /// Pointer to glReleaseShaderCompiler OpenGL function. -extern void (* const glReleaseShaderCompiler)(); +extern void (*const glReleaseShaderCompiler)(); /// Pointer to glRenderbufferStorage OpenGL function. -extern void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei); +extern void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei); /// Pointer to glSampleCoverage OpenGL function. -extern void (* const glSampleCoverage)(GLfloat, GLboolean); +extern void (*const glSampleCoverage)(GLfloat, GLboolean); /// Pointer to glScissor OpenGL function. -extern void (* const glScissor)(GLint, GLint, GLsizei, GLsizei); +extern void (*const glScissor)(GLint, GLint, GLsizei, GLsizei); /// Pointer to glShaderBinary OpenGL function. -extern void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei); +extern void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei); /// Pointer to glShaderSource OpenGL function. -extern void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *); +extern void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*); /// Pointer to glStencilFunc OpenGL function. -extern void (* const glStencilFunc)(GLenum, GLint, GLuint); +extern void (*const glStencilFunc)(GLenum, GLint, GLuint); /// Pointer to glStencilFuncSeparate OpenGL function. -extern void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint); +extern void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint); /// Pointer to glStencilMask OpenGL function. -extern void (* const glStencilMask)(GLuint); +extern void (*const glStencilMask)(GLuint); /// Pointer to glStencilMaskSeparate OpenGL function. -extern void (* const glStencilMaskSeparate)(GLenum, GLuint); +extern void (*const glStencilMaskSeparate)(GLenum, GLuint); /// Pointer to glStencilOp OpenGL function. -extern void (* const glStencilOp)(GLenum, GLenum, GLenum); +extern void (*const glStencilOp)(GLenum, GLenum, GLenum); /// Pointer to glStencilOpSeparate OpenGL function. -extern void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum); +extern void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum); /// Pointer to glTexImage2D OpenGL function. -extern void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *); +extern void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*); /// Pointer to glTexParameterf OpenGL function. -extern void (* const glTexParameterf)(GLenum, GLenum, GLfloat); +extern void (*const glTexParameterf)(GLenum, GLenum, GLfloat); /// Pointer to glTexParameterfv OpenGL function. -extern void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *); +extern void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*); /// Pointer to glTexParameteri OpenGL function. -extern void (* const glTexParameteri)(GLenum, GLenum, GLint); +extern void (*const glTexParameteri)(GLenum, GLenum, GLint); /// Pointer to glTexParameteriv OpenGL function. -extern void (* const glTexParameteriv)(GLenum, GLenum, const GLint *); +extern void (*const glTexParameteriv)(GLenum, GLenum, const GLint*); /// Pointer to glTexSubImage2D OpenGL function. -extern void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *); +extern void (*const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*); /// Pointer to glUniform1f OpenGL function. -extern void (* const glUniform1f)(GLint, GLfloat); +extern void (*const glUniform1f)(GLint, GLfloat); /// Pointer to glUniform1fv OpenGL function. -extern void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *); +extern void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*); /// Pointer to glUniform1i OpenGL function. -extern void (* const glUniform1i)(GLint, GLint); +extern void (*const glUniform1i)(GLint, GLint); /// Pointer to glUniform1iv OpenGL function. -extern void (* const glUniform1iv)(GLint, GLsizei, const GLint *); +extern void (*const glUniform1iv)(GLint, GLsizei, const GLint*); /// Pointer to glUniform2f OpenGL function. -extern void (* const glUniform2f)(GLint, GLfloat, GLfloat); +extern void (*const glUniform2f)(GLint, GLfloat, GLfloat); /// Pointer to glUniform2fv OpenGL function. -extern void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *); +extern void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*); /// Pointer to glUniform2i OpenGL function. -extern void (* const glUniform2i)(GLint, GLint, GLint); +extern void (*const glUniform2i)(GLint, GLint, GLint); /// Pointer to glUniform2iv OpenGL function. -extern void (* const glUniform2iv)(GLint, GLsizei, const GLint *); +extern void (*const glUniform2iv)(GLint, GLsizei, const GLint*); /// Pointer to glUniform3f OpenGL function. -extern void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat); +extern void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat); /// Pointer to glUniform3fv OpenGL function. -extern void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *); +extern void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*); /// Pointer to glUniform3i OpenGL function. -extern void (* const glUniform3i)(GLint, GLint, GLint, GLint); +extern void (*const glUniform3i)(GLint, GLint, GLint, GLint); /// Pointer to glUniform3iv OpenGL function. -extern void (* const glUniform3iv)(GLint, GLsizei, const GLint *); +extern void (*const glUniform3iv)(GLint, GLsizei, const GLint*); /// Pointer to glUniform4f OpenGL function. -extern void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat); +extern void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat); /// Pointer to glUniform4fv OpenGL function. -extern void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *); +extern void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*); /// Pointer to glUniform4i OpenGL function. -extern void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint); +extern void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint); /// Pointer to glUniform4iv OpenGL function. -extern void (* const glUniform4iv)(GLint, GLsizei, const GLint *); +extern void (*const glUniform4iv)(GLint, GLsizei, const GLint*); /// Pointer to glUniformMatrix2fv OpenGL function. -extern void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix3fv OpenGL function. -extern void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix4fv OpenGL function. -extern void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUseProgram OpenGL function. -extern void (* const glUseProgram)(GLuint); +extern void (*const glUseProgram)(GLuint); /// Pointer to glValidateProgram OpenGL function. -extern void (* const glValidateProgram)(GLuint); +extern void (*const glValidateProgram)(GLuint); /// Pointer to glVertexAttrib1f OpenGL function. -extern void (* const glVertexAttrib1f)(GLuint, GLfloat); +extern void (*const glVertexAttrib1f)(GLuint, GLfloat); /// Pointer to glVertexAttrib1fv OpenGL function. -extern void (* const glVertexAttrib1fv)(GLuint, const GLfloat *); +extern void (*const glVertexAttrib1fv)(GLuint, const GLfloat*); /// Pointer to glVertexAttrib2f OpenGL function. -extern void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat); +extern void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat); /// Pointer to glVertexAttrib2fv OpenGL function. -extern void (* const glVertexAttrib2fv)(GLuint, const GLfloat *); +extern void (*const glVertexAttrib2fv)(GLuint, const GLfloat*); /// Pointer to glVertexAttrib3f OpenGL function. -extern void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat); +extern void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat); /// Pointer to glVertexAttrib3fv OpenGL function. -extern void (* const glVertexAttrib3fv)(GLuint, const GLfloat *); +extern void (*const glVertexAttrib3fv)(GLuint, const GLfloat*); /// Pointer to glVertexAttrib4f OpenGL function. -extern void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat); +extern void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat); /// Pointer to glVertexAttrib4fv OpenGL function. -extern void (* const glVertexAttrib4fv)(GLuint, const GLfloat *); +extern void (*const glVertexAttrib4fv)(GLuint, const GLfloat*); /// Pointer to glVertexAttribPointer OpenGL function. -extern void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *); +extern void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*); /// Pointer to glViewport OpenGL function. -extern void (* const glViewport)(GLint, GLint, GLsizei, GLsizei); +extern void (*const glViewport)(GLint, GLint, GLsizei, GLsizei); /* OpenGL ES 3.0 */ /// Pointer to glReadBuffer OpenGL function. -extern void (* const glReadBuffer)(GLenum); +extern void (*const glReadBuffer)(GLenum); /// Pointer to glDrawRangeElements OpenGL function. -extern void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *); +extern void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*); /// Pointer to glTexImage3D OpenGL function. -extern void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); +extern void (*const glTexImage3D +)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*); /// Pointer to glTexSubImage3D OpenGL function. -extern void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +extern void (*const glTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*); /// Pointer to glCopyTexSubImage3D OpenGL function. -extern void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); +extern void (*const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); /// Pointer to glCompressedTexImage3D OpenGL function. -extern void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); +extern void (*const glCompressedTexImage3D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*); /// Pointer to glCompressedTexSubImage3D OpenGL function. -extern void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); +extern void (*const glCompressedTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*); /// Pointer to glGenQueries OpenGL function. -extern void (* const glGenQueries)(GLsizei, GLuint *); +extern void (*const glGenQueries)(GLsizei, GLuint*); /// Pointer to glDeleteQueries OpenGL function. -extern void (* const glDeleteQueries)(GLsizei, const GLuint *); +extern void (*const glDeleteQueries)(GLsizei, const GLuint*); /// Pointer to glIsQuery OpenGL function. -extern GLboolean (* const glIsQuery)(GLuint); +extern GLboolean (*const glIsQuery)(GLuint); /// Pointer to glBeginQuery OpenGL function. -extern void (* const glBeginQuery)(GLenum, GLuint); +extern void (*const glBeginQuery)(GLenum, GLuint); /// Pointer to glEndQuery OpenGL function. -extern void (* const glEndQuery)(GLenum); +extern void (*const glEndQuery)(GLenum); /// Pointer to glGetQueryiv OpenGL function. -extern void (* const glGetQueryiv)(GLenum, GLenum, GLint *); +extern void (*const glGetQueryiv)(GLenum, GLenum, GLint*); /// Pointer to glGetQueryObjectuiv OpenGL function. -extern void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint *); +extern void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*); /// Pointer to glUnmapBuffer OpenGL function. -extern GLboolean (* const glUnmapBuffer)(GLenum); +extern GLboolean (*const glUnmapBuffer)(GLenum); /// Pointer to glGetBufferPointerv OpenGL function. -extern void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid **); +extern void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**); /// Pointer to glDrawBuffers OpenGL function. -extern void (* const glDrawBuffers)(GLsizei, const GLenum *); +extern void (*const glDrawBuffers)(GLsizei, const GLenum*); /// Pointer to glUniformMatrix2x3fv OpenGL function. -extern void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix3x2fv OpenGL function. -extern void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix2x4fv OpenGL function. -extern void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix4x2fv OpenGL function. -extern void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix3x4fv OpenGL function. -extern void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix4x3fv OpenGL function. -extern void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glBlitFramebuffer OpenGL function. -extern void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum); +extern void (*const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum); /// Pointer to glRenderbufferStorageMultisample OpenGL function. -extern void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei); +extern void (*const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei); /// Pointer to glFramebufferTextureLayer OpenGL function. -extern void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint); +extern void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint); /// Pointer to glMapBufferRange OpenGL function. -extern GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield); +extern GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield); /// Pointer to glMapBufferRange OpenGL function. -extern void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr); +extern void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr); /// Pointer to glBindVertexArray OpenGL function. -extern void (* const glBindVertexArray)(GLuint); +extern void (*const glBindVertexArray)(GLuint); /// Pointer to glDeleteVertexArrays OpenGL function. -extern void (* const glDeleteVertexArrays)(GLsizei, const GLuint *); +extern void (*const glDeleteVertexArrays)(GLsizei, const GLuint*); /// Pointer to glGenVertexArrays OpenGL function. -extern void (* const glGenVertexArrays)(GLsizei, GLuint *); +extern void (*const glGenVertexArrays)(GLsizei, GLuint*); /// Pointer to glIsVertexArray OpenGL function. -extern GLboolean (* const glIsVertexArray)(GLuint); +extern GLboolean (*const glIsVertexArray)(GLuint); /// Pointer to glGetIntegeri_v OpenGL function. -extern void (* const glGetIntegeri_v)(GLenum, GLuint, GLint *); +extern void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*); /// Pointer to glBeginTransformFeedback OpenGL function. -extern void (* const glBeginTransformFeedback)(GLenum); +extern void (*const glBeginTransformFeedback)(GLenum); /// Pointer to glEndTransformFeedback OpenGL function. -extern void (* const glEndTransformFeedback)(); +extern void (*const glEndTransformFeedback)(); /// Pointer to glBindBufferRange OpenGL function. -extern void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr); +extern void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr); /// Pointer to glBindBufferBase OpenGL function. -extern void (* const glBindBufferBase)(GLenum, GLuint, GLuint); +extern void (*const glBindBufferBase)(GLenum, GLuint, GLuint); /// Pointer to glTransformFeedbackVaryings OpenGL function. -extern void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar * const*, GLenum); +extern void (*const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum); /// Pointer to glGetTransformFeedbackVarying OpenGL function. -extern void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei *, GLsizei *, GLenum *, GLchar *); +extern void (*const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*); /// Pointer to glVertexAttribIPointer OpenGL function. -extern void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid *); +extern void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*); /// Pointer to glGetVertexAttribIiv OpenGL function. -extern void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint *); +extern void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*); /// Pointer to glGetVertexAttribIiv OpenGL function. -extern void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint *); +extern void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*); /// Pointer to glVertexAttribI4i OpenGL function. -extern void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint); +extern void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint); /// Pointer to glVertexAttribI4ui OpenGL function. -extern void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint); +extern void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint); /// Pointer to glVertexAttribI4iv OpenGL function. -extern void (* const glVertexAttribI4iv)(GLuint, const GLint *); +extern void (*const glVertexAttribI4iv)(GLuint, const GLint*); /// Pointer to glVertexAttribI4uiv OpenGL function. -extern void (* const glVertexAttribI4uiv)(GLuint, const GLuint *); +extern void (*const glVertexAttribI4uiv)(GLuint, const GLuint*); /// Pointer to glGetUniformuiv OpenGL function. -extern void (* const glGetUniformuiv)(GLuint, GLint, GLuint *); +extern void (*const glGetUniformuiv)(GLuint, GLint, GLuint*); /// Pointer to glGetFragDataLocation OpenGL function. -extern GLint (* const glGetFragDataLocation)(GLuint, const GLchar *); +extern GLint (*const glGetFragDataLocation)(GLuint, const GLchar*); /// Pointer to glUniform1ui OpenGL function. -extern void (* const glUniform1ui)(GLint, GLuint); +extern void (*const glUniform1ui)(GLint, GLuint); /// Pointer to glUniform2ui OpenGL function. -extern void (* const glUniform2ui)(GLint, GLuint, GLuint); +extern void (*const glUniform2ui)(GLint, GLuint, GLuint); /// Pointer to glUniform3ui OpenGL function. -extern void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint); +extern void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint); /// Pointer to glUniform4ui OpenGL function. -extern void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint); +extern void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint); /// Pointer to glUniform1uiv OpenGL function. -extern void (* const glUniform1uiv)(GLint, GLsizei, const GLuint *); +extern void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*); /// Pointer to glUniform2uiv OpenGL function. -extern void (* const glUniform2uiv)(GLint, GLsizei, const GLuint *); +extern void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*); /// Pointer to glUniform3uiv OpenGL function. -extern void (* const glUniform3uiv)(GLint, GLsizei, const GLuint *); +extern void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*); /// Pointer to glUniform4uiv OpenGL function. -extern void (* const glUniform4uiv)(GLint, GLsizei, const GLuint *); +extern void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*); /// Pointer to glClearBufferiv OpenGL function. -extern void (* const glClearBufferiv)(GLenum, GLint, const GLint *); +extern void (*const glClearBufferiv)(GLenum, GLint, const GLint*); /// Pointer to glClearBufferuiv OpenGL function. -extern void (* const glClearBufferuiv)(GLenum, GLint, const GLuint *); +extern void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*); /// Pointer to glClearBufferfv OpenGL function. -extern void (* const glClearBufferfv)(GLenum, GLint, const GLfloat *); +extern void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*); /// Pointer to glClearBufferfi OpenGL function. -extern void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint); +extern void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint); /// Pointer to glGetStringi OpenGL function. -extern const GLubyte* (* const glGetStringi)(GLenum, GLuint); +extern const GLubyte* (*const glGetStringi)(GLenum, GLuint); /// Pointer to glCopyBufferSubData OpenGL function. -extern void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr); +extern void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr); /// Pointer to glGetUniformIndices OpenGL function. -extern void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar * const*, GLuint *); +extern void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*); /// Pointer to glGetActiveUniformsiv OpenGL function. -extern void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint *, GLenum, GLint *); +extern void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*); /// Pointer to glGetUniformBlockIndex OpenGL function. -extern GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar *); +extern GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*); /// Pointer to glGetActiveUniformBlockiv OpenGL function. -extern void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint *); +extern void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*); /// Pointer to glGetActiveUniformBlockName OpenGL function. -extern void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *); +extern void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*); /// Pointer to glUniformBlockBinding OpenGL function. -extern void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint); +extern void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint); /// Pointer to glDrawArraysInstanced OpenGL function. -extern void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei); +extern void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei); /// Pointer to glDrawElementsInstanced OpenGL function. -extern void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid *, GLsizei); +extern void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei); /// Pointer to glFenceSync OpenGL function. -extern GLsync (* const glFenceSync)(GLenum, GLbitfield); +extern GLsync (*const glFenceSync)(GLenum, GLbitfield); /// Pointer to glIsSync OpenGL function. -extern GLboolean (* const glIsSync)(GLsync); +extern GLboolean (*const glIsSync)(GLsync); /// Pointer to glDeleteSync OpenGL function. -extern void (* const glDeleteSync)(GLsync); +extern void (*const glDeleteSync)(GLsync); /// Pointer to glClientWaitSync OpenGL function. -extern GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64); +extern GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64); /// Pointer to glWaitSync OpenGL function. -extern void (* const glWaitSync)(GLsync, GLbitfield, GLuint64); +extern void (*const glWaitSync)(GLsync, GLbitfield, GLuint64); /// Pointer to glGetInteger64v OpenGL function. -extern void (* const glGetInteger64v)(GLenum, GLint64 *); +extern void (*const glGetInteger64v)(GLenum, GLint64*); /// Pointer to glGetSynciv OpenGL function. -extern void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei *, GLint *); +extern void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*); /// Pointer to glGetInteger64i_v OpenGL function. -extern void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64 *); +extern void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*); /// Pointer to glGetBufferParameteri64v OpenGL function. -extern void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64 *); +extern void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*); /// Pointer to glGenSamplers OpenGL function. -extern void (* const glGenSamplers)(GLsizei, GLuint *); +extern void (*const glGenSamplers)(GLsizei, GLuint*); /// Pointer to glDeleteSamplers OpenGL function. -extern void (* const glDeleteSamplers)(GLsizei, const GLuint *); +extern void (*const glDeleteSamplers)(GLsizei, const GLuint*); /// Pointer to glIsSampler OpenGL function. -extern GLboolean (* const glIsSampler)(GLuint); +extern GLboolean (*const glIsSampler)(GLuint); /// Pointer to glBindSampler OpenGL function. -extern void (* const glBindSampler)(GLuint, GLuint); +extern void (*const glBindSampler)(GLuint, GLuint); /// Pointer to glSamplerParameteri OpenGL function. -extern void (* const glSamplerParameteri)(GLuint, GLenum, GLint); +extern void (*const glSamplerParameteri)(GLuint, GLenum, GLint); /// Pointer to glSamplerParameteriv OpenGL function. -extern void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint *); +extern void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*); /// Pointer to glSamplerParameterf OpenGL function. -extern void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat); +extern void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat); /// Pointer to glSamplerParameterfv OpenGL function. -extern void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat *); +extern void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*); /// Pointer to glGetSamplerParameteriv OpenGL function. -extern void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint *); +extern void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*); /// Pointer to glGetSamplerParameterfv OpenGL function. -extern void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat *); +extern void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*); /// Pointer to glVertexAttribDivisor OpenGL function. -extern void (* const glVertexAttribDivisor)(GLuint, GLuint); +extern void (*const glVertexAttribDivisor)(GLuint, GLuint); /// Pointer to glBindTransformFeedback OpenGL function. -extern void (* const glBindTransformFeedback)(GLenum, GLuint); +extern void (*const glBindTransformFeedback)(GLenum, GLuint); /// Pointer to glDeleteTransformFeedbacks OpenGL function. -extern void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint *); +extern void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*); /// Pointer to glGenTransformFeedbacks OpenGL function. -extern void (* const glGenTransformFeedbacks)(GLsizei, GLuint *); +extern void (*const glGenTransformFeedbacks)(GLsizei, GLuint*); /// Pointer to glIsTransformFeedback OpenGL function. -extern GLboolean (* const glIsTransformFeedback)(GLuint); +extern GLboolean (*const glIsTransformFeedback)(GLuint); /// Pointer to glPauseTransformFeedback OpenGL function. -extern void (* const glPauseTransformFeedback)(); +extern void (*const glPauseTransformFeedback)(); /// Pointer to glResumeTransformFeedback OpenGL function. -extern void (* const glResumeTransformFeedback)(); +extern void (*const glResumeTransformFeedback)(); /// Pointer to glGetProgramBinary OpenGL function. -extern void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei *, GLenum *, GLvoid *); +extern void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*); /// Pointer to glProgramBinary OpenGL function. -extern void (* const glProgramBinary)(GLuint, GLenum, const GLvoid *, GLsizei); +extern void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei); /// Pointer to glProgramParameteri OpenGL function. -extern void (* const glProgramParameteri)(GLuint, GLenum, GLint); +extern void (*const glProgramParameteri)(GLuint, GLenum, GLint); /// Pointer to glInvalidateFramebuffer OpenGL function. -extern void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum *); +extern void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*); /// Pointer to glInvalidateSubFramebuffer OpenGL function. -extern void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei); +extern void (*const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei); /// Pointer to glTexStorage2D OpenGL function. -extern void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei); +extern void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei); /// Pointer to glTexStorage3D OpenGL function. -extern void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei); +extern void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei); /// Pointer to glGetInternalformativ OpenGL function. -extern void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint *); +extern void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*); #ifndef NDEBUG /// Check for GL errors and print on the console. -void glCheckError(const char *cmd, const char *file, int line); +void glCheckError(const char* cmd, const char* file, int line); #endif -} // namespace platform +} // namespace platform } // namespace mbgl diff --git a/include/mbgl/renderer/query.hpp b/include/mbgl/renderer/query.hpp index 097214a875d..beb9e2ada16 100644 --- a/include/mbgl/renderer/query.hpp +++ b/include/mbgl/renderer/query.hpp @@ -13,8 +13,10 @@ namespace mbgl { */ class RenderedQueryOptions { public: - RenderedQueryOptions(std::optional> layerIDs_ = std::nullopt, - std::optional filter_ = std::nullopt) + RenderedQueryOptions( + std::optional> layerIDs_ = std::nullopt, + std::optional filter_ = std::nullopt + ) : layerIDs(std::move(layerIDs_)), filter(std::move(filter_)) {} @@ -29,8 +31,10 @@ class RenderedQueryOptions { */ class SourceQueryOptions { public: - SourceQueryOptions(std::optional> sourceLayers_ = std::nullopt, - std::optional filter_ = std::nullopt) + SourceQueryOptions( + std::optional> sourceLayers_ = std::nullopt, + std::optional filter_ = std::nullopt + ) : sourceLayers(std::move(sourceLayers_)), filter(std::move(filter_)) {} diff --git a/include/mbgl/renderer/renderer.hpp b/include/mbgl/renderer/renderer.hpp index 6bfdee626c0..20a97d60a23 100644 --- a/include/mbgl/renderer/renderer.hpp +++ b/include/mbgl/renderer/renderer.hpp @@ -42,7 +42,9 @@ struct PlacedSymbolData { class Renderer { public: - Renderer(gfx::RendererBackend&, float pixelRatio_, const std::optional& localFontFamily = std::nullopt); + Renderer( + gfx::RendererBackend&, float pixelRatio_, const std::optional& localFontFamily = std::nullopt + ); ~Renderer(); void markContextLost(); @@ -53,7 +55,8 @@ class Renderer { /// Feature queries std::vector queryRenderedFeatures(const ScreenLineString&, const RenderedQueryOptions& options = {}) const; - std::vector queryRenderedFeatures(const ScreenCoordinate& point, const RenderedQueryOptions& options = {}) const; + std::vector queryRenderedFeatures(const ScreenCoordinate& point, const RenderedQueryOptions& options = {}) + const; std::vector queryRenderedFeatures(const ScreenBox& box, const RenderedQueryOptions& options = {}) const; std::vector querySourceFeatures(const std::string& sourceID, const SourceQueryOptions& options = {}) const; AnnotationIDs queryPointAnnotations(const ScreenBox& box) const; @@ -61,24 +64,34 @@ class Renderer { AnnotationIDs getAnnotationIDs(const std::vector&) const; /// Feature extension query - FeatureExtensionValue queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args = std::nullopt) const; - - void setFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::string& featureID, const FeatureState& state); - - void getFeatureState(FeatureState& state, - const std::string& sourceID, - const std::optional& sourceLayerID, - const std::string& featureID) const; - - void removeFeatureState(const std::string& sourceID, - const std::optional& sourceLayerID, - const std::optional& featureID, - const std::optional& stateKey); + FeatureExtensionValue queryFeatureExtensions( + const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args = std::nullopt + ) const; + + void setFeatureState( + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID, + const FeatureState& state + ); + + void getFeatureState( + FeatureState& state, + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID + ) const; + + void removeFeatureState( + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::optional& featureID, + const std::optional& stateKey + ); // Debug void dumpDebugLogs(); diff --git a/include/mbgl/renderer/renderer_frontend.hpp b/include/mbgl/renderer/renderer_frontend.hpp index 038a905f2ef..3c9fb82181b 100644 --- a/include/mbgl/renderer/renderer_frontend.hpp +++ b/include/mbgl/renderer/renderer_frontend.hpp @@ -14,7 +14,6 @@ class UpdateParameters; /// the original thread. class RendererFrontend { public: - virtual ~RendererFrontend() = default; /// Must synchronously clean up the Renderer if set diff --git a/include/mbgl/renderer/renderer_observer.hpp b/include/mbgl/renderer/renderer_observer.hpp index d0bb7475413..fdaa40477fd 100644 --- a/include/mbgl/renderer/renderer_observer.hpp +++ b/include/mbgl/renderer/renderer_observer.hpp @@ -42,7 +42,7 @@ class RendererObserver { virtual void onRemoveUnusedStyleImages(const std::vector&) {} // Entry point for custom shader registration - virtual void onRegisterShaders(gfx::ShaderRegistry&) {}; + virtual void onRegisterShaders(gfx::ShaderRegistry&){}; }; } // namespace mbgl diff --git a/include/mbgl/renderer/renderer_state.hpp b/include/mbgl/renderer/renderer_state.hpp index bd8c811aa7a..a1bd28fe2bd 100644 --- a/include/mbgl/renderer/renderer_state.hpp +++ b/include/mbgl/renderer/renderer_state.hpp @@ -13,7 +13,6 @@ class UpdateParameters; */ class RendererState { public: - /// Obtains a CameraOptions out of a given UpdateParameters object. static CameraOptions getCameraOptions(const UpdateParameters&, const EdgeInsets& = {}); diff --git a/include/mbgl/shaders/gl/background.hpp b/include/mbgl/shaders/gl/background.hpp index 4a728f31c1e..ba3d012d7d6 100644 --- a/include/mbgl/shaders/gl/background.hpp +++ b/include/mbgl/shaders/gl/background.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; uniform mat4 u_matrix; diff --git a/include/mbgl/shaders/gl/background_pattern.hpp b/include/mbgl/shaders/gl/background_pattern.hpp index 2626c78f495..b3241b2567b 100644 --- a/include/mbgl/shaders/gl/background_pattern.hpp +++ b/include/mbgl/shaders/gl/background_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_pattern_size_a; uniform vec2 u_pattern_size_b; diff --git a/include/mbgl/shaders/gl/circle.hpp b/include/mbgl/shaders/gl/circle.hpp index 9a32675e954..2999d5b5622 100644 --- a/include/mbgl/shaders/gl/circle.hpp +++ b/include/mbgl/shaders/gl/circle.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform bool u_scale_with_map; uniform bool u_pitch_with_map; diff --git a/include/mbgl/shaders/gl/clipping_mask.hpp b/include/mbgl/shaders/gl/clipping_mask.hpp index abb4799f884..45c4903bd33 100644 --- a/include/mbgl/shaders/gl/clipping_mask.hpp +++ b/include/mbgl/shaders/gl/clipping_mask.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; uniform mat4 u_matrix; diff --git a/include/mbgl/shaders/gl/collision_box.hpp b/include/mbgl/shaders/gl/collision_box.hpp index b68f4dddb05..6a6c25aff22 100644 --- a/include/mbgl/shaders/gl/collision_box.hpp +++ b/include/mbgl/shaders/gl/collision_box.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; layout (location = 1) in vec2 a_anchor_pos; layout (location = 2) in vec2 a_extrude; diff --git a/include/mbgl/shaders/gl/collision_circle.hpp b/include/mbgl/shaders/gl/collision_circle.hpp index 2c87ba93102..db07f556310 100644 --- a/include/mbgl/shaders/gl/collision_circle.hpp +++ b/include/mbgl/shaders/gl/collision_circle.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; layout (location = 1) in vec2 a_anchor_pos; layout (location = 2) in vec2 a_extrude; diff --git a/include/mbgl/shaders/gl/debug.hpp b/include/mbgl/shaders/gl/debug.hpp index daae1d7c745..ae0661b6fe5 100644 --- a/include/mbgl/shaders/gl/debug.hpp +++ b/include/mbgl/shaders/gl/debug.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; out vec2 v_uv; diff --git a/include/mbgl/shaders/gl/fill.hpp b/include/mbgl/shaders/gl/fill.hpp index 5fd3872ebce..f9d373f811d 100644 --- a/include/mbgl/shaders/gl/fill.hpp +++ b/include/mbgl/shaders/gl/fill.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; uniform mat4 u_matrix; diff --git a/include/mbgl/shaders/gl/fill_extrusion.hpp b/include/mbgl/shaders/gl/fill_extrusion.hpp index 41cf60e4f8f..cfb5f4339ad 100644 --- a/include/mbgl/shaders/gl/fill_extrusion.hpp +++ b/include/mbgl/shaders/gl/fill_extrusion.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec3 u_lightcolor; uniform lowp vec3 u_lightpos; diff --git a/include/mbgl/shaders/gl/fill_extrusion_pattern.hpp b/include/mbgl/shaders/gl/fill_extrusion_pattern.hpp index 35d9c00cf3a..30c3fb804ed 100644 --- a/include/mbgl/shaders/gl/fill_extrusion_pattern.hpp +++ b/include/mbgl/shaders/gl/fill_extrusion_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_pixel_coord_upper; uniform vec2 u_pixel_coord_lower; diff --git a/include/mbgl/shaders/gl/fill_outline.hpp b/include/mbgl/shaders/gl/fill_outline.hpp index 33be116975b..b7f452e3946 100644 --- a/include/mbgl/shaders/gl/fill_outline.hpp +++ b/include/mbgl/shaders/gl/fill_outline.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; uniform mat4 u_matrix; diff --git a/include/mbgl/shaders/gl/fill_outline_pattern.hpp b/include/mbgl/shaders/gl/fill_outline_pattern.hpp index 2d7a5c40b17..dcfb603f76a 100644 --- a/include/mbgl/shaders/gl/fill_outline_pattern.hpp +++ b/include/mbgl/shaders/gl/fill_outline_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_world; uniform vec2 u_pixel_coord_upper; diff --git a/include/mbgl/shaders/gl/fill_pattern.hpp b/include/mbgl/shaders/gl/fill_pattern.hpp index 38139ca6f09..cea58657720 100644 --- a/include/mbgl/shaders/gl/fill_pattern.hpp +++ b/include/mbgl/shaders/gl/fill_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_pixel_coord_upper; uniform vec2 u_pixel_coord_lower; diff --git a/include/mbgl/shaders/gl/heatmap.hpp b/include/mbgl/shaders/gl/heatmap.hpp index edf51615dd6..c7a13c9287a 100644 --- a/include/mbgl/shaders/gl/heatmap.hpp +++ b/include/mbgl/shaders/gl/heatmap.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform float u_extrude_scale; uniform float u_opacity; diff --git a/include/mbgl/shaders/gl/heatmap_texture.hpp b/include/mbgl/shaders/gl/heatmap_texture.hpp index e052cbdfee1..dc89ad0ad34 100644 --- a/include/mbgl/shaders/gl/heatmap_texture.hpp +++ b/include/mbgl/shaders/gl/heatmap_texture.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_world; layout (location = 0) in vec2 a_pos; diff --git a/include/mbgl/shaders/gl/hillshade.hpp b/include/mbgl/shaders/gl/hillshade.hpp index ed569b814ae..3ade4f435a3 100644 --- a/include/mbgl/shaders/gl/hillshade.hpp +++ b/include/mbgl/shaders/gl/hillshade.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; layout (location = 0) in vec2 a_pos; diff --git a/include/mbgl/shaders/gl/hillshade_prepare.hpp b/include/mbgl/shaders/gl/hillshade_prepare.hpp index 6e26c12a69c..4836ccf17e5 100644 --- a/include/mbgl/shaders/gl/hillshade_prepare.hpp +++ b/include/mbgl/shaders/gl/hillshade_prepare.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_dimension; diff --git a/include/mbgl/shaders/gl/line.hpp b/include/mbgl/shaders/gl/line.hpp index 1c772b165c8..c140c70fa53 100644 --- a/include/mbgl/shaders/gl/line.hpp +++ b/include/mbgl/shaders/gl/line.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(// floor(127 / 2) == 63.0 // the maximum allowed miter limit is 2.0 at the moment. the extrude normal is // stored in a byte (-128..127). we scale regular normals up to length 63, but diff --git a/include/mbgl/shaders/gl/line_gradient.hpp b/include/mbgl/shaders/gl/line_gradient.hpp index 7f2901d8ad1..c98f1746a51 100644 --- a/include/mbgl/shaders/gl/line_gradient.hpp +++ b/include/mbgl/shaders/gl/line_gradient.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"( // the attribute conveying progress along a line is scaled to [0, 2^15) #define MAX_LINE_DISTANCE 32767.0 diff --git a/include/mbgl/shaders/gl/line_pattern.hpp b/include/mbgl/shaders/gl/line_pattern.hpp index 617ed764858..c18c98250f1 100644 --- a/include/mbgl/shaders/gl/line_pattern.hpp +++ b/include/mbgl/shaders/gl/line_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(// floor(127 / 2) == 63.0 // the maximum allowed miter limit is 2.0 at the moment. the extrude normal is // stored in a byte (-128..127). we scale regular normals up to length 63, but diff --git a/include/mbgl/shaders/gl/line_sdf.hpp b/include/mbgl/shaders/gl/line_sdf.hpp index 66206befc48..62a34d7cff0 100644 --- a/include/mbgl/shaders/gl/line_sdf.hpp +++ b/include/mbgl/shaders/gl/line_sdf.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(// floor(127 / 2) == 63.0 // the maximum allowed miter limit is 2.0 at the moment. the extrude normal is // stored in a byte (-128..127). we scale regular normals up to length 63, but diff --git a/include/mbgl/shaders/gl/prelude.hpp b/include/mbgl/shaders/gl/prelude.hpp index f4d4c93e631..822fd2b3941 100644 --- a/include/mbgl/shaders/gl/prelude.hpp +++ b/include/mbgl/shaders/gl/prelude.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(#ifdef GL_ES precision highp float; #else diff --git a/include/mbgl/shaders/gl/raster.hpp b/include/mbgl/shaders/gl/raster.hpp index c275c443de1..7087a548013 100644 --- a/include/mbgl/shaders/gl/raster.hpp +++ b/include/mbgl/shaders/gl/raster.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_tl_parent; uniform float u_scale_parent; diff --git a/include/mbgl/shaders/gl/symbol_icon.hpp b/include/mbgl/shaders/gl/symbol_icon.hpp index 273a1ac393a..abfc29e5180 100644 --- a/include/mbgl/shaders/gl/symbol_icon.hpp +++ b/include/mbgl/shaders/gl/symbol_icon.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(const float PI = 3.141592653589793; layout (location = 0) in vec4 a_pos_offset; diff --git a/include/mbgl/shaders/gl/symbol_sdf_icon.hpp b/include/mbgl/shaders/gl/symbol_sdf_icon.hpp index cbf4b9f1d92..babe133eb32 100644 --- a/include/mbgl/shaders/gl/symbol_sdf_icon.hpp +++ b/include/mbgl/shaders/gl/symbol_sdf_icon.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(const float PI = 3.141592653589793; layout (location = 0) in vec4 a_pos_offset; diff --git a/include/mbgl/shaders/gl/symbol_sdf_text.hpp b/include/mbgl/shaders/gl/symbol_sdf_text.hpp index d453fead3b2..fc170dd5889 100644 --- a/include/mbgl/shaders/gl/symbol_sdf_text.hpp +++ b/include/mbgl/shaders/gl/symbol_sdf_text.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(const float PI = 3.141592653589793; layout (location = 0) in vec4 a_pos_offset; diff --git a/include/mbgl/shaders/gl/symbol_text_and_icon.hpp b/include/mbgl/shaders/gl/symbol_text_and_icon.hpp index 716f75798d1..a448b437bd5 100644 --- a/include/mbgl/shaders/gl/symbol_text_and_icon.hpp +++ b/include/mbgl/shaders/gl/symbol_text_and_icon.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(const float PI = 3.141592653589793; layout (location = 0) in vec4 a_pos_offset; diff --git a/include/mbgl/shaders/shader_source.hpp b/include/mbgl/shaders/shader_source.hpp index 9eb79b6218f..22cf642e882 100644 --- a/include/mbgl/shaders/shader_source.hpp +++ b/include/mbgl/shaders/shader_source.hpp @@ -45,10 +45,12 @@ enum class BuiltIn { /// @tparam T One of the built-in shader types available in the BuiltIn enum /// @tparam The desired graphics API to request shader code for. One of /// gfx::Backend::Type enums. -template struct ShaderSource; +template +struct ShaderSource; /// @brief A specialization of the ShaderSource template for no shader code. -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = ""; static constexpr const char* fragment = ""; }; diff --git a/include/mbgl/storage/database_file_source.hpp b/include/mbgl/storage/database_file_source.hpp index 195e04087c1..762d329e6bc 100644 --- a/include/mbgl/storage/database_file_source.hpp +++ b/include/mbgl/storage/database_file_source.hpp @@ -146,15 +146,13 @@ class DatabaseFileSource : public FileSource { * downloading resources, call `setOfflineRegionDownloadState(OfflineRegionDownloadState::Active)`, * optionally registering an `OfflineRegionObserver` beforehand. */ - virtual void createOfflineRegion(const OfflineRegionDefinition& definition, - const OfflineRegionMetadata& metadata, - std::function)>); + virtual void + createOfflineRegion(const OfflineRegionDefinition& definition, const OfflineRegionMetadata& metadata, std::function)>); /** * Update an offline region metadata in the database. */ - virtual void updateOfflineMetadata(int64_t regionID, - const OfflineRegionMetadata& metadata, - std::function)>); + virtual void + updateOfflineMetadata(int64_t regionID, const OfflineRegionMetadata& metadata, std::function)>); /** * Register an observer to be notified when the state of the region changes. @@ -172,8 +170,9 @@ class DatabaseFileSource : public FileSource { * executed on the database thread; it is the responsibility of the SDK bindings * to re-execute a user-provided callback on the main thread. */ - virtual void getOfflineRegionStatus(const OfflineRegion&, - std::function)>) const; + virtual void + getOfflineRegionStatus(const OfflineRegion&, std::function)>) + const; /** * Merge offline regions from a secondary database into the main offline database. @@ -195,8 +194,8 @@ class DatabaseFileSource : public FileSource { * Merged regions may not be in a completed status if the secondary database * does not contain all the tiles or resources required by the region definition. */ - virtual void mergeOfflineRegions(const std::string& sideDatabasePath, - std::function)>); + virtual void + mergeOfflineRegions(const std::string& sideDatabasePath, std::function)>); /** * Remove an offline region from the database and perform any resources evictions diff --git a/include/mbgl/storage/file_source.hpp b/include/mbgl/storage/file_source.hpp index a5e95ce8d45..504059bc360 100644 --- a/include/mbgl/storage/file_source.hpp +++ b/include/mbgl/storage/file_source.hpp @@ -37,7 +37,7 @@ class FileSource { FileSource& operator=(const FileSource&) = delete; virtual ~FileSource() = default; - using Callback = std::function; + using Callback = std::function; /// Request a resource. The callback will be called asynchronously, in the same /// thread as the request was made. This thread must have an active RunLoop. The diff --git a/include/mbgl/storage/file_source_manager.hpp b/include/mbgl/storage/file_source_manager.hpp index dd78eb319d9..a27fdd23b4e 100644 --- a/include/mbgl/storage/file_source_manager.hpp +++ b/include/mbgl/storage/file_source_manager.hpp @@ -30,7 +30,9 @@ class FileSourceManager { // Returns shared instance of a file source for (type, options) tuple. // Creates new instance via registered factory if needed. If new instance cannot be // created, nullptr would be returned. - [[nodiscard]] std::shared_ptr getFileSource(FileSourceType, const ResourceOptions&, const ClientOptions& = ClientOptions()) noexcept; + [[nodiscard]] std::shared_ptr getFileSource( + FileSourceType, const ResourceOptions&, const ClientOptions& = ClientOptions() + ) noexcept; // Registers file source factory for a provided FileSourceType type. If factory for the // same type was already registered, will unregister previously registered factory. diff --git a/include/mbgl/storage/offline.hpp b/include/mbgl/storage/offline.hpp index 77ad3e31d5a..2612459de83 100644 --- a/include/mbgl/storage/offline.hpp +++ b/include/mbgl/storage/offline.hpp @@ -52,7 +52,9 @@ class OfflineTilePyramidRegionDefinition { */ class OfflineGeometryRegionDefinition { public: - OfflineGeometryRegionDefinition(std::string styleURL, Geometry, double minZoom, double maxZoom, float pixelRatio, bool includeIdeographs); + OfflineGeometryRegionDefinition( + std::string styleURL, Geometry, double minZoom, double maxZoom, float pixelRatio, bool includeIdeographs + ); /* Private */ std::string styleURL; @@ -156,9 +158,7 @@ class OfflineRegionStatus { */ bool requiredResourceCountIsPrecise = false; - bool complete() const { - return completedResourceCount >= requiredResourceCount; - } + bool complete() const { return completedResourceCount >= requiredResourceCount; } }; /* @@ -220,9 +220,7 @@ class OfflineRegion { private: friend class OfflineDatabase; - OfflineRegion(int64_t id, - OfflineRegionDefinition, - OfflineRegionMetadata); + OfflineRegion(int64_t id, OfflineRegionDefinition, OfflineRegionMetadata); int64_t id; OfflineRegionDefinition definition; diff --git a/include/mbgl/storage/resource.hpp b/include/mbgl/storage/resource.hpp index 580d2696278..fa26d740c1b 100644 --- a/include/mbgl/storage/resource.hpp +++ b/include/mbgl/storage/resource.hpp @@ -33,7 +33,10 @@ class Resource { Offline }; - enum class StoragePolicy : bool { Permanent, Volatile }; + enum class StoragePolicy : bool { + Permanent, + Volatile + }; struct TileData { std::string urlTemplate; @@ -44,24 +47,25 @@ class Resource { }; enum class LoadingMethod : uint8_t { - None = 0b00, - Cache = 0b01, - Network = 0b10, + None = 0b00, + Cache = 0b01, + Network = 0b10, - CacheOnly = Cache, + CacheOnly = Cache, NetworkOnly = Network, - All = Cache | Network, + All = Cache | Network, }; - Resource(Kind kind_, - std::string url_, - std::optional tileData_ = std::nullopt, - LoadingMethod loadingMethod_ = LoadingMethod::All) + Resource( + Kind kind_, + std::string url_, + std::optional tileData_ = std::nullopt, + LoadingMethod loadingMethod_ = LoadingMethod::All + ) : kind(kind_), loadingMethod(loadingMethod_), url(std::move(url_)), - tileData(std::move(tileData_)) { - } + tileData(std::move(tileData_)) {} void setPriority(Priority p) { priority = p; } void setUsage(Usage u) { usage = u; } @@ -70,24 +74,26 @@ class Resource { static Resource style(const std::string& url); static Resource source(const std::string& url); - static Resource tile(const std::string& urlTemplate, - float pixelRatio, - int32_t x, - int32_t y, - int8_t z, - Tileset::Scheme scheme, - LoadingMethod = LoadingMethod::All); - static Resource glyphs(const std::string& urlTemplate, - const FontStack& fontStack, - const std::pair& glyphRange); + static Resource tile( + const std::string& urlTemplate, + float pixelRatio, + int32_t x, + int32_t y, + int8_t z, + Tileset::Scheme scheme, + LoadingMethod = LoadingMethod::All + ); + static Resource glyphs( + const std::string& urlTemplate, const FontStack& fontStack, const std::pair& glyphRange + ); static Resource spriteImage(const std::string& base, float pixelRatio); static Resource spriteJSON(const std::string& base, float pixelRatio); static Resource image(const std::string& url); Kind kind; LoadingMethod loadingMethod; - Usage usage{ Usage::Online }; - Priority priority{ Priority::Regular }; + Usage usage{Usage::Online}; + Priority priority{Priority::Regular}; std::string url; // Includes auxiliary data if this is a tile request. diff --git a/include/mbgl/storage/resource_options.hpp b/include/mbgl/storage/resource_options.hpp index 2b14c2bd396..f786fab12e9 100644 --- a/include/mbgl/storage/resource_options.hpp +++ b/include/mbgl/storage/resource_options.hpp @@ -24,7 +24,8 @@ class ResourceOptions final { ResourceOptions clone() const; /** - * @brief Sets the Mapbox access token - see https://docs.mapbox.com/help/how-mapbox-works/access-tokens/ for details. + * @brief Sets the Mapbox access token - see https://docs.mapbox.com/help/how-mapbox-works/access-tokens/ for + * details. * * @param token Mapbox access token. * @return ResourceOptions for chaining options together. diff --git a/include/mbgl/storage/response.hpp b/include/mbgl/storage/response.hpp index 7516c7944f1..64553625e30 100644 --- a/include/mbgl/storage/response.hpp +++ b/include/mbgl/storage/response.hpp @@ -37,15 +37,11 @@ class Response { std::optional expires; std::optional etag; - bool isFresh() const { - return expires ? *expires > util::now() : !error; - } + bool isFresh() const { return expires ? *expires > util::now() : !error; } // Indicates whether we are allowed to use this response according to HTTP caching rules. // It may or may not be stale. - bool isUsable() const { - return !mustRevalidate || (expires && *expires > util::now()); - } + bool isUsable() const { return !mustRevalidate || (expires && *expires > util::now()); } }; class Response::Error { diff --git a/include/mbgl/style/color_ramp_property_value.hpp b/include/mbgl/style/color_ramp_property_value.hpp index cae06e15796..192ff2bb2f2 100644 --- a/include/mbgl/style/color_ramp_property_value.hpp +++ b/include/mbgl/style/color_ramp_property_value.hpp @@ -24,14 +24,18 @@ class ColorRampPropertyValue { } public: - ColorRampPropertyValue() : value(nullptr) {} - ColorRampPropertyValue(std::shared_ptr value_) : value(std::move(value_)) {} + ColorRampPropertyValue() + : value(nullptr) {} + ColorRampPropertyValue(std::shared_ptr value_) + : value(std::move(value_)) {} bool isUndefined() const { return value == nullptr; } // noop, needed for batch evaluation of paint property values to compile template - Color evaluate(const Evaluator&, TimePoint = {}) const { return {}; } + Color evaluate(const Evaluator&, TimePoint = {}) const { + return {}; + } Color evaluate(double rampEvaluationParameter) const { const auto result = value->evaluate(expression::EvaluationContext({}, nullptr, {rampEvaluationParameter})); @@ -44,6 +48,5 @@ class ColorRampPropertyValue { const expression::Expression& getExpression() const { return *value; } }; - } // namespace style } // namespace mbgl diff --git a/include/mbgl/style/conversion.hpp b/include/mbgl/style/conversion.hpp index 29af9fac911..d4db944885a 100644 --- a/include/mbgl/style/conversion.hpp +++ b/include/mbgl/style/conversion.hpp @@ -10,7 +10,9 @@ namespace conversion { // compilation speed. In order to specialize implementations and get access to the actual // implementation, include . -struct Error { std::string message; }; +struct Error { + std::string message; +}; template class ConversionTraits; @@ -26,4 +28,3 @@ struct ValueFactory; } // namespace conversion } // namespace style } // namespace mbgl - diff --git a/include/mbgl/style/conversion/color_ramp_property_value.hpp b/include/mbgl/style/conversion/color_ramp_property_value.hpp index 59ff13932ee..4a359249ae5 100644 --- a/include/mbgl/style/conversion/color_ramp_property_value.hpp +++ b/include/mbgl/style/conversion/color_ramp_property_value.hpp @@ -9,7 +9,12 @@ namespace conversion { template <> struct Converter { - std::optional operator()(const Convertible& value, Error& error, bool /* allowDataExpressions */ = false, bool /* convertTokens */ = false) const; + std::optional operator()( + const Convertible& value, + Error& error, + bool /* allowDataExpressions */ = false, + bool /* convertTokens */ = false + ) const; }; } // namespace conversion diff --git a/include/mbgl/style/conversion/coordinate.hpp b/include/mbgl/style/conversion/coordinate.hpp index 13a992d2e5f..c32e0b38ea2 100644 --- a/include/mbgl/style/conversion/coordinate.hpp +++ b/include/mbgl/style/conversion/coordinate.hpp @@ -8,11 +8,11 @@ namespace mbgl { namespace style { namespace conversion { - -template<> + +template <> struct Converter { public: - std::optional operator() (const Convertible& value, Error& error) const; + std::optional operator()(const Convertible& value, Error& error) const; }; } // namespace conversion diff --git a/include/mbgl/style/conversion/function.hpp b/include/mbgl/style/conversion/function.hpp index 6e9375ff15c..dd715960ffd 100644 --- a/include/mbgl/style/conversion/function.hpp +++ b/include/mbgl/style/conversion/function.hpp @@ -17,10 +17,14 @@ std::unique_ptr convertTokenStringToFormatExpression(con std::unique_ptr convertTokenStringToImageExpression(const std::string&); std::unique_ptr convertTokenStringToExpression(const std::string&); -std::optional> convertFunctionToExpression(expression::type::Type, const Convertible&, Error&, bool convertTokens); +std::optional> convertFunctionToExpression( + expression::type::Type, const Convertible&, Error&, bool convertTokens +); template -std::optional> convertFunctionToExpression(const Convertible& value, Error& error, bool convertTokens); +std::optional> convertFunctionToExpression( + const Convertible& value, Error& error, bool convertTokens +); } // namespace conversion } // namespace style diff --git a/include/mbgl/style/conversion/property_value.hpp b/include/mbgl/style/conversion/property_value.hpp index 75829919bc2..ad7a8c2447d 100644 --- a/include/mbgl/style/conversion/property_value.hpp +++ b/include/mbgl/style/conversion/property_value.hpp @@ -18,7 +18,9 @@ namespace conversion { template struct Converter> { - std::optional> operator()(const Convertible& value, Error& error, bool allowDataExpressions, bool convertTokens) const; + std::optional> operator()( + const Convertible& value, Error& error, bool allowDataExpressions, bool convertTokens + ) const; template PropertyValue maybeConvertTokens(const S& t) const { @@ -26,11 +28,10 @@ struct Converter> { }; PropertyValue maybeConvertTokens(const std::string& t) const { - return hasTokens(t) - ? PropertyValue(PropertyExpression(convertTokenStringToExpression(t))) - : PropertyValue(t); + return hasTokens(t) ? PropertyValue(PropertyExpression(convertTokenStringToExpression(t))) + : PropertyValue(t); } - + PropertyValue maybeConvertTokens(const expression::Formatted& t) const { // This only works with a single-section `Formatted` created automatically // by parsing a plain-text `text-field` property. @@ -38,8 +39,9 @@ struct Converter> { // General purpose `format` expressions with embedded tokens are not supported const std::string& firstUnformattedSection = t.sections[0].text; return hasTokens(firstUnformattedSection) - ? PropertyValue(PropertyExpression(convertTokenStringToFormatExpression(firstUnformattedSection))) - : PropertyValue(t); + ? PropertyValue(PropertyExpression(convertTokenStringToFormatExpression(firstUnformattedSection + ))) + : PropertyValue(t); } PropertyValue maybeConvertTokens(const expression::Image& image) const { @@ -51,7 +53,8 @@ struct Converter> { template <> struct Converter>, void> { - std::optional>> operator()(const Convertible& value, Error& error, bool, bool) const; + std::optional>> operator()(const Convertible& value, Error& error, bool, bool) + const; }; } // namespace conversion } // namespace style diff --git a/include/mbgl/style/conversion/source.hpp b/include/mbgl/style/conversion/source.hpp index 10d06ee665a..ca79360777a 100644 --- a/include/mbgl/style/conversion/source.hpp +++ b/include/mbgl/style/conversion/source.hpp @@ -13,7 +13,8 @@ namespace conversion { template <> struct Converter> { public: - std::optional> operator()(const Convertible& value, Error& error, const std::string& id) const; + std::optional> operator()(const Convertible& value, Error& error, const std::string& id) + const; }; } // namespace conversion diff --git a/include/mbgl/style/conversion_impl.hpp b/include/mbgl/style/conversion_impl.hpp index 94960d27dae..ad691456c5f 100644 --- a/include/mbgl/style/conversion_impl.hpp +++ b/include/mbgl/style/conversion_impl.hpp @@ -97,19 +97,19 @@ class Convertible { public: template // NOLINTNEXTLINE(bugprone-forwarding-reference-overload) - Convertible(T&& value) : vtable(vtableForType>()) { + Convertible(T&& value) + : vtable(vtableForType>()) { static_assert(sizeof(Storage) >= sizeof(std::decay_t), "Storage must be large enough to hold value type"); new (static_cast(&storage)) std::decay_t(std::forward(value)); } - Convertible(Convertible&& v) noexcept : vtable(v.vtable) { + Convertible(Convertible&& v) noexcept + : vtable(v.vtable) { // NOLINTNEXTLINE(performance-move-const-arg) vtable->move(std::move(v.storage), storage); } - ~Convertible() { - vtable->destroy(storage); - } + ~Convertible() { vtable->destroy(storage); } Convertible& operator=(Convertible&& v) noexcept { if (this != &v) { @@ -121,8 +121,8 @@ class Convertible { return *this; } - Convertible() = delete; - Convertible(const Convertible&) = delete; + Convertible() = delete; + Convertible(const Convertible&) = delete; Convertible& operator=(const Convertible&) = delete; friend inline bool isUndefined(const Convertible& v) { @@ -150,12 +150,14 @@ class Convertible { return v.vtable->isObject(v.storage); } - friend inline std::optional objectMember(const Convertible& v, const char * name) { + friend inline std::optional objectMember(const Convertible& v, const char* name) { assert(v.vtable); return v.vtable->objectMember(v.storage, name); } - friend inline std::optional eachMember(const Convertible& v, const std::function (const std::string&, const Convertible&)>& fn) { + friend inline std::optional eachMember( + const Convertible& v, const std::function(const std::string&, const Convertible&)>& fn + ) { assert(v.vtable); return v.vtable->eachMember(v.storage, fn); } @@ -204,33 +206,36 @@ class Convertible { #endif struct VTable { - void (*move) (Storage&& src, Storage& dest); - void (*destroy) (Storage&); + void (*move)(Storage&& src, Storage& dest); + void (*destroy)(Storage&); - bool (*isUndefined) (const Storage&); + bool (*isUndefined)(const Storage&); - bool (*isArray) (const Storage&); - std::size_t (*arrayLength) (const Storage&); - Convertible (*arrayMember) (const Storage&, std::size_t); + bool (*isArray)(const Storage&); + std::size_t (*arrayLength)(const Storage&); + Convertible (*arrayMember)(const Storage&, std::size_t); - bool (*isObject) (const Storage&); - std::optional (*objectMember) (const Storage&, const char *); - std::optional (*eachMember) (const Storage&, const std::function (const std::string&, const Convertible&)>&); + bool (*isObject)(const Storage&); + std::optional (*objectMember)(const Storage&, const char*); + std::optional (*eachMember + )(const Storage&, const std::function(const std::string&, const Convertible&)>&); - std::optional (*toBool) (const Storage&); - std::optional (*toNumber) (const Storage&); - std::optional (*toDouble) (const Storage&); - std::optional (*toString) (const Storage&); - std::optional (*toValue) (const Storage&); + std::optional (*toBool)(const Storage&); + std::optional (*toNumber)(const Storage&); + std::optional (*toDouble)(const Storage&); + std::optional (*toString)(const Storage&); + std::optional (*toValue)(const Storage&); // https://github.com/mapbox/mapbox-gl-native/issues/5623 - std::optional (*toGeoJSON) (const Storage&, Error&); + std::optional (*toGeoJSON)(const Storage&, Error&); }; // Extracted this function from the table below to work around a GCC bug with differing // visibility settings for capturing lambdas: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80947 template - static auto vtableEachMember(const Storage& s, const std::function(const std::string&, const Convertible&)>& fn) { + static auto vtableEachMember( + const Storage& s, const std::function(const std::string&, const Convertible&)>& fn + ) { return ConversionTraits::eachMember(reinterpret_cast(s), [&](const std::string& k, T&& v) { return fn(k, Convertible(std::move(v))); }); @@ -240,28 +245,16 @@ class Convertible { static VTable* vtableForType() { using Traits = ConversionTraits; static VTable vtable = { - [] (Storage&& src, Storage& dest) { - new (static_cast(&dest)) T(reinterpret_cast(src)); - }, - [] (Storage& s) { - reinterpret_cast(s).~T(); - }, - [] (const Storage& s) { - return Traits::isUndefined(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::isArray(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::arrayLength(reinterpret_cast(s)); - }, - [] (const Storage& s, std::size_t i) { + [](Storage&& src, Storage& dest) { new (static_cast(&dest)) T(reinterpret_cast(src)); }, + [](Storage& s) { reinterpret_cast(s).~T(); }, + [](const Storage& s) { return Traits::isUndefined(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::isArray(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::arrayLength(reinterpret_cast(s)); }, + [](const Storage& s, std::size_t i) { return Convertible(Traits::arrayMember(reinterpret_cast(s), i)); }, - [] (const Storage& s) { - return Traits::isObject(reinterpret_cast(s)); - }, - [] (const Storage& s, const char * key) { + [](const Storage& s) { return Traits::isObject(reinterpret_cast(s)); }, + [](const Storage& s, const char* key) { std::optional member = Traits::objectMember(reinterpret_cast(s), key); if (member) { return std::optional(Convertible(std::move(*member))); @@ -270,25 +263,14 @@ class Convertible { } }, vtableEachMember, - [] (const Storage& s) { - return Traits::toBool(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::toNumber(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::toDouble(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::toString(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::toValue(reinterpret_cast(s)); - }, - [] (const Storage& s, Error& err) { + [](const Storage& s) { return Traits::toBool(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::toNumber(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::toDouble(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::toString(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::toValue(reinterpret_cast(s)); }, + [](const Storage& s, Error& err) { return Traits::toGeoJSON(reinterpret_cast(s), err); - } - }; + }}; return &vtable; } @@ -296,8 +278,8 @@ class Convertible { Storage storage; }; -template -std::optional convert(const Convertible& value, Error& error, Args&&...args) { +template +std::optional convert(const Convertible& value, Error& error, Args&&... args) { return Converter()(value, error, std::forward(args)...); } @@ -362,16 +344,18 @@ Value makeValue(T&& arg) { template StyleProperty makeStyleProperty(const PropertyValue& value) { - return value.match([](const Undefined&) -> StyleProperty { return {}; }, - [](const Color& c) -> StyleProperty { - return {makeValue(c), StyleProperty::Kind::Expression}; - }, - [](const PropertyExpression& fn) -> StyleProperty { - return {fn.getExpression().serialize(), StyleProperty::Kind::Expression}; - }, - [](const auto& t) -> StyleProperty { - return {makeValue(t), StyleProperty::Kind::Constant}; - }); + return value.match( + [](const Undefined&) -> StyleProperty { return {}; }, + [](const Color& c) -> StyleProperty { + return {makeValue(c), StyleProperty::Kind::Expression}; + }, + [](const PropertyExpression& fn) -> StyleProperty { + return {fn.getExpression().serialize(), StyleProperty::Kind::Expression}; + }, + [](const auto& t) -> StyleProperty { + return {makeValue(t), StyleProperty::Kind::Constant}; + } + ); } inline StyleProperty makeStyleProperty(const TransitionOptions& value) { diff --git a/include/mbgl/style/expression/assertion.hpp b/include/mbgl/style/expression/assertion.hpp index 8921cf92138..aee30724cd8 100644 --- a/include/mbgl/style/expression/assertion.hpp +++ b/include/mbgl/style/expression/assertion.hpp @@ -11,7 +11,7 @@ namespace mbgl { namespace style { namespace expression { -class Assertion : public Expression { +class Assertion : public Expression { public: Assertion(type::Type type_, std::vector> inputs_); @@ -19,11 +19,11 @@ class Assertion : public Expression { EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - + bool operator==(const Expression& e) const override; std::vector> possibleOutputs() const override; - + mbgl::Value serialize() const override; std::string getOperator() const override; diff --git a/include/mbgl/style/expression/at.hpp b/include/mbgl/style/expression/at.hpp index c208b4712b2..ab6a6247f33 100644 --- a/include/mbgl/style/expression/at.hpp +++ b/include/mbgl/style/expression/at.hpp @@ -10,14 +10,13 @@ namespace expression { class At : public Expression { public: - At(std::unique_ptr index_, std::unique_ptr input_) : - Expression(Kind::At, input_->getType().get().itemType), - index(std::move(index_)), - input(std::move(input_)) - {} - + At(std::unique_ptr index_, std::unique_ptr input_) + : Expression(Kind::At, input_->getType().get().itemType), + index(std::move(index_)), + input(std::move(input_)) {} + static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); - + EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; @@ -29,10 +28,8 @@ class At : public Expression { return false; } - std::vector> possibleOutputs() const override { - return { std::nullopt }; - } - + std::vector> possibleOutputs() const override { return {std::nullopt}; } + std::string getOperator() const override { return "at"; } private: diff --git a/include/mbgl/style/expression/boolean_operator.hpp b/include/mbgl/style/expression/boolean_operator.hpp index cb67fb4aba0..442de3d278f 100644 --- a/include/mbgl/style/expression/boolean_operator.hpp +++ b/include/mbgl/style/expression/boolean_operator.hpp @@ -9,12 +9,11 @@ namespace mbgl { namespace style { namespace expression { -class Any : public Expression { +class Any : public Expression { public: - Any(std::vector> inputs_) : - Expression(Kind::Any, type::Boolean), - inputs(std::move(inputs_)) - {} + Any(std::vector> inputs_) + : Expression(Kind::Any, type::Boolean), + inputs(std::move(inputs_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); @@ -24,16 +23,16 @@ class Any : public Expression { std::vector> possibleOutputs() const override; std::string getOperator() const override { return "any"; } + private: std::vector> inputs; }; -class All : public Expression { +class All : public Expression { public: - All(std::vector> inputs_) : - Expression(Kind::All, type::Boolean), - inputs(std::move(inputs_)) - {} + All(std::vector> inputs_) + : Expression(Kind::All, type::Boolean), + inputs(std::move(inputs_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); @@ -43,6 +42,7 @@ class All : public Expression { std::vector> possibleOutputs() const override; std::string getOperator() const override { return "all"; } + private: std::vector> inputs; }; diff --git a/include/mbgl/style/expression/case.hpp b/include/mbgl/style/expression/case.hpp index 8785049b1e3..93a4edc87c7 100644 --- a/include/mbgl/style/expression/case.hpp +++ b/include/mbgl/style/expression/case.hpp @@ -17,18 +17,21 @@ class Case : public Expression { using Branch = std::pair, std::unique_ptr>; Case(type::Type type_, std::vector branches_, std::unique_ptr otherwise_) - : Expression(Kind::Case, std::move(type_)), branches(std::move(branches_)), otherwise(std::move(otherwise_)) {} + : Expression(Kind::Case, std::move(type_)), + branches(std::move(branches_)), + otherwise(std::move(otherwise_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - + bool operator==(const Expression& e) const override; std::vector> possibleOutputs() const override; std::string getOperator() const override { return "case"; } + private: std::vector branches; std::unique_ptr otherwise; diff --git a/include/mbgl/style/expression/coalesce.hpp b/include/mbgl/style/expression/coalesce.hpp index 3273fbfc652..044ba7b1629 100644 --- a/include/mbgl/style/expression/coalesce.hpp +++ b/include/mbgl/style/expression/coalesce.hpp @@ -14,31 +14,26 @@ namespace expression { class Coalesce : public Expression { public: using Args = std::vector>; - Coalesce(const type::Type& type_, Args args_) : - Expression(Kind::Coalesce, type_), - args(std::move(args_)) - {} + Coalesce(const type::Type& type_, Args args_) + : Expression(Kind::Coalesce, type_), + args(std::move(args_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); - EvaluationResult evaluate(const EvaluationContext& params) const override; - + void eachChild(const std::function& visit) const override; bool operator==(const Expression& e) const override; std::vector> possibleOutputs() const override; - std::size_t getLength() const { - return args.size(); - } - - Expression* getChild(std::size_t i) const { - return args.at(i).get(); - } - + std::size_t getLength() const { return args.size(); } + + Expression* getChild(std::size_t i) const { return args.at(i).get(); } + std::string getOperator() const override { return "coalesce"; } + private: Args args; }; diff --git a/include/mbgl/style/expression/coercion.hpp b/include/mbgl/style/expression/coercion.hpp index df70182ab87..124a1176bf6 100644 --- a/include/mbgl/style/expression/coercion.hpp +++ b/include/mbgl/style/expression/coercion.hpp @@ -10,7 +10,7 @@ namespace mbgl { namespace style { namespace expression { -class Coercion : public Expression { +class Coercion : public Expression { public: Coercion(type::Type type_, std::vector> inputs_); @@ -18,7 +18,7 @@ class Coercion : public Expression { EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - + mbgl::Value serialize() const override; bool operator==(const Expression& e) const override; @@ -26,12 +26,12 @@ class Coercion : public Expression { std::vector> possibleOutputs() const override; std::string getOperator() const override; + private: - EvaluationResult (*coerceSingleValue) (const Value& v); + EvaluationResult (*coerceSingleValue)(const Value& v); std::vector> inputs; }; } // namespace expression } // namespace style } // namespace mbgl - diff --git a/include/mbgl/style/expression/collator.hpp b/include/mbgl/style/expression/collator.hpp index eb82f8f1739..9c94f8109eb 100644 --- a/include/mbgl/style/expression/collator.hpp +++ b/include/mbgl/style/expression/collator.hpp @@ -18,6 +18,7 @@ class Collator { int compare(const std::string& lhs, const std::string& rhs) const; std::string resolvedLocale() const; + private: platform::Collator collator; }; diff --git a/include/mbgl/style/expression/collator_expression.hpp b/include/mbgl/style/expression/collator_expression.hpp index 7889f8a7c8e..0ec619c408d 100644 --- a/include/mbgl/style/expression/collator_expression.hpp +++ b/include/mbgl/style/expression/collator_expression.hpp @@ -12,9 +12,11 @@ namespace expression { class CollatorExpression : public Expression { public: - CollatorExpression(std::unique_ptr caseSensitive, - std::unique_ptr diacriticSensitive, - std::optional> locale); + CollatorExpression( + std::unique_ptr caseSensitive, + std::unique_ptr diacriticSensitive, + std::optional> locale + ); EvaluationResult evaluate(const EvaluationContext&) const override; static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); @@ -28,11 +30,12 @@ class CollatorExpression : public Expression { // by all possibleOutputs of locale/caseSensitive/diacriticSensitive // But for the primary use of Collators in comparison operators, we ignore the Collator's // possibleOutputs anyway, so we can get away with leaving this undefined for now. - return { std::nullopt }; + return {std::nullopt}; } mbgl::Value serialize() const override; std::string getOperator() const override { return "collator"; } + private: std::unique_ptr caseSensitive; std::unique_ptr diacriticSensitive; diff --git a/include/mbgl/style/expression/comparison.hpp b/include/mbgl/style/expression/comparison.hpp index 09f461537ba..4271d24bee7 100644 --- a/include/mbgl/style/expression/comparison.hpp +++ b/include/mbgl/style/expression/comparison.hpp @@ -17,10 +17,7 @@ class BasicComparison : public Expression { public: using CompareFunctionType = bool (*)(const Value&, const Value&); - BasicComparison( - std::string op, - std::unique_ptr lhs, - std::unique_ptr rhs); + BasicComparison(std::string op, std::unique_ptr lhs, std::unique_ptr rhs); void eachChild(const std::function& visit) const override; bool operator==(const Expression&) const override; @@ -44,7 +41,8 @@ class CollatorComparison : public Expression { std::string op, std::unique_ptr lhs, std::unique_ptr rhs, - std::unique_ptr collator); + std::unique_ptr collator + ); void eachChild(const std::function& visit) const override; bool operator==(const Expression&) const override; @@ -61,8 +59,6 @@ class CollatorComparison : public Expression { bool needsRuntimeTypeCheck; }; - - } // namespace expression } // namespace style } // namespace mbgl diff --git a/include/mbgl/style/expression/compound_expression.hpp b/include/mbgl/style/expression/compound_expression.hpp index d4edb512177..234dcf36618 100644 --- a/include/mbgl/style/expression/compound_expression.hpp +++ b/include/mbgl/style/expression/compound_expression.hpp @@ -46,13 +46,13 @@ class CompoundExpression : public Expression { std::vector> args; }; -ParseResult parseCompoundExpression(const std::string& name, - const mbgl::style::conversion::Convertible& value, - ParsingContext& ctx); +ParseResult parseCompoundExpression( + const std::string& name, const mbgl::style::conversion::Convertible& value, ParsingContext& ctx +); -ParseResult createCompoundExpression(const std::string& name, - std::vector> args, - ParsingContext& ctx); +ParseResult createCompoundExpression( + const std::string& name, std::vector> args, ParsingContext& ctx +); } // namespace expression } // namespace style diff --git a/include/mbgl/style/expression/distance.hpp b/include/mbgl/style/expression/distance.hpp index 670ae11cd75..3fc44b9a2bf 100644 --- a/include/mbgl/style/expression/distance.hpp +++ b/include/mbgl/style/expression/distance.hpp @@ -2,8 +2,8 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4244) -#pragma warning(disable: 4267) +#pragma warning(disable : 4244) +#pragma warning(disable : 4267) #endif #include diff --git a/include/mbgl/style/expression/dsl.hpp b/include/mbgl/style/expression/dsl.hpp index c31dd2b4f61..f11bef1fcab 100644 --- a/include/mbgl/style/expression/dsl.hpp +++ b/include/mbgl/style/expression/dsl.hpp @@ -19,7 +19,7 @@ namespace dsl { template std::vector> vec(Args... args) { std::vector> result; - util::ignore({ (result.push_back(std::move(args)), 0)... }); + util::ignore({(result.push_back(std::move(args)), 0)...}); return result; } @@ -32,22 +32,16 @@ std::unique_ptr literal(const Value& value); std::unique_ptr literal(std::initializer_list value); std::unique_ptr literal(std::initializer_list value); -std::unique_ptr assertion(const type::Type&, - std::unique_ptr, - std::unique_ptr def = nullptr); -std::unique_ptr number(std::unique_ptr, - std::unique_ptr def = nullptr); -std::unique_ptr string(std::unique_ptr, - std::unique_ptr def = nullptr); -std::unique_ptr boolean(std::unique_ptr, - std::unique_ptr def = nullptr); - -std::unique_ptr toColor(std::unique_ptr, - std::unique_ptr def = nullptr); -std::unique_ptr toString(std::unique_ptr, - std::unique_ptr def = nullptr); -std::unique_ptr toFormatted(std::unique_ptr, - std::unique_ptr def = nullptr); +std::unique_ptr assertion( + const type::Type&, std::unique_ptr, std::unique_ptr def = nullptr +); +std::unique_ptr number(std::unique_ptr, std::unique_ptr def = nullptr); +std::unique_ptr string(std::unique_ptr, std::unique_ptr def = nullptr); +std::unique_ptr boolean(std::unique_ptr, std::unique_ptr def = nullptr); + +std::unique_ptr toColor(std::unique_ptr, std::unique_ptr def = nullptr); +std::unique_ptr toString(std::unique_ptr, std::unique_ptr def = nullptr); +std::unique_ptr toFormatted(std::unique_ptr, std::unique_ptr def = nullptr); std::unique_ptr toImage(std::unique_ptr, std::unique_ptr def = nullptr); std::unique_ptr get(const char* value); @@ -61,28 +55,40 @@ std::unique_ptr ne(std::unique_ptr, std::unique_ptr gt(std::unique_ptr, std::unique_ptr); std::unique_ptr lt(std::unique_ptr, std::unique_ptr); -std::unique_ptr step(std::unique_ptr input, - std::unique_ptr output0, - double input1, std::unique_ptr output1); +std::unique_ptr step( + std::unique_ptr input, + std::unique_ptr output0, + double input1, + std::unique_ptr output1 +); Interpolator linear(); Interpolator exponential(double base); Interpolator cubicBezier(double x1, double y1, double x2, double y2); -std::unique_ptr interpolate(Interpolator interpolator, - std::unique_ptr input, - double input1, std::unique_ptr output1); - -std::unique_ptr interpolate(Interpolator interpolator, - std::unique_ptr input, - double input1, std::unique_ptr output1, - double input2, std::unique_ptr output2); - -std::unique_ptr interpolate(Interpolator interpolator, - std::unique_ptr input, - double input1, std::unique_ptr output1, - double input2, std::unique_ptr output2, - double input3, std::unique_ptr output3); +std::unique_ptr interpolate( + Interpolator interpolator, std::unique_ptr input, double input1, std::unique_ptr output1 +); + +std::unique_ptr interpolate( + Interpolator interpolator, + std::unique_ptr input, + double input1, + std::unique_ptr output1, + double input2, + std::unique_ptr output2 +); + +std::unique_ptr interpolate( + Interpolator interpolator, + std::unique_ptr input, + double input1, + std::unique_ptr output1, + double input2, + std::unique_ptr output2, + double input3, + std::unique_ptr output3 +); std::unique_ptr concat(std::vector> inputs); diff --git a/include/mbgl/style/expression/error.hpp b/include/mbgl/style/expression/error.hpp index 7cf76f285e8..bcb6e739749 100644 --- a/include/mbgl/style/expression/error.hpp +++ b/include/mbgl/style/expression/error.hpp @@ -10,23 +10,17 @@ namespace expression { class Error : public Expression { public: - Error(std::string message_) + Error(std::string message_) : Expression(Kind::Error, type::Error), message(std::move(message_)) {} void eachChild(const std::function&) const override {} - bool operator==(const Expression& e) const override { - return e.getKind() == Kind::Error; - } + bool operator==(const Expression& e) const override { return e.getKind() == Kind::Error; } - EvaluationResult evaluate(const EvaluationContext&) const override { - return EvaluationError{message}; - } + EvaluationResult evaluate(const EvaluationContext&) const override { return EvaluationError{message}; } - std::vector> possibleOutputs() const override { - return {}; - } + std::vector> possibleOutputs() const override { return {}; } std::string getOperator() const override { return "error"; } diff --git a/include/mbgl/style/expression/expression.hpp b/include/mbgl/style/expression/expression.hpp index e620a8f26af..3afcd1ee62e 100644 --- a/include/mbgl/style/expression/expression.hpp +++ b/include/mbgl/style/expression/expression.hpp @@ -27,17 +27,26 @@ class EvaluationError { class EvaluationContext { public: EvaluationContext() = default; - explicit EvaluationContext(float zoom_) : zoom(zoom_) {} - explicit EvaluationContext(GeometryTileFeature const * feature_) : feature(feature_) {} - EvaluationContext(float zoom_, GeometryTileFeature const* feature_) : zoom(zoom_), feature(feature_) {} - EvaluationContext(std::optional accumulated_, GeometryTileFeature const * feature_) : - accumulated(std::move(accumulated_)), feature(feature_) - {} + explicit EvaluationContext(float zoom_) + : zoom(zoom_) {} + explicit EvaluationContext(GeometryTileFeature const* feature_) + : feature(feature_) {} + EvaluationContext(float zoom_, GeometryTileFeature const* feature_) + : zoom(zoom_), + feature(feature_) {} + EvaluationContext(std::optional accumulated_, GeometryTileFeature const* feature_) + : accumulated(std::move(accumulated_)), + feature(feature_) {} EvaluationContext(float zoom_, GeometryTileFeature const* feature_, const FeatureState* state_) - : zoom(zoom_), feature(feature_), featureState(state_) {} - EvaluationContext(std::optional zoom_, GeometryTileFeature const * feature_, std::optional colorRampParameter_) : - zoom(std::move(zoom_)), feature(feature_), colorRampParameter(std::move(colorRampParameter_)) - {} + : zoom(zoom_), + feature(feature_), + featureState(state_) {} + EvaluationContext( + std::optional zoom_, GeometryTileFeature const* feature_, std::optional colorRampParameter_ + ) + : zoom(std::move(zoom_)), + feature(feature_), + colorRampParameter(std::move(colorRampParameter_)) {} EvaluationContext& withFormattedSection(const Value* formattedSection_) noexcept { formattedSection = formattedSection_; @@ -75,38 +84,37 @@ class Result : private variant { public: using variant::variant; using Value = T; - + Result() = default; template - VARIANT_INLINE Result(U&& val) : variant(val) {} - - explicit operator bool () const { - return this->template is(); - } - + VARIANT_INLINE Result(U&& val) + : variant(val) {} + + explicit operator bool() const { return this->template is(); } + // optional does some type trait magic for this one, so this might // be problematic as is. const T* operator->() const { assert(this->template is()); return std::addressof(this->template get()); } - + T* operator->() { assert(this->template is()); return std::addressof(this->template get()); } - + T& operator*() { assert(this->template is()); return this->template get(); } - + const T& operator*() const { assert(this->template is()); return this->template get(); } - + const EvaluationError& error() const { assert(this->template is()); return this->template get(); @@ -116,17 +124,14 @@ class Result : private variant { class EvaluationResult : public Result { public: using Result::Result; // NOLINT - + EvaluationResult() = default; - EvaluationResult(const std::array& arr) : - Result(toExpressionValue(arr)) - {} - + EvaluationResult(const std::array& arr) + : Result(toExpressionValue(arr)) {} + // used only for the special (private) "error" expression - EvaluationResult(const type::ErrorType&) { - assert(false); - } + EvaluationResult(const type::ErrorType&) { assert(false); } }; /** @@ -137,12 +142,12 @@ class EvaluationResult : public Result { inferring the argument and output from a simple function (const T0& arg0, const T1& arg1, ...) -> Result where T0, T1, ..., U are member types of mbgl::style::expression::Value. - + The other Expression subclasses (Let, Curve, Match, etc.) exist in order to implement expressions that need specialized parsing, type checking, or evaluation logic that can't be handled by CompoundExpression's inference mechanism. - + Each Expression subclass also provides a static ParseResult ExpressionClass::parse(const V&, ParsingContext), which handles parsing a style-spec JSON representation of the expression. @@ -178,29 +183,35 @@ enum class Kind : int32_t { class Expression { public: - Expression(Kind kind_, type::Type type_) : kind(kind_), type(std::move(type_)) {} + Expression(Kind kind_, type::Type type_) + : kind(kind_), + type(std::move(type_)) {} virtual ~Expression() = default; - + virtual EvaluationResult evaluate(const EvaluationContext& params) const = 0; virtual void eachChild(const std::function&) const = 0; virtual bool operator==(const Expression&) const = 0; - bool operator!=(const Expression& rhs) const { - return !operator==(rhs); - } + bool operator!=(const Expression& rhs) const { return !operator==(rhs); } Kind getKind() const { return kind; }; type::Type getType() const { return type; }; - EvaluationResult evaluate(std::optional zoom, const Feature& feature, std::optional colorRampParameter) const; - EvaluationResult evaluate(std::optional zoom, - const Feature& feature, - std::optional colorRampParameter, - const std::set& availableImages) const; - EvaluationResult evaluate(std::optional zoom, - const Feature& feature, - std::optional colorRampParameter, - const std::set& availableImages, - const CanonicalTileID& canonical) const; + EvaluationResult evaluate( + std::optional zoom, const Feature& feature, std::optional colorRampParameter + ) const; + EvaluationResult evaluate( + std::optional zoom, + const Feature& feature, + std::optional colorRampParameter, + const std::set& availableImages + ) const; + EvaluationResult evaluate( + std::optional zoom, + const Feature& feature, + std::optional colorRampParameter, + const std::set& availableImages, + const CanonicalTileID& canonical + ) const; EvaluationResult evaluate(std::optional accumulated, const Feature& feature) const; /** @@ -209,49 +220,49 @@ class Expression { * complete set of outputs is statically undecidable. */ virtual std::vector> possibleOutputs() const = 0; - + virtual mbgl::Value serialize() const { std::vector serialized; serialized.emplace_back(getOperator()); - eachChild([&](const Expression &child) { - serialized.emplace_back(child.serialize()); - }); + eachChild([&](const Expression& child) { serialized.emplace_back(child.serialize()); }); return serialized; }; - + virtual std::string getOperator() const = 0; protected: template static bool childrenEqual(const T& lhs, const T& rhs) { if (lhs.size() != rhs.size()) return false; - for (auto leftChild = lhs.begin(), rightChild = rhs.begin(); - leftChild != lhs.end(); - leftChild++, rightChild++) - { - if (!Expression::childEqual(*leftChild, *rightChild)) return false; - } - return true; + for (auto leftChild = lhs.begin(), rightChild = rhs.begin(); leftChild != lhs.end(); + leftChild++, rightChild++) { + if (!Expression::childEqual(*leftChild, *rightChild)) return false; + } + return true; } - + static bool childEqual(const std::unique_ptr& lhs, const std::unique_ptr& rhs) { return *lhs == *rhs; } - + template - static bool childEqual(const std::pair>& lhs, - const std::pair>& rhs) { + static bool childEqual( + const std::pair>& lhs, const std::pair>& rhs + ) { return lhs.first == rhs.first && *(lhs.second) == *(rhs.second); } - + template - static bool childEqual(const std::pair>& lhs, - const std::pair>& rhs) { + static bool childEqual( + const std::pair>& lhs, const std::pair>& rhs + ) { return lhs.first == rhs.first && *(lhs.second) == *(rhs.second); } - - static bool childEqual(const std::pair, std::unique_ptr>& lhs, - const std::pair, std::unique_ptr>& rhs) { + + static bool childEqual( + const std::pair, std::unique_ptr>& lhs, + const std::pair, std::unique_ptr>& rhs + ) { return *(lhs.first) == *(rhs.first) && *(lhs.second) == *(rhs.second); } diff --git a/include/mbgl/style/expression/format_expression.hpp b/include/mbgl/style/expression/format_expression.hpp index e6fec2e2bc6..33d4e52a183 100644 --- a/include/mbgl/style/expression/format_expression.hpp +++ b/include/mbgl/style/expression/format_expression.hpp @@ -10,9 +10,11 @@ namespace expression { struct FormatExpressionSection { explicit FormatExpressionSection(std::unique_ptr content_); - void setTextSectionOptions(std::optional> fontScale_, - std::optional> textFont_, - std::optional> textColor_); + void setTextSectionOptions( + std::optional> fontScale_, + std::optional> textFont_, + std::optional> textColor_ + ); // Content can be expression that evaluates to String or Image. std::shared_ptr content; @@ -22,32 +24,33 @@ struct FormatExpressionSection { std::optional> textFont; std::optional> textColor; }; - + class FormatExpression final : public Expression { public: explicit FormatExpression(std::vector sections); - + EvaluationResult evaluate(const EvaluationContext&) const override; static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); - + void eachChild(const std::function&) const override; - + bool operator==(const Expression& e) const override; - + std::vector> possibleOutputs() const override { // Technically the combinatoric set of all children // Usually, this.text will be undefined anyway - return { std::nullopt }; + return {std::nullopt}; } - + const std::vector& getSections() const { return sections; } mbgl::Value serialize() const override; std::string getOperator() const override { return "format"; } + private: std::vector sections; }; - + } // namespace expression } // namespace style } // namespace mbgl diff --git a/include/mbgl/style/expression/format_section_override.hpp b/include/mbgl/style/expression/format_section_override.hpp index 2fec025da36..e07bf071704 100644 --- a/include/mbgl/style/expression/format_section_override.hpp +++ b/include/mbgl/style/expression/format_section_override.hpp @@ -7,21 +7,19 @@ namespace mbgl { namespace style { namespace expression { -template +template class FormatSectionOverride final : public Expression { public: - FormatSectionOverride(const type::Type& type_, - PossiblyEvaluatedPropertyValue defaultValue_, - std::string propertyName_) : - Expression(Kind::FormatSectionOverride, type_), - defaultValue(std::move(defaultValue_)), - propertyName(std::move(propertyName_)) - {} + FormatSectionOverride( + const type::Type& type_, PossiblyEvaluatedPropertyValue defaultValue_, std::string propertyName_ + ) + : Expression(Kind::FormatSectionOverride, type_), + defaultValue(std::move(defaultValue_)), + propertyName(std::move(propertyName_)) {} EvaluationResult evaluate(const EvaluationContext& context) const final { using Object = std::unordered_map; - if (context.formattedSection && - context.formattedSection->is()) { + if (context.formattedSection && context.formattedSection->is()) { const auto& section = context.formattedSection->get(); if (section.find(propertyName) != section.end()) { return section.at(propertyName); @@ -29,14 +27,13 @@ class FormatSectionOverride final : public Expression { } return defaultValue.match( - [&context] (const style::PropertyExpression& e) { return e.getExpression().evaluate(context); }, - [] (const T& t) -> EvaluationResult { return t; } + [&context](const style::PropertyExpression& e) { return e.getExpression().evaluate(context); }, + [](const T& t) -> EvaluationResult { return t; } ); } void eachChild(const std::function& fn) const final { - defaultValue.match([&fn] (const style::PropertyExpression& e) { fn(e.getExpression()); }, - [] (const T&) {}); + defaultValue.match([&fn](const style::PropertyExpression& e) { fn(e.getExpression()); }, [](const T&) {}); } bool operator==(const Expression& e) const final { @@ -49,30 +46,25 @@ class FormatSectionOverride final : public Expression { // Check that default values or property expressions are equal. return defaultValue.match( - [other] (const style::PropertyExpression& thisExpr) { - return other->defaultValue.match([&thisExpr] (const style::PropertyExpression& otherExpr) { - return thisExpr == otherExpr; - }, - [] (const T&) { - return false; - }); - }, - [other] (const T& thisValue) { - return other->defaultValue.match([&thisValue] (const T& otherValue) { - return thisValue == otherValue; - }, - [] (const style::PropertyExpression&) { - return false; - }); - }); + [other](const style::PropertyExpression& thisExpr) { + return other->defaultValue.match( + [&thisExpr](const style::PropertyExpression& otherExpr) { return thisExpr == otherExpr; }, + [](const T&) { return false; } + ); + }, + [other](const T& thisValue) { + return other->defaultValue.match( + [&thisValue](const T& otherValue) { return thisValue == otherValue; }, + [](const style::PropertyExpression&) { return false; } + ); + } + ); } return false; } - std::vector> possibleOutputs() const final { - return {std::nullopt}; - } + std::vector> possibleOutputs() const final { return {std::nullopt}; } std::string getOperator() const final { return "format-section-override"; } diff --git a/include/mbgl/style/expression/formatted.hpp b/include/mbgl/style/expression/formatted.hpp index 55c6ca65399..fd2d354e2a6 100644 --- a/include/mbgl/style/expression/formatted.hpp +++ b/include/mbgl/style/expression/formatted.hpp @@ -18,16 +18,19 @@ extern const char* const kFormattedSectionTextFont; extern const char* const kFormattedSectionTextColor; struct FormattedSection { - explicit FormattedSection(std::string text_, - std::optional fontScale_, - std::optional fontStack_, - std::optional textColor_) + explicit FormattedSection( + std::string text_, + std::optional fontScale_, + std::optional fontStack_, + std::optional textColor_ + ) : text(std::move(text_)), fontScale(std::move(fontScale_)), fontStack(std::move(fontStack_)), textColor(std::move(textColor_)) {} - explicit FormattedSection(Image image_) : image(std::move(image_)) {} + explicit FormattedSection(Image image_) + : image(std::move(image_)) {} std::string text; std::optional image; @@ -43,13 +46,12 @@ class Formatted { Formatted(const char* plainU8String) { sections.emplace_back(std::string(plainU8String), std::nullopt, std::nullopt, std::nullopt); } - + Formatted(std::vector sections_) - : sections(std::move(sections_)) - {} - - bool operator==(const Formatted& ) const; - + : sections(std::move(sections_)) {} + + bool operator==(const Formatted&) const; + std::string toString() const; mbgl::Value toObject() const; @@ -57,9 +59,9 @@ class Formatted { std::vector sections; }; - + } // namespace expression - + namespace conversion { template <> @@ -74,6 +76,6 @@ struct ValueFactory { }; } // namespace conversion - + } // namespace style } // namespace mbgl diff --git a/include/mbgl/style/expression/interpolate.hpp b/include/mbgl/style/expression/interpolate.hpp index 0035da713ae..09a7f34e29d 100644 --- a/include/mbgl/style/expression/interpolate.hpp +++ b/include/mbgl/style/expression/interpolate.hpp @@ -19,10 +19,12 @@ ParseResult parseInterpolate(const mbgl::style::conversion::Convertible& value, class Interpolate : public Expression { public: - Interpolate(const type::Type& type_, - Interpolator interpolator_, - std::unique_ptr input_, - std::map> stops_); + Interpolate( + const type::Type& type_, + Interpolator interpolator_, + std::unique_ptr input_, + std::map> stops_ + ); const std::unique_ptr& getInput() const { return input; } const Interpolator& getInterpolator() const { return interpolator; } @@ -39,25 +41,22 @@ class Interpolate : public Expression { visit(stop.first, *stop.second); } } - + // Return the smallest range of stops that covers the interval [lower, upper] Range getCoveringStops(const double lower, const double upper) const { return ::mbgl::style::expression::getCoveringStops(stops, lower, upper); } - + double interpolationFactor(const Range& inputLevels, const double inputValue) const { - return interpolator.match( - [&](const auto& interp) { return interp.interpolationFactor(inputLevels, inputValue); } - ); + return interpolator.match([&](const auto& interp) { + return interp.interpolationFactor(inputLevels, inputValue); + }); } bool operator==(const Expression& e) const override { if (e.getKind() == Kind::Interpolate) { auto rhs = static_cast(&e); - if (interpolator != rhs->interpolator || - *input != *(rhs->input) || - stops.size() != rhs->stops.size()) - { + if (interpolator != rhs->interpolator || *input != *(rhs->input) || stops.size() != rhs->stops.size()) { return false; } @@ -76,11 +75,13 @@ class Interpolate : public Expression { const std::map> stops; }; -ParseResult createInterpolate(type::Type type, - Interpolator interpolator, - std::unique_ptr input, - std::map> stops, - ParsingContext& ctx); +ParseResult createInterpolate( + type::Type type, + Interpolator interpolator, + std::unique_ptr input, + std::map> stops, + ParsingContext& ctx +); } // namespace expression } // namespace style diff --git a/include/mbgl/style/expression/interpolator.hpp b/include/mbgl/style/expression/interpolator.hpp index bd68e5c2f06..35dc64e0131 100644 --- a/include/mbgl/style/expression/interpolator.hpp +++ b/include/mbgl/style/expression/interpolator.hpp @@ -10,42 +10,40 @@ namespace expression { class ExponentialInterpolator { public: - ExponentialInterpolator(double base_) : base(base_) {} + ExponentialInterpolator(double base_) + : base(base_) {} double base; - + double interpolationFactor(const Range& inputLevels, const double input) const { - return util::interpolationFactor(static_cast(base), - Range { - static_cast(inputLevels.min), - static_cast(inputLevels.max) - }, - static_cast(input)); - } - - bool operator==(const ExponentialInterpolator& rhs) const { - return base == rhs.base; + return util::interpolationFactor( + static_cast(base), + Range{static_cast(inputLevels.min), static_cast(inputLevels.max)}, + static_cast(input) + ); } + + bool operator==(const ExponentialInterpolator& rhs) const { return base == rhs.base; } }; class CubicBezierInterpolator { public: - CubicBezierInterpolator(double x1_, double y1_, double x2_, double y2_) : ub(x1_, y1_, x2_, y2_) {} - + CubicBezierInterpolator(double x1_, double y1_, double x2_, double y2_) + : ub(x1_, y1_, x2_, y2_) {} + double interpolationFactor(const Range& inputLevels, const double input) const { - return ub.solve(util::interpolationFactor(1.0f, - Range { - static_cast(inputLevels.min), - static_cast(inputLevels.max) - }, - static_cast(input)), - 1e-6); + return ub.solve( + util::interpolationFactor( + 1.0f, + Range{static_cast(inputLevels.min), static_cast(inputLevels.max)}, + static_cast(input) + ), + 1e-6 + ); } - - bool operator==(const CubicBezierInterpolator& rhs) const { - return ub == rhs.ub; - } - + + bool operator==(const CubicBezierInterpolator& rhs) const { return ub == rhs.ub; } + util::UnitBezier ub; }; diff --git a/include/mbgl/style/expression/let.hpp b/include/mbgl/style/expression/let.hpp index 5e24c0a4ee9..5b37139df4f 100644 --- a/include/mbgl/style/expression/let.hpp +++ b/include/mbgl/style/expression/let.hpp @@ -15,15 +15,14 @@ namespace expression { class Let : public Expression { public: using Bindings = std::map>; - - Let(Bindings bindings_, std::unique_ptr result_) : - Expression(Kind::Let, result_->getType()), - bindings(std::move(bindings_)), - result(std::move(result_)) - {} - + + Let(Bindings bindings_, std::unique_ptr result_) + : Expression(Kind::Let, result_->getType()), + bindings(std::move(bindings_)), + result(std::move(result_)) {} + static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); - + EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; @@ -37,12 +36,11 @@ class Let : public Expression { std::vector> possibleOutputs() const override; - Expression* getResult() const { - return result.get(); - } + Expression* getResult() const { return result.get(); } mbgl::Value serialize() const override; std::string getOperator() const override { return "let"; } + private: Bindings bindings; std::unique_ptr result; @@ -51,7 +49,9 @@ class Let : public Expression { class Var : public Expression { public: Var(std::string name_, std::shared_ptr value_) - : Expression(Kind::Var, value_->getType()), name(std::move(name_)), value(std::move(value_)) {} + : Expression(Kind::Var, value_->getType()), + name(std::move(name_)), + value(std::move(value_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); @@ -70,9 +70,9 @@ class Var : public Expression { mbgl::Value serialize() const override; std::string getOperator() const override { return "var"; } - + const std::shared_ptr& getBoundExpression() const { return value; } - + private: std::string name; std::shared_ptr value; diff --git a/include/mbgl/style/expression/literal.hpp b/include/mbgl/style/expression/literal.hpp index c22e41b3798..857f07cefa9 100644 --- a/include/mbgl/style/expression/literal.hpp +++ b/include/mbgl/style/expression/literal.hpp @@ -12,19 +12,20 @@ namespace expression { class Literal : public Expression { public: - Literal(const Value& value_) : Expression(Kind::Literal, typeOf(value_)), value(value_) {} + Literal(const Value& value_) + : Expression(Kind::Literal, typeOf(value_)), + value(value_) {} Literal(const type::Array& type_, std::vector value_) - : Expression(Kind::Literal, type_), value(std::move(value_)) {} + : Expression(Kind::Literal, type_), + value(std::move(value_)) {} + + EvaluationResult evaluate(const EvaluationContext&) const override { return value; } - EvaluationResult evaluate(const EvaluationContext&) const override { - return value; - } - static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); void eachChild(const std::function&) const override {} - + bool operator==(const Expression& e) const override { if (e.getKind() == Kind::Literal) { auto rhs = static_cast(&e); @@ -33,13 +34,9 @@ class Literal : public Expression { return false; } - std::vector> possibleOutputs() const override { - return {{ value }}; - } - - Value getValue() const { - return value; - } + std::vector> possibleOutputs() const override { return {{value}}; } + + Value getValue() const { return value; } mbgl::Value serialize() const override; std::string getOperator() const override { return "literal"; } diff --git a/include/mbgl/style/expression/match.hpp b/include/mbgl/style/expression/match.hpp index c94b0bd447a..e4084b0664e 100644 --- a/include/mbgl/style/expression/match.hpp +++ b/include/mbgl/style/expression/match.hpp @@ -15,10 +15,12 @@ class Match : public Expression { public: using Branches = std::unordered_map>; - Match(const type::Type& type_, - std::unique_ptr input_, - Branches branches_, - std::unique_ptr otherwise_) + Match( + const type::Type& type_, + std::unique_ptr input_, + Branches branches_, + std::unique_ptr otherwise_ + ) : Expression(Kind::Match, type_), input(std::move(input_)), branches(std::move(branches_)), @@ -31,9 +33,10 @@ class Match : public Expression { bool operator==(const Expression& e) const override; std::vector> possibleOutputs() const override; - + mbgl::Value serialize() const override; std::string getOperator() const override { return "match"; } + private: std::unique_ptr input; Branches branches; diff --git a/include/mbgl/style/expression/number_format.hpp b/include/mbgl/style/expression/number_format.hpp index ed6f2e7df74..5ea9fd3e365 100644 --- a/include/mbgl/style/expression/number_format.hpp +++ b/include/mbgl/style/expression/number_format.hpp @@ -9,11 +9,13 @@ namespace expression { class NumberFormat final : public Expression { public: - NumberFormat(std::unique_ptr number_, - std::unique_ptr locale_, - std::unique_ptr currency_, - std::unique_ptr minFractionDigits_, - std::unique_ptr maxFractionDigits_); + NumberFormat( + std::unique_ptr number_, + std::unique_ptr locale_, + std::unique_ptr currency_, + std::unique_ptr minFractionDigits_, + std::unique_ptr maxFractionDigits_ + ); ~NumberFormat() override; diff --git a/include/mbgl/style/expression/parsing_context.hpp b/include/mbgl/style/expression/parsing_context.hpp index 16ce844acdb..0f420152823 100644 --- a/include/mbgl/style/expression/parsing_context.hpp +++ b/include/mbgl/style/expression/parsing_context.hpp @@ -31,14 +31,13 @@ namespace detail { class Scope { public: - Scope(const std::map>& bindings_, std::shared_ptr parent_ = nullptr) : - bindings(bindings_), - parent(std::move(parent_)) - {} + Scope(const std::map>& bindings_, std::shared_ptr parent_ = nullptr) + : bindings(bindings_), + parent(std::move(parent_)) {} const std::map>& bindings; std::shared_ptr parent; - + std::optional> get(const std::string& name) { auto it = bindings.find(name); if (it != bindings.end()) { @@ -74,14 +73,16 @@ enum class TypeAnnotationOption { class ParsingContext { public: - ParsingContext() : errors(std::make_shared>()) {} - ParsingContext(std::string key_) : key(std::move(key_)), errors(std::make_shared>()) {} + ParsingContext() + : errors(std::make_shared>()) {} + ParsingContext(std::string key_) + : key(std::move(key_)), + errors(std::make_shared>()) {} explicit ParsingContext(type::Type expected_) : expected(std::move(expected_)), - errors(std::make_shared>()) - {} + errors(std::make_shared>()) {} ParsingContext(ParsingContext&&) = default; - + ParsingContext(const ParsingContext&) = delete; ParsingContext& operator=(const ParsingContext&) = delete; @@ -93,8 +94,9 @@ class ParsingContext { /** Parse the given style-spec JSON value as an expression. */ - ParseResult parseExpression(const mbgl::style::conversion::Convertible& value, - const std::optional& = std::nullopt); + ParseResult parseExpression( + const mbgl::style::conversion::Convertible& value, const std::optional& = std::nullopt + ); /** Parse the given style-spec JSON value as an expression intended to be used @@ -106,18 +108,18 @@ class ParsingContext { /** Parse a child expression. For use by individual Expression::parse() methods. */ - ParseResult parse(const mbgl::style::conversion::Convertible&, - std::size_t, - std::optional = std::nullopt, - const std::optional& = std::nullopt); + ParseResult parse( + const mbgl::style::conversion::Convertible&, + std::size_t, + std::optional = std::nullopt, + const std::optional& = std::nullopt + ); /** Parse a child expression. For use by individual Expression::parse() methods. */ - ParseResult parse(const mbgl::style::conversion::Convertible&, - std::size_t index, - std::optional, - const std::map>&); + ParseResult + parse(const mbgl::style::conversion::Convertible&, std::size_t index, std::optional, const std::map>&); /** Check whether `t` is a subtype of `expected`, collecting an error if not. @@ -134,41 +136,42 @@ class ParsingContext { void error(std::string message, std::size_t child) { errors->push_back({std::move(message), key + "[" + util::toString(child) + "]"}); } - + void error(std::string message, std::size_t child, std::size_t grandchild) { errors->push_back( - {std::move(message), key + "[" + util::toString(child) + "][" + util::toString(grandchild) + "]"}); + {std::move(message), key + "[" + util::toString(child) + "][" + util::toString(grandchild) + "]"} + ); } - + void appendErrors(ParsingContext&& ctx) { errors->reserve(errors->size() + ctx.errors->size()); std::move(ctx.errors->begin(), ctx.errors->end(), std::inserter(*errors, errors->end())); ctx.errors->clear(); } - - void clearErrors() { - errors->clear(); - } - + + void clearErrors() { errors->clear(); } + private: - ParsingContext(std::string key_, - std::shared_ptr> errors_, - std::optional expected_, - std::shared_ptr scope_) + ParsingContext( + std::string key_, + std::shared_ptr> errors_, + std::optional expected_, + std::shared_ptr scope_ + ) : key(std::move(key_)), expected(std::move(expected_)), scope(std::move(scope_)), - errors(std::move(errors_)) - {} - - + errors(std::move(errors_)) {} + /** Parse the given style-spec JSON value into an Expression object. Specifically, this function is responsible for determining the expression type (either Literal, or the one named in value[0]) and dispatching to the appropriate ParseXxxx::parse(const V&, ParsingContext) method. */ - ParseResult parse(const mbgl::style::conversion::Convertible& value, const std::optional& = std::nullopt); + ParseResult parse( + const mbgl::style::conversion::Convertible& value, const std::optional& = std::nullopt + ); std::string key; std::optional expected; diff --git a/include/mbgl/style/expression/step.hpp b/include/mbgl/style/expression/step.hpp index 4999ed5d84e..7f565c6326b 100644 --- a/include/mbgl/style/expression/step.hpp +++ b/include/mbgl/style/expression/step.hpp @@ -16,9 +16,11 @@ namespace expression { class Step : public Expression { public: - Step(const type::Type& type_, - std::unique_ptr input_, - std::map> stops_); + Step( + const type::Type& type_, + std::unique_ptr input_, + std::map> stops_ + ); EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; diff --git a/include/mbgl/style/expression/type.hpp b/include/mbgl/style/expression/type.hpp index ddd58dbe57b..155e36f00ac 100644 --- a/include/mbgl/style/expression/type.hpp +++ b/include/mbgl/style/expression/type.hpp @@ -61,13 +61,13 @@ struct ValueType { std::string getName() const { return "value"; } bool operator==(const ValueType&) const { return true; } }; - + struct CollatorType { constexpr CollatorType() = default; std::string getName() const { return "collator"; } bool operator==(const CollatorType&) const { return true; } }; - + struct FormattedType { constexpr FormattedType() = default; std::string getName() const { return "formatted"; } @@ -94,23 +94,29 @@ constexpr ImageType Image; struct Array; -using Type = variant, - CollatorType, - FormattedType, - ErrorType, - ImageType>; +using Type = variant< + NullType, + NumberType, + BooleanType, + StringType, + ColorType, + ObjectType, + ValueType, + mapbox::util::recursive_wrapper, + CollatorType, + FormattedType, + ErrorType, + ImageType>; struct Array { - explicit Array(Type itemType_) : itemType(std::move(itemType_)) {} - Array(Type itemType_, std::size_t N_) : itemType(std::move(itemType_)), N(N_) {} - Array(Type itemType_, std::optional N_) : itemType(std::move(itemType_)), N(std::move(N_)) {} + explicit Array(Type itemType_) + : itemType(std::move(itemType_)) {} + Array(Type itemType_, std::size_t N_) + : itemType(std::move(itemType_)), + N(N_) {} + Array(Type itemType_, std::optional N_) + : itemType(std::move(itemType_)), + N(std::move(N_)) {} std::string getName() const { if (N) { return "array<" + toString(itemType) + ", " + util::toString(*N) + ">"; @@ -122,13 +128,15 @@ struct Array { } bool operator==(const Array& rhs) const { return itemType == rhs.itemType && N == rhs.N; } - + Type itemType; std::optional N; }; - + template -std::string toString(const T& type) { return type.match([&] (const auto& t) { return t.getName(); }); } +std::string toString(const T& type) { + return type.match([&](const auto& t) { return t.getName(); }); +} } // namespace type } // namespace expression diff --git a/include/mbgl/style/expression/value.hpp b/include/mbgl/style/expression/value.hpp index 74af6eedcac..1620d8480ec 100644 --- a/include/mbgl/style/expression/value.hpp +++ b/include/mbgl/style/expression/value.hpp @@ -22,35 +22,33 @@ namespace expression { struct Value; -using ValueBase = variant>, - mapbox::util::recursive_wrapper>>; +using ValueBase = variant< + NullValue, + bool, + double, + std::string, + Color, + Collator, + Formatted, + Image, + mapbox::util::recursive_wrapper>, + mapbox::util::recursive_wrapper>>; struct Value : ValueBase { using ValueBase::ValueBase; - VARIANT_INLINE Value() : ValueBase() {} + VARIANT_INLINE Value() + : ValueBase() {} template - VARIANT_INLINE Value(T&& val) : ValueBase(val) {} + VARIANT_INLINE Value(T&& val) + : ValueBase(val) {} // Javascript's Number.MAX_SAFE_INTEGER static uint64_t maxSafeInteger() { return 9007199254740991ULL; } - + static bool isSafeInteger(uint64_t x) { return x <= maxSafeInteger(); }; - static bool isSafeInteger(int64_t x) { - return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); - } - static bool isSafeInteger(double x) { - return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); - } - + static bool isSafeInteger(int64_t x) { return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); } + static bool isSafeInteger(double x) { return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); } }; constexpr NullValue Null = NullValue(); @@ -74,9 +72,7 @@ type::Type valueTypeToExpressionType(); template struct ValueConverter { - static Value toExpressionValue(const T& value) { - return Value(value); - } + static Value toExpressionValue(const T& value) { return Value(value); } static std::optional fromExpressionValue(const Value& value) { return value.template is() ? value.template get() : std::optional(); @@ -105,18 +101,14 @@ struct ValueConverter { template struct ValueConverter> { - static type::Type expressionType() { - return type::Array(valueTypeToExpressionType(), N); - } + static type::Type expressionType() { return type::Array(valueTypeToExpressionType(), N); } static Value toExpressionValue(const std::array& value); static std::optional> fromExpressionValue(const Value& value); }; template struct ValueConverter> { - static type::Type expressionType() { - return type::Array(valueTypeToExpressionType()); - } + static type::Type expressionType() { return type::Array(valueTypeToExpressionType()); } static Value toExpressionValue(const std::vector& value); static std::optional> fromExpressionValue(const Value& value); }; @@ -129,7 +121,7 @@ struct ValueConverter { }; template -struct ValueConverter >> { +struct ValueConverter>> { static type::Type expressionType() { return type::String; } static Value toExpressionValue(const T& value); static std::optional fromExpressionValue(const Value& value); diff --git a/include/mbgl/style/filter.hpp b/include/mbgl/style/filter.hpp index 2652c01c3f7..bc6e98ff541 100644 --- a/include/mbgl/style/filter.hpp +++ b/include/mbgl/style/filter.hpp @@ -16,17 +16,19 @@ namespace style { class Filter { public: std::optional> expression; + private: std::optional legacyFilter; + public: Filter() = default; Filter(expression::ParseResult _expression, std::optional _filter = std::nullopt) - : expression(std::move(*_expression)), - legacyFilter(std::move(_filter)){ + : expression(std::move(*_expression)), + legacyFilter(std::move(_filter)) { assert(!expression || *expression != nullptr); } - + bool operator()(const expression::EvaluationContext& context) const; operator bool() const { return expression || legacyFilter; } @@ -38,16 +40,13 @@ class Filter { return *(lhs.expression) == *(rhs.expression); } } - - friend bool operator!=(const Filter& lhs, const Filter& rhs) { - return !(lhs == rhs); - } - + + friend bool operator!=(const Filter& lhs, const Filter& rhs) { return !(lhs == rhs); } + mbgl::Value serialize() const { if (legacyFilter) { return *legacyFilter; - } - else if (expression) { + } else if (expression) { return (**expression).serialize(); } return NullValue(); diff --git a/include/mbgl/style/image.hpp b/include/mbgl/style/image.hpp index 2c40d4b7eaa..0b30557707f 100644 --- a/include/mbgl/style/image.hpp +++ b/include/mbgl/style/image.hpp @@ -28,19 +28,23 @@ class ImageContent { class Image { public: - Image(std::string id, - PremultipliedImage&&, - float pixelRatio, - bool sdf, - ImageStretches stretchX = {}, - ImageStretches stretchY = {}, - const std::optional& content = std::nullopt); - Image(std::string id, - PremultipliedImage&& image, - float pixelRatio, - ImageStretches stretchX = {}, - ImageStretches stretchY = {}, - const std::optional& content = std::nullopt) + Image( + std::string id, + PremultipliedImage&&, + float pixelRatio, + bool sdf, + ImageStretches stretchX = {}, + ImageStretches stretchY = {}, + const std::optional& content = std::nullopt + ); + Image( + std::string id, + PremultipliedImage&& image, + float pixelRatio, + ImageStretches stretchX = {}, + ImageStretches stretchY = {}, + const std::optional& content = std::nullopt + ) : Image(std::move(id), std::move(image), pixelRatio, false, std::move(stretchX), std::move(stretchY), content) { } Image(const Image&); @@ -65,7 +69,8 @@ class Image { class Impl; Immutable baseImpl; - explicit Image(Immutable baseImpl_) : baseImpl(std::move(baseImpl_)) {} + explicit Image(Immutable baseImpl_) + : baseImpl(std::move(baseImpl_)) {} }; } // namespace style diff --git a/include/mbgl/style/layer.hpp b/include/mbgl/style/layer.hpp index 233755481ae..b252dbbbac7 100644 --- a/include/mbgl/style/layer.hpp +++ b/include/mbgl/style/layer.hpp @@ -33,37 +33,57 @@ struct LayerTypeInfo { * @brief contains \c Source::Required if the corresponding layer type * requires source. Contains \c Source::NotRequired otherwise. */ - const enum class Source { Required, NotRequired } source; + const enum class Source { + Required, + NotRequired + } source; /** * @brief contains \c Pass3D::Required if the corresponding layer type * requires 3D rendering pass. Contains \c Pass3D::NotRequired otherwise. */ - const enum class Pass3D { Required, NotRequired } pass3d; + const enum class Pass3D { + Required, + NotRequired + } pass3d; /** * @brief contains \c Layout::Required if the corresponding layer type * requires layouting. * contains \c Layout::NotRequired otherwise. */ - const enum class Layout { Required, NotRequired } layout; + const enum class Layout { + Required, + NotRequired + } layout; /** * @brief contains \c FadingTiles::Required if the corresponding layer type * requires rendering on fading tiles. Contains \c FadingTiles::NotRequired otherwise. */ - const enum class FadingTiles { Required, NotRequired } fadingTiles; + const enum class FadingTiles { + Required, + NotRequired + } fadingTiles; /** * @brief contains \c CrossTileIndex::Required if the corresponding layer type * requires cross-tile indexing and placement. Contains \c CrossTileIndex::NotRequired otherwise. */ - const enum class CrossTileIndex { Required, NotRequired } crossTileIndex; + const enum class CrossTileIndex { + Required, + NotRequired + } crossTileIndex; /** * @brief contains the Id of the supported tile type. Used for internal checks. * The contained values correspond to \c Tile::Kind enum. */ - const enum class TileKind : uint8_t { Geometry, Raster, RasterDEM, NotRequired } tileKind; + const enum class TileKind : uint8_t { + Geometry, + Raster, + RasterDEM, + NotRequired + } tileKind; }; /** @@ -84,7 +104,7 @@ struct LayerTypeInfo { */ class Layer { public: - Layer(const Layer& ) = delete; + Layer(const Layer&) = delete; Layer& operator=(const Layer&) = delete; virtual ~Layer(); @@ -126,7 +146,6 @@ class Layer { // Create a layer, copying all properties except id and paint properties from this layer. virtual std::unique_ptr cloneRef(const std::string& id) const = 0; - void setObserver(LayerObserver*); // For use in SDK bindings, which store a reference to a platform-native peer @@ -137,17 +156,16 @@ class Layer { const LayerTypeInfo* getTypeInfo() const noexcept; - mapbox::base::WeakPtr makeWeakPtr() { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() { return weakFactory.makeWeakPtr(); } protected: virtual Mutable mutableBaseImpl() const = 0; void serializeProperty(Value&, const StyleProperty&, const char* propertyName, bool isPaint) const; - virtual std::optional setPropertyInternal(const std::string& name, - const conversion::Convertible& value) = 0; + virtual std::optional setPropertyInternal( + const std::string& name, const conversion::Convertible& value + ) = 0; LayerObserver* observer; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; private: std::optional setVisibility(const conversion::Convertible& value); diff --git a/include/mbgl/style/layer_properties.hpp b/include/mbgl/style/layer_properties.hpp index de0a0a4e16a..f8dd149f589 100644 --- a/include/mbgl/style/layer_properties.hpp +++ b/include/mbgl/style/layer_properties.hpp @@ -7,8 +7,8 @@ namespace style { /** * @brief An interface, wrapping evaluated layer properties. - * - * It is an abstract base class; concrete derived classes that hold the actual data are provided for each layer type. + * + * It is an abstract base class; concrete derived classes that hold the actual data are provided for each layer type. */ class LayerProperties { public: @@ -20,7 +20,8 @@ class LayerProperties { uint8_t renderPasses = 0u; protected: - LayerProperties(Immutable impl) : baseImpl(std::move(impl)) {} + LayerProperties(Immutable impl) + : baseImpl(std::move(impl)) {} }; template diff --git a/include/mbgl/style/position.hpp b/include/mbgl/style/position.hpp index 43b54cb69d5..2cc59a7a85c 100644 --- a/include/mbgl/style/position.hpp +++ b/include/mbgl/style/position.hpp @@ -11,18 +11,19 @@ class Position { public: Position() = default; Position(std::array& position_) - : radial(position_[0]), azimuthal(position_[1]), polar(position_[2]) { + : radial(position_[0]), + azimuthal(position_[1]), + polar(position_[2]) { calculateCartesian(); }; friend bool operator==(const Position& lhs, const Position& rhs) { return lhs.radial == rhs.radial && lhs.azimuthal == rhs.azimuthal && lhs.polar == rhs.polar; - // TODO this doesn't address wrapping, which would be better addressed by comparing cartesian coordinates but being calculated floats are ont to be trusted. + // TODO this doesn't address wrapping, which would be better addressed by comparing cartesian coordinates but + // being calculated floats are ont to be trusted. } - friend bool operator!=(const Position& lhs, const Position& rhs) { - return !(lhs == rhs); - } + friend bool operator!=(const Position& lhs, const Position& rhs) { return !(lhs == rhs); } std::array getCartesian() const { return {{x, y, z}}; }; diff --git a/include/mbgl/style/property_expression.hpp b/include/mbgl/style/property_expression.hpp index 477e7122482..eed27974559 100644 --- a/include/mbgl/style/property_expression.hpp +++ b/include/mbgl/style/property_expression.hpp @@ -42,10 +42,11 @@ template class PropertyExpression final : public PropertyExpressionBase { public: // Second parameter to be used only for conversions from legacy functions. - PropertyExpression(std::unique_ptr expression_, std::optional defaultValue_ = std::nullopt) + PropertyExpression( + std::unique_ptr expression_, std::optional defaultValue_ = std::nullopt + ) : PropertyExpressionBase(std::move(expression_)), - defaultValue(std::move(defaultValue_)) { - } + defaultValue(std::move(defaultValue_)) {} T evaluate(const expression::EvaluationContext& context, T finalDefaultValue = T()) const { const expression::EvaluationResult result = expression->evaluate(context); @@ -68,56 +69,66 @@ class PropertyExpression final : public PropertyExpressionBase { return evaluate(expression::EvaluationContext(&feature), finalDefaultValue); } - T evaluate(const GeometryTileFeature& feature, - const std::set& availableImages, - T finalDefaultValue) const { - return evaluate(expression::EvaluationContext(&feature).withAvailableImages(&availableImages), - finalDefaultValue); + T evaluate(const GeometryTileFeature& feature, const std::set& availableImages, T finalDefaultValue) + const { + return evaluate( + expression::EvaluationContext(&feature).withAvailableImages(&availableImages), finalDefaultValue + ); } T evaluate(const GeometryTileFeature& feature, const CanonicalTileID& canonical, T finalDefaultValue) const { return evaluate(expression::EvaluationContext(&feature).withCanonicalTileID(&canonical), finalDefaultValue); } - T evaluate(const GeometryTileFeature& feature, - const std::set& availableImages, - const CanonicalTileID& canonical, - T finalDefaultValue) const { - return evaluate(expression::EvaluationContext(&feature) - .withAvailableImages(&availableImages) - .withCanonicalTileID(&canonical), - finalDefaultValue); + T evaluate( + const GeometryTileFeature& feature, + const std::set& availableImages, + const CanonicalTileID& canonical, + T finalDefaultValue + ) const { + return evaluate( + expression::EvaluationContext(&feature) + .withAvailableImages(&availableImages) + .withCanonicalTileID(&canonical), + finalDefaultValue + ); } T evaluate(float zoom, const GeometryTileFeature& feature, T finalDefaultValue) const { return evaluate(expression::EvaluationContext(zoom, &feature), finalDefaultValue); } - T evaluate(float zoom, - const GeometryTileFeature& feature, - const std::set& availableImages, - T finalDefaultValue) const { - return evaluate(expression::EvaluationContext(zoom, &feature).withAvailableImages(&availableImages), - finalDefaultValue); + T evaluate( + float zoom, + const GeometryTileFeature& feature, + const std::set& availableImages, + T finalDefaultValue + ) const { + return evaluate( + expression::EvaluationContext(zoom, &feature).withAvailableImages(&availableImages), finalDefaultValue + ); } - T evaluate(float zoom, - const GeometryTileFeature& feature, - const std::set& availableImages, - const CanonicalTileID& canonical, - T finalDefaultValue) const { - return evaluate(expression::EvaluationContext(zoom, &feature) - .withAvailableImages(&availableImages) - .withCanonicalTileID(&canonical), - finalDefaultValue); + T evaluate( + float zoom, + const GeometryTileFeature& feature, + const std::set& availableImages, + const CanonicalTileID& canonical, + T finalDefaultValue + ) const { + return evaluate( + expression::EvaluationContext(zoom, &feature) + .withAvailableImages(&availableImages) + .withCanonicalTileID(&canonical), + finalDefaultValue + ); } - T evaluate(float zoom, - const GeometryTileFeature& feature, - const CanonicalTileID& canonical, - T finalDefaultValue) const { - return evaluate(expression::EvaluationContext(zoom, &feature).withCanonicalTileID(&canonical), - finalDefaultValue); + T evaluate(float zoom, const GeometryTileFeature& feature, const CanonicalTileID& canonical, T finalDefaultValue) + const { + return evaluate( + expression::EvaluationContext(zoom, &feature).withCanonicalTileID(&canonical), finalDefaultValue + ); } T evaluate(float zoom, const GeometryTileFeature& feature, const FeatureState& state, T finalDefaultValue) const { @@ -129,8 +140,7 @@ class PropertyExpression final : public PropertyExpressionBase { return expression::fromExpressionValues(expression->possibleOutputs()); } - friend bool operator==(const PropertyExpression& lhs, - const PropertyExpression& rhs) { + friend bool operator==(const PropertyExpression& lhs, const PropertyExpression& rhs) { return *lhs.expression == *rhs.expression; } diff --git a/include/mbgl/style/property_value.hpp b/include/mbgl/style/property_value.hpp index 86812e23013..37963036881 100644 --- a/include/mbgl/style/property_value.hpp +++ b/include/mbgl/style/property_value.hpp @@ -10,22 +10,13 @@ namespace style { template class PropertyValue { private: - using Value = variant< - Undefined, - T, - PropertyExpression>; + using Value = variant>; Value value; - friend bool operator==(const PropertyValue& lhs, - const PropertyValue& rhs) { - return lhs.value == rhs.value; - } + friend bool operator==(const PropertyValue& lhs, const PropertyValue& rhs) { return lhs.value == rhs.value; } - friend bool operator!=(const PropertyValue& lhs, - const PropertyValue& rhs) { - return !(lhs == rhs); - } + friend bool operator!=(const PropertyValue& lhs, const PropertyValue& rhs) { return !(lhs == rhs); } public: PropertyValue() = default; @@ -36,41 +27,31 @@ class PropertyValue { PropertyValue(PropertyExpression expression) : value(std::move(expression)) {} - bool isUndefined() const { - return value.template is(); - } + bool isUndefined() const { return value.template is(); } - bool isConstant() const { - return value.template is(); - } + bool isConstant() const { return value.template is(); } - bool isExpression() const { - return value.template is>(); - } + bool isExpression() const { return value.template is>(); } bool isDataDriven() const { return value.match( - [] (const Undefined&) { return false; }, - [] (const T&) { return false; }, - [] (const PropertyExpression& fn) { return !fn.isFeatureConstant(); } + [](const Undefined&) { return false; }, + [](const T&) { return false; }, + [](const PropertyExpression& fn) { return !fn.isFeatureConstant(); } ); } bool isZoomConstant() const { return value.match( - [] (const Undefined&) { return true; }, - [] (const T&) { return true; }, - [] (const PropertyExpression& fn) { return fn.isZoomConstant(); } + [](const Undefined&) { return true; }, + [](const T&) { return true; }, + [](const PropertyExpression& fn) { return fn.isZoomConstant(); } ); } - const T& asConstant() const { - return value.template get(); - } + const T& asConstant() const { return value.template get(); } - const PropertyExpression& asExpression() const { - return value.template get>(); - } + const PropertyExpression& asExpression() const { return value.template get>(); } template auto match(Ts&&... ts) const { diff --git a/include/mbgl/style/rotation.hpp b/include/mbgl/style/rotation.hpp index 96b047c68ce..d17d89243d8 100644 --- a/include/mbgl/style/rotation.hpp +++ b/include/mbgl/style/rotation.hpp @@ -9,7 +9,8 @@ namespace style { class Rotation { public: Rotation() = default; - Rotation(double angle_) : angle(mbgl::util::wrap(angle_, 0, period())) {} + Rotation(double angle_) + : angle(mbgl::util::wrap(angle_, 0, period())) {} constexpr double period() const noexcept { return 360.0; } double getAngle() const noexcept { return angle; } diff --git a/include/mbgl/style/sources/custom_geometry_source.hpp b/include/mbgl/style/sources/custom_geometry_source.hpp index 90c9d2dfe08..172bf300a7d 100644 --- a/include/mbgl/style/sources/custom_geometry_source.hpp +++ b/include/mbgl/style/sources/custom_geometry_source.hpp @@ -33,9 +33,10 @@ class CustomGeometrySource final : public Source { struct Options { TileFunction fetchTileFunction; TileFunction cancelTileFunction; - Range zoomRange = { 0, 18}; + Range zoomRange = {0, 18}; TileOptions tileOptions; }; + public: CustomGeometrySource(std::string id, const CustomGeometrySource::Options& options); ~CustomGeometrySource() final; @@ -47,9 +48,7 @@ class CustomGeometrySource final : public Source { class Impl; const Impl& impl() const; bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -57,7 +56,7 @@ class CustomGeometrySource final : public Source { private: std::shared_ptr threadPool; std::unique_ptr> loader; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; }; template <> diff --git a/include/mbgl/style/sources/geojson_source.hpp b/include/mbgl/style/sources/geojson_source.hpp index accb5444935..2ef0a3ad560 100644 --- a/include/mbgl/style/sources/geojson_source.hpp +++ b/include/mbgl/style/sources/geojson_source.hpp @@ -29,8 +29,9 @@ struct GeoJSONOptions { bool cluster = false; uint16_t clusterRadius = 50; uint8_t clusterMaxZoom = 17; - using ClusterExpression = std::pair, - std::shared_ptr>; + using ClusterExpression = std::pair< + std::shared_ptr, + std::shared_ptr>; using ClusterProperties = std::map; ClusterProperties clusterProperties; @@ -40,9 +41,11 @@ class GeoJSONData { public: using TileFeatures = mapbox::feature::feature_collection; using Features = mapbox::feature::feature_collection; - static std::shared_ptr create(const GeoJSON&, - const Immutable& = GeoJSONOptions::defaultOptions(), - std::shared_ptr scheduler = nullptr); + static std::shared_ptr create( + const GeoJSON&, + const Immutable& = GeoJSONOptions::defaultOptions(), + std::shared_ptr scheduler = nullptr + ); virtual ~GeoJSONData() = default; virtual void getTile(const CanonicalTileID&, const std::function&) = 0; @@ -74,9 +77,7 @@ class GeoJSONSource final : public Source { bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -85,7 +86,7 @@ class GeoJSONSource final : public Source { std::optional url; std::unique_ptr req; std::shared_ptr threadPool; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; }; template <> diff --git a/include/mbgl/style/sources/image_source.hpp b/include/mbgl/style/sources/image_source.hpp index aae904a4a38..61429c6ee89 100644 --- a/include/mbgl/style/sources/image_source.hpp +++ b/include/mbgl/style/sources/image_source.hpp @@ -31,9 +31,7 @@ class ImageSource final : public Source { bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -41,7 +39,7 @@ class ImageSource final : public Source { private: std::optional url; std::unique_ptr req; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; }; template <> diff --git a/include/mbgl/style/sources/raster_source.hpp b/include/mbgl/style/sources/raster_source.hpp index 486cf7e0bab..81882c457a3 100644 --- a/include/mbgl/style/sources/raster_source.hpp +++ b/include/mbgl/style/sources/raster_source.hpp @@ -12,7 +12,12 @@ namespace style { class RasterSource : public Source { public: - RasterSource(std::string id, variant urlOrTileset, uint16_t tileSize, SourceType sourceType = SourceType::Raster); + RasterSource( + std::string id, + variant urlOrTileset, + uint16_t tileSize, + SourceType sourceType = SourceType::Raster + ); ~RasterSource() override; const variant& getURLOrTileset() const; @@ -27,9 +32,7 @@ class RasterSource : public Source { bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() final { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() final { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -37,7 +40,7 @@ class RasterSource : public Source { private: const variant urlOrTileset; std::unique_ptr req; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; }; template <> diff --git a/include/mbgl/style/sources/vector_source.hpp b/include/mbgl/style/sources/vector_source.hpp index 55cdd8de2d7..502a25834e4 100644 --- a/include/mbgl/style/sources/vector_source.hpp +++ b/include/mbgl/style/sources/vector_source.hpp @@ -12,8 +12,12 @@ namespace style { class VectorSource final : public Source { public: - VectorSource(std::string id, variant urlOrTileset, std::optional maxZoom = std::nullopt, - std::optional minZoom = std::nullopt); + VectorSource( + std::string id, + variant urlOrTileset, + std::optional maxZoom = std::nullopt, + std::optional minZoom = std::nullopt + ); ~VectorSource() final; const variant& getURLOrTileset() const; @@ -26,9 +30,7 @@ class VectorSource final : public Source { bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -36,7 +38,7 @@ class VectorSource final : public Source { private: const variant urlOrTileset; std::unique_ptr req; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; std::optional maxZoom; std::optional minZoom; }; diff --git a/include/mbgl/style/style.hpp b/include/mbgl/style/style.hpp index 3d987deb901..8d7faab5dc4 100644 --- a/include/mbgl/style/style.hpp +++ b/include/mbgl/style/style.hpp @@ -40,7 +40,7 @@ class Style { void setTransitionOptions(const TransitionOptions&); // Light - Light* getLight(); + Light* getLight(); const Light* getLight() const; void setLight(std::unique_ptr); @@ -51,20 +51,20 @@ class Style { void removeImage(const std::string&); // Sources - std::vector< Source*> getSources(); + std::vector getSources(); std::vector getSources() const; - Source* getSource(const std::string&); + Source* getSource(const std::string&); const Source* getSource(const std::string&) const; void addSource(std::unique_ptr); std::unique_ptr removeSource(const std::string& sourceID); // Layers - std::vector< Layer*> getLayers(); + std::vector getLayers(); std::vector getLayers() const; - Layer* getLayer(const std::string&); + Layer* getLayer(const std::string&); const Layer* getLayer(const std::string&) const; void addLayer(std::unique_ptr, const std::optional& beforeLayerID = std::nullopt); diff --git a/include/mbgl/style/style_property.hpp b/include/mbgl/style/style_property.hpp index fc34078decf..d17d99aca2f 100644 --- a/include/mbgl/style/style_property.hpp +++ b/include/mbgl/style/style_property.hpp @@ -10,8 +10,15 @@ namespace style { */ class StyleProperty { public: - enum class Kind : uint8_t { Undefined, Constant, Expression, Transition }; - StyleProperty(Value value_, Kind kind_) : value(std::move(value_)), kind(kind_) {} + enum class Kind : uint8_t { + Undefined, + Constant, + Expression, + Transition + }; + StyleProperty(Value value_, Kind kind_) + : value(std::move(value_)), + kind(kind_) {} StyleProperty() = default; const Value& getValue() const { return value; } Value& getValue() { return value; } diff --git a/include/mbgl/style/transition_options.hpp b/include/mbgl/style/transition_options.hpp index c5e51267cf7..5382dee4b07 100644 --- a/include/mbgl/style/transition_options.hpp +++ b/include/mbgl/style/transition_options.hpp @@ -15,24 +15,20 @@ class TransitionOptions { std::optional delay; bool enablePlacementTransitions; - TransitionOptions(std::optional duration_ = std::nullopt, - std::optional delay_ = std::nullopt, - bool enablePlacementTransitions_ = true) + TransitionOptions( + std::optional duration_ = std::nullopt, + std::optional delay_ = std::nullopt, + bool enablePlacementTransitions_ = true + ) : duration(std::move(duration_)), delay(std::move(delay_)), enablePlacementTransitions(enablePlacementTransitions_) {} TransitionOptions reverseMerge(const TransitionOptions& defaults) const { - return { - duration ? duration : defaults.duration, - delay ? delay : defaults.delay, - enablePlacementTransitions - }; + return {duration ? duration : defaults.duration, delay ? delay : defaults.delay, enablePlacementTransitions}; } - bool isDefined() const { - return duration || delay; - } + bool isDefined() const { return duration || delay; } mapbox::base::Value serialize() const { mapbox::base::ValueObject result; diff --git a/include/mbgl/style/types.hpp b/include/mbgl/style/types.hpp index 5d88dafb331..3d5780935a8 100644 --- a/include/mbgl/style/types.hpp +++ b/include/mbgl/style/types.hpp @@ -68,7 +68,7 @@ enum class SymbolPlacementType : uint8_t { Line, LineCenter }; - + enum class SymbolZOrderType : uint8_t { Auto, ViewportY, @@ -120,7 +120,7 @@ enum class TextWritingModeType : uint8_t { Vertical }; -enum class LightAnchorType: bool { +enum class LightAnchorType : bool { Map, Viewport }; diff --git a/include/mbgl/style/undefined.hpp b/include/mbgl/style/undefined.hpp index e43f132a80e..b88f42f99f1 100644 --- a/include/mbgl/style/undefined.hpp +++ b/include/mbgl/style/undefined.hpp @@ -5,8 +5,12 @@ namespace style { class Undefined {}; -inline bool operator==(const Undefined&, const Undefined&) { return true; } -inline bool operator!=(const Undefined&, const Undefined&) { return false; } +inline bool operator==(const Undefined&, const Undefined&) { + return true; +} +inline bool operator!=(const Undefined&, const Undefined&) { + return false; +} } // namespace style } // namespace mbgl diff --git a/include/mbgl/tile/tile_id.hpp b/include/mbgl/tile/tile_id.hpp index e7e0ad567bc..42c0c3a77d1 100644 --- a/include/mbgl/tile/tile_id.hpp +++ b/include/mbgl/tile/tile_id.hpp @@ -97,7 +97,10 @@ namespace util { std::string toString(const UnwrappedTileID&); } // namespace util -inline CanonicalTileID::CanonicalTileID(uint8_t z_, uint32_t x_, uint32_t y_) : z(z_), x(x_), y(y_) { +inline CanonicalTileID::CanonicalTileID(uint8_t z_, uint32_t x_, uint32_t y_) + : z(z_), + x(x_), + y(y_) { assert(z <= 32); assert(x < (1ull << z)); assert(y < (1ull << z)); @@ -117,15 +120,14 @@ inline bool CanonicalTileID::operator<(const CanonicalTileID& rhs) const { inline bool CanonicalTileID::isChildOf(const CanonicalTileID& parent) const { // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined. - return parent.z == 0 || - (parent.z < z && parent.x == (x >> (z - parent.z)) && parent.y == (y >> (z - parent.z))); + return parent.z == 0 || (parent.z < z && parent.x == (x >> (z - parent.z)) && parent.y == (y >> (z - parent.z))); } inline CanonicalTileID CanonicalTileID::scaledTo(uint8_t targetZ) const { if (targetZ <= z) { - return { targetZ, x >> (z - targetZ), y >> (z - targetZ) }; // parent or same + return {targetZ, x >> (z - targetZ), y >> (z - targetZ)}; // parent or same } else { - return { targetZ, x << (targetZ - z), y << (targetZ - z) }; // child + return {targetZ, x << (targetZ - z), y << (targetZ - z)}; // child } } @@ -133,40 +135,49 @@ inline std::array CanonicalTileID::children() const { const uint8_t childZ = z + 1; const uint32_t childX = x * 2; const uint32_t childY = y * 2; - return { { - { childZ, childX, childY }, - { childZ, childX, childY + 1 }, - { childZ, childX + 1, childY }, - { childZ, childX + 1, childY + 1 }, - } }; + return {{ + {childZ, childX, childY}, + {childZ, childX, childY + 1}, + {childZ, childX + 1, childY}, + {childZ, childX + 1, childY + 1}, + }}; } inline OverscaledTileID::OverscaledTileID(uint8_t overscaledZ_, int16_t wrap_, CanonicalTileID canonical_) - : overscaledZ(overscaledZ_), wrap(wrap_), canonical(canonical_) { + : overscaledZ(overscaledZ_), + wrap(wrap_), + canonical(canonical_) { assert(overscaledZ >= canonical.z); } inline OverscaledTileID::OverscaledTileID(uint8_t overscaledZ_, int16_t wrap_, uint8_t z, uint32_t x, uint32_t y) - : overscaledZ(overscaledZ_), wrap(wrap_), canonical(z, x, y) { + : overscaledZ(overscaledZ_), + wrap(wrap_), + canonical(z, x, y) { assert(overscaledZ >= canonical.z); } inline OverscaledTileID::OverscaledTileID(uint8_t z, uint32_t x, uint32_t y) - : overscaledZ(z), wrap(0), canonical(z, x, y) { -} + : overscaledZ(z), + wrap(0), + canonical(z, x, y) {} inline OverscaledTileID::OverscaledTileID(const CanonicalTileID& canonical_) - : overscaledZ(canonical_.z), wrap(0), canonical(canonical_) { + : overscaledZ(canonical_.z), + wrap(0), + canonical(canonical_) { assert(overscaledZ >= canonical.z); } inline OverscaledTileID::OverscaledTileID(CanonicalTileID&& canonical_) - : overscaledZ(canonical_.z), wrap(0), canonical(std::forward(canonical_)) { + : overscaledZ(canonical_.z), + wrap(0), + canonical(std::forward(canonical_)) { assert(overscaledZ >= canonical.z); } inline bool OverscaledTileID::operator==(const OverscaledTileID& rhs) const { - return overscaledZ == rhs.overscaledZ && wrap == rhs.wrap &&canonical == rhs.canonical; + return overscaledZ == rhs.overscaledZ && wrap == rhs.wrap && canonical == rhs.canonical; } inline bool OverscaledTileID::operator!=(const OverscaledTileID& rhs) const { @@ -182,21 +193,20 @@ inline uint32_t OverscaledTileID::overscaleFactor() const { } inline bool OverscaledTileID::isChildOf(const OverscaledTileID& rhs) const { - return wrap == rhs.wrap && - overscaledZ > rhs.overscaledZ && + return wrap == rhs.wrap && overscaledZ > rhs.overscaledZ && (canonical == rhs.canonical || canonical.isChildOf(rhs.canonical)); } inline OverscaledTileID OverscaledTileID::scaledTo(uint8_t z) const { - return { z, wrap, z >= canonical.z ? canonical : canonical.scaledTo(z) }; + return {z, wrap, z >= canonical.z ? canonical : canonical.scaledTo(z)}; } inline UnwrappedTileID OverscaledTileID::toUnwrapped() const { - return { wrap, canonical }; + return {wrap, canonical}; } inline OverscaledTileID OverscaledTileID::unwrapTo(int16_t newWrap) const { - return { overscaledZ, newWrap, canonical }; + return {overscaledZ, newWrap, canonical}; } inline UnwrappedTileID::UnwrappedTileID(uint8_t z_, int64_t x_, int64_t y_) @@ -204,11 +214,12 @@ inline UnwrappedTileID::UnwrappedTileID(uint8_t z_, int64_t x_, int64_t y_) canonical( z_, static_cast(x_ - wrap * (1ll << z_)), - y_ < 0 ? 0 : std::min(static_cast(y_), static_cast(1ull << z_) - 1)) { -} + y_ < 0 ? 0 : std::min(static_cast(y_), static_cast(1ull << z_) - 1) + ) {} inline UnwrappedTileID::UnwrappedTileID(int16_t wrap_, CanonicalTileID canonical_) - : wrap(wrap_), canonical(canonical_) {} + : wrap(wrap_), + canonical(canonical_) {} inline bool UnwrappedTileID::operator==(const UnwrappedTileID& rhs) const { return wrap == rhs.wrap && canonical == rhs.canonical; @@ -223,7 +234,7 @@ inline bool UnwrappedTileID::operator<(const UnwrappedTileID& rhs) const { } inline UnwrappedTileID UnwrappedTileID::unwrapTo(int16_t newWrap) const { - return { newWrap, canonical }; + return {newWrap, canonical}; } inline bool UnwrappedTileID::isChildOf(const UnwrappedTileID& parent) const { @@ -234,21 +245,22 @@ inline std::array UnwrappedTileID::children() const { const uint8_t childZ = canonical.z + 1; const uint32_t childX = canonical.x * 2; const uint32_t childY = canonical.y * 2; - return { { - { wrap, { childZ, childX, childY } }, - { wrap, { childZ, childX, childY + 1 } }, - { wrap, { childZ, childX + 1, childY } }, - { wrap, { childZ, childX + 1, childY + 1 } }, - } }; + return {{ + {wrap, {childZ, childX, childY}}, + {wrap, {childZ, childX, childY + 1}}, + {wrap, {childZ, childX + 1, childY}}, + {wrap, {childZ, childX + 1, childY + 1}}, + }}; } inline OverscaledTileID UnwrappedTileID::overscaleTo(const uint8_t overscaledZ) const { assert(overscaledZ >= canonical.z); - return { overscaledZ, wrap, canonical }; + return {overscaledZ, wrap, canonical}; } inline float UnwrappedTileID::pixelsToTileUnits(const float pixelValue, const float zoom) const { - return pixelValue * (static_cast(util::EXTENT) / (static_cast(util::tileSize_D) * std::pow(2.f, zoom - canonical.z))); + return pixelValue * (static_cast(util::EXTENT) / + (static_cast(util::tileSize_D) * std::pow(2.f, zoom - canonical.z))); } } // namespace mbgl @@ -271,4 +283,3 @@ struct hash { }; } // namespace std - diff --git a/include/mbgl/util/bitmask_operations.hpp b/include/mbgl/util/bitmask_operations.hpp index 014fabdea25..b22eb58c2f0 100644 --- a/include/mbgl/util/bitmask_operations.hpp +++ b/include/mbgl/util/bitmask_operations.hpp @@ -5,29 +5,28 @@ namespace mbgl { -template +template MBGL_CONSTEXPR Enum operator|(Enum a, Enum b) { static_assert(std::is_enum::value, "Enum must be an enum type"); return Enum(mbgl::underlying_type(a) | mbgl::underlying_type(b)); } -template +template MBGL_CONSTEXPR Enum& operator|=(Enum& a, Enum b) { static_assert(std::is_enum::value, "Enum must be an enum type"); return (a = a | b); } -template +template MBGL_CONSTEXPR bool operator&(Enum a, Enum b) { static_assert(std::is_enum::value, "Enum must be an enum type"); return bool(mbgl::underlying_type(a) & mbgl::underlying_type(b)); } -template +template MBGL_CONSTEXPR Enum operator~(Enum value) { static_assert(std::is_enum::value, "Enum must be an enum type"); return Enum(~mbgl::underlying_type(value)); } - } // namespace mbgl \ No newline at end of file diff --git a/include/mbgl/util/char_array_buffer.hpp b/include/mbgl/util/char_array_buffer.hpp index 80eeb2db625..0e84062fe6c 100644 --- a/include/mbgl/util/char_array_buffer.hpp +++ b/include/mbgl/util/char_array_buffer.hpp @@ -7,11 +7,12 @@ namespace util { // ref https://artofcode.wordpress.com/2010/12/12/deriving-from-stdstreambuf/ -class CharArrayBuffer : public std::streambuf -{ +class CharArrayBuffer : public std::streambuf { public: CharArrayBuffer(char const* data, std::size_t size) - : begin_(data), end_(data + size), current_(data) {} + : begin_(data), + end_(data + size), + current_(data) {} private: int_type underflow() final { @@ -35,20 +36,21 @@ class CharArrayBuffer : public std::streambuf return traits_type::to_int_type(*--current_); } - std::streamsize showmanyc() final { - return end_ - current_; - } + std::streamsize showmanyc() final { return end_ - current_; } pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode) final { - if (dir == std::ios_base::beg) current_ = std::min(begin_ + off, end_); - else if (dir == std::ios_base::cur) current_ = std::min(current_ + off, end_); - else current_ = std::max(end_ - off, begin_); // dir == std::ios_base::end + if (dir == std::ios_base::beg) + current_ = std::min(begin_ + off, end_); + else if (dir == std::ios_base::cur) + current_ = std::min(current_ + off, end_); + else + current_ = std::max(end_ - off, begin_); // dir == std::ios_base::end return {off_type(current_ - begin_)}; } - char const * const begin_; - char const * const end_; - char const * current_; + char const* const begin_; + char const* const end_; + char const* current_; }; } // namespace util diff --git a/include/mbgl/util/chrono.hpp b/include/mbgl/util/chrono.hpp index 0f2b85b256e..bf9692fb488 100644 --- a/include/mbgl/util/chrono.hpp +++ b/include/mbgl/util/chrono.hpp @@ -15,7 +15,7 @@ using Seconds = std::chrono::seconds; using Milliseconds = std::chrono::milliseconds; using TimePoint = Clock::time_point; -using Duration = Clock::duration; +using Duration = Clock::duration; // Used to measure second-precision times, such as times gathered from HTTP responses. using Timestamp = std::chrono::time_point; @@ -39,16 +39,18 @@ Timestamp parseTimestamp(int32_t timestamp); // C++17 polyfill #if defined(_MSC_VER) && !defined(__clang__) template ::is_signed, int> = 0> -_NODISCARD constexpr std::chrono::duration<_Rep, _Period> abs(const std::chrono::duration<_Rep, _Period> _Dur) noexcept( - std::is_arithmetic_v<_Rep>) /* strengthened */ { +_NODISCARD constexpr std::chrono::duration<_Rep, _Period> abs(const std::chrono::duration<_Rep, _Period> _Dur +) noexcept(std::is_arithmetic_v<_Rep>) /* strengthened */ { // create a duration with count() the absolute value of _Dur.count() - return _Dur < std::chrono::duration<_Rep, _Period>::zero() ? std::chrono::duration<_Rep, _Period>::zero() - _Dur : _Dur; + return _Dur < std::chrono::duration<_Rep, _Period>::zero() ? std::chrono::duration<_Rep, _Period>::zero() - _Dur + : _Dur; } #else -template ::min() < std::chrono::duration::zero()>> -constexpr std::chrono::duration abs(std::chrono::duration d) -{ +template < + class Rep, + class Period, + class = std::enable_if_t::min() < std::chrono::duration::zero()>> +constexpr std::chrono::duration abs(std::chrono::duration d) { return d >= d.zero() ? d : -d; } #endif diff --git a/include/mbgl/util/color.hpp b/include/mbgl/util/color.hpp index c8c48bb16e3..f60c9f4cb72 100644 --- a/include/mbgl/util/color.hpp +++ b/include/mbgl/util/color.hpp @@ -14,7 +14,10 @@ class Color { public: Color() = default; Color(float r_, float g_, float b_, float a_) - : r(r_), g(g_), b(b_), a(a_) { + : r(r_), + g(g_), + b(b_), + a(a_) { assert(r_ >= 0.0f); assert(r_ <= 1.0f); assert(g_ >= 0.0f); @@ -30,12 +33,12 @@ class Color { float b = 0.0f; float a = 0.0f; - static Color black() { return { 0.0f, 0.0f, 0.0f, 1.0f }; }; - static Color white() { return { 1.0f, 1.0f, 1.0f, 1.0f }; }; + static Color black() { return {0.0f, 0.0f, 0.0f, 1.0f}; }; + static Color white() { return {1.0f, 1.0f, 1.0f, 1.0f}; }; - static Color red() { return { 1.0f, 0.0f, 0.0f, 1.0f }; }; - static Color green() { return { 0.0f, 1.0f, 0.0f, 1.0f }; }; - static Color blue() { return { 0.0f, 0.0f, 1.0f, 1.0f }; }; + static Color red() { return {1.0f, 0.0f, 0.0f, 1.0f}; }; + static Color green() { return {0.0f, 1.0f, 0.0f, 1.0f}; }; + static Color blue() { return {0.0f, 0.0f, 1.0f, 1.0f}; }; static std::optional parse(const std::string&); std::string stringify() const; @@ -55,12 +58,7 @@ inline bool operator!=(const Color& colorA, const Color& colorB) { inline Color operator*(const Color& color, float alpha) { assert(alpha >= 0.0f); assert(alpha <= 1.0f); - return { - color.r * alpha, - color.g * alpha, - color.b * alpha, - color.a * alpha - }; + return {color.r * alpha, color.g * alpha, color.b * alpha, color.a * alpha}; } } // namespace mbgl diff --git a/include/mbgl/util/compression.hpp b/include/mbgl/util/compression.hpp index efe87ff2eae..b07cadd6561 100644 --- a/include/mbgl/util/compression.hpp +++ b/include/mbgl/util/compression.hpp @@ -5,7 +5,12 @@ namespace mbgl { namespace util { -enum CompressionFormat { ZLIB = 15, GZIP = 15 + 16, DEFLATE = -15, DETECT = 15 + 32 }; +enum CompressionFormat { + ZLIB = 15, + GZIP = 15 + 16, + DEFLATE = -15, + DETECT = 15 + 32 +}; std::string compress(const std::string& raw, int windowBits = CompressionFormat::ZLIB); std::string decompress(const std::string& raw, int windowBits = CompressionFormat::DETECT); diff --git a/include/mbgl/util/constants.hpp b/include/mbgl/util/constants.hpp index 8b05fad81c7..f79476f7cd4 100644 --- a/include/mbgl/util/constants.hpp +++ b/include/mbgl/util/constants.hpp @@ -35,8 +35,8 @@ constexpr double PITCH_MIN = 0.0; constexpr double PITCH_MAX = M_PI / 3; constexpr double MIN_ZOOM = 0.0; constexpr double MAX_ZOOM = 25.5; -constexpr float MIN_ZOOM_F = MIN_ZOOM; -constexpr float MAX_ZOOM_F = MAX_ZOOM; +constexpr float MIN_ZOOM_F = MIN_ZOOM; +constexpr float MAX_ZOOM_F = MAX_ZOOM; constexpr uint8_t DEFAULT_MAX_ZOOM = 22; // ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout. @@ -51,9 +51,9 @@ constexpr uint64_t DEFAULT_MAX_CACHE_SIZE = 50 * 1024 * 1024; constexpr std::size_t DEFAULT_ON_DEMAND_IMAGES_CACHE_SIZE = 100 * 8192; constexpr Duration DEFAULT_TRANSITION_DURATION = Milliseconds(300); -constexpr Seconds CLOCK_SKEW_RETRY_TIMEOUT { 30 }; +constexpr Seconds CLOCK_SKEW_RETRY_TIMEOUT{30}; -constexpr UnitBezier DEFAULT_TRANSITION_EASE = { 0, 0, 0.25, 1 }; +constexpr UnitBezier DEFAULT_TRANSITION_EASE = {0, 0, 0.25, 1}; constexpr int DEFAULT_RATE_LIMIT_TIMEOUT = 5; diff --git a/include/mbgl/util/convert.hpp b/include/mbgl/util/convert.hpp index e5458f2ed03..67342ea0d4e 100644 --- a/include/mbgl/util/convert.hpp +++ b/include/mbgl/util/convert.hpp @@ -7,10 +7,9 @@ namespace mbgl { namespace util { -template>> -MBGL_CONSTEXPR std::array convert(const std::array&from) { - std::array to {{}}; +template >> +MBGL_CONSTEXPR std::array convert(const std::array& from) { + std::array to{{}}; std::copy(std::begin(from), std::end(from), std::begin(to)); return to; } diff --git a/include/mbgl/util/default_style.hpp b/include/mbgl/util/default_style.hpp index 1fb5f696d6f..39b6afd2b86 100644 --- a/include/mbgl/util/default_style.hpp +++ b/include/mbgl/util/default_style.hpp @@ -10,7 +10,7 @@ class DefaultStyle { DefaultStyle(std::string, std::string, int); const std::string& getUrl() const; - const std::string& getName() const; + const std::string& getName() const; int getCurrentVersion() const; private: diff --git a/include/mbgl/util/enum.hpp b/include/mbgl/util/enum.hpp index c1a376e5f5d..2b80c6ab1ee 100644 --- a/include/mbgl/util/enum.hpp +++ b/include/mbgl/util/enum.hpp @@ -11,26 +11,29 @@ template class Enum { public: using Type = T; - static const char * toString(T); + static const char* toString(T); static std::optional toEnum(const std::string&); }; -#define MBGL_DEFINE_ENUM(T, ...) \ - \ -static const constexpr std::pair T##_names[] = __VA_ARGS__; \ - \ -template <> \ -const char * Enum::toString(T t) { \ - auto it = std::find_if(std::begin(T##_names), std::end(T##_names), \ - [&] (const auto& v) { return t == v.first; }); \ - assert(it != std::end(T##_names)); return it->second; \ -} \ - \ -template <> \ -std::optional Enum::toEnum(const std::string& s) { \ - auto it = std::find_if(std::begin(T##_names), std::end(T##_names), \ - [&] (const auto& v) { return s == v.second; }); \ - return it == std::end(T##_names) ? std::optional() : it->first; \ -} +#define MBGL_DEFINE_ENUM(T, ...) \ + \ + static const constexpr std::pair T##_names[] = __VA_ARGS__; \ + \ + template <> \ + const char* Enum::toString(T t) { \ + auto it = std::find_if(std::begin(T##_names), std::end(T##_names), [&](const auto& v) { \ + return t == v.first; \ + }); \ + assert(it != std::end(T##_names)); \ + return it->second; \ + } \ + \ + template <> \ + std::optional Enum::toEnum(const std::string& s) { \ + auto it = std::find_if(std::begin(T##_names), std::end(T##_names), [&](const auto& v) { \ + return s == v.second; \ + }); \ + return it == std::end(T##_names) ? std::optional() : it->first; \ + } } // namespace mbgl diff --git a/include/mbgl/util/event.hpp b/include/mbgl/util/event.hpp index 15583e956d4..bd517031beb 100644 --- a/include/mbgl/util/event.hpp +++ b/include/mbgl/util/event.hpp @@ -52,8 +52,6 @@ constexpr Event disabledEvents[] = { Event(-1) // Avoid zero size array }; -constexpr EventPermutation disabledEventPermutations[] = { - { EventSeverity::Debug, Event::Shader } -}; +constexpr EventPermutation disabledEventPermutations[] = {{EventSeverity::Debug, Event::Shader}}; } // namespace mbgl diff --git a/include/mbgl/util/exception.hpp b/include/mbgl/util/exception.hpp index f0d7c64f42e..fb42dd6bc53 100644 --- a/include/mbgl/util/exception.hpp +++ b/include/mbgl/util/exception.hpp @@ -6,33 +6,45 @@ namespace mbgl { namespace util { struct Exception : std::runtime_error { - Exception(const char *msg) : std::runtime_error(msg) {} - Exception(const std::string &msg) : std::runtime_error(msg) {} + Exception(const char *msg) + : std::runtime_error(msg) {} + Exception(const std::string &msg) + : std::runtime_error(msg) {} }; struct StyleImageException : Exception { - StyleImageException(const char *msg) : Exception(msg) {} - StyleImageException(const std::string &msg) : Exception(msg) {} + StyleImageException(const char *msg) + : Exception(msg) {} + StyleImageException(const std::string &msg) + : Exception(msg) {} }; struct MisuseException : Exception { - MisuseException(const char *msg) : Exception(msg) {} - MisuseException(const std::string &msg) : Exception(msg) {} + MisuseException(const char *msg) + : Exception(msg) {} + MisuseException(const std::string &msg) + : Exception(msg) {} }; struct StyleParseException : Exception { - StyleParseException(const char *msg) : Exception(msg) {} - StyleParseException(const std::string &msg) : Exception(msg) {} + StyleParseException(const char *msg) + : Exception(msg) {} + StyleParseException(const std::string &msg) + : Exception(msg) {} }; struct StyleLoadException : Exception { - StyleLoadException(const char *msg) : Exception(msg) {} - StyleLoadException(const std::string &msg) : Exception(msg) {} + StyleLoadException(const char *msg) + : Exception(msg) {} + StyleLoadException(const std::string &msg) + : Exception(msg) {} }; struct NotFoundException : Exception { - NotFoundException(const char *msg) : Exception(msg) {} - NotFoundException(const std::string &msg) : Exception(msg) {} + NotFoundException(const char *msg) + : Exception(msg) {} + NotFoundException(const std::string &msg) + : Exception(msg) {} }; } // namespace util diff --git a/include/mbgl/util/feature.hpp b/include/mbgl/util/feature.hpp index c8bd4e0d3f6..94b2b9d9b72 100644 --- a/include/mbgl/util/feature.hpp +++ b/include/mbgl/util/feature.hpp @@ -26,17 +26,22 @@ class Feature : public GeoJSONFeature { using GeometryType = mapbox::geometry::geometry; Feature() = default; - Feature(const GeoJSONFeature& f) : GeoJSONFeature(f) {} - Feature(const GeometryType& geom_) : GeoJSONFeature(geom_) {} - Feature(GeometryType&& geom_) : GeoJSONFeature(std::move(geom_)) {} + Feature(const GeoJSONFeature& f) + : GeoJSONFeature(f) {} + Feature(const GeometryType& geom_) + : GeoJSONFeature(geom_) {} + Feature(GeometryType&& geom_) + : GeoJSONFeature(std::move(geom_)) {} }; template std::optional numericValue(const Value& value) { - return value.match([](uint64_t t) { return std::optional(static_cast(t)); }, - [](int64_t t) { return std::optional(static_cast(t)); }, - [](double t) { return std::optional(static_cast(t)); }, - [](const auto&) { return std::optional(); }); + return value.match( + [](uint64_t t) { return std::optional(static_cast(t)); }, + [](int64_t t) { return std::optional(static_cast(t)); }, + [](double t) { return std::optional(static_cast(t)); }, + [](const auto&) { return std::optional(); } + ); } inline std::optional featureIDtoString(const FeatureIdentifier& id) { @@ -45,9 +50,12 @@ inline std::optional featureIDtoString(const FeatureIdentifier& id) } return id.match( - [](const std::string& value_) { return value_; }, [](uint64_t value_) { return util::toString(value_); }, - [](int64_t value_) { return util::toString(value_); }, [](double value_) { return util::toString(value_); }, -[](const auto&) -> std::optional { return std::nullopt; }); + [](const std::string& value_) { return value_; }, + [](uint64_t value_) { return util::toString(value_); }, + [](int64_t value_) { return util::toString(value_); }, + [](double value_) { return util::toString(value_); }, + [](const auto&) -> std::optional { return std::nullopt; } + ); } } // namespace mbgl diff --git a/include/mbgl/util/geo.hpp b/include/mbgl/util/geo.hpp index ae6c1550fab..eea953c51cb 100644 --- a/include/mbgl/util/geo.hpp +++ b/include/mbgl/util/geo.hpp @@ -19,7 +19,7 @@ class UnwrappedTileID; using ScreenCoordinate = mapbox::geometry::point; using ScreenLineString = mapbox::geometry::line_string; -using ScreenBox = mapbox::geometry::box; +using ScreenBox = mapbox::geometry::box; class LatLng { private: @@ -27,10 +27,14 @@ class LatLng { double lon; public: - enum WrapMode : bool { Unwrapped, Wrapped }; + enum WrapMode : bool { + Unwrapped, + Wrapped + }; LatLng(double lat_ = 0, double lon_ = 0, WrapMode mode = Unwrapped) - : lat(lat_), lon(lon_) { + : lat(lat_), + lon(lon_) { if (std::isnan(lat)) { throw std::domain_error("latitude must not be NaN"); } @@ -51,32 +55,28 @@ class LatLng { double latitude() const { return lat; } double longitude() const { return lon; } - LatLng wrapped() const { return { lat, lon, Wrapped }; } + LatLng wrapped() const { return {lat, lon, Wrapped}; } - void wrap() { - lon = util::wrap(lon, -util::LONGITUDE_MAX, util::LONGITUDE_MAX); - } + void wrap() { lon = util::wrap(lon, -util::LONGITUDE_MAX, util::LONGITUDE_MAX); } // If the distance from start to end longitudes is between half and full // world, unwrap the start longitude to ensure the shortest path is taken. void unwrapForShortestPath(const LatLng& end) { const double delta = std::abs(end.lon - lon); if (delta <= util::LONGITUDE_MAX || delta >= util::DEGREES_MAX) return; - if (lon > 0 && end.lon < 0) lon -= util::DEGREES_MAX; - else if (lon < 0 && end.lon > 0) lon += util::DEGREES_MAX; + if (lon > 0 && end.lon < 0) + lon -= util::DEGREES_MAX; + else if (lon < 0 && end.lon > 0) + lon += util::DEGREES_MAX; } // Constructs a LatLng object with the top left position of the specified tile. LatLng(const CanonicalTileID& id); LatLng(const UnwrappedTileID& id); - friend bool operator==(const LatLng& a, const LatLng& b) { - return a.lat == b.lat && a.lon == b.lon; - } + friend bool operator==(const LatLng& a, const LatLng& b) { return a.lat == b.lat && a.lon == b.lon; } - friend bool operator!=(const LatLng& a, const LatLng& b) { - return !(a == b); - } + friend bool operator!=(const LatLng& a, const LatLng& b) { return !(a == b); } }; class LatLngBounds { @@ -106,19 +106,20 @@ class LatLngBounds { /// /// Note: this is different than LatLngBounds::world() since arbitrary unwrapped /// coordinates are also inside the bounds. - LatLngBounds() : sw({-90, -180}), ne({90, 180}), bounded(false) {} + LatLngBounds() + : sw({-90, -180}), + ne({90, 180}), + bounded(false) {} // Constructs a LatLngBounds object with the tile's exact boundaries. LatLngBounds(const CanonicalTileID&); - bool valid() const { - return (sw.latitude() <= ne.latitude()) && (sw.longitude() <= ne.longitude()); - } + bool valid() const { return (sw.latitude() <= ne.latitude()) && (sw.longitude() <= ne.longitude()); } double south() const { return sw.latitude(); } - double west() const { return sw.longitude(); } + double west() const { return sw.longitude(); } double north() const { return ne.latitude(); } - double east() const { return ne.longitude(); } + double east() const { return ne.longitude(); } LatLng southwest() const { return sw; } LatLng northeast() const { return ne; } @@ -130,10 +131,8 @@ class LatLngBounds { LatLng constrain(const LatLng& p) const; void extend(const LatLng& point) { - sw = LatLng(std::min(point.latitude(), sw.latitude()), - std::min(point.longitude(), sw.longitude())); - ne = LatLng(std::max(point.latitude(), ne.latitude()), - std::max(point.longitude(), ne.longitude())); + sw = LatLng(std::min(point.latitude(), sw.latitude()), std::min(point.longitude(), sw.longitude())); + ne = LatLng(std::max(point.latitude(), ne.latitude()), std::max(point.longitude(), ne.longitude())); } void extend(const LatLngBounds& bounds) { @@ -141,14 +140,9 @@ class LatLngBounds { extend(bounds.ne); } - bool isEmpty() const { - return sw.latitude() > ne.latitude() || - sw.longitude() > ne.longitude(); - } + bool isEmpty() const { return sw.latitude() > ne.latitude() || sw.longitude() > ne.longitude(); } - bool crossesAntimeridian() const { - return (sw.wrapped().longitude() > ne.wrapped().longitude()); - } + bool crossesAntimeridian() const { return (sw.wrapped().longitude() > ne.wrapped().longitude()); } bool contains(const CanonicalTileID& tileID) const; bool contains(const LatLng& point, LatLng::WrapMode wrap = LatLng::Unwrapped) const; @@ -161,7 +155,9 @@ class LatLngBounds { LatLng ne; bool bounded = true; - LatLngBounds(LatLng sw_, LatLng ne_) : sw(sw_), ne(ne_) {} + LatLngBounds(LatLng sw_, LatLng ne_) + : sw(sw_), + ne(ne_) {} bool containsLatitude(double latitude) const; bool containsLongitude(double longitude, LatLng::WrapMode wrap) const; @@ -170,9 +166,7 @@ class LatLngBounds { return (!a.bounded && !b.bounded) || (a.bounded && b.bounded && a.sw == b.sw && a.ne == b.ne); } - friend bool operator!=(const LatLngBounds& a, const LatLngBounds& b) { - return !(a == b); - } + friend bool operator!=(const LatLngBounds& a, const LatLngBounds& b) { return !(a == b); } }; // Determines the orientation of the map. @@ -193,7 +187,10 @@ class EdgeInsets { public: EdgeInsets(double t_ = 0, double l_ = 0, double b_ = 0, double r_ = 0) - : _top(t_), _left(l_), _bottom(b_), _right(r_) { + : _top(t_), + _left(l_), + _bottom(b_), + _right(r_) { if (std::isnan(_top)) { throw std::domain_error("top must not be NaN"); } @@ -213,9 +210,7 @@ class EdgeInsets { double bottom() const { return _bottom; } double right() const { return _right; } - bool isFlush() const { - return _top == 0 && _left == 0 && _bottom == 0 && _right == 0; - } + bool isFlush() const { return _top == 0 && _left == 0 && _bottom == 0 && _right == 0; } void operator+=(const EdgeInsets& o) { _top += o._top; @@ -226,7 +221,10 @@ class EdgeInsets { EdgeInsets operator+(const EdgeInsets& o) const { return { - _top + o._top, _left + o._left, _bottom + o._bottom, _right + o._right, + _top + o._top, + _left + o._left, + _bottom + o._bottom, + _right + o._right, }; } @@ -236,9 +234,7 @@ class EdgeInsets { return a._top == b._top && a._left == b._left && a._bottom == b._bottom && a._right == b._right; } - friend bool operator!=(const EdgeInsets& a, const EdgeInsets& b) { - return !(a == b); - } + friend bool operator!=(const EdgeInsets& a, const EdgeInsets& b) { return !(a == b); } }; struct LatLngAltitude { diff --git a/include/mbgl/util/geometry.hpp b/include/mbgl/util/geometry.hpp index 5fc9c59e7f1..3b56d87240c 100644 --- a/include/mbgl/util/geometry.hpp +++ b/include/mbgl/util/geometry.hpp @@ -42,30 +42,44 @@ template using Geometry = mapbox::geometry::geometry; template -Point convertPoint(const Point& p) { +Point convertPoint(const Point &p) { return Point(static_cast(p.x), static_cast(p.y)); } struct ToFeatureType { - FeatureType operator()(const EmptyGeometry&) const { return FeatureType::Unknown; } + FeatureType operator()(const EmptyGeometry &) const { return FeatureType::Unknown; } template - FeatureType operator()(const Point &) const { return FeatureType::Point; } + FeatureType operator()(const Point &) const { + return FeatureType::Point; + } template - FeatureType operator()(const MultiPoint &) const { return FeatureType::Point; } + FeatureType operator()(const MultiPoint &) const { + return FeatureType::Point; + } template - FeatureType operator()(const LineString &) const { return FeatureType::LineString; } + FeatureType operator()(const LineString &) const { + return FeatureType::LineString; + } template - FeatureType operator()(const MultiLineString &) const { return FeatureType::LineString; } + FeatureType operator()(const MultiLineString &) const { + return FeatureType::LineString; + } template - FeatureType operator()(const Polygon &) const { return FeatureType::Polygon; } + FeatureType operator()(const Polygon &) const { + return FeatureType::Polygon; + } template - FeatureType operator()(const MultiPolygon &) const { return FeatureType::Polygon; } + FeatureType operator()(const MultiPolygon &) const { + return FeatureType::Polygon; + } template - FeatureType operator()(const mapbox::geometry::geometry_collection &) const { return FeatureType::Unknown; } + FeatureType operator()(const mapbox::geometry::geometry_collection &) const { + return FeatureType::Unknown; + } }; template -auto forEachPoint(const Geometry& g, F f) { +auto forEachPoint(const Geometry &g, F f) { mapbox::geometry::for_each_point(g, f); } diff --git a/include/mbgl/util/ignore.hpp b/include/mbgl/util/ignore.hpp index 37160ef9ad6..f32e251cdd2 100644 --- a/include/mbgl/util/ignore.hpp +++ b/include/mbgl/util/ignore.hpp @@ -11,11 +11,13 @@ namespace util { /// /// See https://github.com/mapbox/cpp/blob/1bb519ef25edd6169f1d6d8a65414044616590a9/docs/structural-metaprogramming.md /// for more details. -template void ignore(Ts&&...) {} +template +void ignore(Ts&&...) {} // std::initializer_list overload, for situations where you need sequenced // modifications. -template void ignore(const std::initializer_list&) {} +template +void ignore(const std::initializer_list&) {} // Handle the zero-argument case. inline void ignore(const std::initializer_list&) {} diff --git a/include/mbgl/util/image.hpp b/include/mbgl/util/image.hpp index a3bce11135e..d9d8a452d87 100644 --- a/include/mbgl/util/image.hpp +++ b/include/mbgl/util/image.hpp @@ -22,9 +22,12 @@ class Image : private util::noncopyable { public: Image() = default; - Image(Size size_) : size(size_), data(std::make_unique(bytes())) {} + Image(Size size_) + : size(size_), + data(std::make_unique(bytes())) {} - Image(Size size_, const uint8_t* srcData, std::size_t srcLength) : size(size_) { + Image(Size size_, const uint8_t* srcData, std::size_t srcLength) + : size(size_) { if (srcLength != bytes()) { throw std::invalid_argument("mismatched image size"); } @@ -32,9 +35,15 @@ class Image : private util::noncopyable { std::copy(srcData, srcData + srcLength, data.get()); } - Image(Size size_, std::unique_ptr data_) : size(size_), data(std::move(data_)) {} + Image(Size size_, std::unique_ptr data_) + : size(size_), + data(std::move(data_)) {} - Image(Image&& o) noexcept : size(o.size), data(std::move(o.data)) { o.size.width = o.size.height = 0; } + Image(Image&& o) noexcept + : size(o.size), + data(std::move(o.data)) { + o.size.width = o.size.height = 0; + } Image& operator=(Image&& o) noexcept { size = o.size; @@ -44,13 +53,10 @@ class Image : private util::noncopyable { } friend bool operator==(const Image& lhs, const Image& rhs) { - return std::equal(lhs.data.get(), lhs.data.get() + lhs.bytes(), - rhs.data.get(), rhs.data.get() + rhs.bytes()); + return std::equal(lhs.data.get(), lhs.data.get() + lhs.bytes(), rhs.data.get(), rhs.data.get() + rhs.bytes()); } - friend bool operator!=(const Image& lhs, const Image& rhs) { - return !(lhs == rhs); - } + friend bool operator!=(const Image& lhs, const Image& rhs) { return !(lhs == rhs); } bool valid() const { return !size.isEmpty() && data != nullptr; } @@ -64,9 +70,7 @@ class Image : private util::noncopyable { size_t stride() const { return channels * size.width; } size_t bytes() const { return stride() * size.height; } - void fill(uint8_t value) { - std::fill(data.get(), data.get() + bytes(), value); - } + void fill(uint8_t value) { std::fill(data.get(), data.get() + bytes(), value); } void resize(Size size_) { if (size == size_) { @@ -74,10 +78,7 @@ class Image : private util::noncopyable { } Image newImage(size_); newImage.fill(0); - copy(*this, newImage, {0, 0}, {0, 0}, { - std::min(size.width, size_.width), - std::min(size.height, size_.height) - }); + copy(*this, newImage, {0, 0}, {0, 0}, {std::min(size.width, size_.width), std::min(size.height, size_.height)}); operator=(std::move(newImage)); } @@ -91,10 +92,8 @@ class Image : private util::noncopyable { throw std::invalid_argument("invalid destination for image clear"); } - if (size.width > dstImg.size.width || - size.height > dstImg.size.height || - pt.x > dstImg.size.width - size.width || - pt.y > dstImg.size.height - size.height) { + if (size.width > dstImg.size.width || size.height > dstImg.size.height || + pt.x > dstImg.size.width - size.width || pt.y > dstImg.size.height - size.height) { throw std::out_of_range("out of range destination coordinates for image clear"); } @@ -109,7 +108,9 @@ class Image : private util::noncopyable { /// Copy image data within `rect` from `src` to the rectangle of the same size at `pt` /// in `dst`. If the specified bounds exceed the bounds of the source or destination, /// throw `std::out_of_range`. Must not be used to move data within a single Image. - static void copy(const Image& srcImg, Image& dstImg, const Point& srcPt, const Point& dstPt, const Size& size) { + static void copy( + const Image& srcImg, Image& dstImg, const Point& srcPt, const Point& dstPt, const Size& size + ) { if (size.isEmpty()) { return; } @@ -122,31 +123,25 @@ class Image : private util::noncopyable { throw std::invalid_argument("invalid destination for image copy"); } - if (size.width > srcImg.size.width || - size.height > srcImg.size.height || - srcPt.x > srcImg.size.width - size.width || - srcPt.y > srcImg.size.height - size.height) { + if (size.width > srcImg.size.width || size.height > srcImg.size.height || + srcPt.x > srcImg.size.width - size.width || srcPt.y > srcImg.size.height - size.height) { throw std::out_of_range("out of range source coordinates for image copy"); } - if (size.width > dstImg.size.width || - size.height > dstImg.size.height || - dstPt.x > dstImg.size.width - size.width || - dstPt.y > dstImg.size.height - size.height) { + if (size.width > dstImg.size.width || size.height > dstImg.size.height || + dstPt.x > dstImg.size.width - size.width || dstPt.y > dstImg.size.height - size.height) { throw std::out_of_range("out of range destination coordinates for image copy"); } const uint8_t* srcData = srcImg.data.get(); - uint8_t* dstData = dstImg.data.get(); + uint8_t* dstData = dstImg.data.get(); assert(srcData != dstData); for (uint32_t y = 0; y < size.height; y++) { const std::size_t srcOffset = (srcPt.y + y) * srcImg.stride() + srcPt.x * channels; const std::size_t dstOffset = (dstPt.y + y) * dstImg.stride() + dstPt.x * channels; - std::copy(srcData + srcOffset, - srcData + srcOffset + size.width * channels, - dstData + dstOffset); + std::copy(srcData + srcOffset, srcData + srcOffset + size.width * channels, dstData + dstOffset); } } diff --git a/include/mbgl/util/immutable.hpp b/include/mbgl/util/immutable.hpp index fbd3ac9b342..b3012c04f57 100644 --- a/include/mbgl/util/immutable.hpp +++ b/include/mbgl/util/immutable.hpp @@ -7,9 +7,9 @@ namespace mbgl { /** * `Mutable` is a non-nullable uniquely owning reference to a `T`. It can be efficiently converted * to `Immutable`. - * + * * The lifecycle of `Mutable` and `Immutable` is as follows: - * + * * 1. Create a `Mutable` using `makeMutable(...)` * 2. Mutate it freely * 3. When you're ready to freeze its state and enable safe cross-thread sharing, move assign or @@ -37,11 +37,14 @@ class Mutable { std::shared_ptr ptr; - template friend class Immutable; + template + friend class Immutable; // NOLINTNEXTLINE(readability-redundant-declaration) - template friend Mutable makeMutable(Args&&...); + template + friend Mutable makeMutable(Args&&...); // NOLINTNEXTLINE(readability-redundant-declaration) - template friend Mutable staticMutableCast(const Mutable&); + template + friend Mutable staticMutableCast(const Mutable&); }; template @@ -90,13 +93,9 @@ class Immutable { const T* operator->() const { return ptr.get(); } const T& operator*() const { return *ptr; } - friend bool operator==(const Immutable& lhs, const Immutable& rhs) { - return lhs.ptr == rhs.ptr; - } + friend bool operator==(const Immutable& lhs, const Immutable& rhs) { return lhs.ptr == rhs.ptr; } - friend bool operator!=(const Immutable& lhs, const Immutable& rhs) { - return lhs.ptr != rhs.ptr; - } + friend bool operator!=(const Immutable& lhs, const Immutable& rhs) { return lhs.ptr != rhs.ptr; } private: Immutable(std::shared_ptr&& s) @@ -104,10 +103,12 @@ class Immutable { std::shared_ptr ptr; - template friend class Immutable; + template + friend class Immutable; // NOLINTNEXTLINE(readability-redundant-declaration) - template friend Immutable staticImmutableCast(const Immutable&); + template + friend Immutable staticImmutableCast(const Immutable&); }; template diff --git a/include/mbgl/util/indexed_tuple.hpp b/include/mbgl/util/indexed_tuple.hpp index 4ad9e210956..b5fcb6007cf 100644 --- a/include/mbgl/util/indexed_tuple.hpp +++ b/include/mbgl/util/indexed_tuple.hpp @@ -16,7 +16,8 @@ struct TypeIndex : std::integral_constant {}; template struct TypeIndex : std::integral_constant::value> {}; -template class IndexedTuple; +template +class IndexedTuple; /// A tuple of Ts, where individual members can be accessed via `t.get()` for I ∈ Is. /// @@ -38,15 +39,14 @@ class IndexedTuple, TypeList> : public std::tuple } template - IndexedTuple(Us&&... other) : std::tuple(std::forward(other)...) {}; + IndexedTuple(Us&&... other) + : std::tuple(std::forward(other)...){}; template - IndexedTuple, TypeList> - concat(const IndexedTuple, TypeList>& other) const { - return IndexedTuple, TypeList> { - get()..., - other.template get()... - }; + IndexedTuple, TypeList> concat( + const IndexedTuple, TypeList>& other + ) const { + return IndexedTuple, TypeList>{get()..., other.template get()...}; } // Help out MSVC++ @@ -54,9 +54,7 @@ class IndexedTuple, TypeList> : public std::tuple return static_cast&>(*this) == static_cast&>(other); } - bool operator!=(const IndexedTuple, TypeList>& other) const { - return !(*this == other); - } + bool operator!=(const IndexedTuple, TypeList>& other) const { return !(*this == other); } }; template diff --git a/include/mbgl/util/interpolate.hpp b/include/mbgl/util/interpolate.hpp index 6434fd322a2..1243cdb043c 100644 --- a/include/mbgl/util/interpolate.hpp +++ b/include/mbgl/util/interpolate.hpp @@ -32,16 +32,12 @@ T interpolate(const T& a, const T& b, const float t) { template struct Interpolator { - T operator()(const T& a, const T& b, const double t) const { - return a * (1.0 - t) + b * t; - } + T operator()(const T& a, const T& b, const double t) const { return a * (1.0 - t) + b * t; } }; template <> struct Interpolator { - float operator()(const float& a, const float& b, const float t) const { - return a * (1.0f - t) + b * t; - } + float operator()(const float& a, const float& b, const float t) const { return a * (1.0f - t) + b * t; } float operator()(const float& a, const float& b, const double t) const { return static_cast(a * (1.0 - t) + b * t); @@ -55,7 +51,7 @@ struct Interpolator> { template Array operator()(const Array& a, const Array& b, const double t, std::index_sequence) { - return {{ interpolate(a[I], b[I], t)... }}; + return {{interpolate(a[I], b[I], t)...}}; } public: @@ -71,7 +67,7 @@ struct Interpolator> { template Array operator()(const Array& a, const Array& b, const float t, std::index_sequence) { - return {{ interpolate(a[I], b[I], t)... }}; + return {{interpolate(a[I], b[I], t)...}}; } public: @@ -80,7 +76,6 @@ struct Interpolator> { } }; - /// In order to accept Array as an output value for Curve /// expressions, we need to have an interpolatable std::vector type. /// However, style properties like line-dasharray are represented using @@ -89,21 +84,18 @@ struct Interpolator> { /// asserting that (a) the vectors are the same size, and (b) they contain /// only numeric values. (These invariants should be relatively safe, /// being enforced by the expression type system.) -template<> +template <> struct Interpolator> { - std::vector operator()(const std::vector& a, - const std::vector& b, - const double t) const { + std::vector operator()( + const std::vector& a, const std::vector& b, const double t + ) const { assert(a.size() == b.size()); if (a.empty()) return {}; std::vector result; for (std::size_t i = 0; i < a.size(); i++) { assert(a[i].template is()); assert(b[i].template is()); - style::expression::Value item = interpolate( - a[i].template get(), - b[i].template get(), - t); + style::expression::Value item = interpolate(a[i].template get(), b[i].template get(), t); result.push_back(item); } return result; @@ -117,7 +109,7 @@ struct Interpolator { auto pos = style::Position(); auto interpolated = interpolate(a.getCartesian(), b.getCartesian(), t); pos.setCartesian(interpolated); - return { pos }; + return {pos}; } }; @@ -125,21 +117,11 @@ template <> struct Interpolator { public: Color operator()(const Color& a, const Color& b, const float t) { - return { - interpolate(a.r, b.r, t), - interpolate(a.g, b.g, t), - interpolate(a.b, b.b, t), - interpolate(a.a, b.a, t) - }; + return {interpolate(a.r, b.r, t), interpolate(a.g, b.g, t), interpolate(a.b, b.b, t), interpolate(a.a, b.a, t)}; } Color operator()(const Color& a, const Color& b, const double t) { - return { - interpolate(a.r, b.r, t), - interpolate(a.g, b.g, t), - interpolate(a.b, b.b, t), - interpolate(a.a, b.a, t) - }; + return {interpolate(a.r, b.r, t), interpolate(a.g, b.g, t), interpolate(a.b, b.b, t), interpolate(a.a, b.a, t)}; } }; @@ -172,29 +154,20 @@ struct Uninterpolated { }; template <> -struct Interpolator - : Uninterpolated {}; +struct Interpolator : Uninterpolated {}; template -struct Interpolator>> - : Uninterpolated {}; +struct Interpolator>> : Uninterpolated {}; template <> -struct Interpolator - : Uninterpolated {}; +struct Interpolator : Uninterpolated {}; template -struct Interpolator> - : Uninterpolated {}; +struct Interpolator> : Uninterpolated {}; template struct Interpolatable - : std::conditional_t< - !std::is_base_of_v>, - std::true_type, - std::false_type> {}; - - + : std::conditional_t>, std::true_type, std::false_type> {}; } // namespace util } // namespace mbgl diff --git a/include/mbgl/util/logging.hpp b/include/mbgl/util/logging.hpp index a3d6f776f56..4944da6619b 100644 --- a/include/mbgl/util/logging.hpp +++ b/include/mbgl/util/logging.hpp @@ -18,13 +18,11 @@ class Log { /// When an observer is set, this function will be called for every log /// message. Returning true will consume the message. - virtual bool onRecord(EventSeverity severity, Event event, int64_t code, const std::string &msg) = 0; + virtual bool onRecord(EventSeverity severity, Event event, int64_t code, const std::string& msg) = 0; }; class NullObserver : public Observer { - bool onRecord(EventSeverity, Event, int64_t, const std::string&) override { - return true; - } + bool onRecord(EventSeverity, Event, int64_t, const std::string&) override { return true; } }; static void setObserver(std::unique_ptr Observer); @@ -42,50 +40,51 @@ class Log { static void useLogThread(bool enable); - template - static void Debug(Event event, Args&& ...args) { + template + static void Debug(Event event, Args&&... args) { Record(EventSeverity::Debug, event, ::std::forward(args)...); } - template - static void Info(Event event, Args&& ...args) { + template + static void Info(Event event, Args&&... args) { Record(EventSeverity::Info, event, ::std::forward(args)...); } - template - static void Warning(Event event, Args&& ...args) { + template + static void Warning(Event event, Args&&... args) { Record(EventSeverity::Warning, event, ::std::forward(args)...); } - template - static void Error(Event event, Args&& ...args) { + template + static void Error(Event event, Args&&... args) { Record(EventSeverity::Error, event, ::std::forward(args)...); } - template - static void Record(EventSeverity severity, Event event, Args&& ...args) { - if (!includes(severity, disabledEventSeverities) && - !includes(event, disabledEvents) && - !includes({ severity, event }, disabledEventPermutations)) { - record(severity, event, ::std::forward(args)...); + template + static void Record(EventSeverity severity, Event event, Args&&... args) { + if (!includes(severity, disabledEventSeverities) && !includes(event, disabledEvents) && + !includes({severity, event}, disabledEventPermutations)) { + record(severity, event, ::std::forward(args)...); } } private: static Log* get() noexcept; - static void record(EventSeverity severity, Event event, const std::string &msg); - static void record(EventSeverity severity, Event event, int64_t code, const std::string &msg); - static void record(EventSeverity severity, - Event event, - int64_t code, - const std::string& msg, - const std::optional& threadName); + static void record(EventSeverity severity, Event event, const std::string& msg); + static void record(EventSeverity severity, Event event, int64_t code, const std::string& msg); + static void record( + EventSeverity severity, + Event event, + int64_t code, + const std::string& msg, + const std::optional& threadName + ); // This method is the data sink that must be implemented by each platform we // support. It should ideally output the error message in a human readable // format to the developer. - static void platformRecord(EventSeverity severity, const std::string &msg); + static void platformRecord(EventSeverity severity, const std::string& msg); class Impl; const std::unique_ptr impl; }; diff --git a/include/mbgl/util/noncopyable.hpp b/include/mbgl/util/noncopyable.hpp index 8cb7e198d9a..99706056c80 100644 --- a/include/mbgl/util/noncopyable.hpp +++ b/include/mbgl/util/noncopyable.hpp @@ -1,15 +1,14 @@ #pragma once -namespace mbgl { namespace util { +namespace mbgl { +namespace util { -namespace non_copyable_ -{ +namespace non_copyable_ { -class noncopyable -{ +class noncopyable { public: - noncopyable( noncopyable const& ) = delete; - noncopyable& operator=(noncopyable const& ) = delete; + noncopyable(noncopyable const&) = delete; + noncopyable& operator=(noncopyable const&) = delete; protected: constexpr noncopyable() = default; diff --git a/include/mbgl/util/platform.hpp b/include/mbgl/util/platform.hpp index ed4710424af..96a175ef740 100644 --- a/include/mbgl/util/platform.hpp +++ b/include/mbgl/util/platform.hpp @@ -17,7 +17,7 @@ std::string lowercase(const std::string &string); std::string getCurrentThreadName(); /// Set the name of the current thread, truncated at 15. -void setCurrentThreadName(const std::string& name); +void setCurrentThreadName(const std::string &name); /// Makes the current thread low priority. void makeThreadLowPriority(); diff --git a/include/mbgl/util/projection.hpp b/include/mbgl/util/projection.hpp index 4c2db837c87..3e8e2f9f1e0 100644 --- a/include/mbgl/util/projection.hpp +++ b/include/mbgl/util/projection.hpp @@ -15,7 +15,8 @@ class ProjectedMeters { public: ProjectedMeters(double n_ = 0, double e_ = 0) - : _northing(n_), _easting(e_) { + : _northing(n_), + _easting(e_) { if (std::isnan(_northing)) { throw std::domain_error("northing must not be NaN"); } @@ -31,9 +32,7 @@ class ProjectedMeters { return a._northing == b._northing && a._easting == b._easting; } - friend bool operator!=(const ProjectedMeters& a, const ProjectedMeters& b) { - return !(a == b); - } + friend bool operator!=(const ProjectedMeters& a, const ProjectedMeters& b) { return !(a == b); } }; /// Spherical Mercator projection @@ -41,15 +40,14 @@ class ProjectedMeters { class Projection { public: // Map pixel width at given scale. - static double worldSize(double scale) { - return scale * util::tileSize_D; - } + static double worldSize(double scale) { return scale * util::tileSize_D; } static double getMetersPerPixelAtLatitude(double lat, double zoom) { const double constrainedZoom = util::clamp(zoom, util::MIN_ZOOM, util::MAX_ZOOM); const double constrainedScale = std::pow(2.0, constrainedZoom); const double constrainedLatitude = util::clamp(lat, -util::LATITUDE_MAX, util::LATITUDE_MAX); - return std::cos(util::deg2rad(constrainedLatitude)) * util::M2PI * util::EARTH_RADIUS_M / worldSize(constrainedScale); + return std::cos(util::deg2rad(constrainedLatitude)) * util::M2PI * util::EARTH_RADIUS_M / + worldSize(constrainedScale); } static ProjectedMeters projectedMetersForLatLng(const LatLng& latLng) { @@ -59,14 +57,15 @@ class Projection { const double m = 1 - 1e-15; const double f = util::clamp(std::sin(util::deg2rad(constrainedLatitude)), -m, m); - const double easting = util::deg2rad(util::EARTH_RADIUS_M * constrainedLongitude); + const double easting = util::deg2rad(util::EARTH_RADIUS_M * constrainedLongitude); const double northing = 0.5 * util::EARTH_RADIUS_M * std::log((1 + f) / (1 - f)); return {northing, easting}; } static LatLng latLngForProjectedMeters(const ProjectedMeters& projectedMeters) { - double latitude = util::rad2deg(2 * std::atan(std::exp(projectedMeters.northing() / util::EARTH_RADIUS_M)) - (M_PI / 2.0)); + double latitude = + util::rad2deg(2 * std::atan(std::exp(projectedMeters.northing() / util::EARTH_RADIUS_M)) - (M_PI / 2.0)); double longitude = util::rad2deg(projectedMeters.easting()) / util::EARTH_RADIUS_M; latitude = util::clamp(latitude, -util::LATITUDE_MAX, util::LATITUDE_MAX); @@ -75,31 +74,27 @@ class Projection { return {latitude, longitude}; } - static Point project(const LatLng& latLng, double scale) { - return project_(latLng, worldSize(scale)); - } + static Point project(const LatLng& latLng, double scale) { return project_(latLng, worldSize(scale)); } /// Returns point on tile - static Point project(const LatLng& latLng, int32_t zoom) { - return project_(latLng, 1 << zoom); - } + static Point project(const LatLng& latLng, int32_t zoom) { return project_(latLng, 1 << zoom); } static LatLng unproject(const Point& p, double scale, LatLng::WrapMode wrapMode = LatLng::Unwrapped) { auto p2 = p * util::DEGREES_MAX / worldSize(scale); - return LatLng { + return LatLng{ std::atan(std::exp(util::deg2rad(util::LONGITUDE_MAX - p2.y))) * util::DEGREES_MAX / M_PI - 90.0, p2.x - util::LONGITUDE_MAX, - wrapMode - }; + wrapMode}; } private: static Point project_(const LatLng& latLng, double worldSize) { const double latitude = util::clamp(latLng.latitude(), -util::LATITUDE_MAX, util::LATITUDE_MAX); - return Point { - util::LONGITUDE_MAX + latLng.longitude(), - util::LONGITUDE_MAX - util::rad2deg(std::log(std::tan(M_PI / 4 + latitude * M_PI / util::DEGREES_MAX))) - } * (worldSize / util::DEGREES_MAX); + return Point{ + util::LONGITUDE_MAX + latLng.longitude(), + util::LONGITUDE_MAX - + util::rad2deg(std::log(std::tan(M_PI / 4 + latitude * M_PI / util::DEGREES_MAX)))} * + (worldSize / util::DEGREES_MAX); } }; diff --git a/include/mbgl/util/range.hpp b/include/mbgl/util/range.hpp index 5591a22a1f3..f5e4ac5357a 100644 --- a/include/mbgl/util/range.hpp +++ b/include/mbgl/util/range.hpp @@ -8,7 +8,8 @@ template class Range { public: constexpr Range(T min_, T max_) - : min(std::move(min_)), max(std::move(max_)) {} + : min(std::move(min_)), + max(std::move(max_)) {} T min; T max; diff --git a/include/mbgl/util/run_loop.hpp b/include/mbgl/util/run_loop.hpp index 26d6cbcc165..7e1d94332a9 100644 --- a/include/mbgl/util/run_loop.hpp +++ b/include/mbgl/util/run_loop.hpp @@ -16,10 +16,9 @@ namespace mbgl { namespace util { -using LOOP_HANDLE = void *; +using LOOP_HANDLE = void*; -class RunLoop : public Scheduler, - private util::noncopyable { +class RunLoop : public Scheduler, private util::noncopyable { public: enum class Type : uint8_t { Default, @@ -32,9 +31,9 @@ class RunLoop : public Scheduler, }; enum class Event : uint8_t { - None = 0, - Read = 1, - Write = 2, + None = 0, + Read = 1, + Write = 2, ReadWrite = Read | Write, }; @@ -73,8 +72,7 @@ class RunLoop : public Scheduler, // Post the cancellable work fn(args...) to this RunLoop. template - std::unique_ptr - invokeCancellable(Fn&& fn, Args&&... args) { + std::unique_ptr invokeCancellable(Fn&& fn, Args&&... args) { std::shared_ptr task = WorkTask::make(std::forward(fn), std::forward(args)...); push(Priority::Default, task); return std::make_unique(task); diff --git a/include/mbgl/util/size.hpp b/include/mbgl/util/size.hpp index e20be06bb5c..815ba54cbf7 100644 --- a/include/mbgl/util/size.hpp +++ b/include/mbgl/util/size.hpp @@ -8,20 +8,15 @@ class Size { public: constexpr Size() = default; - constexpr Size(const uint32_t width_, const uint32_t height_) : width(width_), height(height_) { - } - - constexpr uint32_t area() const { - return width * height; - } - - constexpr float aspectRatio() const { - return static_cast(width) / static_cast(height); - } - - constexpr bool isEmpty() const { - return width == 0 || height == 0; - } + constexpr Size(const uint32_t width_, const uint32_t height_) + : width(width_), + height(height_) {} + + constexpr uint32_t area() const { return width * height; } + + constexpr float aspectRatio() const { return static_cast(width) / static_cast(height); } + + constexpr bool isEmpty() const { return width == 0 || height == 0; } uint32_t width = 0; uint32_t height = 0; diff --git a/include/mbgl/util/string.hpp b/include/mbgl/util/string.hpp index 370b08afaf7..70e1212f949 100644 --- a/include/mbgl/util/string.hpp +++ b/include/mbgl/util/string.hpp @@ -11,8 +11,7 @@ namespace std { -inline int stoi(const std::string &str) -{ +inline int stoi(const std::string &str) { return atoi(str.c_str()); } @@ -85,7 +84,7 @@ std::string toString(T) = delete; std::string toHex(uint32_t); std::string toHex(uint64_t); -inline float stof(const std::string& str) { +inline float stof(const std::string &str) { return std::stof(str); } diff --git a/include/mbgl/util/thread.hpp b/include/mbgl/util/thread.hpp index 42a18ba6844..e69c981a586 100644 --- a/include/mbgl/util/thread.hpp +++ b/include/mbgl/util/thread.hpp @@ -62,7 +62,7 @@ class Thread { loop->run(); - (void) establishedActor; + (void)establishedActor; loop = nullptr; } @@ -85,14 +85,12 @@ class Thread { } std::promise stoppable; - + running.wait(); // Invoke a noop task on the run loop to ensure that we're executing // run() before we call stop() - loop->invoke([&] { - stoppable.set_value(); - }); + loop->invoke([&] { stoppable.set_value(); }); stoppable.get_future().get(); @@ -104,9 +102,7 @@ class Thread { /// can be used to send messages to `Object`. It is safe /// to the non-owning reference to outlive this object /// and be used after the `Thread<>` gets destroyed. - ActorRef> actor() { - return object.self(); - } + ActorRef> actor() { return object.self(); } /// Pauses the `Object` thread. It will prevent the object to wake /// up from events such as timers and file descriptor I/O. Messages @@ -153,7 +149,7 @@ class Thread { std::thread thread; std::future running; - + std::unique_ptr> paused; std::unique_ptr> resumed; diff --git a/include/mbgl/util/tile_server_options.hpp b/include/mbgl/util/tile_server_options.hpp index 41c5ba7d1fa..e770018fe77 100644 --- a/include/mbgl/util/tile_server_options.hpp +++ b/include/mbgl/util/tile_server_options.hpp @@ -12,279 +12,290 @@ namespace mbgl { /** * @brief Holds values for tile server options. */ - class TileServerOptions final { - public: - /** - * @brief Constructs a TileServerOptions object with default values. - */ - explicit TileServerOptions(); - ~TileServerOptions(); - - // movable - TileServerOptions(TileServerOptions&& options) noexcept; - TileServerOptions& operator=(TileServerOptions&& options) noexcept; - - // copyable - TileServerOptions(const TileServerOptions&); - - - TileServerOptions clone() const; - - /** - * @brief Sets the API base URL. - * - * @param baseURL API base URL. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withBaseURL(std::string baseURL); - - /** - * @brief Gets the previously set (or default) API base URL. - * - * @return const std::string& API base URL. - */ - const std::string& baseURL() const; - - /** - * @brief Sets the scheme alias for the tile server. For example maptiler:// for MapTiler. - * - * @param alias The URI alias. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withUriSchemeAlias(std::string alias); - - /** - * @brief Gets the previously set (or default) tile server URI alias. - * - * @return const std::string& scheme alias. - */ - const std::string& uriSchemeAlias() const; - - /** - * @brief Sets the template for sources. - * - * @param sourceTemplate The source template. - * @param domainName The domain name. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withSourceTemplate(std::string sourceTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) source template. - * - * @return const std::string& source template. - */ - const std::string& sourceTemplate() const; - - /** - * @brief Gets the previously set (or default) source domain name - * - * @return const std::string& source domain name. - */ - const std::string& sourceDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& sourceVersionPrefix() const; - - /** - * @brief Sets the template for styles. - * - * @param styleTemplate The style template. - * @param domainName If set, the URL domain must contain the specified string to be matched as canonical style URL . - * - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withStyleTemplate(std::string styleTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) style template. - * - * @return const std::string& style template. - */ - const std::string& styleTemplate() const; - - /** - * @brief Gets the previously set (or default) style domain name. - * - * @return const std::string& domain name. - */ - const std::string& styleDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& styleVersionPrefix() const; - - /** - * @brief Sets the template for sprites. - * @param domainName If set, the URL domain must contain the specified string to be matched as canonical sprite URL . - * - * @param spritesTemplate The sprites template. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withSpritesTemplate(std::string spritesTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) sprites template. - * - * @return const std::string& sprites template. - */ - const std::string& spritesTemplate() const; - - /** - * @brief Gets the previously set (or default) sprites domain name. - * - * @return const std::string& domain name. - */ - const std::string& spritesDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& spritesVersionPrefix() const; - - /** - * @brief Sets the template for glyphs. - * - * @param glyphsTemplate The glyphs template. - * @param domainName If set, the URL domain must contain the specified string to be matched as canonical glyphs URL . - * - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withGlyphsTemplate(std::string glyphsTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) glyphs template. - * - * @return const std::string& glyphs template. - */ - const std::string& glyphsTemplate() const; - - /** - * @brief Gets the previously set (or default) glyphs domain name. - * - * @return const std::string& domain name. - */ - const std::string& glyphsDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& glyphsVersionPrefix() const; - - /** - * @brief Sets the template for tiles. - * - * @param tileTemplate The tile template. - * @param domainName If set, the URL domain must contain the specified string to be matched as canonical tile URL . - * - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withTileTemplate(std::string tileTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) tile template. - * - * @return const std::string& tile template. - */ - const std::string& tileTemplate() const; - - /** - * @brief Gets the previously set (or default) tile domain name. - * - * @return const std::string& domain name. - */ - const std::string& tileDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& tileVersionPrefix() const; - - /** - * @brief Sets the access token parameter name. - * - * @param apiKeyParameterName The parameter name. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withApiKeyParameterName(std::string apiKeyParameterName); - - /** - * @brief Gets the previously set (or default) apiKeyParameterName. - * - * @return const std::string& apiKeyParameterName. - */ - const std::string& apiKeyParameterName() const; - - TileServerOptions& setRequiresApiKey(bool apiKeyRequired); - - /** - * @brief Whether the tile server requires API key - * - * @return const bool true if API key is required - */ - bool requiresApiKey() const; - /** - * @brief Gets the default styles. - */ - const std::vector defaultStyles() const; - - /** - * @brief Sets the collection default styles. - * - * @param styles The style set. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withDefaultStyles(std::vector styles); - - /** - * @brief Sets the default style by name. The style name must exists in defaultStyles collection - * - * @param defaultStyle The style name - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withDefaultStyle(std::string defaultStyle); - - /** - * @brief Get the default style name - */ - const std::string& defaultStyle() const; - - /** - * @brief Get the default configuration - */ - static TileServerOptions DefaultConfiguration(); - - /** - * @brief Get the tile server options configured for MapLibre. - */ - static TileServerOptions MapLibreConfiguration(); - - /** - * @brief Get the tile server options configured for Mapbox. - */ - static TileServerOptions MapboxConfiguration(); - - /** - * @brief Get the tile server options configured for MapTiler. - */ - static TileServerOptions MapTilerConfiguration(); - - private: - class Impl; - std::unique_ptr impl_; - }; +class TileServerOptions final { +public: + /** + * @brief Constructs a TileServerOptions object with default values. + */ + explicit TileServerOptions(); + ~TileServerOptions(); + + // movable + TileServerOptions(TileServerOptions&& options) noexcept; + TileServerOptions& operator=(TileServerOptions&& options) noexcept; + + // copyable + TileServerOptions(const TileServerOptions&); + + TileServerOptions clone() const; + + /** + * @brief Sets the API base URL. + * + * @param baseURL API base URL. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withBaseURL(std::string baseURL); + + /** + * @brief Gets the previously set (or default) API base URL. + * + * @return const std::string& API base URL. + */ + const std::string& baseURL() const; + + /** + * @brief Sets the scheme alias for the tile server. For example maptiler:// for MapTiler. + * + * @param alias The URI alias. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withUriSchemeAlias(std::string alias); + + /** + * @brief Gets the previously set (or default) tile server URI alias. + * + * @return const std::string& scheme alias. + */ + const std::string& uriSchemeAlias() const; + + /** + * @brief Sets the template for sources. + * + * @param sourceTemplate The source template. + * @param domainName The domain name. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withSourceTemplate( + std::string sourceTemplate, std::string domainName, std::optional versionPrefix + ); + + /** + * @brief Gets the previously set (or default) source template. + * + * @return const std::string& source template. + */ + const std::string& sourceTemplate() const; + + /** + * @brief Gets the previously set (or default) source domain name + * + * @return const std::string& source domain name. + */ + const std::string& sourceDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& sourceVersionPrefix() const; + + /** + * @brief Sets the template for styles. + * + * @param styleTemplate The style template. + * @param domainName If set, the URL domain must contain the specified string to be matched as canonical style URL . + * + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withStyleTemplate( + std::string styleTemplate, std::string domainName, std::optional versionPrefix + ); + + /** + * @brief Gets the previously set (or default) style template. + * + * @return const std::string& style template. + */ + const std::string& styleTemplate() const; + + /** + * @brief Gets the previously set (or default) style domain name. + * + * @return const std::string& domain name. + */ + const std::string& styleDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& styleVersionPrefix() const; + + /** + * @brief Sets the template for sprites. + * @param domainName If set, the URL domain must contain the specified string to be matched as canonical sprite URL + * . + * + * @param spritesTemplate The sprites template. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withSpritesTemplate( + std::string spritesTemplate, std::string domainName, std::optional versionPrefix + ); + + /** + * @brief Gets the previously set (or default) sprites template. + * + * @return const std::string& sprites template. + */ + const std::string& spritesTemplate() const; + + /** + * @brief Gets the previously set (or default) sprites domain name. + * + * @return const std::string& domain name. + */ + const std::string& spritesDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& spritesVersionPrefix() const; + + /** + * @brief Sets the template for glyphs. + * + * @param glyphsTemplate The glyphs template. + * @param domainName If set, the URL domain must contain the specified string to be matched as canonical glyphs URL + * . + * + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withGlyphsTemplate( + std::string glyphsTemplate, std::string domainName, std::optional versionPrefix + ); + + /** + * @brief Gets the previously set (or default) glyphs template. + * + * @return const std::string& glyphs template. + */ + const std::string& glyphsTemplate() const; + + /** + * @brief Gets the previously set (or default) glyphs domain name. + * + * @return const std::string& domain name. + */ + const std::string& glyphsDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& glyphsVersionPrefix() const; + + /** + * @brief Sets the template for tiles. + * + * @param tileTemplate The tile template. + * @param domainName If set, the URL domain must contain the specified string to be matched as canonical tile URL . + * + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withTileTemplate( + std::string tileTemplate, std::string domainName, std::optional versionPrefix + ); + + /** + * @brief Gets the previously set (or default) tile template. + * + * @return const std::string& tile template. + */ + const std::string& tileTemplate() const; + + /** + * @brief Gets the previously set (or default) tile domain name. + * + * @return const std::string& domain name. + */ + const std::string& tileDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& tileVersionPrefix() const; + + /** + * @brief Sets the access token parameter name. + * + * @param apiKeyParameterName The parameter name. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withApiKeyParameterName(std::string apiKeyParameterName); + + /** + * @brief Gets the previously set (or default) apiKeyParameterName. + * + * @return const std::string& apiKeyParameterName. + */ + const std::string& apiKeyParameterName() const; + + TileServerOptions& setRequiresApiKey(bool apiKeyRequired); + + /** + * @brief Whether the tile server requires API key + * + * @return const bool true if API key is required + */ + bool requiresApiKey() const; + /** + * @brief Gets the default styles. + */ + const std::vector defaultStyles() const; + + /** + * @brief Sets the collection default styles. + * + * @param styles The style set. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withDefaultStyles(std::vector styles); + + /** + * @brief Sets the default style by name. The style name must exists in defaultStyles collection + * + * @param defaultStyle The style name + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withDefaultStyle(std::string defaultStyle); + + /** + * @brief Get the default style name + */ + const std::string& defaultStyle() const; + + /** + * @brief Get the default configuration + */ + static TileServerOptions DefaultConfiguration(); + + /** + * @brief Get the tile server options configured for MapLibre. + */ + static TileServerOptions MapLibreConfiguration(); + + /** + * @brief Get the tile server options configured for Mapbox. + */ + static TileServerOptions MapboxConfiguration(); + + /** + * @brief Get the tile server options configured for MapTiler. + */ + static TileServerOptions MapTilerConfiguration(); + +private: + class Impl; + std::unique_ptr impl_; +}; } // namespace mbgl diff --git a/include/mbgl/util/tileset.hpp b/include/mbgl/util/tileset.hpp index 4bac337ffe3..c27b337cfc2 100644 --- a/include/mbgl/util/tileset.hpp +++ b/include/mbgl/util/tileset.hpp @@ -14,8 +14,14 @@ namespace mbgl { class Tileset { public: - enum class Scheme : bool { XYZ, TMS }; - enum class DEMEncoding : bool { Mapbox, Terrarium }; + enum class Scheme : bool { + XYZ, + TMS + }; + enum class DEMEncoding : bool { + Mapbox, + Terrarium + }; std::vector tiles; Range zoomRange; @@ -25,11 +31,13 @@ class Tileset { DEMEncoding encoding; std::optional bounds; - Tileset(std::vector tiles_ = std::vector(), - Range zoomRange_ = {0, util::DEFAULT_MAX_ZOOM}, - std::string attribution_ = {}, - Scheme scheme_ = Scheme::XYZ, - DEMEncoding encoding_ = DEMEncoding::Mapbox) + Tileset( + std::vector tiles_ = std::vector(), + Range zoomRange_ = {0, util::DEFAULT_MAX_ZOOM}, + std::string attribution_ = {}, + Scheme scheme_ = Scheme::XYZ, + DEMEncoding encoding_ = DEMEncoding::Mapbox + ) : tiles(std::move(tiles_)), zoomRange(zoomRange_), attribution(std::move(attribution_)), @@ -39,13 +47,11 @@ class Tileset { // TileJSON also includes center and zoom but they are not used by mbgl. friend bool operator==(const Tileset& lhs, const Tileset& rhs) { - return std::tie(lhs.tiles, lhs.zoomRange, lhs.attribution, lhs.scheme, lhs.bounds) - == std::tie(rhs.tiles, rhs.zoomRange, rhs.attribution, rhs.scheme, rhs.bounds); + return std::tie(lhs.tiles, lhs.zoomRange, lhs.attribution, lhs.scheme, lhs.bounds) == + std::tie(rhs.tiles, rhs.zoomRange, rhs.attribution, rhs.scheme, rhs.bounds); } - friend bool operator!=(const Tileset& lhs, const Tileset& rhs) { - return !(lhs == rhs); - } + friend bool operator!=(const Tileset& lhs, const Tileset& rhs) { return !(lhs == rhs); } }; } // namespace mbgl diff --git a/include/mbgl/util/traits.hpp b/include/mbgl/util/traits.hpp index 75ae6f315e7..e564fea4942 100644 --- a/include/mbgl/util/traits.hpp +++ b/include/mbgl/util/traits.hpp @@ -7,23 +7,30 @@ namespace mbgl { -template +template constexpr auto underlying_type(T t) -> typename std::underlying_type_t { return typename std::underlying_type_t(t); } -template struct is_utf16char_like: std::false_type {}; -template struct is_utf16char_like: is_utf16char_like {}; -template <> struct is_utf16char_like: std::true_type {}; -template <> struct is_utf16char_like: std::true_type {}; -template <> struct is_utf16char_like: std::true_type {}; +template +struct is_utf16char_like : std::false_type {}; +template +struct is_utf16char_like : is_utf16char_like {}; +template <> +struct is_utf16char_like : std::true_type {}; +template <> +struct is_utf16char_like : std::true_type {}; +template <> +struct is_utf16char_like : std::true_type {}; -template using is_utf16char_like_pointer = std::integral_constant - && is_utf16char_like::type>::value>; +template +using is_utf16char_like_pointer = std:: + integral_constant && is_utf16char_like::type>::value>; template -typename std::enable_if::value && is_utf16char_like_pointer::value, OutPointer>::type utf16char_cast(InChar *in) -{ +typename std::enable_if::value && is_utf16char_like_pointer::value, OutPointer>:: + type + utf16char_cast(InChar *in) { return reinterpret_cast(in); } diff --git a/include/mbgl/util/unitbezier.hpp b/include/mbgl/util/unitbezier.hpp index e55fcc21e64..e6fcf3fbf39 100644 --- a/include/mbgl/util/unitbezier.hpp +++ b/include/mbgl/util/unitbezier.hpp @@ -34,17 +34,14 @@ namespace util { struct UnitBezier { /// Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). constexpr UnitBezier(double p1x, double p1y, double p2x, double p2y) - : cx(3.0 * p1x) - , bx(3.0 * (p2x - p1x) - (3.0 * p1x)) - , ax(1.0 - (3.0 * p1x) - (3.0 * (p2x - p1x) - (3.0 * p1x))) - , cy(3.0 * p1y) - , by(3.0 * (p2y - p1y) - (3.0 * p1y)) - , ay(1.0 - (3.0 * p1y) - (3.0 * (p2y - p1y) - (3.0 * p1y))) { - } + : cx(3.0 * p1x), + bx(3.0 * (p2x - p1x) - (3.0 * p1x)), + ax(1.0 - (3.0 * p1x) - (3.0 * (p2x - p1x) - (3.0 * p1x))), + cy(3.0 * p1y), + by(3.0 * (p2y - p1y) - (3.0 * p1y)), + ay(1.0 - (3.0 * p1y) - (3.0 * (p2y - p1y) - (3.0 * p1y))) {} - std::pair getP1() const { - return { cx / 3.0, cy / 3.0 }; - } + std::pair getP1() const { return {cx / 3.0, cy / 3.0}; } std::pair getP2() const { return { @@ -58,13 +55,9 @@ struct UnitBezier { return ((ax * t + bx) * t + cx) * t; } - double sampleCurveY(double t) const { - return ((ay * t + by) * t + cy) * t; - } + double sampleCurveY(double t) const { return ((ay * t + by) * t + cy) * t; } - double sampleCurveDerivativeX(double t) const { - return (3.0 * ax * t + 2.0 * bx) * t + cx; - } + double sampleCurveDerivativeX(double t) const { return (3.0 * ax * t + 2.0 * bx) * t + cx; } /// Given an x value, find a parametric value it came from. double solveCurveX(double x, double epsilon) const { @@ -78,11 +71,9 @@ struct UnitBezier { // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; ++i) { x2 = sampleCurveX(t2) - x; - if (fabs (x2) < epsilon) - return t2; + if (fabs(x2) < epsilon) return t2; d2 = sampleCurveDerivativeX(t2); - if (fabs(d2) < 1e-6) - break; + if (fabs(d2) < 1e-6) break; t2 = t2 - x2 / d2; } @@ -91,15 +82,12 @@ struct UnitBezier { t1 = 1.0; t2 = x; - if (t2 < t0) - return t0; - if (t2 > t1) - return t1; + if (t2 < t0) return t0; + if (t2 > t1) return t1; while (t0 < t1) { x2 = sampleCurveX(t2); - if (fabs(x2 - x) < epsilon) - return t2; + if (fabs(x2 - x) < epsilon) return t2; if (x > x2) t0 = t2; else @@ -111,13 +99,10 @@ struct UnitBezier { return t2; } - double solve(double x, double epsilon) const { - return sampleCurveY(solveCurveX(x, epsilon)); - } - + double solve(double x, double epsilon) const { return sampleCurveY(solveCurveX(x, epsilon)); } + bool operator==(const UnitBezier& rhs) const { - return std::tie(cx, bx, ax, cy, by, ay) == - std::tie(rhs.cx, rhs.bx, rhs.ax, rhs.cy, rhs.by, rhs.ay); + return std::tie(cx, bx, ax, cy, by, ay) == std::tie(rhs.cx, rhs.bx, rhs.ax, rhs.cy, rhs.by, rhs.ay); } private: diff --git a/include/mbgl/util/work_task_impl.hpp b/include/mbgl/util/work_task_impl.hpp index c194a50189b..7b504f2564a 100644 --- a/include/mbgl/util/work_task_impl.hpp +++ b/include/mbgl/util/work_task_impl.hpp @@ -11,10 +11,9 @@ template class WorkTaskImpl : public WorkTask { public: WorkTaskImpl(F f, P p, std::shared_ptr> canceled_) - : canceled(std::move(canceled_)), - func(std::move(f)), - params(std::move(p)) { - } + : canceled(std::move(canceled_)), + func(std::move(f)), + params(std::move(p)) {} void operator()() override { // Lock the mutex while processing so that cancel() will block. @@ -57,9 +56,8 @@ std::shared_ptr WorkTask::make(Fn&& fn, Args&&... args) { auto tuple = std::make_tuple(std::forward(args)...); return std::make_shared, decltype(tuple)>>( - std::forward(fn), - std::move(tuple), - flag); + std::forward(fn), std::move(tuple), flag + ); } } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp old mode 100755 new mode 100644 index e2d06483854..2d8880a3e64 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp @@ -13,8 +13,8 @@ namespace android { class AndroidGLRenderableResource final : public mbgl::gl::RenderableResource { public: - AndroidGLRenderableResource(AndroidRendererBackend& backend_) : backend(backend_) { - } + AndroidGLRenderableResource(AndroidRendererBackend& backend_) + : backend(backend_) {} void bind() override { assert(gfx::BackendScope::exists()); @@ -28,8 +28,7 @@ class AndroidGLRenderableResource final : public mbgl::gl::RenderableResource { AndroidRendererBackend::AndroidRendererBackend() : gl::RendererBackend(gfx::ContextMode::Unique), - mbgl::gfx::Renderable({ 64, 64 }, std::make_unique(*this)) { -} + mbgl::gfx::Renderable({64, 64}, std::make_unique(*this)) {} AndroidRendererBackend::~AndroidRendererBackend() = default; @@ -44,7 +43,7 @@ void AndroidRendererBackend::updateViewPort() { } void AndroidRendererBackend::resizeFramebuffer(int width, int height) { - size = { static_cast(width), static_cast(height) }; + size = {static_cast(width), static_cast(height)}; } PremultipliedImage AndroidRendererBackend::readFramebuffer() { @@ -64,4 +63,4 @@ void AndroidRendererBackend::markContextLost() { } } // namespace android -} // namspace mbgl +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp old mode 100755 new mode 100644 index f06f38e688f..cdd9df9511c --- a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp @@ -21,9 +21,7 @@ class AndroidRendererBackend : public gl::RendererBackend, public mbgl::gfx::Ren // mbgl::gfx::RendererBackend implementation public: - mbgl::gfx::Renderable& getDefaultRenderable() override { - return *this; - } + mbgl::gfx::Renderable& getDefaultRenderable() override { return *this; } protected: void activate() override { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.cpp index da6d979c377..f42007cd33b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.cpp @@ -18,37 +18,24 @@ namespace android { class ForwardingRendererObserver : public RendererObserver { public: ForwardingRendererObserver(util::RunLoop& mapRunLoop, RendererObserver& delegate_) - : mailbox(std::make_shared(mapRunLoop)) - , delegate(delegate_, mailbox) { - } + : mailbox(std::make_shared(mapRunLoop)), + delegate(delegate_, mailbox) {} - ~ForwardingRendererObserver() { - mailbox->close(); - } + ~ForwardingRendererObserver() { mailbox->close(); } - void onInvalidate() override { - delegate.invoke(&RendererObserver::onInvalidate); - } + void onInvalidate() override { delegate.invoke(&RendererObserver::onInvalidate); } - void onResourceError(std::exception_ptr err) override { - delegate.invoke(&RendererObserver::onResourceError, err); - } + void onResourceError(std::exception_ptr err) override { delegate.invoke(&RendererObserver::onResourceError, err); } - void onWillStartRenderingMap() override { - delegate.invoke(&RendererObserver::onWillStartRenderingMap); - } + void onWillStartRenderingMap() override { delegate.invoke(&RendererObserver::onWillStartRenderingMap); } - void onWillStartRenderingFrame() override { - delegate.invoke(&RendererObserver::onWillStartRenderingFrame); - } + void onWillStartRenderingFrame() override { delegate.invoke(&RendererObserver::onWillStartRenderingFrame); } void onDidFinishRenderingFrame(RenderMode mode, bool repaintNeeded, bool placementChanged) override { delegate.invoke(&RendererObserver::onDidFinishRenderingFrame, mode, repaintNeeded, placementChanged); } - void onDidFinishRenderingMap() override { - delegate.invoke(&RendererObserver::onDidFinishRenderingMap); - } + void onDidFinishRenderingMap() override { delegate.invoke(&RendererObserver::onDidFinishRenderingMap); } void onStyleImageMissing(const std::string& id, const StyleImageMissingCallback& done) override { delegate.invoke(&RendererObserver::onStyleImageMissing, id, done); @@ -64,13 +51,12 @@ class ForwardingRendererObserver : public RendererObserver { }; AndroidRendererFrontend::AndroidRendererFrontend(MapRenderer& mapRenderer_) - : mapRenderer(mapRenderer_) - , mapRunLoop(util::RunLoop::Get()) - , updateAsyncTask(std::make_unique([this]() { - mapRenderer.update(std::move(updateParams)); - mapRenderer.requestRender(); - })) { -} + : mapRenderer(mapRenderer_), + mapRunLoop(util::RunLoop::Get()), + updateAsyncTask(std::make_unique([this]() { + mapRenderer.update(std::move(updateParams)); + mapRenderer.requestRender(); + })) {} AndroidRendererFrontend::~AndroidRendererFrontend() = default; @@ -79,7 +65,7 @@ void AndroidRendererFrontend::reset() { } void AndroidRendererFrontend::setObserver(RendererObserver& observer) { - assert (util::RunLoop::Get()); + assert(util::RunLoop::Get()); // Don't call the Renderer directly, but use MapRenderer#setObserver to make sure // the Renderer may be re-initialised without losing the RendererObserver reference. mapRenderer.setObserver(std::make_unique(*mapRunLoop, observer)); @@ -94,27 +80,30 @@ void AndroidRendererFrontend::reduceMemoryUse() { mapRenderer.actor().invoke(&Renderer::reduceMemoryUse); } -std::vector AndroidRendererFrontend::querySourceFeatures(const std::string& sourceID, - const SourceQueryOptions& options) const { +std::vector AndroidRendererFrontend::querySourceFeatures( + const std::string& sourceID, const SourceQueryOptions& options +) const { // Waits for the result from the orchestration thread and returns return mapRenderer.actor().ask(&Renderer::querySourceFeatures, sourceID, options).get(); } -std::vector AndroidRendererFrontend::queryRenderedFeatures(const ScreenBox& box, - const RenderedQueryOptions& options) const { - +std::vector AndroidRendererFrontend::queryRenderedFeatures( + const ScreenBox& box, const RenderedQueryOptions& options +) const { // Select the right overloaded method - std::vector (Renderer::*fn)(const ScreenBox&, const RenderedQueryOptions&) const = &Renderer::queryRenderedFeatures; + std::vector (Renderer::*fn)(const ScreenBox&, const RenderedQueryOptions&) + const = &Renderer::queryRenderedFeatures; // Waits for the result from the orchestration thread and returns return mapRenderer.actor().ask(fn, box, options).get(); } -std::vector AndroidRendererFrontend::queryRenderedFeatures(const ScreenCoordinate& point, - const RenderedQueryOptions& options) const { - +std::vector AndroidRendererFrontend::queryRenderedFeatures( + const ScreenCoordinate& point, const RenderedQueryOptions& options +) const { // Select the right overloaded method - std::vector (Renderer::*fn)(const ScreenCoordinate&, const RenderedQueryOptions&) const = &Renderer::queryRenderedFeatures; + std::vector (Renderer::*fn)(const ScreenCoordinate&, const RenderedQueryOptions&) + const = &Renderer::queryRenderedFeatures; // Waits for the result from the orchestration thread and returns return mapRenderer.actor().ask(fn, point, options).get(); @@ -130,14 +119,17 @@ AnnotationIDs AndroidRendererFrontend::queryShapeAnnotations(const ScreenBox& bo return mapRenderer.actor().ask(&Renderer::queryShapeAnnotations, box).get(); } -FeatureExtensionValue AndroidRendererFrontend::queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const { - return mapRenderer.actor().ask(&Renderer::queryFeatureExtensions, sourceID, feature, extension, extensionField, args).get(); +FeatureExtensionValue AndroidRendererFrontend::queryFeatureExtensions( + const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args +) const { + return mapRenderer.actor() + .ask(&Renderer::queryFeatureExtensions, sourceID, feature, extension, extensionField, args) + .get(); } } // namespace android } // namespace mbgl - diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.hpp index 7302f6e42d8..0473e4acbf0 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.hpp @@ -29,7 +29,6 @@ namespace android { class AndroidRendererFrontend : public RendererFrontend { public: - AndroidRendererFrontend(MapRenderer&); ~AndroidRendererFrontend() override; @@ -45,14 +44,14 @@ class AndroidRendererFrontend : public RendererFrontend { AnnotationIDs queryPointAnnotations(const ScreenBox& box) const; AnnotationIDs queryShapeAnnotations(const ScreenBox& box) const; - // Feature extension query - FeatureExtensionValue - queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const; + FeatureExtensionValue queryFeatureExtensions( + const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args + ) const; // Memory void reduceMemoryUse(); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/marker.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/marker.hpp index b38a25b4fbd..3a657e36973 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/marker.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/marker.hpp @@ -12,7 +12,6 @@ namespace android { class Marker : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/annotations/Marker"; }; static mbgl::Point getPosition(jni::JNIEnv&, const jni::Object&); @@ -20,9 +19,7 @@ class Marker : private mbgl::util::noncopyable { static std::string getIconId(jni::JNIEnv&, const jni::Object&); static void registerNative(jni::JNIEnv&); - }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/multi_point.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/multi_point.hpp index 20f1b3eaf23..5755bbe3e4e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/multi_point.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/multi_point.hpp @@ -10,24 +10,22 @@ namespace mbgl { namespace android { class MultiPoint : protected mbgl::util::noncopyable { - protected: + template + static Geometry toGeometry(JNIEnv& env, const jni::Object& pointsList) { + auto jarray = java::util::List::toArray(env, pointsList); - template - static Geometry toGeometry(JNIEnv& env, const jni::Object& pointsList) { - auto jarray = java::util::List::toArray(env, pointsList); - - std::size_t size = jarray.Length(env); + std::size_t size = jarray.Length(env); - Geometry geometry; - geometry.reserve(size); + Geometry geometry; + geometry.reserve(size); - for (std::size_t i = 0; i < size; i++) { - geometry.push_back(LatLng::getGeometry(env, jarray.Get(env, i))); - } + for (std::size_t i = 0; i < size; i++) { + geometry.push_back(LatLng::getGeometry(env, jarray.Get(env, i))); + } - return geometry; - } + return geometry; + } }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.cpp index f22cffb1007..95d9f9a0682 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.cpp @@ -13,9 +13,7 @@ mbgl::FillAnnotation Polygon::toAnnotation(jni::JNIEnv& env, const jni::Object

(env, "fillColor"); static auto strokeColor = javaClass.GetField(env, "strokeColor"); - mbgl::Polygon geometry { - MultiPoint::toGeometry>(env, polygon.Get(env, points)) - }; + mbgl::Polygon geometry{MultiPoint::toGeometry>(env, polygon.Get(env, points))}; auto jHoleListsArray = java::util::List::toArray(env, polygon.Get(env, holes)); @@ -24,7 +22,7 @@ mbgl::FillAnnotation Polygon::toAnnotation(jni::JNIEnv& env, const jni::Object

>(env, jHoleListsArray.Get(env, i))); } - mbgl::FillAnnotation annotation { geometry }; + mbgl::FillAnnotation annotation{geometry}; annotation.opacity = polygon.Get(env, alpha); annotation.color = *conversion::convert(env, polygon.Get(env, fillColor)); annotation.outlineColor = *conversion::convert(env, polygon.Get(env, strokeColor)); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.hpp index bc21878ef34..69c44163678 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.hpp @@ -16,6 +16,5 @@ class Polygon : private MultiPoint { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.cpp index d6161e856e0..d8ab30d050f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.cpp @@ -12,9 +12,7 @@ mbgl::LineAnnotation Polyline::toAnnotation(jni::JNIEnv& env, const jni::Object< static auto color = javaClass.GetField(env, "color"); static auto width = javaClass.GetField(env, "width"); - mbgl::LineAnnotation annotation { - MultiPoint::toGeometry>(env, polyline.Get(env, points)) - }; + mbgl::LineAnnotation annotation{MultiPoint::toGeometry>(env, polyline.Get(env, points))}; annotation.opacity = polyline.Get(env, alpha); annotation.color = *conversion::convert(env, polyline.Get(env, color)); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.hpp index 6178e98cfc2..79335450337 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.hpp @@ -16,6 +16,5 @@ class Polyline : private MultiPoint { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager.hpp index b87d1895144..8a0fc76e79a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager.hpp @@ -5,9 +5,7 @@ namespace android { class AssetManager { public: - static constexpr auto Name() { - return "android/content/res/AssetManager"; - }; + static constexpr auto Name() { return "android/content/res/AssetManager"; }; }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.cpp index 1c9e4f99b1b..394237bb293 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.cpp @@ -16,10 +16,15 @@ namespace mbgl { class AssetManagerFileSource::Impl { public: - Impl(ActorRef, AAssetManager* assetManager_, const ResourceOptions resourceOptions_, const ClientOptions clientOptions_) : - resourceOptions(resourceOptions_.clone()), - clientOptions(clientOptions_.clone()), - assetManager(assetManager_) {} + Impl( + ActorRef, + AAssetManager* assetManager_, + const ResourceOptions resourceOptions_, + const ClientOptions clientOptions_ + ) + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()), + assetManager(assetManager_) {} void request(const std::string& url, ActorRef req) { // Note: AssetManager already prepends "assets" to the filename. @@ -29,31 +34,25 @@ class AssetManagerFileSource::Impl { if (AAsset* asset = AAssetManager_open(assetManager, path.c_str(), AASSET_MODE_BUFFER)) { response.data = std::make_shared( - reinterpret_cast(AAsset_getBuffer(asset)), AAsset_getLength64(asset)); + reinterpret_cast(AAsset_getBuffer(asset)), AAsset_getLength64(asset) + ); AAsset_close(asset); } else { - response.error = std::make_unique(Response::Error::Reason::NotFound, - "Could not read asset"); + response.error = std::make_unique( + Response::Error::Reason::NotFound, "Could not read asset" + ); } req.invoke(&FileSourceRequest::setResponse, response); } - void setResourceOptions(ResourceOptions options) { - resourceOptions = options; - } + void setResourceOptions(ResourceOptions options) { resourceOptions = options; } - ResourceOptions getResourceOptions() { - return resourceOptions.clone(); - } + ResourceOptions getResourceOptions() { return resourceOptions.clone(); } - void setClientOptions(ClientOptions options) { - clientOptions = options; - } + void setClientOptions(ClientOptions options) { clientOptions = options; } - ClientOptions getClientOptions() { - return clientOptions.clone(); - } + ClientOptions getClientOptions() { return clientOptions.clone(); } private: AAssetManager* assetManager; @@ -61,17 +60,20 @@ class AssetManagerFileSource::Impl { ClientOptions clientOptions; }; -AssetManagerFileSource::AssetManagerFileSource(jni::JNIEnv& env, - const jni::Object& assetManager_, - const ResourceOptions resourceOptions, - const ClientOptions clientOptions) +AssetManagerFileSource::AssetManagerFileSource( + jni::JNIEnv& env, + const jni::Object& assetManager_, + const ResourceOptions resourceOptions, + const ClientOptions clientOptions +) : assetManager(jni::NewGlobal(env, assetManager_)), impl(std::make_unique>( util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), "AssetManagerFileSource", AAssetManager_fromJava(&env, jni::Unwrap(assetManager.get())), resourceOptions.clone(), - clientOptions.clone())) {} + clientOptions.clone() + )) {} AssetManagerFileSource::~AssetManagerFileSource() = default; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.hpp index edfe0a8e4b6..29a403611c4 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.hpp @@ -11,12 +11,15 @@ namespace mbgl { namespace util { -template class Thread; +template +class Thread; } // namespace util class AssetManagerFileSource : public FileSource { public: - AssetManagerFileSource(jni::JNIEnv&, const jni::Object&, const ResourceOptions, const ClientOptions); + AssetManagerFileSource( + jni::JNIEnv&, const jni::Object&, const ResourceOptions, const ClientOptions + ); ~AssetManagerFileSource() override; std::unique_ptr request(const Resource&, Callback) override; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.cpp index 9c13f1f7490..cd208ddf45e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.cpp @@ -8,34 +8,34 @@ namespace mbgl { namespace android { - /** - * Invoked when the construction is initiated from the jvm - */ - ConnectivityListener::ConnectivityListener(jni::JNIEnv&) {} - - ConnectivityListener::~ConnectivityListener() {} - - void ConnectivityListener::onConnectivityStateChanged(jni::JNIEnv&, jni::jboolean connected) { - NetworkStatus::Set(connected ? NetworkStatus::Status::Online : NetworkStatus::Status::Offline); - } - - void ConnectivityListener::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - std::make_unique, - "initialize", - "finalize", - METHOD(&ConnectivityListener::onConnectivityStateChanged, "nativeOnConnectivityStateChanged") - ); - } +/** + * Invoked when the construction is initiated from the jvm + */ +ConnectivityListener::ConnectivityListener(jni::JNIEnv&) {} + +ConnectivityListener::~ConnectivityListener() {} + +void ConnectivityListener::onConnectivityStateChanged(jni::JNIEnv&, jni::jboolean connected) { + NetworkStatus::Set(connected ? NetworkStatus::Status::Online : NetworkStatus::Status::Offline); +} + +void ConnectivityListener::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + std::make_unique, + "initialize", + "finalize", + METHOD(&ConnectivityListener::onConnectivityStateChanged, "nativeOnConnectivityStateChanged") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.hpp index a09507c0f7a..9a0cfd21486 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.hpp @@ -9,7 +9,6 @@ namespace android { class ConnectivityListener : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/net/NativeConnectivityListener"; }; static void registerNative(jni::JNIEnv&); @@ -22,7 +21,6 @@ class ConnectivityListener : private mbgl::util::noncopyable { ~ConnectivityListener(); void onConnectivityStateChanged(jni::JNIEnv&, jni::jboolean); - }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/collection.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/collection.cpp index 954a161baff..3137c832f62 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/collection.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/collection.cpp @@ -27,6 +27,6 @@ jni::Local> toArray(JNIEnv& env, const std::vector toVector(JNIEnv& env, const jni::Array& array); jni::Local> toArray(JNIEnv& env, const std::vector&); -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.cpp index ce85943e61e..5731800653a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.cpp @@ -7,11 +7,11 @@ namespace conversion { Result Converter::operator()(jni::JNIEnv&, const int& color) const { float r = (color >> 16) & 0xFF; float g = (color >> 8) & 0xFF; - float b = (color) & 0xFF; + float b = (color)&0xFF; float a = (color >> 24) & 0xFF; - return { mbgl::Color( r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f ) }; + return {mbgl::Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f)}; } } // namespace conversion -} // namespace style +} // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.hpp index 2b4144b933e..aa61dce57d9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.hpp @@ -14,5 +14,5 @@ struct Converter { }; } // namespace conversion -} // namespace style +} // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.cpp index 292e1a4ace3..60af0973d35 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.cpp @@ -8,31 +8,45 @@ namespace mbgl { namespace android { namespace conversion { -Result>> Converter>, bool>::operator()(jni::JNIEnv& env, const bool& value) const { +Result>> Converter>, bool>::operator()( + jni::JNIEnv& env, const bool& value +) const { return jni::Box(env, value ? jni::jni_true : jni::jni_false); } -Result>> Converter>, float>::operator()(jni::JNIEnv& env, const float& value) const { +Result>> Converter>, float>::operator()( + jni::JNIEnv& env, const float& value +) const { return jni::Box(env, value); } -Result>> Converter>, double>::operator()(jni::JNIEnv& env, const double& value) const { +Result>> Converter>, double>::operator()( + jni::JNIEnv& env, const double& value +) const { return jni::Box(env, value); } -Result>> Converter>, std::string>::operator()(jni::JNIEnv& env, const std::string& value) const { +Result>> Converter>, std::string>::operator()( + jni::JNIEnv& env, const std::string& value +) const { return jni::Make(env, value); } -Result>> Converter>, Color>::operator()(jni::JNIEnv& env, const Color& value) const { +Result>> Converter>, Color>::operator()( + jni::JNIEnv& env, const Color& value +) const { return jni::Make(env, value.stringify()); } -Result>> Converter>, style::expression::Formatted>::operator()(jni::JNIEnv& env, const style::expression::Formatted& value) const { +Result>> Converter>, style::expression::Formatted>::operator()( + jni::JNIEnv& env, const style::expression::Formatted& value +) const { return Formatted::New(env, value); } -Result>> Converter>, std::vector>::operator()(jni::JNIEnv& env, const std::vector& value) const { +Result>> Converter>, std::vector>::operator()( + jni::JNIEnv& env, const std::vector& value +) const { auto result = jni::Array::New(env, value.size()); for (std::size_t i = 0; i < value.size(); i++) { @@ -42,7 +56,9 @@ Result>> Converter>, std::vect return result; } -Result>> Converter>, std::vector>::operator()(jni::JNIEnv& env, const std::vector& value) const { +Result>> Converter>, std::vector>::operator()( + jni::JNIEnv& env, const std::vector& value +) const { auto result = jni::Array::New(env, value.size()); for (std::size_t i = 0; i < value.size(); i++) { @@ -52,7 +68,9 @@ Result>> Converter>, std::vect return result; } -Result>> Converter>, std::vector>::operator()(jni::JNIEnv& env, const std::vector& value) const { +Result>> Converter>, std::vector>::operator()( + jni::JNIEnv& env, const std::vector& value +) const { auto result = jni::Array::New(env, value.size()); for (std::size_t i = 0; i < value.size(); i++) { @@ -63,14 +81,17 @@ Result>> Converter>, std::vect } Result>> Converter>, style::expression::Image>::operator()( - jni::JNIEnv& env, const style::expression::Image& value) const { + jni::JNIEnv& env, const style::expression::Image& value +) const { return jni::Make(env, value.id()); } -Result>> Converter>, mbgl::style::Rotation>::operator()(jni::JNIEnv& env, const mbgl::style::Rotation& value) const { +Result>> Converter>, mbgl::style::Rotation>::operator()( + jni::JNIEnv& env, const mbgl::style::Rotation& value +) const { return jni::Box(env, value.getAngle()); } } // namespace conversion -} // namespace style +} // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.hpp index dc78d6f3656..c8ff5228ba4 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.hpp @@ -38,7 +38,7 @@ struct Converter>, double> { * All integrals. java is limited to 64 bit signed, so... * TODO: use BigDecimal for > 64 / unsigned? */ -template +template struct Converter>, T, typename std::enable_if::value>::type> { Result>> operator()(jni::JNIEnv& env, const T& value) const { return jni::Box(env, jni::jlong(value)); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/conversion.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/conversion.hpp index d1766f9755c..d9256c8d83e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/conversion.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/conversion.hpp @@ -10,16 +10,16 @@ namespace mbgl { namespace android { namespace conversion { -struct Error { std::string message; }; +struct Error { + std::string message; +}; template class Result : private variant { public: using variant::variant; - explicit operator bool() const { - return this->template is(); - } + explicit operator bool() const { return this->template is(); } T& operator*() { assert(this->template is()); @@ -40,8 +40,8 @@ class Result : private variant { template struct Converter; -template -Result convert(jni::JNIEnv& env, const V& value, Args&&...args) { +template +Result convert(jni::JNIEnv& env, const V& value, Args&&... args) { return Converter()(env, value, std::forward(args)...); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.cpp index dced5a141ef..fabb5a72c7f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.cpp @@ -20,39 +20,50 @@ namespace android { // FileSource // -FileSource::FileSource(jni::JNIEnv& _env, const jni::String& apiKey, const jni::String& _cachePath, const jni::Object& _options) -:activationCounter( std::optional(1)) { +FileSource::FileSource( + jni::JNIEnv& _env, + const jni::String& apiKey, + const jni::String& _cachePath, + const jni::Object& _options +) + : activationCounter(std::optional(1)) { std::string path = jni::Make(_env, _cachePath); mapbox::sqlite::setTempPath(path); mbgl::FileSourceManager::get()->registerFileSourceFactory( - mbgl::FileSourceType::Asset, [](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions) { + mbgl::FileSourceType::Asset, + [](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions) { auto env{android::AttachEnv()}; std::unique_ptr assetFileSource; if (android::Mapbox::hasInstance(*env)) { auto assetManager = android::Mapbox::getAssetManager(*env); - assetFileSource = std::make_unique(*env, assetManager, resourceOptions.clone(), clientOptions.clone()); + assetFileSource = std::make_unique( + *env, assetManager, resourceOptions.clone(), clientOptions.clone() + ); } return assetFileSource; - }); + } + ); auto tileServerOptions = TileServerOptions::getTileServerOptions(_env, _options); - resourceOptions - .withTileServerOptions(tileServerOptions) - .withApiKey(apiKey ? jni::Make(_env, apiKey) : "") - .withCachePath(path + DATABASE_FILE); + resourceOptions.withTileServerOptions(tileServerOptions) + .withApiKey(apiKey ? jni::Make(_env, apiKey) : "") + .withCachePath(path + DATABASE_FILE); // Create a core file sources // TODO: Split Android FileSource API to smaller interfaces - resourceLoader = - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions); + resourceLoader = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions + ); databaseSource = std::static_pointer_cast(std::shared_ptr( - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Database, resourceOptions, clientOptions))); - onlineSource = mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Network, resourceOptions, clientOptions); + mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Database, resourceOptions, clientOptions) + )); + onlineSource = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::Network, resourceOptions, clientOptions + ); } -FileSource::~FileSource() { -} +FileSource::~FileSource() {} void FileSource::setTileServerOptions(jni::JNIEnv& _env, const jni::Object& _options) { auto tileServerOptions = TileServerOptions::getTileServerOptions(_env, _options); @@ -96,7 +107,9 @@ jni::Local FileSource::getAPIBaseUrl(jni::JNIEnv& env) { return jni::Make(env, ""); } -void FileSource::setResourceTransform(jni::JNIEnv& env, const jni::Object& transformCallback) { +void FileSource::setResourceTransform( + jni::JNIEnv& env, const jni::Object& transformCallback +) { // Core could be built without support for network resource provider. if (!onlineSource) { ThrowNew(env, jni::FindClass(env, "java/lang/IllegalStateException"), "Online functionality is disabled."); @@ -112,16 +125,18 @@ void FileSource::setResourceTransform(jni::JNIEnv& env, const jni::Object(std::move(global))]( - mbgl::Resource::Kind kind, const std::string& url_, ResourceTransform::FinishedCallback cb) { + [callback = std::make_shared(std::move(global) + )](mbgl::Resource::Kind kind, const std::string& url_, ResourceTransform::FinishedCallback cb) { android::UniqueEnv _env = android::AttachEnv(); cb(FileSource::ResourceTransformCallback::onURL(*_env, *callback, int(kind), url_)); - }); + } + ); onlineSource->setResourceTransform( - {[actorRef = resourceTransform->self()]( - Resource::Kind kind, const std::string& url, ResourceTransform::FinishedCallback cb) { + {[actorRef = resourceTransform->self( + )](Resource::Kind kind, const std::string& url, ResourceTransform::FinishedCallback cb) { actorRef.invoke(&ResourceTransform::TransformCallback::operator(), kind, url, std::move(cb)); - }}); + }} + ); } else { // Reset the callback resourceTransform.reset(); @@ -129,16 +144,20 @@ void FileSource::setResourceTransform(jni::JNIEnv& env, const jni::Object& _callback) { +void FileSource::setResourceCachePath( + jni::JNIEnv& env, + const jni::String& path, + const jni::Object& _callback +) { if (!databaseSource) { ThrowNew(env, jni::FindClass(env, "java/lang/IllegalStateException"), "Offline functionality is disabled."); return; } if (pathChangeCallback) { - FileSource::ResourcesCachePathChangeCallback::onError(env, _callback, jni::Make(env, "Another resources cache path change is in progress")); + FileSource::ResourcesCachePathChangeCallback::onError( + env, _callback, jni::Make(env, "Another resources cache path change is in progress") + ); return; } @@ -150,9 +169,11 @@ void FileSource::setResourceCachePath(jni::JNIEnv& env, [this, callback = std::make_shared(std::move(global)), newPath] { android::UniqueEnv _env = android::AttachEnv(); FileSource::ResourcesCachePathChangeCallback::onSuccess( - *_env, *callback, jni::Make(*_env, newPath)); + *_env, *callback, jni::Make(*_env, newPath) + ); pathChangeCallback = {}; - }); + } + ); databaseSource->setDatabasePath(newPath + DATABASE_FILE, pathChangeCallback); } @@ -179,18 +200,19 @@ void FileSource::pause(jni::JNIEnv&) { } } -jni::jboolean FileSource::isResumed(jni::JNIEnv &) { - return (jboolean) (activationCounter > 0); +jni::jboolean FileSource::isResumed(jni::JNIEnv&) { + return (jboolean)(activationCounter > 0); } FileSource* FileSource::getNativePeer(jni::JNIEnv& env, const jni::Object& jFileSource) { static auto& javaClass = jni::Class::Singleton(env); static auto field = javaClass.GetField(env, "nativePtr"); - return reinterpret_cast(jFileSource.Get(env, field)); + return reinterpret_cast(jFileSource.Get(env, field)); } -mbgl::ResourceOptions FileSource::getSharedResourceOptions(jni::JNIEnv& env, - const jni::Object& jFileSource) { +mbgl::ResourceOptions FileSource::getSharedResourceOptions( + jni::JNIEnv& env, const jni::Object& jFileSource +) { FileSource* fileSource = FileSource::getNativePeer(env, jFileSource); // Core could be compiled without support for any sources. if (fileSource) { @@ -200,8 +222,7 @@ mbgl::ResourceOptions FileSource::getSharedResourceOptions(jni::JNIEnv& env, return {}; } -mbgl::ClientOptions FileSource::getSharedClientOptions(jni::JNIEnv& env, - const jni::Object& jFileSource) { +mbgl::ClientOptions FileSource::getSharedClientOptions(jni::JNIEnv& env, const jni::Object& jFileSource) { FileSource* fileSource = FileSource::getNativePeer(env, jFileSource); // Core could be compiled without support for any sources. if (fileSource) { @@ -213,20 +234,22 @@ mbgl::ClientOptions FileSource::getSharedClientOptions(jni::JNIEnv& env, // FileSource::ResourcesCachePathChangeCallback // -void FileSource::ResourcesCachePathChangeCallback::onSuccess(jni::JNIEnv& env, - const jni::Object& callback, - const jni::String& path) { +void FileSource::ResourcesCachePathChangeCallback::onSuccess( + jni::JNIEnv& env, const jni::Object& callback, const jni::String& path +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onSuccess"); + static auto method = javaClass.GetMethod(env, "onSuccess"); callback.Call(env, method, path); } -void FileSource::ResourcesCachePathChangeCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - const jni::String& message) { +void FileSource::ResourcesCachePathChangeCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + const jni::String& message +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, message); } @@ -240,37 +263,38 @@ void FileSource::registerNative(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer - jni::RegisterNativePeer(env, - javaClass, - "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&FileSource::setTileServerOptions, "setTileServerOptions"), - METHOD(&FileSource::getApiKey, "getApiKey"), - METHOD(&FileSource::setApiKey, "setApiKey"), - METHOD(&FileSource::setAPIBaseUrl, "setApiBaseUrl"), - METHOD(&FileSource::getAPIBaseUrl, "getApiBaseUrl"), - METHOD(&FileSource::setResourceTransform, "setResourceTransform"), - METHOD(&FileSource::setResourceCachePath, "setResourceCachePath"), - METHOD(&FileSource::resume, "activate"), - METHOD(&FileSource::pause, "deactivate"), - METHOD(&FileSource::isResumed, "isActivated")); + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&FileSource::setTileServerOptions, "setTileServerOptions"), + METHOD(&FileSource::getApiKey, "getApiKey"), + METHOD(&FileSource::setApiKey, "setApiKey"), + METHOD(&FileSource::setAPIBaseUrl, "setApiBaseUrl"), + METHOD(&FileSource::getAPIBaseUrl, "getApiBaseUrl"), + METHOD(&FileSource::setResourceTransform, "setResourceTransform"), + METHOD(&FileSource::setResourceCachePath, "setResourceCachePath"), + METHOD(&FileSource::resume, "activate"), + METHOD(&FileSource::pause, "deactivate"), + METHOD(&FileSource::isResumed, "isActivated") + ); } - // FileSource::ResourceTransformCallback // -std::string FileSource::ResourceTransformCallback::onURL(jni::JNIEnv& env, const jni::Object& callback, int kind, std::string url_) { +std::string FileSource::ResourceTransformCallback::onURL( + jni::JNIEnv& env, const jni::Object& callback, int kind, std::string url_ +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onURL"); + static auto method = javaClass.GetMethod(env, "onURL"); - return jni::Make(env, - callback.Call(env, method, kind, - jni::Make(env, url_))); + return jni::Make(env, callback.Call(env, method, kind, jni::Make(env, url_))); } } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.hpp index b5a9d15d5e8..e6cdda46fe7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.hpp @@ -13,7 +13,8 @@ namespace mbgl { -template class Actor; +template +class Actor; namespace android { @@ -23,25 +24,26 @@ namespace android { */ class FileSource { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/storage/FileSource"; }; struct ResourceTransformCallback { static constexpr auto Name() { return "com/mapbox/mapboxsdk/storage/FileSource$ResourceTransformCallback"; } - static std::string onURL(jni::JNIEnv&, const jni::Object&, int, std::string); + static std::string onURL( + jni::JNIEnv&, const jni::Object&, int, std::string + ); }; struct ResourcesCachePathChangeCallback { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/storage/FileSource$ResourcesCachePathChangeCallback";} + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/storage/FileSource$ResourcesCachePathChangeCallback"; + } - static void onSuccess(jni::JNIEnv&, - const jni::Object&, - const jni::String&); + static void + onSuccess(jni::JNIEnv&, const jni::Object&, const jni::String&); - static void onError(jni::JNIEnv&, - const jni::Object&, - const jni::String&); + static void + onError(jni::JNIEnv&, const jni::Object&, const jni::String&); }; FileSource(jni::JNIEnv&, const jni::String&, const jni::String&, const jni::Object&); @@ -60,7 +62,8 @@ class FileSource { void setResourceTransform(jni::JNIEnv&, const jni::Object&); - void setResourceCachePath(jni::JNIEnv&, const jni::String&, const jni::Object&); + void + setResourceCachePath(jni::JNIEnv&, const jni::String&, const jni::Object&); void resume(jni::JNIEnv&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature.cpp index afbf1ee11ed..aaa503a3b6d 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature.cpp @@ -12,17 +12,18 @@ using namespace gson; mbgl::GeoJSONFeature Feature::convert(jni::JNIEnv& env, const jni::Object& jFeature) { static auto& javaClass = jni::Class::Singleton(env); - static auto id = javaClass.GetMethod(env, "id"); - static auto geometry = javaClass.GetMethod ()>(env, "geometry"); - static auto properties = javaClass.GetMethod ()>(env, "properties"); + static auto id = javaClass.GetMethod(env, "id"); + static auto geometry = javaClass.GetMethod()>(env, "geometry"); + static auto properties = javaClass.GetMethod()>(env, "properties"); auto jId = jFeature.Call(env, id); using mbid = mapbox::feature::identifier; - return mbgl::GeoJSONFeature{Geometry::convert(env, jFeature.Call(env, geometry)), - JsonObject::convert(env, jFeature.Call(env, properties)), - jId ? mbid{jni::Make(env, jId)} : mbid{mapbox::feature::null_value}}; + return mbgl::GeoJSONFeature{ + Geometry::convert(env, jFeature.Call(env, geometry)), + JsonObject::convert(env, jFeature.Call(env, properties)), + jId ? mbid{jni::Make(env, jId)} : mbid{mapbox::feature::null_value}}; } /** @@ -30,35 +31,37 @@ mbgl::GeoJSONFeature Feature::convert(jni::JNIEnv& env, const jni::Object + template std::string operator()(const T& i) const { return util::toString(i); } - std::string operator()(const std::string& i) const { - return i; - } + std::string operator()(const std::string& i) const { return i; } - std::string operator()(const std::nullptr_t&) const { - return {}; - } + std::string operator()(const std::nullptr_t&) const { return {}; } - std::string operator()(const mapbox::feature::null_value_t&) const { - return {}; - } + std::string operator()(const mapbox::feature::null_value_t&) const { return {}; } }; jni::Local> convertFeature(jni::JNIEnv& env, const mbgl::GeoJSONFeature& value) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object, jni::Object, jni::String)>(env, "fromGeometry"); - - return javaClass.Call(env, method, + static auto method = + javaClass.GetStaticMethod(jni::Object, jni::Object, jni::String)>( + env, "fromGeometry" + ); + + return javaClass.Call( + env, + method, Geometry::New(env, value.geometry), JsonObject::New(env, value.properties), - jni::Make(env, value.id.is() ? std::string {} : value.id.match(FeatureIdVisitor()))); + jni::Make(env, value.id.is() ? std::string{} : value.id.match(FeatureIdVisitor())) + ); } -jni::Local>> Feature::convert(jni::JNIEnv& env, const std::vector& value) { +jni::Local>> Feature::convert( + jni::JNIEnv& env, const std::vector& value +) { auto features = jni::Array>::New(env, value.size()); for (size_t i = 0; i < value.size(); ++i) { @@ -68,8 +71,9 @@ jni::Local>> Feature::convert(jni::JNIEnv& env, return features; } -jni::Local>> Feature::convert(jni::JNIEnv& env, - const std::vector& value) { +jni::Local>> Feature::convert( + jni::JNIEnv& env, const std::vector& value +) { auto features = jni::Array>::New(env, value.size()); for (size_t i = 0; i < value.size(); ++i) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature_collection.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature_collection.cpp index f90d5226b78..e046343131b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature_collection.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature_collection.cpp @@ -6,7 +6,9 @@ namespace mbgl { namespace android { namespace geojson { -mbgl::FeatureCollection FeatureCollection::convert(jni::JNIEnv& env, const jni::Object& jCollection) { +mbgl::FeatureCollection FeatureCollection::convert( + jni::JNIEnv& env, const jni::Object& jCollection +) { auto collection = mbgl::FeatureCollection(); if (jCollection) { @@ -22,9 +24,11 @@ mbgl::FeatureCollection FeatureCollection::convert(jni::JNIEnv& env, const jni:: return collection; } -jni::Local> FeatureCollection::features(jni::JNIEnv& env, const jni::Object& jCollection) { +jni::Local> FeatureCollection::features( + jni::JNIEnv& env, const jni::Object& jCollection +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "features"); + static auto method = javaClass.GetMethod()>(env, "features"); return jCollection.Call(env, method); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry.cpp index 0598b9fc596..f2b362cb1c1 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry.cpp @@ -19,8 +19,7 @@ namespace geojson { */ class GeometryEvaluator { public: - - jni::JNIEnv& env; + jni::JNIEnv &env; jni::Local> operator()(const mbgl::EmptyGeometry &) const { // FIXME: mapbox-java needs to have its own Empty type. @@ -35,7 +34,7 @@ class GeometryEvaluator { return LineString::New(env, geometry); } - jni::Local> operator()(const mbgl::MultiLineString &geometry) const { + jni::Local> operator()(const mbgl::MultiLineString &geometry) const { return MultiLineString::New(env, geometry); } @@ -47,44 +46,46 @@ class GeometryEvaluator { return Polygon::New(env, geometry); } - jni::Local> operator()(const mbgl::MultiPolygon &geometry) const { + jni::Local> operator()(const mbgl::MultiPolygon &geometry) const { return MultiPolygon::New(env, geometry); } - jni::Local> operator()(const mapbox::geometry::geometry_collection &geometry) const { + jni::Local> operator()(const mapbox::geometry::geometry_collection &geometry) const { return GeometryCollection::New(env, geometry); } }; -jni::Local> Geometry::New(jni::JNIEnv& env, mbgl::Geometry geometry) { - GeometryEvaluator evaluator { env } ; +jni::Local> Geometry::New(jni::JNIEnv &env, mbgl::Geometry geometry) { + GeometryEvaluator evaluator{env}; return mbgl::Geometry::visit(geometry, evaluator); } -mbgl::Geometry Geometry::convert(jni::JNIEnv &env, const jni::Object& jGeometry) { +mbgl::Geometry Geometry::convert(jni::JNIEnv &env, const jni::Object &jGeometry) { auto type = Geometry::getType(env, jGeometry); if (type == Point::Type()) { - return { Point::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {Point::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == MultiPoint::Type()) { - return { MultiPoint::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {MultiPoint::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == LineString::Type()) { - return { LineString::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {LineString::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == MultiLineString::Type()) { - return { MultiLineString::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {MultiLineString::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == Polygon::Type()) { - return { Polygon::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {Polygon::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == MultiPolygon::Type()) { - return { MultiPolygon::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {MultiPolygon::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == GeometryCollection::Type()) { - return { GeometryCollection::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {GeometryCollection::convert( + env, jni::Cast(env, jni::Class::Singleton(env), jGeometry) + )}; } - throw std::runtime_error(std::string {"Unsupported GeoJSON type: " } + type); + throw std::runtime_error(std::string{"Unsupported GeoJSON type: "} + type); } -std::string Geometry::getType(jni::JNIEnv &env, const jni::Object& jGeometry) { - static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "type"); +std::string Geometry::getType(jni::JNIEnv &env, const jni::Object &jGeometry) { + static auto &javaClass = jni::Class::Singleton(env); + static auto method = javaClass.GetMethod(env, "type"); return jni::Make(env, jGeometry.Call(env, method)); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.cpp index cca909126d4..e4f7cbab318 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.cpp @@ -5,7 +5,9 @@ namespace mbgl { namespace android { namespace geojson { -jni::Local> GeometryCollection::New(jni::JNIEnv& env, const mapbox::geometry::geometry_collection& collection) { +jni::Local> GeometryCollection::New( + jni::JNIEnv& env, const mapbox::geometry::geometry_collection& collection +) { // Create an array of geometries auto jarray = jni::Array>::New(env, collection.size()); @@ -15,14 +17,18 @@ jni::Local> GeometryCollection::New(jni::JNIEnv& // create the GeometryCollection static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "fromGeometries"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromGeometries" + ); return javaClass.Call(env, method, java::util::Arrays::asList(env, jarray)); } -mapbox::geometry::geometry_collection GeometryCollection::convert(jni::JNIEnv &env, const jni::Object& jCollection) { +mapbox::geometry::geometry_collection GeometryCollection::convert( + jni::JNIEnv& env, const jni::Object& jCollection +) { // Get geometries static auto& javaClass = jni::Class::Singleton(env); - static auto getGeometries = javaClass.GetMethod ()>(env, "geometries"); + static auto getGeometries = javaClass.GetMethod()>(env, "geometries"); // Turn into array auto jarray = java::util::List::toArray(env, jCollection.Call(env, getGeometries)); @@ -38,7 +44,7 @@ mapbox::geometry::geometry_collection GeometryCollection::convert(jni::J return collection; } -void GeometryCollection::registerNative(jni::JNIEnv &env) { +void GeometryCollection::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.hpp index 9f02ac848d0..978d31c3869 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.hpp @@ -14,7 +14,8 @@ class GeometryCollection { static constexpr auto Name() { return "com/mapbox/geojson/GeometryCollection"; }; static constexpr auto Type() { return "GeometryCollection"; }; - static jni::Local> New(jni::JNIEnv&, const mapbox::geometry::geometry_collection&); + static jni::Local> + New(jni::JNIEnv&, const mapbox::geometry::geometry_collection&); static mapbox::geometry::geometry_collection convert(jni::JNIEnv&, const jni::Object&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.cpp index ae1345c9584..bde802d04f9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.cpp @@ -9,12 +9,14 @@ namespace geojson { jni::Local> LineString::New(jni::JNIEnv& env, const mbgl::LineString& lineString) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod(jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromLngLats" + ); return javaClass.Call(env, method, asPointsList(env, lineString)); } -mapbox::geojson::line_string LineString::convert(jni::JNIEnv &env, const jni::Object& jLineString) { +mapbox::geojson::line_string LineString::convert(jni::JNIEnv& env, const jni::Object& jLineString) { mapbox::geojson::line_string lineString; if (jLineString) { @@ -24,7 +26,9 @@ mapbox::geojson::line_string LineString::convert(jni::JNIEnv &env, const jni::Ob return lineString; } -mapbox::geojson::line_string LineString::convert(jni::JNIEnv &env, const jni::Object*/>& jPointList) { +mapbox::geojson::line_string LineString::convert( + jni::JNIEnv& env, const jni::Object*/>& jPointList +) { mapbox::geojson::line_string lineString; if (jPointList) { @@ -40,13 +44,15 @@ mapbox::geojson::line_string LineString::convert(jni::JNIEnv &env, const jni::Ob return lineString; } -jni::Local> LineString::coordinates(jni::JNIEnv &env, const jni::Object& jLineString) { +jni::Local> LineString::coordinates( + jni::JNIEnv& env, const jni::Object& jLineString +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jLineString.Call(env, method); } -void LineString::registerNative(jni::JNIEnv &env) { +void LineString::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.hpp index 906d809fa8d..63d2a1e197a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.hpp @@ -13,7 +13,6 @@ namespace mbgl { namespace android { namespace geojson { - class LineString { public: using SuperTag = Geometry; @@ -24,7 +23,7 @@ class LineString { static mapbox::geojson::line_string convert(jni::JNIEnv&, const jni::Object&); - static mapbox::geojson::line_string convert(jni::JNIEnv&, const jni::Object*/>&); + static mapbox::geojson::line_string convert(jni::JNIEnv&, const jni::Object*/>&); static jni::Local> coordinates(jni::JNIEnv&, const jni::Object&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.cpp index 1aaf53c01f2..439e417c8eb 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.cpp @@ -7,14 +7,20 @@ namespace mbgl { namespace android { namespace geojson { -jni::Local> MultiLineString::New(jni::JNIEnv& env, const mbgl::MultiLineString& multiLineString) { +jni::Local> MultiLineString::New( + jni::JNIEnv& env, const mbgl::MultiLineString& multiLineString +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromLngLats" + ); return javaClass.Call(env, method, asPointsListsList(env, multiLineString)); } -mapbox::geojson::multi_line_string MultiLineString::convert(jni::JNIEnv &env, const jni::Object& jMultiLineString) { +mapbox::geojson::multi_line_string MultiLineString::convert( + jni::JNIEnv& env, const jni::Object& jMultiLineString +) { mapbox::geojson::multi_line_string multiLineString; if (jMultiLineString) { @@ -24,7 +30,9 @@ mapbox::geojson::multi_line_string MultiLineString::convert(jni::JNIEnv &env, co return multiLineString; } -mapbox::geojson::multi_line_string MultiLineString::convert(jni::JNIEnv &env, const jni::Object>*/>& jPointListsList) { +mapbox::geojson::multi_line_string MultiLineString::convert( + jni::JNIEnv& env, const jni::Object>*/>& jPointListsList +) { mapbox::geojson::multi_line_string multiLineString; if (jPointListsList) { @@ -41,13 +49,15 @@ mapbox::geojson::multi_line_string MultiLineString::convert(jni::JNIEnv &env, co return multiLineString; } -jni::Local> MultiLineString::coordinates(jni::JNIEnv &env, const jni::Object& jLineString) { +jni::Local> MultiLineString::coordinates( + jni::JNIEnv& env, const jni::Object& jLineString +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jLineString.Call(env, method); } -void MultiLineString::registerNative(jni::JNIEnv &env) { +void MultiLineString::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.hpp index 65ce43bd1ff..d314ec5a9a6 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.hpp @@ -22,7 +22,8 @@ class MultiLineString { static mapbox::geojson::multi_line_string convert(jni::JNIEnv&, const jni::Object&); - static mapbox::geojson::multi_line_string convert(jni::JNIEnv&, const jni::Object>*/>&); + static mapbox::geojson::multi_line_string + convert(jni::JNIEnv&, const jni::Object>*/>&); static jni::Local> coordinates(jni::JNIEnv&, const jni::Object&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_point.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_point.cpp index d530ef721f5..71da30c533a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_point.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_point.cpp @@ -10,7 +10,9 @@ namespace geojson { jni::Local> MultiPoint::New(JNIEnv& env, const mbgl::MultiPoint& multiPoint) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod(jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromLngLats" + ); return javaClass.Call(env, method, asPointsList(env, multiPoint)); } @@ -20,19 +22,22 @@ mapbox::geojson::multi_point MultiPoint::convert(jni::JNIEnv& env, const jni::Ob if (jMultiPoint) { multiPoint = convertExplicit( - LineString::convert(env, MultiPoint::coordinates(env, jMultiPoint))); + LineString::convert(env, MultiPoint::coordinates(env, jMultiPoint)) + ); } return multiPoint; } -jni::Local> MultiPoint::coordinates(jni::JNIEnv& env, const jni::Object& jMultiPoint) { +jni::Local> MultiPoint::coordinates( + jni::JNIEnv& env, const jni::Object& jMultiPoint +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jMultiPoint.Call(env, method); } -void MultiPoint::registerNative(jni::JNIEnv &env) { +void MultiPoint::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_polygon.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_polygon.cpp index 3c5c3ec3383..0ffd58ecf4e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_polygon.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_polygon.cpp @@ -9,7 +9,9 @@ namespace geojson { jni::Local> MultiPolygon::New(JNIEnv& env, const mbgl::MultiPolygon& multiPolygon) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromLngLats" + ); auto jarray = jni::Array>::New(env, multiPolygon.size()); @@ -38,13 +40,15 @@ mapbox::geojson::multi_polygon MultiPolygon::convert(jni::JNIEnv& env, const jni return multiPolygon; } -jni::Local> MultiPolygon::coordinates(jni::JNIEnv& env, const jni::Object& jPolygon) { +jni::Local> MultiPolygon::coordinates( + jni::JNIEnv& env, const jni::Object& jPolygon +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jPolygon.Call(env, method); } -void MultiPolygon::registerNative(jni::JNIEnv &env) { +void MultiPolygon::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/point.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/point.cpp index 2000447c0fe..020d623858c 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/point.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/point.cpp @@ -6,26 +6,23 @@ namespace geojson { jni::Local> Point::New(jni::JNIEnv& env, const mbgl::Point& point) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::jdouble, jni::jdouble)>(env, "fromLngLat"); + static auto method = javaClass.GetStaticMethod(jni::jdouble, jni::jdouble)>(env, "fromLngLat"); return javaClass.Call(env, method, point.x, point.y); } -mbgl::Point Point::convert(jni::JNIEnv &env, const jni::Object& jPoint) { +mbgl::Point Point::convert(jni::JNIEnv& env, const jni::Object& jPoint) { static auto& javaClass = jni::Class::Singleton(env); - static auto longitude = javaClass.GetMethod(env, "longitude"); - static auto latitude = javaClass.GetMethod(env, "latitude"); + static auto longitude = javaClass.GetMethod(env, "longitude"); + static auto latitude = javaClass.GetMethod(env, "latitude"); if (!jPoint) { return {}; } - return { - jPoint.Call(env, longitude), - jPoint.Call(env, latitude) - }; + return {jPoint.Call(env, longitude), jPoint.Call(env, latitude)}; } -void Point::registerNative(jni::JNIEnv &env) { +void Point::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.cpp index 4437d134a8a..cc60f0cc0e0 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.cpp @@ -10,12 +10,14 @@ namespace geojson { jni::Local> Polygon::New(jni::JNIEnv& env, const mbgl::Polygon& polygon) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromLngLats" + ); return javaClass.Call(env, method, asPointsListsList(env, polygon)); } -mapbox::geojson::polygon Polygon::convert(jni::JNIEnv &env, const jni::Object& jPolygon) { +mapbox::geojson::polygon Polygon::convert(jni::JNIEnv& env, const jni::Object& jPolygon) { mapbox::geojson::polygon polygon; if (jPolygon) { @@ -25,7 +27,9 @@ mapbox::geojson::polygon Polygon::convert(jni::JNIEnv &env, const jni::Object>*/>& jPointListsList) { +mapbox::geojson::polygon Polygon::convert( + jni::JNIEnv& env, const jni::Object>*/>& jPointListsList +) { mapbox::geojson::polygon polygon; if (jPointListsList) { @@ -39,14 +43,13 @@ mapbox::geojson::polygon Polygon::convert(jni::JNIEnv &env, const jni::Object> Polygon::coordinates(jni::JNIEnv &env, const jni::Object& jPolygon) { +jni::Local> Polygon::coordinates(jni::JNIEnv& env, const jni::Object& jPolygon) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jPolygon.Call(env, method); } -void Polygon::registerNative(jni::JNIEnv &env) { +void Polygon::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.hpp index 8e1761fedaf..fc9986d1c7c 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.hpp @@ -8,7 +8,6 @@ #include - namespace mbgl { namespace android { namespace geojson { @@ -19,13 +18,14 @@ class Polygon { static constexpr auto Name() { return "com/mapbox/geojson/Polygon"; }; static constexpr auto Type() { return "Polygon"; }; - static jni::Local> New(jni::JNIEnv&, const mbgl::Polygon&); + static jni::Local> New(jni::JNIEnv &, const mbgl::Polygon &); - static mapbox::geojson::polygon convert(jni::JNIEnv &, const jni::Object&); + static mapbox::geojson::polygon convert(jni::JNIEnv &, const jni::Object &); - static mapbox::geojson::polygon convert(jni::JNIEnv&, const jni::Object>*/>&); + static mapbox::geojson::polygon + convert(jni::JNIEnv &, const jni::Object>*/> &); - static jni::Local> coordinates(jni::JNIEnv&, const jni::Object&); + static jni::Local> coordinates(jni::JNIEnv &, const jni::Object &); static void registerNative(jni::JNIEnv &); }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/util.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/util.hpp index 59154516fa4..243d22b9d55 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/util.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/util.hpp @@ -11,11 +11,11 @@ namespace geojson { // Clang 3.8 fails to implicitly convert matching types, so we'll have to do it explicitly. template To convertExplicit(From&& src) { - static_assert(std::is_same::container_type, - typename To::container_type>::value, - "container types do not match"); - static_assert(std::is_rvalue_reference::value, - "argument must be rvalue reference"); + static_assert( + std::is_same::container_type, typename To::container_type>::value, + "container types do not match" + ); + static_assert(std::is_rvalue_reference::value, "argument must be rvalue reference"); return *reinterpret_cast>(&src); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng.hpp index 30b7db1ef34..d44143d9234 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng.hpp @@ -11,7 +11,6 @@ namespace android { class LatLng : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/geometry/LatLng"; }; static jni::Local> New(jni::JNIEnv&, const mbgl::LatLng&); @@ -20,10 +19,8 @@ class LatLng : private mbgl::util::noncopyable { static mbgl::LatLng getLatLng(jni::JNIEnv&, const jni::Object&); - static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.cpp index cf534a06e4f..ca324883061 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.cpp @@ -16,8 +16,8 @@ mbgl::LatLngBounds LatLngBounds::getLatLngBounds(jni::JNIEnv& env, const jni::Ob static auto neLatField = javaClass.GetField(env, "latitudeNorth"); static auto neLonField = javaClass.GetField(env, "longitudeEast"); - mbgl::LatLng sw = { bounds.Get(env, swLatField), bounds.Get(env, swLonField) }; - mbgl::LatLng ne = { bounds.Get(env, neLatField), bounds.Get(env, neLonField) }; + mbgl::LatLng sw = {bounds.Get(env, swLatField), bounds.Get(env, swLonField)}; + mbgl::LatLng ne = {bounds.Get(env, neLatField), bounds.Get(env, neLonField)}; return mbgl::LatLngBounds::hull(sw, ne); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.hpp index d51026711d1..6016061af18 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.hpp @@ -11,7 +11,6 @@ namespace android { class LatLngBounds : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/geometry/LatLngBounds"; }; static jni::Local> New(jni::JNIEnv&, mbgl::LatLngBounds); @@ -21,6 +20,5 @@ class LatLngBounds : private mbgl::util::noncopyable { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.cpp index 1a1e49048bc..fd39e3118ad 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.cpp @@ -6,27 +6,31 @@ namespace android { jni::Local> LatLngQuad::New(jni::JNIEnv& env, std::array coordinates) { static auto& javaClass = jni::Class::Singleton(env); - static auto quadConstructor = javaClass.GetConstructor, jni::Object, jni::Object, jni::Object>(env); - return javaClass.New(env, quadConstructor, + static auto quadConstructor = + javaClass.GetConstructor, jni::Object, jni::Object, jni::Object>(env + ); + return javaClass.New( + env, + quadConstructor, LatLng::New(env, coordinates[0]), LatLng::New(env, coordinates[1]), LatLng::New(env, coordinates[2]), - LatLng::New(env, coordinates[3])); + LatLng::New(env, coordinates[3]) + ); } std::array LatLngQuad::getLatLngArray(jni::JNIEnv& env, const jni::Object& quad) { static auto& javaClass = jni::Class::Singleton(env); - static auto topLeftField = javaClass.GetField >(env, "topLeft"); - static auto topRightField = javaClass.GetField >(env, "topRight"); - static auto bottomRightField = javaClass.GetField >(env, "bottomRight"); - static auto bottomLeftField = javaClass.GetField >(env, "bottomLeft"); + static auto topLeftField = javaClass.GetField>(env, "topLeft"); + static auto topRightField = javaClass.GetField>(env, "topRight"); + static auto bottomRightField = javaClass.GetField>(env, "bottomRight"); + static auto bottomLeftField = javaClass.GetField>(env, "bottomLeft"); - return std::array < mbgl::LatLng, 4 > {{ - LatLng::getLatLng(env, quad.Get(env, topLeftField)), - LatLng::getLatLng(env, quad.Get(env, topRightField)), - LatLng::getLatLng(env, quad.Get(env, bottomRightField)), - LatLng::getLatLng(env, quad.Get(env, bottomLeftField)) - }}; + return std::array{ + {LatLng::getLatLng(env, quad.Get(env, topLeftField)), + LatLng::getLatLng(env, quad.Get(env, topRightField)), + LatLng::getLatLng(env, quad.Get(env, bottomRightField)), + LatLng::getLatLng(env, quad.Get(env, bottomLeftField))}}; } void LatLngQuad::registerNative(jni::JNIEnv& env) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.hpp index f6560b57ba3..f5d93c731e3 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.hpp @@ -12,7 +12,6 @@ namespace android { class LatLngQuad : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/geometry/LatLngQuad"; }; static jni::Local> New(jni::JNIEnv&, std::array); @@ -22,6 +21,5 @@ class LatLngQuad : private mbgl::util::noncopyable { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/pointf.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/pointf.hpp index 899468b8e3f..fda823f02f9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/pointf.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/pointf.hpp @@ -9,7 +9,6 @@ namespace android { class PointF : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "android/graphics/PointF"; }; static jni::Local> New(jni::JNIEnv&, float, float); @@ -19,6 +18,5 @@ class PointF : private mbgl::util::noncopyable { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/rectf.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/rectf.hpp index ba611f22622..5f3126295bc 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/rectf.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/rectf.hpp @@ -9,7 +9,6 @@ namespace android { class RectF : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "android/graphics/RectF"; }; static float getLeft(jni::JNIEnv&, const jni::Object&); @@ -23,6 +22,5 @@ class RectF : private mbgl::util::noncopyable { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_array.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_array.cpp index 8ffa658b764..bcd9c22c435 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_array.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_array.cpp @@ -5,14 +5,14 @@ namespace mbgl { namespace android { namespace gson { -jni::Local> JsonArray::New(jni::JNIEnv& env, const std::vector& values){ +jni::Local> JsonArray::New(jni::JNIEnv& env, const std::vector& values) { static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); - static auto addMethod = javaClass.GetMethod)>(env, "add"); + static auto addMethod = javaClass.GetMethod)>(env, "add"); auto jsonArray = javaClass.New(env, constructor); - for (const auto &v : values) { + for (const auto& v : values) { jsonArray.Call(env, addMethod, JsonElement::New(env, v)); } @@ -24,8 +24,8 @@ std::vector JsonArray::convert(jni::JNIEnv& env, const jni::Object< if (jsonArray) { static auto& javaClass = jni::Class::Singleton(env); - static auto getMethod = javaClass.GetMethod (jni::jint)>(env, "get"); - static auto sizeMethod = javaClass.GetMethod(env, "size"); + static auto getMethod = javaClass.GetMethod(jni::jint)>(env, "get"); + static auto sizeMethod = javaClass.GetMethod(env, "size"); int size = jsonArray.Call(env, sizeMethod); values.reserve(uint(size)); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_element.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_element.cpp index ba22304d072..f311a1553a5 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_element.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_element.cpp @@ -14,50 +14,40 @@ jni::Local> JsonElement::New(jni::JNIEnv& env, const mb static auto booleanConstructor = primitive.GetConstructor(env); return value.match( - [&] (const mbgl::NullValue&) { - return jni::Local>(); - }, - [&] (const std::string& value) { + [&](const mbgl::NullValue&) { return jni::Local>(); }, + [&](const std::string& value) { return primitive.New(env, stringConstructor, jni::Make(env, value)); }, - [&] (const double value) { - return primitive.New(env, numberConstructor, jni::Box(env, value)); - }, - [&] (const int64_t value) { - return primitive.New(env, numberConstructor, jni::Box(env, value)); - }, - [&] (const uint64_t value) { + [&](const double value) { return primitive.New(env, numberConstructor, jni::Box(env, value)); }, + [&](const int64_t value) { return primitive.New(env, numberConstructor, jni::Box(env, value)); }, + [&](const uint64_t value) { return primitive.New(env, numberConstructor, jni::Box(env, int64_t(value))); // TODO: should use BigInteger }, - [&] (const bool value) { + [&](const bool value) { return primitive.New(env, booleanConstructor, jni::Box(env, value ? jni::jni_true : jni::jni_false)); }, - [&] (const std::vector& values) { - return JsonArray::New(env, values); - }, - [&] (const mbgl::PropertyMap& values) { - return JsonObject::New(env, values); - } + [&](const std::vector& values) { return JsonArray::New(env, values); }, + [&](const mbgl::PropertyMap& values) { return JsonObject::New(env, values); } ); } -mbgl::Value JsonElement::convert(jni::JNIEnv &env, const jni::Object& jsonElement) { +mbgl::Value JsonElement::convert(jni::JNIEnv& env, const jni::Object& jsonElement) { if (!jsonElement) { return mbgl::NullValue(); } static auto& elementClass = jni::Class::Singleton(env); - static auto isJsonObject = elementClass.GetMethod(env, "isJsonObject"); - static auto isJsonArray = elementClass.GetMethod(env, "isJsonArray"); - static auto isJsonPrimitive = elementClass.GetMethod(env, "isJsonPrimitive"); + static auto isJsonObject = elementClass.GetMethod(env, "isJsonObject"); + static auto isJsonArray = elementClass.GetMethod(env, "isJsonArray"); + static auto isJsonPrimitive = elementClass.GetMethod(env, "isJsonPrimitive"); static auto& primitiveClass = jni::Class::Singleton(env); - static auto isBoolean = primitiveClass.GetMethod(env, "isBoolean"); - static auto isString = primitiveClass.GetMethod(env, "isString"); - static auto isNumber = primitiveClass.GetMethod(env, "isNumber"); - static auto getAsBoolean = primitiveClass.GetMethod(env, "getAsBoolean"); - static auto getAsString = primitiveClass.GetMethod(env, "getAsString"); - static auto getAsDouble = primitiveClass.GetMethod(env, "getAsDouble"); + static auto isBoolean = primitiveClass.GetMethod(env, "isBoolean"); + static auto isString = primitiveClass.GetMethod(env, "isString"); + static auto isNumber = primitiveClass.GetMethod(env, "isNumber"); + static auto getAsBoolean = primitiveClass.GetMethod(env, "getAsBoolean"); + static auto getAsString = primitiveClass.GetMethod(env, "getAsString"); + static auto getAsDouble = primitiveClass.GetMethod(env, "getAsDouble"); if (jsonElement.Call(env, isJsonPrimitive)) { auto primitive = jni::Cast(env, primitiveClass, jsonElement); @@ -79,7 +69,7 @@ mbgl::Value JsonElement::convert(jni::JNIEnv &env, const jni::Object::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_object.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_object.cpp index 10d244ee48e..e88c6bcb665 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_object.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_object.cpp @@ -8,18 +8,15 @@ namespace mbgl { namespace android { namespace gson { - jni::Local> JsonObject::New(jni::JNIEnv& env, const mbgl::PropertyMap& values) { static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); - static auto addMethod = javaClass.GetMethod)>(env, "add"); + static auto addMethod = javaClass.GetMethod)>(env, "add"); auto jsonObject = javaClass.New(env, constructor); - for (auto &item : values) { - jsonObject.Call(env, addMethod, - jni::Make(env, item.first), - JsonElement::New(env, item.second)); + for (auto& item : values) { + jsonObject.Call(env, addMethod, jni::Make(env, item.first), JsonElement::New(env, item.second)); } return jsonObject; @@ -29,7 +26,7 @@ template // void (jni::String, jni::Object) static void iterateEntrySet(jni::JNIEnv& env, const jni::Object& jsonObject, F callback) { // Get Set> static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "entrySet"); + static auto method = javaClass.GetMethod()>(env, "entrySet"); auto entryArray = java::util::Set::toArray(env, jsonObject.Call(env, method)); @@ -39,7 +36,8 @@ static void iterateEntrySet(jni::JNIEnv& env, const jni::Object& jso if (entry) { callback( java::util::Map::Entry::getKey(env, entry), - java::util::Map::Entry::getValue(env, entry)); + java::util::Map::Entry::getValue(env, entry) + ); } } } @@ -48,15 +46,19 @@ mbgl::PropertyMap JsonObject::convert(jni::JNIEnv& env, const jni::Object& jsonElement) { - map[jni::Make(env, jId)] = JsonElement::convert(env, jsonElement); - }); + iterateEntrySet( + env, + jsonObject, + [&map, &env](const jni::String& jId, const jni::Object& jsonElement) { + map[jni::Make(env, jId)] = JsonElement::convert(env, jsonElement); + } + ); } return map; } -void JsonObject::registerNative(jni::JNIEnv &env) { +void JsonObject::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/http_file_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/http_file_source.cpp index 121d81ab4c1..1b75570c5f2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/http_file_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/http_file_source.cpp @@ -19,15 +19,16 @@ namespace mbgl { class HTTPFileSource::Impl { public: Impl(const ResourceOptions resourceOptions_, const ClientOptions clientOptions_) - : resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()) {}; + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()){}; - android::UniqueEnv env { android::AttachEnv() }; + android::UniqueEnv env{android::AttachEnv()}; - void setResourceOptions(ResourceOptions options) {resourceOptions = options;}; - ResourceOptions getResourceOptions() {return resourceOptions.clone(); }; + void setResourceOptions(ResourceOptions options) { resourceOptions = options; }; + ResourceOptions getResourceOptions() { return resourceOptions.clone(); }; - void setClientOptions(ClientOptions options) {clientOptions = options;}; - ClientOptions getClientOptions() {return clientOptions.clone();}; + void setClientOptions(ClientOptions options) { clientOptions = options; }; + ClientOptions getClientOptions() { return clientOptions.clone(); }; private: ResourceOptions resourceOptions; @@ -42,11 +43,17 @@ class HTTPRequest : public AsyncRequest { ~HTTPRequest(); void onFailure(jni::JNIEnv&, int type, const jni::String& message); - void onResponse(jni::JNIEnv&, int code, - const jni::String& etag, const jni::String& modified, - const jni::String& cacheControl, const jni::String& expires, - const jni::String& retryAfter, const jni::String& xRateLimitReset, - const jni::Array& body); + void onResponse( + jni::JNIEnv&, + int code, + const jni::String& etag, + const jni::String& modified, + const jni::String& cacheControl, + const jni::String& expires, + const jni::String& retryAfter, + const jni::String& xRateLimitReset, + const jni::Array& body + ); jni::Global> javaRequest; @@ -55,12 +62,12 @@ class HTTPRequest : public AsyncRequest { FileSource::Callback callback; Response response; - util::AsyncTask async { [this] { + util::AsyncTask async{[this] { // Calling `callback` may result in deleting `this`. Copy data to temporaries first. auto callback_ = callback; auto response_ = response; callback_(response_); - } }; + }}; static const int connectionError = 0; static const int temporaryError = 1; @@ -72,11 +79,15 @@ namespace android { void RegisterNativeHTTPRequest(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - jni::RegisterNativePeer(env, javaClass, "nativePtr", + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", METHOD(&HTTPRequest::onFailure, "nativeOnFailure"), - METHOD(&HTTPRequest::onResponse, "nativeOnResponse")); + METHOD(&HTTPRequest::onResponse, "nativeOnResponse") + ); } } // namespace android @@ -99,13 +110,16 @@ HTTPRequest::HTTPRequest(jni::JNIEnv& env, const Resource& resource_, FileSource static auto constructor = javaClass.GetConstructor(env); - javaRequest = jni::NewGlobal(env, - javaClass.New(env, constructor, + javaRequest = jni::NewGlobal( + env, + javaClass.New( + env, + constructor, reinterpret_cast(this), jni::Make(env, resource.url), jni::Make(env, etagStr), jni::Make(env, modifiedStr), - (jboolean) (resource_.usage == Resource::Usage::Offline) + (jboolean)(resource_.usage == Resource::Usage::Offline) ) ); } @@ -114,17 +128,22 @@ HTTPRequest::~HTTPRequest() { android::UniqueEnv env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*env); - static auto cancel = javaClass.GetMethod(*env, "cancel"); + static auto cancel = javaClass.GetMethod(*env, "cancel"); javaRequest.Call(*env, cancel); } -void HTTPRequest::onResponse(jni::JNIEnv& env, int code, - const jni::String& etag, const jni::String& modified, - const jni::String& cacheControl, const jni::String& expires, - const jni::String& jRetryAfter, const jni::String& jXRateLimitReset, - const jni::Array& body) { - +void HTTPRequest::onResponse( + jni::JNIEnv& env, + int code, + const jni::String& etag, + const jni::String& modified, + const jni::String& cacheControl, + const jni::String& expires, + const jni::String& jRetryAfter, + const jni::String& jXRateLimitReset, + const jni::Array& body +) { using Error = Response::Error; if (etag) { @@ -168,11 +187,17 @@ void HTTPRequest::onResponse(jni::JNIEnv& env, int code, if (jXRateLimitReset) { xRateLimitReset = jni::Make(env, jXRateLimitReset); } - response.error = std::make_unique(Error::Reason::RateLimit, "HTTP status code 429", http::parseRetryHeaders(retryAfter, xRateLimitReset)); + response.error = std::make_unique( + Error::Reason::RateLimit, "HTTP status code 429", http::parseRetryHeaders(retryAfter, xRateLimitReset) + ); } else if (code >= 500 && code < 600) { - response.error = std::make_unique(Error::Reason::Server, std::string{ "HTTP status code " } + util::toString(code)); + response.error = std::make_unique( + Error::Reason::Server, std::string{"HTTP status code "} + util::toString(code) + ); } else { - response.error = std::make_unique(Error::Reason::Other, std::string{ "HTTP status code " } + util::toString(code)); + response.error = std::make_unique( + Error::Reason::Other, std::string{"HTTP status code "} + util::toString(code) + ); } async.send(); @@ -198,8 +223,7 @@ void HTTPRequest::onFailure(jni::JNIEnv& env, int type, const jni::String& messa } HTTPFileSource::HTTPFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) - : impl(std::make_unique(resourceOptions.clone(), clientOptions.clone())) { -} + : impl(std::make_unique(resourceOptions.clone(), clientOptions.clone())) {} HTTPFileSource::~HTTPFileSource() = default; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator.cpp index 1d8b370fd20..fc25d9953df 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator.cpp @@ -15,19 +15,21 @@ void Collator::registerNative(jni::JNIEnv& env) { jni::Local> Collator::getInstance(jni::JNIEnv& env, const jni::Object& locale) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "getInstance"); + static auto method = javaClass.GetStaticMethod(jni::Object)>(env, "getInstance"); return javaClass.Call(env, method, locale); } void Collator::setStrength(jni::JNIEnv& env, const jni::Object& collator, jni::jint strength) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "setStrength"); + static auto method = javaClass.GetMethod(env, "setStrength"); collator.Call(env, method, strength); } -jni::jint Collator::compare(jni::JNIEnv& env, const jni::Object& collator, const jni::String& lhs, const jni::String& rhs) { +jni::jint Collator::compare( + jni::JNIEnv& env, const jni::Object& collator, const jni::String& lhs, const jni::String& rhs +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "compare"); + static auto method = javaClass.GetMethod(env, "compare"); return collator.Call(env, method, lhs, rhs); } @@ -37,7 +39,7 @@ void StringUtils::registerNative(jni::JNIEnv& env) { jni::Local StringUtils::unaccent(jni::JNIEnv& env, const jni::String& value) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod(env, "unaccent"); + static auto method = javaClass.GetStaticMethod(env, "unaccent"); return javaClass.Call(env, method, value); } @@ -63,19 +65,19 @@ jni::String Locale::toLanguageTag(jni::JNIEnv& env, jni::Object locale) jni::Local Locale::getLanguage(jni::JNIEnv& env, const jni::Object& locale) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "getLanguage"); + static auto method = javaClass.GetMethod(env, "getLanguage"); return locale.Call(env, method); } jni::Local Locale::getCountry(jni::JNIEnv& env, const jni::Object& locale) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "getCountry"); + static auto method = javaClass.GetMethod(env, "getCountry"); return locale.Call(env, method); } jni::Local> Locale::getDefault(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod ()>(env, "getDefault"); + static auto method = javaClass.GetStaticMethod()>(env, "getDefault"); return javaClass.Call(env, method); } @@ -98,21 +100,25 @@ namespace platform { class Collator::Impl { public: Impl(bool caseSensitive_, bool diacriticSensitive_, std::optional locale_) - : caseSensitive(caseSensitive_) - , diacriticSensitive(diacriticSensitive_) - , env(android::AttachEnv()) - { + : caseSensitive(caseSensitive_), + diacriticSensitive(diacriticSensitive_), + env(android::AttachEnv()) { LanguageTag languageTag = locale_ ? LanguageTag::fromBCP47(*locale_) : LanguageTag(); if (!languageTag.language) { - locale = jni::NewGlobal(*env, - android::Locale::getDefault(*env)); + locale = jni::NewGlobal(*env, android::Locale::getDefault(*env)); } else if (!languageTag.region) { - locale = jni::NewGlobal(*env, - android::Locale::New(*env, jni::Make(*env, *languageTag.language))); + locale = jni::NewGlobal( + *env, android::Locale::New(*env, jni::Make(*env, *languageTag.language)) + ); } else { - locale = jni::NewGlobal(*env, - android::Locale::New(*env, jni::Make(*env, *languageTag.language), - jni::Make(*env, *languageTag.region))); + locale = jni::NewGlobal( + *env, + android::Locale::New( + *env, + jni::Make(*env, *languageTag.language), + jni::Make(*env, *languageTag.region) + ) + ); } collator = jni::NewGlobal(*env, android::Collator::getInstance(*env, locale)); if (!diacriticSensitive && !caseSensitive) { @@ -127,9 +133,8 @@ class Collator::Impl { } bool operator==(const Impl& other) const { - return caseSensitive == other.caseSensitive && - diacriticSensitive == other.diacriticSensitive && - resolvedLocale() == other.resolvedLocale(); + return caseSensitive == other.caseSensitive && diacriticSensitive == other.diacriticSensitive && + resolvedLocale() == other.resolvedLocale(); } int compare(const std::string& lhs, const std::string& rhs) const { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator_jni.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator_jni.hpp index 612f9b49f3c..0567d50e545 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator_jni.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator_jni.hpp @@ -29,7 +29,6 @@ class Locale { static jni::Local> New(jni::JNIEnv&, const jni::String&); static jni::Local> New(jni::JNIEnv&, const jni::String&, const jni::String&); - static void registerNative(jni::JNIEnv&); }; @@ -43,18 +42,15 @@ class Collator { static jni::jint compare(jni::JNIEnv&, const jni::Object&, const jni::String&, const jni::String&); - static void registerNative(jni::JNIEnv&); }; - class StringUtils { public: static constexpr auto Name() { return "com/mapbox/mapboxsdk/utils/StringUtils"; }; static jni::Local unaccent(jni::JNIEnv&, const jni::String&); - static void registerNative(jni::JNIEnv&); }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/number_format.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/number_format.cpp index a804e74f1ca..ac195c90b3c 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/number_format.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/number_format.cpp @@ -15,31 +15,37 @@ void NumberFormat::registerNative(jni::JNIEnv& env) { jni::Local> NumberFormat::getInstance(jni::JNIEnv& env, const jni::Object& locale) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "getInstance"); + static auto method = javaClass.GetStaticMethod(jni::Object)>(env, "getInstance"); return javaClass.Call(env, method, locale); } -jni::Local> NumberFormat::getCurrencyInstance(jni::JNIEnv& env, const jni::Object& locale) { +jni::Local> NumberFormat::getCurrencyInstance( + jni::JNIEnv& env, const jni::Object& locale +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "getCurrencyInstance"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "getCurrencyInstance" + ); return javaClass.Call(env, method, locale); } -jni::Local NumberFormat::format(jni::JNIEnv& env, const jni::Object& nf, jni::jdouble number) { +jni::Local NumberFormat::format( + jni::JNIEnv& env, const jni::Object& nf, jni::jdouble number +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "format"); + static auto method = javaClass.GetMethod(env, "format"); return nf.Call(env, method, number); } void NumberFormat::setMinimumFractionDigits(jni::JNIEnv& env, const jni::Object& nf, jni::jint value) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "setMinimumFractionDigits"); + static auto method = javaClass.GetMethod(env, "setMinimumFractionDigits"); return nf.Call(env, method, value); } void NumberFormat::setMaximumFractionDigits(jni::JNIEnv& env, const jni::Object& nf, jni::jint value) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "setMaximumFractionDigits"); + static auto method = javaClass.GetMethod(env, "setMaximumFractionDigits"); return nf.Call(env, method, value); } @@ -47,10 +53,14 @@ void NumberFormat::setMaximumFractionDigits(jni::JNIEnv& env, const jni::Object< namespace platform { -std::string formatNumber(double number, const std::string& localeId, const std::string& currency, - uint8_t minFractionDigits, uint8_t maxFractionDigits) { - - auto env{ android::AttachEnv() }; +std::string formatNumber( + double number, + const std::string& localeId, + const std::string& currency, + uint8_t minFractionDigits, + uint8_t maxFractionDigits +) { + auto env{android::AttachEnv()}; jni::Global> locale; LanguageTag languageTag = !localeId.empty() ? LanguageTag::fromBCP47(localeId) : LanguageTag(); @@ -59,8 +69,14 @@ std::string formatNumber(double number, const std::string& localeId, const std:: } else if (!languageTag.region) { locale = jni::NewGlobal(*env, android::Locale::New(*env, jni::Make(*env, *languageTag.language))); } else { - locale = jni::NewGlobal(*env, android::Locale::New(*env, jni::Make(*env, *languageTag.language), - jni::Make(*env, *languageTag.region))); + locale = jni::NewGlobal( + *env, + android::Locale::New( + *env, + jni::Make(*env, *languageTag.language), + jni::Make(*env, *languageTag.region) + ) + ); } jni::Global> formatter; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/java/util.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/java/util.hpp index 9b0c01459eb..f10b394bc6e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/java/util.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/java/util.hpp @@ -13,10 +13,10 @@ class List : private mbgl::util::noncopyable { public: static constexpr auto Name() { return "java/util/List"; }; - template + template static jni::Local>> toArray(jni::JNIEnv& env, const jni::Object& list) { static auto& javaClass = jni::Class::Singleton(env); - static auto toArray = javaClass.GetMethod> ()>(env, "toArray"); + static auto toArray = javaClass.GetMethod>()>(env, "toArray"); return jni::Local>>(env, list.Call(env, toArray).release()); }; @@ -40,10 +40,10 @@ class Set : private mbgl::util::noncopyable { public: static constexpr auto Name() { return "java/util/Set"; }; - template + template static jni::Local>> toArray(jni::JNIEnv& env, const jni::Object& list) { static auto& javaClass = jni::Class::Singleton(env); - static auto toArray = javaClass.GetMethod> ()>(env, "toArray"); + static auto toArray = javaClass.GetMethod>()>(env, "toArray"); return jni::Local>>(env, list.Call(env, toArray).release()); }; @@ -60,14 +60,14 @@ class Map : private mbgl::util::noncopyable { template static jni::Local> getKey(jni::JNIEnv& env, const jni::Object& entry) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "getKey"); + static auto method = javaClass.GetMethod()>(env, "getKey"); return jni::Cast(env, jni::Class::Singleton(env), entry.Call(env, method)); } template static jni::Local> getValue(jni::JNIEnv& env, const jni::Object& entry) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "getValue"); + static auto method = javaClass.GetMethod()>(env, "getValue"); return jni::Cast(env, jni::Class::Singleton(env), entry.Call(env, method)); } }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.cpp index 7a1ba93a585..e004544ee93 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.cpp @@ -4,46 +4,46 @@ namespace mbgl { namespace android { namespace java { - jni::jclass* ObjectArray::jclass; +jni::jclass* ObjectArray::jclass; - jni::jclass* String::jclass; +jni::jclass* String::jclass; - jni::jclass* Boolean::jclass; - jni::jmethodID* Boolean::booleanValueMethodId; +jni::jclass* Boolean::jclass; +jni::jmethodID* Boolean::booleanValueMethodId; - jni::jclass* Number::jclass; - jni::jmethodID* Number::floatValueMethodId; - jni::jmethodID* Number::doubleValueMethodId; - jni::jmethodID* Number::longValueMethodId; +jni::jclass* Number::jclass; +jni::jmethodID* Number::floatValueMethodId; +jni::jmethodID* Number::doubleValueMethodId; +jni::jmethodID* Number::longValueMethodId; - jni::jclass* Map::jclass; - jni::jmethodID* Map::getMethodId; - jni::jmethodID* Map::keySetMethodId; +jni::jclass* Map::jclass; +jni::jmethodID* Map::getMethodId; +jni::jmethodID* Map::keySetMethodId; - jni::jclass* Set::jclass; - jni::jmethodID* Set::toArrayMethodId; +jni::jclass* Set::jclass; +jni::jmethodID* Set::toArrayMethodId; - void registerNatives(JNIEnv& env) { - ObjectArray::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "[Ljava/lang/Object;")).release(); +void registerNatives(JNIEnv& env) { + ObjectArray::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "[Ljava/lang/Object;")).release(); - String::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/String")).release(); + String::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/String")).release(); - Boolean::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/Boolean")).release(); - Boolean::booleanValueMethodId = &jni::GetMethodID(env, *Boolean::jclass, "booleanValue", "()Z"); + Boolean::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/Boolean")).release(); + Boolean::booleanValueMethodId = &jni::GetMethodID(env, *Boolean::jclass, "booleanValue", "()Z"); - Number::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/Number")).release(); - Number::floatValueMethodId = &jni::GetMethodID(env, *Number::jclass, "floatValue", "()F"); - Number::doubleValueMethodId = &jni::GetMethodID(env, *Number::jclass, "doubleValue", "()D"); - Number::longValueMethodId = &jni::GetMethodID(env, *Number::jclass, "longValue", "()J"); + Number::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/Number")).release(); + Number::floatValueMethodId = &jni::GetMethodID(env, *Number::jclass, "floatValue", "()F"); + Number::doubleValueMethodId = &jni::GetMethodID(env, *Number::jclass, "doubleValue", "()D"); + Number::longValueMethodId = &jni::GetMethodID(env, *Number::jclass, "longValue", "()J"); - Map::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/util/Map")).release(); - Map::getMethodId = &jni::GetMethodID(env, *Map::jclass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); - Map::keySetMethodId = &jni::GetMethodID(env, *Map::jclass, "keySet", "()Ljava/util/Set;"); + Map::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/util/Map")).release(); + Map::getMethodId = &jni::GetMethodID(env, *Map::jclass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); + Map::keySetMethodId = &jni::GetMethodID(env, *Map::jclass, "keySet", "()Ljava/util/Set;"); - Set::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/util/Set")).release(); - Set::toArrayMethodId = &jni::GetMethodID(env, *Set::jclass, "toArray", "()[Ljava/lang/Object;"); - } - -} -} + Set::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/util/Set")).release(); + Set::toArrayMethodId = &jni::GetMethodID(env, *Set::jclass, "toArray", "()[Ljava/lang/Object;"); } + +} // namespace java +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.hpp index c7c93ce71b0..0540fdb9488 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.hpp @@ -6,38 +6,38 @@ namespace mbgl { namespace android { namespace java { - struct ObjectArray { - static jni::jclass* jclass; - }; - - struct String { - static jni::jclass* jclass; - }; - - struct Boolean { - static jni::jclass* jclass; - static jni::jmethodID* booleanValueMethodId; - }; - - struct Number { - static jni::jclass* jclass; - static jni::jmethodID* floatValueMethodId; - static jni::jmethodID* doubleValueMethodId; - static jni::jmethodID* longValueMethodId; - }; - - struct Map { - static jni::jclass* jclass; - static jni::jmethodID* getMethodId; - static jni::jmethodID* keySetMethodId; - }; - - struct Set { - static jni::jclass* jclass; - static jni::jmethodID* toArrayMethodId; - }; - - void registerNatives(JNIEnv&); -} -} -} +struct ObjectArray { + static jni::jclass* jclass; +}; + +struct String { + static jni::jclass* jclass; +}; + +struct Boolean { + static jni::jclass* jclass; + static jni::jmethodID* booleanValueMethodId; +}; + +struct Number { + static jni::jclass* jclass; + static jni::jmethodID* floatValueMethodId; + static jni::jmethodID* doubleValueMethodId; + static jni::jmethodID* longValueMethodId; +}; + +struct Map { + static jni::jclass* jclass; + static jni::jmethodID* getMethodId; + static jni::jmethodID* keySetMethodId; +}; + +struct Set { + static jni::jclass* jclass; + static jni::jmethodID* toArrayMethodId; +}; + +void registerNatives(JNIEnv&); +} // namespace java +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/jni_native.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/jni_native.cpp index 52b3016ff5c..44aea3074f4 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/jni_native.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/jni_native.cpp @@ -62,7 +62,7 @@ namespace android { void RegisterNativeHTTPRequest(JNIEnv&); -void registerNatives(JavaVM *vm) { +void registerNatives(JavaVM* vm) { theJVM = vm; jni::JNIEnv& env = jni::GetEnv(*vm, jni::jni_version_1_6); @@ -101,7 +101,7 @@ void registerNatives(JavaVM *vm) { gson::JsonObject::registerNative(env); gson::JsonPrimitive::registerNative(env); - //Annotation + // Annotation Marker::registerNative(env); Polygon::registerNative(env); Polyline::registerNative(env); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/logger.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/logger.cpp index f5d78cc83ce..abe5c9211cc 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/logger.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/logger.cpp @@ -8,7 +8,7 @@ void Logger::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } -void Logger::log(jni::JNIEnv& env, EventSeverity severity, const std::string &msg) { +void Logger::log(jni::JNIEnv& env, EventSeverity severity, const std::string& msg) { static auto& _class = jni::Class::Singleton(env); auto tag = jni::Make(env, "Mbgl"); @@ -21,7 +21,7 @@ void Logger::log(jni::JNIEnv& env, EventSeverity severity, const std::string &ms } else if (severity == EventSeverity::Info) { auto static info = _class.GetStaticMethod(env, "i"); _class.Call(env, info, tag, message); - } else if(severity == EventSeverity::Warning) { + } else if (severity == EventSeverity::Warning) { auto static warning = _class.GetStaticMethod(env, "w"); _class.Call(env, warning, tag, message); } else { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/logger.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/logger.hpp index 7481ecb2658..2eaa2b523be 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/logger.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/logger.hpp @@ -9,12 +9,10 @@ namespace android { class Logger { public: - static constexpr auto Name() { - return "com/mapbox/mapboxsdk/log/Logger"; - }; - static void registerNative(jni::JNIEnv&); + static constexpr auto Name() { return "com/mapbox/mapboxsdk/log/Logger"; }; + static void registerNative(jni::JNIEnv &); - static void log(jni::JNIEnv&, EventSeverity severity, const std::string &msg); + static void log(jni::JNIEnv &, EventSeverity severity, const std::string &msg); }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/logging_android.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/logging_android.cpp index 1301367280c..46543124bbd 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/logging_android.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/logging_android.cpp @@ -6,8 +6,8 @@ namespace mbgl { void Log::platformRecord(EventSeverity severity, const std::string &msg) { - auto env{ android::AttachEnv() }; + auto env{android::AttachEnv()}; android::Logger::log(*env, severity, msg); } -} \ No newline at end of file +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map/camera_position.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map/camera_position.cpp index 4266b64fdfe..02912b8138f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map/camera_position.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map/camera_position.cpp @@ -4,9 +4,12 @@ namespace mbgl { namespace android { -jni::Local> CameraPosition::New(jni::JNIEnv &env, mbgl::CameraOptions options, float pixelRatio) { +jni::Local> CameraPosition::New( + jni::JNIEnv& env, mbgl::CameraOptions options, float pixelRatio +) { static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, double, double, double, jni::Array>(env); + static auto constructor = + javaClass.GetConstructor, double, double, double, jni::Array>(env); // wrap LatLng values coming from core auto center = options.center.value(); @@ -26,7 +29,7 @@ jni::Local> CameraPosition::New(jni::JNIEnv &env, mb double tilt_degrees = options.pitch.value_or(0); std::vector paddingVect; - auto insets = options.padding.value_or(EdgeInsets {0, 0, 0, 0}); + auto insets = options.padding.value_or(EdgeInsets{0, 0, 0, 0}); auto padding = jni::Array::New(env, 4); paddingVect.push_back(insets.left() * pixelRatio); paddingVect.push_back(insets.top() * pixelRatio); @@ -34,10 +37,14 @@ jni::Local> CameraPosition::New(jni::JNIEnv &env, mb paddingVect.push_back(insets.bottom() * pixelRatio); padding.SetRegion>(env, 0, paddingVect); - return javaClass.New(env, constructor, LatLng::New(env, center), options.zoom.value_or(0), tilt_degrees, bearing_degrees, padding); + return javaClass.New( + env, constructor, LatLng::New(env, center), options.zoom.value_or(0), tilt_degrees, bearing_degrees, padding + ); } -mbgl::CameraOptions CameraPosition::getCameraOptions(jni::JNIEnv& env, const jni::Object& position, float pixelRatio) { +mbgl::CameraOptions CameraPosition::getCameraOptions( + jni::JNIEnv& env, const jni::Object& position, float pixelRatio +) { static auto& javaClass = jni::Class::Singleton(env); static auto bearing = javaClass.GetField(env, "bearing"); static auto target = javaClass.GetField>(env, "target"); @@ -48,22 +55,20 @@ mbgl::CameraOptions CameraPosition::getCameraOptions(jni::JNIEnv& env, const jni auto padding = position.Get(env, paddingField); auto center = LatLng::getLatLng(env, position.Get(env, target)); - return mbgl::CameraOptions{center, - padding && padding.Length(env) == 4 ? EdgeInsets{padding.Get(env, 1) * pixelRatio, - padding.Get(env, 0) * pixelRatio, - padding.Get(env, 3) * pixelRatio, - padding.Get(env, 2) * pixelRatio} - : (EdgeInsets){}, - {}, - position.Get(env, zoom), - position.Get(env, bearing), - position.Get(env, tilt)}; + return mbgl::CameraOptions{ + center, + padding && padding.Length(env) == 4 + ? EdgeInsets{padding.Get(env, 1) * pixelRatio, padding.Get(env, 0) * pixelRatio, padding.Get(env, 3) * pixelRatio, padding.Get(env, 2) * pixelRatio} + : (EdgeInsets){}, + {}, + position.Get(env, zoom), + position.Get(env, bearing), + position.Get(env, tilt)}; } -void CameraPosition::registerNative(jni::JNIEnv &env) { +void CameraPosition::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } } // namespace android -} // namespace mb - +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map/image.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map/image.cpp index 04f5b1a3522..0770195ea75 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map/image.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map/image.cpp @@ -13,7 +13,7 @@ mbgl::style::Image Image::getImage(jni::JNIEnv& env, const jni::Object& i static auto bufferField = javaClass.GetField>(env, "buffer"); static auto nameField = javaClass.GetField(env, "name"); static auto sdfField = javaClass.GetField(env, "sdf"); - static auto contentField = javaClass.GetField>(env, "content"); + static auto contentField = javaClass.GetField>(env, "content"); static auto stretchXField = javaClass.GetField>(env, "stretchX"); static auto stretchYField = javaClass.GetField>(env, "stretchY"); @@ -22,20 +22,19 @@ mbgl::style::Image Image::getImage(jni::JNIEnv& env, const jni::Object& i auto pixelRatio = image.Get(env, pixelRatioField); auto pixels = image.Get(env, bufferField); auto name = jni::Make(env, image.Get(env, nameField)); - auto sdf = (bool) image.Get(env, sdfField); + auto sdf = (bool)image.Get(env, sdfField); auto content = image.Get(env, contentField); auto stretchX = image.Get(env, stretchXField); auto stretchY = image.Get(env, stretchYField); jni::NullCheck(env, pixels.get()); std::size_t size = pixels.Length(env); - mbgl::PremultipliedImage premultipliedImage({ static_cast(width), static_cast(height) }); + mbgl::PremultipliedImage premultipliedImage({static_cast(width), static_cast(height)}); if (premultipliedImage.bytes() != uint32_t(size)) { throw mbgl::util::StyleImageException("Image pixel count mismatch"); } - jni::GetArrayRegion(env, *pixels, 0, size, - reinterpret_cast(premultipliedImage.data.get())); + jni::GetArrayRegion(env, *pixels, 0, size, reinterpret_cast(premultipliedImage.data.get())); style::ImageStretches imageStretchesX = {}; style::ImageStretches imageStretchesY = {}; @@ -53,24 +52,24 @@ mbgl::style::Image Image::getImage(jni::JNIEnv& env, const jni::Object& i } if (content) { - const style::ImageContent imageContent = style::ImageContent{content.Get(env, 0), - content.Get(env, 1), - content.Get(env, 2), - content.Get(env, 3)}; - return mbgl::style::Image{name, std::move(premultipliedImage), pixelRatio, sdf, - imageStretchesX, - imageStretchesY, - std::move(imageContent)}; + const style::ImageContent imageContent = style::ImageContent{ + content.Get(env, 0), content.Get(env, 1), content.Get(env, 2), content.Get(env, 3)}; + return mbgl::style::Image{ + name, + std::move(premultipliedImage), + pixelRatio, + sdf, + imageStretchesX, + imageStretchesY, + std::move(imageContent)}; } - return mbgl::style::Image{name, std::move(premultipliedImage), pixelRatio, sdf, - imageStretchesX, - imageStretchesY}; + return mbgl::style::Image{name, std::move(premultipliedImage), pixelRatio, sdf, imageStretchesX, imageStretchesY}; } -void Image::registerNative(jni::JNIEnv &env) { +void Image::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } } // namespace android -} // namespace mb +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.cpp index 051e99410f7..2203dbedbfd 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.cpp @@ -14,17 +14,22 @@ namespace mbgl { namespace android { -MapRenderer::MapRenderer(jni::JNIEnv& _env, - const jni::Object& obj, - jni::jfloat pixelRatio_, - const jni::String& localIdeographFontFamily_) +MapRenderer::MapRenderer( + jni::JNIEnv& _env, + const jni::Object& obj, + jni::jfloat pixelRatio_, + const jni::String& localIdeographFontFamily_ +) : javaPeer(_env, obj), pixelRatio(pixelRatio_), - localIdeographFontFamily(localIdeographFontFamily_ ? jni::Make(_env, localIdeographFontFamily_) - : std::optional{}), + localIdeographFontFamily( + localIdeographFontFamily_ ? jni::Make(_env, localIdeographFontFamily_) + : std::optional{} + ), mailboxData(this) {} -MapRenderer::MailboxData::MailboxData(Scheduler* scheduler_) : scheduler(scheduler_) { +MapRenderer::MailboxData::MailboxData(Scheduler* scheduler_) + : scheduler(scheduler_) { assert(scheduler); } @@ -70,8 +75,7 @@ void MapRenderer::schedule(std::function scheduled) { // Queue the event on the Java Peer static auto& javaClass = jni::Class::Singleton(*_env); - static auto queueEvent = javaClass.GetMethod)>(*_env, "queueEvent"); + static auto queueEvent = javaClass.GetMethod)>(*_env, "queueEvent"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, queueEvent, peer); @@ -127,15 +131,18 @@ void MapRenderer::setObserver(std::shared_ptr _rendererObserve void MapRenderer::requestSnapshot(SnapshotCallback callback) { auto self = ActorRef(*this, mailboxData.getMailbox()); self.invoke( - &MapRenderer::scheduleSnapshot, - std::make_unique([&, callback=std::move(callback), runloop=util::RunLoop::Get()](PremultipliedImage image) { - runloop->invoke([callback=std::move(callback), image=std::move(image), renderer=std::move(this)]() mutable { + &MapRenderer::scheduleSnapshot, + std::make_unique( + [&, callback = std::move(callback), runloop = util::RunLoop::Get()](PremultipliedImage image) { + runloop->invoke([callback = std::move(callback), image = std::move(image), renderer = std::move(this)]( + ) mutable { if (renderer && !renderer->destroyed) { callback(std::move(image)); } }); snapshotCallback.reset(); - }) + } + ) ); } @@ -152,7 +159,7 @@ void MapRenderer::scheduleSnapshot(std::unique_ptr callback) { } void MapRenderer::render(JNIEnv&) { - assert (renderer); + assert(renderer); std::shared_ptr params; { @@ -165,7 +172,7 @@ void MapRenderer::render(JNIEnv&) { } // Activate the backend - gfx::BackendScope backendGuard { *backend }; + gfx::BackendScope backendGuard{*backend}; // Ensure that the "current" scheduler on the render thread is // this scheduler. @@ -190,7 +197,7 @@ void MapRenderer::onSurfaceCreated(JNIEnv&) { std::lock_guard lock(initialisationMutex); // The GL context is already active if get a new surface. - gfx::BackendScope backendGuard { *backend, gfx::BackendScope::ScopeType::Implicit }; + gfx::BackendScope backendGuard{*backend, gfx::BackendScope::ScopeType::Implicit}; // The android system will have already destroyed the underlying // GL resources if this is not the first initialization and an @@ -244,17 +251,19 @@ void MapRenderer::registerNative(jni::JNIEnv& env) { #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer - jni::RegisterNativePeer(env, javaClass, "nativePtr", - jni::MakePeer&, jni::jfloat, const jni::String&>, - "nativeInitialize", "finalize", - METHOD(&MapRenderer::render, "nativeRender"), - METHOD(&MapRenderer::onRendererReset, "nativeReset"), - METHOD(&MapRenderer::onSurfaceCreated, - "nativeOnSurfaceCreated"), - METHOD(&MapRenderer::onSurfaceChanged, - "nativeOnSurfaceChanged"), - METHOD(&MapRenderer::onSurfaceDestroyed, - "nativeOnSurfaceDestroyed")); + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&, jni::jfloat, const jni::String&>, + "nativeInitialize", + "finalize", + METHOD(&MapRenderer::render, "nativeRender"), + METHOD(&MapRenderer::onRendererReset, "nativeReset"), + METHOD(&MapRenderer::onSurfaceCreated, "nativeOnSurfaceCreated"), + METHOD(&MapRenderer::onSurfaceChanged, "nativeOnSurfaceChanged"), + METHOD(&MapRenderer::onSurfaceDestroyed, "nativeOnSurfaceDestroyed") + ); } MapRenderer& MapRenderer::getNativePeer(JNIEnv& env, const jni::Object& jObject) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.hpp index a7b7ca729af..f9d50e399d7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.hpp @@ -34,17 +34,18 @@ class AndroidRendererBackend; */ class MapRenderer : public Scheduler { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/maps/renderer/MapRenderer"; }; static void registerNative(jni::JNIEnv&); static MapRenderer& getNativePeer(JNIEnv&, const jni::Object&); - MapRenderer(jni::JNIEnv& _env, - const jni::Object&, - jni::jfloat pixelRatio, - const jni::String& localIdeographFontFamily); + MapRenderer( + jni::JNIEnv& _env, + const jni::Object&, + jni::jfloat pixelRatio, + const jni::String& localIdeographFontFamily + ); ~MapRenderer() override; @@ -73,7 +74,7 @@ class MapRenderer : public Scheduler { void requestRender(); // Snapshot - requires a RunLoop on the calling thread - using SnapshotCallback = std::function; + using SnapshotCallback = std::function; void requestSnapshot(SnapshotCallback); protected: @@ -128,7 +129,7 @@ class MapRenderer : public Scheduler { std::mutex updateMutex; bool framebufferSizeChanged = false; - std::atomic destroyed {false}; + std::atomic destroyed{false}; std::unique_ptr snapshotCallback; mapbox::base::WeakPtrFactory weakFactory{this}; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.cpp index 227f49ee3f3..e02bf538ffa 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.cpp @@ -36,13 +36,14 @@ void MapRendererRunnable::registerNative(jni::JNIEnv& env) { #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - std::make_unique, - "nativeInitialize", - "finalize", - METHOD(&MapRendererRunnable::run, "run")); + env, + javaClass, + "nativePtr", + std::make_unique, + "nativeInitialize", + "finalize", + METHOD(&MapRendererRunnable::run, "run") + ); } } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.hpp index 24d0f2af49b..06826b4cb46 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.hpp @@ -19,7 +19,6 @@ namespace android { */ class MapRendererRunnable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/maps/renderer/MapRendererRunnable"; }; static void registerNative(jni::JNIEnv&); @@ -27,9 +26,7 @@ class MapRendererRunnable { MapRendererRunnable(jni::JNIEnv&, std::function); // Only for jni registration, unused - MapRendererRunnable(jni::JNIEnv&) { - assert(false); - } + MapRendererRunnable(jni::JNIEnv&) { assert(false); } ~MapRendererRunnable(); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.cpp index a3da861d442..7246e50b6d5 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.cpp @@ -57,13 +57,17 @@ namespace mbgl { namespace android { -NativeMapView::NativeMapView(jni::JNIEnv& _env, - const jni::Object& _obj, - const jni::Object& jFileSource, - const jni::Object& jMapRenderer, - jni::jfloat pixelRatio_, - jni::jboolean crossSourceCollisions_) - : javaPeer(_env, _obj), mapRenderer(MapRenderer::getNativePeer(_env, jMapRenderer)), pixelRatio(pixelRatio_) { +NativeMapView::NativeMapView( + jni::JNIEnv& _env, + const jni::Object& _obj, + const jni::Object& jFileSource, + const jni::Object& jMapRenderer, + jni::jfloat pixelRatio_, + jni::jboolean crossSourceCollisions_ +) + : javaPeer(_env, _obj), + mapRenderer(MapRenderer::getNativePeer(_env, jMapRenderer)), + pixelRatio(pixelRatio_) { // Get a reference to the JavaVM for callbacks if (_env.GetJavaVM(&vm) < 0) { _env.ExceptionDescribe(); @@ -84,9 +88,12 @@ NativeMapView::NativeMapView(jni::JNIEnv& _env, // Create the core map map = std::make_unique( - *rendererFrontend, *this, options, + *rendererFrontend, + *this, + options, mbgl::android::FileSource::getSharedResourceOptions(_env, jFileSource), - mbgl::android::FileSource::getSharedClientOptions(_env, jFileSource)); + mbgl::android::FileSource::getSharedClientOptions(_env, jFileSource) + ); } /** @@ -102,20 +109,19 @@ void NativeMapView::onCameraWillChange(MapObserver::CameraChangeMode mode) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onCameraWillChange = javaClass.GetMethod(*_env, "onCameraWillChange"); + static auto onCameraWillChange = javaClass.GetMethod(*_env, "onCameraWillChange"); auto weakReference = javaPeer.get(*_env); if (weakReference) { - weakReference.Call(*_env, onCameraWillChange, (jboolean) (mode != MapObserver::CameraChangeMode::Immediate)); + weakReference.Call(*_env, onCameraWillChange, (jboolean)(mode != MapObserver::CameraChangeMode::Immediate)); } } - void NativeMapView::onCameraIsChanging() { assert(vm != nullptr); android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onCameraIsChanging = javaClass.GetMethod(*_env, "onCameraIsChanging"); + static auto onCameraIsChanging = javaClass.GetMethod(*_env, "onCameraIsChanging"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onCameraIsChanging); @@ -127,11 +133,10 @@ void NativeMapView::onCameraDidChange(MapObserver::CameraChangeMode mode) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onCameraDidChange = javaClass.GetMethod(*_env, "onCameraDidChange"); + static auto onCameraDidChange = javaClass.GetMethod(*_env, "onCameraDidChange"); auto weakReference = javaPeer.get(*_env); if (weakReference) { - weakReference.Call(*_env, onCameraDidChange, - (jboolean) (mode != MapObserver::CameraChangeMode::Immediate)); + weakReference.Call(*_env, onCameraDidChange, (jboolean)(mode != MapObserver::CameraChangeMode::Immediate)); } } @@ -140,7 +145,7 @@ void NativeMapView::onWillStartLoadingMap() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onWillStartLoadingMap = javaClass.GetMethod(*_env, "onWillStartLoadingMap"); + static auto onWillStartLoadingMap = javaClass.GetMethod(*_env, "onWillStartLoadingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onWillStartLoadingMap); @@ -152,7 +157,7 @@ void NativeMapView::onDidFinishLoadingMap() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFinishLoadingMap = javaClass.GetMethod(*_env, "onDidFinishLoadingMap"); + static auto onDidFinishLoadingMap = javaClass.GetMethod(*_env, "onDidFinishLoadingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onDidFinishLoadingMap); @@ -164,7 +169,7 @@ void NativeMapView::onDidFailLoadingMap(MapLoadError, const std::string& error) android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFailLoadingMap = javaClass.GetMethod(*_env, "onDidFailLoadingMap"); + static auto onDidFailLoadingMap = javaClass.GetMethod(*_env, "onDidFailLoadingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onDidFailLoadingMap, jni::Make(*_env, error)); @@ -176,7 +181,7 @@ void NativeMapView::onWillStartRenderingFrame() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onWillStartRenderingFrame = javaClass.GetMethod(*_env, "onWillStartRenderingFrame"); + static auto onWillStartRenderingFrame = javaClass.GetMethod(*_env, "onWillStartRenderingFrame"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onWillStartRenderingFrame); @@ -188,20 +193,21 @@ void NativeMapView::onDidFinishRenderingFrame(MapObserver::RenderFrameStatus sta android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFinishRenderingFrame = javaClass.GetMethod(*_env, "onDidFinishRenderingFrame"); + static auto onDidFinishRenderingFrame = javaClass.GetMethod(*_env, "onDidFinishRenderingFrame"); auto weakReference = javaPeer.get(*_env); if (weakReference) { - weakReference.Call(*_env, onDidFinishRenderingFrame, (jboolean) (status.mode != MapObserver::RenderMode::Partial)); + weakReference.Call( + *_env, onDidFinishRenderingFrame, (jboolean)(status.mode != MapObserver::RenderMode::Partial) + ); } } - void NativeMapView::onWillStartRenderingMap() { assert(vm != nullptr); android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onWillStartRenderingMap = javaClass.GetMethod(*_env, "onWillStartRenderingMap"); + static auto onWillStartRenderingMap = javaClass.GetMethod(*_env, "onWillStartRenderingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onWillStartRenderingMap); @@ -213,10 +219,10 @@ void NativeMapView::onDidFinishRenderingMap(MapObserver::RenderMode mode) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFinishRenderingMap = javaClass.GetMethod(*_env, "onDidFinishRenderingMap"); + static auto onDidFinishRenderingMap = javaClass.GetMethod(*_env, "onDidFinishRenderingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { - weakReference.Call(*_env, onDidFinishRenderingMap, (jboolean) (mode != MapObserver::RenderMode::Partial)); + weakReference.Call(*_env, onDidFinishRenderingMap, (jboolean)(mode != MapObserver::RenderMode::Partial)); } } @@ -225,7 +231,7 @@ void NativeMapView::onDidBecomeIdle() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidBecomeIdle = javaClass.GetMethod(*_env, "onDidBecomeIdle"); + static auto onDidBecomeIdle = javaClass.GetMethod(*_env, "onDidBecomeIdle"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onDidBecomeIdle); @@ -237,7 +243,7 @@ void NativeMapView::onDidFinishLoadingStyle() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFinishLoadingStyle = javaClass.GetMethod(*_env, "onDidFinishLoadingStyle"); + static auto onDidFinishLoadingStyle = javaClass.GetMethod(*_env, "onDidFinishLoadingStyle"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onDidFinishLoadingStyle); @@ -249,7 +255,7 @@ void NativeMapView::onSourceChanged(mbgl::style::Source& source) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onSourceChanged = javaClass.GetMethod(*_env, "onSourceChanged"); + static auto onSourceChanged = javaClass.GetMethod(*_env, "onSourceChanged"); auto sourceId = jni::Make(*_env, source.getID()); auto weakReference = javaPeer.get(*_env); if (weakReference) { @@ -262,7 +268,7 @@ void NativeMapView::onStyleImageMissing(const std::string& imageId) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onStyleImageMissing = javaClass.GetMethod(*_env, "onStyleImageMissing"); + static auto onStyleImageMissing = javaClass.GetMethod(*_env, "onStyleImageMissing"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onStyleImageMissing, jni::Make(*_env, imageId)); @@ -274,7 +280,9 @@ bool NativeMapView::onCanRemoveUnusedStyleImage(const std::string& imageId) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onCanRemoveUnusedStyleImage = javaClass.GetMethod(*_env, "onCanRemoveUnusedStyleImage"); + static auto onCanRemoveUnusedStyleImage = javaClass.GetMethod( + *_env, "onCanRemoveUnusedStyleImage" + ); auto weakReference = javaPeer.get(*_env); if (weakReference) { return weakReference.Call(*_env, onCanRemoveUnusedStyleImage, jni::Make(*_env, imageId)); @@ -288,7 +296,7 @@ bool NativeMapView::onCanRemoveUnusedStyleImage(const std::string& imageId) { void NativeMapView::resizeView(jni::JNIEnv&, int w, int h) { width = util::max(64, w); height = util::max(64, h); - map->setSize({ static_cast(width), static_cast(height) }); + map->setSize({static_cast(width), static_cast(height)}); } jni::Local NativeMapView::getStyleUrl(jni::JNIEnv& env) { @@ -328,13 +336,21 @@ void NativeMapView::setGestureInProgress(jni::JNIEnv&, jni::jboolean inProgress) void NativeMapView::moveBy(jni::JNIEnv&, jni::jdouble dx, jni::jdouble dy, jni::jlong duration) { mbgl::AnimationOptions animationOptions; if (duration > 0) { - animationOptions.duration.emplace(mbgl::Milliseconds(duration)); - animationOptions.easing.emplace(mbgl::util::UnitBezier {0.1, 0.4, 0.35, 1.0}); + animationOptions.duration.emplace(mbgl::Milliseconds(duration)); + animationOptions.easing.emplace(mbgl::util::UnitBezier{0.1, 0.4, 0.35, 1.0}); } map->moveBy({dx, dy}, animationOptions); } -void NativeMapView::jumpTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble latitude, jni::jdouble longitude, jni::jdouble pitch, jni::jdouble zoom, const jni::Array& padding) { +void NativeMapView::jumpTo( + jni::JNIEnv& env, + jni::jdouble bearing, + jni::jdouble latitude, + jni::jdouble longitude, + jni::jdouble pitch, + jni::jdouble zoom, + const jni::Array& padding +) { mbgl::CameraOptions options; if (bearing != -1) { options.bearing = bearing; @@ -342,8 +358,8 @@ void NativeMapView::jumpTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble options.center = mbgl::LatLng(latitude, longitude); if (padding) { assert(padding.Length(env) == 4); - options.padding = mbgl::EdgeInsets{padding.Get(env, 0), padding.Get(env, 1), - padding.Get(env, 2), padding.Get(env, 3)}; + options.padding = mbgl::EdgeInsets{ + padding.Get(env, 0), padding.Get(env, 1), padding.Get(env, 2), padding.Get(env, 3)}; } if (pitch != -1) { options.pitch = pitch; @@ -355,7 +371,17 @@ void NativeMapView::jumpTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble map->jumpTo(options); } -void NativeMapView::easeTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble latitude, jni::jdouble longitude, jni::jlong duration, jni::jdouble pitch, jni::jdouble zoom, const jni::Array& padding, jni::jboolean easing) { +void NativeMapView::easeTo( + jni::JNIEnv& env, + jni::jdouble bearing, + jni::jdouble latitude, + jni::jdouble longitude, + jni::jlong duration, + jni::jdouble pitch, + jni::jdouble zoom, + const jni::Array& padding, + jni::jboolean easing +) { mbgl::CameraOptions cameraOptions; if (bearing != -1) { cameraOptions.bearing = bearing; @@ -363,8 +389,8 @@ void NativeMapView::easeTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble cameraOptions.center = mbgl::LatLng(latitude, longitude); if (padding) { assert(padding.Length(env) == 4); - cameraOptions.padding = mbgl::EdgeInsets{padding.Get(env, 0), padding.Get(env, 1), - padding.Get(env, 2), padding.Get(env, 3)}; + cameraOptions.padding = mbgl::EdgeInsets{ + padding.Get(env, 0), padding.Get(env, 1), padding.Get(env, 2), padding.Get(env, 3)}; } if (pitch != -1) { cameraOptions.pitch = pitch; @@ -376,14 +402,23 @@ void NativeMapView::easeTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble mbgl::AnimationOptions animationOptions; animationOptions.duration.emplace(mbgl::Milliseconds(duration)); if (!easing) { - // add a linear interpolator instead of easing - animationOptions.easing.emplace(mbgl::util::UnitBezier { 0, 0, 1, 1 }); + // add a linear interpolator instead of easing + animationOptions.easing.emplace(mbgl::util::UnitBezier{0, 0, 1, 1}); } map->easeTo(cameraOptions, animationOptions); } -void NativeMapView::flyTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble latitude, jni::jdouble longitude, jni::jlong duration, jni::jdouble pitch, jni::jdouble zoom, const jni::Array& padding) { +void NativeMapView::flyTo( + jni::JNIEnv& env, + jni::jdouble bearing, + jni::jdouble latitude, + jni::jdouble longitude, + jni::jlong duration, + jni::jdouble pitch, + jni::jdouble zoom, + const jni::Array& padding +) { mbgl::CameraOptions cameraOptions; if (bearing != -1) { cameraOptions.bearing = bearing; @@ -391,8 +426,8 @@ void NativeMapView::flyTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble l cameraOptions.center = mbgl::LatLng(latitude, longitude); if (padding) { assert(padding.Length(env) == 4); - cameraOptions.padding = mbgl::EdgeInsets{padding.Get(env, 0), padding.Get(env, 1), - padding.Get(env, 2), padding.Get(env, 3)}; + cameraOptions.padding = mbgl::EdgeInsets{ + padding.Get(env, 0), padding.Get(env, 1), padding.Get(env, 2), padding.Get(env, 3)}; } if (pitch != -1) { cameraOptions.pitch = pitch; @@ -410,23 +445,51 @@ jni::Local> NativeMapView::getLatLng(JNIEnv& env) { return LatLng::New(env, *map->getCameraOptions(std::nullopt).center); } -void NativeMapView::setLatLng(jni::JNIEnv& env, jni::jdouble latitude, jni::jdouble longitude, const jni::Array& padding, jni::jlong duration) { +void NativeMapView::setLatLng( + jni::JNIEnv& env, + jni::jdouble latitude, + jni::jdouble longitude, + const jni::Array& padding, + jni::jlong duration +) { mbgl::CameraOptions cameraOptions; cameraOptions.center = mbgl::LatLng(latitude, longitude); if (padding) { assert(padding.Length(env) == 4); - cameraOptions.padding = mbgl::EdgeInsets{padding.Get(env, 0), padding.Get(env, 1), - padding.Get(env, 2), padding.Get(env, 3)}; + cameraOptions.padding = mbgl::EdgeInsets{ + padding.Get(env, 0), padding.Get(env, 1), padding.Get(env, 2), padding.Get(env, 3)}; } map->easeTo(cameraOptions, mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); } -jni::Local> NativeMapView::getCameraForLatLngBounds(jni::JNIEnv& env, const jni::Object& jBounds, double top, double left, double bottom, double right, double bearing, double tilt) { +jni::Local> NativeMapView::getCameraForLatLngBounds( + jni::JNIEnv& env, + const jni::Object& jBounds, + double top, + double left, + double bottom, + double right, + double bearing, + double tilt +) { mbgl::EdgeInsets padding = {top, left, bottom, right}; - return CameraPosition::New(env, map->cameraForLatLngBounds(mbgl::android::LatLngBounds::getLatLngBounds(env, jBounds), padding, bearing, tilt), pixelRatio); + return CameraPosition::New( + env, + map->cameraForLatLngBounds(mbgl::android::LatLngBounds::getLatLngBounds(env, jBounds), padding, bearing, tilt), + pixelRatio + ); } -jni::Local> NativeMapView::getCameraForGeometry(jni::JNIEnv& env, const jni::Object& jGeometry, double top, double left, double bottom, double right, double bearing, double tilt) { +jni::Local> NativeMapView::getCameraForGeometry( + jni::JNIEnv& env, + const jni::Object& jGeometry, + double top, + double left, + double bottom, + double right, + double bearing, + double tilt +) { auto geometry = geojson::Geometry::convert(env, jGeometry); mbgl::EdgeInsets padding = {top, left, bottom, right}; return CameraPosition::New(env, map->cameraForGeometry(geometry, padding, bearing, tilt), pixelRatio); @@ -439,7 +502,7 @@ void NativeMapView::setReachability(jni::JNIEnv&, jni::jboolean reachable) { } void NativeMapView::resetPosition(jni::JNIEnv&) { - map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng {}).withZoom(0.0).withBearing(0.0).withPitch(0.0)); + map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng{}).withZoom(0.0).withBearing(0.0).withPitch(0.0)); } jni::jdouble NativeMapView::getPitch(jni::JNIEnv&) { @@ -447,13 +510,14 @@ jni::jdouble NativeMapView::getPitch(jni::JNIEnv&) { } void NativeMapView::setPitch(jni::JNIEnv&, jni::jdouble pitch, jni::jlong duration) { - map->easeTo(mbgl::CameraOptions().withPitch(pitch), - mbgl::AnimationOptions{ mbgl::Milliseconds(duration) }); + map->easeTo(mbgl::CameraOptions().withPitch(pitch), mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); } void NativeMapView::setZoom(jni::JNIEnv&, jni::jdouble zoom, jni::jdouble x, jni::jdouble y, jni::jlong duration) { - map->easeTo(mbgl::CameraOptions().withZoom(zoom).withAnchor(mbgl::ScreenCoordinate{ x, y }), - mbgl::AnimationOptions{ mbgl::Milliseconds(duration) }); + map->easeTo( + mbgl::CameraOptions().withZoom(zoom).withAnchor(mbgl::ScreenCoordinate{x, y}), + mbgl::AnimationOptions{mbgl::Milliseconds(duration)} + ); } jni::jdouble NativeMapView::getZoom(jni::JNIEnv&) { @@ -496,7 +560,9 @@ jni::jdouble NativeMapView::getMaxPitch(jni::JNIEnv&) { return *map->getBounds().maxPitch; } -void NativeMapView::rotateBy(jni::JNIEnv&, jni::jdouble sx, jni::jdouble sy, jni::jdouble ex, jni::jdouble ey, jni::jlong duration) { +void NativeMapView::rotateBy( + jni::JNIEnv&, jni::jdouble sx, jni::jdouble sy, jni::jdouble ex, jni::jdouble ey, jni::jlong duration +) { mbgl::ScreenCoordinate first(sx, sy); mbgl::ScreenCoordinate second(ex, ey); map->rotateBy(first, second, mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); @@ -506,9 +572,14 @@ void NativeMapView::setBearing(jni::JNIEnv&, jni::jdouble degrees, jni::jlong du map->easeTo(mbgl::CameraOptions().withBearing(degrees), mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); } -void NativeMapView::setBearingXY(jni::JNIEnv&, jni::jdouble degrees, jni::jdouble cx, jni::jdouble cy, jni::jlong duration) { +void NativeMapView::setBearingXY( + jni::JNIEnv&, jni::jdouble degrees, jni::jdouble cx, jni::jdouble cy, jni::jlong duration +) { mbgl::ScreenCoordinate anchor(cx, cy); - map->easeTo(mbgl::CameraOptions().withBearing(degrees).withAnchor(anchor), mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); + map->easeTo( + mbgl::CameraOptions().withBearing(degrees).withAnchor(anchor), + mbgl::AnimationOptions{mbgl::Milliseconds(duration)} + ); } jni::jdouble NativeMapView::getBearing(jni::JNIEnv&) { @@ -516,10 +587,16 @@ jni::jdouble NativeMapView::getBearing(jni::JNIEnv&) { } void NativeMapView::resetNorth(jni::JNIEnv&) { - map->easeTo(mbgl::CameraOptions().withBearing(0.0), mbgl::AnimationOptions {{mbgl::Milliseconds(500)}}); + map->easeTo(mbgl::CameraOptions().withBearing(0.0), mbgl::AnimationOptions{{mbgl::Milliseconds(500)}}); } -void NativeMapView::setVisibleCoordinateBounds(JNIEnv& env, const jni::Array>& coordinates, const jni::Object& padding, jdouble direction, jni::jlong duration) { +void NativeMapView::setVisibleCoordinateBounds( + JNIEnv& env, + const jni::Array>& coordinates, + const jni::Object& padding, + jdouble direction, + jni::jlong duration +) { NullCheck(env, &coordinates); std::size_t count = coordinates.Length(env); @@ -530,7 +607,11 @@ void NativeMapView::setVisibleCoordinateBounds(JNIEnv& env, const jni::ArraycameraForLatLngs(latLngs, mbglInsets); if (direction >= 0) { cameraOptions.bearing = direction; @@ -540,7 +621,7 @@ void NativeMapView::setVisibleCoordinateBounds(JNIEnv& env, const jni::Array 0) { animationOptions.duration.emplace(mbgl::Milliseconds(duration)); // equivalent to kCAMediaTimingFunctionDefault in iOS - animationOptions.easing.emplace(mbgl::util::UnitBezier { 0.25, 0.1, 0.25, 0.1 }); + animationOptions.easing.emplace(mbgl::util::UnitBezier{0.25, 0.1, 0.25, 0.1}); } map->easeTo(cameraOptions, animationOptions); @@ -574,7 +655,7 @@ void NativeMapView::scheduleSnapshot(jni::JNIEnv&) { // invoke Mapview#OnSnapshotReady static auto& javaClass = jni::Class::Singleton(*_env); - static auto onSnapshotReady = javaClass.GetMethod)>(*_env, "onSnapshotReady"); + static auto onSnapshotReady = javaClass.GetMethod)>(*_env, "onSnapshotReady"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onSnapshotReady, bitmap); @@ -586,17 +667,21 @@ jni::Local> NativeMapView::getCameraPosition(jni::JN return CameraPosition::New(env, map->getCameraOptions(std::nullopt), pixelRatio); } -void NativeMapView::updateMarker(jni::JNIEnv& env, jni::jlong markerId, jni::jdouble lat, jni::jdouble lon, const jni::String& jid) { +void NativeMapView::updateMarker( + jni::JNIEnv& env, jni::jlong markerId, jni::jdouble lat, jni::jdouble lon, const jni::String& jid +) { if (markerId == -1) { return; } std::string iconId = jni::Make(env, jid); // Because Java only has int, not unsigned int, we need to bump the annotation id up to a long. - map->updateAnnotation(markerId, mbgl::SymbolAnnotation { mbgl::Point(lon, lat), iconId }); + map->updateAnnotation(markerId, mbgl::SymbolAnnotation{mbgl::Point(lon, lat), iconId}); } -jni::Local> NativeMapView::addMarkers(jni::JNIEnv& env, const jni::Array>& jmarkers) { +jni::Local> NativeMapView::addMarkers( + jni::JNIEnv& env, const jni::Array>& jmarkers +) { jni::NullCheck(env, &jmarkers); std::size_t len = jmarkers.Length(env); @@ -605,10 +690,8 @@ jni::Local> NativeMapView::addMarkers(jni::JNIEnv& env, c for (std::size_t i = 0; i < len; i++) { auto marker = jmarkers.Get(env, i); - ids.push_back(map->addAnnotation(mbgl::SymbolAnnotation { - Marker::getPosition(env, marker), - Marker::getIconId(env, marker) - })); + ids.push_back(map->addAnnotation(mbgl::SymbolAnnotation{ + Marker::getPosition(env, marker), Marker::getIconId(env, marker)})); } auto result = jni::Array::New(env, len); @@ -641,12 +724,17 @@ jni::jdouble NativeMapView::getMetersPerPixelAtLatitude(JNIEnv&, jni::jdouble la return mbgl::Projection::getMetersPerPixelAtLatitude(lat, zoom); } -jni::Local> NativeMapView::projectedMetersForLatLng(JNIEnv& env, jni::jdouble latitude, jni::jdouble longitude) { - mbgl::ProjectedMeters projectedMeters = mbgl::Projection::projectedMetersForLatLng(mbgl::LatLng(latitude, longitude)); +jni::Local> NativeMapView::projectedMetersForLatLng( + JNIEnv& env, jni::jdouble latitude, jni::jdouble longitude +) { + mbgl::ProjectedMeters projectedMeters = mbgl::Projection::projectedMetersForLatLng(mbgl::LatLng(latitude, longitude) + ); return ProjectedMeters::New(env, projectedMeters.northing(), projectedMeters.easting()); } -jni::Local> NativeMapView::latLngForProjectedMeters(JNIEnv& env, jdouble northing, jdouble easting) { +jni::Local> NativeMapView::latLngForProjectedMeters( + JNIEnv& env, jdouble northing, jdouble easting +) { return LatLng::New(env, mbgl::Projection::latLngForProjectedMeters(mbgl::ProjectedMeters(northing, easting))); } @@ -655,10 +743,9 @@ jni::Local> NativeMapView::pixelForLatLng(JNIEnv& env, jdoub return PointF::New(env, static_cast(pixel.x), static_cast(pixel.y)); } -void NativeMapView::pixelsForLatLngs(JNIEnv& env, - const jni::Array& input, - jni::Array& output, - jfloat pixelRatio_) { +void NativeMapView::pixelsForLatLngs( + JNIEnv& env, const jni::Array& input, jni::Array& output, jfloat pixelRatio_ +) { jni::NullCheck(env, &input); std::size_t len = input.Length(env); @@ -685,10 +772,9 @@ jni::Local> NativeMapView::latLngForPixel(JNIEnv& env, jfloa return LatLng::New(env, map->latLngForPixel(mbgl::ScreenCoordinate(x, y))); } -void NativeMapView::latLngsForPixels(JNIEnv& env, - const jni::Array& input, - jni::Array& output, - jfloat pixelRatio_) { +void NativeMapView::latLngsForPixels( + JNIEnv& env, const jni::Array& input, jni::Array& output, jfloat pixelRatio_ +) { jni::NullCheck(env, &input); std::size_t len = input.Length(env); @@ -711,7 +797,9 @@ void NativeMapView::latLngsForPixels(JNIEnv& env, output.SetRegion>(env, 0, buffer); } -jni::Local> NativeMapView::addPolylines(JNIEnv& env, const jni::Array>& polylines) { +jni::Local> NativeMapView::addPolylines( + JNIEnv& env, const jni::Array>& polylines +) { NullCheck(env, &polylines); std::size_t len = polylines.Length(env); @@ -729,8 +817,9 @@ jni::Local> NativeMapView::addPolylines(JNIEnv& env, const jni return result; } - -jni::Local> NativeMapView::addPolygons(JNIEnv& env, const jni::Array>& polygons) { +jni::Local> NativeMapView::addPolygons( + JNIEnv& env, const jni::Array>& polygons +) { NullCheck(env, &polygons); std::size_t len = polygons.Length(env); @@ -765,27 +854,30 @@ void NativeMapView::removeAnnotations(JNIEnv& env, const jni::Array& ids) jlong* jids = std::get<0>(elements).get(); for (std::size_t i = 0; i < len; i++) { - if(jids[i] == -1L) { - continue; + if (jids[i] == -1L) { + continue; } map->removeAnnotation(jids[i]); } } -void NativeMapView::addAnnotationIcon(JNIEnv& env, const jni::String& symbol, jint w, jint h, jfloat scale, const jni::Array& jpixels) { +void NativeMapView::addAnnotationIcon( + JNIEnv& env, const jni::String& symbol, jint w, jint h, jfloat scale, const jni::Array& jpixels +) { const std::string symbolName = jni::Make(env, symbol); NullCheck(env, &jpixels); std::size_t size = jpixels.Length(env); - mbgl::PremultipliedImage premultipliedImage({ static_cast(w), static_cast(h) }); + mbgl::PremultipliedImage premultipliedImage({static_cast(w), static_cast(h)}); if (premultipliedImage.bytes() != uint32_t(size)) { throw mbgl::util::StyleImageException("Annotation icon image pixel count mismatch"); } jni::GetArrayRegion(env, *jpixels, 0, size, reinterpret_cast(premultipliedImage.data.get())); - map->addAnnotationImage(std::make_unique( - symbolName, std::move(premultipliedImage), static_cast(scale))); + map->addAnnotationImage( + std::make_unique(symbolName, std::move(premultipliedImage), static_cast(scale)) + ); } void NativeMapView::removeAnnotationIcon(JNIEnv& env, const jni::String& symbol) { @@ -799,17 +891,22 @@ jdouble NativeMapView::getTopOffsetPixelsForAnnotationSymbol(JNIEnv& env, const jni::Local> NativeMapView::getTransitionOptions(JNIEnv& env) { const auto transitionOptions = map->getStyle().getTransitionOptions(); - const auto duration = std::chrono::duration_cast(transitionOptions.duration.value_or(mbgl::Duration::zero())).count(); - const auto delay = std::chrono::duration_cast(transitionOptions.delay.value_or(mbgl::Duration::zero())).count(); - const auto enablePlacementTransitions = (jboolean) transitionOptions.enablePlacementTransitions; + const auto duration = std::chrono::duration_cast( + transitionOptions.duration.value_or(mbgl::Duration::zero()) + ) + .count(); + const auto delay = + std::chrono::duration_cast(transitionOptions.delay.value_or(mbgl::Duration::zero())) + .count(); + const auto enablePlacementTransitions = (jboolean)transitionOptions.enablePlacementTransitions; return TransitionOptions::fromTransitionOptions(env, duration, delay, enablePlacementTransitions); } void NativeMapView::setTransitionOptions(JNIEnv& env, const jni::Object& options) { const mbgl::style::TransitionOptions transitionOptions( - Duration(mbgl::Milliseconds(TransitionOptions::getDuration(env, options))), - Duration(mbgl::Milliseconds(TransitionOptions::getDelay(env, options))), - TransitionOptions::isEnablePlacementTransitions(env, options) + Duration(mbgl::Milliseconds(TransitionOptions::getDuration(env, options))), + Duration(mbgl::Milliseconds(TransitionOptions::getDelay(env, options))), + TransitionOptions::isEnablePlacementTransitions(env, options) ); map->getStyle().setTransitionOptions(transitionOptions); } @@ -820,8 +917,8 @@ jni::Local> NativeMapView::queryPointAnnotations(JNIEnv& env, // Convert input mbgl::ScreenBox box = { - { RectF::getLeft(env, rect), RectF::getTop(env, rect) }, - { RectF::getRight(env, rect), RectF::getBottom(env, rect) }, + {RectF::getLeft(env, rect), RectF::getTop(env, rect)}, + {RectF::getRight(env, rect), RectF::getBottom(env, rect)}, }; // Assume only points for now @@ -841,8 +938,8 @@ jni::Local> NativeMapView::queryShapeAnnotations(JNIEnv& env, // Convert input mbgl::ScreenBox box = { - {RectF::getLeft(env, rect), RectF::getTop(env, rect)}, - {RectF::getRight(env, rect), RectF::getBottom(env, rect)}, + {RectF::getLeft(env, rect), RectF::getTop(env, rect)}, + {RectF::getRight(env, rect), RectF::getBottom(env, rect)}, }; mbgl::AnnotationIDs ids = rendererFrontend->queryShapeAnnotations(box); @@ -855,9 +952,13 @@ jni::Local> NativeMapView::queryShapeAnnotations(JNIEnv& env, return result; } -jni::Local>> NativeMapView::queryRenderedFeaturesForPoint(JNIEnv& env, jni::jfloat x, jni::jfloat y, - const jni::Array& layerIds, - const jni::Array>& jfilter) { +jni::Local>> NativeMapView::queryRenderedFeaturesForPoint( + JNIEnv& env, + jni::jfloat x, + jni::jfloat y, + const jni::Array& layerIds, + const jni::Array>& jfilter +) { using namespace mbgl::android::conversion; using namespace mbgl::android::geojson; @@ -867,14 +968,18 @@ jni::Local>> NativeMapView::queryRender } mapbox::geometry::point point = {x, y}; - return Feature::convert( - env, - rendererFrontend->queryRenderedFeatures(point, { layers, toFilter(env, jfilter) })); + return Feature::convert(env, rendererFrontend->queryRenderedFeatures(point, {layers, toFilter(env, jfilter)})); } -jni::Local>> NativeMapView::queryRenderedFeaturesForBox(JNIEnv& env, jni::jfloat left, jni::jfloat top, - jni::jfloat right, jni::jfloat bottom, const jni::Array& layerIds, - const jni::Array>& jfilter) { +jni::Local>> NativeMapView::queryRenderedFeaturesForBox( + JNIEnv& env, + jni::jfloat left, + jni::jfloat top, + jni::jfloat right, + jni::jfloat bottom, + const jni::Array& layerIds, + const jni::Array>& jfilter +) { using namespace mbgl::android::conversion; using namespace mbgl::android::geojson; @@ -883,13 +988,9 @@ jni::Local>> NativeMapView::queryRender layers = toVector(env, layerIds); } mapbox::geometry::box box = { - mapbox::geometry::point{ left, top}, - mapbox::geometry::point{ right, bottom } - }; + mapbox::geometry::point{left, top}, mapbox::geometry::point{right, bottom}}; - return Feature::convert( - env, - rendererFrontend->queryRenderedFeatures(box, { layers, toFilter(env, jfilter) })); + return Feature::convert(env, rendererFrontend->queryRenderedFeatures(box, {layers, toFilter(env, jfilter)})); } jni::Local> NativeMapView::getLight(JNIEnv& env) { @@ -902,7 +1003,6 @@ jni::Local> NativeMapView::getLight(JNIEnv& env) { } jni::Local>> NativeMapView::getLayers(JNIEnv& env) { - // Get the core layers std::vector layers = map->getStyle().getLayers(); @@ -918,12 +1018,11 @@ jni::Local>> NativeMapView::getLayers(JNIEnv& env) } jni::Local> NativeMapView::getLayer(JNIEnv& env, const jni::String& layerId) { - // Find the layer mbgl::style::Layer* coreLayer = map->getStyle().getLayer(jni::Make(env, layerId)); if (!coreLayer) { - mbgl::Log::Debug(mbgl::Event::JNI, "No layer found"); - return jni::Local>(); + mbgl::Log::Debug(mbgl::Event::JNI, "No layer found"); + return jni::Local>(); } // Create and return the layer's native peer @@ -933,20 +1032,23 @@ jni::Local> NativeMapView::getLayer(JNIEnv& env, const jni::S void NativeMapView::addLayer(JNIEnv& env, jlong nativeLayerPtr, const jni::String& before) { assert(nativeLayerPtr != 0); - Layer *layer = reinterpret_cast(nativeLayerPtr); + Layer* layer = reinterpret_cast(nativeLayerPtr); try { layer->addToStyle( map->getStyle(), - before ? std::optional(jni::Make(env, before)) : std::optional()); + before ? std::optional(jni::Make(env, before)) : std::optional() + ); } catch (const std::runtime_error& error) { - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + jni::ThrowNew( + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what() + ); } } void NativeMapView::addLayerAbove(JNIEnv& env, jlong nativeLayerPtr, const jni::String& above) { assert(nativeLayerPtr != 0); - Layer *layer = reinterpret_cast(nativeLayerPtr); + Layer* layer = reinterpret_cast(nativeLayerPtr); // Find the sibling auto layers = map->getStyle().getLayers(); @@ -964,34 +1066,42 @@ void NativeMapView::addLayerAbove(JNIEnv& env, jlong nativeLayerPtr, const jni:: std::optional before; if (index + 1 > layers.size()) { // Not found - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), - std::string("Could not find layer: ").append(siblingId).c_str()); + jni::ThrowNew( + env, + jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), + std::string("Could not find layer: ").append(siblingId).c_str() + ); return; } else if (index + 1 < layers.size()) { // Place before the sibling - before = { layers.at(index + 1)->getID() }; + before = {layers.at(index + 1)->getID()}; } // Add the layer try { layer->addToStyle(map->getStyle(), before); } catch (const std::runtime_error& error) { - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + jni::ThrowNew( + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what() + ); } } void NativeMapView::addLayerAt(JNIEnv& env, jlong nativeLayerPtr, jni::jint index) { assert(nativeLayerPtr != 0); - Layer *layer = reinterpret_cast(nativeLayerPtr); + Layer* layer = reinterpret_cast(nativeLayerPtr); auto layers = map->getStyle().getLayers(); // Check index int numLayers = layers.size() - 1; if (index > numLayers || index < 0) { Log::Error(Event::JNI, "Index out of range: " + std::to_string(index)); - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), - std::string("Invalid index").c_str()); + jni::ThrowNew( + env, + jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), + std::string("Invalid index").c_str() + ); return; } @@ -999,11 +1109,12 @@ void NativeMapView::addLayerAt(JNIEnv& env, jlong nativeLayerPtr, jni::jint inde try { layer->addToStyle(map->getStyle(), layers.at(index)->getID()); } catch (const std::runtime_error& error) { - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + jni::ThrowNew( + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what() + ); } } - /** * Remove layer at index. */ @@ -1019,8 +1130,9 @@ jni::jboolean NativeMapView::removeLayerAt(JNIEnv& env, jni::jint index) { std::unique_ptr coreLayer = map->getStyle().removeLayer(layers.at(index)->getID()); if (coreLayer) { - jni::Local> layerObj = - LayerManagerAndroid::get()->createJavaLayerPeer(env, std::move(coreLayer)); + jni::Local> layerObj = LayerManagerAndroid::get()->createJavaLayerPeer( + env, std::move(coreLayer) + ); return jni::jni_true; } return jni::jni_false; @@ -1032,7 +1144,7 @@ jni::jboolean NativeMapView::removeLayerAt(JNIEnv& env, jni::jint index) { jni::jboolean NativeMapView::removeLayer(JNIEnv&, jlong layerPtr) { assert(layerPtr != 0); - mbgl::android::Layer *layer = reinterpret_cast(layerPtr); + mbgl::android::Layer* layer = reinterpret_cast(layerPtr); std::unique_ptr coreLayer = map->getStyle().removeLayer(layer->get().getID()); if (coreLayer) { layer->setLayer(std::move(coreLayer)); @@ -1060,8 +1172,8 @@ jni::Local> NativeMapView::getSource(JNIEnv& env, const jni: // Find the source mbgl::style::Source* coreSource = map->getStyle().getSource(jni::Make(env, sourceId)); if (!coreSource) { - mbgl::Log::Debug(mbgl::Event::JNI, "No source found"); - return jni::Local>(); + mbgl::Log::Debug(mbgl::Event::JNI, "No source found"); + return jni::Local>(); } // Create and return the source's native peer @@ -1071,18 +1183,20 @@ jni::Local> NativeMapView::getSource(JNIEnv& env, const jni: void NativeMapView::addSource(JNIEnv& env, const jni::Object& obj, jlong sourcePtr) { assert(sourcePtr != 0); - Source *source = reinterpret_cast(sourcePtr); + Source* source = reinterpret_cast(sourcePtr); try { source->addToMap(env, obj, *map, *rendererFrontend); } catch (const std::runtime_error& error) { - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/sources/CannotAddSourceException"), error.what()); + jni::ThrowNew( + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/sources/CannotAddSourceException"), error.what() + ); } } jni::jboolean NativeMapView::removeSource(JNIEnv& env, const jni::Object& obj, jlong sourcePtr) { assert(sourcePtr != 0); - mbgl::android::Source *source = reinterpret_cast(sourcePtr); + mbgl::android::Source* source = reinterpret_cast(sourcePtr); if (source->removeFromMap(env, obj, *map)) { source->releaseJavaPeer(); return jni::jni_true; @@ -1091,16 +1205,15 @@ jni::jboolean NativeMapView::removeSource(JNIEnv& env, const jni::Object return jni::jni_false; } -void NativeMapView::addImage(JNIEnv& env, const jni::String& name, const jni::Object& bitmap, jni::jfloat scale, jni::jboolean sdf) { +void NativeMapView::addImage( + JNIEnv& env, const jni::String& name, const jni::Object& bitmap, jni::jfloat scale, jni::jboolean sdf +) { jni::NullCheck(env, &bitmap); mbgl::PremultipliedImage premultipliedImage = Bitmap::GetImage(env, bitmap); map->getStyle().addImage(std::make_unique( - jni::Make(env, name), - std::move(premultipliedImage), - static_cast(scale), - sdf) - ); + jni::Make(env, name), std::move(premultipliedImage), static_cast(scale), sdf + )); } void NativeMapView::addImages(JNIEnv& env, const jni::Array>& jimages) { @@ -1155,19 +1268,20 @@ void NativeMapView::registerNative(jni::JNIEnv& env) { // Lookup the class static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer jni::RegisterNativePeer( env, javaClass, "nativePtr", - jni::MakePeer&, - const jni::Object&, - const jni::Object&, - jni::jfloat, - jni::jboolean>, + jni::MakePeer< + NativeMapView, + const jni::Object&, + const jni::Object&, + const jni::Object&, + jni::jfloat, + jni::jboolean>, "nativeInitialize", "nativeDestroy", METHOD(&NativeMapView::resizeView, "nativeResizeView"), @@ -1257,7 +1371,8 @@ void NativeMapView::registerNative(jni::JNIEnv& env) { METHOD(&NativeMapView::getPrefetchTiles, "nativeGetPrefetchTiles"), METHOD(&NativeMapView::setPrefetchZoomDelta, "nativeSetPrefetchZoomDelta"), METHOD(&NativeMapView::getPrefetchZoomDelta, "nativeGetPrefetchZoomDelta"), - METHOD(&NativeMapView::triggerRepaint, "nativeTriggerRepaint")); + METHOD(&NativeMapView::triggerRepaint, "nativeTriggerRepaint") + ); } } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.hpp index be632e242da..f096da9d104 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.hpp @@ -40,17 +40,18 @@ class MapRenderer; class NativeMapView : public MapObserver { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/maps/NativeMapView"; }; static void registerNative(jni::JNIEnv&); - NativeMapView(jni::JNIEnv&, - const jni::Object&, - const jni::Object&, - const jni::Object&, - jni::jfloat, - jni::jboolean); + NativeMapView( + jni::JNIEnv&, + const jni::Object&, + const jni::Object&, + const jni::Object&, + jni::jfloat, + jni::jboolean + ); virtual ~NativeMapView(); @@ -91,19 +92,49 @@ class NativeMapView : public MapObserver { void moveBy(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jlong); - void jumpTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jdouble, jni::jdouble, const jni::Array&); + void + jumpTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jdouble, jni::jdouble, const jni::Array&); - void easeTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong, jni::jdouble, jni::jdouble, const jni::Array&, jni::jboolean); + void easeTo( + jni::JNIEnv&, + jni::jdouble, + jni::jdouble, + jni::jdouble, + jni::jlong, + jni::jdouble, + jni::jdouble, + const jni::Array&, + jni::jboolean + ); - void flyTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong, jni::jdouble, jni::jdouble, const jni::Array&); + void + flyTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong, jni::jdouble, jni::jdouble, const jni::Array&); jni::Local> getLatLng(JNIEnv&); void setLatLng(jni::JNIEnv&, jni::jdouble, jni::jdouble, const jni::Array&, jni::jlong); - jni::Local> getCameraForLatLngBounds(jni::JNIEnv&, const jni::Object&, double top, double left, double bottom, double right, double bearing, double tilt); - - jni::Local> getCameraForGeometry(jni::JNIEnv&, const jni::Object&, double top, double left, double bottom, double right, double bearing, double tilt); + jni::Local> getCameraForLatLngBounds( + jni::JNIEnv&, + const jni::Object&, + double top, + double left, + double bottom, + double right, + double bearing, + double tilt + ); + + jni::Local> getCameraForGeometry( + jni::JNIEnv&, + const jni::Object&, + double top, + double left, + double bottom, + double right, + double bearing, + double tilt + ); void setReachability(jni::JNIEnv&, jni::jboolean); @@ -145,7 +176,9 @@ class NativeMapView : public MapObserver { void resetNorth(jni::JNIEnv&); - void setVisibleCoordinateBounds(JNIEnv&, const jni::Array>&, const jni::Object&, jni::jdouble, jni::jlong); + void setVisibleCoordinateBounds( + JNIEnv&, const jni::Array>&, const jni::Object&, jni::jdouble, jni::jlong + ); void getVisibleCoordinateBounds(JNIEnv& env, jni::Array& output); @@ -203,13 +236,19 @@ class NativeMapView : public MapObserver { jni::Local> queryShapeAnnotations(JNIEnv&, const jni::Object&); - jni::Local>> queryRenderedFeaturesForPoint(JNIEnv&, jni::jfloat, jni::jfloat, - const jni::Array&, - const jni::Array>& jfilter); + jni::Local>> queryRenderedFeaturesForPoint( + JNIEnv&, jni::jfloat, jni::jfloat, const jni::Array&, const jni::Array>& jfilter + ); - jni::Local>> queryRenderedFeaturesForBox(JNIEnv&, jni::jfloat, jni::jfloat, jni::jfloat, - jni::jfloat, const jni::Array&, - const jni::Array>& jfilter); + jni::Local>> queryRenderedFeaturesForBox( + JNIEnv&, + jni::jfloat, + jni::jfloat, + jni::jfloat, + jni::jfloat, + const jni::Array&, + const jni::Array>& jfilter + ); jni::Local> getLight(JNIEnv&); @@ -258,7 +297,7 @@ class NativeMapView : public MapObserver { private: std::unique_ptr rendererFrontend; - JavaVM *vm = nullptr; + JavaVM* vm = nullptr; jni::WeakReference> javaPeer; MapRenderer& mapRenderer; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.cpp index e2f94eddf68..4f5ddf06bac 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.cpp @@ -11,12 +11,15 @@ namespace android { namespace { // Reattach, the callback comes from a different thread -void handleException(std::exception_ptr exception, - const jni::Object& callback, - android::UniqueEnv env = android::AttachEnv()) { +void handleException( + std::exception_ptr exception, + const jni::Object& callback, + android::UniqueEnv env = android::AttachEnv() +) { if (exception) { OfflineManager::FileSourceCallback::onError( - *env, callback, jni::Make(*env, mbgl::util::toString(exception))); + *env, callback, jni::Make(*env, mbgl::util::toString(exception)) + ); } else { OfflineManager::FileSourceCallback::onSuccess(*env, callback); } @@ -29,7 +32,9 @@ OfflineManager::OfflineManager(jni::JNIEnv& env, const jni::Object& std::shared_ptr(mbgl::FileSourceManager::get()->getFileSource( mbgl::FileSourceType::Database, FileSource::getSharedResourceOptions(env, jFileSource), - FileSource::getSharedClientOptions(env, jFileSource))))) { + FileSource::getSharedClientOptions(env, jFileSource) + )) + )) { if (!fileSource) { ThrowNew(env, jni::FindClass(env, "java/lang/IllegalStateException"), "Offline functionality is disabled."); } @@ -41,34 +46,39 @@ void OfflineManager::setOfflineMapboxTileCountLimit(jni::JNIEnv&, jni::jlong lim fileSource->setOfflineMapboxTileCountLimit(limit); } -void OfflineManager::listOfflineRegions(jni::JNIEnv& env_, const jni::Object& jFileSource_, const jni::Object& callback_) { +void OfflineManager::listOfflineRegions( + jni::JNIEnv& env_, + const jni::Object& jFileSource_, + const jni::Object& callback_ +) { auto globalCallback = jni::NewGlobal(env_, callback_); auto globalFilesource = jni::NewGlobal(env_, jFileSource_); fileSource->listOfflineRegions([ - //Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)), - jFileSource = std::make_shared(std::move(globalFilesource)) - ](mbgl::expected regions) mutable { - + // Keep a shared ptr to a global reference of the callback and file source so + // they are not GC'd in the meanwhile + callback = std::make_shared(std::move(globalCallback)), + jFileSource = std::make_shared( + std::move(globalFilesource) + )](mbgl::expected regions) mutable { // Reattach, the callback comes from a different thread android::UniqueEnv env = android::AttachEnv(); if (regions) { - OfflineManager::ListOfflineRegionsCallback::onList( - *env, *jFileSource, *callback, *regions); + OfflineManager::ListOfflineRegionsCallback::onList(*env, *jFileSource, *callback, *regions); } else { - OfflineManager::ListOfflineRegionsCallback::onError( - *env, *callback, regions.error()); + OfflineManager::ListOfflineRegionsCallback::onError(*env, *callback, regions.error()); } }); } -void OfflineManager::createOfflineRegion(jni::JNIEnv& env_, - const jni::Object& jFileSource_, - const jni::Object& definition_, - const jni::Array& metadata_, - const jni::Object& callback_) { +void OfflineManager::createOfflineRegion( + jni::JNIEnv& env_, + const jni::Object& jFileSource_, + const jni::Object& definition_, + const jni::Array& metadata_, + const jni::Object& callback_ +) { // Convert auto definition = OfflineRegionDefinition::getDefinition(env_, definition_); @@ -81,50 +91,55 @@ void OfflineManager::createOfflineRegion(jni::JNIEnv& env_, auto globalFilesource = jni::NewGlobal(env_, jFileSource_); // Create region - fileSource->createOfflineRegion(definition, metadata, [ - //Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)), - jFileSource = std::make_shared(std::move(globalFilesource)) - ](mbgl::expected region) mutable { - - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (region) { - OfflineManager::CreateOfflineRegionCallback::onCreate( - *env, *jFileSource, *callback, *region - ); - } else { - OfflineManager::CreateOfflineRegionCallback::onError( - *env, *callback, region.error()); + fileSource->createOfflineRegion( + definition, + metadata, + [ + // Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the + // meanwhile + callback = std::make_shared(std::move(globalCallback)), + jFileSource = std::make_shared(std::move(globalFilesource) + )](mbgl::expected region) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (region) { + OfflineManager::CreateOfflineRegionCallback::onCreate(*env, *jFileSource, *callback, *region); + } else { + OfflineManager::CreateOfflineRegionCallback::onError(*env, *callback, region.error()); + } } - }); + ); } -void OfflineManager::mergeOfflineRegions(jni::JNIEnv& env_, const jni::Object& jFileSource_, - const jni::String& jString_, - const jni::Object& callback_) { +void OfflineManager::mergeOfflineRegions( + jni::JNIEnv& env_, + const jni::Object& jFileSource_, + const jni::String& jString_, + const jni::Object& callback_ +) { auto globalCallback = jni::NewGlobal(env_, callback_); auto globalFilesource = jni::NewGlobal(env_, jFileSource_); auto path = jni::Make(env_, jString_); - fileSource->mergeOfflineRegions(path, [ - //Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)), - jFileSource = std::make_shared(std::move(globalFilesource)) - ](mbgl::expected regions) mutable { - - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (regions) { - OfflineManager::MergeOfflineRegionsCallback::onMerge( - *env, *jFileSource, *callback, *regions); - } else { - OfflineManager::MergeOfflineRegionsCallback::onError( - *env, *callback, regions.error()); + fileSource->mergeOfflineRegions( + path, + [ + // Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the + // meanwhile + callback = std::make_shared(std::move(globalCallback)), + jFileSource = std::make_shared(std::move(globalFilesource) + )](mbgl::expected regions) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (regions) { + OfflineManager::MergeOfflineRegionsCallback::onMerge(*env, *jFileSource, *callback, *regions); + } else { + OfflineManager::MergeOfflineRegionsCallback::onError(*env, *callback, regions.error()); + } } - }); + ); } void OfflineManager::resetDatabase(jni::JNIEnv& env_, const jni::Object& callback_) { @@ -133,8 +148,9 @@ void OfflineManager::resetDatabase(jni::JNIEnv& env_, const jni::ObjectresetDatabase( [ // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback))]( - std::exception_ptr exception) mutable { handleException(exception, *callback); }); + callback = std::make_shared(std::move(globalCallback) + )](std::exception_ptr exception) mutable { handleException(exception, *callback); } + ); } void OfflineManager::packDatabase(jni::JNIEnv& env_, const jni::Object& callback_) { @@ -143,8 +159,9 @@ void OfflineManager::packDatabase(jni::JNIEnv& env_, const jni::ObjectpackDatabase( [ // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback))]( - std::exception_ptr exception) mutable { handleException(exception, *callback); }); + callback = std::make_shared(std::move(globalCallback) + )](std::exception_ptr exception) mutable { handleException(exception, *callback); } + ); } void OfflineManager::invalidateAmbientCache(jni::JNIEnv& env_, const jni::Object& callback_) { @@ -153,8 +170,9 @@ void OfflineManager::invalidateAmbientCache(jni::JNIEnv& env_, const jni::Object fileSource->invalidateAmbientCache( [ // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback))]( - std::exception_ptr exception) mutable { handleException(exception, *callback); }); + callback = std::make_shared(std::move(globalCallback) + )](std::exception_ptr exception) mutable { handleException(exception, *callback); } + ); } void OfflineManager::clearAmbientCache(jni::JNIEnv& env_, const jni::Object& callback_) { @@ -163,19 +181,23 @@ void OfflineManager::clearAmbientCache(jni::JNIEnv& env_, const jni::ObjectclearAmbientCache( [ // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback))]( - std::exception_ptr exception) mutable { handleException(exception, *callback); }); + callback = std::make_shared(std::move(globalCallback) + )](std::exception_ptr exception) mutable { handleException(exception, *callback); } + ); } -void OfflineManager::setMaximumAmbientCacheSize(jni::JNIEnv& env_, const jni::jlong size_, const jni::Object& callback_) { +void OfflineManager::setMaximumAmbientCacheSize( + jni::JNIEnv& env_, const jni::jlong size_, const jni::Object& callback_ +) { auto globalCallback = jni::NewGlobal(env_, callback_); fileSource->setMaximumAmbientCacheSize( size_, [ // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback))]( - std::exception_ptr exception) mutable { handleException(exception, *callback); }); + callback = std::make_shared(std::move(globalCallback) + )](std::exception_ptr exception) mutable { handleException(exception, *callback); } + ); } void OfflineManager::runPackDatabaseAutomatically(jni::JNIEnv&, jboolean autopack) { @@ -184,18 +206,19 @@ void OfflineManager::runPackDatabaseAutomatically(jni::JNIEnv&, jboolean autopac // FileSource::FileSourceCallback // -void OfflineManager::FileSourceCallback::onSuccess(jni::JNIEnv& env, - const jni::Object& callback) { +void OfflineManager::FileSourceCallback::onSuccess( + jni::JNIEnv& env, const jni::Object& callback +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onSuccess"); + static auto method = javaClass.GetMethod(env, "onSuccess"); callback.Call(env, method); } -void OfflineManager::FileSourceCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - const jni::String& message) { +void OfflineManager::FileSourceCallback::onError( + jni::JNIEnv& env, const jni::Object& callback, const jni::String& message +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, message); } @@ -207,7 +230,7 @@ void OfflineManager::registerNative(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) jni::RegisterNativePeer( env, @@ -226,26 +249,29 @@ void OfflineManager::registerNative(jni::JNIEnv& env) { METHOD(&OfflineManager::clearAmbientCache, "nativeClearAmbientCache"), METHOD(&OfflineManager::setMaximumAmbientCacheSize, "nativeSetMaximumAmbientCacheSize"), METHOD(&OfflineManager::runPackDatabaseAutomatically, "runPackDatabaseAutomatically"), - METHOD(&OfflineManager::putResourceWithUrl, "putResourceWithUrl")); + METHOD(&OfflineManager::putResourceWithUrl, "putResourceWithUrl") + ); } // OfflineManager::ListOfflineRegionsCallback // -void OfflineManager::ListOfflineRegionsCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineManager::ListOfflineRegionsCallback::onError( + jni::JNIEnv& env, const jni::Object& callback, std::exception_ptr error +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineManager::ListOfflineRegionsCallback::onList(jni::JNIEnv& env, - const jni::Object& jFileSource, - const jni::Object& callback, - mbgl::OfflineRegions& regions) { +void OfflineManager::ListOfflineRegionsCallback::onList( + jni::JNIEnv& env, + const jni::Object& jFileSource, + const jni::Object& callback, + mbgl::OfflineRegions& regions +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod>)>(env, "onList"); + static auto method = javaClass.GetMethod>)>(env, "onList"); std::size_t index = 0; auto jregions = jni::Array>::New(env, regions.size()); @@ -259,42 +285,46 @@ void OfflineManager::ListOfflineRegionsCallback::onList(jni::JNIEnv& env, // OfflineManager::CreateOfflineRegionCallback // -void OfflineManager::CreateOfflineRegionCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineManager::CreateOfflineRegionCallback::onError( + jni::JNIEnv& env, const jni::Object& callback, std::exception_ptr error +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineManager::CreateOfflineRegionCallback::onCreate(jni::JNIEnv& env, - const jni::Object& jFileSource, - const jni::Object& callback, - mbgl::OfflineRegion& region) { +void OfflineManager::CreateOfflineRegionCallback::onCreate( + jni::JNIEnv& env, + const jni::Object& jFileSource, + const jni::Object& callback, + mbgl::OfflineRegion& region +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod)>(env, "onCreate"); + static auto method = javaClass.GetMethod)>(env, "onCreate"); callback.Call(env, method, OfflineRegion::New(env, jFileSource, std::move(region))); } // OfflineManager::MergeOfflineRegionsCallback // -void OfflineManager::MergeOfflineRegionsCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineManager::MergeOfflineRegionsCallback::onError( + jni::JNIEnv& env, const jni::Object& callback, std::exception_ptr error +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineManager::MergeOfflineRegionsCallback::onMerge(jni::JNIEnv& env, - const jni::Object& jFileSource, - const jni::Object& callback, - mbgl::OfflineRegions& regions) { +void OfflineManager::MergeOfflineRegionsCallback::onMerge( + jni::JNIEnv& env, + const jni::Object& jFileSource, + const jni::Object& callback, + mbgl::OfflineRegions& regions +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod>)>(env, "onMerge"); + static auto method = javaClass.GetMethod>)>(env, "onMerge"); std::size_t index = 0; auto jregions = jni::Array>::New(env, regions.size()); @@ -306,14 +336,16 @@ void OfflineManager::MergeOfflineRegionsCallback::onMerge(jni::JNIEnv& env, callback.Call(env, method, jregions); } -void OfflineManager::putResourceWithUrl(jni::JNIEnv& env, - const jni::String& url_, - const jni::Array& arr, - jlong modified, - jlong expires, - const jni::String& eTag_, - jboolean mustRevalidate) { - auto url = jni::Make(env, url_); +void OfflineManager::putResourceWithUrl( + jni::JNIEnv& env, + const jni::String& url_, + const jni::Array& arr, + jlong modified, + jlong expires, + const jni::String& eTag_, + jboolean mustRevalidate +) { + auto url = jni::Make(env, url_); auto data = std::make_shared(arr.Length(env), char()); jni::GetArrayRegion(env, *arr, 0, data->size(), reinterpret_cast(&(*data)[0])); mbgl::Resource resource(mbgl::Resource::Kind::Unknown, url); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.hpp index 84111a74235..931a0ea4629 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.hpp @@ -16,45 +16,50 @@ namespace android { class OfflineManager { public: - class ListOfflineRegionsCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$ListOfflineRegionsCallback";} + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/OfflineManager$ListOfflineRegionsCallback"; + } - static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); + static void onError( + jni::JNIEnv&, const jni::Object&, std::exception_ptr + ); - static void onList(jni::JNIEnv&, - const jni::Object&, - const jni::Object&, - mbgl::OfflineRegions&); + static void + onList(jni::JNIEnv&, const jni::Object&, const jni::Object&, mbgl::OfflineRegions&); }; class CreateOfflineRegionCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$CreateOfflineRegionCallback"; } + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/OfflineManager$CreateOfflineRegionCallback"; + } - static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); + static void onError( + jni::JNIEnv&, const jni::Object&, std::exception_ptr + ); - static void onCreate(jni::JNIEnv&, - const jni::Object&, - const jni::Object&, - mbgl::OfflineRegion&); + static void + onCreate(jni::JNIEnv&, const jni::Object&, const jni::Object&, mbgl::OfflineRegion&); }; class MergeOfflineRegionsCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$MergeOfflineRegionsCallback";} + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/OfflineManager$MergeOfflineRegionsCallback"; + } - static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); + static void onError( + jni::JNIEnv&, const jni::Object&, std::exception_ptr + ); - static void onMerge(jni::JNIEnv&, - const jni::Object&, - const jni::Object&, - mbgl::OfflineRegions&); + static void + onMerge(jni::JNIEnv&, const jni::Object&, const jni::Object&, mbgl::OfflineRegions&); }; struct FileSourceCallback { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$FileSourceCallback";} + static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$FileSourceCallback"; } static void onSuccess(jni::JNIEnv&, const jni::Object&); @@ -70,26 +75,30 @@ class OfflineManager { void setOfflineMapboxTileCountLimit(jni::JNIEnv&, jni::jlong limit); - void listOfflineRegions(jni::JNIEnv&, const jni::Object&, const jni::Object& callback); - - void createOfflineRegion(jni::JNIEnv&, - const jni::Object& jFileSource_, - const jni::Object& definition, - const jni::Array& metadata, - const jni::Object& callback); - - void mergeOfflineRegions(jni::JNIEnv&, - const jni::Object&, - const jni::String&, - const jni::Object&); - - void putResourceWithUrl(jni::JNIEnv&, - const jni::String& url, - const jni::Array& data, - jlong modified, - jlong expires, - const jni::String& eTag, - jboolean mustRevalidate); + void listOfflineRegions( + jni::JNIEnv&, const jni::Object&, const jni::Object& callback + ); + + void createOfflineRegion( + jni::JNIEnv&, + const jni::Object& jFileSource_, + const jni::Object& definition, + const jni::Array& metadata, + const jni::Object& callback + ); + + void + mergeOfflineRegions(jni::JNIEnv&, const jni::Object&, const jni::String&, const jni::Object&); + + void putResourceWithUrl( + jni::JNIEnv&, + const jni::String& url, + const jni::Array& data, + jlong modified, + jlong expires, + const jni::String& eTag, + jboolean mustRevalidate + ); void resetDatabase(jni::JNIEnv&, const jni::Object& callback_); @@ -99,7 +108,9 @@ class OfflineManager { void clearAmbientCache(jni::JNIEnv&, const jni::Object& callback_); - void setMaximumAmbientCacheSize(jni::JNIEnv&, const jni::jlong size, const jni::Object& callback_); + void setMaximumAmbientCacheSize( + jni::JNIEnv&, const jni::jlong size, const jni::Object& callback_ + ); void runPackDatabaseAutomatically(jni::JNIEnv&, jboolean autopack); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.cpp index ab60a02febb..453343f6861 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.cpp @@ -20,7 +20,9 @@ OfflineRegion::OfflineRegion(jni::JNIEnv& env, jni::jlong offlineRegionPtr, cons std::shared_ptr(mbgl::FileSourceManager::get()->getFileSource( mbgl::FileSourceType::Database, FileSource::getSharedResourceOptions(env, jFileSource), - FileSource::getSharedClientOptions(env, jFileSource))))) { + FileSource::getSharedClientOptions(env, jFileSource) + )) + )) { if (!fileSource) { ThrowNew(env, jni::FindClass(env, "java/lang/IllegalStateException"), "Offline functionality is disabled."); } @@ -28,21 +30,21 @@ OfflineRegion::OfflineRegion(jni::JNIEnv& env, jni::jlong offlineRegionPtr, cons OfflineRegion::~OfflineRegion() {} -void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, const jni::Object& callback) { - +void OfflineRegion::setOfflineRegionObserver( + jni::JNIEnv& env_, const jni::Object& callback +) { // Define the observer class Observer : public mbgl::OfflineRegionObserver { public: Observer(jni::Global, jni::EnvAttachingDeleter> callback_) - : callback(std::move(callback_)) { - } + : callback(std::move(callback_)) {} void statusChanged(mbgl::OfflineRegionStatus status) override { // Reattach, the callback comes from a different thread android::UniqueEnv env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*env); - static auto method = javaClass.GetMethod)>(*env, "onStatusChanged"); + static auto method = javaClass.GetMethod)>(*env, "onStatusChanged"); callback.Call(*env, method, OfflineRegionStatus::New(*env, status)); } @@ -52,7 +54,9 @@ void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, const jni::Objec android::UniqueEnv env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*env); - static auto method = javaClass.GetMethod)>(*env, "onError"); + static auto method = javaClass.GetMethod)>( + *env, "onError" + ); callback.Call(*env, method, OfflineRegionError::New(*env, error)); } @@ -62,7 +66,7 @@ void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, const jni::Objec android::UniqueEnv env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*env); - static auto method = javaClass.GetMethod(*env, "mapboxTileCountLimitExceeded"); + static auto method = javaClass.GetMethod(*env, "mapboxTileCountLimitExceeded"); callback.Call(*env, method, jlong(limit)); } @@ -71,7 +75,9 @@ void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, const jni::Objec }; // Set the observer - fileSource->setOfflineRegionObserver(*region, std::make_unique(jni::NewGlobal(env_, callback))); + fileSource->setOfflineRegionObserver( + *region, std::make_unique(jni::NewGlobal(env_, callback)) + ); } void OfflineRegion::setOfflineRegionDownloadState(jni::JNIEnv&, jni::jint jState) { @@ -79,117 +85,142 @@ void OfflineRegion::setOfflineRegionDownloadState(jni::JNIEnv&, jni::jint jState mbgl::OfflineRegionDownloadState state; switch (jState) { case 0: - state = mbgl::OfflineRegionDownloadState::Inactive; - break; + state = mbgl::OfflineRegionDownloadState::Inactive; + break; case 1: - state = mbgl::OfflineRegionDownloadState::Active; - break; + state = mbgl::OfflineRegionDownloadState::Active; + break; default: - mbgl::Log::Error(mbgl::Event::JNI, "State can only be 0 (inactive) or 1 (active)."); - return; + mbgl::Log::Error(mbgl::Event::JNI, "State can only be 0 (inactive) or 1 (active)."); + return; } fileSource->setOfflineRegionDownloadState(*region, state); } -void OfflineRegion::getOfflineRegionStatus(jni::JNIEnv& env_, const jni::Object& callback_) { +void OfflineRegion::getOfflineRegionStatus( + jni::JNIEnv& env_, const jni::Object& callback_ +) { auto globalCallback = jni::NewGlobal(env_, callback_); - fileSource->getOfflineRegionStatus(*region, [ - //Ensure the object is not gc'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)) - ](mbgl::expected status) mutable { - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (status) { - OfflineRegionStatusCallback::onStatus(*env, *callback, std::move(*status)); - } else { - OfflineRegionStatusCallback::onError(*env, *callback, status.error()); + fileSource->getOfflineRegionStatus( + *region, + [ + // Ensure the object is not gc'd in the meanwhile + callback = std::make_shared(std::move(globalCallback) + )](mbgl::expected status) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (status) { + OfflineRegionStatusCallback::onStatus(*env, *callback, std::move(*status)); + } else { + OfflineRegionStatusCallback::onError(*env, *callback, status.error()); + } } - }); + ); } void OfflineRegion::deleteOfflineRegion(jni::JNIEnv& env_, const jni::Object& callback_) { auto globalCallback = jni::NewGlobal(env_, callback_); - fileSource->deleteOfflineRegion(*region, - [ - // Ensure the object is not gc'd in the meanwhile - callback = std::make_shared( - std::move(globalCallback))](std::exception_ptr error) mutable { - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (error) { - OfflineRegionDeleteCallback::onError(*env, *callback, error); - } else { - OfflineRegionDeleteCallback::onDelete(*env, *callback); - } - }); + fileSource->deleteOfflineRegion( + *region, + [ + // Ensure the object is not gc'd in the meanwhile + callback = std::make_shared(std::move(globalCallback))](std::exception_ptr error + ) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (error) { + OfflineRegionDeleteCallback::onError(*env, *callback, error); + } else { + OfflineRegionDeleteCallback::onDelete(*env, *callback); + } + } + ); } -void OfflineRegion::invalidateOfflineRegion(jni::JNIEnv& env_, - const jni::Object& callback_) { +void OfflineRegion::invalidateOfflineRegion( + jni::JNIEnv& env_, const jni::Object& callback_ +) { auto globalCallback = jni::NewGlobal(env_, callback_); - fileSource->invalidateOfflineRegion(*region, - [ - // Ensure the object is not gc'd in the meanwhile - callback = std::make_shared( - std::move(globalCallback))](std::exception_ptr error) mutable { - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (error) { - OfflineRegionInvalidateCallback::onError(*env, *callback, error); - } else { - OfflineRegionInvalidateCallback::onInvalidate(*env, *callback); - } - }); + fileSource->invalidateOfflineRegion( + *region, + [ + // Ensure the object is not gc'd in the meanwhile + callback = std::make_shared(std::move(globalCallback))](std::exception_ptr error + ) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (error) { + OfflineRegionInvalidateCallback::onError(*env, *callback, error); + } else { + OfflineRegionInvalidateCallback::onInvalidate(*env, *callback); + } + } + ); } -void OfflineRegion::updateOfflineRegionMetadata(jni::JNIEnv& env_, const jni::Array& jMetadata, const jni::Object& callback_) { +void OfflineRegion::updateOfflineRegionMetadata( + jni::JNIEnv& env_, + const jni::Array& jMetadata, + const jni::Object& callback_ +) { auto metadata = OfflineRegion::metadata(env_, jMetadata); auto globalCallback = jni::NewGlobal(env_, callback_); - fileSource->updateOfflineMetadata(region->getID(), metadata, [ - //Ensure the object is not gc'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)) - ](mbgl::expected data) mutable { - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (data) { - OfflineRegionUpdateMetadataCallback::onUpdate(*env, *callback, std::move(*data)); - } else { - OfflineRegionUpdateMetadataCallback::onError(*env, *callback, data.error()); + fileSource->updateOfflineMetadata( + region->getID(), + metadata, + [ + // Ensure the object is not gc'd in the meanwhile + callback = std::make_shared(std::move(globalCallback) + )](mbgl::expected data) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (data) { + OfflineRegionUpdateMetadataCallback::onUpdate(*env, *callback, std::move(*data)); + } else { + OfflineRegionUpdateMetadataCallback::onError(*env, *callback, data.error()); + } } - }); + ); } -jni::Local> OfflineRegion::New(jni::JNIEnv& env, - const jni::Object& jFileSource, - mbgl::OfflineRegion region) { +jni::Local> OfflineRegion::New( + jni::JNIEnv& env, const jni::Object& jFileSource, mbgl::OfflineRegion region +) { // Definition auto definition = region.getDefinition().match( [&](const mbgl::OfflineTilePyramidRegionDefinition def) { return OfflineTilePyramidRegionDefinition::New(env, def); }, - [&](const mbgl::OfflineGeometryRegionDefinition def) { - return OfflineGeometryRegionDefinition::New(env, def); - }); + [&](const mbgl::OfflineGeometryRegionDefinition def) { return OfflineGeometryRegionDefinition::New(env, def); } + ); // Create region java object static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, jni::jlong, jni::Object, jni::Array>(env); - - return javaClass.New(env, constructor, - reinterpret_cast(new mbgl::OfflineRegion(std::move(region))), //Copy a region to the heap + static auto constructor = javaClass.GetConstructor< + jni::jlong, + jni::Object, + jni::jlong, + jni::Object, + jni::Array>(env); + + return javaClass.New( + env, + constructor, + reinterpret_cast(new mbgl::OfflineRegion(std::move(region))), // Copy a region to the heap jFileSource, jni::jlong(region.getID()), definition, - OfflineRegion::metadata(env, region.getMetadata())); + OfflineRegion::metadata(env, region.getMetadata()) + ); } jni::Local> OfflineRegion::metadata(jni::JNIEnv& env, mbgl::OfflineRegionMetadata metadata_) { @@ -218,7 +249,7 @@ void OfflineRegion::registerNative(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) jni::RegisterNativePeer( env, @@ -232,83 +263,96 @@ void OfflineRegion::registerNative(jni::JNIEnv& env) { METHOD(&OfflineRegion::getOfflineRegionStatus, "getOfflineRegionStatus"), METHOD(&OfflineRegion::deleteOfflineRegion, "deleteOfflineRegion"), METHOD(&OfflineRegion::invalidateOfflineRegion, "invalidateOfflineRegion"), - METHOD(&OfflineRegion::updateOfflineRegionMetadata, "updateOfflineRegionMetadata")); + METHOD(&OfflineRegion::updateOfflineRegionMetadata, "updateOfflineRegionMetadata") + ); } // OfflineRegionObserver // // OfflineRegionStatusCallback // -void OfflineRegion::OfflineRegionStatusCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineRegion::OfflineRegionStatusCallback::onError( + jni::JNIEnv& env, const jni::Object& callback, std::exception_ptr error +) { static auto& javaClass = jni::Class::Singleton(env); static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineRegion::OfflineRegionStatusCallback::onStatus(jni::JNIEnv& env, - const jni::Object& callback, - std::optional status) { +void OfflineRegion::OfflineRegionStatusCallback::onStatus( + jni::JNIEnv& env, + const jni::Object& callback, + std::optional status +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod)>(env, "onStatus"); + static auto method = javaClass.GetMethod)>(env, "onStatus"); callback.Call(env, method, OfflineRegionStatus::New(env, std::move(*status))); } // OfflineRegionDeleteCallback // -void OfflineRegion::OfflineRegionDeleteCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineRegion::OfflineRegionDeleteCallback::onError( + jni::JNIEnv& env, const jni::Object& callback, std::exception_ptr error +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineRegion::OfflineRegionDeleteCallback::onDelete(jni::JNIEnv& env, const jni::Object& callback) { +void OfflineRegion::OfflineRegionDeleteCallback::onDelete( + jni::JNIEnv& env, const jni::Object& callback +) { // Trigger callback static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onDelete"); + static auto method = javaClass.GetMethod(env, "onDelete"); callback.Call(env, method); } // OfflineRegionUpdateMetadataCallback // -void OfflineRegion::OfflineRegionUpdateMetadataCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineRegion::OfflineRegionUpdateMetadataCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + std::exception_ptr error +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineRegion::OfflineRegionUpdateMetadataCallback::onUpdate(jni::JNIEnv& env, - const jni::Object& callback, - std::optional metadata) { +void OfflineRegion::OfflineRegionUpdateMetadataCallback::onUpdate( + jni::JNIEnv& env, + const jni::Object& callback, + std::optional metadata +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod)>(env, "onUpdate"); + static auto method = javaClass.GetMethod)>(env, "onUpdate"); callback.Call(env, method, OfflineRegion::metadata(env, std::move(*metadata))); } // OfflineRegionInvalidateCallback // -void OfflineRegion::OfflineRegionInvalidateCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineRegion::OfflineRegionInvalidateCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + std::exception_ptr error +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineRegion::OfflineRegionInvalidateCallback::onInvalidate(jni::JNIEnv& env, const jni::Object& callback) { +void OfflineRegion::OfflineRegionInvalidateCallback::onInvalidate( + jni::JNIEnv& env, const jni::Object& callback +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onInvalidate"); + static auto method = javaClass.GetMethod(env, "onInvalidate"); callback.Call(env, method); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.hpp index 4d161e7d934..82065e55c76 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.hpp @@ -19,18 +19,21 @@ class OfflineRegion { class OfflineRegionStatusCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionStatusCallback"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionStatusCallback"; + }; static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); - static void onStatus(jni::JNIEnv&, - const jni::Object&, - std::optional); + static void + onStatus(jni::JNIEnv&, const jni::Object&, std::optional); }; class OfflineRegionDeleteCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionDeleteCallback"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionDeleteCallback"; + }; static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); @@ -39,7 +42,9 @@ class OfflineRegion { class OfflineRegionInvalidateCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionInvalidateCallback"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionInvalidateCallback"; + }; static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); @@ -48,13 +53,14 @@ class OfflineRegion { class OfflineRegionUpdateMetadataCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionUpdateMetadataCallback"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionUpdateMetadataCallback"; + }; static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); - static void onUpdate(jni::JNIEnv&, - const jni::Object&, - std::optional); + static void + onUpdate(jni::JNIEnv&, const jni::Object&, std::optional); }; static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion"; }; @@ -73,9 +79,12 @@ class OfflineRegion { void invalidateOfflineRegion(jni::JNIEnv&, const jni::Object&); - void updateOfflineRegionMetadata(jni::JNIEnv&, const jni::Array&, const jni::Object&); + void + updateOfflineRegionMetadata(jni::JNIEnv&, const jni::Array&, const jni::Object&); - static jni::Local> New(jni::JNIEnv&, const jni::Object&, mbgl::OfflineRegion); + static jni::Local> New( + jni::JNIEnv&, const jni::Object&, mbgl::OfflineRegion + ); static jni::Local> metadata(jni::JNIEnv&, mbgl::OfflineRegionMetadata); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.cpp index bb9dfc8dd0a..160df2249d3 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.cpp @@ -14,12 +14,17 @@ void OfflineRegionDefinition::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } -mbgl::OfflineRegionDefinition OfflineRegionDefinition::getDefinition(JNIEnv& env, - const jni::Object& jDefinition) { +mbgl::OfflineRegionDefinition OfflineRegionDefinition::getDefinition( + JNIEnv& env, const jni::Object& jDefinition +) { if (jDefinition.IsInstanceOf(env, jni::Class::Singleton(env))) { - return OfflineTilePyramidRegionDefinition::getDefinition(env, jni::Cast(env, jni::Class::Singleton(env), jDefinition)); + return OfflineTilePyramidRegionDefinition::getDefinition( + env, jni::Cast(env, jni::Class::Singleton(env), jDefinition) + ); } else if (jDefinition.IsInstanceOf(env, jni::Class::Singleton(env))) { - return OfflineGeometryRegionDefinition::getDefinition(env, jni::Cast(env, jni::Class::Singleton(env), jDefinition)); + return OfflineGeometryRegionDefinition::getDefinition( + env, jni::Cast(env, jni::Class::Singleton(env), jDefinition) + ); } throw std::runtime_error("Unknown offline region definition java class"); @@ -27,20 +32,33 @@ mbgl::OfflineRegionDefinition OfflineRegionDefinition::getDefinition(JNIEnv& env // OfflineTilePyramidRegionDefinition // -jni::Local> OfflineTilePyramidRegionDefinition::New(jni::JNIEnv& env, const mbgl::OfflineTilePyramidRegionDefinition& definition) { +jni::Local> OfflineTilePyramidRegionDefinition::New( + jni::JNIEnv& env, const mbgl::OfflineTilePyramidRegionDefinition& definition +) { static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, jni::jdouble, jni::jdouble, jni::jfloat, jni::jboolean>(env); - - return javaClass.New(env, constructor, + static auto constructor = javaClass.GetConstructor< + jni::String, + jni::Object, + jni::jdouble, + jni::jdouble, + jni::jfloat, + jni::jboolean>(env); + + return javaClass.New( + env, + constructor, jni::Make(env, definition.styleURL), LatLngBounds::New(env, definition.bounds), definition.minZoom, definition.maxZoom, definition.pixelRatio, - jni::jboolean(definition.includeIdeographs)); + jni::jboolean(definition.includeIdeographs) + ); } -mbgl::OfflineTilePyramidRegionDefinition OfflineTilePyramidRegionDefinition::getDefinition(jni::JNIEnv& env, const jni::Object& jDefinition) { +mbgl::OfflineTilePyramidRegionDefinition OfflineTilePyramidRegionDefinition::getDefinition( + jni::JNIEnv& env, const jni::Object& jDefinition +) { // Field references static auto& javaClass = jni::Class::Singleton(env); static auto styleURLF = javaClass.GetField(env, "styleURL"); @@ -48,7 +66,7 @@ mbgl::OfflineTilePyramidRegionDefinition OfflineTilePyramidRegionDefinition::get static auto minZoomF = javaClass.GetField(env, "minZoom"); static auto maxZoomF = javaClass.GetField(env, "maxZoom"); static auto pixelRatioF = javaClass.GetField(env, "pixelRatio"); - static auto includeIdeographsF = javaClass.GetField(env, "includeIdeographs"); + static auto includeIdeographsF = javaClass.GetField(env, "includeIdeographs"); return mbgl::OfflineTilePyramidRegionDefinition( jni::Make(env, jDefinition.Get(env, styleURLF)), @@ -66,20 +84,33 @@ void OfflineTilePyramidRegionDefinition::registerNative(jni::JNIEnv& env) { // OfflineGeometryRegionDefinition // -jni::Local> OfflineGeometryRegionDefinition::New(jni::JNIEnv& env, const mbgl::OfflineGeometryRegionDefinition& definition) { +jni::Local> OfflineGeometryRegionDefinition::New( + jni::JNIEnv& env, const mbgl::OfflineGeometryRegionDefinition& definition +) { static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, jni::jdouble, jni::jdouble, jni::jfloat, jni::jboolean>(env); - - return javaClass.New(env, constructor, + static auto constructor = javaClass.GetConstructor< + jni::String, + jni::Object, + jni::jdouble, + jni::jdouble, + jni::jfloat, + jni::jboolean>(env); + + return javaClass.New( + env, + constructor, jni::Make(env, definition.styleURL), geojson::Geometry::New(env, definition.geometry), definition.minZoom, definition.maxZoom, definition.pixelRatio, - jni::jboolean(definition.includeIdeographs)); + jni::jboolean(definition.includeIdeographs) + ); } -mbgl::OfflineGeometryRegionDefinition OfflineGeometryRegionDefinition::getDefinition(jni::JNIEnv& env, const jni::Object& jDefinition) { +mbgl::OfflineGeometryRegionDefinition OfflineGeometryRegionDefinition::getDefinition( + jni::JNIEnv& env, const jni::Object& jDefinition +) { // Field references static auto& javaClass = jni::Class::Singleton(env); static auto styleURLF = javaClass.GetField(env, "styleURL"); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.hpp index 827fac0a800..8dc06ebd387 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.hpp @@ -12,7 +12,9 @@ class OfflineRegionDefinition { static void registerNative(jni::JNIEnv&); - static mbgl::OfflineRegionDefinition getDefinition(JNIEnv& env, const jni::Object& jDefinition); + static mbgl::OfflineRegionDefinition getDefinition( + JNIEnv& env, const jni::Object& jDefinition + ); }; class OfflineTilePyramidRegionDefinition { @@ -20,9 +22,11 @@ class OfflineTilePyramidRegionDefinition { using SuperTag = OfflineRegionDefinition; static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineTilePyramidRegionDefinition"; }; - static jni::Local> New(jni::JNIEnv&, const mbgl::OfflineTilePyramidRegionDefinition&); + static jni::Local> + New(jni::JNIEnv&, const mbgl::OfflineTilePyramidRegionDefinition&); - static mbgl::OfflineTilePyramidRegionDefinition getDefinition(jni::JNIEnv&, const jni::Object&); + static mbgl::OfflineTilePyramidRegionDefinition + getDefinition(jni::JNIEnv&, const jni::Object&); static void registerNative(jni::JNIEnv&); }; @@ -32,9 +36,11 @@ class OfflineGeometryRegionDefinition { using SuperTag = OfflineRegionDefinition; static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineGeometryRegionDefinition"; }; - static jni::Local> New(jni::JNIEnv&, const mbgl::OfflineGeometryRegionDefinition&); + static jni::Local> + New(jni::JNIEnv&, const mbgl::OfflineGeometryRegionDefinition&); - static mbgl::OfflineGeometryRegionDefinition getDefinition(jni::JNIEnv&, const jni::Object&); + static mbgl::OfflineGeometryRegionDefinition + getDefinition(jni::JNIEnv&, const jni::Object&); static void registerNative(jni::JNIEnv&); }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_error.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_error.cpp index 199bbafa6b9..519ed4127fb 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_error.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_error.cpp @@ -4,10 +4,9 @@ namespace mbgl { namespace android { jni::Local> OfflineRegionError::New(jni::JNIEnv& env, mbgl::Response::Error error) { - // Handle the value of reason independently of the underlying int value std::string reason; - switch(error.reason) { + switch (error.reason) { case mbgl::Response::Error::Reason::Success: reason = "REASON_SUCCESS"; break; @@ -31,9 +30,9 @@ jni::Local> OfflineRegionError::New(jni::JNIEnv& static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, - jni::Make(env, reason), - jni::Make(env, error.message)); + return javaClass.New( + env, constructor, jni::Make(env, reason), jni::Make(env, error.message) + ); } void OfflineRegionError::registerNative(jni::JNIEnv& env) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_status.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_status.cpp index 5dd9f20a7fa..882711a43f4 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_status.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_status.cpp @@ -3,11 +3,12 @@ namespace mbgl { namespace android { -jni::Local> OfflineRegionStatus::New(jni::JNIEnv& env, mbgl::OfflineRegionStatus status) { - +jni::Local> OfflineRegionStatus::New( + jni::JNIEnv& env, mbgl::OfflineRegionStatus status +) { // Convert to jint jint downloadState; - switch(status.downloadState) { + switch (status.downloadState) { case mbgl::OfflineRegionDownloadState::Inactive: downloadState = 0; break; @@ -19,7 +20,9 @@ jni::Local> OfflineRegionStatus::New(jni::JNIEn // Create java object static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, + return javaClass.New( + env, + constructor, downloadState, jlong(status.completedResourceCount), jlong(status.completedResourceSize), diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.cpp index 03a532a43aa..444c5e796da 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.cpp @@ -9,10 +9,9 @@ namespace mbgl { namespace android { MapSnapshot::MapSnapshot(float pixelRatio_, MapSnapshot::PointForFn pointForFn_, MapSnapshot::LatLngForFn latLngForFn_) - : pixelRatio(pixelRatio_) - , pointForFn(std::move(pointForFn_)) - , latLngForFn(std::move(latLngForFn_)) { -} + : pixelRatio(pixelRatio_), + pointForFn(std::move(pointForFn_)), + latLngForFn(std::move(latLngForFn_)) {} MapSnapshot::~MapSnapshot() = default; @@ -27,21 +26,31 @@ jni::Local> MapSnapshot::latLngForPixel(jni::JNIEnv& env, jn // Static methods // -jni::Local> MapSnapshot::New(JNIEnv& env, - PremultipliedImage&& image, - float pixelRatio, - std::vector attributions, - bool showLogo, - mbgl::MapSnapshotter::PointForFn pointForFn, - mbgl::MapSnapshotter::LatLngForFn latLngForFn) { +jni::Local> MapSnapshot::New( + JNIEnv& env, + PremultipliedImage&& image, + float pixelRatio, + std::vector attributions, + bool showLogo, + mbgl::MapSnapshotter::PointForFn pointForFn, + mbgl::MapSnapshotter::LatLngForFn latLngForFn +) { // Create the bitmap auto bitmap = Bitmap::CreateBitmap(env, std::move(image)); // Create the Mapsnapshot peers static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, jni::Array, jni::jboolean>(env); + static auto constructor = + javaClass.GetConstructor, jni::Array, jni::jboolean>(env); auto nativePeer = std::make_unique(pixelRatio, pointForFn, latLngForFn); - return javaClass.New(env, constructor, reinterpret_cast(nativePeer.release()), bitmap, conversion::toArray(env, attributions), (jni::jboolean) showLogo); + return javaClass.New( + env, + constructor, + reinterpret_cast(nativePeer.release()), + bitmap, + conversion::toArray(env, attributions), + (jni::jboolean)showLogo + ); } void MapSnapshot::registerNative(jni::JNIEnv& env) { @@ -51,13 +60,15 @@ void MapSnapshot::registerNative(jni::JNIEnv& env) { #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer - jni::RegisterNativePeer(env, javaClass, - "nativePtr", - std::make_unique, - "initialize", - "finalize", - METHOD(&MapSnapshot::latLngForPixel, "latLngForPixel"), - METHOD(&MapSnapshot::pixelForLatLng, "pixelForLatLng") + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + std::make_unique, + "initialize", + "finalize", + METHOD(&MapSnapshot::latLngForPixel, "latLngForPixel"), + METHOD(&MapSnapshot::pixelForLatLng, "pixelForLatLng") ); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.hpp index 6b82d02835b..ddf22f582e2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.hpp @@ -15,7 +15,6 @@ namespace android { class MapSnapshot { public: - using PointForFn = mbgl::MapSnapshotter::PointForFn; using LatLngForFn = mbgl::MapSnapshotter::LatLngForFn; @@ -23,15 +22,17 @@ class MapSnapshot { static void registerNative(jni::JNIEnv&); - static jni::Local> New(JNIEnv& env, - PremultipliedImage&& image, - float pixelRatio, - std::vector attributions, - bool showLogo, - PointForFn pointForFn, - LatLngForFn latLngForFn); - - MapSnapshot(jni::JNIEnv&) {}; + static jni::Local> New( + JNIEnv& env, + PremultipliedImage&& image, + float pixelRatio, + std::vector attributions, + bool showLogo, + PointForFn pointForFn, + LatLngForFn latLngForFn + ); + + MapSnapshot(jni::JNIEnv&){}; MapSnapshot(float pixelRatio, PointForFn, LatLngForFn); ~MapSnapshot(); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.cpp index 03547c293de..af1bc1a7980 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.cpp @@ -13,21 +13,22 @@ namespace mbgl { namespace android { -MapSnapshotter::MapSnapshotter(jni::JNIEnv& _env, - const jni::Object& _obj, - const jni::Object& _jFileSource, - jni::jfloat _pixelRatio, - jni::jint width, - jni::jint height, - const jni::String& styleURL, - const jni::String& styleJSON, - const jni::Object& region, - const jni::Object& position, - jni::jboolean _showLogo, - const jni::String& _localIdeographFontFamily) - : javaPeer(_env, _obj) - , pixelRatio(_pixelRatio) { - +MapSnapshotter::MapSnapshotter( + jni::JNIEnv& _env, + const jni::Object& _obj, + const jni::Object& _jFileSource, + jni::jfloat _pixelRatio, + jni::jint width, + jni::jint height, + const jni::String& styleURL, + const jni::String& styleJSON, + const jni::Object& region, + const jni::Object& position, + jni::jboolean _showLogo, + const jni::String& _localIdeographFontFamily +) + : javaPeer(_env, _obj), + pixelRatio(_pixelRatio) { // Get a reference to the JavaVM for callbacks if (_env.GetJavaVM(&vm) < 0) { _env.ExceptionDescribe(); @@ -37,7 +38,7 @@ MapSnapshotter::MapSnapshotter(jni::JNIEnv& _env, weakScheduler = mbgl::Scheduler::GetCurrent()->makeWeakPtr(); jFileSource = FileSource::getNativePeer(_env, _jFileSource); - auto size = mbgl::Size { static_cast(width), static_cast(height) }; + auto size = mbgl::Size{static_cast(width), static_cast(height)}; showLogo = _showLogo; @@ -48,7 +49,9 @@ MapSnapshotter::MapSnapshotter(jni::JNIEnv& _env, mbgl::android::FileSource::getSharedResourceOptions(_env, _jFileSource), mbgl::android::FileSource::getSharedClientOptions(_env, _jFileSource), *this, - _localIdeographFontFamily ? jni::Make(_env, _localIdeographFontFamily) : std::optional{}); + _localIdeographFontFamily ? jni::Make(_env, _localIdeographFontFamily) + : std::optional{} + ); if (position) { snapshotter->setCameraOptions(CameraPosition::getCameraOptions(_env, position, pixelRatio)); @@ -80,28 +83,32 @@ MapSnapshotter::~MapSnapshotter() { void MapSnapshotter::start(JNIEnv& env) { MBGL_VERIFY_THREAD(tid); activateFilesource(env); - snapshotter->snapshot([this](std::exception_ptr err, - PremultipliedImage image, - std::vector attributions, - mbgl::MapSnapshotter::PointForFn pointForFn, - mbgl::MapSnapshotter::LatLngForFn latLngForFn) { + snapshotter->snapshot([this]( + std::exception_ptr err, + PremultipliedImage image, + std::vector attributions, + mbgl::MapSnapshotter::PointForFn pointForFn, + mbgl::MapSnapshotter::LatLngForFn latLngForFn + ) { MBGL_VERIFY_THREAD(tid); android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); if (err) { // error handler callback - static auto onSnapshotFailed = javaClass.GetMethod(*_env, "onSnapshotFailed"); + static auto onSnapshotFailed = javaClass.GetMethod(*_env, "onSnapshotFailed"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onSnapshotFailed, jni::Make(*_env, util::toString(err))); } } else { // Create the wrapper - auto mapSnapshot = android::MapSnapshot::New(*_env, std::move(image), pixelRatio, attributions, showLogo, pointForFn, latLngForFn); + auto mapSnapshot = android::MapSnapshot::New( + *_env, std::move(image), pixelRatio, attributions, showLogo, pointForFn, latLngForFn + ); // invoke callback - static auto onSnapshotReady = javaClass.GetMethod)>(*_env, "onSnapshotReady"); + static auto onSnapshotReady = javaClass.GetMethod)>(*_env, "onSnapshotReady"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onSnapshotReady, mapSnapshot); @@ -127,7 +134,7 @@ void MapSnapshotter::setStyleJson(JNIEnv& env, const jni::String& styleJSON) { } void MapSnapshotter::setSize(JNIEnv&, jni::jint width, jni::jint height) { - auto size = mbgl::Size { static_cast(width), static_cast(height) }; + auto size = mbgl::Size{static_cast(width), static_cast(height)}; snapshotter->setSize(size); } @@ -198,16 +205,19 @@ void MapSnapshotter::addLayerAt(JNIEnv& env, jlong nativeLayerPtr, jni::jint ind const int numLayers = layers.size() - 1; if (index > numLayers || index < 0) { Log::Error(Event::JNI, "Index out of range: " + std::to_string(index)); - jni::ThrowNew(env, - jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), - std::string("Invalid index").c_str()); + jni::ThrowNew( + env, + jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), + std::string("Invalid index").c_str() + ); } // Insert it below the current at that index try { layer->addToStyle(snapshotter->getStyle(), layers.at(index)->getID()); } catch (const std::runtime_error& error) { jni::ThrowNew( - env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what() + ); } } @@ -218,10 +228,12 @@ void MapSnapshotter::addLayerBelow(JNIEnv& env, jlong nativeLayerPtr, const jni: try { layer->addToStyle( snapshotter->getStyle(), - below ? std::optional(jni::Make(env, below)) : std::optional()); + below ? std::optional(jni::Make(env, below)) : std::optional() + ); } catch (const std::runtime_error& error) { jni::ThrowNew( - env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what() + ); } } @@ -245,9 +257,11 @@ void MapSnapshotter::addLayerAbove(JNIEnv& env, jlong nativeLayerPtr, const jni: std::optional before; if (index > snapshotterLayers.size()) { // Not found - jni::ThrowNew(env, - jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), - std::string("Could not find layer: ").append(siblingId).c_str()); + jni::ThrowNew( + env, + jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), + std::string("Could not find layer: ").append(siblingId).c_str() + ); } else if (index < snapshotterLayers.size()) { // Place before the sibling before = {snapshotterLayers.at(index)->getID()}; @@ -258,7 +272,8 @@ void MapSnapshotter::addLayerAbove(JNIEnv& env, jlong nativeLayerPtr, const jni: newLayer->addToStyle(snapshotter->getStyle(), before); } catch (const std::runtime_error& error) { jni::ThrowNew( - env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what() + ); } } @@ -270,7 +285,8 @@ void MapSnapshotter::addSource(JNIEnv& env, const jni::Object& obj, jlon source->addToStyle(env, obj, snapshotter->getStyle()); } catch (const std::runtime_error& error) { jni::ThrowNew( - env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/sources/CannotAddSourceException"), error.what()); + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/sources/CannotAddSourceException"), error.what() + ); } } @@ -317,37 +333,40 @@ void MapSnapshotter::registerNative(jni::JNIEnv& env) { #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer - jni::RegisterNativePeer(env, - javaClass, - "nativePtr", - jni::MakePeer&, - const jni::Object&, - jni::jfloat, - jni::jint, - jni::jint, - const jni::String&, - const jni::String&, - const jni::Object&, - const jni::Object&, - jni::jboolean, - const jni::String&>, - "nativeInitialize", - "finalize", - METHOD(&MapSnapshotter::setStyleUrl, "setStyleUrl"), - METHOD(&MapSnapshotter::addLayerAt, "nativeAddLayerAt"), - METHOD(&MapSnapshotter::addLayerBelow, "nativeAddLayerBelow"), - METHOD(&MapSnapshotter::addLayerAbove, "nativeAddLayerAbove"), - METHOD(&MapSnapshotter::addSource, "nativeAddSource"), - METHOD(&MapSnapshotter::addImages, "nativeAddImages"), - METHOD(&MapSnapshotter::getLayer, "nativeGetLayer"), - METHOD(&MapSnapshotter::getSource, "nativeGetSource"), - METHOD(&MapSnapshotter::setStyleJson, "setStyleJson"), - METHOD(&MapSnapshotter::setSize, "setSize"), - METHOD(&MapSnapshotter::setCameraPosition, "setCameraPosition"), - METHOD(&MapSnapshotter::setRegion, "setRegion"), - METHOD(&MapSnapshotter::start, "nativeStart"), - METHOD(&MapSnapshotter::cancel, "nativeCancel")); + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer< + MapSnapshotter, + const jni::Object&, + const jni::Object&, + jni::jfloat, + jni::jint, + jni::jint, + const jni::String&, + const jni::String&, + const jni::Object&, + const jni::Object&, + jni::jboolean, + const jni::String&>, + "nativeInitialize", + "finalize", + METHOD(&MapSnapshotter::setStyleUrl, "setStyleUrl"), + METHOD(&MapSnapshotter::addLayerAt, "nativeAddLayerAt"), + METHOD(&MapSnapshotter::addLayerBelow, "nativeAddLayerBelow"), + METHOD(&MapSnapshotter::addLayerAbove, "nativeAddLayerAbove"), + METHOD(&MapSnapshotter::addSource, "nativeAddSource"), + METHOD(&MapSnapshotter::addImages, "nativeAddImages"), + METHOD(&MapSnapshotter::getLayer, "nativeGetLayer"), + METHOD(&MapSnapshotter::getSource, "nativeGetSource"), + METHOD(&MapSnapshotter::setStyleJson, "setStyleJson"), + METHOD(&MapSnapshotter::setSize, "setSize"), + METHOD(&MapSnapshotter::setCameraPosition, "setCameraPosition"), + METHOD(&MapSnapshotter::setRegion, "setRegion"), + METHOD(&MapSnapshotter::start, "nativeStart"), + METHOD(&MapSnapshotter::cancel, "nativeCancel") + ); } } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.hpp index 4d0186e7f8b..efdfbe0899b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.hpp @@ -19,23 +19,24 @@ namespace android { class MapSnapshotter final : public mbgl::MapSnapshotterObserver { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/snapshotter/MapSnapshotter"; }; static void registerNative(jni::JNIEnv&); - MapSnapshotter(jni::JNIEnv&, - const jni::Object&, - const jni::Object&, - jni::jfloat pixelRatio, - jni::jint width, - jni::jint height, - const jni::String& styleURL, - const jni::String& styleJSON, - const jni::Object& region, - const jni::Object& position, - jni::jboolean showLogo, - const jni::String& localIdeographFontFamily); + MapSnapshotter( + jni::JNIEnv&, + const jni::Object&, + const jni::Object&, + jni::jfloat pixelRatio, + jni::jint width, + jni::jint height, + const jni::String& styleURL, + const jni::String& styleJSON, + const jni::Object& region, + const jni::Object& position, + jni::jboolean showLogo, + const jni::String& localIdeographFontFamily + ); virtual ~MapSnapshotter() override; @@ -69,13 +70,13 @@ class MapSnapshotter final : public mbgl::MapSnapshotterObserver { private: MBGL_STORE_THREAD(tid); - JavaVM *vm = nullptr; + JavaVM* vm = nullptr; jni::WeakReference, jni::EnvAttachingDeleter> javaPeer; float pixelRatio; bool showLogo; - FileSource *jFileSource; + FileSource* jFileSource; void activateFilesource(JNIEnv&); void deactivateFilesource(JNIEnv&); bool activatedFilesource = false; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/android_conversion.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/android_conversion.hpp index 8b33a9f8efd..4ecf05722ec 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/android_conversion.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/android_conversion.hpp @@ -17,25 +17,18 @@ namespace conversion { template <> class ConversionTraits { public: - static bool isUndefined(const mbgl::android::Value& value) { - return value.isNull(); - } + static bool isUndefined(const mbgl::android::Value& value) { return value.isNull(); } - static bool isArray(const mbgl::android::Value& value) { - return value.isArray(); - } + static bool isArray(const mbgl::android::Value& value) { return value.isArray(); } - static bool isObject(const mbgl::android::Value& value) { - return value.isObject(); - } + static bool isObject(const mbgl::android::Value& value) { return value.isObject(); } static std::size_t arrayLength(const mbgl::android::Value& value) { - return value.getLength();; + return value.getLength(); + ; } - static mbgl::android::Value arrayMember(const mbgl::android::Value& value, std::size_t i) { - return value.get(i); - } + static mbgl::android::Value arrayMember(const mbgl::android::Value& value, std::size_t i) { return value.get(i); } static std::optional objectMember(const mbgl::android::Value& value, const char* key) { mbgl::android::Value member = value.get(key); @@ -51,7 +44,7 @@ class ConversionTraits { assert(value.isObject()); mbgl::android::Value keys = value.keyArray(); std::size_t length = arrayLength(keys); - for(std::size_t i = 0; i < length; ++i){ + for (std::size_t i = 0; i < length; ++i) { const auto k = keys.get(i).toString(); auto v = value.get(k.c_str()); std::optional result = fn(k, std::move(v)); @@ -99,19 +92,19 @@ class ConversionTraits { if (value.isNull()) { return {}; } else if (value.isBool()) { - return { value.toBool() }; + return {value.toBool()}; } else if (value.isString()) { - return { value.toString() }; + return {value.toString()}; } else if (value.isNumber()) { - return { value.toDouble() }; + return {value.toDouble()}; } else { return {}; } } - static std::optional toGeoJSON(const mbgl::android::Value &value, Error &error) { + static std::optional toGeoJSON(const mbgl::android::Value& value, Error& error) { if (value.isNull()) { - error = { "no json data found" }; + error = {"no json data found"}; return {}; } @@ -138,8 +131,8 @@ class ConversionTraits { } }; -template -std::optional convert(mbgl::android::Value&& value, Error& error, Args&&...args) { +template +std::optional convert(mbgl::android::Value&& value, Error& error, Args&&... args) { return convert(Convertible(std::move(value)), error, std::forward(args)...); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/filter.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/filter.cpp index 680c72af971..6d87caac571 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/filter.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/filter.cpp @@ -11,12 +11,12 @@ namespace conversion { std::optional toFilter(jni::JNIEnv& env, const jni::Array>& jfilter) { std::optional filter; if (jfilter) { - mbgl::style::conversion::Error error; - auto converted = mbgl::style::conversion::convert(Value(env, jfilter), error); - if (!converted) { - mbgl::Log::Error(mbgl::Event::JNI, "Error converting filter: " + error.message); - } - filter = std::move(*converted); + mbgl::style::conversion::Error error; + auto converted = mbgl::style::conversion::convert(Value(env, jfilter), error); + if (!converted) { + mbgl::Log::Error(mbgl::Event::JNI, "Error converting filter: " + error.message); + } + filter = std::move(*converted); } return filter; } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.cpp index e3c334afd2f..16e039c1640 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.cpp @@ -4,21 +4,26 @@ namespace mbgl { namespace android { namespace conversion { -Result>> Converter>, mbgl::style::Position>::operator()(jni::JNIEnv &env, const mbgl::style::Position &value) const { +Result>> +Converter>, mbgl::style::Position>::operator()( + jni::JNIEnv &env, const mbgl::style::Position &value +) const { std::array cartPosition = value.getSpherical(); return Position::fromPosition(env, cartPosition[0], cartPosition[1], cartPosition[2]); } -Result Converter>::operator()(jni::JNIEnv &env, const jni::Object &value) const { +Result Converter>::operator()( + jni::JNIEnv &env, const jni::Object &value +) const { float radialCoordinate = Position::getRadialCoordinate(env, value); float azimuthalAngle = Position::getAzimuthalAngle(env, value); float polarAngle = Position::getPolarAngle(env, value); - std::array cartPosition {{radialCoordinate, azimuthalAngle, polarAngle}}; + std::array cartPosition{{radialCoordinate, azimuthalAngle, polarAngle}}; mbgl::style::Position position{}; position.set(cartPosition); return position; } -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.hpp index 90409d527d4..66afb5451f6 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.hpp @@ -20,6 +20,6 @@ struct Converter> { Result operator()(jni::JNIEnv &env, const jni::Object &value) const; }; -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_expression.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_expression.hpp index 4e26b11f96b..de9f7089996 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_expression.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_expression.hpp @@ -13,7 +13,9 @@ namespace conversion { template struct Converter>, mbgl::style::PropertyExpression> { - Result>> operator()(jni::JNIEnv& env, const mbgl::style::PropertyExpression& value) const { + Result>> operator()( + jni::JNIEnv& env, const mbgl::style::PropertyExpression& value + ) const { return gson::JsonElement::New(env, value.getExpression().serialize()); } }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_value.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_value.hpp index 317705a2865..7eeb22b3431 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_value.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_value.hpp @@ -17,7 +17,8 @@ namespace conversion { template class PropertyValueEvaluator { public: - PropertyValueEvaluator(jni::JNIEnv& _env) : env(_env) {} + PropertyValueEvaluator(jni::JNIEnv& _env) + : env(_env) {} jni::Local> operator()(const mbgl::style::Undefined) const { return jni::Local>(env, nullptr); @@ -51,7 +52,8 @@ struct Converter>, mbgl::style::PropertyValue> { */ template <> struct Converter>, mbgl::style::ColorRampPropertyValue> { - Result>> operator()(jni::JNIEnv& env, const mbgl::style::ColorRampPropertyValue& value) const { + Result>> operator()(jni::JNIEnv& env, const mbgl::style::ColorRampPropertyValue& value) + const { PropertyValueEvaluator evaluator(env); return std::move(*convert>>(env, value.evaluate(evaluator))); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.cpp index 75d9b4cc0d9..0cbf00d1599 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.cpp @@ -4,14 +4,18 @@ namespace mbgl { namespace android { namespace conversion { -Result>> Converter>, mbgl::style::TransitionOptions>::operator()(jni::JNIEnv& env, const mbgl::style::TransitionOptions& value) const { - return TransitionOptions::fromTransitionOptions(env, +Result>> +Converter>, mbgl::style::TransitionOptions>::operator()( + jni::JNIEnv& env, const mbgl::style::TransitionOptions& value +) const { + return TransitionOptions::fromTransitionOptions( + env, std::chrono::duration_cast(value.duration.value_or(mbgl::Duration::zero())).count(), std::chrono::duration_cast(value.delay.value_or(mbgl::Duration::zero())).count(), - (jboolean) value.enablePlacementTransitions + (jboolean)value.enablePlacementTransitions ); } -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.hpp index 06c042922ed..2709708285c 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.hpp @@ -11,11 +11,12 @@ namespace mbgl { namespace android { namespace conversion { -template<> +template <> struct Converter>, mbgl::style::TransitionOptions> { - Result>> operator()(jni::JNIEnv&, const mbgl::style::TransitionOptions&) const; + Result>> operator()(jni::JNIEnv&, const mbgl::style::TransitionOptions&) + const; }; -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.cpp index 238c3ce070c..be6b665241b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.cpp @@ -20,11 +20,11 @@ variant convertURLOrTileset(mbgl::android::Value&& value) if (!tileset) { throw std::logic_error(error.message); } - return { *tileset }; + return {*tileset}; } else { - return { *toString(convertible) }; + return {*toString(convertible)}; } } -} -} +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.hpp index f42a9b9a2a9..63c617eb869 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.hpp @@ -13,4 +13,4 @@ namespace android { variant convertURLOrTileset(mbgl::android::Value&& value); } -} +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.cpp index 69c3454e23a..21c49dd2c1f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.cpp @@ -24,7 +24,7 @@ jni::Local> Formatted::New(jni::JNIEnv& env, const style: if (section.fontScale) { double fontScale = section.fontScale.value(); - static auto method = formattedSectionClass.GetMethod(env, "setFontScale"); + static auto method = formattedSectionClass.GetMethod(env, "setFontScale"); formattedSection.Call(env, method, jni::Box(env, fontScale)); } @@ -33,14 +33,14 @@ jni::Local> Formatted::New(jni::JNIEnv& env, const style: for (std::size_t j = 0; j < section.fontStack.value().size(); j++) { fontStack.Set(env, j, jni::Make(env, section.fontStack.value().at(j))); } - static auto method = formattedSectionClass.GetMethod)>(env, "setFontStack"); + static auto method = formattedSectionClass.GetMethod)>(env, "setFontStack"); formattedSection.Call(env, method, fontStack); } if (section.textColor) { using namespace mbgl::android::conversion; auto textColor = std::move(*convert>>(env, *section.textColor)); - static auto method = formattedSectionClass.GetMethod)>(env, "setTextColor"); + static auto method = formattedSectionClass.GetMethod)>(env, "setTextColor"); formattedSection.Call(env, method, textColor); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.hpp index ca91f6562c9..a7a0f72196f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.hpp @@ -6,18 +6,17 @@ #include namespace mbgl { - namespace android { +namespace android { - using SuperTag = jni::ObjectTag; - class Formatted : private mbgl::util::noncopyable { - public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/types/Formatted"; }; +using SuperTag = jni::ObjectTag; +class Formatted : private mbgl::util::noncopyable { +public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/types/Formatted"; }; - static jni::Local> - New(jni::JNIEnv&, const style::expression::Formatted &value); + static jni::Local> New(jni::JNIEnv &, const style::expression::Formatted &value); - static void registerNative(jni::JNIEnv &); - }; + static void registerNative(jni::JNIEnv &); +}; - } // namespace android +} // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.cpp index 99fb75cc06e..0f1dbe0000b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.cpp @@ -12,136 +12,142 @@ namespace mbgl { namespace android { - inline mbgl::style::BackgroundLayer& toBackgroundLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - BackgroundLayer::BackgroundLayer(jni::JNIEnv& env, jni::String& layerId) - : Layer(std::make_unique(jni::Make(env, layerId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - BackgroundLayer::BackgroundLayer(mbgl::style::BackgroundLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - BackgroundLayer::BackgroundLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - BackgroundLayer::~BackgroundLayer() = default; - - // Property getters - - jni::Local> BackgroundLayer::getBackgroundColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundColor())); - } - - jni::Local> BackgroundLayer::getBackgroundColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundColorTransition(); - return std::move(*convert>>(env, options)); - } - - void BackgroundLayer::setBackgroundColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toBackgroundLayer(layer).setBackgroundColorTransition(options); - } - - jni::Local> BackgroundLayer::getBackgroundPattern(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundPattern())); - } - - jni::Local> BackgroundLayer::getBackgroundPatternTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundPatternTransition(); - return std::move(*convert>>(env, options)); - } - - void BackgroundLayer::setBackgroundPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toBackgroundLayer(layer).setBackgroundPatternTransition(options); - } - - jni::Local> BackgroundLayer::getBackgroundOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundOpacity())); - } - - jni::Local> BackgroundLayer::getBackgroundOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void BackgroundLayer::setBackgroundOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toBackgroundLayer(layer).setBackgroundOpacityTransition(options); - } - - - // BackgroundJavaLayerPeerFactory - - BackgroundJavaLayerPeerFactory::~BackgroundJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> BackgroundJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new BackgroundLayer(toBackgroundLayer(layer))); - } - - jni::Local> BackgroundJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new BackgroundLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void BackgroundJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&BackgroundLayer::getBackgroundColorTransition, "nativeGetBackgroundColorTransition"), - METHOD(&BackgroundLayer::setBackgroundColorTransition, "nativeSetBackgroundColorTransition"), - METHOD(&BackgroundLayer::getBackgroundColor, "nativeGetBackgroundColor"), - METHOD(&BackgroundLayer::getBackgroundPatternTransition, "nativeGetBackgroundPatternTransition"), - METHOD(&BackgroundLayer::setBackgroundPatternTransition, "nativeSetBackgroundPatternTransition"), - METHOD(&BackgroundLayer::getBackgroundPattern, "nativeGetBackgroundPattern"), - METHOD(&BackgroundLayer::getBackgroundOpacityTransition, "nativeGetBackgroundOpacityTransition"), - METHOD(&BackgroundLayer::setBackgroundOpacityTransition, "nativeSetBackgroundOpacityTransition"), - METHOD(&BackgroundLayer::getBackgroundOpacity, "nativeGetBackgroundOpacity")); - } +inline mbgl::style::BackgroundLayer& toBackgroundLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +BackgroundLayer::BackgroundLayer(jni::JNIEnv& env, jni::String& layerId) + : Layer(std::make_unique(jni::Make(env, layerId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +BackgroundLayer::BackgroundLayer(mbgl::style::BackgroundLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +BackgroundLayer::BackgroundLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +BackgroundLayer::~BackgroundLayer() = default; + +// Property getters + +jni::Local> BackgroundLayer::getBackgroundColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundColor())); +} + +jni::Local> BackgroundLayer::getBackgroundColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundColorTransition(); + return std::move(*convert>>(env, options)); +} + +void BackgroundLayer::setBackgroundColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toBackgroundLayer(layer).setBackgroundColorTransition(options); +} + +jni::Local> BackgroundLayer::getBackgroundPattern(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundPattern())); +} + +jni::Local> BackgroundLayer::getBackgroundPatternTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundPatternTransition(); + return std::move(*convert>>(env, options)); +} + +void BackgroundLayer::setBackgroundPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toBackgroundLayer(layer).setBackgroundPatternTransition(options); +} + +jni::Local> BackgroundLayer::getBackgroundOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundOpacity())); +} + +jni::Local> BackgroundLayer::getBackgroundOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void BackgroundLayer::setBackgroundOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toBackgroundLayer(layer).setBackgroundOpacityTransition(options); +} + +// BackgroundJavaLayerPeerFactory + +BackgroundJavaLayerPeerFactory::~BackgroundJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> BackgroundJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new BackgroundLayer(toBackgroundLayer(layer))); +} + +jni::Local> BackgroundJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new BackgroundLayer( + std::unique_ptr(static_cast(layer.release())) + ) + ); +} + +void BackgroundJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&BackgroundLayer::getBackgroundColorTransition, "nativeGetBackgroundColorTransition"), + METHOD(&BackgroundLayer::setBackgroundColorTransition, "nativeSetBackgroundColorTransition"), + METHOD(&BackgroundLayer::getBackgroundColor, "nativeGetBackgroundColor"), + METHOD(&BackgroundLayer::getBackgroundPatternTransition, "nativeGetBackgroundPatternTransition"), + METHOD(&BackgroundLayer::setBackgroundPatternTransition, "nativeSetBackgroundPatternTransition"), + METHOD(&BackgroundLayer::getBackgroundPattern, "nativeGetBackgroundPattern"), + METHOD(&BackgroundLayer::getBackgroundOpacityTransition, "nativeGetBackgroundOpacityTransition"), + METHOD(&BackgroundLayer::setBackgroundOpacityTransition, "nativeSetBackgroundOpacityTransition"), + METHOD(&BackgroundLayer::getBackgroundOpacity, "nativeGetBackgroundOpacity") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.hpp index 8958c929e6f..94cf41b4d09 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.hpp @@ -40,7 +40,7 @@ class BackgroundLayer : public Layer { }; // class BackgroundLayer -class BackgroundJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::BackgroundLayerFactory { +class BackgroundJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::BackgroundLayerFactory { public: ~BackgroundJavaLayerPeerFactory() override; @@ -52,7 +52,7 @@ class BackgroundJavaLayerPeerFactory final : public JavaLayerPeerFactory, publi LayerFactory* getLayerFactory() final { return this; } -}; // class BackgroundJavaLayerPeerFactory +}; // class BackgroundJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.cpp index f51e2dae99b..bdef71295a6 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.cpp @@ -12,265 +12,272 @@ namespace mbgl { namespace android { - inline mbgl::style::CircleLayer& toCircleLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - CircleLayer::CircleLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - CircleLayer::CircleLayer(mbgl::style::CircleLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - CircleLayer::CircleLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - CircleLayer::~CircleLayer() = default; - - // Property getters - - jni::Local> CircleLayer::getCircleSortKey(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleSortKey())); - } - - jni::Local> CircleLayer::getCircleRadius(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleRadius())); - } - - jni::Local> CircleLayer::getCircleRadiusTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleRadiusTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleRadiusTransition(options); - } - - jni::Local> CircleLayer::getCircleColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleColor())); - } - - jni::Local> CircleLayer::getCircleColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleColorTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleColorTransition(options); - } - - jni::Local> CircleLayer::getCircleBlur(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleBlur())); - } - - jni::Local> CircleLayer::getCircleBlurTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleBlurTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleBlurTransition(options); - } - - jni::Local> CircleLayer::getCircleOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleOpacity())); - } - - jni::Local> CircleLayer::getCircleOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleOpacityTransition(options); - } - - jni::Local> CircleLayer::getCircleTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleTranslate())); - } - - jni::Local> CircleLayer::getCircleTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleTranslateTransition(options); - } - - jni::Local> CircleLayer::getCircleTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleTranslateAnchor())); - } - - jni::Local> CircleLayer::getCirclePitchScale(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCirclePitchScale())); - } - - jni::Local> CircleLayer::getCirclePitchAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCirclePitchAlignment())); - } - - jni::Local> CircleLayer::getCircleStrokeWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeWidth())); - } - - jni::Local> CircleLayer::getCircleStrokeWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleStrokeWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleStrokeWidthTransition(options); - } - - jni::Local> CircleLayer::getCircleStrokeColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeColor())); - } - - jni::Local> CircleLayer::getCircleStrokeColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeColorTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleStrokeColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleStrokeColorTransition(options); - } - - jni::Local> CircleLayer::getCircleStrokeOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeOpacity())); - } - - jni::Local> CircleLayer::getCircleStrokeOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleStrokeOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleStrokeOpacityTransition(options); - } - - - // CircleJavaLayerPeerFactory - - CircleJavaLayerPeerFactory::~CircleJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> CircleJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new CircleLayer(toCircleLayer(layer))); - } - - jni::Local> CircleJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new CircleLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void CircleJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&CircleLayer::getCircleSortKey, "nativeGetCircleSortKey"), - METHOD(&CircleLayer::getCircleRadiusTransition, "nativeGetCircleRadiusTransition"), - METHOD(&CircleLayer::setCircleRadiusTransition, "nativeSetCircleRadiusTransition"), - METHOD(&CircleLayer::getCircleRadius, "nativeGetCircleRadius"), - METHOD(&CircleLayer::getCircleColorTransition, "nativeGetCircleColorTransition"), - METHOD(&CircleLayer::setCircleColorTransition, "nativeSetCircleColorTransition"), - METHOD(&CircleLayer::getCircleColor, "nativeGetCircleColor"), - METHOD(&CircleLayer::getCircleBlurTransition, "nativeGetCircleBlurTransition"), - METHOD(&CircleLayer::setCircleBlurTransition, "nativeSetCircleBlurTransition"), - METHOD(&CircleLayer::getCircleBlur, "nativeGetCircleBlur"), - METHOD(&CircleLayer::getCircleOpacityTransition, "nativeGetCircleOpacityTransition"), - METHOD(&CircleLayer::setCircleOpacityTransition, "nativeSetCircleOpacityTransition"), - METHOD(&CircleLayer::getCircleOpacity, "nativeGetCircleOpacity"), - METHOD(&CircleLayer::getCircleTranslateTransition, "nativeGetCircleTranslateTransition"), - METHOD(&CircleLayer::setCircleTranslateTransition, "nativeSetCircleTranslateTransition"), - METHOD(&CircleLayer::getCircleTranslate, "nativeGetCircleTranslate"), - METHOD(&CircleLayer::getCircleTranslateAnchor, "nativeGetCircleTranslateAnchor"), - METHOD(&CircleLayer::getCirclePitchScale, "nativeGetCirclePitchScale"), - METHOD(&CircleLayer::getCirclePitchAlignment, "nativeGetCirclePitchAlignment"), - METHOD(&CircleLayer::getCircleStrokeWidthTransition, "nativeGetCircleStrokeWidthTransition"), - METHOD(&CircleLayer::setCircleStrokeWidthTransition, "nativeSetCircleStrokeWidthTransition"), - METHOD(&CircleLayer::getCircleStrokeWidth, "nativeGetCircleStrokeWidth"), - METHOD(&CircleLayer::getCircleStrokeColorTransition, "nativeGetCircleStrokeColorTransition"), - METHOD(&CircleLayer::setCircleStrokeColorTransition, "nativeSetCircleStrokeColorTransition"), - METHOD(&CircleLayer::getCircleStrokeColor, "nativeGetCircleStrokeColor"), - METHOD(&CircleLayer::getCircleStrokeOpacityTransition, "nativeGetCircleStrokeOpacityTransition"), - METHOD(&CircleLayer::setCircleStrokeOpacityTransition, "nativeSetCircleStrokeOpacityTransition"), - METHOD(&CircleLayer::getCircleStrokeOpacity, "nativeGetCircleStrokeOpacity")); - } +inline mbgl::style::CircleLayer& toCircleLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +CircleLayer::CircleLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique( + jni::Make(env, layerId), jni::Make(env, sourceId) + )) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +CircleLayer::CircleLayer(mbgl::style::CircleLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +CircleLayer::CircleLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +CircleLayer::~CircleLayer() = default; + +// Property getters + +jni::Local> CircleLayer::getCircleSortKey(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleSortKey())); +} + +jni::Local> CircleLayer::getCircleRadius(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleRadius())); +} + +jni::Local> CircleLayer::getCircleRadiusTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleRadiusTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleRadiusTransition(options); +} + +jni::Local> CircleLayer::getCircleColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleColor())); +} + +jni::Local> CircleLayer::getCircleColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleColorTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleColorTransition(options); +} + +jni::Local> CircleLayer::getCircleBlur(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleBlur())); +} + +jni::Local> CircleLayer::getCircleBlurTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleBlurTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleBlurTransition(options); +} + +jni::Local> CircleLayer::getCircleOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleOpacity())); +} + +jni::Local> CircleLayer::getCircleOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleOpacityTransition(options); +} + +jni::Local> CircleLayer::getCircleTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleTranslate())); +} + +jni::Local> CircleLayer::getCircleTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleTranslateTransition(options); +} + +jni::Local> CircleLayer::getCircleTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleTranslateAnchor())); +} + +jni::Local> CircleLayer::getCirclePitchScale(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCirclePitchScale())); +} + +jni::Local> CircleLayer::getCirclePitchAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCirclePitchAlignment())); +} + +jni::Local> CircleLayer::getCircleStrokeWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeWidth())); +} + +jni::Local> CircleLayer::getCircleStrokeWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleStrokeWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleStrokeWidthTransition(options); +} + +jni::Local> CircleLayer::getCircleStrokeColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeColor())); +} + +jni::Local> CircleLayer::getCircleStrokeColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeColorTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleStrokeColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleStrokeColorTransition(options); +} + +jni::Local> CircleLayer::getCircleStrokeOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeOpacity())); +} + +jni::Local> CircleLayer::getCircleStrokeOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleStrokeOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleStrokeOpacityTransition(options); +} + +// CircleJavaLayerPeerFactory + +CircleJavaLayerPeerFactory::~CircleJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> CircleJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new CircleLayer(toCircleLayer(layer))); +} + +jni::Local> CircleJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new CircleLayer(std::unique_ptr(static_cast(layer.release() + ))) + ); +} + +void CircleJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&CircleLayer::getCircleSortKey, "nativeGetCircleSortKey"), + METHOD(&CircleLayer::getCircleRadiusTransition, "nativeGetCircleRadiusTransition"), + METHOD(&CircleLayer::setCircleRadiusTransition, "nativeSetCircleRadiusTransition"), + METHOD(&CircleLayer::getCircleRadius, "nativeGetCircleRadius"), + METHOD(&CircleLayer::getCircleColorTransition, "nativeGetCircleColorTransition"), + METHOD(&CircleLayer::setCircleColorTransition, "nativeSetCircleColorTransition"), + METHOD(&CircleLayer::getCircleColor, "nativeGetCircleColor"), + METHOD(&CircleLayer::getCircleBlurTransition, "nativeGetCircleBlurTransition"), + METHOD(&CircleLayer::setCircleBlurTransition, "nativeSetCircleBlurTransition"), + METHOD(&CircleLayer::getCircleBlur, "nativeGetCircleBlur"), + METHOD(&CircleLayer::getCircleOpacityTransition, "nativeGetCircleOpacityTransition"), + METHOD(&CircleLayer::setCircleOpacityTransition, "nativeSetCircleOpacityTransition"), + METHOD(&CircleLayer::getCircleOpacity, "nativeGetCircleOpacity"), + METHOD(&CircleLayer::getCircleTranslateTransition, "nativeGetCircleTranslateTransition"), + METHOD(&CircleLayer::setCircleTranslateTransition, "nativeSetCircleTranslateTransition"), + METHOD(&CircleLayer::getCircleTranslate, "nativeGetCircleTranslate"), + METHOD(&CircleLayer::getCircleTranslateAnchor, "nativeGetCircleTranslateAnchor"), + METHOD(&CircleLayer::getCirclePitchScale, "nativeGetCirclePitchScale"), + METHOD(&CircleLayer::getCirclePitchAlignment, "nativeGetCirclePitchAlignment"), + METHOD(&CircleLayer::getCircleStrokeWidthTransition, "nativeGetCircleStrokeWidthTransition"), + METHOD(&CircleLayer::setCircleStrokeWidthTransition, "nativeSetCircleStrokeWidthTransition"), + METHOD(&CircleLayer::getCircleStrokeWidth, "nativeGetCircleStrokeWidth"), + METHOD(&CircleLayer::getCircleStrokeColorTransition, "nativeGetCircleStrokeColorTransition"), + METHOD(&CircleLayer::setCircleStrokeColorTransition, "nativeSetCircleStrokeColorTransition"), + METHOD(&CircleLayer::getCircleStrokeColor, "nativeGetCircleStrokeColor"), + METHOD(&CircleLayer::getCircleStrokeOpacityTransition, "nativeGetCircleStrokeOpacityTransition"), + METHOD(&CircleLayer::setCircleStrokeOpacityTransition, "nativeSetCircleStrokeOpacityTransition"), + METHOD(&CircleLayer::getCircleStrokeOpacity, "nativeGetCircleStrokeOpacity") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.hpp index ee95656d616..4a54bc39aa9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.hpp @@ -68,7 +68,7 @@ class CircleLayer : public Layer { }; // class CircleLayer -class CircleJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::CircleLayerFactory { +class CircleJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::CircleLayerFactory { public: ~CircleJavaLayerPeerFactory() override; @@ -80,7 +80,7 @@ class CircleJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mb LayerFactory* getLayerFactory() final { return this; } -}; // class CircleJavaLayerPeerFactory +}; // class CircleJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.cpp index 5a8b239a8d5..115931dac39 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.cpp @@ -7,55 +7,62 @@ namespace mbgl { namespace android { - CustomLayer::CustomLayer(jni::JNIEnv& env, const jni::String& layerId, jni::jlong host) - : Layer(std::make_unique( - jni::Make(env, layerId), - std::unique_ptr(reinterpret_cast(host))) - ) { - } - - CustomLayer::CustomLayer(mbgl::style::CustomLayer& coreLayer) : Layer(coreLayer) {} - - CustomLayer::CustomLayer(std::unique_ptr coreLayer) : Layer(std::move(coreLayer)) {} - - CustomLayer::~CustomLayer() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } - - CustomJavaLayerPeerFactory::~CustomJavaLayerPeerFactory() = default; - - jni::Local> CustomJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, - mbgl::style::Layer& layer) { - return createJavaPeer(env, new CustomLayer(static_cast(layer))); - } - - jni::Local> CustomJavaLayerPeerFactory::createJavaLayerPeer( - jni::JNIEnv& env, std::unique_ptr layer) { - return createJavaPeer(env, - new CustomLayer(std::unique_ptr( - static_cast(layer.release())))); - } - - void CustomJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer(env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize"); - } +CustomLayer::CustomLayer(jni::JNIEnv& env, const jni::String& layerId, jni::jlong host) + : Layer(std::make_unique( + jni::Make(env, layerId), + std::unique_ptr(reinterpret_cast(host)) + )) {} + +CustomLayer::CustomLayer(mbgl::style::CustomLayer& coreLayer) + : Layer(coreLayer) {} + +CustomLayer::CustomLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +CustomLayer::~CustomLayer() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +CustomJavaLayerPeerFactory::~CustomJavaLayerPeerFactory() = default; + +jni::Local> CustomJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + return createJavaPeer(env, new CustomLayer(static_cast(layer))); +} + +jni::Local> CustomJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + return createJavaPeer( + env, + new CustomLayer(std::unique_ptr(static_cast(layer.release() + ))) + ); +} + +void CustomJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize" + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.hpp index 3856ea73ae8..88c1cbc2c28 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.hpp @@ -23,7 +23,7 @@ class CustomLayer : public Layer { jni::Local> createJavaPeer(jni::JNIEnv&); }; // class CustomLayer -class CustomJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::CustomLayerFactory { +class CustomJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::CustomLayerFactory { public: ~CustomJavaLayerPeerFactory() override; @@ -35,7 +35,7 @@ class CustomJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mb LayerFactory* getLayerFactory() final { return this; } -}; // class CustomJavaLayerPeerFactory +}; // class CustomJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.cpp index 0d1d107b120..c445dbfdc2f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.cpp @@ -12,211 +12,223 @@ namespace mbgl { namespace android { - inline mbgl::style::FillExtrusionLayer& toFillExtrusionLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - FillExtrusionLayer::FillExtrusionLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - FillExtrusionLayer::FillExtrusionLayer(mbgl::style::FillExtrusionLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - FillExtrusionLayer::FillExtrusionLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - FillExtrusionLayer::~FillExtrusionLayer() = default; - - // Property getters - - jni::Local> FillExtrusionLayer::getFillExtrusionOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionOpacity())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionOpacityTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionColor())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionColorTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionColorTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionTranslate())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionTranslateTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionTranslateAnchor())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionPattern(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionPattern())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionPatternTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionPatternTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionPatternTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionHeight(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionHeight())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionHeightTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionHeightTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionHeightTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionHeightTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionBase(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionBase())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionBaseTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionBaseTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionBaseTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionBaseTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionVerticalGradient(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionVerticalGradient())); - } - - - // FillExtrusionJavaLayerPeerFactory - - FillExtrusionJavaLayerPeerFactory::~FillExtrusionJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> FillExtrusionJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new FillExtrusionLayer(toFillExtrusionLayer(layer))); - } - - jni::Local> FillExtrusionJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new FillExtrusionLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void FillExtrusionJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&FillExtrusionLayer::getFillExtrusionOpacityTransition, "nativeGetFillExtrusionOpacityTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionOpacityTransition, "nativeSetFillExtrusionOpacityTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionOpacity, "nativeGetFillExtrusionOpacity"), - METHOD(&FillExtrusionLayer::getFillExtrusionColorTransition, "nativeGetFillExtrusionColorTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionColorTransition, "nativeSetFillExtrusionColorTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionColor, "nativeGetFillExtrusionColor"), - METHOD(&FillExtrusionLayer::getFillExtrusionTranslateTransition, "nativeGetFillExtrusionTranslateTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionTranslateTransition, "nativeSetFillExtrusionTranslateTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionTranslate, "nativeGetFillExtrusionTranslate"), - METHOD(&FillExtrusionLayer::getFillExtrusionTranslateAnchor, "nativeGetFillExtrusionTranslateAnchor"), - METHOD(&FillExtrusionLayer::getFillExtrusionPatternTransition, "nativeGetFillExtrusionPatternTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionPatternTransition, "nativeSetFillExtrusionPatternTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionPattern, "nativeGetFillExtrusionPattern"), - METHOD(&FillExtrusionLayer::getFillExtrusionHeightTransition, "nativeGetFillExtrusionHeightTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionHeightTransition, "nativeSetFillExtrusionHeightTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionHeight, "nativeGetFillExtrusionHeight"), - METHOD(&FillExtrusionLayer::getFillExtrusionBaseTransition, "nativeGetFillExtrusionBaseTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionBaseTransition, "nativeSetFillExtrusionBaseTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionBase, "nativeGetFillExtrusionBase"), - METHOD(&FillExtrusionLayer::getFillExtrusionVerticalGradient, "nativeGetFillExtrusionVerticalGradient")); - } +inline mbgl::style::FillExtrusionLayer& toFillExtrusionLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +FillExtrusionLayer::FillExtrusionLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique( + jni::Make(env, layerId), jni::Make(env, sourceId) + )) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +FillExtrusionLayer::FillExtrusionLayer(mbgl::style::FillExtrusionLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +FillExtrusionLayer::FillExtrusionLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +FillExtrusionLayer::~FillExtrusionLayer() = default; + +// Property getters + +jni::Local> FillExtrusionLayer::getFillExtrusionOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionOpacity())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionOpacityTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionColor())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionColorTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionColorTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionTranslate())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionTranslateTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionTranslateAnchor()) + ); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionPattern(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionPattern())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionPatternTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionPatternTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionPatternTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionHeight(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionHeight())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionHeightTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionHeightTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionHeightTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionHeightTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionBase(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionBase())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionBaseTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionBaseTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionBaseTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionBaseTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionVerticalGradient(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionVerticalGradient()) + ); +} + +// FillExtrusionJavaLayerPeerFactory + +FillExtrusionJavaLayerPeerFactory::~FillExtrusionJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> FillExtrusionJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new FillExtrusionLayer(toFillExtrusionLayer(layer))); +} + +jni::Local> FillExtrusionJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new FillExtrusionLayer(std::unique_ptr( + static_cast(layer.release()) + )) + ); +} + +void FillExtrusionJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&FillExtrusionLayer::getFillExtrusionOpacityTransition, "nativeGetFillExtrusionOpacityTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionOpacityTransition, "nativeSetFillExtrusionOpacityTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionOpacity, "nativeGetFillExtrusionOpacity"), + METHOD(&FillExtrusionLayer::getFillExtrusionColorTransition, "nativeGetFillExtrusionColorTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionColorTransition, "nativeSetFillExtrusionColorTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionColor, "nativeGetFillExtrusionColor"), + METHOD(&FillExtrusionLayer::getFillExtrusionTranslateTransition, "nativeGetFillExtrusionTranslateTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionTranslateTransition, "nativeSetFillExtrusionTranslateTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionTranslate, "nativeGetFillExtrusionTranslate"), + METHOD(&FillExtrusionLayer::getFillExtrusionTranslateAnchor, "nativeGetFillExtrusionTranslateAnchor"), + METHOD(&FillExtrusionLayer::getFillExtrusionPatternTransition, "nativeGetFillExtrusionPatternTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionPatternTransition, "nativeSetFillExtrusionPatternTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionPattern, "nativeGetFillExtrusionPattern"), + METHOD(&FillExtrusionLayer::getFillExtrusionHeightTransition, "nativeGetFillExtrusionHeightTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionHeightTransition, "nativeSetFillExtrusionHeightTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionHeight, "nativeGetFillExtrusionHeight"), + METHOD(&FillExtrusionLayer::getFillExtrusionBaseTransition, "nativeGetFillExtrusionBaseTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionBaseTransition, "nativeSetFillExtrusionBaseTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionBase, "nativeGetFillExtrusionBase"), + METHOD(&FillExtrusionLayer::getFillExtrusionVerticalGradient, "nativeGetFillExtrusionVerticalGradient") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.hpp index aa478e422af..6aa0130ddc0 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.hpp @@ -56,7 +56,7 @@ class FillExtrusionLayer : public Layer { }; // class FillExtrusionLayer -class FillExtrusionJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::FillExtrusionLayerFactory { +class FillExtrusionJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::FillExtrusionLayerFactory { public: ~FillExtrusionJavaLayerPeerFactory() override; @@ -68,7 +68,7 @@ class FillExtrusionJavaLayerPeerFactory final : public JavaLayerPeerFactory, pu LayerFactory* getLayerFactory() final { return this; } -}; // class FillExtrusionJavaLayerPeerFactory +}; // class FillExtrusionJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.cpp index 8b33c80772c..22007e02f2d 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.cpp @@ -12,196 +12,202 @@ namespace mbgl { namespace android { - inline mbgl::style::FillLayer& toFillLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - FillLayer::FillLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - FillLayer::FillLayer(mbgl::style::FillLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - FillLayer::FillLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - FillLayer::~FillLayer() = default; - - // Property getters - - jni::Local> FillLayer::getFillSortKey(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillSortKey())); - } - - jni::Local> FillLayer::getFillAntialias(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillAntialias())); - } - - jni::Local> FillLayer::getFillOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillOpacity())); - } - - jni::Local> FillLayer::getFillOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillOpacityTransition(options); - } - - jni::Local> FillLayer::getFillColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillColor())); - } - - jni::Local> FillLayer::getFillColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillColorTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillColorTransition(options); - } - - jni::Local> FillLayer::getFillOutlineColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillOutlineColor())); - } - - jni::Local> FillLayer::getFillOutlineColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillOutlineColorTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillOutlineColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillOutlineColorTransition(options); - } - - jni::Local> FillLayer::getFillTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillTranslate())); - } - - jni::Local> FillLayer::getFillTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillTranslateTransition(options); - } - - jni::Local> FillLayer::getFillTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillTranslateAnchor())); - } - - jni::Local> FillLayer::getFillPattern(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillPattern())); - } - - jni::Local> FillLayer::getFillPatternTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillPatternTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillPatternTransition(options); - } - - - // FillJavaLayerPeerFactory - - FillJavaLayerPeerFactory::~FillJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> FillJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new FillLayer(toFillLayer(layer))); - } - - jni::Local> FillJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new FillLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void FillJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&FillLayer::getFillSortKey, "nativeGetFillSortKey"), - METHOD(&FillLayer::getFillAntialias, "nativeGetFillAntialias"), - METHOD(&FillLayer::getFillOpacityTransition, "nativeGetFillOpacityTransition"), - METHOD(&FillLayer::setFillOpacityTransition, "nativeSetFillOpacityTransition"), - METHOD(&FillLayer::getFillOpacity, "nativeGetFillOpacity"), - METHOD(&FillLayer::getFillColorTransition, "nativeGetFillColorTransition"), - METHOD(&FillLayer::setFillColorTransition, "nativeSetFillColorTransition"), - METHOD(&FillLayer::getFillColor, "nativeGetFillColor"), - METHOD(&FillLayer::getFillOutlineColorTransition, "nativeGetFillOutlineColorTransition"), - METHOD(&FillLayer::setFillOutlineColorTransition, "nativeSetFillOutlineColorTransition"), - METHOD(&FillLayer::getFillOutlineColor, "nativeGetFillOutlineColor"), - METHOD(&FillLayer::getFillTranslateTransition, "nativeGetFillTranslateTransition"), - METHOD(&FillLayer::setFillTranslateTransition, "nativeSetFillTranslateTransition"), - METHOD(&FillLayer::getFillTranslate, "nativeGetFillTranslate"), - METHOD(&FillLayer::getFillTranslateAnchor, "nativeGetFillTranslateAnchor"), - METHOD(&FillLayer::getFillPatternTransition, "nativeGetFillPatternTransition"), - METHOD(&FillLayer::setFillPatternTransition, "nativeSetFillPatternTransition"), - METHOD(&FillLayer::getFillPattern, "nativeGetFillPattern")); - } +inline mbgl::style::FillLayer& toFillLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +FillLayer::FillLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique( + jni::Make(env, layerId), jni::Make(env, sourceId) + )) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +FillLayer::FillLayer(mbgl::style::FillLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +FillLayer::FillLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +FillLayer::~FillLayer() = default; + +// Property getters + +jni::Local> FillLayer::getFillSortKey(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillSortKey())); +} + +jni::Local> FillLayer::getFillAntialias(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillAntialias())); +} + +jni::Local> FillLayer::getFillOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillOpacity())); +} + +jni::Local> FillLayer::getFillOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillOpacityTransition(options); +} + +jni::Local> FillLayer::getFillColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillColor())); +} + +jni::Local> FillLayer::getFillColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillColorTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillColorTransition(options); +} + +jni::Local> FillLayer::getFillOutlineColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillOutlineColor())); +} + +jni::Local> FillLayer::getFillOutlineColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillOutlineColorTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillOutlineColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillOutlineColorTransition(options); +} + +jni::Local> FillLayer::getFillTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillTranslate())); +} + +jni::Local> FillLayer::getFillTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillTranslateTransition(options); +} + +jni::Local> FillLayer::getFillTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillTranslateAnchor())); +} + +jni::Local> FillLayer::getFillPattern(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillPattern())); +} + +jni::Local> FillLayer::getFillPatternTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillPatternTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillPatternTransition(options); +} + +// FillJavaLayerPeerFactory + +FillJavaLayerPeerFactory::~FillJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> FillJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new FillLayer(toFillLayer(layer))); +} + +jni::Local> FillJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new FillLayer(std::unique_ptr(static_cast(layer.release()))) + ); +} + +void FillJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&FillLayer::getFillSortKey, "nativeGetFillSortKey"), + METHOD(&FillLayer::getFillAntialias, "nativeGetFillAntialias"), + METHOD(&FillLayer::getFillOpacityTransition, "nativeGetFillOpacityTransition"), + METHOD(&FillLayer::setFillOpacityTransition, "nativeSetFillOpacityTransition"), + METHOD(&FillLayer::getFillOpacity, "nativeGetFillOpacity"), + METHOD(&FillLayer::getFillColorTransition, "nativeGetFillColorTransition"), + METHOD(&FillLayer::setFillColorTransition, "nativeSetFillColorTransition"), + METHOD(&FillLayer::getFillColor, "nativeGetFillColor"), + METHOD(&FillLayer::getFillOutlineColorTransition, "nativeGetFillOutlineColorTransition"), + METHOD(&FillLayer::setFillOutlineColorTransition, "nativeSetFillOutlineColorTransition"), + METHOD(&FillLayer::getFillOutlineColor, "nativeGetFillOutlineColor"), + METHOD(&FillLayer::getFillTranslateTransition, "nativeGetFillTranslateTransition"), + METHOD(&FillLayer::setFillTranslateTransition, "nativeSetFillTranslateTransition"), + METHOD(&FillLayer::getFillTranslate, "nativeGetFillTranslate"), + METHOD(&FillLayer::getFillTranslateAnchor, "nativeGetFillTranslateAnchor"), + METHOD(&FillLayer::getFillPatternTransition, "nativeGetFillPatternTransition"), + METHOD(&FillLayer::setFillPatternTransition, "nativeSetFillPatternTransition"), + METHOD(&FillLayer::getFillPattern, "nativeGetFillPattern") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.hpp index 592d951f2a7..6fd29284586 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.hpp @@ -54,7 +54,7 @@ class FillLayer : public Layer { }; // class FillLayer -class FillJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::FillLayerFactory { +class FillJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::FillLayerFactory { public: ~FillJavaLayerPeerFactory() override; @@ -66,7 +66,7 @@ class FillJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl LayerFactory* getLayerFactory() final { return this; } -}; // class FillJavaLayerPeerFactory +}; // class FillJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.cpp index 686e44c3a9d..72bc54df10f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.cpp @@ -12,152 +12,160 @@ namespace mbgl { namespace android { - inline mbgl::style::HeatmapLayer& toHeatmapLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - HeatmapLayer::HeatmapLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - HeatmapLayer::HeatmapLayer(mbgl::style::HeatmapLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - HeatmapLayer::HeatmapLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - HeatmapLayer::~HeatmapLayer() = default; - - // Property getters - - jni::Local> HeatmapLayer::getHeatmapRadius(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapRadius())); - } - - jni::Local> HeatmapLayer::getHeatmapRadiusTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapRadiusTransition(); - return std::move(*convert>>(env, options)); - } - - void HeatmapLayer::setHeatmapRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHeatmapLayer(layer).setHeatmapRadiusTransition(options); - } - - jni::Local> HeatmapLayer::getHeatmapWeight(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapWeight())); - } - - jni::Local> HeatmapLayer::getHeatmapIntensity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapIntensity())); - } - - jni::Local> HeatmapLayer::getHeatmapIntensityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapIntensityTransition(); - return std::move(*convert>>(env, options)); - } - - void HeatmapLayer::setHeatmapIntensityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHeatmapLayer(layer).setHeatmapIntensityTransition(options); - } - - jni::Local> HeatmapLayer::getHeatmapColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - auto propertyValue = toHeatmapLayer(layer).getHeatmapColor(); - if (propertyValue.isUndefined()) { - propertyValue = toHeatmapLayer(layer).getDefaultHeatmapColor(); - } - return std::move(*convert>>(env, propertyValue)); - } - - jni::Local> HeatmapLayer::getHeatmapOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapOpacity())); - } - - jni::Local> HeatmapLayer::getHeatmapOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void HeatmapLayer::setHeatmapOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHeatmapLayer(layer).setHeatmapOpacityTransition(options); - } - - - // HeatmapJavaLayerPeerFactory - - HeatmapJavaLayerPeerFactory::~HeatmapJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> HeatmapJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new HeatmapLayer(toHeatmapLayer(layer))); - } - - jni::Local> HeatmapJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new HeatmapLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void HeatmapJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&HeatmapLayer::getHeatmapRadiusTransition, "nativeGetHeatmapRadiusTransition"), - METHOD(&HeatmapLayer::setHeatmapRadiusTransition, "nativeSetHeatmapRadiusTransition"), - METHOD(&HeatmapLayer::getHeatmapRadius, "nativeGetHeatmapRadius"), - METHOD(&HeatmapLayer::getHeatmapWeight, "nativeGetHeatmapWeight"), - METHOD(&HeatmapLayer::getHeatmapIntensityTransition, "nativeGetHeatmapIntensityTransition"), - METHOD(&HeatmapLayer::setHeatmapIntensityTransition, "nativeSetHeatmapIntensityTransition"), - METHOD(&HeatmapLayer::getHeatmapIntensity, "nativeGetHeatmapIntensity"), - METHOD(&HeatmapLayer::getHeatmapColor, "nativeGetHeatmapColor"), - METHOD(&HeatmapLayer::getHeatmapOpacityTransition, "nativeGetHeatmapOpacityTransition"), - METHOD(&HeatmapLayer::setHeatmapOpacityTransition, "nativeSetHeatmapOpacityTransition"), - METHOD(&HeatmapLayer::getHeatmapOpacity, "nativeGetHeatmapOpacity")); - } +inline mbgl::style::HeatmapLayer& toHeatmapLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +HeatmapLayer::HeatmapLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique( + jni::Make(env, layerId), jni::Make(env, sourceId) + )) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +HeatmapLayer::HeatmapLayer(mbgl::style::HeatmapLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +HeatmapLayer::HeatmapLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +HeatmapLayer::~HeatmapLayer() = default; + +// Property getters + +jni::Local> HeatmapLayer::getHeatmapRadius(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapRadius())); +} + +jni::Local> HeatmapLayer::getHeatmapRadiusTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapRadiusTransition(); + return std::move(*convert>>(env, options)); +} + +void HeatmapLayer::setHeatmapRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHeatmapLayer(layer).setHeatmapRadiusTransition(options); +} + +jni::Local> HeatmapLayer::getHeatmapWeight(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapWeight())); +} + +jni::Local> HeatmapLayer::getHeatmapIntensity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapIntensity())); +} + +jni::Local> HeatmapLayer::getHeatmapIntensityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapIntensityTransition(); + return std::move(*convert>>(env, options)); +} + +void HeatmapLayer::setHeatmapIntensityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHeatmapLayer(layer).setHeatmapIntensityTransition(options); +} + +jni::Local> HeatmapLayer::getHeatmapColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + auto propertyValue = toHeatmapLayer(layer).getHeatmapColor(); + if (propertyValue.isUndefined()) { + propertyValue = toHeatmapLayer(layer).getDefaultHeatmapColor(); + } + return std::move(*convert>>(env, propertyValue)); +} + +jni::Local> HeatmapLayer::getHeatmapOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapOpacity())); +} + +jni::Local> HeatmapLayer::getHeatmapOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void HeatmapLayer::setHeatmapOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHeatmapLayer(layer).setHeatmapOpacityTransition(options); +} + +// HeatmapJavaLayerPeerFactory + +HeatmapJavaLayerPeerFactory::~HeatmapJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> HeatmapJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new HeatmapLayer(toHeatmapLayer(layer))); +} + +jni::Local> HeatmapJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new HeatmapLayer( + std::unique_ptr(static_cast(layer.release())) + ) + ); +} + +void HeatmapJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&HeatmapLayer::getHeatmapRadiusTransition, "nativeGetHeatmapRadiusTransition"), + METHOD(&HeatmapLayer::setHeatmapRadiusTransition, "nativeSetHeatmapRadiusTransition"), + METHOD(&HeatmapLayer::getHeatmapRadius, "nativeGetHeatmapRadius"), + METHOD(&HeatmapLayer::getHeatmapWeight, "nativeGetHeatmapWeight"), + METHOD(&HeatmapLayer::getHeatmapIntensityTransition, "nativeGetHeatmapIntensityTransition"), + METHOD(&HeatmapLayer::setHeatmapIntensityTransition, "nativeSetHeatmapIntensityTransition"), + METHOD(&HeatmapLayer::getHeatmapIntensity, "nativeGetHeatmapIntensity"), + METHOD(&HeatmapLayer::getHeatmapColor, "nativeGetHeatmapColor"), + METHOD(&HeatmapLayer::getHeatmapOpacityTransition, "nativeGetHeatmapOpacityTransition"), + METHOD(&HeatmapLayer::setHeatmapOpacityTransition, "nativeSetHeatmapOpacityTransition"), + METHOD(&HeatmapLayer::getHeatmapOpacity, "nativeGetHeatmapOpacity") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.hpp index 15b24b14722..bf88367df35 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.hpp @@ -44,7 +44,7 @@ class HeatmapLayer : public Layer { }; // class HeatmapLayer -class HeatmapJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::HeatmapLayerFactory { +class HeatmapJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::HeatmapLayerFactory { public: ~HeatmapJavaLayerPeerFactory() override; @@ -56,7 +56,7 @@ class HeatmapJavaLayerPeerFactory final : public JavaLayerPeerFactory, public m LayerFactory* getLayerFactory() final { return this; } -}; // class HeatmapJavaLayerPeerFactory +}; // class HeatmapJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.cpp index fa094f9ae7e..faee9f924a5 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.cpp @@ -12,169 +12,180 @@ namespace mbgl { namespace android { - inline mbgl::style::HillshadeLayer& toHillshadeLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - HillshadeLayer::HillshadeLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - HillshadeLayer::HillshadeLayer(mbgl::style::HillshadeLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - HillshadeLayer::HillshadeLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - HillshadeLayer::~HillshadeLayer() = default; - - // Property getters - - jni::Local> HillshadeLayer::getHillshadeIlluminationDirection(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeIlluminationDirection())); - } - - jni::Local> HillshadeLayer::getHillshadeIlluminationAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeIlluminationAnchor())); - } - - jni::Local> HillshadeLayer::getHillshadeExaggeration(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeExaggeration())); - } - - jni::Local> HillshadeLayer::getHillshadeExaggerationTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeExaggerationTransition(); - return std::move(*convert>>(env, options)); - } - - void HillshadeLayer::setHillshadeExaggerationTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHillshadeLayer(layer).setHillshadeExaggerationTransition(options); - } - - jni::Local> HillshadeLayer::getHillshadeShadowColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeShadowColor())); - } - - jni::Local> HillshadeLayer::getHillshadeShadowColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeShadowColorTransition(); - return std::move(*convert>>(env, options)); - } - - void HillshadeLayer::setHillshadeShadowColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHillshadeLayer(layer).setHillshadeShadowColorTransition(options); - } - - jni::Local> HillshadeLayer::getHillshadeHighlightColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeHighlightColor())); - } - - jni::Local> HillshadeLayer::getHillshadeHighlightColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeHighlightColorTransition(); - return std::move(*convert>>(env, options)); - } - - void HillshadeLayer::setHillshadeHighlightColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHillshadeLayer(layer).setHillshadeHighlightColorTransition(options); - } - - jni::Local> HillshadeLayer::getHillshadeAccentColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeAccentColor())); - } - - jni::Local> HillshadeLayer::getHillshadeAccentColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeAccentColorTransition(); - return std::move(*convert>>(env, options)); - } - - void HillshadeLayer::setHillshadeAccentColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHillshadeLayer(layer).setHillshadeAccentColorTransition(options); - } - - - // HillshadeJavaLayerPeerFactory - - HillshadeJavaLayerPeerFactory::~HillshadeJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> HillshadeJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new HillshadeLayer(toHillshadeLayer(layer))); - } - - jni::Local> HillshadeJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new HillshadeLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void HillshadeJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&HillshadeLayer::getHillshadeIlluminationDirection, "nativeGetHillshadeIlluminationDirection"), - METHOD(&HillshadeLayer::getHillshadeIlluminationAnchor, "nativeGetHillshadeIlluminationAnchor"), - METHOD(&HillshadeLayer::getHillshadeExaggerationTransition, "nativeGetHillshadeExaggerationTransition"), - METHOD(&HillshadeLayer::setHillshadeExaggerationTransition, "nativeSetHillshadeExaggerationTransition"), - METHOD(&HillshadeLayer::getHillshadeExaggeration, "nativeGetHillshadeExaggeration"), - METHOD(&HillshadeLayer::getHillshadeShadowColorTransition, "nativeGetHillshadeShadowColorTransition"), - METHOD(&HillshadeLayer::setHillshadeShadowColorTransition, "nativeSetHillshadeShadowColorTransition"), - METHOD(&HillshadeLayer::getHillshadeShadowColor, "nativeGetHillshadeShadowColor"), - METHOD(&HillshadeLayer::getHillshadeHighlightColorTransition, "nativeGetHillshadeHighlightColorTransition"), - METHOD(&HillshadeLayer::setHillshadeHighlightColorTransition, "nativeSetHillshadeHighlightColorTransition"), - METHOD(&HillshadeLayer::getHillshadeHighlightColor, "nativeGetHillshadeHighlightColor"), - METHOD(&HillshadeLayer::getHillshadeAccentColorTransition, "nativeGetHillshadeAccentColorTransition"), - METHOD(&HillshadeLayer::setHillshadeAccentColorTransition, "nativeSetHillshadeAccentColorTransition"), - METHOD(&HillshadeLayer::getHillshadeAccentColor, "nativeGetHillshadeAccentColor")); - } +inline mbgl::style::HillshadeLayer& toHillshadeLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +HillshadeLayer::HillshadeLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique( + jni::Make(env, layerId), jni::Make(env, sourceId) + )) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +HillshadeLayer::HillshadeLayer(mbgl::style::HillshadeLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +HillshadeLayer::HillshadeLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +HillshadeLayer::~HillshadeLayer() = default; + +// Property getters + +jni::Local> HillshadeLayer::getHillshadeIlluminationDirection(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toHillshadeLayer(layer).getHillshadeIlluminationDirection()) + ); +} + +jni::Local> HillshadeLayer::getHillshadeIlluminationAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeIlluminationAnchor()) + ); +} + +jni::Local> HillshadeLayer::getHillshadeExaggeration(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeExaggeration())); +} + +jni::Local> HillshadeLayer::getHillshadeExaggerationTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeExaggerationTransition(); + return std::move(*convert>>(env, options)); +} + +void HillshadeLayer::setHillshadeExaggerationTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHillshadeLayer(layer).setHillshadeExaggerationTransition(options); +} + +jni::Local> HillshadeLayer::getHillshadeShadowColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeShadowColor())); +} + +jni::Local> HillshadeLayer::getHillshadeShadowColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeShadowColorTransition(); + return std::move(*convert>>(env, options)); +} + +void HillshadeLayer::setHillshadeShadowColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHillshadeLayer(layer).setHillshadeShadowColorTransition(options); +} + +jni::Local> HillshadeLayer::getHillshadeHighlightColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeHighlightColor())); +} + +jni::Local> HillshadeLayer::getHillshadeHighlightColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeHighlightColorTransition(); + return std::move(*convert>>(env, options)); +} + +void HillshadeLayer::setHillshadeHighlightColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHillshadeLayer(layer).setHillshadeHighlightColorTransition(options); +} + +jni::Local> HillshadeLayer::getHillshadeAccentColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeAccentColor())); +} + +jni::Local> HillshadeLayer::getHillshadeAccentColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeAccentColorTransition(); + return std::move(*convert>>(env, options)); +} + +void HillshadeLayer::setHillshadeAccentColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHillshadeLayer(layer).setHillshadeAccentColorTransition(options); +} + +// HillshadeJavaLayerPeerFactory + +HillshadeJavaLayerPeerFactory::~HillshadeJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> HillshadeJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new HillshadeLayer(toHillshadeLayer(layer))); +} + +jni::Local> HillshadeJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new HillshadeLayer( + std::unique_ptr(static_cast(layer.release())) + ) + ); +} + +void HillshadeJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&HillshadeLayer::getHillshadeIlluminationDirection, "nativeGetHillshadeIlluminationDirection"), + METHOD(&HillshadeLayer::getHillshadeIlluminationAnchor, "nativeGetHillshadeIlluminationAnchor"), + METHOD(&HillshadeLayer::getHillshadeExaggerationTransition, "nativeGetHillshadeExaggerationTransition"), + METHOD(&HillshadeLayer::setHillshadeExaggerationTransition, "nativeSetHillshadeExaggerationTransition"), + METHOD(&HillshadeLayer::getHillshadeExaggeration, "nativeGetHillshadeExaggeration"), + METHOD(&HillshadeLayer::getHillshadeShadowColorTransition, "nativeGetHillshadeShadowColorTransition"), + METHOD(&HillshadeLayer::setHillshadeShadowColorTransition, "nativeSetHillshadeShadowColorTransition"), + METHOD(&HillshadeLayer::getHillshadeShadowColor, "nativeGetHillshadeShadowColor"), + METHOD(&HillshadeLayer::getHillshadeHighlightColorTransition, "nativeGetHillshadeHighlightColorTransition"), + METHOD(&HillshadeLayer::setHillshadeHighlightColorTransition, "nativeSetHillshadeHighlightColorTransition"), + METHOD(&HillshadeLayer::getHillshadeHighlightColor, "nativeGetHillshadeHighlightColor"), + METHOD(&HillshadeLayer::getHillshadeAccentColorTransition, "nativeGetHillshadeAccentColorTransition"), + METHOD(&HillshadeLayer::setHillshadeAccentColorTransition, "nativeSetHillshadeAccentColorTransition"), + METHOD(&HillshadeLayer::getHillshadeAccentColor, "nativeGetHillshadeAccentColor") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.hpp index 0c5d489ee56..260a71f1d13 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.hpp @@ -48,7 +48,7 @@ class HillshadeLayer : public Layer { }; // class HillshadeLayer -class HillshadeJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::HillshadeLayerFactory { +class HillshadeJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::HillshadeLayerFactory { public: ~HillshadeJavaLayerPeerFactory() override; @@ -60,7 +60,7 @@ class HillshadeJavaLayerPeerFactory final : public JavaLayerPeerFactory, public LayerFactory* getLayerFactory() final { return this; } -}; // class HillshadeJavaLayerPeerFactory +}; // class HillshadeJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.cpp index a4bf2dd52d6..5b0555dcd3e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.cpp @@ -24,145 +24,150 @@ namespace mbgl { namespace android { - /** - * Invoked when the construction is initiated from the jvm through a subclass - */ - Layer::Layer(std::unique_ptr coreLayer) - : ownedLayer(std::move(coreLayer)) - , layer(*ownedLayer) { - } - - /** - * Takes a non-owning reference. For lookup methods - */ - Layer::Layer(mbgl::style::Layer& coreLayer) : layer(coreLayer) {} - - Layer::~Layer() { - } - - void Layer::addToStyle(mbgl::style::Style& style, std::optional before) { - // Check to see if we own the layer first - if (!ownedLayer) { - throw std::runtime_error("Cannot add layer twice"); - } - - // Add layer to map - style.addLayer(releaseCoreLayer(), before); - } - - void Layer::setLayer(std::unique_ptr sourceLayer) { - this->ownedLayer = std::move(sourceLayer); - } - - std::unique_ptr Layer::releaseCoreLayer() { - assert(ownedLayer != nullptr); - return std::move(ownedLayer); - } - - jni::Local Layer::getId(jni::JNIEnv& env) { - return jni::Make(env, layer.getID()); - } - - style::Layer& Layer::get() { - return layer; - } - - void Layer::setProperty(jni::JNIEnv& env, const jni::String& jname, const jni::Object<>& jvalue) { - // Convert and set property - std::optional error = - layer.setProperty(jni::Make(env, jname), Value(env, jvalue)); - if (error) { - mbgl::Log::Error(mbgl::Event::JNI, "Error setting property: " + jni::Make(env, jname) + " " + error->message); - return; - } - } - - void Layer::setFilter(jni::JNIEnv& env, const jni::Array>& jfilter) { - using namespace mbgl::style; - using namespace mbgl::style::conversion; - - Error error; - std::optional converted = convert(Value(env, jfilter), error); - if (!converted) { - mbgl::Log::Error(mbgl::Event::JNI, "Error setting filter: " + error.message); - return; - } - - layer.setFilter(std::move(*converted)); - } - - jni::Local> Layer::getFilter(jni::JNIEnv& env) { - using namespace mbgl::style; - using namespace mbgl::style::conversion; - - Filter filter = layer.getFilter(); - if (filter.expression) { - mbgl::Value expressionValue = (*filter.expression)->serialize(); - return gson::JsonElement::New(env, expressionValue); - } else { - return jni::Local>(env, nullptr); - } - } - - void Layer::setSourceLayer(jni::JNIEnv& env, const jni::String& sourceLayer) { - layer.setSourceLayer(jni::Make(env, sourceLayer)); - } - - jni::Local Layer::getSourceLayer(jni::JNIEnv& env) { - return jni::Make(env, layer.getSourceLayer()); - } - - jni::Local Layer::getSourceId(jni::JNIEnv& env) { - return jni::Make(env, layer.getSourceID()); - } - - jni::jfloat Layer::getMinZoom(jni::JNIEnv&){ - return layer.getMinZoom(); - } - - jni::jfloat Layer::getMaxZoom(jni::JNIEnv&) { - return layer.getMaxZoom(); - } - - void Layer::setMinZoom(jni::JNIEnv&, jni::jfloat zoom) { - layer.setMinZoom(zoom); - } - - void Layer::setMaxZoom(jni::JNIEnv&, jni::jfloat zoom) { - layer.setMaxZoom(zoom); - } - - jni::Local> Layer::getVisibility(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, layer.getVisibility())); - } - - void Layer::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - METHOD(&Layer::getId, "nativeGetId"), - METHOD(&Layer::setProperty, - "nativeSetLayoutProperty"), // TODO : Export only nativeSetProperty() when #15970 lands. - METHOD(&Layer::setProperty, "nativeSetPaintProperty"), - METHOD(&Layer::setFilter, "nativeSetFilter"), - METHOD(&Layer::getFilter, "nativeGetFilter"), - METHOD(&Layer::setSourceLayer, "nativeSetSourceLayer"), - METHOD(&Layer::getSourceLayer, "nativeGetSourceLayer"), - METHOD(&Layer::getSourceId, "nativeGetSourceId"), - METHOD(&Layer::getMinZoom, "nativeGetMinZoom"), - METHOD(&Layer::getMaxZoom, "nativeGetMaxZoom"), - METHOD(&Layer::setMinZoom, "nativeSetMinZoom"), - METHOD(&Layer::setMaxZoom, "nativeSetMaxZoom"), - METHOD(&Layer::getVisibility, "nativeGetVisibility")); - } +/** + * Invoked when the construction is initiated from the jvm through a subclass + */ +Layer::Layer(std::unique_ptr coreLayer) + : ownedLayer(std::move(coreLayer)), + layer(*ownedLayer) {} + +/** + * Takes a non-owning reference. For lookup methods + */ +Layer::Layer(mbgl::style::Layer& coreLayer) + : layer(coreLayer) {} + +Layer::~Layer() {} + +void Layer::addToStyle(mbgl::style::Style& style, std::optional before) { + // Check to see if we own the layer first + if (!ownedLayer) { + throw std::runtime_error("Cannot add layer twice"); + } + + // Add layer to map + style.addLayer(releaseCoreLayer(), before); +} + +void Layer::setLayer(std::unique_ptr sourceLayer) { + this->ownedLayer = std::move(sourceLayer); +} + +std::unique_ptr Layer::releaseCoreLayer() { + assert(ownedLayer != nullptr); + return std::move(ownedLayer); +} + +jni::Local Layer::getId(jni::JNIEnv& env) { + return jni::Make(env, layer.getID()); +} + +style::Layer& Layer::get() { + return layer; +} + +void Layer::setProperty(jni::JNIEnv& env, const jni::String& jname, const jni::Object<>& jvalue) { + // Convert and set property + std::optional error = layer.setProperty( + jni::Make(env, jname), Value(env, jvalue) + ); + if (error) { + mbgl::Log::Error( + mbgl::Event::JNI, "Error setting property: " + jni::Make(env, jname) + " " + error->message + ); + return; + } +} + +void Layer::setFilter(jni::JNIEnv& env, const jni::Array>& jfilter) { + using namespace mbgl::style; + using namespace mbgl::style::conversion; + + Error error; + std::optional converted = convert(Value(env, jfilter), error); + if (!converted) { + mbgl::Log::Error(mbgl::Event::JNI, "Error setting filter: " + error.message); + return; + } + + layer.setFilter(std::move(*converted)); +} + +jni::Local> Layer::getFilter(jni::JNIEnv& env) { + using namespace mbgl::style; + using namespace mbgl::style::conversion; + + Filter filter = layer.getFilter(); + if (filter.expression) { + mbgl::Value expressionValue = (*filter.expression)->serialize(); + return gson::JsonElement::New(env, expressionValue); + } else { + return jni::Local>(env, nullptr); + } +} + +void Layer::setSourceLayer(jni::JNIEnv& env, const jni::String& sourceLayer) { + layer.setSourceLayer(jni::Make(env, sourceLayer)); +} + +jni::Local Layer::getSourceLayer(jni::JNIEnv& env) { + return jni::Make(env, layer.getSourceLayer()); +} + +jni::Local Layer::getSourceId(jni::JNIEnv& env) { + return jni::Make(env, layer.getSourceID()); +} + +jni::jfloat Layer::getMinZoom(jni::JNIEnv&) { + return layer.getMinZoom(); +} + +jni::jfloat Layer::getMaxZoom(jni::JNIEnv&) { + return layer.getMaxZoom(); +} + +void Layer::setMinZoom(jni::JNIEnv&, jni::jfloat zoom) { + layer.setMinZoom(zoom); +} + +void Layer::setMaxZoom(jni::JNIEnv&, jni::jfloat zoom) { + layer.setMaxZoom(zoom); +} + +jni::Local> Layer::getVisibility(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, layer.getVisibility())); +} + +void Layer::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + METHOD(&Layer::getId, "nativeGetId"), + METHOD( + &Layer::setProperty, + "nativeSetLayoutProperty" + ), // TODO : Export only nativeSetProperty() when #15970 lands. + METHOD(&Layer::setProperty, "nativeSetPaintProperty"), + METHOD(&Layer::setFilter, "nativeSetFilter"), + METHOD(&Layer::getFilter, "nativeGetFilter"), + METHOD(&Layer::setSourceLayer, "nativeSetSourceLayer"), + METHOD(&Layer::getSourceLayer, "nativeGetSourceLayer"), + METHOD(&Layer::getSourceId, "nativeGetSourceId"), + METHOD(&Layer::getMinZoom, "nativeGetMinZoom"), + METHOD(&Layer::getMaxZoom, "nativeGetMaxZoom"), + METHOD(&Layer::setMinZoom, "nativeSetMinZoom"), + METHOD(&Layer::setMaxZoom, "nativeSetMaxZoom"), + METHOD(&Layer::getVisibility, "nativeGetVisibility") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.hpp index d0ebf37fc41..1dfaf3f7101 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.hpp @@ -15,7 +15,6 @@ namespace android { class Layer { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/layers/Layer"; }; static void registerNative(jni::JNIEnv&); @@ -96,8 +95,8 @@ class JavaLayerPeerFactory { /** * @brief Create an owning peer. */ - virtual jni::Local> createJavaLayerPeer(jni::JNIEnv& env, - std::unique_ptr) = 0; + virtual jni::Local> + createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr) = 0; /** * @brief Register peer methods. @@ -106,12 +105,11 @@ class JavaLayerPeerFactory { /** * @brief Get the corresponding layer factory. - * + * * @return style::LayerFactory* must not be \c nullptr. */ virtual LayerFactory* getLayerFactory() = 0; }; - } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.cpp index 1e72b151630..a5518b65a54 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.cpp @@ -88,8 +88,9 @@ jni::Local> LayerManagerAndroid::createJavaLayerPeer(jni::JNI return jni::Local>(); } -jni::Local> LayerManagerAndroid::createJavaLayerPeer(jni::JNIEnv& env, - std::unique_ptr layer) { +jni::Local> LayerManagerAndroid::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { if (JavaLayerPeerFactory* factory = getPeerFactory(layer->getTypeInfo())) { return factory->createJavaLayerPeer(env, std::move(layer)); } @@ -102,7 +103,7 @@ void LayerManagerAndroid::registerNative(jni::JNIEnv& env) { } Layer::registerNative(env); - for (const auto& factory: peerFactories) { + for (const auto& factory : peerFactories) { factory->registerNative(env); } } @@ -129,7 +130,7 @@ void LayerManagerAndroid::registerCoreFactory(mbgl::LayerFactory* factory) { JavaLayerPeerFactory* LayerManagerAndroid::getPeerFactory(const mbgl::style::LayerTypeInfo* typeInfo) { assert(typeInfo); - for (const auto& factory: peerFactories) { + for (const auto& factory : peerFactories) { if (factory->getLayerFactory()->getTypeInfo() == typeInfo) { return factory.get(); } @@ -147,7 +148,7 @@ LayerFactory* LayerManagerAndroid::getFactory(const mbgl::style::LayerTypeInfo* return peerFactory->getLayerFactory(); } - for (const auto& factory: coreFactories) { + for (const auto& factory : coreFactories) { if (factory->getTypeInfo() == info) { return factory.get(); } @@ -168,7 +169,8 @@ LayerManager* LayerManager::get() noexcept { return android::LayerManagerAndroid::get(); } -#if defined(MBGL_LAYER_LINE_DISABLE_ALL) || defined(MBGL_LAYER_SYMBOL_DISABLE_ALL) || defined(MBGL_LAYER_FILL_DISABLE_ALL) +#if defined(MBGL_LAYER_LINE_DISABLE_ALL) || defined(MBGL_LAYER_SYMBOL_DISABLE_ALL) || \ + defined(MBGL_LAYER_FILL_DISABLE_ALL) const bool LayerManager::annotationsEnabled = false; #else const bool LayerManager::annotationsEnabled = true; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.hpp index f7379f6de64..f3e5c4f82da 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.hpp @@ -32,13 +32,13 @@ class LayerManagerAndroid final : public mbgl::LayerManager { /** * @brief Enables a layer type for both JSON style and runtime API. */ - void addLayerType(std::unique_ptr); + void addLayerType(std::unique_ptr); /** * @brief Enables a layer type for JSON style only. * * We might not want to expose runtime API for some layer types * in order to save binary size - JNI glue code for these layer types - * won't be added to the binary. + * won't be added to the binary. */ void addLayerTypeCoreOnly(std::unique_ptr); @@ -53,5 +53,5 @@ class LayerManagerAndroid final : public mbgl::LayerManager { std::map typeToFactory; }; -} // namespace android -} // namespace mbgl +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.cpp index bc05c41a173..dfa4cf570d1 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.cpp @@ -12,304 +12,310 @@ namespace mbgl { namespace android { - inline mbgl::style::LineLayer& toLineLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - LineLayer::LineLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - LineLayer::LineLayer(mbgl::style::LineLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - LineLayer::LineLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - LineLayer::~LineLayer() = default; - - // Property getters - - jni::Local> LineLayer::getLineCap(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineCap())); - } - - jni::Local> LineLayer::getLineJoin(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineJoin())); - } - - jni::Local> LineLayer::getLineMiterLimit(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineMiterLimit())); - } - - jni::Local> LineLayer::getLineRoundLimit(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineRoundLimit())); - } - - jni::Local> LineLayer::getLineSortKey(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineSortKey())); - } - - jni::Local> LineLayer::getLineOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineOpacity())); - } - - jni::Local> LineLayer::getLineOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineOpacityTransition(options); - } - - jni::Local> LineLayer::getLineColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineColor())); - } - - jni::Local> LineLayer::getLineColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineColorTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineColorTransition(options); - } - - jni::Local> LineLayer::getLineTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineTranslate())); - } - - jni::Local> LineLayer::getLineTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineTranslateTransition(options); - } - - jni::Local> LineLayer::getLineTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineTranslateAnchor())); - } - - jni::Local> LineLayer::getLineWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineWidth())); - } - - jni::Local> LineLayer::getLineWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineWidthTransition(options); - } - - jni::Local> LineLayer::getLineGapWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineGapWidth())); - } - - jni::Local> LineLayer::getLineGapWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineGapWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineGapWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineGapWidthTransition(options); - } - - jni::Local> LineLayer::getLineOffset(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineOffset())); - } - - jni::Local> LineLayer::getLineOffsetTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineOffsetTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineOffsetTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineOffsetTransition(options); - } - - jni::Local> LineLayer::getLineBlur(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineBlur())); - } - - jni::Local> LineLayer::getLineBlurTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineBlurTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineBlurTransition(options); - } - - jni::Local> LineLayer::getLineDasharray(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineDasharray())); - } - - jni::Local> LineLayer::getLineDasharrayTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineDasharrayTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineDasharrayTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineDasharrayTransition(options); - } - - jni::Local> LineLayer::getLinePattern(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLinePattern())); - } - - jni::Local> LineLayer::getLinePatternTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLinePatternTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLinePatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLinePatternTransition(options); - } - - jni::Local> LineLayer::getLineGradient(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineGradient())); - } - - - // LineJavaLayerPeerFactory - - LineJavaLayerPeerFactory::~LineJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> LineJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new LineLayer(toLineLayer(layer))); - } - - jni::Local> LineJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new LineLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void LineJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&LineLayer::getLineCap, "nativeGetLineCap"), - METHOD(&LineLayer::getLineJoin, "nativeGetLineJoin"), - METHOD(&LineLayer::getLineMiterLimit, "nativeGetLineMiterLimit"), - METHOD(&LineLayer::getLineRoundLimit, "nativeGetLineRoundLimit"), - METHOD(&LineLayer::getLineSortKey, "nativeGetLineSortKey"), - METHOD(&LineLayer::getLineOpacityTransition, "nativeGetLineOpacityTransition"), - METHOD(&LineLayer::setLineOpacityTransition, "nativeSetLineOpacityTransition"), - METHOD(&LineLayer::getLineOpacity, "nativeGetLineOpacity"), - METHOD(&LineLayer::getLineColorTransition, "nativeGetLineColorTransition"), - METHOD(&LineLayer::setLineColorTransition, "nativeSetLineColorTransition"), - METHOD(&LineLayer::getLineColor, "nativeGetLineColor"), - METHOD(&LineLayer::getLineTranslateTransition, "nativeGetLineTranslateTransition"), - METHOD(&LineLayer::setLineTranslateTransition, "nativeSetLineTranslateTransition"), - METHOD(&LineLayer::getLineTranslate, "nativeGetLineTranslate"), - METHOD(&LineLayer::getLineTranslateAnchor, "nativeGetLineTranslateAnchor"), - METHOD(&LineLayer::getLineWidthTransition, "nativeGetLineWidthTransition"), - METHOD(&LineLayer::setLineWidthTransition, "nativeSetLineWidthTransition"), - METHOD(&LineLayer::getLineWidth, "nativeGetLineWidth"), - METHOD(&LineLayer::getLineGapWidthTransition, "nativeGetLineGapWidthTransition"), - METHOD(&LineLayer::setLineGapWidthTransition, "nativeSetLineGapWidthTransition"), - METHOD(&LineLayer::getLineGapWidth, "nativeGetLineGapWidth"), - METHOD(&LineLayer::getLineOffsetTransition, "nativeGetLineOffsetTransition"), - METHOD(&LineLayer::setLineOffsetTransition, "nativeSetLineOffsetTransition"), - METHOD(&LineLayer::getLineOffset, "nativeGetLineOffset"), - METHOD(&LineLayer::getLineBlurTransition, "nativeGetLineBlurTransition"), - METHOD(&LineLayer::setLineBlurTransition, "nativeSetLineBlurTransition"), - METHOD(&LineLayer::getLineBlur, "nativeGetLineBlur"), - METHOD(&LineLayer::getLineDasharrayTransition, "nativeGetLineDasharrayTransition"), - METHOD(&LineLayer::setLineDasharrayTransition, "nativeSetLineDasharrayTransition"), - METHOD(&LineLayer::getLineDasharray, "nativeGetLineDasharray"), - METHOD(&LineLayer::getLinePatternTransition, "nativeGetLinePatternTransition"), - METHOD(&LineLayer::setLinePatternTransition, "nativeSetLinePatternTransition"), - METHOD(&LineLayer::getLinePattern, "nativeGetLinePattern"), - METHOD(&LineLayer::getLineGradient, "nativeGetLineGradient")); - } +inline mbgl::style::LineLayer& toLineLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +LineLayer::LineLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique( + jni::Make(env, layerId), jni::Make(env, sourceId) + )) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +LineLayer::LineLayer(mbgl::style::LineLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +LineLayer::LineLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +LineLayer::~LineLayer() = default; + +// Property getters + +jni::Local> LineLayer::getLineCap(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineCap())); +} + +jni::Local> LineLayer::getLineJoin(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineJoin())); +} + +jni::Local> LineLayer::getLineMiterLimit(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineMiterLimit())); +} + +jni::Local> LineLayer::getLineRoundLimit(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineRoundLimit())); +} + +jni::Local> LineLayer::getLineSortKey(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineSortKey())); +} + +jni::Local> LineLayer::getLineOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineOpacity())); +} + +jni::Local> LineLayer::getLineOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineOpacityTransition(options); +} + +jni::Local> LineLayer::getLineColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineColor())); +} + +jni::Local> LineLayer::getLineColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineColorTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineColorTransition(options); +} + +jni::Local> LineLayer::getLineTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineTranslate())); +} + +jni::Local> LineLayer::getLineTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineTranslateTransition(options); +} + +jni::Local> LineLayer::getLineTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineTranslateAnchor())); +} + +jni::Local> LineLayer::getLineWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineWidth())); +} + +jni::Local> LineLayer::getLineWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineWidthTransition(options); +} + +jni::Local> LineLayer::getLineGapWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineGapWidth())); +} + +jni::Local> LineLayer::getLineGapWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineGapWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineGapWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineGapWidthTransition(options); +} + +jni::Local> LineLayer::getLineOffset(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineOffset())); +} + +jni::Local> LineLayer::getLineOffsetTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineOffsetTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineOffsetTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineOffsetTransition(options); +} + +jni::Local> LineLayer::getLineBlur(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineBlur())); +} + +jni::Local> LineLayer::getLineBlurTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineBlurTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineBlurTransition(options); +} + +jni::Local> LineLayer::getLineDasharray(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineDasharray())); +} + +jni::Local> LineLayer::getLineDasharrayTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineDasharrayTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineDasharrayTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineDasharrayTransition(options); +} + +jni::Local> LineLayer::getLinePattern(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLinePattern())); +} + +jni::Local> LineLayer::getLinePatternTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLinePatternTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLinePatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLinePatternTransition(options); +} + +jni::Local> LineLayer::getLineGradient(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineGradient())); +} + +// LineJavaLayerPeerFactory + +LineJavaLayerPeerFactory::~LineJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> LineJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new LineLayer(toLineLayer(layer))); +} + +jni::Local> LineJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new LineLayer(std::unique_ptr(static_cast(layer.release()))) + ); +} + +void LineJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&LineLayer::getLineCap, "nativeGetLineCap"), + METHOD(&LineLayer::getLineJoin, "nativeGetLineJoin"), + METHOD(&LineLayer::getLineMiterLimit, "nativeGetLineMiterLimit"), + METHOD(&LineLayer::getLineRoundLimit, "nativeGetLineRoundLimit"), + METHOD(&LineLayer::getLineSortKey, "nativeGetLineSortKey"), + METHOD(&LineLayer::getLineOpacityTransition, "nativeGetLineOpacityTransition"), + METHOD(&LineLayer::setLineOpacityTransition, "nativeSetLineOpacityTransition"), + METHOD(&LineLayer::getLineOpacity, "nativeGetLineOpacity"), + METHOD(&LineLayer::getLineColorTransition, "nativeGetLineColorTransition"), + METHOD(&LineLayer::setLineColorTransition, "nativeSetLineColorTransition"), + METHOD(&LineLayer::getLineColor, "nativeGetLineColor"), + METHOD(&LineLayer::getLineTranslateTransition, "nativeGetLineTranslateTransition"), + METHOD(&LineLayer::setLineTranslateTransition, "nativeSetLineTranslateTransition"), + METHOD(&LineLayer::getLineTranslate, "nativeGetLineTranslate"), + METHOD(&LineLayer::getLineTranslateAnchor, "nativeGetLineTranslateAnchor"), + METHOD(&LineLayer::getLineWidthTransition, "nativeGetLineWidthTransition"), + METHOD(&LineLayer::setLineWidthTransition, "nativeSetLineWidthTransition"), + METHOD(&LineLayer::getLineWidth, "nativeGetLineWidth"), + METHOD(&LineLayer::getLineGapWidthTransition, "nativeGetLineGapWidthTransition"), + METHOD(&LineLayer::setLineGapWidthTransition, "nativeSetLineGapWidthTransition"), + METHOD(&LineLayer::getLineGapWidth, "nativeGetLineGapWidth"), + METHOD(&LineLayer::getLineOffsetTransition, "nativeGetLineOffsetTransition"), + METHOD(&LineLayer::setLineOffsetTransition, "nativeSetLineOffsetTransition"), + METHOD(&LineLayer::getLineOffset, "nativeGetLineOffset"), + METHOD(&LineLayer::getLineBlurTransition, "nativeGetLineBlurTransition"), + METHOD(&LineLayer::setLineBlurTransition, "nativeSetLineBlurTransition"), + METHOD(&LineLayer::getLineBlur, "nativeGetLineBlur"), + METHOD(&LineLayer::getLineDasharrayTransition, "nativeGetLineDasharrayTransition"), + METHOD(&LineLayer::setLineDasharrayTransition, "nativeSetLineDasharrayTransition"), + METHOD(&LineLayer::getLineDasharray, "nativeGetLineDasharray"), + METHOD(&LineLayer::getLinePatternTransition, "nativeGetLinePatternTransition"), + METHOD(&LineLayer::setLinePatternTransition, "nativeSetLinePatternTransition"), + METHOD(&LineLayer::getLinePattern, "nativeGetLinePattern"), + METHOD(&LineLayer::getLineGradient, "nativeGetLineGradient") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.hpp index 1a53b9e3288..2e878d689a2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.hpp @@ -78,7 +78,7 @@ class LineLayer : public Layer { }; // class LineLayer -class LineJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::LineLayerFactory { +class LineJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::LineLayerFactory { public: ~LineJavaLayerPeerFactory() override; @@ -90,7 +90,7 @@ class LineJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl LayerFactory* getLayerFactory() final { return this; } -}; // class LineJavaLayerPeerFactory +}; // class LineJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.cpp index 9e642979290..8b73d8f9c92 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.cpp @@ -12,256 +12,277 @@ namespace mbgl { namespace android { - inline mbgl::style::LocationIndicatorLayer& toLocationIndicatorLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - LocationIndicatorLayer::LocationIndicatorLayer(jni::JNIEnv& env, jni::String& layerId) - : Layer(std::make_unique(jni::Make(env, layerId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - LocationIndicatorLayer::LocationIndicatorLayer(mbgl::style::LocationIndicatorLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - LocationIndicatorLayer::LocationIndicatorLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - LocationIndicatorLayer::~LocationIndicatorLayer() = default; - - // Property getters - - jni::Local> LocationIndicatorLayer::getTopImage(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getTopImage())); - } - - jni::Local> LocationIndicatorLayer::getBearingImage(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearingImage())); - } - - jni::Local> LocationIndicatorLayer::getShadowImage(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getShadowImage())); - } - - jni::Local> LocationIndicatorLayer::getPerspectiveCompensation(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getPerspectiveCompensation())); - } - - jni::Local> LocationIndicatorLayer::getImageTiltDisplacement(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getImageTiltDisplacement())); - } - - jni::Local> LocationIndicatorLayer::getBearing(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearing())); - } - - jni::Local> LocationIndicatorLayer::getLocation(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getLocation())); - } - - jni::Local> LocationIndicatorLayer::getLocationTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getLocationTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setLocationTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setLocationTransition(options); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadius(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadius())); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setAccuracyRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setAccuracyRadiusTransition(options); - } - - jni::Local> LocationIndicatorLayer::getTopImageSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getTopImageSize())); - } - - jni::Local> LocationIndicatorLayer::getTopImageSizeTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getTopImageSizeTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setTopImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setTopImageSizeTransition(options); - } - - jni::Local> LocationIndicatorLayer::getBearingImageSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearingImageSize())); - } - - jni::Local> LocationIndicatorLayer::getBearingImageSizeTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getBearingImageSizeTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setBearingImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setBearingImageSizeTransition(options); - } - - jni::Local> LocationIndicatorLayer::getShadowImageSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getShadowImageSize())); - } - - jni::Local> LocationIndicatorLayer::getShadowImageSizeTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getShadowImageSizeTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setShadowImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setShadowImageSizeTransition(options); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadiusColor())); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusColorTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setAccuracyRadiusColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setAccuracyRadiusColorTransition(options); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusBorderColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadiusBorderColor())); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusBorderColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusBorderColorTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setAccuracyRadiusBorderColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setAccuracyRadiusBorderColorTransition(options); - } - - - // LocationIndicatorJavaLayerPeerFactory - - LocationIndicatorJavaLayerPeerFactory::~LocationIndicatorJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> LocationIndicatorJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new LocationIndicatorLayer(toLocationIndicatorLayer(layer))); - } - - jni::Local> LocationIndicatorJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new LocationIndicatorLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void LocationIndicatorJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&LocationIndicatorLayer::getTopImage, "nativeGetTopImage"), - METHOD(&LocationIndicatorLayer::getBearingImage, "nativeGetBearingImage"), - METHOD(&LocationIndicatorLayer::getShadowImage, "nativeGetShadowImage"), - METHOD(&LocationIndicatorLayer::getPerspectiveCompensation, "nativeGetPerspectiveCompensation"), - METHOD(&LocationIndicatorLayer::getImageTiltDisplacement, "nativeGetImageTiltDisplacement"), - METHOD(&LocationIndicatorLayer::getBearing, "nativeGetBearing"), - METHOD(&LocationIndicatorLayer::getLocationTransition, "nativeGetLocationTransition"), - METHOD(&LocationIndicatorLayer::setLocationTransition, "nativeSetLocationTransition"), - METHOD(&LocationIndicatorLayer::getLocation, "nativeGetLocation"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusTransition, "nativeGetAccuracyRadiusTransition"), - METHOD(&LocationIndicatorLayer::setAccuracyRadiusTransition, "nativeSetAccuracyRadiusTransition"), - METHOD(&LocationIndicatorLayer::getAccuracyRadius, "nativeGetAccuracyRadius"), - METHOD(&LocationIndicatorLayer::getTopImageSizeTransition, "nativeGetTopImageSizeTransition"), - METHOD(&LocationIndicatorLayer::setTopImageSizeTransition, "nativeSetTopImageSizeTransition"), - METHOD(&LocationIndicatorLayer::getTopImageSize, "nativeGetTopImageSize"), - METHOD(&LocationIndicatorLayer::getBearingImageSizeTransition, "nativeGetBearingImageSizeTransition"), - METHOD(&LocationIndicatorLayer::setBearingImageSizeTransition, "nativeSetBearingImageSizeTransition"), - METHOD(&LocationIndicatorLayer::getBearingImageSize, "nativeGetBearingImageSize"), - METHOD(&LocationIndicatorLayer::getShadowImageSizeTransition, "nativeGetShadowImageSizeTransition"), - METHOD(&LocationIndicatorLayer::setShadowImageSizeTransition, "nativeSetShadowImageSizeTransition"), - METHOD(&LocationIndicatorLayer::getShadowImageSize, "nativeGetShadowImageSize"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusColorTransition, "nativeGetAccuracyRadiusColorTransition"), - METHOD(&LocationIndicatorLayer::setAccuracyRadiusColorTransition, "nativeSetAccuracyRadiusColorTransition"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusColor, "nativeGetAccuracyRadiusColor"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusBorderColorTransition, "nativeGetAccuracyRadiusBorderColorTransition"), - METHOD(&LocationIndicatorLayer::setAccuracyRadiusBorderColorTransition, "nativeSetAccuracyRadiusBorderColorTransition"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusBorderColor, "nativeGetAccuracyRadiusBorderColor")); - } +inline mbgl::style::LocationIndicatorLayer& toLocationIndicatorLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +LocationIndicatorLayer::LocationIndicatorLayer(jni::JNIEnv& env, jni::String& layerId) + : Layer(std::make_unique(jni::Make(env, layerId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +LocationIndicatorLayer::LocationIndicatorLayer(mbgl::style::LocationIndicatorLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +LocationIndicatorLayer::LocationIndicatorLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +LocationIndicatorLayer::~LocationIndicatorLayer() = default; + +// Property getters + +jni::Local> LocationIndicatorLayer::getTopImage(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getTopImage())); +} + +jni::Local> LocationIndicatorLayer::getBearingImage(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearingImage())); +} + +jni::Local> LocationIndicatorLayer::getShadowImage(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getShadowImage())); +} + +jni::Local> LocationIndicatorLayer::getPerspectiveCompensation(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toLocationIndicatorLayer(layer).getPerspectiveCompensation()) + ); +} + +jni::Local> LocationIndicatorLayer::getImageTiltDisplacement(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toLocationIndicatorLayer(layer).getImageTiltDisplacement()) + ); +} + +jni::Local> LocationIndicatorLayer::getBearing(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearing())); +} + +jni::Local> LocationIndicatorLayer::getLocation(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getLocation())); +} + +jni::Local> LocationIndicatorLayer::getLocationTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getLocationTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setLocationTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setLocationTransition(options); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadius(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadius())); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setAccuracyRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setAccuracyRadiusTransition(options); +} + +jni::Local> LocationIndicatorLayer::getTopImageSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getTopImageSize())); +} + +jni::Local> LocationIndicatorLayer::getTopImageSizeTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getTopImageSizeTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setTopImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setTopImageSizeTransition(options); +} + +jni::Local> LocationIndicatorLayer::getBearingImageSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearingImageSize())); +} + +jni::Local> LocationIndicatorLayer::getBearingImageSizeTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getBearingImageSizeTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setBearingImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setBearingImageSizeTransition(options); +} + +jni::Local> LocationIndicatorLayer::getShadowImageSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getShadowImageSize())); +} + +jni::Local> LocationIndicatorLayer::getShadowImageSizeTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getShadowImageSizeTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setShadowImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setShadowImageSizeTransition(options); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadiusColor()) + ); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusColorTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setAccuracyRadiusColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setAccuracyRadiusColorTransition(options); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusBorderColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadiusBorderColor()) + ); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusBorderColorTransition( + jni::JNIEnv& env +) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusBorderColorTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setAccuracyRadiusBorderColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setAccuracyRadiusBorderColorTransition(options); +} + +// LocationIndicatorJavaLayerPeerFactory + +LocationIndicatorJavaLayerPeerFactory::~LocationIndicatorJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> LocationIndicatorJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new LocationIndicatorLayer(toLocationIndicatorLayer(layer))); +} + +jni::Local> LocationIndicatorJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new LocationIndicatorLayer(std::unique_ptr( + static_cast(layer.release()) + )) + ); +} + +void LocationIndicatorJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&LocationIndicatorLayer::getTopImage, "nativeGetTopImage"), + METHOD(&LocationIndicatorLayer::getBearingImage, "nativeGetBearingImage"), + METHOD(&LocationIndicatorLayer::getShadowImage, "nativeGetShadowImage"), + METHOD(&LocationIndicatorLayer::getPerspectiveCompensation, "nativeGetPerspectiveCompensation"), + METHOD(&LocationIndicatorLayer::getImageTiltDisplacement, "nativeGetImageTiltDisplacement"), + METHOD(&LocationIndicatorLayer::getBearing, "nativeGetBearing"), + METHOD(&LocationIndicatorLayer::getLocationTransition, "nativeGetLocationTransition"), + METHOD(&LocationIndicatorLayer::setLocationTransition, "nativeSetLocationTransition"), + METHOD(&LocationIndicatorLayer::getLocation, "nativeGetLocation"), + METHOD(&LocationIndicatorLayer::getAccuracyRadiusTransition, "nativeGetAccuracyRadiusTransition"), + METHOD(&LocationIndicatorLayer::setAccuracyRadiusTransition, "nativeSetAccuracyRadiusTransition"), + METHOD(&LocationIndicatorLayer::getAccuracyRadius, "nativeGetAccuracyRadius"), + METHOD(&LocationIndicatorLayer::getTopImageSizeTransition, "nativeGetTopImageSizeTransition"), + METHOD(&LocationIndicatorLayer::setTopImageSizeTransition, "nativeSetTopImageSizeTransition"), + METHOD(&LocationIndicatorLayer::getTopImageSize, "nativeGetTopImageSize"), + METHOD(&LocationIndicatorLayer::getBearingImageSizeTransition, "nativeGetBearingImageSizeTransition"), + METHOD(&LocationIndicatorLayer::setBearingImageSizeTransition, "nativeSetBearingImageSizeTransition"), + METHOD(&LocationIndicatorLayer::getBearingImageSize, "nativeGetBearingImageSize"), + METHOD(&LocationIndicatorLayer::getShadowImageSizeTransition, "nativeGetShadowImageSizeTransition"), + METHOD(&LocationIndicatorLayer::setShadowImageSizeTransition, "nativeSetShadowImageSizeTransition"), + METHOD(&LocationIndicatorLayer::getShadowImageSize, "nativeGetShadowImageSize"), + METHOD(&LocationIndicatorLayer::getAccuracyRadiusColorTransition, "nativeGetAccuracyRadiusColorTransition"), + METHOD(&LocationIndicatorLayer::setAccuracyRadiusColorTransition, "nativeSetAccuracyRadiusColorTransition"), + METHOD(&LocationIndicatorLayer::getAccuracyRadiusColor, "nativeGetAccuracyRadiusColor"), + METHOD( + &LocationIndicatorLayer::getAccuracyRadiusBorderColorTransition, + "nativeGetAccuracyRadiusBorderColorTransition" + ), + METHOD( + &LocationIndicatorLayer::setAccuracyRadiusBorderColorTransition, + "nativeSetAccuracyRadiusBorderColorTransition" + ), + METHOD(&LocationIndicatorLayer::getAccuracyRadiusBorderColor, "nativeGetAccuracyRadiusBorderColor") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.hpp index 81a20d79318..8da3e556519 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.hpp @@ -68,7 +68,8 @@ class LocationIndicatorLayer : public Layer { }; // class LocationIndicatorLayer -class LocationIndicatorJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::LocationIndicatorLayerFactory { +class LocationIndicatorJavaLayerPeerFactory final : public JavaLayerPeerFactory, + public mbgl::LocationIndicatorLayerFactory { public: ~LocationIndicatorJavaLayerPeerFactory() override; @@ -80,7 +81,7 @@ class LocationIndicatorJavaLayerPeerFactory final : public JavaLayerPeerFactory, LayerFactory* getLayerFactory() final { return this; } -}; // class LocationIndicatorJavaLayerPeerFactory +}; // class LocationIndicatorJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.cpp index 759161aeb1b..b5ba33e6805 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.cpp @@ -12,211 +12,218 @@ namespace mbgl { namespace android { - inline mbgl::style::RasterLayer& toRasterLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - RasterLayer::RasterLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - RasterLayer::RasterLayer(mbgl::style::RasterLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - RasterLayer::RasterLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - RasterLayer::~RasterLayer() = default; - - // Property getters - - jni::Local> RasterLayer::getRasterOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterOpacity())); - } - - jni::Local> RasterLayer::getRasterOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterOpacityTransition(options); - } - - jni::Local> RasterLayer::getRasterHueRotate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterHueRotate())); - } - - jni::Local> RasterLayer::getRasterHueRotateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterHueRotateTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterHueRotateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterHueRotateTransition(options); - } - - jni::Local> RasterLayer::getRasterBrightnessMin(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterBrightnessMin())); - } - - jni::Local> RasterLayer::getRasterBrightnessMinTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterBrightnessMinTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterBrightnessMinTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterBrightnessMinTransition(options); - } - - jni::Local> RasterLayer::getRasterBrightnessMax(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterBrightnessMax())); - } - - jni::Local> RasterLayer::getRasterBrightnessMaxTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterBrightnessMaxTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterBrightnessMaxTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterBrightnessMaxTransition(options); - } - - jni::Local> RasterLayer::getRasterSaturation(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterSaturation())); - } - - jni::Local> RasterLayer::getRasterSaturationTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterSaturationTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterSaturationTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterSaturationTransition(options); - } - - jni::Local> RasterLayer::getRasterContrast(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterContrast())); - } - - jni::Local> RasterLayer::getRasterContrastTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterContrastTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterContrastTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterContrastTransition(options); - } - - jni::Local> RasterLayer::getRasterResampling(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterResampling())); - } - - jni::Local> RasterLayer::getRasterFadeDuration(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterFadeDuration())); - } - - - // RasterJavaLayerPeerFactory - - RasterJavaLayerPeerFactory::~RasterJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> RasterJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new RasterLayer(toRasterLayer(layer))); - } - - jni::Local> RasterJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new RasterLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void RasterJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&RasterLayer::getRasterOpacityTransition, "nativeGetRasterOpacityTransition"), - METHOD(&RasterLayer::setRasterOpacityTransition, "nativeSetRasterOpacityTransition"), - METHOD(&RasterLayer::getRasterOpacity, "nativeGetRasterOpacity"), - METHOD(&RasterLayer::getRasterHueRotateTransition, "nativeGetRasterHueRotateTransition"), - METHOD(&RasterLayer::setRasterHueRotateTransition, "nativeSetRasterHueRotateTransition"), - METHOD(&RasterLayer::getRasterHueRotate, "nativeGetRasterHueRotate"), - METHOD(&RasterLayer::getRasterBrightnessMinTransition, "nativeGetRasterBrightnessMinTransition"), - METHOD(&RasterLayer::setRasterBrightnessMinTransition, "nativeSetRasterBrightnessMinTransition"), - METHOD(&RasterLayer::getRasterBrightnessMin, "nativeGetRasterBrightnessMin"), - METHOD(&RasterLayer::getRasterBrightnessMaxTransition, "nativeGetRasterBrightnessMaxTransition"), - METHOD(&RasterLayer::setRasterBrightnessMaxTransition, "nativeSetRasterBrightnessMaxTransition"), - METHOD(&RasterLayer::getRasterBrightnessMax, "nativeGetRasterBrightnessMax"), - METHOD(&RasterLayer::getRasterSaturationTransition, "nativeGetRasterSaturationTransition"), - METHOD(&RasterLayer::setRasterSaturationTransition, "nativeSetRasterSaturationTransition"), - METHOD(&RasterLayer::getRasterSaturation, "nativeGetRasterSaturation"), - METHOD(&RasterLayer::getRasterContrastTransition, "nativeGetRasterContrastTransition"), - METHOD(&RasterLayer::setRasterContrastTransition, "nativeSetRasterContrastTransition"), - METHOD(&RasterLayer::getRasterContrast, "nativeGetRasterContrast"), - METHOD(&RasterLayer::getRasterResampling, "nativeGetRasterResampling"), - METHOD(&RasterLayer::getRasterFadeDuration, "nativeGetRasterFadeDuration")); - } +inline mbgl::style::RasterLayer& toRasterLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +RasterLayer::RasterLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique( + jni::Make(env, layerId), jni::Make(env, sourceId) + )) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +RasterLayer::RasterLayer(mbgl::style::RasterLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +RasterLayer::RasterLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +RasterLayer::~RasterLayer() = default; + +// Property getters + +jni::Local> RasterLayer::getRasterOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterOpacity())); +} + +jni::Local> RasterLayer::getRasterOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterOpacityTransition(options); +} + +jni::Local> RasterLayer::getRasterHueRotate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterHueRotate())); +} + +jni::Local> RasterLayer::getRasterHueRotateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterHueRotateTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterHueRotateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterHueRotateTransition(options); +} + +jni::Local> RasterLayer::getRasterBrightnessMin(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterBrightnessMin())); +} + +jni::Local> RasterLayer::getRasterBrightnessMinTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterBrightnessMinTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterBrightnessMinTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterBrightnessMinTransition(options); +} + +jni::Local> RasterLayer::getRasterBrightnessMax(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterBrightnessMax())); +} + +jni::Local> RasterLayer::getRasterBrightnessMaxTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterBrightnessMaxTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterBrightnessMaxTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterBrightnessMaxTransition(options); +} + +jni::Local> RasterLayer::getRasterSaturation(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterSaturation())); +} + +jni::Local> RasterLayer::getRasterSaturationTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterSaturationTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterSaturationTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterSaturationTransition(options); +} + +jni::Local> RasterLayer::getRasterContrast(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterContrast())); +} + +jni::Local> RasterLayer::getRasterContrastTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterContrastTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterContrastTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterContrastTransition(options); +} + +jni::Local> RasterLayer::getRasterResampling(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterResampling())); +} + +jni::Local> RasterLayer::getRasterFadeDuration(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterFadeDuration())); +} + +// RasterJavaLayerPeerFactory + +RasterJavaLayerPeerFactory::~RasterJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> RasterJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new RasterLayer(toRasterLayer(layer))); +} + +jni::Local> RasterJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new RasterLayer(std::unique_ptr(static_cast(layer.release() + ))) + ); +} + +void RasterJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&RasterLayer::getRasterOpacityTransition, "nativeGetRasterOpacityTransition"), + METHOD(&RasterLayer::setRasterOpacityTransition, "nativeSetRasterOpacityTransition"), + METHOD(&RasterLayer::getRasterOpacity, "nativeGetRasterOpacity"), + METHOD(&RasterLayer::getRasterHueRotateTransition, "nativeGetRasterHueRotateTransition"), + METHOD(&RasterLayer::setRasterHueRotateTransition, "nativeSetRasterHueRotateTransition"), + METHOD(&RasterLayer::getRasterHueRotate, "nativeGetRasterHueRotate"), + METHOD(&RasterLayer::getRasterBrightnessMinTransition, "nativeGetRasterBrightnessMinTransition"), + METHOD(&RasterLayer::setRasterBrightnessMinTransition, "nativeSetRasterBrightnessMinTransition"), + METHOD(&RasterLayer::getRasterBrightnessMin, "nativeGetRasterBrightnessMin"), + METHOD(&RasterLayer::getRasterBrightnessMaxTransition, "nativeGetRasterBrightnessMaxTransition"), + METHOD(&RasterLayer::setRasterBrightnessMaxTransition, "nativeSetRasterBrightnessMaxTransition"), + METHOD(&RasterLayer::getRasterBrightnessMax, "nativeGetRasterBrightnessMax"), + METHOD(&RasterLayer::getRasterSaturationTransition, "nativeGetRasterSaturationTransition"), + METHOD(&RasterLayer::setRasterSaturationTransition, "nativeSetRasterSaturationTransition"), + METHOD(&RasterLayer::getRasterSaturation, "nativeGetRasterSaturation"), + METHOD(&RasterLayer::getRasterContrastTransition, "nativeGetRasterContrastTransition"), + METHOD(&RasterLayer::setRasterContrastTransition, "nativeSetRasterContrastTransition"), + METHOD(&RasterLayer::getRasterContrast, "nativeGetRasterContrast"), + METHOD(&RasterLayer::getRasterResampling, "nativeGetRasterResampling"), + METHOD(&RasterLayer::getRasterFadeDuration, "nativeGetRasterFadeDuration") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.hpp index 4c3d6b19c96..152f9aeffb3 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.hpp @@ -56,7 +56,7 @@ class RasterLayer : public Layer { }; // class RasterLayer -class RasterJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::RasterLayerFactory { +class RasterJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::RasterLayerFactory { public: ~RasterJavaLayerPeerFactory() override; @@ -68,7 +68,7 @@ class RasterJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mb LayerFactory* getLayerFactory() final { return this; } -}; // class RasterJavaLayerPeerFactory +}; // class RasterJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.cpp index 6abf5fd733f..89a2ef13094 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.cpp @@ -12,583 +12,590 @@ namespace mbgl { namespace android { - inline mbgl::style::SymbolLayer& toSymbolLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - SymbolLayer::SymbolLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - SymbolLayer::SymbolLayer(mbgl::style::SymbolLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - SymbolLayer::SymbolLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - SymbolLayer::~SymbolLayer() = default; - - // Property getters - - jni::Local> SymbolLayer::getSymbolPlacement(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolPlacement())); - } - - jni::Local> SymbolLayer::getSymbolSpacing(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolSpacing())); - } - - jni::Local> SymbolLayer::getSymbolAvoidEdges(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolAvoidEdges())); - } - - jni::Local> SymbolLayer::getSymbolSortKey(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolSortKey())); - } - - jni::Local> SymbolLayer::getSymbolZOrder(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolZOrder())); - } - - jni::Local> SymbolLayer::getIconAllowOverlap(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconAllowOverlap())); - } - - jni::Local> SymbolLayer::getIconIgnorePlacement(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconIgnorePlacement())); - } - - jni::Local> SymbolLayer::getIconOptional(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconOptional())); - } - - jni::Local> SymbolLayer::getIconRotationAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconRotationAlignment())); - } - - jni::Local> SymbolLayer::getIconSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconSize())); - } - - jni::Local> SymbolLayer::getIconTextFit(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconTextFit())); - } - - jni::Local> SymbolLayer::getIconTextFitPadding(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconTextFitPadding())); - } - - jni::Local> SymbolLayer::getIconImage(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconImage())); - } - - jni::Local> SymbolLayer::getIconRotate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconRotate())); - } - - jni::Local> SymbolLayer::getIconPadding(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconPadding())); - } - - jni::Local> SymbolLayer::getIconKeepUpright(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconKeepUpright())); - } - - jni::Local> SymbolLayer::getIconOffset(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconOffset())); - } - - jni::Local> SymbolLayer::getIconAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconAnchor())); - } - - jni::Local> SymbolLayer::getIconPitchAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconPitchAlignment())); - } - - jni::Local> SymbolLayer::getTextPitchAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextPitchAlignment())); - } - - jni::Local> SymbolLayer::getTextRotationAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextRotationAlignment())); - } - - jni::Local> SymbolLayer::getTextField(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextField())); - } - - jni::Local> SymbolLayer::getTextFont(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextFont())); - } - - jni::Local> SymbolLayer::getTextSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextSize())); - } - - jni::Local> SymbolLayer::getTextMaxWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextMaxWidth())); - } - - jni::Local> SymbolLayer::getTextLineHeight(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextLineHeight())); - } - - jni::Local> SymbolLayer::getTextLetterSpacing(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextLetterSpacing())); - } - - jni::Local> SymbolLayer::getTextJustify(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextJustify())); - } - - jni::Local> SymbolLayer::getTextRadialOffset(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextRadialOffset())); - } - - jni::Local> SymbolLayer::getTextVariableAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextVariableAnchor())); - } - - jni::Local> SymbolLayer::getTextAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextAnchor())); - } - - jni::Local> SymbolLayer::getTextMaxAngle(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextMaxAngle())); - } - - jni::Local> SymbolLayer::getTextWritingMode(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextWritingMode())); - } - - jni::Local> SymbolLayer::getTextRotate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextRotate())); - } - - jni::Local> SymbolLayer::getTextPadding(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextPadding())); - } - - jni::Local> SymbolLayer::getTextKeepUpright(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextKeepUpright())); - } - - jni::Local> SymbolLayer::getTextTransform(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextTransform())); - } - - jni::Local> SymbolLayer::getTextOffset(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextOffset())); - } - - jni::Local> SymbolLayer::getTextAllowOverlap(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextAllowOverlap())); - } - - jni::Local> SymbolLayer::getTextIgnorePlacement(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextIgnorePlacement())); - } - - jni::Local> SymbolLayer::getTextOptional(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextOptional())); - } - - jni::Local> SymbolLayer::getIconOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconOpacity())); - } - - jni::Local> SymbolLayer::getIconOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconOpacityTransition(options); - } - - jni::Local> SymbolLayer::getIconColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconColor())); - } - - jni::Local> SymbolLayer::getIconColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconColorTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconColorTransition(options); - } - - jni::Local> SymbolLayer::getIconHaloColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloColor())); - } - - jni::Local> SymbolLayer::getIconHaloColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloColorTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconHaloColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconHaloColorTransition(options); - } - - jni::Local> SymbolLayer::getIconHaloWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloWidth())); - } - - jni::Local> SymbolLayer::getIconHaloWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconHaloWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconHaloWidthTransition(options); - } - - jni::Local> SymbolLayer::getIconHaloBlur(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloBlur())); - } - - jni::Local> SymbolLayer::getIconHaloBlurTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloBlurTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconHaloBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconHaloBlurTransition(options); - } - - jni::Local> SymbolLayer::getIconTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconTranslate())); - } - - jni::Local> SymbolLayer::getIconTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconTranslateTransition(options); - } - - jni::Local> SymbolLayer::getIconTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconTranslateAnchor())); - } - - jni::Local> SymbolLayer::getTextOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextOpacity())); - } - - jni::Local> SymbolLayer::getTextOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextOpacityTransition(options); - } - - jni::Local> SymbolLayer::getTextColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextColor())); - } - - jni::Local> SymbolLayer::getTextColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextColorTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextColorTransition(options); - } - - jni::Local> SymbolLayer::getTextHaloColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloColor())); - } - - jni::Local> SymbolLayer::getTextHaloColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloColorTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextHaloColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextHaloColorTransition(options); - } - - jni::Local> SymbolLayer::getTextHaloWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloWidth())); - } - - jni::Local> SymbolLayer::getTextHaloWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextHaloWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextHaloWidthTransition(options); - } - - jni::Local> SymbolLayer::getTextHaloBlur(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloBlur())); - } - - jni::Local> SymbolLayer::getTextHaloBlurTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloBlurTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextHaloBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextHaloBlurTransition(options); - } - - jni::Local> SymbolLayer::getTextTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextTranslate())); - } - - jni::Local> SymbolLayer::getTextTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextTranslateTransition(options); - } - - jni::Local> SymbolLayer::getTextTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextTranslateAnchor())); - } - - - // SymbolJavaLayerPeerFactory - - SymbolJavaLayerPeerFactory::~SymbolJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> SymbolJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new SymbolLayer(toSymbolLayer(layer))); - } - - jni::Local> SymbolJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new SymbolLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void SymbolJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&SymbolLayer::getSymbolPlacement, "nativeGetSymbolPlacement"), - METHOD(&SymbolLayer::getSymbolSpacing, "nativeGetSymbolSpacing"), - METHOD(&SymbolLayer::getSymbolAvoidEdges, "nativeGetSymbolAvoidEdges"), - METHOD(&SymbolLayer::getSymbolSortKey, "nativeGetSymbolSortKey"), - METHOD(&SymbolLayer::getSymbolZOrder, "nativeGetSymbolZOrder"), - METHOD(&SymbolLayer::getIconAllowOverlap, "nativeGetIconAllowOverlap"), - METHOD(&SymbolLayer::getIconIgnorePlacement, "nativeGetIconIgnorePlacement"), - METHOD(&SymbolLayer::getIconOptional, "nativeGetIconOptional"), - METHOD(&SymbolLayer::getIconRotationAlignment, "nativeGetIconRotationAlignment"), - METHOD(&SymbolLayer::getIconSize, "nativeGetIconSize"), - METHOD(&SymbolLayer::getIconTextFit, "nativeGetIconTextFit"), - METHOD(&SymbolLayer::getIconTextFitPadding, "nativeGetIconTextFitPadding"), - METHOD(&SymbolLayer::getIconImage, "nativeGetIconImage"), - METHOD(&SymbolLayer::getIconRotate, "nativeGetIconRotate"), - METHOD(&SymbolLayer::getIconPadding, "nativeGetIconPadding"), - METHOD(&SymbolLayer::getIconKeepUpright, "nativeGetIconKeepUpright"), - METHOD(&SymbolLayer::getIconOffset, "nativeGetIconOffset"), - METHOD(&SymbolLayer::getIconAnchor, "nativeGetIconAnchor"), - METHOD(&SymbolLayer::getIconPitchAlignment, "nativeGetIconPitchAlignment"), - METHOD(&SymbolLayer::getTextPitchAlignment, "nativeGetTextPitchAlignment"), - METHOD(&SymbolLayer::getTextRotationAlignment, "nativeGetTextRotationAlignment"), - METHOD(&SymbolLayer::getTextField, "nativeGetTextField"), - METHOD(&SymbolLayer::getTextFont, "nativeGetTextFont"), - METHOD(&SymbolLayer::getTextSize, "nativeGetTextSize"), - METHOD(&SymbolLayer::getTextMaxWidth, "nativeGetTextMaxWidth"), - METHOD(&SymbolLayer::getTextLineHeight, "nativeGetTextLineHeight"), - METHOD(&SymbolLayer::getTextLetterSpacing, "nativeGetTextLetterSpacing"), - METHOD(&SymbolLayer::getTextJustify, "nativeGetTextJustify"), - METHOD(&SymbolLayer::getTextRadialOffset, "nativeGetTextRadialOffset"), - METHOD(&SymbolLayer::getTextVariableAnchor, "nativeGetTextVariableAnchor"), - METHOD(&SymbolLayer::getTextAnchor, "nativeGetTextAnchor"), - METHOD(&SymbolLayer::getTextMaxAngle, "nativeGetTextMaxAngle"), - METHOD(&SymbolLayer::getTextWritingMode, "nativeGetTextWritingMode"), - METHOD(&SymbolLayer::getTextRotate, "nativeGetTextRotate"), - METHOD(&SymbolLayer::getTextPadding, "nativeGetTextPadding"), - METHOD(&SymbolLayer::getTextKeepUpright, "nativeGetTextKeepUpright"), - METHOD(&SymbolLayer::getTextTransform, "nativeGetTextTransform"), - METHOD(&SymbolLayer::getTextOffset, "nativeGetTextOffset"), - METHOD(&SymbolLayer::getTextAllowOverlap, "nativeGetTextAllowOverlap"), - METHOD(&SymbolLayer::getTextIgnorePlacement, "nativeGetTextIgnorePlacement"), - METHOD(&SymbolLayer::getTextOptional, "nativeGetTextOptional"), - METHOD(&SymbolLayer::getIconOpacityTransition, "nativeGetIconOpacityTransition"), - METHOD(&SymbolLayer::setIconOpacityTransition, "nativeSetIconOpacityTransition"), - METHOD(&SymbolLayer::getIconOpacity, "nativeGetIconOpacity"), - METHOD(&SymbolLayer::getIconColorTransition, "nativeGetIconColorTransition"), - METHOD(&SymbolLayer::setIconColorTransition, "nativeSetIconColorTransition"), - METHOD(&SymbolLayer::getIconColor, "nativeGetIconColor"), - METHOD(&SymbolLayer::getIconHaloColorTransition, "nativeGetIconHaloColorTransition"), - METHOD(&SymbolLayer::setIconHaloColorTransition, "nativeSetIconHaloColorTransition"), - METHOD(&SymbolLayer::getIconHaloColor, "nativeGetIconHaloColor"), - METHOD(&SymbolLayer::getIconHaloWidthTransition, "nativeGetIconHaloWidthTransition"), - METHOD(&SymbolLayer::setIconHaloWidthTransition, "nativeSetIconHaloWidthTransition"), - METHOD(&SymbolLayer::getIconHaloWidth, "nativeGetIconHaloWidth"), - METHOD(&SymbolLayer::getIconHaloBlurTransition, "nativeGetIconHaloBlurTransition"), - METHOD(&SymbolLayer::setIconHaloBlurTransition, "nativeSetIconHaloBlurTransition"), - METHOD(&SymbolLayer::getIconHaloBlur, "nativeGetIconHaloBlur"), - METHOD(&SymbolLayer::getIconTranslateTransition, "nativeGetIconTranslateTransition"), - METHOD(&SymbolLayer::setIconTranslateTransition, "nativeSetIconTranslateTransition"), - METHOD(&SymbolLayer::getIconTranslate, "nativeGetIconTranslate"), - METHOD(&SymbolLayer::getIconTranslateAnchor, "nativeGetIconTranslateAnchor"), - METHOD(&SymbolLayer::getTextOpacityTransition, "nativeGetTextOpacityTransition"), - METHOD(&SymbolLayer::setTextOpacityTransition, "nativeSetTextOpacityTransition"), - METHOD(&SymbolLayer::getTextOpacity, "nativeGetTextOpacity"), - METHOD(&SymbolLayer::getTextColorTransition, "nativeGetTextColorTransition"), - METHOD(&SymbolLayer::setTextColorTransition, "nativeSetTextColorTransition"), - METHOD(&SymbolLayer::getTextColor, "nativeGetTextColor"), - METHOD(&SymbolLayer::getTextHaloColorTransition, "nativeGetTextHaloColorTransition"), - METHOD(&SymbolLayer::setTextHaloColorTransition, "nativeSetTextHaloColorTransition"), - METHOD(&SymbolLayer::getTextHaloColor, "nativeGetTextHaloColor"), - METHOD(&SymbolLayer::getTextHaloWidthTransition, "nativeGetTextHaloWidthTransition"), - METHOD(&SymbolLayer::setTextHaloWidthTransition, "nativeSetTextHaloWidthTransition"), - METHOD(&SymbolLayer::getTextHaloWidth, "nativeGetTextHaloWidth"), - METHOD(&SymbolLayer::getTextHaloBlurTransition, "nativeGetTextHaloBlurTransition"), - METHOD(&SymbolLayer::setTextHaloBlurTransition, "nativeSetTextHaloBlurTransition"), - METHOD(&SymbolLayer::getTextHaloBlur, "nativeGetTextHaloBlur"), - METHOD(&SymbolLayer::getTextTranslateTransition, "nativeGetTextTranslateTransition"), - METHOD(&SymbolLayer::setTextTranslateTransition, "nativeSetTextTranslateTransition"), - METHOD(&SymbolLayer::getTextTranslate, "nativeGetTextTranslate"), - METHOD(&SymbolLayer::getTextTranslateAnchor, "nativeGetTextTranslateAnchor")); - } +inline mbgl::style::SymbolLayer& toSymbolLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +SymbolLayer::SymbolLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique( + jni::Make(env, layerId), jni::Make(env, sourceId) + )) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +SymbolLayer::SymbolLayer(mbgl::style::SymbolLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +SymbolLayer::SymbolLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +SymbolLayer::~SymbolLayer() = default; + +// Property getters + +jni::Local> SymbolLayer::getSymbolPlacement(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolPlacement())); +} + +jni::Local> SymbolLayer::getSymbolSpacing(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolSpacing())); +} + +jni::Local> SymbolLayer::getSymbolAvoidEdges(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolAvoidEdges())); +} + +jni::Local> SymbolLayer::getSymbolSortKey(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolSortKey())); +} + +jni::Local> SymbolLayer::getSymbolZOrder(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolZOrder())); +} + +jni::Local> SymbolLayer::getIconAllowOverlap(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconAllowOverlap())); +} + +jni::Local> SymbolLayer::getIconIgnorePlacement(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconIgnorePlacement())); +} + +jni::Local> SymbolLayer::getIconOptional(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconOptional())); +} + +jni::Local> SymbolLayer::getIconRotationAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconRotationAlignment())); +} + +jni::Local> SymbolLayer::getIconSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconSize())); +} + +jni::Local> SymbolLayer::getIconTextFit(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconTextFit())); +} + +jni::Local> SymbolLayer::getIconTextFitPadding(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconTextFitPadding())); +} + +jni::Local> SymbolLayer::getIconImage(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconImage())); +} + +jni::Local> SymbolLayer::getIconRotate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconRotate())); +} + +jni::Local> SymbolLayer::getIconPadding(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconPadding())); +} + +jni::Local> SymbolLayer::getIconKeepUpright(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconKeepUpright())); +} + +jni::Local> SymbolLayer::getIconOffset(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconOffset())); +} + +jni::Local> SymbolLayer::getIconAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconAnchor())); +} + +jni::Local> SymbolLayer::getIconPitchAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconPitchAlignment())); +} + +jni::Local> SymbolLayer::getTextPitchAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextPitchAlignment())); +} + +jni::Local> SymbolLayer::getTextRotationAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextRotationAlignment())); +} + +jni::Local> SymbolLayer::getTextField(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextField())); +} + +jni::Local> SymbolLayer::getTextFont(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextFont())); +} + +jni::Local> SymbolLayer::getTextSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextSize())); +} + +jni::Local> SymbolLayer::getTextMaxWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextMaxWidth())); +} + +jni::Local> SymbolLayer::getTextLineHeight(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextLineHeight())); +} + +jni::Local> SymbolLayer::getTextLetterSpacing(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextLetterSpacing())); +} + +jni::Local> SymbolLayer::getTextJustify(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextJustify())); +} + +jni::Local> SymbolLayer::getTextRadialOffset(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextRadialOffset())); +} + +jni::Local> SymbolLayer::getTextVariableAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextVariableAnchor())); +} + +jni::Local> SymbolLayer::getTextAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextAnchor())); +} + +jni::Local> SymbolLayer::getTextMaxAngle(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextMaxAngle())); +} + +jni::Local> SymbolLayer::getTextWritingMode(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextWritingMode())); +} + +jni::Local> SymbolLayer::getTextRotate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextRotate())); +} + +jni::Local> SymbolLayer::getTextPadding(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextPadding())); +} + +jni::Local> SymbolLayer::getTextKeepUpright(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextKeepUpright())); +} + +jni::Local> SymbolLayer::getTextTransform(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextTransform())); +} + +jni::Local> SymbolLayer::getTextOffset(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextOffset())); +} + +jni::Local> SymbolLayer::getTextAllowOverlap(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextAllowOverlap())); +} + +jni::Local> SymbolLayer::getTextIgnorePlacement(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextIgnorePlacement())); +} + +jni::Local> SymbolLayer::getTextOptional(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextOptional())); +} + +jni::Local> SymbolLayer::getIconOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconOpacity())); +} + +jni::Local> SymbolLayer::getIconOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconOpacityTransition(options); +} + +jni::Local> SymbolLayer::getIconColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconColor())); +} + +jni::Local> SymbolLayer::getIconColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconColorTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconColorTransition(options); +} + +jni::Local> SymbolLayer::getIconHaloColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloColor())); +} + +jni::Local> SymbolLayer::getIconHaloColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloColorTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconHaloColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconHaloColorTransition(options); +} + +jni::Local> SymbolLayer::getIconHaloWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloWidth())); +} + +jni::Local> SymbolLayer::getIconHaloWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconHaloWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconHaloWidthTransition(options); +} + +jni::Local> SymbolLayer::getIconHaloBlur(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloBlur())); +} + +jni::Local> SymbolLayer::getIconHaloBlurTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloBlurTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconHaloBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconHaloBlurTransition(options); +} + +jni::Local> SymbolLayer::getIconTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconTranslate())); +} + +jni::Local> SymbolLayer::getIconTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconTranslateTransition(options); +} + +jni::Local> SymbolLayer::getIconTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconTranslateAnchor())); +} + +jni::Local> SymbolLayer::getTextOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextOpacity())); +} + +jni::Local> SymbolLayer::getTextOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextOpacityTransition(options); +} + +jni::Local> SymbolLayer::getTextColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextColor())); +} + +jni::Local> SymbolLayer::getTextColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextColorTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextColorTransition(options); +} + +jni::Local> SymbolLayer::getTextHaloColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloColor())); +} + +jni::Local> SymbolLayer::getTextHaloColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloColorTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextHaloColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextHaloColorTransition(options); +} + +jni::Local> SymbolLayer::getTextHaloWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloWidth())); +} + +jni::Local> SymbolLayer::getTextHaloWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextHaloWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextHaloWidthTransition(options); +} + +jni::Local> SymbolLayer::getTextHaloBlur(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloBlur())); +} + +jni::Local> SymbolLayer::getTextHaloBlurTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloBlurTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextHaloBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextHaloBlurTransition(options); +} + +jni::Local> SymbolLayer::getTextTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextTranslate())); +} + +jni::Local> SymbolLayer::getTextTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextTranslateTransition(options); +} + +jni::Local> SymbolLayer::getTextTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextTranslateAnchor())); +} + +// SymbolJavaLayerPeerFactory + +SymbolJavaLayerPeerFactory::~SymbolJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> SymbolJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, mbgl::style::Layer& layer +) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new SymbolLayer(toSymbolLayer(layer))); +} + +jni::Local> SymbolJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer +) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new SymbolLayer(std::unique_ptr(static_cast(layer.release() + ))) + ); +} + +void SymbolJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&SymbolLayer::getSymbolPlacement, "nativeGetSymbolPlacement"), + METHOD(&SymbolLayer::getSymbolSpacing, "nativeGetSymbolSpacing"), + METHOD(&SymbolLayer::getSymbolAvoidEdges, "nativeGetSymbolAvoidEdges"), + METHOD(&SymbolLayer::getSymbolSortKey, "nativeGetSymbolSortKey"), + METHOD(&SymbolLayer::getSymbolZOrder, "nativeGetSymbolZOrder"), + METHOD(&SymbolLayer::getIconAllowOverlap, "nativeGetIconAllowOverlap"), + METHOD(&SymbolLayer::getIconIgnorePlacement, "nativeGetIconIgnorePlacement"), + METHOD(&SymbolLayer::getIconOptional, "nativeGetIconOptional"), + METHOD(&SymbolLayer::getIconRotationAlignment, "nativeGetIconRotationAlignment"), + METHOD(&SymbolLayer::getIconSize, "nativeGetIconSize"), + METHOD(&SymbolLayer::getIconTextFit, "nativeGetIconTextFit"), + METHOD(&SymbolLayer::getIconTextFitPadding, "nativeGetIconTextFitPadding"), + METHOD(&SymbolLayer::getIconImage, "nativeGetIconImage"), + METHOD(&SymbolLayer::getIconRotate, "nativeGetIconRotate"), + METHOD(&SymbolLayer::getIconPadding, "nativeGetIconPadding"), + METHOD(&SymbolLayer::getIconKeepUpright, "nativeGetIconKeepUpright"), + METHOD(&SymbolLayer::getIconOffset, "nativeGetIconOffset"), + METHOD(&SymbolLayer::getIconAnchor, "nativeGetIconAnchor"), + METHOD(&SymbolLayer::getIconPitchAlignment, "nativeGetIconPitchAlignment"), + METHOD(&SymbolLayer::getTextPitchAlignment, "nativeGetTextPitchAlignment"), + METHOD(&SymbolLayer::getTextRotationAlignment, "nativeGetTextRotationAlignment"), + METHOD(&SymbolLayer::getTextField, "nativeGetTextField"), + METHOD(&SymbolLayer::getTextFont, "nativeGetTextFont"), + METHOD(&SymbolLayer::getTextSize, "nativeGetTextSize"), + METHOD(&SymbolLayer::getTextMaxWidth, "nativeGetTextMaxWidth"), + METHOD(&SymbolLayer::getTextLineHeight, "nativeGetTextLineHeight"), + METHOD(&SymbolLayer::getTextLetterSpacing, "nativeGetTextLetterSpacing"), + METHOD(&SymbolLayer::getTextJustify, "nativeGetTextJustify"), + METHOD(&SymbolLayer::getTextRadialOffset, "nativeGetTextRadialOffset"), + METHOD(&SymbolLayer::getTextVariableAnchor, "nativeGetTextVariableAnchor"), + METHOD(&SymbolLayer::getTextAnchor, "nativeGetTextAnchor"), + METHOD(&SymbolLayer::getTextMaxAngle, "nativeGetTextMaxAngle"), + METHOD(&SymbolLayer::getTextWritingMode, "nativeGetTextWritingMode"), + METHOD(&SymbolLayer::getTextRotate, "nativeGetTextRotate"), + METHOD(&SymbolLayer::getTextPadding, "nativeGetTextPadding"), + METHOD(&SymbolLayer::getTextKeepUpright, "nativeGetTextKeepUpright"), + METHOD(&SymbolLayer::getTextTransform, "nativeGetTextTransform"), + METHOD(&SymbolLayer::getTextOffset, "nativeGetTextOffset"), + METHOD(&SymbolLayer::getTextAllowOverlap, "nativeGetTextAllowOverlap"), + METHOD(&SymbolLayer::getTextIgnorePlacement, "nativeGetTextIgnorePlacement"), + METHOD(&SymbolLayer::getTextOptional, "nativeGetTextOptional"), + METHOD(&SymbolLayer::getIconOpacityTransition, "nativeGetIconOpacityTransition"), + METHOD(&SymbolLayer::setIconOpacityTransition, "nativeSetIconOpacityTransition"), + METHOD(&SymbolLayer::getIconOpacity, "nativeGetIconOpacity"), + METHOD(&SymbolLayer::getIconColorTransition, "nativeGetIconColorTransition"), + METHOD(&SymbolLayer::setIconColorTransition, "nativeSetIconColorTransition"), + METHOD(&SymbolLayer::getIconColor, "nativeGetIconColor"), + METHOD(&SymbolLayer::getIconHaloColorTransition, "nativeGetIconHaloColorTransition"), + METHOD(&SymbolLayer::setIconHaloColorTransition, "nativeSetIconHaloColorTransition"), + METHOD(&SymbolLayer::getIconHaloColor, "nativeGetIconHaloColor"), + METHOD(&SymbolLayer::getIconHaloWidthTransition, "nativeGetIconHaloWidthTransition"), + METHOD(&SymbolLayer::setIconHaloWidthTransition, "nativeSetIconHaloWidthTransition"), + METHOD(&SymbolLayer::getIconHaloWidth, "nativeGetIconHaloWidth"), + METHOD(&SymbolLayer::getIconHaloBlurTransition, "nativeGetIconHaloBlurTransition"), + METHOD(&SymbolLayer::setIconHaloBlurTransition, "nativeSetIconHaloBlurTransition"), + METHOD(&SymbolLayer::getIconHaloBlur, "nativeGetIconHaloBlur"), + METHOD(&SymbolLayer::getIconTranslateTransition, "nativeGetIconTranslateTransition"), + METHOD(&SymbolLayer::setIconTranslateTransition, "nativeSetIconTranslateTransition"), + METHOD(&SymbolLayer::getIconTranslate, "nativeGetIconTranslate"), + METHOD(&SymbolLayer::getIconTranslateAnchor, "nativeGetIconTranslateAnchor"), + METHOD(&SymbolLayer::getTextOpacityTransition, "nativeGetTextOpacityTransition"), + METHOD(&SymbolLayer::setTextOpacityTransition, "nativeSetTextOpacityTransition"), + METHOD(&SymbolLayer::getTextOpacity, "nativeGetTextOpacity"), + METHOD(&SymbolLayer::getTextColorTransition, "nativeGetTextColorTransition"), + METHOD(&SymbolLayer::setTextColorTransition, "nativeSetTextColorTransition"), + METHOD(&SymbolLayer::getTextColor, "nativeGetTextColor"), + METHOD(&SymbolLayer::getTextHaloColorTransition, "nativeGetTextHaloColorTransition"), + METHOD(&SymbolLayer::setTextHaloColorTransition, "nativeSetTextHaloColorTransition"), + METHOD(&SymbolLayer::getTextHaloColor, "nativeGetTextHaloColor"), + METHOD(&SymbolLayer::getTextHaloWidthTransition, "nativeGetTextHaloWidthTransition"), + METHOD(&SymbolLayer::setTextHaloWidthTransition, "nativeSetTextHaloWidthTransition"), + METHOD(&SymbolLayer::getTextHaloWidth, "nativeGetTextHaloWidth"), + METHOD(&SymbolLayer::getTextHaloBlurTransition, "nativeGetTextHaloBlurTransition"), + METHOD(&SymbolLayer::setTextHaloBlurTransition, "nativeSetTextHaloBlurTransition"), + METHOD(&SymbolLayer::getTextHaloBlur, "nativeGetTextHaloBlur"), + METHOD(&SymbolLayer::getTextTranslateTransition, "nativeGetTextTranslateTransition"), + METHOD(&SymbolLayer::setTextTranslateTransition, "nativeSetTextTranslateTransition"), + METHOD(&SymbolLayer::getTextTranslate, "nativeGetTextTranslate"), + METHOD(&SymbolLayer::getTextTranslateAnchor, "nativeGetTextTranslateAnchor") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.hpp index f51cdb4e323..382c3865387 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.hpp @@ -162,7 +162,7 @@ class SymbolLayer : public Layer { }; // class SymbolLayer -class SymbolJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::SymbolLayerFactory { +class SymbolJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::SymbolLayerFactory { public: ~SymbolJavaLayerPeerFactory() override; @@ -174,7 +174,7 @@ class SymbolJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mb LayerFactory* getLayerFactory() final { return this; } -}; // class SymbolJavaLayerPeerFactory +}; // class SymbolJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.cpp index d8ed4d9d963..a2960006463 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.cpp @@ -7,8 +7,8 @@ namespace mbgl { namespace android { Light::Light(mbgl::Map& coreMap, mbgl::style::Light& coreLight) - : light(coreLight) , map(&coreMap) { -} + : light(coreLight), + map(&coreMap) {} static Light* initializeLightPeer(mbgl::Map& map, mbgl::style::Light& coreLight) { return new Light(map, coreLight); @@ -58,16 +58,16 @@ jni::Local> Light::getPosition(jni::JNIEnv& env) { } jni::Local> Light::getPositionTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = light.getPositionTransition(); - return std::move(*convert>>(env, options)); + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = light.getPositionTransition(); + return std::move(*convert>>(env, options)); } void Light::setPositionTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - light.setPositionTransition(options); + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + light.setPositionTransition(options); } void Light::setColor(jni::JNIEnv& env, const jni::String& property) { @@ -77,22 +77,22 @@ void Light::setColor(jni::JNIEnv& env, const jni::String& property) { } } -jni::Local Light::getColor(jni::JNIEnv &env) { +jni::Local Light::getColor(jni::JNIEnv& env) { auto color = light.getColor().asConstant(); return jni::Make(env, color.stringify()); } jni::Local> Light::getColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = light.getColorTransition(); - return std::move(*convert>>(env, options)); + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = light.getColorTransition(); + return std::move(*convert>>(env, options)); } void Light::setColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - light.setColorTransition(options); + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + light.setColorTransition(options); } void Light::setIntensity(jni::JNIEnv&, jni::jfloat property) { @@ -104,16 +104,16 @@ jni::jfloat Light::getIntensity(jni::JNIEnv&) { } jni::Local> Light::getIntensityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = light.getIntensityTransition(); - return std::move(*convert>>(env, options)); + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = light.getIntensityTransition(); + return std::move(*convert>>(env, options)); } void Light::setIntensityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - light.setIntensityTransition(options); + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + light.setIntensityTransition(options); } void Light::registerNative(jni::JNIEnv& env) { @@ -122,22 +122,26 @@ void Light::registerNative(jni::JNIEnv& env) { #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer - jni::RegisterNativePeer(env, javaClass, "nativePtr", - METHOD(&Light::getAnchor, "nativeGetAnchor"), - METHOD(&Light::setAnchor, "nativeSetAnchor"), - METHOD(&Light::getPositionTransition, "nativeGetPositionTransition"), - METHOD(&Light::setPositionTransition, "nativeSetPositionTransition"), - METHOD(&Light::getPosition, "nativeGetPosition"), - METHOD(&Light::setPosition, "nativeSetPosition"), - METHOD(&Light::getColorTransition, "nativeGetColorTransition"), - METHOD(&Light::setColorTransition, "nativeSetColorTransition"), - METHOD(&Light::getColor, "nativeGetColor"), - METHOD(&Light::setColor, "nativeSetColor"), - METHOD(&Light::getIntensityTransition, "nativeGetIntensityTransition"), - METHOD(&Light::setIntensityTransition, "nativeSetIntensityTransition"), - METHOD(&Light::getIntensity, "nativeGetIntensity"), - METHOD(&Light::setIntensity, "nativeSetIntensity")); + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + METHOD(&Light::getAnchor, "nativeGetAnchor"), + METHOD(&Light::setAnchor, "nativeSetAnchor"), + METHOD(&Light::getPositionTransition, "nativeGetPositionTransition"), + METHOD(&Light::setPositionTransition, "nativeSetPositionTransition"), + METHOD(&Light::getPosition, "nativeGetPosition"), + METHOD(&Light::setPosition, "nativeSetPosition"), + METHOD(&Light::getColorTransition, "nativeGetColorTransition"), + METHOD(&Light::setColorTransition, "nativeSetColorTransition"), + METHOD(&Light::getColor, "nativeGetColor"), + METHOD(&Light::setColor, "nativeSetColor"), + METHOD(&Light::getIntensityTransition, "nativeGetIntensityTransition"), + METHOD(&Light::setIntensityTransition, "nativeSetIntensityTransition"), + METHOD(&Light::getIntensity, "nativeGetIntensity"), + METHOD(&Light::setIntensity, "nativeSetIntensity") + ); } } // namespace android -} // namespace mb +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.hpp index 97767c4f761..d21849a3686 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.hpp @@ -16,7 +16,6 @@ using namespace style; class Light : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/light/Light"; }; static void registerNative(jni::JNIEnv&); @@ -42,7 +41,6 @@ class Light : private mbgl::util::noncopyable { jni::Local> createJavaPeer(jni::JNIEnv&); protected: - // Raw reference to the light mbgl::style::Light& light; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/position.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/position.cpp index 326310be075..5a4849cef1b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/position.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/position.cpp @@ -3,9 +3,11 @@ namespace mbgl { namespace android { -jni::Local> Position::fromPosition(jni::JNIEnv& env, jfloat radialCoordinate, jfloat azimuthalAngle, jfloat polarAngle) { +jni::Local> Position::fromPosition( + jni::JNIEnv& env, jfloat radialCoordinate, jfloat azimuthalAngle, jfloat polarAngle +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jfloat, jfloat, jfloat)>(env, "fromPosition"); + static auto method = javaClass.GetStaticMethod(jfloat, jfloat, jfloat)>(env, "fromPosition"); return javaClass.Call(env, method, radialCoordinate, azimuthalAngle, polarAngle); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.cpp index 679201deddf..82ee541cb85 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.cpp @@ -18,192 +18,200 @@ namespace mbgl { namespace android { - // This conversion is expected not to fail because it's used only in contexts where - // the value was originally a CustomGeometrySourceOptions object on the Java side. If it fails - // to convert, it's a bug in our serialization or Java-side static typing. - static style::CustomGeometrySource::Options convertCustomGeometrySourceOptions(jni::JNIEnv& env, - const jni::Object<>& options, - style::TileFunction fetchFn, - style::TileFunction cancelFn) { - using namespace mbgl::style::conversion; - if (!options) { - return style::CustomGeometrySource::Options(); - } - Error error; - std::optional result = convert(Value(env, options), error); - if (!result) { - throw std::logic_error(error.message); - } - result->fetchTileFunction = fetchFn; - result->cancelTileFunction = cancelFn; - return *result; +// This conversion is expected not to fail because it's used only in contexts where +// the value was originally a CustomGeometrySourceOptions object on the Java side. If it fails +// to convert, it's a bug in our serialization or Java-side static typing. +static style::CustomGeometrySource::Options convertCustomGeometrySourceOptions( + jni::JNIEnv& env, const jni::Object<>& options, style::TileFunction fetchFn, style::TileFunction cancelFn +) { + using namespace mbgl::style::conversion; + if (!options) { + return style::CustomGeometrySource::Options(); } - - CustomGeometrySource::CustomGeometrySource(jni::JNIEnv& env, - const jni::String& sourceId, - const jni::Object<>& options) - : Source(env, std::make_unique( - jni::Make(env, sourceId), - convertCustomGeometrySourceOptions(env, options, - std::bind(&CustomGeometrySource::fetchTile, this, std::placeholders::_1), - std::bind(&CustomGeometrySource::cancelTile, this, std::placeholders::_1)))) { + Error error; + std::optional result = convert( + Value(env, options), error + ); + if (!result) { + throw std::logic_error(error.message); } - - CustomGeometrySource::CustomGeometrySource(jni::JNIEnv& env, - mbgl::style::Source& coreSource, - AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - CustomGeometrySource::~CustomGeometrySource() { - releaseThreads(); + result->fetchTileFunction = fetchFn; + result->cancelTileFunction = cancelFn; + return *result; +} + +CustomGeometrySource::CustomGeometrySource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& options) + : Source( + env, + std::make_unique( + jni::Make(env, sourceId), + convertCustomGeometrySourceOptions( + env, + options, + std::bind(&CustomGeometrySource::fetchTile, this, std::placeholders::_1), + std::bind(&CustomGeometrySource::cancelTile, this, std::placeholders::_1) + ) + ) + ) {} + +CustomGeometrySource::CustomGeometrySource( + jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend +) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +CustomGeometrySource::~CustomGeometrySource() { + releaseThreads(); +} + +void CustomGeometrySource::fetchTile(const mbgl::CanonicalTileID& tileID) { + android::UniqueEnv _env = android::AttachEnv(); + + static auto& javaClass = jni::Class::Singleton(*_env); + static auto fetchTile = javaClass.GetMethod(*_env, "fetchTile"); + + // The source is removed on the main thread, but it still exists on the Render thread until the frame is complete. + // This might cause fetchTile/cancelTile invocations when the Java thread is shutting down and the peer has already + // been released. See https://github.com/mapbox/mapbox-gl-native/issues/12551. + if (!javaPeer) { + return; } - void CustomGeometrySource::fetchTile (const mbgl::CanonicalTileID& tileID) { - android::UniqueEnv _env = android::AttachEnv(); + auto peer = jni::Cast(*_env, javaClass, javaPeer); + peer.Call(*_env, fetchTile, (int)tileID.z, (int)tileID.x, (int)tileID.y); +}; - static auto& javaClass = jni::Class::Singleton(*_env); - static auto fetchTile = javaClass.GetMethod(*_env, "fetchTile"); +void CustomGeometrySource::cancelTile(const mbgl::CanonicalTileID& tileID) { + android::UniqueEnv _env = android::AttachEnv(); - // The source is removed on the main thread, but it still exists on the Render thread until the frame is complete. - // This might cause fetchTile/cancelTile invocations when the Java thread is shutting down and the peer has already been released. - // See https://github.com/mapbox/mapbox-gl-native/issues/12551. - if(!javaPeer) { - return; - } + static auto& javaClass = jni::Class::Singleton(*_env); + static auto cancelTile = javaClass.GetMethod(*_env, "cancelTile"); - auto peer = jni::Cast(*_env, javaClass, javaPeer); - peer.Call(*_env, fetchTile, (int)tileID.z, (int)tileID.x, (int)tileID.y); - }; + // The source is removed on the main thread, but it still exists on the Render thread until the frame is complete. + // This might cause fetchTile/cancelTile invocations when the Java thread is shutting down and the peer has already + // been released. See https://github.com/mapbox/mapbox-gl-native/issues/12551. + if (!javaPeer) { + return; + } - void CustomGeometrySource::cancelTile(const mbgl::CanonicalTileID& tileID) { - android::UniqueEnv _env = android::AttachEnv(); + auto peer = jni::Cast(*_env, javaClass, javaPeer); + peer.Call(*_env, cancelTile, (int)tileID.z, (int)tileID.x, (int)tileID.y); +}; - static auto& javaClass = jni::Class::Singleton(*_env); - static auto cancelTile = javaClass.GetMethod(*_env, "cancelTile"); +void CustomGeometrySource::startThreads() { + android::UniqueEnv _env = android::AttachEnv(); - // The source is removed on the main thread, but it still exists on the Render thread until the frame is complete. - // This might cause fetchTile/cancelTile invocations when the Java thread is shutting down and the peer has already been released. - // See https://github.com/mapbox/mapbox-gl-native/issues/12551. - if(!javaPeer) { - return; - } + static auto& javaClass = jni::Class::Singleton(*_env); + static auto startThreads = javaClass.GetMethod(*_env, "startThreads"); - auto peer = jni::Cast(*_env, javaClass, javaPeer); - peer.Call(*_env, cancelTile, (int)tileID.z, (int)tileID.x, (int)tileID.y); - }; + assert(javaPeer); - void CustomGeometrySource::startThreads() { - android::UniqueEnv _env = android::AttachEnv(); + auto peer = jni::Cast(*_env, javaClass, javaPeer); + peer.Call(*_env, startThreads); +} - static auto& javaClass = jni::Class::Singleton(*_env); - static auto startThreads = javaClass.GetMethod(*_env, "startThreads"); +void CustomGeometrySource::releaseThreads() { + android::UniqueEnv _env = android::AttachEnv(); - assert(javaPeer); + static auto& javaClass = jni::Class::Singleton(*_env); + static auto releaseThreads = javaClass.GetMethod(*_env, "releaseThreads"); + if (javaPeer) { auto peer = jni::Cast(*_env, javaClass, javaPeer); - peer.Call(*_env, startThreads); + peer.Call(*_env, releaseThreads); } +}; - void CustomGeometrySource::releaseThreads() { - android::UniqueEnv _env = android::AttachEnv(); - - static auto& javaClass = jni::Class::Singleton(*_env); - static auto releaseThreads = javaClass.GetMethod(*_env, "releaseThreads"); - - if(javaPeer) { - auto peer = jni::Cast(*_env, javaClass, javaPeer); - peer.Call(*_env, releaseThreads); - } - }; - - bool CustomGeometrySource::isCancelled(jni::jint z, - jni::jint x, - jni::jint y) { - android::UniqueEnv _env = android::AttachEnv(); - - static auto& javaClass = jni::Class::Singleton(*_env); - static auto isCancelled = javaClass.GetMethod(*_env, "isCancelled"); - - assert(javaPeer); +bool CustomGeometrySource::isCancelled(jni::jint z, jni::jint x, jni::jint y) { + android::UniqueEnv _env = android::AttachEnv(); - auto peer = jni::Cast(*_env, javaClass, javaPeer); - return peer.Call(*_env, isCancelled, z, x, y); - }; - - void CustomGeometrySource::setTileData(jni::JNIEnv& env, - jni::jint z, - jni::jint x, - jni::jint y, - const jni::Object& jFeatures) { - using namespace mbgl::android::geojson; - - // Convert the jni object - auto geometry = geojson::FeatureCollection::convert(env, jFeatures); - - // Update the core source if not cancelled - if (!isCancelled(z, x ,y)) { - source.as()->CustomGeometrySource::setTileData(CanonicalTileID(z, x, y), GeoJSON(geometry)); - } - } - - void CustomGeometrySource::invalidateTile(jni::JNIEnv&, jni::jint z, jni::jint x, jni::jint y) { - source.as()->CustomGeometrySource::invalidateTile(CanonicalTileID(z, x, y)); - } + static auto& javaClass = jni::Class::Singleton(*_env); + static auto isCancelled = javaClass.GetMethod(*_env, "isCancelled"); - void CustomGeometrySource::invalidateBounds(jni::JNIEnv& env, const jni::Object& jBounds) { - auto bounds = LatLngBounds::getLatLngBounds(env, jBounds); - source.as()->CustomGeometrySource::invalidateRegion(bounds); - } + assert(javaPeer); - jni::Local>> CustomGeometrySource::querySourceFeatures(jni::JNIEnv& env, - const jni::Array>& jfilter) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; + auto peer = jni::Cast(*_env, javaClass, javaPeer); + return peer.Call(*_env, isCancelled, z, x, y); +}; - std::vector features; - if (rendererFrontend) { - features = rendererFrontend->querySourceFeatures(source.getID(), { {}, toFilter(env, jfilter) }); - } - return Feature::convert(env, features); - } +void CustomGeometrySource::setTileData( + jni::JNIEnv& env, jni::jint z, jni::jint x, jni::jint y, const jni::Object& jFeatures +) { + using namespace mbgl::android::geojson; - jni::Local> CustomGeometrySource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } + // Convert the jni object + auto geometry = geojson::FeatureCollection::convert(env, jFeatures); - void CustomGeometrySource::addToMap(JNIEnv& env, const jni::Object& obj, mbgl::Map& map, AndroidRendererFrontend& frontend) { - Source::addToMap(env, obj, map, frontend); - startThreads(); + // Update the core source if not cancelled + if (!isCancelled(z, x, y)) { + source.as()->CustomGeometrySource::setTileData( + CanonicalTileID(z, x, y), GeoJSON(geometry) + ); } - - bool CustomGeometrySource::removeFromMap(JNIEnv& env, const jni::Object& source, mbgl::Map& map) { - bool successfullyRemoved = Source::removeFromMap(env, source, map); - if (successfullyRemoved) { - releaseThreads(); - } - return successfullyRemoved; +} + +void CustomGeometrySource::invalidateTile(jni::JNIEnv&, jni::jint z, jni::jint x, jni::jint y) { + source.as()->CustomGeometrySource::invalidateTile(CanonicalTileID(z, x, y)); +} + +void CustomGeometrySource::invalidateBounds(jni::JNIEnv& env, const jni::Object& jBounds) { + auto bounds = LatLngBounds::getLatLngBounds(env, jBounds); + source.as()->CustomGeometrySource::invalidateRegion(bounds); +} + +jni::Local>> CustomGeometrySource::querySourceFeatures( + jni::JNIEnv& env, const jni::Array>& jfilter +) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; + + std::vector features; + if (rendererFrontend) { + features = rendererFrontend->querySourceFeatures(source.getID(), {{}, toFilter(env, jfilter)}); } - - void CustomGeometrySource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&CustomGeometrySource::querySourceFeatures, "querySourceFeatures"), - METHOD(&CustomGeometrySource::setTileData, "nativeSetTileData"), - METHOD(&CustomGeometrySource::invalidateTile, "nativeInvalidateTile"), - METHOD(&CustomGeometrySource::invalidateBounds, "nativeInvalidateBounds") - ); + return Feature::convert(env, features); +} + +jni::Local> CustomGeometrySource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void CustomGeometrySource::addToMap( + JNIEnv& env, const jni::Object& obj, mbgl::Map& map, AndroidRendererFrontend& frontend +) { + Source::addToMap(env, obj, map, frontend); + startThreads(); +} + +bool CustomGeometrySource::removeFromMap(JNIEnv& env, const jni::Object& source, mbgl::Map& map) { + bool successfullyRemoved = Source::removeFromMap(env, source, map); + if (successfullyRemoved) { + releaseThreads(); } + return successfullyRemoved; +} + +void CustomGeometrySource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&CustomGeometrySource::querySourceFeatures, "querySourceFeatures"), + METHOD(&CustomGeometrySource::setTileData, "nativeSetTileData"), + METHOD(&CustomGeometrySource::invalidateTile, "nativeInvalidateTile"), + METHOD(&CustomGeometrySource::invalidateBounds, "nativeInvalidateBounds") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.hpp index 6979ecc25d4..ec0da78d632 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.hpp @@ -34,13 +34,15 @@ class CustomGeometrySource : public Source { void releaseThreads(); private: - void setTileData(jni::JNIEnv& env, jni::jint z, jni::jint x, jni::jint y, const jni::Object& jf); + void setTileData( + jni::JNIEnv& env, jni::jint z, jni::jint x, jni::jint y, const jni::Object& jf + ); void invalidateTile(jni::JNIEnv& env, jni::jint z, jni::jint x, jni::jint y); void invalidateBounds(jni::JNIEnv& env, const jni::Object& bounds); - jni::Local>> querySourceFeatures(jni::JNIEnv&, - const jni::Array>& ); + jni::Local>> + querySourceFeatures(jni::JNIEnv&, const jni::Array>&); jni::Local> createJavaPeer(jni::JNIEnv&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.cpp index 9993f009ba3..abd703bf648 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.cpp @@ -27,16 +27,18 @@ namespace mbgl { namespace android { - // This conversion is expected not to fail because it's used only in contexts where - // the value was originally a GeoJsonOptions object on the Java side. If it fails - // to convert, it's a bug in our serialization or Java-side static typing. +// This conversion is expected not to fail because it's used only in contexts where +// the value was originally a GeoJsonOptions object on the Java side. If it fails +// to convert, it's a bug in our serialization or Java-side static typing. static Immutable convertGeoJSONOptions(jni::JNIEnv& env, const jni::Object<>& options) { using namespace mbgl::style::conversion; if (!options) { return style::GeoJSONOptions::defaultOptions(); } Error error; - std::optional result = convert(mbgl::android::Value(env, options), error); + std::optional result = convert( + mbgl::android::Value(env, options), error + ); if (!result) { throw std::logic_error(error.message); } @@ -44,16 +46,21 @@ static Immutable convertGeoJSONOptions(jni::JNIEnv& env, } GeoJSONSource::GeoJSONSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& options) - : Source(env, - std::make_unique(jni::Make(env, sourceId), - convertGeoJSONOptions(env, options))), - converter(std::make_unique>(Scheduler::GetBackground(), - source.as()->impl().getOptions())) {} + : Source( + env, + std::make_unique( + jni::Make(env, sourceId), convertGeoJSONOptions(env, options) + ) + ), + converter(std::make_unique>( + Scheduler::GetBackground(), source.as()->impl().getOptions() + )) {} GeoJSONSource::GeoJSONSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) : Source(env, coreSource, createJavaPeer(env), frontend), - converter(std::make_unique>(Scheduler::GetBackground(), - source.as()->impl().getOptions())) {} + converter(std::make_unique>( + Scheduler::GetBackground(), source.as()->impl().getOptions() + )) {} GeoJSONSource::~GeoJSONSource() = default; @@ -67,193 +74,211 @@ void GeoJSONSource::setGeoJSONString(jni::JNIEnv& env, const jni::String& jStrin setAsync(converterFn); } - void GeoJSONSource::setFeatureCollection(jni::JNIEnv& env, const jni::Object& jFeatures) { - setCollectionAsync(env, jFeatures); - } +void GeoJSONSource::setFeatureCollection(jni::JNIEnv& env, const jni::Object& jFeatures) { + setCollectionAsync(env, jFeatures); +} - void GeoJSONSource::setFeature(jni::JNIEnv& env, const jni::Object& jFeature) { - setCollectionAsync(env, jFeature); - } +void GeoJSONSource::setFeature(jni::JNIEnv& env, const jni::Object& jFeature) { + setCollectionAsync(env, jFeature); +} - void GeoJSONSource::setGeometry(jni::JNIEnv& env, const jni::Object& jGeometry) { - setCollectionAsync(env, jGeometry); - } +void GeoJSONSource::setGeometry(jni::JNIEnv& env, const jni::Object& jGeometry) { + setCollectionAsync(env, jGeometry); +} - void GeoJSONSource::setURL(jni::JNIEnv& env, const jni::String& url) { - // Update the core source - source.as()->setURL(jni::Make(env, url)); - } +void GeoJSONSource::setURL(jni::JNIEnv& env, const jni::String& url) { + // Update the core source + source.as()->setURL(jni::Make(env, url)); +} - jni::Local GeoJSONSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } +jni::Local GeoJSONSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} - jni::Local>> GeoJSONSource::querySourceFeatures(jni::JNIEnv& env, - const jni::Array>& jfilter) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; +jni::Local>> GeoJSONSource::querySourceFeatures( + jni::JNIEnv& env, const jni::Array>& jfilter +) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; - std::vector features; - if (rendererFrontend) { - features = rendererFrontend->querySourceFeatures(source.getID(), - { {}, toFilter(env, jfilter) }); - } - return Feature::convert(env, features); + std::vector features; + if (rendererFrontend) { + features = rendererFrontend->querySourceFeatures(source.getID(), {{}, toFilter(env, jfilter)}); } + return Feature::convert(env, features); +} - jni::Local>> GeoJSONSource::getClusterChildren(jni::JNIEnv& env, const jni::Object& feature) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; - - if (rendererFrontend) { - mbgl::Feature _feature = Feature::convert(env, feature); - _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); - const auto featureExtension = rendererFrontend->queryFeatureExtensions(source.getID(), _feature, "supercluster", "children", {}); - if (featureExtension.is()) { - return Feature::convert(env, featureExtension.get()); - } +jni::Local>> GeoJSONSource::getClusterChildren( + jni::JNIEnv& env, const jni::Object& feature +) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; + + if (rendererFrontend) { + mbgl::Feature _feature = Feature::convert(env, feature); + _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); + const auto featureExtension = rendererFrontend->queryFeatureExtensions( + source.getID(), _feature, "supercluster", "children", {} + ); + if (featureExtension.is()) { + return Feature::convert(env, featureExtension.get()); } - return jni::Array>::New(env, 0); } + return jni::Array>::New(env, 0); +} - jni::Local>> GeoJSONSource::getClusterLeaves(jni::JNIEnv& env, const jni::Object& feature, jni::jlong limit, jni::jlong offset) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; - - if (rendererFrontend) { - mbgl::Feature _feature = Feature::convert(env, feature); - _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); - const std::map options = { {"limit", static_cast(limit)}, - {"offset", static_cast(offset)} }; - auto featureExtension = rendererFrontend->queryFeatureExtensions(source.getID(), _feature, "supercluster", "leaves", options); - if (featureExtension.is()) { - return Feature::convert(env, featureExtension.get()); - } +jni::Local>> GeoJSONSource::getClusterLeaves( + jni::JNIEnv& env, const jni::Object& feature, jni::jlong limit, jni::jlong offset +) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; + + if (rendererFrontend) { + mbgl::Feature _feature = Feature::convert(env, feature); + _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); + const std::map options = { + {"limit", static_cast(limit)}, {"offset", static_cast(offset)}}; + auto featureExtension = rendererFrontend->queryFeatureExtensions( + source.getID(), _feature, "supercluster", "leaves", options + ); + if (featureExtension.is()) { + return Feature::convert(env, featureExtension.get()); } - return jni::Array>::New(env, 0);; } + return jni::Array>::New(env, 0); + ; +} - jint GeoJSONSource::getClusterExpansionZoom(jni::JNIEnv& env, const jni::Object& feature) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; - - if (rendererFrontend) { - mbgl::Feature _feature = Feature::convert(env, feature); - _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); - auto featureExtension = rendererFrontend->queryFeatureExtensions(source.getID(), _feature, "supercluster", "expansion-zoom", {}); - if (featureExtension.is()) { - auto value = featureExtension.get(); - if (value.is()) { - return value.get(); - } +jint GeoJSONSource::getClusterExpansionZoom(jni::JNIEnv& env, const jni::Object& feature) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; + + if (rendererFrontend) { + mbgl::Feature _feature = Feature::convert(env, feature); + _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); + auto featureExtension = rendererFrontend->queryFeatureExtensions( + source.getID(), _feature, "supercluster", "expansion-zoom", {} + ); + if (featureExtension.is()) { + auto value = featureExtension.get(); + if (value.is()) { + return value.get(); } } - return 0; } + return 0; +} - jni::Local> GeoJSONSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } +jni::Local> GeoJSONSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} - template - void GeoJSONSource::setCollectionAsync(jni::JNIEnv& env, const jni::Object& jObject) { - auto global = jni::NewGlobal(env, jObject); - auto object = std::make_shared(std::move(global)); +template +void GeoJSONSource::setCollectionAsync(jni::JNIEnv& env, const jni::Object& jObject) { + auto global = jni::NewGlobal(env, jObject); + auto object = std::make_shared(std::move(global)); - Update::Converter converterFn = [this, object](ActorRef _callback) { - converter->self().invoke(&FeatureConverter::convertObject, object, _callback); - }; + Update::Converter converterFn = [this, object](ActorRef _callback) { + converter->self().invoke(&FeatureConverter::convertObject, object, _callback); + }; - setAsync(converterFn); - } + setAsync(converterFn); +} - void GeoJSONSource::setAsync(Update::Converter converterFn) { - awaitingUpdate = std::make_unique( - std::move(converterFn), - std::make_unique>( - *Scheduler::GetCurrent(), [this](std::shared_ptr geoJSONData) { - // conversion from Java features to core ones finished - android::UniqueEnv _env = android::AttachEnv(); - - // Update the core source - source.as()->setGeoJSONData(std::move(geoJSONData)); - - // if there is an awaiting update, execute it, otherwise, release resources - if (awaitingUpdate) { - update = std::move(awaitingUpdate); - update->converterFn(update->callback->self()); - } else { - update.reset(); - } - })); - - // If another update is running, wait - if (update) { - return; - } +void GeoJSONSource::setAsync(Update::Converter converterFn) { + awaitingUpdate = std::make_unique( + std::move(converterFn), + std::make_unique>( + *Scheduler::GetCurrent(), + [this](std::shared_ptr geoJSONData) { + // conversion from Java features to core ones finished + android::UniqueEnv _env = android::AttachEnv(); + + // Update the core source + source.as()->setGeoJSONData(std::move(geoJSONData)); + + // if there is an awaiting update, execute it, otherwise, release resources + if (awaitingUpdate) { + update = std::move(awaitingUpdate); + update->converterFn(update->callback->self()); + } else { + update.reset(); + } + } + ) + ); - // no updates are being processed, execute this one - update = std::move(awaitingUpdate); - update->converterFn(update->callback->self()); + // If another update is running, wait + if (update) { + return; } - void GeoJSONSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&GeoJSONSource::setGeoJSONString, "nativeSetGeoJsonString"), - METHOD(&GeoJSONSource::setFeatureCollection, "nativeSetFeatureCollection"), - METHOD(&GeoJSONSource::setFeature, "nativeSetFeature"), - METHOD(&GeoJSONSource::setGeometry, "nativeSetGeometry"), - METHOD(&GeoJSONSource::setURL, "nativeSetUrl"), - METHOD(&GeoJSONSource::getURL, "nativeGetUrl"), - METHOD(&GeoJSONSource::querySourceFeatures, "querySourceFeatures"), - METHOD(&GeoJSONSource::getClusterChildren, "nativeGetClusterChildren"), - METHOD(&GeoJSONSource::getClusterLeaves, "nativeGetClusterLeaves"), - METHOD(&GeoJSONSource::getClusterExpansionZoom, "nativeGetClusterExpansionZoom") - ); - } + // no updates are being processed, execute this one + update = std::move(awaitingUpdate); + update->converterFn(update->callback->self()); +} - void FeatureConverter::convertJson(std::shared_ptr json, ActorRef callback) { - using namespace mbgl::style::conversion; +void GeoJSONSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&GeoJSONSource::setGeoJSONString, "nativeSetGeoJsonString"), + METHOD(&GeoJSONSource::setFeatureCollection, "nativeSetFeatureCollection"), + METHOD(&GeoJSONSource::setFeature, "nativeSetFeature"), + METHOD(&GeoJSONSource::setGeometry, "nativeSetGeometry"), + METHOD(&GeoJSONSource::setURL, "nativeSetUrl"), + METHOD(&GeoJSONSource::getURL, "nativeGetUrl"), + METHOD(&GeoJSONSource::querySourceFeatures, "querySourceFeatures"), + METHOD(&GeoJSONSource::getClusterChildren, "nativeGetClusterChildren"), + METHOD(&GeoJSONSource::getClusterLeaves, "nativeGetClusterLeaves"), + METHOD(&GeoJSONSource::getClusterExpansionZoom, "nativeGetClusterExpansionZoom") + ); +} - android::UniqueEnv _env = android::AttachEnv(); - // Convert the jni object - Error error; - std::optional converted = parseGeoJSON(*json, error); - if(!converted) { - mbgl::Log::Error(mbgl::Event::JNI, "Error setting geo json: " + error.message); - return; - } +void FeatureConverter::convertJson(std::shared_ptr json, ActorRef callback) { + using namespace mbgl::style::conversion; - callback.invoke(&GeoJSONDataCallback::operator(), style::GeoJSONData::create(*converted, options)); + android::UniqueEnv _env = android::AttachEnv(); + // Convert the jni object + Error error; + std::optional converted = parseGeoJSON(*json, error); + if (!converted) { + mbgl::Log::Error(mbgl::Event::JNI, "Error setting geo json: " + error.message); + return; } - template - void FeatureConverter::convertObject( - std::shared_ptr, jni::EnvAttachingDeleter>> jObject, - ActorRef callback) { - using namespace mbgl::android::geojson; + callback.invoke(&GeoJSONDataCallback::operator(), style::GeoJSONData::create(*converted, options)); +} - android::UniqueEnv _env = android::AttachEnv(); - // Convert the jni object - auto geometry = JNIType::convert(*_env, *jObject); - callback.invoke(&GeoJSONDataCallback::operator(), style::GeoJSONData::create(geometry, options)); - } +template +void FeatureConverter::convertObject( + std::shared_ptr, jni::EnvAttachingDeleter>> jObject, + ActorRef callback +) { + using namespace mbgl::android::geojson; + + android::UniqueEnv _env = android::AttachEnv(); + // Convert the jni object + auto geometry = JNIType::convert(*_env, *jObject); + callback.invoke(&GeoJSONDataCallback::operator(), style::GeoJSONData::create(geometry, options)); +} - Update::Update(Converter _converterFn, std::unique_ptr> _callback) - : converterFn(std::move(_converterFn)), callback(std::move(_callback)) {} +Update::Update(Converter _converterFn, std::unique_ptr> _callback) + : converterFn(std::move(_converterFn)), + callback(std::move(_callback)) {} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.hpp index c7ef6e54dea..fed4e740b86 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.hpp @@ -15,12 +15,13 @@ using GeoJSONDataCallback = std::function options_) : options(std::move(options_)) {} + explicit FeatureConverter(Immutable options_) + : options(std::move(options_)) {} void convertJson(std::shared_ptr, ActorRef); template - void convertObject(std::shared_ptr, jni::EnvAttachingDeleter>>, - ActorRef); + void + convertObject(std::shared_ptr, jni::EnvAttachingDeleter>>, ActorRef); private: Immutable options; @@ -53,11 +54,14 @@ class GeoJSONSource : public Source { void setGeometry(jni::JNIEnv&, const jni::Object&); void setURL(jni::JNIEnv&, const jni::String&); - jni::Local>> querySourceFeatures(jni::JNIEnv&, - const jni::Array>&); + jni::Local>> + querySourceFeatures(jni::JNIEnv&, const jni::Array>&); - jni::Local>> getClusterChildren(jni::JNIEnv&, const jni::Object&); - jni::Local>> getClusterLeaves(jni::JNIEnv&, const jni::Object&, jni::jlong, jni::jlong); + jni::Local>> + getClusterChildren(jni::JNIEnv&, const jni::Object&); + jni::Local>> getClusterLeaves( + jni::JNIEnv&, const jni::Object&, jni::jlong, jni::jlong + ); jint getClusterExpansionZoom(jni::JNIEnv&, const jni::Object&); jni::Local getURL(jni::JNIEnv&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/image_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/image_source.cpp index 85924b7cce2..fecc3506de4 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/image_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/image_source.cpp @@ -15,62 +15,65 @@ namespace mbgl { namespace android { - ImageSource::ImageSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object& coordinatesObject) - : Source(env, std::make_unique( - jni::Make(env, sourceId), - LatLngQuad::getLatLngArray(env, coordinatesObject) - ) - ) { - } - - ImageSource::ImageSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - ImageSource::~ImageSource() = default; - - void ImageSource::setURL(jni::JNIEnv& env, const jni::String& url) { - // Update the core source - source.as()->ImageSource::setURL(jni::Make(env, url)); - } - - jni::Local ImageSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->ImageSource::getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } - - void ImageSource::setImage(jni::JNIEnv& env, const jni::Object& bitmap) { - source.as()->setImage(Bitmap::GetImage(env, bitmap)); - } - - void ImageSource::setCoordinates(jni::JNIEnv& env, const jni::Object& coordinatesObject) { - source.as()->setCoordinates( - LatLngQuad::getLatLngArray(env, coordinatesObject)); - } - - jni::Local> ImageSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } - - void ImageSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&ImageSource::setURL, "nativeSetUrl"), - METHOD(&ImageSource::getURL, "nativeGetUrl"), - METHOD(&ImageSource::setImage, "nativeSetImage"), - METHOD(&ImageSource::setCoordinates, "nativeSetCoordinates") - ); - } +ImageSource::ImageSource( + jni::JNIEnv& env, const jni::String& sourceId, const jni::Object& coordinatesObject +) + : Source( + env, + std::make_unique( + jni::Make(env, sourceId), LatLngQuad::getLatLngArray(env, coordinatesObject) + ) + ) {} + +ImageSource::ImageSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +ImageSource::~ImageSource() = default; + +void ImageSource::setURL(jni::JNIEnv& env, const jni::String& url) { + // Update the core source + source.as()->ImageSource::setURL(jni::Make(env, url)); +} + +jni::Local ImageSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->ImageSource::getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} + +void ImageSource::setImage(jni::JNIEnv& env, const jni::Object& bitmap) { + source.as()->setImage(Bitmap::GetImage(env, bitmap)); +} + +void ImageSource::setCoordinates(jni::JNIEnv& env, const jni::Object& coordinatesObject) { + source.as()->setCoordinates(LatLngQuad::getLatLngArray(env, coordinatesObject)); +} + +jni::Local> ImageSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void ImageSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&ImageSource::setURL, "nativeSetUrl"), + METHOD(&ImageSource::getURL, "nativeGetUrl"), + METHOD(&ImageSource::setImage, "nativeSetImage"), + METHOD(&ImageSource::setCoordinates, "nativeSetCoordinates") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_dem_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_dem_source.cpp index f456c030f5a..5ca205ff6ec 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_dem_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_dem_source.cpp @@ -12,50 +12,49 @@ namespace mbgl { namespace android { - RasterDEMSource::RasterDEMSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet, jni::jint tileSize) - : Source( - env, - std::make_unique( - jni::Make(env, sourceId), - convertURLOrTileset(Value(env, urlOrTileSet)), - tileSize - ) - ) { - } - - RasterDEMSource::RasterDEMSource(jni::JNIEnv& env, - mbgl::style::Source& coreSource, - AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - RasterDEMSource::~RasterDEMSource() = default; - - jni::Local RasterDEMSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->RasterDEMSource::getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } - - jni::Local> RasterDEMSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } - - void RasterDEMSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&, jni::jint>, - "initialize", - "finalize", - METHOD(&RasterDEMSource::getURL, "nativeGetUrl") - ); - } +RasterDEMSource::RasterDEMSource( + jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet, jni::jint tileSize +) + : Source( + env, + std::make_unique( + jni::Make(env, sourceId), convertURLOrTileset(Value(env, urlOrTileSet)), tileSize + ) + ) {} + +RasterDEMSource::RasterDEMSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +RasterDEMSource::~RasterDEMSource() = default; + +jni::Local RasterDEMSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->RasterDEMSource::getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} + +jni::Local> RasterDEMSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void RasterDEMSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&, jni::jint>, + "initialize", + "finalize", + METHOD(&RasterDEMSource::getURL, "nativeGetUrl") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_source.cpp index c7462f7d95e..4da5aedd0ed 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_source.cpp @@ -11,48 +11,49 @@ namespace mbgl { namespace android { - RasterSource::RasterSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet, jni::jint tileSize) - : Source( - env, - std::make_unique( - jni::Make(env, sourceId), - convertURLOrTileset(Value(env, urlOrTileSet)), - tileSize - ) - ) { - } - - RasterSource::RasterSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - RasterSource::~RasterSource() = default; - - jni::Local RasterSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->RasterSource::getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } - - jni::Local> RasterSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } - - void RasterSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&, jni::jint>, - "initialize", - "finalize", - METHOD(&RasterSource::getURL, "nativeGetUrl") - ); - } +RasterSource::RasterSource( + jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet, jni::jint tileSize +) + : Source( + env, + std::make_unique( + jni::Make(env, sourceId), convertURLOrTileset(Value(env, urlOrTileSet)), tileSize + ) + ) {} + +RasterSource::RasterSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +RasterSource::~RasterSource() = default; + +jni::Local RasterSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->RasterSource::getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} + +jni::Local> RasterSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void RasterSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&, jni::jint>, + "initialize", + "finalize", + METHOD(&RasterSource::getURL, "nativeGetUrl") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.cpp index f4386336344..926ee056efc 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.cpp @@ -34,9 +34,9 @@ namespace mbgl { namespace android { -static std::unique_ptr createSourcePeer(jni::JNIEnv& env, - mbgl::style::Source& coreSource, - AndroidRendererFrontend* frontend) { +static std::unique_ptr createSourcePeer( + jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend +) { if (coreSource.is()) { return std::make_unique(env, *coreSource.as(), frontend); } else if (coreSource.is()) { @@ -50,205 +50,207 @@ static std::unique_ptr createSourcePeer(jni::JNIEnv& env, } } - const jni::Object& Source::peerForCoreSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend& frontend) { - if (!coreSource.peer.has_value()) { - coreSource.peer = createSourcePeer(env, coreSource, &frontend); - } - return coreSource.peer.get>()->javaPeer; +const jni::Object& Source::peerForCoreSource( + jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend& frontend +) { + if (!coreSource.peer.has_value()) { + coreSource.peer = createSourcePeer(env, coreSource, &frontend); } + return coreSource.peer.get>()->javaPeer; +} - const jni::Object& Source::peerForCoreSource(jni::JNIEnv& env, mbgl::style::Source& coreSource) { - if (!coreSource.peer.has_value()) { - coreSource.peer = createSourcePeer(env, coreSource, nullptr); - } - return coreSource.peer.get>()->javaPeer; +const jni::Object& Source::peerForCoreSource(jni::JNIEnv& env, mbgl::style::Source& coreSource) { + if (!coreSource.peer.has_value()) { + coreSource.peer = createSourcePeer(env, coreSource, nullptr); } + return coreSource.peer.get>()->javaPeer; +} - Source::Source(jni::JNIEnv& env, - mbgl::style::Source& coreSource, - const jni::Object& obj, - AndroidRendererFrontend* frontend) - : source(coreSource), javaPeer(jni::NewGlobal(env, obj)), rendererFrontend(frontend) {} - - Source::Source(jni::JNIEnv&, std::unique_ptr coreSource) - : ownedSource(std::move(coreSource)) - , source(*ownedSource) { +Source::Source( + jni::JNIEnv& env, mbgl::style::Source& coreSource, const jni::Object& obj, AndroidRendererFrontend* frontend +) + : source(coreSource), + javaPeer(jni::NewGlobal(env, obj)), + rendererFrontend(frontend) {} + +Source::Source(jni::JNIEnv&, std::unique_ptr coreSource) + : ownedSource(std::move(coreSource)), + source(*ownedSource) {} + +Source::~Source() { + if (ownedSource) { + ownedSource.reset(); + ownedSource.release(); } - - Source::~Source() { - if (ownedSource) { - ownedSource.reset(); - ownedSource.release(); - } - // Before being added to a map, the Java peer owns this C++ peer and cleans - // up after itself correctly through the jni native peer bindings. - // After being added to the map, the ownership is flipped and the C++ peer has a strong reference - // to it's Java peer, preventing the Java peer from being GC'ed. - // In this case, the core source initiates the destruction, which requires releasing the Java peer, - // while also resetting it's nativePtr to 0 to prevent the subsequent GC of the Java peer from - // re-entering this dtor. - if (ownedSource.get() == nullptr && javaPeer.get() != nullptr) { - // Manually clear the java peer - android::UniqueEnv env = android::AttachEnv(); - static auto& javaClass = jni::Class::Singleton(*env); - static auto nativePtrField = javaClass.GetField(*env, "nativePtr"); - javaPeer.Set(*env, nativePtrField, (jlong) 0); - javaPeer.reset(); - } + // Before being added to a map, the Java peer owns this C++ peer and cleans + // up after itself correctly through the jni native peer bindings. + // After being added to the map, the ownership is flipped and the C++ peer has a strong reference + // to it's Java peer, preventing the Java peer from being GC'ed. + // In this case, the core source initiates the destruction, which requires releasing the Java peer, + // while also resetting it's nativePtr to 0 to prevent the subsequent GC of the Java peer from + // re-entering this dtor. + if (ownedSource.get() == nullptr && javaPeer.get() != nullptr) { + // Manually clear the java peer + android::UniqueEnv env = android::AttachEnv(); + static auto& javaClass = jni::Class::Singleton(*env); + static auto nativePtrField = javaClass.GetField(*env, "nativePtr"); + javaPeer.Set(*env, nativePtrField, (jlong)0); + javaPeer.reset(); } +} - jni::Local Source::getId(jni::JNIEnv& env) { - return jni::Make(env, source.getID()); - } +jni::Local Source::getId(jni::JNIEnv& env) { + return jni::Make(env, source.getID()); +} - jni::Local Source::getAttribution(jni::JNIEnv& env) { - auto attribution = source.getAttribution(); - return attribution ? jni::Make(env, attribution.value()) : jni::Make(env,""); +jni::Local Source::getAttribution(jni::JNIEnv& env) { + auto attribution = source.getAttribution(); + return attribution ? jni::Make(env, attribution.value()) : jni::Make(env, ""); +} + +void Source::setPrefetchZoomDelta(jni::JNIEnv& env, jni::Integer& delta) { + if (!delta) { + source.setPrefetchZoomDelta(std::nullopt); + } else { + source.setPrefetchZoomDelta(jni::Unbox(env, delta)); } +} - void Source::setPrefetchZoomDelta(jni::JNIEnv& env, jni::Integer& delta) { - if (!delta) { - source.setPrefetchZoomDelta(std::nullopt); - } else { - source.setPrefetchZoomDelta(jni::Unbox(env, delta)); - } +jni::Local Source::getPrefetchZoomDelta(jni::JNIEnv& env) { + auto delta = source.getPrefetchZoomDelta(); + if (delta.has_value()) { + return jni::Box(env, jni::jint(delta.value())); } + return jni::Local(env, nullptr); +} - jni::Local Source::getPrefetchZoomDelta(jni::JNIEnv& env) { - auto delta = source.getPrefetchZoomDelta(); - if (delta.has_value()) { - return jni::Box(env, jni::jint(delta.value())); - } - return jni::Local(env, nullptr); +void Source::setMaxOverscaleFactorForParentTiles(jni::JNIEnv& env, jni::Integer& maxOverscaleFactor) { + if (!maxOverscaleFactor) { + source.setMaxOverscaleFactorForParentTiles(std::nullopt); + } else { + source.setMaxOverscaleFactorForParentTiles(jni::Unbox(env, maxOverscaleFactor)); } +} - void Source::setMaxOverscaleFactorForParentTiles(jni::JNIEnv& env, jni::Integer& maxOverscaleFactor) { - if (!maxOverscaleFactor) { - source.setMaxOverscaleFactorForParentTiles(std::nullopt); - } else { - source.setMaxOverscaleFactorForParentTiles(jni::Unbox(env, maxOverscaleFactor)); - } +jni::Local Source::getMaxOverscaleFactorForParentTiles(jni::JNIEnv& env) { + auto maxOverscaleFactor = source.getMaxOverscaleFactorForParentTiles(); + if (maxOverscaleFactor) { + return jni::Box(env, jni::jint(*maxOverscaleFactor)); } + return jni::Local(env, nullptr); +} - jni::Local Source::getMaxOverscaleFactorForParentTiles(jni::JNIEnv& env) { - auto maxOverscaleFactor = source.getMaxOverscaleFactorForParentTiles(); - if (maxOverscaleFactor) { - return jni::Box(env, jni::jint(*maxOverscaleFactor)); - } - return jni::Local(env, nullptr); +void Source::addToStyle(JNIEnv& env, const jni::Object& obj, mbgl::style::Style& style) { + if (!ownedSource) { + throw std::runtime_error("Cannot add source twice"); } - void Source::addToStyle(JNIEnv& env, const jni::Object& obj, mbgl::style::Style& style) { - if (!ownedSource) { - throw std::runtime_error("Cannot add source twice"); - } + // Add source to style and release ownership + style.addSource(std::move(ownedSource)); - // Add source to style and release ownership - style.addSource(std::move(ownedSource)); + // Add peer to core source + source.peer = std::unique_ptr(this); - // Add peer to core source - source.peer = std::unique_ptr(this); + // Add strong reference to java source + javaPeer = jni::NewGlobal(env, obj); +} - // Add strong reference to java source - javaPeer = jni::NewGlobal(env, obj); +void Source::addToMap(JNIEnv& env, const jni::Object& obj, mbgl::Map& map, AndroidRendererFrontend& frontend) { + // Check to see if we own the source first + if (!ownedSource) { + throw std::runtime_error("Cannot add source twice"); } - void Source::addToMap(JNIEnv& env, const jni::Object& obj, mbgl::Map& map, AndroidRendererFrontend& frontend) { - // Check to see if we own the source first - if (!ownedSource) { - throw std::runtime_error("Cannot add source twice"); - } + // Add source to map and release ownership + map.getStyle().addSource(std::move(ownedSource)); - // Add source to map and release ownership - map.getStyle().addSource(std::move(ownedSource)); + // Add peer to core source + source.peer = std::unique_ptr(this); - // Add peer to core source - source.peer = std::unique_ptr(this); + // Add strong reference to java source + javaPeer = jni::NewGlobal(env, obj); - // Add strong reference to java source - javaPeer = jni::NewGlobal(env, obj); + rendererFrontend = &frontend; +} - rendererFrontend = &frontend; +bool Source::removeFromMap(JNIEnv&, const jni::Object&, mbgl::Map& map) { + // Cannot remove if not attached yet + if (ownedSource) { + throw std::runtime_error("Cannot remove detached source"); } - bool Source::removeFromMap(JNIEnv&, const jni::Object&, mbgl::Map& map) { - // Cannot remove if not attached yet - if (ownedSource) { - throw std::runtime_error("Cannot remove detached source"); - } + // Remove the source from the map and take ownership + ownedSource = map.getStyle().removeSource(source.getID()); - // Remove the source from the map and take ownership - ownedSource = map.getStyle().removeSource(source.getID()); + // The source may not be removed if any layers still reference it + return ownedSource != nullptr; +} - // The source may not be removed if any layers still reference it - return ownedSource != nullptr; - } +jni::Local Source::isVolatile(jni::JNIEnv& env) { + return jni::Box(env, jni::jboolean(source.isVolatile())); +} - jni::Local Source::isVolatile(jni::JNIEnv& env) { - return jni::Box(env, jni::jboolean(source.isVolatile())); - } +void Source::setVolatile(JNIEnv& env, jni::Boolean& value) { + source.setVolatile(jni::Unbox(env, value)); +} - void Source::setVolatile(JNIEnv& env, jni::Boolean& value) { - source.setVolatile(jni::Unbox(env, value)); - } +void Source::setMinimumTileUpdateInterval(JNIEnv& env, jni::Long& interval) { + source.setMinimumTileUpdateInterval(Milliseconds(jni::Unbox(env, interval))); +} - void Source::setMinimumTileUpdateInterval(JNIEnv& env, jni::Long& interval) { - source.setMinimumTileUpdateInterval(Milliseconds(jni::Unbox(env, interval))); - } +jni::Local Source::getMinimumTileUpdateInterval(JNIEnv& env) { + return jni::Box(env, jni::jlong(source.getMinimumTileUpdateInterval().count() / 1000000)); +} - jni::Local Source::getMinimumTileUpdateInterval(JNIEnv& env) { - return jni::Box(env, jni::jlong(source.getMinimumTileUpdateInterval().count() / 1000000)); +void Source::releaseJavaPeer() { + // We can't release the peer if the source was not removed from the map + if (!ownedSource) { + return; } - void Source::releaseJavaPeer() { - // We can't release the peer if the source was not removed from the map - if (!ownedSource) { - return; - } + // Release the peer relationships. These will be re-established when the source is added to a map + assert(ownedSource->peer.has_value()); + ownedSource->peer.get>().release(); + ownedSource->peer = mapbox::base::TypeWrapper(); - // Release the peer relationships. These will be re-established when the source is added to a map - assert(ownedSource->peer.has_value()); - ownedSource->peer.get>().release(); - ownedSource->peer = mapbox::base::TypeWrapper(); - - // Release the strong reference to the java peer - assert(javaPeer); - javaPeer.reset(); + // Release the strong reference to the java peer + assert(javaPeer); + javaPeer.reset(); - rendererFrontend = nullptr; - } + rendererFrontend = nullptr; +} - void Source::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - METHOD(&Source::getId, "nativeGetId"), - METHOD(&Source::getAttribution, "nativeGetAttribution"), - METHOD(&Source::setPrefetchZoomDelta, "nativeSetPrefetchZoomDelta"), - METHOD(&Source::getPrefetchZoomDelta, "nativeGetPrefetchZoomDelta"), - METHOD(&Source::setMaxOverscaleFactorForParentTiles, "nativeSetMaxOverscaleFactorForParentTiles"), - METHOD(&Source::getMaxOverscaleFactorForParentTiles, "nativeGetMaxOverscaleFactorForParentTiles"), - METHOD(&Source::isVolatile, "nativeIsVolatile"), - METHOD(&Source::setVolatile, "nativeSetVolatile"), - METHOD(&Source::setMinimumTileUpdateInterval, "nativeSetMinimumTileUpdateInterval"), - METHOD(&Source::getMinimumTileUpdateInterval, "nativeGetMinimumTileUpdateInterval")); - - - // Register subclasses - GeoJSONSource::registerNative(env); - ImageSource::registerNative(env); - RasterSource::registerNative(env); - UnknownSource::registerNative(env); - VectorSource::registerNative(env); - CustomGeometrySource::registerNative(env); - RasterDEMSource::registerNative(env); - } +void Source::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + METHOD(&Source::getId, "nativeGetId"), + METHOD(&Source::getAttribution, "nativeGetAttribution"), + METHOD(&Source::setPrefetchZoomDelta, "nativeSetPrefetchZoomDelta"), + METHOD(&Source::getPrefetchZoomDelta, "nativeGetPrefetchZoomDelta"), + METHOD(&Source::setMaxOverscaleFactorForParentTiles, "nativeSetMaxOverscaleFactorForParentTiles"), + METHOD(&Source::getMaxOverscaleFactorForParentTiles, "nativeGetMaxOverscaleFactorForParentTiles"), + METHOD(&Source::isVolatile, "nativeIsVolatile"), + METHOD(&Source::setVolatile, "nativeSetVolatile"), + METHOD(&Source::setMinimumTileUpdateInterval, "nativeSetMinimumTileUpdateInterval"), + METHOD(&Source::getMinimumTileUpdateInterval, "nativeGetMinimumTileUpdateInterval") + ); + + // Register subclasses + GeoJSONSource::registerNative(env); + ImageSource::registerNative(env); + RasterSource::registerNative(env); + UnknownSource::registerNative(env); + VectorSource::registerNative(env); + CustomGeometrySource::registerNative(env); + RasterDEMSource::registerNative(env); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.hpp index bb398bf2afd..9daddcf8da2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.hpp @@ -14,7 +14,6 @@ namespace android { class Source : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/sources/Source"; }; static void registerNative(jni::JNIEnv&); @@ -54,11 +53,11 @@ class Source : private mbgl::util::noncopyable { void addToStyle(JNIEnv& env, const jni::Object& obj, mbgl::style::Style& style); - jni::Local isVolatile(JNIEnv&); + jni::Local isVolatile(JNIEnv&); void setVolatile(JNIEnv&, jni::Boolean&); - void setMinimumTileUpdateInterval(JNIEnv&, jni::Long &); + void setMinimumTileUpdateInterval(JNIEnv&, jni::Long&); jni::Local getMinimumTileUpdateInterval(JNIEnv&); @@ -73,7 +72,7 @@ class Source : private mbgl::util::noncopyable { jni::Global> javaPeer; // RendererFrontend pointer is valid only when added to the map. - AndroidRendererFrontend* rendererFrontend { nullptr }; + AndroidRendererFrontend* rendererFrontend{nullptr}; }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/unknown_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/unknown_source.cpp index acfd52db8df..925d6b9a575 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/unknown_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/unknown_source.cpp @@ -2,10 +2,10 @@ namespace { - // Dummy initializer (We don't support initializing this from the JVM) - std::unique_ptr init(jni::JNIEnv&) { - throw std::runtime_error("UnknownSource should not be initialized from the JVM"); - } +// Dummy initializer (We don't support initializing this from the JVM) +std::unique_ptr init(jni::JNIEnv&) { + throw std::runtime_error("UnknownSource should not be initialized from the JVM"); +} } // namespace @@ -21,20 +21,15 @@ jni::Local> UnknownSource::createJavaPeer(jni::JNIEnv& env) return javaClass.New(env, constructor, reinterpret_cast(this)); } - void UnknownSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); +void UnknownSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - init, - "initialize", - "finalize" - ); - } + // Register the peer + jni::RegisterNativePeer(env, javaClass, "nativePtr", init, "initialize", "finalize"); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.cpp index 1c34aba5551..2c2760fe111 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.cpp @@ -20,62 +20,63 @@ namespace mbgl { namespace android { - VectorSource::VectorSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet) - : Source( - env, - std::make_unique( - jni::Make(env, sourceId), - convertURLOrTileset(Value(env, urlOrTileSet)) - ) - ) { - } - - VectorSource::VectorSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - VectorSource::~VectorSource() = default; - - jni::Local VectorSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->VectorSource::getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } - - jni::Local>> VectorSource::querySourceFeatures(jni::JNIEnv& env, - const jni::Array& jSourceLayerIds, - const jni::Array>& jfilter) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; - - std::vector features; - if (rendererFrontend) { - features = rendererFrontend->querySourceFeatures(source.getID(), - { toVector(env, jSourceLayerIds), toFilter(env, jfilter) }); - } - return Feature::convert(env, features); - } - - jni::Local> VectorSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } - - void VectorSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&VectorSource::querySourceFeatures, "querySourceFeatures"), - METHOD(&VectorSource::getURL, "nativeGetUrl") +VectorSource::VectorSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet) + : Source( + env, + std::make_unique( + jni::Make(env, sourceId), convertURLOrTileset(Value(env, urlOrTileSet)) + ) + ) {} + +VectorSource::VectorSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +VectorSource::~VectorSource() = default; + +jni::Local VectorSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->VectorSource::getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} + +jni::Local>> VectorSource::querySourceFeatures( + jni::JNIEnv& env, const jni::Array& jSourceLayerIds, const jni::Array>& jfilter +) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; + + std::vector features; + if (rendererFrontend) { + features = rendererFrontend->querySourceFeatures( + source.getID(), {toVector(env, jSourceLayerIds), toFilter(env, jfilter)} ); } + return Feature::convert(env, features); +} + +jni::Local> VectorSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void VectorSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&VectorSource::querySourceFeatures, "querySourceFeatures"), + METHOD(&VectorSource::getURL, "nativeGetUrl") + ); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.hpp index 7ae2e8c9e74..28a08facfcd 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.hpp @@ -20,8 +20,9 @@ class VectorSource : public Source { ~VectorSource(); private: - jni::Local>> querySourceFeatures(jni::JNIEnv&, const jni::Array&, - const jni::Array>& jfilter); + jni::Local>> querySourceFeatures( + jni::JNIEnv&, const jni::Array&, const jni::Array>& jfilter + ); jni::Local getURL(jni::JNIEnv&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.cpp index d70a04e0d55..6a930bc6fd0 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.cpp @@ -3,9 +3,13 @@ namespace mbgl { namespace android { -jni::Local> TransitionOptions::fromTransitionOptions(jni::JNIEnv& env, jlong duration, jlong delay, jboolean enablePlacementTransitions) { +jni::Local> TransitionOptions::fromTransitionOptions( + jni::JNIEnv& env, jlong duration, jlong delay, jboolean enablePlacementTransitions +) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jlong, jlong, jboolean)>(env, "fromTransitionOptions"); + static auto method = javaClass.GetStaticMethod(jlong, jlong, jboolean)>( + env, "fromTransitionOptions" + ); return javaClass.Call(env, method, duration, delay, enablePlacementTransitions); } @@ -21,9 +25,11 @@ long TransitionOptions::getDelay(jni::JNIEnv& env, const jni::Object& transitionOptions) { +bool TransitionOptions::isEnablePlacementTransitions( + jni::JNIEnv& env, const jni::Object& transitionOptions +) { static auto& javaClass = jni::Class::Singleton(env); - static auto field = javaClass.GetField(env, "enablePlacementTransitions"); + static auto field = javaClass.GetField(env, "enablePlacementTransitions"); return transitionOptions.Get(env, field); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.hpp index 58656a94638..a1fc8707ec0 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.hpp @@ -11,7 +11,9 @@ class TransitionOptions : private mbgl::util::noncopyable { public: static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/layers/TransitionOptions"; }; - static jni::Local> fromTransitionOptions(jni::JNIEnv&, jlong duration, jlong delay, jboolean enablePlacementTransitions); + static jni::Local> fromTransitionOptions( + jni::JNIEnv&, jlong duration, jlong delay, jboolean enablePlacementTransitions + ); static long getDuration(jni::JNIEnv&, const jni::Object&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.cpp index 2f048407299..fb50bced263 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.cpp @@ -4,80 +4,81 @@ namespace mbgl { namespace android { - // Instance - - Value::Value(jni::JNIEnv& _env, jni::Local> _value) - : env(_env), - value(std::move(_value)) {} - - Value::Value(jni::JNIEnv& _env, const jni::Object<>& _value) - : env(_env), - value(jni::NewLocal(_env, _value)) {} - - bool Value::isNull() const { - return !value; - } - - bool Value::isArray() const { - return jni::IsInstanceOf(env, value.get(), *java::ObjectArray::jclass); - } - - bool Value::isObject() const { - return jni::IsInstanceOf(env, value.get(), *java::Map::jclass); - } - - bool Value::isString() const { - return jni::IsInstanceOf(env, value.get(), *java::String::jclass); - } - - bool Value::isBool() const { - return jni::IsInstanceOf(env, value.get(), *java::Boolean::jclass); - } - - bool Value::isNumber() const { - return jni::IsInstanceOf(env, value.get(), *java::Number::jclass); - } - - std::string Value::toString() const { - return jni::Make(env, jni::Cast(env, jni::Class::Singleton(env), value)); - } - - float Value::toFloat() const { - return jni::CallMethod(env, value.get(), *java::Number::floatValueMethodId); - } - - double Value::toDouble() const { - return jni::CallMethod(env, value.get(), *java::Number::doubleValueMethodId); - } - - long Value::toLong() const { - return jni::CallMethod(env, value.get(), *java::Number::longValueMethodId); - } - - bool Value::toBool() const { - return jni::CallMethod(env, value.get(), *java::Boolean::booleanValueMethodId); - } - - Value Value::get(const char* key) const { - jni::jobject* member = jni::CallMethod(env, value.get(), *java::Map::getMethodId, jni::Make(env, std::string(key)).get()); - return Value(env, jni::Local>(env, member)); - } - - Value Value::keyArray() const{ - jni::jobject* set = jni::CallMethod(env, value.get(), *java::Map::keySetMethodId); - jni::jobject* array = jni::CallMethod(env, set, *java::Set::toArrayMethodId); - return Value(env, jni::Local>(env, array)); - } - - int Value::getLength() const { - auto array = (jni::jarray*) value.get(); - return jni::GetArrayLength(env, *array); - } - - Value Value::get(const int index) const { - auto array = (jni::jarray*) value.get(); - return Value(env, jni::Local>(env, jni::GetObjectArrayElement(env, *array, index))); - } +// Instance + +Value::Value(jni::JNIEnv& _env, jni::Local> _value) + : env(_env), + value(std::move(_value)) {} + +Value::Value(jni::JNIEnv& _env, const jni::Object<>& _value) + : env(_env), + value(jni::NewLocal(_env, _value)) {} + +bool Value::isNull() const { + return !value; +} + +bool Value::isArray() const { + return jni::IsInstanceOf(env, value.get(), *java::ObjectArray::jclass); +} + +bool Value::isObject() const { + return jni::IsInstanceOf(env, value.get(), *java::Map::jclass); } + +bool Value::isString() const { + return jni::IsInstanceOf(env, value.get(), *java::String::jclass); } +bool Value::isBool() const { + return jni::IsInstanceOf(env, value.get(), *java::Boolean::jclass); +} + +bool Value::isNumber() const { + return jni::IsInstanceOf(env, value.get(), *java::Number::jclass); +} + +std::string Value::toString() const { + return jni::Make(env, jni::Cast(env, jni::Class::Singleton(env), value)); +} + +float Value::toFloat() const { + return jni::CallMethod(env, value.get(), *java::Number::floatValueMethodId); +} + +double Value::toDouble() const { + return jni::CallMethod(env, value.get(), *java::Number::doubleValueMethodId); +} + +long Value::toLong() const { + return jni::CallMethod(env, value.get(), *java::Number::longValueMethodId); +} + +bool Value::toBool() const { + return jni::CallMethod(env, value.get(), *java::Boolean::booleanValueMethodId); +} + +Value Value::get(const char* key) const { + jni::jobject* member = jni::CallMethod( + env, value.get(), *java::Map::getMethodId, jni::Make(env, std::string(key)).get() + ); + return Value(env, jni::Local>(env, member)); +} + +Value Value::keyArray() const { + jni::jobject* set = jni::CallMethod(env, value.get(), *java::Map::keySetMethodId); + jni::jobject* array = jni::CallMethod(env, set, *java::Set::toArrayMethodId); + return Value(env, jni::Local>(env, array)); +} + +int Value::getLength() const { + auto array = (jni::jarray*)value.get(); + return jni::GetArrayLength(env, *array); +} + +Value Value::get(const int index) const { + auto array = (jni::jarray*)value.get(); + return Value(env, jni::Local>(env, jni::GetObjectArrayElement(env, *array, index))); +} +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.hpp index b507c5ed11c..5df4f10b6a7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.hpp @@ -12,10 +12,10 @@ class Value { Value(jni::JNIEnv&, jni::Local>); Value(jni::JNIEnv&, const jni::Object<>&); - Value(Value&&) = default; - Value& operator=(Value&&) = delete; + Value(Value&&) = default; + Value& operator=(Value&&) = delete; - Value(const Value&) = delete; + Value(const Value&) = delete; Value& operator=(const Value&) = delete; bool isNull() const; @@ -33,11 +33,11 @@ class Value { Value get(const char* key) const; Value keyArray() const; int getLength() const; - Value get(const int index ) const; + Value get(const int index) const; jni::JNIEnv& env; jni::Local> value; }; -} -} +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/text/local_glyph_rasterizer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/text/local_glyph_rasterizer.cpp index 67e5caf0539..13beb9a8a60 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/text/local_glyph_rasterizer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/text/local_glyph_rasterizer.cpp @@ -34,7 +34,7 @@ namespace mbgl { namespace android { LocalGlyphRasterizer::LocalGlyphRasterizer() { - UniqueEnv env { AttachEnv() }; + UniqueEnv env{AttachEnv()}; static auto& javaClass = jni::Class::Singleton(*env); static auto constructor = javaClass.GetConstructor(*env); @@ -42,18 +42,26 @@ LocalGlyphRasterizer::LocalGlyphRasterizer() { javaObject = jni::NewGlobal(*env, javaClass.New(*env, constructor)); } -PremultipliedImage LocalGlyphRasterizer::drawGlyphBitmap(const std::string& fontFamily, const bool bold, const GlyphID glyphID) { - UniqueEnv env { AttachEnv() }; +PremultipliedImage LocalGlyphRasterizer::drawGlyphBitmap( + const std::string& fontFamily, const bool bold, const GlyphID glyphID +) { + UniqueEnv env{AttachEnv()}; static auto& javaClass = jni::Class::Singleton(*env); - static auto drawGlyphBitmap = javaClass.GetMethod (jni::String, jni::jboolean, jni::jchar)>(*env, "drawGlyphBitmap"); - - return Bitmap::GetImage(*env, - javaObject.Call(*env, + static auto drawGlyphBitmap = javaClass.GetMethod(jni::String, jni::jboolean, jni::jchar)>( + *env, "drawGlyphBitmap" + ); + + return Bitmap::GetImage( + *env, + javaObject.Call( + *env, drawGlyphBitmap, jni::Make(*env, fontFamily), static_cast(bold), - static_cast(glyphID))); + static_cast(glyphID) + ) + ); } void LocalGlyphRasterizer::registerNative(jni::JNIEnv& env) { @@ -65,12 +73,9 @@ void LocalGlyphRasterizer::registerNative(jni::JNIEnv& env) { class LocalGlyphRasterizer::Impl { public: Impl(const std::optional fontFamily_) - : fontFamily(fontFamily_) - {} + : fontFamily(fontFamily_) {} - bool isConfigured() const { - return bool(fontFamily); - } + bool isConfigured() const { return bool(fontFamily); } PremultipliedImage drawGlyphBitmap(const FontStack& fontStack, GlyphID glyphID) { bool bold = false; @@ -92,11 +97,10 @@ class LocalGlyphRasterizer::Impl { LocalGlyphRasterizer::LocalGlyphRasterizer(const std::optional& fontFamily) : impl(std::make_unique(fontFamily)) {} -LocalGlyphRasterizer::~LocalGlyphRasterizer() -{} +LocalGlyphRasterizer::~LocalGlyphRasterizer() {} bool LocalGlyphRasterizer::canRasterizeGlyph(const FontStack&, GlyphID glyphID) { - return util::i18n::allowsFixedWidthGlyphGeneration(glyphID) && impl->isConfigured(); + return util::i18n::allowsFixedWidthGlyphGeneration(glyphID) && impl->isConfigured(); } Glyph LocalGlyphRasterizer::rasterizeGlyph(const FontStack& fontStack, GlyphID glyphID) { @@ -120,9 +124,10 @@ Glyph LocalGlyphRasterizer::rasterizeGlyph(const FontStack& fontStack, GlyphID g // Copy alpha values from RGBA bitmap into the AlphaImage output fixedMetrics.bitmap = AlphaImage(size); for (uint32_t i = 0; i < size.width * size.height; i++) { - fixedMetrics.bitmap.data[i] = - 0xff - round(0.2126 * rgbaBitmap.data[4 * i] + 0.7152 * rgbaBitmap.data[4 * i + 1] + - 0.0722 * rgbaBitmap.data[4 * i + 2]); + fixedMetrics.bitmap.data[i] = 0xff - round( + 0.2126 * rgbaBitmap.data[4 * i] + 0.7152 * rgbaBitmap.data[4 * i + 1] + + 0.0722 * rgbaBitmap.data[4 * i + 2] + ); } return fixedMetrics; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.cpp index fa5c9730afe..47712ea2907 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.cpp @@ -3,7 +3,9 @@ namespace mbgl { namespace android { -jni::Local> DefaultStyle::New(jni::JNIEnv& env, const mbgl::util::DefaultStyle& jDefaultStyle) { +jni::Local> DefaultStyle::New( + jni::JNIEnv& env, const mbgl::util::DefaultStyle& jDefaultStyle +) { static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); return javaClass.New( @@ -11,12 +13,13 @@ jni::Local> DefaultStyle::New(jni::JNIEnv& env, const constructor, jni::Make(env, jDefaultStyle.getUrl()), jni::Make(env, jDefaultStyle.getName()), - jDefaultStyle.getCurrentVersion()); + jDefaultStyle.getCurrentVersion() + ); } mbgl::util::DefaultStyle DefaultStyle::getDefaultStyle(jni::JNIEnv& env, const jni::Object& options) { static auto& javaClass = jni::Class::Singleton(env); - return mbgl::util::DefaultStyle ( + return mbgl::util::DefaultStyle( jni::Make(env, options.Get(env, javaClass.GetField(env, "url"))), jni::Make(env, options.Get(env, javaClass.GetField(env, "name"))), options.Get(env, javaClass.GetField(env, "version")) diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.hpp index 5b788361f75..ba5352d6ab8 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.hpp @@ -10,16 +10,13 @@ namespace android { class DefaultStyle : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/util/DefaultStyle"; }; static jni::Local> New(jni::JNIEnv&, const mbgl::util::DefaultStyle&); static mbgl::util::DefaultStyle getDefaultStyle(jni::JNIEnv&, const jni::Object&); static void registerNative(jni::JNIEnv&); - }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.cpp index 339c6e6636a..4df2d2ed588 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.cpp @@ -3,21 +3,42 @@ namespace mbgl { namespace android { -jni::Local> TileServerOptions::New(jni::JNIEnv& env, const mbgl::TileServerOptions& tileServerOptions) { +jni::Local> TileServerOptions::New( + jni::JNIEnv& env, const mbgl::TileServerOptions& tileServerOptions +) { static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor< - jni::String, jni::String, jni::String, jni::String, jni::String, jni::String, - jni::String, jni::String, jni::String, jni::String, jni::String, - jni::String, jni::String, jni::String, jni::String, jni::String, - jni::String, jni::String, jni::jboolean, jni::String, jni::Array>>(env); - + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::String, + jni::jboolean, + jni::String, + jni::Array>>(env); + std::optional sourceVersionPrefixValue = tileServerOptions.sourceVersionPrefix(); std::optional styleVersionPrefixValue = tileServerOptions.styleVersionPrefix(); std::optional spritesVersionPrefixValue = tileServerOptions.spritesVersionPrefix(); std::optional glyphsVersionPrefixValue = tileServerOptions.glyphsVersionPrefix(); std::optional tileVersionPrefixValue = tileServerOptions.tileVersionPrefix(); - return javaClass.New(env, constructor, + return javaClass.New( + env, + constructor, jni::Make(env, tileServerOptions.baseURL()), jni::Make(env, tileServerOptions.uriSchemeAlias()), jni::Make(env, tileServerOptions.sourceTemplate()), @@ -42,9 +63,10 @@ jni::Local> TileServerOptions::New(jni::JNIEnv& e ); } -jni::Local>> TileServerOptions::NewStyles(jni::JNIEnv& env, const std::vector &nativeStyles) { - - auto retVal = jni::Array>::New(env, nativeStyles.size()); +jni::Local>> TileServerOptions::NewStyles( + jni::JNIEnv& env, const std::vector& nativeStyles +) { + auto retVal = jni::Array>::New(env, nativeStyles.size()); for (auto it = begin(nativeStyles); it != end(nativeStyles); ++it) { auto converted = DefaultStyle::New(env, *it); retVal.Set(env, it - nativeStyles.begin(), converted); @@ -53,27 +75,37 @@ jni::Local>> TileServerOptions::NewStyles(j return retVal; } -jni::Local> TileServerOptions::DefaultConfiguration(jni::JNIEnv& env, const jni::Class& jOptions) { +jni::Local> TileServerOptions::DefaultConfiguration( + jni::JNIEnv& env, const jni::Class& jOptions +) { auto options = mbgl::TileServerOptions::DefaultConfiguration(); return TileServerOptions::New(env, options); } -jni::Local> TileServerOptions::MapboxConfiguration(jni::JNIEnv& env, const jni::Class& jOptions) { +jni::Local> TileServerOptions::MapboxConfiguration( + jni::JNIEnv& env, const jni::Class& jOptions +) { auto options = mbgl::TileServerOptions::MapboxConfiguration(); return TileServerOptions::New(env, options); } -jni::Local> TileServerOptions::MapTilerConfiguration(jni::JNIEnv& env, const jni::Class& jOptions) { +jni::Local> TileServerOptions::MapTilerConfiguration( + jni::JNIEnv& env, const jni::Class& jOptions +) { auto options = mbgl::TileServerOptions::MapTilerConfiguration(); return TileServerOptions::New(env, options); } -jni::Local> TileServerOptions::MapLibreConfiguration(jni::JNIEnv& env, const jni::Class& jOptions) { +jni::Local> TileServerOptions::MapLibreConfiguration( + jni::JNIEnv& env, const jni::Class& jOptions +) { auto options = mbgl::TileServerOptions::MapLibreConfiguration(); return TileServerOptions::New(env, options); } -mbgl::TileServerOptions TileServerOptions::getTileServerOptions(jni::JNIEnv& env, const jni::Object& options) { +mbgl::TileServerOptions TileServerOptions::getTileServerOptions( + jni::JNIEnv& env, const jni::Object& options +) { auto opts = mbgl::TileServerOptions(); static auto& javaClass = jni::Class::Singleton(env); @@ -107,43 +139,51 @@ mbgl::TileServerOptions TileServerOptions::getTileServerOptions(jni::JNIEnv& env static auto defaultStyleField = javaClass.GetField(env, "defaultStyle"); static auto defaultStylesField = javaClass.GetField>>(env, "defaultStyles"); - std::vector defaultStyles = TileServerOptions::getDefaultStyles(env, options.Get(env, defaultStylesField)); + std::vector defaultStyles = TileServerOptions::getDefaultStyles( + env, options.Get(env, defaultStylesField) + ); auto retVal = mbgl::TileServerOptions() - .withBaseURL(jni::Make(env, options.Get(env, baseURLField))) - .withUriSchemeAlias(jni::Make(env, options.Get(env, uriSchemeAliasField))) - .withApiKeyParameterName(jni::Make(env, options.Get(env, apiKeyParameterNameField))) - .setRequiresApiKey(options.Get(env, apiKeyRequiredField)); - + .withBaseURL(jni::Make(env, options.Get(env, baseURLField))) + .withUriSchemeAlias(jni::Make(env, options.Get(env, uriSchemeAliasField))) + .withApiKeyParameterName(jni::Make(env, options.Get(env, apiKeyParameterNameField))) + .setRequiresApiKey(options.Get(env, apiKeyRequiredField)); + auto sourcePrefixValue = options.Get(env, sourceVersionPrefixField); retVal.withSourceTemplate( jni::Make(env, options.Get(env, sourceTemplateField)), jni::Make(env, options.Get(env, sourceDomainNameField)), - sourcePrefixValue ? jni::Make(env, sourcePrefixValue): std::optional{}); + sourcePrefixValue ? jni::Make(env, sourcePrefixValue) : std::optional{} + ); auto styleVersionPrefixValue = options.Get(env, styleVersionPrefixField); retVal.withStyleTemplate( jni::Make(env, options.Get(env, styleTemplateField)), jni::Make(env, options.Get(env, styleDomainNameField)), - styleVersionPrefixValue ? jni::Make(env, styleVersionPrefixValue): std::optional{}); + styleVersionPrefixValue ? jni::Make(env, styleVersionPrefixValue) : std::optional{} + ); auto spritesVersionPrefixValue = options.Get(env, spritesVersionPrefixField); retVal.withSpritesTemplate( - jni::Make(env, options.Get(env, spritesTemplateField)), - jni::Make(env, options.Get(env, spritesDomainNameField)), - spritesVersionPrefixValue ? jni::Make(env, spritesVersionPrefixValue): std::optional{}); + jni::Make(env, options.Get(env, spritesTemplateField)), + jni::Make(env, options.Get(env, spritesDomainNameField)), + spritesVersionPrefixValue ? jni::Make(env, spritesVersionPrefixValue) + : std::optional{} + ); - auto glyphsVersionPrefixValue = options.Get(env, glyphsVersionPrefixField); + auto glyphsVersionPrefixValue = options.Get(env, glyphsVersionPrefixField); retVal.withGlyphsTemplate( - jni::Make(env, options.Get(env, glyphsTemplateField)), - jni::Make(env, options.Get(env, glyphsDomainNameField)), - glyphsVersionPrefixValue ? jni::Make(env, glyphsVersionPrefixValue) : std::optional{}); + jni::Make(env, options.Get(env, glyphsTemplateField)), + jni::Make(env, options.Get(env, glyphsDomainNameField)), + glyphsVersionPrefixValue ? jni::Make(env, glyphsVersionPrefixValue) : std::optional{} + ); - auto tileVersionPrefixValue = options.Get(env, tileVersionPrefixField); + auto tileVersionPrefixValue = options.Get(env, tileVersionPrefixField); retVal.withTileTemplate( - jni::Make(env, options.Get(env, tileTemplateField)), - jni::Make(env, options.Get(env, tileDomainNameField)), - tileVersionPrefixValue ? jni::Make(env, tileVersionPrefixValue): std::optional{}); + jni::Make(env, options.Get(env, tileTemplateField)), + jni::Make(env, options.Get(env, tileDomainNameField)), + tileVersionPrefixValue ? jni::Make(env, tileVersionPrefixValue) : std::optional{} + ); retVal.withDefaultStyle(jni::Make(env, options.Get(env, defaultStyleField))); retVal.withDefaultStyles(defaultStyles); @@ -151,11 +191,12 @@ mbgl::TileServerOptions TileServerOptions::getTileServerOptions(jni::JNIEnv& env return retVal; } -std::vector TileServerOptions::getDefaultStyles(jni::JNIEnv& env, const jni::Array>& styles_) { - +std::vector TileServerOptions::getDefaultStyles( + jni::JNIEnv& env, const jni::Array>& styles_ +) { std::size_t length = styles_.Length(env); std::vector convertedStyles; - //convertedStyles.reserve(length); + // convertedStyles.reserve(length); for (std::size_t i = 0; i < length; i++) { mbgl::util::DefaultStyle converted = DefaultStyle::getDefaultStyle(env, styles_.Get(env, i)); convertedStyles.push_back(converted); @@ -166,12 +207,22 @@ std::vector TileServerOptions::getDefaultStyles(jni::J void TileServerOptions::registerNative(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - jni::RegisterNatives(env, - *javaClass, - jni::MakeNativeMethod("defaultConfiguration"), - jni::MakeNativeMethod("mapboxConfiguration"), - jni::MakeNativeMethod("mapTilerConfiguration"), - jni::MakeNativeMethod("mapLibreConfiguration")); + jni::RegisterNatives( + env, + *javaClass, + jni::MakeNativeMethod< + decltype(&TileServerOptions::DefaultConfiguration), + &TileServerOptions::DefaultConfiguration>("defaultConfiguration"), + jni::MakeNativeMethod< + decltype(&TileServerOptions::MapboxConfiguration), + &TileServerOptions::MapboxConfiguration>("mapboxConfiguration"), + jni::MakeNativeMethod< + decltype(&TileServerOptions::MapTilerConfiguration), + &TileServerOptions::MapTilerConfiguration>("mapTilerConfiguration"), + jni::MakeNativeMethod< + decltype(&TileServerOptions::MapLibreConfiguration), + &TileServerOptions::MapLibreConfiguration>("mapLibreConfiguration") + ); } } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.hpp index 310580871ff..a8d2538cd70 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.hpp @@ -13,26 +13,29 @@ namespace android { class TileServerOptions : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/util/TileServerOptions"; }; static jni::Local> New(jni::JNIEnv&, const mbgl::TileServerOptions&); - static jni::Local> DefaultConfiguration(jni::JNIEnv&, const jni::Class&); - static jni::Local> MapboxConfiguration(jni::JNIEnv&, const jni::Class&); - static jni::Local> MapTilerConfiguration(jni::JNIEnv&, const jni::Class&); - static jni::Local> MapLibreConfiguration(jni::JNIEnv&, const jni::Class&); + static jni::Local> + DefaultConfiguration(jni::JNIEnv&, const jni::Class&); + static jni::Local> + MapboxConfiguration(jni::JNIEnv&, const jni::Class&); + static jni::Local> + MapTilerConfiguration(jni::JNIEnv&, const jni::Class&); + static jni::Local> + MapLibreConfiguration(jni::JNIEnv&, const jni::Class&); static mbgl::TileServerOptions getTileServerOptions(jni::JNIEnv&, const jni::Object&); - - static void registerNative(jni::JNIEnv&); - static jni::Local>> NewStyles(jni::JNIEnv& env, const std::vector &); - static std::vector getDefaultStyles(jni::JNIEnv& env, const jni::Array>& styles_); - + static void registerNative(jni::JNIEnv&); + static jni::Local>> + NewStyles(jni::JNIEnv& env, const std::vector&); + static std::vector getDefaultStyles( + jni::JNIEnv& env, const jni::Array>& styles_ + ); }; - } // namespace android } // namespace mbgl diff --git a/platform/android/src/async_task.cpp b/platform/android/src/async_task.cpp index 0a4d90a275f..cef046bd993 100644 --- a/platform/android/src/async_task.cpp +++ b/platform/android/src/async_task.cpp @@ -12,8 +12,8 @@ namespace util { class AsyncTask::Impl : public RunLoop::Impl::Runnable { public: Impl(std::function&& fn) - : queued(true), task(std::move(fn)) { - } + : queued(true), + task(std::move(fn)) {} ~Impl() { queued = true; @@ -27,9 +27,7 @@ class AsyncTask::Impl : public RunLoop::Impl::Runnable { } } - TimePoint dueTime() const override { - return due; - } + TimePoint dueTime() const override { return due; } void runTask() override { if (!queued) { @@ -52,8 +50,7 @@ class AsyncTask::Impl : public RunLoop::Impl::Runnable { }; AsyncTask::AsyncTask(std::function&& fn) - : impl(std::make_unique(std::move(fn))) { -} + : impl(std::make_unique(std::move(fn))) {} AsyncTask::~AsyncTask() = default; diff --git a/platform/android/src/attach_env.cpp b/platform/android/src/attach_env.cpp index 6da075ee3e1..f07f5afc34e 100644 --- a/platform/android/src/attach_env.cpp +++ b/platform/android/src/attach_env.cpp @@ -9,14 +9,14 @@ UniqueEnv AttachEnv() { jint err = theJVM->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); switch (err) { - case JNI_OK: - return UniqueEnv(env, JNIEnvDeleter(*theJVM, false)); - case JNI_EDETACHED: - return UniqueEnv(jni::AttachCurrentThread(*theJVM).release(), JNIEnvDeleter(*theJVM, true)); - default: - throw std::system_error(err, jni::ErrorCategory()); + case JNI_OK: + return UniqueEnv(env, JNIEnvDeleter(*theJVM, false)); + case JNI_EDETACHED: + return UniqueEnv(jni::AttachCurrentThread(*theJVM).release(), JNIEnvDeleter(*theJVM, true)); + default: + throw std::system_error(err, jni::ErrorCategory()); } } -} -} +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/attach_env.hpp b/platform/android/src/attach_env.hpp index 8a9f4a7f8b2..03c03dd5c41 100644 --- a/platform/android/src/attach_env.hpp +++ b/platform/android/src/attach_env.hpp @@ -13,19 +13,20 @@ class JNIEnvDeleter { public: JNIEnvDeleter() = default; JNIEnvDeleter(jni::JavaVM& v, bool d) - : vm(&v), detach(d) {} + : vm(&v), + detach(d) {} void operator()(jni::JNIEnv* p) const { if (p && detach) { - assert(vm); - vm->DetachCurrentThread(); + assert(vm); + vm->DetachCurrentThread(); } - } + } }; using UniqueEnv = std::unique_ptr; UniqueEnv AttachEnv(); -} -} +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/bitmap.cpp b/platform/android/src/bitmap.cpp index eb7c676b12b..51e0dfc3ffc 100644 --- a/platform/android/src/bitmap.cpp +++ b/platform/android/src/bitmap.cpp @@ -8,9 +8,10 @@ namespace android { class PixelGuard { public: - PixelGuard(jni::JNIEnv& env_, const jni::Object& bitmap_) : env(env_), bitmap(bitmap_) { - const int result = AndroidBitmap_lockPixels(&env, jni::Unwrap(*bitmap), - reinterpret_cast(&address)); + PixelGuard(jni::JNIEnv& env_, const jni::Object& bitmap_) + : env(env_), + bitmap(bitmap_) { + const int result = AndroidBitmap_lockPixels(&env, jni::Unwrap(*bitmap), reinterpret_cast(&address)); if (result != ANDROID_BITMAP_RESULT_SUCCESS) { throw std::runtime_error("bitmap decoding: could not lock pixels"); } @@ -23,9 +24,7 @@ class PixelGuard { } } - auto* get() { - return address; - } + auto* get() { return address; } private: jni::JNIEnv& env; @@ -36,16 +35,16 @@ class PixelGuard { jni::Local> Bitmap::Config::Create(jni::JNIEnv& env, Value value) { static auto& _class = jni::Class::Singleton(env); switch (value) { - case ALPHA_8: - return _class.Get(env, _class.GetStaticField>(env, "ALPHA_8")); - case ARGB_4444: - return _class.Get(env, _class.GetStaticField>(env, "ARGB_4444")); - case ARGB_8888: - return _class.Get(env, _class.GetStaticField>(env, "ARGB_8888")); - case RGB_565: - return _class.Get(env, _class.GetStaticField>(env, "RGB_565")); - default: - throw std::runtime_error("invalid enum value for Bitmap.Config"); + case ALPHA_8: + return _class.Get(env, _class.GetStaticField>(env, "ALPHA_8")); + case ARGB_4444: + return _class.Get(env, _class.GetStaticField>(env, "ARGB_4444")); + case ARGB_8888: + return _class.Get(env, _class.GetStaticField>(env, "ARGB_8888")); + case RGB_565: + return _class.Get(env, _class.GetStaticField>(env, "RGB_565")); + default: + throw std::runtime_error("invalid enum value for Bitmap.Config"); } } @@ -54,12 +53,13 @@ void Bitmap::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } -jni::Local> Bitmap::CreateBitmap(jni::JNIEnv& env, - jni::jint width, - jni::jint height, - const jni::Object& config) { +jni::Local> Bitmap::CreateBitmap( + jni::JNIEnv& env, jni::jint width, jni::jint height, const jni::Object& config +) { static auto& _class = jni::Class::Singleton(env); - static auto method = _class.GetStaticMethod (jni::jint, jni::jint, jni::Object)>(env, "createBitmap"); + static auto method = _class.GetStaticMethod(jni::jint, jni::jint, jni::Object)>( + env, "createBitmap" + ); return _class.Call(env, method, width, height, config); } @@ -77,15 +77,17 @@ PremultipliedImage Bitmap::GetImage(jni::JNIEnv& env, const jni::Object& PixelGuard guard(env, bitmap); // Copy the Android Bitmap into the PremultipliedImage. - auto pixels = - std::make_unique(info.width * info.height * PremultipliedImage::channels); + auto pixels = std::make_unique(info.width * info.height * PremultipliedImage::channels); for (uint32_t y = 0; y < info.height; y++) { auto begin = guard.get() + y * info.stride; - std::copy(begin, begin + info.width * PremultipliedImage::channels, - pixels.get() + y * info.width * PremultipliedImage::channels); + std::copy( + begin, + begin + info.width * PremultipliedImage::channels, + pixels.get() + y * info.width * PremultipliedImage::channels + ); } - return { Size{ info.width, info.height }, std::move(pixels) }; + return {Size{info.width, info.height}, std::move(pixels)}; } jni::Local> Bitmap::CreateBitmap(jni::JNIEnv& env, const PremultipliedImage& image) { @@ -115,7 +117,7 @@ jni::Local> Bitmap::CreateBitmap(jni::JNIEnv& env, const Pre jni::Local> Bitmap::Copy(jni::JNIEnv& env, const jni::Object& bitmap) { static auto& klass = jni::Class::Singleton(env); - static auto copy = klass.GetMethod (jni::Object, jni::jboolean)>(env, "copy"); + static auto copy = klass.GetMethod(jni::Object, jni::jboolean)>(env, "copy"); return bitmap.Call(env, copy, Bitmap::Config::Create(env, Bitmap::Config::Value::ARGB_8888), jni::jni_false); } diff --git a/platform/android/src/bitmap.hpp b/platform/android/src/bitmap.hpp index 9d96405c26d..a6ea72ca7e2 100644 --- a/platform/android/src/bitmap.hpp +++ b/platform/android/src/bitmap.hpp @@ -29,8 +29,9 @@ class Bitmap { static jni::Local> CreateBitmap(jni::JNIEnv&, jni::jint width, jni::jint height, const jni::Object&); - static jni::Local> - CreateBitmap(jni::JNIEnv& env, jni::jint width, jni::jint height, Config::Value config) { + static jni::Local> CreateBitmap( + jni::JNIEnv& env, jni::jint width, jni::jint height, Config::Value config + ) { return CreateBitmap(env, width, height, Config::Create(env, config)); } diff --git a/platform/android/src/bitmap_factory.cpp b/platform/android/src/bitmap_factory.cpp index 170bd52ea5a..0eb7604f1e4 100644 --- a/platform/android/src/bitmap_factory.cpp +++ b/platform/android/src/bitmap_factory.cpp @@ -7,15 +7,14 @@ void BitmapFactory::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } -jni::Local> BitmapFactory::DecodeByteArray(jni::JNIEnv& env, - jni::Array& data, - jni::jint offset, - jni::jint length) { +jni::Local> BitmapFactory::DecodeByteArray( + jni::JNIEnv& env, jni::Array& data, jni::jint offset, jni::jint length +) { static auto& _class = jni::Class::Singleton(env); // Images are loaded with ARGB_8888 config, and premultiplied by default, which is exactly // what we want, so we're not providing a BitmapFactory.Options object. - using Signature = jni::Object (jni::Array, jni::jint, jni::jint); + using Signature = jni::Object(jni::Array, jni::jint, jni::jint); static auto method = _class.GetStaticMethod(env, "decodeByteArray"); return _class.Call(env, method, data, offset, length); diff --git a/platform/android/src/bitmap_factory.hpp b/platform/android/src/bitmap_factory.hpp index f73b7a29067..7e924f77fd7 100644 --- a/platform/android/src/bitmap_factory.hpp +++ b/platform/android/src/bitmap_factory.hpp @@ -12,8 +12,9 @@ class BitmapFactory { static constexpr auto Name() { return "android/graphics/BitmapFactory"; }; static void registerNative(jni::JNIEnv&); - static jni::Local> - DecodeByteArray(jni::JNIEnv&, jni::Array& data, jni::jint offset, jni::jint length); + static jni::Local> DecodeByteArray( + jni::JNIEnv&, jni::Array& data, jni::jint offset, jni::jint length + ); }; } // namespace android diff --git a/platform/android/src/example_custom_layer.cpp b/platform/android/src/example_custom_layer.cpp index 159df486595..1c6be86cfc5 100644 --- a/platform/android/src/example_custom_layer.cpp +++ b/platform/android/src/example_custom_layer.cpp @@ -6,9 +6,9 @@ // DEBUGGING -const char* LOG_TAG = "Custom Layer Example"; +const char *LOG_TAG = "Custom Layer Example"; -const char* stringFromError(GLenum err) { +const char *stringFromError(GLenum err) { switch (err) { case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; @@ -27,22 +27,22 @@ const char* stringFromError(GLenum err) { #ifdef GL_TABLE_TOO_LARGE case GL_TABLE_TOO_LARGE: - return "GL_TABLE_TOO_LARGE"; + return "GL_TABLE_TOO_LARGE"; #endif #ifdef GL_STACK_OVERFLOW case GL_STACK_OVERFLOW: - return "GL_STACK_OVERFLOW"; + return "GL_STACK_OVERFLOW"; #endif #ifdef GL_STACK_UNDERFLOW case GL_STACK_UNDERFLOW: - return "GL_STACK_UNDERFLOW"; + return "GL_STACK_UNDERFLOW"; #endif #ifdef GL_CONTEXT_LOST case GL_CONTEXT_LOST: - return "GL_CONTEXT_LOST"; + return "GL_CONTEXT_LOST"; #endif default: @@ -55,11 +55,10 @@ struct Error : std::runtime_error { }; void checkError(const char *cmd, const char *file, int line) { - GLenum err = GL_NO_ERROR; if ((err = glGetError()) != GL_NO_ERROR) { std::ostringstream message; - message << cmd << ": Error " << stringFromError(err); + message << cmd << ": Error " << stringFromError(err); // Check for further errors while ((err = glGetError()) != GL_NO_ERROR) { @@ -73,7 +72,13 @@ void checkError(const char *cmd, const char *file, int line) { } #ifndef NDEBUG -#define GL_CHECK_ERROR(cmd) ([&]() { struct __MBGL_C_E { ~__MBGL_C_E() noexcept(false) { checkError(#cmd, __FILE__, __LINE__); } } __MBGL_C_E; return cmd; }()) +#define GL_CHECK_ERROR(cmd) \ + ([&]() { \ + struct __MBGL_C_E { \ + ~__MBGL_C_E() noexcept(false) { checkError(#cmd, __FILE__, __LINE__); } \ + } __MBGL_C_E; \ + return cmd; \ + }()) #else #define GL_CHECK_ERROR(cmd) (cmd) #endif @@ -89,7 +94,6 @@ void checkLinkStatus(GLuint program) { __android_log_write(ANDROID_LOG_ERROR, LOG_TAG, &infoLog[0]); throw Error(infoLog); } - } void checkCompileStatus(GLuint shader) { @@ -109,13 +113,14 @@ void checkCompileStatus(GLuint shader) { // /DEBUGGING -static const GLchar * vertexShaderSource = "#version 300 es\nlayout (location = 0) in vec2 a_pos; void main() { gl_Position = vec4(a_pos, 0, 1); }"; -static const GLchar * fragmentShaderSource = "#version 300 es\nuniform highp vec4 fill_color; out highp vec4 fragColor; void main() { fragColor = fill_color; }"; +static const GLchar *vertexShaderSource = + "#version 300 es\nlayout (location = 0) in vec2 a_pos; void main() { gl_Position = vec4(a_pos, 0, 1); }"; +static const GLchar *fragmentShaderSource = + "#version 300 es\nuniform highp vec4 fill_color; out highp vec4 fragColor; void main() { fragColor = fill_color; }"; -class ExampleCustomLayer: mbgl::style::CustomLayerHost { +class ExampleCustomLayer : mbgl::style::CustomLayerHost { public: - ~ExampleCustomLayer() { - } + ~ExampleCustomLayer() {} void initialize() { __android_log_write(ANDROID_LOG_INFO, LOG_TAG, "Initialize"); @@ -143,13 +148,13 @@ class ExampleCustomLayer: mbgl::style::CustomLayerHost { a_pos = GL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); fill_color = GL_CHECK_ERROR(glGetUniformLocation(program, "fill_color")); - GLfloat background[] = { -1, -1, 1, -1, -1, 1, 1, 1 }; + GLfloat background[] = {-1, -1, 1, -1, -1, 1, 1, 1}; GL_CHECK_ERROR(glGenBuffers(1, &buffer)); GL_CHECK_ERROR(glBindBuffer(GL_ARRAY_BUFFER, buffer)); GL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), background, GL_STATIC_DRAW)); } - void render(const mbgl::style::CustomLayerRenderParameters&) { + void render(const mbgl::style::CustomLayerRenderParameters &) { __android_log_write(ANDROID_LOG_INFO, LOG_TAG, "Render"); glUseProgram(program); glBindBuffer(GL_ARRAY_BUFFER, buffer); @@ -167,7 +172,6 @@ class ExampleCustomLayer: mbgl::style::CustomLayerHost { GL_CHECK_ERROR(glDisable(GL_DEPTH_TEST)); GL_CHECK_ERROR(glUniform4fv(fill_color, 1, color)); GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)); - } void contextLost() { @@ -197,15 +201,15 @@ class ExampleCustomLayer: mbgl::style::CustomLayerHost { static GLfloat color[]; }; -GLfloat ExampleCustomLayer::color[] = { 0.0f, 1.0f, 0.0f, 1.0f }; +GLfloat ExampleCustomLayer::color[] = {0.0f, 1.0f, 0.0f, 1.0f}; -jlong JNICALL nativeCreateContext(JNIEnv*, jobject) { +jlong JNICALL nativeCreateContext(JNIEnv *, jobject) { __android_log_write(ANDROID_LOG_INFO, LOG_TAG, "nativeCreateContext"); auto exampleCustomLayer = std::make_unique(); return reinterpret_cast(exampleCustomLayer.release()); } -void JNICALL nativeSetColor(JNIEnv*, jobject, jfloat red, jfloat green, jfloat blue, jfloat alpha) { +void JNICALL nativeSetColor(JNIEnv *, jobject, jfloat red, jfloat green, jfloat blue, jfloat alpha) { __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "nativeSetColor: %.2f, %.2f, %.2f, %.2f", red, green, blue, alpha); ExampleCustomLayer::color[0] = red; ExampleCustomLayer::color[1] = green; @@ -223,8 +227,7 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { JNINativeMethod methods[] = { {"createContext", "()J", reinterpret_cast(&nativeCreateContext)}, - {"setColor", "(FFFF)V", reinterpret_cast(&nativeSetColor)} - }; + {"setColor", "(FFFF)V", reinterpret_cast(&nativeSetColor)}}; if (env->RegisterNatives(customLayerClass, methods, 2) < 0) { env->ExceptionDescribe(); @@ -234,5 +237,4 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { return JNI_VERSION_1_6; } -extern "C" JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *, void *) { -} +extern "C" JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *, void *) {} diff --git a/platform/android/src/gl_functions.cpp b/platform/android/src/gl_functions.cpp index de72ba38b27..de0328d311f 100644 --- a/platform/android/src/gl_functions.cpp +++ b/platform/android/src/gl_functions.cpp @@ -7,255 +7,270 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = ::glActiveTexture; -void (* const glAttachShader)(GLuint, GLuint) = ::glAttachShader; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *) = ::glBindAttribLocation; -void (* const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; -void (* const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; -void (* const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; -void (* const glBindTexture)(GLenum, GLuint) = ::glBindTexture; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; -void (* const glBlendEquation)(GLenum) = ::glBlendEquation; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; -void (* const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; -void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum) = ::glBufferData; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *) = ::glBufferSubData; -GLenum (* const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; -void (* const glClear)(GLbitfield) = ::glClear; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; -void (* const glClearDepthf)(GLfloat) = ::glClearDepthf; -void (* const glClearStencil)(GLint) = ::glClearStencil; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; -void (* const glCompileShader)(GLuint) = ::glCompileShader; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *) = ::glCompressedTexImage2D; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *) = ::glCompressedTexSubImage2D; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; -GLuint (* const glCreateProgram)() = ::glCreateProgram; -GLuint (* const glCreateShader)(GLenum) = ::glCreateShader; -void (* const glCullFace)(GLenum) = ::glCullFace; -void (* const glDeleteBuffers)(GLsizei, const GLuint *) = ::glDeleteBuffers; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint *) = ::glDeleteFramebuffers; -void (* const glDeleteProgram)(GLuint) = ::glDeleteProgram; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *) = ::glDeleteRenderbuffers; -void (* const glDeleteShader)(GLuint) = ::glDeleteShader; -void (* const glDeleteTextures)(GLsizei, const GLuint *) = ::glDeleteTextures; -void (* const glDepthFunc)(GLenum) = ::glDepthFunc; -void (* const glDepthMask)(GLboolean) = ::glDepthMask; -void (* const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; -void (* const glDetachShader)(GLuint, GLuint) = ::glDetachShader; -void (* const glDisable)(GLenum) = ::glDisable; -void (* const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *) = ::glDrawElements; -void (* const glEnable)(GLenum) = ::glEnable; -void (* const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; -void (* const glFinish)() = ::glFinish; -void (* const glFlush)() = ::glFlush; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; -void (* const glFrontFace)(GLenum) = ::glFrontFace; -void (* const glGenBuffers)(GLsizei, GLuint *) = ::glGenBuffers; -void (* const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; -void (* const glGenFramebuffers)(GLsizei, GLuint *) = ::glGenFramebuffers; -void (* const glGenRenderbuffers)(GLsizei, GLuint *) = ::glGenRenderbuffers; -void (* const glGenTextures)(GLsizei, GLuint *) = ::glGenTextures; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveAttrib; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveUniform; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *) = ::glGetAttachedShaders; -GLint (* const glGetAttribLocation)(GLuint, const GLchar *) = ::glGetAttribLocation; -void (* const glGetBooleanv)(GLenum, GLboolean *) = ::glGetBooleanv; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetBufferParameteriv; -GLenum (* const glGetError)() = ::glGetError; -void (* const glGetFloatv)(GLenum, GLfloat *) = ::glGetFloatv; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *) = ::glGetFramebufferAttachmentParameteriv; -void (* const glGetIntegerv)(GLenum, GLint *) = ::glGetIntegerv; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetProgramInfoLog; -void (* const glGetProgramiv)(GLuint, GLenum, GLint *) = ::glGetProgramiv; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetRenderbufferParameteriv; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderInfoLog; -void (* const glGetShaderiv)(GLuint, GLenum, GLint *) = ::glGetShaderiv; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *) = ::glGetShaderPrecisionFormat; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderSource; -const GLubyte *(* const glGetString)(GLenum) = ::glGetString; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *) = ::glGetTexParameterfv; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *) = ::glGetTexParameteriv; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat *) = ::glGetUniformfv; -void (* const glGetUniformiv)(GLuint, GLint, GLint *) = ::glGetUniformiv; -GLint (* const glGetUniformLocation)(GLuint, const GLchar *) = ::glGetUniformLocation; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *) = ::glGetVertexAttribfv; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribiv; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **) = ::glGetVertexAttribPointerv; -void (* const glHint)(GLenum, GLenum) = ::glHint; -GLboolean (* const glIsBuffer)(GLuint) = ::glIsBuffer; -GLboolean (* const glIsEnabled)(GLenum) = ::glIsEnabled; -GLboolean (* const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; -GLboolean (* const glIsProgram)(GLuint) = ::glIsProgram; -GLboolean (* const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; -GLboolean (* const glIsShader)(GLuint) = ::glIsShader; -GLboolean (* const glIsTexture)(GLuint) = ::glIsTexture; -void (* const glLineWidth)(GLfloat) = ::glLineWidth; -void (* const glLinkProgram)(GLuint) = ::glLinkProgram; -void (* const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; -void (* const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *) = ::glReadPixels; -void (* const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; -void (* const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; -void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei) = ::glShaderBinary; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *) = ::glShaderSource; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; -void (* const glStencilMask)(GLuint) = ::glStencilMask; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *) = ::glTexImage2D; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *) = ::glTexParameterfv; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint *) = ::glTexParameteriv; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *) = ::glTexSubImage2D; -void (* const glUniform1f)(GLint, GLfloat) = ::glUniform1f; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *) = ::glUniform1fv; -void (* const glUniform1i)(GLint, GLint) = ::glUniform1i; -void (* const glUniform1iv)(GLint, GLsizei, const GLint *) = ::glUniform1iv; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *) = ::glUniform2fv; -void (* const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; -void (* const glUniform2iv)(GLint, GLsizei, const GLint *) = ::glUniform2iv; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *) = ::glUniform3fv; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; -void (* const glUniform3iv)(GLint, GLsizei, const GLint *) = ::glUniform3iv; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *) = ::glUniform4fv; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; -void (* const glUniform4iv)(GLint, GLsizei, const GLint *) = ::glUniform4iv; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2fv; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3fv; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4fv; -void (* const glUseProgram)(GLuint) = ::glUseProgram; -void (* const glValidateProgram)(GLuint) = ::glValidateProgram; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat *) = ::glVertexAttrib1fv; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat *) = ::glVertexAttrib2fv; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat *) = ::glVertexAttrib3fv; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat *) = ::glVertexAttrib4fv; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *) = ::glVertexAttribPointer; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; +void (*const glActiveTexture)(GLenum) = ::glActiveTexture; +void (*const glAttachShader)(GLuint, GLuint) = ::glAttachShader; +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = ::glBindAttribLocation; +void (*const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; +void (*const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; +void (*const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; +void (*const glBindTexture)(GLenum, GLuint) = ::glBindTexture; +void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; +void (*const glBlendEquation)(GLenum) = ::glBlendEquation; +void (*const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; +void (*const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; +void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; +void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = ::glBufferData; +void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = ::glBufferSubData; +GLenum (*const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; +void (*const glClear)(GLbitfield) = ::glClear; +void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; +void (*const glClearDepthf)(GLfloat) = ::glClearDepthf; +void (*const glClearStencil)(GLint) = ::glClearStencil; +void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; +void (*const glCompileShader)(GLuint) = ::glCompileShader; +void (*const glCompressedTexImage2D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = ::glCompressedTexImage2D; +void (*const glCompressedTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = ::glCompressedTexSubImage2D; +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; +GLuint (*const glCreateProgram)() = ::glCreateProgram; +GLuint (*const glCreateShader)(GLenum) = ::glCreateShader; +void (*const glCullFace)(GLenum) = ::glCullFace; +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = ::glDeleteBuffers; +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = ::glDeleteFramebuffers; +void (*const glDeleteProgram)(GLuint) = ::glDeleteProgram; +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = ::glDeleteRenderbuffers; +void (*const glDeleteShader)(GLuint) = ::glDeleteShader; +void (*const glDeleteTextures)(GLsizei, const GLuint*) = ::glDeleteTextures; +void (*const glDepthFunc)(GLenum) = ::glDepthFunc; +void (*const glDepthMask)(GLboolean) = ::glDepthMask; +void (*const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; +void (*const glDetachShader)(GLuint, GLuint) = ::glDetachShader; +void (*const glDisable)(GLenum) = ::glDisable; +void (*const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; +void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = ::glDrawElements; +void (*const glEnable)(GLenum) = ::glEnable; +void (*const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; +void (*const glFinish)() = ::glFinish; +void (*const glFlush)() = ::glFlush; +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; +void (*const glFrontFace)(GLenum) = ::glFrontFace; +void (*const glGenBuffers)(GLsizei, GLuint*) = ::glGenBuffers; +void (*const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; +void (*const glGenFramebuffers)(GLsizei, GLuint*) = ::glGenFramebuffers; +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = ::glGenRenderbuffers; +void (*const glGenTextures)(GLsizei, GLuint*) = ::glGenTextures; +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveAttrib; +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveUniform; +void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = ::glGetAttachedShaders; +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = ::glGetAttribLocation; +void (*const glGetBooleanv)(GLenum, GLboolean*) = ::glGetBooleanv; +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetBufferParameteriv; +GLenum (*const glGetError)() = ::glGetError; +void (*const glGetFloatv)(GLenum, GLfloat*) = ::glGetFloatv; +void (*const glGetFramebufferAttachmentParameteriv +)(GLenum, GLenum, GLenum, GLint*) = ::glGetFramebufferAttachmentParameteriv; +void (*const glGetIntegerv)(GLenum, GLint*) = ::glGetIntegerv; +void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetProgramInfoLog; +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = ::glGetProgramiv; +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetRenderbufferParameteriv; +void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderInfoLog; +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = ::glGetShaderiv; +void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = ::glGetShaderPrecisionFormat; +void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderSource; +const GLubyte* (*const glGetString)(GLenum) = ::glGetString; +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = ::glGetTexParameterfv; +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = ::glGetTexParameteriv; +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = ::glGetUniformfv; +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = ::glGetUniformiv; +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = ::glGetUniformLocation; +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = ::glGetVertexAttribfv; +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribiv; +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = ::glGetVertexAttribPointerv; +void (*const glHint)(GLenum, GLenum) = ::glHint; +GLboolean (*const glIsBuffer)(GLuint) = ::glIsBuffer; +GLboolean (*const glIsEnabled)(GLenum) = ::glIsEnabled; +GLboolean (*const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; +GLboolean (*const glIsProgram)(GLuint) = ::glIsProgram; +GLboolean (*const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; +GLboolean (*const glIsShader)(GLuint) = ::glIsShader; +GLboolean (*const glIsTexture)(GLuint) = ::glIsTexture; +void (*const glLineWidth)(GLfloat) = ::glLineWidth; +void (*const glLinkProgram)(GLuint) = ::glLinkProgram; +void (*const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; +void (*const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = ::glReadPixels; +void (*const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; +void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; +void (*const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = ::glShaderBinary; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = ::glShaderSource; +void (*const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; +void (*const glStencilMask)(GLuint) = ::glStencilMask; +void (*const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; +void (*const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; +void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; +void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = ::glTexImage2D; +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = ::glTexParameterfv; +void (*const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = ::glTexParameteriv; +void (*const glTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = ::glTexSubImage2D; +void (*const glUniform1f)(GLint, GLfloat) = ::glUniform1f; +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = ::glUniform1fv; +void (*const glUniform1i)(GLint, GLint) = ::glUniform1i; +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = ::glUniform1iv; +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = ::glUniform2fv; +void (*const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = ::glUniform2iv; +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = ::glUniform3fv; +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = ::glUniform3iv; +void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = ::glUniform4fv; +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = ::glUniform4iv; +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2fv; +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3fv; +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4fv; +void (*const glUseProgram)(GLuint) = ::glUseProgram; +void (*const glValidateProgram)(GLuint) = ::glValidateProgram; +void (*const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = ::glVertexAttrib1fv; +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = ::glVertexAttrib2fv; +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = ::glVertexAttrib3fv; +void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = ::glVertexAttrib4fv; +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = ::glVertexAttribPointer; +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = ::glReadBuffer; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *) = ::glDrawRangeElements; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *) = ::glTexImage3D; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *) = ::glTexSubImage3D; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage3D; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *) = ::glCompressedTexImage3D; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *) = ::glCompressedTexSubImage3D; -void (* const glGenQueries)(GLsizei, GLuint *) = ::glGenQueries; -void (* const glDeleteQueries)(GLsizei, const GLuint *) = ::glDeleteQueries; -GLboolean (* const glIsQuery)(GLuint) = ::glIsQuery; -void (* const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; -void (* const glEndQuery)(GLenum) = ::glEndQuery; -void (* const glGetQueryiv)(GLenum, GLenum, GLint *) = ::glGetQueryiv; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint *) = ::glGetQueryObjectuiv; -GLboolean (* const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid **) = ::glGetBufferPointerv; -void (* const glDrawBuffers)(GLsizei, const GLenum *) = ::glDrawBuffers; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x3fv; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x2fv; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x4fv; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x2fv; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x4fv; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x3fv; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = ::glBlitFramebuffer; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorageMultisample; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; -void (* const glBindVertexArray)(GLuint) = ::glBindVertexArray; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint *) = ::glDeleteVertexArrays; -void (* const glGenVertexArrays)(GLsizei, GLuint *) = ::glGenVertexArrays; -GLboolean (* const glIsVertexArray)(GLuint) = ::glIsVertexArray; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint *) = ::glGetIntegeri_v; -void (* const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; -void (* const glEndTransformFeedback)() = ::glEndTransformFeedback; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar * const*, GLenum) = ::glTransformFeedbackVaryings; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei *, GLsizei *, GLenum *, GLchar *) = ::glGetTransformFeedbackVarying; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid *) = ::glVertexAttribIPointer; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribIiv; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint *) = ::glGetVertexAttribIuiv; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; -void (* const glVertexAttribI4iv)(GLuint, const GLint *) = ::glVertexAttribI4iv; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint *) = ::glVertexAttribI4uiv; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint *) = ::glGetUniformuiv; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar *) = ::glGetFragDataLocation; -void (* const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint *) = ::glUniform1uiv; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint *) = ::glUniform2uiv; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint *) = ::glUniform3uiv; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint *) = ::glUniform4uiv; -void (* const glClearBufferiv)(GLenum, GLint, const GLint *) = ::glClearBufferiv; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint *) = ::glClearBufferuiv; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat *) = ::glClearBufferfv; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = ::glGetStringi; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar * const*, GLuint *) = ::glGetUniformIndices; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint *, GLenum, GLint *) = ::glGetActiveUniformsiv; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar *) = ::glGetUniformBlockIndex; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint *) = ::glGetActiveUniformBlockiv; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetActiveUniformBlockName; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid *, GLsizei) = ::glDrawElementsInstanced; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; -GLboolean (* const glIsSync)(GLsync) = ::glIsSync; -void (* const glDeleteSync)(GLsync) = ::glDeleteSync; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; -void (* const glGetInteger64v)(GLenum, GLint64 *) = ::glGetInteger64v; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei *, GLint *) = ::glGetSynciv; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64 *) = ::glGetInteger64i_v; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64 *) = ::glGetBufferParameteri64v; -void (* const glGenSamplers)(GLsizei, GLuint *) = ::glGenSamplers; -void (* const glDeleteSamplers)(GLsizei, const GLuint *) = ::glDeleteSamplers; -GLboolean (* const glIsSampler)(GLuint) = ::glIsSampler; -void (* const glBindSampler)(GLuint, GLuint) = ::glBindSampler; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint *) = ::glSamplerParameteriv; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat *) = ::glSamplerParameterfv; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint *) = ::glGetSamplerParameteriv; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat *) = ::glGetSamplerParameterfv; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; -void (* const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint *) = ::glDeleteTransformFeedbacks; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint *) = ::glGenTransformFeedbacks; -GLboolean (* const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; -void (* const glPauseTransformFeedback)() = ::glPauseTransformFeedback; -void (* const glResumeTransformFeedback)() = ::glResumeTransformFeedback; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei *, GLenum *, GLvoid *) = ::glGetProgramBinary; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid *, GLsizei) = ::glProgramBinary; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum *) = ::glInvalidateFramebuffer; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei) = ::glInvalidateSubFramebuffer; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint *) = ::glGetInternalformativ; +void (*const glReadBuffer)(GLenum) = ::glReadBuffer; +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = ::glDrawRangeElements; +void (*const glTexImage3D +)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = ::glTexImage3D; +void (*const glTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = ::glTexSubImage3D; +void (*const glCopyTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage3D; +void (*const glCompressedTexImage3D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = ::glCompressedTexImage3D; +void (*const glCompressedTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = + ::glCompressedTexSubImage3D; +void (*const glGenQueries)(GLsizei, GLuint*) = ::glGenQueries; +void (*const glDeleteQueries)(GLsizei, const GLuint*) = ::glDeleteQueries; +GLboolean (*const glIsQuery)(GLuint) = ::glIsQuery; +void (*const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; +void (*const glEndQuery)(GLenum) = ::glEndQuery; +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = ::glGetQueryiv; +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = ::glGetQueryObjectuiv; +GLboolean (*const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = ::glGetBufferPointerv; +void (*const glDrawBuffers)(GLsizei, const GLenum*) = ::glDrawBuffers; +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x3fv; +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x2fv; +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x4fv; +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x2fv; +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x4fv; +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x3fv; +void (*const glBlitFramebuffer +)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = ::glBlitFramebuffer; +void (*const glRenderbufferStorageMultisample +)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorageMultisample; +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; +GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; +void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; +void (*const glBindVertexArray)(GLuint) = ::glBindVertexArray; +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = ::glDeleteVertexArrays; +void (*const glGenVertexArrays)(GLsizei, GLuint*) = ::glGenVertexArrays; +GLboolean (*const glIsVertexArray)(GLuint) = ::glIsVertexArray; +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = ::glGetIntegeri_v; +void (*const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; +void (*const glEndTransformFeedback)() = ::glEndTransformFeedback; +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; +void (*const glTransformFeedbackVaryings +)(GLuint, GLsizei, const GLchar* const*, GLenum) = ::glTransformFeedbackVaryings; +void (*const glGetTransformFeedbackVarying +)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = ::glGetTransformFeedbackVarying; +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = ::glVertexAttribIPointer; +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribIiv; +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = ::glGetVertexAttribIuiv; +void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; +void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = ::glVertexAttribI4iv; +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = ::glVertexAttribI4uiv; +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = ::glGetUniformuiv; +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = ::glGetFragDataLocation; +void (*const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; +void (*const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; +void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = ::glUniform1uiv; +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = ::glUniform2uiv; +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = ::glUniform3uiv; +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = ::glUniform4uiv; +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = ::glClearBufferiv; +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = ::glClearBufferuiv; +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = ::glClearBufferfv; +void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = ::glGetStringi; +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = ::glGetUniformIndices; +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = ::glGetActiveUniformsiv; +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = ::glGetUniformBlockIndex; +void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = ::glGetActiveUniformBlockiv; +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetActiveUniformBlockName; +void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; +void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = ::glDrawElementsInstanced; +GLsync (*const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; +GLboolean (*const glIsSync)(GLsync) = ::glIsSync; +void (*const glDeleteSync)(GLsync) = ::glDeleteSync; +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; +void (*const glGetInteger64v)(GLenum, GLint64*) = ::glGetInteger64v; +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = ::glGetSynciv; +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = ::glGetInteger64i_v; +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = ::glGetBufferParameteri64v; +void (*const glGenSamplers)(GLsizei, GLuint*) = ::glGenSamplers; +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = ::glDeleteSamplers; +GLboolean (*const glIsSampler)(GLuint) = ::glIsSampler; +void (*const glBindSampler)(GLuint, GLuint) = ::glBindSampler; +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = ::glSamplerParameteriv; +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; +void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = ::glSamplerParameterfv; +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = ::glGetSamplerParameteriv; +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = ::glGetSamplerParameterfv; +void (*const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; +void (*const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = ::glDeleteTransformFeedbacks; +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = ::glGenTransformFeedbacks; +GLboolean (*const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; +void (*const glPauseTransformFeedback)() = ::glPauseTransformFeedback; +void (*const glResumeTransformFeedback)() = ::glResumeTransformFeedback; +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = ::glGetProgramBinary; +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = ::glProgramBinary; +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; +void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = ::glInvalidateFramebuffer; +void (*const glInvalidateSubFramebuffer +)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = ::glInvalidateSubFramebuffer; +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = ::glGetInternalformativ; -} // namespace platform -} // namespace mbgl \ No newline at end of file +} // namespace platform +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/image.cpp b/platform/android/src/image.cpp index 31515ff16fd..0c756155db9 100644 --- a/platform/android/src/image.cpp +++ b/platform/android/src/image.cpp @@ -9,11 +9,10 @@ namespace mbgl { PremultipliedImage decodeImage(const std::string& string) { - auto env{ android::AttachEnv() }; + auto env{android::AttachEnv()}; auto array = jni::Array::New(*env, string.size()); - jni::SetArrayRegion(*env, *array, 0, string.size(), - reinterpret_cast(string.data())); + jni::SetArrayRegion(*env, *array, 0, string.size(), reinterpret_cast(string.data())); return android::Bitmap::GetImage(*env, android::BitmapFactory::DecodeByteArray(*env, array, 0, string.size())); } diff --git a/platform/android/src/jni.cpp b/platform/android/src/jni.cpp old mode 100755 new mode 100644 index 1c958c0ff88..9c5a7199065 --- a/platform/android/src/jni.cpp +++ b/platform/android/src/jni.cpp @@ -7,7 +7,7 @@ namespace android { JavaVM* theJVM; -//TODO: remove +// TODO: remove bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName) { assert(vm != nullptr); assert(env != nullptr); @@ -17,7 +17,7 @@ bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName) { jint ret; *env = nullptr; bool detach = false; - ret = vm->GetEnv(reinterpret_cast(env), JNI_VERSION_1_6); + ret = vm->GetEnv(reinterpret_cast(env), JNI_VERSION_1_6); if (ret != JNI_OK) { if (ret != JNI_EDETACHED) { mbgl::Log::Error(mbgl::Event::JNI, "GetEnv() failed with " + std::to_string(ret)); @@ -35,7 +35,7 @@ bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName) { return detach; } -//TODO: remove +// TODO: remove void detach_jni_thread(JavaVM* vm, JNIEnv** env, bool detach) { if (detach) { assert(vm != nullptr); diff --git a/platform/android/src/run_loop.cpp b/platform/android/src/run_loop.cpp index c344353fc92..23f6e467078 100644 --- a/platform/android/src/run_loop.cpp +++ b/platform/android/src/run_loop.cpp @@ -21,7 +21,7 @@ #include #define PIPE_OUT 0 -#define PIPE_IN 1 +#define PIPE_IN 1 namespace { @@ -29,7 +29,8 @@ using namespace mbgl::util; int looperCallbackNew(int fd, int, void* data) { int buffer[1]; - while (read(fd, buffer, sizeof(buffer)) > 0) {} + while (read(fd, buffer, sizeof(buffer)) > 0) { + } auto runLoopImpl = reinterpret_cast(data); @@ -41,7 +42,8 @@ int looperCallbackNew(int fd, int, void* data) { int looperCallbackDefault(int fd, int, void* data) { int buffer[1]; - while (read(fd, buffer, sizeof(buffer)) > 0) {} + while (read(fd, buffer, sizeof(buffer)) > 0) { + } auto runLoopImpl = reinterpret_cast(data); @@ -82,7 +84,8 @@ namespace util { // efficient way of waking up the RunLoop and it is also thread-safe. class Alarm { public: - Alarm(ActorRef, RunLoop::Impl* loop_) : loop(loop_) {} + Alarm(ActorRef, RunLoop::Impl* loop_) + : loop(loop_) {} void set(const Milliseconds& timeout) { alarm.start(timeout, mbgl::Duration::zero(), [this]() { loop->wake(); }); @@ -93,7 +96,8 @@ class Alarm { RunLoop::Impl* loop; }; -RunLoop::Impl::Impl(RunLoop* runLoop_, RunLoop::Type type) : runLoop(runLoop_) { +RunLoop::Impl::Impl(RunLoop* runLoop_, RunLoop::Type type) + : runLoop(runLoop_) { loop = ALooper_prepare(0); assert(loop); @@ -110,16 +114,18 @@ RunLoop::Impl::Impl(RunLoop* runLoop_, RunLoop::Type type) : runLoop(runLoop_) { int ret = 0; switch (type) { - case Type::New: - ret = ALooper_addFd(loop, fds[PIPE_OUT], ALOOPER_POLL_CALLBACK, - ALOOPER_EVENT_INPUT, looperCallbackNew, this); - break; - case Type::Default: - ret = ALooper_addFd(loop, fds[PIPE_OUT], ALOOPER_POLL_CALLBACK, - ALOOPER_EVENT_INPUT, looperCallbackDefault, this); - alarm = std::make_unique>("Alarm", this); - running = true; - break; + case Type::New: + ret = ALooper_addFd( + loop, fds[PIPE_OUT], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallbackNew, this + ); + break; + case Type::Default: + ret = ALooper_addFd( + loop, fds[PIPE_OUT], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallbackDefault, this + ); + alarm = std::make_unique>("Alarm", this); + running = true; + break; } if (ret != 1) { @@ -209,7 +215,8 @@ RunLoop* RunLoop::Get() { return static_cast(Scheduler::GetCurrent()); } -RunLoop::RunLoop(Type type) : impl(std::make_unique(this, type)) { +RunLoop::RunLoop(Type type) + : impl(std::make_unique(this, type)) { Scheduler::SetCurrent(this); } @@ -231,7 +238,7 @@ void RunLoop::run() { impl->running = true; int outFd, outEvents; - char *outData = nullptr; + char* outData = nullptr; while (impl->running) { process(); @@ -262,7 +269,8 @@ void RunLoop::addWatch(int fd, Event event, std::function&& cb ALooper* looper = ALooper_forThread(); ALooper_addFd( - looper, fd, ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallbackReadEvent, this->impl.get()); + looper, fd, ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallbackReadEvent, this->impl.get() + ); } } diff --git a/platform/android/src/run_loop_impl.hpp b/platform/android/src/run_loop_impl.hpp index 8f0a07f8ba2..8bbf6dfc2e3 100644 --- a/platform/android/src/run_loop_impl.hpp +++ b/platform/android/src/run_loop_impl.hpp @@ -18,7 +18,8 @@ namespace util { using WatchCallback = std::function; -template class Thread; +template +class Thread; class Alarm; class RunLoop::Impl { diff --git a/platform/android/src/string_util.cpp b/platform/android/src/string_util.cpp index f02155caff0..9a0dcb27b38 100644 --- a/platform/android/src/string_util.cpp +++ b/platform/android/src/string_util.cpp @@ -6,7 +6,7 @@ namespace mbgl { namespace platform { std::string uppercase(const std::string& str) { - auto env{ android::AttachEnv() }; + auto env{android::AttachEnv()}; jni::Local value = jni::Make(*env, str.c_str()); static auto toUpperCase = jni::Class::Singleton(*env).GetMethod(*env, "toUpperCase"); auto result = value.Call(*env, toUpperCase); @@ -14,7 +14,7 @@ std::string uppercase(const std::string& str) { } std::string lowercase(const std::string& str) { - auto env{ android::AttachEnv() }; + auto env{android::AttachEnv()}; jni::Local value = jni::Make(*env, str.c_str()); static auto toLowerCase = jni::Class::Singleton(*env).GetMethod(*env, "toLowerCase"); auto result = value.Call(*env, toLowerCase); diff --git a/platform/android/src/test/benchmark_runner.cpp b/platform/android/src/test/benchmark_runner.cpp index 8fbc94b2027..0997e6be102 100644 --- a/platform/android/src/test/benchmark_runner.cpp +++ b/platform/android/src/test/benchmark_runner.cpp @@ -12,10 +12,11 @@ bool done = false; ALooper* looper = NULL; void runner() { - std::vector arguments = {"mbgl-benchmark-runner", - "--benchmark_repetitions=10", - "--benchmark_format=json", - "--benchmark_out=/sdcard/benchmark/results/results.json"}; + std::vector arguments = { + "mbgl-benchmark-runner", + "--benchmark_repetitions=10", + "--benchmark_format=json", + "--benchmark_out=/sdcard/benchmark/results/results.json"}; std::vector argv; for (const auto& arg : arguments) { argv.push_back(const_cast(arg.data())); diff --git a/platform/android/src/test/collator_test_stub.cpp b/platform/android/src/test/collator_test_stub.cpp index 137909d06b5..780785fda75 100644 --- a/platform/android/src/test/collator_test_stub.cpp +++ b/platform/android/src/test/collator_test_stub.cpp @@ -16,7 +16,8 @@ class Collator::Impl { std::string resolvedLocale() const { return ""; } }; -Collator::Collator(bool, bool, const std::optional& locale_) : impl(std::make_shared(locale_)) {} +Collator::Collator(bool, bool, const std::optional& locale_) + : impl(std::make_shared(locale_)) {} int Collator::compare(const std::string& lhs, const std::string& rhs) const { return impl->compare(lhs, rhs); diff --git a/platform/android/src/test/http_file_source_test_stub.cpp b/platform/android/src/test/http_file_source_test_stub.cpp index 53648c3fd5e..2ab1855c82a 100644 --- a/platform/android/src/test/http_file_source_test_stub.cpp +++ b/platform/android/src/test/http_file_source_test_stub.cpp @@ -8,20 +8,17 @@ namespace mbgl { class HTTPFileSource::Impl {}; HTTPFileSource::HTTPFileSource(const ResourceOptions& /*resourceOptions*/, const ClientOptions& /*clientOptions*/) - : impl(std::make_unique()) { -} + : impl(std::make_unique()) {} HTTPFileSource::~HTTPFileSource() = default; -void HTTPFileSource::setResourceOptions(ResourceOptions /*options*/) { -} +void HTTPFileSource::setResourceOptions(ResourceOptions /*options*/) {} ResourceOptions HTTPFileSource::getResourceOptions() { return ResourceOptions::Default(); } -void HTTPFileSource::setClientOptions(ClientOptions /*options*/) { -} +void HTTPFileSource::setClientOptions(ClientOptions /*options*/) {} ClientOptions HTTPFileSource::getClientOptions() { return ClientOptions(); diff --git a/platform/android/src/test/number_format_test_stub.cpp b/platform/android/src/test/number_format_test_stub.cpp index 57710c8558e..aaeccb071fd 100644 --- a/platform/android/src/test/number_format_test_stub.cpp +++ b/platform/android/src/test/number_format_test_stub.cpp @@ -3,11 +3,13 @@ namespace mbgl { namespace platform { -std::string formatNumber(double /*number*/, - const std::string& /*localeId */, - const std::string& /*currency*/, - uint8_t /*minFractionDigits*/, - uint8_t /*maxFractionDigits*/) { +std::string formatNumber( + double /*number*/, + const std::string& /*localeId */, + const std::string& /*currency*/, + uint8_t /*minFractionDigits*/, + uint8_t /*maxFractionDigits*/ +) { return ""; } diff --git a/platform/android/src/test/render_test_runner.cpp b/platform/android/src/test/render_test_runner.cpp index 2e6047d0a82..e487c01172e 100644 --- a/platform/android/src/test/render_test_runner.cpp +++ b/platform/android/src/test/render_test_runner.cpp @@ -19,12 +19,13 @@ void android_main(struct android_app* app) { struct android_poll_source* source = nullptr; if (!copyFile(env, app->activity->assetManager, zipFile, storagePath, "data.zip")) { mbgl::Log::Error( - mbgl::Event::General, "Failed to copy zip File '%s' to external storage for upzipping", zipFile.c_str()); + mbgl::Event::General, "Failed to copy zip File '%s' to external storage for upzipping", zipFile.c_str() + ); } else { unZipFile(env, zipFile, storagePath); - auto runTestWithManifest = - [&storagePath, &app, &outFd, &outEvents, &source](const std::string& manifest) -> bool { + auto runTestWithManifest = [&storagePath, &app, &outFd, &outEvents, &source](const std::string& manifest + ) -> bool { const std::string configFile = storagePath + manifest; std::vector arguments = {"mbgl-render-test-runner", "-p", configFile, "-u", "rebaseline"}; std::vector argv; @@ -44,7 +45,8 @@ void android_main(struct android_app* app) { mbgl::Log::Info(mbgl::Event::General, "Current finished tests number is '%d' ", ++finishedTestCount); }; mbgl::Log::Info( - mbgl::Event::General, "Start running RenderTestRunner with manifest: '%s'", manifest.c_str()); + mbgl::Event::General, "Start running RenderTestRunner with manifest: '%s'", manifest.c_str() + ); bool result = mbgl::runRenderTests(argv.size() - 1, argv.data(), testStatus) == 0; mbgl::Log::Info(mbgl::Event::General, "End running RenderTestRunner with manifest: '%s'", manifest.c_str()); return result; diff --git a/platform/android/src/test/runtime.cpp b/platform/android/src/test/runtime.cpp index 1f8f16da3cc..58d7b3569ac 100644 --- a/platform/android/src/test/runtime.cpp +++ b/platform/android/src/test/runtime.cpp @@ -9,9 +9,9 @@ #include // Required for art / libsigchain -extern "C" JNIEXPORT void EnsureFrontOfChain(int, struct sigaction*) { } -extern "C" JNIEXPORT void AddSpecialSignalHandlerFn(int, void*) { } -extern "C" JNIEXPORT void RemoveSpecialSignalHandlerFn(int, bool (*) (int, siginfo_t*, void*)) { } +extern "C" JNIEXPORT void EnsureFrontOfChain(int, struct sigaction*) {} +extern "C" JNIEXPORT void AddSpecialSignalHandlerFn(int, void*) {} +extern "C" JNIEXPORT void RemoveSpecialSignalHandlerFn(int, bool (*)(int, siginfo_t*, void*)) {} namespace { const std::string kClassPathCommand{"--class_path="}; @@ -22,11 +22,11 @@ const std::string kDefaultDex{"/data/local/tmp/core-tests/classes.dex"}; namespace mbgl { namespace android { -bool initRuntime(int argc, char *argv[]) { +bool initRuntime(int argc, char* argv[]) { void* vmHandle = dlopen("libart.so", RTLD_NOW); assert(vmHandle != nullptr); - using CreateJavaVMFn = jint (*)(JavaVM** vm, JNIEnv** env, void* vmArgs); + using CreateJavaVMFn = jint (*)(JavaVM * *vm, JNIEnv * *env, void* vmArgs); CreateJavaVMFn createJavaVMFn = reinterpret_cast(dlsym(vmHandle, "JNI_CreateJavaVM")); assert(createJavaVMFn != nullptr); @@ -58,8 +58,9 @@ bool initRuntime(int argc, char *argv[]) { void* runtimeHandle = dlopen("libandroid_runtime.so", RTLD_NOW); assert(runtimeHandle != nullptr); - using RegisterNativesFn = jint (*)(JNIEnv* env); - RegisterNativesFn registerNativesFn = reinterpret_cast(dlsym(runtimeHandle, "registerFrameworkNatives")); + using RegisterNativesFn = jint (*)(JNIEnv * env); + RegisterNativesFn registerNativesFn = + reinterpret_cast(dlsym(runtimeHandle, "registerFrameworkNatives")); assert(registerNativesFn != nullptr); if (registerNativesFn(env) != JNI_OK) { diff --git a/platform/android/src/test/test_runner.cpp b/platform/android/src/test/test_runner.cpp index 03faa72c107..49d5d31f50a 100644 --- a/platform/android/src/test/test_runner.cpp +++ b/platform/android/src/test/test_runner.cpp @@ -23,7 +23,7 @@ void runner() { mbgl::Log::Info(mbgl::Event::General, "Start TestRunner"); int status = mbgl::runTests(argv.size(), argv.data()); - mbgl::Log::Info(mbgl::Event::General, "TestRunner finished with status: '" + std::to_string(status) + "'"); + mbgl::Log::Info(mbgl::Event::General, "TestRunner finished with status: '" + std::to_string(status) + "'"); running = false; success = (status == 0); ALooper_wake(looper); diff --git a/platform/android/src/test/test_runner_common.cpp b/platform/android/src/test/test_runner_common.cpp index 600e24ce97c..64fa3f05129 100644 --- a/platform/android/src/test/test_runner_common.cpp +++ b/platform/android/src/test/test_runner_common.cpp @@ -27,7 +27,9 @@ int severityToPriority(EventSeverity severity) { template class JavaWrapper { public: - JavaWrapper(JNIEnv* env_, T obj_) : env(env_), obj(obj_) {} + JavaWrapper(JNIEnv* env_, T obj_) + : env(env_), + obj(obj_) {} ~JavaWrapper() { env->DeleteLocalRef(obj); env = nullptr; @@ -51,7 +53,9 @@ std::string jstringToStdString(JNIEnv* env, jstring jStr) { JavaWrapper stringJbytes( env, static_cast( - env->CallObjectMethod(jStr, getBytes, JavaWrapper(env, env->NewStringUTF("UTF-8")).get()))); + env->CallObjectMethod(jStr, getBytes, JavaWrapper(env, env->NewStringUTF("UTF-8")).get()) + ) + ); size_t length = static_cast(env->GetArrayLength(stringJbytes.get())); jbyte* pBytes = env->GetByteArrayElements(stringJbytes.get(), NULL); @@ -79,11 +83,13 @@ void changeState(JNIEnv* env, struct android_app* app, bool result) { } } -bool copyFile(JNIEnv* env, - AAssetManager* assetManager, - const std::string& filePath, - const std::string& destinationPath, - const std::string& fileName) { +bool copyFile( + JNIEnv* env, + AAssetManager* assetManager, + const std::string& filePath, + const std::string& destinationPath, + const std::string& fileName +) { JavaWrapper fileClass(env, env->FindClass("java/io/File")); jmethodID fileCtor = env->GetMethodID(fileClass.get(), "", "(Ljava/lang/String;Ljava/lang/String;)V"); jmethodID fileExists = env->GetMethodID(fileClass.get(), "exists", "()Z"); @@ -98,7 +104,8 @@ bool copyFile(JNIEnv* env, } else { std::unique_ptr> fileAsset( AAssetManager_open(assetManager, fileName.c_str(), AASSET_MODE_BUFFER), - [](AAsset* asset) { AAsset_close(asset); }); + [](AAsset* asset) { AAsset_close(asset); } + ); if (fileAsset == nullptr) { mbgl::Log::Warning(mbgl::Event::General, "Failed to open asset file " + fileName); return false; @@ -106,8 +113,9 @@ bool copyFile(JNIEnv* env, const void* fileData = AAsset_getBuffer(fileAsset.get()); const off_t fileLen = AAsset_getLength(fileAsset.get()); - std::unique_ptr> newFile(std::fopen(filePath.c_str(), "w+"), - [](FILE* file) { std::fclose(file); }); + std::unique_ptr> newFile(std::fopen(filePath.c_str(), "w+"), [](FILE* file) { + std::fclose(file); + }); stateOk = newFile != nullptr; if (!stateOk) { @@ -115,8 +123,7 @@ bool copyFile(JNIEnv* env, } else { auto res = static_cast(std::fwrite(fileData, sizeof(char), fileLen, newFile.get())); if (fileLen != res) { - mbgl::Log::Warning( - mbgl::Event::General, "Failed to generate file entry" + fileName + "from assets"); + mbgl::Log::Warning(mbgl::Event::General, "Failed to generate file entry" + fileName + "from assets"); } } } @@ -179,22 +186,24 @@ void unZipFile(JNIEnv* env, const std::string& zipFilePath, const std::string& d if (!(env->CallBooleanMethod(f, fileIsDirectory))) { jmethodID mkdirs = env->GetMethodID(fileClass, "mkdirs", "()Z"); bool success = (env->CallBooleanMethod(f, mkdirs)); - std::string fileNameStr = - jstringToStdString(env, static_cast(env->CallObjectMethod(f, fileGetName))); + std::string fileNameStr = jstringToStdString( + env, static_cast(env->CallObjectMethod(f, fileGetName)) + ); if (!success) { mbgl::Log::Warning( - mbgl::Event::General, "Failed to create folder entry " + fileNameStr + " from zip"); + mbgl::Event::General, "Failed to create folder entry " + fileNameStr + " from zip" + ); } } } else if (!(env->CallBooleanMethod(f, fileExists))) { bool success = env->CallBooleanMethod(f, createNewFile); - std::string fileNameStr = - jstringToStdString(env, static_cast(env->CallObjectMethod(f, fileGetName))); + std::string fileNameStr = jstringToStdString( + env, static_cast(env->CallObjectMethod(f, fileGetName)) + ); if (!success) { - mbgl::Log::Warning( - mbgl::Event::General, "Failed to create folder entry" + fileNameStr + "from zip"); + mbgl::Log::Warning(mbgl::Event::General, "Failed to create folder entry" + fileNameStr + "from zip"); continue; } diff --git a/platform/android/src/test/test_runner_common.hpp b/platform/android/src/test/test_runner_common.hpp index 4be59e9178c..0ed17a44216 100644 --- a/platform/android/src/test/test_runner_common.hpp +++ b/platform/android/src/test/test_runner_common.hpp @@ -11,11 +11,13 @@ namespace android { int severityToPriority(EventSeverity severity); void changeState(JNIEnv* env, struct android_app* app, bool result); -bool copyFile(JNIEnv* env, - AAssetManager* assetManager, - const std::string& filePath, - const std::string& destinationPath, - const std::string& fileName); +bool copyFile( + JNIEnv* env, + AAssetManager* assetManager, + const std::string& filePath, + const std::string& destinationPath, + const std::string& fileName +); void unZipFile(JNIEnv* env, const std::string& zipFilePath, const std::string& destinationPath); diff --git a/platform/android/src/timer.cpp b/platform/android/src/timer.cpp index 1d3d05c8437..81b1ea1f913 100644 --- a/platform/android/src/timer.cpp +++ b/platform/android/src/timer.cpp @@ -11,11 +11,10 @@ namespace util { class Timer::Impl : public RunLoop::Impl::Runnable { public: - Impl() : active(false) {} + Impl() + : active(false) {} - ~Impl() { - stop(); - } + ~Impl() { stop(); } void start(Duration timeout, Duration repeat_, std::function&& task_) { stop(); @@ -23,8 +22,7 @@ class Timer::Impl : public RunLoop::Impl::Runnable { repeat = repeat_; task = std::move(task_); // Prevent overflows when timeout is set to Duration::max() - due = (timeout == Duration::max()) ? std::chrono::time_point::max() : Clock::now() + - timeout; + due = (timeout == Duration::max()) ? std::chrono::time_point::max() : Clock::now() + timeout; loop->addRunnable(this); active = true; } @@ -43,9 +41,7 @@ class Timer::Impl : public RunLoop::Impl::Runnable { } } - TimePoint dueTime() const override { - return due; - } + TimePoint dueTime() const override { return due; } void runTask() override { if (active) { @@ -64,8 +60,8 @@ class Timer::Impl : public RunLoop::Impl::Runnable { std::atomic active; }; -Timer::Timer() : impl(std::make_unique()) { -} +Timer::Timer() + : impl(std::make_unique()) {} Timer::~Timer() = default; diff --git a/platform/default/include/mbgl/gfx/headless_backend.hpp b/platform/default/include/mbgl/gfx/headless_backend.hpp index 5167e6a465f..a6ea53acbeb 100644 --- a/platform/default/include/mbgl/gfx/headless_backend.hpp +++ b/platform/default/include/mbgl/gfx/headless_backend.hpp @@ -15,12 +15,17 @@ namespace gfx { // of readStillImage. class HeadlessBackend : public gfx::Renderable { public: - enum class SwapBehaviour { NoFlush, Flush }; + enum class SwapBehaviour { + NoFlush, + Flush + }; // Factory. - static std::unique_ptr Create(const Size size = {256, 256}, - SwapBehaviour swapBehavior = SwapBehaviour::NoFlush, - const gfx::ContextMode contextMode = gfx::ContextMode::Unique) { + static std::unique_ptr Create( + const Size size = {256, 256}, + SwapBehaviour swapBehavior = SwapBehaviour::NoFlush, + const gfx::ContextMode contextMode = gfx::ContextMode::Unique + ) { return Backend::Create(size, swapBehavior, contextMode); } diff --git a/platform/default/include/mbgl/gfx/headless_frontend.hpp b/platform/default/include/mbgl/gfx/headless_frontend.hpp index 1e1f1c14030..8aa94a821c5 100644 --- a/platform/default/include/mbgl/gfx/headless_frontend.hpp +++ b/platform/default/include/mbgl/gfx/headless_frontend.hpp @@ -23,15 +23,19 @@ class HeadlessFrontend : public RendererFrontend { gfx::RenderingStats stats; }; - HeadlessFrontend(float pixelRatio_, - gfx::HeadlessBackend::SwapBehaviour swapBehavior = gfx::HeadlessBackend::SwapBehaviour::NoFlush, - gfx::ContextMode mode = gfx::ContextMode::Unique, - const std::optional& localFontFamily = std::nullopt); - HeadlessFrontend(Size, - float pixelRatio_, - gfx::HeadlessBackend::SwapBehaviour swapBehavior = gfx::HeadlessBackend::SwapBehaviour::NoFlush, - gfx::ContextMode mode = gfx::ContextMode::Unique, - const std::optional& localFontFamily = std::nullopt); + HeadlessFrontend( + float pixelRatio_, + gfx::HeadlessBackend::SwapBehaviour swapBehavior = gfx::HeadlessBackend::SwapBehaviour::NoFlush, + gfx::ContextMode mode = gfx::ContextMode::Unique, + const std::optional& localFontFamily = std::nullopt + ); + HeadlessFrontend( + Size, + float pixelRatio_, + gfx::HeadlessBackend::SwapBehaviour swapBehavior = gfx::HeadlessBackend::SwapBehaviour::NoFlush, + gfx::ContextMode mode = gfx::ContextMode::Unique, + const std::optional& localFontFamily = std::nullopt + ); ~HeadlessFrontend() override; void reset() override; diff --git a/platform/default/include/mbgl/gl/headless_backend.hpp b/platform/default/include/mbgl/gl/headless_backend.hpp index c16dcc3559d..048c17d873d 100644 --- a/platform/default/include/mbgl/gl/headless_backend.hpp +++ b/platform/default/include/mbgl/gl/headless_backend.hpp @@ -10,9 +10,9 @@ namespace gl { class HeadlessBackend final : public gl::RendererBackend, public gfx::HeadlessBackend { public: - HeadlessBackend(Size = {256, 256}, - SwapBehaviour = SwapBehaviour::NoFlush, - gfx::ContextMode = gfx::ContextMode::Unique); + HeadlessBackend( + Size = {256, 256}, SwapBehaviour = SwapBehaviour::NoFlush, gfx::ContextMode = gfx::ContextMode::Unique + ); ~HeadlessBackend() override; void updateAssumedState() override; gfx::Renderable& getDefaultRenderable() override; diff --git a/platform/default/include/mbgl/map/map_snapshotter.hpp b/platform/default/include/mbgl/map/map_snapshotter.hpp index f41ffb5e646..97f4a6309fa 100644 --- a/platform/default/include/mbgl/map/map_snapshotter.hpp +++ b/platform/default/include/mbgl/map/map_snapshotter.hpp @@ -34,12 +34,14 @@ class MapSnapshotterObserver { class MapSnapshotter { public: - MapSnapshotter(Size size, - float pixelRatio, - const ResourceOptions&, - const ClientOptions&, - MapSnapshotterObserver&, - std::optional localFontFamily = std::nullopt); + MapSnapshotter( + Size size, + float pixelRatio, + const ResourceOptions&, + const ClientOptions&, + MapSnapshotterObserver&, + std::optional localFontFamily = std::nullopt + ); MapSnapshotter(Size size, float pixelRatio, const ResourceOptions&, const ClientOptions& = ClientOptions()); @@ -63,10 +65,10 @@ class MapSnapshotter { style::Style& getStyle(); const style::Style& getStyle() const; - using PointForFn = std::function; - using LatLngForFn = std::function; + using PointForFn = std::function; + using LatLngForFn = std::function; using Attributions = std::vector; - using Callback = std::function; + using Callback = std::function; void snapshot(Callback); void cancel(); diff --git a/platform/default/include/mbgl/storage/merge_sideloaded.hpp b/platform/default/include/mbgl/storage/merge_sideloaded.hpp index 494018c9660..42075c31326 100644 --- a/platform/default/include/mbgl/storage/merge_sideloaded.hpp +++ b/platform/default/include/mbgl/storage/merge_sideloaded.hpp @@ -6,48 +6,49 @@ namespace mbgl { static constexpr const char* mergeSideloadedDatabaseSQL = -"INSERT INTO regions\n" -" SELECT DISTINCT NULL, sr.definition, sr.description\n" -" FROM side.regions sr \n" -" LEFT JOIN regions r ON sr.definition = r.definition AND sr.description IS r.description\n" -" WHERE r.definition IS NULL;\n" -"CREATE TEMPORARY TABLE region_mapping AS\n" -" SELECT sr.id AS side_region_id,\n" -" r.id AS main_region_id\n" -" FROM side.regions sr\n" -" JOIN regions r ON sr.definition = r.definition AND sr.description IS r.description;\n" -"REPLACE INTO tiles\n" -" SELECT t.id,\n" -" st.url_template, st.pixel_ratio, st.z, st.x, st.y,\n" -" st.expires, st.modified, st.etag, st.data, st.compressed, st.accessed, st.must_revalidate\n" -" FROM (SELECT DISTINCT sti.* FROM side.region_tiles srt JOIN side.tiles sti ON srt.tile_id = sti.id)\n" -" AS st\n" -" LEFT JOIN tiles t ON st.url_template = t.url_template AND st.pixel_ratio = t.pixel_ratio AND st.z = t.z AND st.x = t.x AND st.y = t.y\n" -" WHERE t.id IS NULL\n" -" OR st.modified > t.modified;\n" -"INSERT OR IGNORE INTO region_tiles\n" -" SELECT rm.main_region_id, sti.id\n" -" FROM side.region_tiles srt\n" -" JOIN region_mapping rm ON srt.region_id = rm.side_region_id\n" -" JOIN (SELECT t.id, st.id AS side_tile_id FROM side.tiles st\n" -" JOIN tiles t ON st.url_template = t.url_template AND st.pixel_ratio = t.pixel_ratio AND st.z = t.z AND st.x = t.x AND st.y = t.y\n" -" ) AS sti ON srt.tile_id = sti.side_tile_id;\n" -"REPLACE INTO resources\n" -" SELECT r.id, \n" -" sr.url, sr.kind, sr.expires, sr.modified, sr.etag,\n" -" sr.data, sr.compressed, sr.accessed, sr.must_revalidate\n" -" FROM side.region_resources srr JOIN side.resources sr ON srr.resource_id = sr.id\n" -" LEFT JOIN resources r ON sr.url = r.url\n" -" WHERE r.id IS NULL\n" -" OR sr.modified > r.modified;\n" -"INSERT OR IGNORE INTO region_resources\n" -" SELECT rm.main_region_id, sri.id\n" -" FROM side.region_resources srr\n" -" JOIN region_mapping rm ON srr.region_id = rm.side_region_id\n" -" JOIN (SELECT r.id, sr.id AS side_resource_id FROM side.resources sr\n" -" JOIN resources r ON sr.url = r.url) AS sri ON srr.resource_id = sri.side_resource_id;\n" -" \n" -"DROP TABLE region_mapping;\n" -; + "INSERT INTO regions\n" + " SELECT DISTINCT NULL, sr.definition, sr.description\n" + " FROM side.regions sr \n" + " LEFT JOIN regions r ON sr.definition = r.definition AND sr.description IS r.description\n" + " WHERE r.definition IS NULL;\n" + "CREATE TEMPORARY TABLE region_mapping AS\n" + " SELECT sr.id AS side_region_id,\n" + " r.id AS main_region_id\n" + " FROM side.regions sr\n" + " JOIN regions r ON sr.definition = r.definition AND sr.description IS r.description;\n" + "REPLACE INTO tiles\n" + " SELECT t.id,\n" + " st.url_template, st.pixel_ratio, st.z, st.x, st.y,\n" + " st.expires, st.modified, st.etag, st.data, st.compressed, st.accessed, st.must_revalidate\n" + " FROM (SELECT DISTINCT sti.* FROM side.region_tiles srt JOIN side.tiles sti ON srt.tile_id = sti.id)\n" + " AS st\n" + " LEFT JOIN tiles t ON st.url_template = t.url_template AND st.pixel_ratio = t.pixel_ratio AND st.z = t.z AND " + "st.x = t.x AND st.y = t.y\n" + " WHERE t.id IS NULL\n" + " OR st.modified > t.modified;\n" + "INSERT OR IGNORE INTO region_tiles\n" + " SELECT rm.main_region_id, sti.id\n" + " FROM side.region_tiles srt\n" + " JOIN region_mapping rm ON srt.region_id = rm.side_region_id\n" + " JOIN (SELECT t.id, st.id AS side_tile_id FROM side.tiles st\n" + " JOIN tiles t ON st.url_template = t.url_template AND st.pixel_ratio = t.pixel_ratio AND st.z = t.z " + "AND st.x = t.x AND st.y = t.y\n" + " ) AS sti ON srt.tile_id = sti.side_tile_id;\n" + "REPLACE INTO resources\n" + " SELECT r.id, \n" + " sr.url, sr.kind, sr.expires, sr.modified, sr.etag,\n" + " sr.data, sr.compressed, sr.accessed, sr.must_revalidate\n" + " FROM side.region_resources srr JOIN side.resources sr ON srr.resource_id = sr.id\n" + " LEFT JOIN resources r ON sr.url = r.url\n" + " WHERE r.id IS NULL\n" + " OR sr.modified > r.modified;\n" + "INSERT OR IGNORE INTO region_resources\n" + " SELECT rm.main_region_id, sri.id\n" + " FROM side.region_resources srr\n" + " JOIN region_mapping rm ON srr.region_id = rm.side_region_id\n" + " JOIN (SELECT r.id, sr.id AS side_resource_id FROM side.resources sr\n" + " JOIN resources r ON sr.url = r.url) AS sri ON srr.resource_id = sri.side_resource_id;\n" + " \n" + "DROP TABLE region_mapping;\n"; } // namespace mbgl diff --git a/platform/default/include/mbgl/storage/offline_database.hpp b/platform/default/include/mbgl/storage/offline_database.hpp index 6a49de10acb..7ff8c9143d8 100644 --- a/platform/default/include/mbgl/storage/offline_database.hpp +++ b/platform/default/include/mbgl/storage/offline_database.hpp @@ -32,8 +32,9 @@ namespace util { struct IOException; } // namespace util -struct MapboxTileLimitExceededException : util::Exception { - MapboxTileLimitExceededException() : util::Exception("Mapbox tile limit exceeded") {} +struct MapboxTileLimitExceededException : util::Exception { + MapboxTileLimitExceededException() + : util::Exception("Mapbox tile limit exceeded") {} }; class OfflineDatabase { @@ -63,11 +64,10 @@ class OfflineDatabase { expected listRegions(); - expected createRegion(const OfflineRegionDefinition&, - const OfflineRegionMetadata&); + expected + createRegion(const OfflineRegionDefinition&, const OfflineRegionMetadata&); - expected - mergeDatabase(const std::string& sideDatabasePath); + expected mergeDatabase(const std::string& sideDatabasePath); expected updateMetadata(int64_t regionID, const OfflineRegionMetadata&); @@ -115,17 +115,15 @@ class OfflineDatabase { void vacuum(); void checkFlags(); - mapbox::sqlite::Statement& getStatement(const char *); + mapbox::sqlite::Statement& getStatement(const char*); std::optional> getTile(const Resource::TileData&); std::optional hasTile(const Resource::TileData&); - bool putTile(const Resource::TileData&, const Response&, - const std::string&, bool compressed); + bool putTile(const Resource::TileData&, const Response&, const std::string&, bool compressed); std::optional> getResource(const Resource&); std::optional hasResource(const Resource&); - bool putResource(const Resource&, const Response&, - const std::string&, bool compressed); + bool putResource(const Resource&, const Response&, const std::string&, bool compressed); uint64_t putRegionResourceInternal(int64_t regionID, const Resource&, const Response&); @@ -144,7 +142,7 @@ class OfflineDatabase { std::map> statements; template - T getPragma(const char *); + T getPragma(const char*); uint64_t maximumAmbientCacheSize = util::DEFAULT_MAX_CACHE_SIZE; uint64_t offlineMapboxTileCountLimit = util::mapbox::DEFAULT_OFFLINE_TILE_COUNT_LIMIT; diff --git a/platform/default/include/mbgl/storage/offline_download.hpp b/platform/default/include/mbgl/storage/offline_download.hpp index 973fa826fa9..42bd9d5b822 100644 --- a/platform/default/include/mbgl/storage/offline_download.hpp +++ b/platform/default/include/mbgl/storage/offline_download.hpp @@ -47,7 +47,7 @@ class OfflineDownload { * While the request is in progress, it is recorded in `requests`. If the download * is deactivated, all in progress requests are cancelled. */ - void ensureResource(Resource&&, std::function = {}); + void ensureResource(Resource&&, std::function = {}); void onMapboxTileCountLimitExceeded(); diff --git a/platform/default/include/mbgl/storage/offline_schema.hpp b/platform/default/include/mbgl/storage/offline_schema.hpp index 77c66b7d157..a825435d23c 100644 --- a/platform/default/include/mbgl/storage/offline_schema.hpp +++ b/platform/default/include/mbgl/storage/offline_schema.hpp @@ -6,58 +6,57 @@ namespace mbgl { static constexpr const char* offlineDatabaseSchema = -"CREATE TABLE resources (\n" -" id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" -" url TEXT NOT NULL,\n" -" kind INTEGER NOT NULL,\n" -" expires INTEGER,\n" -" modified INTEGER,\n" -" etag TEXT,\n" -" data BLOB,\n" -" compressed INTEGER NOT NULL DEFAULT 0,\n" -" accessed INTEGER NOT NULL,\n" -" must_revalidate INTEGER NOT NULL DEFAULT 0,\n" -" UNIQUE (url)\n" -");\n" -"CREATE TABLE tiles (\n" -" id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" -" url_template TEXT NOT NULL,\n" -" pixel_ratio INTEGER NOT NULL,\n" -" z INTEGER NOT NULL,\n" -" x INTEGER NOT NULL,\n" -" y INTEGER NOT NULL,\n" -" expires INTEGER,\n" -" modified INTEGER,\n" -" etag TEXT,\n" -" data BLOB,\n" -" compressed INTEGER NOT NULL DEFAULT 0,\n" -" accessed INTEGER NOT NULL,\n" -" must_revalidate INTEGER NOT NULL DEFAULT 0,\n" -" UNIQUE (url_template, pixel_ratio, z, x, y)\n" -");\n" -"CREATE TABLE regions (\n" -" id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" -" definition TEXT NOT NULL,\n" -" description BLOB\n" -");\n" -"CREATE TABLE region_resources (\n" -" region_id INTEGER NOT NULL REFERENCES regions(id) ON DELETE CASCADE,\n" -" resource_id INTEGER NOT NULL REFERENCES resources(id),\n" -" UNIQUE (region_id, resource_id)\n" -");\n" -"CREATE TABLE region_tiles (\n" -" region_id INTEGER NOT NULL REFERENCES regions(id) ON DELETE CASCADE,\n" -" tile_id INTEGER NOT NULL REFERENCES tiles(id),\n" -" UNIQUE (region_id, tile_id)\n" -");\n" -"CREATE INDEX resources_accessed\n" -"ON resources (accessed);\n" -"CREATE INDEX tiles_accessed\n" -"ON tiles (accessed);\n" -"CREATE INDEX region_resources_resource_id\n" -"ON region_resources (resource_id);\n" -"CREATE INDEX region_tiles_tile_id\n" -"ON region_tiles (tile_id);\n" -; + "CREATE TABLE resources (\n" + " id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + " url TEXT NOT NULL,\n" + " kind INTEGER NOT NULL,\n" + " expires INTEGER,\n" + " modified INTEGER,\n" + " etag TEXT,\n" + " data BLOB,\n" + " compressed INTEGER NOT NULL DEFAULT 0,\n" + " accessed INTEGER NOT NULL,\n" + " must_revalidate INTEGER NOT NULL DEFAULT 0,\n" + " UNIQUE (url)\n" + ");\n" + "CREATE TABLE tiles (\n" + " id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + " url_template TEXT NOT NULL,\n" + " pixel_ratio INTEGER NOT NULL,\n" + " z INTEGER NOT NULL,\n" + " x INTEGER NOT NULL,\n" + " y INTEGER NOT NULL,\n" + " expires INTEGER,\n" + " modified INTEGER,\n" + " etag TEXT,\n" + " data BLOB,\n" + " compressed INTEGER NOT NULL DEFAULT 0,\n" + " accessed INTEGER NOT NULL,\n" + " must_revalidate INTEGER NOT NULL DEFAULT 0,\n" + " UNIQUE (url_template, pixel_ratio, z, x, y)\n" + ");\n" + "CREATE TABLE regions (\n" + " id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + " definition TEXT NOT NULL,\n" + " description BLOB\n" + ");\n" + "CREATE TABLE region_resources (\n" + " region_id INTEGER NOT NULL REFERENCES regions(id) ON DELETE CASCADE,\n" + " resource_id INTEGER NOT NULL REFERENCES resources(id),\n" + " UNIQUE (region_id, resource_id)\n" + ");\n" + "CREATE TABLE region_tiles (\n" + " region_id INTEGER NOT NULL REFERENCES regions(id) ON DELETE CASCADE,\n" + " tile_id INTEGER NOT NULL REFERENCES tiles(id),\n" + " UNIQUE (region_id, tile_id)\n" + ");\n" + "CREATE INDEX resources_accessed\n" + "ON resources (accessed);\n" + "CREATE INDEX tiles_accessed\n" + "ON tiles (accessed);\n" + "CREATE INDEX region_resources_resource_id\n" + "ON region_resources (resource_id);\n" + "CREATE INDEX region_tiles_tile_id\n" + "ON region_tiles (tile_id);\n"; } // namespace mbgl diff --git a/platform/default/include/mbgl/storage/sqlite3.hpp b/platform/default/include/mbgl/storage/sqlite3.hpp index 9da98daf25f..9d37502d7c8 100644 --- a/platform/default/include/mbgl/storage/sqlite3.hpp +++ b/platform/default/include/mbgl/storage/sqlite3.hpp @@ -11,7 +11,7 @@ namespace mapbox { namespace sqlite { enum OpenFlag : int { - ReadOnly = 0b001, + ReadOnly = 0b001, ReadWriteCreate = 0b110, }; @@ -50,13 +50,14 @@ enum class ExtendedResultCode : uint8_t { class Exception : public std::runtime_error { public: - Exception(ResultCode err, const char* msg) : Exception(static_cast(err), msg) {} - Exception(int err, const char* msg) : Exception(err, std::string{ msg }) {} + Exception(ResultCode err, const char* msg) + : Exception(static_cast(err), msg) {} + Exception(int err, const char* msg) + : Exception(err, std::string{msg}) {} Exception(int err, const std::string& msg) : std::runtime_error(msg), code(static_cast(err)), - extendedCode(static_cast(err >> 8)) { - } + extendedCode(static_cast(err >> 8)) {} const ResultCode code = ResultCode::OK; const ExtendedResultCode extendedCode = ExtendedResultCode::Unknown; }; @@ -74,17 +75,17 @@ class Database { Database(std::unique_ptr); public: - Database(const Database &) = delete; - Database &operator=(const Database &) = delete; - static mapbox::util::variant tryOpen(const std::string &filename, int flags = 0); - static Database open(const std::string &filename, int flags = 0); + Database(const Database&) = delete; + Database& operator=(const Database&) = delete; + static mapbox::util::variant tryOpen(const std::string& filename, int flags = 0); + static Database open(const std::string& filename, int flags = 0); Database(Database&&) noexcept; ~Database(); Database& operator=(Database&&) noexcept; void setBusyTimeout(std::chrono::milliseconds); - void exec(const std::string &sql); + void exec(const std::string& sql); private: std::unique_ptr impl; diff --git a/platform/default/src/mbgl/gfx/headless_backend.cpp b/platform/default/src/mbgl/gfx/headless_backend.cpp index f3eded8dcb2..27428043890 100644 --- a/platform/default/src/mbgl/gfx/headless_backend.cpp +++ b/platform/default/src/mbgl/gfx/headless_backend.cpp @@ -4,8 +4,7 @@ namespace mbgl { namespace gfx { HeadlessBackend::HeadlessBackend(Size size_) - : mbgl::gfx::Renderable(size_, nullptr) { -} + : mbgl::gfx::Renderable(size_, nullptr) {} void HeadlessBackend::setSize(Size size_) { size = size_; diff --git a/platform/default/src/mbgl/gfx/headless_frontend.cpp b/platform/default/src/mbgl/gfx/headless_frontend.cpp index 3c700abdf83..ef1bd74bb30 100644 --- a/platform/default/src/mbgl/gfx/headless_frontend.cpp +++ b/platform/default/src/mbgl/gfx/headless_frontend.cpp @@ -11,28 +11,33 @@ namespace mbgl { -HeadlessFrontend::HeadlessFrontend(float pixelRatio_, - gfx::HeadlessBackend::SwapBehaviour swapBehavior, - const gfx::ContextMode contextMode, - const std::optional& localFontFamily) +HeadlessFrontend::HeadlessFrontend( + float pixelRatio_, + gfx::HeadlessBackend::SwapBehaviour swapBehavior, + const gfx::ContextMode contextMode, + const std::optional& localFontFamily +) : HeadlessFrontend({256, 256}, pixelRatio_, swapBehavior, contextMode, localFontFamily) {} -HeadlessFrontend::HeadlessFrontend(Size size_, - float pixelRatio_, - gfx::HeadlessBackend::SwapBehaviour swapBehavior, - const gfx::ContextMode contextMode, - const std::optional& localFontFamily) +HeadlessFrontend::HeadlessFrontend( + Size size_, + float pixelRatio_, + gfx::HeadlessBackend::SwapBehaviour swapBehavior, + const gfx::ContextMode contextMode, + const std::optional& localFontFamily +) : size(size_), pixelRatio(pixelRatio_), frameTime(0), backend(gfx::HeadlessBackend::Create( {static_cast(size.width * pixelRatio), static_cast(size.height * pixelRatio)}, swapBehavior, - contextMode)), + contextMode + )), asyncInvalidate([this] { if (renderer && updateParameters) { auto startTime = mbgl::util::MonotonicTimer::now(); - gfx::BackendScope guard {*getBackend()}; + gfx::BackendScope guard{*getBackend()}; // onStyleImageMissing might be called during a render. The user implemented method // could trigger a call to MLNRenderFrontend#update which overwrites `updateParameters`. @@ -82,8 +87,7 @@ gfx::RendererBackend* HeadlessFrontend::getBackend() { } CameraOptions HeadlessFrontend::getCameraOptions() { - if (updateParameters) - return RendererState::getCameraOptions(*updateParameters); + if (updateParameters) return RendererState::getCameraOptions(*updateParameters); static CameraOptions nullCamera; return nullCamera; @@ -117,7 +121,7 @@ ScreenCoordinate HeadlessFrontend::pixelForLatLng(const LatLng& coordinate) { return RendererState::pixelForLatLng(*updateParameters, coordinate); } - return ScreenCoordinate {}; + return ScreenCoordinate{}; } LatLng HeadlessFrontend::latLngForPixel(const ScreenCoordinate& point) { @@ -125,14 +129,15 @@ LatLng HeadlessFrontend::latLngForPixel(const ScreenCoordinate& point) { return RendererState::latLngForPixel(*updateParameters, point); } - return LatLng {}; + return LatLng{}; } void HeadlessFrontend::setSize(Size size_) { if (size != size_) { size = size_; - backend->setSize({ static_cast(size_.width * pixelRatio), - static_cast(size_.height * pixelRatio) }); + backend->setSize( + {static_cast(size_.width * pixelRatio), static_cast(size_.height * pixelRatio)} + ); } } @@ -143,7 +148,7 @@ PremultipliedImage HeadlessFrontend::readStillImage() { HeadlessFrontend::RenderResult HeadlessFrontend::render(Map& map) { HeadlessFrontend::RenderResult result; std::exception_ptr error; - gfx::BackendScope guard { *getBackend() }; + gfx::BackendScope guard{*getBackend()}; map.renderStill([&](const std::exception_ptr& e) { if (e) { diff --git a/platform/default/src/mbgl/gl/headless_backend.cpp b/platform/default/src/mbgl/gl/headless_backend.cpp index f8882c47bbc..c6059264b99 100644 --- a/platform/default/src/mbgl/gl/headless_backend.cpp +++ b/platform/default/src/mbgl/gl/headless_backend.cpp @@ -24,7 +24,7 @@ class HeadlessRenderableResource final : public gl::RenderableResource { void bind() override { context.bindFramebuffer = framebuffer.framebuffer; context.scissorTest = false; - context.viewport = { 0, 0, framebuffer.size }; + context.viewport = {0, 0, framebuffer.size}; } void swap() override { backend.swap(); } @@ -36,13 +36,15 @@ class HeadlessRenderableResource final : public gl::RenderableResource { gl::Framebuffer framebuffer; }; -HeadlessBackend::HeadlessBackend(const Size size_, - gfx::HeadlessBackend::SwapBehaviour swapBehaviour_, - const gfx::ContextMode contextMode_) - : mbgl::gl::RendererBackend(contextMode_), mbgl::gfx::HeadlessBackend(size_), swapBehaviour(swapBehaviour_) {} +HeadlessBackend::HeadlessBackend( + const Size size_, gfx::HeadlessBackend::SwapBehaviour swapBehaviour_, const gfx::ContextMode contextMode_ +) + : mbgl::gl::RendererBackend(contextMode_), + mbgl::gfx::HeadlessBackend(size_), + swapBehaviour(swapBehaviour_) {} HeadlessBackend::~HeadlessBackend() { - gfx::BackendScope guard{ *this, gfx::BackendScope::ScopeType::Implicit }; + gfx::BackendScope guard{*this, gfx::BackendScope::ScopeType::Implicit}; resource.reset(); // Explicitly reset the context so that it is destructed and cleaned up before we destruct // the impl object. @@ -100,7 +102,8 @@ namespace gfx { template <> std::unique_ptr Backend::Create( - const Size size, gfx::HeadlessBackend::SwapBehaviour swapBehavior, const gfx::ContextMode contextMode) { + const Size size, gfx::HeadlessBackend::SwapBehaviour swapBehavior, const gfx::ContextMode contextMode +) { return std::make_unique(size, swapBehavior, contextMode); } diff --git a/platform/default/src/mbgl/i18n/collator.cpp b/platform/default/src/mbgl/i18n/collator.cpp index 847d143cd6f..eb63383a346 100644 --- a/platform/default/src/mbgl/i18n/collator.cpp +++ b/platform/default/src/mbgl/i18n/collator.cpp @@ -52,7 +52,8 @@ namespace platform { class Collator::Impl { public: Impl(bool caseSensitive_, bool diacriticSensitive_, const std::optional&) - : caseSensitive(caseSensitive_), diacriticSensitive(diacriticSensitive_) {} + : caseSensitive(caseSensitive_), + diacriticSensitive(diacriticSensitive_) {} bool operator==(const Impl& other) const { return caseSensitive == other.caseSensitive && diacriticSensitive == other.diacriticSensitive; @@ -60,11 +61,9 @@ class Collator::Impl { int compare(const std::string& lhs, const std::string& rhs) const { if (caseSensitive && diacriticSensitive) { - return nu_strcoll(lhs.c_str(), rhs.c_str(), - nu_utf8_read, nu_utf8_read); + return nu_strcoll(lhs.c_str(), rhs.c_str(), nu_utf8_read, nu_utf8_read); } else if (!caseSensitive && diacriticSensitive) { - return nu_strcasecoll(lhs.c_str(), rhs.c_str(), - nu_utf8_read, nu_utf8_read); + return nu_strcasecoll(lhs.c_str(), rhs.c_str(), nu_utf8_read, nu_utf8_read); } else if (caseSensitive && !diacriticSensitive) { return nu_strcoll(unaccent(lhs).c_str(), unaccent(rhs).c_str(), nu_utf8_read, nu_utf8_read); } else { @@ -72,9 +71,7 @@ class Collator::Impl { } } - std::string resolvedLocale() const { - return ""; - } + std::string resolvedLocale() const { return ""; } private: bool caseSensitive; diff --git a/platform/default/src/mbgl/i18n/number_format.cpp b/platform/default/src/mbgl/i18n/number_format.cpp index 6a975926d74..05855189d4a 100644 --- a/platform/default/src/mbgl/i18n/number_format.cpp +++ b/platform/default/src/mbgl/i18n/number_format.cpp @@ -11,11 +11,13 @@ namespace mbgl { namespace platform { #if !defined(MBGL_USE_BUILTIN_ICU) -std::string formatNumber(double number, - const std::string& localeId, - const std::string& currency, - uint8_t minFractionDigits, - uint8_t maxFractionDigits) { +std::string formatNumber( + double number, + const std::string& localeId, + const std::string& currency, + uint8_t minFractionDigits, + uint8_t maxFractionDigits +) { UErrorCode status = U_ZERO_ERROR; icu::UnicodeString ustr; std::string formatted; diff --git a/platform/default/src/mbgl/layermanager/layer_manager.cpp b/platform/default/src/mbgl/layermanager/layer_manager.cpp index 3e822a7b4b1..6bca6bfc25b 100644 --- a/platform/default/src/mbgl/layermanager/layer_manager.cpp +++ b/platform/default/src/mbgl/layermanager/layer_manager.cpp @@ -85,7 +85,7 @@ void LayerManagerDefault::addLayerType(std::unique_ptr factory) { LayerFactory* LayerManagerDefault::getFactory(const mbgl::style::LayerTypeInfo* typeInfo) noexcept { assert(typeInfo); - for (const auto& factory: factories) { + for (const auto& factory : factories) { if (factory->getTypeInfo() == typeInfo) { return factory.get(); } @@ -105,7 +105,8 @@ LayerManager* LayerManager::get() noexcept { return &instance; } -#if defined(MBGL_LAYER_LINE_DISABLE_ALL) || defined(MBGL_LAYER_SYMBOL_DISABLE_ALL) || defined(MBGL_LAYER_FILL_DISABLE_ALL) +#if defined(MBGL_LAYER_LINE_DISABLE_ALL) || defined(MBGL_LAYER_SYMBOL_DISABLE_ALL) || \ + defined(MBGL_LAYER_FILL_DISABLE_ALL) const bool LayerManager::annotationsEnabled = false; #else const bool LayerManager::annotationsEnabled = true; diff --git a/platform/default/src/mbgl/map/map_snapshotter.cpp b/platform/default/src/mbgl/map/map_snapshotter.cpp index 7ddd4daa2f9..0269f82397d 100644 --- a/platform/default/src/mbgl/map/map_snapshotter.cpp +++ b/platform/default/src/mbgl/map/map_snapshotter.cpp @@ -27,13 +27,12 @@ MapSnapshotterObserver& MapSnapshotterObserver::nullObserver() { class ForwardingRendererObserver final : public RendererObserver { public: explicit ForwardingRendererObserver(RendererObserver& delegate_) - : mailbox(std::make_shared(*Scheduler::GetCurrent())), delegate(delegate_, mailbox) {} + : mailbox(std::make_shared(*Scheduler::GetCurrent())), + delegate(delegate_, mailbox) {} ~ForwardingRendererObserver() override { mailbox->close(); } - void onInvalidate() override { - delegate.invoke(&RendererObserver::onInvalidate); - } + void onInvalidate() override { delegate.invoke(&RendererObserver::onInvalidate); } void onResourceError(std::exception_ptr err) override { delegate.invoke(&RendererObserver::onResourceError, err); } @@ -53,20 +52,16 @@ class ForwardingRendererObserver final : public RendererObserver { class SnapshotterRenderer final : public RendererObserver { public: SnapshotterRenderer(Size size, float pixelRatio, const std::optional& localFontFamily) - : frontend(size, - pixelRatio, - gfx::HeadlessBackend::SwapBehaviour::NoFlush, - gfx::ContextMode::Unique, - localFontFamily) {} + : frontend( + size, pixelRatio, gfx::HeadlessBackend::SwapBehaviour::NoFlush, gfx::ContextMode::Unique, localFontFamily + ) {} void reset() { hasPendingStillImageRequest = false; frontend.reset(); } - void onInvalidate() override { - rendererObserver->onInvalidate(); - } + void onInvalidate() override { rendererObserver->onInvalidate(); } void onResourceError(std::exception_ptr err) override { hasPendingStillImageRequest = false; @@ -114,15 +109,17 @@ class SnapshotterRendererFrontend final : public RendererFrontend { public: SnapshotterRendererFrontend(Size size, float pixelRatio, std::optional localFontFamily) : renderer(std::make_unique>( - "Snapshotter", size, pixelRatio, std::move(localFontFamily))) {} + "Snapshotter", size, pixelRatio, std::move(localFontFamily) + )) {} ~SnapshotterRendererFrontend() override = default; void reset() override { renderer->actor().invoke(&SnapshotterRenderer::reset); } void setObserver(RendererObserver& observer) override { - renderer->actor().invoke(&SnapshotterRenderer::setObserver, - std::make_unique(observer)); + renderer->actor().invoke( + &SnapshotterRenderer::setObserver, std::make_unique(observer) + ); } void update(std::shared_ptr parameters) override { @@ -148,12 +145,14 @@ class SnapshotterRendererFrontend final : public RendererFrontend { class MapSnapshotter::Impl final : public MapObserver { public: - Impl(Size size, - float pixelRatio, - const ResourceOptions& resourceOptions, - const ClientOptions& clientOptions, - MapSnapshotterObserver& observer_, - std::optional localFontFamily) + Impl( + Size size, + float pixelRatio, + const ResourceOptions& resourceOptions, + const ClientOptions& clientOptions, + MapSnapshotterObserver& observer_, + std::optional localFontFamily + ) : observer(observer_), frontend(size, pixelRatio, std::move(localFontFamily)), map(frontend, @@ -175,23 +174,28 @@ class MapSnapshotter::Impl final : public MapObserver { } if (renderStillCallback) { - callback(std::make_exception_ptr(util::MisuseException("MapSnapshotter is currently rendering an image")), - PremultipliedImage(), - {}, - {}, - {}); + callback( + std::make_exception_ptr(util::MisuseException("MapSnapshotter is currently rendering an image")), + PremultipliedImage(), + {}, + {}, + {} + ); } renderStillCallback = std::make_unique>( *Scheduler::GetCurrent(), - [this, cb = std::move(callback)](std::exception_ptr ptr, - PremultipliedImage image, - Attributions attributions, - PointForFn pfn, - LatLngForFn latLonFn) { + [this, cb = std::move(callback)]( + std::exception_ptr ptr, + PremultipliedImage image, + Attributions attributions, + PointForFn pfn, + LatLngForFn latLonFn + ) { cb(std::move(ptr), std::move(image), std::move(attributions), std::move(pfn), std::move(latLonFn)); renderStillCallback.reset(); - }); + } + ); map.renderStill([this, actorRef = renderStillCallback->self()](const std::exception_ptr& error) { // Create lambda that captures the current transform state @@ -209,11 +213,11 @@ class MapSnapshotter::Impl final : public MapObserver { // Create lambda that captures the current transform state // and can be used to translate for geographic to screen // coordinates - LatLngForFn latLngForFn = [transformState = - frontend.getTransformState()](const ScreenCoordinate& screenCoordinate) { - Transform transform{transformState}; - return transform.screenCoordinateToLatLng(screenCoordinate); - }; + LatLngForFn latLngForFn = + [transformState = frontend.getTransformState()](const ScreenCoordinate& screenCoordinate) { + Transform transform{transformState}; + return transform.screenCoordinateToLatLng(screenCoordinate); + }; // Collect all source attributions std::vector attributions; @@ -225,12 +229,14 @@ class MapSnapshotter::Impl final : public MapObserver { } // Invoke callback - actorRef.invoke(&MapSnapshotter::Callback::operator(), - error, - error ? PremultipliedImage() : frontend.takeImage(), - std::move(attributions), - std::move(pointForFn), - std::move(latLngForFn)); + actorRef.invoke( + &MapSnapshotter::Callback::operator(), + error, + error ? PremultipliedImage() : frontend.takeImage(), + std::move(attributions), + std::move(pointForFn), + std::move(latLngForFn) + ); }); } @@ -251,16 +257,21 @@ class MapSnapshotter::Impl final : public MapObserver { Map map; }; -MapSnapshotter::MapSnapshotter(Size size, - float pixelRatio, - const ResourceOptions& resourceOptions, - const ClientOptions& clientOptions, - MapSnapshotterObserver& observer, - std::optional localFontFamily) +MapSnapshotter::MapSnapshotter( + Size size, + float pixelRatio, + const ResourceOptions& resourceOptions, + const ClientOptions& clientOptions, + MapSnapshotterObserver& observer, + std::optional localFontFamily +) : impl(std::make_unique( - size, pixelRatio, resourceOptions, clientOptions, observer, std::move(localFontFamily))) {} + size, pixelRatio, resourceOptions, clientOptions, observer, std::move(localFontFamily) + )) {} -MapSnapshotter::MapSnapshotter(Size size, float pixelRatio, const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) +MapSnapshotter::MapSnapshotter( + Size size, float pixelRatio, const ResourceOptions& resourceOptions, const ClientOptions& clientOptions +) : MapSnapshotter(size, pixelRatio, resourceOptions, clientOptions, MapSnapshotterObserver::nullObserver()) {} MapSnapshotter::~MapSnapshotter() = default; diff --git a/platform/default/src/mbgl/storage/asset_file_source.cpp b/platform/default/src/mbgl/storage/asset_file_source.cpp index 828407b637d..96793814166 100644 --- a/platform/default/src/mbgl/storage/asset_file_source.cpp +++ b/platform/default/src/mbgl/storage/asset_file_source.cpp @@ -21,23 +21,22 @@ namespace mbgl { class AssetFileSource::Impl { public: - Impl(const ActorRef&, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_): - root (resourceOptions_.assetPath()), - resourceOptions (resourceOptions_.clone()), - clientOptions (clientOptions_.clone()) {} + Impl(const ActorRef&, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) + : root(resourceOptions_.assetPath()), + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} void request(const std::string& url, const ActorRef& req) { if (!acceptsURL(url)) { Response response; - response.error = std::make_unique(Response::Error::Reason::Other, - "Invalid asset URL"); + response.error = std::make_unique(Response::Error::Reason::Other, "Invalid asset URL"); req.invoke(&FileSourceRequest::setResponse, response); return; } // Cut off the protocol and prefix with path. - const auto path = - root + "/" + mbgl::util::percentDecode(url.substr(std::char_traits::length(util::ASSET_PROTOCOL))); + const auto path = root + "/" + + mbgl::util::percentDecode(url.substr(std::char_traits::length(util::ASSET_PROTOCOL))); requestLocalFile(path, req); } @@ -70,9 +69,12 @@ class AssetFileSource::Impl { }; AssetFileSource::AssetFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) - : impl(std::make_unique>( - util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), "AssetFileSource", resourceOptions.clone(), clientOptions.clone())) {} - + : impl(std::make_unique>( + util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), + "AssetFileSource", + resourceOptions.clone(), + clientOptions.clone() + )) {} AssetFileSource::~AssetFileSource() = default; @@ -112,5 +114,4 @@ ClientOptions AssetFileSource::getClientOptions() { return impl->actor().ask(&Impl::getClientOptions).get(); } - } // namespace mbgl diff --git a/platform/default/src/mbgl/storage/database_file_source.cpp b/platform/default/src/mbgl/storage/database_file_source.cpp index 3215e161a0e..1b190364599 100644 --- a/platform/default/src/mbgl/storage/database_file_source.cpp +++ b/platform/default/src/mbgl/storage/database_file_source.cpp @@ -19,22 +19,23 @@ namespace mbgl { class DatabaseFileSourceThread { public: DatabaseFileSourceThread(std::shared_ptr onlineFileSource_, const std::string& cachePath) - : db(std::make_unique( - cachePath, - onlineFileSource_->getResourceOptions().tileServerOptions()) - ), onlineFileSource(std::move(onlineFileSource_)) {} + : db(std::make_unique(cachePath, onlineFileSource_->getResourceOptions().tileServerOptions())), + onlineFileSource(std::move(onlineFileSource_)) {} void request(const Resource& resource, const ActorRef& req) { - std::optional offlineResponse = - (resource.storagePolicy != Resource::StoragePolicy::Volatile) ? db->get(resource) : std::nullopt; + std::optional offlineResponse = (resource.storagePolicy != Resource::StoragePolicy::Volatile) + ? db->get(resource) + : std::nullopt; if (!offlineResponse) { offlineResponse.emplace(); offlineResponse->noContent = true; - offlineResponse->error = - std::make_unique(Response::Error::Reason::NotFound, "Not found in offline database"); + offlineResponse->error = std::make_unique( + Response::Error::Reason::NotFound, "Not found in offline database" + ); } else if (!offlineResponse->isUsable()) { - offlineResponse->error = - std::make_unique(Response::Error::Reason::NotFound, "Cached resource is unusable"); + offlineResponse->error = std::make_unique( + Response::Error::Reason::NotFound, "Cached resource is unusable" + ); } req.invoke(&FileSourceRequest::setResponse, *offlineResponse); } @@ -77,25 +78,32 @@ class DatabaseFileSourceThread { callback(db->listRegions()); } - void createRegion(const OfflineRegionDefinition& definition, - const OfflineRegionMetadata& metadata, - const std::function)>& callback) { + void createRegion( + const OfflineRegionDefinition& definition, + const OfflineRegionMetadata& metadata, + const std::function)>& callback + ) { callback(db->createRegion(definition, metadata)); } - void mergeOfflineRegions(const std::string& sideDatabasePath, - const std::function)>& callback) { + void mergeOfflineRegions( + const std::string& sideDatabasePath, + const std::function)>& callback + ) { callback(db->mergeDatabase(sideDatabasePath)); } - void updateMetadata(const int64_t regionID, - const OfflineRegionMetadata& metadata, - const std::function)>& callback) { + void updateMetadata( + const int64_t regionID, + const OfflineRegionMetadata& metadata, + const std::function)>& callback + ) { callback(db->updateMetadata(regionID, metadata)); } - void getRegionStatus(int64_t regionID, - const std::function)>& callback) { + void getRegionStatus( + int64_t regionID, const std::function)>& callback + ) { if (auto download = getDownload(regionID)) { callback(download.value()->getStatus()); } else { @@ -132,7 +140,8 @@ class DatabaseFileSourceThread { expected getDownload(int64_t regionID) { if (!onlineFileSource) { return unexpected( - std::make_exception_ptr(std::runtime_error("Network file source unavailable."))); + std::make_exception_ptr(std::runtime_error("Network file source unavailable.")) + ); } auto it = downloads.find(regionID); @@ -143,8 +152,9 @@ class DatabaseFileSourceThread { if (!definition) { return unexpected(definition.error()); } - auto download = - std::make_unique(regionID, std::move(definition.value()), *db, *onlineFileSource); + auto download = std::make_unique( + regionID, std::move(definition.value()), *db, *onlineFileSource + ); return downloads.emplace(regionID, std::move(download)).first->second.get(); } @@ -155,14 +165,19 @@ class DatabaseFileSourceThread { class DatabaseFileSource::Impl { public: - Impl(std::shared_ptr onlineFileSource, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) : - thread(std::make_unique>( + Impl( + std::shared_ptr onlineFileSource, + const ResourceOptions& resourceOptions_, + const ClientOptions& clientOptions_ + ) + : thread(std::make_unique>( util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_DATABASE), "DatabaseFileSource", std::move(onlineFileSource), - resourceOptions_.cachePath())), - resourceOptions(resourceOptions_.clone()), - clientOptions(clientOptions_.clone()) {} + resourceOptions_.cachePath() + )), + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} ActorRef actor() const { return thread->actor(); } @@ -199,9 +214,10 @@ class DatabaseFileSource::Impl { DatabaseFileSource::DatabaseFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) : impl(std::make_unique( - FileSourceManager::get()->getFileSource(FileSourceType::Network, resourceOptions, clientOptions), - resourceOptions, - clientOptions)) {} + FileSourceManager::get()->getFileSource(FileSourceType::Network, resourceOptions, clientOptions), + resourceOptions, + clientOptions + )) {} DatabaseFileSource::~DatabaseFileSource() = default; @@ -259,42 +275,48 @@ void DatabaseFileSource::setMaximumAmbientCacheSize(uint64_t size, std::function impl->actor().invoke(&DatabaseFileSourceThread::setMaximumAmbientCacheSize, size, std::move(callback)); } -void DatabaseFileSource::listOfflineRegions( - std::function)> callback) { +void DatabaseFileSource::listOfflineRegions(std::function)> callback +) { impl->actor().invoke(&DatabaseFileSourceThread::listRegions, std::move(callback)); } void DatabaseFileSource::createOfflineRegion( const OfflineRegionDefinition& definition, const OfflineRegionMetadata& metadata, - std::function)> callback) { + std::function)> callback +) { impl->actor().invoke(&DatabaseFileSourceThread::createRegion, definition, metadata, std::move(callback)); } void DatabaseFileSource::mergeOfflineRegions( - const std::string& sideDatabasePath, std::function)> callback) { + const std::string& sideDatabasePath, std::function)> callback +) { impl->actor().invoke(&DatabaseFileSourceThread::mergeOfflineRegions, sideDatabasePath, std::move(callback)); } void DatabaseFileSource::updateOfflineMetadata( const int64_t regionID, const OfflineRegionMetadata& metadata, - std::function)> callback) { + std::function)> callback +) { impl->actor().invoke(&DatabaseFileSourceThread::updateMetadata, regionID, metadata, std::move(callback)); } -void DatabaseFileSource::deleteOfflineRegion(const OfflineRegion& region, - std::function callback) { +void DatabaseFileSource::deleteOfflineRegion( + const OfflineRegion& region, std::function callback +) { impl->actor().invoke(&DatabaseFileSourceThread::deleteRegion, region, std::move(callback)); } -void DatabaseFileSource::invalidateOfflineRegion(const OfflineRegion& region, - std::function callback) { +void DatabaseFileSource::invalidateOfflineRegion( + const OfflineRegion& region, std::function callback +) { impl->actor().invoke(&DatabaseFileSourceThread::invalidateRegion, region.getID(), std::move(callback)); } -void DatabaseFileSource::setOfflineRegionObserver(const OfflineRegion& region, - std::unique_ptr observer) { +void DatabaseFileSource::setOfflineRegionObserver( + const OfflineRegion& region, std::unique_ptr observer +) { impl->actor().invoke(&DatabaseFileSourceThread::setRegionObserver, region.getID(), std::move(observer)); } @@ -303,8 +325,8 @@ void DatabaseFileSource::setOfflineRegionDownloadState(const OfflineRegion& regi } void DatabaseFileSource::getOfflineRegionStatus( - const OfflineRegion& region, - std::function)> callback) const { + const OfflineRegion& region, std::function)> callback +) const { impl->actor().invoke(&DatabaseFileSourceThread::getRegionStatus, region.getID(), std::move(callback)); } diff --git a/platform/default/src/mbgl/storage/file_source_manager.cpp b/platform/default/src/mbgl/storage/file_source_manager.cpp index ceddf13f550..3a52459ee3c 100644 --- a/platform/default/src/mbgl/storage/file_source_manager.cpp +++ b/platform/default/src/mbgl/storage/file_source_manager.cpp @@ -12,29 +12,47 @@ namespace mbgl { class DefaultFileSourceManagerImpl final : public FileSourceManager { public: DefaultFileSourceManagerImpl() { - registerFileSourceFactory(FileSourceType::ResourceLoader, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); + registerFileSourceFactory( + FileSourceType::ResourceLoader, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + } + ); - registerFileSourceFactory(FileSourceType::Asset, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); + registerFileSourceFactory( + FileSourceType::Asset, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + } + ); - registerFileSourceFactory(FileSourceType::Database, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); + registerFileSourceFactory( + FileSourceType::Database, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + } + ); - registerFileSourceFactory(FileSourceType::FileSystem, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); + registerFileSourceFactory( + FileSourceType::FileSystem, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + } + ); - registerFileSourceFactory(FileSourceType::Mbtiles, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); + registerFileSourceFactory( + FileSourceType::Mbtiles, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + } + ); - registerFileSourceFactory(FileSourceType::Network, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); + registerFileSourceFactory( + FileSourceType::Network, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + } + ); } }; diff --git a/platform/default/src/mbgl/storage/file_source_request.cpp b/platform/default/src/mbgl/storage/file_source_request.cpp index 09ea8cc32a9..667cbf345af 100644 --- a/platform/default/src/mbgl/storage/file_source_request.cpp +++ b/platform/default/src/mbgl/storage/file_source_request.cpp @@ -6,9 +6,8 @@ namespace mbgl { FileSourceRequest::FileSourceRequest(FileSource::Callback&& callback) - : responseCallback(callback) - , mailbox(std::make_shared(*Scheduler::GetCurrent())) { -} + : responseCallback(callback), + mailbox(std::make_shared(*Scheduler::GetCurrent())) {} FileSourceRequest::~FileSourceRequest() { if (cancelCallback) { diff --git a/platform/default/src/mbgl/storage/http_file_source.cpp b/platform/default/src/mbgl/storage/http_file_source.cpp index dc002a0d8ec..c5e10ff88ac 100644 --- a/platform/default/src/mbgl/storage/http_file_source.cpp +++ b/platform/default/src/mbgl/storage/http_file_source.cpp @@ -38,7 +38,7 @@ namespace mbgl { class HTTPFileSource::Impl { public: - Impl(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_); + Impl(const ResourceOptions &resourceOptions_, const ClientOptions &clientOptions_); ~Impl(); static int handleSocket(CURL *handle, curl_socket_t s, int action, void *userp, void *socketp); @@ -79,7 +79,7 @@ class HTTPFileSource::Impl { class HTTPRequest : public AsyncRequest { public: - HTTPRequest(HTTPFileSource::Impl*, Resource, FileSource::Callback); + HTTPRequest(HTTPFileSource::Impl *, Resource, FileSource::Callback); ~HTTPRequest() override; void handleResult(CURLcode code); @@ -88,7 +88,7 @@ class HTTPRequest : public AsyncRequest { static size_t headerCallback(char *buffer, size_t size, size_t nmemb, void *userp); static size_t writeCallback(void *contents, size_t size, size_t nmemb, void *userp); - HTTPFileSource::Impl* context = nullptr; + HTTPFileSource::Impl *context = nullptr; Resource resource; FileSource::Callback callback; @@ -102,11 +102,12 @@ class HTTPRequest : public AsyncRequest { CURL *handle = nullptr; curl_slist *headers = nullptr; - char error[CURL_ERROR_SIZE] = { 0 }; + char error[CURL_ERROR_SIZE] = {0}; }; -HTTPFileSource::Impl::Impl(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions (resourceOptions_.clone()), clientOptions (clientOptions_.clone()) { +HTTPFileSource::Impl::Impl(const ResourceOptions &resourceOptions_, const ClientOptions &clientOptions_) + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) { if (curl_global_init(CURL_GLOBAL_ALL)) { throw std::runtime_error("Could not init cURL"); } @@ -156,16 +157,16 @@ void HTTPFileSource::Impl::checkMultiInfo() { while ((message = curl_multi_info_read(multi, &pending))) { switch (message->msg) { - case CURLMSG_DONE: { - HTTPRequest *baton = nullptr; - curl_easy_getinfo(message->easy_handle, CURLINFO_PRIVATE, (char *)&baton); - assert(baton); - baton->handleResult(message->data.result); - } break; - - default: - // This should never happen, because there are no other message types. - throw std::runtime_error("CURLMsg returned unknown message type"); + case CURLMSG_DONE: { + HTTPRequest *baton = nullptr; + curl_easy_getinfo(message->easy_handle, CURLINFO_PRIVATE, (char *)&baton); + assert(baton); + baton->handleResult(message->data.result); + } break; + + default: + // This should never happen, because there are no other message types. + throw std::runtime_error("CURLMsg returned unknown message type"); } } } @@ -180,35 +181,36 @@ void HTTPFileSource::Impl::perform(curl_socket_t s, util::RunLoop::Event events) flags |= CURL_CSELECT_OUT; } - int running_handles = 0; curl_multi_socket_action(multi, s, flags, &running_handles); checkMultiInfo(); } -int HTTPFileSource::Impl::handleSocket(CURL * /* handle */, curl_socket_t s, int action, void *userp, - void * /* socketp */) { +int HTTPFileSource::Impl:: + handleSocket(CURL * /* handle */, curl_socket_t s, int action, void *userp, void * /* socketp */) { assert(userp); auto context = reinterpret_cast(userp); switch (action) { - case CURL_POLL_IN: { - using namespace std::placeholders; - util::RunLoop::Get()->addWatch(static_cast(s), util::RunLoop::Event::Read, - std::bind(&Impl::perform, context, _1, _2)); - break; - } - case CURL_POLL_OUT: { - using namespace std::placeholders; - util::RunLoop::Get()->addWatch(static_cast(s), util::RunLoop::Event::Write, - std::bind(&Impl::perform, context, _1, _2)); - break; - } - case CURL_POLL_REMOVE: - util::RunLoop::Get()->removeWatch(static_cast(s)); - break; - default: - throw std::runtime_error("Unhandled CURL socket action"); + case CURL_POLL_IN: { + using namespace std::placeholders; + util::RunLoop::Get()->addWatch( + static_cast(s), util::RunLoop::Event::Read, std::bind(&Impl::perform, context, _1, _2) + ); + break; + } + case CURL_POLL_OUT: { + using namespace std::placeholders; + util::RunLoop::Get()->addWatch( + static_cast(s), util::RunLoop::Event::Write, std::bind(&Impl::perform, context, _1, _2) + ); + break; + } + case CURL_POLL_REMOVE: + util::RunLoop::Get()->removeWatch(static_cast(s)); + break; + default: + throw std::runtime_error("Unhandled CURL socket action"); } return 0; @@ -233,8 +235,7 @@ int HTTPFileSource::Impl::startTimeout(CURLM * /* multi */, long timeout_ms, voi } context->timeout.stop(); - context->timeout.start(mbgl::Milliseconds(timeout_ms), Duration::zero(), - std::bind(&Impl::onTimeout, context)); + context->timeout.start(mbgl::Milliseconds(timeout_ms), Duration::zero(), std::bind(&Impl::onTimeout, context)); return 0; } @@ -259,20 +260,18 @@ ClientOptions HTTPFileSource::Impl::getClientOptions() { return clientOptions.clone(); } -HTTPRequest::HTTPRequest(HTTPFileSource::Impl* context_, Resource resource_, FileSource::Callback callback_) +HTTPRequest::HTTPRequest(HTTPFileSource::Impl *context_, Resource resource_, FileSource::Callback callback_) : context(context_), resource(std::move(resource_)), callback(std::move(callback_)), handle(context->getHandle()) { - // If there's already a response, set the correct etags/modified headers to make sure we are // getting a 304 response if possible. This avoids redownloading unchanged data. if (resource.priorEtag) { const std::string header = std::string("If-None-Match: ") + *resource.priorEtag; headers = curl_slist_append(headers, header.c_str()); } else if (resource.priorModified) { - const std::string time = - std::string("If-Modified-Since: ") + util::rfc1123(*resource.priorModified); + const std::string time = std::string("If-Modified-Since: ") + util::rfc1123(*resource.priorModified); headers = curl_slist_append(headers, time.c_str()); } @@ -363,17 +362,17 @@ size_t HTTPRequest::headerCallback(char *const buffer, const size_t size, const if ((begin = headerMatches("last-modified: ", buffer, length)) != std::string::npos) { // Always overwrite the modification date; We might already have a value here from the // Date header, but this one is more accurate. - const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n + const std::string value{buffer + begin, length - begin - 2}; // remove \r\n baton->response->modified = Timestamp{Seconds(curl_getdate(value.c_str(), nullptr))}; } else if ((begin = headerMatches("etag: ", buffer, length)) != std::string::npos) { baton->response->etag = std::string(buffer + begin, length - begin - 2); // remove \r\n } else if ((begin = headerMatches("cache-control: ", buffer, length)) != std::string::npos) { - const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n + const std::string value{buffer + begin, length - begin - 2}; // remove \r\n const auto cc = http::CacheControl::parse(value); baton->response->expires = cc.toTimePoint(); baton->response->mustRevalidate = cc.mustRevalidate; } else if ((begin = headerMatches("expires: ", buffer, length)) != std::string::npos) { - const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n + const std::string value{buffer + begin, length - begin - 2}; // remove \r\n baton->response->expires = Timestamp{Seconds(curl_getdate(value.c_str(), nullptr))}; } else if ((begin = headerMatches("retry-after: ", buffer, length)) != std::string::npos) { baton->retryAfter = std::string(buffer + begin, length - begin - 2); // remove \r\n @@ -396,19 +395,21 @@ void HTTPRequest::handleResult(CURLcode code) { // Add human-readable error code if (code != CURLE_OK) { switch (code) { - case CURLE_COULDNT_RESOLVE_PROXY: - case CURLE_COULDNT_RESOLVE_HOST: - case CURLE_COULDNT_CONNECT: - case CURLE_OPERATION_TIMEDOUT: - - response->error = std::make_unique(Error::Reason::Connection, - std::string{curl_easy_strerror(code)} + ": " + error); - break; - - default: - response->error = - std::make_unique(Error::Reason::Other, std::string{curl_easy_strerror(code)} + ": " + error); - break; + case CURLE_COULDNT_RESOLVE_PROXY: + case CURLE_COULDNT_RESOLVE_HOST: + case CURLE_COULDNT_CONNECT: + case CURLE_OPERATION_TIMEDOUT: + + response->error = std::make_unique( + Error::Reason::Connection, std::string{curl_easy_strerror(code)} + ": " + error + ); + break; + + default: + response->error = std::make_unique( + Error::Reason::Other, std::string{curl_easy_strerror(code)} + ": " + error + ); + break; } } else { long responseCode = 0; @@ -425,20 +426,19 @@ void HTTPRequest::handleResult(CURLcode code) { } else if (responseCode == 304) { response->notModified = true; } else if (responseCode == 404) { - response->error = - std::make_unique(Error::Reason::NotFound, "HTTP status code 404"); + response->error = std::make_unique(Error::Reason::NotFound, "HTTP status code 404"); } else if (responseCode == 429) { - response->error = - std::make_unique(Error::Reason::RateLimit, "HTTP status code 429", - http::parseRetryHeaders(retryAfter, xRateLimitReset)); + response->error = std::make_unique( + Error::Reason::RateLimit, "HTTP status code 429", http::parseRetryHeaders(retryAfter, xRateLimitReset) + ); } else if (responseCode >= 500 && responseCode < 600) { - response->error = - std::make_unique(Error::Reason::Server, std::string{ "HTTP status code " } + - util::toString(responseCode)); + response->error = std::make_unique( + Error::Reason::Server, std::string{"HTTP status code "} + util::toString(responseCode) + ); } else { - response->error = - std::make_unique(Error::Reason::Other, std::string{ "HTTP status code " } + - util::toString(responseCode)); + response->error = std::make_unique( + Error::Reason::Other, std::string{"HTTP status code "} + util::toString(responseCode) + ); } } @@ -448,13 +448,12 @@ void HTTPRequest::handleResult(CURLcode code) { callback_(response_); } -HTTPFileSource::HTTPFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) - : impl(std::make_unique(resourceOptions, clientOptions)) { -} +HTTPFileSource::HTTPFileSource(const ResourceOptions &resourceOptions, const ClientOptions &clientOptions) + : impl(std::make_unique(resourceOptions, clientOptions)) {} HTTPFileSource::~HTTPFileSource() = default; -std::unique_ptr HTTPFileSource::request(const Resource& resource, Callback callback) { +std::unique_ptr HTTPFileSource::request(const Resource &resource, Callback callback) { return std::make_unique(impl.get(), resource, callback); } diff --git a/platform/default/src/mbgl/storage/local_file_request.cpp b/platform/default/src/mbgl/storage/local_file_request.cpp index 1f00ebdb854..db2dcef7768 100644 --- a/platform/default/src/mbgl/storage/local_file_request.cpp +++ b/platform/default/src/mbgl/storage/local_file_request.cpp @@ -6,7 +6,7 @@ #include #if defined(_WIN32) && !defined(S_ISDIR) -#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +#define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR) #endif namespace mbgl { @@ -24,8 +24,8 @@ void requestLocalFile(const std::string& path, const ActorRef auto data = util::readFile(path); if (!data) { response.error = std::make_unique( - Response::Error::Reason::Other, - std::string("Cannot read file ") + path); + Response::Error::Reason::Other, std::string("Cannot read file ") + path + ); } else { response.data = std::make_shared(std::move(*data)); } diff --git a/platform/default/src/mbgl/storage/local_file_source.cpp b/platform/default/src/mbgl/storage/local_file_source.cpp index 2df1f4e8053..06423d860dd 100644 --- a/platform/default/src/mbgl/storage/local_file_source.cpp +++ b/platform/default/src/mbgl/storage/local_file_source.cpp @@ -22,13 +22,13 @@ namespace mbgl { class LocalFileSource::Impl { public: explicit Impl(const ActorRef&, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions (resourceOptions_.clone()), clientOptions (clientOptions_.clone()) {} + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} void request(const std::string& url, const ActorRef& req) { if (!acceptsURL(url)) { Response response; - response.error = std::make_unique(Response::Error::Reason::Other, - "Invalid file URL"); + response.error = std::make_unique(Response::Error::Reason::Other, "Invalid file URL"); req.invoke(&FileSourceRequest::setResponse, response); return; } @@ -58,7 +58,6 @@ class LocalFileSource::Impl { return clientOptions.clone(); } - private: mutable std::mutex resourceOptionsMutex; mutable std::mutex clientOptionsMutex; @@ -66,9 +65,13 @@ class LocalFileSource::Impl { ClientOptions clientOptions; }; -LocalFileSource::LocalFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions): - impl(std::make_unique>( - util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), "LocalFileSource", resourceOptions.clone(), clientOptions.clone())) {} +LocalFileSource::LocalFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) + : impl(std::make_unique>( + util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), + "LocalFileSource", + resourceOptions.clone(), + clientOptions.clone() + )) {} LocalFileSource::~LocalFileSource() = default; @@ -108,5 +111,4 @@ ClientOptions LocalFileSource::getClientOptions() { return impl->actor().ask(&Impl::getClientOptions).get(); } - } // namespace mbgl diff --git a/platform/default/src/mbgl/storage/main_resource_loader.cpp b/platform/default/src/mbgl/storage/main_resource_loader.cpp index 5d051e796f2..04f27dae0e5 100644 --- a/platform/default/src/mbgl/storage/main_resource_loader.cpp +++ b/platform/default/src/mbgl/storage/main_resource_loader.cpp @@ -17,11 +17,13 @@ namespace mbgl { class MainResourceLoaderThread { public: - MainResourceLoaderThread(std::shared_ptr assetFileSource_, - std::shared_ptr databaseFileSource_, - std::shared_ptr localFileSource_, - std::shared_ptr onlineFileSource_, - std::shared_ptr mbtilesFileSource_) + MainResourceLoaderThread( + std::shared_ptr assetFileSource_, + std::shared_ptr databaseFileSource_, + std::shared_ptr localFileSource_, + std::shared_ptr onlineFileSource_, + std::shared_ptr mbtilesFileSource_ + ) : assetFileSource(std::move(assetFileSource_)), databaseFileSource(std::move(databaseFileSource_)), localFileSource(std::move(localFileSource_)), @@ -29,7 +31,9 @@ class MainResourceLoaderThread { mbtilesFileSource(std::move(mbtilesFileSource_)) {} void request(AsyncRequest* req, const Resource& resource, const ActorRef& ref) { - auto callback = [ref](const Response& res) { ref.invoke(&FileSourceRequest::setResponse, res); }; + auto callback = [ref](const Response& res) { + ref.invoke(&FileSourceRequest::setResponse, res); + }; auto requestFromNetwork = [=](const Resource& res, std::unique_ptr parent) -> std::unique_ptr { @@ -47,12 +51,14 @@ class MainResourceLoaderThread { } if (res.kind == Resource::Kind::Tile) { // onlineResponse.data will be null if data not modified - MBGL_TIMING_FINISH(watch, - " Action: " - << "Requesting," - << " URL: " << res.url.c_str() << " Size: " - << (response.data != nullptr ? response.data->size() : 0) << "B," - << " Time") + MBGL_TIMING_FINISH( + watch, + " Action: " + << "Requesting," + << " URL: " << res.url.c_str() + << " Size: " << (response.data != nullptr ? response.data->size() : 0) << "B," + << " Time" + ) } callback(response); }); @@ -112,8 +118,9 @@ class MainResourceLoaderThread { if (tasks.size() == tasksSize) { Response response; response.noContent = true; - response.error = - std::make_unique(Response::Error::Reason::Other, "Unsupported resource request."); + response.error = std::make_unique( + Response::Error::Reason::Other, "Unsupported resource request." + ); callback(response); } } @@ -134,13 +141,15 @@ class MainResourceLoaderThread { class MainResourceLoader::Impl { public: - Impl(const ResourceOptions& resourceOptions_, - const ClientOptions& clientOptions_, - std::shared_ptr assetFileSource_, - std::shared_ptr databaseFileSource_, - std::shared_ptr localFileSource_, - std::shared_ptr onlineFileSource_, - std::shared_ptr mbtilesFileSource_) + Impl( + const ResourceOptions& resourceOptions_, + const ClientOptions& clientOptions_, + std::shared_ptr assetFileSource_, + std::shared_ptr databaseFileSource_, + std::shared_ptr localFileSource_, + std::shared_ptr onlineFileSource_, + std::shared_ptr mbtilesFileSource_ + ) : assetFileSource(std::move(assetFileSource_)), databaseFileSource(std::move(databaseFileSource_)), localFileSource(std::move(localFileSource_)), @@ -154,9 +163,10 @@ class MainResourceLoader::Impl { databaseFileSource, localFileSource, onlineFileSource, - mbtilesFileSource)), - resourceOptions (resourceOptions_.clone()), - clientOptions (clientOptions_.clone()) {} + mbtilesFileSource + )), + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} std::unique_ptr request(const Resource& resource, Callback callback) { auto req = std::make_unique(std::move(callback)); @@ -226,14 +236,16 @@ class MainResourceLoader::Impl { ClientOptions clientOptions; }; -MainResourceLoader::MainResourceLoader(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions): - impl(std::make_unique(resourceOptions.clone(), - clientOptions.clone(), - FileSourceManager::get()->getFileSource(FileSourceType::Asset, resourceOptions, clientOptions), - FileSourceManager::get()->getFileSource(FileSourceType::Database, resourceOptions, clientOptions), - FileSourceManager::get()->getFileSource(FileSourceType::FileSystem, resourceOptions, clientOptions), - FileSourceManager::get()->getFileSource(FileSourceType::Network, resourceOptions, clientOptions), - FileSourceManager::get()->getFileSource(FileSourceType::Mbtiles, resourceOptions, clientOptions))) {} +MainResourceLoader::MainResourceLoader(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) + : impl(std::make_unique( + resourceOptions.clone(), + clientOptions.clone(), + FileSourceManager::get()->getFileSource(FileSourceType::Asset, resourceOptions, clientOptions), + FileSourceManager::get()->getFileSource(FileSourceType::Database, resourceOptions, clientOptions), + FileSourceManager::get()->getFileSource(FileSourceType::FileSystem, resourceOptions, clientOptions), + FileSourceManager::get()->getFileSource(FileSourceType::Network, resourceOptions, clientOptions), + FileSourceManager::get()->getFileSource(FileSourceType::Mbtiles, resourceOptions, clientOptions) + )) {} MainResourceLoader::~MainResourceLoader() = default; diff --git a/platform/default/src/mbgl/storage/mbtiles_file_source.cpp b/platform/default/src/mbgl/storage/mbtiles_file_source.cpp index f9c6d7dc6c6..a82512b1d4f 100644 --- a/platform/default/src/mbgl/storage/mbtiles_file_source.cpp +++ b/platform/default/src/mbgl/storage/mbtiles_file_source.cpp @@ -27,7 +27,7 @@ #endif namespace { -bool acceptsURL(const std::string& url) { +bool acceptsURL(const std::string &url) { return 0 == url.rfind(mbgl::util::MBTILES_PROTOCOL, 0); } @@ -39,11 +39,11 @@ std::string url_to_path(const std::string &url) { namespace mbgl { using namespace rapidjson; - class MBTilesFileSource::Impl { public: - explicit Impl(const ActorRef&, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions (resourceOptions_.clone()), clientOptions (clientOptions_.clone()) {} + explicit Impl(const ActorRef &, const ResourceOptions &resourceOptions_, const ClientOptions &clientOptions_) + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} std::vector &split(const std::string &s, char delim, std::vector &elems) { std::stringstream ss(s); @@ -62,7 +62,6 @@ class MBTilesFileSource::Impl { } std::string serialize(Document &doc) { - StringBuffer buffer; Writer writer(buffer); doc.Accept(writer); @@ -70,15 +69,9 @@ class MBTilesFileSource::Impl { return std::string(buffer.GetString(), buffer.GetSize()); } + std::string db_path(const std::string &path) { return path.substr(0, path.find('?')); } - - std::string db_path(const std::string &path) { - return path.substr(0, path.find('?')); - } - - bool is_compressed(const std::string &v) { - return (((uint8_t) v[0]) == 0x1f) && (((uint8_t) v[1]) == 0x8b); - } + bool is_compressed(const std::string &v) { return (((uint8_t)v[0]) == 0x1f) && (((uint8_t)v[1]) == 0x8b); } // Generate a tilejson resource from .mbtiles file void request_tilejson(const Resource &resource, ActorRef req) { @@ -140,8 +133,7 @@ class MBTilesFileSource::Impl { values["minzoom"] = minz; values["maxzoom"] = maxz; - } - else { + } else { minz = minzoom_ptr->second; maxz = maxzoom_ptr->second; } @@ -202,15 +194,14 @@ class MBTilesFileSource::Impl { auto y = std::to_string((int)(pow(2, iz) - 1) - iy); auto z = std::to_string(iz); - std::string sql = "SELECT tile_data FROM tiles where zoom_level = " + z + - " AND tile_column = " + x + " AND tile_row = " + y; + std::string sql = "SELECT tile_data FROM tiles where zoom_level = " + z + " AND tile_column = " + x + + " AND tile_row = " + y; mapbox::sqlite::Statement stmt(db, sql.c_str()); Response response; response.noContent = true; for (mapbox::sqlite::Query q(stmt); q.run();) { - std::optional data = q.get>(0); if (data) { response.data = std::make_shared(*data); @@ -227,8 +218,8 @@ class MBTilesFileSource::Impl { } void setResourceOptions(ResourceOptions options) { - std::lock_guard lock(resourceOptionsMutex); - resourceOptions = options; + std::lock_guard lock(resourceOptionsMutex); + resourceOptions = options; } ResourceOptions getResourceOptions() { @@ -246,7 +237,6 @@ class MBTilesFileSource::Impl { return clientOptions.clone(); } - private: std::map db_cache; @@ -257,9 +247,7 @@ class MBTilesFileSource::Impl { } } - void close_all() { - db_cache.clear(); - } + void close_all() { db_cache.clear(); } // Multiple databases open simultaneoulsy, to effectively support multiple .mbtiles maps mapbox::sqlite::Database &get_db(const std::string &path) { @@ -268,7 +256,9 @@ class MBTilesFileSource::Impl { return ptr->second; }; - auto ptr2 = db_cache.insert(std::pair(path, mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly))); + auto ptr2 = db_cache.insert(std::pair( + path, mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly) + )); return ptr2.first->second; } @@ -278,10 +268,13 @@ class MBTilesFileSource::Impl { ClientOptions clientOptions; }; - -MBTilesFileSource::MBTilesFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) : - thread(std::make_unique>( - util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), "MBTilesFileSource", resourceOptions.clone(), clientOptions.clone())) {} +MBTilesFileSource::MBTilesFileSource(const ResourceOptions &resourceOptions, const ClientOptions &clientOptions) + : thread(std::make_unique>( + util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), + "MBTilesFileSource", + resourceOptions.clone(), + clientOptions.clone() + )) {} std::unique_ptr MBTilesFileSource::request(const Resource &resource, FileSource::Callback callback) { auto req = std::make_unique(std::move(callback)); @@ -296,7 +289,8 @@ std::unique_ptr MBTilesFileSource::request(const Resource &resourc Response response; response.noContent = true; response.error = std::make_unique( - Response::Error::Reason::Other, "MBTilesFileSource only supports absolute path urls"); + Response::Error::Reason::Other, "MBTilesFileSource only supports absolute path urls" + ); req->actor().invoke(&FileSourceRequest::setResponse, response); return req; } @@ -308,7 +302,9 @@ std::unique_ptr MBTilesFileSource::request(const Resource &resourc if (result == -1 && errno == ENOENT) { Response response; response.noContent = true; - response.error = std::make_unique(Response::Error::Reason::NotFound, "path not found: "+path); + response.error = std::make_unique( + Response::Error::Reason::NotFound, "path not found: " + path + ); req->actor().invoke(&FileSourceRequest::setResponse, response); return req; } @@ -318,7 +314,7 @@ std::unique_ptr MBTilesFileSource::request(const Resource &resourc return req; } -bool MBTilesFileSource::canRequest(const Resource& resource) const { +bool MBTilesFileSource::canRequest(const Resource &resource) const { return acceptsURL(resource.url); } @@ -340,4 +336,4 @@ ClientOptions MBTilesFileSource::getClientOptions() { return thread->actor().ask(&Impl::getClientOptions).get(); } -} +} // namespace mbgl diff --git a/platform/default/src/mbgl/storage/offline.cpp b/platform/default/src/mbgl/storage/offline.cpp index a2e42359f03..1c659ec14e1 100644 --- a/platform/default/src/mbgl/storage/offline.cpp +++ b/platform/default/src/mbgl/storage/offline.cpp @@ -16,35 +16,44 @@ namespace mbgl { // OfflineTilePyramidRegionDefinition -OfflineTilePyramidRegionDefinition::OfflineTilePyramidRegionDefinition(std::string styleURL_, - LatLngBounds bounds_, - double minZoom_, - double maxZoom_, - float pixelRatio_, - bool includeIdeographs_) +OfflineTilePyramidRegionDefinition::OfflineTilePyramidRegionDefinition( + std::string styleURL_, + LatLngBounds bounds_, + double minZoom_, + double maxZoom_, + float pixelRatio_, + bool includeIdeographs_ +) : styleURL(std::move(styleURL_)), bounds(bounds_), minZoom(minZoom_), maxZoom(maxZoom_), pixelRatio(pixelRatio_), includeIdeographs(includeIdeographs_) { - if (minZoom < 0 || maxZoom < 0 || maxZoom < minZoom || pixelRatio < 0 || - !std::isfinite(minZoom) || std::isnan(maxZoom) || !std::isfinite(pixelRatio)) { + if (minZoom < 0 || maxZoom < 0 || maxZoom < minZoom || pixelRatio < 0 || !std::isfinite(minZoom) || + std::isnan(maxZoom) || !std::isfinite(pixelRatio)) { throw std::invalid_argument("Invalid offline region definition"); } } // OfflineGeometryRegionDefinition -OfflineGeometryRegionDefinition::OfflineGeometryRegionDefinition(std::string styleURL_, Geometry geometry_, double minZoom_, double maxZoom_, float pixelRatio_, bool includeIdeographs_) - : styleURL(std::move(styleURL_)) - , geometry(std::move(geometry_)) - , minZoom(minZoom_) - , maxZoom(maxZoom_) - , pixelRatio(pixelRatio_) - , includeIdeographs(includeIdeographs_){ - if (minZoom < 0 || maxZoom < 0 || maxZoom < minZoom || pixelRatio < 0 || - !std::isfinite(minZoom) || std::isnan(maxZoom) || !std::isfinite(pixelRatio)) { +OfflineGeometryRegionDefinition::OfflineGeometryRegionDefinition( + std::string styleURL_, + Geometry geometry_, + double minZoom_, + double maxZoom_, + float pixelRatio_, + bool includeIdeographs_ +) + : styleURL(std::move(styleURL_)), + geometry(std::move(geometry_)), + minZoom(minZoom_), + maxZoom(maxZoom_), + pixelRatio(pixelRatio_), + includeIdeographs(includeIdeographs_) { + if (minZoom < 0 || maxZoom < 0 || maxZoom < minZoom || pixelRatio < 0 || !std::isfinite(minZoom) || + std::isnan(maxZoom) || !std::isfinite(pixelRatio)) { throw std::invalid_argument("Invalid offline region definition"); } } @@ -56,47 +65,51 @@ OfflineRegionDefinition decodeOfflineRegionDefinition(const std::string& region) // validation auto hasValidBounds = [&] { - return doc.HasMember("bounds") && doc["bounds"].IsArray() && doc["bounds"].Size() == 4 - && doc["bounds"][0].IsDouble() && doc["bounds"][1].IsDouble() - && doc["bounds"][2].IsDouble() && doc["bounds"][3].IsDouble(); + return doc.HasMember("bounds") && doc["bounds"].IsArray() && doc["bounds"].Size() == 4 && + doc["bounds"][0].IsDouble() && doc["bounds"][1].IsDouble() && doc["bounds"][2].IsDouble() && + doc["bounds"][3].IsDouble(); }; auto hasValidGeometry = [&] { return doc.HasMember("geometry") && doc["geometry"].IsObject(); }; - if (doc.HasParseError() - || !doc.HasMember("style_url") || !doc["style_url"].IsString() - || !(hasValidBounds() || hasValidGeometry()) - || !doc.HasMember("min_zoom") || !doc["min_zoom"].IsDouble() - || (doc.HasMember("max_zoom") && !doc["max_zoom"].IsDouble()) - || !doc.HasMember("pixel_ratio") || !doc["pixel_ratio"].IsDouble() - || (doc.HasMember("include_ideographs") && !doc["include_ideographs"].IsBool())) { + if (doc.HasParseError() || !doc.HasMember("style_url") || !doc["style_url"].IsString() || + !(hasValidBounds() || hasValidGeometry()) || !doc.HasMember("min_zoom") || !doc["min_zoom"].IsDouble() || + (doc.HasMember("max_zoom") && !doc["max_zoom"].IsDouble()) || !doc.HasMember("pixel_ratio") || + !doc["pixel_ratio"].IsDouble() || + (doc.HasMember("include_ideographs") && !doc["include_ideographs"].IsBool())) { throw std::runtime_error("Malformed offline region definition"); } // Common properties - std::string styleURL { doc["style_url"].GetString(), doc["style_url"].GetStringLength() }; + std::string styleURL{doc["style_url"].GetString(), doc["style_url"].GetStringLength()}; double minZoom = doc["min_zoom"].GetDouble(); double maxZoom = doc.HasMember("max_zoom") ? doc["max_zoom"].GetDouble() : INFINITY; auto pixelRatio = static_cast(doc["pixel_ratio"].GetDouble()); bool includeIdeographs = doc.HasMember("include_ideographs") ? doc["include_ideographs"].GetBool() : true; - + if (doc.HasMember("bounds")) { return OfflineTilePyramidRegionDefinition{ - styleURL, - LatLngBounds::hull( - LatLng(doc["bounds"][0].GetDouble(), doc["bounds"][1].GetDouble()), - LatLng(doc["bounds"][2].GetDouble(), doc["bounds"][3].GetDouble())), - minZoom, maxZoom, pixelRatio, includeIdeographs }; + styleURL, + LatLngBounds::hull( + LatLng(doc["bounds"][0].GetDouble(), doc["bounds"][1].GetDouble()), + LatLng(doc["bounds"][2].GetDouble(), doc["bounds"][3].GetDouble()) + ), + minZoom, + maxZoom, + pixelRatio, + includeIdeographs}; } else { return OfflineGeometryRegionDefinition{ - styleURL, - mapbox::geojson::convert>(doc["geometry"].GetObject()), - minZoom, maxZoom, pixelRatio, includeIdeographs }; + styleURL, + mapbox::geojson::convert>(doc["geometry"].GetObject()), + minZoom, + maxZoom, + pixelRatio, + includeIdeographs}; }; - } std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition& region) { @@ -105,7 +118,9 @@ std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition& region) // Encode common properties region.match([&](auto& _region) { - doc.AddMember("style_url", rapidjson::StringRef(_region.styleURL.data(), _region.styleURL.length()), doc.GetAllocator()); + doc.AddMember( + "style_url", rapidjson::StringRef(_region.styleURL.data(), _region.styleURL.length()), doc.GetAllocator() + ); doc.AddMember("min_zoom", _region.minZoom, doc.GetAllocator()); if (std::isfinite(_region.maxZoom)) { doc.AddMember("max_zoom", _region.maxZoom, doc.GetAllocator()); @@ -117,19 +132,19 @@ std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition& region) // Encode specific properties region.match( - [&] (const OfflineTilePyramidRegionDefinition& _region) { - rapidjson::GenericValue, rapidjson::CrtAllocator> bounds(rapidjson::kArrayType); - bounds.PushBack(_region.bounds.south(), doc.GetAllocator()); - bounds.PushBack(_region.bounds.west(), doc.GetAllocator()); - bounds.PushBack(_region.bounds.north(), doc.GetAllocator()); - bounds.PushBack(_region.bounds.east(), doc.GetAllocator()); - doc.AddMember("bounds", bounds, doc.GetAllocator()); - - }, - [&] (const OfflineGeometryRegionDefinition& _region) { - doc.AddMember("geometry", mapbox::geojson::convert(_region.geometry, doc.GetAllocator()), doc.GetAllocator()); - - } + [&](const OfflineTilePyramidRegionDefinition& _region) { + rapidjson::GenericValue, rapidjson::CrtAllocator> bounds(rapidjson::kArrayType); + bounds.PushBack(_region.bounds.south(), doc.GetAllocator()); + bounds.PushBack(_region.bounds.west(), doc.GetAllocator()); + bounds.PushBack(_region.bounds.north(), doc.GetAllocator()); + bounds.PushBack(_region.bounds.east(), doc.GetAllocator()); + doc.AddMember("bounds", bounds, doc.GetAllocator()); + }, + [&](const OfflineGeometryRegionDefinition& _region) { + doc.AddMember( + "geometry", mapbox::geojson::convert(_region.geometry, doc.GetAllocator()), doc.GetAllocator() + ); + } ); rapidjson::StringBuffer buffer; @@ -139,16 +154,12 @@ std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition& region) return buffer.GetString(); } - // OfflineRegion -OfflineRegion::OfflineRegion(int64_t id_, - OfflineRegionDefinition definition_, - OfflineRegionMetadata metadata_) +OfflineRegion::OfflineRegion(int64_t id_, OfflineRegionDefinition definition_, OfflineRegionMetadata metadata_) : id(id_), definition(std::move(definition_)), - metadata(std::move(metadata_)) { -} + metadata(std::move(metadata_)) {} OfflineRegion::~OfflineRegion() = default; diff --git a/platform/default/src/mbgl/storage/offline_database.cpp b/platform/default/src/mbgl/storage/offline_database.cpp index f11836ad268..5445908fcdb 100644 --- a/platform/default/src/mbgl/storage/offline_database.cpp +++ b/platform/default/src/mbgl/storage/offline_database.cpp @@ -14,7 +14,8 @@ namespace mbgl { OfflineDatabase::OfflineDatabase(std::string path_, const TileServerOptions& options) - : path(std::move(path_)), tileServerOptions(options) { + : path(std::move(path_)), + tileServerOptions(options) { try { initialize(); } catch (...) { @@ -41,37 +42,38 @@ void OfflineDatabase::initialize() { } db = std::make_unique( - mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadWriteCreate)); + mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadWriteCreate) + ); db->setBusyTimeout(Milliseconds::max()); db->exec("PRAGMA foreign_keys = ON"); const auto userVersion = getPragma("PRAGMA user_version"); switch (userVersion) { - case 0: - case 1: - // Newly created database, or old cache-only database; remove old table if it exists. - removeOldCacheTable(); - createSchema(); - return; - case 2: - migrateToVersion3(); - // fall through - case 3: - // Removed migration, see below. - // fall through - case 4: - migrateToVersion5(); - // fall through - case 5: - migrateToVersion6(); - // fall through - case 6: - // Happy path; we're done - return; - default: - // Downgrade: delete the database and try to reinitialize. - removeExisting(); - initialize(); + case 0: + case 1: + // Newly created database, or old cache-only database; remove old table if it exists. + removeOldCacheTable(); + createSchema(); + return; + case 2: + migrateToVersion3(); + // fall through + case 3: + // Removed migration, see below. + // fall through + case 4: + migrateToVersion5(); + // fall through + case 5: + migrateToVersion6(); + // fall through + case 6: + // Happy path; we're done + return; + default: + // Downgrade: delete the database and try to reinitialize. + removeExisting(); + initialize(); } } @@ -102,8 +104,7 @@ bool OfflineDatabase::disabled() { } void OfflineDatabase::handleError(const mapbox::sqlite::Exception& ex, const char* action) { - if (ex.code == mapbox::sqlite::ResultCode::NotADB || - ex.code == mapbox::sqlite::ResultCode::Corrupt || + if (ex.code == mapbox::sqlite::ResultCode::NotADB || ex.code == mapbox::sqlite::ResultCode::Corrupt || (ex.code == mapbox::sqlite::ResultCode::ReadOnly && ex.extendedCode == mapbox::sqlite::ExtendedResultCode::ReadOnlyDBMoved)) { // The database was corruped, moved away, or deleted. We're going to start fresh with a @@ -246,7 +247,7 @@ std::optional OfflineDatabase::get(const Resource& resource) try { } auto result = getInternal(resource); - return result ? std::optional{ result->first } : std::nullopt; + return result ? std::optional{result->first} : std::nullopt; } catch (...) { handleError("read resource"); return std::nullopt; @@ -278,7 +279,7 @@ std::pair OfflineDatabase::put(const Resource& resource, const R } if (disabled()) { - return { false, 0 }; + return {false, 0}; } mapbox::sqlite::Transaction transaction(*db, mapbox::sqlite::Transaction::Immediate); @@ -290,11 +291,13 @@ std::pair OfflineDatabase::put(const Resource& resource, const R return {false, 0}; } -std::pair OfflineDatabase::putInternal(const Resource& resource, const Response& response, bool evict_) { +std::pair OfflineDatabase::putInternal( + const Resource& resource, const Response& response, bool evict_ +) { checkFlags(); if (response.error) { - return { false, 0 }; + return {false, 0}; } std::string compressedData; @@ -320,20 +323,30 @@ std::pair OfflineDatabase::putInternal(const Resource& resource, if (resource.kind == Resource::Kind::Tile) { assert(resource.tileData); - inserted = putTile(*resource.tileData, response, - compressed ? compressedData : response.data ? *response.data : "", - compressed); + inserted = putTile( + *resource.tileData, + response, + compressed ? compressedData + : response.data ? *response.data + : "", + compressed + ); } else { - inserted = putResource(resource, response, - compressed ? compressedData : response.data ? *response.data : "", - compressed); + inserted = putResource( + resource, + response, + compressed ? compressedData + : response.data ? *response.data + : "", + compressed + ); } if (stats) { updateAmbientCacheSize(*stats); } - return { inserted, size }; + return {inserted, size}; } std::optional> OfflineDatabase::getResource(const Resource& resource) { @@ -350,7 +363,9 @@ std::optional> OfflineDatabase::getResource(const } // If we don't have any indication that the database is corrupt, continue as usual. - Log::Warning(Event::Database, static_cast(ex.code), std::string("Can't update timestamp: ") + ex.what()); + Log::Warning( + Event::Database, static_cast(ex.code), std::string("Can't update timestamp: ") + ex.what() + ); } } @@ -371,10 +386,10 @@ std::optional> OfflineDatabase::getResource(const Response response; uint64_t size = 0; - response.etag = query.get>(0); - response.expires = query.get>(1); + response.etag = query.get>(0); + response.expires = query.get>(1); response.mustRevalidate = query.get(2); - response.modified = query.get>(3); + response.modified = query.get>(3); auto data = query.get>(4); if (!data) { @@ -391,7 +406,7 @@ std::optional> OfflineDatabase::getResource(const } std::optional OfflineDatabase::hasResource(const Resource& resource) { - mapbox::sqlite::Query query{ getStatement("SELECT length(data) FROM resources WHERE url = ?") }; + mapbox::sqlite::Query query{getStatement("SELECT length(data) FROM resources WHERE url = ?")}; query.bind(1, resource.url); if (!query.run()) { return std::nullopt; @@ -400,10 +415,9 @@ std::optional OfflineDatabase::hasResource(const Resource& resource) { return query.get>(0); } -bool OfflineDatabase::putResource(const Resource& resource, - const Response& response, - const std::string& data, - bool compressed) { +bool OfflineDatabase::putResource( + const Resource& resource, const Response& response, const std::string& data, bool compressed +) { checkFlags(); if (response.notModified) { @@ -515,7 +529,9 @@ std::optional> OfflineDatabase::getTile(const Reso } // If we don't have any indication that the database is corrupt, continue as usual. - Log::Warning(Event::Database, static_cast(ex.code), std::string("Can't update timestamp: ") + ex.what()); + Log::Warning( + Event::Database, static_cast(ex.code), std::string("Can't update timestamp: ") + ex.what() + ); } } @@ -544,10 +560,10 @@ std::optional> OfflineDatabase::getTile(const Reso Response response; uint64_t size = 0; - response.etag = query.get>(0); - response.expires = query.get>(1); - response.mustRevalidate = query.get(2); - response.modified = query.get>(3); + response.etag = query.get>(0); + response.expires = query.get>(1); + response.mustRevalidate = query.get(2); + response.modified = query.get>(3); std::optional data = query.get>(4); if (!data) { @@ -588,10 +604,9 @@ std::optional OfflineDatabase::hasTile(const Resource::TileData& tile) return size.get>(0); } -bool OfflineDatabase::putTile(const Resource::TileData& tile, - const Response& response, - const std::string& data, - bool compressed) { +bool OfflineDatabase::putTile( + const Resource::TileData& tile, const Response& response, const std::string& data, bool compressed +) { checkFlags(); if (response.notModified) { @@ -798,7 +813,7 @@ std::exception_ptr OfflineDatabase::invalidateRegion(int64_t regionID) try { } expected OfflineDatabase::listRegions() try { - mapbox::sqlite::Query query{ getStatement("SELECT id, definition, description FROM regions") }; + mapbox::sqlite::Query query{getStatement("SELECT id, definition, description FROM regions")}; OfflineRegions result; while (query.run()) { const auto id = query.get(0); @@ -815,15 +830,15 @@ expected OfflineDatabase::listRegions() try } } // Explicit move to avoid triggering the copy constructor. - return { std::move(result) }; + return {std::move(result)}; } catch (...) { handleError("list regions"); return unexpected(std::current_exception()); } -expected -OfflineDatabase::createRegion(const OfflineRegionDefinition& definition, - const OfflineRegionMetadata& metadata) try { +expected OfflineDatabase::createRegion( + const OfflineRegionDefinition& definition, const OfflineRegionMetadata& metadata +) try { checkFlags(); // clang-format off @@ -841,8 +856,7 @@ OfflineDatabase::createRegion(const OfflineRegionDefinition& definition, return unexpected(std::current_exception()); } -expected -OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { +expected OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { checkFlags(); try { @@ -853,7 +867,11 @@ OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { query.bind(1, sideDatabasePath); query.run(); } catch (const mapbox::sqlite::Exception& ex) { - Log::Error(Event::Database, static_cast(ex.code), std::string("Can't attach database (") + sideDatabasePath + ") for merge: " + ex.what()); + Log::Error( + Event::Database, + static_cast(ex.code), + std::string("Can't attach database (") + sideDatabasePath + ") for merge: " + ex.what() + ); return unexpected(std::current_exception()); } @@ -904,14 +922,16 @@ OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { OfflineRegions result; while (queryRegions.run()) { // Construct, then move because this constructor is private. - OfflineRegion region(queryRegions.get(0), + OfflineRegion region( + queryRegions.get(0), decodeOfflineRegionDefinition(queryRegions.get(1)), - queryRegions.get>(2)); + queryRegions.get>(2) + ); result.emplace_back(std::move(region)); } db->exec("DETACH DATABASE side"); // Explicit move to avoid triggering the copy constructor. - return { std::move(result) }; + return {std::move(result)}; } catch (const std::runtime_error& ex) { db->exec("DETACH DATABASE side"); Log::Error(Event::Database, std::string(ex.what())); @@ -921,8 +941,9 @@ OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { return {}; } -expected -OfflineDatabase::updateMetadata(const int64_t regionID, const OfflineRegionMetadata& metadata) try { +expected OfflineDatabase::updateMetadata( + const int64_t regionID, const OfflineRegionMetadata& metadata +) try { checkFlags(); // clang-format off @@ -944,7 +965,7 @@ std::exception_ptr OfflineDatabase::deleteRegion(OfflineRegion&& region) try { checkFlags(); { - mapbox::sqlite::Query query{ getStatement("DELETE FROM regions WHERE id = ?") }; + mapbox::sqlite::Query query{getStatement("DELETE FROM regions WHERE id = ?")}; query.bind(1, region.getID()); query.run(); } @@ -977,9 +998,7 @@ std::optional OfflineDatabase::hasRegionResource(const Resource& resour return std::nullopt; } -uint64_t OfflineDatabase::putRegionResource(int64_t regionID, - const Resource& resource, - const Response& response) try { +uint64_t OfflineDatabase::putRegionResource(int64_t regionID, const Resource& resource, const Response& response) try { checkFlags(); if (!db) { @@ -994,9 +1013,9 @@ uint64_t OfflineDatabase::putRegionResource(int64_t regionID, return 0; } -void OfflineDatabase::putRegionResources(int64_t regionID, - const std::list>& resources, - OfflineRegionStatus& status) try { +void OfflineDatabase::putRegionResources( + int64_t regionID, const std::list>& resources, OfflineRegionStatus& status +) try { checkFlags(); if (!db) { @@ -1041,7 +1060,9 @@ void OfflineDatabase::putRegionResources(int64_t regionID, handleError("write region resources"); } -uint64_t OfflineDatabase::putRegionResourceInternal(int64_t regionID, const Resource& resource, const Response& response) { +uint64_t OfflineDatabase::putRegionResourceInternal( + int64_t regionID, const Resource& resource, const Response& response +) { checkFlags(); uint64_t size = putInternal(resource, response, false).second; @@ -1051,10 +1072,8 @@ uint64_t OfflineDatabase::putRegionResourceInternal(int64_t regionID, const Reso throw MapboxTileLimitExceededException(); } - if (offlineMapboxTileCount - && resource.kind == Resource::Kind::Tile - && util::mapbox::isCanonicalURL(tileServerOptions, resource.url) - && previouslyUnused) { + if (offlineMapboxTileCount && resource.kind == Resource::Kind::Tile && + util::mapbox::isCanonicalURL(tileServerOptions, resource.url) && previouslyUnused) { *offlineMapboxTileCount += 1; } @@ -1145,7 +1164,7 @@ bool OfflineDatabase::markUsed(int64_t regionID, const Resource& resource) { } expected OfflineDatabase::getRegionDefinition(int64_t regionID) try { - mapbox::sqlite::Query query{ getStatement("SELECT definition FROM regions WHERE id = ?1") }; + mapbox::sqlite::Query query{getStatement("SELECT definition FROM regions WHERE id = ?1")}; query.bind(1, regionID); query.run(); @@ -1158,10 +1177,8 @@ expected OfflineDatabase::getRegion expected OfflineDatabase::getRegionCompletedStatus(int64_t regionID) try { OfflineRegionStatus result; - std::tie(result.completedResourceCount, result.completedResourceSize) - = getCompletedResourceCountAndSize(regionID); - std::tie(result.completedTileCount, result.completedTileSize) - = getCompletedTileCountAndSize(regionID); + std::tie(result.completedResourceCount, result.completedResourceSize) = getCompletedResourceCountAndSize(regionID); + std::tie(result.completedTileCount, result.completedTileSize) = getCompletedTileCountAndSize(regionID); result.completedResourceCount += result.completedTileCount; result.completedResourceSize += result.completedTileSize; @@ -1182,7 +1199,7 @@ std::pair OfflineDatabase::getCompletedResourceCountAndSize(in // clang-format on query.bind(1, regionID); query.run(); - return { query.get(0), query.get(1) }; + return {query.get(0), query.get(1)}; } std::pair OfflineDatabase::getCompletedTileCountAndSize(int64_t regionID) { @@ -1195,12 +1212,12 @@ std::pair OfflineDatabase::getCompletedTileCountAndSize(int64_ // clang-format on query.bind(1, regionID); query.run(); - return { query.get(0), query.get(1) }; + return {query.get(0), query.get(1)}; } template T OfflineDatabase::getPragma(const char* sql) { - mapbox::sqlite::Query query{ getStatement(sql) }; + mapbox::sqlite::Query query{getStatement(sql)}; query.run(); return query.get(0); } @@ -1217,8 +1234,8 @@ T OfflineDatabase::getPragma(const char* sql) { // us from calling VACUUM or keeping a running total, which can be costly. bool OfflineDatabase::evict(uint64_t neededFreeSize, DatabaseSizeChangeStats& stats) { checkFlags(); - uint64_t ambientCacheSize = - (initAmbientCacheSize() == nullptr) ? *currentAmbientCacheSize : maximumAmbientCacheSize; + uint64_t ambientCacheSize = (initAmbientCacheSize() == nullptr) ? *currentAmbientCacheSize + : maximumAmbientCacheSize; uint64_t newAmbientCacheSize = ambientCacheSize + neededFreeSize + stats.pageSize(); while (newAmbientCacheSize > maximumAmbientCacheSize) { @@ -1279,7 +1296,8 @@ bool OfflineDatabase::evict(uint64_t neededFreeSize, DatabaseSizeChangeStats& st // Update current ambient cache size, based on how many bytes were released. newAmbientCacheSize = std::max( - static_cast(newAmbientCacheSize) - static_cast(stats.bytesReleased()), 0u); + static_cast(newAmbientCacheSize) - static_cast(stats.bytesReleased()), 0u + ); // The cached value of offlineTileCount does not need to be updated // here because only non-offline tiles can be removed by eviction. @@ -1410,9 +1428,8 @@ uint64_t OfflineDatabase::getOfflineMapboxTileCount() try { } bool OfflineDatabase::exceedsOfflineMapboxTileCountLimit(const Resource& resource) { - return resource.kind == Resource::Kind::Tile - && util::mapbox::isCanonicalURL(tileServerOptions, resource.url) - && offlineMapboxTileCountLimitExceeded(); + return resource.kind == Resource::Kind::Tile && util::mapbox::isCanonicalURL(tileServerOptions, resource.url) && + offlineMapboxTileCountLimitExceeded(); } void OfflineDatabase::markUsedResources(int64_t regionID, const std::list& resources) try { @@ -1457,7 +1474,8 @@ void OfflineDatabase::reopenDatabaseReadOnly(bool readOnly_) { } } -OfflineDatabase::DatabaseSizeChangeStats::DatabaseSizeChangeStats(OfflineDatabase* db_) : db(db_) { +OfflineDatabase::DatabaseSizeChangeStats::DatabaseSizeChangeStats(OfflineDatabase* db_) + : db(db_) { assert(db); pageSize_ = db->getPragma("PRAGMA page_size"); pageCount_ = db->getPragma("PRAGMA page_count"); diff --git a/platform/default/src/mbgl/storage/offline_download.cpp b/platform/default/src/mbgl/storage/offline_download.cpp index c4933a1090e..1f71209d8fa 100644 --- a/platform/default/src/mbgl/storage/offline_download.cpp +++ b/platform/default/src/mbgl/storage/offline_download.cpp @@ -34,8 +34,9 @@ using namespace style; // Generic functions template -Range coveringZoomRange(const RegionDefinition& definition, - style::SourceType type, uint16_t tileSize, const Range& zoomRange) { +Range coveringZoomRange( + const RegionDefinition& definition, style::SourceType type, uint16_t tileSize, const Range& zoomRange +) { double minZ = std::max(util::coveringZoomLevel(definition.minZoom, type, tileSize), zoomRange.min); double maxZ = std::min(util::coveringZoomLevel(definition.maxZoom, type, tileSize), zoomRange.max); @@ -43,7 +44,7 @@ Range coveringZoomRange(const RegionDefinition& definition, assert(maxZ >= 0); assert(minZ < std::numeric_limits::max()); assert(maxZ < std::numeric_limits::max()); - return { static_cast(minZ), static_cast(maxZ) }; + return {static_cast(minZ), static_cast(maxZ)}; } template @@ -54,32 +55,41 @@ void tileCover(const Geometry& geometry, uint8_t z, Fn&& fn) { } } - template -void tileCover(const OfflineRegionDefinition& definition, style::SourceType type, - uint16_t tileSize, const Range& zoomRange, Fn&& fn) { - const Range clampedZoomRange = - definition.match([&](auto& reg) { return coveringZoomRange(reg, type, tileSize, zoomRange); }); +void tileCover( + const OfflineRegionDefinition& definition, + style::SourceType type, + uint16_t tileSize, + const Range& zoomRange, + Fn&& fn +) { + const Range clampedZoomRange = definition.match([&](auto& reg) { + return coveringZoomRange(reg, type, tileSize, zoomRange); + }); for (uint8_t z = clampedZoomRange.min; z <= clampedZoomRange.max; z++) { definition.match( - [&](const OfflineTilePyramidRegionDefinition& reg){ tileCover(reg.bounds, z, fn); }, - [&](const OfflineGeometryRegionDefinition& reg){ tileCover(reg.geometry, z, fn); } + [&](const OfflineTilePyramidRegionDefinition& reg) { tileCover(reg.bounds, z, fn); }, + [&](const OfflineGeometryRegionDefinition& reg) { tileCover(reg.geometry, z, fn); } ); } } -uint64_t tileCount(const OfflineRegionDefinition& definition, style::SourceType type, - uint16_t tileSize, const Range& zoomRange) { - - const Range clampedZoomRange = - definition.match([&](auto& reg) { return coveringZoomRange(reg, type, tileSize, zoomRange); }); +uint64_t tileCount( + const OfflineRegionDefinition& definition, + style::SourceType type, + uint16_t tileSize, + const Range& zoomRange +) { + const Range clampedZoomRange = definition.match([&](auto& reg) { + return coveringZoomRange(reg, type, tileSize, zoomRange); + }); uint64_t result{}; for (uint8_t z = clampedZoomRange.min; z <= clampedZoomRange.max; z++) { result += definition.match( - [&](const OfflineTilePyramidRegionDefinition& reg){ return util::tileCount(reg.bounds, z); }, - [&](const OfflineGeometryRegionDefinition& reg){ return util::tileCount(reg.geometry, z); } + [&](const OfflineTilePyramidRegionDefinition& reg) { return util::tileCount(reg.bounds, z); }, + [&](const OfflineGeometryRegionDefinition& reg) { return util::tileCount(reg.geometry, z); } ); } @@ -88,10 +98,9 @@ uint64_t tileCount(const OfflineRegionDefinition& definition, style::SourceType // OfflineDownload -OfflineDownload::OfflineDownload(int64_t id_, - OfflineRegionDefinition definition_, - OfflineDatabase& offlineDatabase_, - FileSource& onlineFileSource_) +OfflineDownload::OfflineDownload( + int64_t id_, OfflineRegionDefinition definition_, OfflineDatabase& offlineDatabase_, FileSource& onlineFileSource_ +) : id(id_), definition(std::move(definition_)), offlineDatabase(offlineDatabase_), @@ -135,7 +144,7 @@ OfflineRegionStatus OfflineDownload::getStatus() const { result->requiredResourceCount++; std::optional styleResponse = - offlineDatabase.get(Resource::style(definition.match([](auto& reg){ return reg.styleURL; }))); + offlineDatabase.get(Resource::style(definition.match([](auto& reg) { return reg.styleURL; }))); if (!styleResponse) { return *result; } @@ -148,7 +157,7 @@ OfflineRegionStatus OfflineDownload::getStatus() const { for (const auto& source : parser.sources) { SourceType type = source->getType(); - auto handleTiledSource = [&] (const variant& urlOrTileset, const uint16_t tileSize) { + auto handleTiledSource = [&](const variant& urlOrTileset, const uint16_t tileSize) { if (urlOrTileset.is()) { uint64_t tileSourceCount = tileCount(definition, type, tileSize, urlOrTileset.get().zoomRange); result->requiredTileCount += tileSourceCount; @@ -159,7 +168,9 @@ OfflineRegionStatus OfflineDownload::getStatus() const { std::optional sourceResponse = offlineDatabase.get(Resource::source(url)); if (sourceResponse) { style::conversion::Error error; - std::optional tileset = style::conversion::convertJSON(*sourceResponse->data, error); + std::optional tileset = style::conversion::convertJSON( + *sourceResponse->data, error + ); if (tileset) { uint64_t tileSourceCount = tileCount(definition, type, tileSize, (*tileset).zoomRange); result->requiredTileCount += tileSourceCount; @@ -172,52 +183,52 @@ OfflineRegionStatus OfflineDownload::getStatus() const { }; switch (type) { - case SourceType::Vector: { - const auto& vectorSource = *source->as(); - handleTiledSource(vectorSource.getURLOrTileset(), util::tileSize_I); - break; - } + case SourceType::Vector: { + const auto& vectorSource = *source->as(); + handleTiledSource(vectorSource.getURLOrTileset(), util::tileSize_I); + break; + } - case SourceType::Raster: { - const auto& rasterSource = *source->as(); - handleTiledSource(rasterSource.getURLOrTileset(), rasterSource.getTileSize()); - break; - } + case SourceType::Raster: { + const auto& rasterSource = *source->as(); + handleTiledSource(rasterSource.getURLOrTileset(), rasterSource.getTileSize()); + break; + } - case SourceType::RasterDEM: { - const auto& rasterDEMSource = *source->as(); - handleTiledSource(rasterDEMSource.getURLOrTileset(), rasterDEMSource.getTileSize()); - break; - } + case SourceType::RasterDEM: { + const auto& rasterDEMSource = *source->as(); + handleTiledSource(rasterDEMSource.getURLOrTileset(), rasterDEMSource.getTileSize()); + break; + } - case SourceType::GeoJSON: { - const auto& geojsonSource = *source->as(); - if (geojsonSource.getURL()) { - result->requiredResourceCount += 1; + case SourceType::GeoJSON: { + const auto& geojsonSource = *source->as(); + if (geojsonSource.getURL()) { + result->requiredResourceCount += 1; + } + break; } - break; - } - case SourceType::Image: { - const auto& imageSource = *source->as(); - if (imageSource.getURL()) { - result->requiredResourceCount += 1; + case SourceType::Image: { + const auto& imageSource = *source->as(); + if (imageSource.getURL()) { + result->requiredResourceCount += 1; + } + break; } - break; - } - case SourceType::Video: - case SourceType::Annotations: - case SourceType::CustomVector: - break; + case SourceType::Video: + case SourceType::Annotations: + case SourceType::CustomVector: + break; } } if (!parser.glyphURL.empty()) { result->requiredResourceCount += parser.fontStacks().size() * - (definition.match([](auto& reg){ return reg.includeIdeographs; }) ? - GLYPH_RANGES_PER_FONT_STACK : - NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK); + (definition.match([](auto& reg) { return reg.includeIdeographs; }) + ? GLYPH_RANGES_PER_FONT_STACK + : NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK); } if (!parser.spriteURL.empty()) { @@ -232,7 +243,7 @@ void OfflineDownload::activateDownload() { status.downloadState = OfflineRegionDownloadState::Active; status.requiredResourceCount++; - auto styleResource = Resource::style(definition.match([](auto& reg){ return reg.styleURL; })); + auto styleResource = Resource::style(definition.match([](auto& reg) { return reg.styleURL; })); styleResource.setPriority(Resource::Priority::Low); styleResource.setUsage(Resource::Usage::Offline); @@ -241,21 +252,21 @@ void OfflineDownload::activateDownload() { style::Parser parser; parser.parse(*styleResponse.data); - + auto tileServerOptions = onlineFileSource.getResourceOptions().tileServerOptions(); parser.spriteURL = util::mapbox::canonicalizeSpriteURL(tileServerOptions, parser.spriteURL); parser.glyphURL = util::mapbox::canonicalizeGlyphURL(tileServerOptions, parser.glyphURL); - + for (const auto& source : parser.sources) { SourceType type = source->getType(); - auto handleTiledSource = [&] (const variant& urlOrTileset, const uint16_t tileSize) { + auto handleTiledSource = [&](const variant& urlOrTileset, const uint16_t tileSize) { if (urlOrTileset.is()) { queueTiles(type, tileSize, urlOrTileset.get()); } else { const auto& rawUrl = urlOrTileset.get(); const auto& url = util::mapbox::canonicalizeSourceURL(tileServerOptions, rawUrl); - + status.requiredResourceCountIsPrecise = false; status.requiredResourceCount++; requiredSourceURLs.insert(url); @@ -266,10 +277,14 @@ void OfflineDownload::activateDownload() { ensureResource(std::move(sourceResource), [=](const Response& sourceResponse) { style::conversion::Error error; - std::optional tileset = style::conversion::convertJSON(*sourceResponse.data, error); + std::optional tileset = style::conversion::convertJSON( + *sourceResponse.data, error + ); if (tileset) { auto resourceOptions = onlineFileSource.getResourceOptions(); - util::mapbox::canonicalizeTileset(resourceOptions.tileServerOptions(), *tileset, url, type, tileSize); + util::mapbox::canonicalizeTileset( + resourceOptions.tileServerOptions(), *tileset, url, type, tileSize + ); queueTiles(type, tileSize, *tileset); requiredSourceURLs.erase(url); @@ -325,13 +340,15 @@ void OfflineDownload::activateDownload() { } if (!parser.glyphURL.empty()) { - const bool includeIdeographs = definition.match([](auto& reg){ return reg.includeIdeographs; }); + const bool includeIdeographs = definition.match([](auto& reg) { return reg.includeIdeographs; }); for (const auto& fontStack : parser.fontStacks()) { for (char16_t i = 0; i < GLYPH_RANGES_PER_FONT_STACK; i++) { // Assumes that if a glyph range starts with fixed width/ideographic characters, the entire // range will be fixed width. if (includeIdeographs || !util::i18n::allowsFixedWidthGlyphGeneration(i * GLYPHS_PER_GLYPH_RANGE)) { - queueResource(Resource::glyphs(parser.glyphURL, fontStack, getGlyphRange(i * GLYPHS_PER_GLYPH_RANGE))); + queueResource( + Resource::glyphs(parser.glyphURL, fontStack, getGlyphRange(i * GLYPHS_PER_GLYPH_RANGE)) + ); } } } @@ -427,8 +444,13 @@ void OfflineDownload::queueTiles(SourceType type, uint16_t tileSize, const Tiles status.requiredTileCount++; auto tileResource = Resource::tile( - tileset.tiles[0], definition.match([](auto& def) { return def.pixelRatio; }), - tile.x, tile.y, tile.z, tileset.scheme); + tileset.tiles[0], + definition.match([](auto& def) { return def.pixelRatio; }), + tile.x, + tile.y, + tile.z, + tileset.scheme + ); tileResource.setPriority(Resource::Priority::Low); tileResource.setUsage(Resource::Usage::Offline); @@ -442,8 +464,7 @@ void OfflineDownload::markPendingUsedResources() { resourcesToBeMarkedAsUsed.clear(); } -void OfflineDownload::ensureResource(Resource&& resource, - std::function callback) { +void OfflineDownload::ensureResource(Resource&& resource, std::function callback) { assert(resource.priority == Resource::Priority::Low); assert(resource.usage == Resource::Usage::Offline); @@ -451,7 +472,7 @@ void OfflineDownload::ensureResource(Resource&& resource, *workRequestsIt = util::RunLoop::Get()->invokeCancellable([=]() { requests.erase(workRequestsIt); const auto resourceKind = resource.kind; - auto getResourceSizeInDatabase = [&] () -> std::optional { + auto getResourceSizeInDatabase = [&]() -> std::optional { std::optional result; if (!callback) { result = offlineDatabase.hasRegionResource(resource); diff --git a/platform/default/src/mbgl/storage/online_file_source.cpp b/platform/default/src/mbgl/storage/online_file_source.cpp index 1e2b928caf6..3b51acd7f62 100644 --- a/platform/default/src/mbgl/storage/online_file_source.cpp +++ b/platform/default/src/mbgl/storage/online_file_source.cpp @@ -76,7 +76,9 @@ struct OnlineFileRequest { class OnlineFileSourceThread { public: OnlineFileSourceThread(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()), httpFileSource(resourceOptions_, clientOptions_) { + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()), + httpFileSource(resourceOptions_, clientOptions_) { NetworkStatus::Subscribe(&reachability); setMaximumConcurrentRequests(util::DEFAULT_MAXIMUM_CONCURRENT_REQUESTS); } @@ -84,7 +86,9 @@ class OnlineFileSourceThread { ~OnlineFileSourceThread() { NetworkStatus::Unsubscribe(&reachability); } void request(AsyncRequest* req, Resource resource, const ActorRef& ref) { - auto callback = [ref](const Response& res) { ref.invoke(&FileSourceRequest::setResponse, res); }; + auto callback = [ref](const Response& res) { + ref.invoke(&FileSourceRequest::setResponse, res); + }; tasks[req] = std::make_unique(std::move(resource), std::move(callback), *this); } @@ -101,9 +105,10 @@ class OnlineFileSourceThread { // Request the ResourceTransform actor a new url and replace the resource url with the // transformed one before proceeding to schedule the request. resourceTransform.transform( - req->resource.kind, req->resource.url, [ref = req->actor()](const std::string& url) { - ref.invoke(&OnlineFileRequest::setTransformedURL, url); - }); + req->resource.kind, + req->resource.url, + [ref = req->actor()](const std::string& url) { ref.invoke(&OnlineFileRequest::setTransformedURL, url); } + ); } else { req->activate(); } @@ -146,8 +151,9 @@ class OnlineFileSourceThread { req->request = httpFileSource.request(req->resource, callback); } else { Response response; - response.error = std::make_unique(Response::Error::Reason::Connection, - "Online connectivity is disabled."); + response.error = std::make_unique( + Response::Error::Reason::Connection, "Online connectivity is disabled." + ); callback(response); } } @@ -166,21 +172,13 @@ class OnlineFileSourceThread { void setResourceTransform(ResourceTransform transform) { resourceTransform = std::move(transform); } - void setResourceOptions(ResourceOptions options) { - resourceOptions = options; - } + void setResourceOptions(ResourceOptions options) { resourceOptions = options; } - const ResourceOptions& getResourceOptions() const { - return resourceOptions; - } + const ResourceOptions& getResourceOptions() const { return resourceOptions; } - void setClientOptions(ClientOptions options) { - clientOptions = options; - } + void setClientOptions(ClientOptions options) { clientOptions = options; } - const ClientOptions& getClientOptions() const { - return clientOptions; - } + const ClientOptions& getClientOptions() const { return clientOptions; } void setOnlineStatus(bool status) { online = status; @@ -189,9 +187,7 @@ class OnlineFileSourceThread { } } - uint32_t getMaximumConcurrentRequests() const { - return maximumConcurrentRequests; - } + uint32_t getMaximumConcurrentRequests() const { return maximumConcurrentRequests; } void setMaximumConcurrentRequests(uint32_t maximumConcurrentRequests_) { maximumConcurrentRequests = maximumConcurrentRequests_; @@ -237,7 +233,8 @@ class OnlineFileSourceThread { // firstLowPriorityRequest struct PendingRequests { - PendingRequests() : firstLowPriorityRequest(queue.begin()) {} + PendingRequests() + : firstLowPriorityRequest(queue.begin()) {} std::list queue; std::list::iterator firstLowPriorityRequest; @@ -256,12 +253,10 @@ class OnlineFileSourceThread { if (request->resource.priority == Resource::Priority::Regular) { firstLowPriorityRequest = queue.insert(firstLowPriorityRequest, request); firstLowPriorityRequest++; - } - else { + } else { if (firstLowPriorityRequest == queue.end()) { firstLowPriorityRequest = queue.insert(queue.end(), request); - } - else { + } else { queue.insert(queue.end(), request); } } @@ -284,7 +279,6 @@ class OnlineFileSourceThread { bool contains(OnlineFileRequest* request) const { return (std::find(queue.begin(), queue.end(), request) != queue.end()); } - }; ResourceTransform resourceTransform; @@ -318,20 +312,25 @@ class OnlineFileSourceThread { class OnlineFileSource::Impl { public: - Impl(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) : - cachedResourceOptions(resourceOptions.clone()), - cachedClientOptions(clientOptions.clone()), - thread(std::make_unique>( - util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_NETWORK), "OnlineFileSource", resourceOptions.clone(), clientOptions.clone())) {} + Impl(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) + : cachedResourceOptions(resourceOptions.clone()), + cachedClientOptions(clientOptions.clone()), + thread(std::make_unique>( + util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_NETWORK), + "OnlineFileSource", + resourceOptions.clone(), + clientOptions.clone() + )) {} std::unique_ptr request(Callback callback, Resource res) { auto req = std::make_unique(std::move(callback)); - req->onCancel( - [actorRef = thread->actor(), req = req.get()]() { actorRef.invoke(&OnlineFileSourceThread::cancel, req); }); + req->onCancel([actorRef = thread->actor(), req = req.get()]() { + actorRef.invoke(&OnlineFileSourceThread::cancel, req); + }); thread->actor().invoke(&OnlineFileSourceThread::request, req.get(), std::move(res), req->actor()); return req; } - + void pause() { thread->pause(); } void resume() { thread->resume(); } @@ -409,7 +408,9 @@ class OnlineFileSource::Impl { thread->actor().invoke(&OnlineFileSourceThread::setAPIBaseURL, *baseURL); { std::lock_guard lock(resourceOptionsMutex); - cachedResourceOptions.withTileServerOptions(cachedResourceOptions.tileServerOptions().clone().withBaseURL(*baseURL)); + cachedResourceOptions.withTileServerOptions( + cachedResourceOptions.tileServerOptions().clone().withBaseURL(*baseURL) + ); } } else { Log::Error(Event::General, "Invalid base-url property value type."); @@ -433,7 +434,9 @@ class OnlineFileSource::Impl { }; OnlineFileRequest::OnlineFileRequest(Resource resource_, Callback callback_, OnlineFileSourceThread& impl_) - : impl(impl_), resource(std::move(resource_)), callback(std::move(callback_)) { + : impl(impl_), + resource(std::move(resource_)), + callback(std::move(callback_)) { impl.add(this); } @@ -504,17 +507,16 @@ void OnlineFileRequest::schedule(Duration timeout) { timeout = Duration::max(); } - timer.start(timeout, Duration::zero(), [&] { - impl.activateOrQueueRequest(this); - }); + timer.start(timeout, Duration::zero(), [&] { impl.activateOrQueueRequest(this); }); } Duration OnlineFileRequest::getUpdateInterval(std::optional expires) const { // Calculate a timeout that depends on how many // consecutive errors we've encountered, and on the expiration time, if present. Duration errorRetryTimeout = http::errorRetryTimeout(failedRequestReason, failedRequests, retryAfter); - Duration expirationTimeout = - std::max(http::expirationTimeout(std::move(expires), expiredRequests), resource.minimumUpdateInterval); + Duration expirationTimeout = std::max( + http::expirationTimeout(std::move(expires), expiredRequests), resource.minimumUpdateInterval + ); return std::min(errorRetryTimeout, expirationTimeout); } @@ -628,8 +630,7 @@ std::unique_ptr OnlineFileSource::request(const Resource& resource break; case Resource::Kind::Style: - res.url = - mbgl::util::mapbox::normalizeStyleURL(options, resource.url, impl->getApiKey()); + res.url = mbgl::util::mapbox::normalizeStyleURL(options, resource.url, impl->getApiKey()); break; case Resource::Kind::Source: diff --git a/platform/default/src/mbgl/storage/sqlite3.cpp b/platform/default/src/mbgl/storage/sqlite3.cpp index c6d4c6fc500..72e223a7f12 100644 --- a/platform/default/src/mbgl/storage/sqlite3.cpp +++ b/platform/default/src/mbgl/storage/sqlite3.cpp @@ -11,9 +11,12 @@ #include #include -#define MBGL_CONSTRUCTOR(f) \ - static void f(void); \ - struct f##_t_ { f##_t_(void) { f(); } }; static f##_t_ f##_; \ +#define MBGL_CONSTRUCTOR(f) \ + static void f(void); \ + struct f##_t_ { \ + f##_t_(void) { f(); } \ + }; \ + static f##_t_ f##_; \ static void f(void) namespace mapbox { @@ -51,15 +54,19 @@ void setTempPath(const std::string& path) { class DatabaseImpl { public: - explicit DatabaseImpl(sqlite3* db_) : db(db_) { + explicit DatabaseImpl(sqlite3* db_) + : db(db_) { const int error = sqlite3_extended_result_codes(db, true); if (error != SQLITE_OK) { - mbgl::Log::Warning(mbgl::Event::Database, error, std::string("Failed to enable extended result codes: ") + sqlite3_errmsg(db)); + mbgl::Log::Warning( + mbgl::Event::Database, + error, + std::string("Failed to enable extended result codes: ") + sqlite3_errmsg(db) + ); } } - ~DatabaseImpl() - { + ~DatabaseImpl() { const int error = sqlite3_close(db); if (error != SQLITE_OK) { mbgl::Log::Error(mbgl::Event::Database, error, "Failed to close database: %s", sqlite3_errmsg(db)); @@ -74,17 +81,15 @@ class DatabaseImpl { class StatementImpl { public: - StatementImpl(sqlite3* db, const char* sql) - { + StatementImpl(sqlite3* db, const char* sql) { const int error = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (error != SQLITE_OK) { stmt = nullptr; - throw Exception { error, sqlite3_errmsg(db) }; + throw Exception{error, sqlite3_errmsg(db)}; } } - ~StatementImpl() - { + ~StatementImpl() { if (!stmt) return; sqlite3_finalize(stmt); @@ -92,7 +97,7 @@ class StatementImpl { void check(int err) { if (err != SQLITE_OK) { - throw Exception { err, sqlite3_errmsg(sqlite3_db_handle(stmt)) }; + throw Exception{err, sqlite3_errmsg(sqlite3_db_handle(stmt))}; } } @@ -102,7 +107,7 @@ class StatementImpl { }; #ifndef NDEBUG -void logSqlMessage(void *, const int err, const char *msg) { +void logSqlMessage(void*, const int err, const char* msg) { mbgl::Log::Record(mbgl::EventSeverity::Debug, mbgl::Event::Database, err, "%s", msg); } #endif @@ -110,9 +115,13 @@ void logSqlMessage(void *, const int err, const char *msg) { MBGL_CONSTRUCTOR(initialize) { if (sqlite3_libversion_number() / 1000000 != SQLITE_VERSION_NUMBER / 1000000) { char message[96]; - snprintf(message, 96, - "sqlite3 libversion mismatch: headers report %d, but library reports %d", - SQLITE_VERSION_NUMBER, sqlite3_libversion_number()); + snprintf( + message, + 96, + "sqlite3 libversion mismatch: headers report %d, but library reports %d", + SQLITE_VERSION_NUMBER, + sqlite3_libversion_number() + ); throw std::runtime_error(message); } @@ -122,18 +131,18 @@ MBGL_CONSTRUCTOR(initialize) { #endif } -mapbox::util::variant Database::tryOpen(const std::string &filename, int flags) { +mapbox::util::variant Database::tryOpen(const std::string& filename, int flags) { sqlite3* db = nullptr; const int error = sqlite3_open_v2(filename.c_str(), &db, flags | SQLITE_OPEN_URI, nullptr); if (error != SQLITE_OK) { const auto message = sqlite3_errmsg(db); sqlite3_close(db); - return Exception { error, message }; + return Exception{error, message}; } return Database(std::make_unique(db)); } -Database Database::open(const std::string &filename, int flags) { +Database Database::open(const std::string& filename, int flags) { auto result = tryOpen(filename, flags); if (result.is()) { throw std::move(result.get()); @@ -143,10 +152,10 @@ Database Database::open(const std::string &filename, int flags) { } Database::Database(std::unique_ptr impl_) - : impl(std::move(impl_)) -{} + : impl(std::move(impl_)) {} -Database::Database(Database&& other) noexcept : impl(std::move(other.impl)) {} +Database::Database(Database&& other) noexcept + : impl(std::move(other.impl)) {} Database& Database::operator=(Database&& other) noexcept { std::swap(impl, other.impl); @@ -161,33 +170,33 @@ void Database::setBusyTimeout(std::chrono::milliseconds timeout) { } void DatabaseImpl::setBusyTimeout(std::chrono::milliseconds timeout) { - const int err = sqlite3_busy_timeout(db, - int(std::min(timeout.count(), std::numeric_limits::max()))); + const int err = sqlite3_busy_timeout( + db, int(std::min(timeout.count(), std::numeric_limits::max())) + ); if (err != SQLITE_OK) { - throw Exception { err, sqlite3_errmsg(db) }; + throw Exception{err, sqlite3_errmsg(db)}; } } -void Database::exec(const std::string &sql) { +void Database::exec(const std::string& sql) { assert(impl); impl->exec(sql); } void DatabaseImpl::exec(const std::string& sql) { - char *msg = nullptr; + char* msg = nullptr; const int err = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, &msg); if (msg) { const std::string message = msg; sqlite3_free(msg); - throw Exception { err, message }; + throw Exception{err, message}; } else if (err != SQLITE_OK) { - throw Exception { err, sqlite3_errmsg(db) }; + throw Exception{err, sqlite3_errmsg(db)}; } } Statement::Statement(Database& db, const char* sql) - : impl(std::make_unique(db.impl->db, sql)) { -} + : impl(std::make_unique(db.impl->db, sql)) {} // NOLINTNEXTLINE(modernize-use-equals-default) Statement::~Statement() { @@ -197,7 +206,8 @@ Statement::~Statement() { #endif } -Query::Query(Statement& stmt_) : stmt(stmt_) { +Query::Query(Statement& stmt_) + : stmt(stmt_) { assert(stmt.impl); #ifndef NDEBUG @@ -215,86 +225,100 @@ Query::~Query() { #endif } -template <> void Query::bind(int offset, std::nullptr_t) { +template <> +void Query::bind(int offset, std::nullptr_t) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_null(stmt.impl->stmt, offset)); } -template <> void Query::bind(int offset, int8_t value) { +template <> +void Query::bind(int offset, int8_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, int16_t value) { +template <> +void Query::bind(int offset, int16_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, int32_t value) { +template <> +void Query::bind(int offset, int32_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, int64_t value) { +template <> +void Query::bind(int offset, int64_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, uint8_t value) { +template <> +void Query::bind(int offset, uint8_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, uint16_t value) { +template <> +void Query::bind(int offset, uint16_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, uint32_t value) { +template <> +void Query::bind(int offset, uint32_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, float value) { +template <> +void Query::bind(int offset, float value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_double(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, double value) { +template <> +void Query::bind(int offset, double value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_double(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, bool value) { +template <> +void Query::bind(int offset, bool value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, const char *value) { +template <> +void Query::bind(int offset, const char* value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_text(stmt.impl->stmt, offset, value, -1, SQLITE_STATIC)); } -void Query::bind(int offset, const char * value, std::size_t length, bool retain) { +void Query::bind(int offset, const char* value, std::size_t length, bool retain) { assert(stmt.impl); if (length > std::numeric_limits::max()) { throw std::range_error("value too long for sqlite3_bind_text"); } - stmt.impl->check(sqlite3_bind_text(stmt.impl->stmt, offset, value, int(length), - retain ? SQLITE_TRANSIENT : SQLITE_STATIC)); + stmt.impl->check( + sqlite3_bind_text(stmt.impl->stmt, offset, value, int(length), retain ? SQLITE_TRANSIENT : SQLITE_STATIC) + ); } void Query::bind(int offset, const std::string& value, bool retain) { bind(offset, value.data(), value.size(), retain); } -void Query::bindBlob(int offset, const void * value, std::size_t length, bool retain) { +void Query::bindBlob(int offset, const void* value, std::size_t length, bool retain) { assert(stmt.impl); if (length > std::numeric_limits::max()) { throw std::range_error("value too long for sqlite3_bind_text"); } - stmt.impl->check(sqlite3_bind_blob(stmt.impl->stmt, offset, value, int(length), - retain ? SQLITE_TRANSIENT : SQLITE_STATIC)); + stmt.impl->check( + sqlite3_bind_blob(stmt.impl->stmt, offset, value, int(length), retain ? SQLITE_TRANSIENT : SQLITE_STATIC) + ); } void Query::bindBlob(int offset, const std::vector& value, bool retain) { @@ -302,13 +326,13 @@ void Query::bindBlob(int offset, const std::vector& value, bool retain) } template <> -void Query::bind( - int offset, std::chrono::time_point value) { +void Query::bind(int offset, std::chrono::time_point value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, std::chrono::system_clock::to_time_t(value))); } -template <> void Query::bind(int offset, std::optional value) { +template <> +void Query::bind(int offset, std::optional value) { if (!value) { bind(offset, nullptr); } else { @@ -318,8 +342,8 @@ template <> void Query::bind(int offset, std::optional value) { template <> void Query::bind( - int offset, - std::optional> value) { + int offset, std::optional> value +) { if (!value) { bind(offset, nullptr); } else { @@ -337,56 +361,62 @@ bool Query::run() { } else if (err == SQLITE_ROW) { return true; } else if (err != SQLITE_OK) { - throw Exception { err, sqlite3_errmsg(sqlite3_db_handle(stmt.impl->stmt)) }; + throw Exception{err, sqlite3_errmsg(sqlite3_db_handle(stmt.impl->stmt))}; } else { return false; } } -template <> bool Query::get(int offset) { +template <> +bool Query::get(int offset) { assert(stmt.impl); return sqlite3_column_int(stmt.impl->stmt, offset); } -template <> int Query::get(int offset) { +template <> +int Query::get(int offset) { assert(stmt.impl); return sqlite3_column_int(stmt.impl->stmt, offset); } -template <> int64_t Query::get(int offset) { +template <> +int64_t Query::get(int offset) { assert(stmt.impl); return sqlite3_column_int64(stmt.impl->stmt, offset); } -template <> double Query::get(int offset) { +template <> +double Query::get(int offset) { assert(stmt.impl); return sqlite3_column_double(stmt.impl->stmt, offset); } -template <> std::string Query::get(int offset) { +template <> +std::string Query::get(int offset) { assert(stmt.impl); return { - reinterpret_cast(sqlite3_column_blob(stmt.impl->stmt, offset)), - size_t(sqlite3_column_bytes(stmt.impl->stmt, offset)) - }; + reinterpret_cast(sqlite3_column_blob(stmt.impl->stmt, offset)), + size_t(sqlite3_column_bytes(stmt.impl->stmt, offset))}; } -template <> std::vector Query::get(int offset) { +template <> +std::vector Query::get(int offset) { assert(stmt.impl); const auto* begin = reinterpret_cast(sqlite3_column_blob(stmt.impl->stmt, offset)); - const uint8_t* end = begin + sqlite3_column_bytes(stmt.impl->stmt, offset); - return { begin, end }; + const uint8_t* end = begin + sqlite3_column_bytes(stmt.impl->stmt, offset); + return {begin, end}; } template <> -std::chrono::time_point -Query::get(int offset) { +std::chrono::time_point Query::get(int offset) { assert(stmt.impl); return std::chrono::time_point_cast( - std::chrono::system_clock::from_time_t(sqlite3_column_int64(stmt.impl->stmt, offset))); + std::chrono::system_clock::from_time_t(sqlite3_column_int64(stmt.impl->stmt, offset)) + ); } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl); if (sqlite3_column_type(stmt.impl->stmt, offset) == SQLITE_NULL) { return std::nullopt; @@ -395,7 +425,8 @@ template <> std::optional Query::get(int offset) { } } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl); if (sqlite3_column_type(stmt.impl->stmt, offset) == SQLITE_NULL) { return std::nullopt; @@ -404,7 +435,8 @@ template <> std::optional Query::get(int offset) { } } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl); if (sqlite3_column_type(stmt.impl->stmt, offset) == SQLITE_NULL) { return std::nullopt; @@ -414,14 +446,12 @@ template <> std::optional Query::get(int offset) { } template <> -std::optional> -Query::get(int offset) { +std::optional> Query::get(int offset) { assert(stmt.impl); if (sqlite3_column_type(stmt.impl->stmt, offset) == SQLITE_NULL) { return std::nullopt; } else { - return get>( - offset); + return get>(offset); } } @@ -449,15 +479,15 @@ uint64_t Query::changes() const { Transaction::Transaction(Database& db_, Mode mode) : dbImpl(*db_.impl) { switch (mode) { - case Deferred: - dbImpl.exec("BEGIN DEFERRED TRANSACTION"); - break; - case Immediate: - dbImpl.exec("BEGIN IMMEDIATE TRANSACTION"); - break; - case Exclusive: - dbImpl.exec("BEGIN EXCLUSIVE TRANSACTION"); - break; + case Deferred: + dbImpl.exec("BEGIN DEFERRED TRANSACTION"); + break; + case Immediate: + dbImpl.exec("BEGIN IMMEDIATE TRANSACTION"); + break; + case Exclusive: + dbImpl.exec("BEGIN EXCLUSIVE TRANSACTION"); + break; } } diff --git a/platform/default/src/mbgl/text/bidi.cpp b/platform/default/src/mbgl/text/bidi.cpp index 6d6ebd5d4c6..7d3e0bb4614 100644 --- a/platform/default/src/mbgl/text/bidi.cpp +++ b/platform/default/src/mbgl/text/bidi.cpp @@ -12,8 +12,9 @@ namespace mbgl { class BiDiImpl { public: - BiDiImpl() : bidiText(ubidi_open()), bidiLine(ubidi_open()) { - } + BiDiImpl() + : bidiText(ubidi_open()), + bidiLine(ubidi_open()) {} ~BiDiImpl() { ubidi_close(bidiText); ubidi_close(bidiLine); @@ -23,7 +24,8 @@ class BiDiImpl { UBiDi* bidiLine = nullptr; }; -BiDi::BiDi() : impl(std::make_unique()) {} +BiDi::BiDi() + : impl(std::make_unique()) {} BiDi::~BiDi() = default; // Takes UTF16 input in logical order and applies Arabic shaping to the input while maintaining @@ -31,25 +33,31 @@ BiDi::~BiDi() = default; std::u16string applyArabicShaping(const std::u16string& input) { UErrorCode errorCode = U_ZERO_ERROR; - const int32_t outputLength = - u_shapeArabic(mbgl::utf16char_cast(input.c_str()), static_cast(input.size()), nullptr, 0, - (U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) | - (U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK), - &errorCode); + const int32_t outputLength = u_shapeArabic( + mbgl::utf16char_cast(input.c_str()), + static_cast(input.size()), + nullptr, + 0, + (U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) | (U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK), + &errorCode + ); // Pre-flighting will always set U_BUFFER_OVERFLOW_ERROR errorCode = U_ZERO_ERROR; std::u16string outputText(outputLength, 0); - u_shapeArabic(mbgl::utf16char_cast(input.c_str()), static_cast(input.size()), mbgl::utf16char_cast(outputText.data()), outputLength, - (U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) | - (U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK), - &errorCode); + u_shapeArabic( + mbgl::utf16char_cast(input.c_str()), + static_cast(input.size()), + mbgl::utf16char_cast(outputText.data()), + outputLength, + (U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) | (U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK), + &errorCode + ); // If the algorithm fails for any reason, fall back to non-transformed text - if (U_FAILURE(errorCode)) - return input; + if (U_FAILURE(errorCode)) return input; return outputText; } @@ -62,8 +70,9 @@ void BiDi::mergeParagraphLineBreaks(std::set& lineBreakPoints) { ubidi_getParagraphByIndex(impl->bidiText, i, nullptr, ¶graphEndIndex, nullptr, &errorCode); if (U_FAILURE(errorCode)) { - throw std::runtime_error(std::string("ProcessedBiDiText::mergeParagraphLineBreaks: ") + - u_errorName(errorCode)); + throw std::runtime_error( + std::string("ProcessedBiDiText::mergeParagraphLineBreaks: ") + u_errorName(errorCode) + ); } lineBreakPoints.insert(static_cast(paragraphEndIndex)); @@ -89,12 +98,17 @@ std::vector BiDi::applyLineBreaking(std::set lineBr return transformedLines; } -std::vector BiDi::processText(const std::u16string& input, - std::set lineBreakPoints) { +std::vector BiDi::processText(const std::u16string& input, std::set lineBreakPoints) { UErrorCode errorCode = U_ZERO_ERROR; - ubidi_setPara(impl->bidiText, mbgl::utf16char_cast(input.c_str()), static_cast(input.size()), - UBIDI_DEFAULT_LTR, nullptr, &errorCode); + ubidi_setPara( + impl->bidiText, + mbgl::utf16char_cast(input.c_str()), + static_cast(input.size()), + UBIDI_DEFAULT_LTR, + nullptr, + &errorCode + ); if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::processText: ") + u_errorName(errorCode)); @@ -102,47 +116,59 @@ std::vector BiDi::processText(const std::u16string& input, return applyLineBreaking(std::move(lineBreakPoints)); } - + std::vector BiDi::processStyledText(const StyledText& input, std::set lineBreakPoints) { std::vector lines; const auto& inputText = input.first; const auto& styleIndices = input.second; - + UErrorCode errorCode = U_ZERO_ERROR; - - ubidi_setPara(impl->bidiText, mbgl::utf16char_cast(inputText.c_str()), static_cast(inputText.size()), - UBIDI_DEFAULT_LTR, nullptr, &errorCode); - + + ubidi_setPara( + impl->bidiText, + mbgl::utf16char_cast(inputText.c_str()), + static_cast(inputText.size()), + UBIDI_DEFAULT_LTR, + nullptr, + &errorCode + ); + if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::processStyledText: ") + u_errorName(errorCode)); } - + mergeParagraphLineBreaks(lineBreakPoints); - + std::size_t lineStartIndex = 0; - + for (std::size_t lineBreakPoint : lineBreakPoints) { StyledText line; line.second.reserve(lineBreakPoint - lineStartIndex); errorCode = U_ZERO_ERROR; - ubidi_setLine(impl->bidiText, static_cast(lineStartIndex), static_cast(lineBreakPoint), impl->bidiLine, &errorCode); + ubidi_setLine( + impl->bidiText, + static_cast(lineStartIndex), + static_cast(lineBreakPoint), + impl->bidiLine, + &errorCode + ); if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::processStyledText (setLine): ") + u_errorName(errorCode)); } - + errorCode = U_ZERO_ERROR; uint32_t runCount = ubidi_countRuns(impl->bidiLine, &errorCode); if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::processStyledText (countRuns): ") + u_errorName(errorCode)); } - + for (uint32_t runIndex = 0; runIndex < runCount; runIndex++) { int32_t runLogicalStart; int32_t runLength; UBiDiDirection direction = ubidi_getVisualRun(impl->bidiLine, runIndex, &runLogicalStart, &runLength); const bool isReversed = direction == UBIDI_RTL; - + std::size_t logicalStart = lineStartIndex + runLogicalStart; std::size_t logicalEnd = logicalStart + runLength; if (isReversed) { @@ -166,10 +192,14 @@ std::vector BiDi::processStyledText(const StyledText& input, std::se break; } } - + } else { line.first += input.first.substr(logicalStart, runLength); - line.second.insert(line.second.end(), styleIndices.begin() + logicalStart, styleIndices.begin() + logicalStart + runLength); + line.second.insert( + line.second.end(), + styleIndices.begin() + logicalStart, + styleIndices.begin() + logicalStart + runLength + ); } } @@ -179,27 +209,28 @@ std::vector BiDi::processStyledText(const StyledText& input, std::se return lines; } - + std::u16string BiDi::writeReverse(const std::u16string& input, std::size_t logicalStart, std::size_t logicalEnd) { UErrorCode errorCode = U_ZERO_ERROR; auto logicalLength = static_cast(logicalEnd - logicalStart); std::u16string outputText(logicalLength + 1, 0); - + // UBIDI_DO_MIRRORING: Apply unicode mirroring of characters like parentheses // UBIDI_REMOVE_BIDI_CONTROLS: Now that all the lines are set, remove control characters so that // they don't show up on screen (some fonts have glyphs representing them) - int32_t outputLength = - ubidi_writeReverse(mbgl::utf16char_cast(&input[logicalStart]), - logicalLength, - mbgl::utf16char_cast(outputText.data()), - logicalLength + 1, // Extra room for null terminator, although we don't really need to have ICU write it for us - UBIDI_DO_MIRRORING | UBIDI_REMOVE_BIDI_CONTROLS, - &errorCode); - + int32_t outputLength = ubidi_writeReverse( + mbgl::utf16char_cast(&input[logicalStart]), + logicalLength, + mbgl::utf16char_cast(outputText.data()), + logicalLength + 1, // Extra room for null terminator, although we don't really need to have ICU write it for us + UBIDI_DO_MIRRORING | UBIDI_REMOVE_BIDI_CONTROLS, + &errorCode + ); + if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::writeReverse: ") + u_errorName(errorCode)); } - + outputText.resize(outputLength); // REMOVE_BIDI_CONTROLS may have shrunk the string return outputText; @@ -222,17 +253,18 @@ std::u16string BiDi::getLine(std::size_t start, std::size_t end) { // UBIDI_DO_MIRRORING: Apply unicode mirroring of characters like parentheses // UBIDI_REMOVE_BIDI_CONTROLS: Now that all the lines are set, remove control characters so that // they don't show up on screen (some fonts have glyphs representing them) - int32_t finalLength = ubidi_writeReordered(impl->bidiLine, - mbgl::utf16char_cast(outputText.data()), - outputLength, - UBIDI_DO_MIRRORING | UBIDI_REMOVE_BIDI_CONTROLS, - &errorCode); + int32_t finalLength = ubidi_writeReordered( + impl->bidiLine, + mbgl::utf16char_cast(outputText.data()), + outputLength, + UBIDI_DO_MIRRORING | UBIDI_REMOVE_BIDI_CONTROLS, + &errorCode + ); outputText.resize(finalLength); // REMOVE_BIDI_CONTROLS may have shrunk the string if (U_FAILURE(errorCode)) { - throw std::runtime_error(std::string("BiDi::getLine (writeReordered): ") + - u_errorName(errorCode)); + throw std::runtime_error(std::string("BiDi::getLine (writeReordered): ") + u_errorName(errorCode)); } return outputText; diff --git a/platform/default/src/mbgl/text/local_glyph_rasterizer.cpp b/platform/default/src/mbgl/text/local_glyph_rasterizer.cpp index ac9b40b297a..caf81fd465a 100644 --- a/platform/default/src/mbgl/text/local_glyph_rasterizer.cpp +++ b/platform/default/src/mbgl/text/local_glyph_rasterizer.cpp @@ -2,8 +2,7 @@ namespace mbgl { -class LocalGlyphRasterizer::Impl { -}; +class LocalGlyphRasterizer::Impl {}; LocalGlyphRasterizer::LocalGlyphRasterizer(const std::optional&) {} diff --git a/platform/default/src/mbgl/util/async_task.cpp b/platform/default/src/mbgl/util/async_task.cpp index d82b8085a1a..b3d1b4fe52a 100644 --- a/platform/default/src/mbgl/util/async_task.cpp +++ b/platform/default/src/mbgl/util/async_task.cpp @@ -12,7 +12,9 @@ namespace util { class AsyncTask::Impl { public: - explicit Impl(std::function fn) : async(new uv_async_t), task(std::move(fn)) { + explicit Impl(std::function fn) + : async(new uv_async_t), + task(std::move(fn)) { auto* loop = reinterpret_cast(RunLoop::getLoopHandle()); if (uv_async_init(loop, async, asyncCallback) != 0) { throw std::runtime_error("Failed to initialize async."); @@ -23,9 +25,7 @@ class AsyncTask::Impl { } ~Impl() { - uv_close(handle(), [](uv_handle_t* h) { - delete reinterpret_cast(h); - }); + uv_close(handle(), [](uv_handle_t* h) { delete reinterpret_cast(h); }); } void maySend() { @@ -36,13 +36,9 @@ class AsyncTask::Impl { } private: - static void asyncCallback(uv_async_t* handle) { - reinterpret_cast(handle->data)->task(); - } + static void asyncCallback(uv_async_t* handle) { reinterpret_cast(handle->data)->task(); } - uv_handle_t* handle() { - return reinterpret_cast(async); - } + uv_handle_t* handle() { return reinterpret_cast(async); } uv_async_t* async; @@ -50,8 +46,7 @@ class AsyncTask::Impl { }; AsyncTask::AsyncTask(std::function&& fn) - : impl(std::make_unique(std::move(fn))) { -} + : impl(std::make_unique(std::move(fn))) {} AsyncTask::~AsyncTask() = default; diff --git a/platform/default/src/mbgl/util/compression.cpp b/platform/default/src/mbgl/util/compression.cpp index 10513e9d1d1..bfb58811354 100644 --- a/platform/default/src/mbgl/util/compression.cpp +++ b/platform/default/src/mbgl/util/compression.cpp @@ -21,8 +21,9 @@ const static bool zlibVersionCheck MBGL_UNUSED = []() { const char *const version = zlibVersion(); if (version[0] != ZLIB_VERSION[0]) { char message[96]; - snprintf(message, 96, "zlib version mismatch: headers report %s, but library reports %s", - ZLIB_VERSION, version); + snprintf( + message, 96, "zlib version mismatch: headers report %s, but library reports %s", ZLIB_VERSION, version + ); throw std::runtime_error(message); } diff --git a/platform/default/src/mbgl/util/jpeg_reader.cpp b/platform/default/src/mbgl/util/jpeg_reader.cpp index 72db47687f1..8891d43d185 100644 --- a/platform/default/src/mbgl/util/jpeg_reader.cpp +++ b/platform/default/src/mbgl/util/jpeg_reader.cpp @@ -5,8 +5,7 @@ #include #include -extern "C" -{ +extern "C" { #include } @@ -38,13 +37,10 @@ static void skip(j_decompress_ptr cinfo, long count) { if (count <= 0) return; // A zero or negative skip count should be treated as a no-op. auto* wrap = reinterpret_cast(cinfo->src); - if (wrap->manager.bytes_in_buffer > 0 && count < static_cast(wrap->manager.bytes_in_buffer)) - { + if (wrap->manager.bytes_in_buffer > 0 && count < static_cast(wrap->manager.bytes_in_buffer)) { wrap->manager.bytes_in_buffer -= count; wrap->manager.next_input_byte = &wrap->buffer[BUF_SIZE - wrap->manager.bytes_in_buffer]; - } - else - { + } else { wrap->stream->seekg(count - wrap->manager.bytes_in_buffer, std::ios_base::cur); // trigger buffer fill wrap->manager.next_input_byte = nullptr; @@ -56,10 +52,10 @@ static void term(j_decompress_ptr) {} static void attach_stream(j_decompress_ptr cinfo, std::istream* in) { if (cinfo->src == nullptr) { - cinfo->src = static_cast((*cinfo->mem->alloc_small)( - reinterpret_cast(cinfo), JPOOL_PERMANENT, sizeof(jpeg_stream_wrapper))); + cinfo->src = static_cast((*cinfo->mem->alloc_small + )(reinterpret_cast(cinfo), JPOOL_PERMANENT, sizeof(jpeg_stream_wrapper))); } - auto * src = reinterpret_cast (cinfo->src); + auto* src = reinterpret_cast(cinfo->src); src->manager.init_source = init_source; src->manager.fill_input_buffer = fill_input_buffer; src->manager.skip_input_data = skip; @@ -79,17 +75,16 @@ static void on_error_message(j_common_ptr cinfo) { } struct jpeg_info_guard { - explicit jpeg_info_guard(jpeg_decompress_struct* cinfo) : i_(cinfo) {} + explicit jpeg_info_guard(jpeg_decompress_struct* cinfo) + : i_(cinfo) {} - ~jpeg_info_guard() { - jpeg_destroy_decompress(i_); - } + ~jpeg_info_guard() { jpeg_destroy_decompress(i_); } jpeg_decompress_struct* i_; }; PremultipliedImage decodeJPEG(const uint8_t* data, size_t size) { - util::CharArrayBuffer dataBuffer { reinterpret_cast(data), size }; + util::CharArrayBuffer dataBuffer{reinterpret_cast(data), size}; std::istream stream(&dataBuffer); jpeg_decompress_struct cinfo; @@ -102,8 +97,7 @@ PremultipliedImage decodeJPEG(const uint8_t* data, size_t size) { attach_stream(&cinfo, &stream); int ret = jpeg_read_header(&cinfo, TRUE); - if (ret != JPEG_HEADER_OK) - throw std::runtime_error("JPEG Reader: failed to read header"); + if (ret != JPEG_HEADER_OK) throw std::runtime_error("JPEG Reader: failed to read header"); jpeg_start_decompress(&cinfo); @@ -118,10 +112,11 @@ PremultipliedImage decodeJPEG(const uint8_t* data, size_t size) { size_t components = cinfo.output_components; size_t rowStride = components * width; - PremultipliedImage image({ static_cast(width), static_cast(height) }); + PremultipliedImage image({static_cast(width), static_cast(height)}); uint8_t* dst = image.data.get(); - JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray)(reinterpret_cast(&cinfo), JPOOL_IMAGE, static_cast(rowStride), 1); + JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray + )(reinterpret_cast(&cinfo), JPOOL_IMAGE, static_cast(rowStride), 1); while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, buffer, 1); diff --git a/platform/default/src/mbgl/util/png_reader.cpp b/platform/default/src/mbgl/util/png_reader.cpp index 40448cf2795..11a8db01d7e 100644 --- a/platform/default/src/mbgl/util/png_reader.cpp +++ b/platform/default/src/mbgl/util/png_reader.cpp @@ -6,13 +6,12 @@ #include #include -extern "C" -{ +extern "C" { #include } -template -static std::string sprintf(const char *msg, Args... args) { +template +static std::string sprintf(const char* msg, Args... args) { char res[max]; int len = snprintf(res, sizeof(res), msg, args...); return std::string(res, len); @@ -23,8 +22,13 @@ const static bool png_version_check [[maybe_unused]] = []() { if (version != PNG_LIBPNG_VER) { throw std::runtime_error(sprintf<96>( "libpng version mismatch: headers report %d.%d.%d, but library reports %d.%d.%d", - PNG_LIBPNG_VER / 10000, (PNG_LIBPNG_VER / 100) % 100, PNG_LIBPNG_VER % 100, - version / 10000, (version / 100) % 100, version % 100)); + PNG_LIBPNG_VER / 10000, + (PNG_LIBPNG_VER / 100) % 100, + PNG_LIBPNG_VER % 100, + version / 10000, + (version / 100) % 100, + version % 100 + )); } return true; }(); @@ -43,8 +47,7 @@ static void png_read_data(png_structp png_ptr, png_bytep data, png_size_t length auto* fin = reinterpret_cast(png_get_io_ptr(png_ptr)); fin->read(reinterpret_cast(data), length); std::streamsize read_count = fin->gcount(); - if (read_count < 0 || static_cast(read_count) != length) - { + if (read_count < 0 || static_cast(read_count) != length) { png_error(png_ptr, "Read Error"); } } @@ -54,30 +57,25 @@ struct png_struct_guard { : p_(png_ptr_ptr), i_(info_ptr_ptr) {} - ~png_struct_guard() { - png_destroy_read_struct(p_,i_,nullptr); - } + ~png_struct_guard() { png_destroy_read_struct(p_, i_, nullptr); } png_structpp p_; png_infopp i_; }; PremultipliedImage decodePNG(const uint8_t* data, size_t size) { - util::CharArrayBuffer dataBuffer { reinterpret_cast(data), size }; + util::CharArrayBuffer dataBuffer{reinterpret_cast(data), size}; std::istream stream(&dataBuffer); - png_byte header[8] = { 0 }; + png_byte header[8] = {0}; stream.read(reinterpret_cast(header), 8); - if (stream.gcount() != 8) - throw std::runtime_error("PNG reader: Could not read image"); + if (stream.gcount() != 8) throw std::runtime_error("PNG reader: Could not read image"); int is_png = !png_sig_cmp(header, 0, 8); - if (!is_png) - throw std::runtime_error("File or stream is not a png"); + if (!is_png) throw std::runtime_error("File or stream is not a png"); png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); - if (!png_ptr) - throw std::runtime_error("failed to allocate png_ptr"); + if (!png_ptr) throw std::runtime_error("failed to allocate png_ptr"); // catch errors in a custom way to avoid the need for setjmp png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn); @@ -85,8 +83,7 @@ PremultipliedImage decodePNG(const uint8_t* data, size_t size) { png_infop info_ptr; png_struct_guard sguard(&png_ptr, &info_ptr); info_ptr = png_create_info_struct(png_ptr); - if (!info_ptr) - throw std::runtime_error("failed to create info_ptr"); + if (!info_ptr) throw std::runtime_error("failed to create info_ptr"); png_set_read_fn(png_ptr, &stream, png_read_data); png_set_sig_bytes(png_ptr, 8); @@ -98,27 +95,21 @@ PremultipliedImage decodePNG(const uint8_t* data, size_t size) { int color_type = 0; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, nullptr, nullptr, nullptr); - UnassociatedImage image({ static_cast(width), static_cast(height) }); + UnassociatedImage image({static_cast(width), static_cast(height)}); - if (color_type == PNG_COLOR_TYPE_PALETTE) - png_set_expand(png_ptr); + if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); - if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) - png_set_expand(png_ptr); + if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand(png_ptr); - if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) - png_set_expand(png_ptr); + if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); - if (bit_depth == 16) - png_set_strip_16(png_ptr); + if (bit_depth == 16) png_set_strip_16(png_ptr); - if (color_type == PNG_COLOR_TYPE_GRAY || - color_type == PNG_COLOR_TYPE_GRAY_ALPHA) - png_set_gray_to_rgb(png_ptr); + if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); - if (png_get_interlace_type(png_ptr,info_ptr) == PNG_INTERLACE_ADAM7) { + if (png_get_interlace_type(png_ptr, info_ptr) == PNG_INTERLACE_ADAM7) { png_set_interlace_handling(png_ptr); // FIXME: libpng bug? // according to docs png_read_image // "..automatically handles interlacing, @@ -130,8 +121,7 @@ PremultipliedImage decodePNG(const uint8_t* data, size_t size) { // we can read whole image at once // alloc row pointers const std::unique_ptr rows(new png_bytep[height]); - for (unsigned row = 0; row < height; ++row) - rows[row] = image.data.get() + row * width * 4; + for (unsigned row = 0; row < height; ++row) rows[row] = image.data.get() + row * width * 4; png_read_image(png_ptr, rows.get()); png_read_end(png_ptr, nullptr); diff --git a/platform/default/src/mbgl/util/png_writer.cpp b/platform/default/src/mbgl/util/png_writer.cpp index 4a7ef43052c..19290cc9952 100644 --- a/platform/default/src/mbgl/util/png_writer.cpp +++ b/platform/default/src/mbgl/util/png_writer.cpp @@ -19,8 +19,8 @@ void addChunk(std::string& png, const char* type, const char* data = "", const u checksum.process_bytes(type, 4); checksum.process_bytes(data, size); - const char length[4] = { NETWORK_BYTE_UINT32(size) }; - const char crc[4] = { NETWORK_BYTE_UINT32(checksum.checksum()) }; + const char length[4] = {NETWORK_BYTE_UINT32(size)}; + const char crc[4] = {NETWORK_BYTE_UINT32(checksum.checksum())}; png.reserve(png.size() + 4 /* length */ + 4 /* type */ + size + 4 /* CRC */); png.append(length, 4); @@ -39,7 +39,7 @@ std::string encodePNG(const PremultipliedImage& pre) { const auto src = util::unpremultiply(pre.clone()); // PNG magic bytes - const char preamble[8] = { char(0x89), 'P', 'N', 'G', '\r', '\n', 0x1a, '\n' }; + const char preamble[8] = {char(0x89), 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}; // IHDR chunk for our RGBA image. const char ihdr[13] = { @@ -64,8 +64,7 @@ std::string encodePNG(const PremultipliedImage& pre) { // Assemble the PNG. std::string png; - png.reserve((8 /* preamble */) + (12 + 13 /* IHDR */) + - (12 + idat.size() /* IDAT */) + (12 /* IEND */)); + png.reserve((8 /* preamble */) + (12 + 13 /* IHDR */) + (12 + idat.size() /* IDAT */) + (12 /* IEND */)); png.append(preamble, 8); addChunk(png, "IHDR", ihdr, 13); addChunk(png, "IDAT", idat.data(), static_cast(idat.size())); diff --git a/platform/default/src/mbgl/util/run_loop.cpp b/platform/default/src/mbgl/util/run_loop.cpp index 8e8eb35052a..3d4ac14b685 100644 --- a/platform/default/src/mbgl/util/run_loop.cpp +++ b/platform/default/src/mbgl/util/run_loop.cpp @@ -24,21 +24,21 @@ struct Watch { RunLoop::Event watchEvent = RunLoop::Event::None; switch (event) { - case UV_READABLE: - watchEvent = RunLoop::Event::Read; - break; - case UV_WRITABLE: - watchEvent = RunLoop::Event::Write; - break; - case UV_READABLE | UV_WRITABLE: - watchEvent = RunLoop::Event::ReadWrite; - break; + case UV_READABLE: + watchEvent = RunLoop::Event::Read; + break; + case UV_WRITABLE: + watchEvent = RunLoop::Event::Write; + break; + case UV_READABLE | UV_WRITABLE: + watchEvent = RunLoop::Event::ReadWrite; + break; } watch->eventCallback(watch->fd, watchEvent); }; - static void onClose(uv_handle_t *poll) { + static void onClose(uv_handle_t* poll) { auto watch = reinterpret_cast(poll->data); watch->closeCallback(); }; @@ -58,16 +58,12 @@ RunLoop* RunLoop::Get() { class RunLoop::Impl { public: void closeHolder() { - uv_close(holderHandle(), [](uv_handle_t* h) { - delete reinterpret_cast(h); - }); + uv_close(holderHandle(), [](uv_handle_t* h) { delete reinterpret_cast(h); }); } - uv_handle_t* holderHandle() { - return reinterpret_cast(holder); - } + uv_handle_t* holderHandle() { return reinterpret_cast(holder); } - uv_loop_t *loop = nullptr; + uv_loop_t* loop = nullptr; uv_async_t* holder = new uv_async_t; RunLoop::Type type; @@ -76,17 +72,18 @@ class RunLoop::Impl { std::unordered_map> watchPoll; }; -RunLoop::RunLoop(Type type) : impl(std::make_unique()) { +RunLoop::RunLoop(Type type) + : impl(std::make_unique()) { switch (type) { - case Type::New: - impl->loop = new uv_loop_t; - if (uv_loop_init(impl->loop) != 0) { - throw std::runtime_error("Failed to initialize loop."); - } - break; - case Type::Default: - impl->loop = uv_default_loop(); - break; + case Type::New: + impl->loop = new uv_loop_t; + if (uv_loop_init(impl->loop) != 0) { + throw std::runtime_error("Failed to initialize loop."); + } + break; + case Type::Default: + impl->loop = uv_default_loop(); + break; } // Just for holding a ref to the main loop and keep @@ -153,7 +150,7 @@ void RunLoop::stop() { void RunLoop::addWatch(int fd, Event event, std::function&& callback) { MBGL_VERIFY_THREAD(tid); - Watch *watch = nullptr; + Watch* watch = nullptr; auto watchPollIter = impl->watchPoll.find(fd); if (watchPollIter == impl->watchPoll.end()) { @@ -179,17 +176,17 @@ void RunLoop::addWatch(int fd, Event event, std::function&& ca int pollEvent = 0; switch (event) { - case Event::Read: - pollEvent = UV_READABLE; - break; - case Event::Write: - pollEvent = UV_WRITABLE; - break; - case Event::ReadWrite: - pollEvent = UV_READABLE | UV_WRITABLE; - break; - default: - throw std::runtime_error("Unhandled event."); + case Event::Read: + pollEvent = UV_READABLE; + break; + case Event::Write: + pollEvent = UV_WRITABLE; + break; + case Event::ReadWrite: + pollEvent = UV_READABLE | UV_WRITABLE; + break; + default: + throw std::runtime_error("Unhandled event."); } if (uv_poll_start(&watch->poll, pollEvent, &Watch::onEvent)) { diff --git a/platform/default/src/mbgl/util/string_stdlib.cpp b/platform/default/src/mbgl/util/string_stdlib.cpp index f2c554a3e9f..8eef7b373f2 100644 --- a/platform/default/src/mbgl/util/string_stdlib.cpp +++ b/platform/default/src/mbgl/util/string_stdlib.cpp @@ -3,68 +3,54 @@ #include #include -namespace mbgl { namespace platform { +namespace mbgl { +namespace platform { -std::string uppercase(const std::string& str) -{ +std::string uppercase(const std::string &str) { std::stringstream output; char const *itr = str.c_str(); char const *nitr; char const *end = itr + str.length(); - char lo[5] = { 0 }; + char lo[5] = {0}; - for (; itr < end; itr = nitr) - { + for (; itr < end; itr = nitr) { uint32_t code_point = 0; - char const* buf = nullptr; + char const *buf = nullptr; nitr = _nu_toupper(itr, end, nu_utf8_read, &code_point, &buf, nullptr); - if (buf != nullptr) - { - do - { + if (buf != nullptr) { + do { buf = NU_CASEMAP_DECODING_FUNCTION(buf, &code_point); if (code_point == 0) break; output.write(lo, nu_utf8_write(code_point, lo) - lo); - } - while (code_point != 0); - } - else - { + } while (code_point != 0); + } else { output.write(itr, nitr - itr); } } return output.str(); - } -std::string lowercase(const std::string& str) -{ +std::string lowercase(const std::string &str) { std::stringstream output; char const *itr = str.c_str(); char const *nitr; char const *end = itr + str.length(); - char lo[5] = { 0 }; + char lo[5] = {0}; - for (; itr < end; itr = nitr) - { + for (; itr < end; itr = nitr) { uint32_t code_point = 0; - char const* buf = nullptr; + char const *buf = nullptr; nitr = _nu_tolower(itr, end, nu_utf8_read, &code_point, &buf, nullptr); - if (buf != nullptr) - { - do - { + if (buf != nullptr) { + do { buf = NU_CASEMAP_DECODING_FUNCTION(buf, &code_point); if (code_point == 0) break; output.write(lo, nu_utf8_write(code_point, lo) - lo); - } - while (code_point != 0); - } - else - { + } while (code_point != 0); + } else { output.write(itr, nitr - itr); } } diff --git a/platform/default/src/mbgl/util/timer.cpp b/platform/default/src/mbgl/util/timer.cpp index f59b3528428..91fd838134c 100644 --- a/platform/default/src/mbgl/util/timer.cpp +++ b/platform/default/src/mbgl/util/timer.cpp @@ -9,7 +9,8 @@ namespace util { class Timer::Impl { public: - Impl() : timer(new uv_timer_t) { + Impl() + : timer(new uv_timer_t) { auto* loop = reinterpret_cast(RunLoop::getLoopHandle()); if (uv_timer_init(loop, timer) != 0) { throw std::runtime_error("Failed to initialize timer."); @@ -20,12 +21,10 @@ class Timer::Impl { } ~Impl() { - uv_close(handle(), [](uv_handle_t* h) { - delete reinterpret_cast(h); - }); + uv_close(handle(), [](uv_handle_t* h) { delete reinterpret_cast(h); }); } - void start(uint64_t timeout, uint64_t repeat, std::function&& cb_) { + void start(uint64_t timeout, uint64_t repeat, std::function&& cb_) { cb = std::move(cb_); if (uv_timer_start(timer, timerCallback, timeout, repeat) != 0) { throw std::runtime_error("Failed to start timer."); @@ -40,13 +39,9 @@ class Timer::Impl { } private: - static void timerCallback(uv_timer_t* handle) { - reinterpret_cast(handle->data)->cb(); - } + static void timerCallback(uv_timer_t* handle) { reinterpret_cast(handle->data)->cb(); } - uv_handle_t* handle() { - return reinterpret_cast(timer); - } + uv_handle_t* handle() { return reinterpret_cast(timer); } uv_timer_t* timer; @@ -54,15 +49,16 @@ class Timer::Impl { }; Timer::Timer() - : impl(std::make_unique()) { -} + : impl(std::make_unique()) {} Timer::~Timer() = default; void Timer::start(Duration timeout, Duration repeat, std::function&& cb) { - impl->start(static_cast(std::chrono::duration_cast(timeout).count()), - static_cast(std::chrono::duration_cast(repeat).count()), - std::move(cb)); + impl->start( + static_cast(std::chrono::duration_cast(timeout).count()), + static_cast(std::chrono::duration_cast(repeat).count()), + std::move(cb) + ); } void Timer::stop() { diff --git a/platform/glfw/glfw_gl_backend.cpp b/platform/glfw/glfw_gl_backend.cpp index 6af68d83d66..8c17b40c44c 100644 --- a/platform/glfw/glfw_gl_backend.cpp +++ b/platform/glfw/glfw_gl_backend.cpp @@ -7,16 +7,15 @@ class GLFWGLRenderableResource final : public mbgl::gl::RenderableResource { public: - explicit GLFWGLRenderableResource(GLFWGLBackend& backend_) : backend(backend_) {} + explicit GLFWGLRenderableResource(GLFWGLBackend& backend_) + : backend(backend_) {} void bind() override { backend.setFramebufferBinding(0); backend.setViewport(0, 0, backend.getSize()); } - void swap() override { - backend.swap(); - } + void swap() override { backend.swap(); } private: GLFWGLBackend& backend; @@ -29,9 +28,10 @@ GLFWGLBackend::GLFWGLBackend(GLFWwindow* window_, const bool capFrameRate) int fbWidth; int fbHeight; glfwGetFramebufferSize(window_, &fbWidth, &fbHeight); - return mbgl::Size{ static_cast(fbWidth), static_cast(fbHeight) }; + return mbgl::Size{static_cast(fbWidth), static_cast(fbHeight)}; }(), - std::make_unique(*this)), + std::make_unique(*this) + ), window(window_) { glfwMakeContextCurrent(window); if (!capFrameRate) { @@ -77,8 +77,7 @@ namespace mbgl { namespace gfx { template <> -std::unique_ptr -Backend::Create(GLFWwindow* window, bool capFrameRate) { +std::unique_ptr Backend::Create(GLFWwindow* window, bool capFrameRate) { return std::make_unique(window, capFrameRate); } diff --git a/platform/glfw/glfw_gl_backend.hpp b/platform/glfw/glfw_gl_backend.hpp index 5971bbd0c50..cd7a2ab0180 100644 --- a/platform/glfw/glfw_gl_backend.hpp +++ b/platform/glfw/glfw_gl_backend.hpp @@ -7,9 +7,7 @@ struct GLFWwindow; -class GLFWGLBackend final : public GLFWBackend, - public mbgl::gl::RendererBackend, - public mbgl::gfx::Renderable { +class GLFWGLBackend final : public GLFWBackend, public mbgl::gl::RendererBackend, public mbgl::gfx::Renderable { public: GLFWGLBackend(GLFWwindow*, bool capFrameRate); ~GLFWGLBackend() override; @@ -18,17 +16,13 @@ class GLFWGLBackend final : public GLFWBackend, // GLFWRendererBackend implementation public: - mbgl::gfx::RendererBackend& getRendererBackend() override { - return *this; - } + mbgl::gfx::RendererBackend& getRendererBackend() override { return *this; } mbgl::Size getSize() const override; void setSize(mbgl::Size) override; // mbgl::gfx::RendererBackend implementation public: - mbgl::gfx::Renderable& getDefaultRenderable() override { - return *this; - } + mbgl::gfx::Renderable& getDefaultRenderable() override { return *this; } protected: void activate() override; diff --git a/platform/glfw/glfw_renderer_frontend.cpp b/platform/glfw/glfw_renderer_frontend.cpp index 6c7335d6a1d..f08659e2ff7 100644 --- a/platform/glfw/glfw_renderer_frontend.cpp +++ b/platform/glfw/glfw_renderer_frontend.cpp @@ -4,9 +4,9 @@ #include GLFWRendererFrontend::GLFWRendererFrontend(std::unique_ptr renderer_, GLFWView& glfwView_) - : glfwView(glfwView_) - , renderer(std::move(renderer_)) { - glfwView.setRenderFrontend(this); + : glfwView(glfwView_), + renderer(std::move(renderer_)) { + glfwView.setRenderFrontend(this); } GLFWRendererFrontend::~GLFWRendererFrontend() = default; @@ -28,10 +28,10 @@ void GLFWRendererFrontend::update(std::shared_ptr params void GLFWRendererFrontend::render() { assert(renderer); - + if (!updateParameters) return; - - mbgl::gfx::BackendScope guard { glfwView.getRendererBackend(), mbgl::gfx::BackendScope::ScopeType::Implicit }; + + mbgl::gfx::BackendScope guard{glfwView.getRendererBackend(), mbgl::gfx::BackendScope::ScopeType::Implicit}; // onStyleImageMissing might be called during a render. The user implemented method // could trigger a call to MLNRenderFrontend#update which overwrites `updateParameters`. diff --git a/platform/glfw/glfw_renderer_frontend.hpp b/platform/glfw/glfw_renderer_frontend.hpp index c992fe20fe9..08e649f6e84 100644 --- a/platform/glfw/glfw_renderer_frontend.hpp +++ b/platform/glfw/glfw_renderer_frontend.hpp @@ -13,13 +13,13 @@ class GLFWRendererFrontend : public mbgl::RendererFrontend { public: GLFWRendererFrontend(std::unique_ptr, GLFWView&); ~GLFWRendererFrontend() override; - + void reset() override; void setObserver(mbgl::RendererObserver&) override; void update(std::shared_ptr) override; void render(); - + mbgl::Renderer* getRenderer(); private: diff --git a/platform/glfw/glfw_view.cpp b/platform/glfw/glfw_view.cpp index afd5a4c5f44..c8e8953fa1c 100644 --- a/platform/glfw/glfw_view.cpp +++ b/platform/glfw/glfw_view.cpp @@ -104,14 +104,16 @@ void addFillExtrusionLayer(mbgl::style::Style &style, bool visible) { extrusionLayer->setSourceLayer("building"); extrusionLayer->setMinZoom(15.0f); extrusionLayer->setFilter(Filter(eq(get("extrude"), literal("true")))); - extrusionLayer->setFillExtrusionColor(PropertyExpression(interpolate(linear(), - number(get("height")), - 0.f, - toColor(literal("#160e23")), - 50.f, - toColor(literal("#00615f")), - 100.f, - toColor(literal("#55e9ff"))))); + extrusionLayer->setFillExtrusionColor(PropertyExpression(interpolate( + linear(), + number(get("height")), + 0.f, + toColor(literal("#160e23")), + 50.f, + toColor(literal("#00615f")), + 100.f, + toColor(literal("#55e9ff")) + ))); extrusionLayer->setFillExtrusionOpacity(0.6f); extrusionLayer->setFillExtrusionHeight(PropertyExpression(get("height"))); extrusionLayer->setFillExtrusionBase(PropertyExpression(get("min_height"))); @@ -121,10 +123,14 @@ void addFillExtrusionLayer(mbgl::style::Style &style, bool visible) { void glfwError(int error, const char *description) { mbgl::Log::Error(mbgl::Event::OpenGL, std::string("GLFW error (") + std::to_string(error) + "): " + description); - } -GLFWView::GLFWView(bool fullscreen_, bool benchmark_, const mbgl::ResourceOptions &resourceOptions, const mbgl::ClientOptions &clientOptions) +GLFWView::GLFWView( + bool fullscreen_, + bool benchmark_, + const mbgl::ResourceOptions &resourceOptions, + const mbgl::ClientOptions &clientOptions +) : fullscreen(fullscreen_), benchmark(benchmark_), snapshotterObserver(std::make_unique()), @@ -212,7 +218,10 @@ GLFWView::GLFWView(bool fullscreen_, bool benchmark_, const mbgl::ResourceOption printf("- Press `I` to delete existing database and re-initialize\n"); printf("- Press `A` to cycle through Mapbox offices in the world + dateline monument\n"); printf("- Press `B` to cycle through the color, stencil, and depth buffer\n"); - printf("- Press `D` to cycle through camera bounds: inside, crossing IDL at left, crossing IDL at right, and disabled\n"); + printf( + "- Press `D` to cycle through camera bounds: inside, crossing IDL at left, crossing IDL at right, and " + "disabled\n" + ); printf("- Press `T` to add custom geometry source\n"); printf("- Press `F` to enable feature-state demo\n"); printf("- Press `U` to toggle pitch bounds\n"); @@ -252,7 +261,7 @@ void GLFWView::setMap(mbgl::Map *map_) { map->addAnnotationImage(makeImage("default_marker", 22, 22, 1)); } -void GLFWView::setRenderFrontend(GLFWRendererFrontend* rendererFrontend_) { +void GLFWView::setRenderFrontend(GLFWRendererFrontend *rendererFrontend_) { rendererFrontend = rendererFrontend_; } @@ -276,7 +285,8 @@ void GLFWView::onKey(GLFWwindow *window, int key, int /*scancode*/, int action, case GLFW_KEY_X: if (!mods) view->map->jumpTo( - mbgl::CameraOptions().withCenter(mbgl::LatLng{}).withZoom(0.0).withBearing(0.0).withPitch(0.0)); + mbgl::CameraOptions().withCenter(mbgl::LatLng{}).withZoom(0.0).withBearing(0.0).withPitch(0.0) + ); break; case GLFW_KEY_O: view->onlineStatusCallback(); @@ -284,231 +294,272 @@ void GLFWView::onKey(GLFWwindow *window, int key, int /*scancode*/, int action, case GLFW_KEY_S: if (view->changeStyleCallback) view->changeStyleCallback(); break; - case GLFW_KEY_N: - if (!mods) - view->map->easeTo(mbgl::CameraOptions().withBearing(0.0), mbgl::AnimationOptions {{mbgl::Milliseconds(500)}}); - break; - case GLFW_KEY_Z: - view->nextOrientation(); - break; - case GLFW_KEY_Q: { - auto result = view->rendererFrontend->getRenderer()->queryPointAnnotations({ {}, { static_cast(view->getSize().width), static_cast(view->getSize().height) } }); - printf("visible point annotations: %zu\n", result.size()); - auto features = view->rendererFrontend->getRenderer()->queryRenderedFeatures( - mbgl::ScreenBox{{view->getSize().width * 0.5, view->getSize().height * 0.5}, - {view->getSize().width * 0.5 + 1.0, view->getSize().height * 0.5 + 1}}, - {}); - printf("Rendered features at the center of the screen: %zu\n", features.size()); - } break; - case GLFW_KEY_P: - view->pauseResumeCallback(); - break; - case GLFW_KEY_C: - view->clearAnnotations(); - break; - case GLFW_KEY_I: - view->resetDatabaseCallback(); - break; - case GLFW_KEY_K: - view->addRandomCustomPointAnnotations(1); - break; - case GLFW_KEY_L: - view->addRandomLineAnnotations(1); - break; - case GLFW_KEY_A: { - // XXX Fix precision loss in flyTo: - // https://github.com/mapbox/mapbox-gl-native/issues/4298 - static const std::vector places = { - mbgl::LatLng { -16.796665, -179.999983 }, // Dateline monument - mbgl::LatLng { 12.9810542, 77.6345551 }, // Mapbox Bengaluru, India - mbgl::LatLng { -13.15607,-74.21773 }, // Mapbox Peru - mbgl::LatLng { 37.77572, -122.4158818 }, // Mapbox SF, USA - mbgl::LatLng { 38.91318,-77.03255 }, // Mapbox DC, USA - }; - static size_t nextPlace = 0; - mbgl::CameraOptions cameraOptions; - cameraOptions.center = places[nextPlace++]; - cameraOptions.zoom = 20; - cameraOptions.pitch = 30; - - mbgl::AnimationOptions animationOptions(mbgl::Seconds(10)); - view->map->flyTo(cameraOptions, animationOptions); - nextPlace = nextPlace % places.size(); - } break; - case GLFW_KEY_R: { - view->show3DExtrusions = true; - view->toggle3DExtrusions(view->show3DExtrusions); - if (view->animateRouteCallback) break; - view->animateRouteCallback = [](mbgl::Map* routeMap) { - static mapbox::cheap_ruler::CheapRuler ruler { 40.7 }; // New York - static mapbox::geojson::geojson route { mapbox::geojson::parse(mbgl::platform::glfw::route) }; - const auto& geometry = route.get>(); - const auto& lineString = geometry.get>(); - - static double routeDistance = ruler.lineDistance(lineString); - static double routeProgress = 0; - routeProgress += 0.0005; - if (routeProgress > 1.0) { - routeProgress = 0.0; + case GLFW_KEY_N: + if (!mods) + view->map->easeTo( + mbgl::CameraOptions().withBearing(0.0), mbgl::AnimationOptions{{mbgl::Milliseconds(500)}} + ); + break; + case GLFW_KEY_Z: + view->nextOrientation(); + break; + case GLFW_KEY_Q: { + auto result = view->rendererFrontend->getRenderer()->queryPointAnnotations( + {{}, {static_cast(view->getSize().width), static_cast(view->getSize().height)}} + ); + printf("visible point annotations: %zu\n", result.size()); + auto features = view->rendererFrontend->getRenderer()->queryRenderedFeatures( + mbgl::ScreenBox{ + {view->getSize().width * 0.5, view->getSize().height * 0.5}, + {view->getSize().width * 0.5 + 1.0, view->getSize().height * 0.5 + 1}}, + {} + ); + printf("Rendered features at the center of the screen: %zu\n", features.size()); + } break; + case GLFW_KEY_P: + view->pauseResumeCallback(); + break; + case GLFW_KEY_C: + view->clearAnnotations(); + break; + case GLFW_KEY_I: + view->resetDatabaseCallback(); + break; + case GLFW_KEY_K: + view->addRandomCustomPointAnnotations(1); + break; + case GLFW_KEY_L: + view->addRandomLineAnnotations(1); + break; + case GLFW_KEY_A: { + // XXX Fix precision loss in flyTo: + // https://github.com/mapbox/mapbox-gl-native/issues/4298 + static const std::vector places = { + mbgl::LatLng{-16.796665, -179.999983}, // Dateline monument + mbgl::LatLng{12.9810542, 77.6345551}, // Mapbox Bengaluru, India + mbgl::LatLng{-13.15607, -74.21773}, // Mapbox Peru + mbgl::LatLng{37.77572, -122.4158818}, // Mapbox SF, USA + mbgl::LatLng{38.91318, -77.03255}, // Mapbox DC, USA + }; + static size_t nextPlace = 0; + mbgl::CameraOptions cameraOptions; + cameraOptions.center = places[nextPlace++]; + cameraOptions.zoom = 20; + cameraOptions.pitch = 30; + + mbgl::AnimationOptions animationOptions(mbgl::Seconds(10)); + view->map->flyTo(cameraOptions, animationOptions); + nextPlace = nextPlace % places.size(); + } break; + case GLFW_KEY_R: { + view->show3DExtrusions = true; + view->toggle3DExtrusions(view->show3DExtrusions); + if (view->animateRouteCallback) break; + view->animateRouteCallback = [](mbgl::Map *routeMap) { + static mapbox::cheap_ruler::CheapRuler ruler{40.7}; // New York + static mapbox::geojson::geojson route{mapbox::geojson::parse(mbgl::platform::glfw::route)}; + const auto &geometry = route.get>(); + const auto &lineString = geometry.get>(); + + static double routeDistance = ruler.lineDistance(lineString); + static double routeProgress = 0; + routeProgress += 0.0005; + if (routeProgress > 1.0) { + routeProgress = 0.0; + } + + auto camera = routeMap->getCameraOptions(); + + auto point = ruler.along(lineString, routeProgress * routeDistance); + const mbgl::LatLng center{point.y, point.x}; + auto latLng = *camera.center; + double bearing = ruler.bearing({latLng.longitude(), latLng.latitude()}, point); + double easing = bearing - *camera.bearing; + easing += easing > 180.0 ? -360.0 : easing < -180 ? 360.0 : 0; + bearing = *camera.bearing + (easing / 20); + routeMap->jumpTo( + mbgl::CameraOptions().withCenter(center).withZoom(18.0).withBearing(bearing).withPitch(60.0) + ); + }; + view->animateRouteCallback(view->map); + } break; + case GLFW_KEY_E: + view->toggle3DExtrusions(!view->show3DExtrusions); + break; + case GLFW_KEY_D: { + static const std::vector bounds = { + mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -170.0}, mbgl::LatLng{45.0, 170.0}), // inside + mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -200.0}, mbgl::LatLng{45.0, -160.0}), // left IDL + mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, 160.0}, mbgl::LatLng{45.0, 200.0}), // right IDL + mbgl::LatLngBounds()}; + static size_t nextBound = 0u; + static mbgl::AnnotationID boundAnnotationID = std::numeric_limits::max(); + + mbgl::LatLngBounds bound = bounds[nextBound++]; + nextBound = nextBound % bounds.size(); + + view->map->setBounds(mbgl::BoundOptions().withLatLngBounds(bound)); + + if (bound == mbgl::LatLngBounds()) { + view->map->removeAnnotation(boundAnnotationID); + boundAnnotationID = std::numeric_limits::max(); + } else { + mbgl::Polygon rect; + rect.push_back({ + mbgl::Point{bound.west(), bound.north()}, + mbgl::Point{bound.east(), bound.north()}, + mbgl::Point{bound.east(), bound.south()}, + mbgl::Point{bound.west(), bound.south()}, + }); + + auto boundAnnotation = mbgl::FillAnnotation{ + rect, 0.5f, {view->makeRandomColor()}, {view->makeRandomColor()}}; + + if (boundAnnotationID == std::numeric_limits::max()) { + boundAnnotationID = view->map->addAnnotation(boundAnnotation); + } else { + view->map->updateAnnotation(boundAnnotationID, boundAnnotation); + } + } + } break; + case GLFW_KEY_T: + view->toggleCustomSource(); + break; + case GLFW_KEY_F: { + using namespace mbgl; + using namespace mbgl::style; + using namespace mbgl::style::expression::dsl; + + auto &style = view->map->getStyle(); + if (!style.getSource("states")) { + std::string url = "https://maplibre.org/maplibre-gl-js-docs/assets/us_states.geojson"; + auto source = std::make_unique("states"); + source->setURL(url); + style.addSource(std::move(source)); + + mbgl::CameraOptions cameraOptions; + cameraOptions.center = mbgl::LatLng{42.619626, -103.523181}; + cameraOptions.zoom = 3; + cameraOptions.pitch = 0; + cameraOptions.bearing = 0; + view->map->jumpTo(cameraOptions); } - auto camera = routeMap->getCameraOptions(); - - auto point = ruler.along(lineString, routeProgress * routeDistance); - const mbgl::LatLng center { point.y, point.x }; - auto latLng = *camera.center; - double bearing = ruler.bearing({ latLng.longitude(), latLng.latitude() }, point); - double easing = bearing - *camera.bearing; - easing += easing > 180.0 ? -360.0 : easing < -180 ? 360.0 : 0; - bearing = *camera.bearing + (easing / 20); - routeMap->jumpTo(mbgl::CameraOptions().withCenter(center).withZoom(18.0).withBearing(bearing).withPitch(60.0)); - }; - view->animateRouteCallback(view->map); - } break; - case GLFW_KEY_E: - view->toggle3DExtrusions(!view->show3DExtrusions); - break; - case GLFW_KEY_D: { - static const std::vector bounds = { - mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -170.0}, mbgl::LatLng{45.0, 170.0}), // inside - mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -200.0}, mbgl::LatLng{45.0, -160.0}), // left IDL - mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, 160.0}, mbgl::LatLng{45.0, 200.0}), // right IDL - mbgl::LatLngBounds()}; - static size_t nextBound = 0u; - static mbgl::AnnotationID boundAnnotationID = std::numeric_limits::max(); - - mbgl::LatLngBounds bound = bounds[nextBound++]; - nextBound = nextBound % bounds.size(); - - view->map->setBounds(mbgl::BoundOptions().withLatLngBounds(bound)); - - if (bound == mbgl::LatLngBounds()) { - view->map->removeAnnotation(boundAnnotationID); - boundAnnotationID = std::numeric_limits::max(); - } else { - mbgl::Polygon rect; - rect.push_back({ - mbgl::Point{ bound.west(), bound.north() }, - mbgl::Point{ bound.east(), bound.north() }, - mbgl::Point{ bound.east(), bound.south() }, - mbgl::Point{ bound.west(), bound.south() }, - }); - - auto boundAnnotation = mbgl::FillAnnotation { rect, 0.5f, { view->makeRandomColor() }, { view->makeRandomColor() } }; - - if (boundAnnotationID == std::numeric_limits::max()) { - boundAnnotationID = view->map->addAnnotation(boundAnnotation); + auto layer = style.getLayer("state-fills"); + if (!layer) { + auto fillLayer = std::make_unique("state-fills", "states"); + fillLayer->setFillColor(mbgl::Color{0.0, 0.0, 1.0, 0.5}); + fillLayer->setFillOpacity(PropertyExpression( + createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 1, 0.5])") + )); + style.addLayer(std::move(fillLayer)); } else { - view->map->updateAnnotation(boundAnnotationID, boundAnnotation); + layer->setVisibility( + layer->getVisibility() == mbgl::style::VisibilityType::Visible + ? mbgl::style::VisibilityType::None + : mbgl::style::VisibilityType::Visible + ); } - } - } break; - case GLFW_KEY_T: - view->toggleCustomSource(); - break; - case GLFW_KEY_F: { - using namespace mbgl; - using namespace mbgl::style; - using namespace mbgl::style::expression::dsl; - - auto &style = view->map->getStyle(); - if (!style.getSource("states")) { - std::string url = "https://maplibre.org/maplibre-gl-js-docs/assets/us_states.geojson"; - auto source = std::make_unique("states"); - source->setURL(url); - style.addSource(std::move(source)); - - mbgl::CameraOptions cameraOptions; - cameraOptions.center = mbgl::LatLng{42.619626, -103.523181}; - cameraOptions.zoom = 3; - cameraOptions.pitch = 0; - cameraOptions.bearing = 0; - view->map->jumpTo(cameraOptions); - } - - auto layer = style.getLayer("state-fills"); - if (!layer) { - auto fillLayer = std::make_unique("state-fills", "states"); - fillLayer->setFillColor(mbgl::Color{0.0, 0.0, 1.0, 0.5}); - fillLayer->setFillOpacity(PropertyExpression( - createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 1, 0.5])"))); - style.addLayer(std::move(fillLayer)); - } else { - layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible - ? mbgl::style::VisibilityType::None - : mbgl::style::VisibilityType::Visible); - } - layer = style.getLayer("state-borders"); - if (!layer) { - auto borderLayer = std::make_unique("state-borders", "states"); - borderLayer->setLineColor(mbgl::Color{0.0, 0.0, 1.0, 1.0}); - borderLayer->setLineWidth(PropertyExpression( - createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 2, 1])"))); - style.addLayer(std::move(borderLayer)); - } else { - layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible - ? mbgl::style::VisibilityType::None - : mbgl::style::VisibilityType::Visible); - } - } break; - case GLFW_KEY_F1: { - bool success = TestWriter() - .withInitialSize(mbgl::Size(view->width, view->height)) - .withStyle(view->map->getStyle()) - .withCameraOptions(view->map->getCameraOptions()) - .write(view->testDirectory); - - if (success) { - mbgl::Log::Info(mbgl::Event::General, "Render test created!"); - } else { - mbgl::Log::Error(mbgl::Event::General, - "Fail to create render test! Base directory does not exist or permission denied."); - } - } break; - case GLFW_KEY_U: { - auto bounds = view->map->getBounds(); - if (bounds.minPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MIN) && - bounds.maxPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MAX)) { - mbgl::Log::Info(mbgl::Event::General, "Limiting pitch bounds to [30, 40] degrees"); - view->map->setBounds(mbgl::BoundOptions().withMinPitch(30).withMaxPitch(40)); - } else { - mbgl::Log::Info(mbgl::Event::General, "Resetting pitch bounds to [0, 60] degrees"); - view->map->setBounds(mbgl::BoundOptions().withMinPitch(0).withMaxPitch(60)); - } - } break; - case GLFW_KEY_H: { - view->makeSnapshot(); - } break; - case GLFW_KEY_J: { - // Snapshot with overlay - view->makeSnapshot(true); - } break; - case GLFW_KEY_G: { - view->toggleLocationIndicatorLayer(); - } break; - case GLFW_KEY_Y: { - view->freeCameraDemoPhase = 0; - view->freeCameraDemoStartTime = mbgl::Clock::now(); - view->invalidate(); - } break; + layer = style.getLayer("state-borders"); + if (!layer) { + auto borderLayer = std::make_unique("state-borders", "states"); + borderLayer->setLineColor(mbgl::Color{0.0, 0.0, 1.0, 1.0}); + borderLayer->setLineWidth(PropertyExpression( + createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 2, 1])") + )); + style.addLayer(std::move(borderLayer)); + } else { + layer->setVisibility( + layer->getVisibility() == mbgl::style::VisibilityType::Visible + ? mbgl::style::VisibilityType::None + : mbgl::style::VisibilityType::Visible + ); + } + } break; + case GLFW_KEY_F1: { + bool success = TestWriter() + .withInitialSize(mbgl::Size(view->width, view->height)) + .withStyle(view->map->getStyle()) + .withCameraOptions(view->map->getCameraOptions()) + .write(view->testDirectory); + + if (success) { + mbgl::Log::Info(mbgl::Event::General, "Render test created!"); + } else { + mbgl::Log::Error( + mbgl::Event::General, + "Fail to create render test! Base directory does not exist or permission denied." + ); + } + } break; + case GLFW_KEY_U: { + auto bounds = view->map->getBounds(); + if (bounds.minPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MIN) && + bounds.maxPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MAX)) { + mbgl::Log::Info(mbgl::Event::General, "Limiting pitch bounds to [30, 40] degrees"); + view->map->setBounds(mbgl::BoundOptions().withMinPitch(30).withMaxPitch(40)); + } else { + mbgl::Log::Info(mbgl::Event::General, "Resetting pitch bounds to [0, 60] degrees"); + view->map->setBounds(mbgl::BoundOptions().withMinPitch(0).withMaxPitch(60)); + } + } break; + case GLFW_KEY_H: { + view->makeSnapshot(); + } break; + case GLFW_KEY_J: { + // Snapshot with overlay + view->makeSnapshot(true); + } break; + case GLFW_KEY_G: { + view->toggleLocationIndicatorLayer(); + } break; + case GLFW_KEY_Y: { + view->freeCameraDemoPhase = 0; + view->freeCameraDemoStartTime = mbgl::Clock::now(); + view->invalidate(); + } break; } } if (action == GLFW_RELEASE || action == GLFW_REPEAT) { switch (key) { - case GLFW_KEY_W: view->popAnnotation(); break; - case GLFW_KEY_1: view->addRandomPointAnnotations(1); break; - case GLFW_KEY_2: view->addRandomPointAnnotations(10); break; - case GLFW_KEY_3: view->addRandomPointAnnotations(100); break; - case GLFW_KEY_4: view->addRandomPointAnnotations(1000); break; - case GLFW_KEY_5: view->addRandomPointAnnotations(10000); break; - case GLFW_KEY_6: view->addRandomPointAnnotations(100000); break; - case GLFW_KEY_7: view->addRandomShapeAnnotations(1); break; - case GLFW_KEY_8: view->addRandomShapeAnnotations(10); break; - case GLFW_KEY_9: view->addRandomShapeAnnotations(100); break; - case GLFW_KEY_0: view->addRandomShapeAnnotations(1000); break; - case GLFW_KEY_M: view->addAnimatedAnnotation(); break; + case GLFW_KEY_W: + view->popAnnotation(); + break; + case GLFW_KEY_1: + view->addRandomPointAnnotations(1); + break; + case GLFW_KEY_2: + view->addRandomPointAnnotations(10); + break; + case GLFW_KEY_3: + view->addRandomPointAnnotations(100); + break; + case GLFW_KEY_4: + view->addRandomPointAnnotations(1000); + break; + case GLFW_KEY_5: + view->addRandomPointAnnotations(10000); + break; + case GLFW_KEY_6: + view->addRandomPointAnnotations(100000); + break; + case GLFW_KEY_7: + view->addRandomShapeAnnotations(1); + break; + case GLFW_KEY_8: + view->addRandomShapeAnnotations(10); + break; + case GLFW_KEY_9: + view->addRandomShapeAnnotations(100); + break; + case GLFW_KEY_0: + view->addRandomShapeAnnotations(1000); + break; + case GLFW_KEY_M: + view->addAnimatedAnnotation(); + break; } } } @@ -563,18 +614,19 @@ mbgl::Color GLFWView::makeRandomColor() const { const auto r = static_cast(std::rand()) / static_cast(RAND_MAX); const auto g = static_cast(std::rand()) / static_cast(RAND_MAX); const auto b = static_cast(std::rand()) / static_cast(RAND_MAX); - return { r, g, b, 1.0f }; + return {r, g, b, 1.0f}; } mbgl::Point GLFWView::makeRandomPoint() const { const double x = width * static_cast(std::rand()) / RAND_MAX; const double y = height * static_cast(std::rand()) / RAND_MAX; - mbgl::LatLng latLng = map->latLngForPixel({ x, y }); - return { latLng.longitude(), latLng.latitude() }; + mbgl::LatLng latLng = map->latLngForPixel({x, y}); + return {latLng.longitude(), latLng.latitude()}; } -std::unique_ptr -GLFWView::makeImage(const std::string& id, int width, int height, float pixelRatio) { +std::unique_ptr GLFWView::makeImage( + const std::string &id, int width, int height, float pixelRatio +) { const int r = static_cast(255 * (static_cast(std::rand()) / RAND_MAX)); const int g = static_cast(255 * (static_cast(std::rand()) / RAND_MAX)); const int b = static_cast(255 * (static_cast(std::rand()) / RAND_MAX)); @@ -582,8 +634,8 @@ GLFWView::makeImage(const std::string& id, int width, int height, float pixelRat const int w = static_cast(std::ceil(pixelRatio * width)); const int h = static_cast(std::ceil(pixelRatio * height)); - mbgl::PremultipliedImage image({ static_cast(w), static_cast(h) }); - auto data = reinterpret_cast(image.data.get()); + mbgl::PremultipliedImage image({static_cast(w), static_cast(h)}); + auto data = reinterpret_cast(image.data.get()); const int dist = (w / 2) * (w / 2); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { @@ -593,8 +645,7 @@ GLFWView::makeImage(const std::string& id, int width, int height, float pixelRat if (diff > 0) { const int a = std::min(0xFF, diff) * 0xFF / dist; // Premultiply the rgb values with alpha - data[w * y + x] = - (a << 24) | ((a * r / 0xFF) << 16) | ((a * g / 0xFF) << 8) | (a * b / 0xFF); + data[w * y + x] = (a << 24) | ((a * r / 0xFF) << 16) | ((a * g / 0xFF) << 8) | (a * b / 0xFF); } } } @@ -605,26 +656,34 @@ GLFWView::makeImage(const std::string& id, int width, int height, float pixelRat void GLFWView::nextOrientation() { using NO = mbgl::NorthOrientation; switch (map->getMapOptions().northOrientation()) { - case NO::Upwards: map->setNorthOrientation(NO::Rightwards); break; - case NO::Rightwards: map->setNorthOrientation(NO::Downwards); break; - case NO::Downwards: map->setNorthOrientation(NO::Leftwards); break; - default: map->setNorthOrientation(NO::Upwards); break; + case NO::Upwards: + map->setNorthOrientation(NO::Rightwards); + break; + case NO::Rightwards: + map->setNorthOrientation(NO::Downwards); + break; + case NO::Downwards: + map->setNorthOrientation(NO::Leftwards); + break; + default: + map->setNorthOrientation(NO::Upwards); + break; } } void GLFWView::addRandomCustomPointAnnotations(int count) { for (int i = 0; i < count; i++) { static int spriteID = 1; - const auto name = std::string{ "marker-" } + mbgl::util::toString(spriteID++); + const auto name = std::string{"marker-"} + mbgl::util::toString(spriteID++); map->addAnnotationImage(makeImage(name, 22, 22, 1)); spriteIDs.push_back(name); - annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation { makeRandomPoint(), name })); + annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation{makeRandomPoint(), name})); } } void GLFWView::addRandomPointAnnotations(int count) { for (int i = 0; i < count; ++i) { - annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation { makeRandomPoint(), "default_marker" })); + annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation{makeRandomPoint(), "default_marker"})); } } @@ -634,21 +693,22 @@ void GLFWView::addRandomLineAnnotations(int count) { for (int j = 0; j < 3; ++j) { lineString.push_back(makeRandomPoint()); } - annotationIDs.push_back(map->addAnnotation(mbgl::LineAnnotation { lineString, 1.0f, 2.0f, { makeRandomColor() } })); + annotationIDs.push_back(map->addAnnotation(mbgl::LineAnnotation{lineString, 1.0f, 2.0f, {makeRandomColor()}})); } } void GLFWView::addRandomShapeAnnotations(int count) { for (int i = 0; i < count; ++i) { mbgl::Polygon triangle; - triangle.push_back({ makeRandomPoint(), makeRandomPoint(), makeRandomPoint() }); - annotationIDs.push_back(map->addAnnotation(mbgl::FillAnnotation { triangle, 0.5f, { makeRandomColor() }, { makeRandomColor() } })); + triangle.push_back({makeRandomPoint(), makeRandomPoint(), makeRandomPoint()}); + annotationIDs.push_back(map->addAnnotation(mbgl::FillAnnotation{ + triangle, 0.5f, {makeRandomColor()}, {makeRandomColor()}})); } } void GLFWView::addAnimatedAnnotation() { const double started = glfwGetTime(); - animatedAnnotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation { { 0, 0 } , "default_marker" })); + animatedAnnotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation{{0, 0}, "default_marker"})); animatedAnnotationAddedTimes.push_back(started); } @@ -659,8 +719,8 @@ void GLFWView::updateAnimatedAnnotations() { const double period = 10; const double x = dt / period * 360 - 180; - const double y = std::sin(dt/ period * M_PI * 2.0) * 80; - map->updateAnnotation(animatedAnnotationIDs[i], mbgl::SymbolAnnotation { {x, y }, "default_marker" }); + const double y = std::sin(dt / period * M_PI * 2.0) * 80; + map->updateAnnotation(animatedAnnotationIDs[i], mbgl::SymbolAnnotation{{x, y}, "default_marker"}); } } @@ -684,13 +744,13 @@ void GLFWView::cycleDebugOptions() { } void GLFWView::clearAnnotations() { - for (const auto& id : annotationIDs) { + for (const auto &id : annotationIDs) { map->removeAnnotation(id); } annotationIDs.clear(); - for (const auto& id : animatedAnnotationIDs) { + for (const auto &id : animatedAnnotationIDs) { map->removeAnnotation(id); } @@ -709,7 +769,12 @@ void GLFWView::popAnnotation() { void GLFWView::makeSnapshot(bool withOverlay) { if (!snapshotter || snapshotter->getStyleURL() != map->getStyle().getURL()) { snapshotter = std::make_unique( - map->getMapOptions().size(), map->getMapOptions().pixelRatio(), mapResourceOptions, mapClientOptions, *snapshotterObserver); + map->getMapOptions().size(), + map->getMapOptions().pixelRatio(), + mapResourceOptions, + mapClientOptions, + *snapshotterObserver + ); snapshotter->setStyleURL(map->getStyle().getURL()); } @@ -722,7 +787,8 @@ void GLFWView::makeSnapshot(bool withOverlay) { const mbgl::MapSnapshotter::LatLngForFn &) { if (!ptr) { std::ostringstream oss; - oss << "Made snapshot './snapshot.png' with size w:" << image.size.width << "px h:" << image.size.height << "px"; + oss << "Made snapshot './snapshot.png' with size w:" << image.size.width << "px h:" << image.size.height + << "px"; mbgl::Log::Info(mbgl::Event::General, oss.str()); std::ofstream file("./snapshot.png"); file << mbgl::encodePNG(image); @@ -761,7 +827,7 @@ void GLFWView::onScroll(GLFWwindow *window, double /*xOffset*/, double yOffset) scale = 1.0 / scale; } - view->map->scaleBy(scale, mbgl::ScreenCoordinate { view->lastX, view->lastY }); + view->map->scaleBy(scale, mbgl::ScreenCoordinate{view->lastX, view->lastY}); #if defined(MBGL_RENDER_BACKEND_OPENGL) && !defined(MBGL_LAYER_CUSTOM_DISABLE_ALL) if (view->puck && view->puckFollowsCameraCenter) { mbgl::LatLng mapCenter = view->map->getCameraOptions().center.value(); @@ -774,12 +840,12 @@ void GLFWView::onWindowResize(GLFWwindow *window, int width, int height) { auto *view = reinterpret_cast(glfwGetWindowUserPointer(window)); view->width = width; view->height = height; - view->map->setSize({ static_cast(view->width), static_cast(view->height) }); + view->map->setSize({static_cast(view->width), static_cast(view->height)}); } void GLFWView::onFramebufferResize(GLFWwindow *window, int width, int height) { auto *view = reinterpret_cast(glfwGetWindowUserPointer(window)); - view->backend->setSize({ static_cast(width), static_cast(height) }); + view->backend->setSize({static_cast(width), static_cast(height)}); // This is only triggered when the framebuffer is resized, but not the window. It can // happen when you move the window between screens with a different pixel ratio. @@ -791,8 +857,7 @@ void GLFWView::onFramebufferResize(GLFWwindow *window, int width, int height) { void GLFWView::onMouseClick(GLFWwindow *window, int button, int action, int modifiers) { auto *view = reinterpret_cast(glfwGetWindowUserPointer(window)); - if (button == GLFW_MOUSE_BUTTON_RIGHT || - (button == GLFW_MOUSE_BUTTON_LEFT && modifiers & GLFW_MOD_CONTROL)) { + if (button == GLFW_MOUSE_BUTTON_RIGHT || (button == GLFW_MOUSE_BUTTON_LEFT && modifiers & GLFW_MOD_CONTROL)) { view->rotating = action == GLFW_PRESS; view->map->setGestureInProgress(view->rotating); } else if (button == GLFW_MOUSE_BUTTON_LEFT && (modifiers & GLFW_MOD_SHIFT)) { @@ -806,9 +871,17 @@ void GLFWView::onMouseClick(GLFWwindow *window, int button, int action, int modi double now = glfwGetTime(); if (now - view->lastClick < 0.4 /* ms */) { if (modifiers & GLFW_MOD_SHIFT) { - view->map->scaleBy(0.5, mbgl::ScreenCoordinate { view->lastX, view->lastY }, mbgl::AnimationOptions{{mbgl::Milliseconds(500)}}); + view->map->scaleBy( + 0.5, + mbgl::ScreenCoordinate{view->lastX, view->lastY}, + mbgl::AnimationOptions{{mbgl::Milliseconds(500)}} + ); } else { - view->map->scaleBy(2.0, mbgl::ScreenCoordinate { view->lastX, view->lastY }, mbgl::AnimationOptions{{mbgl::Milliseconds(500)}}); + view->map->scaleBy( + 2.0, + mbgl::ScreenCoordinate{view->lastX, view->lastY}, + mbgl::AnimationOptions{{mbgl::Milliseconds(500)}} + ); } } view->lastClick = now; @@ -822,10 +895,10 @@ void GLFWView::onMouseMove(GLFWwindow *window, double x, double y) { const double dx = x - view->lastX; const double dy = y - view->lastY; if (dx || dy) { - view->map->moveBy(mbgl::ScreenCoordinate { dx, dy }); + view->map->moveBy(mbgl::ScreenCoordinate{dx, dy}); } } else if (view->rotating) { - view->map->rotateBy({ view->lastX, view->lastY }, { x, y }); + view->map->rotateBy({view->lastX, view->lastY}, {x, y}); } else if (view->pitching) { const double dy = y - view->lastY; if (dy) { @@ -896,12 +969,11 @@ void GLFWView::run() { dirty = false; const double started = glfwGetTime(); - if (animateRouteCallback) - animateRouteCallback(map); + if (animateRouteCallback) animateRouteCallback(map); updateAnimatedAnnotations(); - mbgl::gfx::BackendScope scope { backend->getRendererBackend() }; + mbgl::gfx::BackendScope scope{backend->getRendererBackend()}; rendererFrontend->render(); @@ -929,7 +1001,7 @@ float GLFWView::getPixelRatio() const { } mbgl::Size GLFWView::getSize() const { - return { static_cast(width), static_cast(height) }; + return {static_cast(width), static_cast(height)}; } void GLFWView::invalidate() { @@ -965,8 +1037,8 @@ void GLFWView::setShouldClose() { glfwPostEmptyEvent(); } -void GLFWView::setWindowTitle(const std::string& title) { - glfwSetWindowTitle(window, (std::string { "Mapbox GL: " } + title).c_str()); +void GLFWView::setWindowTitle(const std::string &title) { + glfwSetWindowTitle(window, (std::string{"Mapbox GL: "} + title).c_str()); } void GLFWView::onDidFinishLoadingStyle() { @@ -987,13 +1059,15 @@ void GLFWView::toggle3DExtrusions(bool visible) { void GLFWView::toggleCustomSource() { if (!map->getStyle().getSource("custom")) { mbgl::style::CustomGeometrySource::Options options; - options.cancelTileFunction = [](const mbgl::CanonicalTileID&) {}; - options.fetchTileFunction = [&](const mbgl::CanonicalTileID& tileID) { + options.cancelTileFunction = [](const mbgl::CanonicalTileID &) { + }; + options.fetchTileFunction = [&](const mbgl::CanonicalTileID &tileID) { double gridSpacing = 0.1; mbgl::FeatureCollection features; const mbgl::LatLngBounds bounds(tileID); - for (double y = ceil(bounds.north() / gridSpacing) * gridSpacing; y >= floor(bounds.south() / gridSpacing) * gridSpacing; y -= gridSpacing) { - + for (double y = ceil(bounds.north() / gridSpacing) * gridSpacing; + y >= floor(bounds.south() / gridSpacing) * gridSpacing; + y -= gridSpacing) { mapbox::geojson::line_string gridLine; gridLine.emplace_back(bounds.west(), y); gridLine.emplace_back(bounds.east(), y); @@ -1001,7 +1075,9 @@ void GLFWView::toggleCustomSource() { features.emplace_back(gridLine); } - for (double x = floor(bounds.west() / gridSpacing) * gridSpacing; x <= ceil(bounds.east() / gridSpacing) * gridSpacing; x += gridSpacing) { + for (double x = floor(bounds.west() / gridSpacing) * gridSpacing; + x <= ceil(bounds.east() / gridSpacing) * gridSpacing; + x += gridSpacing) { mapbox::geojson::line_string gridLine; gridLine.emplace_back(x, bounds.south()); gridLine.emplace_back(x, bounds.north()); @@ -1017,15 +1093,17 @@ void GLFWView::toggleCustomSource() { map->getStyle().addSource(std::make_unique("custom", options)); } - auto* layer = map->getStyle().getLayer("grid"); + auto *layer = map->getStyle().getLayer("grid"); if (!layer) { auto lineLayer = std::make_unique("grid", "custom"); - lineLayer->setLineColor(mbgl::Color{ 1.0, 0.0, 0.0, 1.0 }); + lineLayer->setLineColor(mbgl::Color{1.0, 0.0, 0.0, 1.0}); map->getStyle().addLayer(std::move(lineLayer)); } else { - layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible ? - mbgl::style::VisibilityType::None : mbgl::style::VisibilityType::Visible); + layer->setVisibility( + layer->getVisibility() == mbgl::style::VisibilityType::Visible ? mbgl::style::VisibilityType::None + : mbgl::style::VisibilityType::Visible + ); } } @@ -1036,14 +1114,14 @@ void GLFWView::toggleLocationIndicatorLayer() { if (puck == nullptr) { auto puckLayer = std::make_unique("puck"); - puckLayer->setLocationTransition(mbgl::style::TransitionOptions( - mbgl::Duration::zero(), mbgl::Duration::zero())); // Note: This is used here for demo purpose. - // SDKs should not use this, or else the location - // will "jump" to positions. + puckLayer->setLocationTransition(mbgl::style::TransitionOptions(mbgl::Duration::zero(), mbgl::Duration::zero()) + ); // Note: This is used here for demo purpose. + // SDKs should not use this, or else the location + // will "jump" to positions. puckLayer->setLocation(toArray(puckLocation)); puckLayer->setAccuracyRadius(50); - puckLayer->setAccuracyRadiusColor( - premultiply(mbgl::Color{0.0f, 1.0f, 0.0f, 0.2f})); // Note: these must be fed premultiplied + puckLayer->setAccuracyRadiusColor(premultiply(mbgl::Color{0.0f, 1.0f, 0.0f, 0.2f}) + ); // Note: these must be fed premultiplied puckLayer->setBearingTransition(mbgl::style::TransitionOptions(mbgl::Duration::zero(), mbgl::Duration::zero())); puckLayer->setBearing(mbgl::style::Rotation(0.0)); @@ -1055,13 +1133,16 @@ void GLFWView::toggleLocationIndicatorLayer() { puckLayer->setPerspectiveCompensation(0.9f); map->getStyle().addImage(std::make_unique( - "puck.png", mbgl::decodeImage(mbgl::util::read_file(mbglPuckAssetsPath + "puck.png")), 1.0f)); + "puck.png", mbgl::decodeImage(mbgl::util::read_file(mbglPuckAssetsPath + "puck.png")), 1.0f + )); map->getStyle().addImage(std::make_unique( - "puck_shadow.png", mbgl::decodeImage(mbgl::util::read_file(mbglPuckAssetsPath + "puck_shadow.png")), 1.0f)); + "puck_shadow.png", mbgl::decodeImage(mbgl::util::read_file(mbglPuckAssetsPath + "puck_shadow.png")), 1.0f + )); map->getStyle().addImage(std::make_unique( - "puck_hat.png", mbgl::decodeImage(mbgl::util::read_file(mbglPuckAssetsPath + "puck_hat.png")), 1.0f)); + "puck_hat.png", mbgl::decodeImage(mbgl::util::read_file(mbglPuckAssetsPath + "puck_hat.png")), 1.0f + )); puckLayer->setBearingImage(mbgl::style::expression::Image("puck.png")); puckLayer->setShadowImage(mbgl::style::expression::Image("puck_shadow.png")); diff --git a/platform/glfw/glfw_view.hpp b/platform/glfw/glfw_view.hpp index c430fad6d94..f76816c861d 100644 --- a/platform/glfw/glfw_view.hpp +++ b/platform/glfw/glfw_view.hpp @@ -25,16 +25,21 @@ class RendererBackend; class GLFWView : public mbgl::MapObserver { public: - GLFWView(bool fullscreen, bool benchmark, const mbgl::ResourceOptions &resourceOptions, const mbgl::ClientOptions &clientOptions); + GLFWView( + bool fullscreen, + bool benchmark, + const mbgl::ResourceOptions &resourceOptions, + const mbgl::ClientOptions &clientOptions + ); ~GLFWView() override; float getPixelRatio() const; - void setMap(mbgl::Map*); - - void setRenderFrontend(GLFWRendererFrontend*); + void setMap(mbgl::Map *); - mbgl::gfx::RendererBackend& getRendererBackend(); + void setRenderFrontend(GLFWRendererFrontend *); + + mbgl::gfx::RendererBackend &getRendererBackend(); void setTestDirectory(std::string dir) { testDirectory = std::move(dir); }; @@ -50,10 +55,10 @@ class GLFWView : public mbgl::MapObserver { void setShouldClose(); - void setWindowTitle(const std::string&); + void setWindowTitle(const std::string &); void run(); - + void invalidate(); mbgl::Size getSize() const; @@ -80,7 +85,9 @@ class GLFWView : public mbgl::MapObserver { mbgl::Color makeRandomColor() const; mbgl::Point makeRandomPoint() const; - static std::unique_ptr makeImage(const std::string& id, int width, int height, float pixelRatio); + static std::unique_ptr makeImage( + const std::string &id, int width, int height, float pixelRatio + ); void nextOrientation(); @@ -109,8 +116,8 @@ class GLFWView : public mbgl::MapObserver { private: void toggle3DExtrusions(bool visible); - mbgl::Map* map = nullptr; - GLFWRendererFrontend* rendererFrontend = nullptr; + mbgl::Map *map = nullptr; + GLFWRendererFrontend *rendererFrontend = nullptr; std::unique_ptr backend; std::string testDirectory = "."; @@ -141,7 +148,7 @@ class GLFWView : public mbgl::MapObserver { std::function pauseResumeCallback; std::function onlineStatusCallback; std::function resetDatabaseCallback; - std::function animateRouteCallback; + std::function animateRouteCallback; mbgl::util::RunLoop runLoop; mbgl::util::Timer frameTick; diff --git a/platform/glfw/main.cpp b/platform/glfw/main.cpp index 876486bf6c4..50e5f7a086c 100644 --- a/platform/glfw/main.cpp +++ b/platform/glfw/main.cpp @@ -35,7 +35,7 @@ void quit_handler(int) { } } -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { args::ArgumentParser argumentParser("Mapbox GL GLFW example"); args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {'h', "help"}); @@ -44,7 +44,8 @@ int main(int argc, char *argv[]) { args::Flag offlineFlag(argumentParser, "offline", "Toggle offline", {'o', "offline"}); args::ValueFlag testDirValue( - argumentParser, "directory", "Root directory for test generation", {"testDir"}); + argumentParser, "directory", "Root directory for test generation", {"testDir"} + ); args::ValueFlag backendValue(argumentParser, "backend", "Rendering backend", {"backend"}); args::ValueFlag apikeyValue(argumentParser, "key", "API key", {'t', "apikey"}); args::ValueFlag styleValue(argumentParser, "URL", "Map stylesheet", {'s', "style"}); @@ -112,22 +113,30 @@ int main(int argc, char *argv[]) { GLFWView backend(fullscreen, benchmark, resourceOptions, clientOptions); view = &backend; - std::shared_ptr onlineFileSource = - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Network, resourceOptions, clientOptions); + std::shared_ptr onlineFileSource = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::Network, resourceOptions, clientOptions + ); if (!settings.online) { if (onlineFileSource) { onlineFileSource->setProperty("online-status", false); mbgl::Log::Warning(mbgl::Event::Setup, "Application is offline. Press `O` to toggle online status."); } else { - mbgl::Log::Warning(mbgl::Event::Setup, - "Network resource provider is not available, only local requests are supported."); + mbgl::Log::Warning( + mbgl::Event::Setup, "Network resource provider is not available, only local requests are supported." + ); } } - GLFWRendererFrontend rendererFrontend { std::make_unique(view->getRendererBackend(), view->getPixelRatio()), *view }; + GLFWRendererFrontend rendererFrontend{ + std::make_unique(view->getRendererBackend(), view->getPixelRatio()), *view}; - mbgl::Map map(rendererFrontend, *view, - mbgl::MapOptions().withSize(view->getSize()).withPixelRatio(view->getPixelRatio()), resourceOptions, clientOptions); + mbgl::Map map( + rendererFrontend, + *view, + mbgl::MapOptions().withSize(view->getSize()).withPixelRatio(view->getPixelRatio()), + resourceOptions, + clientOptions + ); backend.setMap(&map); @@ -136,7 +145,7 @@ int main(int argc, char *argv[]) { } map.jumpTo(mbgl::CameraOptions() - .withCenter(mbgl::LatLng {settings.latitude, settings.longitude}) + .withCenter(mbgl::LatLng{settings.latitude, settings.longitude}) .withZoom(settings.zoom) .withBearing(settings.bearing) .withPitch(settings.pitch)); @@ -146,16 +155,21 @@ int main(int argc, char *argv[]) { view->setOnlineStatusCallback([&settings, onlineFileSource]() { if (!onlineFileSource) { - mbgl::Log::Warning(mbgl::Event::Setup, - "Cannot change online status. Network resource provider is not available."); + mbgl::Log::Warning( + mbgl::Event::Setup, "Cannot change online status. Network resource provider is not available." + ); return; } settings.online = !settings.online; onlineFileSource->setProperty("online-status", settings.online); - mbgl::Log::Info(mbgl::Event::Setup, std::string("Application is ") + (settings.online ? "online" : "offline") + ". Press `O` to toggle online status."); + mbgl::Log::Info( + mbgl::Event::Setup, + std::string("Application is ") + (settings.online ? "online" : "offline") + + ". Press `O` to toggle online status." + ); }); - view->setChangeStyleCallback([&map,&orderedStyles] () { + view->setChangeStyleCallback([&map, &orderedStyles]() { static uint8_t currentStyleIndex; if (++currentStyleIndex == orderedStyles.size()) { @@ -170,8 +184,9 @@ int main(int argc, char *argv[]) { }); // Resource loader controls top-level request processing and can resume / pause all managed sources simultaneously. - std::shared_ptr resourceLoader = - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions); + std::shared_ptr resourceLoader = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions + ); view->setPauseResumeCallback([resourceLoader]() { static bool isPaused = false; @@ -186,7 +201,8 @@ int main(int argc, char *argv[]) { // Database file source. auto databaseFileSource = std::static_pointer_cast(std::shared_ptr( - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Database, resourceOptions, clientOptions))); + mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Database, resourceOptions, clientOptions) + )); view->setResetCacheCallback([databaseFileSource]() { databaseFileSource->resetDatabase([](const std::exception_ptr& ex) { if (ex) { @@ -197,7 +213,7 @@ int main(int argc, char *argv[]) { // Load style if (style.empty()) { - const char *url = getenv("MAPBOX_STYLE_URL"); + const char* url = getenv("MAPBOX_STYLE_URL"); if (url == nullptr) { mbgl::util::DefaultStyle newStyle = orderedStyles[0]; style = newStyle.getUrl(); @@ -221,11 +237,12 @@ int main(int argc, char *argv[]) { settings.pitch = *camera.pitch; settings.debug = mbgl::EnumType(map.getDebug()); settings.save(); - mbgl::Log::Info(mbgl::Event::General, - "Exit location: --lat=\"" + std::to_string(settings.latitude) + - "\" --lon=\"" + std::to_string(settings.longitude) + - "\" --zoom=\"" + std::to_string(settings.zoom) + - "\" --bearing=\"" + std::to_string(settings.bearing) + "\""); + mbgl::Log::Info( + mbgl::Event::General, + "Exit location: --lat=\"" + std::to_string(settings.latitude) + "\" --lon=\"" + + std::to_string(settings.longitude) + "\" --zoom=\"" + std::to_string(settings.zoom) + "\" --bearing=\"" + + std::to_string(settings.bearing) + "\"" + ); view = nullptr; diff --git a/platform/glfw/settings_json.cpp b/platform/glfw/settings_json.cpp index 5b6aa4e0da1..1355e16f2c2 100644 --- a/platform/glfw/settings_json.cpp +++ b/platform/glfw/settings_json.cpp @@ -3,7 +3,9 @@ namespace mbgl { -Settings_JSON::Settings_JSON() { load(); } +Settings_JSON::Settings_JSON() { + load(); +} void Settings_JSON::load() { std::ifstream file("/tmp/mbgl-native.cfg"); diff --git a/platform/glfw/test_writer.cpp b/platform/glfw/test_writer.cpp index 4fcb79a8121..82dc8d0164d 100644 --- a/platform/glfw/test_writer.cpp +++ b/platform/glfw/test_writer.cpp @@ -20,7 +20,8 @@ class TestOperationSerializer { class SetCamera final : public TestOperationSerializer { public: - explicit SetCamera(mbgl::CameraOptions camera_) : camera(std::move(camera_)) {} + explicit SetCamera(mbgl::CameraOptions camera_) + : camera(std::move(camera_)) {} void serialize(Writer& writer) const override { if (camera.zoom) { @@ -59,7 +60,8 @@ class SetCamera final : public TestOperationSerializer { class SetStyle final : public TestOperationSerializer { public: - explicit SetStyle(const mbgl::style::Style& style) : url(style.getURL()) {} + explicit SetStyle(const mbgl::style::Style& style) + : url(style.getURL()) {} void serialize(Writer& writer) const override { writer.StartArray(); @@ -74,7 +76,9 @@ class SetStyle final : public TestOperationSerializer { class SetInitialSize final : public TestOperationSerializer { public: - explicit SetInitialSize(const mbgl::Size& size) : width(size.width), height(size.height) {} + explicit SetInitialSize(const mbgl::Size& size) + : width(size.width), + height(size.height) {} void serialize(Writer& writer) const override { writer.Key("width"); diff --git a/platform/linux/src/gl_functions.cpp b/platform/linux/src/gl_functions.cpp index f13626f3db7..24e9e61e3ef 100644 --- a/platform/linux/src/gl_functions.cpp +++ b/platform/linux/src/gl_functions.cpp @@ -10,255 +10,270 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = ::glActiveTexture; -void (* const glAttachShader)(GLuint, GLuint) = ::glAttachShader; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *) = ::glBindAttribLocation; -void (* const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; -void (* const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; -void (* const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; -void (* const glBindTexture)(GLenum, GLuint) = ::glBindTexture; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; -void (* const glBlendEquation)(GLenum) = ::glBlendEquation; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; -void (* const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; -void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum) = ::glBufferData; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *) = ::glBufferSubData; -GLenum (* const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; -void (* const glClear)(GLbitfield) = ::glClear; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; -void (* const glClearDepthf)(GLfloat) = ::glClearDepthf; -void (* const glClearStencil)(GLint) = ::glClearStencil; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; -void (* const glCompileShader)(GLuint) = ::glCompileShader; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *) = ::glCompressedTexImage2D; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *) = ::glCompressedTexSubImage2D; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; -GLuint (* const glCreateProgram)() = ::glCreateProgram; -GLuint (* const glCreateShader)(GLenum) = ::glCreateShader; -void (* const glCullFace)(GLenum) = ::glCullFace; -void (* const glDeleteBuffers)(GLsizei, const GLuint *) = ::glDeleteBuffers; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint *) = ::glDeleteFramebuffers; -void (* const glDeleteProgram)(GLuint) = ::glDeleteProgram; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *) = ::glDeleteRenderbuffers; -void (* const glDeleteShader)(GLuint) = ::glDeleteShader; -void (* const glDeleteTextures)(GLsizei, const GLuint *) = ::glDeleteTextures; -void (* const glDepthFunc)(GLenum) = ::glDepthFunc; -void (* const glDepthMask)(GLboolean) = ::glDepthMask; -void (* const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; -void (* const glDetachShader)(GLuint, GLuint) = ::glDetachShader; -void (* const glDisable)(GLenum) = ::glDisable; -void (* const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *) = ::glDrawElements; -void (* const glEnable)(GLenum) = ::glEnable; -void (* const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; -void (* const glFinish)() = ::glFinish; -void (* const glFlush)() = ::glFlush; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; -void (* const glFrontFace)(GLenum) = ::glFrontFace; -void (* const glGenBuffers)(GLsizei, GLuint *) = ::glGenBuffers; -void (* const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; -void (* const glGenFramebuffers)(GLsizei, GLuint *) = ::glGenFramebuffers; -void (* const glGenRenderbuffers)(GLsizei, GLuint *) = ::glGenRenderbuffers; -void (* const glGenTextures)(GLsizei, GLuint *) = ::glGenTextures; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveAttrib; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveUniform; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *) = ::glGetAttachedShaders; -GLint (* const glGetAttribLocation)(GLuint, const GLchar *) = ::glGetAttribLocation; -void (* const glGetBooleanv)(GLenum, GLboolean *) = ::glGetBooleanv; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetBufferParameteriv; -GLenum (* const glGetError)() = ::glGetError; -void (* const glGetFloatv)(GLenum, GLfloat *) = ::glGetFloatv; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *) = ::glGetFramebufferAttachmentParameteriv; -void (* const glGetIntegerv)(GLenum, GLint *) = ::glGetIntegerv; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetProgramInfoLog; -void (* const glGetProgramiv)(GLuint, GLenum, GLint *) = ::glGetProgramiv; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetRenderbufferParameteriv; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderInfoLog; -void (* const glGetShaderiv)(GLuint, GLenum, GLint *) = ::glGetShaderiv; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *) = ::glGetShaderPrecisionFormat; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderSource; -const GLubyte *(* const glGetString)(GLenum) = ::glGetString; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *) = ::glGetTexParameterfv; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *) = ::glGetTexParameteriv; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat *) = ::glGetUniformfv; -void (* const glGetUniformiv)(GLuint, GLint, GLint *) = ::glGetUniformiv; -GLint (* const glGetUniformLocation)(GLuint, const GLchar *) = ::glGetUniformLocation; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *) = ::glGetVertexAttribfv; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribiv; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **) = ::glGetVertexAttribPointerv; -void (* const glHint)(GLenum, GLenum) = ::glHint; -GLboolean (* const glIsBuffer)(GLuint) = ::glIsBuffer; -GLboolean (* const glIsEnabled)(GLenum) = ::glIsEnabled; -GLboolean (* const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; -GLboolean (* const glIsProgram)(GLuint) = ::glIsProgram; -GLboolean (* const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; -GLboolean (* const glIsShader)(GLuint) = ::glIsShader; -GLboolean (* const glIsTexture)(GLuint) = ::glIsTexture; -void (* const glLineWidth)(GLfloat) = ::glLineWidth; -void (* const glLinkProgram)(GLuint) = ::glLinkProgram; -void (* const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; -void (* const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *) = ::glReadPixels; -void (* const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; -void (* const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; -void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei) = ::glShaderBinary; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *) = ::glShaderSource; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; -void (* const glStencilMask)(GLuint) = ::glStencilMask; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *) = ::glTexImage2D; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *) = ::glTexParameterfv; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint *) = ::glTexParameteriv; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *) = ::glTexSubImage2D; -void (* const glUniform1f)(GLint, GLfloat) = ::glUniform1f; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *) = ::glUniform1fv; -void (* const glUniform1i)(GLint, GLint) = ::glUniform1i; -void (* const glUniform1iv)(GLint, GLsizei, const GLint *) = ::glUniform1iv; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *) = ::glUniform2fv; -void (* const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; -void (* const glUniform2iv)(GLint, GLsizei, const GLint *) = ::glUniform2iv; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *) = ::glUniform3fv; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; -void (* const glUniform3iv)(GLint, GLsizei, const GLint *) = ::glUniform3iv; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *) = ::glUniform4fv; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; -void (* const glUniform4iv)(GLint, GLsizei, const GLint *) = ::glUniform4iv; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2fv; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3fv; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4fv; -void (* const glUseProgram)(GLuint) = ::glUseProgram; -void (* const glValidateProgram)(GLuint) = ::glValidateProgram; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat *) = ::glVertexAttrib1fv; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat *) = ::glVertexAttrib2fv; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat *) = ::glVertexAttrib3fv; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat *) = ::glVertexAttrib4fv; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *) = ::glVertexAttribPointer; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; +void (*const glActiveTexture)(GLenum) = ::glActiveTexture; +void (*const glAttachShader)(GLuint, GLuint) = ::glAttachShader; +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = ::glBindAttribLocation; +void (*const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; +void (*const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; +void (*const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; +void (*const glBindTexture)(GLenum, GLuint) = ::glBindTexture; +void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; +void (*const glBlendEquation)(GLenum) = ::glBlendEquation; +void (*const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; +void (*const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; +void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; +void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = ::glBufferData; +void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = ::glBufferSubData; +GLenum (*const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; +void (*const glClear)(GLbitfield) = ::glClear; +void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; +void (*const glClearDepthf)(GLfloat) = ::glClearDepthf; +void (*const glClearStencil)(GLint) = ::glClearStencil; +void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; +void (*const glCompileShader)(GLuint) = ::glCompileShader; +void (*const glCompressedTexImage2D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = ::glCompressedTexImage2D; +void (*const glCompressedTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = ::glCompressedTexSubImage2D; +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; +GLuint (*const glCreateProgram)() = ::glCreateProgram; +GLuint (*const glCreateShader)(GLenum) = ::glCreateShader; +void (*const glCullFace)(GLenum) = ::glCullFace; +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = ::glDeleteBuffers; +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = ::glDeleteFramebuffers; +void (*const glDeleteProgram)(GLuint) = ::glDeleteProgram; +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = ::glDeleteRenderbuffers; +void (*const glDeleteShader)(GLuint) = ::glDeleteShader; +void (*const glDeleteTextures)(GLsizei, const GLuint*) = ::glDeleteTextures; +void (*const glDepthFunc)(GLenum) = ::glDepthFunc; +void (*const glDepthMask)(GLboolean) = ::glDepthMask; +void (*const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; +void (*const glDetachShader)(GLuint, GLuint) = ::glDetachShader; +void (*const glDisable)(GLenum) = ::glDisable; +void (*const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; +void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = ::glDrawElements; +void (*const glEnable)(GLenum) = ::glEnable; +void (*const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; +void (*const glFinish)() = ::glFinish; +void (*const glFlush)() = ::glFlush; +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; +void (*const glFrontFace)(GLenum) = ::glFrontFace; +void (*const glGenBuffers)(GLsizei, GLuint*) = ::glGenBuffers; +void (*const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; +void (*const glGenFramebuffers)(GLsizei, GLuint*) = ::glGenFramebuffers; +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = ::glGenRenderbuffers; +void (*const glGenTextures)(GLsizei, GLuint*) = ::glGenTextures; +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveAttrib; +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveUniform; +void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = ::glGetAttachedShaders; +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = ::glGetAttribLocation; +void (*const glGetBooleanv)(GLenum, GLboolean*) = ::glGetBooleanv; +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetBufferParameteriv; +GLenum (*const glGetError)() = ::glGetError; +void (*const glGetFloatv)(GLenum, GLfloat*) = ::glGetFloatv; +void (*const glGetFramebufferAttachmentParameteriv +)(GLenum, GLenum, GLenum, GLint*) = ::glGetFramebufferAttachmentParameteriv; +void (*const glGetIntegerv)(GLenum, GLint*) = ::glGetIntegerv; +void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetProgramInfoLog; +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = ::glGetProgramiv; +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetRenderbufferParameteriv; +void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderInfoLog; +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = ::glGetShaderiv; +void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = ::glGetShaderPrecisionFormat; +void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderSource; +const GLubyte* (*const glGetString)(GLenum) = ::glGetString; +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = ::glGetTexParameterfv; +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = ::glGetTexParameteriv; +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = ::glGetUniformfv; +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = ::glGetUniformiv; +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = ::glGetUniformLocation; +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = ::glGetVertexAttribfv; +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribiv; +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = ::glGetVertexAttribPointerv; +void (*const glHint)(GLenum, GLenum) = ::glHint; +GLboolean (*const glIsBuffer)(GLuint) = ::glIsBuffer; +GLboolean (*const glIsEnabled)(GLenum) = ::glIsEnabled; +GLboolean (*const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; +GLboolean (*const glIsProgram)(GLuint) = ::glIsProgram; +GLboolean (*const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; +GLboolean (*const glIsShader)(GLuint) = ::glIsShader; +GLboolean (*const glIsTexture)(GLuint) = ::glIsTexture; +void (*const glLineWidth)(GLfloat) = ::glLineWidth; +void (*const glLinkProgram)(GLuint) = ::glLinkProgram; +void (*const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; +void (*const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = ::glReadPixels; +void (*const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; +void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; +void (*const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = ::glShaderBinary; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = ::glShaderSource; +void (*const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; +void (*const glStencilMask)(GLuint) = ::glStencilMask; +void (*const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; +void (*const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; +void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; +void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = ::glTexImage2D; +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = ::glTexParameterfv; +void (*const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = ::glTexParameteriv; +void (*const glTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = ::glTexSubImage2D; +void (*const glUniform1f)(GLint, GLfloat) = ::glUniform1f; +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = ::glUniform1fv; +void (*const glUniform1i)(GLint, GLint) = ::glUniform1i; +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = ::glUniform1iv; +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = ::glUniform2fv; +void (*const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = ::glUniform2iv; +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = ::glUniform3fv; +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = ::glUniform3iv; +void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = ::glUniform4fv; +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = ::glUniform4iv; +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2fv; +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3fv; +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4fv; +void (*const glUseProgram)(GLuint) = ::glUseProgram; +void (*const glValidateProgram)(GLuint) = ::glValidateProgram; +void (*const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = ::glVertexAttrib1fv; +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = ::glVertexAttrib2fv; +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = ::glVertexAttrib3fv; +void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = ::glVertexAttrib4fv; +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = ::glVertexAttribPointer; +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = ::glReadBuffer; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *) = ::glDrawRangeElements; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *) = ::glTexImage3D; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *) = ::glTexSubImage3D; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage3D; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *) = ::glCompressedTexImage3D; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *) = ::glCompressedTexSubImage3D; -void (* const glGenQueries)(GLsizei, GLuint *) = ::glGenQueries; -void (* const glDeleteQueries)(GLsizei, const GLuint *) = ::glDeleteQueries; -GLboolean (* const glIsQuery)(GLuint) = ::glIsQuery; -void (* const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; -void (* const glEndQuery)(GLenum) = ::glEndQuery; -void (* const glGetQueryiv)(GLenum, GLenum, GLint *) = ::glGetQueryiv; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint *) = ::glGetQueryObjectuiv; -GLboolean (* const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid **) = ::glGetBufferPointerv; -void (* const glDrawBuffers)(GLsizei, const GLenum *) = ::glDrawBuffers; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x3fv; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x2fv; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x4fv; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x2fv; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x4fv; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x3fv; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = ::glBlitFramebuffer; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorageMultisample; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; -void (* const glBindVertexArray)(GLuint) = ::glBindVertexArray; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint *) = ::glDeleteVertexArrays; -void (* const glGenVertexArrays)(GLsizei, GLuint *) = ::glGenVertexArrays; -GLboolean (* const glIsVertexArray)(GLuint) = ::glIsVertexArray; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint *) = ::glGetIntegeri_v; -void (* const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; -void (* const glEndTransformFeedback)() = ::glEndTransformFeedback; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar * const*, GLenum) = ::glTransformFeedbackVaryings; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei *, GLsizei *, GLenum *, GLchar *) = ::glGetTransformFeedbackVarying; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid *) = ::glVertexAttribIPointer; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribIiv; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint *) = ::glGetVertexAttribIuiv; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; -void (* const glVertexAttribI4iv)(GLuint, const GLint *) = ::glVertexAttribI4iv; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint *) = ::glVertexAttribI4uiv; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint *) = ::glGetUniformuiv; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar *) = ::glGetFragDataLocation; -void (* const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint *) = ::glUniform1uiv; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint *) = ::glUniform2uiv; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint *) = ::glUniform3uiv; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint *) = ::glUniform4uiv; -void (* const glClearBufferiv)(GLenum, GLint, const GLint *) = ::glClearBufferiv; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint *) = ::glClearBufferuiv; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat *) = ::glClearBufferfv; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = ::glGetStringi; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar * const*, GLuint *) = ::glGetUniformIndices; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint *, GLenum, GLint *) = ::glGetActiveUniformsiv; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar *) = ::glGetUniformBlockIndex; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint *) = ::glGetActiveUniformBlockiv; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetActiveUniformBlockName; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid *, GLsizei) = ::glDrawElementsInstanced; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; -GLboolean (* const glIsSync)(GLsync) = ::glIsSync; -void (* const glDeleteSync)(GLsync) = ::glDeleteSync; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; -void (* const glGetInteger64v)(GLenum, GLint64 *) = ::glGetInteger64v; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei *, GLint *) = ::glGetSynciv; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64 *) = ::glGetInteger64i_v; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64 *) = ::glGetBufferParameteri64v; -void (* const glGenSamplers)(GLsizei, GLuint *) = ::glGenSamplers; -void (* const glDeleteSamplers)(GLsizei, const GLuint *) = ::glDeleteSamplers; -GLboolean (* const glIsSampler)(GLuint) = ::glIsSampler; -void (* const glBindSampler)(GLuint, GLuint) = ::glBindSampler; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint *) = ::glSamplerParameteriv; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat *) = ::glSamplerParameterfv; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint *) = ::glGetSamplerParameteriv; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat *) = ::glGetSamplerParameterfv; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; -void (* const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint *) = ::glDeleteTransformFeedbacks; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint *) = ::glGenTransformFeedbacks; -GLboolean (* const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; -void (* const glPauseTransformFeedback)() = ::glPauseTransformFeedback; -void (* const glResumeTransformFeedback)() = ::glResumeTransformFeedback; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei *, GLenum *, GLvoid *) = ::glGetProgramBinary; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid *, GLsizei) = ::glProgramBinary; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum *) = ::glInvalidateFramebuffer; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei) = ::glInvalidateSubFramebuffer; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint *) = ::glGetInternalformativ; +void (*const glReadBuffer)(GLenum) = ::glReadBuffer; +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = ::glDrawRangeElements; +void (*const glTexImage3D +)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = ::glTexImage3D; +void (*const glTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = ::glTexSubImage3D; +void (*const glCopyTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage3D; +void (*const glCompressedTexImage3D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = ::glCompressedTexImage3D; +void (*const glCompressedTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = + ::glCompressedTexSubImage3D; +void (*const glGenQueries)(GLsizei, GLuint*) = ::glGenQueries; +void (*const glDeleteQueries)(GLsizei, const GLuint*) = ::glDeleteQueries; +GLboolean (*const glIsQuery)(GLuint) = ::glIsQuery; +void (*const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; +void (*const glEndQuery)(GLenum) = ::glEndQuery; +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = ::glGetQueryiv; +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = ::glGetQueryObjectuiv; +GLboolean (*const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = ::glGetBufferPointerv; +void (*const glDrawBuffers)(GLsizei, const GLenum*) = ::glDrawBuffers; +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x3fv; +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x2fv; +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x4fv; +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x2fv; +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x4fv; +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x3fv; +void (*const glBlitFramebuffer +)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = ::glBlitFramebuffer; +void (*const glRenderbufferStorageMultisample +)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorageMultisample; +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; +GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; +void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; +void (*const glBindVertexArray)(GLuint) = ::glBindVertexArray; +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = ::glDeleteVertexArrays; +void (*const glGenVertexArrays)(GLsizei, GLuint*) = ::glGenVertexArrays; +GLboolean (*const glIsVertexArray)(GLuint) = ::glIsVertexArray; +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = ::glGetIntegeri_v; +void (*const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; +void (*const glEndTransformFeedback)() = ::glEndTransformFeedback; +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; +void (*const glTransformFeedbackVaryings +)(GLuint, GLsizei, const GLchar* const*, GLenum) = ::glTransformFeedbackVaryings; +void (*const glGetTransformFeedbackVarying +)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = ::glGetTransformFeedbackVarying; +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = ::glVertexAttribIPointer; +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribIiv; +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = ::glGetVertexAttribIuiv; +void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; +void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = ::glVertexAttribI4iv; +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = ::glVertexAttribI4uiv; +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = ::glGetUniformuiv; +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = ::glGetFragDataLocation; +void (*const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; +void (*const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; +void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = ::glUniform1uiv; +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = ::glUniform2uiv; +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = ::glUniform3uiv; +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = ::glUniform4uiv; +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = ::glClearBufferiv; +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = ::glClearBufferuiv; +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = ::glClearBufferfv; +void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = ::glGetStringi; +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = ::glGetUniformIndices; +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = ::glGetActiveUniformsiv; +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = ::glGetUniformBlockIndex; +void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = ::glGetActiveUniformBlockiv; +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetActiveUniformBlockName; +void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; +void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = ::glDrawElementsInstanced; +GLsync (*const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; +GLboolean (*const glIsSync)(GLsync) = ::glIsSync; +void (*const glDeleteSync)(GLsync) = ::glDeleteSync; +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; +void (*const glGetInteger64v)(GLenum, GLint64*) = ::glGetInteger64v; +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = ::glGetSynciv; +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = ::glGetInteger64i_v; +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = ::glGetBufferParameteri64v; +void (*const glGenSamplers)(GLsizei, GLuint*) = ::glGenSamplers; +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = ::glDeleteSamplers; +GLboolean (*const glIsSampler)(GLuint) = ::glIsSampler; +void (*const glBindSampler)(GLuint, GLuint) = ::glBindSampler; +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = ::glSamplerParameteriv; +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; +void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = ::glSamplerParameterfv; +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = ::glGetSamplerParameteriv; +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = ::glGetSamplerParameterfv; +void (*const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; +void (*const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = ::glDeleteTransformFeedbacks; +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = ::glGenTransformFeedbacks; +GLboolean (*const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; +void (*const glPauseTransformFeedback)() = ::glPauseTransformFeedback; +void (*const glResumeTransformFeedback)() = ::glResumeTransformFeedback; +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = ::glGetProgramBinary; +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = ::glProgramBinary; +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; +void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = ::glInvalidateFramebuffer; +void (*const glInvalidateSubFramebuffer +)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = ::glInvalidateSubFramebuffer; +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = ::glGetInternalformativ; -} // namespace platform -} // namespace mbgl +} // namespace platform +} // namespace mbgl diff --git a/platform/linux/src/headless_backend_egl.cpp b/platform/linux/src/headless_backend_egl.cpp index 31c64b415ea..ca76ca004e4 100644 --- a/platform/linux/src/headless_backend_egl.cpp +++ b/platform/linux/src/headless_backend_egl.cpp @@ -16,7 +16,9 @@ namespace gl { class EGLDisplayConfig { private: // Key for singleton construction. - struct Key { explicit Key() = default; }; + struct Key { + explicit Key() = default; + }; public: EGLDisplayConfig(Key) { @@ -31,16 +33,13 @@ class EGLDisplayConfig { } if (!eglBindAPI(EGL_OPENGL_ES_API)) { - mbgl::Log::Error(mbgl::Event::OpenGL, "eglBindAPI(EGL_OPENGL_ES_API) returned error " + - std::to_string(eglGetError())); + mbgl::Log::Error( + mbgl::Event::OpenGL, "eglBindAPI(EGL_OPENGL_ES_API) returned error " + std::to_string(eglGetError()) + ); throw std::runtime_error("eglBindAPI() failed"); } - const EGLint attribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, - EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, - EGL_NONE - }; + const EGLint attribs[] = {EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE}; // Note: we're choosing an arbitrary pixel format, since we're not using the default surface // anyway; all rendering will be directed to framebuffers which have their own configuration. @@ -49,9 +48,7 @@ class EGLDisplayConfig { } } - ~EGLDisplayConfig() { - eglTerminate(display); - } + ~EGLDisplayConfig() { eglTerminate(display); } static std::shared_ptr create() { static std::weak_ptr instance; @@ -74,10 +71,7 @@ class EGLBackendImpl final : public HeadlessBackend::Impl { // use OpenGL ES 2.0 which has the ability to create shader and program // objects and also to write vertex and fragment shaders in the OpenGL ES // Shading Language. - const EGLint attribs[] = { - EGL_CONTEXT_CLIENT_VERSION, 3, - EGL_NONE - }; + const EGLint attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE}; eglContext = eglCreateContext(eglDisplay->display, eglDisplay->config, EGL_NO_CONTEXT, attribs); if (eglContext == EGL_NO_CONTEXT) { @@ -92,12 +86,7 @@ class EGLBackendImpl final : public HeadlessBackend::Impl { // activate the context. // Note that to be able to create pbuffer surfaces, we need to choose a config that // includes EGL_SURFACE_TYPE, EGL_PBUFFER_BIT in HeadlessDisplay. - const EGLint surfAttribs[] = { - EGL_WIDTH, 8, - EGL_HEIGHT, 8, - EGL_LARGEST_PBUFFER, EGL_TRUE, - EGL_NONE - }; + const EGLint surfAttribs[] = {EGL_WIDTH, 8, EGL_HEIGHT, 8, EGL_LARGEST_PBUFFER, EGL_TRUE, EGL_NONE}; eglSurface = eglCreatePbufferSurface(eglDisplay->display, eglDisplay->config, surfAttribs); if (eglSurface == EGL_NO_SURFACE) { @@ -117,9 +106,7 @@ class EGLBackendImpl final : public HeadlessBackend::Impl { } } - gl::ProcAddress getExtensionFunctionPointer(const char* name) final { - return eglGetProcAddress(name); - } + gl::ProcAddress getExtensionFunctionPointer(const char* name) final { return eglGetProcAddress(name); } void activateContext() final { if (!eglMakeCurrent(eglDisplay->display, eglSurface, eglSurface, eglContext)) { diff --git a/platform/linux/src/headless_backend_glx.cpp b/platform/linux/src/headless_backend_glx.cpp index 4bb503a8a71..7c1d2f7a588 100644 --- a/platform/linux/src/headless_backend_glx.cpp +++ b/platform/linux/src/headless_backend_glx.cpp @@ -14,7 +14,9 @@ namespace gl { class GLXDisplayConfig { private: // Key for singleton construction. - struct Key { explicit Key() = default; }; + struct Key { + explicit Key() = default; + }; public: explicit GLXDisplayConfig(Key) { @@ -27,8 +29,8 @@ class GLXDisplayConfig { throw std::runtime_error("Failed to open X display."); } - const auto* extensions = reinterpret_cast( - glXQueryServerString(xDisplay, DefaultScreen(xDisplay), GLX_EXTENSIONS)); + const auto* extensions = + reinterpret_cast(glXQueryServerString(xDisplay, DefaultScreen(xDisplay), GLX_EXTENSIONS)); if (!extensions) { throw std::runtime_error("Cannot read GLX extensions."); } @@ -40,7 +42,7 @@ class GLXDisplayConfig { } // We're creating a dummy pbuffer anyway that we're not using. - static int pixelFormat[] = { GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, None }; + static int pixelFormat[] = {GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, None}; int configs = 0; fbConfigs = glXChooseFBConfig(xDisplay, DefaultScreen(xDisplay), pixelFormat, &configs); @@ -75,8 +77,7 @@ class GLXBackendImpl final : public HeadlessBackend::Impl { public: GLXBackendImpl() { // Try to create a legacy context. - glContext = glXCreateNewContext(glxDisplay->xDisplay, glxDisplay->fbConfigs[0], - GLX_RGBA_TYPE, None, True); + glContext = glXCreateNewContext(glxDisplay->xDisplay, glxDisplay->fbConfigs[0], GLX_RGBA_TYPE, None, True); if (glContext && !glXIsDirect(glxDisplay->xDisplay, glContext)) { Log::Error(Event::OpenGL, "failed to create direct OpenGL Legacy context"); glXDestroyContext(glxDisplay->xDisplay, glContext); @@ -88,9 +89,8 @@ class GLXBackendImpl final : public HeadlessBackend::Impl { // Create a dummy pbuffer. We will render to framebuffers anyway, but we need a pbuffer to // activate the context. - int pbufferAttributes[] = { GLX_PBUFFER_WIDTH, 8, GLX_PBUFFER_HEIGHT, 8, None }; - glxPbuffer = - glXCreatePbuffer(glxDisplay->xDisplay, glxDisplay->fbConfigs[0], pbufferAttributes); + int pbufferAttributes[] = {GLX_PBUFFER_WIDTH, 8, GLX_PBUFFER_HEIGHT, 8, None}; + glxPbuffer = glXCreatePbuffer(glxDisplay->xDisplay, glxDisplay->fbConfigs[0], pbufferAttributes); } ~GLXBackendImpl() final { diff --git a/platform/node/src/node_conversion.hpp b/platform/node/src/node_conversion.hpp index 64da82d203f..fa783ba1066 100644 --- a/platform/node/src/node_conversion.hpp +++ b/platform/node/src/node_conversion.hpp @@ -46,12 +46,14 @@ class ConversionTraits> { return value->IsObject() && !value->IsArray(); } - static std::optional> objectMember(const v8::Local& value, const char * name) { + static std::optional> objectMember(const v8::Local& value, const char* name) { Nan::EscapableHandleScope scope; if (!Nan::Has(Nan::To(value).ToLocalChecked(), Nan::New(name).ToLocalChecked()).FromJust()) { return {}; } - Nan::MaybeLocal result = Nan::Get(Nan::To(value).ToLocalChecked(), Nan::New(name).ToLocalChecked()); + Nan::MaybeLocal result = Nan::Get( + Nan::To(value).ToLocalChecked(), Nan::New(name).ToLocalChecked() + ); if (result.IsEmpty()) { return {}; } @@ -61,7 +63,8 @@ class ConversionTraits> { template static std::optional eachMember(const v8::Local& value, Fn&& fn) { Nan::HandleScope scope; - v8::Local names = Nan::GetOwnPropertyNames(Nan::To(value).ToLocalChecked()).ToLocalChecked(); + v8::Local names = + Nan::GetOwnPropertyNames(Nan::To(value).ToLocalChecked()).ToLocalChecked(); for (uint32_t i = 0; i < names->Length(); ++i) { v8::Local k = Nan::Get(names, i).ToLocalChecked(); v8::Local v = Nan::Get(Nan::To(value).ToLocalChecked(), k).ToLocalChecked(); @@ -107,17 +110,17 @@ class ConversionTraits> { static std::optional toValue(const v8::Local& value) { if (value->IsFalse()) { - return { false }; + return {false}; } else if (value->IsTrue()) { - return { true }; + return {true}; } else if (value->IsString()) { - return { std::string(*Nan::Utf8String(value)) }; + return {std::string(*Nan::Utf8String(value))}; } else if (value->IsUint32()) { - return { Nan::To(value).ToChecked() }; + return {Nan::To(value).ToChecked()}; } else if (value->IsInt32()) { - return { Nan::To(value).ToChecked() }; + return {Nan::To(value).ToChecked()}; } else if (value->IsNumber()) { - return { Nan::To(value).ToChecked() }; + return {Nan::To(value).ToChecked()}; } else { return {}; } @@ -131,14 +134,14 @@ class ConversionTraits> { std::string string = *Nan::Utf8String(stringified); return parseGeoJSON(string, error); } catch (const std::exception& ex) { - error = { ex.what() }; + error = {ex.what()}; return {}; } } }; -template -std::optional convert(const v8::Local& value, Error& error, Args&&...args) { +template +std::optional convert(const v8::Local& value, Error& error, Args&&... args) { return convert(Convertible(value), error, std::forward(args)...); } diff --git a/platform/node/src/node_expression.cpp b/platform/node/src/node_expression.cpp index 7da4f12c355..eeba94f507b 100644 --- a/platform/node/src/node_expression.cpp +++ b/platform/node/src/node_expression.cpp @@ -40,15 +40,16 @@ void NodeExpression::Init(v8::Local target) { } type::Type parseType(v8::Local type) { - static std::unordered_map types = {{"string", type::String}, - {"number", type::Number}, - {"boolean", type::Boolean}, - {"object", type::Object}, - {"color", type::Color}, - {"value", type::Value}, - {"formatted", type::Formatted}, - {"number-format", type::String}, - {"resolvedImage", type::Image}}; + static std::unordered_map types = { + {"string", type::String}, + {"number", type::Number}, + {"boolean", type::Boolean}, + {"object", type::Object}, + {"color", type::Color}, + {"value", type::Value}, + {"formatted", type::Formatted}, + {"number-format", type::String}, + {"resolvedImage", type::Image}}; v8::Local v8kind = Nan::Get(type, Nan::New("kind").ToLocalChecked()).ToLocalChecked(); std::string kind(*v8::String::Utf8Value(v8::Isolate::GetCurrent(), v8kind)); @@ -59,7 +60,9 @@ type::Type parseType(v8::Local type) { #else v8::Local context = type->GetCreationContext().ToLocalChecked(); #endif - type::Type itemType = parseType(Nan::Get(type, Nan::New("itemType").ToLocalChecked()).ToLocalChecked()->ToObject(context).ToLocalChecked()); + type::Type itemType = parseType( + Nan::Get(type, Nan::New("itemType").ToLocalChecked()).ToLocalChecked()->ToObject(context).ToLocalChecked() + ); std::optional N; v8::Local Nkey = Nan::New("N").ToLocalChecked(); @@ -97,12 +100,8 @@ void NodeExpression::Parse(const Nan::FunctionCallbackInfo& info) { for (std::size_t i = 0; i < errors.size(); ++i) { const auto& error = errors[i]; v8::Local err = Nan::New(); - Nan::Set(err, - Nan::New("key").ToLocalChecked(), - Nan::New(error.key.c_str()).ToLocalChecked()); - Nan::Set(err, - Nan::New("error").ToLocalChecked(), - Nan::New(error.message.c_str()).ToLocalChecked()); + Nan::Set(err, Nan::New("key").ToLocalChecked(), Nan::New(error.key.c_str()).ToLocalChecked()); + Nan::Set(err, Nan::New("error").ToLocalChecked(), Nan::New(error.message.c_str()).ToLocalChecked()); Nan::Set(result, Nan::New(static_cast(i)), err); } info.GetReturnValue().Set(result); @@ -119,7 +118,7 @@ void NodeExpression::Parse(const Nan::FunctionCallbackInfo& info) { if (func) { return success(std::move(*func)); } - return fail({ { error.message, "" } }); + return fail({{error.message, ""}}); } ParsingContext ctx = expected ? ParsingContext(*expected) : ParsingContext(); @@ -129,7 +128,7 @@ void NodeExpression::Parse(const Nan::FunctionCallbackInfo& info) { return success(std::move(*parsed)); } return fail(ctx.getErrors()); - } catch(std::exception &ex) { + } catch (std::exception& ex) { return Nan::ThrowError(ex.what()); } } @@ -213,12 +212,11 @@ struct ToValue { } v8::Local operator()(const mbgl::Color& color) { - return operator()(std::vector { + return operator()(std::vector{ static_cast(color.r), static_cast(color.g), static_cast(color.b), - static_cast(color.a) - }); + static_cast(color.a)}); } v8::Local operator()(const std::unordered_map& map) { @@ -248,11 +246,14 @@ void NodeExpression::Evaluate(const Nan::FunctionCallbackInfo& info) } std::optional zoom; - v8::Local v8zoom = Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("zoom").ToLocalChecked()).ToLocalChecked(); + v8::Local v8zoom = + Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("zoom").ToLocalChecked()).ToLocalChecked(); if (v8zoom->IsNumber()) zoom = static_cast(Nan::To(v8zoom).FromJust()); std::optional heatmapDensity; - v8::Local v8heatmapDensity = Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("heatmapDensity").ToLocalChecked()).ToLocalChecked(); + v8::Local v8heatmapDensity = + Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("heatmapDensity").ToLocalChecked()) + .ToLocalChecked(); if (v8heatmapDensity->IsNumber()) heatmapDensity = Nan::To(v8heatmapDensity).FromJust(); Nan::JSON NanJSON; @@ -270,12 +271,12 @@ void NodeExpression::Evaluate(const Nan::FunctionCallbackInfo& info) info.GetReturnValue().Set(toJS(*result)); } else { v8::Local res = Nan::New(); - Nan::Set(res, - Nan::New("error").ToLocalChecked(), - Nan::New(result.error().message.c_str()).ToLocalChecked()); + Nan::Set( + res, Nan::New("error").ToLocalChecked(), Nan::New(result.error().message.c_str()).ToLocalChecked() + ); info.GetReturnValue().Set(res); } - } catch(std::exception &ex) { + } catch (std::exception& ex) { return Nan::ThrowTypeError(ex.what()); } } @@ -285,7 +286,7 @@ void NodeExpression::GetType(const Nan::FunctionCallbackInfo& info) { const std::unique_ptr& expression = nodeExpr->expression; const type::Type type = expression->getType(); - const std::string name = type.match([&] (const auto& t) { return t.getName(); }); + const std::string name = type.match([&](const auto& t) { return t.getName(); }); info.GetReturnValue().Set(Nan::New(name.c_str()).ToLocalChecked()); } diff --git a/platform/node/src/node_feature.cpp b/platform/node/src/node_feature.cpp index 7f2c5f35fe8..fa9a72675b1 100644 --- a/platform/node/src/node_feature.cpp +++ b/platform/node/src/node_feature.cpp @@ -14,37 +14,21 @@ using Properties = mbgl::PropertyMap; template struct ToType { public: - v8::Local operator()(const empty&) { - return type("Empty"); - } + v8::Local operator()(const empty&) { return type("Empty"); } - v8::Local operator()(const point&) { - return type("Point"); - } + v8::Local operator()(const point&) { return type("Point"); } - v8::Local operator()(const line_string&) { - return type("LineString"); - } + v8::Local operator()(const line_string&) { return type("LineString"); } - v8::Local operator()(const polygon&) { - return type("Polygon"); - } + v8::Local operator()(const polygon&) { return type("Polygon"); } - v8::Local operator()(const multi_point&) { - return type("MultiPoint"); - } + v8::Local operator()(const multi_point&) { return type("MultiPoint"); } - v8::Local operator()(const multi_line_string&) { - return type("MultiLineString"); - } + v8::Local operator()(const multi_line_string&) { return type("MultiLineString"); } - v8::Local operator()(const multi_polygon&) { - return type("MultiPolygon"); - } + v8::Local operator()(const multi_polygon&) { return type("MultiPolygon"); } - v8::Local operator()(const geometry_collection&) { - return type("GeometryCollection"); - } + v8::Local operator()(const geometry_collection&) { return type("GeometryCollection"); } private: v8::Local type(const char* type_) { @@ -75,9 +59,7 @@ struct ToCoordinatesOrGeometries { return scope.Escape(result); } - v8::Local operator()(const geometry& geometry) { - return toJS(geometry); - } + v8::Local operator()(const geometry& geometry) { return toJS(geometry); } }; struct ToValue { @@ -91,13 +73,9 @@ struct ToValue { return scope.Escape(Nan::New(t)); } - v8::Local operator()(int64_t t) { - return operator()(static_cast(t)); - } + v8::Local operator()(int64_t t) { return operator()(static_cast(t)); } - v8::Local operator()(uint64_t t) { - return operator()(static_cast(t)); - } + v8::Local operator()(uint64_t t) { return operator()(static_cast(t)); } v8::Local operator()(double t) { Nan::EscapableHandleScope scope; @@ -118,9 +96,7 @@ struct ToValue { return scope.Escape(result); } - v8::Local operator()(const std::unordered_map& map) { - return toJS(map); - } + v8::Local operator()(const std::unordered_map& map) { return toJS(map); } }; v8::Local toJS(const Geometry& geometry) { @@ -128,13 +104,13 @@ v8::Local toJS(const Geometry& geometry) { v8::Local result = Nan::New(); - Nan::Set(result, - Nan::New("type").ToLocalChecked(), - Geometry::visit(geometry, ToType())); + Nan::Set(result, Nan::New("type").ToLocalChecked(), Geometry::visit(geometry, ToType())); - Nan::Set(result, + Nan::Set( + result, Nan::New(geometry.is() ? "geometries" : "coordinates").ToLocalChecked(), - Geometry::visit(geometry, ToCoordinatesOrGeometries())); + Geometry::visit(geometry, ToCoordinatesOrGeometries()) + ); return scope.Escape(result); } diff --git a/platform/node/src/node_feature.hpp b/platform/node/src/node_feature.hpp index 8d1eceba38f..4a7e6be23da 100644 --- a/platform/node/src/node_feature.hpp +++ b/platform/node/src/node_feature.hpp @@ -15,4 +15,4 @@ v8::Local toJS(const mbgl::Feature&); v8::Local toJS(const mbgl::Feature::geometry_type&); v8::Local toJS(const mbgl::PropertyMap&); -} +} // namespace node_mbgl diff --git a/platform/node/src/node_logging.cpp b/platform/node/src/node_logging.cpp index 5e7326e90a9..aa208967615 100644 --- a/platform/node/src/node_logging.cpp +++ b/platform/node/src/node_logging.cpp @@ -12,9 +12,9 @@ struct NodeLogObserver::LogMessage { LogMessage(mbgl::EventSeverity severity_, mbgl::Event event_, int64_t code_, std::string text_) : severity(severity_), - event(event_), - code(code_), - text(std::move(text_)) {} + event(event_), + code(code_), + text(std::move(text_)) {} }; NodeLogObserver::NodeLogObserver(v8::Local target) @@ -23,25 +23,30 @@ NodeLogObserver::NodeLogObserver(v8::Local target) auto msg = Nan::New(); - Nan::Set(msg, Nan::New("class").ToLocalChecked(), - Nan::New(mbgl::Enum::toString(message.event)).ToLocalChecked()); + Nan::Set( + msg, + Nan::New("class").ToLocalChecked(), + Nan::New(mbgl::Enum::toString(message.event)).ToLocalChecked() + ); - Nan::Set(msg, Nan::New("severity").ToLocalChecked(), - Nan::New(mbgl::Enum::toString(message.severity)).ToLocalChecked()); + Nan::Set( + msg, + Nan::New("severity").ToLocalChecked(), + Nan::New(mbgl::Enum::toString(message.severity)).ToLocalChecked() + ); if (message.code != -1) { - Nan::Set(msg, Nan::New("code").ToLocalChecked(), - Nan::New(message.code)); + Nan::Set(msg, Nan::New("code").ToLocalChecked(), Nan::New(message.code)); } if (!message.text.empty()) { - Nan::Set(msg, Nan::New("text").ToLocalChecked(), - Nan::New(message.text).ToLocalChecked()); + Nan::Set(msg, Nan::New("text").ToLocalChecked(), Nan::New(message.text).ToLocalChecked()); } - v8::Local argv[] = { Nan::New("message").ToLocalChecked(), msg }; + v8::Local argv[] = {Nan::New("message").ToLocalChecked(), msg}; auto handle = Nan::New(module); - auto emit = Nan::To(Nan::Get(handle, Nan::New("emit").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); + auto emit = Nan::To(Nan::Get(handle, Nan::New("emit").ToLocalChecked()).ToLocalChecked()) + .ToLocalChecked(); Nan::CallAsFunction(emit, handle, 2, argv); })) { Nan::HandleScope scope; @@ -56,7 +61,7 @@ NodeLogObserver::~NodeLogObserver() { } bool NodeLogObserver::onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &text) { - queue->send({ severity, event, code, text }); + queue->send({severity, event, code, text}); return true; } diff --git a/platform/node/src/node_logging.hpp b/platform/node/src/node_logging.hpp index 67f4ace079d..c03c7a00e29 100644 --- a/platform/node/src/node_logging.hpp +++ b/platform/node/src/node_logging.hpp @@ -12,7 +12,10 @@ namespace node_mbgl { -namespace util { template class AsyncQueue; } +namespace util { +template +class AsyncQueue; +} class NodeLogObserver : public mbgl::Log::Observer { public: diff --git a/platform/node/src/node_map.cpp b/platform/node/src/node_map.cpp index bb5536ef0dd..2aeef08a0e5 100644 --- a/platform/node/src/node_map.cpp +++ b/platform/node/src/node_map.cpp @@ -41,7 +41,7 @@ struct NodeMap::RenderOptions { double pitch = 0; double latitude = 0; double longitude = 0; - mbgl::Size size = { 512, 512 }; + mbgl::Size size = {512, 512}; bool axonometric = false; double xSkew = 0; double ySkew = 1; @@ -77,7 +77,9 @@ class ParseError extends Error { } } } -ParseError)JS").ToLocalChecked()).ToLocalChecked(); +ParseError)JS") + .ToLocalChecked()) + .ToLocalChecked(); parseError.Reset(Nan::To(Nan::RunScript(script).ToLocalChecked()).ToLocalChecked()); Nan::Set(target, Nan::New("ParseError").ToLocalChecked(), Nan::New(parseError)); @@ -177,7 +179,7 @@ void NodeMap::New(const Nan::FunctionCallbackInfo& info) { v8::Local options; - if(info.Length() > 0) { + if (info.Length() > 0) { options = Nan::To(info[0]).ToLocalChecked(); } else { options = Nan::New(); @@ -185,36 +187,39 @@ void NodeMap::New(const Nan::FunctionCallbackInfo& info) { // Check that if 'request' is set it must be a function, if 'cancel' is set it must be a // function and if 'ratio' is set it must be a number. - if (Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() - && !Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) { + if (Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() && + !Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) { return Nan::ThrowError("Options object 'request' property must be a function"); } - if (Nan::Has(options, Nan::New("cancel").ToLocalChecked()).FromJust() - && !Nan::Get(options, Nan::New("cancel").ToLocalChecked()).ToLocalChecked()->IsFunction()) { + if (Nan::Has(options, Nan::New("cancel").ToLocalChecked()).FromJust() && + !Nan::Get(options, Nan::New("cancel").ToLocalChecked()).ToLocalChecked()->IsFunction()) { return Nan::ThrowError("Options object 'cancel' property must be a function"); } - if (Nan::Has(options, Nan::New("ratio").ToLocalChecked()).FromJust() - && !Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()->IsNumber()) { + if (Nan::Has(options, Nan::New("ratio").ToLocalChecked()).FromJust() && + !Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()->IsNumber()) { return Nan::ThrowError("Options object 'ratio' property must be a number"); } info.This()->SetInternalField(1, options); - if(Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() - && Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) { + if (Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() && + Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) { mbgl::FileSourceManager::get()->registerFileSourceFactory( - mbgl::FileSourceType::ResourceLoader, [](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions&) { + mbgl::FileSourceType::ResourceLoader, + [](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions&) { return std::make_unique( - reinterpret_cast(resourceOptions.platformContext())); - }); + reinterpret_cast(resourceOptions.platformContext()) + ); + } + ); } try { auto nodeMap = new NodeMap(options); nodeMap->Wrap(info.This()); - } catch(std::exception &ex) { + } catch (std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -267,7 +272,7 @@ void NodeMap::Load(const Nan::FunctionCallbackInfo& info) { nodeMap->map->getStyle().loadJSON(style); } catch (const mbgl::util::StyleParseException& ex) { return Nan::ThrowError(ParseError(ex.what())); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -280,7 +285,8 @@ void NodeMap::Load(const Nan::FunctionCallbackInfo& info) { if (!Nan::Get(options, Nan::New("defaultStyleCamera").ToLocalChecked()).ToLocalChecked()->IsBoolean()) { return Nan::ThrowError("Options object 'defaultStyleCamera' property must be a boolean"); } - if (Nan::To(Nan::Get(options, Nan::New("cameraMutated").ToLocalChecked()).ToLocalChecked()).ToChecked()) { + if (Nan::To(Nan::Get(options, Nan::New("cameraMutated").ToLocalChecked()).ToLocalChecked()) + .ToChecked()) { nodeMap->map->jumpTo(nodeMap->map->getStyle().getDefaultCamera()); } } @@ -299,7 +305,7 @@ void NodeMap::Loaded(const Nan::FunctionCallbackInfo& info) { try { loaded = nodeMap->map->isFullyLoaded(); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -316,7 +322,8 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local obj) { } if (Nan::Has(obj, Nan::New("bearing").ToLocalChecked()).FromJust()) { - options.bearing = Nan::To(Nan::Get(obj, Nan::New("bearing").ToLocalChecked()).ToLocalChecked()).ToChecked(); + options.bearing = + Nan::To(Nan::Get(obj, Nan::New("bearing").ToLocalChecked()).ToLocalChecked()).ToChecked(); } if (Nan::Has(obj, Nan::New("pitch").ToLocalChecked()).FromJust()) { @@ -334,15 +341,20 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local obj) { } if (Nan::Has(obj, Nan::New("axonometric").ToLocalChecked()).FromJust()) { - options.axonometric = Nan::To(Nan::Get(obj, Nan::New("axonometric").ToLocalChecked()).ToLocalChecked()).ToChecked(); + options.axonometric = + Nan::To(Nan::Get(obj, Nan::New("axonometric").ToLocalChecked()).ToLocalChecked()).ToChecked(); } if (Nan::Has(obj, Nan::New("skew").ToLocalChecked()).FromJust()) { auto skewObj = Nan::Get(obj, Nan::New("skew").ToLocalChecked()).ToLocalChecked(); if (skewObj->IsArray()) { auto skew = skewObj.As(); - if (skew->Length() > 0) { options.xSkew = Nan::To(Nan::Get(skew, 0).ToLocalChecked()).ToChecked(); } - if (skew->Length() > 1) { options.ySkew = Nan::To(Nan::Get(skew, 1).ToLocalChecked()).ToChecked(); } + if (skew->Length() > 0) { + options.xSkew = Nan::To(Nan::Get(skew, 0).ToLocalChecked()).ToChecked(); + } + if (skew->Length() > 1) { + options.ySkew = Nan::To(Nan::Get(skew, 1).ToLocalChecked()).ToChecked(); + } } } @@ -350,30 +362,42 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local obj) { auto centerObj = Nan::Get(obj, Nan::New("center").ToLocalChecked()).ToLocalChecked(); if (centerObj->IsArray()) { auto center = centerObj.As(); - if (center->Length() > 0) { options.longitude = Nan::To(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); } - if (center->Length() > 1) { options.latitude = Nan::To(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); } + if (center->Length() > 0) { + options.longitude = Nan::To(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); + } + if (center->Length() > 1) { + options.latitude = Nan::To(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); + } } } if (Nan::Has(obj, Nan::New("width").ToLocalChecked()).FromJust()) { - options.size.width = static_cast(Nan::To(Nan::Get(obj, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked()); + options.size.width = static_cast( + Nan::To(Nan::Get(obj, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked() + ); } if (Nan::Has(obj, Nan::New("height").ToLocalChecked()).FromJust()) { - options.size.height = static_cast(Nan::To(Nan::Get(obj, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked()); + options.size.height = static_cast( + Nan::To(Nan::Get(obj, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked() + ); } if (Nan::Has(obj, Nan::New("classes").ToLocalChecked()).FromJust()) { - auto classes = Nan::To(Nan::Get(obj, Nan::New("classes").ToLocalChecked()).ToLocalChecked()).ToLocalChecked().As(); + auto classes = Nan::To(Nan::Get(obj, Nan::New("classes").ToLocalChecked()).ToLocalChecked()) + .ToLocalChecked() + .As(); const int length = classes->Length(); options.classes.reserve(length); for (int i = 0; i < length; i++) { - options.classes.emplace_back(std::string { *Nan::Utf8String(Nan::To(Nan::Get(classes, i).ToLocalChecked()).ToLocalChecked()) }); + options.classes.emplace_back(std::string{ + *Nan::Utf8String(Nan::To(Nan::Get(classes, i).ToLocalChecked()).ToLocalChecked())}); } } if (Nan::Has(obj, Nan::New("debug").ToLocalChecked()).FromJust()) { - auto debug = Nan::To(Nan::Get(obj, Nan::New("debug").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); + auto debug = + Nan::To(Nan::Get(obj, Nan::New("debug").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); if (Nan::Has(debug, Nan::New("tileBorders").ToLocalChecked()).FromJust()) { if (Nan::To(Nan::Get(debug, Nan::New("tileBorders").ToLocalChecked()).ToLocalChecked()).ToChecked()) { options.debugOptions = options.debugOptions | mbgl::MapDebugOptions::TileBorders; @@ -406,12 +430,11 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local obj) { class RenderRequest : public Nan::AsyncResource { public: - explicit RenderRequest(v8::Local callback_) : AsyncResource("mbgl:RenderRequest") { + explicit RenderRequest(v8::Local callback_) + : AsyncResource("mbgl:RenderRequest") { callback.Reset(callback_); } - ~RenderRequest() { - callback.Reset(); - } + ~RenderRequest() { callback.Reset(); } Nan::Persistent callback; }; @@ -471,7 +494,7 @@ void NodeMap::Render(const Nan::FunctionCallbackInfo& info) { return Nan::ThrowTypeError(err.message.c_str()); } catch (const mbgl::util::StyleParseException& ex) { return Nan::ThrowError(ParseError(ex.what())); - } catch (const mbgl::util::Exception &ex) { + } catch (const mbgl::util::Exception& ex) { return Nan::ThrowError(ex.what()); } @@ -504,15 +527,13 @@ void NodeMap::startRender(const NodeMap::RenderOptions& options) { map->setSize(options.size); mbgl::CameraOptions camera; - camera.center = mbgl::LatLng { options.latitude, options.longitude }; + camera.center = mbgl::LatLng{options.latitude, options.longitude}; camera.zoom = options.zoom; camera.bearing = options.bearing; camera.pitch = options.pitch; - auto projectionOptions = mbgl::ProjectionMode() - .withAxonometric(options.axonometric) - .withXSkew(options.xSkew) - .withYSkew(options.ySkew); + auto projectionOptions = + mbgl::ProjectionMode().withAxonometric(options.axonometric).withXSkew(options.xSkew).withYSkew(options.ySkew); map->setProjectionMode(projectionOptions); @@ -533,11 +554,11 @@ void NodeMap::startRender(const NodeMap::RenderOptions& options) { // Similarly, we're now waiting for the async to be called, so we need to make sure that it // keeps the loop alive. - uv_ref(reinterpret_cast(async)); + uv_ref(reinterpret_cast(async)); } v8::Local NodeMap::ParseError(const char* msg) { - v8::Local argv[] = { Nan::New(msg).ToLocalChecked() }; + v8::Local argv[] = {Nan::New(msg).ToLocalChecked()}; return Nan::CallAsConstructor(Nan::New(parseError), 1, argv).ToLocalChecked(); } @@ -547,7 +568,7 @@ void NodeMap::renderFinished() { Nan::HandleScope scope; // We're done with this render call, so we're unrefing so that the loop could close. - uv_unref(reinterpret_cast(async)); + uv_unref(reinterpret_cast(async)); // Move the callback and image out of the way so that the callback can start a new render call. auto request = std::move(req); @@ -573,9 +594,7 @@ void NodeMap::renderFinished() { err = Nan::Error(ex.what()); } - v8::Local argv[] = { - err - }; + v8::Local argv[] = {err}; // This must be empty to be prepared for the next render call. error = nullptr; @@ -584,26 +603,21 @@ void NodeMap::renderFinished() { request->runInAsyncScope(target, callback, 1, argv); } else if (img.data) { v8::Local pixels = Nan::NewBuffer( - reinterpret_cast(img.data.get()), img.bytes(), - // Retain the data until the buffer is deleted. - [](char *, void * hint) { - delete [] reinterpret_cast(hint); - }, - img.data.get() - ).ToLocalChecked(); + reinterpret_cast(img.data.get()), + img.bytes(), + // Retain the data until the buffer is deleted. + [](char*, void* hint) { delete[] reinterpret_cast(hint); }, + img.data.get() + ) + .ToLocalChecked(); if (!pixels.IsEmpty()) { img.data.release(); } - v8::Local argv[] = { - Nan::Null(), - pixels - }; + v8::Local argv[] = {Nan::Null(), pixels}; request->runInAsyncScope(target, callback, 2, argv); } else { - v8::Local argv[] = { - Nan::Error("Didn't get an image") - }; + v8::Local argv[] = {Nan::Error("Didn't get an image")}; request->runInAsyncScope(target, callback, 1, argv); } @@ -623,7 +637,7 @@ void NodeMap::Release(const Nan::FunctionCallbackInfo& info) { try { nodeMap->release(); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -633,9 +647,7 @@ void NodeMap::Release(const Nan::FunctionCallbackInfo& info) { void NodeMap::release() { if (!map) throw mbgl::util::Exception(releasedMessage()); - uv_close(reinterpret_cast(async), [] (uv_handle_t *h) { - delete reinterpret_cast(h); - }); + uv_close(reinterpret_cast(async), [](uv_handle_t* h) { delete reinterpret_cast(h); }); map.reset(); frontend.reset(); @@ -655,7 +667,7 @@ void NodeMap::Cancel(const Nan::FunctionCallbackInfo& info) { try { nodeMap->cancel(); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -669,24 +681,26 @@ void NodeMap::cancel() { map.reset(); // Remove the existing async handle to flush any scheduled calls to renderFinished. - uv_unref(reinterpret_cast(async)); - uv_close(reinterpret_cast(async), [] (uv_handle_t *h) { - delete reinterpret_cast(h); - }); + uv_unref(reinterpret_cast(async)); + uv_close(reinterpret_cast(async), [](uv_handle_t* h) { delete reinterpret_cast(h); }); async = new uv_async_t; async->data = this; uv_async_init(uv_default_loop(), async, [](uv_async_t* h) { - reinterpret_cast(h->data)->renderFinished(); + reinterpret_cast(h->data)->renderFinished(); }); - frontend = std::make_unique(mbgl::Size{ 512, 512 }, pixelRatio); - map = std::make_unique(*frontend, mapObserver, - mbgl::MapOptions().withSize(frontend->getSize()) - .withPixelRatio(pixelRatio) - .withMapMode(mode) - .withCrossSourceCollisions(crossSourceCollisions), - mbgl::ResourceOptions().withPlatformContext(reinterpret_cast(this)), - mbgl::ClientOptions()); + frontend = std::make_unique(mbgl::Size{512, 512}, pixelRatio); + map = std::make_unique( + *frontend, + mapObserver, + mbgl::MapOptions() + .withSize(frontend->getSize()) + .withPixelRatio(pixelRatio) + .withMapMode(mode) + .withCrossSourceCollisions(crossSourceCollisions), + mbgl::ResourceOptions().withPlatformContext(reinterpret_cast(this)), + mbgl::ClientOptions() + ); // FIXME: Reload the style after recreating the map. We need to find // a better way of canceling an ongoing rendering on the core level @@ -717,7 +731,9 @@ void NodeMap::AddSource(const Nan::FunctionCallbackInfo& info) { } Error error; - std::optional> source = convert>(info[1], error, *Nan::Utf8String(info[0])); + std::optional> source = convert>( + info[1], error, *Nan::Utf8String(info[0]) + ); if (!source) { Nan::ThrowTypeError(error.message.c_str()); return; @@ -822,8 +838,10 @@ void NodeMap::AddImage(const Nan::FunctionCallbackInfo& info) { return Nan::ThrowTypeError("pixelRatio parameter required"); } - uint32_t imageHeight = Nan::To(Nan::Get(optionObject, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked(); - uint32_t imageWidth = Nan::To(Nan::Get(optionObject, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked(); + uint32_t imageHeight = + Nan::To(Nan::Get(optionObject, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked(); + uint32_t imageWidth = + Nan::To(Nan::Get(optionObject, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked(); if (imageWidth > 1024 || imageHeight > 1024) { return Nan::ThrowTypeError("Max height and width is 1024"); @@ -834,10 +852,12 @@ void NodeMap::AddImage(const Nan::FunctionCallbackInfo& info) { sdf = Nan::To(Nan::Get(optionObject, Nan::New("sdf").ToLocalChecked()).ToLocalChecked()).ToChecked(); } - float pixelRatio = (float)Nan::To(Nan::Get(optionObject, Nan::New("pixelRatio").ToLocalChecked()).ToLocalChecked()).ToChecked(); + float pixelRatio = (float + )Nan::To(Nan::Get(optionObject, Nan::New("pixelRatio").ToLocalChecked()).ToLocalChecked()) + .ToChecked(); auto imageBuffer = Nan::To(info[1]).ToLocalChecked()->ToObject(context).ToLocalChecked(); - char * imageDataBuffer = node::Buffer::Data(imageBuffer); + char* imageDataBuffer = node::Buffer::Data(imageBuffer); size_t imageLength = node::Buffer::Length(imageBuffer); if (imageLength != imageHeight * imageWidth * 4) { @@ -847,9 +867,11 @@ void NodeMap::AddImage(const Nan::FunctionCallbackInfo& info) { std::unique_ptr data = std::make_unique(imageLength); std::copy(imageDataBuffer, imageDataBuffer + imageLength, data.get()); - mbgl::UnassociatedImage cImage({ imageWidth, imageHeight}, std::move(data)); + mbgl::UnassociatedImage cImage({imageWidth, imageHeight}, std::move(data)); mbgl::PremultipliedImage cPremultipliedImage = mbgl::util::premultiply(std::move(cImage)); - nodeMap->map->getStyle().addImage(std::make_unique(*Nan::Utf8String(info[0]), std::move(cPremultipliedImage), pixelRatio, sdf)); + nodeMap->map->getStyle().addImage( + std::make_unique(*Nan::Utf8String(info[0]), std::move(cPremultipliedImage), pixelRatio, sdf) + ); } void NodeMap::RemoveImage(const Nan::FunctionCallbackInfo& info) { @@ -973,15 +995,19 @@ void NodeMap::SetSize(const Nan::FunctionCallbackInfo& info) { } auto size = info[0].As(); - uint32_t width= 0; + uint32_t width = 0; uint32_t height = 0; - if (size->Length() > 0) { width = Nan::To(Nan::Get(size, 0).ToLocalChecked()).ToChecked(); } - if (size->Length() > 1) { height = Nan::To(Nan::Get(size, 1).ToLocalChecked()).ToChecked(); } + if (size->Length() > 0) { + width = Nan::To(Nan::Get(size, 0).ToLocalChecked()).ToChecked(); + } + if (size->Length() > 1) { + height = Nan::To(Nan::Get(size, 1).ToLocalChecked()).ToChecked(); + } try { - nodeMap->frontend->setSize({ width, height }); - nodeMap->map->setSize({ width, height }); - } catch (const std::exception &ex) { + nodeMap->frontend->setSize({width, height}); + nodeMap->map->setSize({width, height}); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -999,12 +1025,16 @@ void NodeMap::SetCenter(const Nan::FunctionCallbackInfo& info) { auto center = info[0].As(); double latitude = 0; double longitude = 0; - if (center->Length() > 0) { longitude = Nan::To(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); } - if (center->Length() > 1) { latitude = Nan::To(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); } + if (center->Length() > 0) { + longitude = Nan::To(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); + } + if (center->Length() > 1) { + latitude = Nan::To(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); + } try { - nodeMap->map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng { latitude, longitude })); - } catch (const std::exception &ex) { + nodeMap->map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng{latitude, longitude})); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1021,7 +1051,7 @@ void NodeMap::SetZoom(const Nan::FunctionCallbackInfo& info) { try { nodeMap->map->jumpTo(mbgl::CameraOptions().withZoom(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1038,7 +1068,7 @@ void NodeMap::SetBearing(const Nan::FunctionCallbackInfo& info) { try { nodeMap->map->jumpTo(mbgl::CameraOptions().withBearing(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1055,7 +1085,7 @@ void NodeMap::SetPitch(const Nan::FunctionCallbackInfo& info) { try { nodeMap->map->jumpTo(mbgl::CameraOptions().withPitch(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1080,7 +1110,7 @@ void NodeMap::SetLight(const Nan::FunctionCallbackInfo& info) { } else { return Nan::ThrowTypeError(conversionError.message.c_str()); } - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1096,9 +1126,8 @@ void NodeMap::SetAxonometric(const Nan::FunctionCallbackInfo& info) { } try { - nodeMap->map->setProjectionMode(mbgl::ProjectionMode() - .withAxonometric(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + nodeMap->map->setProjectionMode(mbgl::ProjectionMode().withAxonometric(Nan::To(info[0]).ToChecked())); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1114,9 +1143,8 @@ void NodeMap::SetXSkew(const Nan::FunctionCallbackInfo& info) { } try { - nodeMap->map->setProjectionMode(mbgl::ProjectionMode() - .withXSkew(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + nodeMap->map->setProjectionMode(mbgl::ProjectionMode().withXSkew(Nan::To(info[0]).ToChecked())); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1132,9 +1160,8 @@ void NodeMap::SetYSkew(const Nan::FunctionCallbackInfo& info) { } try { - nodeMap->map->setProjectionMode(mbgl::ProjectionMode() - .withYSkew(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + nodeMap->map->setProjectionMode(mbgl::ProjectionMode().withYSkew(Nan::To(info[0]).ToChecked())); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1397,7 +1424,7 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo& auto options = Nan::To(info[1]).ToLocalChecked(); - //Check if layers is set. If provided, it must be an array of strings + // Check if layers is set. If provided, it must be an array of strings if (Nan::Has(options, Nan::New("layers").ToLocalChecked()).FromJust()) { auto layersOption = Nan::Get(options, Nan::New("layers").ToLocalChecked()).ToLocalChecked(); if (!layersOption->IsArray()) { @@ -1405,13 +1432,13 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo& } auto layers = layersOption.As(); std::vector layersVec; - for (uint32_t i=0; i < layers->Length(); i++) { - layersVec.emplace_back(*Nan::Utf8String(Nan::Get(layers,i).ToLocalChecked())); + for (uint32_t i = 0; i < layers->Length(); i++) { + layersVec.emplace_back(*Nan::Utf8String(Nan::Get(layers, i).ToLocalChecked())); } queryOptions.layerIDs = layersVec; } - //Check if filter is provided. If set it must be a valid Filter object + // Check if filter is provided. If set it must be a valid Filter object if (Nan::Has(options, Nan::New("filter").ToLocalChecked()).FromJust()) { auto filterOption = Nan::Get(options, Nan::New("filter").ToLocalChecked()).ToLocalChecked(); Error error; @@ -1427,25 +1454,25 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo& std::vector optional; if (Nan::Get(posOrBox, 0).ToLocalChecked()->IsArray()) { - auto pos0 = Nan::Get(posOrBox, 0).ToLocalChecked().As(); auto pos1 = Nan::Get(posOrBox, 1).ToLocalChecked().As(); - optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures(mbgl::ScreenBox { - { - Nan::To(Nan::Get(pos0, 0).ToLocalChecked()).ToChecked(), - Nan::To(Nan::Get(pos0, 1).ToLocalChecked()).ToChecked() - }, { - Nan::To(Nan::Get(pos1, 0).ToLocalChecked()).ToChecked(), - Nan::To(Nan::Get(pos1, 1).ToLocalChecked()).ToChecked() - } - }, queryOptions); + optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures( + mbgl::ScreenBox{ + {Nan::To(Nan::Get(pos0, 0).ToLocalChecked()).ToChecked(), + Nan::To(Nan::Get(pos0, 1).ToLocalChecked()).ToChecked()}, + {Nan::To(Nan::Get(pos1, 0).ToLocalChecked()).ToChecked(), + Nan::To(Nan::Get(pos1, 1).ToLocalChecked()).ToChecked()}}, + queryOptions + ); } else { - optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures(mbgl::ScreenCoordinate { - Nan::To(Nan::Get(posOrBox, 0).ToLocalChecked()).ToChecked(), - Nan::To(Nan::Get(posOrBox, 1).ToLocalChecked()).ToChecked() - }, queryOptions); + optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures( + mbgl::ScreenCoordinate{ + Nan::To(Nan::Get(posOrBox, 0).ToLocalChecked()).ToChecked(), + Nan::To(Nan::Get(posOrBox, 1).ToLocalChecked()).ToChecked()}, + queryOptions + ); } auto array = Nan::New(); @@ -1453,7 +1480,7 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo& Nan::Set(array, static_cast(i), toJS(optional[i])); } info.GetReturnValue().Set(array); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } } @@ -1462,42 +1489,52 @@ NodeMap::NodeMap(v8::Local options) : pixelRatio([&] { Nan::HandleScope scope; return Nan::Has(options, Nan::New("ratio").ToLocalChecked()).FromJust() - ? static_cast(Nan::To(Nan::Get(options, Nan::New("ratio").ToLocalChecked()) - .ToLocalChecked()).ToChecked()) + ? static_cast( + Nan::To(Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()) + .ToChecked() + ) : 1.0f; - }()) - , mode([&] { - Nan::HandleScope scope; - if (std::string(*v8::String::Utf8Value(v8::Isolate::GetCurrent(), Nan::Get(options, Nan::New("mode").ToLocalChecked()).ToLocalChecked())) == "tile") { - return mbgl::MapMode::Tile; - } else { - return mbgl::MapMode::Static; - } - }()) - , crossSourceCollisions([&] { - Nan::HandleScope scope; - return Nan::Has(options, Nan::New("crossSourceCollisions").ToLocalChecked()).FromJust() - ? Nan::To(Nan::Get(options, Nan::New("crossSourceCollisions").ToLocalChecked()) - .ToLocalChecked()).ToChecked() - : true; - }()) - , mapObserver(NodeMapObserver()) - , frontend(std::make_unique(mbgl::Size { 512, 512 }, pixelRatio)) - , map(std::make_unique(*frontend, mapObserver, - mbgl::MapOptions().withSize(frontend->getSize()) - .withPixelRatio(pixelRatio) - .withMapMode(mode) - .withCrossSourceCollisions(crossSourceCollisions), - mbgl::ResourceOptions().withPlatformContext(reinterpret_cast(this)), - mbgl::ClientOptions())) - , async(new uv_async_t) { + }()), + mode([&] { + Nan::HandleScope scope; + if (std::string(*v8::String::Utf8Value( + v8::Isolate::GetCurrent(), Nan::Get(options, Nan::New("mode").ToLocalChecked()).ToLocalChecked() + )) == "tile") { + return mbgl::MapMode::Tile; + } else { + return mbgl::MapMode::Static; + } + }()), + crossSourceCollisions([&] { + Nan::HandleScope scope; + return Nan::Has(options, Nan::New("crossSourceCollisions").ToLocalChecked()).FromJust() + ? Nan::To( + Nan::Get(options, Nan::New("crossSourceCollisions").ToLocalChecked()).ToLocalChecked() + ) + .ToChecked() + : true; + }()), + mapObserver(NodeMapObserver()), + frontend(std::make_unique(mbgl::Size{512, 512}, pixelRatio)), + map(std::make_unique( + *frontend, + mapObserver, + mbgl::MapOptions() + .withSize(frontend->getSize()) + .withPixelRatio(pixelRatio) + .withMapMode(mode) + .withCrossSourceCollisions(crossSourceCollisions), + mbgl::ResourceOptions().withPlatformContext(reinterpret_cast(this)), + mbgl::ClientOptions() + )), + async(new uv_async_t) { async->data = this; uv_async_init(uv_default_loop(), async, [](uv_async_t* h) { - reinterpret_cast(h->data)->renderFinished(); + reinterpret_cast(h->data)->renderFinished(); }); // Make sure the async handle doesn't keep the loop alive. - uv_unref(reinterpret_cast(async)); + uv_unref(reinterpret_cast(async)); } NodeMap::~NodeMap() { @@ -1508,7 +1545,9 @@ NodeMap::~NodeMap() { } } -std::unique_ptr NodeFileSource::request(const mbgl::Resource& resource, mbgl::FileSource::Callback callback_) { +std::unique_ptr NodeFileSource::request( + const mbgl::Resource& resource, mbgl::FileSource::Callback callback_ +) { assert(nodeMap); Nan::HandleScope scope; @@ -1524,8 +1563,7 @@ std::unique_ptr NodeFileSource::request(const mbgl::Resource Nan::New(&callback_), Nan::New(asyncRequest.get()), Nan::New(resource.url).ToLocalChecked(), - Nan::New(resource.kind) - }; + Nan::New(resource.kind)}; Nan::NewInstance(Nan::New(node_mbgl::NodeRequest::constructor), 5, argv).ToLocalChecked(); @@ -1537,7 +1575,7 @@ bool NodeFileSource::canRequest(const mbgl::Resource&) const { } void NodeFileSource::setResourceOptions(mbgl::ResourceOptions options) { - this->_resourceOptions = std::move(options); + this->_resourceOptions = std::move(options); } mbgl::ResourceOptions NodeFileSource::getResourceOptions() { diff --git a/platform/node/src/node_map.hpp b/platform/node/src/node_map.hpp index 179ab4121be..9f170d32750 100644 --- a/platform/node/src/node_map.hpp +++ b/platform/node/src/node_map.hpp @@ -94,13 +94,14 @@ class NodeMap : public Nan::ObjectWrap { std::unique_ptr req; // Async for delivering the notifications of render completion. - uv_async_t *async; + uv_async_t* async; bool loaded = false; }; struct NodeFileSource : public mbgl::FileSource { - NodeFileSource(NodeMap* nodeMap_) : nodeMap(nodeMap_) {} + NodeFileSource(NodeMap* nodeMap_) + : nodeMap(nodeMap_) {} ~NodeFileSource() override = default; std::unique_ptr request(const mbgl::Resource&, mbgl::FileSource::Callback) final; bool canRequest(const mbgl::Resource&) const override; diff --git a/platform/node/src/node_mapbox_gl_native.cpp b/platform/node/src/node_mapbox_gl_native.cpp index 425dd2b8aa5..3078cd8c852 100644 --- a/platform/node/src/node_mapbox_gl_native.cpp +++ b/platform/node/src/node_mapbox_gl_native.cpp @@ -14,13 +14,12 @@ #include "node_request.hpp" #include "node_expression.hpp" - void SetBackendType(const Nan::FunctionCallbackInfo& info) { if (info.Length() < 1 || info[0]->IsUndefined()) { return Nan::ThrowTypeError("Requires a render backend name"); } - const std::string backendName { *Nan::Utf8String(info[0]) }; + const std::string backendName{*Nan::Utf8String(info[0])}; (void)backendName; } @@ -40,54 +39,35 @@ void RegisterModule(v8::Local target, v8::Local module) // Exports Resource constants. v8::Local resource = Nan::New(); - Nan::Set(resource, - Nan::New("Unknown").ToLocalChecked(), - Nan::New(mbgl::Resource::Unknown)); + Nan::Set(resource, Nan::New("Unknown").ToLocalChecked(), Nan::New(mbgl::Resource::Unknown)); - Nan::Set(resource, - Nan::New("Style").ToLocalChecked(), - Nan::New(mbgl::Resource::Style)); + Nan::Set(resource, Nan::New("Style").ToLocalChecked(), Nan::New(mbgl::Resource::Style)); - Nan::Set(resource, - Nan::New("Source").ToLocalChecked(), - Nan::New(mbgl::Resource::Source)); + Nan::Set(resource, Nan::New("Source").ToLocalChecked(), Nan::New(mbgl::Resource::Source)); - Nan::Set(resource, - Nan::New("Tile").ToLocalChecked(), - Nan::New(mbgl::Resource::Tile)); + Nan::Set(resource, Nan::New("Tile").ToLocalChecked(), Nan::New(mbgl::Resource::Tile)); - Nan::Set(resource, - Nan::New("Glyphs").ToLocalChecked(), - Nan::New(mbgl::Resource::Glyphs)); + Nan::Set(resource, Nan::New("Glyphs").ToLocalChecked(), Nan::New(mbgl::Resource::Glyphs)); - Nan::Set(resource, - Nan::New("SpriteImage").ToLocalChecked(), - Nan::New(mbgl::Resource::SpriteImage)); + Nan::Set(resource, Nan::New("SpriteImage").ToLocalChecked(), Nan::New(mbgl::Resource::SpriteImage)); - Nan::Set(resource, - Nan::New("SpriteJSON").ToLocalChecked(), - Nan::New(mbgl::Resource::SpriteJSON)); + Nan::Set(resource, Nan::New("SpriteJSON").ToLocalChecked(), Nan::New(mbgl::Resource::SpriteJSON)); - Nan::Set(target, - Nan::New("Resource").ToLocalChecked(), - resource); + Nan::Set(target, Nan::New("Resource").ToLocalChecked(), resource); // Make the exported object inherit from EventEmitter - v8::Local require = Nan::Get(module, - Nan::New("require").ToLocalChecked()).ToLocalChecked().As(); + v8::Local require = + Nan::Get(module, Nan::New("require").ToLocalChecked()).ToLocalChecked().As(); v8::Local eventsString = Nan::New("events").ToLocalChecked(); - v8::Local events = Nan::To(Nan::Call(require, module, 1, &eventsString).ToLocalChecked()).ToLocalChecked(); + v8::Local events = + Nan::To(Nan::Call(require, module, 1, &eventsString).ToLocalChecked()).ToLocalChecked(); - v8::Local EventEmitter = Nan::To( - Nan::Get( - events, - Nan::New("EventEmitter").ToLocalChecked() - ).ToLocalChecked() - ).ToLocalChecked(); + v8::Local EventEmitter = + Nan::To(Nan::Get(events, Nan::New("EventEmitter").ToLocalChecked()).ToLocalChecked()) + .ToLocalChecked(); - Nan::SetPrototype(target, - Nan::Get(EventEmitter, Nan::New("prototype").ToLocalChecked()).ToLocalChecked()); + Nan::SetPrototype(target, Nan::Get(EventEmitter, Nan::New("prototype").ToLocalChecked()).ToLocalChecked()); Nan::CallAsFunction(EventEmitter, target, 0, nullptr); mbgl::Log::setObserver(std::make_unique(target)); diff --git a/platform/node/src/node_request.cpp b/platform/node/src/node_request.cpp index c8901f07a19..d83d9289e1d 100644 --- a/platform/node/src/node_request.cpp +++ b/platform/node/src/node_request.cpp @@ -7,12 +7,10 @@ namespace node_mbgl { -NodeRequest::NodeRequest( - mbgl::FileSource::Callback callback_, - NodeAsyncRequest* asyncRequest_) +NodeRequest::NodeRequest(mbgl::FileSource::Callback callback_, NodeAsyncRequest* asyncRequest_) : callback(std::move(callback_)), - asyncRequest(asyncRequest_) { - asyncRequest->request = this; + asyncRequest(asyncRequest_) { + asyncRequest->request = this; } NodeRequest::~NodeRequest() { @@ -53,12 +51,9 @@ void NodeRequest::New(const Nan::FunctionCallbackInfo& info) { request->Ref(); Nan::Set(info.This(), Nan::New("url").ToLocalChecked(), info[3]); Nan::Set(info.This(), Nan::New("kind").ToLocalChecked(), info[4]); - v8::Local argv[] = { info.This() }; + v8::Local argv[] = {info.This()}; request->asyncResource->runInAsyncScope( - Nan::To(target->handle()->GetInternalField(1)).ToLocalChecked(), - "request", - 1, - argv + Nan::To(target->handle()->GetInternalField(1)).ToLocalChecked(), "request", 1, argv ); info.GetReturnValue().Set(info.This()); } @@ -84,14 +79,12 @@ void NodeRequest::HandleCallback(const Nan::FunctionCallbackInfo& inf if (Nan::Has(err, msg).FromJust()) { response.error = std::make_unique( - mbgl::Response::Error::Reason::Other, - *Nan::Utf8String(Nan::Get(err, msg).ToLocalChecked()) + mbgl::Response::Error::Reason::Other, *Nan::Utf8String(Nan::Get(err, msg).ToLocalChecked()) ); } } else if (info[0]->IsString()) { response.error = std::make_unique( - mbgl::Response::Error::Reason::Other, - *Nan::Utf8String(info[0]) + mbgl::Response::Error::Reason::Other, *Nan::Utf8String(info[0]) ); } else if (info.Length() < 2 || !info[1]->IsObject()) { request->unrefRequest(); @@ -100,33 +93,30 @@ void NodeRequest::HandleCallback(const Nan::FunctionCallbackInfo& inf auto res = Nan::To(info[1]).ToLocalChecked(); if (Nan::Has(res, Nan::New("modified").ToLocalChecked()).FromJust()) { - const double modified = Nan::To(Nan::Get(res, Nan::New("modified").ToLocalChecked()).ToLocalChecked()).FromJust(); + const double modified = + Nan::To(Nan::Get(res, Nan::New("modified").ToLocalChecked()).ToLocalChecked()).FromJust(); if (!std::isnan(modified)) { - response.modified = mbgl::Timestamp{ mbgl::Seconds( - static_cast(modified / 1000)) }; + response.modified = mbgl::Timestamp{mbgl::Seconds(static_cast(modified / 1000))}; } } if (Nan::Has(res, Nan::New("expires").ToLocalChecked()).FromJust()) { - const double expires = Nan::To(Nan::Get(res, Nan::New("expires").ToLocalChecked()).ToLocalChecked()).FromJust(); + const double expires = + Nan::To(Nan::Get(res, Nan::New("expires").ToLocalChecked()).ToLocalChecked()).FromJust(); if (!std::isnan(expires)) { - response.expires = mbgl::Timestamp{ mbgl::Seconds( - static_cast(expires / 1000)) }; + response.expires = mbgl::Timestamp{mbgl::Seconds(static_cast(expires / 1000))}; } } if (Nan::Has(res, Nan::New("etag").ToLocalChecked()).FromJust()) { const Nan::Utf8String etag(Nan::Get(res, Nan::New("etag").ToLocalChecked()).ToLocalChecked()); - response.etag = std::string { *etag, size_t(etag.length()) }; + response.etag = std::string{*etag, size_t(etag.length())}; } if (Nan::Has(res, Nan::New("data").ToLocalChecked()).FromJust()) { auto data = Nan::Get(res, Nan::New("data").ToLocalChecked()).ToLocalChecked(); if (node::Buffer::HasInstance(data)) { - response.data = std::make_shared( - node::Buffer::Data(data), - node::Buffer::Length(data) - ); + response.data = std::make_shared(node::Buffer::Data(data), node::Buffer::Length(data)); } else { request->unrefRequest(); return Nan::ThrowTypeError("Response data must be a Buffer"); diff --git a/platform/node/src/node_request.hpp b/platform/node/src/node_request.hpp index 71cccfe9ddb..fa8f8752e0d 100644 --- a/platform/node/src/node_request.hpp +++ b/platform/node/src/node_request.hpp @@ -21,9 +21,7 @@ struct NodeAsyncRequest : public mbgl::AsyncRequest { }; class NodeRequest : public Nan::ObjectWrap { - public: - NodeRequest(mbgl::FileSource::Callback, NodeAsyncRequest*); ~NodeRequest() override; diff --git a/platform/node/src/util/async_queue.hpp b/platform/node/src/util/async_queue.hpp index adf40e3ff5d..d2de95741e0 100644 --- a/platform/node/src/util/async_queue.hpp +++ b/platform/node/src/util/async_queue.hpp @@ -15,9 +15,10 @@ namespace util { template class AsyncQueue { public: - AsyncQueue(uv_loop_t *loop, std::function fn) : callback(std::move(fn)) { + AsyncQueue(uv_loop_t *loop, std::function fn) + : callback(std::move(fn)) { async.data = this; - uv_async_init(loop, &async, [](uv_async_t* handle) { + uv_async_init(loop, &async, [](uv_async_t *handle) { auto q = reinterpret_cast(handle->data); q->process(); }); @@ -41,8 +42,9 @@ class AsyncQueue { } void stop() { - uv_close(reinterpret_cast(&async), - [](uv_handle_t *handle) { delete reinterpret_cast(handle->data); }); + uv_close(reinterpret_cast(&async), [](uv_handle_t *handle) { + delete reinterpret_cast(handle->data); + }); } void ref() { uv_ref(reinterpret_cast(&async)); } diff --git a/platform/qt/app/main.cpp b/platform/qt/app/main.cpp index 134ccddba95..ce19aeb0f1c 100644 --- a/platform/qt/app/main.cpp +++ b/platform/qt/app/main.cpp @@ -2,8 +2,7 @@ #include -int main(int argc, char **argv) -{ +int main(int argc, char **argv) { QApplication app(argc, argv); QMapLibreGL::Settings settings; diff --git a/platform/qt/app/mapwindow.cpp b/platform/qt/app/mapwindow.cpp index 54c457fb577..a0ce1eb49c7 100644 --- a/platform/qt/app/mapwindow.cpp +++ b/platform/qt/app/mapwindow.cpp @@ -12,20 +12,17 @@ int kAnimationDuration = 10000; MapWindow::MapWindow(const QMapLibreGL::Settings &settings) - : m_settings(settings) -{ + : m_settings(settings) { setWindowIcon(QIcon(":icon.png")); } -MapWindow::~MapWindow() -{ +MapWindow::~MapWindow() { // Make sure we have a valid context so we // can delete the QMapLibreGL::Map. makeCurrent(); } -void MapWindow::selfTest() -{ +void MapWindow::selfTest() { if (m_bearingAnimation) { m_bearingAnimation->setDuration(kAnimationDuration); m_bearingAnimation->setEndValue(m_map->bearing() + 360 * 4); @@ -43,25 +40,21 @@ qreal MapWindow::pixelRatio() { return devicePixelRatioF(); } - -void MapWindow::animationFinished() -{ - qDebug() << "Animation ticks/s: " << m_animationTicks / static_cast(kAnimationDuration) * 1000.; - qDebug() << "Frame draws/s: " << m_frameDraws / static_cast(kAnimationDuration) * 1000.; +void MapWindow::animationFinished() { + qDebug() << "Animation ticks/s: " << m_animationTicks / static_cast(kAnimationDuration) * 1000.; + qDebug() << "Frame draws/s: " << m_frameDraws / static_cast(kAnimationDuration) * 1000.; qApp->quit(); } -void MapWindow::animationValueChanged() -{ +void MapWindow::animationValueChanged() { m_animationTicks++; } -void MapWindow::changeStyle() -{ +void MapWindow::changeStyle() { static uint8_t currentStyleIndex; - auto& styles = m_map->defaultStyles(); + auto &styles = m_map->defaultStyles(); m_map->setStyleUrl(styles[currentStyleIndex].first); setWindowTitle(QString("MapLibre GL: ") + styles[currentStyleIndex].second); @@ -73,13 +66,12 @@ void MapWindow::changeStyle() m_sourceAdded = false; } -void MapWindow::keyPressEvent(QKeyEvent *ev) -{ +void MapWindow::keyPressEvent(QKeyEvent *ev) { switch (ev->key()) { - case Qt::Key_S: - changeStyle(); - break; - case Qt::Key_L: { + case Qt::Key_S: + changeStyle(); + break; + case Qt::Key_L: { if (m_sourceAdded) { return; } @@ -246,25 +238,23 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) extrusionBase["property"] = "min_height"; m_map->setPaintProperty("3d-buildings", "fill-extrusion-base", extrusionBase); - } - break; - case Qt::Key_1: { + } break; + case Qt::Key_1: { if (m_symbolAnnotationId.isNull()) { QMapLibreGL::Coordinate coordinate = m_map->coordinate(); - QMapLibreGL::SymbolAnnotation symbol { coordinate, "default_marker" }; + QMapLibreGL::SymbolAnnotation symbol{coordinate, "default_marker"}; m_map->addAnnotationIcon("default_marker", QImage(":default_marker.svg")); m_symbolAnnotationId = m_map->addAnnotation(QVariant::fromValue(symbol)); } else { m_map->removeAnnotation(m_symbolAnnotationId.toUInt()); m_symbolAnnotationId.clear(); } - } - break; - case Qt::Key_2: { + } break; + case Qt::Key_2: { if (m_lineAnnotationId.isNull()) { QMapLibreGL::Coordinates coordinates; - coordinates.push_back(m_map->coordinateForPixel({ 0, 0 })); - coordinates.push_back(m_map->coordinateForPixel({ qreal(size().width()), qreal(size().height()) })); + coordinates.push_back(m_map->coordinateForPixel({0, 0})); + coordinates.push_back(m_map->coordinateForPixel({qreal(size().width()), qreal(size().height())})); QMapLibreGL::CoordinatesCollection collection; collection.push_back(coordinates); @@ -272,7 +262,9 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) QMapLibreGL::CoordinatesCollections lineGeometry; lineGeometry.push_back(collection); - QMapLibreGL::ShapeAnnotationGeometry annotationGeometry(QMapLibreGL::ShapeAnnotationGeometry::LineStringType, lineGeometry); + QMapLibreGL::ShapeAnnotationGeometry annotationGeometry( + QMapLibreGL::ShapeAnnotationGeometry::LineStringType, lineGeometry + ); QMapLibreGL::LineAnnotation line; line.geometry = annotationGeometry; @@ -284,15 +276,14 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) m_map->removeAnnotation(m_lineAnnotationId.toUInt()); m_lineAnnotationId.clear(); } - } - break; - case Qt::Key_3: { + } break; + case Qt::Key_3: { if (m_fillAnnotationId.isNull()) { QMapLibreGL::Coordinates coordinates; - coordinates.push_back(m_map->coordinateForPixel({ qreal(size().width()), 0 })); - coordinates.push_back(m_map->coordinateForPixel({ qreal(size().width()), qreal(size().height()) })); - coordinates.push_back(m_map->coordinateForPixel({ 0, qreal(size().height()) })); - coordinates.push_back(m_map->coordinateForPixel({ 0, 0 })); + coordinates.push_back(m_map->coordinateForPixel({qreal(size().width()), 0})); + coordinates.push_back(m_map->coordinateForPixel({qreal(size().width()), qreal(size().height())})); + coordinates.push_back(m_map->coordinateForPixel({0, qreal(size().height())})); + coordinates.push_back(m_map->coordinateForPixel({0, 0})); QMapLibreGL::CoordinatesCollection collection; collection.push_back(coordinates); @@ -300,7 +291,9 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) QMapLibreGL::CoordinatesCollections fillGeometry; fillGeometry.push_back(collection); - QMapLibreGL::ShapeAnnotationGeometry annotationGeometry(QMapLibreGL::ShapeAnnotationGeometry::PolygonType, fillGeometry); + QMapLibreGL::ShapeAnnotationGeometry annotationGeometry( + QMapLibreGL::ShapeAnnotationGeometry::PolygonType, fillGeometry + ); QMapLibreGL::FillAnnotation fill; fill.geometry = annotationGeometry; @@ -312,9 +305,8 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) m_map->removeAnnotation(m_fillAnnotationId.toUInt()); m_fillAnnotationId.clear(); } - } - break; - case Qt::Key_5: { + } break; + case Qt::Key_5: { if (m_map->layerExists("circleLayer")) { m_map->removeLayer("circleLayer"); m_map->removeSource("circleSource"); @@ -344,53 +336,38 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) m_map->setPaintProperty("circleLayer", "circle-radius", 10.0); m_map->setPaintProperty("circleLayer", "circle-color", QColor("black")); } - } - break; - case Qt::Key_6: { + } break; + case Qt::Key_6: { if (m_map->layerExists("innerCirclesLayer") || m_map->layerExists("outerCirclesLayer")) { m_map->removeLayer("innerCirclesLayer"); m_map->removeLayer("outerCirclesLayer"); m_map->removeSource("innerCirclesSource"); m_map->removeSource("outerCirclesSource"); } else { - auto makePoint = [&] (double dx, double dy, const QString &color) { + auto makePoint = [&](double dx, double dy, const QString &color) { auto coordinate = m_map->coordinate(); coordinate.first += dx; coordinate.second += dy; - return QMapLibreGL::Feature{QMapLibreGL::Feature::PointType, - {{{coordinate}}}, {{"color", color}}, {}}; + return QMapLibreGL::Feature{ + QMapLibreGL::Feature::PointType, {{{coordinate}}}, {{"color", color}}, {}}; }; // multiple features by QVector QVector inner{ - makePoint(0.001, 0, "red"), - makePoint(0, 0.001, "green"), - makePoint(0, -0.001, "blue") - }; + makePoint(0.001, 0, "red"), makePoint(0, 0.001, "green"), makePoint(0, -0.001, "blue")}; - m_map->addSource("innerCirclesSource", - {{"type", "geojson"}, {"data", QVariant::fromValue(inner)}}); - m_map->addLayer({ - {"id", "innerCirclesLayer"}, - {"type", "circle"}, - {"source", "innerCirclesSource"} - }); + m_map->addSource("innerCirclesSource", {{"type", "geojson"}, {"data", QVariant::fromValue(inner)}}); + m_map->addLayer({{"id", "innerCirclesLayer"}, {"type", "circle"}, {"source", "innerCirclesSource"}}); // multiple features by QList QList outer{ - makePoint( 0.002, 0.002, "cyan"), - makePoint(-0.002, 0.002, "magenta"), - makePoint( 0.002, -0.002, "yellow"), - makePoint(-0.002, -0.002, "black") - }; + makePoint(0.002, 0.002, "cyan"), + makePoint(-0.002, 0.002, "magenta"), + makePoint(0.002, -0.002, "yellow"), + makePoint(-0.002, -0.002, "black")}; - m_map->addSource("outerCirclesSource", - {{"type", "geojson"}, {"data", QVariant::fromValue(outer)}}); - m_map->addLayer({ - {"id", "outerCirclesLayer"}, - {"type", "circle"}, - {"source", "outerCirclesSource"} - }); + m_map->addSource("outerCirclesSource", {{"type", "geojson"}, {"data", QVariant::fromValue(outer)}}); + m_map->addLayer({{"id", "outerCirclesLayer"}, {"type", "circle"}, {"source", "outerCirclesSource"}}); QVariantList getColor{"get", "color"}; m_map->setPaintProperty("innerCirclesLayer", "circle-radius", 10.0); @@ -398,17 +375,15 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) m_map->setPaintProperty("outerCirclesLayer", "circle-radius", 15.0); m_map->setPaintProperty("outerCirclesLayer", "circle-color", getColor); } - } - break; - default: - break; + } break; + default: + break; } ev->accept(); } -void MapWindow::mousePressEvent(QMouseEvent *ev) -{ +void MapWindow::mousePressEvent(QMouseEvent *ev) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) m_lastPos = ev->position(); #else @@ -432,8 +407,7 @@ void MapWindow::mousePressEvent(QMouseEvent *ev) ev->accept(); } -void MapWindow::mouseMoveEvent(QMouseEvent *ev) -{ +void MapWindow::mouseMoveEvent(QMouseEvent *ev) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) const QPointF &position = ev->position(); #else @@ -455,8 +429,7 @@ void MapWindow::mouseMoveEvent(QMouseEvent *ev) ev->accept(); } -void MapWindow::wheelEvent(QWheelEvent *ev) -{ +void MapWindow::wheelEvent(QWheelEvent *ev) { if (ev->angleDelta().y() == 0) { return; } @@ -474,8 +447,7 @@ void MapWindow::wheelEvent(QWheelEvent *ev) ev->accept(); } -void MapWindow::initializeGL() -{ +void MapWindow::initializeGL() { m_map.reset(new QMapLibreGL::Map(nullptr, m_settings, size(), pixelRatio())); connect(m_map.get(), SIGNAL(needsRendering()), this, SLOT(update())); @@ -497,8 +469,7 @@ void MapWindow::initializeGL() connect(m_zoomAnimation, &QPropertyAnimation::valueChanged, this, &MapWindow::animationValueChanged); } -void MapWindow::paintGL() -{ +void MapWindow::paintGL() { m_frameDraws++; m_map->resize(size()); m_map->setFramebufferObject(defaultFramebufferObject(), size() * pixelRatio()); diff --git a/platform/qt/app/mapwindow.hpp b/platform/qt/app/mapwindow.hpp index 06b6fb02337..d03483356dd 100644 --- a/platform/qt/app/mapwindow.hpp +++ b/platform/qt/app/mapwindow.hpp @@ -18,8 +18,7 @@ class QWheelEvent; QT_END_NAMESPACE -class MapWindow : public QOpenGLWidget -{ +class MapWindow : public QOpenGLWidget { Q_OBJECT public: diff --git a/platform/qt/include/QMapLibreGL/export.hpp b/platform/qt/include/QMapLibreGL/export.hpp index 9d4b14d3675..4017e5dc442 100644 --- a/platform/qt/include/QMapLibreGL/export.hpp +++ b/platform/qt/include/QMapLibreGL/export.hpp @@ -4,13 +4,13 @@ // This header follows the Qt coding style: https://wiki.qt.io/Qt_Coding_Style #if !defined(QT_MAPLIBREGL_STATIC) -# if defined(QT_BUILD_MAPLIBREGL_LIB) -# define Q_MAPLIBREGL_EXPORT Q_DECL_EXPORT -# else -# define Q_MAPLIBREGL_EXPORT Q_DECL_IMPORT -# endif +#if defined(QT_BUILD_MAPLIBREGL_LIB) +#define Q_MAPLIBREGL_EXPORT Q_DECL_EXPORT #else -# define Q_MAPLIBREGL_EXPORT +#define Q_MAPLIBREGL_EXPORT Q_DECL_IMPORT +#endif +#else +#define Q_MAPLIBREGL_EXPORT #endif #endif // QMAPLIBRE_EXPORT_H diff --git a/platform/qt/include/QMapLibreGL/map.hpp b/platform/qt/include/QMapLibreGL/map.hpp index 4b6450ca60d..1d7d32fc7df 100644 --- a/platform/qt/include/QMapLibreGL/map.hpp +++ b/platform/qt/include/QMapLibreGL/map.hpp @@ -21,8 +21,7 @@ class MapPrivate; // This header follows the Qt coding style: https://wiki.qt.io/Qt_Coding_Style -class Q_MAPLIBREGL_EXPORT Map : public QObject -{ +class Q_MAPLIBREGL_EXPORT Map : public QObject { Q_OBJECT Q_PROPERTY(double latitude READ latitude WRITE setLatitude) Q_PROPERTY(double longitude READ longitude WRITE setLongitude) @@ -70,10 +69,7 @@ class Q_MAPLIBREGL_EXPORT Map : public QObject NorthLeftwards, }; - Map(QObject* parent = 0, - const Settings& = Settings(), - const QSize& size = QSize(), - qreal pixelRatio = 1); + Map(QObject *parent = 0, const Settings & = Settings(), const QSize &size = QSize(), qreal pixelRatio = 1); virtual ~Map(); QString styleJson() const; @@ -112,7 +108,7 @@ class Q_MAPLIBREGL_EXPORT Map : public QObject void setCoordinate(const Coordinate &); void setCoordinateZoom(const Coordinate &, double zoom); - void jumpTo(const CameraOptions&); + void jumpTo(const CameraOptions &); void setGestureInProgress(bool inProgress); @@ -139,26 +135,23 @@ class Q_MAPLIBREGL_EXPORT Map : public QObject Coordinate coordinateForPixel(const QPointF &) const; CoordinateZoom coordinateZoomForBounds(const Coordinate &sw, const Coordinate &ne) const; - CoordinateZoom coordinateZoomForBounds(const Coordinate &sw, - const Coordinate &ne, - double bearing, - double pitch); + CoordinateZoom coordinateZoomForBounds(const Coordinate &sw, const Coordinate &ne, double bearing, double pitch); void setMargins(const QMargins &margins); QMargins margins() const; - void addSource(const QString &sourceID, const QVariantMap& params); + void addSource(const QString &sourceID, const QVariantMap ¶ms); bool sourceExists(const QString &sourceID); - void updateSource(const QString &sourceID, const QVariantMap& params); + void updateSource(const QString &sourceID, const QVariantMap ¶ms); void removeSource(const QString &sourceID); void addImage(const QString &name, const QImage &sprite); void removeImage(const QString &name); - void addCustomLayer(const QString &id, - std::unique_ptr host, - const QString &before = QString()); - void addLayer(const QVariantMap ¶ms, const QString& before = QString()); + void addCustomLayer( + const QString &id, std::unique_ptr host, const QString &before = QString() + ); + void addLayer(const QVariantMap ¶ms, const QString &before = QString()); bool layerExists(const QString &id); void removeLayer(const QString &id); diff --git a/platform/qt/include/QMapLibreGL/settings.hpp b/platform/qt/include/QMapLibreGL/settings.hpp index d814dfc8b70..6ffdde8239f 100644 --- a/platform/qt/include/QMapLibreGL/settings.hpp +++ b/platform/qt/include/QMapLibreGL/settings.hpp @@ -11,16 +11,13 @@ // This header follows the Qt coding style: https://wiki.qt.io/Qt_Coding_Style // TODO: this will be wrapped at some point -namespace mbgl -{ - class TileServerOptions; +namespace mbgl { +class TileServerOptions; } - namespace QMapLibreGL { -class Q_MAPLIBREGL_EXPORT Settings -{ +class Q_MAPLIBREGL_EXPORT Settings { public: Settings(); diff --git a/platform/qt/include/QMapLibreGL/types.hpp b/platform/qt/include/QMapLibreGL/types.hpp index ce601d3182a..598d5f3f1e8 100644 --- a/platform/qt/include/QMapLibreGL/types.hpp +++ b/platform/qt/include/QMapLibreGL/types.hpp @@ -28,9 +28,16 @@ struct Q_MAPLIBREGL_EXPORT Feature { }; /*! Class constructor. */ - Feature(Type type_ = PointType, const CoordinatesCollections& geometry_ = CoordinatesCollections(), - const QVariantMap& properties_ = QVariantMap(), const QVariant& id_ = QVariant()) - : type(type_), geometry(geometry_), properties(properties_), id(id_) {} + Feature( + Type type_ = PointType, + const CoordinatesCollections& geometry_ = CoordinatesCollections(), + const QVariantMap& properties_ = QVariantMap(), + const QVariant& id_ = QVariant() + ) + : type(type_), + geometry(geometry_), + properties(properties_), + id(id_) {} Type type; CoordinatesCollections geometry; @@ -47,8 +54,11 @@ struct Q_MAPLIBREGL_EXPORT ShapeAnnotationGeometry { }; /*! Class constructor. */ - ShapeAnnotationGeometry(Type type_ = LineStringType, const CoordinatesCollections& geometry_ = CoordinatesCollections()) - : type(type_), geometry(geometry_) {} + ShapeAnnotationGeometry( + Type type_ = LineStringType, const CoordinatesCollections& geometry_ = CoordinatesCollections() + ) + : type(type_), + geometry(geometry_) {} Type type; CoordinatesCollections geometry; @@ -61,9 +71,16 @@ struct Q_MAPLIBREGL_EXPORT SymbolAnnotation { struct Q_MAPLIBREGL_EXPORT LineAnnotation { /*! Class constructor. */ - LineAnnotation(const ShapeAnnotationGeometry& geometry_ = ShapeAnnotationGeometry(), float opacity_ = 1.0f, - float width_ = 1.0f, const QColor& color_ = Qt::black) - : geometry(geometry_), opacity(opacity_), width(width_), color(color_) {} + LineAnnotation( + const ShapeAnnotationGeometry& geometry_ = ShapeAnnotationGeometry(), + float opacity_ = 1.0f, + float width_ = 1.0f, + const QColor& color_ = Qt::black + ) + : geometry(geometry_), + opacity(opacity_), + width(width_), + color(color_) {} ShapeAnnotationGeometry geometry; float opacity; @@ -73,9 +90,16 @@ struct Q_MAPLIBREGL_EXPORT LineAnnotation { struct Q_MAPLIBREGL_EXPORT FillAnnotation { /*! Class constructor. */ - FillAnnotation(const ShapeAnnotationGeometry& geometry_ = ShapeAnnotationGeometry(), float opacity_ = 1.0f, - const QColor& color_ = Qt::black, const QVariant& outlineColor_ = QVariant()) - : geometry(geometry_), opacity(opacity_), color(color_), outlineColor(outlineColor_) {} + FillAnnotation( + const ShapeAnnotationGeometry& geometry_ = ShapeAnnotationGeometry(), + float opacity_ = 1.0f, + const QColor& color_ = Qt::black, + const QVariant& outlineColor_ = QVariant() + ) + : geometry(geometry_), + opacity(opacity_), + color(color_), + outlineColor(outlineColor_) {} ShapeAnnotationGeometry geometry; float opacity; diff --git a/platform/qt/src/map.cpp b/platform/qt/src/map.cpp index b0ababa80b1..cccf72415ed 100644 --- a/platform/qt/src/map.cpp +++ b/platform/qt/src/map.cpp @@ -63,37 +63,47 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4805) +#pragma warning(disable : 4805) #endif // mbgl::NorthOrientation -static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthUpwards) == mbgl::underlying_type(mbgl::NorthOrientation::Upwards), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthRightwards) == mbgl::underlying_type(mbgl::NorthOrientation::Rightwards), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthDownwards) == mbgl::underlying_type(mbgl::NorthOrientation::Downwards), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthLeftwards) == mbgl::underlying_type(mbgl::NorthOrientation::Leftwards), "error"); +static_assert( + mbgl::underlying_type(QMapLibreGL::Map::NorthUpwards) == mbgl::underlying_type(mbgl::NorthOrientation::Upwards), + "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Map::NorthRightwards) == + mbgl::underlying_type(mbgl::NorthOrientation::Rightwards), + "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Map::NorthDownwards) == mbgl::underlying_type(mbgl::NorthOrientation::Downwards), + "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Map::NorthLeftwards) == mbgl::underlying_type(mbgl::NorthOrientation::Leftwards), + "error" +); #ifdef _MSC_VER #pragma warning(pop) #endif - namespace { QThreadStorage> loop; // Conversion helper functions. -mbgl::Size sanitizedSize(const QSize& size) { - return mbgl::Size { +mbgl::Size sanitizedSize(const QSize &size) { + return mbgl::Size{ mbgl::util::max(0u, static_cast(size.width())), mbgl::util::max(0u, static_cast(size.height())), }; }; std::unique_ptr toStyleImage(const QString &id, const QImage &sprite) { - const QImage swapped = sprite - .rgbSwapped() - .convertToFormat(QImage::Format_ARGB32_Premultiplied); + const QImage swapped = sprite.rgbSwapped().convertToFormat(QImage::Format_ARGB32_Premultiplied); #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) auto img = std::make_unique(swapped.sizeInBytes()); @@ -106,72 +116,78 @@ std::unique_ptr toStyleImage(const QString &id, const QImage return std::make_unique( id.toStdString(), mbgl::PremultipliedImage( - { static_cast(swapped.width()), static_cast(swapped.height()) }, - std::move(img)), - 1.0); + {static_cast(swapped.width()), static_cast(swapped.height())}, std::move(img) + ), + 1.0 + ); } mbgl::MapOptions mapOptionsFromSettings(const QMapLibreGL::Settings &settings, const QSize &size, qreal pixelRatio) { return std::move(mbgl::MapOptions() - .withSize(sanitizedSize(size)) - .withPixelRatio(pixelRatio) - .withMapMode(static_cast(settings.mapMode())) - .withConstrainMode(static_cast(settings.constrainMode())) - .withViewportMode(static_cast(settings.viewportMode()))); + .withSize(sanitizedSize(size)) + .withPixelRatio(pixelRatio) + .withMapMode(static_cast(settings.mapMode())) + .withConstrainMode(static_cast(settings.constrainMode())) + .withViewportMode(static_cast(settings.viewportMode()))); } mbgl::ResourceOptions resourceOptionsFromSettings(const QMapLibreGL::Settings &settings) { return std::move(mbgl::ResourceOptions() - .withApiKey(settings.apiKey().toStdString()) - .withAssetPath(settings.assetPath().toStdString()) - .withTileServerOptions(*settings.tileServerOptionsInternal()) - .withCachePath(settings.cacheDatabasePath().toStdString()) - .withMaximumCacheSize(settings.cacheDatabaseMaximumSize())); + .withApiKey(settings.apiKey().toStdString()) + .withAssetPath(settings.assetPath().toStdString()) + .withTileServerOptions(*settings.tileServerOptionsInternal()) + .withCachePath(settings.cacheDatabasePath().toStdString()) + .withMaximumCacheSize(settings.cacheDatabaseMaximumSize())); } mbgl::ClientOptions clientOptionsFromSettings(const QMapLibreGL::Settings &settings) { return std::move(mbgl::ClientOptions() - .withName(settings.clientName().toStdString()) - .withVersion(settings.clientVersion().toStdString())); + .withName(settings.clientName().toStdString()) + .withVersion(settings.clientVersion().toStdString())); } - -std::optional asAnnotation(const QMapLibreGL::Annotation & annotation) { +std::optional asAnnotation(const QMapLibreGL::Annotation &annotation) { auto asGeometry = [](const QMapLibreGL::ShapeAnnotationGeometry &geometry) { mbgl::ShapeAnnotationGeometry result; switch (geometry.type) { - case QMapLibreGL::ShapeAnnotationGeometry::LineStringType: - result = QMapLibreGL::GeoJSON::asLineString(geometry.geometry.first().first()); - break; - case QMapLibreGL::ShapeAnnotationGeometry::PolygonType: - result = QMapLibreGL::GeoJSON::asPolygon(geometry.geometry.first()); - break; - case QMapLibreGL::ShapeAnnotationGeometry::MultiLineStringType: - result = QMapLibreGL::GeoJSON::asMultiLineString(geometry.geometry.first()); - break; - case QMapLibreGL::ShapeAnnotationGeometry::MultiPolygonType: - result = QMapLibreGL::GeoJSON::asMultiPolygon(geometry.geometry); - break; + case QMapLibreGL::ShapeAnnotationGeometry::LineStringType: + result = QMapLibreGL::GeoJSON::asLineString(geometry.geometry.first().first()); + break; + case QMapLibreGL::ShapeAnnotationGeometry::PolygonType: + result = QMapLibreGL::GeoJSON::asPolygon(geometry.geometry.first()); + break; + case QMapLibreGL::ShapeAnnotationGeometry::MultiLineStringType: + result = QMapLibreGL::GeoJSON::asMultiLineString(geometry.geometry.first()); + break; + case QMapLibreGL::ShapeAnnotationGeometry::MultiPolygonType: + result = QMapLibreGL::GeoJSON::asMultiPolygon(geometry.geometry); + break; } return result; }; if (annotation.canConvert()) { QMapLibreGL::SymbolAnnotation symbolAnnotation = annotation.value(); - QMapLibreGL::Coordinate& pair = symbolAnnotation.geometry; - return { mbgl::SymbolAnnotation(mbgl::Point { pair.second, pair.first }, symbolAnnotation.icon.toStdString()) }; + QMapLibreGL::Coordinate &pair = symbolAnnotation.geometry; + return { + mbgl::SymbolAnnotation(mbgl::Point{pair.second, pair.first}, symbolAnnotation.icon.toStdString())}; } else if (annotation.canConvert()) { QMapLibreGL::LineAnnotation lineAnnotation = annotation.value(); auto color = mbgl::Color::parse(mbgl::style::conversion::convertColor(lineAnnotation.color)); - return { mbgl::LineAnnotation(asGeometry(lineAnnotation.geometry), lineAnnotation.opacity, lineAnnotation.width, { *color }) }; + return {mbgl::LineAnnotation( + asGeometry(lineAnnotation.geometry), lineAnnotation.opacity, lineAnnotation.width, {*color} + )}; } else if (annotation.canConvert()) { QMapLibreGL::FillAnnotation fillAnnotation = annotation.value(); auto color = mbgl::Color::parse(mbgl::style::conversion::convertColor(fillAnnotation.color)); if (fillAnnotation.outlineColor.canConvert()) { - auto outlineColor = mbgl::Color::parse(mbgl::style::conversion::convertColor(fillAnnotation.outlineColor.value())); - return { mbgl::FillAnnotation(asGeometry(fillAnnotation.geometry), fillAnnotation.opacity, { *color }, { *outlineColor }) }; + auto outlineColor = + mbgl::Color::parse(mbgl::style::conversion::convertColor(fillAnnotation.outlineColor.value())); + return {mbgl::FillAnnotation( + asGeometry(fillAnnotation.geometry), fillAnnotation.opacity, {*color}, {*outlineColor} + )}; } else { - return { mbgl::FillAnnotation(asGeometry(fillAnnotation.geometry), fillAnnotation.opacity, { *color }, {}) }; + return {mbgl::FillAnnotation(asGeometry(fillAnnotation.geometry), fillAnnotation.opacity, {*color}, {})}; } } @@ -181,7 +197,6 @@ std::optional asAnnotation(const QMapLibreGL::Annotation & ann } // namespace - namespace QMapLibreGL { /*! @@ -286,9 +301,8 @@ namespace QMapLibreGL { \a size represents the size of the viewport and the \a pixelRatio the initial pixel density of the screen. */ -Map::Map(QObject *parent_, const Settings &settings, const QSize& size, qreal pixelRatio) - : QObject(parent_) -{ +Map::Map(QObject *parent_, const Settings &settings, const QSize &size, qreal pixelRatio) + : QObject(parent_) { assert(!size.isEmpty()); // Multiple QMapLibreGL::Map running on the same thread @@ -303,8 +317,7 @@ Map::Map(QObject *parent_, const Settings &settings, const QSize& size, qreal pi /*! Destroys this QMapLibreGL::Map. */ -Map::~Map() -{ +Map::~Map() { delete d_ptr; } @@ -319,13 +332,11 @@ Map::~Map() \note In case of a invalid style it will trigger a mapChanged signal with QMapLibreGL::Map::MapChangeDidFailLoadingMap as argument. */ -QString Map::styleJson() const -{ +QString Map::styleJson() const { return QString::fromStdString(d_ptr->mapObj->getStyle().getJSON()); } -void Map::setStyleJson(const QString &style) -{ +void Map::setStyleJson(const QString &style) { d_ptr->mapObj->getStyle().loadJSON(style.toStdString()); } @@ -344,13 +355,11 @@ void Map::setStyleJson(const QString &style) \note In case of a invalid style it will trigger a mapChanged signal with QMapLibreGL::Map::MapChangeDidFailLoadingMap as argument. */ -QString Map::styleUrl() const -{ +QString Map::styleUrl() const { return QString::fromStdString(d_ptr->mapObj->getStyle().getURL()); } -void Map::setStyleUrl(const QString &url) -{ +void Map::setStyleUrl(const QString &url) { d_ptr->mapObj->getStyle().loadURL(url.toStdString()); } @@ -361,14 +370,14 @@ void Map::setStyleUrl(const QString &url) Setting a latitude doesn't necessarily mean it will be accepted since QMapLibreGL::Map might constrain it within the limits of the Web Mercator projection. */ -double Map::latitude() const -{ +double Map::latitude() const { return d_ptr->mapObj->getCameraOptions(d_ptr->margins).center->latitude(); } -void Map::setLatitude(double latitude_) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng { latitude_, longitude() }).withPadding(d_ptr->margins)); +void Map::setLatitude(double latitude_) { + d_ptr->mapObj->jumpTo( + mbgl::CameraOptions().withCenter(mbgl::LatLng{latitude_, longitude()}).withPadding(d_ptr->margins) + ); } /*! @@ -379,14 +388,14 @@ void Map::setLatitude(double latitude_) the map wrap. As an example, setting the longitude to 360 is effectively the same as setting it to 0. */ -double Map::longitude() const -{ +double Map::longitude() const { return d_ptr->mapObj->getCameraOptions(d_ptr->margins).center->longitude(); } -void Map::setLongitude(double longitude_) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng { latitude(), longitude_ }).withPadding(d_ptr->margins)); +void Map::setLongitude(double longitude_) { + d_ptr->mapObj->jumpTo( + mbgl::CameraOptions().withCenter(mbgl::LatLng{latitude(), longitude_}).withPadding(d_ptr->margins) + ); } /*! @@ -402,14 +411,14 @@ void Map::setLongitude(double longitude_) \sa zoom() */ -double Map::scale() const -{ +double Map::scale() const { return std::pow(2.0, zoom()); } -void Map::setScale(double scale_, const QPointF ¢er) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withZoom(::log2(scale_)).withAnchor(mbgl::ScreenCoordinate { center.x(), center.y() })); +void Map::setScale(double scale_, const QPointF ¢er) { + d_ptr->mapObj->jumpTo( + mbgl::CameraOptions().withZoom(::log2(scale_)).withAnchor(mbgl::ScreenCoordinate{center.x(), center.y()}) + ); } /*! @@ -422,13 +431,11 @@ void Map::setScale(double scale_, const QPointF ¢er) \sa scale() */ -double Map::zoom() const -{ +double Map::zoom() const { return *d_ptr->mapObj->getCameraOptions().zoom; } -void Map::setZoom(double zoom_) -{ +void Map::setZoom(double zoom_) { d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withZoom(zoom_).withPadding(d_ptr->margins)); } @@ -437,8 +444,7 @@ void Map::setZoom(double zoom_) \sa maximumZoom() */ -double Map::minimumZoom() const -{ +double Map::minimumZoom() const { return *d_ptr->mapObj->getBounds().minZoom; } @@ -447,8 +453,7 @@ double Map::minimumZoom() const \sa minimumZoom() */ -double Map::maximumZoom() const -{ +double Map::maximumZoom() const { return *d_ptr->mapObj->getBounds().maxZoom; } @@ -460,16 +465,14 @@ double Map::maximumZoom() const \sa margins() */ -Coordinate Map::coordinate() const -{ +Coordinate Map::coordinate() const { const mbgl::LatLng latLng = *d_ptr->mapObj->getCameraOptions(d_ptr->margins).center; return Coordinate(latLng.latitude(), latLng.longitude()); } -void Map::setCoordinate(const Coordinate &coordinate_) -{ +void Map::setCoordinate(const Coordinate &coordinate_) { d_ptr->mapObj->jumpTo(mbgl::CameraOptions() - .withCenter(mbgl::LatLng { coordinate_.first, coordinate_.second }) + .withCenter(mbgl::LatLng{coordinate_.first, coordinate_.second}) .withPadding(d_ptr->margins)); } @@ -484,10 +487,9 @@ void Map::setCoordinate(const Coordinate &coordinate_) \sa zoom() \sa coordinate() */ -void Map::setCoordinateZoom(const Coordinate &coordinate_, double zoom_) -{ +void Map::setCoordinateZoom(const Coordinate &coordinate_, double zoom_) { d_ptr->mapObj->jumpTo(mbgl::CameraOptions() - .withCenter(mbgl::LatLng { coordinate_.first, coordinate_.second }) + .withCenter(mbgl::LatLng{coordinate_.first, coordinate_.second}) .withZoom(zoom_) .withPadding(d_ptr->margins)); } @@ -495,16 +497,15 @@ void Map::setCoordinateZoom(const Coordinate &coordinate_, double zoom_) /*! Atomically jumps to the \a camera options. */ -void Map::jumpTo(const CameraOptions& camera) -{ +void Map::jumpTo(const CameraOptions &camera) { mbgl::CameraOptions mbglCamera; if (camera.center.isValid()) { const Coordinate center = camera.center.value(); - mbglCamera.center = mbgl::LatLng { center.first, center.second }; + mbglCamera.center = mbgl::LatLng{center.first, center.second}; } if (camera.anchor.isValid()) { const QPointF anchor = camera.anchor.value(); - mbglCamera.anchor = mbgl::ScreenCoordinate { anchor.x(), anchor.y() }; + mbglCamera.anchor = mbgl::ScreenCoordinate{anchor.x(), anchor.y()}; } if (camera.zoom.isValid()) { mbglCamera.zoom = camera.zoom.value(); @@ -533,23 +534,17 @@ void Map::jumpTo(const CameraOptions& camera) \sa margins() */ -double Map::bearing() const -{ +double Map::bearing() const { return *d_ptr->mapObj->getCameraOptions().bearing; } -void Map::setBearing(double degrees) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions() - .withBearing(degrees) - .withPadding(d_ptr->margins)); +void Map::setBearing(double degrees) { + d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withBearing(degrees).withPadding(d_ptr->margins)); } -void Map::setBearing(double degrees, const QPointF ¢er) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions() - .withBearing(degrees) - .withAnchor(mbgl::ScreenCoordinate { center.x(), center.y() })); +void Map::setBearing(double degrees, const QPointF ¢er) { + d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withBearing(degrees).withAnchor(mbgl::ScreenCoordinate{ + center.x(), center.y()})); } /*! @@ -561,34 +556,29 @@ void Map::setBearing(double degrees, const QPointF ¢er) \sa margins() */ -double Map::pitch() const -{ +double Map::pitch() const { return *d_ptr->mapObj->getCameraOptions().pitch; } -void Map::setPitch(double pitch_) -{ +void Map::setPitch(double pitch_) { d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withPitch(pitch_)); } -void Map::pitchBy(double pitch_) -{ +void Map::pitchBy(double pitch_) { d_ptr->mapObj->pitchBy(pitch_); } /*! Returns the north orientation mode. */ -Map::NorthOrientation Map::northOrientation() const -{ +Map::NorthOrientation Map::northOrientation() const { return static_cast(d_ptr->mapObj->getMapOptions().northOrientation()); } /*! Sets the north orientation mode to \a orientation. */ -void Map::setNorthOrientation(NorthOrientation orientation) -{ +void Map::setNorthOrientation(NorthOrientation orientation) { d_ptr->mapObj->setNorthOrientation(static_cast(orientation)); } @@ -597,8 +587,7 @@ void Map::setNorthOrientation(NorthOrientation orientation) affects how the map renders labels, as it will use different texture filters if a gesture is ongoing. */ -void Map::setGestureInProgress(bool progress) -{ +void Map::setGestureInProgress(bool progress) { d_ptr->mapObj->setGestureInProgress(progress); } @@ -611,7 +600,7 @@ void Map::setTransitionOptions(qint64 duration, qint64 delay) { return std::chrono::duration_cast(mbgl::Milliseconds(value)); }; - d_ptr->mapObj->getStyle().setTransitionOptions(mbgl::style::TransitionOptions{ convert(duration), convert(delay) }); + d_ptr->mapObj->getStyle().setTransitionOptions(mbgl::style::TransitionOptions{convert(duration), convert(delay)}); } /*! @@ -621,8 +610,7 @@ void Map::setTransitionOptions(qint64 duration, qint64 delay) { \sa addAnnotationIcon() */ -AnnotationID Map::addAnnotation(const Annotation &annotation) -{ +AnnotationID Map::addAnnotation(const Annotation &annotation) { return static_cast(d_ptr->mapObj->addAnnotation(*asAnnotation(annotation))); } @@ -631,16 +619,14 @@ AnnotationID Map::addAnnotation(const Annotation &annotation) \sa addAnnotationIcon() */ -void Map::updateAnnotation(AnnotationID id, const Annotation &annotation) -{ +void Map::updateAnnotation(AnnotationID id, const Annotation &annotation) { d_ptr->mapObj->updateAnnotation(id, *asAnnotation(annotation)); } /*! Removes an existing annotation referred by \a id. */ -void Map::removeAnnotation(AnnotationID id) -{ +void Map::removeAnnotation(AnnotationID id) { d_ptr->mapObj->removeAnnotation(id); } @@ -683,8 +669,7 @@ void Map::removeAnnotation(AnnotationID id) \li QVariantList \endtable */ -bool Map::setLayoutProperty(const QString& layer, const QString& propertyName, const QVariant& value) -{ +bool Map::setLayoutProperty(const QString &layer, const QString &propertyName, const QVariant &value) { return d_ptr->setProperty(&mbgl::style::Layer::setProperty, layer, propertyName, value); } @@ -743,8 +728,7 @@ bool Map::setLayoutProperty(const QString& layer, const QString& propertyName, c \endcode */ -bool Map::setPaintProperty(const QString& layer, const QString& propertyName, const QVariant& value) -{ +bool Map::setPaintProperty(const QString &layer, const QString &propertyName, const QVariant &value) { return d_ptr->setProperty(&mbgl::style::Layer::setProperty, layer, propertyName, value); } @@ -752,8 +736,7 @@ bool Map::setPaintProperty(const QString& layer, const QString& propertyName, co Returns true when the map is completely rendered, false otherwise. A partially rendered map ranges from nothing rendered at all to only labels missing. */ -bool Map::isFullyLoaded() const -{ +bool Map::isFullyLoaded() const { return d_ptr->mapObj->isFullyLoaded(); } @@ -762,9 +745,8 @@ bool Map::isFullyLoaded() const The pixel coordinate origin is located at the upper left corner of the map. */ -void Map::moveBy(const QPointF &offset) -{ - d_ptr->mapObj->moveBy(mbgl::ScreenCoordinate { offset.x(), offset.y() }); +void Map::moveBy(const QPointF &offset) { + d_ptr->mapObj->moveBy(mbgl::ScreenCoordinate{offset.x(), offset.y()}); } /*! @@ -774,7 +756,7 @@ void Map::moveBy(const QPointF &offset) can be used for implementing a pinch gesture. */ void Map::scaleBy(double scale_, const QPointF ¢er) { - d_ptr->mapObj->scaleBy(scale_, mbgl::ScreenCoordinate { center.x(), center.y() }); + d_ptr->mapObj->scaleBy(scale_, mbgl::ScreenCoordinate{center.x(), center.y()}); } /*! @@ -783,23 +765,20 @@ void Map::scaleBy(double scale_, const QPointF ¢er) { being \a first the cursor coordinate at the last frame and \a second the cursor coordinate at the current frame. */ -void Map::rotateBy(const QPointF &first, const QPointF &second) -{ +void Map::rotateBy(const QPointF &first, const QPointF &second) { d_ptr->mapObj->rotateBy( - mbgl::ScreenCoordinate { first.x(), first.y() }, - mbgl::ScreenCoordinate { second.x(), second.y() }); + mbgl::ScreenCoordinate{first.x(), first.y()}, mbgl::ScreenCoordinate{second.x(), second.y()} + ); } /*! Resize the map to \a size_ and scale to fit at the framebuffer. For high DPI screens, the size will be smaller than the framebuffer. */ -void Map::resize(const QSize& size_) -{ +void Map::resize(const QSize &size_) { auto size = sanitizedSize(size_); - if (d_ptr->mapObj->getMapOptions().size() == size) - return; + if (d_ptr->mapObj->getMapOptions().size() == size) return; d_ptr->mapObj->setSize(size); } @@ -813,8 +792,7 @@ void Map::resize(const QSize& size_) \sa addAnnotation() */ -void Map::addAnnotationIcon(const QString &name, const QImage &icon) -{ +void Map::addAnnotationIcon(const QString &name, const QImage &icon) { if (icon.isNull()) return; d_ptr->mapObj->addAnnotationImage(toStyleImage(name, icon)); @@ -831,10 +809,9 @@ void Map::addAnnotationIcon(const QString &name, const QImage &icon) /note The return value is affected by the current zoom level, bearing and pitch. */ -QPointF Map::pixelForCoordinate(const Coordinate &coordinate_) const -{ - const mbgl::ScreenCoordinate pixel = - d_ptr->mapObj->pixelForLatLng(mbgl::LatLng { coordinate_.first, coordinate_.second }); +QPointF Map::pixelForCoordinate(const Coordinate &coordinate_) const { + const mbgl::ScreenCoordinate pixel = d_ptr->mapObj->pixelForLatLng(mbgl::LatLng{ + coordinate_.first, coordinate_.second}); return QPointF(pixel.x, pixel.y); } @@ -842,10 +819,8 @@ QPointF Map::pixelForCoordinate(const Coordinate &coordinate_) const /*! Returns the geographic coordinate for the \a pixel coordinate. */ -Coordinate Map::coordinateForPixel(const QPointF &pixel) const -{ - const mbgl::LatLng latLng = - d_ptr->mapObj->latLngForPixel(mbgl::ScreenCoordinate { pixel.x(), pixel.y() }); +Coordinate Map::coordinateForPixel(const QPointF &pixel) const { + const mbgl::LatLng latLng = d_ptr->mapObj->latLngForPixel(mbgl::ScreenCoordinate{pixel.x(), pixel.y()}); return Coordinate(latLng.latitude(), latLng.longitude()); } @@ -854,27 +829,25 @@ Coordinate Map::coordinateForPixel(const QPointF &pixel) const Returns the coordinate and zoom combination needed in order to make the coordinate bounding box \a sw and \a ne visible. */ -CoordinateZoom Map::coordinateZoomForBounds(const Coordinate &sw, - const Coordinate &ne) const { - auto bounds = mbgl::LatLngBounds::hull(mbgl::LatLng { sw.first, sw.second }, mbgl::LatLng { ne.first, ne.second }); +CoordinateZoom Map::coordinateZoomForBounds(const Coordinate &sw, const Coordinate &ne) const { + auto bounds = mbgl::LatLngBounds::hull(mbgl::LatLng{sw.first, sw.second}, mbgl::LatLng{ne.first, ne.second}); mbgl::CameraOptions camera = d_ptr->mapObj->cameraForLatLngBounds(bounds, d_ptr->margins); - return {{ (*camera.center).latitude(), (*camera.center).longitude() }, *camera.zoom }; + return {{(*camera.center).latitude(), (*camera.center).longitude()}, *camera.zoom}; } /*! Returns the coordinate and zoom combination needed in order to make the coordinate bounding box \a sw and \a ne visible taking into account \a newBearing and \a newPitch. */ -CoordinateZoom Map::coordinateZoomForBounds(const Coordinate &sw, - const Coordinate &ne, - double newBearing, - double newPitch) +CoordinateZoom Map::coordinateZoomForBounds( + const Coordinate &sw, const Coordinate &ne, double newBearing, double newPitch +) { - auto bounds = mbgl::LatLngBounds::hull(mbgl::LatLng { sw.first, sw.second }, mbgl::LatLng { ne.first, ne.second }); + auto bounds = mbgl::LatLngBounds::hull(mbgl::LatLng{sw.first, sw.second}, mbgl::LatLng{ne.first, ne.second}); mbgl::CameraOptions camera = d_ptr->mapObj->cameraForLatLngBounds(bounds, d_ptr->margins, newBearing, newPitch); - return {{ (*camera.center).latitude(), (*camera.center).longitude() }, *camera.zoom }; + return {{(*camera.center).latitude(), (*camera.center).longitude()}, *camera.zoom}; } /*! @@ -883,24 +856,16 @@ CoordinateZoom Map::coordinateZoomForBounds(const Coordinate &sw, This property sets a new reference center for the map. */ -void Map::setMargins(const QMargins &margins_) -{ +void Map::setMargins(const QMargins &margins_) { d_ptr->margins = { static_cast(margins_.top()), static_cast(margins_.left()), static_cast(margins_.bottom()), - static_cast(margins_.right()) - }; + static_cast(margins_.right())}; } -QMargins Map::margins() const -{ - return QMargins( - d_ptr->margins.left(), - d_ptr->margins.top(), - d_ptr->margins.right(), - d_ptr->margins.bottom() - ); +QMargins Map::margins() const { + return QMargins(d_ptr->margins.left(), d_ptr->margins.top(), d_ptr->margins.right(), d_ptr->margins.bottom()); } /*! @@ -921,13 +886,14 @@ QMargins Map::margins() const map->addSource("routeSource", routeSource); \endcode */ -void Map::addSource(const QString &id, const QVariantMap ¶ms) -{ +void Map::addSource(const QString &id, const QVariantMap ¶ms) { using namespace mbgl::style; using namespace mbgl::style::conversion; Error error; - std::optional> source = convert>(QVariant(params), error, id.toStdString()); + std::optional> source = convert>( + QVariant(params), error, id.toStdString() + ); if (!source) { qWarning() << "Unable to add source:" << error.message.c_str(); return; @@ -939,8 +905,7 @@ void Map::addSource(const QString &id, const QVariantMap ¶ms) /*! Returns true if the layer with given \a sourceID exists, false otherwise. */ -bool Map::sourceExists(const QString& sourceID) -{ +bool Map::sourceExists(const QString &sourceID) { return !!d_ptr->mapObj->getStyle().getSource(sourceID.toStdString()); } @@ -950,8 +915,7 @@ bool Map::sourceExists(const QString& sourceID) If the source does not exist, it will be added like in addSource(). Only image and GeoJSON sources can be updated. */ -void Map::updateSource(const QString &id, const QVariantMap ¶ms) -{ +void Map::updateSource(const QString &id, const QVariantMap ¶ms) { using namespace mbgl::style; using namespace mbgl::style::conversion; @@ -984,8 +948,7 @@ void Map::updateSource(const QString &id, const QVariantMap ¶ms) This method has no effect if the source does not exist. */ -void Map::removeSource(const QString& id) -{ +void Map::removeSource(const QString &id) { auto sourceIDStdString = id.toStdString(); if (d_ptr->mapObj->getStyle().getSource(sourceIDStdString)) { @@ -1001,22 +964,16 @@ void Map::removeSource(const QString& id) \warning This is used for delegating the rendering of a layer to the user of this API and is not officially supported. Use at your own risk. */ -void Map::addCustomLayer(const QString &id, - std::unique_ptr host, - const QString &before) -{ +void Map::addCustomLayer(const QString &id, std::unique_ptr host, const QString &before) { class HostWrapper : public mbgl::style::CustomLayerHost { - public: + public: std::unique_ptr ptr{}; HostWrapper(std::unique_ptr p) - : ptr(std::move(p)) { - } + : ptr(std::move(p)) {} - void initialize() { - ptr->initialize(); - } + void initialize() { ptr->initialize(); } - void render(const mbgl::style::CustomLayerRenderParameters& params) { + void render(const mbgl::style::CustomLayerRenderParameters ¶ms) { CustomLayerRenderParameters renderParams; renderParams.width = params.width; renderParams.height = params.height; @@ -1029,17 +986,15 @@ void Map::addCustomLayer(const QString &id, ptr->render(renderParams); } - void contextLost() { } + void contextLost() {} - void deinitialize() { - ptr->deinitialize(); - } + void deinitialize() { ptr->deinitialize(); } }; - d_ptr->mapObj->getStyle().addLayer(std::make_unique( - id.toStdString(), - std::make_unique(std::move(host))), - before.isEmpty() ? std::optional() : std::optional(before.toStdString())); + d_ptr->mapObj->getStyle().addLayer( + std::make_unique(id.toStdString(), std::make_unique(std::move(host))), + before.isEmpty() ? std::optional() : std::optional(before.toStdString()) + ); } /*! @@ -1062,8 +1017,7 @@ void Map::addCustomLayer(const QString &id, /note The source must exist prior to adding a layer. */ -void Map::addLayer(const QVariantMap ¶ms, const QString& before) -{ +void Map::addLayer(const QVariantMap ¶ms, const QString &before) { using namespace mbgl::style; using namespace mbgl::style::conversion; @@ -1074,31 +1028,30 @@ void Map::addLayer(const QVariantMap ¶ms, const QString& before) return; } - d_ptr->mapObj->getStyle().addLayer(std::move(*layer), - before.isEmpty() ? std::optional() : std::optional(before.toStdString())); + d_ptr->mapObj->getStyle().addLayer( + std::move(*layer), + before.isEmpty() ? std::optional() : std::optional(before.toStdString()) + ); } /*! Returns true if the layer with given \a id exists, false otherwise. */ -bool Map::layerExists(const QString& id) -{ +bool Map::layerExists(const QString &id) { return !!d_ptr->mapObj->getStyle().getLayer(id.toStdString()); } /*! Removes the layer with given \a id. */ -void Map::removeLayer(const QString& id) -{ +void Map::removeLayer(const QString &id) { d_ptr->mapObj->getStyle().removeLayer(id.toStdString()); } /*! List of all existing layer ids from the current style. */ -QVector Map::layerIds() const -{ +QVector Map::layerIds() const { const auto &layers = d_ptr->mapObj->getStyle().getLayers(); QVector layerIds; @@ -1121,8 +1074,7 @@ QVector Map::layerIds() const \sa addLayer() */ -void Map::addImage(const QString &id, const QImage &image) -{ +void Map::addImage(const QString &id, const QImage &image) { if (image.isNull()) return; d_ptr->mapObj->getStyle().addImage(toStyleImage(id, image)); @@ -1131,8 +1083,7 @@ void Map::addImage(const QString &id, const QImage &image) /*! Removes the image \a id. */ -void Map::removeImage(const QString &id) -{ +void Map::removeImage(const QString &id) { d_ptr->mapObj->getStyle().removeImage(id.toStdString()); } @@ -1156,12 +1107,11 @@ void Map::removeImage(const QString &id) map->setFilter(QLatin1String("marker"), filter); \endcode */ -void Map::setFilter(const QString& layer, const QVariant& filter) -{ +void Map::setFilter(const QString &layer, const QVariant &filter) { using namespace mbgl::style; using namespace mbgl::style::conversion; - Layer* layer_ = d_ptr->mapObj->getStyle().getLayer(layer.toStdString()); + Layer *layer_ = d_ptr->mapObj->getStyle().getLayer(layer.toStdString()); if (!layer_) { qWarning() << "Layer not found:" << layer; return; @@ -1179,49 +1129,44 @@ void Map::setFilter(const QString& layer, const QVariant& filter) QVariant QVariantFromValue(const mbgl::Value &value) { return value.match( - [](const mbgl::NullValue) { - return QVariant(); - }, [](const bool value_) { - return QVariant(value_); - }, [](const float value_) { - return QVariant(value_); - }, [](const int64_t value_) { - return QVariant(static_cast(value_)); - }, [](const double value_) { - return QVariant(value_); - }, [](const std::string &value_) { - return QVariant(value_.c_str()); - }, [](const mbgl::Color &value_) { - return QColor(value_.r, value_.g, value_.b, value_.a); - }, [&](const std::vector &vector) { + [](const mbgl::NullValue) { return QVariant(); }, + [](const bool value_) { return QVariant(value_); }, + [](const float value_) { return QVariant(value_); }, + [](const int64_t value_) { return QVariant(static_cast(value_)); }, + [](const double value_) { return QVariant(value_); }, + [](const std::string &value_) { return QVariant(value_.c_str()); }, + [](const mbgl::Color &value_) { return QColor(value_.r, value_.g, value_.b, value_.a); }, + [&](const std::vector &vector) { QVariantList list; list.reserve(static_cast(vector.size())); for (const auto &value_ : vector) { list.push_back(QVariantFromValue(value_)); } return list; - }, [&](const std::unordered_map &map) { + }, + [&](const std::unordered_map &map) { QVariantMap varMap; for (auto &item : map) { varMap.insert(item.first.c_str(), QVariantFromValue(item.second)); } return varMap; - }, [](const auto &) { - return QVariant(); - }); + }, + [](const auto &) { return QVariant(); } + ); } /*! Returns the current \a expression-based filter value applied to a style \layer, if any. - Filter value types are described in the {https://maplibre.org/maplibre-gl-js-docs/style-spec/#types}{Mapbox style specification}. + Filter value types are described in the {https://maplibre.org/maplibre-gl-js-docs/style-spec/#types}{Mapbox style + specification}. */ -QVariant Map::getFilter(const QString &layer) const { +QVariant Map::getFilter(const QString &layer) const { using namespace mbgl::style; using namespace mbgl::style::conversion; - Layer* layer_ = d_ptr->mapObj->getStyle().getLayer(layer.toStdString()); + Layer *layer_ = d_ptr->mapObj->getStyle().getLayer(layer.toStdString()); if (!layer_) { qWarning() << "Layer not found:" << layer; return QVariant(); @@ -1237,8 +1182,7 @@ QVariant Map::getFilter(const QString &layer) const { Must be called on the render thread. */ -void Map::createRenderer() -{ +void Map::createRenderer() { d_ptr->createRenderer(); } @@ -1248,8 +1192,7 @@ void Map::createRenderer() Must be called on the render thread. */ -void Map::destroyRenderer() -{ +void Map::destroyRenderer() { d_ptr->destroyRenderer(); } @@ -1259,8 +1202,7 @@ void Map::destroyRenderer() \sa QMapLibreGL::Settings::MapMode */ -void Map::startStaticRender() -{ +void Map::startStaticRender() { d_ptr->mapObj->renderStill([this](std::exception_ptr err) { QString what; @@ -1268,7 +1210,7 @@ void Map::startStaticRender() if (err) { std::rethrow_exception(err); } - } catch(const std::exception& e) { + } catch (const std::exception &e) { what = e.what(); } @@ -1287,8 +1229,7 @@ void Map::startStaticRender() Must be called on the render thread. */ -void Map::render() -{ +void Map::render() { d_ptr->render(); } @@ -1299,8 +1240,7 @@ void Map::render() Must be called on the render thread. */ -void Map::setFramebufferObject(quint32 fbo, const QSize& size) -{ +void Map::setFramebufferObject(quint32 fbo, const QSize &size) { d_ptr->setFramebufferObject(fbo, size); } @@ -1308,8 +1248,7 @@ void Map::setFramebufferObject(quint32 fbo, const QSize& size) Informs the map that the network connection has been established, causing all network requests that previously timed out to be retried immediately. */ -void Map::connectionEstablished() -{ +void Map::connectionEstablished() { mbgl::NetworkStatus::Reachable(); } @@ -1317,8 +1256,7 @@ void Map::connectionEstablished() Returns a list containing a pair of string objects, representing the style URL and name, respectively. */ -const QVector> &Map::defaultStyles() const -{ +const QVector> &Map::defaultStyles() const { return d_ptr->defaultStyles; } @@ -1367,11 +1305,10 @@ const QVector> &Map::defaultStyles() const */ MapPrivate::MapPrivate(Map *q, const Settings &settings, const QSize &size, qreal pixelRatio_) - : QObject(q) - , m_mode(settings.contextMode()) - , m_pixelRatio(pixelRatio_) - , m_localFontFamily(settings.localFontFamily()) -{ + : QObject(q), + m_mode(settings.contextMode()), + m_pixelRatio(pixelRatio_), + m_localFontFamily(settings.localFontFamily()) { // Setup MapObserver m_mapObserver = std::make_unique(this); @@ -1383,47 +1320,49 @@ MapPrivate::MapPrivate(Map *q, const Settings &settings, const QSize &size, qrea auto resourceOptions = resourceOptionsFromSettings(settings); for (auto style : resourceOptions.tileServerOptions().defaultStyles()) { - defaultStyles.append(QPair( - QString::fromStdString(style.getUrl()), QString::fromStdString(style.getName()))); + defaultStyles.append( + QPair(QString::fromStdString(style.getUrl()), QString::fromStdString(style.getName())) + ); } - + auto clientOptions = clientOptionsFromSettings(settings); // Setup the Map object. - mapObj = std::make_unique(*this, *m_mapObserver, - mapOptionsFromSettings(settings, size, m_pixelRatio), - resourceOptions, - clientOptionsFromSettings(settings)); - - if (settings.resourceTransform()) { - m_resourceTransform = std::make_unique>( - *mbgl::Scheduler::GetCurrent(), - [callback = settings.resourceTransform()]( - mbgl::Resource::Kind, const std::string &url_, mbgl::ResourceTransform::FinishedCallback onFinished) { - onFinished(callback(std::move(url_))); - }); - - mbgl::ResourceTransform transform{[actorRef = m_resourceTransform->self()]( - mbgl::Resource::Kind kind, - const std::string &url, - mbgl::ResourceTransform::FinishedCallback onFinished) { - actorRef.invoke(&mbgl::ResourceTransform::TransformCallback::operator(), kind, url, std::move(onFinished)); - }}; - std::shared_ptr fs = - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Network, resourceOptions, clientOptions); - fs->setResourceTransform(std::move(transform)); - } + mapObj = std::make_unique( + *this, + *m_mapObserver, + mapOptionsFromSettings(settings, size, m_pixelRatio), + resourceOptions, + clientOptionsFromSettings(settings) + ); + + if (settings.resourceTransform()) { + m_resourceTransform = std::make_unique>( + *mbgl::Scheduler::GetCurrent(), + [callback = settings.resourceTransform()]( + mbgl::Resource::Kind, const std::string &url_, mbgl::ResourceTransform::FinishedCallback onFinished + ) { onFinished(callback(std::move(url_))); } + ); + + mbgl::ResourceTransform transform{[actorRef = m_resourceTransform->self( + )](mbgl::Resource::Kind kind, + const std::string &url, + mbgl::ResourceTransform::FinishedCallback onFinished) { + actorRef.invoke(&mbgl::ResourceTransform::TransformCallback::operator(), kind, url, std::move(onFinished)); + }}; + std::shared_ptr fs = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::Network, resourceOptions, clientOptions + ); + fs->setResourceTransform(std::move(transform)); + } // Needs to be Queued to give time to discard redundant draw calls via the `renderQueued` flag. connect(this, &MapPrivate::needsRendering, q, &Map::needsRendering, Qt::QueuedConnection); } -MapPrivate::~MapPrivate() -{ -} +MapPrivate::~MapPrivate() {} -void MapPrivate::update(std::shared_ptr parameters) -{ +void MapPrivate::update(std::shared_ptr parameters) { std::lock_guard lock(m_mapRendererMutex); m_updateParameters = std::move(parameters); @@ -1437,10 +1376,8 @@ void MapPrivate::update(std::shared_ptr parameters) requestRendering(); } -void MapPrivate::setObserver(mbgl::RendererObserver &observer) -{ - m_rendererObserver = std::make_shared( - *mbgl::util::RunLoop::Get(), observer); +void MapPrivate::setObserver(mbgl::RendererObserver &observer) { + m_rendererObserver = std::make_shared(*mbgl::util::RunLoop::Get(), observer); std::lock_guard lock(m_mapRendererMutex); @@ -1449,19 +1386,14 @@ void MapPrivate::setObserver(mbgl::RendererObserver &observer) } } -void MapPrivate::createRenderer() -{ +void MapPrivate::createRenderer() { std::lock_guard lock(m_mapRendererMutex); if (m_mapRenderer) { return; } - m_mapRenderer = std::make_unique( - m_pixelRatio, - m_mode, - m_localFontFamily - ); + m_mapRenderer = std::make_unique(m_pixelRatio, m_mode, m_localFontFamily); connect(m_mapRenderer.get(), &MapRenderer::needsRendering, this, &MapPrivate::requestRendering); @@ -1473,15 +1405,13 @@ void MapPrivate::createRenderer() } } -void MapPrivate::destroyRenderer() -{ +void MapPrivate::destroyRenderer() { std::lock_guard lock(m_mapRendererMutex); m_mapRenderer.reset(); } -void MapPrivate::render() -{ +void MapPrivate::render() { std::lock_guard lock(m_mapRendererMutex); if (!m_mapRenderer) { @@ -1492,8 +1422,7 @@ void MapPrivate::render() m_mapRenderer->render(); } -void MapPrivate::setFramebufferObject(quint32 fbo, const QSize& size) -{ +void MapPrivate::setFramebufferObject(quint32 fbo, const QSize &size) { std::lock_guard lock(m_mapRendererMutex); if (!m_mapRenderer) { @@ -1503,23 +1432,24 @@ void MapPrivate::setFramebufferObject(quint32 fbo, const QSize& size) m_mapRenderer->updateFramebuffer(fbo, sanitizedSize(size)); } -void MapPrivate::requestRendering() -{ +void MapPrivate::requestRendering() { if (!m_renderQueued.test_and_set()) { emit needsRendering(); } } -bool MapPrivate::setProperty(const PropertySetter& setter, const QString& layer, const QString& name, const QVariant& value) { +bool MapPrivate::setProperty( + const PropertySetter &setter, const QString &layer, const QString &name, const QVariant &value +) { using namespace mbgl::style; - Layer* layerObject = mapObj->getStyle().getLayer(layer.toStdString()); + Layer *layerObject = mapObj->getStyle().getLayer(layer.toStdString()); if (!layerObject) { qWarning() << "Layer not found:" << layer; return false; } - const std::string& propertyString = name.toStdString(); + const std::string &propertyString = name.toStdString(); std::optional result; @@ -1532,7 +1462,7 @@ bool MapPrivate::setProperty(const PropertySetter& setter, const QString& layer, document.Parse<0>(value.toString().toStdString()); if (!document.HasParseError()) { // Treat value as a valid JSON. - const mbgl::JSValue* jsonValue = &document; + const mbgl::JSValue *jsonValue = &document; result = (layerObject->*setter)(propertyString, jsonValue); } else { result = (layerObject->*setter)(propertyString, value); @@ -1542,7 +1472,8 @@ bool MapPrivate::setProperty(const PropertySetter& setter, const QString& layer, } if (result) { - qWarning() << "Error setting property" << name << "on layer" << layer << ":" << QString::fromStdString(result->message); + qWarning() << "Error setting property" << name << "on layer" << layer << ":" + << QString::fromStdString(result->message); return false; } diff --git a/platform/qt/src/map_p.hpp b/platform/qt/src/map_p.hpp index b93492d4a11..6bacad772ad 100644 --- a/platform/qt/src/map_p.hpp +++ b/platform/qt/src/map_p.hpp @@ -19,17 +19,16 @@ namespace QMapLibreGL { -class MapPrivate : public QObject, public mbgl::RendererFrontend -{ +class MapPrivate : public QObject, public mbgl::RendererFrontend { Q_OBJECT public: - explicit MapPrivate(Map *, const Settings &, const QSize &size, qreal pixelRatio); + explicit MapPrivate(Map*, const Settings&, const QSize& size, qreal pixelRatio); virtual ~MapPrivate(); // mbgl::RendererFrontend implementation. void reset() final {} - void setObserver(mbgl::RendererObserver &) final; + void setObserver(mbgl::RendererObserver&) final; void update(std::shared_ptr) final; // These need to be called on the same thread. @@ -38,7 +37,9 @@ class MapPrivate : public QObject, public mbgl::RendererFrontend void render(); void setFramebufferObject(quint32 fbo, const QSize& size); - using PropertySetter = std::optional (mbgl::style::Layer::*)(const std::string&, const mbgl::style::conversion::Convertible&); + using PropertySetter = std::optional< + mbgl::style::conversion::Error> (mbgl::style:: + Layer::*)(const std::string&, const mbgl::style::conversion::Convertible&); bool setProperty(const PropertySetter& setter, const QString& layer, const QString& name, const QVariant& value); mbgl::EdgeInsets margins; diff --git a/platform/qt/src/mbgl/async_task.cpp b/platform/qt/src/mbgl/async_task.cpp index 2422e547e85..3ae29254f07 100644 --- a/platform/qt/src/mbgl/async_task.cpp +++ b/platform/qt/src/mbgl/async_task.cpp @@ -28,15 +28,13 @@ void AsyncTask::Impl::runTask() { } AsyncTask::AsyncTask(std::function&& fn) - : impl(std::make_unique(std::move(fn))) { -} + : impl(std::make_unique(std::move(fn))) {} -AsyncTask::~AsyncTask() { -} +AsyncTask::~AsyncTask() {} void AsyncTask::send() { impl->maySend(); } -} -} +} // namespace util +} // namespace mbgl diff --git a/platform/qt/src/mbgl/async_task_impl.hpp b/platform/qt/src/mbgl/async_task_impl.hpp index ea86079a90f..c608306968b 100644 --- a/platform/qt/src/mbgl/async_task_impl.hpp +++ b/platform/qt/src/mbgl/async_task_impl.hpp @@ -16,7 +16,7 @@ class AsyncTask::Impl : public QObject { Q_OBJECT public: - Impl(std::function &&); + Impl(std::function&&); void maySend(); @@ -33,6 +33,5 @@ public slots: std::atomic_flag queued = ATOMIC_FLAG_INIT; }; - } // namespace util } // namespace mbgl diff --git a/platform/qt/src/mbgl/bidi.cpp b/platform/qt/src/mbgl/bidi.cpp index 57e61d33427..28bbe3adcc5 100644 --- a/platform/qt/src/mbgl/bidi.cpp +++ b/platform/qt/src/mbgl/bidi.cpp @@ -14,9 +14,8 @@ std::u16string applyArabicShaping(const std::u16string& input) { return input; } -BiDi::BiDi() : impl(std::make_unique()) -{ -} +BiDi::BiDi() + : impl(std::make_unique()) {} BiDi::~BiDi() = default; @@ -42,7 +41,8 @@ std::vector BiDi::processStyledText(const StyledText& input, std::se if (lineBreakPoint <= input.second.size()) { transformedLines.emplace_back( input.first.substr(start, lineBreakPoint - start), - std::vector(input.second.begin() + start, input.second.begin() + lineBreakPoint)); + std::vector(input.second.begin() + start, input.second.begin() + lineBreakPoint) + ); start = lineBreakPoint; } } diff --git a/platform/qt/src/mbgl/gl_functions.cpp b/platform/qt/src/mbgl/gl_functions.cpp index 2009646905f..8967f69bed8 100644 --- a/platform/qt/src/mbgl/gl_functions.cpp +++ b/platform/qt/src/mbgl/gl_functions.cpp @@ -9,888 +9,903 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = [](auto... args) { +void (*const glActiveTexture)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glActiveTexture(args...); }; -void (* const glAttachShader)(GLuint, GLuint) = [](auto... args) { +void (*const glAttachShader)(GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glAttachShader(args...); }; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *) = [](auto... args) { +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindAttribLocation(args...); }; -void (* const glBindBuffer)(GLenum, GLuint) = [](auto... args) { +void (*const glBindBuffer)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindBuffer(args...); }; -void (* const glBindFramebuffer)(GLenum, GLuint) = [](auto... args) { +void (*const glBindFramebuffer)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindFramebuffer(args...); }; -void (* const glBindRenderbuffer)(GLenum, GLuint) = [](auto... args) { +void (*const glBindRenderbuffer)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindRenderbuffer(args...); }; -void (* const glBindTexture)(GLenum, GLuint) = [](auto... args) { +void (*const glBindTexture)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindTexture(args...); }; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendColor(args...); }; -void (* const glBlendEquation)(GLenum) = [](auto... args) { +void (*const glBlendEquation)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendEquation(args...); }; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = [](auto... args) { +void (*const glBlendEquationSeparate)(GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendEquationSeparate(args...); }; -void (* const glBlendFunc)(GLenum, GLenum) = [](auto... args) { +void (*const glBlendFunc)(GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendFunc(args...); }; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = [](auto... args) { +void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendFuncSeparate(args...); }; -void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum) = [](auto... args) { +void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBufferData(args...); }; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *) = [](auto... args) { +void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBufferSubData(args...); }; -GLenum (* const glCheckFramebufferStatus)(GLenum) = [](auto... args) { +GLenum (*const glCheckFramebufferStatus)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCheckFramebufferStatus(args...); }; -void (* const glClear)(GLbitfield) = [](auto... args) { +void (*const glClear)(GLbitfield) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glClear(args...); }; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glClearColor(args...); }; -void (* const glClearDepthf)(GLfloat) = [](auto... args) { +void (*const glClearDepthf)(GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glClearDepthf(args...); }; -void (* const glClearStencil)(GLint) = [](auto... args) { +void (*const glClearStencil)(GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glClearStencil(args...); }; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = [](auto... args) { +void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glColorMask(args...); }; -void (* const glCompileShader)(GLuint) = [](auto... args) { +void (*const glCompileShader)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCompileShader(args...); }; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *) = [](auto... args) { +void (*const glCompressedTexImage2D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCompressedTexImage2D(args...); }; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *) = [](auto... args) { +void (*const glCompressedTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCompressedTexSubImage2D(args...); }; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = [](auto... args) { +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCopyTexImage2D(args...); }; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCopyTexSubImage2D(args...); }; -GLuint (* const glCreateProgram)() = [](auto... args) { +GLuint (*const glCreateProgram)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCreateProgram(args...); }; -GLuint (* const glCreateShader)(GLenum) = [](auto... args) { +GLuint (*const glCreateShader)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCreateShader(args...); }; -void (* const glCullFace)(GLenum) = [](auto... args) { +void (*const glCullFace)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCullFace(args...); }; -void (* const glDeleteBuffers)(GLsizei, const GLuint *) = [](auto... args) { +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteBuffers(args...); }; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint *) = [](auto... args) { +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteFramebuffers(args...); }; -void (* const glDeleteProgram)(GLuint) = [](auto... args) { +void (*const glDeleteProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteProgram(args...); }; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *) = [](auto... args) { +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteRenderbuffers(args...); }; -void (* const glDeleteShader)(GLuint) = [](auto... args) { +void (*const glDeleteShader)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteShader(args...); }; -void (* const glDeleteTextures)(GLsizei, const GLuint *) = [](auto... args) { +void (*const glDeleteTextures)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteTextures(args...); }; -void (* const glDepthFunc)(GLenum) = [](auto... args) { +void (*const glDepthFunc)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDepthFunc(args...); }; -void (* const glDepthMask)(GLboolean) = [](auto... args) { +void (*const glDepthMask)(GLboolean) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDepthMask(args...); }; -void (* const glDepthRangef)(GLfloat, GLfloat) = [](auto... args) { +void (*const glDepthRangef)(GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDepthRangef(args...); }; -void (* const glDetachShader)(GLuint, GLuint) = [](auto... args) { +void (*const glDetachShader)(GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDetachShader(args...); }; -void (* const glDisable)(GLenum) = [](auto... args) { +void (*const glDisable)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDisable(args...); }; -void (* const glDisableVertexAttribArray)(GLuint) = [](auto... args) { +void (*const glDisableVertexAttribArray)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDisableVertexAttribArray(args...); }; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = [](auto... args) { +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDrawArrays(args...); }; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *) = [](auto... args) { +void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDrawElements(args...); }; -void (* const glEnable)(GLenum) = [](auto... args) { +void (*const glEnable)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glEnable(args...); }; -void (* const glEnableVertexAttribArray)(GLuint) = [](auto... args) { +void (*const glEnableVertexAttribArray)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glEnableVertexAttribArray(args...); }; -void (* const glFinish)() = [](auto... args) { +void (*const glFinish)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFinish(args...); }; -void (* const glFlush)() = [](auto... args) { +void (*const glFlush)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFlush(args...); }; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = [](auto... args) { +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFramebufferRenderbuffer(args...); }; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = [](auto... args) { +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFramebufferTexture2D(args...); }; -void (* const glFrontFace)(GLenum) = [](auto... args) { +void (*const glFrontFace)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFrontFace(args...); }; -void (* const glGenBuffers)(GLsizei, GLuint *) = [](auto... args) { +void (*const glGenBuffers)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenBuffers(args...); }; -void (* const glGenerateMipmap)(GLenum) = [](auto... args) { +void (*const glGenerateMipmap)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenerateMipmap(args...); }; -void (* const glGenFramebuffers)(GLsizei, GLuint *) = [](auto... args) { +void (*const glGenFramebuffers)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenFramebuffers(args...); }; -void (* const glGenRenderbuffers)(GLsizei, GLuint *) = [](auto... args) { +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenRenderbuffers(args...); }; -void (* const glGenTextures)(GLsizei, GLuint *) = [](auto... args) { +void (*const glGenTextures)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenTextures(args...); }; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = [](auto... args) { +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetActiveAttrib(args...); }; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = [](auto... args) { +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetActiveUniform(args...); }; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *) = [](auto... args) { +void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetAttachedShaders(args...); }; -GLint (* const glGetAttribLocation)(GLuint, const GLchar *) = [](auto... args) { +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetAttribLocation(args...); }; -void (* const glGetBooleanv)(GLenum, GLboolean *) = [](auto... args) { +void (*const glGetBooleanv)(GLenum, GLboolean*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetBooleanv(args...); }; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *) = [](auto... args) { +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetBufferParameteriv(args...); }; -GLenum (* const glGetError)() = [](auto... args) { +GLenum (*const glGetError)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetError(args...); }; -void (* const glGetFloatv)(GLenum, GLfloat *) = [](auto... args) { +void (*const glGetFloatv)(GLenum, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetFloatv(args...); }; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *) = [](auto... args) { +void (*const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetFramebufferAttachmentParameteriv(args...); }; -void (* const glGetIntegerv)(GLenum, GLint *) = [](auto... args) { +void (*const glGetIntegerv)(GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetIntegerv(args...); }; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = [](auto... args) { +void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetProgramInfoLog(args...); }; -void (* const glGetProgramiv)(GLuint, GLenum, GLint *) = [](auto... args) { +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetProgramiv(args...); }; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *) = [](auto... args) { +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetRenderbufferParameteriv(args...); }; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = [](auto... args) { +void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetShaderInfoLog(args...); }; -void (* const glGetShaderiv)(GLuint, GLenum, GLint *) = [](auto... args) { +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetShaderiv(args...); }; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *) = [](auto... args) { +void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetShaderPrecisionFormat(args...); }; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *) = [](auto... args) { +void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetShaderSource(args...); }; -const GLubyte *(* const glGetString)(GLenum) = [](auto... args) { +const GLubyte* (*const glGetString)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetString(args...); }; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *) = [](auto... args) { +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetTexParameterfv(args...); }; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *) = [](auto... args) { +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetTexParameteriv(args...); }; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat *) = [](auto... args) { +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetUniformfv(args...); }; -void (* const glGetUniformiv)(GLuint, GLint, GLint *) = [](auto... args) { +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetUniformiv(args...); }; -GLint (* const glGetUniformLocation)(GLuint, const GLchar *) = [](auto... args) { +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetUniformLocation(args...); }; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *) = [](auto... args) { +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetVertexAttribfv(args...); }; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *) = [](auto... args) { +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetVertexAttribiv(args...); }; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **) = [](auto... args) { +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetVertexAttribPointerv(args...); }; -void (* const glHint)(GLenum, GLenum) = [](auto... args) { +void (*const glHint)(GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glHint(args...); }; -GLboolean (* const glIsBuffer)(GLuint) = [](auto... args) { +GLboolean (*const glIsBuffer)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsBuffer(args...); }; -GLboolean (* const glIsEnabled)(GLenum) = [](auto... args) { +GLboolean (*const glIsEnabled)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsEnabled(args...); }; -GLboolean (* const glIsFramebuffer)(GLuint) = [](auto... args) { +GLboolean (*const glIsFramebuffer)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsFramebuffer(args...); }; -GLboolean (* const glIsProgram)(GLuint) = [](auto... args) { +GLboolean (*const glIsProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsProgram(args...); }; -GLboolean (* const glIsRenderbuffer)(GLuint) = [](auto... args) { +GLboolean (*const glIsRenderbuffer)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsRenderbuffer(args...); }; -GLboolean (* const glIsShader)(GLuint) = [](auto... args) { +GLboolean (*const glIsShader)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsShader(args...); }; -GLboolean (* const glIsTexture)(GLuint) = [](auto... args) { +GLboolean (*const glIsTexture)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsTexture(args...); }; -void (* const glLineWidth)(GLfloat) = [](auto... args) { +void (*const glLineWidth)(GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glLineWidth(args...); }; -void (* const glLinkProgram)(GLuint) = [](auto... args) { +void (*const glLinkProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glLinkProgram(args...); }; -void (* const glPixelStorei)(GLenum, GLint) = [](auto... args) { +void (*const glPixelStorei)(GLenum, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glPixelStorei(args...); }; -void (* const glPolygonOffset)(GLfloat, GLfloat) = [](auto... args) { +void (*const glPolygonOffset)(GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glPolygonOffset(args...); }; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *) = [](auto... args) { +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glReadPixels(args...); }; -void (* const glReleaseShaderCompiler)() = [](auto... args) { +void (*const glReleaseShaderCompiler)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glReleaseShaderCompiler(args...); }; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = [](auto... args) { +void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glRenderbufferStorage(args...); }; -void (* const glSampleCoverage)(GLfloat, GLboolean) = [](auto... args) { +void (*const glSampleCoverage)(GLfloat, GLboolean) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glSampleCoverage(args...); }; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glScissor(args...); }; -void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei) = [](auto... args) { +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glShaderBinary(args...); }; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *) = [](GLuint shader, GLsizei count, const GLchar * const * string, const GLint *length) { - return QOpenGLContext::currentContext()->functions()->glShaderSource(shader, count, const_cast(string), length); -}; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = + [](GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length) { + return QOpenGLContext::currentContext()->functions()->glShaderSource( + shader, count, const_cast(string), length + ); + }; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = [](auto... args) { +void (*const glStencilFunc)(GLenum, GLint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilFunc(args...); }; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = [](auto... args) { +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilFuncSeparate(args...); }; -void (* const glStencilMask)(GLuint) = [](auto... args) { +void (*const glStencilMask)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilMask(args...); }; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = [](auto... args) { +void (*const glStencilMaskSeparate)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilMaskSeparate(args...); }; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = [](auto... args) { +void (*const glStencilOp)(GLenum, GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilOp(args...); }; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = [](auto... args) { +void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilOpSeparate(args...); }; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *) = [](auto... args) { +void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = [](auto... args + ) { return QOpenGLContext::currentContext()->functions()->glTexImage2D(args...); }; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = [](auto... args) { +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glTexParameterf(args...); }; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *) = [](auto... args) { +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glTexParameterfv(args...); }; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = [](auto... args) { +void (*const glTexParameteri)(GLenum, GLenum, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glTexParameteri(args...); }; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint *) = [](auto... args) { +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glTexParameteriv(args...); }; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *) = [](auto... args) { +void (*const glTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glTexSubImage2D(args...); }; -void (* const glUniform1f)(GLint, GLfloat) = [](auto... args) { +void (*const glUniform1f)(GLint, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform1f(args...); }; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *) = [](auto... args) { +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform1fv(args...); }; -void (* const glUniform1i)(GLint, GLint) = [](auto... args) { +void (*const glUniform1i)(GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform1i(args...); }; -void (* const glUniform1iv)(GLint, GLsizei, const GLint *) = [](auto... args) { +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform1iv(args...); }; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = [](auto... args) { +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform2f(args...); }; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *) = [](auto... args) { +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform2fv(args...); }; -void (* const glUniform2i)(GLint, GLint, GLint) = [](auto... args) { +void (*const glUniform2i)(GLint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform2i(args...); }; -void (* const glUniform2iv)(GLint, GLsizei, const GLint *) = [](auto... args) { +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform2iv(args...); }; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform3f(args...); }; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *) = [](auto... args) { +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform3fv(args...); }; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = [](auto... args) { +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform3i(args...); }; -void (* const glUniform3iv)(GLint, GLsizei, const GLint *) = [](auto... args) { +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform3iv(args...); }; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform4f(args...); }; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *) = [](auto... args) { +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform4fv(args...); }; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = [](auto... args) { +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform4i(args...); }; -void (* const glUniform4iv)(GLint, GLsizei, const GLint *) = [](auto... args) { +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform4iv(args...); }; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = [](auto... args) { +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniformMatrix2fv(args...); }; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = [](auto... args) { +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniformMatrix3fv(args...); }; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = [](auto... args) { +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniformMatrix4fv(args...); }; -void (* const glUseProgram)(GLuint) = [](auto... args) { +void (*const glUseProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUseProgram(args...); }; -void (* const glValidateProgram)(GLuint) = [](auto... args) { +void (*const glValidateProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glValidateProgram(args...); }; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = [](auto... args) { +void (*const glVertexAttrib1f)(GLuint, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib1f(args...); }; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat *) = [](auto... args) { +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib1fv(args...); }; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = [](auto... args) { +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib2f(args...); }; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat *) = [](auto... args) { +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib2fv(args...); }; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib3f(args...); }; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat *) = [](auto... args) { +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib3fv(args...); }; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib4f(args...); }; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat *) = [](auto... args) { +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib4fv(args...); }; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *) = [](auto... args) { +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttribPointer(args...); }; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glViewport(args...); }; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = [](auto... args) { +void (*const glReadBuffer)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glReadBuffer(args...); }; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = [](auto... args) { +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDrawRangeElements(args...); }; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = [](auto... args) { +void (*const glTexImage3D +)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glTexImage3D(args...); }; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = [](auto... args) { +void (*const glTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glTexSubImage3D(args...); }; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](auto... args + ) { return QOpenGLContext::currentContext()->extraFunctions()->glCopyTexSubImage3D(args...); }; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = [](auto... args) { +void (*const glCompressedTexImage3D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glCompressedTexImage3D(args...); }; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = [](auto... args) { +void (*const glCompressedTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glCompressedTexSubImage3D(args...); }; -void (* const glGenQueries)(GLsizei, GLuint*) = [](auto... args) { +void (*const glGenQueries)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGenQueries(args...); }; -void (* const glDeleteQueries)(GLsizei, const GLuint*) = [](auto... args) { +void (*const glDeleteQueries)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteQueries(args...); }; -GLboolean (* const glIsQuery)(GLuint) = [](auto... args) { +GLboolean (*const glIsQuery)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsQuery(args...); }; -void (* const glBeginQuery)(GLenum, GLuint) = [](auto... args) { +void (*const glBeginQuery)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBeginQuery(args...); }; -void (* const glEndQuery)(GLenum) = [](auto... args) { +void (*const glEndQuery)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glEndQuery(args...); }; -void (* const glGetQueryiv)(GLenum, GLenum, GLint*) = [](auto... args) { +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetQueryiv(args...); }; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = [](auto... args) { +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetQueryObjectuiv(args...); }; -GLboolean (* const glUnmapBuffer)(GLenum) = [](auto... args) { +GLboolean (*const glUnmapBuffer)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUnmapBuffer(args...); }; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = [](auto... args) { +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetBufferPointerv(args...); }; -void (* const glDrawBuffers)(GLsizei, const GLenum*) = [](auto... args) { +void (*const glDrawBuffers)(GLsizei, const GLenum*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDrawBuffers(args...); }; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix2x3fv(args...); }; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix3x2fv(args...); }; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix2x4fv(args...); }; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix4x2fv(args...); }; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix3x4fv(args...); }; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix4x3fv(args...); }; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = [](auto... args) { +void (*const glBlitFramebuffer +)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBlitFramebuffer(args...); }; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](auto... args) { +void (*const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glRenderbufferStorageMultisample(args...); }; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = [](auto... args) { +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glFramebufferTextureLayer(args...); }; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = [](auto... args) { +GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glMapBufferRange(args...); }; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = [](auto... args) { +void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glFlushMappedBufferRange(args...); }; -void (* const glBindVertexArray)(GLuint) = [](auto... args) { +void (*const glBindVertexArray)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindVertexArray(args...); }; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint*) = [](auto... args) { +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteVertexArrays(args...); }; -void (* const glGenVertexArrays)(GLsizei, GLuint*) = [](auto... args) { +void (*const glGenVertexArrays)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGenVertexArrays(args...); }; -GLboolean (* const glIsVertexArray)(GLuint) = [](auto... args) { +GLboolean (*const glIsVertexArray)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsVertexArray(args...); }; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint*) = [](auto... args) { +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetIntegeri_v(args...); }; -void (* const glBeginTransformFeedback)(GLenum) = [](auto... args) { +void (*const glBeginTransformFeedback)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBeginTransformFeedback(args...); }; -void (* const glEndTransformFeedback)() = [](auto... args) { +void (*const glEndTransformFeedback)() = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glEndTransformFeedback(args...); }; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = [](auto... args) { +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindBufferRange(args...); }; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = [](auto... args) { +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindBufferBase(args...); }; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum) = [](auto... args) { +void (*const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glTransformFeedbackVaryings(args...); }; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = [](auto... args) { +void (*const glGetTransformFeedbackVarying +)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetTransformFeedbackVarying(args...); }; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = [](auto... args) { +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribIPointer(args...); }; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = [](auto... args) { +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetVertexAttribIiv(args...); }; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = [](auto... args) { +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetVertexAttribIuiv(args...); }; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = [](auto... args) { +void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribI4i(args...); }; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = [](auto... args) { +void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribI4ui(args...); }; -void (* const glVertexAttribI4iv)(GLuint, const GLint*) = [](auto... args) { +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribI4iv(args...); }; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint*) = [](auto... args) { +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribI4uiv(args...); }; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint*) = [](auto... args) { +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetUniformuiv(args...); }; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar*) = [](auto... args) { +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetFragDataLocation(args...); }; -void (* const glUniform1ui)(GLint, GLuint) = [](auto... args) { +void (*const glUniform1ui)(GLint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform1ui(args...); }; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = [](auto... args) { +void (*const glUniform2ui)(GLint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform2ui(args...); }; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = [](auto... args) { +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform3ui(args...); }; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = [](auto... args) { +void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform4ui(args...); }; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform1uiv(args...); }; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform2uiv(args...); }; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform3uiv(args...); }; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform4uiv(args...); }; -void (* const glClearBufferiv)(GLenum, GLint, const GLint*) = [](auto... args) { +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClearBufferiv(args...); }; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint*) = [](auto... args) { +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClearBufferuiv(args...); }; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat*) = [](auto... args) { +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClearBufferfv(args...); }; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = [](auto... args) { +void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClearBufferfi(args...); }; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = [](auto... args) { +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetStringi(args...); }; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = [](auto... args) { +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glCopyBufferSubData(args...); }; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = [](auto... args) { +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetUniformIndices(args...); }; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = [](auto... args) { +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetActiveUniformsiv(args...); }; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar*) = [](auto... args) { +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetUniformBlockIndex(args...); }; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = [](auto... args) { +void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetActiveUniformBlockiv(args...); }; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetActiveUniformBlockName(args...); }; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = [](auto... args) { +void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformBlockBinding(args...); }; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDrawArraysInstanced(args...); }; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = [](auto... args) { +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDrawElementsInstanced(args...); }; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = [](auto... args) { +GLsync (*const glFenceSync)(GLenum, GLbitfield) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glFenceSync(args...); }; -GLboolean (* const glIsSync)(GLsync) = [](auto... args) { +GLboolean (*const glIsSync)(GLsync) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsSync(args...); }; -void (* const glDeleteSync)(GLsync) = [](auto... args) { +void (*const glDeleteSync)(GLsync) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteSync(args...); }; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = [](auto... args) { +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClientWaitSync(args...); }; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = [](auto... args) { +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glWaitSync(args...); }; -void (* const glGetInteger64v)(GLenum, GLint64*) = [](auto... args) { +void (*const glGetInteger64v)(GLenum, GLint64*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetInteger64v(args...); }; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = [](auto... args) { +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetSynciv(args...); }; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = [](auto... args) { +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetInteger64i_v(args...); }; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = [](auto... args) { +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetBufferParameteri64v(args...); }; -void (* const glGenSamplers)(GLsizei, GLuint*) = [](auto... args) { +void (*const glGenSamplers)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGenSamplers(args...); }; -void (* const glDeleteSamplers)(GLsizei, const GLuint*) = [](auto... args) { +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteSamplers(args...); }; -GLboolean (* const glIsSampler)(GLuint) = [](auto... args) { +GLboolean (*const glIsSampler)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsSampler(args...); }; -void (* const glBindSampler)(GLuint, GLuint) = [](auto... args) { +void (*const glBindSampler)(GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindSampler(args...); }; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = [](auto... args) { +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glSamplerParameteri(args...); }; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = [](auto... args) { +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glSamplerParameteriv(args...); }; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = [](auto... args) { +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glSamplerParameterf(args...); }; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = [](auto... args) { +void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glSamplerParameterfv(args...); }; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = [](auto... args) { +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetSamplerParameteriv(args...); }; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = [](auto... args) { +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetSamplerParameterfv(args...); }; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = [](auto... args) { +void (*const glVertexAttribDivisor)(GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribDivisor(args...); }; -void (* const glBindTransformFeedback)(GLenum, GLuint) = [](auto... args) { +void (*const glBindTransformFeedback)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindTransformFeedback(args...); }; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = [](auto... args) { +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteTransformFeedbacks(args...); }; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint*) = [](auto... args) { +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGenTransformFeedbacks(args...); }; -GLboolean (* const glIsTransformFeedback)(GLuint) = [](auto... args) { +GLboolean (*const glIsTransformFeedback)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsTransformFeedback(args...); }; -void (* const glPauseTransformFeedback)() = [](auto... args) { +void (*const glPauseTransformFeedback)() = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glPauseTransformFeedback(args...); }; -void (* const glResumeTransformFeedback)() = [](auto... args) { +void (*const glResumeTransformFeedback)() = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glResumeTransformFeedback(args...); }; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = [](auto... args) { +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetProgramBinary(args...); }; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = [](auto... args) { +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glProgramBinary(args...); }; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = [](auto... args) { +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glProgramParameteri(args...); }; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = [](auto... args) { +void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glInvalidateFramebuffer(args...); }; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glInvalidateSubFramebuffer +)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glInvalidateSubFramebuffer(args...); }; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](auto... args) { +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glTexStorage2D(args...); }; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = [](auto... args) { +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glTexStorage3D(args...); }; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = [](auto... args) { +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetInternalformativ(args...); }; -} // namespace platform -} // namespace mbgl \ No newline at end of file +} // namespace platform +} // namespace mbgl \ No newline at end of file diff --git a/platform/qt/src/mbgl/headless_backend_qt.cpp b/platform/qt/src/mbgl/headless_backend_qt.cpp index 03bf3bfb16b..bce5ae0cf5d 100644 --- a/platform/qt/src/mbgl/headless_backend_qt.cpp +++ b/platform/qt/src/mbgl/headless_backend_qt.cpp @@ -23,13 +23,9 @@ class QtBackendImpl final : public HeadlessBackend::Impl { return thisContext->getProcAddress(name); } - void activateContext() { - context.makeCurrent(&surface); - } + void activateContext() { context.makeCurrent(&surface); } - void deactivateContext() { - context.doneCurrent(); - } + void deactivateContext() { context.doneCurrent(); } private: QOpenGLContext context; diff --git a/platform/qt/src/mbgl/http_file_source.cpp b/platform/qt/src/mbgl/http_file_source.cpp index 1819aa8bcb3..43df2470715 100644 --- a/platform/qt/src/mbgl/http_file_source.cpp +++ b/platform/qt/src/mbgl/http_file_source.cpp @@ -14,13 +14,11 @@ namespace mbgl { HTTPFileSource::Impl::Impl(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) : m_manager(new QNetworkAccessManager(this)), m_resourceOptions(resourceOptions.clone()), - m_clientOptions(clientOptions.clone()) -{ + m_clientOptions(clientOptions.clone()) { QNetworkProxyFactory::setUseSystemConfiguration(true); } -void HTTPFileSource::Impl::request(HTTPRequest* req) -{ +void HTTPFileSource::Impl::request(HTTPRequest* req) { QUrl url = req->requestUrl(); QPair, QVector>& data = m_pending[url]; @@ -33,12 +31,11 @@ void HTTPFileSource::Impl::request(HTTPRequest* req) QNetworkRequest networkRequest = req->networkRequest(); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) -# if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) - networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, - QNetworkRequest::NoLessSafeRedirectPolicy); -# elif QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) + networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); +#elif QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); -# endif +#endif #endif data.first = m_manager->get(networkRequest); @@ -50,8 +47,7 @@ void HTTPFileSource::Impl::request(HTTPRequest* req) #endif } -void HTTPFileSource::Impl::cancel(HTTPRequest* req) -{ +void HTTPFileSource::Impl::cancel(HTTPRequest* req) { QUrl url = req->requestUrl(); auto it = m_pending.find(url); @@ -76,9 +72,8 @@ void HTTPFileSource::Impl::cancel(HTTPRequest* req) } } -void HTTPFileSource::Impl::onReplyFinished() -{ - QNetworkReply* reply = qobject_cast(sender()); +void HTTPFileSource::Impl::onReplyFinished() { + QNetworkReply* reply = qobject_cast(sender()); const QUrl& url = reply->request().url(); auto it = m_pending.find(url); @@ -101,34 +96,28 @@ void HTTPFileSource::Impl::onReplyFinished() reply->deleteLater(); } -void HTTPFileSource::Impl::setResourceOptions(ResourceOptions options) -{ +void HTTPFileSource::Impl::setResourceOptions(ResourceOptions options) { m_resourceOptions = options; } -ResourceOptions HTTPFileSource::Impl::getResourceOptions() -{ +ResourceOptions HTTPFileSource::Impl::getResourceOptions() { return m_resourceOptions.clone(); } -void HTTPFileSource::Impl::setClientOptions(ClientOptions options) -{ +void HTTPFileSource::Impl::setClientOptions(ClientOptions options) { m_clientOptions = options; } -ClientOptions HTTPFileSource::Impl::getClientOptions() -{ +ClientOptions HTTPFileSource::Impl::getClientOptions() { return m_clientOptions.clone(); } HTTPFileSource::HTTPFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) - : impl(std::make_unique(resourceOptions, clientOptions)) { -} + : impl(std::make_unique(resourceOptions, clientOptions)) {} HTTPFileSource::~HTTPFileSource() = default; -std::unique_ptr HTTPFileSource::request(const Resource& resource, Callback callback) -{ +std::unique_ptr HTTPFileSource::request(const Resource& resource, Callback callback) { return std::make_unique(impl.get(), resource, callback); } @@ -148,5 +137,4 @@ ClientOptions HTTPFileSource::getClientOptions() { return impl->getClientOptions(); } - } // namespace mbgl diff --git a/platform/qt/src/mbgl/http_file_source.hpp b/platform/qt/src/mbgl/http_file_source.hpp index 156c7e7f162..7ed59526f08 100644 --- a/platform/qt/src/mbgl/http_file_source.hpp +++ b/platform/qt/src/mbgl/http_file_source.hpp @@ -18,12 +18,11 @@ namespace mbgl { class HTTPRequest; -class HTTPFileSource::Impl : public QObject -{ +class HTTPFileSource::Impl : public QObject { Q_OBJECT public: - Impl(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions); + Impl(const ResourceOptions &resourceOptions, const ClientOptions &clientOptions); virtual ~Impl() = default; void request(HTTPRequest *); diff --git a/platform/qt/src/mbgl/http_request.cpp b/platform/qt/src/mbgl/http_request.cpp index ed33403a8cb..3f302c72cf1 100644 --- a/platform/qt/src/mbgl/http_request.cpp +++ b/platform/qt/src/mbgl/http_request.cpp @@ -14,42 +14,36 @@ namespace mbgl { HTTPRequest::HTTPRequest(HTTPFileSource::Impl* context, const Resource& resource, FileSource::Callback callback) - : m_context(context) - , m_resource(resource) - , m_callback(callback) -{ + : m_context(context), + m_resource(resource), + m_callback(callback) { m_context->request(this); } -HTTPRequest::~HTTPRequest() -{ +HTTPRequest::~HTTPRequest() { if (!m_handled) { m_context->cancel(this); } } -QUrl HTTPRequest::requestUrl() const -{ +QUrl HTTPRequest::requestUrl() const { return QUrl::fromPercentEncoding(QByteArray(m_resource.url.data(), static_cast(m_resource.url.size()))); } -QNetworkRequest HTTPRequest::networkRequest() const -{ +QNetworkRequest HTTPRequest::networkRequest() const { QNetworkRequest req = QNetworkRequest(requestUrl()); req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); - static const QByteArray agent = !m_context->getClientOptions().name().empty() - ? QString("%1/%2 (%3) MapLibreGL/%4 (Qt %5)") - .arg(QString::fromStdString(m_context->getClientOptions().name())) - .arg(QString::fromStdString(m_context->getClientOptions().version())) - .arg(QSysInfo::prettyProductName()) - .arg(version::revision) - .arg(QT_VERSION_STR) - .toLatin1() - : QString("MapLibreGL/%1 (Qt %2)") - .arg(version::revision) - .arg(QT_VERSION_STR) - .toLatin1(); + static const QByteArray agent = + !m_context->getClientOptions().name().empty() + ? QString("%1/%2 (%3) MapLibreGL/%4 (Qt %5)") + .arg(QString::fromStdString(m_context->getClientOptions().name())) + .arg(QString::fromStdString(m_context->getClientOptions().version())) + .arg(QSysInfo::prettyProductName()) + .arg(version::revision) + .arg(QT_VERSION_STR) + .toLatin1() + : QString("MapLibreGL/%1 (Qt %2)").arg(version::revision).arg(QT_VERSION_STR).toLatin1(); req.setRawHeader("User-Agent", agent); if (m_resource.priorEtag) { @@ -62,8 +56,7 @@ QNetworkRequest HTTPRequest::networkRequest() const return req; } -void HTTPRequest::handleNetworkReply(QNetworkReply *reply, const QByteArray& data) -{ +void HTTPRequest::handleNetworkReply(QNetworkReply* reply, const QByteArray& data) { m_handled = true; // Calling `callback` may result in deleting `this`. @@ -75,8 +68,7 @@ void HTTPRequest::handleNetworkReply(QNetworkReply *reply, const QByteArray& dat // Handle non-HTTP errors (i.e. like connection). if (reply->error() && reply->error() < 100) { - response.error = std::make_unique( - Error::Reason::Connection, reply->errorString().toStdString()); + response.error = std::make_unique(Error::Reason::Connection, reply->errorString().toStdString()); callback(response); return; } @@ -84,7 +76,7 @@ void HTTPRequest::handleNetworkReply(QNetworkReply *reply, const QByteArray& dat QPair line; std::optional retryAfter; std::optional xRateLimitReset; - foreach(line, reply->rawHeaderPairs()) { + foreach (line, reply->rawHeaderPairs()) { QString header = QString(line.first).toLower(); if (header == "last-modified") { @@ -116,41 +108,39 @@ void HTTPRequest::handleNetworkReply(QNetworkReply *reply, const QByteArray& dat int responseCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - switch(responseCode) { - case 200: { - if (data.isEmpty()) { - response.data = std::make_shared(); - } else { - response.data = std::make_shared(data.constData(), data.size()); + switch (responseCode) { + case 200: { + if (data.isEmpty()) { + response.data = std::make_shared(); + } else { + response.data = std::make_shared(data.constData(), data.size()); + } + break; } - break; - } - case 204: - response.noContent = true; - break; - case 304: - response.notModified = true; - break; - case 404: { - if (m_resource.kind == Resource::Kind::Tile) { + case 204: response.noContent = true; - } else { - response.error = std::make_unique( - Error::Reason::NotFound, "HTTP status code 404"); + break; + case 304: + response.notModified = true; + break; + case 404: { + if (m_resource.kind == Resource::Kind::Tile) { + response.noContent = true; + } else { + response.error = std::make_unique(Error::Reason::NotFound, "HTTP status code 404"); + } + break; } - break; - } - case 429: - response.error = std::make_unique( - Error::Reason::RateLimit, "HTTP status code 429", - http::parseRetryHeaders(retryAfter, xRateLimitReset)); - break; - default: - Response::Error::Reason reason = (responseCode >= 500 && responseCode < 600) ? - Error::Reason::Server : Error::Reason::Other; - - response.error = std::make_unique( - reason, "HTTP status code " + util::toString(responseCode)); + case 429: + response.error = std::make_unique( + Error::Reason::RateLimit, "HTTP status code 429", http::parseRetryHeaders(retryAfter, xRateLimitReset) + ); + break; + default: + Response::Error::Reason reason = (responseCode >= 500 && responseCode < 600) ? Error::Reason::Server + : Error::Reason::Other; + + response.error = std::make_unique(reason, "HTTP status code " + util::toString(responseCode)); } callback(response); diff --git a/platform/qt/src/mbgl/http_request.hpp b/platform/qt/src/mbgl/http_request.hpp index 2e760fc8d56..5486b686caf 100644 --- a/platform/qt/src/mbgl/http_request.hpp +++ b/platform/qt/src/mbgl/http_request.hpp @@ -12,16 +12,15 @@ namespace mbgl { class Response; -class HTTPRequest : public AsyncRequest -{ +class HTTPRequest : public AsyncRequest { public: - HTTPRequest(HTTPFileSource::Impl *, const Resource&, FileSource::Callback); + HTTPRequest(HTTPFileSource::Impl*, const Resource&, FileSource::Callback); virtual ~HTTPRequest(); QUrl requestUrl() const; QNetworkRequest networkRequest() const; - void handleNetworkReply(QNetworkReply *, const QByteArray& data); + void handleNetworkReply(QNetworkReply*, const QByteArray& data); private: HTTPFileSource::Impl* m_context; diff --git a/platform/qt/src/mbgl/image.cpp b/platform/qt/src/mbgl/image.cpp index 59816a65585..a4a69a494f8 100644 --- a/platform/qt/src/mbgl/image.cpp +++ b/platform/qt/src/mbgl/image.cpp @@ -7,8 +7,7 @@ namespace mbgl { std::string encodePNG(const PremultipliedImage& pre) { - QImage image(pre.data.get(), pre.size.width, pre.size.height, - QImage::Format_ARGB32_Premultiplied); + QImage image(pre.data.get(), pre.size.width, pre.size.height, QImage::Format_ARGB32_Premultiplied); QByteArray array; QBuffer buffer(&array); @@ -36,10 +35,9 @@ PremultipliedImage decodeImage(const std::string& string) { } #endif - QImage image = - QImage::fromData(data, static_cast(size)) - .rgbSwapped() - .convertToFormat(QImage::Format_ARGB32_Premultiplied); + QImage image = QImage::fromData(data, static_cast(size)) + .rgbSwapped() + .convertToFormat(QImage::Format_ARGB32_Premultiplied); if (image.isNull()) { throw std::runtime_error("Unsupported image type"); @@ -53,7 +51,6 @@ PremultipliedImage decodeImage(const std::string& string) { memcpy(img.get(), image.constBits(), image.byteCount()); #endif - return { { static_cast(image.width()), static_cast(image.height()) }, - std::move(img) }; -} + return {{static_cast(image.width()), static_cast(image.height())}, std::move(img)}; } +} // namespace mbgl diff --git a/platform/qt/src/mbgl/local_glyph_rasterizer.cpp b/platform/qt/src/mbgl/local_glyph_rasterizer.cpp index 8cadb54b09b..3a3e7c278c0 100644 --- a/platform/qt/src/mbgl/local_glyph_rasterizer.cpp +++ b/platform/qt/src/mbgl/local_glyph_rasterizer.cpp @@ -21,7 +21,8 @@ class LocalGlyphRasterizer::Impl { std::optional metrics; }; -LocalGlyphRasterizer::Impl::Impl(const std::optional& fontFamily_) : fontFamily(fontFamily_) { +LocalGlyphRasterizer::Impl::Impl(const std::optional& fontFamily_) + : fontFamily(fontFamily_) { if (isConfigured()) { font.setFamily(QString::fromStdString(*fontFamily)); font.setPixelSize(util::ONE_EM); @@ -36,11 +37,11 @@ bool LocalGlyphRasterizer::Impl::isConfigured() const { LocalGlyphRasterizer::LocalGlyphRasterizer(const std::optional& fontFamily) : impl(std::make_unique(fontFamily)) {} -LocalGlyphRasterizer::~LocalGlyphRasterizer() { -} +LocalGlyphRasterizer::~LocalGlyphRasterizer() {} bool LocalGlyphRasterizer::canRasterizeGlyph(const FontStack&, GlyphID glyphID) { - return impl->isConfigured() && impl->metrics->inFont(glyphID) && util::i18n::allowsFixedWidthGlyphGeneration(glyphID); + return impl->isConfigured() && impl->metrics->inFont(glyphID) && + util::i18n::allowsFixedWidthGlyphGeneration(glyphID); } Glyph LocalGlyphRasterizer::rasterizeGlyph(const FontStack&, GlyphID glyphID) { @@ -80,7 +81,7 @@ Glyph LocalGlyphRasterizer::rasterizeGlyph(const FontStack&, GlyphID glyphID) { memcpy(img.get(), image.constBits(), image.byteCount()); #endif - glyph.bitmap = AlphaImage { size, std::move(img) }; + glyph.bitmap = AlphaImage{size, std::move(img)}; return glyph; } diff --git a/platform/qt/src/mbgl/number_format.cpp b/platform/qt/src/mbgl/number_format.cpp index b6fe3558e6f..bc5c21f7141 100644 --- a/platform/qt/src/mbgl/number_format.cpp +++ b/platform/qt/src/mbgl/number_format.cpp @@ -6,9 +6,13 @@ namespace mbgl { namespace platform { -std::string formatNumber(double number, const std::string& localeId, const std::string& currency, - uint8_t minFractionDigits, uint8_t maxFractionDigits) { - +std::string formatNumber( + double number, + const std::string& localeId, + const std::string& currency, + uint8_t minFractionDigits, + uint8_t maxFractionDigits +) { QString formatted; // Qt Locale::toString() API takes only one precision argument (void)minFractionDigits; diff --git a/platform/qt/src/mbgl/run_loop.cpp b/platform/qt/src/mbgl/run_loop.cpp index 7394fc7bc28..6bd9cb035c5 100644 --- a/platform/qt/src/mbgl/run_loop.cpp +++ b/platform/qt/src/mbgl/run_loop.cpp @@ -24,14 +24,15 @@ RunLoop* RunLoop::Get() { return static_cast(Scheduler::GetCurrent()); } -RunLoop::RunLoop(Type type) : impl(std::make_unique()) { +RunLoop::RunLoop(Type type) + : impl(std::make_unique()) { switch (type) { - case Type::New: - impl->loop = std::make_unique(); - break; - case Type::Default: - // Use QCoreApplication::instance(). - break; + case Type::New: + impl->loop = std::make_unique(); + break; + case Type::Default: + // Use QCoreApplication::instance(). + break; } impl->type = type; @@ -119,5 +120,5 @@ void RunLoop::removeWatch(int fd) { } } -} -} +} // namespace util +} // namespace mbgl diff --git a/platform/qt/src/mbgl/sqlite3.cpp b/platform/qt/src/mbgl/sqlite3.cpp index b3f5abdb394..15ba0a75dfd 100644 --- a/platform/qt/src/mbgl/sqlite3.cpp +++ b/platform/qt/src/mbgl/sqlite3.cpp @@ -26,30 +26,28 @@ namespace sqlite { void checkQueryError(const QSqlQuery& query) { QSqlError lastError = query.lastError(); if (lastError.type() != QSqlError::NoError) { - throw Exception { lastError.nativeErrorCode().toInt(), lastError.databaseText().toStdString() }; + throw Exception{lastError.nativeErrorCode().toInt(), lastError.databaseText().toStdString()}; } } -void checkDatabaseError(const QSqlDatabase &db) { +void checkDatabaseError(const QSqlDatabase& db) { QSqlError lastError = db.lastError(); if (lastError.type() != QSqlError::NoError) { - throw Exception { lastError.nativeErrorCode().toInt(), lastError.databaseText().toStdString() }; + throw Exception{lastError.nativeErrorCode().toInt(), lastError.databaseText().toStdString()}; } } namespace { - QString incrementCounter() { - static QAtomicInt count = 0; - return QString::number(count.fetchAndAddAcquire(1)); - } +QString incrementCounter() { + static QAtomicInt count = 0; + return QString::number(count.fetchAndAddAcquire(1)); } +} // namespace class DatabaseImpl { public: DatabaseImpl(QString connectionName_) - : connectionName(std::move(connectionName_)) - { - } + : connectionName(std::move(connectionName_)) {} ~DatabaseImpl() { auto db = QSqlDatabase::database(connectionName); @@ -65,24 +63,23 @@ class DatabaseImpl { class StatementImpl { public: - StatementImpl(const QString& sql, const QSqlDatabase& db) : query(db) { + StatementImpl(const QString& sql, const QSqlDatabase& db) + : query(db) { if (!query.prepare(sql)) { checkQueryError(query); } } - ~StatementImpl() { - query.clear(); - } + ~StatementImpl() { query.clear(); } QSqlQuery query; int64_t lastInsertRowId = 0; int64_t changes = 0; }; -mapbox::util::variant Database::tryOpen(const std::string &filename, int flags) { +mapbox::util::variant Database::tryOpen(const std::string& filename, int flags) { if (!QSqlDatabase::drivers().contains("QSQLITE")) { - return Exception { ResultCode::CantOpen, "SQLite driver not found." }; + return Exception{ResultCode::CantOpen, "SQLite driver not found."}; } QString connectionName = QString::number(uint64_t(QThread::currentThread())) + incrementCounter(); @@ -107,13 +104,13 @@ mapbox::util::variant Database::tryOpen(const std::string & if (!db.open()) { // Assume every error when opening the data as CANTOPEN. Qt // always returns -1 for `nativeErrorCode()` on database errors. - return Exception { ResultCode::CantOpen, "Error opening the database." }; + return Exception{ResultCode::CantOpen, "Error opening the database."}; } return Database(std::make_unique(connectionName)); } -Database Database::open(const std::string &filename, int flags) { +Database Database::open(const std::string& filename, int flags) { auto result = tryOpen(filename, flags); if (result.is()) { throw result.get(); @@ -123,22 +120,20 @@ Database Database::open(const std::string &filename, int flags) { } Database::Database(std::unique_ptr impl_) - : impl(std::move(impl_)) -{} + : impl(std::move(impl_)) {} -Database::Database(Database &&other) noexcept - : impl(std::move(other.impl)) { +Database::Database(Database&& other) noexcept + : impl(std::move(other.impl)) { assert(impl); } -Database &Database::operator=(Database &&other) noexcept { +Database& Database::operator=(Database&& other) noexcept { std::swap(impl, other.impl); assert(impl); return *this; } -Database::~Database() { -} +Database::~Database() {} void Database::setBusyTimeout(std::chrono::milliseconds timeout) { assert(impl); @@ -163,11 +158,11 @@ void DatabaseImpl::setBusyTimeout(std::chrono::milliseconds timeout) { if (!db.open()) { // Assume every error when opening the data as CANTOPEN. Qt // always returns -1 for `nativeErrorCode()` on database errors. - throw Exception { ResultCode::CantOpen, "Error opening the database." }; + throw Exception{ResultCode::CantOpen, "Error opening the database."}; } } -void Database::exec(const std::string &sql) { +void Database::exec(const std::string& sql) { assert(impl); impl->exec(sql); } @@ -193,8 +188,7 @@ void DatabaseImpl::exec(const std::string& sql) { } Statement::Statement(Database& db, const char* sql) - : impl(std::make_unique(QString(sql), - QSqlDatabase::database(db.impl->connectionName))) { + : impl(std::make_unique(QString(sql), QSqlDatabase::database(db.impl->connectionName))) { assert(impl); } @@ -205,7 +199,8 @@ Statement::~Statement() { #endif } -Query::Query(Statement& stmt_) : stmt(stmt_) { +Query::Query(Statement& stmt_) + : stmt(stmt_) { assert(stmt.impl); #ifndef NDEBUG @@ -314,8 +309,11 @@ void Query::bindBlob(int offset, const void* value_, std::size_t length, bool re } // Field numbering starts at 0. - stmt.impl->query.bindValue(offset - 1, retain ? QByteArray(value, static_cast(length)) : - QByteArray::fromRawData(value, static_cast(length)), QSql::In | QSql::Binary); + stmt.impl->query.bindValue( + offset - 1, + retain ? QByteArray(value, static_cast(length)) : QByteArray::fromRawData(value, static_cast(length)), + QSql::In | QSql::Binary + ); checkQueryError(stmt.impl->query); } @@ -328,12 +326,12 @@ bool Query::run() { assert(stmt.impl); if (!stmt.impl->query.isValid()) { - if (stmt.impl->query.exec()) { - stmt.impl->lastInsertRowId = stmt.impl->query.lastInsertId().value(); - stmt.impl->changes = stmt.impl->query.numRowsAffected(); - } else { - checkQueryError(stmt.impl->query); - } + if (stmt.impl->query.exec()) { + stmt.impl->lastInsertRowId = stmt.impl->query.lastInsertId().value(); + stmt.impl->changes = stmt.impl->query.numRowsAffected(); + } else { + checkQueryError(stmt.impl->query); + } } const bool hasNext = stmt.impl->query.next(); @@ -347,14 +345,16 @@ template int Query::get(int); template int64_t Query::get(int); template double Query::get(int); -template T Query::get(int offset) { +template +T Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); return value.value(); } -template <> std::vector Query::get(int offset) { +template <> +std::vector Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QByteArray byteArray = stmt.impl->query.value(offset).toByteArray(); checkQueryError(stmt.impl->query); @@ -362,56 +362,59 @@ template <> std::vector Query::get(int offset) { return blob; } -template <> mbgl::Timestamp Query::get(int offset) { +template <> +mbgl::Timestamp Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); return std::chrono::time_point_cast( - std::chrono::system_clock::from_time_t(value.value<::time_t>())); + std::chrono::system_clock::from_time_t(value.value<::time_t>()) + ); } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); - if (value.isNull()) - return {}; - return { value.value() }; + if (value.isNull()) return {}; + return {value.value()}; } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); - if (value.isNull()) - return {}; - return { value.value() }; + if (value.isNull()) return {}; + return {value.value()}; } -template <> std::string Query::get(int offset) { +template <> +std::string Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QByteArray value = stmt.impl->query.value(offset).toByteArray(); checkQueryError(stmt.impl->query); return std::string(value.constData(), value.size()); } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QByteArray value = stmt.impl->query.value(offset).toByteArray(); checkQueryError(stmt.impl->query); - if (value.isNull()) - return {}; - return { std::string(value.constData(), value.size()) }; + if (value.isNull()) return {}; + return {std::string(value.constData(), value.size())}; } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); - if (value.isNull()) - return {}; - return { std::chrono::time_point_cast( - std::chrono::system_clock::from_time_t(value.value<::time_t>())) }; + if (value.isNull()) return {}; + return { + std::chrono::time_point_cast(std::chrono::system_clock::from_time_t(value.value<::time_t>()))}; } void Query::reset() { @@ -436,15 +439,15 @@ uint64_t Query::changes() const { Transaction::Transaction(Database& db_, Mode mode) : dbImpl(*db_.impl) { switch (mode) { - case Deferred: - dbImpl.exec("BEGIN DEFERRED TRANSACTION"); - break; - case Immediate: - dbImpl.exec("BEGIN IMMEDIATE TRANSACTION"); - break; - case Exclusive: - dbImpl.exec("BEGIN EXCLUSIVE TRANSACTION"); - break; + case Deferred: + dbImpl.exec("BEGIN DEFERRED TRANSACTION"); + break; + case Immediate: + dbImpl.exec("BEGIN IMMEDIATE TRANSACTION"); + break; + case Exclusive: + dbImpl.exec("BEGIN EXCLUSIVE TRANSACTION"); + break; } } diff --git a/platform/qt/src/mbgl/thread.cpp b/platform/qt/src/mbgl/thread.cpp index 6c7d14042d5..cee03b252bf 100644 --- a/platform/qt/src/mbgl/thread.cpp +++ b/platform/qt/src/mbgl/thread.cpp @@ -10,19 +10,15 @@ std::string getCurrentThreadName() { return "unknown"; } -void setCurrentThreadName(const std::string&) { -} +void setCurrentThreadName(const std::string&) {} -void makeThreadLowPriority() { -} +void makeThreadLowPriority() {} void setCurrentThreadPriority(double) {} -void attachThread() { -} +void attachThread() {} -void detachThread() { -} +void detachThread() {} } // namespace platform } // namespace mbgl diff --git a/platform/qt/src/mbgl/thread_local.cpp b/platform/qt/src/mbgl/thread_local.cpp index 60b1d038959..12d2f59f929 100644 --- a/platform/qt/src/mbgl/thread_local.cpp +++ b/platform/qt/src/mbgl/thread_local.cpp @@ -31,7 +31,7 @@ void* ThreadLocalBase::get() { } void ThreadLocalBase::set(void* ptr) { - reinterpret_cast(storage).setLocalData({{ ptr }}); + reinterpret_cast(storage).setLocalData({{ptr}}); } } // namespace impl diff --git a/platform/qt/src/mbgl/timer.cpp b/platform/qt/src/mbgl/timer.cpp index e7e1195c0d2..b7a5b085361 100644 --- a/platform/qt/src/mbgl/timer.cpp +++ b/platform/qt/src/mbgl/timer.cpp @@ -13,7 +13,7 @@ Timer::Impl::Impl() { connect(&timer, &QTimer::timeout, this, &Timer::Impl::timerFired); } -void Timer::Impl::start(uint64_t timeout, uint64_t repeat_, std::function&& cb) { +void Timer::Impl::start(uint64_t timeout, uint64_t repeat_, std::function&& cb) { repeat = repeat_; callback = std::move(cb); @@ -43,20 +43,21 @@ void Timer::Impl::timerFired() { } Timer::Timer() - : impl(std::make_unique()) { -} + : impl(std::make_unique()) {} Timer::~Timer() = default; void Timer::start(Duration timeout, Duration repeat, std::function&& cb) { - impl->start(std::chrono::duration_cast(timeout).count(), - std::chrono::duration_cast(repeat).count(), - std::move(cb)); + impl->start( + std::chrono::duration_cast(timeout).count(), + std::chrono::duration_cast(repeat).count(), + std::move(cb) + ); } void Timer::stop() { impl->stop(); } -} -} +} // namespace util +} // namespace mbgl diff --git a/platform/qt/src/mbgl/timer_impl.hpp b/platform/qt/src/mbgl/timer_impl.hpp index ea22b20974e..c5d73e12af6 100644 --- a/platform/qt/src/mbgl/timer_impl.hpp +++ b/platform/qt/src/mbgl/timer_impl.hpp @@ -14,7 +14,7 @@ class Timer::Impl : public QObject { public: Impl(); - void start(uint64_t timeout, uint64_t repeat, std::function &&); + void start(uint64_t timeout, uint64_t repeat, std::function &&); void stop(); public slots: diff --git a/platform/qt/src/settings.cpp b/platform/qt/src/settings.cpp index 91dfb98bfd5..76b32718467 100644 --- a/platform/qt/src/settings.cpp +++ b/platform/qt/src/settings.cpp @@ -10,31 +10,61 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4805) +#pragma warning(disable : 4805) #endif // mbgl::GLContextMode -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::UniqueGLContext) == mbgl::underlying_type(mbgl::gfx::ContextMode::Unique), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::SharedGLContext) == mbgl::underlying_type(mbgl::gfx::ContextMode::Shared), "error"); +static_assert( + mbgl::underlying_type(QMapLibreGL::Settings::UniqueGLContext) == + mbgl::underlying_type(mbgl::gfx::ContextMode::Unique), + "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Settings::SharedGLContext) == + mbgl::underlying_type(mbgl::gfx::ContextMode::Shared), + "error" +); // mbgl::MapMode -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::Continuous) == mbgl::underlying_type(mbgl::MapMode::Continuous), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::Static) == mbgl::underlying_type(mbgl::MapMode::Static), "error"); +static_assert( + mbgl::underlying_type(QMapLibreGL::Settings::Continuous) == mbgl::underlying_type(mbgl::MapMode::Continuous), + "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Settings::Static) == mbgl::underlying_type(mbgl::MapMode::Static), "error" +); // mbgl::ConstrainMode -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::NoConstrain) == mbgl::underlying_type(mbgl::ConstrainMode::None), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::ConstrainHeightOnly) == mbgl::underlying_type(mbgl::ConstrainMode::HeightOnly), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::ConstrainWidthAndHeight) == mbgl::underlying_type(mbgl::ConstrainMode::WidthAndHeight), "error"); +static_assert( + mbgl::underlying_type(QMapLibreGL::Settings::NoConstrain) == mbgl::underlying_type(mbgl::ConstrainMode::None), + "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Settings::ConstrainHeightOnly) == + mbgl::underlying_type(mbgl::ConstrainMode::HeightOnly), + "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Settings::ConstrainWidthAndHeight) == + mbgl::underlying_type(mbgl::ConstrainMode::WidthAndHeight), + "error" +); // mbgl::ViewportMode -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::DefaultViewport) == mbgl::underlying_type(mbgl::ViewportMode::Default), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::FlippedYViewport) == mbgl::underlying_type(mbgl::ViewportMode::FlippedY), "error"); +static_assert( + mbgl::underlying_type(QMapLibreGL::Settings::DefaultViewport) == mbgl::underlying_type(mbgl::ViewportMode::Default), + "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Settings::FlippedYViewport) == + mbgl::underlying_type(mbgl::ViewportMode::FlippedY), + "error" +); #ifdef _MSC_VER #pragma warning(pop) #endif - namespace QMapLibreGL { /*! @@ -125,17 +155,15 @@ namespace QMapLibreGL { configuration is valid for initializing a QMapLibreGL::Map. */ Settings::Settings() - : m_contextMode(Settings::SharedGLContext) - , m_mapMode(Settings::Continuous) - , m_constrainMode(Settings::ConstrainHeightOnly) - , m_viewportMode(Settings::DefaultViewport) - , m_cacheMaximumSize(mbgl::util::DEFAULT_MAX_CACHE_SIZE) - , m_cacheDatabasePath(":memory:") - , m_assetPath(QCoreApplication::applicationDirPath()) - , m_apiKey(qgetenv("MLN_API_KEY")) - , m_tileServerOptionsInternal(new mbgl::TileServerOptions(mbgl::TileServerOptions::DefaultConfiguration())) -{ -} + : m_contextMode(Settings::SharedGLContext), + m_mapMode(Settings::Continuous), + m_constrainMode(Settings::ConstrainHeightOnly), + m_viewportMode(Settings::DefaultViewport), + m_cacheMaximumSize(mbgl::util::DEFAULT_MAX_CACHE_SIZE), + m_cacheDatabasePath(":memory:"), + m_assetPath(QCoreApplication::applicationDirPath()), + m_apiKey(qgetenv("MLN_API_KEY")), + m_tileServerOptionsInternal(new mbgl::TileServerOptions(mbgl::TileServerOptions::DefaultConfiguration())) {} /*! Returns the OpenGL context mode. This is specially important when mixing @@ -143,16 +171,14 @@ Settings::Settings() By default, it is set to Settings::SharedGLContext. */ -Settings::GLContextMode Settings::contextMode() const -{ +Settings::GLContextMode Settings::contextMode() const { return m_contextMode; } /*! Sets the OpenGL context \a mode. */ -void Settings::setContextMode(GLContextMode mode) -{ +void Settings::setContextMode(GLContextMode mode) { m_contextMode = mode; } @@ -168,16 +194,14 @@ void Settings::setContextMode(GLContextMode mode) By default, it is set to QMapLibreGL::Settings::Continuous. */ -Settings::MapMode Settings::mapMode() const -{ +Settings::MapMode Settings::mapMode() const { return m_mapMode; } /*! Sets the map \a mode. */ -void Settings::setMapMode(MapMode mode) -{ +void Settings::setMapMode(MapMode mode) { m_mapMode = mode; } @@ -187,16 +211,14 @@ void Settings::setMapMode(MapMode mode) By default, it is set to QMapLibreGL::Settings::ConstrainHeightOnly. */ -Settings::ConstrainMode Settings::constrainMode() const -{ +Settings::ConstrainMode Settings::constrainMode() const { return m_constrainMode; } /*! Sets the map constrain \a mode. */ -void Settings::setConstrainMode(ConstrainMode mode) -{ +void Settings::setConstrainMode(ConstrainMode mode) { m_constrainMode = mode; } @@ -206,16 +228,14 @@ void Settings::setConstrainMode(ConstrainMode mode) By default, it is set to QMapLibreGL::Settings::DefaultViewport. */ -Settings::ViewportMode Settings::viewportMode() const -{ +Settings::ViewportMode Settings::viewportMode() const { return m_viewportMode; } /*! Sets the viewport \a mode. */ -void Settings::setViewportMode(ViewportMode mode) -{ +void Settings::setViewportMode(ViewportMode mode) { m_viewportMode = mode; } @@ -227,16 +247,14 @@ void Settings::setViewportMode(ViewportMode mode) By default, it is set to 50 MB. */ -unsigned Settings::cacheDatabaseMaximumSize() const -{ +unsigned Settings::cacheDatabaseMaximumSize() const { return m_cacheMaximumSize; } /*! Returns the maximum allowed cache database \a size in bytes. */ -void Settings::setCacheDatabaseMaximumSize(unsigned size) -{ +void Settings::setCacheDatabaseMaximumSize(unsigned size) { m_cacheMaximumSize = size; } @@ -250,8 +268,7 @@ void Settings::setCacheDatabaseMaximumSize(unsigned size) By default, it is set to \c :memory: meaning it will create an in-memory cache instead of a file on disk. */ -QString Settings::cacheDatabasePath() const -{ +QString Settings::cacheDatabasePath() const { return m_cacheDatabasePath; } @@ -260,8 +277,7 @@ QString Settings::cacheDatabasePath() const Setting the \a path to \c :memory: will create an in-memory cache. */ -void Settings::setCacheDatabasePath(const QString &path) -{ +void Settings::setCacheDatabasePath(const QString &path) { m_cacheDatabasePath = path; } @@ -273,16 +289,14 @@ void Settings::setCacheDatabasePath(const QString &path) By default, it is set to the value returned by QCoreApplication::applicationDirPath(). */ -QString Settings::assetPath() const -{ +QString Settings::assetPath() const { return m_assetPath; } /*! Sets the asset \a path. */ -void Settings::setAssetPath(const QString &path) -{ +void Settings::setAssetPath(const QString &path) { m_assetPath = path; } @@ -302,16 +316,14 @@ QString Settings::apiKey() const { MapTiler-hosted and Mapbox-hosted vector tiles and styles require an API key or access token. */ -void Settings::setApiKey(const QString &key) -{ +void Settings::setApiKey(const QString &key) { m_apiKey = key; } /*! Returns the API base URL. */ -QString Settings::apiBaseUrl() const -{ +QString Settings::apiBaseUrl() const { return QString::fromStdString(m_tileServerOptionsInternal->baseURL()); } @@ -322,16 +334,14 @@ QString Settings::apiBaseUrl() const be resolved to. It defaults to "https://api.mapbox.com" but can be changed, for instance, to a tile cache server address. */ -void Settings::setApiBaseUrl(const QString& url) -{ +void Settings::setApiBaseUrl(const QString &url) { m_tileServerOptionsInternal = &m_tileServerOptionsInternal->withBaseURL(url.toStdString()); } /*! Returns the local font family. Returns an empty string if no local font family is set. */ -QString Settings::localFontFamily() const -{ +QString Settings::localFontFamily() const { return m_localFontFamily; } @@ -343,40 +353,35 @@ QString Settings::localFontFamily() const localIdeographFontFamily setting to speed up map load times by using locally available fonts instead of font data fetched from the server. */ -void Settings::setLocalFontFamily(const QString &family) -{ +void Settings::setLocalFontFamily(const QString &family) { m_localFontFamily = family; } /*! Returns the client name. Returns an empty string if no client name is set. */ -QString Settings::clientName() const -{ +QString Settings::clientName() const { return m_clientName; } /*! Sets the client name. */ -void Settings::setClientName(const QString &name) -{ +void Settings::setClientName(const QString &name) { m_clientName = name; } /*! Returns the client version. Returns an empty string if no client version is set. */ -QString Settings::clientVersion() const -{ +QString Settings::clientVersion() const { return m_clientVersion; } /*! Sets the client version. */ -void Settings::setClientVersion(const QString &version) -{ +void Settings::setClientVersion(const QString &version) { m_clientVersion = version; } @@ -407,17 +412,16 @@ void Settings::setResourceTransform(const std::function > Settings::defaultStyles() const { +QVector> Settings::defaultStyles() const { QVector> styles; for (const auto &style : tileServerOptionsInternal()->defaultStyles()) { - styles.append(QPair( - QString::fromStdString(style.getUrl()), QString::fromStdString(style.getName()))); + styles.append( + QPair(QString::fromStdString(style.getUrl()), QString::fromStdString(style.getName())) + ); } return styles; } diff --git a/platform/qt/src/types.cpp b/platform/qt/src/types.cpp index b766e255344..3a9aa563a36 100644 --- a/platform/qt/src/types.cpp +++ b/platform/qt/src/types.cpp @@ -4,9 +4,17 @@ #include "mbgl/util/traits.hpp" // mbgl::FeatureType -static_assert(mbgl::underlying_type(QMapLibreGL::Feature::PointType) == mbgl::underlying_type(mbgl::FeatureType::Point), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Feature::LineStringType) == mbgl::underlying_type(mbgl::FeatureType::LineString), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Feature::PolygonType) == mbgl::underlying_type(mbgl::FeatureType::Polygon), "error"); +static_assert( + mbgl::underlying_type(QMapLibreGL::Feature::PointType) == mbgl::underlying_type(mbgl::FeatureType::Point), "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Feature::LineStringType) == mbgl::underlying_type(mbgl::FeatureType::LineString), + "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Feature::PolygonType) == mbgl::underlying_type(mbgl::FeatureType::Polygon), + "error" +); namespace QMapLibreGL { diff --git a/platform/qt/src/utils.cpp b/platform/qt/src/utils.cpp index e27769728f2..f0dac8d4e39 100644 --- a/platform/qt/src/utils.cpp +++ b/platform/qt/src/utils.cpp @@ -8,8 +8,12 @@ #include // mbgl::NetworkStatus::Status -static_assert(mbgl::underlying_type(QMapLibreGL::Online) == mbgl::underlying_type(mbgl::NetworkStatus::Status::Online), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Offline) == mbgl::underlying_type(mbgl::NetworkStatus::Status::Offline), "error"); +static_assert( + mbgl::underlying_type(QMapLibreGL::Online) == mbgl::underlying_type(mbgl::NetworkStatus::Status::Online), "error" +); +static_assert( + mbgl::underlying_type(QMapLibreGL::Offline) == mbgl::underlying_type(mbgl::NetworkStatus::Status::Offline), "error" +); namespace QMapLibreGL { @@ -27,8 +31,7 @@ namespace QMapLibreGL { Returns the current QMapLibreGL::NetworkMode. */ -NetworkMode networkMode() -{ +NetworkMode networkMode() { return static_cast(mbgl::NetworkStatus::Get()); } @@ -40,34 +43,32 @@ NetworkMode networkMode() File source requests uses the available network when \a mode is set to \b Online, otherwise scoped to the local cache. */ -void setNetworkMode(NetworkMode mode) -{ +void setNetworkMode(NetworkMode mode) { mbgl::NetworkStatus::Set(static_cast(mode)); } /*! Returns the amount of meters per pixel from a given \a latitude and \a zoom. */ -double metersPerPixelAtLatitude(double latitude, double zoom) -{ +double metersPerPixelAtLatitude(double latitude, double zoom) { return mbgl::Projection::getMetersPerPixelAtLatitude(latitude, zoom); } /*! Return the projected meters for a given \a coordinate object. */ -ProjectedMeters projectedMetersForCoordinate(const Coordinate &coordinate) -{ - auto projectedMeters = mbgl::Projection::projectedMetersForLatLng(mbgl::LatLng { coordinate.first, coordinate.second }); +ProjectedMeters projectedMetersForCoordinate(const Coordinate &coordinate) { + auto projectedMeters = mbgl::Projection::projectedMetersForLatLng(mbgl::LatLng{coordinate.first, coordinate.second} + ); return ProjectedMeters(projectedMeters.northing(), projectedMeters.easting()); } /*! Returns the coordinate for a given \a projectedMeters object. */ -Coordinate coordinateForProjectedMeters(const ProjectedMeters &projectedMeters) -{ - auto latLng = mbgl::Projection::latLngForProjectedMeters(mbgl::ProjectedMeters { projectedMeters.first, projectedMeters.second }); +Coordinate coordinateForProjectedMeters(const ProjectedMeters &projectedMeters) { + auto latLng = mbgl::Projection::latLngForProjectedMeters(mbgl::ProjectedMeters{ + projectedMeters.first, projectedMeters.second}); return Coordinate(latLng.latitude(), latLng.longitude()); } diff --git a/platform/qt/src/utils/conversion.hpp b/platform/qt/src/utils/conversion.hpp index 678588e6e47..9bd5ec46a4f 100644 --- a/platform/qt/src/utils/conversion.hpp +++ b/platform/qt/src/utils/conversion.hpp @@ -16,14 +16,12 @@ namespace mbgl { namespace style { namespace conversion { -std::string convertColor(const QColor &color); +std::string convertColor(const QColor& color); template <> class ConversionTraits { public: - static bool isUndefined(const QVariant& value) { - return value.isNull() || !value.isValid(); - } + static bool isUndefined(const QVariant& value) { return value.isNull() || !value.isValid(); } static bool isArray(const QVariant& value) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) @@ -43,16 +41,15 @@ class ConversionTraits { static bool isObject(const QVariant& value) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - return QMetaType::canConvert(value.metaType(), QMetaType(QMetaType::QVariantMap)) - || value.typeId() == QMetaType::QByteArray + return QMetaType::canConvert(value.metaType(), QMetaType(QMetaType::QVariantMap)) || + value.typeId() == QMetaType::QByteArray #else - return value.canConvert(QVariant::Map) - || value.type() == QVariant::ByteArray + return value.canConvert(QVariant::Map) || value.type() == QVariant::ByteArray #endif - || QString(value.typeName()) == QStringLiteral("QMapLibreGL::Feature") - || value.userType() == qMetaTypeId>() - || value.userType() == qMetaTypeId>() - || value.userType() == qMetaTypeId>(); + || QString(value.typeName()) == QStringLiteral("QMapLibreGL::Feature") || + value.userType() == qMetaTypeId>() || + value.userType() == qMetaTypeId>() || + value.userType() == qMetaTypeId>(); } static std::optional objectMember(const QVariant& value, const char* key) { @@ -142,29 +139,29 @@ class ConversionTraits { static std::optional toValue(const QVariant& value) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) if (value.typeId() == QMetaType::Bool) { - return { value.toBool() }; + return {value.toBool()}; } else if (value.typeId() == QMetaType::QString) { - return { value.toString().toStdString() }; + return {value.toString().toStdString()}; } else if (value.typeId() == QMetaType::QColor) { - return { convertColor(value.value()) }; + return {convertColor(value.value())}; } else if (value.typeId() == QMetaType::Int) { - return { int64_t(value.toInt()) }; + return {int64_t(value.toInt())}; } else if (QMetaType::canConvert(value.metaType(), QMetaType(QMetaType::Double))) { - return { value.toDouble() }; + return {value.toDouble()}; } else { return {}; } #else if (value.type() == QVariant::Bool) { - return { value.toBool() }; + return {value.toBool()}; } else if (value.type() == QVariant::String) { - return { value.toString().toStdString() }; + return {value.toString().toStdString()}; } else if (value.type() == QVariant::Color) { - return { convertColor(value.value()) }; + return {convertColor(value.value())}; } else if (value.type() == QVariant::Int) { - return { int64_t(value.toInt()) }; + return {int64_t(value.toInt())}; } else if (value.canConvert(QVariant::Double)) { - return { value.toDouble() }; + return {value.toDouble()}; } else { return {}; } @@ -173,7 +170,7 @@ class ConversionTraits { static std::optional toGeoJSON(const QVariant& value, Error& error) { if (value.typeName() == QStringLiteral("QMapLibreGL::Feature")) { - return GeoJSON { QMapLibreGL::GeoJSON::asFeature(value.value()) }; + return GeoJSON{QMapLibreGL::GeoJSON::asFeature(value.value())}; } else if (value.userType() == qMetaTypeId>()) { return featureCollectionToGeoJSON(value.value>()); } else if (value.userType() == qMetaTypeId>()) { @@ -185,7 +182,7 @@ class ConversionTraits { #else } else if (value.type() != QVariant::ByteArray) { #endif - error = { "JSON data must be in QByteArray" }; + error = {"JSON data must be in QByteArray"}; return {}; } @@ -194,25 +191,25 @@ class ConversionTraits { } private: - template - static GeoJSON featureCollectionToGeoJSON(const T &features) { + template + static GeoJSON featureCollectionToGeoJSON(const T& features) { mapbox::feature::feature_collection collection; collection.reserve(static_cast(features.size())); - for (const auto &feature : features) { + for (const auto& feature : features) { collection.push_back(QMapLibreGL::GeoJSON::asFeature(feature)); } - return GeoJSON { std::move(collection) }; + return GeoJSON{std::move(collection)}; } }; -template -std::optional convert(const QVariant& value, Error& error, Args&&...args) { +template +std::optional convert(const QVariant& value, Error& error, Args&&... args) { return convert(Convertible(value), error, std::forward(args)...); } -inline std::string convertColor(const QColor &color) { - return QString::asprintf("rgba(%d,%d,%d,%lf)", - color.red(), color.green(), color.blue(), color.alphaF()).toStdString(); +inline std::string convertColor(const QColor& color) { + return QString::asprintf("rgba(%d,%d,%d,%lf)", color.red(), color.green(), color.blue(), color.alphaF()) + .toStdString(); } } // namespace conversion diff --git a/platform/qt/src/utils/geojson.cpp b/platform/qt/src/utils/geojson.cpp index a37e51520e1..6b438e5583d 100644 --- a/platform/qt/src/utils/geojson.cpp +++ b/platform/qt/src/utils/geojson.cpp @@ -5,13 +5,13 @@ namespace QMapLibreGL::GeoJSON { mbgl::Point asPoint(const Coordinate &coordinate) { - return mbgl::Point { coordinate.second, coordinate.first }; + return mbgl::Point{coordinate.second, coordinate.first}; } mbgl::MultiPoint asMultiPoint(const Coordinates &multiPoint) { mbgl::MultiPoint mbglMultiPoint; mbglMultiPoint.reserve(multiPoint.size()); - for (const auto &point: multiPoint) { + for (const auto &point : multiPoint) { mbglMultiPoint.emplace_back(asPoint(point)); } return mbglMultiPoint; @@ -41,7 +41,7 @@ mbgl::Polygon asPolygon(const CoordinatesCollection &polygon) { for (const auto &linearRing : polygon) { mbgl::LinearRing mbglLinearRing; mbglLinearRing.reserve(linearRing.size()); - for (const auto &coordinate: linearRing) { + for (const auto &coordinate : linearRing) { mbglLinearRing.emplace_back(asPoint(coordinate)); } mbglPolygon.emplace_back(std::move(mbglLinearRing)); @@ -62,7 +62,7 @@ mbgl::Value asPropertyValue(const QVariant &value) { auto valueList = [](const QVariantList &list) { std::vector mbglList; mbglList.reserve(list.size()); - for (const auto& listValue : list) { + for (const auto &listValue : list) { mbglList.emplace_back(asPropertyValue(listValue)); } return mbglList; @@ -82,25 +82,25 @@ mbgl::Value asPropertyValue(const QVariant &value) { #else switch (static_cast(value.type())) { #endif - case QMetaType::UnknownType: - return mbgl::NullValue {}; - case QMetaType::Bool: - return { value.toBool() }; - case QMetaType::ULongLong: - return { uint64_t(value.toULongLong()) }; - case QMetaType::LongLong: - return { int64_t(value.toLongLong()) }; - case QMetaType::Double: - return { value.toDouble() }; - case QMetaType::QString: - return { value.toString().toStdString() }; - case QMetaType::QVariantList: - return valueList(value.toList()); - case QMetaType::QVariantMap: - return valueMap(value.toMap()); - default: - qWarning() << "Unsupported feature property value:" << value; - return {}; + case QMetaType::UnknownType: + return mbgl::NullValue{}; + case QMetaType::Bool: + return {value.toBool()}; + case QMetaType::ULongLong: + return {uint64_t(value.toULongLong())}; + case QMetaType::LongLong: + return {int64_t(value.toLongLong())}; + case QMetaType::Double: + return {value.toDouble()}; + case QMetaType::QString: + return {value.toString().toStdString()}; + case QMetaType::QVariantList: + return valueList(value.toList()); + case QMetaType::QVariantMap: + return valueMap(value.toMap()); + default: + qWarning() << "Unsupported feature property value:" << value; + return {}; } } @@ -110,19 +110,19 @@ mbgl::FeatureIdentifier asFeatureIdentifier(const QVariant &id) { #else switch (static_cast(id.type())) { #endif - case QMetaType::UnknownType: - return {}; - case QMetaType::ULongLong: - return { uint64_t(id.toULongLong()) }; - case QMetaType::LongLong: - return { int64_t(id.toLongLong()) }; - case QMetaType::Double: - return { id.toDouble() }; - case QMetaType::QString: - return { id.toString().toStdString() }; - default: - qWarning() << "Unsupported feature identifier:" << id; - return {}; + case QMetaType::UnknownType: + return {}; + case QMetaType::ULongLong: + return {uint64_t(id.toULongLong())}; + case QMetaType::LongLong: + return {int64_t(id.toLongLong())}; + case QMetaType::Double: + return {id.toDouble()}; + case QMetaType::QString: + return {id.toString().toStdString()}; + default: + qWarning() << "Unsupported feature identifier:" << id; + return {}; } } @@ -138,23 +138,23 @@ mbgl::GeoJSONFeature asFeature(const Feature &feature) { if (feature.type == Feature::PointType) { const Coordinates &points = feature.geometry.first().first(); if (points.size() == 1) { - return { asPoint(points.first()), std::move(properties), std::move(id) }; + return {asPoint(points.first()), std::move(properties), std::move(id)}; } else { - return { asMultiPoint(points), std::move(properties), std::move(id) }; + return {asMultiPoint(points), std::move(properties), std::move(id)}; } } else if (feature.type == Feature::LineStringType) { const CoordinatesCollection &lineStrings = feature.geometry.first(); if (lineStrings.size() == 1) { - return { asLineString(lineStrings.first()), std::move(properties), std::move(id) }; + return {asLineString(lineStrings.first()), std::move(properties), std::move(id)}; } else { - return { asMultiLineString(lineStrings), std::move(properties), std::move(id) }; + return {asMultiLineString(lineStrings), std::move(properties), std::move(id)}; } } else { // PolygonType const CoordinatesCollections &polygons = feature.geometry; if (polygons.size() == 1) { - return { asPolygon(polygons.first()), std::move(properties), std::move(id) }; + return {asPolygon(polygons.first()), std::move(properties), std::move(id)}; } else { - return { asMultiPolygon(polygons), std::move(properties), std::move(id) }; + return {asMultiPolygon(polygons), std::move(properties), std::move(id)}; } } }; diff --git a/platform/qt/src/utils/map_observer.cpp b/platform/qt/src/utils/map_observer.cpp index 3773d6544a2..f153df5bb51 100644 --- a/platform/qt/src/utils/map_observer.cpp +++ b/platform/qt/src/utils/map_observer.cpp @@ -8,17 +8,12 @@ namespace QMapLibreGL { -MapObserver::MapObserver(MapPrivate *d) - : d_ptr(d) -{ -} +MapObserver::MapObserver(MapPrivate* d) + : d_ptr(d) {} -MapObserver::~MapObserver() -{ -} +MapObserver::~MapObserver() {} -void MapObserver::onCameraWillChange(mbgl::MapObserver::CameraChangeMode mode) -{ +void MapObserver::onCameraWillChange(mbgl::MapObserver::CameraChangeMode mode) { if (mode == mbgl::MapObserver::CameraChangeMode::Immediate) { emit mapChanged(Map::MapChangeRegionWillChange); } else { @@ -26,13 +21,11 @@ void MapObserver::onCameraWillChange(mbgl::MapObserver::CameraChangeMode mode) } } -void MapObserver::onCameraIsChanging() -{ +void MapObserver::onCameraIsChanging() { emit mapChanged(Map::MapChangeRegionIsChanging); } -void MapObserver::onCameraDidChange(mbgl::MapObserver::CameraChangeMode mode) -{ +void MapObserver::onCameraDidChange(mbgl::MapObserver::CameraChangeMode mode) { if (mode == mbgl::MapObserver::CameraChangeMode::Immediate) { emit mapChanged(Map::MapChangeRegionDidChange); } else { @@ -40,18 +33,15 @@ void MapObserver::onCameraDidChange(mbgl::MapObserver::CameraChangeMode mode) } } -void MapObserver::onWillStartLoadingMap() -{ +void MapObserver::onWillStartLoadingMap() { emit mapChanged(Map::MapChangeWillStartLoadingMap); } -void MapObserver::onDidFinishLoadingMap() -{ +void MapObserver::onDidFinishLoadingMap() { emit mapChanged(Map::MapChangeDidFinishLoadingMap); } -void MapObserver::onDidFailLoadingMap(mbgl::MapLoadError error, const std::string& what) -{ +void MapObserver::onDidFailLoadingMap(mbgl::MapLoadError error, const std::string& what) { emit mapChanged(Map::MapChangeDidFailLoadingMap); Map::MapLoadingFailure type; @@ -74,13 +64,11 @@ void MapObserver::onDidFailLoadingMap(mbgl::MapLoadError error, const std::strin emit mapLoadingFailed(type, description); } -void MapObserver::onWillStartRenderingFrame() -{ +void MapObserver::onWillStartRenderingFrame() { emit mapChanged(Map::MapChangeWillStartRenderingFrame); } -void MapObserver::onDidFinishRenderingFrame(mbgl::MapObserver::RenderFrameStatus status) -{ +void MapObserver::onDidFinishRenderingFrame(mbgl::MapObserver::RenderFrameStatus status) { if (status.mode == mbgl::MapObserver::RenderMode::Partial) { emit mapChanged(Map::MapChangeDidFinishRenderingFrame); } else { @@ -88,13 +76,11 @@ void MapObserver::onDidFinishRenderingFrame(mbgl::MapObserver::RenderFrameStatus } } -void MapObserver::onWillStartRenderingMap() -{ +void MapObserver::onWillStartRenderingMap() { emit mapChanged(Map::MapChangeWillStartRenderingMap); } -void MapObserver::onDidFinishRenderingMap(mbgl::MapObserver::RenderMode mode) -{ +void MapObserver::onDidFinishRenderingMap(mbgl::MapObserver::RenderMode mode) { if (mode == mbgl::MapObserver::RenderMode::Partial) { emit mapChanged(Map::MapChangeDidFinishRenderingMap); } else { @@ -102,13 +88,11 @@ void MapObserver::onDidFinishRenderingMap(mbgl::MapObserver::RenderMode mode) } } -void MapObserver::onDidFinishLoadingStyle() -{ +void MapObserver::onDidFinishLoadingStyle() { emit mapChanged(Map::MapChangeDidFinishLoadingStyle); } -void MapObserver::onSourceChanged(mbgl::style::Source&) -{ +void MapObserver::onSourceChanged(mbgl::style::Source&) { std::string attribution; for (const auto& source : d_ptr->mapObj->getStyle().getSources()) { // Avoid duplicates by using the most complete attribution HTML snippet. diff --git a/platform/qt/src/utils/map_observer.hpp b/platform/qt/src/utils/map_observer.hpp index c45387d56be..4ab0b960209 100644 --- a/platform/qt/src/utils/map_observer.hpp +++ b/platform/qt/src/utils/map_observer.hpp @@ -14,8 +14,7 @@ namespace QMapLibreGL { class MapPrivate; -class MapObserver : public QObject, public mbgl::MapObserver -{ +class MapObserver : public QObject, public mbgl::MapObserver { Q_OBJECT public: @@ -28,13 +27,13 @@ class MapObserver : public QObject, public mbgl::MapObserver void onCameraDidChange(mbgl::MapObserver::CameraChangeMode) final; void onWillStartLoadingMap() final; void onDidFinishLoadingMap() final; - void onDidFailLoadingMap(mbgl::MapLoadError, const std::string&) final; + void onDidFailLoadingMap(mbgl::MapLoadError, const std::string &) final; void onWillStartRenderingFrame() final; void onDidFinishRenderingFrame(mbgl::MapObserver::RenderFrameStatus) final; void onWillStartRenderingMap() final; void onDidFinishRenderingMap(mbgl::MapObserver::RenderMode) final; void onDidFinishLoadingStyle() final; - void onSourceChanged(mbgl::style::Source&) final; + void onSourceChanged(mbgl::style::Source &) final; signals: void mapChanged(Map::MapChange); diff --git a/platform/qt/src/utils/map_renderer.cpp b/platform/qt/src/utils/map_renderer.cpp index b0fced73695..8e8f613ed84 100644 --- a/platform/qt/src/utils/map_renderer.cpp +++ b/platform/qt/src/utils/map_renderer.cpp @@ -29,15 +29,16 @@ static auto *getScheduler() { } // namespace - namespace QMapLibreGL { MapRenderer::MapRenderer(qreal pixelRatio, Settings::GLContextMode mode, const QString &localFontFamily) : m_backend(static_cast(mode)), - m_renderer(std::make_unique(m_backend, pixelRatio, - localFontFamily.isEmpty() ? std::nullopt : std::optional { localFontFamily.toStdString() })) - , m_forceScheduler(needsToForceScheduler()) -{ + m_renderer(std::make_unique( + m_backend, + pixelRatio, + localFontFamily.isEmpty() ? std::nullopt : std::optional{localFontFamily.toStdString()} + )), + m_forceScheduler(needsToForceScheduler()) { // If we don't have a Scheduler on this thread, which // is usually the case for render threads, use a shared // dummy scheduler that needs to be explicitly forced to @@ -53,26 +54,22 @@ MapRenderer::MapRenderer(qreal pixelRatio, Settings::GLContextMode mode, const Q } } -MapRenderer::~MapRenderer() -{ +MapRenderer::~MapRenderer() { MBGL_VERIFY_THREAD(tid); } -void MapRenderer::updateParameters(std::shared_ptr newParameters) -{ +void MapRenderer::updateParameters(std::shared_ptr newParameters) { std::lock_guard lock(m_updateMutex); m_updateParameters = std::move(newParameters); } -void MapRenderer::updateFramebuffer(quint32 fbo, const mbgl::Size &size) -{ +void MapRenderer::updateFramebuffer(quint32 fbo, const mbgl::Size &size) { MBGL_VERIFY_THREAD(tid); m_backend.updateFramebuffer(fbo, size); } -void MapRenderer::render() -{ +void MapRenderer::render() { MBGL_VERIFY_THREAD(tid); std::shared_ptr params; @@ -97,8 +94,7 @@ void MapRenderer::render() } } -void MapRenderer::setObserver(std::shared_ptr observer) -{ +void MapRenderer::setObserver(std::shared_ptr observer) { m_renderer->setObserver(observer.get()); } diff --git a/platform/qt/src/utils/map_renderer.hpp b/platform/qt/src/utils/map_renderer.hpp index e37d384eee2..4b5f0fc5fb0 100644 --- a/platform/qt/src/utils/map_renderer.hpp +++ b/platform/qt/src/utils/map_renderer.hpp @@ -23,8 +23,7 @@ namespace QMapLibreGL { class RendererBackend; -class MapRenderer : public QObject -{ +class MapRenderer : public QObject { Q_OBJECT public: diff --git a/platform/qt/src/utils/renderer_backend.cpp b/platform/qt/src/utils/renderer_backend.cpp index 9ea227ddf7f..c32aa1aa63b 100644 --- a/platform/qt/src/utils/renderer_backend.cpp +++ b/platform/qt/src/utils/renderer_backend.cpp @@ -10,8 +10,8 @@ namespace QMapLibreGL { class RenderableResource final : public mbgl::gl::RenderableResource { public: - RenderableResource(RendererBackend& backend_) : backend(backend_) { - } + RenderableResource(RendererBackend& backend_) + : backend(backend_) {} void bind() override { assert(mbgl::gfx::BackendScope::exists()); @@ -25,8 +25,7 @@ class RenderableResource final : public mbgl::gl::RenderableResource { RendererBackend::RendererBackend(const mbgl::gfx::ContextMode contextMode_) : mbgl::gl::RendererBackend(contextMode_), - mbgl::gfx::Renderable({ 0, 0 }, std::make_unique(*this)) { -} + mbgl::gfx::Renderable({0, 0}, std::make_unique(*this)) {} RendererBackend::~RendererBackend() = default; diff --git a/platform/qt/src/utils/renderer_backend.hpp b/platform/qt/src/utils/renderer_backend.hpp index 678905ad84a..c83c24338cb 100644 --- a/platform/qt/src/utils/renderer_backend.hpp +++ b/platform/qt/src/utils/renderer_backend.hpp @@ -7,8 +7,7 @@ namespace QMapLibreGL { -class RendererBackend final : public mbgl::gl::RendererBackend, - public mbgl::gfx::Renderable { +class RendererBackend final : public mbgl::gl::RendererBackend, public mbgl::gfx::Renderable { public: RendererBackend(mbgl::gfx::ContextMode); ~RendererBackend() override; @@ -18,9 +17,7 @@ class RendererBackend final : public mbgl::gl::RendererBackend, // mbgl::gfx::RendererBackend implementation public: - mbgl::gfx::Renderable& getDefaultRenderable() override { - return *this; - } + mbgl::gfx::Renderable& getDefaultRenderable() override { return *this; } protected: // No-op, implicit mode. diff --git a/platform/qt/src/utils/renderer_observer.hpp b/platform/qt/src/utils/renderer_observer.hpp index 3fd515f9944..29dc29125a2 100644 --- a/platform/qt/src/utils/renderer_observer.hpp +++ b/platform/qt/src/utils/renderer_observer.hpp @@ -15,37 +15,26 @@ namespace QMapLibreGL { class RendererObserver : public mbgl::RendererObserver { public: RendererObserver(mbgl::util::RunLoop& mapRunLoop, mbgl::RendererObserver& delegate_) - : mailbox(std::make_shared(mapRunLoop)) - , delegate(delegate_, mailbox) { - } + : mailbox(std::make_shared(mapRunLoop)), + delegate(delegate_, mailbox) {} - ~RendererObserver() { - mailbox->close(); - } + ~RendererObserver() { mailbox->close(); } - void onInvalidate() final { - delegate.invoke(&mbgl::RendererObserver::onInvalidate); - } + void onInvalidate() final { delegate.invoke(&mbgl::RendererObserver::onInvalidate); } void onResourceError(std::exception_ptr err) final { delegate.invoke(&mbgl::RendererObserver::onResourceError, err); } - void onWillStartRenderingMap() final { - delegate.invoke(&mbgl::RendererObserver::onWillStartRenderingMap); - } + void onWillStartRenderingMap() final { delegate.invoke(&mbgl::RendererObserver::onWillStartRenderingMap); } - void onWillStartRenderingFrame() final { - delegate.invoke(&mbgl::RendererObserver::onWillStartRenderingFrame); - } + void onWillStartRenderingFrame() final { delegate.invoke(&mbgl::RendererObserver::onWillStartRenderingFrame); } void onDidFinishRenderingFrame(RenderMode mode, bool repaintNeeded, bool placementChanged) final { delegate.invoke(&mbgl::RendererObserver::onDidFinishRenderingFrame, mode, repaintNeeded, placementChanged); } - void onDidFinishRenderingMap() final { - delegate.invoke(&mbgl::RendererObserver::onDidFinishRenderingMap); - } + void onDidFinishRenderingMap() final { delegate.invoke(&mbgl::RendererObserver::onDidFinishRenderingMap); } private: std::shared_ptr mailbox{}; diff --git a/platform/qt/src/utils/scheduler.cpp b/platform/qt/src/utils/scheduler.cpp index 4b2c1322510..bcc5e97f1b5 100644 --- a/platform/qt/src/utils/scheduler.cpp +++ b/platform/qt/src/utils/scheduler.cpp @@ -6,12 +6,9 @@ namespace QMapLibreGL { -Scheduler::Scheduler() -{ -} +Scheduler::Scheduler() {} -Scheduler::~Scheduler() -{ +Scheduler::~Scheduler() { MBGL_VERIFY_THREAD(tid); } @@ -24,8 +21,7 @@ void Scheduler::schedule(std::function function) { emit needsProcessing(); } -void Scheduler::processEvents() -{ +void Scheduler::processEvents() { std::queue> taskQueue; { std::unique_lock lock(m_taskQueueMutex); diff --git a/platform/qt/src/utils/scheduler.hpp b/platform/qt/src/utils/scheduler.hpp index 2b69ea769fc..cbe4dfc13c0 100644 --- a/platform/qt/src/utils/scheduler.hpp +++ b/platform/qt/src/utils/scheduler.hpp @@ -11,8 +11,7 @@ namespace QMapLibreGL { -class Scheduler : public QObject, public mbgl::Scheduler -{ +class Scheduler : public QObject, public mbgl::Scheduler { Q_OBJECT public: @@ -36,4 +35,4 @@ class Scheduler : public QObject, public mbgl::Scheduler mapbox::base::WeakPtrFactory weakFactory{this}; }; -} // namepace QMapLibreGL +} // namespace QMapLibreGL diff --git a/platform/qt/test/qmaplibregl.test.cpp b/platform/qt/test/qmaplibregl.test.cpp index b5dd6ea9b76..ef685a36cbe 100644 --- a/platform/qt/test/qmaplibregl.test.cpp +++ b/platform/qt/test/qmaplibregl.test.cpp @@ -10,7 +10,10 @@ #include -QMapLibreGLTest::QMapLibreGLTest() : size(512, 512), fbo((assert(widget.context()->isValid()), widget.makeCurrent(), size)), map(nullptr, settings, size) { +QMapLibreGLTest::QMapLibreGLTest() + : size(512, 512), + fbo((assert(widget.context()->isValid()), widget.makeCurrent(), size)), + map(nullptr, settings, size) { connect(&map, &QMapLibreGL::mapChanged, this, &QMapLibreGLTest::onMapChanged); connect(&map, &QMapLibreGL::needsRendering, this, &QMapLibreGLTest::onNeedsRendering); map.resize(fbo.size()); @@ -42,7 +45,6 @@ void QMapLibreGLTest::onNeedsRendering() { map.render(); } - TEST_F(QMapLibreGLTest, TEST_DISABLED_ON_CI(styleJson)) { QFile f("test/fixtures/resources/style_vector.json"); diff --git a/platform/windows/include/gl_functions_wgl.h b/platform/windows/include/gl_functions_wgl.h index f2b01d7174c..944d7b1d712 100644 --- a/platform/windows/include/gl_functions_wgl.h +++ b/platform/windows/include/gl_functions_wgl.h @@ -280,12 +280,12 @@ PFNWGLGETEXTENSIONSSTRINGEXTPROC wgl_wglGetExtensionsStringEXT = NULL; HMODULE opengl32 = NULL; -typedef PROC (WINAPI * PFNWGLLOADERWGLGETPROCADDRESSPROC) (LPCSTR lpszProc); +typedef PROC(WINAPI* PFNWGLLOADERWGLGETPROCADDRESSPROC)(LPCSTR lpszProc); PFNWGLLOADERWGLGETPROCADDRESSPROC wgl_wglGetProcAddress = NULL; PROC WINAPI wgl_GetProcAddress(LPCSTR procName) { PROC proc = NULL; - proc = wgl_wglGetProcAddress(procName); + proc = wgl_wglGetProcAddress(procName); if (!proc) { proc = GetProcAddress(opengl32, procName); @@ -295,160 +295,164 @@ PROC WINAPI wgl_GetProcAddress(LPCSTR procName) { } void loadWGL() { - if(opengl32) { - return; - } + if (opengl32) { + return; + } - opengl32 = LoadLibraryA("opengl32.dll"); - wgl_wglGetProcAddress = (PFNWGLLOADERWGLGETPROCADDRESSPROC)GetProcAddress(opengl32, "wglGetProcAddress"); + opengl32 = LoadLibraryA("opengl32.dll"); + wgl_wglGetProcAddress = (PFNWGLLOADERWGLGETPROCADDRESSPROC)GetProcAddress(opengl32, "wglGetProcAddress"); /* OpenGL ES 2.0 */ - - wgl_glActiveTexture = (PFNGLACTIVETEXTUREPROC)wgl_GetProcAddress("glActiveTexture"); - wgl_glAttachShader = (PFNGLATTACHSHADERPROC)wgl_GetProcAddress("glAttachShader"); - wgl_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)wgl_GetProcAddress("glBindAttribLocation"); - wgl_glBindBuffer = (PFNGLBINDBUFFERPROC)wgl_GetProcAddress("glBindBuffer"); - wgl_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wgl_GetProcAddress("glBindFramebuffer"); - wgl_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)wgl_GetProcAddress("glBindRenderbuffer"); - wgl_glBindTexture = (PFNGLBINDTEXTUREPROC)wgl_GetProcAddress("glBindTexture"); - wgl_glBlendColor = (PFNGLBLENDCOLORPROC)wgl_GetProcAddress("glBlendColor"); - wgl_glBlendEquation = (PFNGLBLENDEQUATIONPROC)wgl_GetProcAddress("glBlendEquation"); - wgl_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)wgl_GetProcAddress("glBlendEquationSeparate"); - wgl_glBlendFunc = (PFNGLBLENDFUNCPROC)wgl_GetProcAddress("glBlendFunc"); - wgl_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)wgl_GetProcAddress("glBlendFuncSeparate"); - wgl_glBufferData = (PFNGLBUFFERDATAPROC)wgl_GetProcAddress("glBufferData"); - wgl_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)wgl_GetProcAddress("glBufferSubData"); - wgl_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wgl_GetProcAddress("glCheckFramebufferStatus"); - wgl_glClear = (PFNGLCLEARPROC)wgl_GetProcAddress("glClear"); - wgl_glClearColor = (PFNGLCLEARCOLORPROC)wgl_GetProcAddress("glClearColor"); - wgl_glClearDepthf = (PFNGLCLEARDEPTHFPROC)wgl_GetProcAddress("glClearDepthf"); - wgl_glClearStencil = (PFNGLCLEARSTENCILPROC)wgl_GetProcAddress("glClearStencil"); - wgl_glColorMask = (PFNGLCOLORMASKPROC)wgl_GetProcAddress("glColorMask"); - wgl_glCompileShader = (PFNGLCOMPILESHADERPROC)wgl_GetProcAddress("glCompileShader"); - wgl_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)wgl_GetProcAddress("glCompressedTexImage2D"); - wgl_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glCompressedTexSubImage2D"); - wgl_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)wgl_GetProcAddress("glCopyTexImage2D"); - wgl_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glCopyTexSubImage2D"); - wgl_glCreateProgram = (PFNGLCREATEPROGRAMPROC)wgl_GetProcAddress("glCreateProgram"); - wgl_glCreateShader = (PFNGLCREATESHADERPROC)wgl_GetProcAddress("glCreateShader"); - wgl_glCullFace = (PFNGLCULLFACEPROC)wgl_GetProcAddress("glCullFace"); - wgl_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)wgl_GetProcAddress("glDeleteBuffers"); - wgl_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)wgl_GetProcAddress("glDeleteFramebuffers"); - wgl_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wgl_GetProcAddress("glDeleteProgram"); - wgl_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)wgl_GetProcAddress("glDeleteRenderbuffers"); - wgl_glDeleteShader = (PFNGLDELETESHADERPROC)wgl_GetProcAddress("glDeleteShader"); - wgl_glDeleteTextures = (PFNGLDELETETEXTURESPROC)wgl_GetProcAddress("glDeleteTextures"); - wgl_glDepthFunc = (PFNGLDEPTHFUNCPROC)wgl_GetProcAddress("glDepthFunc"); - wgl_glDepthMask = (PFNGLDEPTHMASKPROC)wgl_GetProcAddress("glDepthMask"); - wgl_glDepthRangef = (PFNGLDEPTHRANGEFPROC)wgl_GetProcAddress("glDepthRangef"); - wgl_glDetachShader = (PFNGLDETACHSHADERPROC)wgl_GetProcAddress("glDetachShader"); - wgl_glDisable = (PFNGLDISABLEPROC)wgl_GetProcAddress("glDisable"); - wgl_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)wgl_GetProcAddress("glDisableVertexAttribArray"); - wgl_glDrawArrays = (PFNGLDRAWARRAYSPROC)wgl_GetProcAddress("glDrawArrays"); - wgl_glDrawElements = (PFNGLDRAWELEMENTSPROC)wgl_GetProcAddress("glDrawElements"); - wgl_glEnable = (PFNGLENABLEPROC)wgl_GetProcAddress("glEnable"); - wgl_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)wgl_GetProcAddress("glEnableVertexAttribArray"); - wgl_glFinish = (PFNGLFINISHPROC)wgl_GetProcAddress("glFinish"); - wgl_glFlush = (PFNGLFLUSHPROC)wgl_GetProcAddress("glFlush"); - wgl_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)wgl_GetProcAddress("glFramebufferRenderbuffer"); - wgl_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wgl_GetProcAddress("glFramebufferTexture2D"); - wgl_glFrontFace = (PFNGLFRONTFACEPROC)wgl_GetProcAddress("glFrontFace"); - wgl_glGenBuffers = (PFNGLGENBUFFERSPROC)wgl_GetProcAddress("glGenBuffers"); - wgl_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)wgl_GetProcAddress("glGenerateMipmap"); - wgl_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wgl_GetProcAddress("glGenFramebuffers"); - wgl_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)wgl_GetProcAddress("glGenRenderbuffers"); - wgl_glGenTextures = (PFNGLGENTEXTURESPROC)wgl_GetProcAddress("glGenTextures"); - wgl_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)wgl_GetProcAddress("glGetActiveAttrib"); - wgl_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)wgl_GetProcAddress("glGetActiveUniform"); - wgl_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)wgl_GetProcAddress("glGetAttachedShaders"); - wgl_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)wgl_GetProcAddress("glGetAttribLocation"); - wgl_glGetBooleanv = (PFNGLGETBOOLEANVPROC)wgl_GetProcAddress("glGetBooleanv"); - wgl_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)wgl_GetProcAddress("glGetBufferParameteriv"); - wgl_glGetError = (PFNGLGETERRORPROC)wgl_GetProcAddress("glGetError"); - wgl_glGetFloatv = (PFNGLGETFLOATVPROC)wgl_GetProcAddress("glGetFloatv"); - wgl_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)wgl_GetProcAddress("glGetFramebufferAttachmentParameteriv"); - wgl_glGetIntegerv = (PFNGLGETINTEGERVPROC)wgl_GetProcAddress("glGetIntegerv"); - wgl_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)wgl_GetProcAddress("glGetProgramInfoLog"); - wgl_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)wgl_GetProcAddress("glGetProgramiv"); - wgl_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)wgl_GetProcAddress("glGetRenderbufferParameteriv"); - wgl_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wgl_GetProcAddress("glGetShaderInfoLog"); - wgl_glGetShaderiv = (PFNGLGETSHADERIVPROC)wgl_GetProcAddress("glGetShaderiv"); - wgl_glGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)wgl_GetProcAddress("glGetShaderPrecisionFormat"); - wgl_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)wgl_GetProcAddress("glGetShaderSource"); - wgl_glGetString = (PFNGLGETSTRINGPROC)wgl_GetProcAddress("glGetString"); - wgl_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)wgl_GetProcAddress("glGetTexParameterfv"); - wgl_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)wgl_GetProcAddress("glGetTexParameteriv"); - wgl_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)wgl_GetProcAddress("glGetUniformfv"); - wgl_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)wgl_GetProcAddress("glGetUniformiv"); - wgl_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)wgl_GetProcAddress("glGetUniformLocation"); - wgl_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)wgl_GetProcAddress("glGetVertexAttribfv"); - wgl_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)wgl_GetProcAddress("glGetVertexAttribiv"); - wgl_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)wgl_GetProcAddress("glGetVertexAttribPointerv"); - wgl_glHint = (PFNGLHINTPROC)wgl_GetProcAddress("glHint"); - wgl_glIsBuffer = (PFNGLISBUFFERPROC)wgl_GetProcAddress("glIsBuffer"); - wgl_glIsEnabled = (PFNGLISENABLEDPROC)wgl_GetProcAddress("glIsEnabled"); - wgl_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)wgl_GetProcAddress("glIsFramebuffer"); - wgl_glIsProgram = (PFNGLISPROGRAMPROC)wgl_GetProcAddress("glIsProgram"); - wgl_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)wgl_GetProcAddress("glIsRenderbuffer"); - wgl_glIsShader = (PFNGLISSHADERPROC)wgl_GetProcAddress("glIsShader"); - wgl_glIsTexture = (PFNGLISTEXTUREPROC)wgl_GetProcAddress("glIsTexture"); - wgl_glLineWidth = (PFNGLLINEWIDTHPROC)wgl_GetProcAddress("glLineWidth"); - wgl_glLinkProgram = (PFNGLLINKPROGRAMPROC)wgl_GetProcAddress("glLinkProgram"); - wgl_glPixelStorei = (PFNGLPIXELSTOREIPROC)wgl_GetProcAddress("glPixelStorei"); - wgl_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)wgl_GetProcAddress("glPolygonOffset"); - wgl_glReadPixels = (PFNGLREADPIXELSPROC)wgl_GetProcAddress("glReadPixels"); + + wgl_glActiveTexture = (PFNGLACTIVETEXTUREPROC)wgl_GetProcAddress("glActiveTexture"); + wgl_glAttachShader = (PFNGLATTACHSHADERPROC)wgl_GetProcAddress("glAttachShader"); + wgl_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)wgl_GetProcAddress("glBindAttribLocation"); + wgl_glBindBuffer = (PFNGLBINDBUFFERPROC)wgl_GetProcAddress("glBindBuffer"); + wgl_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wgl_GetProcAddress("glBindFramebuffer"); + wgl_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)wgl_GetProcAddress("glBindRenderbuffer"); + wgl_glBindTexture = (PFNGLBINDTEXTUREPROC)wgl_GetProcAddress("glBindTexture"); + wgl_glBlendColor = (PFNGLBLENDCOLORPROC)wgl_GetProcAddress("glBlendColor"); + wgl_glBlendEquation = (PFNGLBLENDEQUATIONPROC)wgl_GetProcAddress("glBlendEquation"); + wgl_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)wgl_GetProcAddress("glBlendEquationSeparate"); + wgl_glBlendFunc = (PFNGLBLENDFUNCPROC)wgl_GetProcAddress("glBlendFunc"); + wgl_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)wgl_GetProcAddress("glBlendFuncSeparate"); + wgl_glBufferData = (PFNGLBUFFERDATAPROC)wgl_GetProcAddress("glBufferData"); + wgl_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)wgl_GetProcAddress("glBufferSubData"); + wgl_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wgl_GetProcAddress("glCheckFramebufferStatus"); + wgl_glClear = (PFNGLCLEARPROC)wgl_GetProcAddress("glClear"); + wgl_glClearColor = (PFNGLCLEARCOLORPROC)wgl_GetProcAddress("glClearColor"); + wgl_glClearDepthf = (PFNGLCLEARDEPTHFPROC)wgl_GetProcAddress("glClearDepthf"); + wgl_glClearStencil = (PFNGLCLEARSTENCILPROC)wgl_GetProcAddress("glClearStencil"); + wgl_glColorMask = (PFNGLCOLORMASKPROC)wgl_GetProcAddress("glColorMask"); + wgl_glCompileShader = (PFNGLCOMPILESHADERPROC)wgl_GetProcAddress("glCompileShader"); + wgl_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)wgl_GetProcAddress("glCompressedTexImage2D"); + wgl_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glCompressedTexSubImage2D"); + wgl_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)wgl_GetProcAddress("glCopyTexImage2D"); + wgl_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glCopyTexSubImage2D"); + wgl_glCreateProgram = (PFNGLCREATEPROGRAMPROC)wgl_GetProcAddress("glCreateProgram"); + wgl_glCreateShader = (PFNGLCREATESHADERPROC)wgl_GetProcAddress("glCreateShader"); + wgl_glCullFace = (PFNGLCULLFACEPROC)wgl_GetProcAddress("glCullFace"); + wgl_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)wgl_GetProcAddress("glDeleteBuffers"); + wgl_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)wgl_GetProcAddress("glDeleteFramebuffers"); + wgl_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wgl_GetProcAddress("glDeleteProgram"); + wgl_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)wgl_GetProcAddress("glDeleteRenderbuffers"); + wgl_glDeleteShader = (PFNGLDELETESHADERPROC)wgl_GetProcAddress("glDeleteShader"); + wgl_glDeleteTextures = (PFNGLDELETETEXTURESPROC)wgl_GetProcAddress("glDeleteTextures"); + wgl_glDepthFunc = (PFNGLDEPTHFUNCPROC)wgl_GetProcAddress("glDepthFunc"); + wgl_glDepthMask = (PFNGLDEPTHMASKPROC)wgl_GetProcAddress("glDepthMask"); + wgl_glDepthRangef = (PFNGLDEPTHRANGEFPROC)wgl_GetProcAddress("glDepthRangef"); + wgl_glDetachShader = (PFNGLDETACHSHADERPROC)wgl_GetProcAddress("glDetachShader"); + wgl_glDisable = (PFNGLDISABLEPROC)wgl_GetProcAddress("glDisable"); + wgl_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)wgl_GetProcAddress("glDisableVertexAttribArray" + ); + wgl_glDrawArrays = (PFNGLDRAWARRAYSPROC)wgl_GetProcAddress("glDrawArrays"); + wgl_glDrawElements = (PFNGLDRAWELEMENTSPROC)wgl_GetProcAddress("glDrawElements"); + wgl_glEnable = (PFNGLENABLEPROC)wgl_GetProcAddress("glEnable"); + wgl_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)wgl_GetProcAddress("glEnableVertexAttribArray"); + wgl_glFinish = (PFNGLFINISHPROC)wgl_GetProcAddress("glFinish"); + wgl_glFlush = (PFNGLFLUSHPROC)wgl_GetProcAddress("glFlush"); + wgl_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)wgl_GetProcAddress("glFramebufferRenderbuffer"); + wgl_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wgl_GetProcAddress("glFramebufferTexture2D"); + wgl_glFrontFace = (PFNGLFRONTFACEPROC)wgl_GetProcAddress("glFrontFace"); + wgl_glGenBuffers = (PFNGLGENBUFFERSPROC)wgl_GetProcAddress("glGenBuffers"); + wgl_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)wgl_GetProcAddress("glGenerateMipmap"); + wgl_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wgl_GetProcAddress("glGenFramebuffers"); + wgl_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)wgl_GetProcAddress("glGenRenderbuffers"); + wgl_glGenTextures = (PFNGLGENTEXTURESPROC)wgl_GetProcAddress("glGenTextures"); + wgl_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)wgl_GetProcAddress("glGetActiveAttrib"); + wgl_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)wgl_GetProcAddress("glGetActiveUniform"); + wgl_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)wgl_GetProcAddress("glGetAttachedShaders"); + wgl_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)wgl_GetProcAddress("glGetAttribLocation"); + wgl_glGetBooleanv = (PFNGLGETBOOLEANVPROC)wgl_GetProcAddress("glGetBooleanv"); + wgl_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)wgl_GetProcAddress("glGetBufferParameteriv"); + wgl_glGetError = (PFNGLGETERRORPROC)wgl_GetProcAddress("glGetError"); + wgl_glGetFloatv = (PFNGLGETFLOATVPROC)wgl_GetProcAddress("glGetFloatv"); + wgl_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC + )wgl_GetProcAddress("glGetFramebufferAttachmentParameteriv"); + wgl_glGetIntegerv = (PFNGLGETINTEGERVPROC)wgl_GetProcAddress("glGetIntegerv"); + wgl_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)wgl_GetProcAddress("glGetProgramInfoLog"); + wgl_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)wgl_GetProcAddress("glGetProgramiv"); + wgl_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC + )wgl_GetProcAddress("glGetRenderbufferParameteriv"); + wgl_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wgl_GetProcAddress("glGetShaderInfoLog"); + wgl_glGetShaderiv = (PFNGLGETSHADERIVPROC)wgl_GetProcAddress("glGetShaderiv"); + wgl_glGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)wgl_GetProcAddress("glGetShaderPrecisionFormat" + ); + wgl_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)wgl_GetProcAddress("glGetShaderSource"); + wgl_glGetString = (PFNGLGETSTRINGPROC)wgl_GetProcAddress("glGetString"); + wgl_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)wgl_GetProcAddress("glGetTexParameterfv"); + wgl_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)wgl_GetProcAddress("glGetTexParameteriv"); + wgl_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)wgl_GetProcAddress("glGetUniformfv"); + wgl_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)wgl_GetProcAddress("glGetUniformiv"); + wgl_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)wgl_GetProcAddress("glGetUniformLocation"); + wgl_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)wgl_GetProcAddress("glGetVertexAttribfv"); + wgl_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)wgl_GetProcAddress("glGetVertexAttribiv"); + wgl_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)wgl_GetProcAddress("glGetVertexAttribPointerv"); + wgl_glHint = (PFNGLHINTPROC)wgl_GetProcAddress("glHint"); + wgl_glIsBuffer = (PFNGLISBUFFERPROC)wgl_GetProcAddress("glIsBuffer"); + wgl_glIsEnabled = (PFNGLISENABLEDPROC)wgl_GetProcAddress("glIsEnabled"); + wgl_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)wgl_GetProcAddress("glIsFramebuffer"); + wgl_glIsProgram = (PFNGLISPROGRAMPROC)wgl_GetProcAddress("glIsProgram"); + wgl_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)wgl_GetProcAddress("glIsRenderbuffer"); + wgl_glIsShader = (PFNGLISSHADERPROC)wgl_GetProcAddress("glIsShader"); + wgl_glIsTexture = (PFNGLISTEXTUREPROC)wgl_GetProcAddress("glIsTexture"); + wgl_glLineWidth = (PFNGLLINEWIDTHPROC)wgl_GetProcAddress("glLineWidth"); + wgl_glLinkProgram = (PFNGLLINKPROGRAMPROC)wgl_GetProcAddress("glLinkProgram"); + wgl_glPixelStorei = (PFNGLPIXELSTOREIPROC)wgl_GetProcAddress("glPixelStorei"); + wgl_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)wgl_GetProcAddress("glPolygonOffset"); + wgl_glReadPixels = (PFNGLREADPIXELSPROC)wgl_GetProcAddress("glReadPixels"); wgl_glReleaseShaderCompiler = (PFNGLRELEASESHADERCOMPILERPROC)wgl_GetProcAddress("glReleaseShaderCompiler"); - wgl_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)wgl_GetProcAddress("glRenderbufferStorage"); - wgl_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)wgl_GetProcAddress("glSampleCoverage"); - wgl_glScissor = (PFNGLSCISSORPROC)wgl_GetProcAddress("glScissor"); + wgl_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)wgl_GetProcAddress("glRenderbufferStorage"); + wgl_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)wgl_GetProcAddress("glSampleCoverage"); + wgl_glScissor = (PFNGLSCISSORPROC)wgl_GetProcAddress("glScissor"); wgl_glShaderBinary = (PFNGLSHADERBINARYPROC)wgl_GetProcAddress("glShaderBinary"); - wgl_glShaderSource = (PFNGLSHADERSOURCEPROC)wgl_GetProcAddress("glShaderSource"); - wgl_glStencilFunc = (PFNGLSTENCILFUNCPROC)wgl_GetProcAddress("glStencilFunc"); - wgl_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)wgl_GetProcAddress("glStencilFuncSeparate"); - wgl_glStencilMask = (PFNGLSTENCILMASKPROC)wgl_GetProcAddress("glStencilMask"); - wgl_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)wgl_GetProcAddress("glStencilMaskSeparate"); - wgl_glStencilOp = (PFNGLSTENCILOPPROC)wgl_GetProcAddress("glStencilOp"); - wgl_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)wgl_GetProcAddress("glStencilOpSeparate"); - wgl_glTexImage2D = (PFNGLTEXIMAGE2DPROC)wgl_GetProcAddress("glTexImage2D"); - wgl_glTexParameterf = (PFNGLTEXPARAMETERFPROC)wgl_GetProcAddress("glTexParameterf"); - wgl_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)wgl_GetProcAddress("glTexParameterfv"); - wgl_glTexParameteri = (PFNGLTEXPARAMETERIPROC)wgl_GetProcAddress("glTexParameteri"); - wgl_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)wgl_GetProcAddress("glTexParameteriv"); - wgl_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glTexSubImage2D"); - wgl_glUniform1f = (PFNGLUNIFORM1FPROC)wgl_GetProcAddress("glUniform1f"); - wgl_glUniform1fv = (PFNGLUNIFORM1FVPROC)wgl_GetProcAddress("glUniform1fv"); - wgl_glUniform1i = (PFNGLUNIFORM1IPROC)wgl_GetProcAddress("glUniform1i"); - wgl_glUniform1iv = (PFNGLUNIFORM1IVPROC)wgl_GetProcAddress("glUniform1iv"); - wgl_glUniform2f = (PFNGLUNIFORM2FPROC)wgl_GetProcAddress("glUniform2f"); - wgl_glUniform2fv = (PFNGLUNIFORM2FVPROC)wgl_GetProcAddress("glUniform2fv"); - wgl_glUniform2i = (PFNGLUNIFORM2IPROC)wgl_GetProcAddress("glUniform2i"); - wgl_glUniform2iv = (PFNGLUNIFORM2IVPROC)wgl_GetProcAddress("glUniform2iv"); - wgl_glUniform3f = (PFNGLUNIFORM3FPROC)wgl_GetProcAddress("glUniform3f"); - wgl_glUniform3fv = (PFNGLUNIFORM3FVPROC)wgl_GetProcAddress("glUniform3fv"); - wgl_glUniform3i = (PFNGLUNIFORM3IPROC)wgl_GetProcAddress("glUniform3i"); - wgl_glUniform3iv = (PFNGLUNIFORM3IVPROC)wgl_GetProcAddress("glUniform3iv"); - wgl_glUniform4f = (PFNGLUNIFORM4FPROC)wgl_GetProcAddress("glUniform4f"); - wgl_glUniform4fv = (PFNGLUNIFORM4FVPROC)wgl_GetProcAddress("glUniform4fv"); - wgl_glUniform4i = (PFNGLUNIFORM4IPROC)wgl_GetProcAddress("glUniform4i"); - wgl_glUniform4iv = (PFNGLUNIFORM4IVPROC)wgl_GetProcAddress("glUniform4iv"); - wgl_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)wgl_GetProcAddress("glUniformMatrix2fv"); - wgl_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)wgl_GetProcAddress("glUniformMatrix3fv"); - wgl_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)wgl_GetProcAddress("glUniformMatrix4fv"); - wgl_glUseProgram = (PFNGLUSEPROGRAMPROC)wgl_GetProcAddress("glUseProgram"); - wgl_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)wgl_GetProcAddress("glValidateProgram"); - wgl_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)wgl_GetProcAddress("glVertexAttrib1f"); - wgl_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)wgl_GetProcAddress("glVertexAttrib1fv"); - wgl_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)wgl_GetProcAddress("glVertexAttrib2f"); - wgl_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)wgl_GetProcAddress("glVertexAttrib2fv"); - wgl_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)wgl_GetProcAddress("glVertexAttrib3f"); - wgl_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)wgl_GetProcAddress("glVertexAttrib3fv"); - wgl_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)wgl_GetProcAddress("glVertexAttrib4f"); - wgl_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)wgl_GetProcAddress("glVertexAttrib4fv"); - wgl_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)wgl_GetProcAddress("glVertexAttribPointer"); - wgl_glViewport = (PFNGLVIEWPORTPROC)wgl_GetProcAddress("glViewport"); + wgl_glShaderSource = (PFNGLSHADERSOURCEPROC)wgl_GetProcAddress("glShaderSource"); + wgl_glStencilFunc = (PFNGLSTENCILFUNCPROC)wgl_GetProcAddress("glStencilFunc"); + wgl_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)wgl_GetProcAddress("glStencilFuncSeparate"); + wgl_glStencilMask = (PFNGLSTENCILMASKPROC)wgl_GetProcAddress("glStencilMask"); + wgl_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)wgl_GetProcAddress("glStencilMaskSeparate"); + wgl_glStencilOp = (PFNGLSTENCILOPPROC)wgl_GetProcAddress("glStencilOp"); + wgl_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)wgl_GetProcAddress("glStencilOpSeparate"); + wgl_glTexImage2D = (PFNGLTEXIMAGE2DPROC)wgl_GetProcAddress("glTexImage2D"); + wgl_glTexParameterf = (PFNGLTEXPARAMETERFPROC)wgl_GetProcAddress("glTexParameterf"); + wgl_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)wgl_GetProcAddress("glTexParameterfv"); + wgl_glTexParameteri = (PFNGLTEXPARAMETERIPROC)wgl_GetProcAddress("glTexParameteri"); + wgl_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)wgl_GetProcAddress("glTexParameteriv"); + wgl_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glTexSubImage2D"); + wgl_glUniform1f = (PFNGLUNIFORM1FPROC)wgl_GetProcAddress("glUniform1f"); + wgl_glUniform1fv = (PFNGLUNIFORM1FVPROC)wgl_GetProcAddress("glUniform1fv"); + wgl_glUniform1i = (PFNGLUNIFORM1IPROC)wgl_GetProcAddress("glUniform1i"); + wgl_glUniform1iv = (PFNGLUNIFORM1IVPROC)wgl_GetProcAddress("glUniform1iv"); + wgl_glUniform2f = (PFNGLUNIFORM2FPROC)wgl_GetProcAddress("glUniform2f"); + wgl_glUniform2fv = (PFNGLUNIFORM2FVPROC)wgl_GetProcAddress("glUniform2fv"); + wgl_glUniform2i = (PFNGLUNIFORM2IPROC)wgl_GetProcAddress("glUniform2i"); + wgl_glUniform2iv = (PFNGLUNIFORM2IVPROC)wgl_GetProcAddress("glUniform2iv"); + wgl_glUniform3f = (PFNGLUNIFORM3FPROC)wgl_GetProcAddress("glUniform3f"); + wgl_glUniform3fv = (PFNGLUNIFORM3FVPROC)wgl_GetProcAddress("glUniform3fv"); + wgl_glUniform3i = (PFNGLUNIFORM3IPROC)wgl_GetProcAddress("glUniform3i"); + wgl_glUniform3iv = (PFNGLUNIFORM3IVPROC)wgl_GetProcAddress("glUniform3iv"); + wgl_glUniform4f = (PFNGLUNIFORM4FPROC)wgl_GetProcAddress("glUniform4f"); + wgl_glUniform4fv = (PFNGLUNIFORM4FVPROC)wgl_GetProcAddress("glUniform4fv"); + wgl_glUniform4i = (PFNGLUNIFORM4IPROC)wgl_GetProcAddress("glUniform4i"); + wgl_glUniform4iv = (PFNGLUNIFORM4IVPROC)wgl_GetProcAddress("glUniform4iv"); + wgl_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)wgl_GetProcAddress("glUniformMatrix2fv"); + wgl_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)wgl_GetProcAddress("glUniformMatrix3fv"); + wgl_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)wgl_GetProcAddress("glUniformMatrix4fv"); + wgl_glUseProgram = (PFNGLUSEPROGRAMPROC)wgl_GetProcAddress("glUseProgram"); + wgl_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)wgl_GetProcAddress("glValidateProgram"); + wgl_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)wgl_GetProcAddress("glVertexAttrib1f"); + wgl_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)wgl_GetProcAddress("glVertexAttrib1fv"); + wgl_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)wgl_GetProcAddress("glVertexAttrib2f"); + wgl_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)wgl_GetProcAddress("glVertexAttrib2fv"); + wgl_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)wgl_GetProcAddress("glVertexAttrib3f"); + wgl_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)wgl_GetProcAddress("glVertexAttrib3fv"); + wgl_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)wgl_GetProcAddress("glVertexAttrib4f"); + wgl_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)wgl_GetProcAddress("glVertexAttrib4fv"); + wgl_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)wgl_GetProcAddress("glVertexAttribPointer"); + wgl_glViewport = (PFNGLVIEWPORTPROC)wgl_GetProcAddress("glViewport"); /* OpenGL ES 3.0 */ - + wgl_glReadBuffer = (PFNGLREADBUFFERPROC)wgl_GetProcAddress("glReadBuffer"); wgl_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)wgl_GetProcAddress("glDrawRangeElements"); wgl_glTexImage3D = (PFNGLTEXIMAGE3DPROC)wgl_GetProcAddress("glTexImage3D"); @@ -473,7 +477,8 @@ void loadWGL() { wgl_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)wgl_GetProcAddress("glUniformMatrix3x4fv"); wgl_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)wgl_GetProcAddress("glUniformMatrix4x3fv"); wgl_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)wgl_GetProcAddress("glBlitFramebuffer"); - wgl_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)wgl_GetProcAddress("glRenderbufferStorageMultisample"); + wgl_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC + )wgl_GetProcAddress("glRenderbufferStorageMultisample"); wgl_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)wgl_GetProcAddress("glFramebufferTextureLayer"); wgl_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)wgl_GetProcAddress("glMapBufferRange"); wgl_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)wgl_GetProcAddress("glFlushMappedBufferRange"); @@ -486,8 +491,10 @@ void loadWGL() { wgl_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)wgl_GetProcAddress("glEndTransformFeedback"); wgl_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)wgl_GetProcAddress("glBindBufferRange"); wgl_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)wgl_GetProcAddress("glBindBufferBase"); - wgl_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)wgl_GetProcAddress("glTransformFeedbackVaryings"); - wgl_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)wgl_GetProcAddress("glGetTransformFeedbackVarying"); + wgl_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC + )wgl_GetProcAddress("glTransformFeedbackVaryings"); + wgl_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC + )wgl_GetProcAddress("glGetTransformFeedbackVarying"); wgl_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)wgl_GetProcAddress("glVertexAttribIPointer"); wgl_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)wgl_GetProcAddress("glGetVertexAttribIiv"); wgl_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)wgl_GetProcAddress("glGetVertexAttribIuiv"); @@ -515,7 +522,8 @@ void loadWGL() { wgl_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)wgl_GetProcAddress("glGetActiveUniformsiv"); wgl_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)wgl_GetProcAddress("glGetUniformBlockIndex"); wgl_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)wgl_GetProcAddress("glGetActiveUniformBlockiv"); - wgl_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)wgl_GetProcAddress("glGetActiveUniformBlockName"); + wgl_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC + )wgl_GetProcAddress("glGetActiveUniformBlockName"); wgl_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)wgl_GetProcAddress("glUniformBlockBinding"); wgl_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)wgl_GetProcAddress("glDrawArraysInstanced"); wgl_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)wgl_GetProcAddress("glDrawElementsInstanced"); @@ -540,7 +548,8 @@ void loadWGL() { wgl_glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)wgl_GetProcAddress("glGetSamplerParameterfv"); wgl_glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)wgl_GetProcAddress("glVertexAttribDivisor"); wgl_glBindTransformFeedback = (PFNGLBINDTRANSFORMFEEDBACKPROC)wgl_GetProcAddress("glBindTransformFeedback"); - wgl_glDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)wgl_GetProcAddress("glDeleteTransformFeedbacks"); + wgl_glDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)wgl_GetProcAddress("glDeleteTransformFeedbacks" + ); wgl_glGenTransformFeedbacks = (PFNGLGENTRANSFORMFEEDBACKSPROC)wgl_GetProcAddress("glGenTransformFeedbacks"); wgl_glIsTransformFeedback = (PFNGLISTRANSFORMFEEDBACKPROC)wgl_GetProcAddress("glIsTransformFeedback"); wgl_glPauseTransformFeedback = (PFNGLPAUSETRANSFORMFEEDBACKPROC)wgl_GetProcAddress("glPauseTransformFeedback"); @@ -549,17 +558,19 @@ void loadWGL() { wgl_glProgramBinary = (PFNGLPROGRAMBINARYPROC)wgl_GetProcAddress("glProgramBinary"); wgl_glProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)wgl_GetProcAddress("glProgramParameteri"); wgl_glInvalidateFramebuffer = (PFNGLINVALIDATEFRAMEBUFFERPROC)wgl_GetProcAddress("glInvalidateFramebuffer"); - wgl_glInvalidateSubFramebuffer = (PFNGLINVALIDATESUBFRAMEBUFFERPROC)wgl_GetProcAddress("glInvalidateSubFramebuffer"); + wgl_glInvalidateSubFramebuffer = (PFNGLINVALIDATESUBFRAMEBUFFERPROC)wgl_GetProcAddress("glInvalidateSubFramebuffer" + ); wgl_glTexStorage2D = (PFNGLTEXSTORAGE2DPROC)wgl_GetProcAddress("glTexStorage2D"); wgl_glTexStorage3D = (PFNGLTEXSTORAGE3DPROC)wgl_GetProcAddress("glTexStorage3D"); wgl_glGetInternalformativ = (PFNGLGETINTERNALFORMATIVPROC)wgl_GetProcAddress("glGetInternalformativ"); - + /* OpenGL Windows Extensions */ - - wgl_wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wgl_GetProcAddress("wglChoosePixelFormatARB"); - wgl_wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wgl_GetProcAddress("wglCreateContextAttribsARB"); - wgl_wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wgl_GetProcAddress("wglGetExtensionsStringARB"); - wgl_wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wgl_GetProcAddress("wglGetExtensionsStringEXT"); + + wgl_wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wgl_GetProcAddress("wglChoosePixelFormatARB"); + wgl_wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wgl_GetProcAddress("wglCreateContextAttribsARB" + ); + wgl_wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wgl_GetProcAddress("wglGetExtensionsStringARB"); + wgl_wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wgl_GetProcAddress("wglGetExtensionsStringEXT"); } #ifdef __cplusplus @@ -571,263 +582,1194 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = [](GLenum texture) { if (!opengl32) loadWGL(); ::wgl_glActiveTexture(texture); }; -void (* const glAttachShader)(GLuint, GLuint) = [](GLuint program, GLuint shader) { if (!opengl32) loadWGL(); ::wgl_glAttachShader(program, shader); }; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = [](GLuint program, GLuint index, const GLchar* name) { if (!opengl32) loadWGL(); ::wgl_glBindAttribLocation(program, index, name); }; -void (* const glBindBuffer)(GLenum, GLuint) = [](GLenum target, GLuint buffer) { if (!opengl32) loadWGL(); ::wgl_glBindBuffer(target, buffer); }; -void (* const glBindFramebuffer)(GLenum, GLuint) = [](GLenum target, GLuint framebuffer) { if (!opengl32) loadWGL(); ::wgl_glBindFramebuffer(target, framebuffer); }; -void (* const glBindRenderbuffer)(GLenum, GLuint) = [](GLenum target, GLuint renderbuffer) { if (!opengl32) loadWGL(); ::wgl_glBindRenderbuffer(target, renderbuffer); }; -void (* const glBindTexture)(GLenum, GLuint) = [](GLenum target, GLuint texture) { if (!opengl32) loadWGL(); ::wgl_glBindTexture(target, texture); }; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { if (!opengl32) loadWGL(); ::wgl_glBlendColor(red, green, blue, alpha); }; -void (* const glBlendEquation)(GLenum) = [](GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glBlendEquation(mode); }; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = [](GLenum modeRGB, GLenum modeAlpha) { if (!opengl32) loadWGL(); ::wgl_glBlendEquationSeparate(modeRGB, modeAlpha); }; -void (* const glBlendFunc)(GLenum, GLenum) = [](GLenum sfactor, GLenum dfactor) { if (!opengl32) loadWGL(); ::wgl_glBlendFunc(sfactor, dfactor); }; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = [](GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) { if (!opengl32) loadWGL(); ::wgl_glBlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); }; -void (* const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = [](GLenum target, GLsizeiptr size, const void* data, GLenum usage) { if (!opengl32) loadWGL(); ::wgl_glBufferData(target, size, data, usage); }; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = [](GLenum target, GLintptr offset, GLsizeiptr size, const void* data) { if (!opengl32) loadWGL(); ::wgl_glBufferSubData(target, offset, size, data); }; -GLenum(* const glCheckFramebufferStatus)(GLenum) = [](GLenum target) { if (!opengl32) loadWGL(); return ::wgl_glCheckFramebufferStatus(target); }; -void (* const glClear)(GLbitfield) = [](GLbitfield mask) { if (!opengl32) loadWGL(); ::wgl_glClear(mask); }; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { if (!opengl32) loadWGL(); ::wgl_glClearColor(red, green, blue, alpha); }; -void (* const glClearDepthf)(GLfloat) = [](GLfloat d) { if (!opengl32) loadWGL(); ::wgl_glClearDepthf(d); }; -void (* const glClearStencil)(GLint) = [](GLint s) { if (!opengl32) loadWGL(); ::wgl_glClearStencil(s); }; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = [](GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) { if (!opengl32) loadWGL(); ::wgl_glColorMask(red, green, blue, alpha); }; -void (* const glCompileShader)(GLuint) = [](GLuint shader) { if (!opengl32) loadWGL(); ::wgl_glCompileShader(shader); }; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = [](GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data) { if (!opengl32) loadWGL(); ::wgl_glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); }; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data) { if (!opengl32) loadWGL(); ::wgl_glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); }; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = [](GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) { if (!opengl32) loadWGL(); ::wgl_glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); }; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); }; -GLuint(* const glCreateProgram)() = [](void) { if (!opengl32) loadWGL(); return ::wgl_glCreateProgram(); }; -GLuint(* const glCreateShader)(GLenum) = [](GLenum type) { if (!opengl32) loadWGL(); return ::wgl_glCreateShader(type); }; -void (* const glCullFace)(GLenum) = [](GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glCullFace(mode); }; -void (* const glDeleteBuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* buffers) { if (!opengl32) loadWGL(); ::wgl_glDeleteBuffers(n, buffers); }; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* framebuffers) { if (!opengl32) loadWGL(); ::wgl_glDeleteFramebuffers(n, framebuffers); }; -void (* const glDeleteProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); ::wgl_glDeleteProgram(program); }; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* renderbuffers) { if (!opengl32) loadWGL(); ::wgl_glDeleteRenderbuffers(n, renderbuffers); }; -void (* const glDeleteShader)(GLuint) = [](GLuint shader) { if (!opengl32) loadWGL(); ::wgl_glDeleteShader(shader); }; -void (* const glDeleteTextures)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* textures) { if (!opengl32) loadWGL(); ::wgl_glDeleteTextures(n, textures); }; -void (* const glDepthFunc)(GLenum) = [](GLenum func) { if (!opengl32) loadWGL(); ::wgl_glDepthFunc(func); }; -void (* const glDepthMask)(GLboolean) = [](GLboolean flag) { if (!opengl32) loadWGL(); ::wgl_glDepthMask(flag); }; -void (* const glDepthRangef)(GLfloat, GLfloat) = [](GLfloat n, GLfloat f) { if (!opengl32) loadWGL(); ::wgl_glDepthRangef(n, f); }; -void (* const glDetachShader)(GLuint, GLuint) = [](GLuint program, GLuint shader) { if (!opengl32) loadWGL(); ::wgl_glDetachShader(program, shader); }; -void (* const glDisable)(GLenum) = [](GLenum cap) { if (!opengl32) loadWGL(); ::wgl_glDisable(cap); }; -void (* const glDisableVertexAttribArray)(GLuint) = [](GLuint index) { if (!opengl32) loadWGL(); ::wgl_glDisableVertexAttribArray(index); }; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = [](GLenum mode, GLint first, GLsizei count) { if (!opengl32) loadWGL(); ::wgl_glDrawArrays(mode, first, count); }; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = [](GLenum mode, GLsizei count, GLenum type, const void* indices) { if (!opengl32) loadWGL(); ::wgl_glDrawElements(mode, count, type, indices); }; -void (* const glEnable)(GLenum) = [](GLenum cap) { if (!opengl32) loadWGL(); ::wgl_glEnable(cap); }; -void (* const glEnableVertexAttribArray)(GLuint) = [](GLuint index) { if (!opengl32) loadWGL(); ::wgl_glEnableVertexAttribArray(index); }; -void (* const glFinish)() = [](void) { if (!opengl32) loadWGL(); ::wgl_glFinish(); }; -void (* const glFlush)() = [](void) { if (!opengl32) loadWGL(); ::wgl_glFlush(); }; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = [](GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) { if (!opengl32) loadWGL(); ::wgl_glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); }; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = [](GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) { if (!opengl32) loadWGL(); ::wgl_glFramebufferTexture2D(target, attachment, textarget, texture, level); }; -void (* const glFrontFace)(GLenum) = [](GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glFrontFace(mode); }; -void (* const glGenBuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* buffers) { if (!opengl32) loadWGL(); ::wgl_glGenBuffers(n, buffers); }; -void (* const glGenerateMipmap)(GLenum) = [](GLenum target) { if (!opengl32) loadWGL(); ::wgl_glGenerateMipmap(target); }; -void (* const glGenFramebuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* framebuffers) { if (!opengl32) loadWGL(); ::wgl_glGenFramebuffers(n, framebuffers); }; -void (* const glGenRenderbuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* renderbuffers) { if (!opengl32) loadWGL(); ::wgl_glGenRenderbuffers(n, renderbuffers); }; -void (* const glGenTextures)(GLsizei, GLuint*) = [](GLsizei n, GLuint* textures) { if (!opengl32) loadWGL(); ::wgl_glGenTextures(n, textures); }; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name) { if (!opengl32) loadWGL(); ::wgl_glGetActiveAttrib(program, index, bufSize, length, size, type, name); }; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name) { if (!opengl32) loadWGL(); ::wgl_glGetActiveUniform(program, index, bufSize, length, size, type, name); }; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = [](GLuint program, GLsizei maxCount, GLsizei* count, GLuint* shaders) { if (!opengl32) loadWGL(); ::wgl_glGetAttachedShaders(program, maxCount, count, shaders); }; -GLint(* const glGetAttribLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { if (!opengl32) loadWGL(); return ::wgl_glGetAttribLocation(program, name); }; -void (* const glGetBooleanv)(GLenum, GLboolean*) = [](GLenum pname, GLboolean* data) { if (!opengl32) loadWGL(); ::wgl_glGetBooleanv(pname, data); }; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetBufferParameteriv(target, pname, params); }; -GLenum(* const glGetError)() = [](void) { if (!opengl32) loadWGL(); return ::wgl_glGetError(); }; -void (* const glGetFloatv)(GLenum, GLfloat*) = [](GLenum pname, GLfloat* data) { if (!opengl32) loadWGL(); ::wgl_glGetFloatv(pname, data); }; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint*) = [](GLenum target, GLenum attachment, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetFramebufferAttachmentParameteriv(target, attachment, pname, params); }; -void (* const glGetIntegerv)(GLenum, GLint*) = [](GLenum pname, GLint* data) { if (!opengl32) loadWGL(); ::wgl_glGetIntegerv(pname, data); }; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog) { if (!opengl32) loadWGL(); ::wgl_glGetProgramInfoLog(program, bufSize, length, infoLog); }; -void (* const glGetProgramiv)(GLuint, GLenum, GLint*) = [](GLuint program, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetProgramiv(program, pname, params); }; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetRenderbufferParameteriv(target, pname, params); }; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog) { if (!opengl32) loadWGL(); ::wgl_glGetShaderInfoLog(shader, bufSize, length, infoLog); }; -void (* const glGetShaderiv)(GLuint, GLenum, GLint*) = [](GLuint shader, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetShaderiv(shader, pname, params); }; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = [](GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) { if (!opengl32) loadWGL(); ::wgl_glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision); }; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* source) { if (!opengl32) loadWGL(); ::wgl_glGetShaderSource(shader, bufSize, length, source); }; -const GLubyte* (* const glGetString)(GLenum) = [](GLenum name) { if (!opengl32) loadWGL(); return ::wgl_glGetString(name); }; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = [](GLenum target, GLenum pname, GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glGetTexParameterfv(target, pname, params); }; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetTexParameteriv(target, pname, params); }; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat*) = [](GLuint program, GLint location, GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glGetUniformfv(program, location, params); }; -void (* const glGetUniformiv)(GLuint, GLint, GLint*) = [](GLuint program, GLint location, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetUniformiv(program, location, params); }; -GLint(* const glGetUniformLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { if (!opengl32) loadWGL(); return ::wgl_glGetUniformLocation(program, name); }; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = [](GLuint index, GLenum pname, GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribfv(index, pname, params); }; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = [](GLuint index, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribiv(index, pname, params); }; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = [](GLuint index, GLenum pname, void** pointer) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribPointerv(index, pname, pointer); }; -void (* const glHint)(GLenum, GLenum) = [](GLenum target, GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glHint(target, mode); }; -GLboolean(* const glIsBuffer)(GLuint) = [](GLuint buffer) { if (!opengl32) loadWGL(); return ::wgl_glIsBuffer(buffer); }; -GLboolean(* const glIsEnabled)(GLenum) = [](GLenum cap) { if (!opengl32) loadWGL(); return ::wgl_glIsEnabled(cap); }; -GLboolean(* const glIsFramebuffer)(GLuint) = [](GLuint framebuffer) { if (!opengl32) loadWGL(); return ::wgl_glIsFramebuffer(framebuffer); }; -GLboolean(* const glIsProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); return ::wgl_glIsProgram(program); }; -GLboolean(* const glIsRenderbuffer)(GLuint) = [](GLuint renderbuffer) { if (!opengl32) loadWGL(); return ::wgl_glIsRenderbuffer(renderbuffer); }; -GLboolean(* const glIsShader)(GLuint) = [](GLuint shader) { if (!opengl32) loadWGL(); return ::wgl_glIsShader(shader); }; -GLboolean(* const glIsTexture)(GLuint) = [](GLuint texture) { if (!opengl32) loadWGL(); return ::wgl_glIsTexture(texture); }; -void (* const glLineWidth)(GLfloat) = [](GLfloat width) { if (!opengl32) loadWGL(); ::wgl_glLineWidth(width); }; -void (* const glLinkProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); ::wgl_glLinkProgram(program); }; -void (* const glPixelStorei)(GLenum, GLint) = [](GLenum pname, GLint param) { if (!opengl32) loadWGL(); ::wgl_glPixelStorei(pname, param); }; -void (* const glPolygonOffset)(GLfloat, GLfloat) = [](GLfloat factor, GLfloat units) { if (!opengl32) loadWGL(); ::wgl_glPolygonOffset(factor, units); }; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = [](GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) { if (!opengl32) loadWGL(); ::wgl_glReadPixels(x, y, width, height, format, type, pixels); }; -void (* const glReleaseShaderCompiler)() = []() { if (!opengl32) loadWGL(); ::wgl_glReleaseShaderCompiler(); }; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = [](GLenum target, GLenum internalformat, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glRenderbufferStorage(target, internalformat, width, height); }; -void (* const glSampleCoverage)(GLfloat, GLboolean) = [](GLfloat value, GLboolean invert) { if (!opengl32) loadWGL(); ::wgl_glSampleCoverage(value, invert); }; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = [](GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glScissor(x, y, width, height); }; -void (* const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = [](GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length) { if (!opengl32) loadWGL(); ::wgl_glShaderBinary(n, shaders, binaryformat, binary, length); }; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = [](GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length) { if (!opengl32) loadWGL(); ::wgl_glShaderSource(shader, count, string, length); }; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = [](GLenum func, GLint ref, GLuint mask) { if (!opengl32) loadWGL(); ::wgl_glStencilFunc(func, ref, mask); }; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = [](GLenum face, GLenum func, GLint ref, GLuint mask) { if (!opengl32) loadWGL(); ::wgl_glStencilFuncSeparate(face, func, ref, mask); }; -void (* const glStencilMask)(GLuint) = [](GLuint mask) { if (!opengl32) loadWGL(); ::wgl_glStencilMask(mask); }; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = [](GLenum face, GLuint mask) { if (!opengl32) loadWGL(); ::wgl_glStencilMaskSeparate(face, mask); }; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = [](GLenum fail, GLenum zfail, GLenum zpass) { if (!opengl32) loadWGL(); ::wgl_glStencilOp(fail, zfail, zpass); }; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = [](GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass) { if (!opengl32) loadWGL(); ::wgl_glStencilOpSeparate(face, sfail, dpfail, dppass); }; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = [](GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { if (!opengl32) loadWGL(); ::wgl_glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); }; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = [](GLenum target, GLenum pname, GLfloat param) { if (!opengl32) loadWGL(); ::wgl_glTexParameterf(target, pname, param); }; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = [](GLenum target, GLenum pname, const GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glTexParameterfv(target, pname, params); }; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = [](GLenum target, GLenum pname, GLint param) { if (!opengl32) loadWGL(); ::wgl_glTexParameteri(target, pname, param); }; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint*) = [](GLenum target, GLenum pname, const GLint* params) { if (!opengl32) loadWGL(); ::wgl_glTexParameteriv(target, pname, params); }; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels) { if (!opengl32) loadWGL(); ::wgl_glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); }; -void (* const glUniform1f)(GLint, GLfloat) = [](GLint location, GLfloat v0) { if (!opengl32) loadWGL(); ::wgl_glUniform1f(location, v0); }; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniform1fv(location, count, value); }; -void (* const glUniform1i)(GLint, GLint) = [](GLint location, GLint v0) { if (!opengl32) loadWGL(); ::wgl_glUniform1i(location, v0); }; -void (* const glUniform1iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform1iv(location, count, value); }; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1) { if (!opengl32) loadWGL(); ::wgl_glUniform2f(location, v0, v1); }; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniform2fv(location, count, value); }; -void (* const glUniform2i)(GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1) { if (!opengl32) loadWGL(); ::wgl_glUniform2i(location, v0, v1); }; -void (* const glUniform2iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform2iv(location, count, value); }; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1, GLfloat v2) { if (!opengl32) loadWGL(); ::wgl_glUniform3f(location, v0, v1, v2); }; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniform3fv(location, count, value); }; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1, GLint v2) { if (!opengl32) loadWGL(); ::wgl_glUniform3i(location, v0, v1, v2); }; -void (* const glUniform3iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform3iv(location, count, value); }; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { if (!opengl32) loadWGL(); ::wgl_glUniform4f(location, v0, v1, v2, v3); }; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniform4fv(location, count, value); }; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1, GLint v2, GLint v3) { if (!opengl32) loadWGL(); ::wgl_glUniform4i(location, v0, v1, v2, v3); }; -void (* const glUniform4iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform4iv(location, count, value); }; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix2fv(location, count, transpose, value); }; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix3fv(location, count, transpose, value); }; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix4fv(location, count, transpose, value); }; -void (* const glUseProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); ::wgl_glUseProgram(program); }; -void (* const glValidateProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); ::wgl_glValidateProgram(program); }; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = [](GLuint index, GLfloat x) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib1f(index, x); }; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib1fv(index, v); }; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib2f(index, x, y); }; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib2fv(index, v); }; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y, GLfloat z) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib3f(index, x, y, z); }; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib3fv(index, v); }; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib4f(index, x, y, z, w); }; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib4fv(index, v); }; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = [](GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* pointer) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribPointer(index, size, type, normalized, stride, pointer); }; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = [](GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glViewport(x, y, width, height); }; +void (*const glActiveTexture)(GLenum) = [](GLenum texture) { + if (!opengl32) loadWGL(); + ::wgl_glActiveTexture(texture); +}; +void (*const glAttachShader)(GLuint, GLuint) = [](GLuint program, GLuint shader) { + if (!opengl32) loadWGL(); + ::wgl_glAttachShader(program, shader); +}; +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = [](GLuint program, GLuint index, const GLchar* name + ) { + if (!opengl32) loadWGL(); + ::wgl_glBindAttribLocation(program, index, name); +}; +void (*const glBindBuffer)(GLenum, GLuint) = [](GLenum target, GLuint buffer) { + if (!opengl32) loadWGL(); + ::wgl_glBindBuffer(target, buffer); +}; +void (*const glBindFramebuffer)(GLenum, GLuint) = [](GLenum target, GLuint framebuffer) { + if (!opengl32) loadWGL(); + ::wgl_glBindFramebuffer(target, framebuffer); +}; +void (*const glBindRenderbuffer)(GLenum, GLuint) = [](GLenum target, GLuint renderbuffer) { + if (!opengl32) loadWGL(); + ::wgl_glBindRenderbuffer(target, renderbuffer); +}; +void (*const glBindTexture)(GLenum, GLuint) = [](GLenum target, GLuint texture) { + if (!opengl32) loadWGL(); + ::wgl_glBindTexture(target, texture); +}; +void (*const glBlendColor +)(GLfloat, GLfloat, GLfloat, GLfloat) = [](GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { + if (!opengl32) loadWGL(); + ::wgl_glBlendColor(red, green, blue, alpha); +}; +void (*const glBlendEquation)(GLenum) = [](GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glBlendEquation(mode); +}; +void (*const glBlendEquationSeparate)(GLenum, GLenum) = [](GLenum modeRGB, GLenum modeAlpha) { + if (!opengl32) loadWGL(); + ::wgl_glBlendEquationSeparate(modeRGB, modeAlpha); +}; +void (*const glBlendFunc)(GLenum, GLenum) = [](GLenum sfactor, GLenum dfactor) { + if (!opengl32) loadWGL(); + ::wgl_glBlendFunc(sfactor, dfactor); +}; +void (*const glBlendFuncSeparate +)(GLenum, GLenum, GLenum, GLenum) = [](GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) { + if (!opengl32) loadWGL(); + ::wgl_glBlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); +}; +void (*const glBufferData +)(GLenum, GLsizeiptr, const void*, GLenum) = [](GLenum target, GLsizeiptr size, const void* data, GLenum usage) { + if (!opengl32) loadWGL(); + ::wgl_glBufferData(target, size, data, usage); +}; +void (*const glBufferSubData +)(GLenum, GLintptr, GLsizeiptr, const void*) = [](GLenum target, GLintptr offset, GLsizeiptr size, const void* data) { + if (!opengl32) loadWGL(); + ::wgl_glBufferSubData(target, offset, size, data); +}; +GLenum (*const glCheckFramebufferStatus)(GLenum) = [](GLenum target) { + if (!opengl32) loadWGL(); + return ::wgl_glCheckFramebufferStatus(target); +}; +void (*const glClear)(GLbitfield) = [](GLbitfield mask) { + if (!opengl32) loadWGL(); + ::wgl_glClear(mask); +}; +void (*const glClearColor +)(GLfloat, GLfloat, GLfloat, GLfloat) = [](GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { + if (!opengl32) loadWGL(); + ::wgl_glClearColor(red, green, blue, alpha); +}; +void (*const glClearDepthf)(GLfloat) = [](GLfloat d) { + if (!opengl32) loadWGL(); + ::wgl_glClearDepthf(d); +}; +void (*const glClearStencil)(GLint) = [](GLint s) { + if (!opengl32) loadWGL(); + ::wgl_glClearStencil(s); +}; +void (*const glColorMask +)(GLboolean, GLboolean, GLboolean, GLboolean) = [](GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) { + if (!opengl32) loadWGL(); + ::wgl_glColorMask(red, green, blue, alpha); +}; +void (*const glCompileShader)(GLuint) = [](GLuint shader) { + if (!opengl32) loadWGL(); + ::wgl_glCompileShader(shader); +}; +void (*const glCompressedTexImage2D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = [](GLenum target, + GLint level, + GLenum internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLsizei imageSize, + const void* data) { + if (!opengl32) loadWGL(); + ::wgl_glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); +}; +void (*const glCompressedTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLsizei width, + GLsizei height, + GLenum format, + GLsizei imageSize, + const void* data) { + if (!opengl32) loadWGL(); + ::wgl_glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); +}; +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = + [](GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border + ) { + if (!opengl32) loadWGL(); + ::wgl_glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); + }; +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = + [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); + }; +GLuint (*const glCreateProgram)() = [](void) { + if (!opengl32) loadWGL(); + return ::wgl_glCreateProgram(); +}; +GLuint (*const glCreateShader)(GLenum) = [](GLenum type) { + if (!opengl32) loadWGL(); + return ::wgl_glCreateShader(type); +}; +void (*const glCullFace)(GLenum) = [](GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glCullFace(mode); +}; +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* buffers) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteBuffers(n, buffers); +}; +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* framebuffers) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteFramebuffers(n, framebuffers); +}; +void (*const glDeleteProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteProgram(program); +}; +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* renderbuffers) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteRenderbuffers(n, renderbuffers); +}; +void (*const glDeleteShader)(GLuint) = [](GLuint shader) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteShader(shader); +}; +void (*const glDeleteTextures)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* textures) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteTextures(n, textures); +}; +void (*const glDepthFunc)(GLenum) = [](GLenum func) { + if (!opengl32) loadWGL(); + ::wgl_glDepthFunc(func); +}; +void (*const glDepthMask)(GLboolean) = [](GLboolean flag) { + if (!opengl32) loadWGL(); + ::wgl_glDepthMask(flag); +}; +void (*const glDepthRangef)(GLfloat, GLfloat) = [](GLfloat n, GLfloat f) { + if (!opengl32) loadWGL(); + ::wgl_glDepthRangef(n, f); +}; +void (*const glDetachShader)(GLuint, GLuint) = [](GLuint program, GLuint shader) { + if (!opengl32) loadWGL(); + ::wgl_glDetachShader(program, shader); +}; +void (*const glDisable)(GLenum) = [](GLenum cap) { + if (!opengl32) loadWGL(); + ::wgl_glDisable(cap); +}; +void (*const glDisableVertexAttribArray)(GLuint) = [](GLuint index) { + if (!opengl32) loadWGL(); + ::wgl_glDisableVertexAttribArray(index); +}; +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = [](GLenum mode, GLint first, GLsizei count) { + if (!opengl32) loadWGL(); + ::wgl_glDrawArrays(mode, first, count); +}; +void (*const glDrawElements +)(GLenum, GLsizei, GLenum, const void*) = [](GLenum mode, GLsizei count, GLenum type, const void* indices) { + if (!opengl32) loadWGL(); + ::wgl_glDrawElements(mode, count, type, indices); +}; +void (*const glEnable)(GLenum) = [](GLenum cap) { + if (!opengl32) loadWGL(); + ::wgl_glEnable(cap); +}; +void (*const glEnableVertexAttribArray)(GLuint) = [](GLuint index) { + if (!opengl32) loadWGL(); + ::wgl_glEnableVertexAttribArray(index); +}; +void (*const glFinish)() = [](void) { + if (!opengl32) loadWGL(); + ::wgl_glFinish(); +}; +void (*const glFlush)() = [](void) { + if (!opengl32) loadWGL(); + ::wgl_glFlush(); +}; +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = + [](GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) { + if (!opengl32) loadWGL(); + ::wgl_glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); + }; +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = + [](GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) { + if (!opengl32) loadWGL(); + ::wgl_glFramebufferTexture2D(target, attachment, textarget, texture, level); + }; +void (*const glFrontFace)(GLenum) = [](GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glFrontFace(mode); +}; +void (*const glGenBuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* buffers) { + if (!opengl32) loadWGL(); + ::wgl_glGenBuffers(n, buffers); +}; +void (*const glGenerateMipmap)(GLenum) = [](GLenum target) { + if (!opengl32) loadWGL(); + ::wgl_glGenerateMipmap(target); +}; +void (*const glGenFramebuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* framebuffers) { + if (!opengl32) loadWGL(); + ::wgl_glGenFramebuffers(n, framebuffers); +}; +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* renderbuffers) { + if (!opengl32) loadWGL(); + ::wgl_glGenRenderbuffers(n, renderbuffers); +}; +void (*const glGenTextures)(GLsizei, GLuint*) = [](GLsizei n, GLuint* textures) { + if (!opengl32) loadWGL(); + ::wgl_glGenTextures(n, textures); +}; +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = + [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveAttrib(program, index, bufSize, length, size, type, name); + }; +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = + [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveUniform(program, index, bufSize, length, size, type, name); + }; +void (*const glGetAttachedShaders +)(GLuint, GLsizei, GLsizei*, GLuint*) = [](GLuint program, GLsizei maxCount, GLsizei* count, GLuint* shaders) { + if (!opengl32) loadWGL(); + ::wgl_glGetAttachedShaders(program, maxCount, count, shaders); +}; +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { + if (!opengl32) loadWGL(); + return ::wgl_glGetAttribLocation(program, name); +}; +void (*const glGetBooleanv)(GLenum, GLboolean*) = [](GLenum pname, GLboolean* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetBooleanv(pname, data); +}; +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetBufferParameteriv(target, pname, params); +}; +GLenum (*const glGetError)() = [](void) { + if (!opengl32) loadWGL(); + return ::wgl_glGetError(); +}; +void (*const glGetFloatv)(GLenum, GLfloat*) = [](GLenum pname, GLfloat* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetFloatv(pname, data); +}; +void (*const glGetFramebufferAttachmentParameteriv +)(GLenum, GLenum, GLenum, GLint*) = [](GLenum target, GLenum attachment, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetFramebufferAttachmentParameteriv(target, attachment, pname, params); +}; +void (*const glGetIntegerv)(GLenum, GLint*) = [](GLenum pname, GLint* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetIntegerv(pname, data); +}; +void (*const glGetProgramInfoLog +)(GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog) { + if (!opengl32) loadWGL(); + ::wgl_glGetProgramInfoLog(program, bufSize, length, infoLog); +}; +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = [](GLuint program, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetProgramiv(program, pname, params); +}; +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetRenderbufferParameteriv(target, pname, params); +}; +void (*const glGetShaderInfoLog +)(GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog) { + if (!opengl32) loadWGL(); + ::wgl_glGetShaderInfoLog(shader, bufSize, length, infoLog); +}; +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = [](GLuint shader, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetShaderiv(shader, pname, params); +}; +void (*const glGetShaderPrecisionFormat +)(GLenum, GLenum, GLint*, GLint*) = [](GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) { + if (!opengl32) loadWGL(); + ::wgl_glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision); +}; +void (*const glGetShaderSource +)(GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* source) { + if (!opengl32) loadWGL(); + ::wgl_glGetShaderSource(shader, bufSize, length, source); +}; +const GLubyte* (*const glGetString)(GLenum) = [](GLenum name) { + if (!opengl32) loadWGL(); + return ::wgl_glGetString(name); +}; +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = [](GLenum target, GLenum pname, GLfloat* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetTexParameterfv(target, pname, params); +}; +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetTexParameteriv(target, pname, params); +}; +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = [](GLuint program, GLint location, GLfloat* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetUniformfv(program, location, params); +}; +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = [](GLuint program, GLint location, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetUniformiv(program, location, params); +}; +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { + if (!opengl32) loadWGL(); + return ::wgl_glGetUniformLocation(program, name); +}; +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = [](GLuint index, GLenum pname, GLfloat* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribfv(index, pname, params); +}; +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = [](GLuint index, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribiv(index, pname, params); +}; +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = [](GLuint index, GLenum pname, void** pointer) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribPointerv(index, pname, pointer); +}; +void (*const glHint)(GLenum, GLenum) = [](GLenum target, GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glHint(target, mode); +}; +GLboolean (*const glIsBuffer)(GLuint) = [](GLuint buffer) { + if (!opengl32) loadWGL(); + return ::wgl_glIsBuffer(buffer); +}; +GLboolean (*const glIsEnabled)(GLenum) = [](GLenum cap) { + if (!opengl32) loadWGL(); + return ::wgl_glIsEnabled(cap); +}; +GLboolean (*const glIsFramebuffer)(GLuint) = [](GLuint framebuffer) { + if (!opengl32) loadWGL(); + return ::wgl_glIsFramebuffer(framebuffer); +}; +GLboolean (*const glIsProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + return ::wgl_glIsProgram(program); +}; +GLboolean (*const glIsRenderbuffer)(GLuint) = [](GLuint renderbuffer) { + if (!opengl32) loadWGL(); + return ::wgl_glIsRenderbuffer(renderbuffer); +}; +GLboolean (*const glIsShader)(GLuint) = [](GLuint shader) { + if (!opengl32) loadWGL(); + return ::wgl_glIsShader(shader); +}; +GLboolean (*const glIsTexture)(GLuint) = [](GLuint texture) { + if (!opengl32) loadWGL(); + return ::wgl_glIsTexture(texture); +}; +void (*const glLineWidth)(GLfloat) = [](GLfloat width) { + if (!opengl32) loadWGL(); + ::wgl_glLineWidth(width); +}; +void (*const glLinkProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + ::wgl_glLinkProgram(program); +}; +void (*const glPixelStorei)(GLenum, GLint) = [](GLenum pname, GLint param) { + if (!opengl32) loadWGL(); + ::wgl_glPixelStorei(pname, param); +}; +void (*const glPolygonOffset)(GLfloat, GLfloat) = [](GLfloat factor, GLfloat units) { + if (!opengl32) loadWGL(); + ::wgl_glPolygonOffset(factor, units); +}; +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = + [](GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glReadPixels(x, y, width, height, format, type, pixels); + }; +void (*const glReleaseShaderCompiler)() = []() { + if (!opengl32) loadWGL(); + ::wgl_glReleaseShaderCompiler(); +}; +void (*const glRenderbufferStorage +)(GLenum, GLenum, GLsizei, GLsizei) = [](GLenum target, GLenum internalformat, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glRenderbufferStorage(target, internalformat, width, height); +}; +void (*const glSampleCoverage)(GLfloat, GLboolean) = [](GLfloat value, GLboolean invert) { + if (!opengl32) loadWGL(); + ::wgl_glSampleCoverage(value, invert); +}; +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = [](GLint x, GLint y, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glScissor(x, y, width, height); +}; +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = + [](GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length) { + if (!opengl32) loadWGL(); + ::wgl_glShaderBinary(n, shaders, binaryformat, binary, length); + }; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = + [](GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length) { + if (!opengl32) loadWGL(); + ::wgl_glShaderSource(shader, count, string, length); + }; +void (*const glStencilFunc)(GLenum, GLint, GLuint) = [](GLenum func, GLint ref, GLuint mask) { + if (!opengl32) loadWGL(); + ::wgl_glStencilFunc(func, ref, mask); +}; +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = [](GLenum face, GLenum func, GLint ref, GLuint mask + ) { + if (!opengl32) loadWGL(); + ::wgl_glStencilFuncSeparate(face, func, ref, mask); +}; +void (*const glStencilMask)(GLuint) = [](GLuint mask) { + if (!opengl32) loadWGL(); + ::wgl_glStencilMask(mask); +}; +void (*const glStencilMaskSeparate)(GLenum, GLuint) = [](GLenum face, GLuint mask) { + if (!opengl32) loadWGL(); + ::wgl_glStencilMaskSeparate(face, mask); +}; +void (*const glStencilOp)(GLenum, GLenum, GLenum) = [](GLenum fail, GLenum zfail, GLenum zpass) { + if (!opengl32) loadWGL(); + ::wgl_glStencilOp(fail, zfail, zpass); +}; +void (*const glStencilOpSeparate +)(GLenum, GLenum, GLenum, GLenum) = [](GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass) { + if (!opengl32) loadWGL(); + ::wgl_glStencilOpSeparate(face, sfail, dpfail, dppass); +}; +void (*const glTexImage2D +)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = [](GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); +}; +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = [](GLenum target, GLenum pname, GLfloat param) { + if (!opengl32) loadWGL(); + ::wgl_glTexParameterf(target, pname, param); +}; +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = [](GLenum target, GLenum pname, const GLfloat* params + ) { + if (!opengl32) loadWGL(); + ::wgl_glTexParameterfv(target, pname, params); +}; +void (*const glTexParameteri)(GLenum, GLenum, GLint) = [](GLenum target, GLenum pname, GLint param) { + if (!opengl32) loadWGL(); + ::wgl_glTexParameteri(target, pname, param); +}; +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = [](GLenum target, GLenum pname, const GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glTexParameteriv(target, pname, params); +}; +void (*const glTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLsizei width, + GLsizei height, + GLenum format, + GLenum type, + const void* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); +}; +void (*const glUniform1f)(GLint, GLfloat) = [](GLint location, GLfloat v0) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1f(location, v0); +}; +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1fv(location, count, value); +}; +void (*const glUniform1i)(GLint, GLint) = [](GLint location, GLint v0) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1i(location, v0); +}; +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1iv(location, count, value); +}; +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2f(location, v0, v1); +}; +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2fv(location, count, value); +}; +void (*const glUniform2i)(GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2i(location, v0, v1); +}; +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2iv(location, count, value); +}; +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1, GLfloat v2) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3f(location, v0, v1, v2); +}; +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3fv(location, count, value); +}; +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1, GLint v2) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3i(location, v0, v1, v2); +}; +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3iv(location, count, value); +}; +void (*const glUniform4f +)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4f(location, v0, v1, v2, v3); +}; +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4fv(location, count, value); +}; +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1, GLint v2, GLint v3 + ) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4i(location, v0, v1, v2, v3); +}; +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4iv(location, count, value); +}; +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix2fv(location, count, transpose, value); + }; +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix3fv(location, count, transpose, value); + }; +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix4fv(location, count, transpose, value); + }; +void (*const glUseProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + ::wgl_glUseProgram(program); +}; +void (*const glValidateProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + ::wgl_glValidateProgram(program); +}; +void (*const glVertexAttrib1f)(GLuint, GLfloat) = [](GLuint index, GLfloat x) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib1f(index, x); +}; +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib1fv(index, v); +}; +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib2f(index, x, y); +}; +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib2fv(index, v); +}; +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y, GLfloat z) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib3f(index, x, y, z); +}; +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib3fv(index, v); +}; +void (*const glVertexAttrib4f +)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib4f(index, x, y, z, w); +}; +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib4fv(index, v); +}; +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = + [](GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* pointer) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribPointer(index, size, type, normalized, stride, pointer); + }; +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = [](GLint x, GLint y, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glViewport(x, y, width, height); +}; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = [](GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glReadBuffer(mode); }; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = [](GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices) { if (!opengl32) loadWGL(); ::wgl_glDrawRangeElements(mode, start, end, count, type, indices); }; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = [](GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels) { if (!opengl32) loadWGL(); ::wgl_glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels); }; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels) { if (!opengl32) loadWGL(); ::wgl_glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels); }; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height); }; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = [](GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data) { if (!opengl32) loadWGL(); ::wgl_glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data); }; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data) { if (!opengl32) loadWGL(); ::wgl_glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data); }; -void (* const glGenQueries)(GLsizei, GLuint*) = [](GLsizei n, GLuint* ids) { if (!opengl32) loadWGL(); ::wgl_glGenQueries(n, ids); }; -void (* const glDeleteQueries)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* ids) { if (!opengl32) loadWGL(); ::wgl_glDeleteQueries(n, ids); }; -GLboolean (* const glIsQuery)(GLuint) = [](GLuint id) { if (!opengl32) loadWGL(); return ::wgl_glIsQuery(id); }; -void (* const glBeginQuery)(GLenum, GLuint) = [](GLenum target, GLuint id) { if (!opengl32) loadWGL(); ::wgl_glBeginQuery(target, id); }; -void (* const glEndQuery)(GLenum) = [](GLenum target) { if (!opengl32) loadWGL(); ::wgl_glEndQuery(target); }; -void (* const glGetQueryiv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetQueryiv(target, pname, params); }; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = [](GLuint id, GLenum pname, GLuint* params) { if (!opengl32) loadWGL(); ::wgl_glGetQueryObjectuiv(id, pname, params); }; -GLboolean (* const glUnmapBuffer)(GLenum) = [](GLenum target) { if (!opengl32) loadWGL(); return ::wgl_glUnmapBuffer(target); }; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = [](GLenum target, GLenum pname, GLvoid** params) { if (!opengl32) loadWGL(); ::wgl_glGetBufferPointerv(target, pname, params); }; -void (* const glDrawBuffers)(GLsizei, const GLenum*) = [](GLsizei n, const GLenum* bufs) { if (!opengl32) loadWGL(); ::wgl_glDrawBuffers(n, bufs); }; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix2x3fv(location, count, transpose, value); }; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix3x2fv(location, count, transpose, value); }; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix2x4fv(location, count, transpose, value); }; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix4x2fv(location, count, transpose, value); }; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix3x4fv(location, count, transpose, value); }; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix4x3fv(location, count, transpose, value); }; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = [](GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) { if (!opengl32) loadWGL(); ::wgl_glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); }; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glRenderbufferStorageMultisample(target, samples, internalformat, width, height); }; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = [](GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer) { if (!opengl32) loadWGL(); ::wgl_glFramebufferTextureLayer(target, attachment, texture, level, layer); }; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = [](GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) { if (!opengl32) loadWGL(); return ::wgl_glMapBufferRange(target, offset, length, access); }; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = [](GLenum target, GLintptr offset, GLsizeiptr length) { if (!opengl32) loadWGL(); ::wgl_glFlushMappedBufferRange(target, offset, length); }; -void (* const glBindVertexArray)(GLuint) = [](GLuint array) { if (!opengl32) loadWGL(); ::wgl_glBindVertexArray(array); }; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* arrays) { if (!opengl32) loadWGL(); ::wgl_glDeleteVertexArrays(n, arrays); }; -void (* const glGenVertexArrays)(GLsizei, GLuint*) = [](GLsizei n, GLuint* arrays) { if (!opengl32) loadWGL(); ::wgl_glGenVertexArrays(n, arrays); }; -GLboolean (* const glIsVertexArray)(GLuint) = [](GLuint array) { if (!opengl32) loadWGL(); return ::wgl_glIsVertexArray(array); }; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint*) = [](GLenum target, GLuint index, GLint* data) { if (!opengl32) loadWGL(); ::wgl_glGetIntegeri_v(target, index, data); }; -void (* const glBeginTransformFeedback)(GLenum) = [](GLenum primitiveMode) { if (!opengl32) loadWGL(); ::wgl_glBeginTransformFeedback(primitiveMode); }; -void (* const glEndTransformFeedback)() = []() { if (!opengl32) loadWGL(); ::wgl_glEndTransformFeedback(); }; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = [](GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) { if (!opengl32) loadWGL(); ::wgl_glBindBufferRange(target, index, buffer, offset, size); }; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = [](GLenum target, GLuint index, GLuint buffer) { if (!opengl32) loadWGL(); ::wgl_glBindBufferBase(target, index, buffer); }; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum) = [](GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode) { if (!opengl32) loadWGL(); ::wgl_glTransformFeedbackVaryings(program, count, varyings, bufferMode); }; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name) { if (!opengl32) loadWGL(); ::wgl_glGetTransformFeedbackVarying(program, index, bufSize, length, size, type, name); }; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = [](GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribIPointer(index, size, type, stride, pointer); }; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = [](GLuint index, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribIiv(index, pname, params); }; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = [](GLuint index, GLenum pname, GLuint* params) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribIuiv(index, pname, params); }; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = [](GLuint index, GLint x, GLint y, GLint z, GLint w) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribI4i(index, x, y, z, w); }; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = [](GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribI4ui(index, x, y, z, w); }; -void (* const glVertexAttribI4iv)(GLuint, const GLint*) = [](GLuint index, const GLint* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribI4iv(index, v); }; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint*) = [](GLuint index, const GLuint* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribI4uiv(index, v); }; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint*) = [](GLuint program, GLint location, GLuint* params) { if (!opengl32) loadWGL(); ::wgl_glGetUniformuiv(program, location, params); }; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { if (!opengl32) loadWGL(); return ::wgl_glGetFragDataLocation(program, name); }; -void (* const glUniform1ui)(GLint, GLuint) = [](GLint location, GLuint v0) { if (!opengl32) loadWGL(); ::wgl_glUniform1ui(location, v0); }; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1) { if (!opengl32) loadWGL(); ::wgl_glUniform2ui(location, v0, v1); }; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1, GLuint v2) { if (!opengl32) loadWGL(); ::wgl_glUniform3ui(location, v0, v1, v2); }; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) { if (!opengl32) loadWGL(); ::wgl_glUniform4ui(location, v0, v1, v2, v3); }; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform1uiv(location, count, value); }; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform2uiv(location, count, value); }; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform3uiv(location, count, value); }; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform4uiv(location, count, value); }; -void (* const glClearBufferiv)(GLenum, GLint, const GLint*) = [](GLenum buffer, GLint drawbuffer, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glClearBufferiv(buffer, drawbuffer, value); }; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint*) = [](GLenum buffer, GLint drawbuffer, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glClearBufferuiv(buffer, drawbuffer, value); }; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat*) = [](GLenum buffer, GLint drawbuffer, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glClearBufferfv(buffer, drawbuffer, value); }; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = [](GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) { if (!opengl32) loadWGL(); ::wgl_glClearBufferfi(buffer, drawbuffer, depth, stencil); }; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = [](GLenum name, GLuint index) { if (!opengl32) loadWGL(); return ::wgl_glGetStringi(name, index); }; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = [](GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { if (!opengl32) loadWGL(); ::wgl_glCopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size); }; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = [](GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices) { if (!opengl32) loadWGL(); ::wgl_glGetUniformIndices(program, uniformCount, uniformNames, uniformIndices); }; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = [](GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params); }; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar*) = [](GLuint program, const GLchar* uniformBlockName) { if (!opengl32) loadWGL(); return ::wgl_glGetUniformBlockIndex(program, uniformBlockName); }; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = [](GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetActiveUniformBlockiv(program, uniformBlockIndex, pname, params); }; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName) { if (!opengl32) loadWGL(); ::wgl_glGetActiveUniformBlockName(program, uniformBlockIndex, bufSize, length, uniformBlockName); }; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = [](GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) { if (!opengl32) loadWGL(); ::wgl_glUniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding); }; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = [](GLenum mode, GLint first, GLsizei count, GLsizei instancecount) { if (!opengl32) loadWGL(); ::wgl_glDrawArraysInstanced(mode, first, count, instancecount); }; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = [](GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instancecount) { if (!opengl32) loadWGL(); ::wgl_glDrawElementsInstanced(mode, count, type, indices, instancecount); }; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = [](GLenum condition, GLbitfield flags) { if (!opengl32) loadWGL(); return ::wgl_glFenceSync(condition, flags); }; -GLboolean (* const glIsSync)(GLsync) = [](GLsync sync) { if (!opengl32) loadWGL(); return ::wgl_glIsSync(sync); }; -void (* const glDeleteSync)(GLsync) = [](GLsync sync) { if (!opengl32) loadWGL(); ::wgl_glDeleteSync(sync); }; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = [](GLsync sync, GLbitfield flags, GLuint64 timeout) { if (!opengl32) loadWGL(); return ::wgl_glClientWaitSync(sync, flags, timeout); }; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = [](GLsync sync, GLbitfield flags, GLuint64 timeout) { if (!opengl32) loadWGL(); ::wgl_glWaitSync(sync, flags, timeout); }; -void (* const glGetInteger64v)(GLenum, GLint64*) = [](GLenum pname, GLint64* params) { if (!opengl32) loadWGL(); ::wgl_glGetInteger64v(pname, params); }; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = [](GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values) { if (!opengl32) loadWGL(); ::wgl_glGetSynciv(sync, pname, bufSize, length, values); }; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = [](GLenum target, GLuint index, GLint64* data) { if (!opengl32) loadWGL(); ::wgl_glGetInteger64i_v(target, index, data); }; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = [](GLenum target, GLenum pname, GLint64* params) { if (!opengl32) loadWGL(); ::wgl_glGetBufferParameteri64v(target, pname, params); }; -void (* const glGenSamplers)(GLsizei, GLuint*) = [](GLsizei count, GLuint* samplers) { if (!opengl32) loadWGL(); ::wgl_glGenSamplers(count, samplers); }; -void (* const glDeleteSamplers)(GLsizei, const GLuint*) = [](GLsizei count, const GLuint* samplers) { if (!opengl32) loadWGL(); ::wgl_glDeleteSamplers(count, samplers); }; -GLboolean (* const glIsSampler)(GLuint) = [](GLuint sampler) { if (!opengl32) loadWGL(); return ::wgl_glIsSampler(sampler); }; -void (* const glBindSampler)(GLuint, GLuint) = [](GLuint unit, GLuint sampler) { if (!opengl32) loadWGL(); ::wgl_glBindSampler(unit, sampler); }; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = [](GLuint sampler, GLenum pname, GLint param) { if (!opengl32) loadWGL(); ::wgl_glSamplerParameteri(sampler, pname, param); }; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = [](GLuint sampler, GLenum pname, const GLint* param) { if (!opengl32) loadWGL(); ::wgl_glSamplerParameteriv(sampler, pname, param); }; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = [](GLuint sampler, GLenum pname, GLfloat param) { if (!opengl32) loadWGL(); ::wgl_glSamplerParameterf(sampler, pname, param); }; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = [](GLuint sampler, GLenum pname, const GLfloat* param) { if (!opengl32) loadWGL(); ::wgl_glSamplerParameterfv(sampler, pname, param); }; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = [](GLuint sampler, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetSamplerParameteriv(sampler, pname, params); }; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = [](GLuint sampler, GLenum pname, GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glGetSamplerParameterfv(sampler, pname, params); }; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = [](GLuint index, GLuint divisor) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribDivisor(index, divisor); }; -void (* const glBindTransformFeedback)(GLenum, GLuint) = [](GLenum target, GLuint id) { if (!opengl32) loadWGL(); ::wgl_glBindTransformFeedback(target, id); }; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* ids) { if (!opengl32) loadWGL(); ::wgl_glDeleteTransformFeedbacks(n, ids); }; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint*) = [](GLsizei n, GLuint* ids) { if (!opengl32) loadWGL(); ::wgl_glGenTransformFeedbacks(n, ids); }; -GLboolean (* const glIsTransformFeedback)(GLuint) = [](GLuint id) { if (!opengl32) loadWGL(); return ::wgl_glIsTransformFeedback(id); }; -void (* const glPauseTransformFeedback)() = []() { if (!opengl32) loadWGL(); ::wgl_glPauseTransformFeedback(); }; -void (* const glResumeTransformFeedback)() = []() { if (!opengl32) loadWGL(); ::wgl_glResumeTransformFeedback(); }; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = [](GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary) { if (!opengl32) loadWGL(); ::wgl_glGetProgramBinary(program, bufSize, length, binaryFormat, binary); }; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = [](GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length) { if (!opengl32) loadWGL(); ::wgl_glProgramBinary(program, binaryFormat, binary, length); }; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = [](GLuint program, GLenum pname, GLint value) { if (!opengl32) loadWGL(); ::wgl_glProgramParameteri(program, pname, value); }; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = [](GLenum target, GLsizei numAttachments, const GLenum* attachments) { if (!opengl32) loadWGL(); ::wgl_glInvalidateFramebuffer(target, numAttachments, attachments); }; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = [](GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glInvalidateSubFramebuffer(target, numAttachments, attachments, x, y, width, height); }; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glTexStorage2D(target, levels, internalformat, width, height); }; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = [](GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth) { if (!opengl32) loadWGL(); ::wgl_glTexStorage3D(target, levels, internalformat, width, height, depth); }; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = [](GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetInternalformativ(target, internalformat, pname, bufSize, params); }; +void (*const glReadBuffer)(GLenum) = [](GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glReadBuffer(mode); +}; +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = + [](GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices) { + if (!opengl32) loadWGL(); + ::wgl_glDrawRangeElements(mode, start, end, count, type, indices); + }; +void (*const glTexImage3D +)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = [](GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border, + GLenum format, + GLenum type, + const GLvoid* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels); +}; +void (*const glTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = + [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLenum type, + const GLvoid* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels); + }; +void (*const glCopyTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLint x, + GLint y, + GLsizei width, + GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height); +}; +void (*const glCompressedTexImage3D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = [](GLenum target, + GLint level, + GLenum internalformat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border, + GLsizei imageSize, + const GLvoid* data) { + if (!opengl32) loadWGL(); + ::wgl_glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data); +}; +void (*const glCompressedTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLsizei imageSize, + const GLvoid* data + ) { + if (!opengl32) loadWGL(); + ::wgl_glCompressedTexSubImage3D( + target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data + ); +}; +void (*const glGenQueries)(GLsizei, GLuint*) = [](GLsizei n, GLuint* ids) { + if (!opengl32) loadWGL(); + ::wgl_glGenQueries(n, ids); +}; +void (*const glDeleteQueries)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* ids) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteQueries(n, ids); +}; +GLboolean (*const glIsQuery)(GLuint) = [](GLuint id) { + if (!opengl32) loadWGL(); + return ::wgl_glIsQuery(id); +}; +void (*const glBeginQuery)(GLenum, GLuint) = [](GLenum target, GLuint id) { + if (!opengl32) loadWGL(); + ::wgl_glBeginQuery(target, id); +}; +void (*const glEndQuery)(GLenum) = [](GLenum target) { + if (!opengl32) loadWGL(); + ::wgl_glEndQuery(target); +}; +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetQueryiv(target, pname, params); +}; +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = [](GLuint id, GLenum pname, GLuint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetQueryObjectuiv(id, pname, params); +}; +GLboolean (*const glUnmapBuffer)(GLenum) = [](GLenum target) { + if (!opengl32) loadWGL(); + return ::wgl_glUnmapBuffer(target); +}; +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = [](GLenum target, GLenum pname, GLvoid** params) { + if (!opengl32) loadWGL(); + ::wgl_glGetBufferPointerv(target, pname, params); +}; +void (*const glDrawBuffers)(GLsizei, const GLenum*) = [](GLsizei n, const GLenum* bufs) { + if (!opengl32) loadWGL(); + ::wgl_glDrawBuffers(n, bufs); +}; +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix2x3fv(location, count, transpose, value); + }; +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix3x2fv(location, count, transpose, value); + }; +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix2x4fv(location, count, transpose, value); + }; +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix4x2fv(location, count, transpose, value); + }; +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix3x4fv(location, count, transpose, value); + }; +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix4x3fv(location, count, transpose, value); + }; +void (*const glBlitFramebuffer +)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = [](GLint srcX0, + GLint srcY0, + GLint srcX1, + GLint srcY1, + GLint dstX0, + GLint dstY0, + GLint dstX1, + GLint dstY1, + GLbitfield mask, + GLenum filter) { + if (!opengl32) loadWGL(); + ::wgl_glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); +}; +void (*const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = + [](GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glRenderbufferStorageMultisample(target, samples, internalformat, width, height); + }; +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = + [](GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer) { + if (!opengl32) loadWGL(); + ::wgl_glFramebufferTextureLayer(target, attachment, texture, level, layer); + }; +GLvoid* (*const glMapBufferRange +)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = [](GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) { + if (!opengl32) loadWGL(); + return ::wgl_glMapBufferRange(target, offset, length, access); +}; +void (*const glFlushMappedBufferRange +)(GLenum, GLintptr, GLsizeiptr) = [](GLenum target, GLintptr offset, GLsizeiptr length) { + if (!opengl32) loadWGL(); + ::wgl_glFlushMappedBufferRange(target, offset, length); +}; +void (*const glBindVertexArray)(GLuint) = [](GLuint array) { + if (!opengl32) loadWGL(); + ::wgl_glBindVertexArray(array); +}; +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* arrays) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteVertexArrays(n, arrays); +}; +void (*const glGenVertexArrays)(GLsizei, GLuint*) = [](GLsizei n, GLuint* arrays) { + if (!opengl32) loadWGL(); + ::wgl_glGenVertexArrays(n, arrays); +}; +GLboolean (*const glIsVertexArray)(GLuint) = [](GLuint array) { + if (!opengl32) loadWGL(); + return ::wgl_glIsVertexArray(array); +}; +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = [](GLenum target, GLuint index, GLint* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetIntegeri_v(target, index, data); +}; +void (*const glBeginTransformFeedback)(GLenum) = [](GLenum primitiveMode) { + if (!opengl32) loadWGL(); + ::wgl_glBeginTransformFeedback(primitiveMode); +}; +void (*const glEndTransformFeedback)() = []() { + if (!opengl32) loadWGL(); + ::wgl_glEndTransformFeedback(); +}; +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = + [](GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) { + if (!opengl32) loadWGL(); + ::wgl_glBindBufferRange(target, index, buffer, offset, size); + }; +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = [](GLenum target, GLuint index, GLuint buffer) { + if (!opengl32) loadWGL(); + ::wgl_glBindBufferBase(target, index, buffer); +}; +void (*const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum) = + [](GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode) { + if (!opengl32) loadWGL(); + ::wgl_glTransformFeedbackVaryings(program, count, varyings, bufferMode); + }; +void (*const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = + [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name) { + if (!opengl32) loadWGL(); + ::wgl_glGetTransformFeedbackVarying(program, index, bufSize, length, size, type, name); + }; +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = + [](GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribIPointer(index, size, type, stride, pointer); + }; +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = [](GLuint index, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribIiv(index, pname, params); +}; +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = [](GLuint index, GLenum pname, GLuint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribIuiv(index, pname, params); +}; +void (*const glVertexAttribI4i +)(GLuint, GLint, GLint, GLint, GLint) = [](GLuint index, GLint x, GLint y, GLint z, GLint w) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribI4i(index, x, y, z, w); +}; +void (*const glVertexAttribI4ui +)(GLuint, GLuint, GLuint, GLuint, GLuint) = [](GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribI4ui(index, x, y, z, w); +}; +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = [](GLuint index, const GLint* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribI4iv(index, v); +}; +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = [](GLuint index, const GLuint* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribI4uiv(index, v); +}; +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = [](GLuint program, GLint location, GLuint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetUniformuiv(program, location, params); +}; +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { + if (!opengl32) loadWGL(); + return ::wgl_glGetFragDataLocation(program, name); +}; +void (*const glUniform1ui)(GLint, GLuint) = [](GLint location, GLuint v0) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1ui(location, v0); +}; +void (*const glUniform2ui)(GLint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2ui(location, v0, v1); +}; +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1, GLuint v2) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3ui(location, v0, v1, v2); +}; +void (*const glUniform4ui +)(GLint, GLuint, GLuint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4ui(location, v0, v1, v2, v3); +}; +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1uiv(location, count, value); +}; +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2uiv(location, count, value); +}; +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3uiv(location, count, value); +}; +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4uiv(location, count, value); +}; +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = [](GLenum buffer, GLint drawbuffer, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glClearBufferiv(buffer, drawbuffer, value); +}; +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = [](GLenum buffer, GLint drawbuffer, const GLuint* value + ) { + if (!opengl32) loadWGL(); + ::wgl_glClearBufferuiv(buffer, drawbuffer, value); +}; +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = [](GLenum buffer, GLint drawbuffer, const GLfloat* value + ) { + if (!opengl32) loadWGL(); + ::wgl_glClearBufferfv(buffer, drawbuffer, value); +}; +void (*const glClearBufferfi +)(GLenum, GLint, GLfloat, GLint) = [](GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) { + if (!opengl32) loadWGL(); + ::wgl_glClearBufferfi(buffer, drawbuffer, depth, stencil); +}; +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = [](GLenum name, GLuint index) { + if (!opengl32) loadWGL(); + return ::wgl_glGetStringi(name, index); +}; +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = + [](GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { + if (!opengl32) loadWGL(); + ::wgl_glCopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size); + }; +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = + [](GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices) { + if (!opengl32) loadWGL(); + ::wgl_glGetUniformIndices(program, uniformCount, uniformNames, uniformIndices); + }; +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = + [](GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params); + }; +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = [](GLuint program, const GLchar* uniformBlockName) { + if (!opengl32) loadWGL(); + return ::wgl_glGetUniformBlockIndex(program, uniformBlockName); +}; +void (*const glGetActiveUniformBlockiv +)(GLuint, GLuint, GLenum, GLint*) = [](GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveUniformBlockiv(program, uniformBlockIndex, pname, params); +}; +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = + [](GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveUniformBlockName(program, uniformBlockIndex, bufSize, length, uniformBlockName); + }; +void (*const glUniformBlockBinding +)(GLuint, GLuint, GLuint) = [](GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) { + if (!opengl32) loadWGL(); + ::wgl_glUniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding); +}; +void (*const glDrawArraysInstanced +)(GLenum, GLint, GLsizei, GLsizei) = [](GLenum mode, GLint first, GLsizei count, GLsizei instancecount) { + if (!opengl32) loadWGL(); + ::wgl_glDrawArraysInstanced(mode, first, count, instancecount); +}; +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = + [](GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instancecount) { + if (!opengl32) loadWGL(); + ::wgl_glDrawElementsInstanced(mode, count, type, indices, instancecount); + }; +GLsync (*const glFenceSync)(GLenum, GLbitfield) = [](GLenum condition, GLbitfield flags) { + if (!opengl32) loadWGL(); + return ::wgl_glFenceSync(condition, flags); +}; +GLboolean (*const glIsSync)(GLsync) = [](GLsync sync) { + if (!opengl32) loadWGL(); + return ::wgl_glIsSync(sync); +}; +void (*const glDeleteSync)(GLsync) = [](GLsync sync) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteSync(sync); +}; +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = [](GLsync sync, GLbitfield flags, GLuint64 timeout) { + if (!opengl32) loadWGL(); + return ::wgl_glClientWaitSync(sync, flags, timeout); +}; +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = [](GLsync sync, GLbitfield flags, GLuint64 timeout) { + if (!opengl32) loadWGL(); + ::wgl_glWaitSync(sync, flags, timeout); +}; +void (*const glGetInteger64v)(GLenum, GLint64*) = [](GLenum pname, GLint64* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetInteger64v(pname, params); +}; +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = + [](GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values) { + if (!opengl32) loadWGL(); + ::wgl_glGetSynciv(sync, pname, bufSize, length, values); + }; +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = [](GLenum target, GLuint index, GLint64* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetInteger64i_v(target, index, data); +}; +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = [](GLenum target, GLenum pname, GLint64* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetBufferParameteri64v(target, pname, params); +}; +void (*const glGenSamplers)(GLsizei, GLuint*) = [](GLsizei count, GLuint* samplers) { + if (!opengl32) loadWGL(); + ::wgl_glGenSamplers(count, samplers); +}; +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = [](GLsizei count, const GLuint* samplers) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteSamplers(count, samplers); +}; +GLboolean (*const glIsSampler)(GLuint) = [](GLuint sampler) { + if (!opengl32) loadWGL(); + return ::wgl_glIsSampler(sampler); +}; +void (*const glBindSampler)(GLuint, GLuint) = [](GLuint unit, GLuint sampler) { + if (!opengl32) loadWGL(); + ::wgl_glBindSampler(unit, sampler); +}; +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = [](GLuint sampler, GLenum pname, GLint param) { + if (!opengl32) loadWGL(); + ::wgl_glSamplerParameteri(sampler, pname, param); +}; +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = [](GLuint sampler, GLenum pname, const GLint* param + ) { + if (!opengl32) loadWGL(); + ::wgl_glSamplerParameteriv(sampler, pname, param); +}; +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = [](GLuint sampler, GLenum pname, GLfloat param) { + if (!opengl32) loadWGL(); + ::wgl_glSamplerParameterf(sampler, pname, param); +}; +void (*const glSamplerParameterfv +)(GLuint, GLenum, const GLfloat*) = [](GLuint sampler, GLenum pname, const GLfloat* param) { + if (!opengl32) loadWGL(); + ::wgl_glSamplerParameterfv(sampler, pname, param); +}; +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = [](GLuint sampler, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetSamplerParameteriv(sampler, pname, params); +}; +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = [](GLuint sampler, GLenum pname, GLfloat* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetSamplerParameterfv(sampler, pname, params); +}; +void (*const glVertexAttribDivisor)(GLuint, GLuint) = [](GLuint index, GLuint divisor) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribDivisor(index, divisor); +}; +void (*const glBindTransformFeedback)(GLenum, GLuint) = [](GLenum target, GLuint id) { + if (!opengl32) loadWGL(); + ::wgl_glBindTransformFeedback(target, id); +}; +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* ids) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteTransformFeedbacks(n, ids); +}; +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = [](GLsizei n, GLuint* ids) { + if (!opengl32) loadWGL(); + ::wgl_glGenTransformFeedbacks(n, ids); +}; +GLboolean (*const glIsTransformFeedback)(GLuint) = [](GLuint id) { + if (!opengl32) loadWGL(); + return ::wgl_glIsTransformFeedback(id); +}; +void (*const glPauseTransformFeedback)() = []() { + if (!opengl32) loadWGL(); + ::wgl_glPauseTransformFeedback(); +}; +void (*const glResumeTransformFeedback)() = []() { + if (!opengl32) loadWGL(); + ::wgl_glResumeTransformFeedback(); +}; +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = + [](GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary) { + if (!opengl32) loadWGL(); + ::wgl_glGetProgramBinary(program, bufSize, length, binaryFormat, binary); + }; +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = + [](GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length) { + if (!opengl32) loadWGL(); + ::wgl_glProgramBinary(program, binaryFormat, binary, length); + }; +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = [](GLuint program, GLenum pname, GLint value) { + if (!opengl32) loadWGL(); + ::wgl_glProgramParameteri(program, pname, value); +}; +void (*const glInvalidateFramebuffer +)(GLenum, GLsizei, const GLenum*) = [](GLenum target, GLsizei numAttachments, const GLenum* attachments) { + if (!opengl32) loadWGL(); + ::wgl_glInvalidateFramebuffer(target, numAttachments, attachments); +}; +void (*const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = + [](GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height + ) { + if (!opengl32) loadWGL(); + ::wgl_glInvalidateSubFramebuffer(target, numAttachments, attachments, x, y, width, height); + }; +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = + [](GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glTexStorage2D(target, levels, internalformat, width, height); + }; +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = + [](GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth) { + if (!opengl32) loadWGL(); + ::wgl_glTexStorage3D(target, levels, internalformat, width, height, depth); + }; +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = + [](GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetInternalformativ(target, internalformat, pname, bufSize, params); + }; /* OpenGL Windows Extensions */ -BOOL(* const wglChoosePixelFormatARB)(HDC, const int*, const FLOAT*, UINT, int*, UINT*) = [](HDC hdc, const int* piAttribIList, const FLOAT* pfAttribFList, UINT nMaxFormats, int* piFormats, UINT* nNumFormats) { if (!opengl32) loadWGL(); return ::wgl_wglChoosePixelFormatARB(hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats); }; -HGLRC(* const wglCreateContextAttribsARB)(HDC, HGLRC, const int*) = [](HDC hDC, HGLRC hShareContext, const int* attribList) { if (!opengl32) loadWGL(); return ::wgl_wglCreateContextAttribsARB(hDC, hShareContext, attribList); }; -const char* (* const wglGetExtensionsStringARB)(HDC) = [](HDC hdc) { if (!opengl32) loadWGL(); return ::wgl_wglGetExtensionsStringARB(hdc); }; -const char* (* const wglGetExtensionsStringEXT)() = [](void) { if (!opengl32) loadWGL(); return ::wgl_wglGetExtensionsStringEXT(); }; +BOOL(*const wglChoosePixelFormatARB) +(HDC, const int*, const FLOAT*, UINT, int*, UINT*) = [](HDC hdc, + const int* piAttribIList, + const FLOAT* pfAttribFList, + UINT nMaxFormats, + int* piFormats, + UINT* nNumFormats) { + if (!opengl32) loadWGL(); + return ::wgl_wglChoosePixelFormatARB(hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats); +}; +HGLRC(*const wglCreateContextAttribsARB) +(HDC, HGLRC, const int*) = [](HDC hDC, HGLRC hShareContext, const int* attribList) { + if (!opengl32) loadWGL(); + return ::wgl_wglCreateContextAttribsARB(hDC, hShareContext, attribList); +}; +const char* (*const wglGetExtensionsStringARB)(HDC) = [](HDC hdc) { + if (!opengl32) loadWGL(); + return ::wgl_wglGetExtensionsStringARB(hdc); +}; +const char* (*const wglGetExtensionsStringEXT)() = [](void) { + if (!opengl32) loadWGL(); + return ::wgl_wglGetExtensionsStringEXT(); +}; -} // namespace platform -} // namespace mbgl +} // namespace platform +} // namespace mbgl #endif diff --git a/platform/windows/include/thread.h b/platform/windows/include/thread.h index b701c2e8802..ba325cdef17 100644 --- a/platform/windows/include/thread.h +++ b/platform/windows/include/thread.h @@ -21,22 +21,21 @@ extern "C" { // const DWORD MS_VC_EXCEPTION = 0x406D1388; -#pragma pack(push,8) -typedef struct tagTHREADNAME_INFO -{ - DWORD dwType; // Must be 0x1000. - LPCSTR szName; // Pointer to name (in user addr space). +#pragma pack(push, 8) +typedef struct tagTHREADNAME_INFO { + DWORD dwType; // Must be 0x1000. + LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). - DWORD dwFlags; // Reserved for future use, must be zero. + DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) void SetThreadName(DWORD dwThreadID, const char* threadName); typedef struct structTHREAD_INFO { - DWORD id; - DWORD key; - char* name; + DWORD id; + DWORD key; + char* name; } THREAD_INFO; #ifdef __cplusplus @@ -47,13 +46,9 @@ extern DWORD selfThreadKey; class DummyClassThread { public: - DummyClassThread() { - selfThreadKey = TlsAlloc(); - } + DummyClassThread() { selfThreadKey = TlsAlloc(); } - ~DummyClassThread() { - TlsFree(selfThreadKey); - } + ~DummyClassThread() { TlsFree(selfThreadKey); } }; extern DummyClassThread dummyClassThread; @@ -66,7 +61,7 @@ std::string getCurrentThreadName(); void setCurrentThreadName(const std::string& name); void makeThreadLowPriority(); void setCurrentThreadPriority(double priority); -} -} +} // namespace platform +} // namespace mbgl #endif diff --git a/platform/windows/src/gl_functions.cpp b/platform/windows/src/gl_functions.cpp index 6453416e252..7737c2b48c7 100644 --- a/platform/windows/src/gl_functions.cpp +++ b/platform/windows/src/gl_functions.cpp @@ -14,255 +14,270 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = ::glActiveTexture; -void (* const glAttachShader)(GLuint, GLuint) = ::glAttachShader; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *) = ::glBindAttribLocation; -void (* const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; -void (* const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; -void (* const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; -void (* const glBindTexture)(GLenum, GLuint) = ::glBindTexture; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; -void (* const glBlendEquation)(GLenum) = ::glBlendEquation; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; -void (* const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; -void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum) = ::glBufferData; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *) = ::glBufferSubData; -GLenum (* const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; -void (* const glClear)(GLbitfield) = ::glClear; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; -void (* const glClearDepthf)(GLfloat) = ::glClearDepthf; -void (* const glClearStencil)(GLint) = ::glClearStencil; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; -void (* const glCompileShader)(GLuint) = ::glCompileShader; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *) = ::glCompressedTexImage2D; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *) = ::glCompressedTexSubImage2D; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; -GLuint (* const glCreateProgram)() = ::glCreateProgram; -GLuint (* const glCreateShader)(GLenum) = ::glCreateShader; -void (* const glCullFace)(GLenum) = ::glCullFace; -void (* const glDeleteBuffers)(GLsizei, const GLuint *) = ::glDeleteBuffers; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint *) = ::glDeleteFramebuffers; -void (* const glDeleteProgram)(GLuint) = ::glDeleteProgram; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *) = ::glDeleteRenderbuffers; -void (* const glDeleteShader)(GLuint) = ::glDeleteShader; -void (* const glDeleteTextures)(GLsizei, const GLuint *) = ::glDeleteTextures; -void (* const glDepthFunc)(GLenum) = ::glDepthFunc; -void (* const glDepthMask)(GLboolean) = ::glDepthMask; -void (* const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; -void (* const glDetachShader)(GLuint, GLuint) = ::glDetachShader; -void (* const glDisable)(GLenum) = ::glDisable; -void (* const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *) = ::glDrawElements; -void (* const glEnable)(GLenum) = ::glEnable; -void (* const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; -void (* const glFinish)() = ::glFinish; -void (* const glFlush)() = ::glFlush; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; -void (* const glFrontFace)(GLenum) = ::glFrontFace; -void (* const glGenBuffers)(GLsizei, GLuint *) = ::glGenBuffers; -void (* const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; -void (* const glGenFramebuffers)(GLsizei, GLuint *) = ::glGenFramebuffers; -void (* const glGenRenderbuffers)(GLsizei, GLuint *) = ::glGenRenderbuffers; -void (* const glGenTextures)(GLsizei, GLuint *) = ::glGenTextures; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveAttrib; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveUniform; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *) = ::glGetAttachedShaders; -GLint (* const glGetAttribLocation)(GLuint, const GLchar *) = ::glGetAttribLocation; -void (* const glGetBooleanv)(GLenum, GLboolean *) = ::glGetBooleanv; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetBufferParameteriv; -GLenum (* const glGetError)() = ::glGetError; -void (* const glGetFloatv)(GLenum, GLfloat *) = ::glGetFloatv; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *) = ::glGetFramebufferAttachmentParameteriv; -void (* const glGetIntegerv)(GLenum, GLint *) = ::glGetIntegerv; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetProgramInfoLog; -void (* const glGetProgramiv)(GLuint, GLenum, GLint *) = ::glGetProgramiv; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetRenderbufferParameteriv; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderInfoLog; -void (* const glGetShaderiv)(GLuint, GLenum, GLint *) = ::glGetShaderiv; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *) = ::glGetShaderPrecisionFormat; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderSource; -const GLubyte *(* const glGetString)(GLenum) = ::glGetString; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *) = ::glGetTexParameterfv; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *) = ::glGetTexParameteriv; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat *) = ::glGetUniformfv; -void (* const glGetUniformiv)(GLuint, GLint, GLint *) = ::glGetUniformiv; -GLint (* const glGetUniformLocation)(GLuint, const GLchar *) = ::glGetUniformLocation; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *) = ::glGetVertexAttribfv; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribiv; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **) = ::glGetVertexAttribPointerv; -void (* const glHint)(GLenum, GLenum) = ::glHint; -GLboolean (* const glIsBuffer)(GLuint) = ::glIsBuffer; -GLboolean (* const glIsEnabled)(GLenum) = ::glIsEnabled; -GLboolean (* const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; -GLboolean (* const glIsProgram)(GLuint) = ::glIsProgram; -GLboolean (* const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; -GLboolean (* const glIsShader)(GLuint) = ::glIsShader; -GLboolean (* const glIsTexture)(GLuint) = ::glIsTexture; -void (* const glLineWidth)(GLfloat) = ::glLineWidth; -void (* const glLinkProgram)(GLuint) = ::glLinkProgram; -void (* const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; -void (* const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *) = ::glReadPixels; -void (* const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; -void (* const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; -void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei) = ::glShaderBinary; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *) = ::glShaderSource; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; -void (* const glStencilMask)(GLuint) = ::glStencilMask; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *) = ::glTexImage2D; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *) = ::glTexParameterfv; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint *) = ::glTexParameteriv; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *) = ::glTexSubImage2D; -void (* const glUniform1f)(GLint, GLfloat) = ::glUniform1f; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *) = ::glUniform1fv; -void (* const glUniform1i)(GLint, GLint) = ::glUniform1i; -void (* const glUniform1iv)(GLint, GLsizei, const GLint *) = ::glUniform1iv; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *) = ::glUniform2fv; -void (* const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; -void (* const glUniform2iv)(GLint, GLsizei, const GLint *) = ::glUniform2iv; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *) = ::glUniform3fv; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; -void (* const glUniform3iv)(GLint, GLsizei, const GLint *) = ::glUniform3iv; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *) = ::glUniform4fv; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; -void (* const glUniform4iv)(GLint, GLsizei, const GLint *) = ::glUniform4iv; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2fv; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3fv; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4fv; -void (* const glUseProgram)(GLuint) = ::glUseProgram; -void (* const glValidateProgram)(GLuint) = ::glValidateProgram; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat *) = ::glVertexAttrib1fv; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat *) = ::glVertexAttrib2fv; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat *) = ::glVertexAttrib3fv; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat *) = ::glVertexAttrib4fv; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *) = ::glVertexAttribPointer; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; +void (*const glActiveTexture)(GLenum) = ::glActiveTexture; +void (*const glAttachShader)(GLuint, GLuint) = ::glAttachShader; +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = ::glBindAttribLocation; +void (*const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; +void (*const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; +void (*const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; +void (*const glBindTexture)(GLenum, GLuint) = ::glBindTexture; +void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; +void (*const glBlendEquation)(GLenum) = ::glBlendEquation; +void (*const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; +void (*const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; +void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; +void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = ::glBufferData; +void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = ::glBufferSubData; +GLenum (*const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; +void (*const glClear)(GLbitfield) = ::glClear; +void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; +void (*const glClearDepthf)(GLfloat) = ::glClearDepthf; +void (*const glClearStencil)(GLint) = ::glClearStencil; +void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; +void (*const glCompileShader)(GLuint) = ::glCompileShader; +void (*const glCompressedTexImage2D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = ::glCompressedTexImage2D; +void (*const glCompressedTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = ::glCompressedTexSubImage2D; +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; +GLuint (*const glCreateProgram)() = ::glCreateProgram; +GLuint (*const glCreateShader)(GLenum) = ::glCreateShader; +void (*const glCullFace)(GLenum) = ::glCullFace; +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = ::glDeleteBuffers; +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = ::glDeleteFramebuffers; +void (*const glDeleteProgram)(GLuint) = ::glDeleteProgram; +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = ::glDeleteRenderbuffers; +void (*const glDeleteShader)(GLuint) = ::glDeleteShader; +void (*const glDeleteTextures)(GLsizei, const GLuint*) = ::glDeleteTextures; +void (*const glDepthFunc)(GLenum) = ::glDepthFunc; +void (*const glDepthMask)(GLboolean) = ::glDepthMask; +void (*const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; +void (*const glDetachShader)(GLuint, GLuint) = ::glDetachShader; +void (*const glDisable)(GLenum) = ::glDisable; +void (*const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; +void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = ::glDrawElements; +void (*const glEnable)(GLenum) = ::glEnable; +void (*const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; +void (*const glFinish)() = ::glFinish; +void (*const glFlush)() = ::glFlush; +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; +void (*const glFrontFace)(GLenum) = ::glFrontFace; +void (*const glGenBuffers)(GLsizei, GLuint*) = ::glGenBuffers; +void (*const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; +void (*const glGenFramebuffers)(GLsizei, GLuint*) = ::glGenFramebuffers; +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = ::glGenRenderbuffers; +void (*const glGenTextures)(GLsizei, GLuint*) = ::glGenTextures; +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveAttrib; +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveUniform; +void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = ::glGetAttachedShaders; +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = ::glGetAttribLocation; +void (*const glGetBooleanv)(GLenum, GLboolean*) = ::glGetBooleanv; +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetBufferParameteriv; +GLenum (*const glGetError)() = ::glGetError; +void (*const glGetFloatv)(GLenum, GLfloat*) = ::glGetFloatv; +void (*const glGetFramebufferAttachmentParameteriv +)(GLenum, GLenum, GLenum, GLint*) = ::glGetFramebufferAttachmentParameteriv; +void (*const glGetIntegerv)(GLenum, GLint*) = ::glGetIntegerv; +void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetProgramInfoLog; +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = ::glGetProgramiv; +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetRenderbufferParameteriv; +void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderInfoLog; +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = ::glGetShaderiv; +void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = ::glGetShaderPrecisionFormat; +void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderSource; +const GLubyte* (*const glGetString)(GLenum) = ::glGetString; +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = ::glGetTexParameterfv; +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = ::glGetTexParameteriv; +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = ::glGetUniformfv; +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = ::glGetUniformiv; +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = ::glGetUniformLocation; +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = ::glGetVertexAttribfv; +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribiv; +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = ::glGetVertexAttribPointerv; +void (*const glHint)(GLenum, GLenum) = ::glHint; +GLboolean (*const glIsBuffer)(GLuint) = ::glIsBuffer; +GLboolean (*const glIsEnabled)(GLenum) = ::glIsEnabled; +GLboolean (*const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; +GLboolean (*const glIsProgram)(GLuint) = ::glIsProgram; +GLboolean (*const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; +GLboolean (*const glIsShader)(GLuint) = ::glIsShader; +GLboolean (*const glIsTexture)(GLuint) = ::glIsTexture; +void (*const glLineWidth)(GLfloat) = ::glLineWidth; +void (*const glLinkProgram)(GLuint) = ::glLinkProgram; +void (*const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; +void (*const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = ::glReadPixels; +void (*const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; +void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; +void (*const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = ::glShaderBinary; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = ::glShaderSource; +void (*const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; +void (*const glStencilMask)(GLuint) = ::glStencilMask; +void (*const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; +void (*const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; +void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; +void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = ::glTexImage2D; +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = ::glTexParameterfv; +void (*const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = ::glTexParameteriv; +void (*const glTexSubImage2D +)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = ::glTexSubImage2D; +void (*const glUniform1f)(GLint, GLfloat) = ::glUniform1f; +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = ::glUniform1fv; +void (*const glUniform1i)(GLint, GLint) = ::glUniform1i; +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = ::glUniform1iv; +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = ::glUniform2fv; +void (*const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = ::glUniform2iv; +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = ::glUniform3fv; +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = ::glUniform3iv; +void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = ::glUniform4fv; +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = ::glUniform4iv; +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2fv; +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3fv; +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4fv; +void (*const glUseProgram)(GLuint) = ::glUseProgram; +void (*const glValidateProgram)(GLuint) = ::glValidateProgram; +void (*const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = ::glVertexAttrib1fv; +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = ::glVertexAttrib2fv; +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = ::glVertexAttrib3fv; +void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = ::glVertexAttrib4fv; +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = ::glVertexAttribPointer; +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = ::glReadBuffer; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *) = ::glDrawRangeElements; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *) = ::glTexImage3D; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *) = ::glTexSubImage3D; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage3D; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *) = ::glCompressedTexImage3D; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *) = ::glCompressedTexSubImage3D; -void (* const glGenQueries)(GLsizei, GLuint *) = ::glGenQueries; -void (* const glDeleteQueries)(GLsizei, const GLuint *) = ::glDeleteQueries; -GLboolean (* const glIsQuery)(GLuint) = ::glIsQuery; -void (* const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; -void (* const glEndQuery)(GLenum) = ::glEndQuery; -void (* const glGetQueryiv)(GLenum, GLenum, GLint *) = ::glGetQueryiv; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint *) = ::glGetQueryObjectuiv; -GLboolean (* const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid **) = ::glGetBufferPointerv; -void (* const glDrawBuffers)(GLsizei, const GLenum *) = ::glDrawBuffers; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x3fv; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x2fv; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x4fv; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x2fv; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x4fv; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x3fv; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = ::glBlitFramebuffer; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorageMultisample; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; -void (* const glBindVertexArray)(GLuint) = ::glBindVertexArray; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint *) = ::glDeleteVertexArrays; -void (* const glGenVertexArrays)(GLsizei, GLuint *) = ::glGenVertexArrays; -GLboolean (* const glIsVertexArray)(GLuint) = ::glIsVertexArray; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint *) = ::glGetIntegeri_v; -void (* const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; -void (* const glEndTransformFeedback)() = ::glEndTransformFeedback; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar * const*, GLenum) = ::glTransformFeedbackVaryings; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei *, GLsizei *, GLenum *, GLchar *) = ::glGetTransformFeedbackVarying; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid *) = ::glVertexAttribIPointer; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribIiv; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint *) = ::glGetVertexAttribIuiv; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; -void (* const glVertexAttribI4iv)(GLuint, const GLint *) = ::glVertexAttribI4iv; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint *) = ::glVertexAttribI4uiv; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint *) = ::glGetUniformuiv; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar *) = ::glGetFragDataLocation; -void (* const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint *) = ::glUniform1uiv; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint *) = ::glUniform2uiv; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint *) = ::glUniform3uiv; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint *) = ::glUniform4uiv; -void (* const glClearBufferiv)(GLenum, GLint, const GLint *) = ::glClearBufferiv; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint *) = ::glClearBufferuiv; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat *) = ::glClearBufferfv; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = ::glGetStringi; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar * const*, GLuint *) = ::glGetUniformIndices; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint *, GLenum, GLint *) = ::glGetActiveUniformsiv; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar *) = ::glGetUniformBlockIndex; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint *) = ::glGetActiveUniformBlockiv; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetActiveUniformBlockName; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid *, GLsizei) = ::glDrawElementsInstanced; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; -GLboolean (* const glIsSync)(GLsync) = ::glIsSync; -void (* const glDeleteSync)(GLsync) = ::glDeleteSync; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; -void (* const glGetInteger64v)(GLenum, GLint64 *) = ::glGetInteger64v; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei *, GLint *) = ::glGetSynciv; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64 *) = ::glGetInteger64i_v; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64 *) = ::glGetBufferParameteri64v; -void (* const glGenSamplers)(GLsizei, GLuint *) = ::glGenSamplers; -void (* const glDeleteSamplers)(GLsizei, const GLuint *) = ::glDeleteSamplers; -GLboolean (* const glIsSampler)(GLuint) = ::glIsSampler; -void (* const glBindSampler)(GLuint, GLuint) = ::glBindSampler; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint *) = ::glSamplerParameteriv; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat *) = ::glSamplerParameterfv; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint *) = ::glGetSamplerParameteriv; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat *) = ::glGetSamplerParameterfv; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; -void (* const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint *) = ::glDeleteTransformFeedbacks; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint *) = ::glGenTransformFeedbacks; -GLboolean (* const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; -void (* const glPauseTransformFeedback)() = ::glPauseTransformFeedback; -void (* const glResumeTransformFeedback)() = ::glResumeTransformFeedback; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei *, GLenum *, GLvoid *) = ::glGetProgramBinary; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid *, GLsizei) = ::glProgramBinary; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum *) = ::glInvalidateFramebuffer; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei) = ::glInvalidateSubFramebuffer; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint *) = ::glGetInternalformativ; +void (*const glReadBuffer)(GLenum) = ::glReadBuffer; +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = ::glDrawRangeElements; +void (*const glTexImage3D +)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = ::glTexImage3D; +void (*const glTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = ::glTexSubImage3D; +void (*const glCopyTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage3D; +void (*const glCompressedTexImage3D +)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = ::glCompressedTexImage3D; +void (*const glCompressedTexSubImage3D +)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = + ::glCompressedTexSubImage3D; +void (*const glGenQueries)(GLsizei, GLuint*) = ::glGenQueries; +void (*const glDeleteQueries)(GLsizei, const GLuint*) = ::glDeleteQueries; +GLboolean (*const glIsQuery)(GLuint) = ::glIsQuery; +void (*const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; +void (*const glEndQuery)(GLenum) = ::glEndQuery; +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = ::glGetQueryiv; +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = ::glGetQueryObjectuiv; +GLboolean (*const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = ::glGetBufferPointerv; +void (*const glDrawBuffers)(GLsizei, const GLenum*) = ::glDrawBuffers; +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x3fv; +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x2fv; +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x4fv; +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x2fv; +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x4fv; +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x3fv; +void (*const glBlitFramebuffer +)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = ::glBlitFramebuffer; +void (*const glRenderbufferStorageMultisample +)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorageMultisample; +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; +GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; +void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; +void (*const glBindVertexArray)(GLuint) = ::glBindVertexArray; +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = ::glDeleteVertexArrays; +void (*const glGenVertexArrays)(GLsizei, GLuint*) = ::glGenVertexArrays; +GLboolean (*const glIsVertexArray)(GLuint) = ::glIsVertexArray; +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = ::glGetIntegeri_v; +void (*const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; +void (*const glEndTransformFeedback)() = ::glEndTransformFeedback; +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; +void (*const glTransformFeedbackVaryings +)(GLuint, GLsizei, const GLchar* const*, GLenum) = ::glTransformFeedbackVaryings; +void (*const glGetTransformFeedbackVarying +)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = ::glGetTransformFeedbackVarying; +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = ::glVertexAttribIPointer; +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribIiv; +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = ::glGetVertexAttribIuiv; +void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; +void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = ::glVertexAttribI4iv; +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = ::glVertexAttribI4uiv; +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = ::glGetUniformuiv; +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = ::glGetFragDataLocation; +void (*const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; +void (*const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; +void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = ::glUniform1uiv; +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = ::glUniform2uiv; +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = ::glUniform3uiv; +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = ::glUniform4uiv; +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = ::glClearBufferiv; +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = ::glClearBufferuiv; +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = ::glClearBufferfv; +void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = ::glGetStringi; +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = ::glGetUniformIndices; +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = ::glGetActiveUniformsiv; +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = ::glGetUniformBlockIndex; +void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = ::glGetActiveUniformBlockiv; +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetActiveUniformBlockName; +void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; +void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = ::glDrawElementsInstanced; +GLsync (*const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; +GLboolean (*const glIsSync)(GLsync) = ::glIsSync; +void (*const glDeleteSync)(GLsync) = ::glDeleteSync; +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; +void (*const glGetInteger64v)(GLenum, GLint64*) = ::glGetInteger64v; +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = ::glGetSynciv; +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = ::glGetInteger64i_v; +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = ::glGetBufferParameteri64v; +void (*const glGenSamplers)(GLsizei, GLuint*) = ::glGenSamplers; +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = ::glDeleteSamplers; +GLboolean (*const glIsSampler)(GLuint) = ::glIsSampler; +void (*const glBindSampler)(GLuint, GLuint) = ::glBindSampler; +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = ::glSamplerParameteriv; +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; +void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = ::glSamplerParameterfv; +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = ::glGetSamplerParameteriv; +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = ::glGetSamplerParameterfv; +void (*const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; +void (*const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = ::glDeleteTransformFeedbacks; +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = ::glGenTransformFeedbacks; +GLboolean (*const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; +void (*const glPauseTransformFeedback)() = ::glPauseTransformFeedback; +void (*const glResumeTransformFeedback)() = ::glResumeTransformFeedback; +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = ::glGetProgramBinary; +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = ::glProgramBinary; +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; +void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = ::glInvalidateFramebuffer; +void (*const glInvalidateSubFramebuffer +)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = ::glInvalidateSubFramebuffer; +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = ::glGetInternalformativ; -} // namespace platform -} // namespace mbgl +} // namespace platform +} // namespace mbgl diff --git a/platform/windows/src/headless_backend_egl.cpp b/platform/windows/src/headless_backend_egl.cpp index 68b931916bf..0aff3baeca5 100644 --- a/platform/windows/src/headless_backend_egl.cpp +++ b/platform/windows/src/headless_backend_egl.cpp @@ -17,7 +17,9 @@ namespace gl { class EGLDisplayConfig { private: // Key for singleton construction. - struct Key { explicit Key() = default; }; + struct Key { + explicit Key() = default; + }; public: EGLDisplayConfig(Key) { @@ -38,11 +40,7 @@ class EGLDisplayConfig { throw std::runtime_error("eglBindAPI() failed"); } - const EGLint attribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, - EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, - EGL_NONE - }; + const EGLint attribs[] = {EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE}; // Note: we're choosing an arbitrary pixel format, since we're not using the default surface // anyway; all rendering will be directed to framebuffers which have their own configuration. @@ -51,9 +49,7 @@ class EGLDisplayConfig { } } - ~EGLDisplayConfig() { - eglTerminate(display); - } + ~EGLDisplayConfig() { eglTerminate(display); } static std::shared_ptr create() { static std::weak_ptr instance; @@ -76,15 +72,13 @@ class EGLBackendImpl : public HeadlessBackend::Impl { // use OpenGL ES 2.0 which has the ability to create shader and program // objects and also to write vertex and fragment shaders in the OpenGL ES // Shading Language. - const EGLint attribs[] = { - EGL_CONTEXT_CLIENT_VERSION, 2, - EGL_NONE - }; + const EGLint attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; eglContext = eglCreateContext(eglDisplay->display, eglDisplay->config, EGL_NO_CONTEXT, attribs); if (eglContext == EGL_NO_CONTEXT) { std::ostringstream logMsg; - logMsg << "eglCreateContext() returned error 0x" << std::setw(4) << std::setfill('0') << std::hex << eglGetError(); + logMsg << "eglCreateContext() returned error 0x" << std::setw(4) << std::setfill('0') << std::hex + << eglGetError(); mbgl::Log::Error(mbgl::Event::OpenGL, logMsg.str()); throw std::runtime_error("Error creating the EGL context object.\n"); } @@ -93,12 +87,7 @@ class EGLBackendImpl : public HeadlessBackend::Impl { // activate the context. // Note that to be able to create pbuffer surfaces, we need to choose a config that // includes EGL_SURFACE_TYPE, EGL_PBUFFER_BIT in HeadlessDisplay. - const EGLint surfAttribs[] = { - EGL_WIDTH, 8, - EGL_HEIGHT, 8, - EGL_LARGEST_PBUFFER, EGL_TRUE, - EGL_NONE - }; + const EGLint surfAttribs[] = {EGL_WIDTH, 8, EGL_HEIGHT, 8, EGL_LARGEST_PBUFFER, EGL_TRUE, EGL_NONE}; eglSurface = eglCreatePbufferSurface(eglDisplay->display, eglDisplay->config, surfAttribs); if (eglSurface == EGL_NO_SURFACE) { @@ -118,9 +107,7 @@ class EGLBackendImpl : public HeadlessBackend::Impl { } } - gl::ProcAddress getExtensionFunctionPointer(const char* name) final { - return eglGetProcAddress(name); - } + gl::ProcAddress getExtensionFunctionPointer(const char* name) final { return eglGetProcAddress(name); } void activateContext() final { if (!eglMakeCurrent(eglDisplay->display, eglSurface, eglSurface, eglContext)) { diff --git a/platform/windows/src/headless_backend_osmesa.cpp b/platform/windows/src/headless_backend_osmesa.cpp index 1484fcdd596..ee3325db376 100644 --- a/platform/windows/src/headless_backend_osmesa.cpp +++ b/platform/windows/src/headless_backend_osmesa.cpp @@ -15,29 +15,30 @@ namespace gl { class OSMesaBackendImpl final : public HeadlessBackend::Impl { public: OSMesaBackendImpl() { - context = OSMesaCreateContextAttribs(std::initializer_list({ - OSMESA_FORMAT, OSMESA_RGBA, - OSMESA_DEPTH_BITS, 24, - OSMESA_STENCIL_BITS, 8, - OSMESA_PROFILE, OSMESA_COMPAT_PROFILE, + context = OSMesaCreateContextAttribs( + std::initializer_list({OSMESA_FORMAT, + OSMESA_RGBA, + OSMESA_DEPTH_BITS, + 24, + OSMESA_STENCIL_BITS, + 8, + OSMESA_PROFILE, + OSMESA_COMPAT_PROFILE, + NULL}) + .begin(), NULL - }).begin(), NULL); + ); } - ~OSMesaBackendImpl() final { - OSMesaDestroyContext(context); - } + ~OSMesaBackendImpl() final { OSMesaDestroyContext(context); } gl::ProcAddress getExtensionFunctionPointer(const char* name) final { return (ProcAddress)::OSMesaGetProcAddress(name); } - void activateContext() final { - OSMesaMakeCurrent(context, buffer.get(), GL_UNSIGNED_BYTE, 2048, 2048); - } + void activateContext() final { OSMesaMakeCurrent(context, buffer.get(), GL_UNSIGNED_BYTE, 2048, 2048); } - void deactivateContext() final { - } + void deactivateContext() final {} private: std::unique_ptr buffer = std::make_unique(2048 * 2048 * 4); diff --git a/platform/windows/src/headless_backend_wgl.cpp b/platform/windows/src/headless_backend_wgl.cpp index dcfeec534c7..7712e1b54c6 100644 --- a/platform/windows/src/headless_backend_wgl.cpp +++ b/platform/windows/src/headless_backend_wgl.cpp @@ -21,9 +21,11 @@ namespace gl { class WGLDisplayConfig { private: // Key for singleton construction. - struct Key { explicit Key() = default; }; + struct Key { + explicit Key() = default; + }; - WNDCLASSEXA helperWindowClass = { sizeof(WNDCLASSEXA) }; + WNDCLASSEXA helperWindowClass = {sizeof(WNDCLASSEXA)}; HWND helperWindowHandle = NULL; HDC helperWindowDeviceContext = NULL; HGLRC helperWindowRenderingContext = NULL; @@ -33,7 +35,9 @@ class WGLDisplayConfig { MSG message; helperWindowClass.style = CS_OWNDC; - helperWindowClass.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hWnd, uMsg, wParam, lParam); }; + helperWindowClass.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { + return DefWindowProc(hWnd, uMsg, wParam, lParam); + }; helperWindowClass.lpszClassName = "WGL Helper Window"; GetModuleHandleExA(0, NULL, &helperWindowClass.hInstance); @@ -47,7 +51,10 @@ class WGLDisplayConfig { helperWindowClass.lpszClassName, "WGL Helper Window", WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - 0, 0, 1, 1, + 0, + 0, + 1, + 1, NULL, NULL, helperWindowClass.hInstance, @@ -79,18 +86,16 @@ class WGLDisplayConfig { bool StringInExtensionString(const char* string, const char* extensions) { const char* start = extensions; - while(true) { + while (true) { const char* where; const char* terminator; where = strstr(start, string); - if (!where) - return false; + if (!where) return false; terminator = where + strlen(string); if (where == start || *(where - 1) == ' ') { - if (*terminator == ' ' || *terminator == '\0') - break; + if (*terminator == ' ' || *terminator == '\0') break; } start = terminator; @@ -104,23 +109,23 @@ class WGLDisplayConfig { extensions = mbgl::platform::wglGetExtensionsStringARB(wglGetCurrentDC()); - if(!extensions || !StringInExtensionString(extension, extensions)) + if (!extensions || !StringInExtensionString(extension, extensions)) extensions = mbgl::platform::wglGetExtensionsStringEXT(); - if(!extensions || !StringInExtensionString(extension, extensions)) - extensions = (const char *)wgl_glGetString(GL_EXTENSIONS); + if (!extensions || !StringInExtensionString(extension, extensions)) + extensions = (const char*)wgl_glGetString(GL_EXTENSIONS); - if (!extensions) - return false; + if (!extensions) return false; return StringInExtensionString(extension, extensions); } + public: explicit WGLDisplayConfig(Key) { HDC dummyDC, previousDC; HGLRC dummyRC, previousRC; PIXELFORMATDESCRIPTOR pfd; - + CreateHelperWindow(); dummyDC = GetDC(helperWindowHandle); @@ -178,7 +183,9 @@ class WGLDisplayConfig { DestroyHelperWindow(); renderingWindowClass.style = CS_OWNDC; - renderingWindowClass.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hWnd, uMsg, wParam, lParam); }; + renderingWindowClass.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { + return DefWindowProc(hWnd, uMsg, wParam, lParam); + }; renderingWindowClass.lpszClassName = "WGL Rendering Window"; GetModuleHandleExA(0, NULL, &renderingWindowClass.hInstance); @@ -188,20 +195,19 @@ class WGLDisplayConfig { } } - ~WGLDisplayConfig() { - UnregisterClassA(renderingWindowClass.lpszClassName, renderingWindowClass.hInstance); - } + ~WGLDisplayConfig() { UnregisterClassA(renderingWindowClass.lpszClassName, renderingWindowClass.hInstance); } static std::shared_ptr create() { static std::weak_ptr instance; auto shared = instance.lock(); - + if (!shared) { instance = shared = std::make_shared(Key{}); } - + return shared; } + public: bool ARB_multisample = false; bool ARB_create_context = false; @@ -209,7 +215,7 @@ class WGLDisplayConfig { bool EXT_colorspace = false; bool ARB_pixel_format = false; bool ARB_ES3_compatibility = false; - WNDCLASSEXA renderingWindowClass = { sizeof(WNDCLASSEXA) }; + WNDCLASSEXA renderingWindowClass = {sizeof(WNDCLASSEXA)}; }; class WGLBackendImpl final : public HeadlessBackend::Impl { @@ -219,6 +225,7 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { HWND renderingWindowHandle = NULL; HDC renderingWindowDeviceContext = NULL; HGLRC renderingWindowRenderingContext = NULL; + private: void CreateRenderingWindow() { MSG message; @@ -228,7 +235,10 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { wglDisplayConfig->renderingWindowClass.lpszClassName, "WGL Render Window", WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - 0, 0, 1, 1, + 0, + 0, + 1, + 1, NULL, NULL, wglDisplayConfig->renderingWindowClass.hInstance, @@ -282,17 +292,31 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { renderingWindowDeviceContext = GetDC(renderingWindowHandle); } - if (!mbgl::platform::wglChoosePixelFormatARB(renderingWindowDeviceContext, std::initializer_list({ - WGL_SUPPORT_OPENGL_ARB, GL_TRUE, - WGL_DOUBLE_BUFFER_ARB, GL_TRUE, - WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, - WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, - WGL_COLOR_BITS_ARB, 24, - WGL_ALPHA_BITS_ARB, 8, - WGL_DEPTH_BITS_ARB, 24, - WGL_STENCIL_BITS_ARB, 8, - NULL - }).begin(), NULL, 1, &pixelFormat, &numFormats)) { + if (!mbgl::platform::wglChoosePixelFormatARB( + renderingWindowDeviceContext, + std::initializer_list({WGL_SUPPORT_OPENGL_ARB, + GL_TRUE, + WGL_DOUBLE_BUFFER_ARB, + GL_TRUE, + WGL_ACCELERATION_ARB, + WGL_FULL_ACCELERATION_ARB, + WGL_PIXEL_TYPE_ARB, + WGL_TYPE_RGBA_ARB, + WGL_COLOR_BITS_ARB, + 24, + WGL_ALPHA_BITS_ARB, + 8, + WGL_DEPTH_BITS_ARB, + 24, + WGL_STENCIL_BITS_ARB, + 8, + NULL}) + .begin(), + NULL, + 1, + &pixelFormat, + &numFormats + )) { Log::Error(Event::OpenGL, "Failed to choose pixel format for context"); throw std::runtime_error("Failed to choose pixel format for context"); } @@ -312,13 +336,18 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { } if (wglDisplayConfig->ARB_create_context) { - renderingWindowRenderingContext = mbgl::platform::wglCreateContextAttribsARB(renderingWindowDeviceContext, NULL, - std::initializer_list({ - WGL_CONTEXT_MAJOR_VERSION_ARB, 3, - WGL_CONTEXT_MINOR_VERSION_ARB, 0, - WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, - NULL - }).begin()); + renderingWindowRenderingContext = mbgl::platform::wglCreateContextAttribsARB( + renderingWindowDeviceContext, + NULL, + std::initializer_list({WGL_CONTEXT_MAJOR_VERSION_ARB, + 3, + WGL_CONTEXT_MINOR_VERSION_ARB, + 0, + WGL_CONTEXT_PROFILE_MASK_ARB, + WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, + NULL}) + .begin() + ); if (!renderingWindowRenderingContext) { const DWORD error = GetLastError(); @@ -326,24 +355,20 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { if (error == (0xc0070000 | ERROR_INVALID_VERSION_ARB)) { Log::Error(Event::OpenGL, "Driver does not support OpenGL ES version 2.0"); throw std::runtime_error("Driver does not support OpenGL ES version 2.0"); - } - else if (error == (0xc0070000 | ERROR_INVALID_PROFILE_ARB)) { + } else if (error == (0xc0070000 | ERROR_INVALID_PROFILE_ARB)) { Log::Error(Event::OpenGL, "Driver does not support the requested OpenGL profile"); throw std::runtime_error("Driver does not support the requested OpenGL profile"); - } - else if (error == (0xc0070000 | ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB)) { + } else if (error == (0xc0070000 | ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB)) { Log::Error(Event::OpenGL, "The share context is not compatible with the requested context"); throw std::runtime_error("The share context is not compatible with the requested context"); - } - else { + } else { Log::Error(Event::OpenGL, "Failed to create OpenGL ES context"); throw std::runtime_error("Failed to create OpenGL ES context"); } return false; } - } - else { + } else { renderingWindowRenderingContext = wglCreateContext(renderingWindowDeviceContext); if (!renderingWindowRenderingContext) { @@ -365,13 +390,13 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { bool DestroyRenderingContext() { if (renderingWindowRenderingContext && !wglMakeCurrent(renderingWindowDeviceContext, NULL)) { Log::Error(Event::OpenGL, "Failed to make context current"); - //throw std::runtime_error("Failed to make context current"); + // throw std::runtime_error("Failed to make context current"); return false; } if (renderingWindowRenderingContext && !wglDeleteContext(renderingWindowRenderingContext)) { Log::Error(Event::OpenGL, "Failed to delete current context"); - //throw std::runtime_error("Failed to delete current context"); + // throw std::runtime_error("Failed to delete current context"); return false; } @@ -381,9 +406,7 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { } public: - WGLBackendImpl() { - auto renderingContext = GetContext(); - } + WGLBackendImpl() { auto renderingContext = GetContext(); } ~WGLBackendImpl() final { if (renderingWindowRenderingContext) { @@ -398,16 +421,17 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { } void activateContext() final { - if (renderingWindowRenderingContext && !wglMakeCurrent(renderingWindowDeviceContext, renderingWindowRenderingContext)) { + if (renderingWindowRenderingContext && + !wglMakeCurrent(renderingWindowDeviceContext, renderingWindowRenderingContext)) { Log::Error(Event::OpenGL, "Switching OpenGL context failed"); - //throw std::runtime_error("Switching OpenGL context failed"); + // throw std::runtime_error("Switching OpenGL context failed"); } } void deactivateContext() final { if (renderingWindowRenderingContext && !wglMakeCurrent(NULL, NULL)) { Log::Error(Event::OpenGL, "Removing OpenGL context failed"); - //throw std::runtime_error("Removing OpenGL context failed"); + // throw std::runtime_error("Removing OpenGL context failed"); } } }; diff --git a/platform/windows/src/thread.cpp b/platform/windows/src/thread.cpp index 22405dcfcd8..9c1b597c701 100644 --- a/platform/windows/src/thread.cpp +++ b/platform/windows/src/thread.cpp @@ -20,11 +20,10 @@ void SetThreadName(DWORD dwThreadID, const char* threadName) { info.dwFlags = 0; #pragma warning(push) -#pragma warning(disable: 6320 6322) +#pragma warning(disable : 6320 6322) __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); - } - __except (EXCEPTION_EXECUTE_HANDLER){ + } __except (EXCEPTION_EXECUTE_HANDLER) { } #pragma warning(pop) } @@ -50,24 +49,22 @@ namespace platform { std::string getCurrentThreadName() { THREAD_INFO* info = GetCurrentThreadInfo(); - if (info && info->name) - { + if (info && info->name) { return std::string(info->name); } - + return std::string(); } void setCurrentThreadName(const std::string& name) { THREAD_INFO* info = GetCurrentThreadInfo(); - if (info && info->name) - { + if (info && info->name) { free(info->name); info->name = new char[name.length() + 1]; std::strcpy(info->name, name.c_str()); } - + SetThreadName(-1, name.c_str()); } diff --git a/render-test/allocation_index.cpp b/render-test/allocation_index.cpp index 144c18ddd5d..7f776076db2 100644 --- a/render-test/allocation_index.cpp +++ b/render-test/allocation_index.cpp @@ -19,7 +19,9 @@ std::mutex indexMutex; class FlagGuard { public: explicit FlagGuard(std::atomic_bool& flag_) - : flag(flag_) { flag = true; } + : flag(flag_) { + flag = true; + } ~FlagGuard() { flag = false; } private: @@ -74,7 +76,7 @@ void AllocationIndex::reset() { // static void* AllocationIndex::allocate(size_t size) { - void *ptr = std::malloc(size); + void* ptr = std::malloc(size); if (ptr && canModifyIndex()) addToIndex(size, ptr); return ptr; } diff --git a/render-test/allocation_index.hpp b/render-test/allocation_index.hpp index 71da441c1f9..00d00046c85 100644 --- a/render-test/allocation_index.hpp +++ b/render-test/allocation_index.hpp @@ -20,34 +20,34 @@ class AllocationIndex { /** * @brief Same as `malloc()` + indexes the allocated data, * if indexing is active. - * - * @return void* + * + * @return void* */ static void* allocate(size_t); /** * @brief Same as `free()` + removes the corresponding data from index, * if these data are present in the index and indexing is active. - * - * @return void* + * + * @return void* */ static void deallocate(void*) noexcept; /** * @brief Returns the size (in bytes) of allocated data, currently present in the index. - * + * * @return size_t */ static size_t getAllocatedSize(); /** * @brief Returns the total amount of allocations since indexing start. - * - * @return size_t + * + * @return size_t */ static size_t getAllocationsCount(); /** * @brief Returns the maximum size (in bytes) of the allocated data in the index, since last `reset()` call. - * - * @return size_t + * + * @return size_t */ static size_t getAllocatedSizePeak(); }; diff --git a/render-test/file_source.cpp b/render-test/file_source.cpp index 51810dc27d2..e047f33ad4d 100644 --- a/render-test/file_source.cpp +++ b/render-test/file_source.cpp @@ -16,15 +16,22 @@ std::atomic_size_t transferredSize{0}; std::atomic_bool active{false}; std::atomic_bool offline{true}; -ProxyFileSource::ProxyFileSource(std::shared_ptr defaultResourceLoader_, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) +ProxyFileSource::ProxyFileSource( + std::shared_ptr defaultResourceLoader_, + const ResourceOptions& resourceOptions_, + const ClientOptions& clientOptions_ +) : defaultResourceLoader(std::move(defaultResourceLoader_)), - resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()) { + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) { assert(defaultResourceLoader); if (offline) { - std::shared_ptr dbfs = FileSourceManager::get()->getFileSource(FileSourceType::Database, resourceOptions_, clientOptions_); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, resourceOptions_, clientOptions_ + ); dbfs->setProperty(READ_ONLY_MODE_KEY, true); } -} +} ProxyFileSource::~ProxyFileSource() = default; @@ -59,10 +66,10 @@ std::unique_ptr ProxyFileSource::request(const Resource& resource, return defaultResourceLoader->request(transformed, [=](Response response) { if (transformed.loadingMethod == Resource::LoadingMethod::CacheOnly && response.noContent) { if (transformed.kind == Resource::Kind::Tile && transformed.tileData) { - mbgl::Log::Info(mbgl::Event::Database, - "Resource not found in cache: " + - transformed.url + "(" + - transformed.tileData->urlTemplate + ")"); + mbgl::Log::Info( + mbgl::Event::Database, + "Resource not found in cache: " + transformed.url + "(" + transformed.tileData->urlTemplate + ")" + ); } else { mbgl::Log::Info(mbgl::Event::Database, "Resource not found in cache: " + transformed.url); } @@ -78,7 +85,7 @@ std::unique_ptr ProxyFileSource::request(const Resource& resource, } void ProxyFileSource::setResourceOptions(ResourceOptions options) { - resourceOptions = options; + resourceOptions = options; } ResourceOptions ProxyFileSource::getResourceOptions() { @@ -86,14 +93,13 @@ ResourceOptions ProxyFileSource::getResourceOptions() { } void ProxyFileSource::setClientOptions(ClientOptions options) { - clientOptions = options; + clientOptions = options; } ClientOptions ProxyFileSource::getClientOptions() { return clientOptions.clone(); } - // static void ProxyFileSource::setOffline(bool status) { offline = status; diff --git a/render-test/file_source.hpp b/render-test/file_source.hpp index b03b70142eb..c06d223079d 100644 --- a/render-test/file_source.hpp +++ b/render-test/file_source.hpp @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace mbgl { diff --git a/render-test/manifest_parser.cpp b/render-test/manifest_parser.cpp index 27589140f33..c27736643ca 100644 --- a/render-test/manifest_parser.cpp +++ b/render-test/manifest_parser.cpp @@ -75,9 +75,11 @@ std::vector> parseIgnores(const std::vector< // defaultExpectationPath: absolute path that constains the style.json file for testing // testId: Test case id that used for composing expectation path // expectatedPaths: absolute paths that constain possible expected.png/metrics.json files for result checking -std::vector getTestExpectations(const mbgl::filesystem::path& defaultExpectationPath, - const std::string& testId, - std::vector expectatedPaths) { +std::vector getTestExpectations( + const mbgl::filesystem::path& defaultExpectationPath, + const std::string& testId, + std::vector expectatedPaths +) { std::vector expectations{defaultExpectationPath}; for (const auto& expectedPath : expectatedPaths) { expectations.emplace_back(expectedPath / testId); @@ -100,15 +102,16 @@ mbgl::filesystem::path getValidPath(const std::string& manifestPath, const std:: } // namespace -std::optional ManifestParser::parseManifest(const std::string& manifestPath, - std::string testFilter) { +std::optional ManifestParser::parseManifest(const std::string& manifestPath, std::string testFilter) { Manifest manifest; const auto filePath = mbgl::filesystem::path(manifestPath); manifest.manifestPath = manifestPath.substr(0, manifestPath.find(filePath.filename())); auto contents = readJson(filePath); if (!contents.is()) { - mbgl::Log::Error(mbgl::Event::General, "Provided manifest file: " + std::string(filePath) + " is not a valid json"); + mbgl::Log::Error( + mbgl::Event::General, "Provided manifest file: " + std::string(filePath) + " is not a valid json" + ); return std::nullopt; } @@ -117,7 +120,9 @@ std::optional ManifestParser::parseManifest(const std::string& manifes const auto& resultPathValue = document["result_path"]; if (!resultPathValue.IsString()) { mbgl::Log::Warning( - mbgl::Event::General, "Invalid result_path is provided inside the manifest file: " + std::string(filePath)); + mbgl::Event::General, + "Invalid result_path is provided inside the manifest file: " + std::string(filePath) + ); return std::nullopt; } manifest.resultPath = (getValidPath(manifest.manifestPath, resultPathValue.GetString()) / "").string(); @@ -129,7 +134,9 @@ std::optional ManifestParser::parseManifest(const std::string& manifes const auto& cachePathValue = document["cache_path"]; if (!cachePathValue.IsString()) { mbgl::Log::Warning( - mbgl::Event::General, "Invalid cache_path is provided inside the manifest file: " + std::string(filePath)); + mbgl::Event::General, + "Invalid cache_path is provided inside the manifest file: " + std::string(filePath) + ); return std::nullopt; } manifest.cachePath = (getValidPath(manifest.manifestPath, ".") / cachePathValue.GetString()).string(); @@ -137,12 +144,14 @@ std::optional ManifestParser::parseManifest(const std::string& manifes return std::nullopt; } } - //TODO:PP + // TODO:PP if (document.HasMember("access_token")) { const auto& apiKeyValue = document["access_token"]; if (!apiKeyValue.IsString()) { - mbgl::Log::Warning(mbgl::Event::General, - "Invalid access_token is provided inside the manifest file: " + std::string(filePath)); + mbgl::Log::Warning( + mbgl::Event::General, + "Invalid access_token is provided inside the manifest file: " + std::string(filePath) + ); return std::nullopt; } manifest.apiKey = apiKeyValue.GetString(); @@ -154,8 +163,10 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (document.HasMember("base_test_path")) { const auto& testPathValue = document["base_test_path"]; if (!testPathValue.IsString()) { - mbgl::Log::Warning(mbgl::Event::General, - "Invalid base_test_path is provided inside the manifest file: " + std::string(filePath)); + mbgl::Log::Warning( + mbgl::Event::General, + "Invalid base_test_path is provided inside the manifest file: " + std::string(filePath) + ); return std::nullopt; } baseTestPath = getValidPath(manifest.manifestPath, testPathValue.GetString()); @@ -168,7 +179,9 @@ std::optional ManifestParser::parseManifest(const std::string& manifes const auto& metricPathValue = document["metric_path"]; if (!metricPathValue.IsString()) { mbgl::Log::Warning( - mbgl::Event::General, "Invalid metric_path is provided inside the manifest file: " + std::string(filePath)); + mbgl::Event::General, + "Invalid metric_path is provided inside the manifest file: " + std::string(filePath) + ); return std::nullopt; } expectedMetricPath = getValidPath(manifest.manifestPath, metricPathValue.GetString()); @@ -180,14 +193,18 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (document.HasMember("expectation_paths")) { const auto& expectationPathValue = document["expectation_paths"]; if (!expectationPathValue.IsArray()) { - mbgl::Log::Warning(mbgl::Event::General, - "Provided expectation_paths inside the manifest file: %s is not a valid array" + std::string(filePath)); + mbgl::Log::Warning( + mbgl::Event::General, + "Provided expectation_paths inside the manifest file: %s is not a valid array" + std::string(filePath) + ); return std::nullopt; } for (const auto& value : expectationPathValue.GetArray()) { if (!value.IsString()) { - mbgl::Log::Warning(mbgl::Event::General, - "Invalid expectation path item is provided inside the manifest file: " + std::string(filePath)); + mbgl::Log::Warning( + mbgl::Event::General, + "Invalid expectation path item is provided inside the manifest file: " + std::string(filePath) + ); return std::nullopt; } expectationPaths.emplace_back(getValidPath(manifest.manifestPath, value.GetString())); @@ -200,14 +217,18 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (document.HasMember("ignore_paths")) { const auto& ignorePathValue = document["ignore_paths"]; if (!ignorePathValue.IsArray()) { - mbgl::Log::Warning(mbgl::Event::General, - "Provided ignore_paths inside the manifest file: " + std::string(filePath) + " is not a valid array"); + mbgl::Log::Warning( + mbgl::Event::General, + "Provided ignore_paths inside the manifest file: " + std::string(filePath) + " is not a valid array" + ); return std::nullopt; } for (const auto& value : ignorePathValue.GetArray()) { if (!value.IsString()) { - mbgl::Log::Warning(mbgl::Event::General, - "Invalid ignore path item is provided inside the manifest file: " + std::string(filePath)); + mbgl::Log::Warning( + mbgl::Event::General, + "Invalid ignore path item is provided inside the manifest file: " + std::string(filePath) + ); return std::nullopt; } ignorePaths.emplace_back(getValidPath(manifest.manifestPath, value.GetString())); @@ -221,15 +242,18 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (document.HasMember("probes")) { const auto& probesValue = document["probes"]; if (!probesValue.IsArray()) { - mbgl::Log::Warning(mbgl::Event::General, - "Provided probes inside the manifest file: " + std::string(filePath) + "is not a valid array"); + mbgl::Log::Warning( + mbgl::Event::General, + "Provided probes inside the manifest file: " + std::string(filePath) + "is not a valid array" + ); return std::nullopt; } for (const auto& value : probesValue.GetArray()) { if (!value.IsString()) { - mbgl::Log::Warning(mbgl::Event::General, - "Invalid probe type is provided inside the manifest file: " + - std::string(filePath)); + mbgl::Log::Warning( + mbgl::Event::General, + "Invalid probe type is provided inside the manifest file: " + std::string(filePath) + ); return std::nullopt; } manifest.probes.emplace(value.GetString()); @@ -240,7 +264,8 @@ std::optional ManifestParser::parseManifest(const std::string& manifes const auto& filterValue = document["filter"]; if (!filterValue.IsString()) { mbgl::Log::Warning( - mbgl::Event::General, "Invalid filter is provided inside the manifest file: " + std::string(filePath)); + mbgl::Event::General, "Invalid filter is provided inside the manifest file: " + std::string(filePath) + ); return std::nullopt; } @@ -281,9 +306,11 @@ std::optional ManifestParser::parseManifest(const std::string& manifes #elif defined(__APPLE__) expectedMetricPaths.emplace_back(manifest.manifestPath + "/baselines/"); #endif - testPaths.emplace_back(testPath, - getTestExpectations(defaultExpectationPath, testId, expectationPaths), - getTestExpectations(defaultExpectationPath, testId, expectedMetricPaths)); + testPaths.emplace_back( + testPath, + getTestExpectations(defaultExpectationPath, testId, expectationPaths), + getTestExpectations(defaultExpectationPath, testId, expectedMetricPaths) + ); } } diff --git a/render-test/manifest_parser.hpp b/render-test/manifest_parser.hpp index 2fad5ce7272..14c58703a79 100644 --- a/render-test/manifest_parser.hpp +++ b/render-test/manifest_parser.hpp @@ -39,6 +39,5 @@ class Manifest { class ManifestParser { public: - static std::optional parseManifest(const std::string& manifestPath, - std::string testFilter); + static std::optional parseManifest(const std::string& manifestPath, std::string testFilter); }; diff --git a/render-test/metadata.hpp b/render-test/metadata.hpp index 07cb599042b..ef179c7f2c2 100644 --- a/render-test/metadata.hpp +++ b/render-test/metadata.hpp @@ -34,9 +34,11 @@ struct TestStatistics { struct TestPaths { TestPaths() = default; - TestPaths(mbgl::filesystem::path stylePath_, - std::vector expectations_, - std::vector expectedMetrics_) + TestPaths( + mbgl::filesystem::path stylePath_, + std::vector expectations_, + std::vector expectedMetrics_ + ) : stylePath(std::move(stylePath_)), expectations(std::move(expectations_)), expectedMetrics(std::move(expectedMetrics_)) {} @@ -60,7 +62,9 @@ inline std::tuple checkValue(float expected, float actual, float to struct FileSizeProbe { FileSizeProbe() = default; FileSizeProbe(std::string path_, uintmax_t size_, float tolerance_) - : path(std::move(path_)), size(size_), tolerance(tolerance_) {} + : path(std::move(path_)), + size(size_), + tolerance(tolerance_) {} std::string path; uintmax_t size; @@ -69,7 +73,10 @@ struct FileSizeProbe { struct MemoryProbe { MemoryProbe() = default; - MemoryProbe(size_t peak_, size_t allocations_) : peak(peak_), allocations(allocations_), tolerance(0.0f) {} + MemoryProbe(size_t peak_, size_t allocations_) + : peak(peak_), + allocations(allocations_), + tolerance(0.0f) {} size_t peak; size_t allocations; @@ -80,7 +87,9 @@ struct MemoryProbe { } static std::tuple checkAllocations(const MemoryProbe& expected, const MemoryProbe& actual) { - return checkValue(static_cast(expected.allocations), static_cast(actual.allocations), actual.tolerance); + return checkValue( + static_cast(expected.allocations), static_cast(actual.allocations), actual.tolerance + ); } }; @@ -92,7 +101,9 @@ struct FpsProbe { struct NetworkProbe { NetworkProbe() = default; - NetworkProbe(size_t requests_, size_t transferred_) : requests(requests_), transferred(transferred_) {} + NetworkProbe(size_t requests_, size_t transferred_) + : requests(requests_), + transferred(transferred_) {} size_t requests; size_t transferred; @@ -101,7 +112,9 @@ struct NetworkProbe { struct GfxProbe { struct Memory { Memory() = default; - Memory(int allocated_, int peak_) : allocated(allocated_), peak(peak_) {} + Memory(int allocated_, int peak_) + : allocated(allocated_), + peak(peak_) {} int allocated; int peak; @@ -144,7 +157,7 @@ struct TestMetadata { // to prevent the unit test fail, and just verify the render result. bool ignoreProbing = false; - mbgl::Size size{ 512u, 512u }; + mbgl::Size size{512u, 512u}; float pixelRatio = 1.0f; double allowed = 0.00015; // diff std::string description; @@ -185,7 +198,6 @@ struct TestMetadata { std::string errorMessage; double difference = 0.0; - }; class TestContext { diff --git a/render-test/parser.cpp b/render-test/parser.cpp index e42f00b1ae3..2a044db3b5c 100644 --- a/render-test/parser.cpp +++ b/render-test/parser.cpp @@ -103,28 +103,30 @@ const char* resultsHeaderButtons = R"HTML( )HTML"; void writeJSON(rapidjson::PrettyWriter& writer, const mbgl::Value& value) { - value.match([&writer](const mbgl::NullValue&) { writer.Null(); }, - [&writer](bool b) { writer.Bool(b); }, - [&writer](uint64_t u) { writer.Uint64(u); }, - [&writer](int64_t i) { writer.Int64(i); }, - [&writer](double d) { d == std::floor(d) ? writer.Int64(static_cast(d)) : writer.Double(d); }, - [&writer](const std::string& s) { writer.String(s); }, - [&writer](const std::vector& arr) { - writer.StartArray(); - for (const auto& item : arr) { - writeJSON(writer, item); - } - writer.EndArray(); - }, - [&writer](const std::unordered_map& obj) { - writer.StartObject(); - std::map sorted(obj.begin(), obj.end()); - for (const auto& entry : sorted) { - writer.Key(entry.first.c_str()); - writeJSON(writer, entry.second); - } - writer.EndObject(); - }); + value.match( + [&writer](const mbgl::NullValue&) { writer.Null(); }, + [&writer](bool b) { writer.Bool(b); }, + [&writer](uint64_t u) { writer.Uint64(u); }, + [&writer](int64_t i) { writer.Int64(i); }, + [&writer](double d) { d == std::floor(d) ? writer.Int64(static_cast(d)) : writer.Double(d); }, + [&writer](const std::string& s) { writer.String(s); }, + [&writer](const std::vector& arr) { + writer.StartArray(); + for (const auto& item : arr) { + writeJSON(writer, item); + } + writer.EndArray(); + }, + [&writer](const std::unordered_map& obj) { + writer.StartObject(); + std::map sorted(obj.begin(), obj.end()); + for (const auto& entry : sorted) { + writer.Key(entry.first.c_str()); + writeJSON(writer, entry.second); + } + writer.EndObject(); + } + ); } } // namespace @@ -154,7 +156,8 @@ std::string toJSON(const std::vector& features, unsigned indent, result.AddMember("type", "Feature", allocator); if (!feature.id.is()) { result.AddMember( - "id", mapbox::geojson::identifier::visit(feature.id, mapbox::geojson::to_value{allocator}), allocator); + "id", mapbox::geojson::identifier::visit(feature.id, mapbox::geojson::to_value{allocator}), allocator + ); } result.AddMember("geometry", mapbox::geojson::convert(feature.geometry, allocator), allocator); result.AddMember("properties", mapbox::geojson::to_value{allocator}(feature.properties), allocator); @@ -172,13 +175,13 @@ std::string toJSON(const std::vector& features, unsigned indent, JSONReply readJson(const mbgl::filesystem::path& jsonPath) { auto maybeJSON = mbgl::util::readFile(jsonPath); if (!maybeJSON) { - return { std::string("Unable to open file ") + jsonPath.string() }; + return {std::string("Unable to open file ") + jsonPath.string()}; } mbgl::JSDocument document; document.Parse<0>(*maybeJSON); if (document.HasParseError()) { - return { mbgl::formatJSONParseError(document) }; + return {mbgl::formatJSONParseError(document)}; } return {std::move(document)}; @@ -350,9 +353,11 @@ TestMetrics readExpectedMetrics(const mbgl::filesystem::path& path) { std::string filePath{probeValue[1].GetString(), probeValue[1].GetStringLength()}; assert(!filePath.empty()); - result.fileSize.emplace(std::piecewise_construct, - std::forward_as_tuple(std::move(mark)), - std::forward_as_tuple(std::move(filePath), probeValue[2].GetUint64(), 0.f)); + result.fileSize.emplace( + std::piecewise_construct, + std::forward_as_tuple(std::move(mark)), + std::forward_as_tuple(std::move(filePath), probeValue[2].GetUint64(), 0.f) + ); } } @@ -368,9 +373,11 @@ TestMetrics readExpectedMetrics(const mbgl::filesystem::path& path) { std::string mark{probeValue[0].GetString(), probeValue[0].GetStringLength()}; assert(!mark.empty()); - result.memory.emplace(std::piecewise_construct, - std::forward_as_tuple(std::move(mark)), - std::forward_as_tuple(probeValue[1].GetUint64(), probeValue[2].GetUint64())); + result.memory.emplace( + std::piecewise_construct, + std::forward_as_tuple(std::move(mark)), + std::forward_as_tuple(probeValue[1].GetUint64(), probeValue[2].GetUint64()) + ); } } @@ -387,9 +394,11 @@ TestMetrics readExpectedMetrics(const mbgl::filesystem::path& path) { std::string mark{probeValue[0].GetString(), probeValue[0].GetStringLength()}; assert(!mark.empty()); - result.network.emplace(std::piecewise_construct, - std::forward_as_tuple(std::move(mark)), - std::forward_as_tuple(probeValue[1].GetUint64(), probeValue[2].GetUint64())); + result.network.emplace( + std::piecewise_construct, + std::forward_as_tuple(std::move(mark)), + std::forward_as_tuple(probeValue[1].GetUint64(), probeValue[2].GetUint64()) + ); } } @@ -406,7 +415,8 @@ TestMetrics readExpectedMetrics(const mbgl::filesystem::path& path) { const std::string mark{probeValue[0].GetString(), probeValue[0].GetStringLength()}; assert(!mark.empty()); result.fps.insert( - {std::move(mark), {probeValue[1].GetFloat(), probeValue[2].GetFloat(), probeValue[3].GetFloat()}}); + {std::move(mark), {probeValue[1].GetFloat(), probeValue[2].GetFloat(), probeValue[3].GetFloat()}} + ); } } @@ -486,7 +496,8 @@ TestMetadata parseTestMetadata(const TestPaths& paths) { metadata.mapMode = mbgl::MapMode::Static; else { mbgl::Log::Warning( - mbgl::Event::ParseStyle, "Unknown map mode: " + mapModeStr + ". Falling back to static mode"); + mbgl::Event::ParseStyle, "Unknown map mode: " + mapModeStr + ". Falling back to static mode" + ); metadata.mapMode = mbgl::MapMode::Static; } } @@ -521,8 +532,8 @@ TestMetadata parseTestMetadata(const TestPaths& paths) { if (testValue.HasMember("description")) { assert(testValue["description"].IsString()); - metadata.description = - std::string{testValue["description"].GetString(), testValue["description"].GetStringLength()}; + metadata.description = std::string{ + testValue["description"].GetString(), testValue["description"].GetStringLength()}; } // Test operations handled in runner.cpp. @@ -568,7 +579,7 @@ TestMetadata parseTestMetadata(const TestPaths& paths) { } metadata.renderTest = false; } - + if (testValue.HasMember("ignoreProbing")) { if (testValue["ignoreProbing"].IsBool()) { metadata.ignoreProbing = testValue["ignoreProbing"].GetBool(); @@ -714,14 +725,16 @@ TestOperations parseTestOperations(TestMetadata& metadata) { std::optional maybeImage; bool requestCompleted = false; - auto req = ctx.getFileSource().request(mbgl::Resource::image("mapbox://render-tests/" + imagePath), - [&](mbgl::Response response) { - if (response.data) { - maybeImage = *response.data; - } + auto req = ctx.getFileSource().request( + mbgl::Resource::image("mapbox://render-tests/" + imagePath), + [&](mbgl::Response response) { + if (response.data) { + maybeImage = *response.data; + } - requestCompleted = true; - }); + requestCompleted = true; + } + ); while (!requestCompleted) { mbgl::util::RunLoop::Get()->runOnce(); @@ -733,7 +746,8 @@ TestOperations parseTestOperations(TestMetadata& metadata) { } ctx.getMap().getStyle().addImage( - std::make_unique(imageName, mbgl::decodeImage(*maybeImage), pixelRatio, sdf)); + std::make_unique(imageName, mbgl::decodeImage(*maybeImage), pixelRatio, sdf) + ); return true; }); @@ -879,8 +893,9 @@ TestOperations parseTestOperations(TestMetadata& metadata) { assert(operationArray.Size() >= 2u); assert(operationArray[1].IsString()); std::string layerName = operationArray[1].GetString(); - result.emplace_back( - [layerName](TestContext& ctx) { return bool(ctx.getMap().getStyle().removeLayer(layerName)); }); + result.emplace_back([layerName](TestContext& ctx) { + return bool(ctx.getMap().getStyle().removeLayer(layerName)); + }); } else if (operationArray[0].GetString() == addSourceOp) { // addSource assert(operationArray.Size() >= 3u); @@ -890,8 +905,9 @@ TestOperations parseTestOperations(TestMetadata& metadata) { result.emplace_back([sourceName, json = serializeJsonValue(operationArray[2])](TestContext& ctx) { mbgl::style::conversion::Error error; - auto converted = - mbgl::style::conversion::convertJSON>(json, error, sourceName); + auto converted = mbgl::style::conversion::convertJSON>( + json, error, sourceName + ); if (!converted) { ctx.getMetadata().errorMessage = std::string("Unable to convert source: ") + error.message; return false; @@ -904,10 +920,10 @@ TestOperations parseTestOperations(TestMetadata& metadata) { assert(operationArray.Size() >= 2u); assert(operationArray[1].IsString()); std::string sourceName = operationArray[1].GetString(); - result.emplace_back( - [sourceName](TestContext& ctx) { return bool(ctx.getMap().getStyle().removeSource(sourceName)); }); - } else if (operationArray[0].GetString() == setLayoutPropertyOp || - operationArray[0].GetString() == setPaintPropertyOp) { + result.emplace_back([sourceName](TestContext& ctx) { + return bool(ctx.getMap().getStyle().removeSource(sourceName)); + }); + } else if (operationArray[0].GetString() == setLayoutPropertyOp || operationArray[0].GetString() == setPaintPropertyOp) { // set{Paint|Layout}Property assert(operationArray.Size() >= 4u); assert(operationArray[1].IsString()); @@ -915,19 +931,19 @@ TestOperations parseTestOperations(TestMetadata& metadata) { std::string layerName{operationArray[1].GetString(), operationArray[1].GetStringLength()}; std::string propertyName{operationArray[2].GetString(), operationArray[2].GetStringLength()}; - result.emplace_back( - [layerName, propertyName, json = serializeJsonValue(operationArray[3])](TestContext& ctx) { - auto layer = ctx.getMap().getStyle().getLayer(layerName); - if (!layer) { - ctx.getMetadata().errorMessage = std::string("Layer not found: ") + layerName; - return false; - } - mbgl::JSDocument d; - d.Parse(json.c_str(), json.length()); - const mbgl::JSValue* propertyValue = &d; - layer->setProperty(propertyName, propertyValue); - return true; - }); + result.emplace_back([layerName, propertyName, json = serializeJsonValue(operationArray[3])](TestContext& ctx + ) { + auto layer = ctx.getMap().getStyle().getLayer(layerName); + if (!layer) { + ctx.getMetadata().errorMessage = std::string("Layer not found: ") + layerName; + return false; + } + mbgl::JSDocument d; + d.Parse(json.c_str(), json.length()); + const mbgl::JSValue* propertyValue = &d; + layer->setProperty(propertyName, propertyValue); + return true; + }); } else if (operationArray[0].GetString() == fileSizeProbeOp) { // probeFileSize assert(operationArray.Size() >= 4u); @@ -964,9 +980,11 @@ TestOperations parseTestOperations(TestMetadata& metadata) { size = mbgl::filesystem::file_size(filePath); } - ctx.getMetadata().metrics.fileSize.emplace(std::piecewise_construct, - std::forward_as_tuple(std::move(mark)), - std::forward_as_tuple(std::move(path), size, tolerance)); + ctx.getMetadata().metrics.fileSize.emplace( + std::piecewise_construct, + std::forward_as_tuple(std::move(mark)), + std::forward_as_tuple(std::move(path), size, tolerance) + ); return true; }); } else if (operationArray[0].GetString() == memoryProbeStartOp) { @@ -991,8 +1009,10 @@ TestOperations parseTestOperations(TestMetadata& metadata) { auto emplaced = ctx.getMetadata().metrics.memory.emplace( std::piecewise_construct, std::forward_as_tuple(std::move(mark)), - std::forward_as_tuple(AllocationIndex::getAllocatedSizePeak(), - AllocationIndex::getAllocationsCount())); + std::forward_as_tuple( + AllocationIndex::getAllocatedSizePeak(), AllocationIndex::getAllocationsCount() + ) + ); if (tolerance >= 0.0f) emplaced.first->second.tolerance = tolerance; return true; }); @@ -1019,8 +1039,10 @@ TestOperations parseTestOperations(TestMetadata& metadata) { ctx.getMetadata().metrics.network.emplace( std::piecewise_construct, std::forward_as_tuple(std::move(mark)), - std::forward_as_tuple(mbgl::ProxyFileSource::getRequestCount(), - mbgl::ProxyFileSource::getTransferredSize())); + std::forward_as_tuple( + mbgl::ProxyFileSource::getRequestCount(), mbgl::ProxyFileSource::getTransferredSize() + ) + ); return true; }); } else if (operationArray[0].GetString() == networkProbeEndOp) { @@ -1229,7 +1251,9 @@ TestOperations parseTestOperations(TestMetadata& metadata) { mbgl::AnimationOptions animationOptions(mbgl::Milliseconds(duration * 1000)); animationOptions.minZoom = mbgl::util::min(startZoom, endZoom); - animationOptions.transitionFinishFn = [&]() { transitionFinished = true; }; + animationOptions.transitionFinishFn = [&]() { + transitionFinished = true; + }; map.flyTo(mbgl::CameraOptions().withCenter(endPos).withZoom(endZoom), animationOptions); @@ -1313,12 +1337,15 @@ std::string encodeBase64(const std::string& data) { } std::string createResultItem(const TestMetadata& metadata, bool hasFailedTests) { - const bool shouldHide = - (hasFailedTests && metadata.status == "passed") || (metadata.status.find("ignored") != std::string::npos); + const bool shouldHide = (hasFailedTests && metadata.status == "passed") || + (metadata.status.find("ignored") != std::string::npos); std::string html; html.append("

\n"); - html.append(R"(

" + metadata.status + " " + metadata.id + "

\n"); + html.append( + R"(

" + metadata.status + " " + + metadata.id + "

\n" + ); if (!metadata.renderErrored) { if (metadata.outputsImage) { @@ -1344,14 +1371,17 @@ std::string createResultItem(const TestMetadata& metadata, bool hasFailedTests) } if (metadata.metricsFailed || metadata.metricsErrored || metadata.labelCutOffFound) { - html.append("

Error: " + - std::regex_replace(metadata.errorMessage, std::regex{"\n"}, "
") + "

\n"); + html.append( + "

Error: " + + std::regex_replace(metadata.errorMessage, std::regex{"\n"}, "
") + "

\n" + ); } if (metadata.difference != 0.0) { if (metadata.renderTest) { - html.append("

Diff: " + mbgl::util::toString(metadata.difference) + - "

\n"); + html.append( + "

Diff: " + mbgl::util::toString(metadata.difference) + "

\n" + ); } else { html.append("

Diff: " + metadata.diff + "

\n"); } @@ -1361,7 +1391,9 @@ std::string createResultItem(const TestMetadata& metadata, bool hasFailedTests) return html; } -std::string createResultPage(const TestStatistics& stats, const std::vector& metadatas, bool shuffle, uint32_t seed) { +std::string createResultPage( + const TestStatistics& stats, const std::vector& metadatas, bool shuffle, uint32_t seed +) { const uint32_t unsuccessful = stats.erroredTests + stats.failedTests; std::string resultsPage; diff --git a/render-test/render_test.cpp b/render-test/render_test.cpp index 0c3473b159d..6a17d9cc9ed 100644 --- a/render-test/render_test.cpp +++ b/render-test/render_test.cpp @@ -14,15 +14,15 @@ #include "parser.hpp" #include "runner.hpp" -#define ANSI_COLOR_RED "\x1b[31m" -#define ANSI_COLOR_GREEN "\x1b[32m" -#define ANSI_COLOR_YELLOW "\x1b[33m" -#define ANSI_COLOR_BLUE "\x1b[34m" -#define ANSI_COLOR_MAGENTA "\x1b[35m" -#define ANSI_COLOR_CYAN "\x1b[36m" -#define ANSI_COLOR_GRAY "\x1b[37m" +#define ANSI_COLOR_RED "\x1b[31m" +#define ANSI_COLOR_GREEN "\x1b[32m" +#define ANSI_COLOR_YELLOW "\x1b[33m" +#define ANSI_COLOR_BLUE "\x1b[34m" +#define ANSI_COLOR_MAGENTA "\x1b[35m" +#define ANSI_COLOR_CYAN "\x1b[36m" +#define ANSI_COLOR_GRAY "\x1b[37m" #define ANSI_COLOR_LIGHT_GRAY "\x1b[90m" -#define ANSI_COLOR_RESET "\x1b[0m" +#define ANSI_COLOR_RESET "\x1b[0m" #if !defined(SANITIZE) void* operator new(std::size_t sz) { @@ -58,10 +58,12 @@ ArgumentsTuple parseArguments(int argc, char** argv) { args::Flag recycleMapFlag(argumentParser, "recycle map", "Toggle reusing the map object", {'r', "recycle-map"}); args::Flag shuffleFlag(argumentParser, "shuffle", "Toggle shuffling the tests order", {'s', "shuffle"}); args::Flag onlineFlag( - argumentParser, "online", "Toggle online mode (by default tests will run offline)", {'o', "online"}); + argumentParser, "online", "Toggle online mode (by default tests will run offline)", {'o', "online"} + ); args::ValueFlag seedValue(argumentParser, "seed", "Shuffle seed (default: random)", {"seed"}); args::ValueFlag testPathValue( - argumentParser, "manifestPath", "Test manifest file path", {'p', "manifestPath"}, args::Options::Required); + argumentParser, "manifestPath", "Test manifest file path", {'p', "manifestPath"}, args::Options::Required + ); args::ValueFlag testFilterValue(argumentParser, "filter", "Test filter regex", {'f', "filter"}); args::MapFlag testUpdateResultsValue( argumentParser, @@ -71,7 +73,8 @@ ArgumentsTuple parseArguments(int argc, char** argv) { \n\"metrics\" Updates expected metrics for configuration defined by a manifest.\ \n\"rebaseline\" Updates or creates expected metrics for configuration defined by a manifest.", {'u', "update"}, - updateResultsFlags); + updateResultsFlags + ); try { argumentParser.ParseCLI(argc, argv); @@ -96,8 +99,9 @@ ArgumentsTuple parseArguments(int argc, char** argv) { mbgl::filesystem::path manifestPath = args::get(testPathValue); if (!mbgl::filesystem::exists(manifestPath) || !manifestPath.has_filename()) { - mbgl::Log::Error(mbgl::Event::General, - "Provided test manifest file path '" + manifestPath.string() + "' does not exist"); + mbgl::Log::Error( + mbgl::Event::General, "Provided test manifest file path '" + manifestPath.string() + "' does not exist" + ); exit(3); } @@ -105,15 +109,16 @@ ArgumentsTuple parseArguments(int argc, char** argv) { const auto shuffle = shuffleFlag ? args::get(shuffleFlag) : false; const auto online = onlineFlag ? args::get(onlineFlag) : false; const auto seed = seedValue ? args::get(seedValue) : 1u; - TestRunner::UpdateResults updateResults = - testUpdateResultsValue ? args::get(testUpdateResultsValue) : TestRunner::UpdateResults::NO; - return ArgumentsTuple{recycleMapFlag ? args::get(recycleMapFlag) : false, - shuffle, - online, - seed, - manifestPath.string(), - updateResults, - std::move(testFilter)}; + TestRunner::UpdateResults updateResults = testUpdateResultsValue ? args::get(testUpdateResultsValue) + : TestRunner::UpdateResults::NO; + return ArgumentsTuple{ + recycleMapFlag ? args::get(recycleMapFlag) : false, + shuffle, + online, + seed, + manifestPath.string(), + updateResults, + std::move(testFilter)}; } } // namespace namespace mbgl { @@ -174,7 +179,9 @@ int runRenderTests(int argc, char** argv, std::function testStatus) { std::string ignoreReason; const std::string ignoreName = id; - const auto it = std::find_if(ignores.cbegin(), ignores.cend(), [&ignoreName](auto pair) { return pair.first == ignoreName; }); + const auto it = std::find_if(ignores.cbegin(), ignores.cend(), [&ignoreName](auto pair) { + return pair.first == ignoreName; + }); if (it != ignores.end()) { metadata.ignoredTest = shouldIgnore = true; ignoreReason = it->second; @@ -204,7 +211,9 @@ int runRenderTests(int argc, char** argv, std::function testStatus) { status = "ignored failed"; color = "#9E9E9E"; stats.ignoreFailedTests++; - printf(ANSI_COLOR_LIGHT_GRAY "* ignore %s (%s)" ANSI_COLOR_RESET "\n", id.c_str(), ignoreReason.c_str()); + printf( + ANSI_COLOR_LIGHT_GRAY "* ignore %s (%s)" ANSI_COLOR_RESET "\n", id.c_str(), ignoreReason.c_str() + ); } } else { // Only fail the bots on render errors, this is a CI limitation that we need @@ -247,23 +256,43 @@ int runRenderTests(int argc, char** argv, std::function testStatus) { std::string resultsHTML = createResultPage(stats, metadatas, shuffle, seed); mbgl::util::write_file(resultPath, resultsHTML); - const uint32_t count = - stats.erroredTests + stats.failedTests + stats.ignoreFailedTests + stats.ignorePassedTests + stats.passedTests; + const uint32_t count = stats.erroredTests + stats.failedTests + stats.ignoreFailedTests + stats.ignorePassedTests + + stats.passedTests; if (stats.passedTests) { - printf(ANSI_COLOR_GREEN "%u passed (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.passedTests, 100.0 * stats.passedTests / count); + printf( + ANSI_COLOR_GREEN "%u passed (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.passedTests, + 100.0 * stats.passedTests / count + ); } if (stats.ignorePassedTests) { - printf(ANSI_COLOR_YELLOW "%u passed but were ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.ignorePassedTests, 100.0 * stats.ignorePassedTests / count); + printf( + ANSI_COLOR_YELLOW "%u passed but were ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.ignorePassedTests, + 100.0 * stats.ignorePassedTests / count + ); } if (stats.ignoreFailedTests) { - printf(ANSI_COLOR_LIGHT_GRAY "%u ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.ignoreFailedTests, 100.0 * stats.ignoreFailedTests / count); + printf( + ANSI_COLOR_LIGHT_GRAY "%u ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.ignoreFailedTests, + 100.0 * stats.ignoreFailedTests / count + ); } if (stats.failedTests) { - printf(ANSI_COLOR_RED "%u failed (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.failedTests, 100.0 * stats.failedTests / count); + printf( + ANSI_COLOR_RED "%u failed (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.failedTests, + 100.0 * stats.failedTests / count + ); } if (stats.erroredTests) { - printf(ANSI_COLOR_RED "%u errored (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.erroredTests, 100.0 * stats.erroredTests / count); + printf( + ANSI_COLOR_RED "%u errored (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.erroredTests, + 100.0 * stats.erroredTests / count + ); } printf("Results at: %s\n", mbgl::filesystem::canonical(resultPath).c_str()); diff --git a/render-test/runner.cpp b/render-test/runner.cpp index d07ac971186..607b6431c0d 100644 --- a/render-test/runner.cpp +++ b/render-test/runner.cpp @@ -90,7 +90,8 @@ std::string simpleDiff(const Value& result, const Value& expected) { } TestRunner::TestRunner(Manifest manifest_, UpdateResults updateResults_) - : manifest(std::move(manifest_)), updateResults(updateResults_) { + : manifest(std::move(manifest_)), + updateResults(updateResults_) { registerProxyFileSource(); } @@ -99,9 +100,10 @@ void TestRunner::registerProxyFileSource() { std::call_once(registerProxyFlag, [] { auto* fileSourceManager = mbgl::FileSourceManager::get(); - auto resourceLoaderFactory = - fileSourceManager->unRegisterFileSourceFactory(mbgl::FileSourceType::ResourceLoader); - auto factory = [defaultFactory = std::move(resourceLoaderFactory)](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions) { + auto resourceLoaderFactory = fileSourceManager->unRegisterFileSourceFactory(mbgl::FileSourceType::ResourceLoader + ); + auto factory = [defaultFactory = std::move(resourceLoaderFactory + )](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions) { assert(defaultFactory); std::shared_ptr fileSource = defaultFactory(resourceOptions, clientOptions); return std::make_unique(std::move(fileSource), resourceOptions, clientOptions); @@ -119,9 +121,9 @@ void TestRunner::doShuffle(uint32_t seed) { manifest.doShuffle(seed); } -void TestRunner::checkQueryTestResults(mbgl::PremultipliedImage&& actualImage, - std::vector&& features, - TestMetadata& metadata) { +void TestRunner::checkQueryTestResults( + mbgl::PremultipliedImage&& actualImage, std::vector&& features, TestMetadata& metadata +) { const std::string& base = metadata.paths.defaultExpectations(); const std::vector& expectations = metadata.paths.expectations; @@ -257,13 +259,14 @@ void TestRunner::checkRenderTestResults(mbgl::PremultipliedImage&& actualImage, expectedImage = mbgl::decodeImage(*maybeExpectedImage); - pixels = static_cast( - mapbox::pixelmatch(actualImage.data.get(), - expectedImage.data.get(), - expectedImage.size.width, - expectedImage.size.height, - imageDiff.data.get(), - 0.1285) // Defined in GL JS + pixels = static_cast(mapbox::pixelmatch( + actualImage.data.get(), + expectedImage.data.get(), + expectedImage.size.width, + expectedImage.size.height, + imageDiff.data.get(), + 0.1285 + ) // Defined in GL JS ); metadata.diff = mbgl::encodePNG(imageDiff); @@ -284,12 +287,12 @@ void TestRunner::checkRenderTestResults(mbgl::PremultipliedImage&& actualImage, void TestRunner::checkProbingResults(TestMetadata& resultMetadata) { if (resultMetadata.metrics.isEmpty()) return; - const auto writeMetrics = [&resultMetadata](const mbgl::filesystem::path& path, - const std::string& message = std::string()) { - mbgl::filesystem::create_directories(path); - mbgl::util::write_file(path / "metrics.json", serializeMetrics(resultMetadata.metrics)); - resultMetadata.errorMessage += message; - }; + const auto writeMetrics = + [&resultMetadata](const mbgl::filesystem::path& path, const std::string& message = std::string()) { + mbgl::filesystem::create_directories(path); + mbgl::util::write_file(path / "metrics.json", serializeMetrics(resultMetadata.metrics)); + resultMetadata.errorMessage += message; + }; const std::vector& expectedMetrics = resultMetadata.paths.expectedMetrics; if (updateResults == UpdateResults::METRICS) { @@ -322,8 +325,8 @@ void TestRunner::checkProbingResults(TestMetadata& resultMetadata) { } if (resultMetadata.expectedMetrics.isEmpty()) { - resultMetadata.errorMessage = - "Failed to find metric expectations for: " + resultMetadata.paths.stylePath.string(); + resultMetadata.errorMessage = "Failed to find metric expectations for: " + + resultMetadata.paths.stylePath.string(); if (updateResults == UpdateResults::REBASELINE && !resultMetadata.ignoredTest) { writeMetrics(expectedMetrics.back(), ". Created baseline for missing metrics."); } @@ -350,7 +353,11 @@ void TestRunner::checkProbingResults(TestMetadata& resultMetadata) { return; } - auto result = checkValue(static_cast(expected.second.size), static_cast(actual->second.size), actual->second.tolerance); + auto result = checkValue( + static_cast(expected.second.size), + static_cast(actual->second.size), + actual->second.tolerance + ); if (!std::get(result)) { std::stringstream ss; ss << "File size does not match at probe \"" << expected.first << "\" for file \"" @@ -557,10 +564,13 @@ TestOperations getBeforeOperations(const Manifest& manifest) { result.emplace_back([](TestContext& ctx) { assert(!AllocationIndex::isActive()); AllocationIndex::setActive(true); - ctx.getMetadata().metrics.memory.emplace(std::piecewise_construct, - std::forward_as_tuple(memoryProbeOp + mark), - std::forward_as_tuple(AllocationIndex::getAllocatedSizePeak(), - AllocationIndex::getAllocationsCount())); + ctx.getMetadata().metrics.memory.emplace( + std::piecewise_construct, + std::forward_as_tuple(memoryProbeOp + mark), + std::forward_as_tuple( + AllocationIndex::getAllocatedSizePeak(), AllocationIndex::getAllocationsCount() + ) + ); return true; }); continue; @@ -582,7 +592,8 @@ TestOperations getBeforeOperations(const Manifest& manifest) { ctx.getMetadata().metrics.network.emplace( std::piecewise_construct, std::forward_as_tuple(networkProbeOp + mark), - std::forward_as_tuple(ProxyFileSource::getRequestCount(), ProxyFileSource::getTransferredSize())); + std::forward_as_tuple(ProxyFileSource::getRequestCount(), ProxyFileSource::getTransferredSize()) + ); return true; }); continue; @@ -602,8 +613,10 @@ TestOperations getAfterOperations(const Manifest& manifest) { auto emplaced = ctx.getMetadata().metrics.memory.emplace( std::piecewise_construct, std::forward_as_tuple(memoryProbeOp + mark), - std::forward_as_tuple(AllocationIndex::getAllocatedSizePeak(), - AllocationIndex::getAllocationsCount())); + std::forward_as_tuple( + AllocationIndex::getAllocatedSizePeak(), AllocationIndex::getAllocationsCount() + ) + ); assert(emplaced.second); // TODO: Improve tolerance handling for memory tests. emplaced.first->second.tolerance = 0.2f; @@ -632,7 +645,8 @@ TestOperations getAfterOperations(const Manifest& manifest) { ctx.getMetadata().metrics.network.emplace( std::piecewise_construct, std::forward_as_tuple(networkProbeOp + mark), - std::forward_as_tuple(ProxyFileSource::getRequestCount(), ProxyFileSource::getTransferredSize())); + std::forward_as_tuple(ProxyFileSource::getRequestCount(), ProxyFileSource::getTransferredSize()) + ); ProxyFileSource::setTrackingActive(false); return true; }); @@ -648,17 +662,17 @@ void resetContext(const TestMetadata& metadata, TestContext& ctx) { ctx.getFrontend().setSize(metadata.size); auto& map = ctx.getMap(); map.setSize(metadata.size); - map.setProjectionMode(mbgl::ProjectionMode() - .withAxonometric(metadata.axonometric) - .withXSkew(metadata.xSkew) - .withYSkew(metadata.ySkew)); + map.setProjectionMode( + mbgl::ProjectionMode().withAxonometric(metadata.axonometric).withXSkew(metadata.xSkew).withYSkew(metadata.ySkew) + ); map.setDebug(metadata.debug); map.getStyle().loadJSON(serializeJsonValue(metadata.document)); } LatLng getTileCenterCoordinates(const UnwrappedTileID& tileId) { double scale = (1 << tileId.canonical.z); - Point tileCenter{(tileId.canonical.x + 0.5) * util::tileSize_D, (tileId.canonical.y + 0.5) * util::tileSize_D}; + Point tileCenter{ + (tileId.canonical.x + 0.5) * util::tileSize_D, (tileId.canonical.y + 0.5) * util::tileSize_D}; return Projection::unproject(tileCenter, scale); } @@ -677,10 +691,14 @@ uint32_t getImageTileOffset(const std::set& dims, uint32_t dim, float } // namespace -TestRunner::Impl::Impl(const TestMetadata& metadata, const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions) +TestRunner::Impl::Impl( + const TestMetadata& metadata, const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions +) : observer(std::make_unique()), frontend(metadata.size, metadata.pixelRatio, swapBehavior(metadata.mapMode)), - fileSource(mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions)), + fileSource(mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions + )), map(frontend, *observer.get(), mbgl::MapOptions() @@ -699,7 +717,8 @@ void TestRunner::run(TestMetadata& metadata) { ProxyFileSource::setTrackingActive(false); struct ContextImpl final : public TestContext { - ContextImpl(TestMetadata& metadata_) : metadata(metadata_) {} + ContextImpl(TestMetadata& metadata_) + : metadata(metadata_) {} HeadlessFrontend& getFrontend() override { assert(runnerImpl); return runnerImpl->frontend; @@ -740,7 +759,8 @@ void TestRunner::run(TestMetadata& metadata) { maps[key] = std::make_unique( metadata, mbgl::ResourceOptions().withCachePath(manifest.getCachePath()).withApiKey(manifest.getApiKey()), - mbgl::ClientOptions()); + mbgl::ClientOptions() + ); } ctx.runnerImpl = maps[key].get(); @@ -837,17 +857,20 @@ void TestRunner::run(TestMetadata& metadata) { if (placedSymbol.intersectsTileBorder) { if (placedSymbol.textCollisionBox) { findCutOffs( - placedSymbol, *placedSymbol.textCollisionBox, placedSymbol.textPlaced, false /*isIcon*/); + placedSymbol, *placedSymbol.textCollisionBox, placedSymbol.textPlaced, false /*isIcon*/ + ); } if (placedSymbol.iconCollisionBox) { findCutOffs( - placedSymbol, *placedSymbol.iconCollisionBox, placedSymbol.iconPlaced, true /*isIcon*/); + placedSymbol, *placedSymbol.iconCollisionBox, placedSymbol.iconPlaced, true /*isIcon*/ + ); } } } PremultipliedImage::copy( - resultForTile.image, result.image, {0, 0}, {xOffset, yOffset}, resultForTile.image.size); + resultForTile.image, result.image, {0, 0}, {xOffset, yOffset}, resultForTile.image.size + ); result.stats += resultForTile.stats; } } else { @@ -881,9 +904,9 @@ void TestRunner::run(TestMetadata& metadata) { } } -void TestRunner::appendLabelCutOffResults(TestMetadata& resultMetadata, - const std::string& cutOffLabelsReport, - const std::string& duplicationsReport) { +void TestRunner::appendLabelCutOffResults( + TestMetadata& resultMetadata, const std::string& cutOffLabelsReport, const std::string& duplicationsReport +) { if (resultMetadata.labelCutOffFound) { // Append label cut-off statistics. resultMetadata.errorMessage += "\n Label cut-offs:"; resultMetadata.errorMessage += cutOffLabelsReport; diff --git a/render-test/runner.hpp b/render-test/runner.hpp index b2cb8d57f81..52d0bd22bdc 100644 --- a/render-test/runner.hpp +++ b/render-test/runner.hpp @@ -36,7 +36,13 @@ class TestRunnerMapObserver : public mbgl::MapObserver { class TestRunner { public: - enum class UpdateResults { NO, DEFAULT, PLATFORM, METRICS, REBASELINE }; + enum class UpdateResults { + NO, + DEFAULT, + PLATFORM, + METRICS, + REBASELINE + }; TestRunner(Manifest, UpdateResults); void run(TestMetadata&); @@ -48,9 +54,8 @@ class TestRunner { private: mbgl::HeadlessFrontend::RenderResult runTest(TestMetadata& metadata, TestContext& ctx); - void checkQueryTestResults(mbgl::PremultipliedImage&& actualImage, - std::vector&& features, - TestMetadata&); + void + checkQueryTestResults(mbgl::PremultipliedImage&& actualImage, std::vector&& features, TestMetadata&); void checkRenderTestResults(mbgl::PremultipliedImage&& image, TestMetadata&); void checkProbingResults(TestMetadata&); void appendLabelCutOffResults(TestMetadata&, const std::string&, const std::string&); diff --git a/src/mbgl/actor/mailbox.cpp b/src/mbgl/actor/mailbox.cpp index e53584efef3..511a9aee9ae 100644 --- a/src/mbgl/actor/mailbox.cpp +++ b/src/mbgl/actor/mailbox.cpp @@ -8,7 +8,8 @@ namespace mbgl { Mailbox::Mailbox() = default; -Mailbox::Mailbox(Scheduler& scheduler_) : weakScheduler(scheduler_.makeWeakPtr()) {} +Mailbox::Mailbox(Scheduler& scheduler_) + : weakScheduler(scheduler_.makeWeakPtr()) {} void Mailbox::open(Scheduler& scheduler_) { assert(!weakScheduler); @@ -99,7 +100,9 @@ void Mailbox::maybeReceive(const std::weak_ptr& mailbox) { // static std::function Mailbox::makeClosure(std::weak_ptr mailbox) { - return [mailbox = std::move(mailbox)]() { maybeReceive(mailbox); }; + return [mailbox = std::move(mailbox)]() { + maybeReceive(mailbox); + }; } } // namespace mbgl diff --git a/src/mbgl/actor/scheduler.cpp b/src/mbgl/actor/scheduler.cpp index 0e051d0273a..b6132ebc66d 100644 --- a/src/mbgl/actor/scheduler.cpp +++ b/src/mbgl/actor/scheduler.cpp @@ -68,4 +68,4 @@ std::shared_ptr Scheduler::GetSequenced() { return result; } -} //namespace mbgl +} // namespace mbgl diff --git a/src/mbgl/algorithm/update_renderables.hpp b/src/mbgl/algorithm/update_renderables.hpp index 7fa8fee788f..189ed735805 100644 --- a/src/mbgl/algorithm/update_renderables.hpp +++ b/src/mbgl/algorithm/update_renderables.hpp @@ -10,18 +10,21 @@ namespace mbgl { namespace algorithm { -template -void updateRenderables(GetTileFn getTile, - CreateTileFn createTile, - RetainTileFn retainTile, - RenderTileFn renderTile, - const IdealTileIDs& idealTileIDs, - const Range& zoomRange, - const std::optional& maxParentOverscaleFactor = std::nullopt) { +template < + typename GetTileFn, + typename CreateTileFn, + typename RetainTileFn, + typename RenderTileFn, + typename IdealTileIDs> +void updateRenderables( + GetTileFn getTile, + CreateTileFn createTile, + RetainTileFn retainTile, + RenderTileFn renderTile, + const IdealTileIDs& idealTileIDs, + const Range& zoomRange, + const std::optional& maxParentOverscaleFactor = std::nullopt +) { std::unordered_set checked; bool covered; int32_t overscaledZ; @@ -38,7 +41,7 @@ void updateRenderables(GetTileFn getTile, tile = createTile(idealDataTileID); // For source types where TileJSON.bounds is set, tiles outside the // bounds are not created - if(tile == nullptr) { + if (tile == nullptr) { continue; } } diff --git a/src/mbgl/algorithm/update_tile_masks.hpp b/src/mbgl/algorithm/update_tile_masks.hpp index 000be1606c2..dec26a72eb0 100644 --- a/src/mbgl/algorithm/update_tile_masks.hpp +++ b/src/mbgl/algorithm/update_tile_masks.hpp @@ -10,21 +10,28 @@ namespace mbgl { namespace algorithm { template -bool tileNeedsMask(const std::reference_wrapper& tile) { return tile.get().usedByRenderedLayers; } -template -void setTileMask(const std::reference_wrapper& tile, TileMask&& mask ) { return tile.get().setMask(std::move(mask)); } +bool tileNeedsMask(const std::reference_wrapper& tile) { + return tile.get().usedByRenderedLayers; +} +template +void setTileMask(const std::reference_wrapper& tile, TileMask&& mask) { + return tile.get().setMask(std::move(mask)); +} // Overloads for tests -template bool tileNeedsMask(const T& tile) { return tile.usedByRenderedLayers; } -template void setTileMask(T& tile, TileMask&& mask ) { return tile.setMask(std::move(mask)); } +template +bool tileNeedsMask(const T& tile) { + return tile.usedByRenderedLayers; +} +template +void setTileMask(T& tile, TileMask&& mask) { + return tile.setMask(std::move(mask)); +} template void computeTileMasks( - const CanonicalTileID& root, - const UnwrappedTileID& ref, - const Iterator begin, - const Iterator end, - TileMask& mask) { + const CanonicalTileID& root, const UnwrappedTileID& ref, const Iterator begin, const Iterator end, TileMask& mask +) { // If the reference or any of its children is found in the list, we need to recurse. for (auto it = begin; it != end; ++it) { const UnwrappedTileID& id = it->first; @@ -35,7 +42,7 @@ void computeTileMasks( if (ref == id) { // The current tile is masked out, so we don't need to add them to the mask set. return; - } + } if (id.isChildOf(ref)) { // There's at least one child tile that is masked out, so recursively descend. @@ -118,9 +125,11 @@ void updateTileMasks(RenderableTilesMap& renderables) { // can never be children of the current wrap. auto child_it = std::next(it); const auto children_end = std::lower_bound( - child_it, end, - UnwrappedTileID{ static_cast(id.wrap + 1), { 0, 0, 0 } }, - [](auto& a, auto& b) { return a.first < b; }); + child_it, + end, + UnwrappedTileID{static_cast(id.wrap + 1), {0, 0, 0}}, + [](auto& a, auto& b) { return a.first < b; } + ); mask.clear(); computeTileMasks(id.canonical, id, child_it, children_end, mask); diff --git a/src/mbgl/annotation/annotation_manager.cpp b/src/mbgl/annotation/annotation_manager.cpp index b890a24c33c..f8e1eb881a6 100644 --- a/src/mbgl/annotation/annotation_manager.cpp +++ b/src/mbgl/annotation/annotation_manager.cpp @@ -18,15 +18,15 @@ // at compile time, so that linker (with LTO on) is able // to optimize out the unreachable code. #define CHECK_ANNOTATIONS_ENABLED_AND_RETURN_NOARG() \ -if (!LayerManager::annotationsEnabled) { \ - assert(false); \ - return; \ -} + if (!LayerManager::annotationsEnabled) { \ + assert(false); \ + return; \ + } #define CHECK_ANNOTATIONS_ENABLED_AND_RETURN(result) \ -if (!LayerManager::annotationsEnabled) { \ - assert(false); \ - return result; \ -} + if (!LayerManager::annotationsEnabled) { \ + assert(false); \ + return result; \ + } namespace mbgl { @@ -37,8 +37,7 @@ const std::string AnnotationManager::PointLayerID = "com.mapbox.annotations.poin const std::string AnnotationManager::ShapeLayerID = "com.mapbox.annotations.shape."; AnnotationManager::AnnotationManager(Style& style_) - : style(style_) { -}; + : style(style_){}; AnnotationManager::~AnnotationManager() = default; @@ -56,9 +55,7 @@ AnnotationID AnnotationManager::addAnnotation(const Annotation& annotation) { CHECK_ANNOTATIONS_ENABLED_AND_RETURN(nextID++); std::lock_guard lock(mutex); AnnotationID id = nextID++; - Annotation::visit(annotation, [&] (const auto& annotation_) { - this->add(id, annotation_); - }); + Annotation::visit(annotation, [&](const auto& annotation_) { this->add(id, annotation_); }); dirty = true; return id; } @@ -66,9 +63,7 @@ AnnotationID AnnotationManager::addAnnotation(const Annotation& annotation) { bool AnnotationManager::updateAnnotation(const AnnotationID& id, const Annotation& annotation) { CHECK_ANNOTATIONS_ENABLED_AND_RETURN(true); std::lock_guard lock(mutex); - Annotation::visit(annotation, [&] (const auto& annotation_) { - this->update(id, annotation_); - }); + Annotation::visit(annotation, [&](const auto& annotation_) { this->update(id, annotation_); }); return dirty; } @@ -86,14 +81,14 @@ void AnnotationManager::add(const AnnotationID& id, const SymbolAnnotation& anno } void AnnotationManager::add(const AnnotationID& id, const LineAnnotation& annotation) { - ShapeAnnotationImpl& impl = *shapeAnnotations.emplace(id, - std::make_unique(id, annotation)).first->second; + ShapeAnnotationImpl& impl = + *shapeAnnotations.emplace(id, std::make_unique(id, annotation)).first->second; impl.updateStyle(*style.get().impl); } void AnnotationManager::add(const AnnotationID& id, const FillAnnotation& annotation) { - ShapeAnnotationImpl& impl = *shapeAnnotations.emplace(id, - std::make_unique(id, annotation)).first->second; + ShapeAnnotationImpl& impl = + *shapeAnnotations.emplace(id, std::make_unique(id, annotation)).first->second; impl.updateStyle(*style.get().impl); } @@ -153,8 +148,7 @@ void AnnotationManager::remove(const AnnotationID& id) { } std::unique_ptr AnnotationManager::getTileData(const CanonicalTileID& tileID) { - if (symbolAnnotations.empty() && shapeAnnotations.empty()) - return nullptr; + if (symbolAnnotations.empty() && shapeAnnotations.empty()) return nullptr; auto tileData = std::make_unique(); @@ -167,11 +161,11 @@ std::unique_ptr AnnotationManager::getTileData(const Canonic // The rendering/querying logic will make sure the symbols show up in only one of the tiles tileBounds.extend(LatLng(tileBounds.south() - 0.000000001, tileBounds.west() - 0.000000001)); tileBounds.extend(LatLng(tileBounds.north() + 0.000000001, tileBounds.east() + 0.000000001)); - - symbolTree.query(boost::geometry::index::intersects(tileBounds), - boost::make_function_output_iterator([&](const auto& val){ - val->updateLayer(tileID, *pointLayer); - })); + + symbolTree.query( + boost::geometry::index::intersects(tileBounds), + boost::make_function_output_iterator([&](const auto& val) { val->updateLayer(tileID, *pointLayer); }) + ); for (const auto& shape : shapeAnnotations) { shape.second->updateTileData(tileID, *tileData); @@ -190,8 +184,9 @@ void AnnotationManager::updateStyle() { using namespace expression::dsl; layer->setSourceLayer(PointLayerID); - layer->setIconImage(PropertyExpression( - image(concat(vec(literal(SourceID + "."), toString(get("sprite"))))))); + layer->setIconImage( + PropertyExpression(image(concat(vec(literal(SourceID + "."), toString(get("sprite")))))) + ); layer->setIconAllowOverlap(true); layer->setIconIgnorePlacement(true); @@ -250,8 +245,9 @@ void AnnotationManager::addImage(std::unique_ptr image) { std::lock_guard lock(mutex); const std::string id = prefixedImageID(image->getID()); images.erase(id); - auto inserted = images.emplace(id, style::Image(id, image->getImage().clone(), - image->getPixelRatio(), image->isSdf())); + auto inserted = images.emplace( + id, style::Image(id, image->getImage().clone(), image->getPixelRatio(), image->isSdf()) + ); style.get().impl->addImage(std::make_unique(inserted.first->second)); } diff --git a/src/mbgl/annotation/annotation_manager.hpp b/src/mbgl/annotation/annotation_manager.hpp index 57f27c63528..301b39d823f 100644 --- a/src/mbgl/annotation/annotation_manager.hpp +++ b/src/mbgl/annotation/annotation_manager.hpp @@ -72,12 +72,13 @@ class AnnotationManager : private util::noncopyable { std::mutex mutex; bool dirty = false; - + AnnotationID nextID = 0; - using SymbolAnnotationTree = boost::geometry::index::rtree, boost::geometry::index::rstar<16, 4>>; - // Unlike std::unordered_map, std::map is guaranteed to sort by AnnotationID, ensuring that older annotations are below newer annotations. - // + using SymbolAnnotationTree = boost::geometry::index:: + rtree, boost::geometry::index::rstar<16, 4>>; + // Unlike std::unordered_map, std::map is guaranteed to sort by AnnotationID, ensuring that older annotations are + // below newer annotations. using SymbolAnnotationMap = std::map>; using ShapeAnnotationMap = std::map>; using ImageMap = std::unordered_map; diff --git a/src/mbgl/annotation/annotation_source.cpp b/src/mbgl/annotation/annotation_source.cpp index 19a33bb02ac..7c55c412b59 100644 --- a/src/mbgl/annotation/annotation_source.cpp +++ b/src/mbgl/annotation/annotation_source.cpp @@ -7,12 +7,10 @@ namespace mbgl { using namespace style; AnnotationSource::AnnotationSource() - : Source(makeMutable()) { -} + : Source(makeMutable()) {} AnnotationSource::Impl::Impl() - : Source::Impl(SourceType::Annotations, AnnotationManager::SourceID) { -} + : Source::Impl(SourceType::Annotations, AnnotationManager::SourceID) {} const AnnotationSource::Impl& AnnotationSource::impl() const { return static_cast(*baseImpl); diff --git a/src/mbgl/annotation/annotation_source.hpp b/src/mbgl/annotation/annotation_source.hpp index 3d1cd33ec3e..65b2a83e2c1 100644 --- a/src/mbgl/annotation/annotation_source.hpp +++ b/src/mbgl/annotation/annotation_source.hpp @@ -18,10 +18,8 @@ class AnnotationSource final : public style::Source { private: void loadDescription(FileSource&) final; bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } + mapbox::base::WeakPtrFactory weakFactory{this}; }; class AnnotationSource::Impl : public style::Source::Impl { diff --git a/src/mbgl/annotation/annotation_tile.cpp b/src/mbgl/annotation/annotation_tile.cpp index aa910ae54ce..7ffae2317eb 100644 --- a/src/mbgl/annotation/annotation_tile.cpp +++ b/src/mbgl/annotation/annotation_tile.cpp @@ -7,8 +7,7 @@ namespace mbgl { -AnnotationTile::AnnotationTile(const OverscaledTileID& overscaledTileID, - const TileParameters& parameters) +AnnotationTile::AnnotationTile(const OverscaledTileID& overscaledTileID, const TileParameters& parameters) : GeometryTile(overscaledTileID, AnnotationManager::SourceID, parameters), annotationManager(parameters.annotationManager) { auto guard = annotationManager.lock(); @@ -26,15 +25,16 @@ AnnotationTile::~AnnotationTile() { class AnnotationTileFeatureData { public: - AnnotationTileFeatureData(const AnnotationID id_, - FeatureType type_, - GeometryCollection&& geometries_, - std::unordered_map&& properties_) + AnnotationTileFeatureData( + const AnnotationID id_, + FeatureType type_, + GeometryCollection&& geometries_, + std::unordered_map&& properties_ + ) : id(id_), type(type_), geometries(std::move(geometries_)), - properties(std::move(properties_)) { - } + properties(std::move(properties_)) {} AnnotationID id; FeatureType type; @@ -43,8 +43,7 @@ class AnnotationTileFeatureData { }; AnnotationTileFeature::AnnotationTileFeature(std::shared_ptr data_) - : data(std::move(data_)) { -} + : data(std::move(data_)) {} AnnotationTileFeature::~AnnotationTileFeature() = default; @@ -70,14 +69,15 @@ const GeometryCollection& AnnotationTileFeature::getGeometries() const { class AnnotationTileLayerData { public: - explicit AnnotationTileLayerData(std::string name_) : name(std::move(name_)) {} + explicit AnnotationTileLayerData(std::string name_) + : name(std::move(name_)) {} const std::string name; std::vector> features; }; -AnnotationTileLayer::AnnotationTileLayer(std::shared_ptr layer_) : layer(std::move(layer_)) { -} +AnnotationTileLayer::AnnotationTileLayer(std::shared_ptr layer_) + : layer(std::move(layer_)) {} std::size_t AnnotationTileLayer::featureCount() const { return layer->features.size(); @@ -91,13 +91,15 @@ std::string AnnotationTileLayer::getName() const { return layer->name; } -void AnnotationTileLayer::addFeature(const AnnotationID id, - FeatureType type, - GeometryCollection geometries, - std::unordered_map properties) { - - layer->features.emplace_back(std::make_shared( - id, type, std::move(geometries), std::move(properties))); +void AnnotationTileLayer::addFeature( + const AnnotationID id, + FeatureType type, + GeometryCollection geometries, + std::unordered_map properties +) { + layer->features.emplace_back( + std::make_shared(id, type, std::move(geometries), std::move(properties)) + ); } std::unique_ptr AnnotationTileData::clone() const { diff --git a/src/mbgl/annotation/annotation_tile.hpp b/src/mbgl/annotation/annotation_tile.hpp index 5fba885014b..d860d8f65ae 100644 --- a/src/mbgl/annotation/annotation_tile.hpp +++ b/src/mbgl/annotation/annotation_tile.hpp @@ -44,10 +44,9 @@ class AnnotationTileLayer : public GeometryTileLayer { std::unique_ptr getFeature(std::size_t i) const override; std::string getName() const override; - void addFeature(AnnotationID, - FeatureType, - GeometryCollection, - std::unordered_map properties = {{}}); + void addFeature( + AnnotationID, FeatureType, GeometryCollection, std::unordered_map properties = {{}} + ); private: std::shared_ptr layer; diff --git a/src/mbgl/annotation/fill_annotation_impl.cpp b/src/mbgl/annotation/fill_annotation_impl.cpp index 59b8133cf78..cce6f753d4a 100644 --- a/src/mbgl/annotation/fill_annotation_impl.cpp +++ b/src/mbgl/annotation/fill_annotation_impl.cpp @@ -9,8 +9,12 @@ using namespace style; FillAnnotationImpl::FillAnnotationImpl(AnnotationID id_, FillAnnotation annotation_) : ShapeAnnotationImpl(id_), - annotation(ShapeAnnotationGeometry::visit(annotation_.geometry, CloseShapeAnnotation{}), annotation_.opacity, annotation_.color, annotation_.outlineColor) { -} + annotation( + ShapeAnnotationGeometry::visit(annotation_.geometry, CloseShapeAnnotation{}), + annotation_.opacity, + annotation_.color, + annotation_.outlineColor + ) {} void FillAnnotationImpl::updateStyle(Style::Impl& style) const { Layer* layer = style.getLayer(layerID); diff --git a/src/mbgl/annotation/line_annotation_impl.cpp b/src/mbgl/annotation/line_annotation_impl.cpp index 533a137a3df..ad50365867b 100644 --- a/src/mbgl/annotation/line_annotation_impl.cpp +++ b/src/mbgl/annotation/line_annotation_impl.cpp @@ -9,8 +9,12 @@ using namespace style; LineAnnotationImpl::LineAnnotationImpl(AnnotationID id_, LineAnnotation annotation_) : ShapeAnnotationImpl(id_), - annotation(ShapeAnnotationGeometry::visit(annotation_.geometry, CloseShapeAnnotation{}), annotation_.opacity, annotation_.width, annotation_.color) { -} + annotation( + ShapeAnnotationGeometry::visit(annotation_.geometry, CloseShapeAnnotation{}), + annotation_.opacity, + annotation_.width, + annotation_.color + ) {} void LineAnnotationImpl::updateStyle(Style::Impl& style) const { Layer* layer = style.getLayer(layerID); diff --git a/src/mbgl/annotation/render_annotation_source.cpp b/src/mbgl/annotation/render_annotation_source.cpp index 3cd74b0258e..3778c21a646 100644 --- a/src/mbgl/annotation/render_annotation_source.cpp +++ b/src/mbgl/annotation/render_annotation_source.cpp @@ -19,11 +19,13 @@ const AnnotationSource::Impl& RenderAnnotationSource::impl() const { return static_cast(*baseImpl); } -void RenderAnnotationSource::update(Immutable baseImpl_, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) { +void RenderAnnotationSource::update( + Immutable baseImpl_, + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters +) { std::swap(baseImpl, baseImpl_); enabled = needsRendering; @@ -39,15 +41,17 @@ void RenderAnnotationSource::update(Immutable baseImpl_, // See https://github.com/mapbox/mapbox-gl-native/issues/10197 {0, 16}, std::nullopt, - [&](const OverscaledTileID& tileID) { return std::make_unique(tileID, parameters); }); + [&](const OverscaledTileID& tileID) { return std::make_unique(tileID, parameters); } + ); } -std::unordered_map> -RenderAnnotationSource::queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const { +std::unordered_map> RenderAnnotationSource::queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix +) const { return tilePyramid.queryRenderedFeatures(geometry, transformState, layers, options, projMatrix, {}); } @@ -55,5 +59,4 @@ std::vector RenderAnnotationSource::querySourceFeatures(const SourceQue return {}; } - } // namespace mbgl diff --git a/src/mbgl/annotation/render_annotation_source.hpp b/src/mbgl/annotation/render_annotation_source.hpp index c920d760c2c..fb5295bb9ad 100644 --- a/src/mbgl/annotation/render_annotation_source.hpp +++ b/src/mbgl/annotation/render_annotation_source.hpp @@ -9,21 +9,19 @@ class RenderAnnotationSource final : public RenderTileSource { public: explicit RenderAnnotationSource(Immutable); - void update(Immutable, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) final; - - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const final; - - std::vector - querySourceFeatures(const SourceQueryOptions&) const final; + void + update(Immutable, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) + final; + + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix + ) const final; + + std::vector querySourceFeatures(const SourceQueryOptions&) const final; private: const AnnotationSource::Impl& impl() const; diff --git a/src/mbgl/annotation/shape_annotation_impl.cpp b/src/mbgl/annotation/shape_annotation_impl.cpp index 0da98acb84c..f86bd493920 100644 --- a/src/mbgl/annotation/shape_annotation_impl.cpp +++ b/src/mbgl/annotation/shape_annotation_impl.cpp @@ -14,16 +14,16 @@ using namespace style; ShapeAnnotationImpl::ShapeAnnotationImpl(const AnnotationID id_) : id(id_), - layerID(AnnotationManager::ShapeLayerID + util::toString(id)) { -} + layerID(AnnotationManager::ShapeLayerID + util::toString(id)) {} void ShapeAnnotationImpl::updateTileData(const CanonicalTileID& tileID, AnnotationTileData& data) { static const double baseTolerance = 4; if (!shapeTiler) { mapbox::feature::feature_collection features; - features.emplace_back(ShapeAnnotationGeometry::visit( - geometry(), [](auto&& geom) { return Feature{std::forward(geom)}; })); + features.emplace_back(ShapeAnnotationGeometry::visit(geometry(), [](auto&& geom) { + return Feature{std::forward(geom)}; + })); mapbox::geojsonvt::Options options; // The annotation source is currently hard coded to maxzoom 16, so we're topping out at z16 // here as well. @@ -35,8 +35,7 @@ void ShapeAnnotationImpl::updateTileData(const CanonicalTileID& tileID, Annotati } const auto& shapeTile = shapeTiler->getTile(tileID.z, tileID.x, tileID.y); - if (shapeTile.features.empty()) - return; + if (shapeTile.features.empty()) return; auto layer = data.addLayer(layerID); diff --git a/src/mbgl/annotation/shape_annotation_impl.hpp b/src/mbgl/annotation/shape_annotation_impl.hpp index 64007d4fa1c..b18c2ab845c 100644 --- a/src/mbgl/annotation/shape_annotation_impl.hpp +++ b/src/mbgl/annotation/shape_annotation_impl.hpp @@ -20,10 +20,10 @@ class ShapeAnnotationImpl { ShapeAnnotationImpl(AnnotationID); virtual ~ShapeAnnotationImpl() = default; - virtual void updateStyle(style::Style::Impl&) const = 0; - virtual const ShapeAnnotationGeometry& geometry() const = 0; + virtual void updateStyle(style::Style::Impl &) const = 0; + virtual const ShapeAnnotationGeometry &geometry() const = 0; - void updateTileData(const CanonicalTileID&, AnnotationTileData&); + void updateTileData(const CanonicalTileID &, AnnotationTileData &); const AnnotationID id; const std::string layerID; @@ -31,12 +31,8 @@ class ShapeAnnotationImpl { }; struct CloseShapeAnnotation { - ShapeAnnotationGeometry operator()(const mbgl::LineString &geom) const { - return geom; - } - ShapeAnnotationGeometry operator()(const mbgl::MultiLineString &geom) const { - return geom; - } + ShapeAnnotationGeometry operator()(const mbgl::LineString &geom) const { return geom; } + ShapeAnnotationGeometry operator()(const mbgl::MultiLineString &geom) const { return geom; } ShapeAnnotationGeometry operator()(const mbgl::Polygon &geom) const { mbgl::Polygon closed = geom; for (auto &ring : closed) { diff --git a/src/mbgl/annotation/symbol_annotation_impl.cpp b/src/mbgl/annotation/symbol_annotation_impl.cpp index c95eb481b5a..44ad7b4b7c2 100644 --- a/src/mbgl/annotation/symbol_annotation_impl.cpp +++ b/src/mbgl/annotation/symbol_annotation_impl.cpp @@ -7,18 +7,17 @@ namespace mbgl { SymbolAnnotationImpl::SymbolAnnotationImpl(AnnotationID id_, SymbolAnnotation annotation_) -: id(id_), - annotation(std::move(annotation_)) { -} + : id(id_), + annotation(std::move(annotation_)) {} void SymbolAnnotationImpl::updateLayer(const CanonicalTileID& tileID, AnnotationTileLayer& layer) const { std::unordered_map featureProperties; featureProperties.emplace("sprite", annotation.icon.empty() ? std::string("default_marker") : annotation.icon); - LatLng latLng { annotation.geometry.y, annotation.geometry.x }; + LatLng latLng{annotation.geometry.y, annotation.geometry.x}; TileCoordinate coordinate = TileCoordinate::fromLatLng(0, latLng); GeometryCoordinate tilePoint = TileCoordinate::toGeometryCoordinate(UnwrappedTileID(0, tileID), coordinate.p); - layer.addFeature(id, FeatureType::Point, GeometryCollection {{ {{ tilePoint }} }}, featureProperties); + layer.addFeature(id, FeatureType::Point, GeometryCollection{{{{tilePoint}}}}, featureProperties); } } // namespace mbgl diff --git a/src/mbgl/annotation/symbol_annotation_impl.hpp b/src/mbgl/annotation/symbol_annotation_impl.hpp index 928a6059574..9b26b7cff1f 100644 --- a/src/mbgl/annotation/symbol_annotation_impl.hpp +++ b/src/mbgl/annotation/symbol_annotation_impl.hpp @@ -35,30 +35,50 @@ namespace geometry { // Make Boost Geometry aware of our LatLng type namespace traits { -template<> struct tag { using type = point_tag; }; -template<> struct dimension : boost::mpl::int_<2> {}; -template<> struct coordinate_type { using type = double; }; -template<> struct coordinate_system { using type = boost::geometry::cs::cartesian; }; +template <> +struct tag { + using type = point_tag; +}; +template <> +struct dimension : boost::mpl::int_<2> {}; +template <> +struct coordinate_type { + using type = double; +}; +template <> +struct coordinate_system { + using type = boost::geometry::cs::cartesian; +}; -template<> struct access { static inline double get(mbgl::LatLng const& p) { return p.longitude(); } }; -template<> struct access { static inline double get(mbgl::LatLng const& p) { return p.latitude(); } }; +template <> +struct access { + static inline double get(mbgl::LatLng const& p) { return p.longitude(); } +}; +template <> +struct access { + static inline double get(mbgl::LatLng const& p) { return p.latitude(); } +}; -template<> struct tag { using type = box_tag; }; -template<> struct point_type { using type = mbgl::LatLng; }; +template <> +struct tag { + using type = box_tag; +}; +template <> +struct point_type { + using type = mbgl::LatLng; +}; template -struct indexed_access -{ +struct indexed_access { using ct = coordinate_type::type; static inline ct get(mbgl::LatLngBounds const& b) { return geometry::get(b.southwest()); } static inline void set(mbgl::LatLngBounds& b, ct const& value) { geometry::set(b.southwest(), value); } }; template -struct indexed_access -{ +struct indexed_access { using ct = coordinate_type::type; - static inline ct get(mbgl::LatLngBounds const& b) { return geometry::get(b.northeast()); } + static inline ct get(mbgl::LatLngBounds const& b) { return geometry::get(b.northeast()); } static inline void set(mbgl::LatLngBounds& b, ct const& value) { geometry::set(b.northeast(), value); } }; diff --git a/src/mbgl/geometry/anchor.hpp b/src/mbgl/geometry/anchor.hpp index 454d3ad0719..89cc4456a26 100644 --- a/src/mbgl/geometry/anchor.hpp +++ b/src/mbgl/geometry/anchor.hpp @@ -15,7 +15,9 @@ class Anchor { std::optional segment; Anchor(float x_, float y_, float angle_, std::optional segment_ = std::nullopt) - : point(x_, y_), angle(angle_), segment(std::move(segment_)) {} + : point(x_, y_), + angle(angle_), + segment(std::move(segment_)) {} }; using Anchors = std::vector; diff --git a/src/mbgl/geometry/debug_font_data.hpp b/src/mbgl/geometry/debug_font_data.hpp index 26c54cb4808..4ac7eaea7ea 100644 --- a/src/mbgl/geometry/debug_font_data.hpp +++ b/src/mbgl/geometry/debug_font_data.hpp @@ -3,100 +3,148 @@ #include #include -const int8_t simplex_1[] = { 5, 21, 5, 7, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2 }; -const int8_t simplex_2[] = { 4, 21, 4, 14, -1, -1, 12, 21, 12, 14 }; -const int8_t simplex_3[] = { 11, 25, 4, -7, -1, -1, 17, 25, 10, -7, -1, -1, 4, 12, 18, 12, -1, -1, 3, 6, 17, 6 }; -const int8_t simplex_4[] = { 8, 25, 8, -4, -1, -1, 12, 25, 12, -4, -1, -1, 17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3 }; -const int8_t simplex_5[] = { 21, 21, 3, 0, -1, -1, 8, 21, 10, 19, 10, 17, 9, 15, 7, 14, 5, 14, 3, 16, 3, 18, 4, 20, 6, 21, 8, 21, 10, 20, 13, 19, 16, 19, 19, 20, 21, 21, -1, -1, 17, 7, 15, 6, 14, 4, 14, 2, 16, 0, 18, 0, 20, 1, 21, 3, 21, 5, 19, 7, 17, 7 }; -const int8_t simplex_6[] = { 23, 12, 23, 13, 22, 14, 21, 14, 20, 13, 19, 11, 17, 6, 15, 3, 13, 1, 11, 0, 7, 0, 5, 1, 4, 2, 3, 4, 3, 6, 4, 8, 5, 9, 12, 13, 13, 14, 14, 16, 14, 18, 13, 20, 11, 21, 9, 20, 8, 18, 8, 16, 9, 13, 11, 10, 16, 3, 18, 1, 20, 0, 22, 0, 23, 1, 23, 2 }; -const int8_t simplex_7[] = { 5, 19, 4, 20, 5, 21, 6, 20, 6, 18, 5, 16, 4, 15 }; -const int8_t simplex_8[] = { 11, 25, 9, 23, 7, 20, 5, 16, 4, 11, 4, 7, 5, 2, 7, -2, 9, -5, 11, -7 }; -const int8_t simplex_9[] = { 3, 25, 5, 23, 7, 20, 9, 16, 10, 11, 10, 7, 9, 2, 7, -2, 5, -5, 3, -7 }; -const int8_t simplex_10[] = { 8, 21, 8, 9, -1, -1, 3, 18, 13, 12, -1, -1, 13, 18, 3, 12 }; -const int8_t simplex_11[] = { 13, 18, 13, 0, -1, -1, 4, 9, 22, 9 }; -const int8_t simplex_12[] = { 6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4 }; -const int8_t simplex_13[] = { 4, 9, 22, 9 }; -const int8_t simplex_14[] = { 5, 2, 4, 1, 5, 0, 6, 1, 5, 2 }; -const int8_t simplex_15[] = { 20, 25, 2, -7 }; -const int8_t simplex_16[] = { 9, 21, 6, 20, 4, 17, 3, 12, 3, 9, 4, 4, 6, 1, 9, 0, 11, 0, 14, 1, 16, 4, 17, 9, 17, 12, 16, 17, 14, 20, 11, 21, 9, 21 }; -const int8_t simplex_17[] = { 6, 17, 8, 18, 11, 21, 11, 0 }; -const int8_t simplex_18[] = { 4, 16, 4, 17, 5, 19, 6, 20, 8, 21, 12, 21, 14, 20, 15, 19, 16, 17, 16, 15, 15, 13, 13, 10, 3, 0, 17, 0 }; -const int8_t simplex_19[] = { 5, 21, 16, 21, 10, 13, 13, 13, 15, 12, 16, 11, 17, 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4 }; -const int8_t simplex_20[] = { 13, 21, 3, 7, 18, 7, -1, -1, 13, 21, 13, 0 }; -const int8_t simplex_21[] = { 15, 21, 5, 21, 4, 12, 5, 13, 8, 14, 11, 14, 14, 13, 16, 11, 17, 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4 }; -const int8_t simplex_22[] = { 16, 18, 15, 20, 12, 21, 10, 21, 7, 20, 5, 17, 4, 12, 4, 7, 5, 3, 7, 1, 10, 0, 11, 0, 14, 1, 16, 3, 17, 6, 17, 7, 16, 10, 14, 12, 11, 13, 10, 13, 7, 12, 5, 10, 4, 7 }; -const int8_t simplex_23[] = { 17, 21, 7, 0, -1, -1, 3, 21, 17, 21 }; -const int8_t simplex_24[] = { 8, 21, 5, 20, 4, 18, 4, 16, 5, 14, 7, 13, 11, 12, 14, 11, 16, 9, 17, 7, 17, 4, 16, 2, 15, 1, 12, 0, 8, 0, 5, 1, 4, 2, 3, 4, 3, 7, 4, 9, 6, 11, 9, 12, 13, 13, 15, 14, 16, 16, 16, 18, 15, 20, 12, 21, 8, 21 }; -const int8_t simplex_25[] = { 16, 14, 15, 11, 13, 9, 10, 8, 9, 8, 6, 9, 4, 11, 3, 14, 3, 15, 4, 18, 6, 20, 9, 21, 10, 21, 13, 20, 15, 18, 16, 14, 16, 9, 15, 4, 13, 1, 10, 0, 8, 0, 5, 1, 4, 3 }; -const int8_t simplex_26[] = { 5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2 }; -const int8_t simplex_27[] = { 5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4 }; -const int8_t simplex_28[] = { 20, 18, 4, 9, 20, 0 }; -const int8_t simplex_29[] = { 4, 12, 22, 12, -1, -1, 4, 6, 22, 6 }; -const int8_t simplex_30[] = { 4, 18, 20, 9, 4, 0 }; -const int8_t simplex_31[] = { 3, 16, 3, 17, 4, 19, 5, 20, 7, 21, 11, 21, 13, 20, 14, 19, 15, 17, 15, 15, 14, 13, 13, 12, 9, 10, 9, 7, -1, -1, 9, 2, 8, 1, 9, 0, 10, 1, 9, 2 }; -const int8_t simplex_32[] = { 18, 13, 17, 15, 15, 16, 12, 16, 10, 15, 9, 14, 8, 11, 8, 8, 9, 6, 11, 5, 14, 5, 16, 6, 17, 8, -1, -1, 12, 16, 10, 14, 9, 11, 9, 8, 10, 6, 11, 5, -1, -1, 18, 16, 17, 8, 17, 6, 19, 5, 21, 5, 23, 7, 24, 10, 24, 12, 23, 15, 22, 17, 20, 19, 18, 20, 15, 21, 12, 21, 9, 20, 7, 19, 5, 17, 4, 15, 3, 12, 3, 9, 4, 6, 5, 4, 7, 2, 9, 1, 12, 0, 15, 0, 18, 1, 20, 2, 21, 3, -1, -1, 19, 16, 18, 8, 18, 6, 19, 5 }; -const int8_t simplex_33[] = { 9, 21, 1, 0, -1, -1, 9, 21, 17, 0, -1, -1, 4, 7, 14, 7 }; -const int8_t simplex_34[] = { 4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, 11, -1, -1, 4, 11, 13, 11, 16, 10, 17, 9, 18, 7, 18, 4, 17, 2, 16, 1, 13, 0, 4, 0 }; -const int8_t simplex_35[] = { 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5 }; -const int8_t simplex_36[] = { 4, 21, 4, 0, -1, -1, 4, 21, 11, 21, 14, 20, 16, 18, 17, 16, 18, 13, 18, 8, 17, 5, 16, 3, 14, 1, 11, 0, 4, 0 }; -const int8_t simplex_37[] = { 4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11, -1, -1, 4, 0, 17, 0 }; -const int8_t simplex_38[] = { 4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11 }; -const int8_t simplex_39[] = { 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 18, 8, -1, -1, 13, 8, 18, 8 }; -const int8_t simplex_40[] = { 4, 21, 4, 0, -1, -1, 18, 21, 18, 0, -1, -1, 4, 11, 18, 11 }; -const int8_t simplex_41[] = { 4, 21, 4, 0 }; -const int8_t simplex_42[] = { 12, 21, 12, 5, 11, 2, 10, 1, 8, 0, 6, 0, 4, 1, 3, 2, 2, 5, 2, 7 }; -const int8_t simplex_43[] = { 4, 21, 4, 0, -1, -1, 18, 21, 4, 7, -1, -1, 9, 12, 18, 0 }; -const int8_t simplex_44[] = { 4, 21, 4, 0, -1, -1, 4, 0, 16, 0 }; -const int8_t simplex_45[] = { 4, 21, 4, 0, -1, -1, 4, 21, 12, 0, -1, -1, 20, 21, 12, 0, -1, -1, 20, 21, 20, 0 }; -const int8_t simplex_46[] = { 4, 21, 4, 0, -1, -1, 4, 21, 18, 0, -1, -1, 18, 21, 18, 0 }; -const int8_t simplex_47[] = { 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21 }; -const int8_t simplex_48[] = { 4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 14, 17, 12, 16, 11, 13, 10, 4, 10 }; -const int8_t simplex_49[] = { 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, -1, -1, 12, 4, 18, -2 }; -const int8_t simplex_50[] = { 4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, 11, 4, 11, -1, -1, 11, 11, 18, 0 }; -const int8_t simplex_51[] = { 17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3 }; -const int8_t simplex_52[] = { 8, 21, 8, 0, -1, -1, 1, 21, 15, 21 }; -const int8_t simplex_53[] = { 4, 21, 4, 6, 5, 3, 7, 1, 10, 0, 12, 0, 15, 1, 17, 3, 18, 6, 18, 21 }; -const int8_t simplex_54[] = { 1, 21, 9, 0, -1, -1, 17, 21, 9, 0 }; -const int8_t simplex_55[] = { 2, 21, 7, 0, -1, -1, 12, 21, 7, 0, -1, -1, 12, 21, 17, 0, -1, -1, 22, 21, 17, 0 }; -const int8_t simplex_56[] = { 3, 21, 17, 0, -1, -1, 17, 21, 3, 0 }; -const int8_t simplex_57[] = { 1, 21, 9, 11, 9, 0, -1, -1, 17, 21, 9, 11 }; -const int8_t simplex_58[] = { 17, 21, 3, 0, -1, -1, 3, 21, 17, 21, -1, -1, 3, 0, 17, 0 }; -const int8_t simplex_59[] = { 4, 25, 4, -7, -1, -1, 5, 25, 5, -7, -1, -1, 4, 25, 11, 25, -1, -1, 4, -7, 11, -7 }; -const int8_t simplex_60[] = { 0, 21, 14, -3 }; -const int8_t simplex_61[] = { 9, 25, 9, -7, -1, -1, 10, 25, 10, -7, -1, -1, 3, 25, 10, 25, -1, -1, 3, -7, 10, -7 }; -const int8_t simplex_62[] = { 6, 15, 8, 18, 10, 15, -1, -1, 3, 12, 8, 17, 13, 12, -1, -1, 8, 17, 8, 0 }; -const int8_t simplex_63[] = { 0, -2, 16, -2 }; -const int8_t simplex_64[] = { 6, 21, 5, 20, 4, 18, 4, 16, 5, 15, 6, 16, 5, 17 }; -const int8_t simplex_65[] = { 15, 14, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_66[] = { 4, 21, 4, 0, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3 }; -const int8_t simplex_67[] = { 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_68[] = { 15, 21, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_69[] = { 3, 8, 15, 8, 15, 10, 14, 12, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_70[] = { 10, 21, 8, 21, 6, 20, 5, 17, 5, 0, -1, -1, 2, 14, 9, 14 }; -const int8_t simplex_71[] = { 15, 14, 15, -2, 14, -5, 13, -6, 11, -7, 8, -7, 6, -6, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_72[] = { 4, 21, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0 }; -const int8_t simplex_73[] = { 3, 21, 4, 20, 5, 21, 4, 22, 3, 21, -1, -1, 4, 14, 4, 0 }; -const int8_t simplex_74[] = { 5, 21, 6, 20, 7, 21, 6, 22, 5, 21, -1, -1, 6, 14, 6, -3, 5, -6, 3, -7, 1, -7 }; -const int8_t simplex_75[] = { 4, 21, 4, 0, -1, -1, 14, 14, 4, 4, -1, -1, 8, 8, 15, 0 }; -const int8_t simplex_76[] = { 4, 21, 4, 0 }; -const int8_t simplex_77[] = { 4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0, -1, -1, 15, 10, 18, 13, 20, 14, 23, 14, 25, 13, 26, 10, 26, 0 }; -const int8_t simplex_78[] = { 4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0 }; -const int8_t simplex_79[] = { 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, 16, 6, 16, 8, 15, 11, 13, 13, 11, 14, 8, 14 }; -const int8_t simplex_80[] = { 4, 14, 4, -7, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3 }; -const int8_t simplex_81[] = { 15, 14, 15, -7, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_82[] = { 4, 14, 4, 0, -1, -1, 4, 8, 5, 11, 7, 13, 9, 14, 12, 14 }; -const int8_t simplex_83[] = { 14, 11, 13, 13, 10, 14, 7, 14, 4, 13, 3, 11, 4, 9, 6, 8, 11, 7, 13, 6, 14, 4, 14, 3, 13, 1, 10, 0, 7, 0, 4, 1, 3, 3 }; -const int8_t simplex_84[] = { 5, 21, 5, 4, 6, 1, 8, 0, 10, 0, -1, -1, 2, 14, 9, 14 }; -const int8_t simplex_85[] = { 4, 14, 4, 4, 5, 1, 7, 0, 10, 0, 12, 1, 15, 4, -1, -1, 15, 14, 15, 0 }; -const int8_t simplex_86[] = { 2, 14, 8, 0, -1, -1, 14, 14, 8, 0 }; -const int8_t simplex_87[] = { 3, 14, 7, 0, -1, -1, 11, 14, 7, 0, -1, -1, 11, 14, 15, 0, -1, -1, 19, 14, 15, 0 }; -const int8_t simplex_88[] = { 3, 14, 14, 0, -1, -1, 14, 14, 3, 0 }; -const int8_t simplex_89[] = { 2, 14, 8, 0, -1, -1, 14, 14, 8, 0, 6, -4, 4, -6, 2, -7, 1, -7 }; -const int8_t simplex_90[] = { 14, 14, 3, 0, -1, -1, 3, 14, 14, 14, -1, -1, 3, 0, 14, 0 }; -const int8_t simplex_91[] = { 9, 25, 7, 24, 6, 23, 5, 21, 5, 19, 6, 17, 7, 16, 8, 14, 8, 12, 6, 10, -1, -1, 7, 24, 6, 22, 6, 20, 7, 18, 8, 17, 9, 15, 9, 13, 8, 11, 4, 9, 8, 7, 9, 5, 9, 3, 8, 1, 7, 0, 6, -2, 6, -4, 7, -6, -1, -1, 6, 8, 8, 6, 8, 4, 7, 2, 6, 1, 5, -1, 5, -3, 6, -5, 7, -6, 9, -7 }; -const int8_t simplex_92[] = { 4, 25, 4, -7 }; -const int8_t simplex_93[] = { 5, 25, 7, 24, 8, 23, 9, 21, 9, 19, 8, 17, 7, 16, 6, 14, 6, 12, 8, 10, -1, -1, 7, 24, 8, 22, 8, 20, 7, 18, 6, 17, 5, 15, 5, 13, 6, 11, 10, 9, 6, 7, 5, 5, 5, 3, 6, 1, 7, 0, 8, -2, 8, -4, 7, -6, -1, -1, 8, 8, 6, 6, 6, 4, 7, 2, 8, 1, 9, -1, 9, -3, 8, -5, 7, -6, 5, -7 }; -const int8_t simplex_94[] = { 3, 6, 3, 8, 4, 11, 6, 12, 8, 12, 10, 11, 14, 8, 16, 7, 18, 7, 20, 8, 21, 10, -1, -1, 3, 8, 4, 10, 6, 11, 8, 11, 10, 10, 14, 7, 16, 6, 18, 6, 20, 7, 21, 10, 21, 12 }; +const int8_t simplex_1[] = {5, 21, 5, 7, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2}; +const int8_t simplex_2[] = {4, 21, 4, 14, -1, -1, 12, 21, 12, 14}; +const int8_t simplex_3[] = {11, 25, 4, -7, -1, -1, 17, 25, 10, -7, -1, -1, 4, 12, 18, 12, -1, -1, 3, 6, 17, 6}; +const int8_t simplex_4[] = {8, 25, 8, -4, -1, -1, 12, 25, 12, -4, -1, -1, 17, 18, 15, 20, 12, 21, + 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, + 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3}; +const int8_t simplex_5[] = {21, 21, 3, 0, -1, -1, 8, 21, 10, 19, 10, 17, 9, 15, 7, 14, 5, 14, 3, 16, 3, + 18, 4, 20, 6, 21, 8, 21, 10, 20, 13, 19, 16, 19, 19, 20, 21, 21, -1, -1, 17, 7, + 15, 6, 14, 4, 14, 2, 16, 0, 18, 0, 20, 1, 21, 3, 21, 5, 19, 7, 17, 7}; +const int8_t simplex_6[] = {23, 12, 23, 13, 22, 14, 21, 14, 20, 13, 19, 11, 17, 6, 15, 3, 13, 1, 11, 0, 7, 0, 5, + 1, 4, 2, 3, 4, 3, 6, 4, 8, 5, 9, 12, 13, 13, 14, 14, 16, 14, 18, 13, 20, 11, 21, + 9, 20, 8, 18, 8, 16, 9, 13, 11, 10, 16, 3, 18, 1, 20, 0, 22, 0, 23, 1, 23, 2}; +const int8_t simplex_7[] = {5, 19, 4, 20, 5, 21, 6, 20, 6, 18, 5, 16, 4, 15}; +const int8_t simplex_8[] = {11, 25, 9, 23, 7, 20, 5, 16, 4, 11, 4, 7, 5, 2, 7, -2, 9, -5, 11, -7}; +const int8_t simplex_9[] = {3, 25, 5, 23, 7, 20, 9, 16, 10, 11, 10, 7, 9, 2, 7, -2, 5, -5, 3, -7}; +const int8_t simplex_10[] = {8, 21, 8, 9, -1, -1, 3, 18, 13, 12, -1, -1, 13, 18, 3, 12}; +const int8_t simplex_11[] = {13, 18, 13, 0, -1, -1, 4, 9, 22, 9}; +const int8_t simplex_12[] = {6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4}; +const int8_t simplex_13[] = {4, 9, 22, 9}; +const int8_t simplex_14[] = {5, 2, 4, 1, 5, 0, 6, 1, 5, 2}; +const int8_t simplex_15[] = {20, 25, 2, -7}; +const int8_t simplex_16[] = {9, 21, 6, 20, 4, 17, 3, 12, 3, 9, 4, 4, 6, 1, 9, 0, 11, + 0, 14, 1, 16, 4, 17, 9, 17, 12, 16, 17, 14, 20, 11, 21, 9, 21}; +const int8_t simplex_17[] = {6, 17, 8, 18, 11, 21, 11, 0}; +const int8_t simplex_18[] = {4, 16, 4, 17, 5, 19, 6, 20, 8, 21, 12, 21, 14, 20, + 15, 19, 16, 17, 16, 15, 15, 13, 13, 10, 3, 0, 17, 0}; +const int8_t simplex_19[] = {5, 21, 16, 21, 10, 13, 13, 13, 15, 12, 16, 11, 17, 8, 17, + 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4}; +const int8_t simplex_20[] = {13, 21, 3, 7, 18, 7, -1, -1, 13, 21, 13, 0}; +const int8_t simplex_21[] = {15, 21, 5, 21, 4, 12, 5, 13, 8, 14, 11, 14, 14, 13, 16, 11, 17, + 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4}; +const int8_t simplex_22[] = {16, 18, 15, 20, 12, 21, 10, 21, 7, 20, 5, 17, 4, 12, 4, 7, 5, 3, 7, 1, 10, 0, 11, + 0, 14, 1, 16, 3, 17, 6, 17, 7, 16, 10, 14, 12, 11, 13, 10, 13, 7, 12, 5, 10, 4, 7}; +const int8_t simplex_23[] = {17, 21, 7, 0, -1, -1, 3, 21, 17, 21}; +const int8_t simplex_24[] = {8, 21, 5, 20, 4, 18, 4, 16, 5, 14, 7, 13, 11, 12, 14, 11, 16, 9, 17, 7, + 17, 4, 16, 2, 15, 1, 12, 0, 8, 0, 5, 1, 4, 2, 3, 4, 3, 7, 4, 9, + 6, 11, 9, 12, 13, 13, 15, 14, 16, 16, 16, 18, 15, 20, 12, 21, 8, 21}; +const int8_t simplex_25[] = {16, 14, 15, 11, 13, 9, 10, 8, 9, 8, 6, 9, 4, 11, 3, 14, 3, 15, 4, 18, 6, 20, 9, + 21, 10, 21, 13, 20, 15, 18, 16, 14, 16, 9, 15, 4, 13, 1, 10, 0, 8, 0, 5, 1, 4, 3}; +const int8_t simplex_26[] = {5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2}; +const int8_t simplex_27[] = {5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 6, 1, + 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4}; +const int8_t simplex_28[] = {20, 18, 4, 9, 20, 0}; +const int8_t simplex_29[] = {4, 12, 22, 12, -1, -1, 4, 6, 22, 6}; +const int8_t simplex_30[] = {4, 18, 20, 9, 4, 0}; +const int8_t simplex_31[] = {3, 16, 3, 17, 4, 19, 5, 20, 7, 21, 11, 21, 13, 20, 14, 19, 15, 17, 15, 15, + 14, 13, 13, 12, 9, 10, 9, 7, -1, -1, 9, 2, 8, 1, 9, 0, 10, 1, 9, 2}; +const int8_t simplex_32[] = {18, 13, 17, 15, 15, 16, 12, 16, 10, 15, 9, 14, 8, 11, 8, 8, 9, 6, 11, 5, 14, 5, + 16, 6, 17, 8, -1, -1, 12, 16, 10, 14, 9, 11, 9, 8, 10, 6, 11, 5, -1, -1, 18, 16, + 17, 8, 17, 6, 19, 5, 21, 5, 23, 7, 24, 10, 24, 12, 23, 15, 22, 17, 20, 19, 18, 20, + 15, 21, 12, 21, 9, 20, 7, 19, 5, 17, 4, 15, 3, 12, 3, 9, 4, 6, 5, 4, 7, 2, + 9, 1, 12, 0, 15, 0, 18, 1, 20, 2, 21, 3, -1, -1, 19, 16, 18, 8, 18, 6, 19, 5}; +const int8_t simplex_33[] = {9, 21, 1, 0, -1, -1, 9, 21, 17, 0, -1, -1, 4, 7, 14, 7}; +const int8_t simplex_34[] = {4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, + 11, -1, -1, 4, 11, 13, 11, 16, 10, 17, 9, 18, 7, 18, 4, 17, 2, 16, 1, 13, 0, 4, 0}; +const int8_t simplex_35[] = {18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, + 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5}; +const int8_t simplex_36[] = {4, 21, 4, 0, -1, -1, 4, 21, 11, 21, 14, 20, 16, 18, 17, + 16, 18, 13, 18, 8, 17, 5, 16, 3, 14, 1, 11, 0, 4, 0}; +const int8_t simplex_37[] = {4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11, -1, -1, 4, 0, 17, 0}; +const int8_t simplex_38[] = {4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11}; +const int8_t simplex_39[] = {18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, + 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 18, 8, -1, -1, 13, 8, 18, 8}; +const int8_t simplex_40[] = {4, 21, 4, 0, -1, -1, 18, 21, 18, 0, -1, -1, 4, 11, 18, 11}; +const int8_t simplex_41[] = {4, 21, 4, 0}; +const int8_t simplex_42[] = {12, 21, 12, 5, 11, 2, 10, 1, 8, 0, 6, 0, 4, 1, 3, 2, 2, 5, 2, 7}; +const int8_t simplex_43[] = {4, 21, 4, 0, -1, -1, 18, 21, 4, 7, -1, -1, 9, 12, 18, 0}; +const int8_t simplex_44[] = {4, 21, 4, 0, -1, -1, 4, 0, 16, 0}; +const int8_t simplex_45[] = {4, 21, 4, 0, -1, -1, 4, 21, 12, 0, -1, -1, 20, 21, 12, 0, -1, -1, 20, 21, 20, 0}; +const int8_t simplex_46[] = {4, 21, 4, 0, -1, -1, 4, 21, 18, 0, -1, -1, 18, 21, 18, 0}; +const int8_t simplex_47[] = {9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, + 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21}; +const int8_t simplex_48[] = {4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, + 19, 18, 17, 18, 14, 17, 12, 16, 11, 13, 10, 4, 10}; +const int8_t simplex_49[] = {9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, + 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, + 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, -1, -1, 12, 4, 18, -2}; +const int8_t simplex_50[] = {4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, + 18, 15, 17, 13, 16, 12, 13, 11, 4, 11, -1, -1, 11, 11, 18, 0}; +const int8_t simplex_51[] = {17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, + 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3}; +const int8_t simplex_52[] = {8, 21, 8, 0, -1, -1, 1, 21, 15, 21}; +const int8_t simplex_53[] = {4, 21, 4, 6, 5, 3, 7, 1, 10, 0, 12, 0, 15, 1, 17, 3, 18, 6, 18, 21}; +const int8_t simplex_54[] = {1, 21, 9, 0, -1, -1, 17, 21, 9, 0}; +const int8_t simplex_55[] = {2, 21, 7, 0, -1, -1, 12, 21, 7, 0, -1, -1, 12, 21, 17, 0, -1, -1, 22, 21, 17, 0}; +const int8_t simplex_56[] = {3, 21, 17, 0, -1, -1, 17, 21, 3, 0}; +const int8_t simplex_57[] = {1, 21, 9, 11, 9, 0, -1, -1, 17, 21, 9, 11}; +const int8_t simplex_58[] = {17, 21, 3, 0, -1, -1, 3, 21, 17, 21, -1, -1, 3, 0, 17, 0}; +const int8_t simplex_59[] = {4, 25, 4, -7, -1, -1, 5, 25, 5, -7, -1, -1, 4, 25, 11, 25, -1, -1, 4, -7, 11, -7}; +const int8_t simplex_60[] = {0, 21, 14, -3}; +const int8_t simplex_61[] = {9, 25, 9, -7, -1, -1, 10, 25, 10, -7, -1, -1, 3, 25, 10, 25, -1, -1, 3, -7, 10, -7}; +const int8_t simplex_62[] = {6, 15, 8, 18, 10, 15, -1, -1, 3, 12, 8, 17, 13, 12, -1, -1, 8, 17, 8, 0}; +const int8_t simplex_63[] = {0, -2, 16, -2}; +const int8_t simplex_64[] = {6, 21, 5, 20, 4, 18, 4, 16, 5, 15, 6, 16, 5, 17}; +const int8_t simplex_65[] = {15, 14, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, + 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_66[] = {4, 21, 4, 0, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, + 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3}; +const int8_t simplex_67[] = {15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, + 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_68[] = {15, 21, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, + 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_69[] = {3, 8, 15, 8, 15, 10, 14, 12, 13, 13, 11, 14, 8, 14, 6, 13, 4, + 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_70[] = {10, 21, 8, 21, 6, 20, 5, 17, 5, 0, -1, -1, 2, 14, 9, 14}; +const int8_t simplex_71[] = {15, 14, 15, -2, 14, -5, 13, -6, 11, -7, 8, -7, 6, -6, -1, -1, 15, 11, 13, 13, 11, 14, + 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_72[] = {4, 21, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0}; +const int8_t simplex_73[] = {3, 21, 4, 20, 5, 21, 4, 22, 3, 21, -1, -1, 4, 14, 4, 0}; +const int8_t simplex_74[] = {5, 21, 6, 20, 7, 21, 6, 22, 5, 21, -1, -1, 6, 14, 6, -3, 5, -6, 3, -7, 1, -7}; +const int8_t simplex_75[] = {4, 21, 4, 0, -1, -1, 14, 14, 4, 4, -1, -1, 8, 8, 15, 0}; +const int8_t simplex_76[] = {4, 21, 4, 0}; +const int8_t simplex_77[] = {4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, + 15, 0, -1, -1, 15, 10, 18, 13, 20, 14, 23, 14, 25, 13, 26, 10, 26, 0}; +const int8_t simplex_78[] = {4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0}; +const int8_t simplex_79[] = {8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, + 0, 13, 1, 15, 3, 16, 6, 16, 8, 15, 11, 13, 13, 11, 14, 8, 14}; +const int8_t simplex_80[] = {4, 14, 4, -7, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, + 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3}; +const int8_t simplex_81[] = {15, 14, 15, -7, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, + 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_82[] = {4, 14, 4, 0, -1, -1, 4, 8, 5, 11, 7, 13, 9, 14, 12, 14}; +const int8_t simplex_83[] = {14, 11, 13, 13, 10, 14, 7, 14, 4, 13, 3, 11, 4, 9, 6, 8, 11, + 7, 13, 6, 14, 4, 14, 3, 13, 1, 10, 0, 7, 0, 4, 1, 3, 3}; +const int8_t simplex_84[] = {5, 21, 5, 4, 6, 1, 8, 0, 10, 0, -1, -1, 2, 14, 9, 14}; +const int8_t simplex_85[] = {4, 14, 4, 4, 5, 1, 7, 0, 10, 0, 12, 1, 15, 4, -1, -1, 15, 14, 15, 0}; +const int8_t simplex_86[] = {2, 14, 8, 0, -1, -1, 14, 14, 8, 0}; +const int8_t simplex_87[] = {3, 14, 7, 0, -1, -1, 11, 14, 7, 0, -1, -1, 11, 14, 15, 0, -1, -1, 19, 14, 15, 0}; +const int8_t simplex_88[] = {3, 14, 14, 0, -1, -1, 14, 14, 3, 0}; +const int8_t simplex_89[] = {2, 14, 8, 0, -1, -1, 14, 14, 8, 0, 6, -4, 4, -6, 2, -7, 1, -7}; +const int8_t simplex_90[] = {14, 14, 3, 0, -1, -1, 3, 14, 14, 14, -1, -1, 3, 0, 14, 0}; +const int8_t simplex_91[] = {9, 25, 7, 24, 6, 23, 5, 21, 5, 19, 6, 17, 7, 16, 8, 14, 8, 12, 6, 10, + -1, -1, 7, 24, 6, 22, 6, 20, 7, 18, 8, 17, 9, 15, 9, 13, 8, 11, 4, 9, + 8, 7, 9, 5, 9, 3, 8, 1, 7, 0, 6, -2, 6, -4, 7, -6, -1, -1, 6, 8, + 8, 6, 8, 4, 7, 2, 6, 1, 5, -1, 5, -3, 6, -5, 7, -6, 9, -7}; +const int8_t simplex_92[] = {4, 25, 4, -7}; +const int8_t simplex_93[] = {5, 25, 7, 24, 8, 23, 9, 21, 9, 19, 8, 17, 7, 16, 6, 14, 6, 12, 8, 10, + -1, -1, 7, 24, 8, 22, 8, 20, 7, 18, 6, 17, 5, 15, 5, 13, 6, 11, 10, 9, + 6, 7, 5, 5, 5, 3, 6, 1, 7, 0, 8, -2, 8, -4, 7, -6, -1, -1, 8, 8, + 6, 6, 6, 4, 7, 2, 8, 1, 9, -1, 9, -3, 8, -5, 7, -6, 5, -7}; +const int8_t simplex_94[] = {3, 6, 3, 8, 4, 11, 6, 12, 8, 12, 10, 11, 14, 8, 16, 7, 18, 7, 20, 8, 21, 10, -1, + -1, 3, 8, 4, 10, 6, 11, 8, 11, 10, 10, 14, 7, 16, 6, 18, 6, 20, 7, 21, 10, 21, 12}; struct glyph { uint8_t width; @@ -108,99 +156,193 @@ struct glyph { // http://paulbourke.net/dataformats/hershey/ const glyph simplex[] = { - /* 32 */ { 16, 0, nullptr }, - /* 33 ! */ { 10, sizeof(simplex_1), simplex_1 }, - /* 34 " */ { 16, sizeof(simplex_2), simplex_2 }, - /* 35 # */ { 21, sizeof(simplex_3), simplex_3 }, - /* 36 $ */ { 20, sizeof(simplex_4), simplex_4 }, - /* 37 % */ { 24, sizeof(simplex_5), simplex_5 }, - /* 38 & */ { 26, sizeof(simplex_6), simplex_6 }, - /* 39 ' */ { 10, sizeof(simplex_7), simplex_7 }, - /* 40 ( */ { 14, sizeof(simplex_8), simplex_8 }, - /* 41 ) */ { 14, sizeof(simplex_9), simplex_9 }, - /* 42 * */ { 16, sizeof(simplex_10), simplex_10 }, - /* 43 + */ { 26, sizeof(simplex_11), simplex_11 }, - /* 44 , */ { 10, sizeof(simplex_12), simplex_12 }, - /* 45 - */ { 26, sizeof(simplex_13), simplex_13 }, - /* 46 . */ { 10, sizeof(simplex_14), simplex_14 }, - /* 47 / */ { 22, sizeof(simplex_15), simplex_15 }, - /* 48 0 */ { 20, sizeof(simplex_16), simplex_16 }, - /* 49 1 */ { 20, sizeof(simplex_17), simplex_17 }, - /* 50 2 */ { 20, sizeof(simplex_18), simplex_18 }, - /* 51 3 */ { 20, sizeof(simplex_19), simplex_19 }, - /* 52 4 */ { 20, sizeof(simplex_20), simplex_20 }, - /* 53 5 */ { 20, sizeof(simplex_21), simplex_21 }, - /* 54 6 */ { 20, sizeof(simplex_22), simplex_22 }, - /* 55 7 */ { 20, sizeof(simplex_23), simplex_23 }, - /* 56 8 */ { 20, sizeof(simplex_24), simplex_24 }, - /* 57 9 */ { 20, sizeof(simplex_25), simplex_25 }, - /* 58 : */ { 10, sizeof(simplex_26), simplex_26 }, - /* 59 ; */ { 10, sizeof(simplex_27), simplex_27 }, - /* 60 < */ { 24, sizeof(simplex_28), simplex_28 }, - /* 61 = */ { 26, sizeof(simplex_29), simplex_29 }, - /* 62 > */ { 24, sizeof(simplex_30), simplex_30 }, - /* 63 ? */ { 18, sizeof(simplex_31), simplex_31 }, - /* 64 @ */ { 27, sizeof(simplex_32), simplex_32 }, - /* 65 A */ { 18, sizeof(simplex_33), simplex_33 }, - /* 66 B */ { 21, sizeof(simplex_34), simplex_34 }, - /* 67 C */ { 21, sizeof(simplex_35), simplex_35 }, - /* 68 D */ { 21, sizeof(simplex_36), simplex_36 }, - /* 69 E */ { 19, sizeof(simplex_37), simplex_37 }, - /* 70 F */ { 18, sizeof(simplex_38), simplex_38 }, - /* 71 G */ { 21, sizeof(simplex_39), simplex_39 }, - /* 72 H */ { 22, sizeof(simplex_40), simplex_40 }, - /* 73 I */ { 8, sizeof(simplex_41), simplex_41 }, - /* 74 J */ { 16, sizeof(simplex_42), simplex_42 }, - /* 75 K */ { 21, sizeof(simplex_43), simplex_43 }, - /* 76 L */ { 17, sizeof(simplex_44), simplex_44 }, - /* 77 M */ { 24, sizeof(simplex_45), simplex_45 }, - /* 78 N */ { 22, sizeof(simplex_46), simplex_46 }, - /* 79 O */ { 22, sizeof(simplex_47), simplex_47 }, - /* 80 P */ { 21, sizeof(simplex_48), simplex_48 }, - /* 81 Q */ { 22, sizeof(simplex_49), simplex_49 }, - /* 82 R */ { 21, sizeof(simplex_50), simplex_50 }, - /* 83 S */ { 20, sizeof(simplex_51), simplex_51 }, - /* 84 T */ { 16, sizeof(simplex_52), simplex_52 }, - /* 85 U */ { 22, sizeof(simplex_53), simplex_53 }, - /* 86 V */ { 18, sizeof(simplex_54), simplex_54 }, - /* 87 W */ { 24, sizeof(simplex_55), simplex_55 }, - /* 88 X */ { 20, sizeof(simplex_56), simplex_56 }, - /* 89 Y */ { 18, sizeof(simplex_57), simplex_57 }, - /* 90 Z */ { 20, sizeof(simplex_58), simplex_58 }, - /* 91 [ */ { 14, sizeof(simplex_59), simplex_59 }, - /* 92 \ */ { 14, sizeof(simplex_60), simplex_60 }, - /* 93 ] */ { 14, sizeof(simplex_61), simplex_61 }, - /* 94 ^ */ { 16, sizeof(simplex_62), simplex_62 }, - /* 95 _ */ { 16, sizeof(simplex_63), simplex_63 }, - /* 96 ` */ { 10, sizeof(simplex_64), simplex_64 }, - /* 97 a */ { 19, sizeof(simplex_65), simplex_65 }, - /* 98 b */ { 19, sizeof(simplex_66), simplex_66 }, - /* 99 c */ { 18, sizeof(simplex_67), simplex_67 }, - /* 100 d */ { 19, sizeof(simplex_68), simplex_68 }, - /* 101 e */ { 18, sizeof(simplex_69), simplex_69 }, - /* 102 f */ { 12, sizeof(simplex_70), simplex_70 }, - /* 103 g */ { 19, sizeof(simplex_71), simplex_71 }, - /* 104 h */ { 19, sizeof(simplex_72), simplex_72 }, - /* 105 i */ { 8, sizeof(simplex_73), simplex_73 }, - /* 106 j */ { 10, sizeof(simplex_74), simplex_74 }, - /* 107 k */ { 17, sizeof(simplex_75), simplex_75 }, - /* 108 l */ { 8, sizeof(simplex_76), simplex_76 }, - /* 109 m */ { 30, sizeof(simplex_77), simplex_77 }, - /* 110 n */ { 19, sizeof(simplex_78), simplex_78 }, - /* 111 o */ { 19, sizeof(simplex_79), simplex_79 }, - /* 112 p */ { 19, sizeof(simplex_80), simplex_80 }, - /* 113 q */ { 19, sizeof(simplex_81), simplex_81 }, - /* 114 r */ { 13, sizeof(simplex_82), simplex_82 }, - /* 115 s */ { 17, sizeof(simplex_83), simplex_83 }, - /* 116 t */ { 12, sizeof(simplex_84), simplex_84 }, - /* 117 u */ { 19, sizeof(simplex_85), simplex_85 }, - /* 118 v */ { 16, sizeof(simplex_86), simplex_86 }, - /* 119 w */ { 22, sizeof(simplex_87), simplex_87 }, - /* 120 x */ { 17, sizeof(simplex_88), simplex_88 }, - /* 121 y */ { 16, sizeof(simplex_89), simplex_89 }, - /* 122 z */ { 17, sizeof(simplex_90), simplex_90 }, - /* 123 { */ { 14, sizeof(simplex_91), simplex_91 }, - /* 124 | */ { 8, sizeof(simplex_92), simplex_92 }, - /* 125 } */ { 14, sizeof(simplex_93), simplex_93 }, - /* 126 ~ */ { 24, sizeof(simplex_94), simplex_94 }, + /* 32 */ {16, 0, nullptr}, + /* 33 ! */ + {10, sizeof(simplex_1), simplex_1}, + /* 34 " */ + {16, sizeof(simplex_2), simplex_2}, + /* 35 # */ + {21, sizeof(simplex_3), simplex_3}, + /* 36 $ */ + {20, sizeof(simplex_4), simplex_4}, + /* 37 % */ + {24, sizeof(simplex_5), simplex_5}, + /* 38 & */ + {26, sizeof(simplex_6), simplex_6}, + /* 39 ' */ + {10, sizeof(simplex_7), simplex_7}, + /* 40 ( */ + {14, sizeof(simplex_8), simplex_8}, + /* 41 ) */ + {14, sizeof(simplex_9), simplex_9}, + /* 42 * */ + {16, sizeof(simplex_10), simplex_10}, + /* 43 + */ + {26, sizeof(simplex_11), simplex_11}, + /* 44 , */ + {10, sizeof(simplex_12), simplex_12}, + /* 45 - */ + {26, sizeof(simplex_13), simplex_13}, + /* 46 . */ + {10, sizeof(simplex_14), simplex_14}, + /* 47 / */ + {22, sizeof(simplex_15), simplex_15}, + /* 48 0 */ + {20, sizeof(simplex_16), simplex_16}, + /* 49 1 */ + {20, sizeof(simplex_17), simplex_17}, + /* 50 2 */ + {20, sizeof(simplex_18), simplex_18}, + /* 51 3 */ + {20, sizeof(simplex_19), simplex_19}, + /* 52 4 */ + {20, sizeof(simplex_20), simplex_20}, + /* 53 5 */ + {20, sizeof(simplex_21), simplex_21}, + /* 54 6 */ + {20, sizeof(simplex_22), simplex_22}, + /* 55 7 */ + {20, sizeof(simplex_23), simplex_23}, + /* 56 8 */ + {20, sizeof(simplex_24), simplex_24}, + /* 57 9 */ + {20, sizeof(simplex_25), simplex_25}, + /* 58 : */ + {10, sizeof(simplex_26), simplex_26}, + /* 59 ; */ + {10, sizeof(simplex_27), simplex_27}, + /* 60 < */ + {24, sizeof(simplex_28), simplex_28}, + /* 61 = */ + {26, sizeof(simplex_29), simplex_29}, + /* 62 > */ + {24, sizeof(simplex_30), simplex_30}, + /* 63 ? */ + {18, sizeof(simplex_31), simplex_31}, + /* 64 @ */ + {27, sizeof(simplex_32), simplex_32}, + /* 65 A */ + {18, sizeof(simplex_33), simplex_33}, + /* 66 B */ + {21, sizeof(simplex_34), simplex_34}, + /* 67 C */ + {21, sizeof(simplex_35), simplex_35}, + /* 68 D */ + {21, sizeof(simplex_36), simplex_36}, + /* 69 E */ + {19, sizeof(simplex_37), simplex_37}, + /* 70 F */ + {18, sizeof(simplex_38), simplex_38}, + /* 71 G */ + {21, sizeof(simplex_39), simplex_39}, + /* 72 H */ + {22, sizeof(simplex_40), simplex_40}, + /* 73 I */ + {8, sizeof(simplex_41), simplex_41}, + /* 74 J */ + {16, sizeof(simplex_42), simplex_42}, + /* 75 K */ + {21, sizeof(simplex_43), simplex_43}, + /* 76 L */ + {17, sizeof(simplex_44), simplex_44}, + /* 77 M */ + {24, sizeof(simplex_45), simplex_45}, + /* 78 N */ + {22, sizeof(simplex_46), simplex_46}, + /* 79 O */ + {22, sizeof(simplex_47), simplex_47}, + /* 80 P */ + {21, sizeof(simplex_48), simplex_48}, + /* 81 Q */ + {22, sizeof(simplex_49), simplex_49}, + /* 82 R */ + {21, sizeof(simplex_50), simplex_50}, + /* 83 S */ + {20, sizeof(simplex_51), simplex_51}, + /* 84 T */ + {16, sizeof(simplex_52), simplex_52}, + /* 85 U */ + {22, sizeof(simplex_53), simplex_53}, + /* 86 V */ + {18, sizeof(simplex_54), simplex_54}, + /* 87 W */ + {24, sizeof(simplex_55), simplex_55}, + /* 88 X */ + {20, sizeof(simplex_56), simplex_56}, + /* 89 Y */ + {18, sizeof(simplex_57), simplex_57}, + /* 90 Z */ + {20, sizeof(simplex_58), simplex_58}, + /* 91 [ */ + {14, sizeof(simplex_59), simplex_59}, + /* 92 \ */ + {14, sizeof(simplex_60), simplex_60}, + /* 93 ] */ + {14, sizeof(simplex_61), simplex_61}, + /* 94 ^ */ + {16, sizeof(simplex_62), simplex_62}, + /* 95 _ */ + {16, sizeof(simplex_63), simplex_63}, + /* 96 ` */ + {10, sizeof(simplex_64), simplex_64}, + /* 97 a */ + {19, sizeof(simplex_65), simplex_65}, + /* 98 b */ + {19, sizeof(simplex_66), simplex_66}, + /* 99 c */ + {18, sizeof(simplex_67), simplex_67}, + /* 100 d */ + {19, sizeof(simplex_68), simplex_68}, + /* 101 e */ + {18, sizeof(simplex_69), simplex_69}, + /* 102 f */ + {12, sizeof(simplex_70), simplex_70}, + /* 103 g */ + {19, sizeof(simplex_71), simplex_71}, + /* 104 h */ + {19, sizeof(simplex_72), simplex_72}, + /* 105 i */ + {8, sizeof(simplex_73), simplex_73}, + /* 106 j */ + {10, sizeof(simplex_74), simplex_74}, + /* 107 k */ + {17, sizeof(simplex_75), simplex_75}, + /* 108 l */ + {8, sizeof(simplex_76), simplex_76}, + /* 109 m */ + {30, sizeof(simplex_77), simplex_77}, + /* 110 n */ + {19, sizeof(simplex_78), simplex_78}, + /* 111 o */ + {19, sizeof(simplex_79), simplex_79}, + /* 112 p */ + {19, sizeof(simplex_80), simplex_80}, + /* 113 q */ + {19, sizeof(simplex_81), simplex_81}, + /* 114 r */ + {13, sizeof(simplex_82), simplex_82}, + /* 115 s */ + {17, sizeof(simplex_83), simplex_83}, + /* 116 t */ + {12, sizeof(simplex_84), simplex_84}, + /* 117 u */ + {19, sizeof(simplex_85), simplex_85}, + /* 118 v */ + {16, sizeof(simplex_86), simplex_86}, + /* 119 w */ + {22, sizeof(simplex_87), simplex_87}, + /* 120 x */ + {17, sizeof(simplex_88), simplex_88}, + /* 121 y */ + {16, sizeof(simplex_89), simplex_89}, + /* 122 z */ + {17, sizeof(simplex_90), simplex_90}, + /* 123 { */ + {14, sizeof(simplex_91), simplex_91}, + /* 124 | */ + {8, sizeof(simplex_92), simplex_92}, + /* 125 } */ + {14, sizeof(simplex_93), simplex_93}, + /* 126 ~ */ + {24, sizeof(simplex_94), simplex_94}, }; diff --git a/src/mbgl/geometry/dem_data.cpp b/src/mbgl/geometry/dem_data.cpp index 80a3289a3b3..9984903b03e 100644 --- a/src/mbgl/geometry/dem_data.cpp +++ b/src/mbgl/geometry/dem_data.cpp @@ -3,14 +3,13 @@ namespace mbgl { -DEMData::DEMData(const PremultipliedImage& _image, Tileset::DEMEncoding _encoding): - dim(_image.size.height), - // extra two pixels per row for border backfilling on either edge - stride(dim + 2), - encoding(_encoding), - image({ static_cast(stride), static_cast(stride) }) { - - if (_image.size.height != _image.size.width){ +DEMData::DEMData(const PremultipliedImage& _image, Tileset::DEMEncoding _encoding) + : dim(_image.size.height), + // extra two pixels per row for border backfilling on either edge + stride(dim + 2), + encoding(_encoding), + image({static_cast(stride), static_cast(stride)}) { + if (_image.size.height != _image.size.width) { throw std::runtime_error("raster-dem tiles must be square."); } @@ -21,7 +20,7 @@ DEMData::DEMData(const PremultipliedImage& _image, Tileset::DEMEncoding _encodin dest += stride; source += dim; } - + // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of // pixels around the image with the data of the nearest pixel from the image. this data is eventually // replaced when the tile's neighboring tiles are loaded and the accurate data can be backfilled using @@ -36,7 +35,7 @@ DEMData::DEMData(const PremultipliedImage& _image, Tileset::DEMEncoding _encodin // right vertical border data[rowOffset + dim + 1] = data[rowOffset + dim]; } - + // top horizontal border with corners memcpy(data, data + stride, stride * 4); // bottom horizontal border with corners @@ -62,16 +61,20 @@ void DEMData::backfillBorder(const DEMData& borderTileData, int8_t dx, int8_t dy int32_t xMax = dx * dim + dim; int32_t yMin = dy * dim; int32_t yMax = dy * dim + dim; - - if (dx == -1) xMin = xMax - 1; - else if (dx == 1) xMax = xMin + 1; - - if (dy == -1) yMin = yMax - 1; - else if (dy == 1) yMax = yMin + 1; - + + if (dx == -1) + xMin = xMax - 1; + else if (dx == 1) + xMax = xMin + 1; + + if (dy == -1) + yMin = yMax - 1; + else if (dy == 1) + yMax = yMin + 1; + int32_t ox = -dx * dim; int32_t oy = -dy * dim; - + auto* dest = reinterpret_cast(image.data.get()); auto* source = reinterpret_cast(o.image.data.get()); @@ -90,9 +93,9 @@ int32_t DEMData::get(const int32_t x, const int32_t y) const { const std::array& DEMData::getUnpackVector() const { // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb - static const std::array unpackMapbox = {{ 6553.6f, 25.6f, 0.1f, 10000.0f }}; + static const std::array unpackMapbox = {{6553.6f, 25.6f, 0.1f, 10000.0f}}; // https://aws.amazon.com/public-datasets/terrain/ - static const std::array unpackTerrarium = {{ 256.0f, 1.0f, 1.0f / 256.0f, 32768.0f }}; + static const std::array unpackTerrarium = {{256.0f, 1.0f, 1.0f / 256.0f, 32768.0f}}; return encoding == Tileset::DEMEncoding::Terrarium ? unpackTerrarium : unpackMapbox; } diff --git a/src/mbgl/geometry/dem_data.hpp b/src/mbgl/geometry/dem_data.hpp index 5044fb06589..b087afb63f0 100644 --- a/src/mbgl/geometry/dem_data.hpp +++ b/src/mbgl/geometry/dem_data.hpp @@ -19,14 +19,11 @@ class DEMData { int32_t get(int32_t x, int32_t y) const; const std::array& getUnpackVector() const; - const PremultipliedImage* getImage() const { - return ℑ - } + const PremultipliedImage* getImage() const { return ℑ } const int32_t dim; const int32_t stride; - private: Tileset::DEMEncoding encoding; PremultipliedImage image; @@ -38,7 +35,6 @@ class DEMData { assert(y < dim + 1); return (y + 1) * stride + (x + 1); } - }; } // namespace mbgl diff --git a/src/mbgl/geometry/feature_index.cpp b/src/mbgl/geometry/feature_index.cpp index c64bdf8bd7b..10a5ad49b16 100644 --- a/src/mbgl/geometry/feature_index.cpp +++ b/src/mbgl/geometry/feature_index.cpp @@ -18,9 +18,11 @@ #include namespace { -mbgl::LatLng screenCoordinateToLatLng(mbgl::ScreenCoordinate point, - const mbgl::TransformState& state, - mbgl::LatLng::WrapMode wrapMode = mbgl::LatLng::Wrapped) { +mbgl::LatLng screenCoordinateToLatLng( + mbgl::ScreenCoordinate point, + const mbgl::TransformState& state, + mbgl::LatLng::WrapMode wrapMode = mbgl::LatLng::Wrapped +) { point.y = state.getSize().height - point.y; return state.screenCoordinateToLatLng(point, wrapMode); } @@ -35,58 +37,78 @@ namespace mbgl { FeatureIndex::FeatureIndex(std::unique_ptr tileData_) : grid(util::EXTENT, util::EXTENT, util::EXTENT / 16) // 16x16 grid -> 32px cell - , tileData(std::move(tileData_)) { -} - -void FeatureIndex::insert(const GeometryCollection& geometries, - std::size_t index, - const std::string& sourceLayerName, - const std::string& bucketLeaderID) { + , + tileData(std::move(tileData_)) {} + +void FeatureIndex::insert( + const GeometryCollection& geometries, + std::size_t index, + const std::string& sourceLayerName, + const std::string& bucketLeaderID +) { auto featureSortIndex = sortIndex++; for (const auto& ring : geometries) { auto envelope = mapbox::geometry::envelope(ring); - if (envelope.min.x < util::EXTENT && - envelope.min.y < util::EXTENT && - envelope.max.x >= 0 && + if (envelope.min.x < util::EXTENT && envelope.min.y < util::EXTENT && envelope.max.x >= 0 && envelope.max.y >= 0) { - grid.insert(IndexedSubfeature(index, sourceLayerName, bucketLeaderID, featureSortIndex), - {convertPoint(envelope.min), convertPoint(envelope.max)}); + grid.insert( + IndexedSubfeature(index, sourceLayerName, bucketLeaderID, featureSortIndex), + {convertPoint(envelope.min), convertPoint(envelope.max)} + ); } } } -void FeatureIndex::query(std::unordered_map>& result, - const GeometryCoordinates& queryGeometry, const TransformState& transformState, - const mat4& posMatrix, const double tileSize, const double scale, - const RenderedQueryOptions& queryOptions, const UnwrappedTileID& tileID, - const std::unordered_map& layers, - const float additionalQueryPadding, const SourceFeatureState& sourceFeatureState) const { +void FeatureIndex::query( + std::unordered_map>& result, + const GeometryCoordinates& queryGeometry, + const TransformState& transformState, + const mat4& posMatrix, + const double tileSize, + const double scale, + const RenderedQueryOptions& queryOptions, + const UnwrappedTileID& tileID, + const std::unordered_map& layers, + const float additionalQueryPadding, + const SourceFeatureState& sourceFeatureState +) const { if (!tileData) { return; } // Determine query radius const auto pixelsToTileUnits = static_cast(util::EXTENT / tileSize / scale); - const int16_t additionalPadding = std::min(util::EXTENT, static_cast(additionalQueryPadding * pixelsToTileUnits)); + const int16_t additionalPadding = std::min( + util::EXTENT, static_cast(additionalQueryPadding * pixelsToTileUnits) + ); // Query the grid index mapbox::geometry::box box = mapbox::geometry::envelope(queryGeometry); - std::vector features = grid.query({ convertPoint(box.min - additionalPadding), - convertPoint(box.max + additionalPadding) }); - + std::vector features = grid.query( + {convertPoint(box.min - additionalPadding), convertPoint(box.max + additionalPadding)} + ); std::sort(features.begin(), features.end(), [](const IndexedSubfeature& a, const IndexedSubfeature& b) { return a.sortIndex > b.sortIndex; }); size_t previousSortIndex = std::numeric_limits::max(); for (const auto& indexedFeature : features) { - // If this feature is the same as the previous feature, skip it. if (indexedFeature.sortIndex == previousSortIndex) continue; previousSortIndex = indexedFeature.sortIndex; - addFeature(result, indexedFeature, queryOptions, tileID.canonical, layers, queryGeometry, transformState, - pixelsToTileUnits, posMatrix, &sourceFeatureState); + addFeature( + result, + indexedFeature, + queryOptions, + tileID.canonical, + layers, + queryGeometry, + transformState, + pixelsToTileUnits, + posMatrix, + &sourceFeatureState + ); } } @@ -95,49 +117,70 @@ std::unordered_map> FeatureIndex::lookupSymbol const RenderedQueryOptions& queryOptions, const std::unordered_map& layers, const OverscaledTileID& tileID, - const FeatureSortOrder& featureSortOrder) const { + const FeatureSortOrder& featureSortOrder +) const { std::unordered_map> result; if (!tileData) { return result; } std::vector sortedFeatures(symbolFeatures.begin(), symbolFeatures.end()); - std::sort(sortedFeatures.begin(), sortedFeatures.end(), [featureSortOrder](const IndexedSubfeature& a, const IndexedSubfeature& b) { - // Same idea as the non-symbol sort order, but symbol features may have changed their sort order - // since their corresponding IndexedSubfeature was added to the CollisionIndex - // The 'featureSortOrder' is relatively inefficient for querying but cheap to build on every bucket sort - if (featureSortOrder) { - // queryRenderedSymbols documentation says we'll return features in - // "top-to-bottom" rendering order (aka last-to-first). - // Actually there can be multiple symbol instances per feature, so - // we sort each feature based on the first matching symbol instance. - auto sortedA = std::find(featureSortOrder->begin(), featureSortOrder->end(), a.index); - auto sortedB = std::find(featureSortOrder->begin(), featureSortOrder->end(), b.index); - assert(sortedA != featureSortOrder->end()); - assert(sortedB != featureSortOrder->end()); - return sortedA > sortedB; - } else { - // Bucket hasn't been re-sorted based on angle, so use same "reverse of appearance in source data" - // logic as non-symboles - return a.sortIndex > b.sortIndex; + std::sort( + sortedFeatures.begin(), + sortedFeatures.end(), + [featureSortOrder](const IndexedSubfeature& a, const IndexedSubfeature& b) { + // Same idea as the non-symbol sort order, but symbol features may have changed their sort order + // since their corresponding IndexedSubfeature was added to the CollisionIndex + // The 'featureSortOrder' is relatively inefficient for querying but cheap to build on every bucket + // sort + if (featureSortOrder) { + // queryRenderedSymbols documentation says we'll return features in + // "top-to-bottom" rendering order (aka last-to-first). + // Actually there can be multiple symbol instances per feature, so + // we sort each feature based on the first matching symbol instance. + auto sortedA = std::find(featureSortOrder->begin(), featureSortOrder->end(), a.index); + auto sortedB = std::find(featureSortOrder->begin(), featureSortOrder->end(), b.index); + assert(sortedA != featureSortOrder->end()); + assert(sortedB != featureSortOrder->end()); + return sortedA > sortedB; + } else { + // Bucket hasn't been re-sorted based on angle, so use same "reverse of appearance in source data" + // logic as non-symboles + return a.sortIndex > b.sortIndex; + } } - }); + ); for (const auto& symbolFeature : sortedFeatures) { mat4 unusedMatrix; - addFeature(result, symbolFeature, queryOptions, tileID.canonical, layers, GeometryCoordinates(), {}, 0, - unusedMatrix, nullptr); + addFeature( + result, + symbolFeature, + queryOptions, + tileID.canonical, + layers, + GeometryCoordinates(), + {}, + 0, + unusedMatrix, + nullptr + ); } return result; } -void FeatureIndex::addFeature(std::unordered_map>& result, - const IndexedSubfeature& indexedFeature, const RenderedQueryOptions& options, - const CanonicalTileID& tileID, - const std::unordered_map& layers, - const GeometryCoordinates& queryGeometry, const TransformState& transformState, - const float pixelsToTileUnits, const mat4& posMatrix, - const SourceFeatureState* sourceFeatureState) const { +void FeatureIndex::addFeature( + std::unordered_map>& result, + const IndexedSubfeature& indexedFeature, + const RenderedQueryOptions& options, + const CanonicalTileID& tileID, + const std::unordered_map& layers, + const GeometryCoordinates& queryGeometry, + const TransformState& transformState, + const float pixelsToTileUnits, + const mat4& posMatrix, + const SourceFeatureState* sourceFeatureState +) const { // Lazily calculated. std::unique_ptr sourceLayer; std::unique_ptr geometryTileFeature; @@ -165,14 +208,17 @@ void FeatureIndex::addFeature(std::unordered_mapbaseImpl->getTypeInfo()->crossTileIndex == style::LayerTypeInfo::CrossTileIndex::Required; + bool needsCrossTileIndex = renderLayer->baseImpl->getTypeInfo()->crossTileIndex == + style::LayerTypeInfo::CrossTileIndex::Required; if (!needsCrossTileIndex && - !renderLayer->queryIntersectsFeature(queryGeometry, *geometryTileFeature, tileID.z, transformState, - pixelsToTileUnits, posMatrix, state)) { + !renderLayer->queryIntersectsFeature( + queryGeometry, *geometryTileFeature, tileID.z, transformState, pixelsToTileUnits, posMatrix, state + )) { continue; } - if (options.filter && !(*options.filter)(style::expression::EvaluationContext { static_cast(tileID.z), geometryTileFeature.get() })) { + if (options.filter && !(*options.filter)(style::expression::EvaluationContext{ + static_cast(tileID.z), geometryTileFeature.get()})) { continue; } @@ -185,16 +231,19 @@ void FeatureIndex::addFeature(std::unordered_map FeatureIndex::translateQueryGeometry( - const GeometryCoordinates& queryGeometry, - const std::array& translate, - const style::TranslateAnchorType anchorType, - const float bearing, - const float pixelsToTileUnits) { + const GeometryCoordinates& queryGeometry, + const std::array& translate, + const style::TranslateAnchorType anchorType, + const float bearing, + const float pixelsToTileUnits +) { if (translate[0] == 0 && translate[1] == 0) { return {}; } - GeometryCoordinate translateVec(static_cast(translate[0] * pixelsToTileUnits), static_cast(translate[1] * pixelsToTileUnits)); + GeometryCoordinate translateVec( + static_cast(translate[0] * pixelsToTileUnits), static_cast(translate[1] * pixelsToTileUnits) + ); if (anchorType == style::TranslateAnchorType::Viewport) { translateVec = util::rotate(translateVec, -bearing); } @@ -212,9 +261,11 @@ void FeatureIndex::setBucketLayerIDs(const std::string& bucketLeaderID, const st DynamicFeatureIndex::~DynamicFeatureIndex() = default; -void DynamicFeatureIndex::query(std::unordered_map>& result, - const mbgl::ScreenLineString& queryGeometry, - const TransformState& state) const { +void DynamicFeatureIndex::query( + std::unordered_map>& result, + const mbgl::ScreenLineString& queryGeometry, + const TransformState& state +) const { if (features.empty()) return; mbgl::GeometryBBox queryBox = DefaultWithinBBox; for (const auto& p : queryGeometry) { @@ -236,8 +287,9 @@ void DynamicFeatureIndex::query(std::unordered_map feature, - std::shared_ptr> envelope) { +void DynamicFeatureIndex::insert( + std::shared_ptr feature, std::shared_ptr> envelope +) { features.push_back({std::move(feature), std::move(envelope)}); } diff --git a/src/mbgl/geometry/feature_index.hpp b/src/mbgl/geometry/feature_index.hpp index 7f1976910b9..049f102886f 100644 --- a/src/mbgl/geometry/feature_index.hpp +++ b/src/mbgl/geometry/feature_index.hpp @@ -25,23 +25,20 @@ class IndexedSubfeature { public: IndexedSubfeature() = delete; IndexedSubfeature(std::size_t index_, std::string sourceLayerName_, std::string bucketName_, size_t sortIndex_) - : index(index_) - , sourceLayerName(std::move(sourceLayerName_)) - , bucketLeaderID(std::move(bucketName_)) - , sortIndex(sortIndex_) - , bucketInstanceId(0) - , collisionGroupId(0) - {} - - + : index(index_), + sourceLayerName(std::move(sourceLayerName_)), + bucketLeaderID(std::move(bucketName_)), + sortIndex(sortIndex_), + bucketInstanceId(0), + collisionGroupId(0) {} + IndexedSubfeature(const IndexedSubfeature& other, uint32_t bucketInstanceId_, uint16_t collisionGroupId_) - : index(other.index) - , sourceLayerName(other.sourceLayerName) - , bucketLeaderID(other.bucketLeaderID) - , sortIndex(other.sortIndex) - , bucketInstanceId(bucketInstanceId_) - , collisionGroupId(collisionGroupId_) - {} + : index(other.index), + sourceLayerName(other.sourceLayerName), + bucketLeaderID(other.bucketLeaderID), + sortIndex(other.sortIndex), + bucketInstanceId(bucketInstanceId_), + collisionGroupId(collisionGroupId_) {} size_t index; std::string sourceLayerName; std::string bucketLeaderID; @@ -57,9 +54,11 @@ using FeatureSortOrder = std::shared_ptr>; class DynamicFeatureIndex { public: ~DynamicFeatureIndex(); - void query(std::unordered_map>& result, - const mbgl::ScreenLineString& queryGeometry, - const TransformState& state) const; + void query( + std::unordered_map>& result, + const mbgl::ScreenLineString& queryGeometry, + const TransformState& state + ) const; void insert(std::shared_ptr feature, std::shared_ptr> envelope); @@ -77,26 +76,35 @@ class FeatureIndex { FeatureIndex(std::unique_ptr tileData_); const GeometryTileData* getData() { return tileData.get(); } - - void insert(const GeometryCollection&, std::size_t index, const std::string& sourceLayerName, const std::string& bucketLeaderID); - - void query(std::unordered_map>& result, - const GeometryCoordinates& queryGeometry, - const TransformState&, - const mat4& posMatrix, - double tileSize, - double scale, - const RenderedQueryOptions& options, - const UnwrappedTileID&, - const std::unordered_map&, - float additionalQueryPadding, - const SourceFeatureState& sourceFeatureState) const; - - static std::optional translateQueryGeometry(const GeometryCoordinates& queryGeometry, - const std::array& translate, - style::TranslateAnchorType, - float bearing, - float pixelsToTileUnits); + + void insert( + const GeometryCollection&, + std::size_t index, + const std::string& sourceLayerName, + const std::string& bucketLeaderID + ); + + void query( + std::unordered_map>& result, + const GeometryCoordinates& queryGeometry, + const TransformState&, + const mat4& posMatrix, + double tileSize, + double scale, + const RenderedQueryOptions& options, + const UnwrappedTileID&, + const std::unordered_map&, + float additionalQueryPadding, + const SourceFeatureState& sourceFeatureState + ) const; + + static std::optional translateQueryGeometry( + const GeometryCoordinates& queryGeometry, + const std::array& translate, + style::TranslateAnchorType, + float bearing, + float pixelsToTileUnits + ); void setBucketLayerIDs(const std::string& bucketLeaderID, const std::vector& layerIDs); @@ -105,19 +113,22 @@ class FeatureIndex { const RenderedQueryOptions& options, const std::unordered_map& layers, const OverscaledTileID& tileID, - const FeatureSortOrder& featureSortOrder) const; + const FeatureSortOrder& featureSortOrder + ) const; private: - void addFeature(std::unordered_map>& result, - const IndexedSubfeature&, - const RenderedQueryOptions& options, - const CanonicalTileID&, - const std::unordered_map&, - const GeometryCoordinates& queryGeometry, - const TransformState& transformState, - float pixelsToTileUnits, - const mat4& posMatrix, - const SourceFeatureState* sourceFeatureState) const; + void addFeature( + std::unordered_map>& result, + const IndexedSubfeature&, + const RenderedQueryOptions& options, + const CanonicalTileID&, + const std::unordered_map&, + const GeometryCoordinates& queryGeometry, + const TransformState& transformState, + float pixelsToTileUnits, + const mat4& posMatrix, + const SourceFeatureState* sourceFeatureState + ) const; GridIndex grid; unsigned int sortIndex = 0; diff --git a/src/mbgl/geometry/line_atlas.cpp b/src/mbgl/geometry/line_atlas.cpp index 2042195b6c2..a86447ad253 100644 --- a/src/mbgl/geometry/line_atlas.cpp +++ b/src/mbgl/geometry/line_atlas.cpp @@ -11,8 +11,8 @@ namespace mbgl { namespace { size_t getDashPatternHash(const std::vector& dasharray, const LinePatternCap patternCap) { - size_t key = - patternCap == LinePatternCap::Round ? std::numeric_limits::min() : std::numeric_limits::max(); + size_t key = patternCap == LinePatternCap::Round ? std::numeric_limits::min() + : std::numeric_limits::max(); for (const float part : dasharray) { util::hash_combine(key, part); } @@ -48,7 +48,8 @@ std::vector getDashRanges(const std::vector& dasharray, float } void addRoundDash( - const std::vector& ranges, uint32_t yOffset, float stretch, const int n, AlphaImage& image) { + const std::vector& ranges, uint32_t yOffset, float stretch, const int n, AlphaImage& image +) { const float halfStretch = stretch * 0.5f; if (ranges.empty()) return; @@ -136,10 +137,9 @@ void addRegularDash(std::vector& ranges, uint32_t yOffset, AlphaImage } } -LinePatternPos addDashPattern(AlphaImage& image, - uint32_t yOffset, - const std::vector& dasharray, - const LinePatternCap patternCap) { +LinePatternPos addDashPattern( + AlphaImage& image, uint32_t yOffset, const std::vector& dasharray, const LinePatternCap patternCap +) { const uint8_t n = patternCap == LinePatternCap::Round ? 7 : 0; if (dasharray.size() < 2) { @@ -171,9 +171,9 @@ LinePatternPos addDashPattern(AlphaImage& image, } // namespace -DashPatternTexture::DashPatternTexture(const std::vector& from_, - const std::vector& to_, - const LinePatternCap cap) { +DashPatternTexture::DashPatternTexture( + const std::vector& from_, const std::vector& to_, const LinePatternCap cap +) { const bool patternsIdentical = from_ == to_; const uint32_t patternHeight = cap == LinePatternCap::Round ? 15 : 1; const uint32_t height = (patternsIdentical ? 1 : 2) * patternHeight; @@ -211,11 +211,12 @@ void DashPatternTexture::upload(gfx::UploadPass& uploadPass) { gfx::TextureBinding DashPatternTexture::textureBinding() const { // The texture needs to have been uploaded already. assert(texture.is()); - return {texture.get().getResource(), - gfx::TextureFilterType::Linear, - gfx::TextureMipMapType::No, - gfx::TextureWrapType::Repeat, - gfx::TextureWrapType::Clamp}; + return { + texture.get().getResource(), + gfx::TextureFilterType::Linear, + gfx::TextureMipMapType::No, + gfx::TextureWrapType::Repeat, + gfx::TextureWrapType::Clamp}; } Size DashPatternTexture::getSize() const { @@ -226,16 +227,17 @@ LineAtlas::LineAtlas() = default; LineAtlas::~LineAtlas() = default; -DashPatternTexture& LineAtlas::getDashPatternTexture(const std::vector& from, - const std::vector& to, - const LinePatternCap cap) { +DashPatternTexture& LineAtlas::getDashPatternTexture( + const std::vector& from, const std::vector& to, const LinePatternCap cap +) { const size_t hash = util::hash(getDashPatternHash(from, cap), getDashPatternHash(to, cap)); // Note: We're not handling hash collisions here. const auto it = textures.find(hash); if (it == textures.end()) { auto inserted = textures.emplace( - std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(from, to, cap)); + std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(from, to, cap) + ); assert(inserted.second); needsUpload.emplace_back(hash); return inserted.first->second; diff --git a/src/mbgl/geometry/line_atlas.hpp b/src/mbgl/geometry/line_atlas.hpp index 942e1a84b1a..c630c0bd798 100644 --- a/src/mbgl/geometry/line_atlas.hpp +++ b/src/mbgl/geometry/line_atlas.hpp @@ -62,9 +62,9 @@ class LineAtlas { ~LineAtlas(); // Obtains or creates a texture that has both line patterns in it - DashPatternTexture& getDashPatternTexture(const std::vector& from, - const std::vector& to, - LinePatternCap); + DashPatternTexture& getDashPatternTexture( + const std::vector& from, const std::vector& to, LinePatternCap + ); // Uploads the textures to the GPU to be available when we need it. void upload(gfx::UploadPass&); diff --git a/src/mbgl/gfx/attribute.cpp b/src/mbgl/gfx/attribute.cpp index a96bd7593d1..74b851d39d6 100644 --- a/src/mbgl/gfx/attribute.cpp +++ b/src/mbgl/gfx/attribute.cpp @@ -6,7 +6,9 @@ namespace mbgl { namespace gfx { -std::optional offsetAttributeBinding(const std::optional& binding, std::size_t vertexOffset) { +std::optional offsetAttributeBinding( + const std::optional& binding, std::size_t vertexOffset +) { assert(vertexOffset <= std::numeric_limits::max()); if (binding) { AttributeBinding result = *binding; diff --git a/src/mbgl/gfx/attribute.hpp b/src/mbgl/gfx/attribute.hpp index 1707e13dcb0..3f7462dee7e 100644 --- a/src/mbgl/gfx/attribute.hpp +++ b/src/mbgl/gfx/attribute.hpp @@ -11,12 +11,10 @@ #include #include -#define MBGL_DEFINE_ATTRIBUTE(type_, n_, name_) \ - struct name_ { \ - using Type = ::mbgl::gfx::AttributeType; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_ATTRIBUTE(type_, n_, name_) \ + struct name_ { \ + using Type = ::mbgl::gfx::AttributeType; \ + static constexpr auto name() { return #name_; } \ } #if defined(_MSC_VER) && !defined(__clang__) @@ -28,35 +26,64 @@ namespace mbgl { namespace gfx { -template struct AttributeDataTypeOf; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; +template +struct AttributeDataTypeOf; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; template class AttributeType { @@ -90,15 +117,11 @@ class AttributeBinding { uint32_t vertexOffset; friend bool operator==(const AttributeBinding& lhs, const AttributeBinding& rhs) { - return lhs.attribute == rhs.attribute && - lhs.vertexStride == rhs.vertexStride && - lhs.vertexBufferResource == rhs.vertexBufferResource && - lhs.vertexOffset == rhs.vertexOffset; + return lhs.attribute == rhs.attribute && lhs.vertexStride == rhs.vertexStride && + lhs.vertexBufferResource == rhs.vertexBufferResource && lhs.vertexOffset == rhs.vertexOffset; } - bool operator!=(const AttributeBinding& rhs) const { - return !(*this == rhs); - } + bool operator!=(const AttributeBinding& rhs) const { return !(*this == rhs); } }; // Attribute binding requires member offsets. The only standard way to @@ -161,9 +184,12 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 1, { - { A1::DataType, offsetof(Type, a1) }, - }}; + static constexpr const VertexDescriptor data = { + sizeof(Type), + 1, + { + {A1::DataType, offsetof(Type, a1)}, + }}; }; template @@ -174,10 +200,13 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 2, { - { A1::DataType, offsetof(Type, a1) }, - { A2::DataType, offsetof(Type, a2) }, - }}; + static constexpr const VertexDescriptor data = { + sizeof(Type), + 2, + { + {A1::DataType, offsetof(Type, a1)}, + {A2::DataType, offsetof(Type, a2)}, + }}; }; template @@ -188,11 +217,14 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 3, { - { A1::DataType, offsetof(Type, a1) }, - { A2::DataType, offsetof(Type, a2) }, - { A3::DataType, offsetof(Type, a3) }, - }}; + static constexpr const VertexDescriptor data = { + sizeof(Type), + 3, + { + {A1::DataType, offsetof(Type, a1)}, + {A2::DataType, offsetof(Type, a2)}, + {A3::DataType, offsetof(Type, a3)}, + }}; }; template @@ -203,12 +235,15 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 4, { - { A1::DataType, offsetof(Type, a1) }, - { A2::DataType, offsetof(Type, a2) }, - { A3::DataType, offsetof(Type, a3) }, - { A4::DataType, offsetof(Type, a4) }, - }}; + static constexpr const VertexDescriptor data = { + sizeof(Type), + 4, + { + {A1::DataType, offsetof(Type, a1)}, + {A2::DataType, offsetof(Type, a2)}, + {A3::DataType, offsetof(Type, a3)}, + {A4::DataType, offsetof(Type, a4)}, + }}; }; template @@ -219,13 +254,16 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 5, { - { A1::DataType, offsetof(Type, a1) }, - { A2::DataType, offsetof(Type, a2) }, - { A3::DataType, offsetof(Type, a3) }, - { A4::DataType, offsetof(Type, a4) }, - { A5::DataType, offsetof(Type, a5) }, - }}; + static constexpr const VertexDescriptor data = { + sizeof(Type), + 5, + { + {A1::DataType, offsetof(Type, a1)}, + {A2::DataType, offsetof(Type, a2)}, + {A3::DataType, offsetof(Type, a3)}, + {A4::DataType, offsetof(Type, a4)}, + {A5::DataType, offsetof(Type, a5)}, + }}; }; template @@ -259,34 +297,33 @@ AttributeBinding attributeBinding(const VertexBuffer>& }; } -std::optional offsetAttributeBinding(const std::optional& binding, std::size_t vertexOffset); +std::optional offsetAttributeBinding( + const std::optional& binding, std::size_t vertexOffset +); template class AttributeBindings; template class AttributeBindings> final - : public IndexedTuple, - TypeList>...>> { - using Base = IndexedTuple, - TypeList>...>>; + : public IndexedTuple, TypeList>...>> { + using Base = IndexedTuple, TypeList>...>>; public: AttributeBindings(const VertexBuffer>>& buffer) - : Base{ attributeBinding::value>(buffer)... } { - } + : Base{attributeBinding::value>(buffer)...} {} template - AttributeBindings(Args&&... args) : Base(std::forward(args)...) { - } + AttributeBindings(Args&&... args) + : Base(std::forward(args)...) {} AttributeBindings offset(const std::size_t vertexOffset) const { - return { offsetAttributeBinding(Base::template get(), vertexOffset)... }; + return {offsetAttributeBinding(Base::template get(), vertexOffset)...}; } uint32_t activeCount() const { uint32_t result = 0; - util::ignore({ ((result += bool(Base::template get())), 0)... }); + util::ignore({((result += bool(Base::template get())), 0)...}); return result; } }; diff --git a/src/mbgl/gfx/color_mode.hpp b/src/mbgl/gfx/color_mode.hpp index 077c7771bd3..578a681a27c 100644 --- a/src/mbgl/gfx/color_mode.hpp +++ b/src/mbgl/gfx/color_mode.hpp @@ -29,15 +29,11 @@ class ColorMode { static constexpr ColorBlendFactorType dstFactor = ColorBlendFactorType::Zero; }; - using Add = LinearBlend; - using Subtract = LinearBlend; - using ReverseSubtract = LinearBlend; + using Add = LinearBlend; + using Subtract = LinearBlend; + using ReverseSubtract = LinearBlend; - using BlendFunction = variant< - Replace, - Add, - Subtract, - ReverseSubtract>; + using BlendFunction = variant; BlendFunction blendFunction; Color blendColor; @@ -51,20 +47,16 @@ class ColorMode { Mask mask; - static ColorMode disabled() { - return { Replace{}, {}, { false, false, false, false } }; - } + static ColorMode disabled() { return {Replace{}, {}, {false, false, false, false}}; } - static ColorMode unblended() { - return { Replace{}, {}, { true, true, true, true } }; - } + static ColorMode unblended() { return {Replace{}, {}, {true, true, true, true}}; } static ColorMode alphaBlended() { - return { Add{ ColorBlendFactorType::One, ColorBlendFactorType::OneMinusSrcAlpha }, {}, { true, true, true, true } }; + return {Add{ColorBlendFactorType::One, ColorBlendFactorType::OneMinusSrcAlpha}, {}, {true, true, true, true}}; } static ColorMode additive() { - return { Add{ ColorBlendFactorType::One, ColorBlendFactorType::One }, {}, { true, true, true, true } }; + return {Add{ColorBlendFactorType::One, ColorBlendFactorType::One}, {}, {true, true, true, true}}; } }; diff --git a/src/mbgl/gfx/command_encoder.hpp b/src/mbgl/gfx/command_encoder.hpp index 5692615643c..617a20b3fe6 100644 --- a/src/mbgl/gfx/command_encoder.hpp +++ b/src/mbgl/gfx/command_encoder.hpp @@ -25,9 +25,7 @@ class CommandEncoder { CommandEncoder(const CommandEncoder&) = delete; CommandEncoder& operator=(const CommandEncoder&) = delete; - DebugGroup createDebugGroup(const char* name) { - return { *this, name }; - } + DebugGroup createDebugGroup(const char* name) { return {*this, name}; } virtual std::unique_ptr createUploadPass(const char* name) = 0; virtual std::unique_ptr createRenderPass(const char* name, const RenderPassDescriptor&) = 0; diff --git a/src/mbgl/gfx/context.hpp b/src/mbgl/gfx/context.hpp index 3062ab2c6b4..8cf624d7e4b 100644 --- a/src/mbgl/gfx/context.hpp +++ b/src/mbgl/gfx/context.hpp @@ -20,8 +20,7 @@ class OffscreenTexture; class Context { protected: Context(uint32_t maximumVertexBindingCount_) - : maximumVertexBindingCount(maximumVertexBindingCount_) { - } + : maximumVertexBindingCount(maximumVertexBindingCount_) {} public: static constexpr const uint32_t minimumRequiredVertexBindingCount = 8; @@ -46,31 +45,28 @@ class Context { public: // Creates an empty texture with the specified dimensions. - Texture createTexture(const Size size, - TexturePixelType format = TexturePixelType::RGBA, - TextureChannelDataType type = TextureChannelDataType::UnsignedByte) { - return { size, createTextureResource(size, format, type) }; + Texture createTexture( + const Size size, + TexturePixelType format = TexturePixelType::RGBA, + TextureChannelDataType type = TextureChannelDataType::UnsignedByte + ) { + return {size, createTextureResource(size, format, type)}; } protected: - virtual std::unique_ptr - createTextureResource(Size, TexturePixelType, TextureChannelDataType) = 0; + virtual std::unique_ptr createTextureResource(Size, TexturePixelType, TextureChannelDataType) = 0; public: template - Renderbuffer - createRenderbuffer(const Size size) { - return { size, createRenderbufferResource(pixelType, size) }; + Renderbuffer createRenderbuffer(const Size size) { + return {size, createRenderbufferResource(pixelType, size)}; } protected: - virtual std::unique_ptr - createRenderbufferResource(RenderbufferPixelType, Size) = 0; + virtual std::unique_ptr createRenderbufferResource(RenderbufferPixelType, Size) = 0; public: - DrawScope createDrawScope() { - return DrawScope{ createDrawScopeResource() }; - } + DrawScope createDrawScope() { return DrawScope{createDrawScopeResource()}; } protected: virtual std::unique_ptr createDrawScopeResource() = 0; diff --git a/src/mbgl/gfx/cull_face_mode.hpp b/src/mbgl/gfx/cull_face_mode.hpp index 42920ee02ab..f71a66225d3 100644 --- a/src/mbgl/gfx/cull_face_mode.hpp +++ b/src/mbgl/gfx/cull_face_mode.hpp @@ -11,13 +11,9 @@ class CullFaceMode { CullFaceSideType side; CullFaceWindingType winding; - static CullFaceMode disabled() { - return { false, CullFaceSideType::Back, CullFaceWindingType::CounterClockwise }; - } + static CullFaceMode disabled() { return {false, CullFaceSideType::Back, CullFaceWindingType::CounterClockwise}; } - static CullFaceMode backCCW() { - return { true, CullFaceSideType::Back, CullFaceWindingType::CounterClockwise }; - } + static CullFaceMode backCCW() { return {true, CullFaceSideType::Back, CullFaceWindingType::CounterClockwise}; } }; } // namespace gfx diff --git a/src/mbgl/gfx/debug_group.hpp b/src/mbgl/gfx/debug_group.hpp index e5e3630b4c1..c3265879821 100644 --- a/src/mbgl/gfx/debug_group.hpp +++ b/src/mbgl/gfx/debug_group.hpp @@ -6,11 +6,15 @@ namespace gfx { template class DebugGroup { public: - DebugGroup(T& scope_, const char* name) : scope(&scope_) { + DebugGroup(T& scope_, const char* name) + : scope(&scope_) { scope->pushDebugGroup(name); } - DebugGroup(DebugGroup&& rhs) noexcept : scope(rhs.scope) { rhs.scope = nullptr; } + DebugGroup(DebugGroup&& rhs) noexcept + : scope(rhs.scope) { + rhs.scope = nullptr; + } ~DebugGroup() { if (scope) { diff --git a/src/mbgl/gfx/depth_mode.hpp b/src/mbgl/gfx/depth_mode.hpp index 93a13be091e..4548240c999 100644 --- a/src/mbgl/gfx/depth_mode.hpp +++ b/src/mbgl/gfx/depth_mode.hpp @@ -12,9 +12,7 @@ class DepthMode { DepthMaskType mask; Range range; - static DepthMode disabled() { - return DepthMode { DepthFunctionType::Always, DepthMaskType::ReadOnly, { 0.0, 1.0 } }; - } + static DepthMode disabled() { return DepthMode{DepthFunctionType::Always, DepthMaskType::ReadOnly, {0.0, 1.0}}; } }; } // namespace gfx diff --git a/src/mbgl/gfx/draw_mode.hpp b/src/mbgl/gfx/draw_mode.hpp index e18a38903e5..850821105d3 100644 --- a/src/mbgl/gfx/draw_mode.hpp +++ b/src/mbgl/gfx/draw_mode.hpp @@ -10,68 +10,83 @@ namespace gfx { class DrawMode { protected: DrawMode(DrawModeType type_, float size_) - : type(type_), size(size_) { - } + : type(type_), + size(size_) {} public: const DrawModeType type; const float size; }; -template struct BufferGroupSizeOf; -template struct PrimitiveTypeOf; +template +struct BufferGroupSizeOf; +template +struct PrimitiveTypeOf; class Points : public DrawMode { public: - explicit Points(float pointSize_) : DrawMode(DrawModeType::Points, pointSize_) { + explicit Points(float pointSize_) + : DrawMode(DrawModeType::Points, pointSize_) { assert(size > 0); } }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; class Lines : public DrawMode { public: - explicit Lines(float lineWidth_) : DrawMode(DrawModeType::Lines, lineWidth_) { + explicit Lines(float lineWidth_) + : DrawMode(DrawModeType::Lines, lineWidth_) { assert(size > 0); } }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; // LineStrip is a form of "Line" rendering, but the element buffer // cannot be grouped into logical elements beyond a single Point. class LineStrip : public DrawMode { public: - explicit LineStrip(float lineWidth_) : DrawMode(DrawModeType::LineStrip, lineWidth_) { + explicit LineStrip(float lineWidth_) + : DrawMode(DrawModeType::LineStrip, lineWidth_) { assert(size > 0); } }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; class Triangles : public DrawMode { public: - explicit Triangles() : DrawMode(DrawModeType::Triangles, 0) { - } + explicit Triangles() + : DrawMode(DrawModeType::Triangles, 0) {} }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; // TriangleStrip is a form of "Triangle" rendering, but the element buffer // cannot be grouped into logical elements beyond a single Point. class TriangleStrip : public DrawMode { public: - explicit TriangleStrip() : DrawMode(DrawModeType::TriangleStrip, 0) { - } + explicit TriangleStrip() + : DrawMode(DrawModeType::TriangleStrip, 0) {} }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; } // namespace gfx } // namespace mbgl diff --git a/src/mbgl/gfx/draw_scope.hpp b/src/mbgl/gfx/draw_scope.hpp index 5cdb588317b..009f733f40f 100644 --- a/src/mbgl/gfx/draw_scope.hpp +++ b/src/mbgl/gfx/draw_scope.hpp @@ -9,14 +9,15 @@ namespace gfx { class DrawScopeResource { protected: DrawScopeResource() = default; + public: virtual ~DrawScopeResource() = default; }; class DrawScope { public: - explicit DrawScope(std::unique_ptr resource_) : resource(std::move(resource_)) { - } + explicit DrawScope(std::unique_ptr resource_) + : resource(std::move(resource_)) {} template T& getResource() const { diff --git a/src/mbgl/gfx/index_buffer.hpp b/src/mbgl/gfx/index_buffer.hpp index 60f361b497e..27efc67cbfc 100644 --- a/src/mbgl/gfx/index_buffer.hpp +++ b/src/mbgl/gfx/index_buffer.hpp @@ -9,6 +9,7 @@ namespace gfx { class IndexBufferResource { protected: IndexBufferResource() = default; + public: virtual ~IndexBufferResource() = default; }; @@ -16,8 +17,8 @@ class IndexBufferResource { class IndexBuffer { public: IndexBuffer(const std::size_t elements_, std::unique_ptr&& resource_) - : elements(elements_), resource(std::move(resource_)) { - } + : elements(elements_), + resource(std::move(resource_)) {} std::size_t elements; diff --git a/src/mbgl/gfx/index_vector.hpp b/src/mbgl/gfx/index_vector.hpp index 826d43bee3a..db922b12dd0 100644 --- a/src/mbgl/gfx/index_vector.hpp +++ b/src/mbgl/gfx/index_vector.hpp @@ -16,32 +16,20 @@ class IndexVector { template void emplace_back(Args&&... args) { static_assert(sizeof...(args) == groupSize, "wrong buffer element count"); - util::ignore({ (v.emplace_back(std::forward(args)), 0)... }); + util::ignore({(v.emplace_back(std::forward(args)), 0)...}); } - std::size_t elements() const { - return v.size(); - } + std::size_t elements() const { return v.size(); } - std::size_t bytes() const { - return v.size() * sizeof(uint16_t); - } + std::size_t bytes() const { return v.size() * sizeof(uint16_t); } - bool empty() const { - return v.empty(); - } + bool empty() const { return v.empty(); } - void clear() { - v.clear(); - } + void clear() { v.clear(); } - const uint16_t* data() const { - return v.data(); - } + const uint16_t* data() const { return v.data(); } - const std::vector& vector() const { - return v; - } + const std::vector& vector() const { return v; } private: std::vector v; diff --git a/src/mbgl/gfx/offscreen_texture.hpp b/src/mbgl/gfx/offscreen_texture.hpp index d4bf5149fdf..7e83a51119d 100644 --- a/src/mbgl/gfx/offscreen_texture.hpp +++ b/src/mbgl/gfx/offscreen_texture.hpp @@ -11,8 +11,7 @@ class Texture; class OffscreenTexture : public gfx::Renderable { protected: OffscreenTexture(const Size size_, std::unique_ptr resource_) - : gfx::Renderable(size_, std::move(resource_)) { - } + : gfx::Renderable(size_, std::move(resource_)) {} public: ~OffscreenTexture() override = default; diff --git a/src/mbgl/gfx/program.hpp b/src/mbgl/gfx/program.hpp index b636bc26549..6e8686c8092 100644 --- a/src/mbgl/gfx/program.hpp +++ b/src/mbgl/gfx/program.hpp @@ -14,9 +14,12 @@ class CullFaceMode; class DrawScope; class IndexBuffer; class RenderPass; -template class UniformValues; -template class AttributeBindings; -template class TextureBindings; +template +class UniformValues; +template +class AttributeBindings; +template +class TextureBindings; template class Program { @@ -35,20 +38,22 @@ class Program { using UniformList = typename Name::UniformList; using TextureList = typename Name::TextureList; - virtual void draw(Context&, - RenderPass&, - const DrawMode&, - const DepthMode&, - const StencilMode&, - const ColorMode&, - const CullFaceMode&, - const UniformValues&, - DrawScope&, - const AttributeBindings&, - const TextureBindings&, - const IndexBuffer&, - std::size_t indexOffset, - std::size_t indexLength) = 0; + virtual void draw( + Context&, + RenderPass&, + const DrawMode&, + const DepthMode&, + const StencilMode&, + const ColorMode&, + const CullFaceMode&, + const UniformValues&, + DrawScope&, + const AttributeBindings&, + const TextureBindings&, + const IndexBuffer&, + std::size_t indexOffset, + std::size_t indexLength + ) = 0; }; } // namespace gfx diff --git a/src/mbgl/gfx/render_pass.hpp b/src/mbgl/gfx/render_pass.hpp index 3cc377429a8..8ceb61da767 100644 --- a/src/mbgl/gfx/render_pass.hpp +++ b/src/mbgl/gfx/render_pass.hpp @@ -32,9 +32,7 @@ class RenderPass { RenderPass(const RenderPass&) = delete; RenderPass& operator=(const RenderPass&) = delete; - DebugGroup createDebugGroup(const char* name) { - return { *this, name }; - } + DebugGroup createDebugGroup(const char* name) { return {*this, name}; } }; } // namespace gfx diff --git a/src/mbgl/gfx/renderbuffer.hpp b/src/mbgl/gfx/renderbuffer.hpp index 209b7ed3f9c..bbc0c1be685 100644 --- a/src/mbgl/gfx/renderbuffer.hpp +++ b/src/mbgl/gfx/renderbuffer.hpp @@ -21,20 +21,14 @@ template class Renderbuffer final { public: Renderbuffer(const Size size_, std::unique_ptr resource_) - : size(size_), resource(std::move(resource_)) { - } + : size(size_), + resource(std::move(resource_)) {} - void setShouldClear(bool clear) { - dirty = clear; - } + void setShouldClear(bool clear) { dirty = clear; } - bool needsClearing() const { - return dirty; - } + bool needsClearing() const { return dirty; } - const Size& getSize() const { - return size; - } + const Size& getSize() const { return size; } template T& getResource() const { diff --git a/src/mbgl/gfx/renderer_backend.cpp b/src/mbgl/gfx/renderer_backend.cpp index e6fe0c0b245..b24a66a27be 100644 --- a/src/mbgl/gfx/renderer_backend.cpp +++ b/src/mbgl/gfx/renderer_backend.cpp @@ -5,15 +5,13 @@ namespace mbgl { namespace gfx { -RendererBackend::RendererBackend(const ContextMode contextMode_) : contextMode(contextMode_) { -} +RendererBackend::RendererBackend(const ContextMode contextMode_) + : contextMode(contextMode_) {} RendererBackend::~RendererBackend() = default; gfx::Context& RendererBackend::getContext() { assert(BackendScope::exists()); - std::call_once(initialized, [this] { - context = createContext(); - }); + std::call_once(initialized, [this] { context = createContext(); }); assert(context); return *context; } diff --git a/src/mbgl/gfx/shader_registry.cpp b/src/mbgl/gfx/shader_registry.cpp index 67b1fac0b4a..87aeed6ead4 100644 --- a/src/mbgl/gfx/shader_registry.cpp +++ b/src/mbgl/gfx/shader_registry.cpp @@ -6,16 +6,12 @@ namespace gfx { ShaderRegistry::ShaderRegistry() {} -bool ShaderRegistry::isShader(const std::string& shaderName) - const noexcept -{ +bool ShaderRegistry::isShader(const std::string& shaderName) const noexcept { std::shared_lock readerLock(programLock); return programs.find(shaderName) != programs.end(); } -const std::shared_ptr ShaderRegistry::getShader(const std::string& shaderName) - const noexcept -{ +const std::shared_ptr ShaderRegistry::getShader(const std::string& shaderName) const noexcept { std::shared_lock readerLock(programLock); const auto it = programs.find(shaderName); if (it == programs.end()) { @@ -25,15 +21,11 @@ const std::shared_ptr ShaderRegistry::getShader(const std::string& return it->second; } -bool ShaderRegistry::replaceShader( - std::shared_ptr&& shader) noexcept -{ +bool ShaderRegistry::replaceShader(std::shared_ptr&& shader) noexcept { return replaceShader(std::move(shader), std::string{shader->typeName()}); } -bool ShaderRegistry::replaceShader(std::shared_ptr&& shader, - const std::string& shaderName) noexcept -{ +bool ShaderRegistry::replaceShader(std::shared_ptr&& shader, const std::string& shaderName) noexcept { std::unique_lock writerLock(programLock); if (programs.find(shaderName) == programs.end()) { return false; @@ -43,15 +35,11 @@ bool ShaderRegistry::replaceShader(std::shared_ptr&& shader, return true; } -bool ShaderRegistry::registerShader( - std::shared_ptr&& shader) noexcept -{ +bool ShaderRegistry::registerShader(std::shared_ptr&& shader) noexcept { return registerShader(std::move(shader), std::string{shader->typeName()}); } -bool ShaderRegistry::registerShader(std::shared_ptr&& shader, - const std::string& shaderName) noexcept -{ +bool ShaderRegistry::registerShader(std::shared_ptr&& shader, const std::string& shaderName) noexcept { std::unique_lock writerLock(programLock); if (programs.find(shaderName) != programs.end()) { return false; @@ -61,5 +49,5 @@ bool ShaderRegistry::registerShader(std::shared_ptr&& shader, return true; } -} // namespace gl +} // namespace gfx } // namespace mbgl diff --git a/src/mbgl/gfx/stencil_mode.hpp b/src/mbgl/gfx/stencil_mode.hpp index aec403b59bf..0ccf21faee6 100644 --- a/src/mbgl/gfx/stencil_mode.hpp +++ b/src/mbgl/gfx/stencil_mode.hpp @@ -20,24 +20,16 @@ class StencilMode { uint32_t mask; }; - using Never = SimpleTest; - using Less = MaskedTest; - using Equal = MaskedTest; - using LessEqual = MaskedTest; - using Greater = MaskedTest; - using NotEqual = MaskedTest; + using Never = SimpleTest; + using Less = MaskedTest; + using Equal = MaskedTest; + using LessEqual = MaskedTest; + using Greater = MaskedTest; + using NotEqual = MaskedTest; using GreaterEqual = MaskedTest; - using Always = SimpleTest; + using Always = SimpleTest; - using Test = variant< - Never, - Less, - Equal, - LessEqual, - Greater, - NotEqual, - GreaterEqual, - Always>; + using Test = variant; Test test; int32_t ref; @@ -48,7 +40,7 @@ class StencilMode { StencilOpType pass; static StencilMode disabled() { - return StencilMode { Always(), 0, 0, StencilOpType::Keep, StencilOpType::Keep, StencilOpType::Keep }; + return StencilMode{Always(), 0, 0, StencilOpType::Keep, StencilOpType::Keep, StencilOpType::Keep}; } }; diff --git a/src/mbgl/gfx/texture.hpp b/src/mbgl/gfx/texture.hpp index 00e94a8f6c6..29f0b6b97a2 100644 --- a/src/mbgl/gfx/texture.hpp +++ b/src/mbgl/gfx/texture.hpp @@ -8,12 +8,10 @@ #include #include -#define MBGL_DEFINE_TEXTURE(name_) \ - struct name_ { \ - using Value = ::mbgl::gfx::TextureBinding; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_TEXTURE(name_) \ + struct name_ { \ + using Value = ::mbgl::gfx::TextureBinding; \ + static constexpr auto name() { return #name_; } \ } namespace mbgl { @@ -22,6 +20,7 @@ namespace gfx { class TextureResource { protected: TextureResource() = default; + public: virtual ~TextureResource() = default; }; @@ -29,8 +28,8 @@ class TextureResource { class Texture { public: Texture(const Size size_, std::unique_ptr&& resource_) - : size(size_), resource(std::move(resource_)) { - } + : size(size_), + resource(std::move(resource_)) {} template T& getResource() const { @@ -46,13 +45,18 @@ class Texture { class TextureBinding { public: - TextureBinding(TextureResource& resource_, - TextureFilterType filter_ = TextureFilterType::Nearest, - TextureMipMapType mipmap_ = TextureMipMapType::No, - TextureWrapType wrapX_ = TextureWrapType::Clamp, - TextureWrapType wrapY_ = TextureWrapType::Clamp) - : resource(&resource_), filter(filter_), mipmap(mipmap_), wrapX(wrapX_), wrapY(wrapY_) { - } + TextureBinding( + TextureResource& resource_, + TextureFilterType filter_ = TextureFilterType::Nearest, + TextureMipMapType mipmap_ = TextureMipMapType::No, + TextureWrapType wrapX_ = TextureWrapType::Clamp, + TextureWrapType wrapY_ = TextureWrapType::Clamp + ) + : resource(&resource_), + filter(filter_), + mipmap(mipmap_), + wrapX(wrapX_), + wrapY(wrapY_) {} TextureResource* resource; TextureFilterType filter; @@ -71,8 +75,8 @@ class TextureBindings> final public: template - TextureBindings(Args&&... args) : Base(std::forward(args)...) { - } + TextureBindings(Args&&... args) + : Base(std::forward(args)...) {} }; } // namespace gfx diff --git a/src/mbgl/gfx/uniform.hpp b/src/mbgl/gfx/uniform.hpp index f6896b91387..c69d6f0141d 100644 --- a/src/mbgl/gfx/uniform.hpp +++ b/src/mbgl/gfx/uniform.hpp @@ -5,28 +5,22 @@ #include -#define MBGL_DEFINE_UNIFORM_SCALAR(type_, name_) \ - struct name_ { \ - using Value = type_; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_UNIFORM_SCALAR(type_, name_) \ + struct name_ { \ + using Value = type_; \ + static constexpr auto name() { return #name_; } \ } -#define MBGL_DEFINE_UNIFORM_VECTOR(type_, n_, name_) \ - struct name_ { \ - using Value = std::array; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_UNIFORM_VECTOR(type_, n_, name_) \ + struct name_ { \ + using Value = std::array; \ + static constexpr auto name() { return #name_; } \ } -#define MBGL_DEFINE_UNIFORM_MATRIX(type_, n_, name_) \ - struct name_ { \ - using Value = std::array; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_UNIFORM_MATRIX(type_, n_, name_) \ + struct name_ { \ + using Value = std::array; \ + static constexpr auto name() { return #name_; } \ } namespace mbgl { @@ -36,14 +30,13 @@ template class UniformValues; template -class UniformValues> final - : public IndexedTuple, TypeList> { +class UniformValues> final : public IndexedTuple, TypeList> { using Base = IndexedTuple, TypeList>; public: template - UniformValues(Args&&... args) : Base(std::forward(args)...) { - } + UniformValues(Args&&... args) + : Base(std::forward(args)...) {} }; } // namespace gfx diff --git a/src/mbgl/gfx/upload_pass.hpp b/src/mbgl/gfx/upload_pass.hpp index 4324cb57738..bb74bc9d805 100644 --- a/src/mbgl/gfx/upload_pass.hpp +++ b/src/mbgl/gfx/upload_pass.hpp @@ -24,16 +24,14 @@ class UploadPass { UploadPass(const UploadPass&) = delete; UploadPass& operator=(const UploadPass&) = delete; - DebugGroup createDebugGroup(const char* name) { - return { *this, name }; - } + DebugGroup createDebugGroup(const char* name) { return {*this, name}; } public: template - VertexBuffer - createVertexBuffer(VertexVector&& v, - const BufferUsageType usage = BufferUsageType::StaticDraw) { - return { v.elements(), createVertexBufferResource(v.data(), v.bytes(), usage) }; + VertexBuffer createVertexBuffer( + VertexVector&& v, const BufferUsageType usage = BufferUsageType::StaticDraw + ) { + return {v.elements(), createVertexBufferResource(v.data(), v.bytes(), usage)}; } template @@ -43,9 +41,10 @@ class UploadPass { } template - IndexBuffer createIndexBuffer(IndexVector&& v, - const BufferUsageType usage = BufferUsageType::StaticDraw) { - return { v.elements(), createIndexBufferResource(v.data(), v.bytes(), usage) }; + IndexBuffer createIndexBuffer( + IndexVector&& v, const BufferUsageType usage = BufferUsageType::StaticDraw + ) { + return {v.elements(), createIndexBufferResource(v.data(), v.bytes(), usage)}; } template @@ -55,43 +54,41 @@ class UploadPass { } protected: - virtual std::unique_ptr createVertexBufferResource(const void* data, - std::size_t size, - BufferUsageType) = 0; - virtual void - updateVertexBufferResource(VertexBufferResource&, const void* data, std::size_t size) = 0; - - virtual std::unique_ptr createIndexBufferResource(const void* data, - std::size_t size, - BufferUsageType) = 0; - virtual void - updateIndexBufferResource(IndexBufferResource&, const void* data, std::size_t size) = 0; + virtual std::unique_ptr createVertexBufferResource( + const void* data, std::size_t size, BufferUsageType + ) = 0; + virtual void updateVertexBufferResource(VertexBufferResource&, const void* data, std::size_t size) = 0; + + virtual std::unique_ptr createIndexBufferResource( + const void* data, std::size_t size, BufferUsageType + ) = 0; + virtual void updateIndexBufferResource(IndexBufferResource&, const void* data, std::size_t size) = 0; public: // Create a texture from an image with data. template - Texture createTexture(const Image& image, - TextureChannelDataType type = TextureChannelDataType::UnsignedByte) { + Texture createTexture(const Image& image, TextureChannelDataType type = TextureChannelDataType::UnsignedByte) { auto format = image.channels == 4 ? TexturePixelType::RGBA : TexturePixelType::Alpha; - return { image.size, - createTextureResource(image.size, image.data.get(), format, type) }; + return {image.size, createTextureResource(image.size, image.data.get(), format, type)}; } template - void updateTexture(Texture& texture, - const Image& image, - TextureChannelDataType type = TextureChannelDataType::UnsignedByte) { + void updateTexture( + Texture& texture, const Image& image, TextureChannelDataType type = TextureChannelDataType::UnsignedByte + ) { auto format = image.channels == 4 ? TexturePixelType::RGBA : TexturePixelType::Alpha; updateTextureResource(texture.getResource(), image.size, image.data.get(), format, type); texture.size = image.size; } template - void updateTextureSub(Texture& texture, - const Image& image, - const uint16_t offsetX, - const uint16_t offsetY, - TextureChannelDataType type = TextureChannelDataType::UnsignedByte) { + void updateTextureSub( + Texture& texture, + const Image& image, + const uint16_t offsetX, + const uint16_t offsetY, + TextureChannelDataType type = TextureChannelDataType::UnsignedByte + ) { assert(image.size.width + offsetX <= texture.size.width); assert(image.size.height + offsetY <= texture.size.height); auto format = image.channels == 4 ? TexturePixelType::RGBA : TexturePixelType::Alpha; @@ -100,11 +97,20 @@ class UploadPass { protected: virtual std::unique_ptr createTextureResource( - Size, const void* data, TexturePixelType, TextureChannelDataType) = 0; - virtual void updateTextureResource(TextureResource&, Size, const void* data, - TexturePixelType, TextureChannelDataType) = 0; - virtual void updateTextureResourceSub(TextureResource&, uint16_t xOffset, uint16_t yOffset, Size, const void* data, - TexturePixelType, TextureChannelDataType) = 0; + Size, const void* data, TexturePixelType, TextureChannelDataType + ) = 0; + virtual void updateTextureResource( + TextureResource&, Size, const void* data, TexturePixelType, TextureChannelDataType + ) = 0; + virtual void updateTextureResourceSub( + TextureResource&, + uint16_t xOffset, + uint16_t yOffset, + Size, + const void* data, + TexturePixelType, + TextureChannelDataType + ) = 0; }; } // namespace gfx diff --git a/src/mbgl/gfx/vertex_buffer.hpp b/src/mbgl/gfx/vertex_buffer.hpp index fe98ec65052..fdd74f5a9a3 100644 --- a/src/mbgl/gfx/vertex_buffer.hpp +++ b/src/mbgl/gfx/vertex_buffer.hpp @@ -9,6 +9,7 @@ namespace gfx { class VertexBufferResource { protected: VertexBufferResource() = default; + public: virtual ~VertexBufferResource() = default; }; @@ -19,8 +20,8 @@ template class VertexBuffer { public: VertexBuffer(const std::size_t elements_, std::unique_ptr&& resource_) - : elements(elements_), resource(std::move(resource_)) { - } + : elements(elements_), + resource(std::move(resource_)) {} std::size_t elements; diff --git a/src/mbgl/gfx/vertex_vector.hpp b/src/mbgl/gfx/vertex_vector.hpp index 091ecb912ec..fdda3c75070 100644 --- a/src/mbgl/gfx/vertex_vector.hpp +++ b/src/mbgl/gfx/vertex_vector.hpp @@ -11,43 +11,29 @@ template class VertexVector { public: using Vertex = V; - template + template void emplace_back(Arg&& vertex) { v.emplace_back(std::forward(vertex)); } - void extend(std::size_t n, const Vertex& val) { - v.resize(v.size() + n, val); - } + void extend(std::size_t n, const Vertex& val) { v.resize(v.size() + n, val); } Vertex& at(std::size_t n) { assert(n < v.size()); return v.at(n); } - std::size_t elements() const { - return v.size(); - } + std::size_t elements() const { return v.size(); } - std::size_t bytes() const { - return v.size() * sizeof(Vertex); - } + std::size_t bytes() const { return v.size() * sizeof(Vertex); } - bool empty() const { - return v.empty(); - } + bool empty() const { return v.empty(); } - void clear() { - v.clear(); - } + void clear() { v.clear(); } - const Vertex* data() const { - return v.data(); - } + const Vertex* data() const { return v.data(); } - const std::vector& vector() const { - return v; - } + const std::vector& vector() const { return v; } private: std::vector v; diff --git a/src/mbgl/gl/attribute.hpp b/src/mbgl/gl/attribute.hpp index 88836164971..2950fb79720 100644 --- a/src/mbgl/gl/attribute.hpp +++ b/src/mbgl/gl/attribute.hpp @@ -23,8 +23,7 @@ class AttributeLocations; template class AttributeLocations> final { private: - using Locations = - IndexedTuple, TypeList>...>>; + using Locations = IndexedTuple, TypeList>...>>; Locations locations; @@ -33,7 +32,7 @@ class AttributeLocations> final { void queryLocations(const ProgramID& id) { locations = Locations{ - queryLocation(id, concat_literals<&string_literal<'a', '_'>::value, &As::name>::value())... }; + queryLocation(id, concat_literals<&string_literal<'a', '_'>::value, &As::name>::value())...}; using TypeOfFirst = typename std::tuple_element_t<0, std::tuple>; [[maybe_unused]] auto first = locations.template get(); assert(first && first.value() == 0); @@ -42,23 +41,30 @@ class AttributeLocations> final { static constexpr const char* getFirstAttribName() { // Static assert that attribute list starts with position: we bind it on location 0. using TypeOfFirst = typename std::tuple_element_t<0, std::tuple>; - static_assert(std::is_same::value || std::is_same::value || - std::is_same::value, "Program must start with position related attribute."); + static_assert( + std::is_same::value || + std::is_same::value || + std::is_same::value, + "Program must start with position related attribute." + ); return concat_literals<&string_literal<'a', '_'>::value, TypeOfFirst::name>::value(); } NamedAttributeLocations getNamedLocations() const { NamedAttributeLocations result; - auto maybeAddLocation = [&] (const std::string& name, const std::optional& location) { + auto maybeAddLocation = [&](const std::string& name, const std::optional& location) { if (location) { result.emplace_back(name, *location); } }; - util::ignore({ (maybeAddLocation(concat_literals<&string_literal<'a', '_'>::value, &As::name>::value(), - locations.template get()), - 0)... }); + util::ignore( + {(maybeAddLocation( + concat_literals<&string_literal<'a', '_'>::value, &As::name>::value(), locations.template get() + ), + 0)...} + ); return result; } @@ -67,14 +73,14 @@ class AttributeLocations> final { AttributeBindingArray result; result.resize(sizeof...(As)); - auto maybeAddBinding = [&] (const std::optional& location, - const std::optional& binding) { + auto maybeAddBinding = [&](const std::optional& location, + const std::optional& binding) { if (location) { result.at(*location) = binding; } }; - util::ignore({ (maybeAddBinding(locations.template get(), bindings.template get()), 0)... }); + util::ignore({(maybeAddBinding(locations.template get(), bindings.template get()), 0)...}); return result; } @@ -94,19 +100,20 @@ class AttributeKey> final { static uint32_t compute(const gfx::AttributeBindings>& bindings) { uint32_t value = 0; - util::ignore( - { (bindings.template get() ? (void)(value |= 1 << TypeIndex::value) - : (void)0, - 0)... }); + util::ignore({(bindings.template get() ? (void)(value |= 1 << TypeIndex::value) : (void)0, 0)...} + ); return value; } static std::string defines(const gfx::AttributeBindings>& bindings) { std::string result; - util::ignore({ (!bindings.template get() - ? (void)(result += concat_literals<&attributeDefinePrefix, &As::name, &string_literal<'\n'>::value>::value()) - : (void)0, - 0)... }); + util::ignore({( + !bindings.template get() + ? (void + )(result += concat_literals<&attributeDefinePrefix, &As::name, &string_literal<'\n'>::value>::value()) + : (void)0, + 0 + )...}); return result; } }; diff --git a/src/mbgl/gl/command_encoder.cpp b/src/mbgl/gl/command_encoder.cpp index a7df14df09a..42076313dc1 100644 --- a/src/mbgl/gl/command_encoder.cpp +++ b/src/mbgl/gl/command_encoder.cpp @@ -16,13 +16,13 @@ CommandEncoder::~CommandEncoder() { context.performCleanup(); } -std::unique_ptr -CommandEncoder::createUploadPass(const char* name) { +std::unique_ptr CommandEncoder::createUploadPass(const char* name) { return std::make_unique(*this, name); } -std::unique_ptr -CommandEncoder::createRenderPass(const char* name, const gfx::RenderPassDescriptor& descriptor) { +std::unique_ptr CommandEncoder::createRenderPass( + const char* name, const gfx::RenderPassDescriptor& descriptor +) { return std::make_unique(*this, name, descriptor); } @@ -35,8 +35,9 @@ void CommandEncoder::pushDebugGroup(const char* name) { #ifndef NDEBUG if (auto debugging = context.getDebuggingExtension()) { if (debugging->pushDebugGroup) { - MBGL_CHECK_ERROR(debugging->pushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 0, - platform::GLsizei(strlen(name)), name)); + MBGL_CHECK_ERROR( + debugging->pushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 0, platform::GLsizei(strlen(name)), name) + ); } else if (debugging->pushGroupMarkerEXT) { MBGL_CHECK_ERROR(debugging->pushGroupMarkerEXT(platform::GLsizei(strlen(name) + 1), name)); } diff --git a/src/mbgl/gl/command_encoder.hpp b/src/mbgl/gl/command_encoder.hpp index f47aad49464..8c3e575453f 100644 --- a/src/mbgl/gl/command_encoder.hpp +++ b/src/mbgl/gl/command_encoder.hpp @@ -9,8 +9,8 @@ class Context; class CommandEncoder final : public gfx::CommandEncoder { public: - explicit CommandEncoder(gl::Context& context_) : context(context_) { - } + explicit CommandEncoder(gl::Context& context_) + : context(context_) {} ~CommandEncoder() override; diff --git a/src/mbgl/gl/context.cpp b/src/mbgl/gl/context.cpp index 6bbb433f3d4..01ebe8ea85a 100644 --- a/src/mbgl/gl/context.cpp +++ b/src/mbgl/gl/context.cpp @@ -67,11 +67,8 @@ Context::~Context() noexcept { } void Context::initializeExtensions(const std::function& getProcAddress) { - if (const auto* extensions = - reinterpret_cast(MBGL_CHECK_ERROR(glGetString(GL_EXTENSIONS)))) { - - auto fn = [&]( - std::initializer_list> probes) -> ProcAddress { + if (const auto* extensions = reinterpret_cast(MBGL_CHECK_ERROR(glGetString(GL_EXTENSIONS)))) { + auto fn = [&](std::initializer_list> probes) -> ProcAddress { for (auto probe : probes) { if (strstr(extensions, probe.first) != nullptr) { if (ProcAddress ptr = getProcAddress(probe.second)) { @@ -89,8 +86,7 @@ void Context::initializeExtensions(const std::function(fn); } } @@ -105,15 +101,21 @@ void Context::enableDebugging() { // MBGL_CHECK_ERROR(debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE)); // This will only enable high and medium severity messages - MBGL_CHECK_ERROR(debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, GL_TRUE)); - MBGL_CHECK_ERROR(debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, nullptr, GL_TRUE)); - MBGL_CHECK_ERROR(debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE)); + MBGL_CHECK_ERROR( + debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, GL_TRUE) + ); + MBGL_CHECK_ERROR( + debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, nullptr, GL_TRUE) + ); + MBGL_CHECK_ERROR( + debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE) + ); MBGL_CHECK_ERROR(debugging->debugMessageCallback(extension::Debugging::DebugCallback, nullptr)); } UniqueShader Context::createShader(ShaderType type, const std::initializer_list& sources) { - UniqueShader result { MBGL_CHECK_ERROR(glCreateShader(static_cast(type))), { this } }; + UniqueShader result{MBGL_CHECK_ERROR(glCreateShader(static_cast(type))), {this}}; MBGL_CHECK_ERROR(glShaderSource(result, static_cast(sources.size()), sources.begin(), nullptr)); MBGL_CHECK_ERROR(glCompileShader(result)); @@ -136,7 +138,7 @@ UniqueShader Context::createShader(ShaderType type, const std::initializer_list< } UniqueProgram Context::createProgram(ShaderID vertexShader, ShaderID fragmentShader, const char* location0AttribName) { - UniqueProgram result { MBGL_CHECK_ERROR(glCreateProgram()), { this } }; + UniqueProgram result{MBGL_CHECK_ERROR(glCreateProgram()), {this}}; MBGL_CHECK_ERROR(glAttachShader(result, vertexShader)); MBGL_CHECK_ERROR(glAttachShader(result, fragmentShader)); @@ -193,8 +195,8 @@ VertexArray Context::createVertexArray() { VertexArrayID id = 0; MBGL_CHECK_ERROR(glGenVertexArrays(1, &id)); // NOLINTNEXTLINE(performance-move-const-arg) - UniqueVertexArray vao(std::move(id), { this }); - return { UniqueVertexArrayState(new VertexArrayState(std::move(vao)), VertexArrayStateDeleter { true })}; + UniqueVertexArray vao(std::move(id), {this}); + return {UniqueVertexArrayState(new VertexArrayState(std::move(vao)), VertexArrayStateDeleter{true})}; } UniqueFramebuffer Context::createFramebuffer() { @@ -202,26 +204,35 @@ UniqueFramebuffer Context::createFramebuffer() { MBGL_CHECK_ERROR(glGenFramebuffers(1, &id)); stats.numFrameBuffers++; // NOLINTNEXTLINE(performance-move-const-arg) - return UniqueFramebuffer{ std::move(id), { this } }; + return UniqueFramebuffer{std::move(id), {this}}; } std::unique_ptr Context::createTextureResource( - const Size size, const gfx::TexturePixelType format, const gfx::TextureChannelDataType type) { + const Size size, const gfx::TexturePixelType format, const gfx::TextureChannelDataType type +) { auto obj = createUniqueTexture(); int textureByteSize = gl::TextureResource::getStorageSize(size, format, type); stats.memTextures += textureByteSize; - std::unique_ptr resource = - std::make_unique(std::move(obj), textureByteSize); + std::unique_ptr resource = std::make_unique( + std::move(obj), textureByteSize + ); // Always use texture unit 0 for manipulating it. activeTextureUnit = 0; texture[0] = static_cast(*resource).texture; // Creates an empty texture with the specified size and format. - MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, Enum::sizedFor(format, type), - size.width, size.height, 0, - Enum::to(format), - Enum::to(type), nullptr)); + MBGL_CHECK_ERROR(glTexImage2D( + GL_TEXTURE_2D, + 0, + Enum::sizedFor(format, type), + size.width, + size.height, + 0, + Enum::to(format), + Enum::to(type), + nullptr + )); // We are using clamp to edge here since OpenGL ES doesn't allow GL_REPEAT on NPOT textures. // We use those when the pixelRatio isn't a power of two, e.g. on iPhone 6 Plus. @@ -233,32 +244,35 @@ std::unique_ptr Context::createTextureResource( return resource; } -std::unique_ptr -Context::createRenderbufferResource(const gfx::RenderbufferPixelType type, const Size size) { +std::unique_ptr Context::createRenderbufferResource( + const gfx::RenderbufferPixelType type, const Size size +) { RenderbufferID id = 0; MBGL_CHECK_ERROR(glGenRenderbuffers(1, &id)); // NOLINTNEXTLINE(performance-move-const-arg) - UniqueRenderbuffer renderbuffer{ std::move(id), { this } }; + UniqueRenderbuffer renderbuffer{std::move(id), {this}}; bindRenderbuffer = renderbuffer; MBGL_CHECK_ERROR( - glRenderbufferStorage(GL_RENDERBUFFER, Enum::to(type), size.width, size.height)); + glRenderbufferStorage(GL_RENDERBUFFER, Enum::to(type), size.width, size.height) + ); bindRenderbuffer = 0; return std::make_unique(std::move(renderbuffer)); } - -std::unique_ptr Context::readFramebuffer(const Size size, const gfx::TexturePixelType format, const bool flip) { +std::unique_ptr Context::readFramebuffer( + const Size size, const gfx::TexturePixelType format, const bool flip +) { const size_t stride = size.width * (format == gfx::TexturePixelType::RGBA ? 4 : 1); auto data = std::make_unique(stride * size.height); // When reading data from the framebuffer, make sure that we are storing the values // tightly packed into the buffer to avoid buffer overruns. - pixelStorePack = { 1 }; + pixelStorePack = {1}; - MBGL_CHECK_ERROR(glReadPixels(0, 0, size.width, size.height, - Enum::to(format), GL_UNSIGNED_BYTE, - data.get())); + MBGL_CHECK_ERROR(glReadPixels( + 0, 0, size.width, size.height, Enum::to(format), GL_UNSIGNED_BYTE, data.get() + )); if (flip) { auto tmp = std::make_unique(stride); @@ -279,50 +293,53 @@ void checkFramebuffer() { GLenum status = MBGL_CHECK_ERROR(glCheckFramebufferStatus(GL_FRAMEBUFFER)); if (status != GL_FRAMEBUFFER_COMPLETE) { switch (status) { - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - throw std::runtime_error("Couldn't create framebuffer: incomplete attachment"); - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - throw std::runtime_error("Couldn't create framebuffer: incomplete missing attachment"); + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + throw std::runtime_error("Couldn't create framebuffer: incomplete attachment"); + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + throw std::runtime_error("Couldn't create framebuffer: incomplete missing attachment"); #ifdef GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: - throw std::runtime_error("Couldn't create framebuffer: incomplete draw buffer"); + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + throw std::runtime_error("Couldn't create framebuffer: incomplete draw buffer"); #endif #ifdef GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER - case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - throw std::runtime_error("Couldn't create framebuffer: incomplete read buffer"); + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + throw std::runtime_error("Couldn't create framebuffer: incomplete read buffer"); #endif #ifdef GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - throw std::runtime_error("Couldn't create framebuffer: incomplete dimensions"); + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + throw std::runtime_error("Couldn't create framebuffer: incomplete dimensions"); #endif - case GL_FRAMEBUFFER_UNSUPPORTED: - throw std::runtime_error("Couldn't create framebuffer: unsupported"); - default: - throw std::runtime_error("Couldn't create framebuffer: other"); + case GL_FRAMEBUFFER_UNSUPPORTED: + throw std::runtime_error("Couldn't create framebuffer: unsupported"); + default: + throw std::runtime_error("Couldn't create framebuffer: other"); } } } -void bindDepthStencilRenderbuffer( - const gfx::Renderbuffer& depthStencil) { +void bindDepthStencilRenderbuffer(const gfx::Renderbuffer& depthStencil) { auto& depthStencilResource = depthStencil.getResource(); #ifdef GL_DEPTH_STENCIL_ATTACHMENT - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, depthStencilResource.renderbuffer)); + MBGL_CHECK_ERROR(glFramebufferRenderbuffer( + GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthStencilResource.renderbuffer + )); #else - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, - depthStencilResource.renderbuffer)); - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, depthStencilResource.renderbuffer)); + MBGL_CHECK_ERROR(glFramebufferRenderbuffer( + GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthStencilResource.renderbuffer + )); + MBGL_CHECK_ERROR(glFramebufferRenderbuffer( + GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthStencilResource.renderbuffer + )); #endif } } // namespace -Framebuffer -Context::createFramebuffer(const gfx::Renderbuffer& color, - const gfx::Renderbuffer& depthStencil) { +Framebuffer Context::createFramebuffer( + const gfx::Renderbuffer& color, + const gfx::Renderbuffer& depthStencil +) { if (color.getSize() != depthStencil.getSize()) { throw std::runtime_error("Renderbuffer size mismatch"); } @@ -330,67 +347,74 @@ Context::createFramebuffer(const gfx::Renderbuffer(); - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - GL_RENDERBUFFER, colorResource.renderbuffer)); + MBGL_CHECK_ERROR( + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorResource.renderbuffer) + ); bindDepthStencilRenderbuffer(depthStencil); checkFramebuffer(); - return { color.getSize(), std::move(fbo) }; + return {color.getSize(), std::move(fbo)}; } Framebuffer Context::createFramebuffer(const gfx::Renderbuffer& color) { auto fbo = createFramebuffer(); bindFramebuffer = fbo; auto& colorResource = color.getResource(); - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - GL_RENDERBUFFER, colorResource.renderbuffer)); + MBGL_CHECK_ERROR( + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorResource.renderbuffer) + ); checkFramebuffer(); - return { color.getSize(), std::move(fbo) }; + return {color.getSize(), std::move(fbo)}; } -Framebuffer -Context::createFramebuffer(const gfx::Texture& color, - const gfx::Renderbuffer& depthStencil) { +Framebuffer Context::createFramebuffer( + const gfx::Texture& color, const gfx::Renderbuffer& depthStencil +) { if (color.size != depthStencil.getSize()) { throw std::runtime_error("Renderbuffer size mismatch"); } auto fbo = createFramebuffer(); bindFramebuffer = fbo; - MBGL_CHECK_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - color.getResource().texture, 0)); + MBGL_CHECK_ERROR(glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color.getResource().texture, 0 + )); bindDepthStencilRenderbuffer(depthStencil); checkFramebuffer(); - return { color.size, std::move(fbo) }; + return {color.size, std::move(fbo)}; } Framebuffer Context::createFramebuffer(const gfx::Texture& color) { auto fbo = createFramebuffer(); bindFramebuffer = fbo; - MBGL_CHECK_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - color.getResource().texture, 0)); + MBGL_CHECK_ERROR(glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color.getResource().texture, 0 + )); checkFramebuffer(); - return { color.size, std::move(fbo) }; + return {color.size, std::move(fbo)}; } -Framebuffer -Context::createFramebuffer(const gfx::Texture& color, - const gfx::Renderbuffer& depth) { +Framebuffer Context::createFramebuffer( + const gfx::Texture& color, const gfx::Renderbuffer& depth +) { if (color.size != depth.getSize()) { throw std::runtime_error("Renderbuffer size mismatch"); } auto fbo = createFramebuffer(); bindFramebuffer = fbo; - MBGL_CHECK_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - color.getResource().texture, 0)); + MBGL_CHECK_ERROR(glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color.getResource().texture, 0 + )); auto& depthResource = depth.getResource(); - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, - depthResource.renderbuffer)); + MBGL_CHECK_ERROR( + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthResource.renderbuffer) + ); checkFramebuffer(); - return { depth.getSize(), std::move(fbo) }; + return {depth.getSize(), std::move(fbo)}; } -std::unique_ptr -Context::createOffscreenTexture(const Size size, const gfx::TextureChannelDataType type) { +std::unique_ptr Context::createOffscreenTexture( + const Size size, const gfx::TextureChannelDataType type +) { return std::make_unique(*this, size, type); } @@ -432,16 +456,14 @@ void Context::setDirtyState() { pixelStorePack.setDirty(); pixelStoreUnpack.setDirty(); for (auto& tex : texture) { - tex.setDirty(); + tex.setDirty(); } vertexBuffer.setDirty(); bindVertexArray.setDirty(); globalVertexArrayState.setDirty(); } -void Context::clear(std::optional color, - std::optional depth, - std::optional stencil) { +void Context::clear(std::optional color, std::optional depth, std::optional stencil) { GLbitfield mask = 0; if (color) { @@ -501,10 +523,8 @@ void Context::setStencilMode(const gfx::StencilMode& stencil) { } else { stencilTest = true; stencilMask = stencil.mask; - stencilOp = { stencil.fail, stencil.depthFail, stencil.pass }; - apply_visitor([&] (const auto& test) { - stencilFunc = { test.func, stencil.ref, test.mask }; - }, stencil.test); + stencilOp = {stencil.fail, stencil.depthFail, stencil.pass}; + apply_visitor([&](const auto& test) { stencilFunc = {test.func, stencil.ref, test.mask}; }, stencil.test); } } @@ -514,10 +534,13 @@ void Context::setColorMode(const gfx::ColorMode& color) { } else { blend = true; blendColor = color.blendColor; - apply_visitor([&] (const auto& blendFunction) { - blendEquation = gfx::ColorBlendEquationType(blendFunction.equation); - blendFunc = { blendFunction.srcFactor, blendFunction.dstFactor }; - }, color.blendFunction); + apply_visitor( + [&](const auto& blendFunction) { + blendEquation = gfx::ColorBlendEquationType(blendFunction.equation); + blendFunc = {blendFunction.srcFactor, blendFunction.dstFactor}; + }, + color.blendFunction + ); } colorMask = color.mask; @@ -543,26 +566,25 @@ void Context::finish() { MBGL_CHECK_ERROR(glFinish()); } -void Context::draw(const gfx::DrawMode& drawMode, - std::size_t indexOffset, - std::size_t indexLength) { +void Context::draw(const gfx::DrawMode& drawMode, std::size_t indexOffset, std::size_t indexLength) { switch (drawMode.type) { - case gfx::DrawModeType::Points: - break; - case gfx::DrawModeType::Lines: - case gfx::DrawModeType::LineLoop: - case gfx::DrawModeType::LineStrip: - lineWidth = drawMode.size; - break; - default: - break; + case gfx::DrawModeType::Points: + break; + case gfx::DrawModeType::Lines: + case gfx::DrawModeType::LineLoop: + case gfx::DrawModeType::LineStrip: + lineWidth = drawMode.size; + break; + default: + break; } MBGL_CHECK_ERROR(glDrawElements( Enum::to(drawMode.type), static_cast(indexLength), GL_UNSIGNED_SHORT, - reinterpret_cast(sizeof(uint16_t) * indexOffset))); + reinterpret_cast(sizeof(uint16_t) * indexOffset) + )); stats.numDrawCalls++; } @@ -635,16 +657,14 @@ void Context::performCleanup() { bindFramebuffer.setDirty(); } } - MBGL_CHECK_ERROR( - glDeleteFramebuffers(int(abandonedFramebuffers.size()), abandonedFramebuffers.data())); + MBGL_CHECK_ERROR(glDeleteFramebuffers(int(abandonedFramebuffers.size()), abandonedFramebuffers.data())); stats.numFrameBuffers -= int(abandonedFramebuffers.size()); assert(stats.numFrameBuffers >= 0); abandonedFramebuffers.clear(); } if (!abandonedRenderbuffers.empty()) { - MBGL_CHECK_ERROR(glDeleteRenderbuffers(int(abandonedRenderbuffers.size()), - abandonedRenderbuffers.data())); + MBGL_CHECK_ERROR(glDeleteRenderbuffers(int(abandonedRenderbuffers.size()), abandonedRenderbuffers.data())); abandonedRenderbuffers.clear(); } } diff --git a/src/mbgl/gl/context.hpp b/src/mbgl/gl/context.hpp index 186b2925635..f1fa3a7eedc 100644 --- a/src/mbgl/gl/context.hpp +++ b/src/mbgl/gl/context.hpp @@ -15,7 +15,6 @@ #include #include - #include #include #include @@ -56,36 +55,31 @@ class Context final : public gfx::Context { void linkProgram(ProgramID); UniqueTexture createUniqueTexture(); - Framebuffer createFramebuffer(const gfx::Renderbuffer&, - const gfx::Renderbuffer&); + Framebuffer + createFramebuffer(const gfx::Renderbuffer&, const gfx::Renderbuffer&); Framebuffer createFramebuffer(const gfx::Renderbuffer&); - Framebuffer createFramebuffer(const gfx::Texture&, - const gfx::Renderbuffer&); + Framebuffer + createFramebuffer(const gfx::Texture&, const gfx::Renderbuffer&); Framebuffer createFramebuffer(const gfx::Texture&); - Framebuffer createFramebuffer(const gfx::Texture&, - const gfx::Renderbuffer&); + Framebuffer createFramebuffer(const gfx::Texture&, const gfx::Renderbuffer&); - template + template < + typename Image, + gfx::TexturePixelType format = Image::channels == 4 ? gfx::TexturePixelType::RGBA + : gfx::TexturePixelType::Alpha> Image readFramebuffer(const Size size, bool flip = true) { - static_assert(Image::channels == (format == gfx::TexturePixelType::RGBA ? 4 : 1), - "image format mismatch"); - return { size, readFramebuffer(size, format, flip) }; + static_assert(Image::channels == (format == gfx::TexturePixelType::RGBA ? 4 : 1), "image format mismatch"); + return {size, readFramebuffer(size, format, flip)}; } - void clear(std::optional color, - std::optional depth, - std::optional stencil); + void clear(std::optional color, std::optional depth, std::optional stencil); void setDepthMode(const gfx::DepthMode&); void setStencilMode(const gfx::StencilMode&); void setColorMode(const gfx::ColorMode&); void setCullFaceMode(const gfx::CullFaceMode&); - void draw(const gfx::DrawMode&, - std::size_t indexOffset, - std::size_t indexLength); + void draw(const gfx::DrawMode&, std::size_t indexOffset, std::size_t indexLength); void finish(); @@ -100,24 +94,16 @@ class Context final : public gfx::Context { void reset(); bool empty() const { - return pooledTextures.empty() - && abandonedPrograms.empty() - && abandonedShaders.empty() - && abandonedBuffers.empty() - && abandonedTextures.empty() - && abandonedVertexArrays.empty() - && abandonedFramebuffers.empty(); + return pooledTextures.empty() && abandonedPrograms.empty() && abandonedShaders.empty() && + abandonedBuffers.empty() && abandonedTextures.empty() && abandonedVertexArrays.empty() && + abandonedFramebuffers.empty(); } void setDirtyState(); - extension::Debugging* getDebuggingExtension() const { - return debugging.get(); - } + extension::Debugging* getDebuggingExtension() const { return debugging.get(); } - void setCleanupOnDestruction(bool cleanup) { - cleanupOnDestruction = cleanup; - } + void setCleanupOnDestruction(bool cleanup) { cleanupOnDestruction = cleanup; } private: RendererBackend& backend; @@ -136,7 +122,7 @@ class Context final : public gfx::Context { State vertexBuffer; State bindVertexArray; - VertexArrayState globalVertexArrayState { UniqueVertexArray(0, { const_cast(this) }) }; + VertexArrayState globalVertexArrayState{UniqueVertexArray(0, {const_cast(this)})}; State pixelStorePack; State pixelStoreUnpack; @@ -166,10 +152,12 @@ class Context final : public gfx::Context { std::unique_ptr createOffscreenTexture(Size, gfx::TextureChannelDataType) override; - std::unique_ptr - createTextureResource(Size, gfx::TexturePixelType, gfx::TextureChannelDataType) override; + std::unique_ptr createTextureResource( + Size, gfx::TexturePixelType, gfx::TextureChannelDataType + ) override; - std::unique_ptr createRenderbufferResource(gfx::RenderbufferPixelType, Size size) override; + std::unique_ptr createRenderbufferResource(gfx::RenderbufferPixelType, Size size) + override; std::unique_ptr createDrawScopeResource() override; diff --git a/src/mbgl/gl/custom_layer.cpp b/src/mbgl/gl/custom_layer.cpp index 853b6e4008d..fc9381cd779 100644 --- a/src/mbgl/gl/custom_layer.cpp +++ b/src/mbgl/gl/custom_layer.cpp @@ -7,19 +7,18 @@ namespace mbgl { namespace style { namespace { -const LayerTypeInfo typeInfoCustom{"custom", - LayerTypeInfo::Source::NotRequired, - LayerTypeInfo::Pass3D::NotRequired, - LayerTypeInfo::Layout::NotRequired, - LayerTypeInfo::FadingTiles::NotRequired, - LayerTypeInfo::CrossTileIndex::NotRequired, - LayerTypeInfo::TileKind::NotRequired}; -} // namespace - -CustomLayer::CustomLayer(const std::string& layerID, - std::unique_ptr host) - : Layer(makeMutable(layerID, std::move(host))) { -} +const LayerTypeInfo typeInfoCustom{ + "custom", + LayerTypeInfo::Source::NotRequired, + LayerTypeInfo::Pass3D::NotRequired, + LayerTypeInfo::Layout::NotRequired, + LayerTypeInfo::FadingTiles::NotRequired, + LayerTypeInfo::CrossTileIndex::NotRequired, + LayerTypeInfo::TileKind::NotRequired}; +} // namespace + +CustomLayer::CustomLayer(const std::string& layerID, std::unique_ptr host) + : Layer(makeMutable(layerID, std::move(host))) {} CustomLayer::~CustomLayer() = default; @@ -39,7 +38,7 @@ std::unique_ptr CustomLayer::cloneRef(const std::string&) const { using namespace conversion; std::optional CustomLayer::setPropertyInternal(const std::string&, const Convertible&) { - return Error { "layer doesn't support this property" }; + return Error{"layer doesn't support this property"}; } StyleProperty CustomLayer::getProperty(const std::string&) const { diff --git a/src/mbgl/gl/custom_layer_factory.cpp b/src/mbgl/gl/custom_layer_factory.cpp index 616d0271e0a..ce77ac85da0 100644 --- a/src/mbgl/gl/custom_layer_factory.cpp +++ b/src/mbgl/gl/custom_layer_factory.cpp @@ -9,7 +9,8 @@ const style::LayerTypeInfo* CustomLayerFactory::getTypeInfo() const noexcept { return style::CustomLayer::Impl::staticTypeInfo(); } -std::unique_ptr CustomLayerFactory::createLayer(const std::string&, const style::conversion::Convertible&) noexcept { +std::unique_ptr +CustomLayerFactory::createLayer(const std::string&, const style::conversion::Convertible&) noexcept { assert(false); return nullptr; } diff --git a/src/mbgl/gl/custom_layer_impl.cpp b/src/mbgl/gl/custom_layer_impl.cpp index 85df44bc800..8268272ae4f 100644 --- a/src/mbgl/gl/custom_layer_impl.cpp +++ b/src/mbgl/gl/custom_layer_impl.cpp @@ -3,8 +3,7 @@ namespace mbgl { namespace style { -CustomLayer::Impl::Impl(const std::string& id_, - std::unique_ptr host_) +CustomLayer::Impl::Impl(const std::string& id_, std::unique_ptr host_) : Layer::Impl(id_, std::string()) { host = std::move(host_); } @@ -13,8 +12,7 @@ bool CustomLayer::Impl::hasLayoutDifference(const Layer::Impl&) const { return false; } -void CustomLayer::Impl::stringifyLayout(rapidjson::Writer&) const { -} +void CustomLayer::Impl::stringifyLayout(rapidjson::Writer&) const {} } // namespace style } // namespace mbgl diff --git a/src/mbgl/gl/custom_layer_impl.hpp b/src/mbgl/gl/custom_layer_impl.hpp index 0c9339adf18..d0ea5f38278 100644 --- a/src/mbgl/gl/custom_layer_impl.hpp +++ b/src/mbgl/gl/custom_layer_impl.hpp @@ -14,8 +14,7 @@ namespace style { class CustomLayer::Impl : public Layer::Impl { public: - Impl(const std::string& id, - std::unique_ptr host); + Impl(const std::string& id, std::unique_ptr host); bool hasLayoutDifference(const Layer::Impl&) const override; void stringifyLayout(rapidjson::Writer&) const override; diff --git a/src/mbgl/gl/debugging_extension.cpp b/src/mbgl/gl/debugging_extension.cpp index 06bdd70d90d..3d36ec5efbb 100644 --- a/src/mbgl/gl/debugging_extension.cpp +++ b/src/mbgl/gl/debugging_extension.cpp @@ -5,54 +5,101 @@ namespace mbgl { namespace gl { namespace extension { -void Debugging::DebugCallback(GLenum source, - GLenum type, - GLuint id, - GLenum severity, - GLsizei /* length */, - const GLchar* message, - const void* /* userParam */) { +void Debugging::DebugCallback( + GLenum source, + GLenum type, + GLuint id, + GLenum severity, + GLsizei /* length */, + const GLchar* message, + const void* /* userParam */ +) { std::string strSource; switch (source) { - case GL_DEBUG_SOURCE_API: strSource = "DEBUG_SOURCE_API"; break; - case GL_DEBUG_SOURCE_WINDOW_SYSTEM: strSource = "DEBUG_SOURCE_WINDOW_SYSTEM"; break; - case GL_DEBUG_SOURCE_SHADER_COMPILER: strSource = "DEBUG_SOURCE_SHADER_COMPILER"; break; - case GL_DEBUG_SOURCE_THIRD_PARTY: strSource = "DEBUG_SOURCE_THIRD_PARTY"; break; - case GL_DEBUG_SOURCE_APPLICATION: strSource = "DEBUG_SOURCE_APPLICATION"; break; - case GL_DEBUG_SOURCE_OTHER: strSource = "DEBUG_SOURCE_OTHER"; break; - default: strSource = "(unknown)"; break; + case GL_DEBUG_SOURCE_API: + strSource = "DEBUG_SOURCE_API"; + break; + case GL_DEBUG_SOURCE_WINDOW_SYSTEM: + strSource = "DEBUG_SOURCE_WINDOW_SYSTEM"; + break; + case GL_DEBUG_SOURCE_SHADER_COMPILER: + strSource = "DEBUG_SOURCE_SHADER_COMPILER"; + break; + case GL_DEBUG_SOURCE_THIRD_PARTY: + strSource = "DEBUG_SOURCE_THIRD_PARTY"; + break; + case GL_DEBUG_SOURCE_APPLICATION: + strSource = "DEBUG_SOURCE_APPLICATION"; + break; + case GL_DEBUG_SOURCE_OTHER: + strSource = "DEBUG_SOURCE_OTHER"; + break; + default: + strSource = "(unknown)"; + break; } std::string strType; switch (type) { - case GL_DEBUG_TYPE_ERROR: strType = "DEBUG_TYPE_ERROR"; break; - case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: strType = "DEBUG_TYPE_DEPRECATED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: strType = "DEBUG_TYPE_UNDEFINED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_PERFORMANCE: strType = "DEBUG_TYPE_PERFORMANCE"; break; - case GL_DEBUG_TYPE_PORTABILITY: strType = "DEBUG_TYPE_PORTABILITY"; break; - case GL_DEBUG_TYPE_OTHER: strType = "DEBUG_TYPE_OTHER"; break; - case GL_DEBUG_TYPE_MARKER: strType = "DEBUG_TYPE_MARKER"; break; - case GL_DEBUG_TYPE_PUSH_GROUP: strType = "DEBUG_TYPE_OTHER"; break; - case GL_DEBUG_TYPE_POP_GROUP: strType = "DEBUG_TYPE_POP_GROUP"; break; - default: strSource = "(unknown)"; break; + case GL_DEBUG_TYPE_ERROR: + strType = "DEBUG_TYPE_ERROR"; + break; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: + strType = "DEBUG_TYPE_DEPRECATED_BEHAVIOR"; + break; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: + strType = "DEBUG_TYPE_UNDEFINED_BEHAVIOR"; + break; + case GL_DEBUG_TYPE_PERFORMANCE: + strType = "DEBUG_TYPE_PERFORMANCE"; + break; + case GL_DEBUG_TYPE_PORTABILITY: + strType = "DEBUG_TYPE_PORTABILITY"; + break; + case GL_DEBUG_TYPE_OTHER: + strType = "DEBUG_TYPE_OTHER"; + break; + case GL_DEBUG_TYPE_MARKER: + strType = "DEBUG_TYPE_MARKER"; + break; + case GL_DEBUG_TYPE_PUSH_GROUP: + strType = "DEBUG_TYPE_OTHER"; + break; + case GL_DEBUG_TYPE_POP_GROUP: + strType = "DEBUG_TYPE_POP_GROUP"; + break; + default: + strSource = "(unknown)"; + break; } std::string strSeverity; mbgl::EventSeverity evtSeverity; switch (severity) { - case GL_DEBUG_SEVERITY_HIGH: strSeverity = "DEBUG_SEVERITY_HIGH"; evtSeverity = mbgl::EventSeverity::Error; break; - case GL_DEBUG_SEVERITY_MEDIUM: strSeverity = "DEBUG_SEVERITY_MEDIUM"; evtSeverity = mbgl::EventSeverity::Warning; break; - case GL_DEBUG_SEVERITY_LOW: strSeverity = "DEBUG_SEVERITY_LOW"; evtSeverity = mbgl::EventSeverity::Info; break; - case GL_DEBUG_SEVERITY_NOTIFICATION: strSeverity = "DEBUG_SEVERITY_NOTIFICATION"; evtSeverity = mbgl::EventSeverity::Debug; break; - default: strSource = "(unknown)"; evtSeverity = mbgl::EventSeverity::Debug; break; + case GL_DEBUG_SEVERITY_HIGH: + strSeverity = "DEBUG_SEVERITY_HIGH"; + evtSeverity = mbgl::EventSeverity::Error; + break; + case GL_DEBUG_SEVERITY_MEDIUM: + strSeverity = "DEBUG_SEVERITY_MEDIUM"; + evtSeverity = mbgl::EventSeverity::Warning; + break; + case GL_DEBUG_SEVERITY_LOW: + strSeverity = "DEBUG_SEVERITY_LOW"; + evtSeverity = mbgl::EventSeverity::Info; + break; + case GL_DEBUG_SEVERITY_NOTIFICATION: + strSeverity = "DEBUG_SEVERITY_NOTIFICATION"; + evtSeverity = mbgl::EventSeverity::Debug; + break; + default: + strSource = "(unknown)"; + evtSeverity = mbgl::EventSeverity::Debug; + break; } - const std::string logMsg = "GL_" + strSource + - " GL_" + strType + - " " + std::to_string(id) + - " GL_" + strSeverity + - " - " + message; + const std::string logMsg = "GL_" + strSource + " GL_" + strType + " " + std::to_string(id) + " GL_" + strSeverity + + " - " + message; mbgl::Log::Record(evtSeverity, mbgl::Event::OpenGL, logMsg); - } } // namespace extension diff --git a/src/mbgl/gl/debugging_extension.hpp b/src/mbgl/gl/debugging_extension.hpp index 0fa5a7b424c..2df63197c5b 100644 --- a/src/mbgl/gl/debugging_extension.hpp +++ b/src/mbgl/gl/debugging_extension.hpp @@ -3,49 +3,49 @@ #include #include -#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 +#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 #define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 -#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 -#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 -#define GL_DEBUG_SOURCE_API 0x8246 -#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 -#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 -#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 -#define GL_DEBUG_SOURCE_APPLICATION 0x824A -#define GL_DEBUG_SOURCE_OTHER 0x824B -#define GL_DEBUG_TYPE_ERROR 0x824C +#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 +#define GL_DEBUG_SOURCE_API 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION 0x824A +#define GL_DEBUG_SOURCE_OTHER 0x824B +#define GL_DEBUG_TYPE_ERROR 0x824C #define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D -#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E -#define GL_DEBUG_TYPE_PORTABILITY 0x824F -#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 -#define GL_DEBUG_TYPE_OTHER 0x8251 -#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 -#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 -#define GL_DEBUG_LOGGED_MESSAGES 0x9145 -#define GL_DEBUG_SEVERITY_HIGH 0x9146 -#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 -#define GL_DEBUG_SEVERITY_LOW 0x9148 -#define GL_DEBUG_TYPE_MARKER 0x8268 -#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 -#define GL_DEBUG_TYPE_POP_GROUP 0x826A -#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B -#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C -#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D -#define GL_BUFFER 0x82E0 -#define GL_SHADER 0x82E1 -#define GL_PROGRAM 0x82E2 -#define GL_QUERY 0x82E3 -#define GL_PROGRAM_PIPELINE 0x82E4 -#define GL_SAMPLER 0x82E6 -#define GL_MAX_LABEL_LENGTH 0x82E8 -#define GL_DEBUG_OUTPUT 0x92E0 -#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 -#define GL_DISPLAY_LIST 0x82E7 -#define GL_VERTEX_ARRAY 0x8074 -#define GL_TRANSFORM_FEEDBACK 0x8E22 -#define GL_TEXTURE 0x1702 -#define GL_RENDERBUFFER 0x8D41 -#define GL_FRAMEBUFFER 0x8D40 +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E +#define GL_DEBUG_TYPE_PORTABILITY 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 +#define GL_DEBUG_TYPE_OTHER 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES 0x9145 +#define GL_DEBUG_SEVERITY_HIGH 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 +#define GL_DEBUG_SEVERITY_LOW 0x9148 +#define GL_DEBUG_TYPE_MARKER 0x8268 +#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 +#define GL_DEBUG_TYPE_POP_GROUP 0x826A +#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B +#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C +#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D +#define GL_BUFFER 0x82E0 +#define GL_SHADER 0x82E1 +#define GL_PROGRAM 0x82E2 +#define GL_QUERY 0x82E3 +#define GL_PROGRAM_PIPELINE 0x82E4 +#define GL_SAMPLER 0x82E6 +#define GL_MAX_LABEL_LENGTH 0x82E8 +#define GL_DEBUG_OUTPUT 0x92E0 +#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 +#define GL_DISPLAY_LIST 0x82E7 +#define GL_VERTEX_ARRAY 0x8074 +#define GL_TRANSFORM_FEEDBACK 0x8E22 +#define GL_TEXTURE 0x1702 +#define GL_RENDERBUFFER 0x8D41 +#define GL_FRAMEBUFFER 0x8D40 namespace mbgl { namespace gl { @@ -55,66 +55,58 @@ using namespace platform; class Debugging { public: - using Callback = void (*)(GLenum source, - GLenum type, - GLuint id, - GLenum severity, - GLsizei length, - const GLchar* message, - const void* userParam); + using Callback = void (*)( + GLenum source, + GLenum type, + GLuint id, + GLenum severity, + GLsizei length, + const GLchar* message, + const void* userParam + ); - static void DebugCallback(GLenum source, - GLenum type, - GLuint id, - GLenum severity, - GLsizei /* length */, - const GLchar* message, - const void* /* userParam */); + static void DebugCallback( + GLenum source, + GLenum type, + GLuint id, + GLenum severity, + GLsizei /* length */, + const GLchar* message, + const void* /* userParam */ + ); template Debugging(const Fn& loadExtension) : #ifndef NDEBUG - pushDebugGroup( - loadExtension({ { "GL_KHR_debug", "glPushDebugGroup" } })), - popDebugGroup( - loadExtension({ { "GL_KHR_debug", "glPopDebugGroup" } })), - pushGroupMarkerEXT( - loadExtension({ { "GL_EXT_debug_marker", "glPushGroupMarkerEXT" } })), - popGroupMarkerEXT( - loadExtension({ { "GL_EXT_debug_marker", "glPopGroupMarkerEXT" } })), + pushDebugGroup(loadExtension({{"GL_KHR_debug", "glPushDebugGroup"}})), + popDebugGroup(loadExtension({{"GL_KHR_debug", "glPopDebugGroup"}})), + pushGroupMarkerEXT(loadExtension({{"GL_EXT_debug_marker", "glPushGroupMarkerEXT"}})), + popGroupMarkerEXT(loadExtension({{"GL_EXT_debug_marker", "glPopGroupMarkerEXT"}})), #endif - debugMessageControl( - loadExtension({ { "GL_KHR_debug", "glDebugMessageControl" }, - { "GL_ARB_debug_output", "glDebugMessageControlARB" } })), - debugMessageCallback( - loadExtension({ { "GL_KHR_debug", "glDebugMessageCallback" }, - { "GL_ARB_debug_output", "glDebugMessageCallbackARB" } })) { + debugMessageControl(loadExtension( + {{"GL_KHR_debug", "glDebugMessageControl"}, {"GL_ARB_debug_output", "glDebugMessageControlARB"}} + )), + debugMessageCallback(loadExtension( + {{"GL_KHR_debug", "glDebugMessageCallback"}, {"GL_ARB_debug_output", "glDebugMessageCallbackARB"}} + )) { } #ifndef NDEBUG - const ExtensionFunction pushDebugGroup; + const ExtensionFunction pushDebugGroup; const ExtensionFunction popDebugGroup; - const ExtensionFunction pushGroupMarkerEXT; + const ExtensionFunction pushGroupMarkerEXT; const ExtensionFunction popGroupMarkerEXT; #endif - const ExtensionFunction debugMessageControl; + const ExtensionFunction< + void(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint* ids, GLboolean enabled)> + debugMessageControl; - const ExtensionFunction debugMessageCallback; + const ExtensionFunction debugMessageCallback; }; } // namespace extension diff --git a/src/mbgl/gl/defines.hpp b/src/mbgl/gl/defines.hpp index 5f8c748fcbd..7cc3223b246 100644 --- a/src/mbgl/gl/defines.hpp +++ b/src/mbgl/gl/defines.hpp @@ -3,84 +3,84 @@ /* OpenGL ES 2.0 */ /* ClearBufferMask */ -#define GL_DEPTH_BUFFER_BIT 0x00000100 -#define GL_STENCIL_BUFFER_BIT 0x00000400 -#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_COLOR_BUFFER_BIT 0x00004000 /* Boolean */ -#define GL_FALSE 0 -#define GL_TRUE 1 +#define GL_FALSE 0 +#define GL_TRUE 1 /* BeginMode */ -#define GL_POINTS 0x0000 -#define GL_LINES 0x0001 -#define GL_LINE_LOOP 0x0002 -#define GL_LINE_STRIP 0x0003 -#define GL_TRIANGLES 0x0004 -#define GL_TRIANGLE_STRIP 0x0005 -#define GL_TRIANGLE_FAN 0x0006 +#define GL_POINTS 0x0000 +#define GL_LINES 0x0001 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_STRIP 0x0003 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_FAN 0x0006 /* BlendingFactorDest */ -#define GL_ZERO 0 -#define GL_ONE 1 -#define GL_SRC_COLOR 0x0300 -#define GL_ONE_MINUS_SRC_COLOR 0x0301 -#define GL_SRC_ALPHA 0x0302 -#define GL_ONE_MINUS_SRC_ALPHA 0x0303 -#define GL_DST_ALPHA 0x0304 -#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_ZERO 0 +#define GL_ONE 1 +#define GL_SRC_COLOR 0x0300 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_DST_ALPHA 0x0304 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 /* BlendingFactorSrc */ /* GL_ZERO */ /* GL_ONE */ -#define GL_DST_COLOR 0x0306 -#define GL_ONE_MINUS_DST_COLOR 0x0307 -#define GL_SRC_ALPHA_SATURATE 0x0308 +#define GL_DST_COLOR 0x0306 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_SRC_ALPHA_SATURATE 0x0308 /* GL_SRC_ALPHA */ /* GL_ONE_MINUS_SRC_ALPHA */ /* GL_DST_ALPHA */ /* GL_ONE_MINUS_DST_ALPHA */ /* BlendEquationSeparate */ -#define GL_FUNC_ADD 0x8006 -#define GL_BLEND_EQUATION 0x8009 -#define GL_BLEND_EQUATION_RGB 0x8009 /* same as BLEND_EQUATION */ -#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_FUNC_ADD 0x8006 +#define GL_BLEND_EQUATION 0x8009 +#define GL_BLEND_EQUATION_RGB 0x8009 /* same as BLEND_EQUATION */ +#define GL_BLEND_EQUATION_ALPHA 0x883D /* BlendSubtract */ -#define GL_FUNC_SUBTRACT 0x800A -#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_FUNC_SUBTRACT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT 0x800B /* Separate Blend Functions */ -#define GL_BLEND_DST_RGB 0x80C8 -#define GL_BLEND_SRC_RGB 0x80C9 -#define GL_BLEND_DST_ALPHA 0x80CA -#define GL_BLEND_SRC_ALPHA 0x80CB -#define GL_CONSTANT_COLOR 0x8001 -#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 -#define GL_CONSTANT_ALPHA 0x8003 -#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 -#define GL_BLEND_COLOR 0x8005 +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_BLEND_COLOR 0x8005 /* Buffer Objects */ -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#define GL_ARRAY_BUFFER_BINDING 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_STREAM_DRAW 0x88E0 -#define GL_STATIC_DRAW 0x88E4 -#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_STREAM_DRAW 0x88E0 +#define GL_STATIC_DRAW 0x88E4 +#define GL_DYNAMIC_DRAW 0x88E8 -#define GL_BUFFER_SIZE 0x8764 -#define GL_BUFFER_USAGE 0x8765 +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 -#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 /* CullFaceMode */ -#define GL_FRONT 0x0404 -#define GL_BACK 0x0405 -#define GL_FRONT_AND_BACK 0x0408 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_FRONT_AND_BACK 0x0408 /* DepthFunction */ /* GL_NEVER */ @@ -93,77 +93,77 @@ /* GL_ALWAYS */ /* EnableCap */ -#define GL_TEXTURE_2D 0x0DE1 -#define GL_CULL_FACE 0x0B44 -#define GL_BLEND 0x0BE2 -#define GL_DITHER 0x0BD0 -#define GL_STENCIL_TEST 0x0B90 -#define GL_DEPTH_TEST 0x0B71 -#define GL_SCISSOR_TEST 0x0C11 -#define GL_POLYGON_OFFSET_FILL 0x8037 -#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E -#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_CULL_FACE 0x0B44 +#define GL_BLEND 0x0BE2 +#define GL_DITHER 0x0BD0 +#define GL_STENCIL_TEST 0x0B90 +#define GL_DEPTH_TEST 0x0B71 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_COVERAGE 0x80A0 /* ErrorCode */ -#define GL_NO_ERROR 0 -#define GL_INVALID_ENUM 0x0500 -#define GL_INVALID_VALUE 0x0501 -#define GL_INVALID_OPERATION 0x0502 -#define GL_OUT_OF_MEMORY 0x0505 +#define GL_NO_ERROR 0 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVALID_OPERATION 0x0502 +#define GL_OUT_OF_MEMORY 0x0505 /* FrontFaceDirection */ -#define GL_CW 0x0900 -#define GL_CCW 0x0901 +#define GL_CW 0x0900 +#define GL_CCW 0x0901 /* GetPName */ -#define GL_LINE_WIDTH 0x0B21 -#define GL_ALIASED_POINT_SIZE_RANGE 0x846D -#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E -#define GL_CULL_FACE_MODE 0x0B45 -#define GL_FRONT_FACE 0x0B46 -#define GL_DEPTH_RANGE 0x0B70 -#define GL_DEPTH_WRITEMASK 0x0B72 -#define GL_DEPTH_CLEAR_VALUE 0x0B73 -#define GL_DEPTH_FUNC 0x0B74 -#define GL_STENCIL_CLEAR_VALUE 0x0B91 -#define GL_STENCIL_FUNC 0x0B92 -#define GL_STENCIL_FAIL 0x0B94 -#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 -#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 -#define GL_STENCIL_REF 0x0B97 -#define GL_STENCIL_VALUE_MASK 0x0B93 -#define GL_STENCIL_WRITEMASK 0x0B98 -#define GL_STENCIL_BACK_FUNC 0x8800 -#define GL_STENCIL_BACK_FAIL 0x8801 -#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 -#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 -#define GL_STENCIL_BACK_REF 0x8CA3 -#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 -#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 -#define GL_VIEWPORT 0x0BA2 -#define GL_SCISSOR_BOX 0x0C10 +#define GL_LINE_WIDTH 0x0B21 +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_FRONT_FACE 0x0B46 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_VIEWPORT 0x0BA2 +#define GL_SCISSOR_BOX 0x0C10 /* GL_SCISSOR_TEST */ -#define GL_COLOR_CLEAR_VALUE 0x0C22 -#define GL_COLOR_WRITEMASK 0x0C23 -#define GL_UNPACK_ALIGNMENT 0x0CF5 -#define GL_PACK_ALIGNMENT 0x0D05 -#define GL_MAX_TEXTURE_SIZE 0x0D33 -#define GL_MAX_VIEWPORT_DIMS 0x0D3A -#define GL_SUBPIXEL_BITS 0x0D50 -#define GL_RED_BITS 0x0D52 -#define GL_GREEN_BITS 0x0D53 -#define GL_BLUE_BITS 0x0D54 -#define GL_ALPHA_BITS 0x0D55 -#define GL_DEPTH_BITS 0x0D56 -#define GL_STENCIL_BITS 0x0D57 -#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_RED_BITS 0x0D52 +#define GL_GREEN_BITS 0x0D53 +#define GL_BLUE_BITS 0x0D54 +#define GL_ALPHA_BITS 0x0D55 +#define GL_DEPTH_BITS 0x0D56 +#define GL_STENCIL_BITS 0x0D57 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 /* GL_POLYGON_OFFSET_FILL */ -#define GL_POLYGON_OFFSET_FACTOR 0x8038 -#define GL_TEXTURE_BINDING_2D 0x8069 -#define GL_SAMPLE_BUFFERS 0x80A8 -#define GL_SAMPLES 0x80A9 -#define GL_SAMPLE_COVERAGE_VALUE 0x80AA -#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB /* GetTextureParameter */ /* GL_TEXTURE_MAG_FILTER */ @@ -171,561 +171,561 @@ /* GL_TEXTURE_WRAP_S */ /* GL_TEXTURE_WRAP_T */ -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 /* HintMode */ -#define GL_DONT_CARE 0x1100 -#define GL_FASTEST 0x1101 -#define GL_NICEST 0x1102 +#define GL_DONT_CARE 0x1100 +#define GL_FASTEST 0x1101 +#define GL_NICEST 0x1102 /* HintTarget */ -#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_GENERATE_MIPMAP_HINT 0x8192 /* DataType */ -#define GL_BYTE 0x1400 -#define GL_UNSIGNED_BYTE 0x1401 -#define GL_SHORT 0x1402 -#define GL_UNSIGNED_SHORT 0x1403 -#define GL_INT 0x1404 -#define GL_UNSIGNED_INT 0x1405 -#define GL_FLOAT 0x1406 -#define GL_FIXED 0x140C +#define GL_BYTE 0x1400 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_SHORT 0x1402 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_INT 0x1404 +#define GL_UNSIGNED_INT 0x1405 +#define GL_FLOAT 0x1406 +#define GL_FIXED 0x140C /* PixelFormat */ -#define GL_STENCIL_INDEX 0x1901 -#define GL_DEPTH_COMPONENT 0x1902 -#define GL_ALPHA 0x1906 -#define GL_RGB 0x1907 -#define GL_RGBA 0x1908 -#define GL_LUMINANCE 0x1909 -#define GL_LUMINANCE_ALPHA 0x190A +#define GL_STENCIL_INDEX 0x1901 +#define GL_DEPTH_COMPONENT 0x1902 +#define GL_ALPHA 0x1906 +#define GL_RGB 0x1907 +#define GL_RGBA 0x1908 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE_ALPHA 0x190A /* PixelType */ /* GL_UNSIGNED_BYTE */ -#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 -#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 /* Shaders */ -#define GL_FRAGMENT_SHADER 0x8B30 -#define GL_VERTEX_SHADER 0x8B31 -#define GL_MAX_VERTEX_ATTRIBS 0x8869 -#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB -#define GL_MAX_VARYING_VECTORS 0x8DFC -#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D -#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C -#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 -#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD -#define GL_SHADER_TYPE 0x8B4F -#define GL_DELETE_STATUS 0x8B80 -#define GL_LINK_STATUS 0x8B82 -#define GL_VALIDATE_STATUS 0x8B83 -#define GL_ATTACHED_SHADERS 0x8B85 -#define GL_ACTIVE_UNIFORMS 0x8B86 -#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 -#define GL_ACTIVE_ATTRIBUTES 0x8B89 -#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A -#define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB +#define GL_MAX_VARYING_VECTORS 0x8DFC +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD +#define GL_SHADER_TYPE 0x8B4F +#define GL_DELETE_STATUS 0x8B80 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D /* StencilFunction */ -#define GL_NEVER 0x0200 -#define GL_LESS 0x0201 -#define GL_EQUAL 0x0202 -#define GL_LEQUAL 0x0203 -#define GL_GREATER 0x0204 -#define GL_NOTEQUAL 0x0205 -#define GL_GEQUAL 0x0206 -#define GL_ALWAYS 0x0207 +#define GL_NEVER 0x0200 +#define GL_LESS 0x0201 +#define GL_EQUAL 0x0202 +#define GL_LEQUAL 0x0203 +#define GL_GREATER 0x0204 +#define GL_NOTEQUAL 0x0205 +#define GL_GEQUAL 0x0206 +#define GL_ALWAYS 0x0207 /* StencilOp */ /* GL_ZERO */ -#define GL_KEEP 0x1E00 -#define GL_REPLACE 0x1E01 -#define GL_INCR 0x1E02 -#define GL_DECR 0x1E03 -#define GL_INVERT 0x150A -#define GL_INCR_WRAP 0x8507 -#define GL_DECR_WRAP 0x8508 +#define GL_KEEP 0x1E00 +#define GL_REPLACE 0x1E01 +#define GL_INCR 0x1E02 +#define GL_DECR 0x1E03 +#define GL_INVERT 0x150A +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 /* StringName */ -#define GL_VENDOR 0x1F00 -#define GL_RENDERER 0x1F01 -#define GL_VERSION 0x1F02 -#define GL_EXTENSIONS 0x1F03 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 /* TextureMagFilter */ -#define GL_NEAREST 0x2600 -#define GL_LINEAR 0x2601 +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 /* TextureMinFilter */ /* GL_NEAREST */ /* GL_LINEAR */ -#define GL_NEAREST_MIPMAP_NEAREST 0x2700 -#define GL_LINEAR_MIPMAP_NEAREST 0x2701 -#define GL_NEAREST_MIPMAP_LINEAR 0x2702 -#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 /* TextureParameterName */ -#define GL_TEXTURE_MAG_FILTER 0x2800 -#define GL_TEXTURE_MIN_FILTER 0x2801 -#define GL_TEXTURE_WRAP_S 0x2802 -#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 /* TextureTarget */ /* GL_TEXTURE_2D */ -#define GL_TEXTURE 0x1702 - -#define GL_TEXTURE_CUBE_MAP 0x8513 -#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A -#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_TEXTURE 0x1702 + +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C /* TextureUnit */ -#define GL_TEXTURE0 0x84C0 -#define GL_TEXTURE1 0x84C1 -#define GL_TEXTURE2 0x84C2 -#define GL_TEXTURE3 0x84C3 -#define GL_TEXTURE4 0x84C4 -#define GL_TEXTURE5 0x84C5 -#define GL_TEXTURE6 0x84C6 -#define GL_TEXTURE7 0x84C7 -#define GL_TEXTURE8 0x84C8 -#define GL_TEXTURE9 0x84C9 -#define GL_TEXTURE10 0x84CA -#define GL_TEXTURE11 0x84CB -#define GL_TEXTURE12 0x84CC -#define GL_TEXTURE13 0x84CD -#define GL_TEXTURE14 0x84CE -#define GL_TEXTURE15 0x84CF -#define GL_TEXTURE16 0x84D0 -#define GL_TEXTURE17 0x84D1 -#define GL_TEXTURE18 0x84D2 -#define GL_TEXTURE19 0x84D3 -#define GL_TEXTURE20 0x84D4 -#define GL_TEXTURE21 0x84D5 -#define GL_TEXTURE22 0x84D6 -#define GL_TEXTURE23 0x84D7 -#define GL_TEXTURE24 0x84D8 -#define GL_TEXTURE25 0x84D9 -#define GL_TEXTURE26 0x84DA -#define GL_TEXTURE27 0x84DB -#define GL_TEXTURE28 0x84DC -#define GL_TEXTURE29 0x84DD -#define GL_TEXTURE30 0x84DE -#define GL_TEXTURE31 0x84DF -#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 /* TextureWrapMode */ -#define GL_REPEAT 0x2901 -#define GL_CLAMP_TO_EDGE 0x812F -#define GL_MIRRORED_REPEAT 0x8370 +#define GL_REPEAT 0x2901 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_MIRRORED_REPEAT 0x8370 /* Uniform Types */ -#define GL_FLOAT_VEC2 0x8B50 -#define GL_FLOAT_VEC3 0x8B51 -#define GL_FLOAT_VEC4 0x8B52 -#define GL_INT_VEC2 0x8B53 -#define GL_INT_VEC3 0x8B54 -#define GL_INT_VEC4 0x8B55 -#define GL_BOOL 0x8B56 -#define GL_BOOL_VEC2 0x8B57 -#define GL_BOOL_VEC3 0x8B58 -#define GL_BOOL_VEC4 0x8B59 -#define GL_FLOAT_MAT2 0x8B5A -#define GL_FLOAT_MAT3 0x8B5B -#define GL_FLOAT_MAT4 0x8B5C -#define GL_SAMPLER_2D 0x8B5E -#define GL_SAMPLER_CUBE 0x8B60 +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_CUBE 0x8B60 /* Vertex Arrays */ -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A -#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F /* Read Format */ -#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A -#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B +#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B /* Shader Source */ -#define GL_COMPILE_STATUS 0x8B81 -#define GL_INFO_LOG_LENGTH 0x8B84 -#define GL_SHADER_SOURCE_LENGTH 0x8B88 -#define GL_SHADER_COMPILER 0x8DFA +#define GL_COMPILE_STATUS 0x8B81 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_SHADER_COMPILER 0x8DFA /* Shader Binary */ -#define GL_SHADER_BINARY_FORMATS 0x8DF8 -#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 +#define GL_SHADER_BINARY_FORMATS 0x8DF8 +#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 /* Shader Precision-Specified Types */ -#define GL_LOW_FLOAT 0x8DF0 -#define GL_MEDIUM_FLOAT 0x8DF1 -#define GL_HIGH_FLOAT 0x8DF2 -#define GL_LOW_INT 0x8DF3 -#define GL_MEDIUM_INT 0x8DF4 -#define GL_HIGH_INT 0x8DF5 +#define GL_LOW_FLOAT 0x8DF0 +#define GL_MEDIUM_FLOAT 0x8DF1 +#define GL_HIGH_FLOAT 0x8DF2 +#define GL_LOW_INT 0x8DF3 +#define GL_MEDIUM_INT 0x8DF4 +#define GL_HIGH_INT 0x8DF5 /* Framebuffer Object. */ -#define GL_FRAMEBUFFER 0x8D40 -#define GL_RENDERBUFFER 0x8D41 - -#define GL_RGBA4 0x8056 -#define GL_RGB5_A1 0x8057 -#define GL_RGB565 0x8D62 -#define GL_DEPTH_COMPONENT16 0x81A5 -#define GL_STENCIL_INDEX8 0x8D48 - -#define GL_RENDERBUFFER_WIDTH 0x8D42 -#define GL_RENDERBUFFER_HEIGHT 0x8D43 -#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 -#define GL_RENDERBUFFER_RED_SIZE 0x8D50 -#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 -#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 -#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 -#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 -#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 - -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 - -#define GL_COLOR_ATTACHMENT0 0x8CE0 -#define GL_DEPTH_ATTACHMENT 0x8D00 -#define GL_STENCIL_ATTACHMENT 0x8D20 - -#define GL_NONE 0 - -#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 -#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 -#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 -#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 -#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD - -#define GL_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_RENDERBUFFER_BINDING 0x8CA7 -#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 - -#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +#define GL_FRAMEBUFFER 0x8D40 +#define GL_RENDERBUFFER 0x8D41 + +#define GL_RGBA4 0x8056 +#define GL_RGB5_A1 0x8057 +#define GL_RGB565 0x8D62 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_STENCIL_INDEX8 0x8D48 + +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 + +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 + +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_STENCIL_ATTACHMENT 0x8D20 + +#define GL_NONE 0 + +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD + +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 + +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 /* OpenGL ES 3.0 */ -#define GL_READ_BUFFER 0x0C02 -#define GL_UNPACK_ROW_LENGTH 0x0CF2 -#define GL_UNPACK_SKIP_ROWS 0x0CF3 -#define GL_UNPACK_SKIP_PIXELS 0x0CF4 -#define GL_PACK_ROW_LENGTH 0x0D02 -#define GL_PACK_SKIP_ROWS 0x0D03 -#define GL_PACK_SKIP_PIXELS 0x0D04 -#define GL_COLOR 0x1800 -#define GL_DEPTH 0x1801 -#define GL_STENCIL 0x1802 -#define GL_RED 0x1903 -#define GL_RGB8 0x8051 -#define GL_RGBA8 0x8058 -#define GL_RGB10_A2 0x8059 -#define GL_TEXTURE_BINDING_3D 0x806A -#define GL_UNPACK_SKIP_IMAGES 0x806D -#define GL_UNPACK_IMAGE_HEIGHT 0x806E -#define GL_TEXTURE_3D 0x806F -#define GL_TEXTURE_WRAP_R 0x8072 -#define GL_MAX_3D_TEXTURE_SIZE 0x8073 -#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 -#define GL_MAX_ELEMENTS_VERTICES 0x80E8 -#define GL_MAX_ELEMENTS_INDICES 0x80E9 -#define GL_TEXTURE_MIN_LOD 0x813A -#define GL_TEXTURE_MAX_LOD 0x813B -#define GL_TEXTURE_BASE_LEVEL 0x813C -#define GL_TEXTURE_MAX_LEVEL 0x813D -#define GL_MIN 0x8007 -#define GL_MAX 0x8008 -#define GL_DEPTH_COMPONENT24 0x81A6 -#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD -#define GL_TEXTURE_COMPARE_MODE 0x884C -#define GL_TEXTURE_COMPARE_FUNC 0x884D -#define GL_CURRENT_QUERY 0x8865 -#define GL_QUERY_RESULT 0x8866 -#define GL_QUERY_RESULT_AVAILABLE 0x8867 -#define GL_BUFFER_MAPPED 0x88BC -#define GL_BUFFER_MAP_POINTER 0x88BD -#define GL_STREAM_READ 0x88E1 -#define GL_STREAM_COPY 0x88E2 -#define GL_STATIC_READ 0x88E5 -#define GL_STATIC_COPY 0x88E6 -#define GL_DYNAMIC_READ 0x88E9 -#define GL_DYNAMIC_COPY 0x88EA -#define GL_MAX_DRAW_BUFFERS 0x8824 -#define GL_DRAW_BUFFER0 0x8825 -#define GL_DRAW_BUFFER1 0x8826 -#define GL_DRAW_BUFFER2 0x8827 -#define GL_DRAW_BUFFER3 0x8828 -#define GL_DRAW_BUFFER4 0x8829 -#define GL_DRAW_BUFFER5 0x882A -#define GL_DRAW_BUFFER6 0x882B -#define GL_DRAW_BUFFER7 0x882C -#define GL_DRAW_BUFFER8 0x882D -#define GL_DRAW_BUFFER9 0x882E -#define GL_DRAW_BUFFER10 0x882F -#define GL_DRAW_BUFFER11 0x8830 -#define GL_DRAW_BUFFER12 0x8831 -#define GL_DRAW_BUFFER13 0x8832 -#define GL_DRAW_BUFFER14 0x8833 -#define GL_DRAW_BUFFER15 0x8834 -#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 -#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A -#define GL_SAMPLER_3D 0x8B5F -#define GL_SAMPLER_2D_SHADOW 0x8B62 -#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B -#define GL_PIXEL_PACK_BUFFER 0x88EB -#define GL_PIXEL_UNPACK_BUFFER 0x88EC -#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED -#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF -#define GL_FLOAT_MAT2x3 0x8B65 -#define GL_FLOAT_MAT2x4 0x8B66 -#define GL_FLOAT_MAT3x2 0x8B67 -#define GL_FLOAT_MAT3x4 0x8B68 -#define GL_FLOAT_MAT4x2 0x8B69 -#define GL_FLOAT_MAT4x3 0x8B6A -#define GL_SRGB 0x8C40 -#define GL_SRGB8 0x8C41 -#define GL_SRGB8_ALPHA8 0x8C43 -#define GL_COMPARE_REF_TO_TEXTURE 0x884E -#define GL_MAJOR_VERSION 0x821B -#define GL_MINOR_VERSION 0x821C -#define GL_NUM_EXTENSIONS 0x821D -#define GL_RGBA32F 0x8814 -#define GL_RGB32F 0x8815 -#define GL_RGBA16F 0x881A -#define GL_RGB16F 0x881B -#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD -#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF -#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 -#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 -#define GL_MAX_VARYING_COMPONENTS 0x8B4B -#define GL_TEXTURE_2D_ARRAY 0x8C1A -#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D -#define GL_R11F_G11F_B10F 0x8C3A -#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B -#define GL_RGB9_E5 0x8C3D -#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E -#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 -#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 -#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 -#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 -#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 -#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 -#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_READ_BUFFER 0x0C02 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_COLOR 0x1800 +#define GL_DEPTH 0x1801 +#define GL_STENCIL 0x1802 +#define GL_RED 0x1903 +#define GL_RGB8 0x8051 +#define GL_RGBA8 0x8058 +#define GL_RGB10_A2 0x8059 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_MAJOR_VERSION 0x821B +#define GL_MINOR_VERSION 0x821C +#define GL_NUM_EXTENSIONS 0x821D +#define GL_RGBA32F 0x8814 +#define GL_RGB32F 0x8815 +#define GL_RGBA16F 0x881A +#define GL_RGB16F 0x881B +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_RGB9_E5 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_RASTERIZER_DISCARD 0x8C89 #define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B -#define GL_INTERLEAVED_ATTRIBS 0x8C8C -#define GL_SEPARATE_ATTRIBS 0x8C8D -#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E -#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F -#define GL_RGBA32UI 0x8D70 -#define GL_RGB32UI 0x8D71 -#define GL_RGBA16UI 0x8D76 -#define GL_RGB16UI 0x8D77 -#define GL_RGBA8UI 0x8D7C -#define GL_RGB8UI 0x8D7D -#define GL_RGBA32I 0x8D82 -#define GL_RGB32I 0x8D83 -#define GL_RGBA16I 0x8D88 -#define GL_RGB16I 0x8D89 -#define GL_RGBA8I 0x8D8E -#define GL_RGB8I 0x8D8F -#define GL_RED_INTEGER 0x8D94 -#define GL_RGB_INTEGER 0x8D98 -#define GL_RGBA_INTEGER 0x8D99 -#define GL_SAMPLER_2D_ARRAY 0x8DC1 -#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 -#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 -#define GL_UNSIGNED_INT_VEC2 0x8DC6 -#define GL_UNSIGNED_INT_VEC3 0x8DC7 -#define GL_UNSIGNED_INT_VEC4 0x8DC8 -#define GL_INT_SAMPLER_2D 0x8DCA -#define GL_INT_SAMPLER_3D 0x8DCB -#define GL_INT_SAMPLER_CUBE 0x8DCC -#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF -#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 -#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 -#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 -#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 -#define GL_BUFFER_ACCESS_FLAGS 0x911F -#define GL_BUFFER_MAP_LENGTH 0x9120 -#define GL_BUFFER_MAP_OFFSET 0x9121 -#define GL_DEPTH_COMPONENT32F 0x8CAC -#define GL_DEPTH32F_STENCIL8 0x8CAD -#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD -#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 -#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 -#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 -#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 -#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 -#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 -#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 -#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 -#define GL_FRAMEBUFFER_DEFAULT 0x8218 -#define GL_FRAMEBUFFER_UNDEFINED 0x8219 -#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A -#define GL_DEPTH_STENCIL 0x84F9 -#define GL_UNSIGNED_INT_24_8 0x84FA -#define GL_DEPTH24_STENCIL8 0x88F0 -#define GL_UNSIGNED_NORMALIZED 0x8C17 -#define GL_DRAW_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING -#define GL_READ_FRAMEBUFFER 0x8CA8 -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA -#define GL_RENDERBUFFER_SAMPLES 0x8CAB -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 -#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF -#define GL_COLOR_ATTACHMENT1 0x8CE1 -#define GL_COLOR_ATTACHMENT2 0x8CE2 -#define GL_COLOR_ATTACHMENT3 0x8CE3 -#define GL_COLOR_ATTACHMENT4 0x8CE4 -#define GL_COLOR_ATTACHMENT5 0x8CE5 -#define GL_COLOR_ATTACHMENT6 0x8CE6 -#define GL_COLOR_ATTACHMENT7 0x8CE7 -#define GL_COLOR_ATTACHMENT8 0x8CE8 -#define GL_COLOR_ATTACHMENT9 0x8CE9 -#define GL_COLOR_ATTACHMENT10 0x8CEA -#define GL_COLOR_ATTACHMENT11 0x8CEB -#define GL_COLOR_ATTACHMENT12 0x8CEC -#define GL_COLOR_ATTACHMENT13 0x8CED -#define GL_COLOR_ATTACHMENT14 0x8CEE -#define GL_COLOR_ATTACHMENT15 0x8CEF -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 -#define GL_MAX_SAMPLES 0x8D57 -#define GL_HALF_FLOAT 0x140B -#define GL_MAP_READ_BIT 0x0001 -#define GL_MAP_WRITE_BIT 0x0002 -#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 -#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 -#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 -#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 -#define GL_RG 0x8227 -#define GL_RG_INTEGER 0x8228 -#define GL_R8 0x8229 -#define GL_RG8 0x822B -#define GL_R16F 0x822D -#define GL_R32F 0x822E -#define GL_RG16F 0x822F -#define GL_RG32F 0x8230 -#define GL_R8I 0x8231 -#define GL_R8UI 0x8232 -#define GL_R16I 0x8233 -#define GL_R16UI 0x8234 -#define GL_R32I 0x8235 -#define GL_R32UI 0x8236 -#define GL_RG8I 0x8237 -#define GL_RG8UI 0x8238 -#define GL_RG16I 0x8239 -#define GL_RG16UI 0x823A -#define GL_RG32I 0x823B -#define GL_RG32UI 0x823C -#define GL_VERTEX_ARRAY_BINDING 0x85B5 -#define GL_R8_SNORM 0x8F94 -#define GL_RG8_SNORM 0x8F95 -#define GL_RGB8_SNORM 0x8F96 -#define GL_RGBA8_SNORM 0x8F97 -#define GL_SIGNED_NORMALIZED 0x8F9C -#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 -#define GL_COPY_READ_BUFFER 0x8F36 -#define GL_COPY_WRITE_BUFFER 0x8F37 -#define GL_COPY_READ_BUFFER_BINDING GL_COPY_READ_BUFFER -#define GL_COPY_WRITE_BUFFER_BINDING GL_COPY_WRITE_BUFFER -#define GL_UNIFORM_BUFFER 0x8A11 -#define GL_UNIFORM_BUFFER_BINDING 0x8A28 -#define GL_UNIFORM_BUFFER_START 0x8A29 -#define GL_UNIFORM_BUFFER_SIZE 0x8A2A -#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B -#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D -#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E -#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F -#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 -#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 -#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 -#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 -#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 -#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 -#define GL_UNIFORM_TYPE 0x8A37 -#define GL_UNIFORM_SIZE 0x8A38 -#define GL_UNIFORM_NAME_LENGTH 0x8A39 -#define GL_UNIFORM_BLOCK_INDEX 0x8A3A -#define GL_UNIFORM_OFFSET 0x8A3B -#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C -#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D -#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E -#define GL_UNIFORM_BLOCK_BINDING 0x8A3F -#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 -#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 -#define GL_INVALID_INDEX 0xFFFFFFFFu -#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 -#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 -#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 -#define GL_OBJECT_TYPE 0x9112 -#define GL_SYNC_CONDITION 0x9113 -#define GL_SYNC_STATUS 0x9114 -#define GL_SYNC_FLAGS 0x9115 -#define GL_SYNC_FENCE 0x9116 -#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 -#define GL_UNSIGNALED 0x9118 -#define GL_SIGNALED 0x9119 -#define GL_ALREADY_SIGNALED 0x911A -#define GL_TIMEOUT_EXPIRED 0x911B -#define GL_CONDITION_SATISFIED 0x911C -#define GL_WAIT_FAILED 0x911D -#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 -#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull -#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE -#define GL_ANY_SAMPLES_PASSED 0x8C2F -#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A -#define GL_SAMPLER_BINDING 0x8919 -#define GL_RGB10_A2UI 0x906F -#define GL_TEXTURE_SWIZZLE_R 0x8E42 -#define GL_TEXTURE_SWIZZLE_G 0x8E43 -#define GL_TEXTURE_SWIZZLE_B 0x8E44 -#define GL_TEXTURE_SWIZZLE_A 0x8E45 -#define GL_GREEN 0x1904 -#define GL_BLUE 0x1905 -#define GL_INT_2_10_10_10_REV 0x8D9F -#define GL_TRANSFORM_FEEDBACK 0x8E22 -#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 -#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 -#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 -#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 -#define GL_PROGRAM_BINARY_LENGTH 0x8741 -#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE -#define GL_PROGRAM_BINARY_FORMATS 0x87FF -#define GL_COMPRESSED_R11_EAC 0x9270 -#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 -#define GL_COMPRESSED_RG11_EAC 0x9272 -#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 -#define GL_COMPRESSED_RGB8_ETC2 0x9274 -#define GL_COMPRESSED_SRGB8_ETC2 0x9275 -#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 -#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 -#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 -#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 -#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F -#define GL_MAX_ELEMENT_INDEX 0x8D6B -#define GL_NUM_SAMPLE_COUNTS 0x9380 -#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_RGBA32UI 0x8D70 +#define GL_RGB32UI 0x8D71 +#define GL_RGBA16UI 0x8D76 +#define GL_RGB16UI 0x8D77 +#define GL_RGBA8UI 0x8D7C +#define GL_RGB8UI 0x8D7D +#define GL_RGBA32I 0x8D82 +#define GL_RGB32I 0x8D83 +#define GL_RGBA16I 0x8D88 +#define GL_RGB16I 0x8D89 +#define GL_RGBA8I 0x8D8E +#define GL_RGB8I 0x8D8F +#define GL_RED_INTEGER 0x8D94 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RGBA_INTEGER 0x8D99 +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_DRAW_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_HALF_FLOAT 0x140B +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +#define GL_RG 0x8227 +#define GL_RG_INTEGER 0x8228 +#define GL_R8 0x8229 +#define GL_RG8 0x822B +#define GL_R16F 0x822D +#define GL_R32F 0x822E +#define GL_RG16F 0x822F +#define GL_RG32F 0x8230 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_COPY_READ_BUFFER_BINDING GL_COPY_READ_BUFFER +#define GL_COPY_WRITE_BUFFER_BINDING GL_COPY_WRITE_BUFFER +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_INVALID_INDEX 0xFFFFFFFFu +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_OBJECT_TYPE 0x9112 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_STATUS 0x9114 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_UNSIGNALED 0x9118 +#define GL_SIGNALED 0x9119 +#define GL_ALREADY_SIGNALED 0x911A +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_CONDITION_SATISFIED 0x911C +#define GL_WAIT_FAILED 0x911D +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A +#define GL_SAMPLER_BINDING 0x8919 +#define GL_RGB10_A2UI 0x906F +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_GREEN 0x1904 +#define GL_BLUE 0x1905 +#define GL_INT_2_10_10_10_REV 0x8D9F +#define GL_TRANSFORM_FEEDBACK 0x8E22 +#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 +#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 +#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 +#define GL_PROGRAM_BINARY_LENGTH 0x8741 +#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE +#define GL_PROGRAM_BINARY_FORMATS 0x87FF +#define GL_COMPRESSED_R11_EAC 0x9270 +#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 +#define GL_COMPRESSED_RG11_EAC 0x9272 +#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 +#define GL_COMPRESSED_RGB8_ETC2 0x9274 +#define GL_COMPRESSED_SRGB8_ETC2 0x9275 +#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 +#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 +#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 +#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 +#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F +#define GL_MAX_ELEMENT_INDEX 0x8D6B +#define GL_NUM_SAMPLE_COUNTS 0x9380 +#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF /* OpenGL ES Extensions */ -#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE diff --git a/src/mbgl/gl/draw_scope_resource.hpp b/src/mbgl/gl/draw_scope_resource.hpp index 4c446cd4fe7..298aaf29bbd 100644 --- a/src/mbgl/gl/draw_scope_resource.hpp +++ b/src/mbgl/gl/draw_scope_resource.hpp @@ -8,8 +8,8 @@ namespace gl { class DrawScopeResource : public gfx::DrawScopeResource { public: - DrawScopeResource(VertexArray&& vertexArray_) : vertexArray(std::move(vertexArray_)) { - } + DrawScopeResource(VertexArray&& vertexArray_) + : vertexArray(std::move(vertexArray_)) {} VertexArray vertexArray; }; diff --git a/src/mbgl/gl/enum.cpp b/src/mbgl/gl/enum.cpp index 899fb496cc4..4ee11e693cd 100644 --- a/src/mbgl/gl/enum.cpp +++ b/src/mbgl/gl/enum.cpp @@ -8,13 +8,20 @@ namespace gl { template <> platform::GLenum Enum::to(const gfx::DrawModeType value) { switch (value) { - case gfx::DrawModeType::Points: return GL_POINTS; - case gfx::DrawModeType::Lines: return GL_LINES; - case gfx::DrawModeType::LineLoop: return GL_LINE_LOOP; - case gfx::DrawModeType::LineStrip: return GL_LINE_STRIP; - case gfx::DrawModeType::Triangles: return GL_TRIANGLES; - case gfx::DrawModeType::TriangleStrip: return GL_TRIANGLE_STRIP; - case gfx::DrawModeType::TriangleFan: return GL_TRIANGLE_FAN; + case gfx::DrawModeType::Points: + return GL_POINTS; + case gfx::DrawModeType::Lines: + return GL_LINES; + case gfx::DrawModeType::LineLoop: + return GL_LINE_LOOP; + case gfx::DrawModeType::LineStrip: + return GL_LINE_STRIP; + case gfx::DrawModeType::Triangles: + return GL_TRIANGLES; + case gfx::DrawModeType::TriangleStrip: + return GL_TRIANGLE_STRIP; + case gfx::DrawModeType::TriangleFan: + return GL_TRIANGLE_FAN; } return GL_INVALID_ENUM; } @@ -22,9 +29,12 @@ platform::GLenum Enum::to(const gfx::DrawModeType value) { template <> gfx::ColorBlendEquationType Enum::from(const platform::GLint value) { switch (value) { - case GL_FUNC_ADD: return gfx::ColorBlendEquationType::Add; - case GL_FUNC_SUBTRACT: return gfx::ColorBlendEquationType::Subtract; - case GL_FUNC_REVERSE_SUBTRACT: return gfx::ColorBlendEquationType::ReverseSubtract; + case GL_FUNC_ADD: + return gfx::ColorBlendEquationType::Add; + case GL_FUNC_SUBTRACT: + return gfx::ColorBlendEquationType::Subtract; + case GL_FUNC_REVERSE_SUBTRACT: + return gfx::ColorBlendEquationType::ReverseSubtract; } return {}; } @@ -32,9 +42,12 @@ gfx::ColorBlendEquationType Enum::from(const platfo template <> platform::GLenum Enum::to(const gfx::ColorBlendEquationType value) { switch (value) { - case gfx::ColorBlendEquationType::Add: return GL_FUNC_ADD; - case gfx::ColorBlendEquationType::Subtract: return GL_FUNC_SUBTRACT; - case gfx::ColorBlendEquationType::ReverseSubtract: return GL_FUNC_REVERSE_SUBTRACT; + case gfx::ColorBlendEquationType::Add: + return GL_FUNC_ADD; + case gfx::ColorBlendEquationType::Subtract: + return GL_FUNC_SUBTRACT; + case gfx::ColorBlendEquationType::ReverseSubtract: + return GL_FUNC_REVERSE_SUBTRACT; } return GL_INVALID_ENUM; } @@ -42,21 +55,36 @@ platform::GLenum Enum::to(const gfx::ColorBlendEqua template <> gfx::ColorBlendFactorType Enum::from(const platform::GLint value) { switch (value) { - case GL_ZERO: return gfx::ColorBlendFactorType::Zero; - case GL_ONE: return gfx::ColorBlendFactorType::One; - case GL_SRC_COLOR: return gfx::ColorBlendFactorType::SrcColor; - case GL_ONE_MINUS_SRC_COLOR: return gfx::ColorBlendFactorType::OneMinusSrcColor; - case GL_DST_COLOR: return gfx::ColorBlendFactorType::DstColor; - case GL_ONE_MINUS_DST_COLOR: return gfx::ColorBlendFactorType::OneMinusDstColor; - case GL_SRC_ALPHA: return gfx::ColorBlendFactorType::SrcAlpha; - case GL_ONE_MINUS_SRC_ALPHA: return gfx::ColorBlendFactorType::OneMinusSrcAlpha; - case GL_DST_ALPHA: return gfx::ColorBlendFactorType::DstAlpha; - case GL_ONE_MINUS_DST_ALPHA: return gfx::ColorBlendFactorType::OneMinusDstAlpha; - case GL_CONSTANT_COLOR: return gfx::ColorBlendFactorType::ConstantColor; - case GL_ONE_MINUS_CONSTANT_COLOR: return gfx::ColorBlendFactorType::OneMinusConstantColor; - case GL_CONSTANT_ALPHA: return gfx::ColorBlendFactorType::ConstantAlpha; - case GL_ONE_MINUS_CONSTANT_ALPHA: return gfx::ColorBlendFactorType::OneMinusConstantAlpha; - case GL_SRC_ALPHA_SATURATE: return gfx::ColorBlendFactorType::SrcAlphaSaturate; + case GL_ZERO: + return gfx::ColorBlendFactorType::Zero; + case GL_ONE: + return gfx::ColorBlendFactorType::One; + case GL_SRC_COLOR: + return gfx::ColorBlendFactorType::SrcColor; + case GL_ONE_MINUS_SRC_COLOR: + return gfx::ColorBlendFactorType::OneMinusSrcColor; + case GL_DST_COLOR: + return gfx::ColorBlendFactorType::DstColor; + case GL_ONE_MINUS_DST_COLOR: + return gfx::ColorBlendFactorType::OneMinusDstColor; + case GL_SRC_ALPHA: + return gfx::ColorBlendFactorType::SrcAlpha; + case GL_ONE_MINUS_SRC_ALPHA: + return gfx::ColorBlendFactorType::OneMinusSrcAlpha; + case GL_DST_ALPHA: + return gfx::ColorBlendFactorType::DstAlpha; + case GL_ONE_MINUS_DST_ALPHA: + return gfx::ColorBlendFactorType::OneMinusDstAlpha; + case GL_CONSTANT_COLOR: + return gfx::ColorBlendFactorType::ConstantColor; + case GL_ONE_MINUS_CONSTANT_COLOR: + return gfx::ColorBlendFactorType::OneMinusConstantColor; + case GL_CONSTANT_ALPHA: + return gfx::ColorBlendFactorType::ConstantAlpha; + case GL_ONE_MINUS_CONSTANT_ALPHA: + return gfx::ColorBlendFactorType::OneMinusConstantAlpha; + case GL_SRC_ALPHA_SATURATE: + return gfx::ColorBlendFactorType::SrcAlphaSaturate; } return {}; } @@ -64,21 +92,36 @@ gfx::ColorBlendFactorType Enum::from(const platform:: template <> platform::GLenum Enum::to(const gfx::ColorBlendFactorType value) { switch (value) { - case gfx::ColorBlendFactorType::Zero: return GL_ZERO; - case gfx::ColorBlendFactorType::One: return GL_ONE; - case gfx::ColorBlendFactorType::SrcColor: return GL_SRC_COLOR; - case gfx::ColorBlendFactorType::OneMinusSrcColor: return GL_ONE_MINUS_SRC_COLOR; - case gfx::ColorBlendFactorType::DstColor: return GL_DST_COLOR; - case gfx::ColorBlendFactorType::OneMinusDstColor: return GL_ONE_MINUS_DST_COLOR; - case gfx::ColorBlendFactorType::SrcAlpha: return GL_SRC_ALPHA; - case gfx::ColorBlendFactorType::OneMinusSrcAlpha: return GL_ONE_MINUS_SRC_ALPHA; - case gfx::ColorBlendFactorType::DstAlpha: return GL_DST_ALPHA; - case gfx::ColorBlendFactorType::OneMinusDstAlpha: return GL_ONE_MINUS_DST_ALPHA; - case gfx::ColorBlendFactorType::ConstantColor: return GL_CONSTANT_COLOR; - case gfx::ColorBlendFactorType::OneMinusConstantColor: return GL_ONE_MINUS_CONSTANT_COLOR; - case gfx::ColorBlendFactorType::ConstantAlpha: return GL_CONSTANT_ALPHA; - case gfx::ColorBlendFactorType::OneMinusConstantAlpha: return GL_ONE_MINUS_CONSTANT_ALPHA; - case gfx::ColorBlendFactorType::SrcAlphaSaturate: return GL_SRC_ALPHA_SATURATE; + case gfx::ColorBlendFactorType::Zero: + return GL_ZERO; + case gfx::ColorBlendFactorType::One: + return GL_ONE; + case gfx::ColorBlendFactorType::SrcColor: + return GL_SRC_COLOR; + case gfx::ColorBlendFactorType::OneMinusSrcColor: + return GL_ONE_MINUS_SRC_COLOR; + case gfx::ColorBlendFactorType::DstColor: + return GL_DST_COLOR; + case gfx::ColorBlendFactorType::OneMinusDstColor: + return GL_ONE_MINUS_DST_COLOR; + case gfx::ColorBlendFactorType::SrcAlpha: + return GL_SRC_ALPHA; + case gfx::ColorBlendFactorType::OneMinusSrcAlpha: + return GL_ONE_MINUS_SRC_ALPHA; + case gfx::ColorBlendFactorType::DstAlpha: + return GL_DST_ALPHA; + case gfx::ColorBlendFactorType::OneMinusDstAlpha: + return GL_ONE_MINUS_DST_ALPHA; + case gfx::ColorBlendFactorType::ConstantColor: + return GL_CONSTANT_COLOR; + case gfx::ColorBlendFactorType::OneMinusConstantColor: + return GL_ONE_MINUS_CONSTANT_COLOR; + case gfx::ColorBlendFactorType::ConstantAlpha: + return GL_CONSTANT_ALPHA; + case gfx::ColorBlendFactorType::OneMinusConstantAlpha: + return GL_ONE_MINUS_CONSTANT_ALPHA; + case gfx::ColorBlendFactorType::SrcAlphaSaturate: + return GL_SRC_ALPHA_SATURATE; } return GL_INVALID_ENUM; } @@ -86,14 +129,22 @@ platform::GLenum Enum::to(const gfx::ColorBlendFactor template <> gfx::DepthFunctionType Enum::from(const platform::GLint value) { switch (value) { - case GL_NEVER: return gfx::DepthFunctionType::Never; - case GL_LESS: return gfx::DepthFunctionType::Less; - case GL_EQUAL: return gfx::DepthFunctionType::Equal; - case GL_LEQUAL: return gfx::DepthFunctionType::LessEqual; - case GL_GREATER: return gfx::DepthFunctionType::Greater; - case GL_NOTEQUAL: return gfx::DepthFunctionType::NotEqual; - case GL_GEQUAL: return gfx::DepthFunctionType::GreaterEqual; - case GL_ALWAYS: return gfx::DepthFunctionType::Always; + case GL_NEVER: + return gfx::DepthFunctionType::Never; + case GL_LESS: + return gfx::DepthFunctionType::Less; + case GL_EQUAL: + return gfx::DepthFunctionType::Equal; + case GL_LEQUAL: + return gfx::DepthFunctionType::LessEqual; + case GL_GREATER: + return gfx::DepthFunctionType::Greater; + case GL_NOTEQUAL: + return gfx::DepthFunctionType::NotEqual; + case GL_GEQUAL: + return gfx::DepthFunctionType::GreaterEqual; + case GL_ALWAYS: + return gfx::DepthFunctionType::Always; } return {}; } @@ -101,14 +152,22 @@ gfx::DepthFunctionType Enum::from(const platform::GLint template <> platform::GLenum Enum::to(const gfx::DepthFunctionType value) { switch (value) { - case gfx::DepthFunctionType::Never: return GL_NEVER; - case gfx::DepthFunctionType::Less: return GL_LESS; - case gfx::DepthFunctionType::Equal: return GL_EQUAL; - case gfx::DepthFunctionType::LessEqual: return GL_LEQUAL; - case gfx::DepthFunctionType::Greater: return GL_GREATER; - case gfx::DepthFunctionType::NotEqual: return GL_NOTEQUAL; - case gfx::DepthFunctionType::GreaterEqual: return GL_GEQUAL; - case gfx::DepthFunctionType::Always: return GL_ALWAYS; + case gfx::DepthFunctionType::Never: + return GL_NEVER; + case gfx::DepthFunctionType::Less: + return GL_LESS; + case gfx::DepthFunctionType::Equal: + return GL_EQUAL; + case gfx::DepthFunctionType::LessEqual: + return GL_LEQUAL; + case gfx::DepthFunctionType::Greater: + return GL_GREATER; + case gfx::DepthFunctionType::NotEqual: + return GL_NOTEQUAL; + case gfx::DepthFunctionType::GreaterEqual: + return GL_GEQUAL; + case gfx::DepthFunctionType::Always: + return GL_ALWAYS; } return GL_INVALID_ENUM; } @@ -126,14 +185,22 @@ platform::GLboolean Enum::to(const gfx::DepthMaskType value) template <> gfx::StencilFunctionType Enum::from(const platform::GLint value) { switch (value) { - case GL_NEVER: return gfx::StencilFunctionType::Never; - case GL_LESS: return gfx::StencilFunctionType::Less; - case GL_EQUAL: return gfx::StencilFunctionType::Equal; - case GL_LEQUAL: return gfx::StencilFunctionType::LessEqual; - case GL_GREATER: return gfx::StencilFunctionType::Greater; - case GL_NOTEQUAL: return gfx::StencilFunctionType::NotEqual; - case GL_GEQUAL: return gfx::StencilFunctionType::GreaterEqual; - case GL_ALWAYS: return gfx::StencilFunctionType::Always; + case GL_NEVER: + return gfx::StencilFunctionType::Never; + case GL_LESS: + return gfx::StencilFunctionType::Less; + case GL_EQUAL: + return gfx::StencilFunctionType::Equal; + case GL_LEQUAL: + return gfx::StencilFunctionType::LessEqual; + case GL_GREATER: + return gfx::StencilFunctionType::Greater; + case GL_NOTEQUAL: + return gfx::StencilFunctionType::NotEqual; + case GL_GEQUAL: + return gfx::StencilFunctionType::GreaterEqual; + case GL_ALWAYS: + return gfx::StencilFunctionType::Always; } return {}; } @@ -141,14 +208,22 @@ gfx::StencilFunctionType Enum::from(const platform::GL template <> platform::GLenum Enum::to(const gfx::StencilFunctionType value) { switch (value) { - case gfx::StencilFunctionType::Never: return GL_NEVER; - case gfx::StencilFunctionType::Less: return GL_LESS; - case gfx::StencilFunctionType::Equal: return GL_EQUAL; - case gfx::StencilFunctionType::LessEqual: return GL_LEQUAL; - case gfx::StencilFunctionType::Greater: return GL_GREATER; - case gfx::StencilFunctionType::NotEqual: return GL_NOTEQUAL; - case gfx::StencilFunctionType::GreaterEqual: return GL_GEQUAL; - case gfx::StencilFunctionType::Always: return GL_ALWAYS; + case gfx::StencilFunctionType::Never: + return GL_NEVER; + case gfx::StencilFunctionType::Less: + return GL_LESS; + case gfx::StencilFunctionType::Equal: + return GL_EQUAL; + case gfx::StencilFunctionType::LessEqual: + return GL_LEQUAL; + case gfx::StencilFunctionType::Greater: + return GL_GREATER; + case gfx::StencilFunctionType::NotEqual: + return GL_NOTEQUAL; + case gfx::StencilFunctionType::GreaterEqual: + return GL_GEQUAL; + case gfx::StencilFunctionType::Always: + return GL_ALWAYS; } return GL_INVALID_ENUM; } @@ -156,14 +231,22 @@ platform::GLenum Enum::to(const gfx::StencilFunctionTy template <> gfx::StencilOpType Enum::from(const platform::GLint value) { switch (value) { - case GL_KEEP: return gfx::StencilOpType::Keep; - case GL_ZERO: return gfx::StencilOpType::Zero; - case GL_REPLACE: return gfx::StencilOpType::Replace; - case GL_INCR: return gfx::StencilOpType::Increment; - case GL_INCR_WRAP: return gfx::StencilOpType::IncrementWrap; - case GL_DECR: return gfx::StencilOpType::Decrement; - case GL_DECR_WRAP: return gfx::StencilOpType::DecrementWrap; - case GL_INVERT: return gfx::StencilOpType::Invert; + case GL_KEEP: + return gfx::StencilOpType::Keep; + case GL_ZERO: + return gfx::StencilOpType::Zero; + case GL_REPLACE: + return gfx::StencilOpType::Replace; + case GL_INCR: + return gfx::StencilOpType::Increment; + case GL_INCR_WRAP: + return gfx::StencilOpType::IncrementWrap; + case GL_DECR: + return gfx::StencilOpType::Decrement; + case GL_DECR_WRAP: + return gfx::StencilOpType::DecrementWrap; + case GL_INVERT: + return gfx::StencilOpType::Invert; } return {}; } @@ -171,14 +254,22 @@ gfx::StencilOpType Enum::from(const platform::GLint value) { template <> platform::GLenum Enum::to(const gfx::StencilOpType value) { switch (value) { - case gfx::StencilOpType::Keep: return GL_KEEP; - case gfx::StencilOpType::Zero: return GL_ZERO; - case gfx::StencilOpType::Replace: return GL_REPLACE; - case gfx::StencilOpType::Increment: return GL_INCR; - case gfx::StencilOpType::IncrementWrap: return GL_INCR_WRAP; - case gfx::StencilOpType::Decrement: return GL_DECR; - case gfx::StencilOpType::DecrementWrap: return GL_DECR_WRAP; - case gfx::StencilOpType::Invert: return GL_INVERT; + case gfx::StencilOpType::Keep: + return GL_KEEP; + case gfx::StencilOpType::Zero: + return GL_ZERO; + case gfx::StencilOpType::Replace: + return GL_REPLACE; + case gfx::StencilOpType::Increment: + return GL_INCR; + case gfx::StencilOpType::IncrementWrap: + return GL_INCR_WRAP; + case gfx::StencilOpType::Decrement: + return GL_DECR; + case gfx::StencilOpType::DecrementWrap: + return GL_DECR_WRAP; + case gfx::StencilOpType::Invert: + return GL_INVERT; } return GL_INVALID_ENUM; } @@ -186,9 +277,12 @@ platform::GLenum Enum::to(const gfx::StencilOpType value) { template <> gfx::CullFaceSideType Enum::from(const platform::GLint value) { switch (value) { - case GL_FRONT: return gfx::CullFaceSideType::Front; - case GL_BACK: return gfx::CullFaceSideType::Back; - case GL_FRONT_AND_BACK: return gfx::CullFaceSideType::FrontAndBack; + case GL_FRONT: + return gfx::CullFaceSideType::Front; + case GL_BACK: + return gfx::CullFaceSideType::Back; + case GL_FRONT_AND_BACK: + return gfx::CullFaceSideType::FrontAndBack; } return {}; } @@ -196,9 +290,12 @@ gfx::CullFaceSideType Enum::from(const platform::GLint va template <> platform::GLenum Enum::to(const gfx::CullFaceSideType value) { switch (value) { - case gfx::CullFaceSideType::Front: return GL_FRONT; - case gfx::CullFaceSideType::Back: return GL_BACK; - case gfx::CullFaceSideType::FrontAndBack: return GL_FRONT_AND_BACK; + case gfx::CullFaceSideType::Front: + return GL_FRONT; + case gfx::CullFaceSideType::Back: + return GL_BACK; + case gfx::CullFaceSideType::FrontAndBack: + return GL_FRONT_AND_BACK; } return GL_INVALID_ENUM; } @@ -206,8 +303,10 @@ platform::GLenum Enum::to(const gfx::CullFaceSideType val template <> gfx::CullFaceWindingType Enum::from(const platform::GLint value) { switch (value) { - case GL_CW: return gfx::CullFaceWindingType::Clockwise; - case GL_CCW: return gfx::CullFaceWindingType::CounterClockwise; + case GL_CW: + return gfx::CullFaceWindingType::Clockwise; + case GL_CCW: + return gfx::CullFaceWindingType::CounterClockwise; } return {}; } @@ -215,8 +314,10 @@ gfx::CullFaceWindingType Enum::from(const platform::GL template <> platform::GLenum Enum::to(const gfx::CullFaceWindingType value) { switch (value) { - case gfx::CullFaceWindingType::Clockwise: return GL_CW; - case gfx::CullFaceWindingType::CounterClockwise: return GL_CCW; + case gfx::CullFaceWindingType::Clockwise: + return GL_CW; + case gfx::CullFaceWindingType::CounterClockwise: + return GL_CCW; } return GL_INVALID_ENUM; } @@ -224,9 +325,12 @@ platform::GLenum Enum::to(const gfx::CullFaceWindingTy template <> gfx::BufferUsageType Enum::from(const platform::GLint value) { switch (value) { - case GL_STREAM_DRAW: return gfx::BufferUsageType::StreamDraw; - case GL_STATIC_DRAW: return gfx::BufferUsageType::StaticDraw; - case GL_DYNAMIC_DRAW: return gfx::BufferUsageType::DynamicDraw; + case GL_STREAM_DRAW: + return gfx::BufferUsageType::StreamDraw; + case GL_STATIC_DRAW: + return gfx::BufferUsageType::StaticDraw; + case GL_DYNAMIC_DRAW: + return gfx::BufferUsageType::DynamicDraw; } return {}; } @@ -234,9 +338,12 @@ gfx::BufferUsageType Enum::from(const platform::GLint valu template <> platform::GLenum Enum::to(const gfx::BufferUsageType value) { switch (value) { - case gfx::BufferUsageType::StreamDraw: return GL_STREAM_DRAW; - case gfx::BufferUsageType::StaticDraw: return GL_STATIC_DRAW; - case gfx::BufferUsageType::DynamicDraw: return GL_DYNAMIC_DRAW; + case gfx::BufferUsageType::StreamDraw: + return GL_STREAM_DRAW; + case gfx::BufferUsageType::StaticDraw: + return GL_STATIC_DRAW; + case gfx::BufferUsageType::DynamicDraw: + return GL_DYNAMIC_DRAW; } return GL_INVALID_ENUM; } @@ -244,11 +351,16 @@ platform::GLenum Enum::to(const gfx::BufferUsageType value template <> gfx::TexturePixelType Enum::from(const platform::GLint value) { switch (value) { - case GL_RGBA: return gfx::TexturePixelType::RGBA; - case GL_ALPHA: return gfx::TexturePixelType::Alpha; - case GL_STENCIL_INDEX: return gfx::TexturePixelType::Stencil; - case GL_DEPTH_COMPONENT: return gfx::TexturePixelType::Depth; - case GL_LUMINANCE: return gfx::TexturePixelType::Luminance; + case GL_RGBA: + return gfx::TexturePixelType::RGBA; + case GL_ALPHA: + return gfx::TexturePixelType::Alpha; + case GL_STENCIL_INDEX: + return gfx::TexturePixelType::Stencil; + case GL_DEPTH_COMPONENT: + return gfx::TexturePixelType::Depth; + case GL_LUMINANCE: + return gfx::TexturePixelType::Luminance; } return {}; } @@ -256,19 +368,25 @@ gfx::TexturePixelType Enum::from(const platform::GLint va template <> platform::GLenum Enum::to(const gfx::TexturePixelType value) { switch (value) { - case gfx::TexturePixelType::RGBA: return GL_RGBA; - case gfx::TexturePixelType::Alpha: return GL_ALPHA; - case gfx::TexturePixelType::Stencil: return GL_STENCIL_INDEX; - case gfx::TexturePixelType::Depth: return GL_DEPTH_COMPONENT; - case gfx::TexturePixelType::Luminance: return GL_LUMINANCE; + case gfx::TexturePixelType::RGBA: + return GL_RGBA; + case gfx::TexturePixelType::Alpha: + return GL_ALPHA; + case gfx::TexturePixelType::Stencil: + return GL_STENCIL_INDEX; + case gfx::TexturePixelType::Depth: + return GL_DEPTH_COMPONENT; + case gfx::TexturePixelType::Luminance: + return GL_LUMINANCE; } return GL_INVALID_ENUM; } -template <> template<> -platform::GLenum Enum::sizedFor<>(const gfx::TexturePixelType value, - gfx::TextureChannelDataType type) -{ +template <> +template <> +platform::GLenum Enum::sizedFor<>( + const gfx::TexturePixelType value, gfx::TextureChannelDataType type +) { switch (type) { case gfx::TextureChannelDataType::UnsignedByte: { return Enum::to(value); @@ -277,7 +395,8 @@ platform::GLenum Enum::sizedFor<>(const gfx::TexturePixel switch (value) { case gfx::TexturePixelType::RGBA: return GL_RGBA16F; - default: break; + default: + break; } } } @@ -288,8 +407,10 @@ platform::GLenum Enum::sizedFor<>(const gfx::TexturePixel template <> gfx::TextureChannelDataType Enum::from(const platform::GLint value) { switch (value) { - case GL_UNSIGNED_BYTE: return gfx::TextureChannelDataType::UnsignedByte; - case GL_HALF_FLOAT: return gfx::TextureChannelDataType::HalfFloat; + case GL_UNSIGNED_BYTE: + return gfx::TextureChannelDataType::UnsignedByte; + case GL_HALF_FLOAT: + return gfx::TextureChannelDataType::HalfFloat; } return {}; } @@ -297,8 +418,10 @@ gfx::TextureChannelDataType Enum::from(const platfo template <> platform::GLenum Enum::to(const gfx::TextureChannelDataType value) { switch (value) { - case gfx::TextureChannelDataType::UnsignedByte: return GL_UNSIGNED_BYTE; - case gfx::TextureChannelDataType::HalfFloat: return GL_HALF_FLOAT; + case gfx::TextureChannelDataType::UnsignedByte: + return GL_UNSIGNED_BYTE; + case gfx::TextureChannelDataType::HalfFloat: + return GL_HALF_FLOAT; } return GL_INVALID_ENUM; } @@ -306,9 +429,12 @@ platform::GLenum Enum::to(const gfx::TextureChannel template <> gfx::RenderbufferPixelType Enum::from(const platform::GLint value) { switch (value) { - case GL_RGBA8: return gfx::RenderbufferPixelType::RGBA; - case GL_DEPTH_COMPONENT16: return gfx::RenderbufferPixelType::Depth; - case GL_DEPTH24_STENCIL8: return gfx::RenderbufferPixelType::DepthStencil; + case GL_RGBA8: + return gfx::RenderbufferPixelType::RGBA; + case GL_DEPTH_COMPONENT16: + return gfx::RenderbufferPixelType::Depth; + case GL_DEPTH24_STENCIL8: + return gfx::RenderbufferPixelType::DepthStencil; } return {}; } @@ -316,9 +442,12 @@ gfx::RenderbufferPixelType Enum::from(const platform template <> platform::GLenum Enum::to(const gfx::RenderbufferPixelType value) { switch (value) { - case gfx::RenderbufferPixelType::RGBA: return GL_RGBA8; - case gfx::RenderbufferPixelType::Depth: return GL_DEPTH_COMPONENT16; - case gfx::RenderbufferPixelType::DepthStencil: return GL_DEPTH24_STENCIL8; + case gfx::RenderbufferPixelType::RGBA: + return GL_RGBA8; + case gfx::RenderbufferPixelType::Depth: + return GL_DEPTH_COMPONENT16; + case gfx::RenderbufferPixelType::DepthStencil: + return GL_DEPTH24_STENCIL8; } return GL_INVALID_ENUM; } diff --git a/src/mbgl/gl/enum.hpp b/src/mbgl/gl/enum.hpp index d4ef3eea3e4..f662fd8516b 100644 --- a/src/mbgl/gl/enum.hpp +++ b/src/mbgl/gl/enum.hpp @@ -10,13 +10,15 @@ namespace gl { template class Enum { public: - using InType = std::conditional_t, bool>, platform::GLboolean, platform::GLint>; - using OutType = std::conditional_t, bool>, platform::GLboolean, platform::GLenum>; + using InType = + std::conditional_t, bool>, platform::GLboolean, platform::GLint>; + using OutType = + std::conditional_t, bool>, platform::GLboolean, platform::GLenum>; static T from(InType); static OutType to(T); - template + template static OutType sizedFor(T, U type); }; diff --git a/src/mbgl/gl/extension.hpp b/src/mbgl/gl/extension.hpp index 8710314ef2c..9186fab7285 100644 --- a/src/mbgl/gl/extension.hpp +++ b/src/mbgl/gl/extension.hpp @@ -15,16 +15,12 @@ class ExtensionFunction; template class ExtensionFunction { public: - ExtensionFunction(const ProcAddress ptr_) : ptr(ptr_) { - } + ExtensionFunction(const ProcAddress ptr_) + : ptr(ptr_) {} - explicit operator bool() const { - return ptr; - } + explicit operator bool() const { return ptr; } - R operator()(Args... args) const { - return (*reinterpret_cast(ptr))(std::forward(args)...); - } + R operator()(Args... args) const { return (*reinterpret_cast(ptr))(std::forward(args)...); } private: const ProcAddress ptr; diff --git a/src/mbgl/gl/index_buffer_resource.hpp b/src/mbgl/gl/index_buffer_resource.hpp index 10d9bfc8014..f3f42d3efc4 100644 --- a/src/mbgl/gl/index_buffer_resource.hpp +++ b/src/mbgl/gl/index_buffer_resource.hpp @@ -8,7 +8,9 @@ namespace gl { class IndexBufferResource : public gfx::IndexBufferResource { public: - IndexBufferResource(UniqueBuffer&& buffer_, int byteSize_) : buffer(std::move(buffer_)), byteSize(byteSize_) {} + IndexBufferResource(UniqueBuffer&& buffer_, int byteSize_) + : buffer(std::move(buffer_)), + byteSize(byteSize_) {} ~IndexBufferResource() noexcept override; UniqueBuffer buffer; diff --git a/src/mbgl/gl/offscreen_texture.cpp b/src/mbgl/gl/offscreen_texture.cpp index ab9e72a5378..0382eac6c7b 100644 --- a/src/mbgl/gl/offscreen_texture.cpp +++ b/src/mbgl/gl/offscreen_texture.cpp @@ -8,10 +8,10 @@ namespace gl { class OffscreenTextureResource final : public gl::RenderableResource { public: - OffscreenTextureResource(gl::Context& context_, - const Size size_, - const gfx::TextureChannelDataType type_) - : context(context_), size(size_), type(type_) { + OffscreenTextureResource(gl::Context& context_, const Size size_, const gfx::TextureChannelDataType type_) + : context(context_), + size(size_), + type(type_) { assert(!size.isEmpty()); } @@ -28,7 +28,7 @@ class OffscreenTextureResource final : public gl::RenderableResource { context.activeTextureUnit = 0; context.scissorTest = false; - context.viewport = { 0, 0, size }; + context.viewport = {0, 0, size}; } PremultipliedImage readStillImage() { @@ -50,11 +50,8 @@ class OffscreenTextureResource final : public gl::RenderableResource { std::optional framebuffer; }; -OffscreenTexture::OffscreenTexture(gl::Context& context, - const Size size_, - const gfx::TextureChannelDataType type) - : gfx::OffscreenTexture(size, std::make_unique(context, size_, type)) { -} +OffscreenTexture::OffscreenTexture(gl::Context& context, const Size size_, const gfx::TextureChannelDataType type) + : gfx::OffscreenTexture(size, std::make_unique(context, size_, type)) {} bool OffscreenTexture::isRenderable() { try { diff --git a/src/mbgl/gl/offscreen_texture.hpp b/src/mbgl/gl/offscreen_texture.hpp index 5f3863d3e9c..593931123f9 100644 --- a/src/mbgl/gl/offscreen_texture.hpp +++ b/src/mbgl/gl/offscreen_texture.hpp @@ -10,9 +10,9 @@ class Context; class OffscreenTexture final : public gfx::OffscreenTexture { public: - OffscreenTexture(gl::Context&, - Size size, - gfx::TextureChannelDataType type = gfx::TextureChannelDataType::UnsignedByte); + OffscreenTexture( + gl::Context&, Size size, gfx::TextureChannelDataType type = gfx::TextureChannelDataType::UnsignedByte + ); bool isRenderable() override; diff --git a/src/mbgl/gl/program.hpp b/src/mbgl/gl/program.hpp index c601652498d..f2d45e6cac4 100644 --- a/src/mbgl/gl/program.hpp +++ b/src/mbgl/gl/program.hpp @@ -31,46 +31,45 @@ class Program final : public gfx::Program { using TextureList = typename Name::TextureList; Program(ProgramParameters programParameters_) - : programParameters(std::move(programParameters_)) { - } + : programParameters(std::move(programParameters_)) {} const ProgramParameters programParameters; class Instance { public: - Instance(Context& context, - const std::initializer_list& vertexSource, - const std::initializer_list& fragmentSource) + Instance( + Context& context, + const std::initializer_list& vertexSource, + const std::initializer_list& fragmentSource + ) : program(context.createProgram( context.createShader(ShaderType::Vertex, vertexSource), context.createShader(ShaderType::Fragment, fragmentSource), - attributeLocations.getFirstAttribName())) { + attributeLocations.getFirstAttribName() + )) { attributeLocations.queryLocations(program); uniformStates.queryLocations(program); // Texture units are specified via uniforms as well, so we need query their locations textureStates.queryLocations(program); } - static std::unique_ptr - createInstance(gl::Context& context, - const ProgramParameters& programParameters, - const std::string& additionalDefines) { + static std::unique_ptr createInstance( + gl::Context& context, const ProgramParameters& programParameters, const std::string& additionalDefines + ) { // Compile the shader std::initializer_list vertexSource = { "#version 300 es\n", programParameters.getDefines().c_str(), additionalDefines.c_str(), shaders::ShaderSource::vertex, - programParameters.vertexSource(gfx::Backend::Type::OpenGL).c_str() - }; + programParameters.vertexSource(gfx::Backend::Type::OpenGL).c_str()}; std::initializer_list fragmentSource = { "#version 300 es\n", programParameters.getDefines().c_str(), additionalDefines.c_str(), shaders::ShaderSource::fragment, - programParameters.fragmentSource(gfx::Backend::Type::OpenGL).c_str() - }; + programParameters.fragmentSource(gfx::Backend::Type::OpenGL).c_str()}; return std::make_unique(context, vertexSource, fragmentSource); } @@ -81,20 +80,22 @@ class Program final : public gfx::Program { gl::TextureStates textureStates; }; - void draw(gfx::Context& genericContext, - gfx::RenderPass&, - const gfx::DrawMode& drawMode, - const gfx::DepthMode& depthMode, - const gfx::StencilMode& stencilMode, - const gfx::ColorMode& colorMode, - const gfx::CullFaceMode& cullFaceMode, - const gfx::UniformValues& uniformValues, - gfx::DrawScope& drawScope, - const gfx::AttributeBindings& attributeBindings, - const gfx::TextureBindings& textureBindings, - const gfx::IndexBuffer& indexBuffer, - std::size_t indexOffset, - std::size_t indexLength) override { + void draw( + gfx::Context& genericContext, + gfx::RenderPass&, + const gfx::DrawMode& drawMode, + const gfx::DepthMode& depthMode, + const gfx::StencilMode& stencilMode, + const gfx::ColorMode& colorMode, + const gfx::CullFaceMode& cullFaceMode, + const gfx::UniformValues& uniformValues, + gfx::DrawScope& drawScope, + const gfx::AttributeBindings& attributeBindings, + const gfx::TextureBindings& textureBindings, + const gfx::IndexBuffer& indexBuffer, + std::size_t indexOffset, + std::size_t indexLength + ) override { auto& context = static_cast(genericContext); context.setDepthMode(depthMode); @@ -106,12 +107,14 @@ class Program final : public gfx::Program { auto it = instances.find(key); if (it == instances.end()) { try { - it = instances.emplace(key, - Instance::createInstance( - context, - programParameters, - gl::AttributeKey::defines(attributeBindings) - )).first; + it = instances + .emplace( + key, + Instance::createInstance( + context, programParameters, gl::AttributeKey::defines(attributeBindings) + ) + ) + .first; } catch (const std::runtime_error& e) { Log::Error(Event::OpenGL, e.what()); return; @@ -126,13 +129,9 @@ class Program final : public gfx::Program { instance.textureStates.bind(context, textureBindings); auto& vertexArray = drawScope.getResource().vertexArray; - vertexArray.bind(context, - indexBuffer, - instance.attributeLocations.toBindingArray(attributeBindings)); + vertexArray.bind(context, indexBuffer, instance.attributeLocations.toBindingArray(attributeBindings)); - context.draw(drawMode, - indexOffset, - indexLength); + context.draw(drawMode, indexOffset, indexLength); } private: diff --git a/src/mbgl/gl/render_custom_layer.cpp b/src/mbgl/gl/render_custom_layer.cpp index 91df5537a84..d81e5595225 100644 --- a/src/mbgl/gl/render_custom_layer.cpp +++ b/src/mbgl/gl/render_custom_layer.cpp @@ -56,12 +56,11 @@ void RenderCustomLayer::markContextDestroyed() { contextDestroyed = true; } -void RenderCustomLayer::prepare(const LayerPrepareParameters&) { -} +void RenderCustomLayer::prepare(const LayerPrepareParameters&) {} void RenderCustomLayer::render(PaintParameters& paintParameters) { if (host != impl(baseImpl).host) { - //If the context changed, deinitialize the previous one before initializing the new one. + // If the context changed, deinitialize the previous one before initializing the new one. if (host && !contextDestroyed) { MBGL_CHECK_ERROR(host->deinitialize()); } diff --git a/src/mbgl/gl/render_pass.cpp b/src/mbgl/gl/render_pass.cpp index b327f7954fd..e9f69305099 100644 --- a/src/mbgl/gl/render_pass.cpp +++ b/src/mbgl/gl/render_pass.cpp @@ -6,14 +6,14 @@ namespace mbgl { namespace gl { -RenderPass::RenderPass(gl::CommandEncoder& commandEncoder_, - const char* name, - const gfx::RenderPassDescriptor& descriptor) - : commandEncoder(commandEncoder_), debugGroup(commandEncoder.createDebugGroup(name)) { +RenderPass::RenderPass( + gl::CommandEncoder& commandEncoder_, const char* name, const gfx::RenderPassDescriptor& descriptor +) + : commandEncoder(commandEncoder_), + debugGroup(commandEncoder.createDebugGroup(name)) { descriptor.renderable.getResource().bind(); const auto clearDebugGroup(commandEncoder.createDebugGroup("clear")); - commandEncoder.context.clear(descriptor.clearColor, descriptor.clearDepth, - descriptor.clearStencil); + commandEncoder.context.clear(descriptor.clearColor, descriptor.clearDepth, descriptor.clearStencil); } void RenderPass::pushDebugGroup(const char* name) { diff --git a/src/mbgl/gl/renderbuffer_resource.hpp b/src/mbgl/gl/renderbuffer_resource.hpp index 9a318cbd48a..dc701a480a9 100644 --- a/src/mbgl/gl/renderbuffer_resource.hpp +++ b/src/mbgl/gl/renderbuffer_resource.hpp @@ -9,8 +9,7 @@ namespace gl { class RenderbufferResource final : public gfx::RenderbufferResource { public: explicit RenderbufferResource(UniqueRenderbuffer renderbuffer_) - : renderbuffer(std::move(renderbuffer_)) { - } + : renderbuffer(std::move(renderbuffer_)) {} ~RenderbufferResource() noexcept override = default; diff --git a/src/mbgl/gl/renderer_backend.cpp b/src/mbgl/gl/renderer_backend.cpp index 1f52ce06a9b..6a2bf2fb237 100644 --- a/src/mbgl/gl/renderer_backend.cpp +++ b/src/mbgl/gl/renderer_backend.cpp @@ -9,14 +9,12 @@ namespace mbgl { namespace gl { RendererBackend::RendererBackend(const gfx::ContextMode contextMode_) - : gfx::RendererBackend(contextMode_) { -} + : gfx::RendererBackend(contextMode_) {} std::unique_ptr RendererBackend::createContext() { auto result = std::make_unique(*this); result->enableDebugging(); - result->initializeExtensions( - std::bind(&RendererBackend::getExtensionFunctionPointer, this, std::placeholders::_1)); + result->initializeExtensions(std::bind(&RendererBackend::getExtensionFunctionPointer, this, std::placeholders::_1)); return result; } @@ -32,7 +30,7 @@ void RendererBackend::assumeFramebufferBinding(const gl::FramebufferID fbo) { } void RendererBackend::assumeViewport(int32_t x, int32_t y, const Size& size) { - getContext().viewport.setCurrentValue({ x, y, size }); + getContext().viewport.setCurrentValue({x, y, size}); assert(gl::value::Viewport::Get() == getContext().viewport.getCurrentValue()); } @@ -53,7 +51,7 @@ void RendererBackend::setFramebufferBinding(const gl::FramebufferID fbo) { } void RendererBackend::setViewport(int32_t x, int32_t y, const Size& size) { - getContext().viewport = { x, y, size }; + getContext().viewport = {x, y, size}; assert(gl::value::Viewport::Get() == getContext().viewport.getCurrentValue()); } diff --git a/src/mbgl/gl/state.hpp b/src/mbgl/gl/state.hpp index 77effb17810..ac40dfc02c1 100644 --- a/src/mbgl/gl/state.hpp +++ b/src/mbgl/gl/state.hpp @@ -17,8 +17,8 @@ namespace gl { template class State { public: - State(Args&&... args) : params(std::forward_as_tuple(::std::forward(args)...)) { - } + State(Args&&... args) + : params(std::forward_as_tuple(::std::forward(args)...)) {} State& operator=(const typename T::Type& value) { if (*this != value) { @@ -29,13 +29,9 @@ class State { return *this; } - bool operator==(const typename T::Type& value) const { - return !(*this != value); - } + bool operator==(const typename T::Type& value) const { return !(*this != value); } - bool operator!=(const typename T::Type& value) const { - return dirty || currentValue != value; - } + bool operator!=(const typename T::Type& value) const { return dirty || currentValue != value; } void setCurrentValue(const typename T::Type& value) { dirty = false; @@ -44,17 +40,11 @@ class State { // Mark the state as dirty. This means that the next time we are assigning a value to this // piece of OpenGL state will always result in an actual OpenGL call. - void setDirty() { - dirty = true; - } + void setDirty() { dirty = true; } - typename T::Type getCurrentValue() const { - return currentValue; - } + typename T::Type getCurrentValue() const { return currentValue; } - bool isDirty() const { - return dirty; - } + bool isDirty() const { return dirty; } private: template diff --git a/src/mbgl/gl/texture.cpp b/src/mbgl/gl/texture.cpp index ef4d0836772..3354e19f925 100644 --- a/src/mbgl/gl/texture.cpp +++ b/src/mbgl/gl/texture.cpp @@ -10,36 +10,41 @@ using namespace platform; void bindTexture(gl::Context& context, const uint8_t unit, const gfx::TextureBinding& binding) { auto& resource = static_cast(*binding.resource); - if (binding.filter != resource.filter || binding.mipmap != resource.mipmap || - binding.wrapX != resource.wrapX || binding.wrapY != resource.wrapY) { + if (binding.filter != resource.filter || binding.mipmap != resource.mipmap || binding.wrapX != resource.wrapX || + binding.wrapY != resource.wrapY) { context.activeTextureUnit = unit; context.texture[unit] = resource.texture; if (binding.filter != resource.filter || binding.mipmap != resource.mipmap) { MBGL_CHECK_ERROR(glTexParameteri( - GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + GL_TEXTURE_2D, + GL_TEXTURE_MIN_FILTER, binding.filter == gfx::TextureFilterType::Linear - ? (binding.mipmap == gfx::TextureMipMapType::Yes ? GL_LINEAR_MIPMAP_NEAREST - : GL_LINEAR) - : (binding.mipmap == gfx::TextureMipMapType::Yes ? GL_NEAREST_MIPMAP_NEAREST - : GL_NEAREST))); + ? (binding.mipmap == gfx::TextureMipMapType::Yes ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR) + : (binding.mipmap == gfx::TextureMipMapType::Yes ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST) + )); MBGL_CHECK_ERROR(glTexParameteri( - GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, - binding.filter == gfx::TextureFilterType::Linear ? GL_LINEAR : GL_NEAREST)); + GL_TEXTURE_2D, + GL_TEXTURE_MAG_FILTER, + binding.filter == gfx::TextureFilterType::Linear ? GL_LINEAR : GL_NEAREST + )); resource.filter = binding.filter; resource.mipmap = binding.mipmap; } if (binding.wrapX != resource.wrapX) { - MBGL_CHECK_ERROR(glTexParameteri( - GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, - binding.wrapX == gfx::TextureWrapType::Clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT)); + GL_TEXTURE_2D, + GL_TEXTURE_WRAP_S, + binding.wrapX == gfx::TextureWrapType::Clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT + )); resource.wrapX = binding.wrapX; } if (binding.wrapY != resource.wrapY) { MBGL_CHECK_ERROR(glTexParameteri( - GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, - binding.wrapY == gfx::TextureWrapType::Clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT)); + GL_TEXTURE_2D, + GL_TEXTURE_WRAP_T, + binding.wrapY == gfx::TextureWrapType::Clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT + )); resource.wrapY = binding.wrapY; } } else if (context.texture[unit] != resource.texture) { diff --git a/src/mbgl/gl/texture.hpp b/src/mbgl/gl/texture.hpp index 74a314d2a7b..097281c4f78 100644 --- a/src/mbgl/gl/texture.hpp +++ b/src/mbgl/gl/texture.hpp @@ -21,27 +21,28 @@ class TextureStates; template class TextureStates> { private: - using State = - IndexedTuple, TypeList>...>>; + using State = IndexedTuple, TypeList>...>>; State state; public: void queryLocations(const ProgramID& id) { - state = State{ gl::uniformLocation(id, - concat_literals<&string_literal<'u', '_'>::value, &Ts::name>::value())... }; + state = State{ + gl::uniformLocation(id, concat_literals<&string_literal<'u', '_'>::value, &Ts::name>::value())...}; } NamedUniformLocations getNamedLocations() const { - return NamedUniformLocations{ { concat_literals<&string_literal<'u', '_'>::value, &Ts::name>::value(), - state.template get().location }... }; + return NamedUniformLocations{ + {concat_literals<&string_literal<'u', '_'>::value, &Ts::name>::value(), + state.template get().location}...}; } void bind(gl::Context& context, const gfx::TextureBindings>& bindings) { util::ignore( - { (state.template get() = TypeIndex::value, - gl::bindTexture(context, TypeIndex::value, bindings.template get()), - 0)... }); + {(state.template get() = TypeIndex::value, + gl::bindTexture(context, TypeIndex::value, bindings.template get()), + 0)...} + ); } }; diff --git a/src/mbgl/gl/texture_resource.hpp b/src/mbgl/gl/texture_resource.hpp index e2162beb8a5..100beadb6cc 100644 --- a/src/mbgl/gl/texture_resource.hpp +++ b/src/mbgl/gl/texture_resource.hpp @@ -8,7 +8,9 @@ namespace gl { class TextureResource : public gfx::TextureResource { public: - TextureResource(UniqueTexture&& texture_, int byteSize_) : texture(std::move(texture_)), byteSize(byteSize_) {} + TextureResource(UniqueTexture&& texture_, int byteSize_) + : texture(std::move(texture_)), + byteSize(byteSize_) {} ~TextureResource() noexcept override; static int getStorageSize(const Size& size, gfx::TexturePixelType format, gfx::TextureChannelDataType type); diff --git a/src/mbgl/gl/uniform.cpp b/src/mbgl/gl/uniform.cpp index b4750cc8510..67af60599ab 100644 --- a/src/mbgl/gl/uniform.cpp +++ b/src/mbgl/gl/uniform.cpp @@ -61,7 +61,6 @@ void bindUniform>(UniformLocation location, const std::ar MBGL_CHECK_ERROR(glUniformMatrix4fv(location, 1, GL_FALSE, util::convert(t).data())); } - template <> void bindUniform(UniformLocation location, const bool& t) { return bindUniform(location, int32_t(t)); @@ -79,12 +78,12 @@ void bindUniform(UniformLocation location, const uint8_t& t) { template <> void bindUniform(UniformLocation location, const Color& t) { - bindUniform(location, std::array {{ t.r, t.g, t.b, t.a }}); + bindUniform(location, std::array{{t.r, t.g, t.b, t.a}}); } template <> void bindUniform(UniformLocation location, const Size& t) { - bindUniform(location, util::convert(std::array {{ t.width, t.height }})); + bindUniform(location, util::convert(std::array{{t.width, t.height}})); } template <> @@ -120,8 +119,9 @@ ActiveUniforms activeUniforms(ProgramID id) { for (GLint index = 0; index < count; index++) { MBGL_CHECK_ERROR(glGetActiveUniform(id, index, maxLength, &length, &size, &type, name.get())); active.emplace( - std::string{ name.get(), static_cast(length) }, - ActiveUniform{ static_cast(size), static_cast(type) }); + std::string{name.get(), static_cast(length)}, + ActiveUniform{static_cast(size), static_cast(type)} + ); } return active; @@ -159,19 +159,19 @@ bool verifyUniform>(const ActiveUniform& uniform) { template <> bool verifyUniform(const ActiveUniform& uniform) { - assert(uniform.size == 1 && - (uniform.type == UniformDataType::Bool || - uniform.type == UniformDataType::Int || - uniform.type == UniformDataType::Float)); + assert( + uniform.size == 1 && (uniform.type == UniformDataType::Bool || uniform.type == UniformDataType::Int || + uniform.type == UniformDataType::Float) + ); return true; } template <> bool verifyUniform(const ActiveUniform& uniform) { - assert(uniform.size == 1 && - (uniform.type == UniformDataType::Int || - uniform.type == UniformDataType::Float || - uniform.type == UniformDataType::Sampler2D)); + assert( + uniform.size == 1 && (uniform.type == UniformDataType::Int || uniform.type == UniformDataType::Float || + uniform.type == UniformDataType::Sampler2D) + ); return true; } @@ -189,17 +189,17 @@ bool verifyUniform(const ActiveUniform& uniform) { template <> bool verifyUniform>(const ActiveUniform& uniform) { - assert(uniform.size == 1 && - (uniform.type == UniformDataType::IntVec2 || - uniform.type == UniformDataType::FloatVec2)); + assert( + uniform.size == 1 && (uniform.type == UniformDataType::IntVec2 || uniform.type == UniformDataType::FloatVec2) + ); return true; } template <> bool verifyUniform>(const ActiveUniform& uniform) { - assert(uniform.size == 1 && - (uniform.type == UniformDataType::IntVec4 || - uniform.type == UniformDataType::FloatVec4)); + assert( + uniform.size == 1 && (uniform.type == UniformDataType::IntVec4 || uniform.type == UniformDataType::FloatVec4) + ); return true; } diff --git a/src/mbgl/gl/uniform.hpp b/src/mbgl/gl/uniform.hpp index f26bafd77b2..3bd85245e59 100644 --- a/src/mbgl/gl/uniform.hpp +++ b/src/mbgl/gl/uniform.hpp @@ -38,7 +38,8 @@ ActiveUniforms activeUniforms(ProgramID); template class UniformState { public: - UniformState(UniformLocation location_ = -1) : location(location_) {} + UniformState(UniformLocation location_ = -1) + : location(location_) {} UniformState& operator=(const Value& value) { if (location >= 0 && (!current || *current != value)) { @@ -73,23 +74,28 @@ class UniformStates> final { // Verify active uniform types match the enum const auto active = gl::activeUniforms(id); - util::ignore( - { // Some shader programs have uniforms declared, but not used, so they're not active. - // Therefore, we'll only verify them when they are indeed active. - (active.find(concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value()) != active.end() - ? verifyUniform(active.at(concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value())) - : false)... }); + util::ignore({// Some shader programs have uniforms declared, but not used, so they're not active. + // Therefore, we'll only verify them when they are indeed active. + (active.find(concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value()) != + active.end() + ? verifyUniform( + active.at(concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value()) + ) + : false)...}); #endif - state = State{ gl::uniformLocation(id, concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value())... }; + state = State{ + gl::uniformLocation(id, concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value())...}; } NamedUniformLocations getNamedLocations() const { - return NamedUniformLocations{ { concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value(), state.template get().location }... }; + return NamedUniformLocations{ + {concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value(), + state.template get().location}...}; } void bind(const gfx::UniformValues>& values) { - util::ignore({ (state.template get() = values.template get(), 0)... }); + util::ignore({(state.template get() = values.template get(), 0)...}); } }; diff --git a/src/mbgl/gl/upload_pass.cpp b/src/mbgl/gl/upload_pass.cpp index 8615bfbc25a..406739fd4fc 100644 --- a/src/mbgl/gl/upload_pass.cpp +++ b/src/mbgl/gl/upload_pass.cpp @@ -13,67 +13,61 @@ namespace gl { using namespace platform; UploadPass::UploadPass(gl::CommandEncoder& commandEncoder_, const char* name) - : commandEncoder(commandEncoder_), debugGroup(commandEncoder.createDebugGroup(name)) { -} + : commandEncoder(commandEncoder_), + debugGroup(commandEncoder.createDebugGroup(name)) {} std::unique_ptr UploadPass::createVertexBufferResource( - const void* data, std::size_t size, const gfx::BufferUsageType usage) { + const void* data, std::size_t size, const gfx::BufferUsageType usage +) { BufferID id = 0; MBGL_CHECK_ERROR(glGenBuffers(1, &id)); commandEncoder.context.renderingStats().numBuffers++; commandEncoder.context.renderingStats().memVertexBuffers += static_cast(size); // NOLINTNEXTLINE(performance-move-const-arg) - UniqueBuffer result{ std::move(id), { commandEncoder.context } }; + UniqueBuffer result{std::move(id), {commandEncoder.context}}; commandEncoder.context.vertexBuffer = result; - MBGL_CHECK_ERROR( - glBufferData(GL_ARRAY_BUFFER, size, data, Enum::to(usage))); + MBGL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, size, data, Enum::to(usage))); return std::make_unique(std::move(result), static_cast(size)); } -void UploadPass::updateVertexBufferResource(gfx::VertexBufferResource& resource, - const void* data, - std::size_t size) { +void UploadPass::updateVertexBufferResource(gfx::VertexBufferResource& resource, const void* data, std::size_t size) { commandEncoder.context.vertexBuffer = static_cast(resource).buffer; MBGL_CHECK_ERROR(glBufferSubData(GL_ARRAY_BUFFER, 0, size, data)); } std::unique_ptr UploadPass::createIndexBufferResource( - const void* data, std::size_t size, const gfx::BufferUsageType usage) { + const void* data, std::size_t size, const gfx::BufferUsageType usage +) { BufferID id = 0; MBGL_CHECK_ERROR(glGenBuffers(1, &id)); commandEncoder.context.renderingStats().numBuffers++; commandEncoder.context.renderingStats().memIndexBuffers += static_cast(size); // NOLINTNEXTLINE(performance-move-const-arg) - UniqueBuffer result{ std::move(id), { commandEncoder.context } }; + UniqueBuffer result{std::move(id), {commandEncoder.context}}; commandEncoder.context.bindVertexArray = 0; commandEncoder.context.globalVertexArrayState.indexBuffer = result; - MBGL_CHECK_ERROR( - glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, Enum::to(usage))); + MBGL_CHECK_ERROR(glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, Enum::to(usage))); return std::make_unique(std::move(result), static_cast(size)); } -void UploadPass::updateIndexBufferResource(gfx::IndexBufferResource& resource, - const void* data, - std::size_t size) { +void UploadPass::updateIndexBufferResource(gfx::IndexBufferResource& resource, const void* data, std::size_t size) { // Be sure to unbind any existing vertex array object before binding the index buffer // so that we don't mess up another VAO commandEncoder.context.bindVertexArray = 0; - commandEncoder.context.globalVertexArrayState.indexBuffer = - static_cast(resource).buffer; + commandEncoder.context.globalVertexArrayState.indexBuffer = static_cast(resource).buffer; MBGL_CHECK_ERROR(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, size, data)); } -std::unique_ptr -UploadPass::createTextureResource(const Size size, - const void* data, - gfx::TexturePixelType format, - gfx::TextureChannelDataType type) { +std::unique_ptr UploadPass::createTextureResource( + const Size size, const void* data, gfx::TexturePixelType format, gfx::TextureChannelDataType type +) { auto obj = commandEncoder.context.createUniqueTexture(); int textureByteSize = gl::TextureResource::getStorageSize(size, format, type); commandEncoder.context.renderingStats().memTextures += textureByteSize; - std::unique_ptr resource = - std::make_unique(std::move(obj), textureByteSize); - commandEncoder.context.pixelStoreUnpack = { 1 }; + std::unique_ptr resource = std::make_unique( + std::move(obj), textureByteSize + ); + commandEncoder.context.pixelStoreUnpack = {1}; updateTextureResource(*resource, size, data, format, type); // We are using clamp to edge here since OpenGL ES doesn't allow GL_REPEAT on NPOT textures. // We use those when the pixelRatio isn't a power of two, e.g. on iPhone 6 Plus. @@ -84,33 +78,52 @@ UploadPass::createTextureResource(const Size size, return resource; } -void UploadPass::updateTextureResource(gfx::TextureResource& resource, - const Size size, - const void* data, - gfx::TexturePixelType format, - gfx::TextureChannelDataType type) { +void UploadPass::updateTextureResource( + gfx::TextureResource& resource, + const Size size, + const void* data, + gfx::TexturePixelType format, + gfx::TextureChannelDataType type +) { // Always use texture unit 0 for manipulating it. commandEncoder.context.activeTextureUnit = 0; commandEncoder.context.texture[0] = static_cast(resource).texture; - MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, Enum::to(format), - size.width, size.height, 0, - Enum::to(format), - Enum::to(type), data)); + MBGL_CHECK_ERROR(glTexImage2D( + GL_TEXTURE_2D, + 0, + Enum::to(format), + size.width, + size.height, + 0, + Enum::to(format), + Enum::to(type), + data + )); } -void UploadPass::updateTextureResourceSub(gfx::TextureResource& resource, - const uint16_t xOffset, - const uint16_t yOffset, - const Size size, - const void* data, - gfx::TexturePixelType format, - gfx::TextureChannelDataType type) { +void UploadPass::updateTextureResourceSub( + gfx::TextureResource& resource, + const uint16_t xOffset, + const uint16_t yOffset, + const Size size, + const void* data, + gfx::TexturePixelType format, + gfx::TextureChannelDataType type +) { // Always use texture unit 0 for manipulating it. commandEncoder.context.activeTextureUnit = 0; commandEncoder.context.texture[0] = static_cast(resource).texture; - MBGL_CHECK_ERROR(glTexSubImage2D(GL_TEXTURE_2D, 0, xOffset, yOffset, size.width, size.height, - Enum::to(format), - Enum::to(type), data)); + MBGL_CHECK_ERROR(glTexSubImage2D( + GL_TEXTURE_2D, + 0, + xOffset, + yOffset, + size.width, + size.height, + Enum::to(format), + Enum::to(type), + data + )); } void UploadPass::pushDebugGroup(const char* name) { diff --git a/src/mbgl/gl/upload_pass.hpp b/src/mbgl/gl/upload_pass.hpp index 692652a8239..9da6f3db948 100644 --- a/src/mbgl/gl/upload_pass.hpp +++ b/src/mbgl/gl/upload_pass.hpp @@ -23,25 +23,31 @@ class UploadPass final : public gfx::UploadPass { void popDebugGroup() override; public: - std::unique_ptr createVertexBufferResource(const void* data, - std::size_t size, - gfx::BufferUsageType) override; + std::unique_ptr createVertexBufferResource( + const void* data, std::size_t size, gfx::BufferUsageType + ) override; void updateVertexBufferResource(gfx::VertexBufferResource&, const void* data, std::size_t size) override; - std::unique_ptr createIndexBufferResource(const void* data, - std::size_t size, - gfx::BufferUsageType) override; + std::unique_ptr createIndexBufferResource( + const void* data, std::size_t size, gfx::BufferUsageType + ) override; void updateIndexBufferResource(gfx::IndexBufferResource&, const void* data, std::size_t size) override; public: - std::unique_ptr createTextureResource(Size, const void* data, gfx::TexturePixelType, gfx::TextureChannelDataType) override; - void updateTextureResource(gfx::TextureResource&, Size, const void* data, gfx::TexturePixelType, gfx::TextureChannelDataType) override; - void updateTextureResourceSub(gfx::TextureResource&, - uint16_t xOffset, - uint16_t yOffset, - Size, - const void* data, - gfx::TexturePixelType, - gfx::TextureChannelDataType) override; + std::unique_ptr createTextureResource( + Size, const void* data, gfx::TexturePixelType, gfx::TextureChannelDataType + ) override; + void updateTextureResource( + gfx::TextureResource&, Size, const void* data, gfx::TexturePixelType, gfx::TextureChannelDataType + ) override; + void updateTextureResourceSub( + gfx::TextureResource&, + uint16_t xOffset, + uint16_t yOffset, + Size, + const void* data, + gfx::TexturePixelType, + gfx::TextureChannelDataType + ) override; private: gl::CommandEncoder& commandEncoder; diff --git a/src/mbgl/gl/value.cpp b/src/mbgl/gl/value.cpp index b19bbd020de..9adede3334d 100644 --- a/src/mbgl/gl/value.cpp +++ b/src/mbgl/gl/value.cpp @@ -22,7 +22,7 @@ ClearDepth::Type ClearDepth::Get() { return clearDepth; } -const ClearColor::Type ClearColor::Default { 0, 0, 0, 0 }; +const ClearColor::Type ClearColor::Default{0, 0, 0, 0}; void ClearColor::Set(const Type& value) { MBGL_CHECK_ERROR(glClearColor(value.r, value.g, value.b, value.a)); @@ -31,7 +31,7 @@ void ClearColor::Set(const Type& value) { ClearColor::Type ClearColor::Get() { GLfloat clearColor[4]; MBGL_CHECK_ERROR(glGetFloatv(GL_COLOR_CLEAR_VALUE, clearColor)); - return { clearColor[0], clearColor[1], clearColor[2], clearColor[3] }; + return {clearColor[0], clearColor[1], clearColor[2], clearColor[3]}; } const constexpr ClearStencil::Type ClearStencil::Default; @@ -79,8 +79,11 @@ void ColorMask::Set(const Type& value) { ColorMask::Type ColorMask::Get() { GLboolean bools[4]; MBGL_CHECK_ERROR(glGetBooleanv(GL_COLOR_WRITEMASK, bools)); - return { static_cast(bools[0]), static_cast(bools[1]), static_cast(bools[2]), - static_cast(bools[3]) }; + return { + static_cast(bools[0]), + static_cast(bools[1]), + static_cast(bools[2]), + static_cast(bools[3])}; } const constexpr StencilFunc::Type StencilFunc::Default; @@ -96,7 +99,7 @@ StencilFunc::Type StencilFunc::Get() { MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_FUNC, &func)); MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_REF, &ref)); MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_VALUE_MASK, &mask)); - return { Enum::from(func), ref, static_cast(mask) }; + return {Enum::from(func), ref, static_cast(mask)}; } const constexpr StencilTest::Type StencilTest::Default; @@ -114,9 +117,11 @@ StencilTest::Type StencilTest::Get() { const constexpr StencilOp::Type StencilOp::Default; void StencilOp::Set(const Type& value) { - MBGL_CHECK_ERROR(glStencilOp(Enum::to(value.sfail), - Enum::to(value.dpfail), - Enum::to(value.dppass))); + MBGL_CHECK_ERROR(glStencilOp( + Enum::to(value.sfail), + Enum::to(value.dpfail), + Enum::to(value.dppass) + )); } StencilOp::Type StencilOp::Get() { @@ -126,9 +131,10 @@ StencilOp::Type StencilOp::Get() { MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_FAIL, &sfail)); MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &dpfail)); MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &dppass)); - return { Enum::from(sfail), - Enum::from(dpfail), - Enum::from(dppass) }; + return { + Enum::from(sfail), + Enum::from(dpfail), + Enum::from(dppass)}; } const constexpr DepthRange::Type DepthRange::Default; @@ -140,7 +146,7 @@ void DepthRange::Set(const Type& value) { DepthRange::Type DepthRange::Get() { GLfloat floats[2]; MBGL_CHECK_ERROR(glGetFloatv(GL_DEPTH_RANGE, floats)); - return { floats[0], floats[1] }; + return {floats[0], floats[1]}; } const constexpr DepthTest::Type DepthTest::Default; @@ -194,8 +200,9 @@ BlendEquation::Type BlendEquation::Get() { const constexpr BlendFunc::Type BlendFunc::Default; void BlendFunc::Set(const Type& value) { - MBGL_CHECK_ERROR(glBlendFunc(Enum::to(value.sfactor), - Enum::to(value.dfactor))); + MBGL_CHECK_ERROR(glBlendFunc( + Enum::to(value.sfactor), Enum::to(value.dfactor) + )); } BlendFunc::Type BlendFunc::Get() { @@ -203,11 +210,10 @@ BlendFunc::Type BlendFunc::Get() { GLint dfactor; MBGL_CHECK_ERROR(glGetIntegerv(GL_BLEND_SRC_ALPHA, &sfactor)); MBGL_CHECK_ERROR(glGetIntegerv(GL_BLEND_DST_ALPHA, &dfactor)); - return { Enum::from(sfactor), - Enum::from(dfactor) }; + return {Enum::from(sfactor), Enum::from(dfactor)}; } -const BlendColor::Type BlendColor::Default { 0, 0, 0, 0 }; +const BlendColor::Type BlendColor::Default{0, 0, 0, 0}; void BlendColor::Set(const Type& value) { MBGL_CHECK_ERROR(glBlendColor(value.r, value.g, value.b, value.a)); @@ -216,7 +222,7 @@ void BlendColor::Set(const Type& value) { BlendColor::Type BlendColor::Get() { GLfloat floats[4]; MBGL_CHECK_ERROR(glGetFloatv(GL_BLEND_COLOR, floats)); - return { floats[0], floats[1], floats[2], floats[3] }; + return {floats[0], floats[1], floats[2], floats[3]}; } const constexpr Program::Type Program::Default; @@ -264,8 +270,10 @@ void Viewport::Set(const Type& value) { Viewport::Type Viewport::Get() { GLint viewport[4]; MBGL_CHECK_ERROR(glGetIntegerv(GL_VIEWPORT, viewport)); - return { static_cast(viewport[0]), static_cast(viewport[1]), - { static_cast(viewport[2]), static_cast(viewport[3]) } }; + return { + static_cast(viewport[0]), + static_cast(viewport[1]), + {static_cast(viewport[2]), static_cast(viewport[3])}}; } const constexpr ScissorTest::Type ScissorTest::Default; @@ -388,7 +396,7 @@ BindVertexArray::Type BindVertexArray::Get() { return binding; } -const VertexAttribute::Type VertexAttribute::Default {}; +const VertexAttribute::Type VertexAttribute::Default{}; namespace { @@ -477,7 +485,7 @@ GLint components(const gfx::AttributeDataType type) { #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4312) // reinterpret_cast different size +#pragma warning(disable : 4312) // reinterpret_cast different size #endif void VertexAttribute::Set(const Type& binding, Context& context, AttributeLocation location) { @@ -490,7 +498,8 @@ void VertexAttribute::Set(const Type& binding, Context& context, AttributeLocati vertexType(binding->attribute.dataType), static_cast(false), static_cast(binding->vertexStride), - reinterpret_cast(binding->attribute.offset + (binding->vertexStride * binding->vertexOffset)))); + reinterpret_cast(binding->attribute.offset + (binding->vertexStride * binding->vertexOffset)) + )); } else { MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); } @@ -503,8 +512,7 @@ void VertexAttribute::Set(const Type& binding, Context& context, AttributeLocati const constexpr PixelStorePack::Type PixelStorePack::Default; void PixelStorePack::Set(const Type& value) { - assert(value.alignment == 1 || value.alignment == 2 || value.alignment == 4 || - value.alignment == 8); + assert(value.alignment == 1 || value.alignment == 2 || value.alignment == 4 || value.alignment == 8); MBGL_CHECK_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, value.alignment)); } @@ -517,8 +525,7 @@ PixelStorePack::Type PixelStorePack::Get() { const constexpr PixelStoreUnpack::Type PixelStoreUnpack::Default; void PixelStoreUnpack::Set(const Type& value) { - assert(value.alignment == 1 || value.alignment == 2 || value.alignment == 4 || - value.alignment == 8); + assert(value.alignment == 1 || value.alignment == 2 || value.alignment == 4 || value.alignment == 8); MBGL_CHECK_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, value.alignment)); } diff --git a/src/mbgl/gl/value.hpp b/src/mbgl/gl/value.hpp index d45b2d5a250..feda4410c6e 100644 --- a/src/mbgl/gl/value.hpp +++ b/src/mbgl/gl/value.hpp @@ -55,7 +55,7 @@ struct DepthMask { struct ColorMask { using Type = gfx::ColorMode::Mask; - static const constexpr Type Default = { true, true, true, true }; + static const constexpr Type Default = {true, true, true, true}; static void Set(const Type&); static Type Get(); }; @@ -66,7 +66,7 @@ struct StencilFunc { int32_t ref; uint32_t mask; }; - static const constexpr Type Default = { gfx::StencilMode::Always::func, 0, ~0u }; + static const constexpr Type Default = {gfx::StencilMode::Always::func, 0, ~0u}; static void Set(const Type&); static Type Get(); }; @@ -88,7 +88,8 @@ struct StencilOp { gfx::StencilOpType dpfail; gfx::StencilOpType dppass; }; - static const constexpr Type Default = { gfx::StencilOpType::Keep, gfx::StencilOpType::Keep, gfx::StencilOpType::Keep }; + static const constexpr Type Default = { + gfx::StencilOpType::Keep, gfx::StencilOpType::Keep, gfx::StencilOpType::Keep}; static void Set(const Type&); static Type Get(); }; @@ -99,7 +100,7 @@ constexpr bool operator!=(const StencilOp::Type& a, const StencilOp::Type& b) { struct DepthRange { using Type = Range; - static const constexpr Type Default = { 0, 1 }; + static const constexpr Type Default = {0, 1}; static void Set(const Type&); static Type Get(); }; @@ -137,7 +138,7 @@ struct BlendFunc { gfx::ColorBlendFactorType sfactor; gfx::ColorBlendFactorType dfactor; }; - static const constexpr Type Default = { gfx::ColorBlendFactorType::One, gfx::ColorBlendFactorType::Zero }; + static const constexpr Type Default = {gfx::ColorBlendFactorType::One, gfx::ColorBlendFactorType::Zero}; static void Set(const Type&); static Type Get(); }; @@ -180,7 +181,7 @@ struct Viewport { int32_t y; Size size; }; - static const constexpr Type Default = { 0, 0, { 0, 0 } }; + static const constexpr Type Default = {0, 0, {0, 0}}; static void Set(const Type&); static Type Get(); }; @@ -271,14 +272,14 @@ struct VertexAttribute { struct PixelStorePack { using Type = PixelStorageType; - static const constexpr Type Default = { 4 }; + static const constexpr Type Default = {4}; static void Set(const Type&); static Type Get(); }; struct PixelStoreUnpack { using Type = PixelStorageType; - static const constexpr Type Default = { 4 }; + static const constexpr Type Default = {4}; static void Set(const Type&); static Type Get(); }; diff --git a/src/mbgl/gl/vertex_array.cpp b/src/mbgl/gl/vertex_array.cpp index 168080a050a..4705b8bb20b 100644 --- a/src/mbgl/gl/vertex_array.cpp +++ b/src/mbgl/gl/vertex_array.cpp @@ -5,9 +5,7 @@ namespace mbgl { namespace gl { -void VertexArray::bind(Context& context, - const gfx::IndexBuffer& indexBuffer, - const AttributeBindingArray& bindings) { +void VertexArray::bind(Context& context, const gfx::IndexBuffer& indexBuffer, const AttributeBindingArray& bindings) { context.bindVertexArray = state->vertexArray; state->indexBuffer = indexBuffer.getResource().buffer; diff --git a/src/mbgl/gl/vertex_array.hpp b/src/mbgl/gl/vertex_array.hpp index 70413050b26..8ad6742de79 100644 --- a/src/mbgl/gl/vertex_array.hpp +++ b/src/mbgl/gl/vertex_array.hpp @@ -21,8 +21,7 @@ class Context; class VertexArrayState { public: VertexArrayState(UniqueVertexArray vertexArray_) - : vertexArray(std::move(vertexArray_)) { - } + : vertexArray(std::move(vertexArray_)) {} void setDirty() { indexBuffer.setDirty(); @@ -58,8 +57,7 @@ using UniqueVertexArrayState = std::unique_ptr BackgroundLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr BackgroundLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value +) noexcept { (void)value; return std::unique_ptr(new style::BackgroundLayer(id)); } diff --git a/src/mbgl/layermanager/circle_layer_factory.cpp b/src/mbgl/layermanager/circle_layer_factory.cpp index 1e51b4f5b82..8967f996a60 100644 --- a/src/mbgl/layermanager/circle_layer_factory.cpp +++ b/src/mbgl/layermanager/circle_layer_factory.cpp @@ -12,7 +12,9 @@ const style::LayerTypeInfo* CircleLayerFactory::getTypeInfo() const noexcept { return style::CircleLayer::Impl::staticTypeInfo(); } -std::unique_ptr CircleLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr CircleLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value +) noexcept { auto const source = getSource(value); if (!source) { return nullptr; @@ -24,7 +26,8 @@ std::unique_ptr CircleLayerFactory::createLayer(const std::string& std::unique_ptr CircleLayerFactory::createLayout( const LayoutParameters& parameters, std::unique_ptr layer, - const std::vector>& group) noexcept { + const std::vector>& group +) noexcept { return std::make_unique(parameters.bucketParameters, group, std::move(layer)); } diff --git a/src/mbgl/layermanager/fill_extrusion_layer_factory.cpp b/src/mbgl/layermanager/fill_extrusion_layer_factory.cpp index 234ba894746..c3d971dfb87 100644 --- a/src/mbgl/layermanager/fill_extrusion_layer_factory.cpp +++ b/src/mbgl/layermanager/fill_extrusion_layer_factory.cpp @@ -11,7 +11,9 @@ const style::LayerTypeInfo* FillExtrusionLayerFactory::getTypeInfo() const noexc return style::FillExtrusionLayer::Impl::staticTypeInfo(); } -std::unique_ptr FillExtrusionLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr FillExtrusionLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value +) noexcept { auto const source = getSource(value); if (!source) { return nullptr; @@ -20,9 +22,11 @@ std::unique_ptr FillExtrusionLayerFactory::createLayer(const std:: return std::unique_ptr(new style::FillExtrusionLayer(id, *source)); } -std::unique_ptr FillExtrusionLayerFactory::createLayout(const LayoutParameters& parameters, - std::unique_ptr layer, - const std::vector>& group) noexcept { +std::unique_ptr FillExtrusionLayerFactory::createLayout( + const LayoutParameters& parameters, + std::unique_ptr layer, + const std::vector>& group +) noexcept { using namespace style; using LayoutType = PatternLayout; return std::make_unique(parameters.bucketParameters, group, std::move(layer), parameters); diff --git a/src/mbgl/layermanager/fill_layer_factory.cpp b/src/mbgl/layermanager/fill_layer_factory.cpp index 441dbb79127..73aadf9bbbd 100644 --- a/src/mbgl/layermanager/fill_layer_factory.cpp +++ b/src/mbgl/layermanager/fill_layer_factory.cpp @@ -11,7 +11,9 @@ const style::LayerTypeInfo* FillLayerFactory::getTypeInfo() const noexcept { return style::FillLayer::Impl::staticTypeInfo(); } -std::unique_ptr FillLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr FillLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value +) noexcept { std::optional source = getSource(value); if (!source) { return nullptr; @@ -20,10 +22,11 @@ std::unique_ptr FillLayerFactory::createLayer(const std::string& i return std::unique_ptr(new style::FillLayer(id, *source)); } -std::unique_ptr -FillLayerFactory::createLayout(const LayoutParameters& parameters, - std::unique_ptr layer, - const std::vector>& group) noexcept { +std::unique_ptr FillLayerFactory::createLayout( + const LayoutParameters& parameters, + std::unique_ptr layer, + const std::vector>& group +) noexcept { using namespace style; using LayoutTypeUnsorted = PatternLayout; using LayoutTypeSorted = diff --git a/src/mbgl/layermanager/heatmap_layer_factory.cpp b/src/mbgl/layermanager/heatmap_layer_factory.cpp index 636afd5fdc5..91d3ca95e97 100644 --- a/src/mbgl/layermanager/heatmap_layer_factory.cpp +++ b/src/mbgl/layermanager/heatmap_layer_factory.cpp @@ -11,7 +11,9 @@ const style::LayerTypeInfo* HeatmapLayerFactory::getTypeInfo() const noexcept { return style::HeatmapLayer::Impl::staticTypeInfo(); } -std::unique_ptr HeatmapLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr HeatmapLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value +) noexcept { auto const source = getSource(value); if (!source) { return nullptr; @@ -20,7 +22,9 @@ std::unique_ptr HeatmapLayerFactory::createLayer(const std::string return std::unique_ptr(new style::HeatmapLayer(id, *source)); } -std::unique_ptr HeatmapLayerFactory::createBucket(const BucketParameters& parameters, const std::vector>& layers) noexcept { +std::unique_ptr HeatmapLayerFactory::createBucket( + const BucketParameters& parameters, const std::vector>& layers +) noexcept { return std::make_unique(parameters, layers); } diff --git a/src/mbgl/layermanager/hillshade_layer_factory.cpp b/src/mbgl/layermanager/hillshade_layer_factory.cpp index 4e1d78a69c5..fa4bfbe8704 100644 --- a/src/mbgl/layermanager/hillshade_layer_factory.cpp +++ b/src/mbgl/layermanager/hillshade_layer_factory.cpp @@ -10,7 +10,9 @@ const style::LayerTypeInfo* HillshadeLayerFactory::getTypeInfo() const noexcept return style::HillshadeLayer::Impl::staticTypeInfo(); } -std::unique_ptr HillshadeLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr HillshadeLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value +) noexcept { auto const source = getSource(value); if (!source) { return nullptr; diff --git a/src/mbgl/layermanager/layer_factory.cpp b/src/mbgl/layermanager/layer_factory.cpp index 80f9e08d42e..1ebee7c2295 100644 --- a/src/mbgl/layermanager/layer_factory.cpp +++ b/src/mbgl/layermanager/layer_factory.cpp @@ -25,14 +25,14 @@ std::optional LayerFactory::getSource(const style::conversion::Conv return source; } -std::unique_ptr LayerFactory::createBucket(const BucketParameters&, const std::vector>&) noexcept { +std::unique_ptr +LayerFactory::createBucket(const BucketParameters&, const std::vector>&) noexcept { assert(false); return nullptr; } -std::unique_ptr LayerFactory::createLayout(const LayoutParameters&, - std::unique_ptr, - const std::vector>&) noexcept { +std::unique_ptr LayerFactory:: + createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept { assert(false); return nullptr; } diff --git a/src/mbgl/layermanager/layer_manager.cpp b/src/mbgl/layermanager/layer_manager.cpp index 377d3acce40..ac9a739d9da 100644 --- a/src/mbgl/layermanager/layer_manager.cpp +++ b/src/mbgl/layermanager/layer_manager.cpp @@ -12,8 +12,11 @@ namespace mbgl { std::unique_ptr LayerManager::createLayer( - const std::string& type, const std::string& id, - const style::conversion::Convertible& value, style::conversion::Error& error) noexcept { + const std::string& type, + const std::string& id, + const style::conversion::Convertible& value, + style::conversion::Error& error +) noexcept { LayerFactory* factory = getFactory(type); if (factory) { auto layer = factory->createLayer(id, value); @@ -28,8 +31,9 @@ std::unique_ptr LayerManager::createLayer( return nullptr; } -std::unique_ptr LayerManager::createBucket(const BucketParameters& parameters, - const std::vector>& layers) noexcept { +std::unique_ptr LayerManager::createBucket( + const BucketParameters& parameters, const std::vector>& layers +) noexcept { assert(!layers.empty()); assert(parameters.layerType->layout == style::LayerTypeInfo::Layout::NotRequired); LayerFactory* factory = getFactory(parameters.layerType); @@ -37,9 +41,11 @@ std::unique_ptr LayerManager::createBucket(const BucketParameters& param return factory->createBucket(parameters, layers); } -std::unique_ptr LayerManager::createLayout(const LayoutParameters& parameters, - std::unique_ptr tileLayer, - const std::vector>& layers) noexcept { +std::unique_ptr LayerManager::createLayout( + const LayoutParameters& parameters, + std::unique_ptr tileLayer, + const std::vector>& layers +) noexcept { assert(!layers.empty()); assert(parameters.bucketParameters.layerType->layout == style::LayerTypeInfo::Layout::Required); LayerFactory* factory = getFactory(parameters.bucketParameters.layerType); diff --git a/src/mbgl/layermanager/line_layer_factory.cpp b/src/mbgl/layermanager/line_layer_factory.cpp index cdffb2661d4..346f62749db 100644 --- a/src/mbgl/layermanager/line_layer_factory.cpp +++ b/src/mbgl/layermanager/line_layer_factory.cpp @@ -11,7 +11,9 @@ const style::LayerTypeInfo* LineLayerFactory::getTypeInfo() const noexcept { return style::LineLayer::Impl::staticTypeInfo(); } -std::unique_ptr LineLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr LineLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value +) noexcept { auto const source = getSource(value); if (!source) { return nullptr; @@ -19,9 +21,11 @@ std::unique_ptr LineLayerFactory::createLayer(const std::string& i return std::unique_ptr(new style::LineLayer(id, *source)); } -std::unique_ptr LineLayerFactory::createLayout(const LayoutParameters& parameters, - std::unique_ptr layer, - const std::vector>& group) noexcept { +std::unique_ptr LineLayerFactory::createLayout( + const LayoutParameters& parameters, + std::unique_ptr layer, + const std::vector>& group +) noexcept { using namespace style; using LayoutTypeUnsorted = PatternLayout; using LayoutTypeSorted = diff --git a/src/mbgl/layermanager/location_indicator_layer_factory.cpp b/src/mbgl/layermanager/location_indicator_layer_factory.cpp index 67f7280e934..018e573bed6 100644 --- a/src/mbgl/layermanager/location_indicator_layer_factory.cpp +++ b/src/mbgl/layermanager/location_indicator_layer_factory.cpp @@ -10,16 +10,16 @@ const style::LayerTypeInfo* LocationIndicatorLayerFactory::getTypeInfo() const n return style::LocationIndicatorLayer::Impl::staticTypeInfo(); } -std::unique_ptr LocationIndicatorLayerFactory::createLayer( - const std::string& id, const style::conversion::Convertible&) noexcept { +std::unique_ptr +LocationIndicatorLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible&) noexcept { return std::unique_ptr(new style::LocationIndicatorLayer(id)); } -std::unique_ptr LocationIndicatorLayerFactory::createRenderLayer( - Immutable impl) noexcept { +std::unique_ptr LocationIndicatorLayerFactory::createRenderLayer(Immutable impl +) noexcept { assert(impl->getTypeInfo() == getTypeInfo()); - return std::make_unique( - staticImmutableCast(impl)); + return std::make_unique(staticImmutableCast(impl) + ); } } // namespace mbgl diff --git a/src/mbgl/layermanager/raster_layer_factory.cpp b/src/mbgl/layermanager/raster_layer_factory.cpp index dcc1f817e17..a1319df7c99 100644 --- a/src/mbgl/layermanager/raster_layer_factory.cpp +++ b/src/mbgl/layermanager/raster_layer_factory.cpp @@ -10,7 +10,9 @@ const style::LayerTypeInfo* RasterLayerFactory::getTypeInfo() const noexcept { return style::RasterLayer::Impl::staticTypeInfo(); } -std::unique_ptr RasterLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr RasterLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value +) noexcept { auto const source = getSource(value); if (!source) { return nullptr; diff --git a/src/mbgl/layermanager/symbol_layer_factory.cpp b/src/mbgl/layermanager/symbol_layer_factory.cpp index d307def5df4..280add38096 100644 --- a/src/mbgl/layermanager/symbol_layer_factory.cpp +++ b/src/mbgl/layermanager/symbol_layer_factory.cpp @@ -11,7 +11,9 @@ const style::LayerTypeInfo* SymbolLayerFactory::getTypeInfo() const noexcept { return style::SymbolLayer::Impl::staticTypeInfo(); } -std::unique_ptr SymbolLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr SymbolLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value +) noexcept { std::optional source = getSource(value); if (!source) { return nullptr; @@ -19,9 +21,11 @@ std::unique_ptr SymbolLayerFactory::createLayer(const std::string& return std::unique_ptr(new style::SymbolLayer(id, *source)); } -std::unique_ptr SymbolLayerFactory::createLayout(const LayoutParameters& parameters, - std::unique_ptr tileLayer, - const std::vector>& group) noexcept { +std::unique_ptr SymbolLayerFactory::createLayout( + const LayoutParameters& parameters, + std::unique_ptr tileLayer, + const std::vector>& group +) noexcept { return std::make_unique(parameters.bucketParameters, group, std::move(tileLayer), parameters); } diff --git a/src/mbgl/layout/circle_layout.hpp b/src/mbgl/layout/circle_layout.hpp index 620e04542cd..18d9ca940b4 100644 --- a/src/mbgl/layout/circle_layout.hpp +++ b/src/mbgl/layout/circle_layout.hpp @@ -10,10 +10,14 @@ namespace mbgl { class CircleLayout final : public Layout { public: - CircleLayout(const BucketParameters& parameters, - const std::vector>& group, - std::unique_ptr sourceLayer_) - : sourceLayer(std::move(sourceLayer_)), zoom(parameters.tileID.overscaledZ), mode(parameters.mode) { + CircleLayout( + const BucketParameters& parameters, + const std::vector>& group, + std::unique_ptr sourceLayer_ + ) + : sourceLayer(std::move(sourceLayer_)), + zoom(parameters.tileID.overscaledZ), + mode(parameters.mode) { assert(!group.empty()); auto leaderLayerProperties = staticImmutableCast(group.front()); const auto& unevaluatedLayout = leaderLayerProperties->layerImpl().layout; @@ -50,12 +54,14 @@ class CircleLayout final : public Layout { bool hasDependencies() const override { return false; } - void createBucket(const ImagePositions&, - std::unique_ptr& featureIndex, - std::unordered_map& renderData, - const bool, - const bool, - const CanonicalTileID& canonical) override { + void createBucket( + const ImagePositions&, + std::unique_ptr& featureIndex, + std::unordered_map& renderData, + const bool, + const bool, + const CanonicalTileID& canonical + ) override { auto bucket = std::make_shared(layerPropertiesMap, mode, zoom); for (auto& circleFeature : features) { @@ -85,12 +91,14 @@ class CircleLayout final : public Layout { float sortKey; }; - void addCircle(CircleBucket& bucket, - const GeometryTileFeature& feature, - const GeometryCollection& geometry, - std::size_t featureIndex, - float sortKey, - const CanonicalTileID& canonical) { + void addCircle( + CircleBucket& bucket, + const GeometryTileFeature& feature, + const GeometryCollection& geometry, + std::size_t featureIndex, + float sortKey, + const CanonicalTileID& canonical + ) { constexpr const uint16_t vertexLength = 4; auto& segments = bucket.segments; diff --git a/src/mbgl/layout/clip_lines.cpp b/src/mbgl/layout/clip_lines.cpp index 022c296e190..a5d0aa7ace2 100644 --- a/src/mbgl/layout/clip_lines.cpp +++ b/src/mbgl/layout/clip_lines.cpp @@ -5,15 +5,13 @@ namespace mbgl { namespace util { -GeometryCollection clipLines(const GeometryCollection &lines, - const int16_t x1, const int16_t y1, const int16_t x2, const int16_t y2) { - +GeometryCollection clipLines( + const GeometryCollection& lines, const int16_t x1, const int16_t y1, const int16_t x2, const int16_t y2 +) { GeometryCollection clippedLines; for (auto& line : lines) { - - if (line.empty()) - continue; + if (line.empty()) continue; auto end = line.end() - 1; for (auto it = line.begin(); it != end; it++) { @@ -23,49 +21,65 @@ GeometryCollection clipLines(const GeometryCollection &lines, if (p0.x < x1 && p1.x < x1) { continue; } else if (p0.x < x1) { - p0 = {x1, - static_cast( - std::round(p0.y + (p1.y - p0.y) * (static_cast(x1 - p0.x) / (p1.x - p0.x))))}; + p0 = { + x1, + static_cast( + std::round(p0.y + (p1.y - p0.y) * (static_cast(x1 - p0.x) / (p1.x - p0.x))) + )}; } else if (p1.x < x1) { - p1 = {x1, - static_cast( - std::round(p0.y + (p1.y - p0.y) * (static_cast(x1 - p0.x) / (p1.x - p0.x))))}; + p1 = { + x1, + static_cast( + std::round(p0.y + (p1.y - p0.y) * (static_cast(x1 - p0.x) / (p1.x - p0.x))) + )}; } if (p0.y < y1 && p1.y < y1) { continue; } else if (p0.y < y1) { - p0 = {static_cast( - std::round(p0.x + (p1.x - p0.x) * (static_cast(y1 - p0.y) / (p1.y - p0.y)))), - y1}; + p0 = { + static_cast( + std::round(p0.x + (p1.x - p0.x) * (static_cast(y1 - p0.y) / (p1.y - p0.y))) + ), + y1}; } else if (p1.y < y1) { - p1 = {static_cast( - std::round(p0.x + (p1.x - p0.x) * (static_cast(y1 - p0.y) / (p1.y - p0.y)))), - y1}; + p1 = { + static_cast( + std::round(p0.x + (p1.x - p0.x) * (static_cast(y1 - p0.y) / (p1.y - p0.y))) + ), + y1}; } if (p0.x >= x2 && p1.x >= x2) { continue; } else if (p0.x >= x2) { - p0 = {x2, - static_cast( - std::round(p0.y + (p1.y - p0.y) * (static_cast(x2 - p0.x) / (p1.x - p0.x))))}; + p0 = { + x2, + static_cast( + std::round(p0.y + (p1.y - p0.y) * (static_cast(x2 - p0.x) / (p1.x - p0.x))) + )}; } else if (p1.x >= x2) { - p1 = {x2, - static_cast( - std::round(p0.y + (p1.y - p0.y) * (static_cast(x2 - p0.x) / (p1.x - p0.x))))}; + p1 = { + x2, + static_cast( + std::round(p0.y + (p1.y - p0.y) * (static_cast(x2 - p0.x) / (p1.x - p0.x))) + )}; } if (p0.y >= y2 && p1.y >= y2) { continue; } else if (p0.y >= y2) { - p0 = {static_cast( - std::round(p0.x + (p1.x - p0.x) * (static_cast(y2 - p0.y) / (p1.y - p0.y)))), - y2}; + p0 = { + static_cast( + std::round(p0.x + (p1.x - p0.x) * (static_cast(y2 - p0.y) / (p1.y - p0.y))) + ), + y2}; } else if (p1.y >= y2) { - p1 = {static_cast( - std::round(p0.x + (p1.x - p0.x) * (static_cast(y2 - p0.y) / (p1.y - p0.y)))), - y2}; + p1 = { + static_cast( + std::round(p0.x + (p1.x - p0.x) * (static_cast(y2 - p0.y) / (p1.y - p0.y))) + ), + y2}; } if (clippedLines.empty() || (!clippedLines.back().empty() && !(p0 == clippedLines.back().back()))) { diff --git a/src/mbgl/layout/layout.hpp b/src/mbgl/layout/layout.hpp index aaa4d4b8e1f..416be9d76a8 100644 --- a/src/mbgl/layout/layout.hpp +++ b/src/mbgl/layout/layout.hpp @@ -17,19 +17,13 @@ class Layout { public: virtual ~Layout() = default; - virtual void createBucket(const ImagePositions&, - std::unique_ptr&, - std::unordered_map&, - bool, - bool, - const CanonicalTileID&) = 0; + virtual void + createBucket(const ImagePositions&, std::unique_ptr&, std::unordered_map&, bool, bool, const CanonicalTileID&) = 0; virtual void prepareSymbols(const GlyphMap&, const GlyphPositions&, const ImageMap&, const ImagePositions&){}; - virtual bool hasSymbolInstances() const { - return true; - }; - + virtual bool hasSymbolInstances() const { return true; }; + virtual bool hasDependencies() const = 0; }; diff --git a/src/mbgl/layout/merge_lines.cpp b/src/mbgl/layout/merge_lines.cpp index 616a8a3ff56..d7e24e4af3e 100644 --- a/src/mbgl/layout/merge_lines.cpp +++ b/src/mbgl/layout/merge_lines.cpp @@ -8,34 +8,34 @@ namespace util { // Map of key -> index into features using Index = std::unordered_map; -size_t mergeFromRight(std::vector& features, - Index& rightIndex, - Index::iterator left, - size_t rightKey, - GeometryCollection& geom) { - +size_t mergeFromRight( + std::vector& features, + Index& rightIndex, + Index::iterator left, + size_t rightKey, + GeometryCollection& geom +) { const size_t index = left->second; rightIndex.erase(left); rightIndex[rightKey] = index; features[index].geometry[0].pop_back(); - features[index].geometry[0].insert( - features[index].geometry[0].end(), geom[0].begin(), geom[0].end()); + features[index].geometry[0].insert(features[index].geometry[0].end(), geom[0].begin(), geom[0].end()); geom[0].clear(); return index; } -size_t mergeFromLeft(std::vector& features, - Index& leftIndex, - Index::iterator right, - size_t leftKey, - GeometryCollection& geom) { - +size_t mergeFromLeft( + std::vector& features, + Index& leftIndex, + Index::iterator right, + size_t leftKey, + GeometryCollection& geom +) { const size_t index = right->second; leftIndex.erase(right); leftIndex[leftKey] = index; geom[0].pop_back(); - geom[0].insert( - geom[0].end(), features[index].geometry[0].begin(), features[index].geometry[0].end()); + geom[0].insert(geom[0].end(), features[index].geometry[0].begin(), features[index].geometry[0].end()); features[index].geometry[0].clear(); std::swap(features[index].geometry[0], geom[0]); return index; @@ -56,7 +56,7 @@ void mergeLines(std::vector& features) { if (!feature.formattedText || geometry.empty() || geometry[0].empty()) { continue; } - + // TODO: Key should include formatting options (see https://github.com/mapbox/mapbox-gl-js/issues/3645) const size_t leftKey = getKey(feature.formattedText->rawText(), geometry[0].front()); diff --git a/src/mbgl/layout/merge_lines.hpp b/src/mbgl/layout/merge_lines.hpp index 4cce39a6528..b6daa69b0bf 100644 --- a/src/mbgl/layout/merge_lines.hpp +++ b/src/mbgl/layout/merge_lines.hpp @@ -12,17 +12,21 @@ class SymbolFeature; namespace util { -unsigned int mergeFromRight(std::vector &features, - std::unordered_map &rightIndex, - std::unordered_map::iterator left, - std::string &rightKey, - GeometryCollection &geom); - -unsigned int mergeFromLeft(std::vector &features, - std::unordered_map &leftIndex, - std::string &leftKey, - std::unordered_map::iterator right, - GeometryCollection &geom); +unsigned int mergeFromRight( + std::vector &features, + std::unordered_map &rightIndex, + std::unordered_map::iterator left, + std::string &rightKey, + GeometryCollection &geom +); + +unsigned int mergeFromLeft( + std::vector &features, + std::unordered_map &leftIndex, + std::string &leftKey, + std::unordered_map::iterator right, + GeometryCollection &geom +); void mergeLines(std::vector &features); diff --git a/src/mbgl/layout/pattern_layout.hpp b/src/mbgl/layout/pattern_layout.hpp index b2bcd1b3194..38650d9db5b 100644 --- a/src/mbgl/layout/pattern_layout.hpp +++ b/src/mbgl/layout/pattern_layout.hpp @@ -18,13 +18,15 @@ class PatternDependency { using PatternLayerMap = std::map; -class PatternFeature { +class PatternFeature { public: - PatternFeature(std::size_t i_, - std::unique_ptr feature_, - PatternLayerMap patterns_, - float sortKey_ = 0.0f) - : i(i_), feature(std::move(feature_)), patterns(std::move(patterns_)), sortKey(sortKey_) {} + PatternFeature( + std::size_t i_, std::unique_ptr feature_, PatternLayerMap patterns_, float sortKey_ = 0.0f + ) + : i(i_), + feature(std::move(feature_)), + patterns(std::move(patterns_)), + sortKey(sortKey_) {} friend bool operator<(const PatternFeature& lhs, const PatternFeature& rhs) { return lhs.sortKey < rhs.sortKey; } @@ -40,13 +42,8 @@ struct PatternFeatureInserter; template <> struct PatternFeatureInserter { template - static void insert(std::vector& features, - std::size_t index, - std::unique_ptr feature, - PatternLayerMap patternDependencyMap, - float /*zoom*/, - const PropertiesType&, - const CanonicalTileID&) { + static void + insert(std::vector& features, std::size_t index, std::unique_ptr feature, PatternLayerMap patternDependencyMap, float /*zoom*/, const PropertiesType&, const CanonicalTileID&) { features.emplace_back(index, std::move(feature), std::move(patternDependencyMap)); } }; @@ -54,13 +51,15 @@ struct PatternFeatureInserter { template struct PatternFeatureInserter { template - static void insert(std::vector& features, - std::size_t index, - std::unique_ptr feature, - PatternLayerMap patternDependencyMap, - float zoom, - const PropertiesType& properties, - const CanonicalTileID& canonical) { + static void insert( + std::vector& features, + std::size_t index, + std::unique_ptr feature, + PatternLayerMap patternDependencyMap, + float zoom, + const PropertiesType& properties, + const CanonicalTileID& canonical + ) { const auto& sortKeyProperty = properties.template get(); float sortKey = sortKeyProperty.evaluate(*feature, zoom, canonical, SortKeyPropertyType::defaultValue()); PatternFeature patternFeature{index, std::move(feature), std::move(patternDependencyMap), sortKey}; @@ -69,17 +68,20 @@ struct PatternFeatureInserter { } }; -template , - class SortKeyPropertyType = void> +template < + class BucketType, + class LayerPropertiesType, + class PatternPropertyType, + class LayoutPropertiesType = typename style::Properties<>, + class SortKeyPropertyType = void> class PatternLayout : public Layout { public: - PatternLayout(const BucketParameters& parameters, - const std::vector>& group, - std::unique_ptr sourceLayer_, - const LayoutParameters& layoutParameters) + PatternLayout( + const BucketParameters& parameters, + const std::vector>& group, + std::unique_ptr sourceLayer_, + const LayoutParameters& layoutParameters + ) : sourceLayer(std::move(sourceLayer_)), zoom(parameters.tileID.overscaledZ), overscaling(parameters.tileID.overscaleFactor()), @@ -112,7 +114,8 @@ class PatternLayout : public Layout { auto feature = sourceLayer->getFeature(i); if (!leaderLayerProperties->layerImpl().filter( style::expression::EvaluationContext(this->zoom, feature.get()) - .withCanonicalTileID(¶meters.tileID.canonical))) + .withCanonicalTileID(¶meters.tileID.canonical) + )) continue; PatternLayerMap patternDependencyMap; @@ -126,52 +129,63 @@ class PatternLayout : public Layout { if (!patternProperty.isConstant()) { // For layers with non-data-constant pattern properties, evaluate their expression and add // the patterns to the dependency vector - const auto min = patternProperty.evaluate(*feature, - zoom - 1, - layoutParameters.availableImages, - parameters.tileID.canonical, - PatternPropertyType::defaultValue()); - const auto mid = patternProperty.evaluate(*feature, - zoom, - layoutParameters.availableImages, - parameters.tileID.canonical, - PatternPropertyType::defaultValue()); - const auto max = patternProperty.evaluate(*feature, - zoom + 1, - layoutParameters.availableImages, - parameters.tileID.canonical, - PatternPropertyType::defaultValue()); + const auto min = patternProperty.evaluate( + *feature, + zoom - 1, + layoutParameters.availableImages, + parameters.tileID.canonical, + PatternPropertyType::defaultValue() + ); + const auto mid = patternProperty.evaluate( + *feature, + zoom, + layoutParameters.availableImages, + parameters.tileID.canonical, + PatternPropertyType::defaultValue() + ); + const auto max = patternProperty.evaluate( + *feature, + zoom + 1, + layoutParameters.availableImages, + parameters.tileID.canonical, + PatternPropertyType::defaultValue() + ); layoutParameters.imageDependencies.emplace(min.to.id(), ImageType::Pattern); layoutParameters.imageDependencies.emplace(mid.to.id(), ImageType::Pattern); layoutParameters.imageDependencies.emplace(max.to.id(), ImageType::Pattern); - patternDependencyMap.emplace(layerId, - PatternDependency{min.to.id(), mid.to.id(), max.to.id()}); + patternDependencyMap.emplace( + layerId, PatternDependency{min.to.id(), mid.to.id(), max.to.id()} + ); } } } } - PatternFeatureInserter::insert(features, - i, - std::move(feature), - std::move(patternDependencyMap), - zoom, - layout, - parameters.tileID.canonical); + PatternFeatureInserter::insert( + features, + i, + std::move(feature), + std::move(patternDependencyMap), + zoom, + layout, + parameters.tileID.canonical + ); } }; bool hasDependencies() const override { return hasPattern; } - void createBucket(const ImagePositions& patternPositions, - std::unique_ptr& featureIndex, - std::unordered_map& renderData, - const bool /*firstLoad*/, - const bool /*showCollisionBoxes*/, - const CanonicalTileID& canonical) override { + void createBucket( + const ImagePositions& patternPositions, + std::unique_ptr& featureIndex, + std::unordered_map& renderData, + const bool /*firstLoad*/, + const bool /*showCollisionBoxes*/, + const CanonicalTileID& canonical + ) override { auto bucket = std::make_shared(layout, layerPropertiesMap, zoom, overscaling); - for (auto & patternFeature : features) { + for (auto& patternFeature : features) { const auto i = patternFeature.i; std::unique_ptr feature = std::move(patternFeature.feature); const PatternLayerMap& patterns = patternFeature.patterns; @@ -182,7 +196,7 @@ class PatternLayout : public Layout { } if (bucket->hasData()) { for (const auto& pair : layerPropertiesMap) { - renderData.emplace(pair.first, LayerRenderData {bucket, pair.second}); + renderData.emplace(pair.first, LayerRenderData{bucket, pair.second}); } } }; diff --git a/src/mbgl/layout/symbol_feature.hpp b/src/mbgl/layout/symbol_feature.hpp index e1000500419..85756a9ce5e 100644 --- a/src/mbgl/layout/symbol_feature.hpp +++ b/src/mbgl/layout/symbol_feature.hpp @@ -23,9 +23,7 @@ class SymbolFeature : public GeometryTileFeature { FeatureIdentifier getID() const override { return feature->getID(); }; const GeometryCollection& getGeometries() const override { return feature->getGeometries(); } - friend bool operator < (const SymbolFeature& lhs, const SymbolFeature& rhs) { - return lhs.sortKey < rhs.sortKey; - } + friend bool operator<(const SymbolFeature& lhs, const SymbolFeature& rhs) { return lhs.sortKey < rhs.sortKey; } std::unique_ptr feature; GeometryCollection geometry; diff --git a/src/mbgl/layout/symbol_instance.cpp b/src/mbgl/layout/symbol_instance.cpp index 2175859200a..80292510d16 100644 --- a/src/mbgl/layout/symbol_instance.cpp +++ b/src/mbgl/layout/symbol_instance.cpp @@ -18,18 +18,20 @@ const Shaping& getAnyShaping(const ShapedTextOrientations& shapedTextOrientation } // namespace -SymbolInstanceSharedData::SymbolInstanceSharedData(GeometryCoordinates line_, - const ShapedTextOrientations& shapedTextOrientations, - const std::optional& shapedIcon, - const std::optional& verticallyShapedIcon, - const style::SymbolLayoutProperties::Evaluated& layout, - const style::SymbolPlacementType textPlacement, - const std::array& textOffset, - const ImageMap& imageMap, - float iconRotation, - SymbolContent iconType, - bool hasIconTextFit, - bool allowVerticalPlacement) +SymbolInstanceSharedData::SymbolInstanceSharedData( + GeometryCoordinates line_, + const ShapedTextOrientations& shapedTextOrientations, + const std::optional& shapedIcon, + const std::optional& verticallyShapedIcon, + const style::SymbolLayoutProperties::Evaluated& layout, + const style::SymbolPlacementType textPlacement, + const std::array& textOffset, + const ImageMap& imageMap, + float iconRotation, + SymbolContent iconType, + bool hasIconTextFit, + bool allowVerticalPlacement +) : line(std::move(line_)) { // Create the quads used for rendering the icon and glyphs. if (shapedIcon) { @@ -40,14 +42,15 @@ SymbolInstanceSharedData::SymbolInstanceSharedData(GeometryCoordinates line_, } bool singleLineInitialized = false; - const auto initHorizontalGlyphQuads = [&] (SymbolQuads& quads, const Shaping& shaping) { + const auto initHorizontalGlyphQuads = [&](SymbolQuads& quads, const Shaping& shaping) { if (!shapedTextOrientations.singleLine) { quads = getGlyphQuads(shaping, textOffset, layout, textPlacement, imageMap, allowVerticalPlacement); return; } if (!singleLineInitialized) { - rightJustifiedGlyphQuads = - getGlyphQuads(shaping, textOffset, layout, textPlacement, imageMap, allowVerticalPlacement); + rightJustifiedGlyphQuads = getGlyphQuads( + shaping, textOffset, layout, textPlacement, imageMap, allowVerticalPlacement + ); singleLineInitialized = true; } }; @@ -66,64 +69,93 @@ SymbolInstanceSharedData::SymbolInstanceSharedData(GeometryCoordinates line_, if (shapedTextOrientations.vertical) { verticalGlyphQuads = getGlyphQuads( - shapedTextOrientations.vertical, textOffset, layout, textPlacement, imageMap, allowVerticalPlacement); + shapedTextOrientations.vertical, textOffset, layout, textPlacement, imageMap, allowVerticalPlacement + ); } } bool SymbolInstanceSharedData::empty() const { - return rightJustifiedGlyphQuads.empty() && centerJustifiedGlyphQuads.empty() && leftJustifiedGlyphQuads.empty() && verticalGlyphQuads.empty(); -} - -SymbolInstance::SymbolInstance(Anchor& anchor_, - std::shared_ptr sharedData_, - const ShapedTextOrientations& shapedTextOrientations, - const std::optional& shapedIcon, - const std::optional& verticallyShapedIcon, - const float textBoxScale_, - const float textPadding, - const SymbolPlacementType textPlacement, - const std::array& textOffset_, - const float iconBoxScale, - const float iconPadding, - const std::array& iconOffset_, - const IndexedSubfeature& indexedFeature, - const std::size_t layoutFeatureIndex_, - const std::size_t dataFeatureIndex_, - std::u16string key_, - const float overscaling, - const float iconRotation, - const float textRotation, - const std::array& variableTextOffset_, - bool allowVerticalPlacement, - const SymbolContent iconType) : - sharedData(std::move(sharedData_)), - anchor(anchor_), - symbolContent(iconType), - // Create the collision features that will be used to check whether this symbol instance can be placed - // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature - textCollisionFeature(sharedData->line, anchor, getAnyShaping(shapedTextOrientations), textBoxScale_, textPadding, textPlacement, indexedFeature, overscaling, textRotation), - iconCollisionFeature(sharedData->line, anchor, shapedIcon, iconBoxScale, iconPadding, indexedFeature, iconRotation), - writingModes(WritingModeType::None), - layoutFeatureIndex(layoutFeatureIndex_), - dataFeatureIndex(dataFeatureIndex_), - textOffset(textOffset_), - iconOffset(iconOffset_), - key(std::move(key_)), - textBoxScale(textBoxScale_), - variableTextOffset(variableTextOffset_), - singleLine(shapedTextOrientations.singleLine) { + return rightJustifiedGlyphQuads.empty() && centerJustifiedGlyphQuads.empty() && leftJustifiedGlyphQuads.empty() && + verticalGlyphQuads.empty(); +} + +SymbolInstance::SymbolInstance( + Anchor& anchor_, + std::shared_ptr sharedData_, + const ShapedTextOrientations& shapedTextOrientations, + const std::optional& shapedIcon, + const std::optional& verticallyShapedIcon, + const float textBoxScale_, + const float textPadding, + const SymbolPlacementType textPlacement, + const std::array& textOffset_, + const float iconBoxScale, + const float iconPadding, + const std::array& iconOffset_, + const IndexedSubfeature& indexedFeature, + const std::size_t layoutFeatureIndex_, + const std::size_t dataFeatureIndex_, + std::u16string key_, + const float overscaling, + const float iconRotation, + const float textRotation, + const std::array& variableTextOffset_, + bool allowVerticalPlacement, + const SymbolContent iconType +) + : sharedData(std::move(sharedData_)), + anchor(anchor_), + symbolContent(iconType), + // Create the collision features that will be used to check whether this symbol instance can be placed + // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature + textCollisionFeature( + sharedData->line, + anchor, + getAnyShaping(shapedTextOrientations), + textBoxScale_, + textPadding, + textPlacement, + indexedFeature, + overscaling, + textRotation + ), + iconCollisionFeature( + sharedData->line, anchor, shapedIcon, iconBoxScale, iconPadding, indexedFeature, iconRotation + ), + writingModes(WritingModeType::None), + layoutFeatureIndex(layoutFeatureIndex_), + dataFeatureIndex(dataFeatureIndex_), + textOffset(textOffset_), + iconOffset(iconOffset_), + key(std::move(key_)), + textBoxScale(textBoxScale_), + variableTextOffset(variableTextOffset_), + singleLine(shapedTextOrientations.singleLine) { // 'hasText' depends on finding at least one glyph in the shaping that's also in the GlyphPositionMap - if(!sharedData->empty()) symbolContent |= SymbolContent::Text; + if (!sharedData->empty()) symbolContent |= SymbolContent::Text; if (allowVerticalPlacement && shapedTextOrientations.vertical) { const float verticalPointLabelAngle = 90.0f; - verticalTextCollisionFeature = CollisionFeature(line(), anchor, shapedTextOrientations.vertical, textBoxScale_, textPadding, textPlacement, indexedFeature, overscaling, textRotation + verticalPointLabelAngle); + verticalTextCollisionFeature = CollisionFeature( + line(), + anchor, + shapedTextOrientations.vertical, + textBoxScale_, + textPadding, + textPlacement, + indexedFeature, + overscaling, + textRotation + verticalPointLabelAngle + ); if (verticallyShapedIcon) { - verticalIconCollisionFeature = CollisionFeature(sharedData->line, - anchor, - verticallyShapedIcon, - iconBoxScale, iconPadding, - indexedFeature, - iconRotation + verticalPointLabelAngle); + verticalIconCollisionFeature = CollisionFeature( + sharedData->line, + anchor, + verticallyShapedIcon, + iconBoxScale, + iconPadding, + indexedFeature, + iconRotation + verticalPointLabelAngle + ); } } @@ -175,11 +207,11 @@ const std::optional& SymbolInstance::iconQuads() const { bool SymbolInstance::hasText() const { return static_cast(symbolContent & SymbolContent::Text); } - + bool SymbolInstance::hasIcon() const { return static_cast(symbolContent & SymbolContent::IconRGBA) || hasSdfIcon(); } - + bool SymbolInstance::hasSdfIcon() const { return static_cast(symbolContent & SymbolContent::IconSDF); } diff --git a/src/mbgl/layout/symbol_instance.hpp b/src/mbgl/layout/symbol_instance.hpp index ea109fc4c61..7a8b25c7011 100644 --- a/src/mbgl/layout/symbol_instance.hpp +++ b/src/mbgl/layout/symbol_instance.hpp @@ -15,27 +15,34 @@ struct ShapedTextOrientations { Shaping horizontal; Shaping vertical; // The following are used with variable text placement on. - Shaping& right = horizontal; + Shaping& right = horizontal; Shaping center; Shaping left; bool singleLine = false; }; -enum class SymbolContent : uint8_t { None = 0, Text = 1 << 0, IconRGBA = 1 << 1, IconSDF = 1 << 2 }; +enum class SymbolContent : uint8_t { + None = 0, + Text = 1 << 0, + IconRGBA = 1 << 1, + IconSDF = 1 << 2 +}; struct SymbolInstanceSharedData { - SymbolInstanceSharedData(GeometryCoordinates line, - const ShapedTextOrientations& shapedTextOrientations, - const std::optional& shapedIcon, - const std::optional& verticallyShapedIcon, - const style::SymbolLayoutProperties::Evaluated& layout, - style::SymbolPlacementType textPlacement, - const std::array& textOffset, - const ImageMap& imageMap, - float iconRotation, - SymbolContent iconType, - bool hasIconTextFit, - bool allowVerticalPlacement); + SymbolInstanceSharedData( + GeometryCoordinates line, + const ShapedTextOrientations& shapedTextOrientations, + const std::optional& shapedIcon, + const std::optional& verticallyShapedIcon, + const style::SymbolLayoutProperties::Evaluated& layout, + style::SymbolPlacementType textPlacement, + const std::array& textOffset, + const ImageMap& imageMap, + float iconRotation, + SymbolContent iconType, + bool hasIconTextFit, + bool allowVerticalPlacement + ); bool empty() const; GeometryCoordinates line; // Note: When singleLine == true, only `rightJustifiedGlyphQuads` is populated. @@ -49,28 +56,30 @@ struct SymbolInstanceSharedData { class SymbolInstance { public: - SymbolInstance(Anchor& anchor_, - std::shared_ptr sharedData, - const ShapedTextOrientations& shapedTextOrientations, - const std::optional& shapedIcon, - const std::optional& verticallyShapedIcon, - float textBoxScale, - float textPadding, - style::SymbolPlacementType textPlacement, - const std::array& textOffset, - float iconBoxScale, - float iconPadding, - const std::array& iconOffset, - const IndexedSubfeature& indexedFeature, - std::size_t layoutFeatureIndex, - std::size_t dataFeatureIndex, - std::u16string key, - float overscaling, - float iconRotation, - float textRotation, - const std::array& variableTextOffset, - bool allowVerticalPlacement, - SymbolContent iconType = SymbolContent::None); + SymbolInstance( + Anchor& anchor_, + std::shared_ptr sharedData, + const ShapedTextOrientations& shapedTextOrientations, + const std::optional& shapedIcon, + const std::optional& verticallyShapedIcon, + float textBoxScale, + float textPadding, + style::SymbolPlacementType textPlacement, + const std::array& textOffset, + float iconBoxScale, + float iconPadding, + const std::array& iconOffset, + const IndexedSubfeature& indexedFeature, + std::size_t layoutFeatureIndex, + std::size_t dataFeatureIndex, + std::u16string key, + float overscaling, + float iconRotation, + float textRotation, + const std::array& variableTextOffset, + bool allowVerticalPlacement, + SymbolContent iconType = SymbolContent::None + ); std::optional getDefaultHorizontalPlacedTextIndex() const; const GeometryCoordinates& line() const; diff --git a/src/mbgl/layout/symbol_layout.cpp b/src/mbgl/layout/symbol_layout.cpp index a83787b1351..2960b9b2f4a 100644 --- a/src/mbgl/layout/symbol_layout.cpp +++ b/src/mbgl/layout/symbol_layout.cpp @@ -24,8 +24,7 @@ using namespace style; template static bool has(const style::SymbolLayoutProperties::PossiblyEvaluated& layout) { return layout.get().match( - [] (const typename Property::Type& t) { return !t.empty(); }, - [] (const auto&) { return true; } + [](const typename Property::Type& t) { return !t.empty(); }, [](const auto&) { return true; } ); } @@ -47,8 +46,12 @@ inline const SymbolLayerProperties& toSymbolLayerProperties(const Immutable(*layer); } -inline Immutable createLayout(const SymbolLayoutProperties::Unevaluated& unevaluated, float zoom) { - auto layout = makeMutable(unevaluated.evaluate(PropertyEvaluationParameters(zoom))); +inline Immutable createLayout( + const SymbolLayoutProperties::Unevaluated& unevaluated, float zoom +) { + auto layout = makeMutable( + unevaluated.evaluate(PropertyEvaluationParameters(zoom)) + ); if (layout->get() == AlignmentType::Auto) { if (layout->get() != SymbolPlacementType::Point) { @@ -79,10 +82,12 @@ inline Immutable createLayout( } // namespace -SymbolLayout::SymbolLayout(const BucketParameters& parameters, - const std::vector>& layers, - std::unique_ptr sourceLayer_, - const LayoutParameters& layoutParameters) +SymbolLayout::SymbolLayout( + const BucketParameters& parameters, + const std::vector>& layers, + std::unique_ptr sourceLayer_, + const LayoutParameters& layoutParameters +) : bucketLeaderID(layers.front()->baseImpl->id), sourceLayer(std::move(sourceLayer_)), overscaling(static_cast(parameters.tileID.overscaleFactor())), @@ -109,19 +114,18 @@ SymbolLayout::SymbolLayout(const BucketParameters& parameters, const bool hasSymbolSortKey = !leader.layout.get().isUndefined(); const auto symbolZOrder = layout->get(); sortFeaturesByKey = symbolZOrder != SymbolZOrderType::ViewportY && hasSymbolSortKey; - const bool zOrderByViewportY = symbolZOrder == SymbolZOrderType::ViewportY || (symbolZOrder == SymbolZOrderType::Auto && !sortFeaturesByKey); + const bool zOrderByViewportY = symbolZOrder == SymbolZOrderType::ViewportY || + (symbolZOrder == SymbolZOrderType::Auto && !sortFeaturesByKey); sortFeaturesByY = zOrderByViewportY && (layout->get() || layout->get() || - layout->get() || layout->get()); + layout->get() || layout->get()); if (layout->get() == SymbolPlacementType::Point) { auto modes = layout->get(); // Remove duplicates and preserve order. std::set seen; - auto end = std::remove_if(modes.begin(), - modes.end(), - [&seen, this](const auto& placementMode) { - allowVerticalPlacement = allowVerticalPlacement || placementMode == style::TextWritingModeType::Vertical; - return !seen.insert(placementMode).second; - }); + auto end = std::remove_if(modes.begin(), modes.end(), [&seen, this](const auto& placementMode) { + allowVerticalPlacement = allowVerticalPlacement || placementMode == style::TextWritingModeType::Vertical; + return !seen.insert(placementMode).second; + }); modes.erase(end, modes.end()); placementModes = std::move(modes); } @@ -148,7 +152,7 @@ SymbolLayout::SymbolLayout(const BucketParameters& parameters, FontStack baseFontStack = layout->evaluate(zoom, ft, canonicalID); ft.formattedText = TaggedString(); - for (const auto & section : formatted.sections) { + for (const auto& section : formatted.sections) { if (!section.image) { std::string u8string = section.text; if (textTransform == TextTransformType::Uppercase) { @@ -157,19 +161,21 @@ SymbolLayout::SymbolLayout(const BucketParameters& parameters, u8string = platform::lowercase(u8string); } - ft.formattedText->addTextSection(applyArabicShaping(util::convertUTF8ToUTF16(u8string)), - section.fontScale ? *section.fontScale : 1.0, - section.fontStack ? *section.fontStack : baseFontStack, - section.textColor); + ft.formattedText->addTextSection( + applyArabicShaping(util::convertUTF8ToUTF16(u8string)), + section.fontScale ? *section.fontScale : 1.0, + section.fontStack ? *section.fontStack : baseFontStack, + section.textColor + ); } else { layoutParameters.imageDependencies.emplace(section.image->id(), ImageType::Icon); ft.formattedText->addImageSection(section.image->id()); } } - const bool canVerticalizeText = layout->get() == AlignmentType::Map - && layout->get() != SymbolPlacementType::Point - && ft.formattedText->allowsVerticalWritingMode(); + const bool canVerticalizeText = layout->get() == AlignmentType::Map && + layout->get() != SymbolPlacementType::Point && + ft.formattedText->allowsVerticalWritingMode(); // Loop through all characters of this text and collect unique codepoints. for (std::size_t j = 0; j < ft.formattedText->length(); j++) { @@ -237,17 +243,20 @@ const Shaping& getDefaultHorizontalShaping(const ShapedTextOrientations& shapedT } Shaping& shapingForTextJustifyType(ShapedTextOrientations& shapedTextOrientations, style::TextJustifyType type) { - switch(type) { - case style::TextJustifyType::Right: return shapedTextOrientations.right; - case style::TextJustifyType::Left: return shapedTextOrientations.left; - case style::TextJustifyType::Center: return shapedTextOrientations.center; - default: - assert(false); - return shapedTextOrientations.horizontal; + switch (type) { + case style::TextJustifyType::Right: + return shapedTextOrientations.right; + case style::TextJustifyType::Left: + return shapedTextOrientations.left; + case style::TextJustifyType::Center: + return shapedTextOrientations.center; + default: + assert(false); + return shapedTextOrientations.horizontal; } } -std::array evaluateRadialOffset(style::SymbolAnchorType anchor, float radialOffset) { +std::array evaluateRadialOffset(style::SymbolAnchorType anchor, float radialOffset) { std::array result{{0.0f, 0.0f}}; if (radialOffset < 0.0f) radialOffset = 0.0f; // Ignore negative offset. // solve for r where r^2 + r^2 = radialOffset^2 @@ -255,41 +264,41 @@ std::array evaluateRadialOffset(style::SymbolAnchorType anchor, float const float hypotenuse = radialOffset / sqrt2; switch (anchor) { - case SymbolAnchorType::TopRight: - case SymbolAnchorType::TopLeft: - result[1] = hypotenuse - baselineOffset; - break; - case SymbolAnchorType::BottomRight: - case SymbolAnchorType::BottomLeft: - result[1] = -hypotenuse + baselineOffset; - break; - case SymbolAnchorType::Bottom: - result[1] = -radialOffset + baselineOffset; - break; - case SymbolAnchorType::Top: - result[1] = radialOffset - baselineOffset; - break; - default: - break; + case SymbolAnchorType::TopRight: + case SymbolAnchorType::TopLeft: + result[1] = hypotenuse - baselineOffset; + break; + case SymbolAnchorType::BottomRight: + case SymbolAnchorType::BottomLeft: + result[1] = -hypotenuse + baselineOffset; + break; + case SymbolAnchorType::Bottom: + result[1] = -radialOffset + baselineOffset; + break; + case SymbolAnchorType::Top: + result[1] = radialOffset - baselineOffset; + break; + default: + break; } switch (anchor) { - case SymbolAnchorType::TopRight: - case SymbolAnchorType::BottomRight: - result[0] = -hypotenuse; - break; - case SymbolAnchorType::TopLeft: - case SymbolAnchorType::BottomLeft: - result[0] = hypotenuse; - break; - case SymbolAnchorType::Left: - result[0] = radialOffset; - break; - case SymbolAnchorType::Right: - result[0] = -radialOffset; - break; - default: - break; + case SymbolAnchorType::TopRight: + case SymbolAnchorType::BottomRight: + result[0] = -hypotenuse; + break; + case SymbolAnchorType::TopLeft: + case SymbolAnchorType::BottomLeft: + result[0] = hypotenuse; + break; + case SymbolAnchorType::Left: + result[0] = radialOffset; + break; + case SymbolAnchorType::Right: + result[0] = -radialOffset; + break; + default: + break; } return result; @@ -307,46 +316,48 @@ std::array SymbolLayout::evaluateVariableOffset(style::SymbolAnchorTyp offset[1] = std::abs(offset[1]); switch (anchor) { - case SymbolAnchorType::TopRight: - case SymbolAnchorType::TopLeft: - case SymbolAnchorType::Top: - result[1] = offset[1] - baselineOffset; - break; - case SymbolAnchorType::BottomRight: - case SymbolAnchorType::BottomLeft: - case SymbolAnchorType::Bottom: - result[1] = -offset[1] + baselineOffset; - break; - case SymbolAnchorType::Center: - case SymbolAnchorType::Left: - case SymbolAnchorType::Right: - break; + case SymbolAnchorType::TopRight: + case SymbolAnchorType::TopLeft: + case SymbolAnchorType::Top: + result[1] = offset[1] - baselineOffset; + break; + case SymbolAnchorType::BottomRight: + case SymbolAnchorType::BottomLeft: + case SymbolAnchorType::Bottom: + result[1] = -offset[1] + baselineOffset; + break; + case SymbolAnchorType::Center: + case SymbolAnchorType::Left: + case SymbolAnchorType::Right: + break; } switch (anchor) { - case SymbolAnchorType::TopRight: - case SymbolAnchorType::BottomRight: - case SymbolAnchorType::Right: - result[0] = -offset[0]; - break; - case SymbolAnchorType::TopLeft: - case SymbolAnchorType::BottomLeft: - case SymbolAnchorType::Left: - result[0] = offset[0]; - break; - case SymbolAnchorType::Center: - case SymbolAnchorType::Top: - case SymbolAnchorType::Bottom: - break; + case SymbolAnchorType::TopRight: + case SymbolAnchorType::BottomRight: + case SymbolAnchorType::Right: + result[0] = -offset[0]; + break; + case SymbolAnchorType::TopLeft: + case SymbolAnchorType::BottomLeft: + case SymbolAnchorType::Left: + result[0] = offset[0]; + break; + case SymbolAnchorType::Center: + case SymbolAnchorType::Top: + case SymbolAnchorType::Bottom: + break; } return result; } -void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, - const GlyphPositions& glyphPositions, - const ImageMap& imageMap, - const ImagePositions& imagePositions) { +void SymbolLayout::prepareSymbols( + const GlyphMap& glyphMap, + const GlyphPositions& glyphPositions, + const ImageMap& imageMap, + const ImagePositions& imagePositions +) { const bool isPointPlacement = layout->get() == SymbolPlacementType::Point; const bool textAlongLine = layout->get() == AlignmentType::Map && !isPointPlacement; @@ -388,13 +399,15 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, /* images */ imagePositions, layoutTextSize, layoutTextSizeAtBucketZoomLevel, - allowVerticalPlacement); + allowVerticalPlacement + ); return result; }; - const std::vector variableTextAnchor = - layout->evaluate(zoom, feature, canonicalID); + const std::vector variableTextAnchor = layout->evaluate( + zoom, feature, canonicalID + ); const SymbolAnchorType textAnchor = layout->evaluate(zoom, feature, canonicalID); if (variableTextAnchor.empty()) { // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector @@ -405,12 +418,13 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, // but doesn't actually specify what happens if you use both. We go with the radial offset. textOffset = evaluateRadialOffset(textAnchor, radialOffset * util::ONE_EM); } else { - textOffset = {{layout->evaluate(zoom, feature, canonicalID)[0] * util::ONE_EM, - layout->evaluate(zoom, feature, canonicalID)[1] * util::ONE_EM}}; + textOffset = { + {layout->evaluate(zoom, feature, canonicalID)[0] * util::ONE_EM, + layout->evaluate(zoom, feature, canonicalID)[1] * util::ONE_EM}}; } } - TextJustifyType textJustify = - textAlongLine ? TextJustifyType::Center : layout->evaluate(zoom, feature, canonicalID); + TextJustifyType textJustify = textAlongLine ? TextJustifyType::Center + : layout->evaluate(zoom, feature, canonicalID); const auto addVerticalShapingForPointLabelIfNeeded = [&] { if (allowVerticalPlacement && feature.formattedText->allowsVerticalWritingMode()) { @@ -418,7 +432,9 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, // Vertical POI label placement is meant to be used for scripts that support vertical // writing mode, thus, default style::TextJustifyType::Left justification is used. If Latin // scripts would need to be supported, this should take into account other justifications. - shapedTextOrientations.vertical = applyShaping(*feature.formattedText, WritingModeType::Vertical, textAnchor, style::TextJustifyType::Left); + shapedTextOrientations.vertical = applyShaping( + *feature.formattedText, WritingModeType::Vertical, textAnchor, style::TextJustifyType::Left + ); } }; @@ -432,14 +448,16 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, justifications.push_back(getAnchorJustification(anchor)); } } - for (TextJustifyType justification: justifications) { + for (TextJustifyType justification : justifications) { Shaping& shapingForJustification = shapingForTextJustifyType(shapedTextOrientations, justification); if (shapingForJustification) { continue; } // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply // the offsets for the anchor in the placement step. - Shaping shaping = applyShaping(*feature.formattedText, WritingModeType::Horizontal, SymbolAnchorType::Center, justification); + Shaping shaping = applyShaping( + *feature.formattedText, WritingModeType::Horizontal, SymbolAnchorType::Center, justification + ); if (shaping) { shapingForJustification = std::move(shaping); if (shapingForJustification.positionedLines.size() == 1u) { @@ -457,7 +475,9 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, } // Horizontal point or line label. - Shaping shaping = applyShaping(*feature.formattedText, WritingModeType::Horizontal, textAnchor, textJustify); + Shaping shaping = applyShaping( + *feature.formattedText, WritingModeType::Horizontal, textAnchor, textJustify + ); if (shaping) { shapedTextOrientations.horizontal = std::move(shaping); } @@ -468,7 +488,9 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, // Verticalized line label. if (textAlongLine && feature.formattedText->allowsVerticalWritingMode()) { feature.formattedText->verticalizePunctuation(); - shapedTextOrientations.vertical = applyShaping(*feature.formattedText, WritingModeType::Vertical, textAnchor, textJustify); + shapedTextOrientations.vertical = applyShaping( + *feature.formattedText, WritingModeType::Vertical, textAnchor, textJustify + ); } } } @@ -479,9 +501,11 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, auto image = imageMap.find(feature.icon->id()); if (image != imageMap.end()) { iconType = SymbolContent::IconRGBA; - shapedIcon = PositionedIcon::shapeIcon(imagePositions.at(feature.icon->id()), - layout->evaluate(zoom, feature, canonicalID), - layout->evaluate(zoom, feature, canonicalID)); + shapedIcon = PositionedIcon::shapeIcon( + imagePositions.at(feature.icon->id()), + layout->evaluate(zoom, feature, canonicalID), + layout->evaluate(zoom, feature, canonicalID) + ); if (image->second->sdf) { iconType = SymbolContent::IconSDF; } @@ -497,15 +521,17 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, const Shaping& defaultShaping = getDefaultHorizontalShaping(shapedTextOrientations); iconsInText = defaultShaping ? defaultShaping.iconsInText : false; if (defaultShaping || shapedIcon) { - addFeature(std::distance(features.begin(), it), - feature, - shapedTextOrientations, - std::move(shapedIcon), - imageMap, - textOffset, - layoutTextSize, - layoutIconSize, - iconType); + addFeature( + std::distance(features.begin(), it), + feature, + shapedTextOrientations, + std::move(shapedIcon), + imageMap, + textOffset, + layoutTextSize, + layoutIconSize, + iconType + ); } feature.geometry.clear(); @@ -514,15 +540,17 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, compareText.clear(); } -void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, - const SymbolFeature& feature, - const ShapedTextOrientations& shapedTextOrientations, - std::optional shapedIcon, - const ImageMap& imageMap, - std::array textOffset, - float layoutTextSize, - float layoutIconSize, - const SymbolContent iconType) { +void SymbolLayout::addFeature( + const std::size_t layoutFeatureIndex, + const SymbolFeature& feature, + const ShapedTextOrientations& shapedTextOrientations, + std::optional shapedIcon, + const ImageMap& imageMap, + std::array textOffset, + float layoutTextSize, + float layoutIconSize, + const SymbolContent iconType +) { const float minScale = 0.5f; const float glyphSize = 24.0f; @@ -549,8 +577,9 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, variableTextOffset = { {layout->evaluate(zoom, feature, canonicalID) * util::ONE_EM, INVALID_OFFSET_VALUE}}; } else { - variableTextOffset = {{layout->evaluate(zoom, feature, canonicalID)[0] * util::ONE_EM, - layout->evaluate(zoom, feature, canonicalID)[1] * util::ONE_EM}}; + variableTextOffset = { + {layout->evaluate(zoom, feature, canonicalID)[0] * util::ONE_EM, + layout->evaluate(zoom, feature, canonicalID)[1] * util::ONE_EM}}; } const SymbolPlacementType textPlacement = layout->get() != AlignmentType::Map @@ -570,12 +599,14 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, if (allowVerticalPlacement && shapedTextOrientations.vertical) { verticallyShapedIcon = shapedIcon; verticallyShapedIcon->fitIconToText( - shapedTextOrientations.vertical, iconTextFit, layout->get(), iconOffset, fontScale); + shapedTextOrientations.vertical, iconTextFit, layout->get(), iconOffset, fontScale + ); } const auto& shapedText = getDefaultHorizontalShaping(shapedTextOrientations); if (shapedText) { shapedIcon->fitIconToText( - shapedText, iconTextFit, layout->get(), iconOffset, fontScale); + shapedText, iconTextFit, layout->get(), iconOffset, fontScale + ); } } @@ -590,28 +621,30 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, // In tiled rendering mode, add all symbols in the buffers so that we can: // (1) render symbols that overlap into this tile // (2) approximate collision detection effects from neighboring symbols - symbolInstances.emplace_back(anchor, - std::move(sharedData), - shapedTextOrientations, - shapedIcon, - verticallyShapedIcon, - textBoxScale, - textPadding, - textPlacement, - textOffset, - iconBoxScale, - iconPadding, - iconOffset, - indexedFeature, - layoutFeatureIndex, - feature.index, - feature.formattedText ? feature.formattedText->rawText() : std::u16string(), - overscaling, - iconRotation, - textRotation, - variableTextOffset, - allowVerticalPlacement, - iconType); + symbolInstances.emplace_back( + anchor, + std::move(sharedData), + shapedTextOrientations, + shapedIcon, + verticallyShapedIcon, + textBoxScale, + textPadding, + textPlacement, + textOffset, + iconBoxScale, + iconPadding, + iconOffset, + indexedFeature, + layoutFeatureIndex, + feature.index, + feature.formattedText ? feature.formattedText->rawText() : std::u16string(), + overscaling, + iconRotation, + textRotation, + variableTextOffset, + allowVerticalPlacement, + iconType + ); if (sortFeaturesByKey) { if (!sortKeyRanges.empty() && sortKeyRanges.back().sortKey == feature.sortKey) { @@ -624,18 +657,20 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, }; const auto createSymbolInstanceSharedData = [&](GeometryCoordinates line) { - return std::make_shared(std::move(line), - shapedTextOrientations, - shapedIcon, - verticallyShapedIcon, - evaluatedLayoutProperties, - textPlacement, - textOffset, - imageMap, - iconRotation, - iconType, - hasIconTextFit, - allowVerticalPlacement); + return std::make_shared( + std::move(line), + shapedTextOrientations, + shapedIcon, + verticallyShapedIcon, + evaluatedLayoutProperties, + textPlacement, + textOffset, + imageMap, + iconRotation, + iconType, + hasIconTextFit, + allowVerticalPlacement + ); }; const auto& type = feature.getType(); @@ -643,19 +678,26 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, if (layout->get() == SymbolPlacementType::Line) { auto clippedLines = util::clipLines(feature.geometry, 0, 0, util::EXTENT, util::EXTENT); for (auto& line : clippedLines) { - Anchors anchors = getAnchors(line, - symbolSpacing, - textMaxAngle, - (shapedTextOrientations.vertical ? shapedTextOrientations.vertical : getDefaultHorizontalShaping(shapedTextOrientations)).left, - (shapedTextOrientations.vertical ? shapedTextOrientations.vertical : getDefaultHorizontalShaping(shapedTextOrientations)).right, - (shapedIcon ? shapedIcon->left() : 0), - (shapedIcon ? shapedIcon->right() : 0), - glyphSize, - textMaxBoxScale, - overscaling); + Anchors anchors = getAnchors( + line, + symbolSpacing, + textMaxAngle, + (shapedTextOrientations.vertical ? shapedTextOrientations.vertical + : getDefaultHorizontalShaping(shapedTextOrientations)) + .left, + (shapedTextOrientations.vertical ? shapedTextOrientations.vertical + : getDefaultHorizontalShaping(shapedTextOrientations)) + .right, + (shapedIcon ? shapedIcon->left() : 0), + (shapedIcon ? shapedIcon->right() : 0), + glyphSize, + textMaxBoxScale, + overscaling + ); auto sharedData = createSymbolInstanceSharedData(std::move(line)); for (auto& anchor : anchors) { - if (!feature.formattedText || !anchorIsTooClose(feature.formattedText->rawText(), textRepeatDistance, anchor)) { + if (!feature.formattedText || + !anchorIsTooClose(feature.formattedText->rawText(), textRepeatDistance, anchor)) { addSymbolInstance(anchor, sharedData); } } @@ -665,14 +707,20 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, // "lines" with only one point are ignored as in clipLines for (const auto& line : feature.geometry) { if (line.size() > 1) { - std::optional anchor = getCenterAnchor(line, - textMaxAngle, - (shapedTextOrientations.vertical ? shapedTextOrientations.vertical : getDefaultHorizontalShaping(shapedTextOrientations)).left, - (shapedTextOrientations.vertical ? shapedTextOrientations.vertical : getDefaultHorizontalShaping(shapedTextOrientations)).right, - (shapedIcon ? shapedIcon->left() : 0), - (shapedIcon ? shapedIcon->right() : 0), - glyphSize, - textMaxBoxScale); + std::optional anchor = getCenterAnchor( + line, + textMaxAngle, + (shapedTextOrientations.vertical ? shapedTextOrientations.vertical + : getDefaultHorizontalShaping(shapedTextOrientations)) + .left, + (shapedTextOrientations.vertical ? shapedTextOrientations.vertical + : getDefaultHorizontalShaping(shapedTextOrientations)) + .right, + (shapedIcon ? shapedIcon->left() : 0), + (shapedIcon ? shapedIcon->right() : 0), + glyphSize, + textMaxBoxScale + ); if (anchor) { addSymbolInstance(*anchor, createSymbolInstanceSharedData(line)); } @@ -699,13 +747,17 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, // Skip invalid LineStrings. if (line.empty()) continue; - Anchor anchor(static_cast(line[0].x), static_cast(line[0].y), 0.0f, static_cast(minScale)); + Anchor anchor( + static_cast(line[0].x), static_cast(line[0].y), 0.0f, static_cast(minScale) + ); addSymbolInstance(anchor, createSymbolInstanceSharedData(line)); } } else if (type == FeatureType::Point) { for (const auto& points : feature.geometry) { for (const auto& point : points) { - Anchor anchor(static_cast(point.x), static_cast(point.y), 0.0f, static_cast(minScale)); + Anchor anchor( + static_cast(point.x), static_cast(point.y), 0.0f, static_cast(minScale) + ); addSymbolInstance(anchor, createSymbolInstanceSharedData({point})); } } @@ -754,28 +806,32 @@ std::vector SymbolLayout::calculateTileDistances(const GeometryCoordinate return tileDistances; } -void SymbolLayout::createBucket(const ImagePositions&, - std::unique_ptr&, - std::unordered_map& renderData, - const bool firstLoad, - const bool showCollisionBoxes, - const CanonicalTileID& canonical) { - auto bucket = std::make_shared(layout, - layerPaintProperties, - textSize, - iconSize, - zoom, - iconsNeedLinear, - sortFeaturesByY, - bucketLeaderID, - std::move(symbolInstances), - std::move(sortKeyRanges), - tilePixelRatio, - allowVerticalPlacement, - std::move(placementModes), - iconsInText); - - for (SymbolInstance &symbolInstance : bucket->symbolInstances) { +void SymbolLayout::createBucket( + const ImagePositions&, + std::unique_ptr&, + std::unordered_map& renderData, + const bool firstLoad, + const bool showCollisionBoxes, + const CanonicalTileID& canonical +) { + auto bucket = std::make_shared( + layout, + layerPaintProperties, + textSize, + iconSize, + zoom, + iconsNeedLinear, + sortFeaturesByY, + bucketLeaderID, + std::move(symbolInstances), + std::move(sortKeyRanges), + tilePixelRatio, + allowVerticalPlacement, + std::move(placementModes), + iconsInText + ); + + for (SymbolInstance& symbolInstance : bucket->symbolInstances) { const bool hasText = symbolInstance.hasText(); const bool hasIcon = symbolInstance.hasIcon(); const bool singleLine = symbolInstance.singleLine; @@ -790,31 +846,39 @@ void SymbolLayout::createBucket(const ImagePositions&, const Range sizeData = bucket->iconSizeBinder->getVertexSizeData(feature); auto& iconBuffer = symbolInstance.hasSdfIcon() ? bucket->sdfIcon : bucket->icon; const auto placeIcon = [&](const SymbolQuads& iconQuads, auto& index, const WritingModeType writingMode) { - iconBuffer.placedSymbols.emplace_back(symbolInstance.anchor.point, - symbolInstance.anchor.segment.value_or(0u), - sizeData.min, - sizeData.max, - symbolInstance.iconOffset, - writingMode, - symbolInstance.line(), - std::vector()); + iconBuffer.placedSymbols.emplace_back( + symbolInstance.anchor.point, + symbolInstance.anchor.segment.value_or(0u), + sizeData.min, + sizeData.max, + symbolInstance.iconOffset, + writingMode, + symbolInstance.line(), + std::vector() + ); index = iconBuffer.placedSymbols.size() - 1; PlacedSymbol& iconSymbol = iconBuffer.placedSymbols.back(); - iconSymbol.angle = (allowVerticalPlacement && writingMode == WritingModeType::Vertical) ? static_cast(M_PI_2) : 0.0f; - iconSymbol.vertexStartIndex = - addSymbols(iconBuffer, sizeData, iconQuads, symbolInstance.anchor, iconSymbol, feature.sortKey); + iconSymbol.angle = (allowVerticalPlacement && writingMode == WritingModeType::Vertical) + ? static_cast(M_PI_2) + : 0.0f; + iconSymbol.vertexStartIndex = addSymbols( + iconBuffer, sizeData, iconQuads, symbolInstance.anchor, iconSymbol, feature.sortKey + ); }; placeIcon(*symbolInstance.iconQuads(), symbolInstance.placedIconIndex, WritingModeType::None); if (symbolInstance.verticalIconQuads()) { - placeIcon(*symbolInstance.verticalIconQuads(), - symbolInstance.placedVerticalIconIndex, - WritingModeType::Vertical); + placeIcon( + *symbolInstance.verticalIconQuads(), + symbolInstance.placedVerticalIconIndex, + WritingModeType::Vertical + ); } for (auto& pair : bucket->paintProperties) { pair.second.iconBinders.populateVertexVectors( - feature, iconBuffer.vertices.elements(), symbolInstance.dataFeatureIndex, {}, {}, canonical); + feature, iconBuffer.vertices.elements(), symbolInstance.dataFeatureIndex, {}, {}, canonical + ); } } @@ -822,58 +886,68 @@ void SymbolLayout::createBucket(const ImagePositions&, std::optional lastAddedSection; if (singleLine) { std::optional placedTextIndex; - lastAddedSection = addSymbolGlyphQuads(*bucket, - symbolInstance, - feature, - symbolInstance.writingModes, - placedTextIndex, - symbolInstance.rightJustifiedGlyphQuads(), - canonical, - lastAddedSection); + lastAddedSection = addSymbolGlyphQuads( + *bucket, + symbolInstance, + feature, + symbolInstance.writingModes, + placedTextIndex, + symbolInstance.rightJustifiedGlyphQuads(), + canonical, + lastAddedSection + ); symbolInstance.placedRightTextIndex = placedTextIndex; symbolInstance.placedCenterTextIndex = placedTextIndex; symbolInstance.placedLeftTextIndex = placedTextIndex; } else { if (symbolInstance.rightJustifiedGlyphQuadsSize) { - lastAddedSection = addSymbolGlyphQuads(*bucket, - symbolInstance, - feature, - symbolInstance.writingModes, - symbolInstance.placedRightTextIndex, - symbolInstance.rightJustifiedGlyphQuads(), - canonical, - lastAddedSection); + lastAddedSection = addSymbolGlyphQuads( + *bucket, + symbolInstance, + feature, + symbolInstance.writingModes, + symbolInstance.placedRightTextIndex, + symbolInstance.rightJustifiedGlyphQuads(), + canonical, + lastAddedSection + ); } if (symbolInstance.centerJustifiedGlyphQuadsSize) { - lastAddedSection = addSymbolGlyphQuads(*bucket, - symbolInstance, - feature, - symbolInstance.writingModes, - symbolInstance.placedCenterTextIndex, - symbolInstance.centerJustifiedGlyphQuads(), - canonical, - lastAddedSection); + lastAddedSection = addSymbolGlyphQuads( + *bucket, + symbolInstance, + feature, + symbolInstance.writingModes, + symbolInstance.placedCenterTextIndex, + symbolInstance.centerJustifiedGlyphQuads(), + canonical, + lastAddedSection + ); } if (symbolInstance.leftJustifiedGlyphQuadsSize) { - lastAddedSection = addSymbolGlyphQuads(*bucket, - symbolInstance, - feature, - symbolInstance.writingModes, - symbolInstance.placedLeftTextIndex, - symbolInstance.leftJustifiedGlyphQuads(), - canonical, - lastAddedSection); + lastAddedSection = addSymbolGlyphQuads( + *bucket, + symbolInstance, + feature, + symbolInstance.writingModes, + symbolInstance.placedLeftTextIndex, + symbolInstance.leftJustifiedGlyphQuads(), + canonical, + lastAddedSection + ); } } if (symbolInstance.writingModes & WritingModeType::Vertical && symbolInstance.verticalGlyphQuadsSize) { - lastAddedSection = addSymbolGlyphQuads(*bucket, - symbolInstance, - feature, - WritingModeType::Vertical, - symbolInstance.placedVerticalTextIndex, - symbolInstance.verticalGlyphQuads(), - canonical, - lastAddedSection); + lastAddedSection = addSymbolGlyphQuads( + *bucket, + symbolInstance, + feature, + WritingModeType::Vertical, + symbolInstance.placedVerticalTextIndex, + symbolInstance.verticalGlyphQuads(), + canonical, + lastAddedSection + ); } assert(lastAddedSection); // True, as hasText == true; updatePaintPropertiesForSection(*bucket, feature, *lastAddedSection, canonical); @@ -885,7 +959,7 @@ void SymbolLayout::createBucket(const ImagePositions&, if (showCollisionBoxes) { addToDebugBuffers(*bucket); } - if (bucket->hasData()){ + if (bucket->hasData()) { for (const auto& pair : layerPaintProperties) { if (!firstLoad) { bucket->justReloaded = true; @@ -895,40 +969,47 @@ void SymbolLayout::createBucket(const ImagePositions&, } } -void SymbolLayout::updatePaintPropertiesForSection(SymbolBucket& bucket, - const SymbolFeature& feature, - std::size_t sectionIndex, - const CanonicalTileID& canonical) { +void SymbolLayout::updatePaintPropertiesForSection( + SymbolBucket& bucket, const SymbolFeature& feature, std::size_t sectionIndex, const CanonicalTileID& canonical +) { const auto& formattedSection = sectionOptionsToValue((*feature.formattedText).sectionAt(sectionIndex)); for (auto& pair : bucket.paintProperties) { pair.second.textBinders.populateVertexVectors( - feature, bucket.text.vertices.elements(), feature.index, {}, {}, canonical, formattedSection); + feature, bucket.text.vertices.elements(), feature.index, {}, {}, canonical, formattedSection + ); } } -std::size_t SymbolLayout::addSymbolGlyphQuads(SymbolBucket& bucket, - SymbolInstance& symbolInstance, - const SymbolFeature& feature, - WritingModeType writingMode, - std::optional& placedIndex, - const SymbolQuads& glyphQuads, - const CanonicalTileID& canonical, - std::optional lastAddedSection) { +std::size_t SymbolLayout::addSymbolGlyphQuads( + SymbolBucket& bucket, + SymbolInstance& symbolInstance, + const SymbolFeature& feature, + WritingModeType writingMode, + std::optional& placedIndex, + const SymbolQuads& glyphQuads, + const CanonicalTileID& canonical, + std::optional lastAddedSection +) { const Range sizeData = bucket.textSizeBinder->getVertexSizeData(feature); const bool hasFormatSectionOverrides = bucket.hasFormatSectionOverrides(); - const auto& placedIconIndex = writingMode == WritingModeType::Vertical ? symbolInstance.placedVerticalIconIndex : symbolInstance.placedIconIndex; - bucket.text.placedSymbols.emplace_back(symbolInstance.anchor.point, - symbolInstance.anchor.segment.value_or(0u), - sizeData.min, - sizeData.max, - symbolInstance.textOffset, - writingMode, - symbolInstance.line(), - calculateTileDistances(symbolInstance.line(), symbolInstance.anchor), - placedIconIndex); + const auto& placedIconIndex = writingMode == WritingModeType::Vertical ? symbolInstance.placedVerticalIconIndex + : symbolInstance.placedIconIndex; + bucket.text.placedSymbols.emplace_back( + symbolInstance.anchor.point, + symbolInstance.anchor.segment.value_or(0u), + sizeData.min, + sizeData.max, + symbolInstance.textOffset, + writingMode, + symbolInstance.line(), + calculateTileDistances(symbolInstance.line(), symbolInstance.anchor), + placedIconIndex + ); placedIndex = bucket.text.placedSymbols.size() - 1; PlacedSymbol& placedSymbol = bucket.text.placedSymbols.back(); - placedSymbol.angle = (allowVerticalPlacement && writingMode == WritingModeType::Vertical) ? static_cast(M_PI_2) : 0.0f; + placedSymbol.angle = (allowVerticalPlacement && writingMode == WritingModeType::Vertical) + ? static_cast(M_PI_2) + : 0.0f; bool firstSymbol = true; for (const auto& symbolQuad : glyphQuads) { @@ -938,7 +1019,9 @@ std::size_t SymbolLayout::addSymbolGlyphQuads(SymbolBucket& bucket, } lastAddedSection = symbolQuad.sectionIndex; } - size_t index = addSymbol(bucket.text, sizeData, symbolQuad, symbolInstance.anchor, placedSymbol, feature.sortKey); + size_t index = addSymbol( + bucket.text, sizeData, symbolQuad, symbolInstance.anchor, placedSymbol, feature.sortKey + ); if (firstSymbol) { placedSymbol.vertexStartIndex = index; firstSymbol = false; @@ -948,19 +1031,21 @@ std::size_t SymbolLayout::addSymbolGlyphQuads(SymbolBucket& bucket, return lastAddedSection ? *lastAddedSection : 0u; } -size_t SymbolLayout::addSymbol(SymbolBucket::Buffer& buffer, - const Range sizeData, - const SymbolQuad& symbol, - const Anchor& labelAnchor, - PlacedSymbol& placedSymbol, - float sortKey) { +size_t SymbolLayout::addSymbol( + SymbolBucket::Buffer& buffer, + const Range sizeData, + const SymbolQuad& symbol, + const Anchor& labelAnchor, + PlacedSymbol& placedSymbol, + float sortKey +) { constexpr const uint16_t vertexLength = 4; - const auto &tl = symbol.tl; - const auto &tr = symbol.tr; - const auto &bl = symbol.bl; - const auto &br = symbol.br; - const auto &tex = symbol.tex; + const auto& tl = symbol.tl; + const auto& tr = symbol.tr; + const auto& bl = symbol.bl; + const auto& br = symbol.br; + const auto& tex = symbol.tex; const auto& pixelOffsetTL = symbol.pixelOffsetTL; const auto& pixelOffsetBR = symbol.pixelOffsetBR; const auto& minFontScale = symbol.minFontScale; @@ -978,42 +1063,42 @@ size_t SymbolLayout::addSymbol(SymbolBucket::Buffer& buffer, auto index = static_cast(segment.vertexLength); // coordinates (2 triangles) - buffer.vertices.emplace_back(SymbolSDFIconProgram::layoutVertex(labelAnchor.point, - tl, - symbol.glyphOffset.y, - tex.x, - tex.y, - sizeData, - symbol.isSDF, - pixelOffsetTL, - minFontScale)); - buffer.vertices.emplace_back(SymbolSDFIconProgram::layoutVertex(labelAnchor.point, - tr, - symbol.glyphOffset.y, - tex.x + tex.w, - tex.y, - sizeData, - symbol.isSDF, - {pixelOffsetBR.x, pixelOffsetTL.y}, - minFontScale)); - buffer.vertices.emplace_back(SymbolSDFIconProgram::layoutVertex(labelAnchor.point, - bl, - symbol.glyphOffset.y, - tex.x, - tex.y + tex.h, - sizeData, - symbol.isSDF, - {pixelOffsetTL.x, pixelOffsetBR.y}, - minFontScale)); - buffer.vertices.emplace_back(SymbolSDFIconProgram::layoutVertex(labelAnchor.point, - br, - symbol.glyphOffset.y, - tex.x + tex.w, - tex.y + tex.h, - sizeData, - symbol.isSDF, - pixelOffsetBR, - minFontScale)); + buffer.vertices.emplace_back(SymbolSDFIconProgram::layoutVertex( + labelAnchor.point, tl, symbol.glyphOffset.y, tex.x, tex.y, sizeData, symbol.isSDF, pixelOffsetTL, minFontScale + )); + buffer.vertices.emplace_back(SymbolSDFIconProgram::layoutVertex( + labelAnchor.point, + tr, + symbol.glyphOffset.y, + tex.x + tex.w, + tex.y, + sizeData, + symbol.isSDF, + {pixelOffsetBR.x, pixelOffsetTL.y}, + minFontScale + )); + buffer.vertices.emplace_back(SymbolSDFIconProgram::layoutVertex( + labelAnchor.point, + bl, + symbol.glyphOffset.y, + tex.x, + tex.y + tex.h, + sizeData, + symbol.isSDF, + {pixelOffsetTL.x, pixelOffsetBR.y}, + minFontScale + )); + buffer.vertices.emplace_back(SymbolSDFIconProgram::layoutVertex( + labelAnchor.point, + br, + symbol.glyphOffset.y, + tex.x + tex.w, + tex.y + tex.h, + sizeData, + symbol.isSDF, + pixelOffsetBR, + minFontScale + )); // Dynamic/Opacity vertices are initialized so that the vertex count always agrees with // the layout vertex buffer, but they will always be updated before rendering happens @@ -1041,12 +1126,14 @@ size_t SymbolLayout::addSymbol(SymbolBucket::Buffer& buffer, return index; } -size_t SymbolLayout::addSymbols(SymbolBucket::Buffer& buffer, - const Range sizeData, - const SymbolQuads& symbols, - const Anchor& labelAnchor, - PlacedSymbol& placedSymbol, - float sortKey) { +size_t SymbolLayout::addSymbols( + SymbolBucket::Buffer& buffer, + const Range sizeData, + const SymbolQuads& symbols, + const Anchor& labelAnchor, + PlacedSymbol& placedSymbol, + float sortKey +) { bool firstSymbol = true; size_t firstIndex = 0; for (auto& symbol : symbols) { @@ -1060,7 +1147,6 @@ size_t SymbolLayout::addSymbols(SymbolBucket::Buffer& buffer, } void SymbolLayout::addToDebugBuffers(SymbolBucket& bucket) { - if (!hasSymbolInstances()) { return; } @@ -1068,10 +1154,12 @@ void SymbolLayout::addToDebugBuffers(SymbolBucket& bucket) { for (const SymbolInstance& symbolInstance : symbolInstances) { auto populateCollisionBox = [&](const auto& feature, bool isText) { SymbolBucket::CollisionBuffer& collisionBuffer = - feature.alongLine ? (isText ? static_cast(bucket.getOrCreateTextCollisionCircleBuffer()) - : static_cast(bucket.getOrCreateIconCollisionCircleBuffer())) - : (isText ? static_cast(bucket.getOrCreateTextCollisionBox()) - : static_cast(bucket.getOrCreateIconCollisionBox())); + feature.alongLine + ? (isText + ? static_cast(bucket.getOrCreateTextCollisionCircleBuffer()) + : static_cast(bucket.getOrCreateIconCollisionCircleBuffer())) + : (isText ? static_cast(bucket.getOrCreateTextCollisionBox()) + : static_cast(bucket.getOrCreateIconCollisionBox())); for (const CollisionBox& box : feature.boxes) { auto& anchor = box.anchor; @@ -1084,21 +1172,32 @@ void SymbolLayout::addToDebugBuffers(SymbolBucket& bucket) { static constexpr std::size_t vertexLength = 4; const std::size_t indexLength = feature.alongLine ? 6 : 8; - if (collisionBuffer.segments.empty() || collisionBuffer.segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { + if (collisionBuffer.segments.empty() || collisionBuffer.segments.back().vertexLength + vertexLength > + std::numeric_limits::max()) { collisionBuffer.segments.emplace_back( collisionBuffer.vertices.elements(), - feature.alongLine - ? (isText ? bucket.textCollisionCircle->triangles.elements() : bucket.iconCollisionCircle->triangles.elements()) - : (isText ? bucket.textCollisionBox->lines.elements() : bucket.iconCollisionBox->lines.elements())); + feature.alongLine ? (isText ? bucket.textCollisionCircle->triangles.elements() + : bucket.iconCollisionCircle->triangles.elements()) + : (isText ? bucket.textCollisionBox->lines.elements() + : bucket.iconCollisionBox->lines.elements()) + ); } auto& segment = collisionBuffer.segments.back(); auto index = static_cast(segment.vertexLength); - collisionBuffer.vertices.emplace_back(CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, tl)); - collisionBuffer.vertices.emplace_back(CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, tr)); - collisionBuffer.vertices.emplace_back(CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, br)); - collisionBuffer.vertices.emplace_back(CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, bl)); + collisionBuffer.vertices.emplace_back( + CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, tl) + ); + collisionBuffer.vertices.emplace_back( + CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, tr) + ); + collisionBuffer.vertices.emplace_back( + CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, br) + ); + collisionBuffer.vertices.emplace_back( + CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, bl) + ); // Dynamic vertices are initialized so that the vertex count always agrees with // the layout vertex buffer, but they will always be updated before rendering happens diff --git a/src/mbgl/layout/symbol_layout.hpp b/src/mbgl/layout/symbol_layout.hpp index 12234fba829..eee595e69d7 100644 --- a/src/mbgl/layout/symbol_layout.hpp +++ b/src/mbgl/layout/symbol_layout.hpp @@ -24,24 +24,26 @@ class Filter; class SymbolLayout final : public Layout { public: - SymbolLayout(const BucketParameters&, - const std::vector>&, - std::unique_ptr, - const LayoutParameters& parameters); + SymbolLayout( + const BucketParameters&, + const std::vector>&, + std::unique_ptr, + const LayoutParameters& parameters + ); ~SymbolLayout() final = default; - void prepareSymbols(const GlyphMap& glyphMap, - const GlyphPositions&, - const ImageMap&, - const ImagePositions&) override; + void prepareSymbols(const GlyphMap& glyphMap, const GlyphPositions&, const ImageMap&, const ImagePositions&) + override; - void createBucket(const ImagePositions&, - std::unique_ptr&, - std::unordered_map&, - bool firstLoad, - bool showCollisionBoxes, - const CanonicalTileID& canonical) override; + void createBucket( + const ImagePositions&, + std::unique_ptr&, + std::unordered_map&, + bool firstLoad, + bool showCollisionBoxes, + const CanonicalTileID& canonical + ) override; bool hasSymbolInstances() const override; bool hasDependencies() const override; @@ -55,7 +57,7 @@ class SymbolLayout final : public Layout { static constexpr float INVALID_OFFSET_VALUE = std::numeric_limits::max(); /** * @brief Calculates variable text offset. - * + * * @param anchor text anchor * @param textOffset Either `text-offset` or [ `text-radial-offset`, INVALID_OFFSET_VALUE ] * @return std::array offset along x- and y- axis correspondingly. @@ -65,15 +67,17 @@ class SymbolLayout final : public Layout { static std::vector calculateTileDistances(const GeometryCoordinates& line, const Anchor& anchor); private: - void addFeature(size_t, - const SymbolFeature&, - const ShapedTextOrientations& shapedTextOrientations, - std::optional shapedIcon, - const ImageMap&, - std::array textOffset, - float layoutTextSize, - float layoutIconSize, - SymbolContent iconType); + void addFeature( + size_t, + const SymbolFeature&, + const ShapedTextOrientations& shapedTextOrientations, + std::optional shapedIcon, + const ImageMap&, + std::array textOffset, + float layoutTextSize, + float layoutIconSize, + SymbolContent iconType + ); bool anchorIsTooClose(const std::u16string& text, float repeatDistance, const Anchor&); std::map> compareText; @@ -81,34 +85,39 @@ class SymbolLayout final : public Layout { void addToDebugBuffers(SymbolBucket&); // Adds placed items to the buffer. - size_t addSymbol(SymbolBucket::Buffer&, - Range sizeData, - const SymbolQuad&, - const Anchor& labelAnchor, - PlacedSymbol& placedSymbol, - float sortKey); - size_t addSymbols(SymbolBucket::Buffer&, - Range sizeData, - const SymbolQuads&, - const Anchor& labelAnchor, - PlacedSymbol& placedSymbol, - float sortKey); + size_t addSymbol( + SymbolBucket::Buffer&, + Range sizeData, + const SymbolQuad&, + const Anchor& labelAnchor, + PlacedSymbol& placedSymbol, + float sortKey + ); + size_t addSymbols( + SymbolBucket::Buffer&, + Range sizeData, + const SymbolQuads&, + const Anchor& labelAnchor, + PlacedSymbol& placedSymbol, + float sortKey + ); // Adds symbol quads to bucket and returns formatted section index of last // added quad. - std::size_t addSymbolGlyphQuads(SymbolBucket&, - SymbolInstance&, - const SymbolFeature&, - WritingModeType, - std::optional& placedIndex, - const SymbolQuads&, - const CanonicalTileID& canonical, - std::optional lastAddedSection = std::nullopt); - - void updatePaintPropertiesForSection(SymbolBucket&, - const SymbolFeature&, - std::size_t sectionIndex, - const CanonicalTileID& canonical); + std::size_t addSymbolGlyphQuads( + SymbolBucket&, + SymbolInstance&, + const SymbolFeature&, + WritingModeType, + std::optional& placedIndex, + const SymbolQuads&, + const CanonicalTileID& canonical, + std::optional lastAddedSection = std::nullopt + ); + + void updatePaintPropertiesForSection( + SymbolBucket&, const SymbolFeature&, std::size_t sectionIndex, const CanonicalTileID& canonical + ); // Stores the layer so that we can hold on to GeometryTileFeature instances in SymbolFeature, // which may reference data from this object. @@ -135,7 +144,8 @@ class SymbolLayout final : public Layout { Immutable layout; std::vector features; - BiDi bidi; // Consider moving this up to geometry tile worker to reduce reinstantiation costs; use of BiDi/ubiditransform object must be constrained to one thread + BiDi bidi; // Consider moving this up to geometry tile worker to reduce reinstantiation costs; use of + // BiDi/ubiditransform object must be constrained to one thread }; } // namespace mbgl diff --git a/src/mbgl/layout/symbol_projection.cpp b/src/mbgl/layout/symbol_projection.cpp index 674b0ca966e..68f3be304d9 100644 --- a/src/mbgl/layout/symbol_projection.cpp +++ b/src/mbgl/layout/symbol_projection.cpp @@ -7,418 +7,535 @@ namespace mbgl { - /* - * # Overview of coordinate spaces - * - * ## Tile coordinate spaces - * Each label has an anchor. Some labels have corresponding line geometries. - * The points for both anchors and lines are stored in tile units. Each tile has it's own - * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right. - * - * ## GL coordinate space - * At the end of everything, the vertex shader needs to produce a position in GL coordinate space, - * which is (-1, 1) at the top left and (1, -1) in the bottom right. - * - * ## Map pixel coordinate spaces - * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is - * whatever counts as 1 pixel at the current zoom. - * This space is used for pitch-alignment=map, rotation-alignment=map - * - * ## Rotated map pixel coordinate spaces - * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile. - * This space is used for pitch-alignment=map, rotation-alignment=viewport - * - * ## Viewport pixel coordinate space - * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner - * of the canvas. This space is used for pitch-alignment=viewport - * - * - * # Vertex projection - * It goes roughly like this: - * 1. project the anchor and line from tile units into the correct label coordinate space - * - map pixel space pitch-alignment=map rotation-alignment=map - * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport - * - viewport pixel space pitch-alignment=viewport rotation-alignment=* - * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor. - * 3. add the glyph's corner offset to the point from step 3 - * 4. convert from the label coordinate space to gl coordinates - * - * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work). - * This is what `u_label_plane_matrix` is used for. - * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry. - * This is what `updateLineLabels(...)` in JS, `reprojectLineLabels()` in gl-native, does. - * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix. - * - * Steps 3 and 4 are done in the shaders for all labels. - */ - - /* - * Returns a matrix for converting from tile units to the correct label coordinate space. - */ - mat4 getLabelPlaneMatrix(const mat4& posMatrix, const bool pitchWithMap, const bool rotateWithMap, const TransformState& state, const float pixelsToTileUnits) { - mat4 m; - matrix::identity(m); - if (pitchWithMap) { - matrix::scale(m, m, 1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1); - if (!rotateWithMap) { - matrix::rotate_z(m, m, state.getBearing()); - } - } else { - matrix::scale(m, m, state.getSize().width / 2.0, -(state.getSize().height / 2.0), 1.0); - matrix::translate(m, m, 1, -1, 0); - matrix::multiply(m, m, posMatrix); +/* + * # Overview of coordinate spaces + * + * ## Tile coordinate spaces + * Each label has an anchor. Some labels have corresponding line geometries. + * The points for both anchors and lines are stored in tile units. Each tile has it's own + * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right. + * + * ## GL coordinate space + * At the end of everything, the vertex shader needs to produce a position in GL coordinate space, + * which is (-1, 1) at the top left and (1, -1) in the bottom right. + * + * ## Map pixel coordinate spaces + * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is + * whatever counts as 1 pixel at the current zoom. + * This space is used for pitch-alignment=map, rotation-alignment=map + * + * ## Rotated map pixel coordinate spaces + * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile. + * This space is used for pitch-alignment=map, rotation-alignment=viewport + * + * ## Viewport pixel coordinate space + * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner + * of the canvas. This space is used for pitch-alignment=viewport + * + * + * # Vertex projection + * It goes roughly like this: + * 1. project the anchor and line from tile units into the correct label coordinate space + * - map pixel space pitch-alignment=map rotation-alignment=map + * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport + * - viewport pixel space pitch-alignment=viewport rotation-alignment=* + * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor. + * 3. add the glyph's corner offset to the point from step 3 + * 4. convert from the label coordinate space to gl coordinates + * + * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work). + * This is what `u_label_plane_matrix` is used for. + * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry. + * This is what `updateLineLabels(...)` in JS, `reprojectLineLabels()` in gl-native, does. + * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix. + * + * Steps 3 and 4 are done in the shaders for all labels. + */ + +/* + * Returns a matrix for converting from tile units to the correct label coordinate space. + */ +mat4 getLabelPlaneMatrix( + const mat4& posMatrix, + const bool pitchWithMap, + const bool rotateWithMap, + const TransformState& state, + const float pixelsToTileUnits +) { + mat4 m; + matrix::identity(m); + if (pitchWithMap) { + matrix::scale(m, m, 1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1); + if (!rotateWithMap) { + matrix::rotate_z(m, m, state.getBearing()); } - return m; + } else { + matrix::scale(m, m, state.getSize().width / 2.0, -(state.getSize().height / 2.0), 1.0); + matrix::translate(m, m, 1, -1, 0); + matrix::multiply(m, m, posMatrix); } - - /* - * Returns a matrix for converting from the correct label coordinate space to gl coords. - */ - mat4 getGlCoordMatrix(const mat4& posMatrix, const bool pitchWithMap, const bool rotateWithMap, const TransformState& state, const float pixelsToTileUnits) { - mat4 m; - matrix::identity(m); - if (pitchWithMap) { - matrix::multiply(m, m, posMatrix); - matrix::scale(m, m, pixelsToTileUnits, pixelsToTileUnits, 1); - if (!rotateWithMap) { - matrix::rotate_z(m, m, -state.getBearing()); - } - } else { - matrix::scale(m, m, 1, -1, 1); - matrix::translate(m, m, -1, -1, 0); - matrix::scale(m, m, 2.0 / state.getSize().width, 2.0 / state.getSize().height, 1.0); + return m; +} + +/* + * Returns a matrix for converting from the correct label coordinate space to gl coords. + */ +mat4 getGlCoordMatrix( + const mat4& posMatrix, + const bool pitchWithMap, + const bool rotateWithMap, + const TransformState& state, + const float pixelsToTileUnits +) { + mat4 m; + matrix::identity(m); + if (pitchWithMap) { + matrix::multiply(m, m, posMatrix); + matrix::scale(m, m, pixelsToTileUnits, pixelsToTileUnits, 1); + if (!rotateWithMap) { + matrix::rotate_z(m, m, -state.getBearing()); } - return m; - } - - PointAndCameraDistance project(const Point& point, const mat4& matrix) { - vec4 pos = {{ point.x, point.y, 0, 1 }}; - matrix::transformMat4(pos, pos, matrix); - return {{ static_cast(pos[0] / pos[3]), static_cast(pos[1] / pos[3]) }, static_cast(pos[3]) }; + } else { + matrix::scale(m, m, 1, -1, 1); + matrix::translate(m, m, -1, -1, 0); + matrix::scale(m, m, 2.0 / state.getSize().width, 2.0 / state.getSize().height, 1.0); } - - float evaluateSizeForFeature(const ZoomEvaluatedSize& zoomEvaluatedSize, const PlacedSymbol& placedSymbol) { - if (zoomEvaluatedSize.isFeatureConstant) { - return zoomEvaluatedSize.size; + return m; +} + +PointAndCameraDistance project(const Point& point, const mat4& matrix) { + vec4 pos = {{point.x, point.y, 0, 1}}; + matrix::transformMat4(pos, pos, matrix); + return {{static_cast(pos[0] / pos[3]), static_cast(pos[1] / pos[3])}, static_cast(pos[3])}; +} + +float evaluateSizeForFeature(const ZoomEvaluatedSize& zoomEvaluatedSize, const PlacedSymbol& placedSymbol) { + if (zoomEvaluatedSize.isFeatureConstant) { + return zoomEvaluatedSize.size; + } else { + if (zoomEvaluatedSize.isZoomConstant) { + return placedSymbol.lowerSize; } else { - if (zoomEvaluatedSize.isZoomConstant) { - return placedSymbol.lowerSize; - } else { - return placedSymbol.lowerSize + zoomEvaluatedSize.sizeT * (placedSymbol.upperSize - placedSymbol.lowerSize); - } + return placedSymbol.lowerSize + zoomEvaluatedSize.sizeT * (placedSymbol.upperSize - placedSymbol.lowerSize); } } - - bool isVisible(const vec4& anchorPos, const std::array& clippingBuffer) { - const double x = anchorPos[0] / anchorPos[3]; - const double y = anchorPos[1] / anchorPos[3]; - const bool inPaddedViewport = ( - x >= -clippingBuffer[0] && - x <= clippingBuffer[0] && - y >= -clippingBuffer[1] && - y <= clippingBuffer[1]); - return inPaddedViewport; +} + +bool isVisible(const vec4& anchorPos, const std::array& clippingBuffer) { + const double x = anchorPos[0] / anchorPos[3]; + const double y = anchorPos[1] / anchorPos[3]; + const bool inPaddedViewport = + (x >= -clippingBuffer[0] && x <= clippingBuffer[0] && y >= -clippingBuffer[1] && y <= clippingBuffer[1]); + return inPaddedViewport; +} + +void addDynamicAttributes( + const Point& anchorPoint, + const float angle, + gfx::VertexVector>& dynamicVertexArray +) { + auto dynamicVertex = SymbolSDFIconProgram::dynamicLayoutVertex(anchorPoint, angle); + dynamicVertexArray.emplace_back(dynamicVertex); + dynamicVertexArray.emplace_back(dynamicVertex); + dynamicVertexArray.emplace_back(dynamicVertex); + dynamicVertexArray.emplace_back(dynamicVertex); +} + +void hideGlyphs(size_t numGlyphs, gfx::VertexVector>& dynamicVertexArray) { + const Point offscreenPoint = {-INFINITY, -INFINITY}; + for (size_t i = 0; i < numGlyphs; i++) { + addDynamicAttributes(offscreenPoint, 0, dynamicVertexArray); } - - void addDynamicAttributes(const Point& anchorPoint, const float angle, - gfx::VertexVector>& dynamicVertexArray) { - auto dynamicVertex = SymbolSDFIconProgram::dynamicLayoutVertex(anchorPoint, angle); - dynamicVertexArray.emplace_back(dynamicVertex); - dynamicVertexArray.emplace_back(dynamicVertex); - dynamicVertexArray.emplace_back(dynamicVertex); - dynamicVertexArray.emplace_back(dynamicVertex); +} + +enum PlacementResult { + OK, + NotEnoughRoom, + NeedsFlipping, + UseVertical +}; + +Point projectTruncatedLineSegment( + const Point& previousTilePoint, + const Point& currentTilePoint, + const Point& previousProjectedPoint, + const float minimumLength, + const mat4& projectionMatrix +) { + // We are assuming "previousTilePoint" won't project to a point within one unit of the camera plane + // If it did, that would mean our label extended all the way out from within the viewport to a (very distant) + // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the + // plane of the camera. + const Point projectedUnitVertex = + project(previousTilePoint + util::unit(previousTilePoint - currentTilePoint), projectionMatrix).first; + const Point projectedUnitSegment = previousProjectedPoint - projectedUnitVertex; + + return previousProjectedPoint + (projectedUnitSegment * (minimumLength / util::mag(projectedUnitSegment))); +} + +std::optional placeGlyphAlongLine( + const float offsetX, + const float lineOffsetX, + const float lineOffsetY, + const bool flip, + const Point& projectedAnchorPoint, + const Point& tileAnchorPoint, + const uint16_t anchorSegment, + const GeometryCoordinates& line, + const std::vector& tileDistances, + const mat4& labelPlaneMatrix, + const bool returnTileDistance +) { + const float combinedOffsetX = flip ? offsetX - lineOffsetX : offsetX + lineOffsetX; + + int16_t dir = combinedOffsetX > 0 ? 1 : -1; + + float angle = 0.0; + if (flip) { + // The label needs to be flipped to keep text upright. + // Iterate in the reverse direction. + dir *= -1; + angle = static_cast(M_PI); } - void hideGlyphs(size_t numGlyphs, gfx::VertexVector>& dynamicVertexArray) { - const Point offscreenPoint = { -INFINITY, -INFINITY }; - for (size_t i = 0; i < numGlyphs; i++) { - addDynamicAttributes(offscreenPoint, 0, dynamicVertexArray); - } - } - - enum PlacementResult { - OK, - NotEnoughRoom, - NeedsFlipping, - UseVertical - }; - - Point projectTruncatedLineSegment(const Point& previousTilePoint, const Point& currentTilePoint, const Point& previousProjectedPoint, const float minimumLength, const mat4& projectionMatrix) { - // We are assuming "previousTilePoint" won't project to a point within one unit of the camera plane - // If it did, that would mean our label extended all the way out from within the viewport to a (very distant) - // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the - // plane of the camera. - const Point projectedUnitVertex = project(previousTilePoint + util::unit(previousTilePoint - currentTilePoint), projectionMatrix).first; - const Point projectedUnitSegment = previousProjectedPoint - projectedUnitVertex; - - return previousProjectedPoint + (projectedUnitSegment * (minimumLength / util::mag(projectedUnitSegment))); - } + if (dir < 0) angle += static_cast(M_PI); - std::optional placeGlyphAlongLine(const float offsetX, const float lineOffsetX, const float lineOffsetY, const bool flip, - const Point& projectedAnchorPoint, const Point& tileAnchorPoint, const uint16_t anchorSegment, const GeometryCoordinates& line, const std::vector& tileDistances, const mat4& labelPlaneMatrix, const bool returnTileDistance) { + int32_t currentIndex = dir > 0 ? anchorSegment : anchorSegment + 1; - const float combinedOffsetX = flip ? - offsetX - lineOffsetX : - offsetX + lineOffsetX; + const int32_t initialIndex = currentIndex; + Point current = projectedAnchorPoint; + Point prev = projectedAnchorPoint; + float distanceToPrev = 0.0; + float currentSegmentDistance = 0.0; + const float absOffsetX = std::abs(combinedOffsetX); - int16_t dir = combinedOffsetX > 0 ? 1 : -1; + while (distanceToPrev + currentSegmentDistance <= absOffsetX) { + currentIndex += dir; - float angle = 0.0; - if (flip) { - // The label needs to be flipped to keep text upright. - // Iterate in the reverse direction. - dir *= -1; - angle = static_cast(M_PI); + // offset does not fit on the projected line + if (currentIndex < 0 || currentIndex >= static_cast(line.size())) { + return {}; } - if (dir < 0) angle += static_cast(M_PI); - - int32_t currentIndex = dir > 0 ? anchorSegment : anchorSegment + 1; - - const int32_t initialIndex = currentIndex; - Point current = projectedAnchorPoint; - Point prev = projectedAnchorPoint; - float distanceToPrev = 0.0; - float currentSegmentDistance = 0.0; - const float absOffsetX = std::abs(combinedOffsetX); - - while (distanceToPrev + currentSegmentDistance <= absOffsetX) { - currentIndex += dir; - - // offset does not fit on the projected line - if (currentIndex < 0 || currentIndex >= static_cast(line.size())) { - return {}; - } - - prev = current; - PointAndCameraDistance projection = project(convertPoint(line.at(currentIndex)), labelPlaneMatrix); - if (projection.second > 0) { - current = projection.first; - } else { - // The vertex is behind the plane of the camera, so we can't project it - // Instead, we'll create a vertex along the line that's far enough to include the glyph - const Point previousTilePoint = distanceToPrev == 0 ? - tileAnchorPoint : - convertPoint(line.at(currentIndex - dir)); - const Point currentTilePoint = convertPoint(line.at(currentIndex)); - current = projectTruncatedLineSegment(previousTilePoint, currentTilePoint, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix); - } - - distanceToPrev += currentSegmentDistance; - currentSegmentDistance = util::dist(prev, current); + prev = current; + PointAndCameraDistance projection = project(convertPoint(line.at(currentIndex)), labelPlaneMatrix); + if (projection.second > 0) { + current = projection.first; + } else { + // The vertex is behind the plane of the camera, so we can't project it + // Instead, we'll create a vertex along the line that's far enough to include the glyph + const Point previousTilePoint = distanceToPrev == 0 + ? tileAnchorPoint + : convertPoint(line.at(currentIndex - dir)); + const Point currentTilePoint = convertPoint(line.at(currentIndex)); + current = projectTruncatedLineSegment( + previousTilePoint, currentTilePoint, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix + ); } - // The point is on the current segment. Interpolate to find it. - const float segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance; - const Point prevToCurrent = current - prev; - Point p = (prevToCurrent * segmentInterpolationT) + prev; - - // offset the point from the line to text-offset and icon-offset - p += util::perp(prevToCurrent) * static_cast(lineOffsetY * dir / util::mag(prevToCurrent)); - - const float segmentAngle = angle + std::atan2(current.y - prev.y, current.x - prev.x); - - return {{ - p, - segmentAngle, - returnTileDistance ? - TileDistance( - (currentIndex - dir) == initialIndex ? 0 : tileDistances[currentIndex - dir], - absOffsetX - distanceToPrev - ) : - std::optional() - }}; + distanceToPrev += currentSegmentDistance; + currentSegmentDistance = util::dist(prev, current); } - - std::optional> placeFirstAndLastGlyph(const float fontScale, - const float lineOffsetX, - const float lineOffsetY, - const bool flip, - const Point& anchorPoint, - const Point& tileAnchorPoint, - const PlacedSymbol& symbol, - const mat4& labelPlaneMatrix, - const bool returnTileDistance) { - if (symbol.glyphOffsets.empty()) { - assert(false); - return {}; - } - - const float firstGlyphOffset = symbol.glyphOffsets.front(); - const float lastGlyphOffset = symbol.glyphOffsets.back();; - - std::optional firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, static_cast(symbol.segment), symbol.line, symbol.tileDistances, labelPlaneMatrix, returnTileDistance); - if (!firstPlacedGlyph) return {}; - - std::optional lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, static_cast(symbol.segment), symbol.line, symbol.tileDistances, labelPlaneMatrix, returnTileDistance); - if (!lastPlacedGlyph) return {}; - return std::make_pair(*firstPlacedGlyph, *lastPlacedGlyph); + // The point is on the current segment. Interpolate to find it. + const float segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance; + const Point prevToCurrent = current - prev; + Point p = (prevToCurrent * segmentInterpolationT) + prev; + + // offset the point from the line to text-offset and icon-offset + p += util::perp(prevToCurrent) * static_cast(lineOffsetY * dir / util::mag(prevToCurrent)); + + const float segmentAngle = angle + std::atan2(current.y - prev.y, current.x - prev.x); + + return { + {p, + segmentAngle, + returnTileDistance ? TileDistance( + (currentIndex - dir) == initialIndex ? 0 : tileDistances[currentIndex - dir], + absOffsetX - distanceToPrev + ) + : std::optional()}}; +} + +std::optional> placeFirstAndLastGlyph( + const float fontScale, + const float lineOffsetX, + const float lineOffsetY, + const bool flip, + const Point& anchorPoint, + const Point& tileAnchorPoint, + const PlacedSymbol& symbol, + const mat4& labelPlaneMatrix, + const bool returnTileDistance +) { + if (symbol.glyphOffsets.empty()) { + assert(false); + return {}; } - - std::optional requiresOrientationChange(const WritingModeType writingModes, const Point& firstPoint, const Point& lastPoint, const float aspectRatio) { - if (writingModes == (WritingModeType::Horizontal | WritingModeType::Vertical)) { - // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate - // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal - // and vertical versions can have slightly different projections which could lead to angles where both or - // neither showed. - auto rise = std::abs(lastPoint.y - firstPoint.y); - auto run = std::abs(lastPoint.x - firstPoint.x) * aspectRatio; - if (rise > run) { - return PlacementResult::UseVertical; - } - } - if ((writingModes == WritingModeType::Vertical) ? - (firstPoint.y < lastPoint.y) : - (firstPoint.x > lastPoint.x)) { - // Includes "horizontalOnly" case for labels without vertical glyphs - return PlacementResult::NeedsFlipping; + const float firstGlyphOffset = symbol.glyphOffsets.front(); + const float lastGlyphOffset = symbol.glyphOffsets.back(); + ; + + std::optional firstPlacedGlyph = placeGlyphAlongLine( + fontScale * firstGlyphOffset, + lineOffsetX, + lineOffsetY, + flip, + anchorPoint, + tileAnchorPoint, + static_cast(symbol.segment), + symbol.line, + symbol.tileDistances, + labelPlaneMatrix, + returnTileDistance + ); + if (!firstPlacedGlyph) return {}; + + std::optional lastPlacedGlyph = placeGlyphAlongLine( + fontScale * lastGlyphOffset, + lineOffsetX, + lineOffsetY, + flip, + anchorPoint, + tileAnchorPoint, + static_cast(symbol.segment), + symbol.line, + symbol.tileDistances, + labelPlaneMatrix, + returnTileDistance + ); + if (!lastPlacedGlyph) return {}; + + return std::make_pair(*firstPlacedGlyph, *lastPlacedGlyph); +} + +std::optional requiresOrientationChange( + const WritingModeType writingModes, + const Point& firstPoint, + const Point& lastPoint, + const float aspectRatio +) { + if (writingModes == (WritingModeType::Horizontal | WritingModeType::Vertical)) { + // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate + // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal + // and vertical versions can have slightly different projections which could lead to angles where both or + // neither showed. + auto rise = std::abs(lastPoint.y - firstPoint.y); + auto run = std::abs(lastPoint.x - firstPoint.x) * aspectRatio; + if (rise > run) { + return PlacementResult::UseVertical; } - return {}; } - PlacementResult placeGlyphsAlongLine(const PlacedSymbol& symbol, - const float fontSize, - const bool flip, - const bool keepUpright, - const mat4& posMatrix, - const mat4& labelPlaneMatrix, - const mat4& glCoordMatrix, - gfx::VertexVector>& dynamicVertexArray, - const Point& projectedAnchorPoint, - const float aspectRatio) { - const float fontScale = fontSize / util::ONE_EM; - const float lineOffsetX = symbol.lineOffset[0] * fontScale; - const float lineOffsetY = symbol.lineOffset[1] * fontScale; - - std::vector placedGlyphs; - if (symbol.glyphOffsets.size() > 1) { - - const std::optional> firstAndLastGlyph = - placeFirstAndLastGlyph(fontScale, lineOffsetX, lineOffsetY, flip, projectedAnchorPoint, symbol.anchorPoint, symbol, labelPlaneMatrix, false); - if (!firstAndLastGlyph) { - return PlacementResult::NotEnoughRoom; - } + if ((writingModes == WritingModeType::Vertical) ? (firstPoint.y < lastPoint.y) : (firstPoint.x > lastPoint.x)) { + // Includes "horizontalOnly" case for labels without vertical glyphs + return PlacementResult::NeedsFlipping; + } + return {}; +} + +PlacementResult placeGlyphsAlongLine( + const PlacedSymbol& symbol, + const float fontSize, + const bool flip, + const bool keepUpright, + const mat4& posMatrix, + const mat4& labelPlaneMatrix, + const mat4& glCoordMatrix, + gfx::VertexVector>& dynamicVertexArray, + const Point& projectedAnchorPoint, + const float aspectRatio +) { + const float fontScale = fontSize / util::ONE_EM; + const float lineOffsetX = symbol.lineOffset[0] * fontScale; + const float lineOffsetY = symbol.lineOffset[1] * fontScale; + + std::vector placedGlyphs; + if (symbol.glyphOffsets.size() > 1) { + const std::optional> firstAndLastGlyph = placeFirstAndLastGlyph( + fontScale, + lineOffsetX, + lineOffsetY, + flip, + projectedAnchorPoint, + symbol.anchorPoint, + symbol, + labelPlaneMatrix, + false + ); + if (!firstAndLastGlyph) { + return PlacementResult::NotEnoughRoom; + } - const Point firstPoint = project(firstAndLastGlyph->first.point, glCoordMatrix).first; - const Point lastPoint = project(firstAndLastGlyph->second.point, glCoordMatrix).first; + const Point firstPoint = project(firstAndLastGlyph->first.point, glCoordMatrix).first; + const Point lastPoint = project(firstAndLastGlyph->second.point, glCoordMatrix).first; - if (keepUpright && !flip) { - auto orientationChange = requiresOrientationChange(symbol.writingModes, firstPoint, lastPoint, aspectRatio); - if (orientationChange) { - return *orientationChange; - } + if (keepUpright && !flip) { + auto orientationChange = requiresOrientationChange(symbol.writingModes, firstPoint, lastPoint, aspectRatio); + if (orientationChange) { + return *orientationChange; } + } - placedGlyphs.push_back(firstAndLastGlyph->first); - for (size_t glyphIndex = 1; glyphIndex < symbol.glyphOffsets.size() - 1; glyphIndex++) { - const float glyphOffsetX = symbol.glyphOffsets[glyphIndex]; - // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed - auto placedGlyph = placeGlyphAlongLine(glyphOffsetX * fontScale, lineOffsetX, lineOffsetY, flip, projectedAnchorPoint, symbol.anchorPoint, static_cast(symbol.segment), symbol.line, symbol.tileDistances, labelPlaneMatrix, false); - if (placedGlyph) { - placedGlyphs.push_back(*placedGlyph); - } else { - placedGlyphs.emplace_back(Point{-INFINITY, -INFINITY}, 0.0f, std::nullopt); - } + placedGlyphs.push_back(firstAndLastGlyph->first); + for (size_t glyphIndex = 1; glyphIndex < symbol.glyphOffsets.size() - 1; glyphIndex++) { + const float glyphOffsetX = symbol.glyphOffsets[glyphIndex]; + // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed + auto placedGlyph = placeGlyphAlongLine( + glyphOffsetX * fontScale, + lineOffsetX, + lineOffsetY, + flip, + projectedAnchorPoint, + symbol.anchorPoint, + static_cast(symbol.segment), + symbol.line, + symbol.tileDistances, + labelPlaneMatrix, + false + ); + if (placedGlyph) { + placedGlyphs.push_back(*placedGlyph); + } else { + placedGlyphs.emplace_back(Point{-INFINITY, -INFINITY}, 0.0f, std::nullopt); } - placedGlyphs.push_back(firstAndLastGlyph->second); - } else if (symbol.glyphOffsets.size() == 1) { - // Only a single glyph to place - // So, determine whether to flip based on projected angle of the line segment it's on - if (keepUpright && !flip) { - const Point a = project(symbol.anchorPoint, posMatrix).first; - const Point tileSegmentEnd = convertPoint(symbol.line.at(symbol.segment + 1)); - const PointAndCameraDistance projectedVertex = project(tileSegmentEnd, posMatrix); - // We know the anchor will be in the viewport, but the end of the line segment may be - // behind the plane of the camera, in which case we can use a point at any arbitrary (closer) - // point on the segment. - const Point b = (projectedVertex.second > 0) ? - projectedVertex.first : - projectTruncatedLineSegment(symbol.anchorPoint,tileSegmentEnd, a, 1, posMatrix); - - auto orientationChange = requiresOrientationChange(symbol.writingModes, a, b, aspectRatio); - if (orientationChange) { - return *orientationChange; - } + } + placedGlyphs.push_back(firstAndLastGlyph->second); + } else if (symbol.glyphOffsets.size() == 1) { + // Only a single glyph to place + // So, determine whether to flip based on projected angle of the line segment it's on + if (keepUpright && !flip) { + const Point a = project(symbol.anchorPoint, posMatrix).first; + const Point tileSegmentEnd = convertPoint(symbol.line.at(symbol.segment + 1)); + const PointAndCameraDistance projectedVertex = project(tileSegmentEnd, posMatrix); + // We know the anchor will be in the viewport, but the end of the line segment may be + // behind the plane of the camera, in which case we can use a point at any arbitrary (closer) + // point on the segment. + const Point b = (projectedVertex.second > 0) + ? projectedVertex.first + : projectTruncatedLineSegment( + symbol.anchorPoint, tileSegmentEnd, a, 1, posMatrix + ); + + auto orientationChange = requiresOrientationChange(symbol.writingModes, a, b, aspectRatio); + if (orientationChange) { + return *orientationChange; } - const float glyphOffsetX = symbol.glyphOffsets.front(); - std::optional singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetX, lineOffsetX, lineOffsetY, flip, projectedAnchorPoint, symbol.anchorPoint, static_cast(symbol.segment), - symbol.line, symbol.tileDistances, labelPlaneMatrix, false); - if (!singleGlyph) - return PlacementResult::NotEnoughRoom; - - placedGlyphs.push_back(*singleGlyph); } + const float glyphOffsetX = symbol.glyphOffsets.front(); + std::optional singleGlyph = placeGlyphAlongLine( + fontScale * glyphOffsetX, + lineOffsetX, + lineOffsetY, + flip, + projectedAnchorPoint, + symbol.anchorPoint, + static_cast(symbol.segment), + symbol.line, + symbol.tileDistances, + labelPlaneMatrix, + false + ); + if (!singleGlyph) return PlacementResult::NotEnoughRoom; + + placedGlyphs.push_back(*singleGlyph); + } - // The number of placedGlyphs must equal the number of glyphOffsets, which must correspond to the number of glyph vertices - // There may be 0 glyphs here, if a label consists entirely of glyphs that have 0x0 dimensions - for (auto& placedGlyph : placedGlyphs) { - addDynamicAttributes(placedGlyph.point, placedGlyph.angle, dynamicVertexArray); - } - - return PlacementResult::OK; + // The number of placedGlyphs must equal the number of glyphOffsets, which must correspond to the number of glyph + // vertices There may be 0 glyphs here, if a label consists entirely of glyphs that have 0x0 dimensions + for (auto& placedGlyph : placedGlyphs) { + addDynamicAttributes(placedGlyph.point, placedGlyph.angle, dynamicVertexArray); } + return PlacementResult::OK; +} - void reprojectLineLabels(gfx::VertexVector>& dynamicVertexArray, const std::vector& placedSymbols, - const mat4& posMatrix, bool pitchWithMap, bool rotateWithMap, bool keepUpright, - const RenderTile& tile, const SymbolSizeBinder& sizeBinder, const TransformState& state) { +void reprojectLineLabels( + gfx::VertexVector>& dynamicVertexArray, + const std::vector& placedSymbols, + const mat4& posMatrix, + bool pitchWithMap, + bool rotateWithMap, + bool keepUpright, + const RenderTile& tile, + const SymbolSizeBinder& sizeBinder, + const TransformState& state +) { + const ZoomEvaluatedSize partiallyEvaluatedSize = sizeBinder.evaluateForZoom(static_cast(state.getZoom())); - const ZoomEvaluatedSize partiallyEvaluatedSize = sizeBinder.evaluateForZoom(static_cast(state.getZoom())); + const std::array clippingBuffer = { + {256.0 / state.getSize().width * 2.0 + 1.0, 256.0 / state.getSize().height * 2.0 + 1.0}}; - const std::array clippingBuffer = {{ 256.0 / state.getSize().width * 2.0 + 1.0, 256.0 / state.getSize().height * 2.0 + 1.0 }}; + const float pixelsToTileUnits = tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom())); - const float pixelsToTileUnits = tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom())); + const mat4 labelPlaneMatrix = getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); - const mat4 labelPlaneMatrix = getLabelPlaneMatrix(posMatrix, pitchWithMap, - rotateWithMap, state, pixelsToTileUnits); - - const mat4 glCoordMatrix = getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); - - dynamicVertexArray.clear(); - - bool useVertical = false; + const mat4 glCoordMatrix = getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); - for (auto& placedSymbol : placedSymbols) { - // Don't do calculations for vertical glyphs unless the previous symbol was horizontal - // and we determined that vertical glyphs were necessary. - // Also don't do calculations for symbols that are collided and fully faded out - if (placedSymbol.hidden || (placedSymbol.writingModes == WritingModeType::Vertical && !useVertical)) { - hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); - continue; - } - // Awkward... but we're counting on the paired "vertical" symbol coming immediately after its horizontal counterpart - useVertical = false; - - vec4 anchorPos = {{ placedSymbol.anchorPoint.x, placedSymbol.anchorPoint.y, 0, 1 }}; - matrix::transformMat4(anchorPos, anchorPos, posMatrix); - - // Don't bother calculating the correct point for invisible labels. - if (!isVisible(anchorPos, clippingBuffer)) { - hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); - continue; - } + dynamicVertexArray.clear(); - const auto cameraToAnchorDistance = static_cast(anchorPos[3]); - const float perspectiveRatio = 0.5f + 0.5f * (cameraToAnchorDistance / state.getCameraToCenterDistance()); + bool useVertical = false; - const float fontSize = evaluateSizeForFeature(partiallyEvaluatedSize, placedSymbol); - const float pitchScaledFontSize = pitchWithMap ? - fontSize * perspectiveRatio : - fontSize / perspectiveRatio; + for (auto& placedSymbol : placedSymbols) { + // Don't do calculations for vertical glyphs unless the previous symbol was horizontal + // and we determined that vertical glyphs were necessary. + // Also don't do calculations for symbols that are collided and fully faded out + if (placedSymbol.hidden || (placedSymbol.writingModes == WritingModeType::Vertical && !useVertical)) { + hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); + continue; + } + // Awkward... but we're counting on the paired "vertical" symbol coming immediately after its horizontal + // counterpart + useVertical = false; - const Point anchorPoint = project(placedSymbol.anchorPoint, labelPlaneMatrix).first; + vec4 anchorPos = {{placedSymbol.anchorPoint.x, placedSymbol.anchorPoint.y, 0, 1}}; + matrix::transformMat4(anchorPos, anchorPos, posMatrix); - PlacementResult placeUnflipped = placeGlyphsAlongLine(placedSymbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, dynamicVertexArray, anchorPoint, state.getSize().aspectRatio()); - - useVertical = placeUnflipped == PlacementResult::UseVertical; + // Don't bother calculating the correct point for invisible labels. + if (!isVisible(anchorPos, clippingBuffer)) { + hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); + continue; + } - if (placeUnflipped == PlacementResult::NotEnoughRoom || useVertical || - (placeUnflipped == PlacementResult::NeedsFlipping && - placeGlyphsAlongLine(placedSymbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, dynamicVertexArray, anchorPoint, state.getSize().aspectRatio()) == PlacementResult::NotEnoughRoom)) { - hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); - } + const auto cameraToAnchorDistance = static_cast(anchorPos[3]); + const float perspectiveRatio = 0.5f + 0.5f * (cameraToAnchorDistance / state.getCameraToCenterDistance()); + + const float fontSize = evaluateSizeForFeature(partiallyEvaluatedSize, placedSymbol); + const float pitchScaledFontSize = pitchWithMap ? fontSize * perspectiveRatio : fontSize / perspectiveRatio; + + const Point anchorPoint = project(placedSymbol.anchorPoint, labelPlaneMatrix).first; + + PlacementResult placeUnflipped = placeGlyphsAlongLine( + placedSymbol, + pitchScaledFontSize, + false /*unflipped*/, + keepUpright, + posMatrix, + labelPlaneMatrix, + glCoordMatrix, + dynamicVertexArray, + anchorPoint, + state.getSize().aspectRatio() + ); + + useVertical = placeUnflipped == PlacementResult::UseVertical; + + if (placeUnflipped == PlacementResult::NotEnoughRoom || useVertical || + (placeUnflipped == PlacementResult::NeedsFlipping && placeGlyphsAlongLine( + placedSymbol, + pitchScaledFontSize, + true /*flipped*/, + keepUpright, + posMatrix, + labelPlaneMatrix, + glCoordMatrix, + dynamicVertexArray, + anchorPoint, + state.getSize().aspectRatio() + ) == PlacementResult::NotEnoughRoom)) { + hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); } } +} } // end namespace mbgl diff --git a/src/mbgl/layout/symbol_projection.hpp b/src/mbgl/layout/symbol_projection.hpp index afd5fd5a060..50b7e135329 100644 --- a/src/mbgl/layout/symbol_projection.hpp +++ b/src/mbgl/layout/symbol_projection.hpp @@ -6,69 +6,71 @@ namespace mbgl { - class TransformState; - class RenderTile; - class SymbolSizeBinder; - class PlacedSymbol; - namespace style { - class SymbolPropertyValues; - } // end namespace style - - struct TileDistance { - TileDistance(float prevTileDistance_, float lastSegmentViewportDistance_) - : prevTileDistance(prevTileDistance_), lastSegmentViewportDistance(lastSegmentViewportDistance_) - {} - float prevTileDistance; - float lastSegmentViewportDistance; - }; - - struct PlacedGlyph { - PlacedGlyph() = default; +class TransformState; +class RenderTile; +class SymbolSizeBinder; +class PlacedSymbol; +namespace style { +class SymbolPropertyValues; +} // end namespace style - PlacedGlyph(Point point_, float angle_, std::optional tileDistance_) - : point(point_), angle(angle_), tileDistance(std::move(tileDistance_)) - {} - PlacedGlyph(PlacedGlyph&& other) noexcept - : point(other.point), angle(other.angle), tileDistance(std::move(other.tileDistance)) {} - PlacedGlyph(const PlacedGlyph& other) = default; - Point point; - float angle; - std::optional tileDistance; - }; +struct TileDistance { + TileDistance(float prevTileDistance_, float lastSegmentViewportDistance_) + : prevTileDistance(prevTileDistance_), + lastSegmentViewportDistance(lastSegmentViewportDistance_) {} + float prevTileDistance; + float lastSegmentViewportDistance; +}; - float evaluateSizeForFeature(const ZoomEvaluatedSize& zoomEvaluatedSize, const PlacedSymbol& placedSymbol); - mat4 getLabelPlaneMatrix(const mat4& posMatrix, - bool pitchWithMap, - bool rotateWithMap, - const TransformState& state, - float pixelsToTileUnits); - mat4 getGlCoordMatrix(const mat4& posMatrix, - bool pitchWithMap, - bool rotateWithMap, - const TransformState& state, - float pixelsToTileUnits); +struct PlacedGlyph { + PlacedGlyph() = default; - using PointAndCameraDistance = std::pair,float>; - PointAndCameraDistance project(const Point& point, const mat4& matrix); + PlacedGlyph(Point point_, float angle_, std::optional tileDistance_) + : point(point_), + angle(angle_), + tileDistance(std::move(tileDistance_)) {} + PlacedGlyph(PlacedGlyph&& other) noexcept + : point(other.point), + angle(other.angle), + tileDistance(std::move(other.tileDistance)) {} + PlacedGlyph(const PlacedGlyph& other) = default; + Point point; + float angle; + std::optional tileDistance; +}; - void reprojectLineLabels(gfx::VertexVector>&, const std::vector&, - const mat4& posMatrix, bool pitchWithMap, bool rotateWithMap, bool keepUpright, - const RenderTile&, const SymbolSizeBinder& sizeBinder, const TransformState&); +float evaluateSizeForFeature(const ZoomEvaluatedSize& zoomEvaluatedSize, const PlacedSymbol& placedSymbol); +mat4 getLabelPlaneMatrix( + const mat4& posMatrix, bool pitchWithMap, bool rotateWithMap, const TransformState& state, float pixelsToTileUnits +); +mat4 getGlCoordMatrix( + const mat4& posMatrix, bool pitchWithMap, bool rotateWithMap, const TransformState& state, float pixelsToTileUnits +); - std::optional> placeFirstAndLastGlyph(float fontScale, - float lineOffsetX, - float lineOffsetY, - bool flip, - const Point& anchorPoint, - const Point& tileAnchorPoint, - const PlacedSymbol& symbol, - const mat4& labelPlaneMatrix, - bool returnTileDistance); +using PointAndCameraDistance = std::pair, float>; +PointAndCameraDistance project(const Point& point, const mat4& matrix); - void hideGlyphs(std::size_t numGlyphs, - gfx::VertexVector>& dynamicVertexArray); - void addDynamicAttributes(const Point& anchorPoint, - float angle, - gfx::VertexVector>& dynamicVertexArray); +void reprojectLineLabels(gfx::VertexVector>&, const std::vector&, const mat4& posMatrix, bool pitchWithMap, bool rotateWithMap, bool keepUpright, const RenderTile&, const SymbolSizeBinder& sizeBinder, const TransformState&); + +std::optional> placeFirstAndLastGlyph( + float fontScale, + float lineOffsetX, + float lineOffsetY, + bool flip, + const Point& anchorPoint, + const Point& tileAnchorPoint, + const PlacedSymbol& symbol, + const mat4& labelPlaneMatrix, + bool returnTileDistance +); + +void hideGlyphs( + std::size_t numGlyphs, gfx::VertexVector>& dynamicVertexArray +); +void addDynamicAttributes( + const Point& anchorPoint, + float angle, + gfx::VertexVector>& dynamicVertexArray +); } // end namespace mbgl diff --git a/src/mbgl/map/map.cpp b/src/mbgl/map/map.cpp index 7bc201a1683..4cad4ae22eb 100644 --- a/src/mbgl/map/map.cpp +++ b/src/mbgl/map/map.cpp @@ -27,20 +27,25 @@ namespace mbgl { using namespace style; -Map::Map(RendererFrontend& frontend, - MapObserver& observer, - const MapOptions& mapOptions, - const ResourceOptions& resourceOptions, - const ClientOptions& clientOptions) +Map::Map( + RendererFrontend& frontend, + MapObserver& observer, + const MapOptions& mapOptions, + const ResourceOptions& resourceOptions, + const ClientOptions& clientOptions +) : impl(std::make_unique( frontend, observer, - FileSourceManager::get() - ? std::shared_ptr(FileSourceManager::get()->getFileSource(ResourceLoader, resourceOptions, clientOptions)) - : nullptr, - mapOptions)) {} + FileSourceManager::get() ? std::shared_ptr(FileSourceManager::get()->getFileSource( + ResourceLoader, resourceOptions, clientOptions + )) + : nullptr, + mapOptions + )) {} -Map::Map(std::unique_ptr impl_) : impl(std::move(impl_)) {} +Map::Map(std::unique_ptr impl_) + : impl(std::move(impl_)) {} Map::~Map() = default; @@ -171,10 +176,12 @@ void Map::rotateBy(const ScreenCoordinate& first, const ScreenCoordinate& second impl->onUpdate(); } -CameraOptions Map::cameraForLatLngBounds(const LatLngBounds& bounds, - const EdgeInsets& padding, - const std::optional& bearing, - const std::optional& pitch) const { +CameraOptions Map::cameraForLatLngBounds( + const LatLngBounds& bounds, + const EdgeInsets& padding, + const std::optional& bearing, + const std::optional& pitch +) const { return cameraForLatLngs( { bounds.northwest(), @@ -184,10 +191,13 @@ CameraOptions Map::cameraForLatLngBounds(const LatLngBounds& bounds, }, padding, bearing, - pitch); + pitch + ); } -CameraOptions cameraForLatLngs(const std::vector& latLngs, const Transform& transform, const EdgeInsets& padding) { +CameraOptions cameraForLatLngs( + const std::vector& latLngs, const Transform& transform, const EdgeInsets& padding +) { if (latLngs.empty()) { return {}; } @@ -217,9 +227,15 @@ CameraOptions cameraForLatLngs(const std::vector& latLngs, const Transfo double zoom = transform.getZoom(); if (minScale > 0) { - zoom = util::clamp(zoom + util::log2(minScale), transform.getState().getMinZoom(), transform.getState().getMaxZoom()); + zoom = util::clamp( + zoom + util::log2(minScale), transform.getState().getMinZoom(), transform.getState().getMaxZoom() + ); } else { - Log::Error(Event::General, "Unable to calculate appropriate zoom level for bounds. Vertical or horizontal padding is greater than map's height or width."); + Log::Error( + Event::General, + "Unable to calculate appropriate zoom level for bounds. Vertical or horizontal padding is greater " + "than map's height or width." + ); } // Calculate the center point of a virtual bounds that is extended in all directions by padding. @@ -232,10 +248,12 @@ CameraOptions cameraForLatLngs(const std::vector& latLngs, const Transfo .withZoom(zoom); } -CameraOptions Map::cameraForLatLngs(const std::vector& latLngs, - const EdgeInsets& padding, - const std::optional& bearing, - const std::optional& pitch) const { +CameraOptions Map::cameraForLatLngs( + const std::vector& latLngs, + const EdgeInsets& padding, + const std::optional& bearing, + const std::optional& pitch +) const { if (!bearing && !pitch) { return mbgl::cameraForLatLngs(latLngs, impl->transform, padding); } @@ -251,25 +269,25 @@ CameraOptions Map::cameraForLatLngs(const std::vector& latLngs, .withPitch(util::rad2deg(transform.getPitch())); } -CameraOptions Map::cameraForGeometry(const Geometry& geometry, - const EdgeInsets& padding, - const std::optional& bearing, - const std::optional& pitch) const { +CameraOptions Map::cameraForGeometry( + const Geometry& geometry, + const EdgeInsets& padding, + const std::optional& bearing, + const std::optional& pitch +) const { std::vector latLngs; - forEachPoint(geometry, [&](const Point& pt) { - latLngs.emplace_back(pt.y, pt.x); - }); + forEachPoint(geometry, [&](const Point& pt) { latLngs.emplace_back(pt.y, pt.x); }); return cameraForLatLngs(latLngs, padding, bearing, pitch); } LatLngBounds Map::latLngBoundsForCamera(const CameraOptions& camera) const { - Transform shallow { impl->transform.getState() }; + Transform shallow{impl->transform.getState()}; Size size = shallow.getState().getSize(); shallow.jumpTo(camera); return LatLngBounds::hull( shallow.screenCoordinateToLatLng({}), - shallow.screenCoordinateToLatLng({ static_cast(size.width), static_cast(size.height) }) + shallow.screenCoordinateToLatLng({static_cast(size.width), static_cast(size.height)}) ); } @@ -282,7 +300,8 @@ LatLngBounds Map::latLngBoundsForCameraUnwrapped(const CameraOptions& camera) co LatLng se = shallow.screenCoordinateToLatLng({static_cast(size.width), static_cast(size.height)}); LatLng ne = shallow.screenCoordinateToLatLng({static_cast(size.width), 0.0}); LatLng sw = shallow.screenCoordinateToLatLng({0.0, static_cast(size.height)}); - LatLng center = shallow.screenCoordinateToLatLng({static_cast(size.width) / 2, static_cast(size.height) / 2}); + LatLng center = + shallow.screenCoordinateToLatLng({static_cast(size.width) / 2, static_cast(size.height) / 2}); nw.unwrapForShortestPath(center); se.unwrapForShortestPath(center); ne.unwrapForShortestPath(center); @@ -375,13 +394,13 @@ void Map::setViewportMode(mbgl::ViewportMode mode) { MapOptions Map::getMapOptions() const { return std::move(MapOptions() - .withMapMode(impl->mode) - .withConstrainMode(impl->transform.getConstrainMode()) - .withViewportMode(impl->transform.getViewportMode()) - .withCrossSourceCollisions(impl->crossSourceCollisions) - .withNorthOrientation(impl->transform.getNorthOrientation()) - .withSize(impl->transform.getState().getSize()) - .withPixelRatio(impl->pixelRatio)); + .withMapMode(impl->mode) + .withConstrainMode(impl->transform.getConstrainMode()) + .withViewportMode(impl->transform.getViewportMode()) + .withCrossSourceCollisions(impl->crossSourceCollisions) + .withNorthOrientation(impl->transform.getNorthOrientation()) + .withSize(impl->transform.getState().getSize()) + .withPixelRatio(impl->pixelRatio)); } // MARK: - Projection mode diff --git a/src/mbgl/map/map_impl.cpp b/src/mbgl/map/map_impl.cpp index 4fd9ba63ae5..ff57abb63b3 100644 --- a/src/mbgl/map/map_impl.cpp +++ b/src/mbgl/map/map_impl.cpp @@ -7,10 +7,12 @@ namespace mbgl { -Map::Impl::Impl(RendererFrontend& frontend_, - MapObserver& observer_, - std::shared_ptr fileSource_, - const MapOptions& mapOptions) +Map::Impl::Impl( + RendererFrontend& frontend_, + MapObserver& observer_, + std::shared_ptr fileSource_, + const MapOptions& mapOptions +) : observer(observer_), rendererFrontend(frontend_), transform(observer, mapOptions.constrainMode(), mapOptions.viewportMode()), @@ -48,24 +50,25 @@ void Map::Impl::onUpdate() { transform.updateTransitions(timePoint); - UpdateParameters params = {style->impl->isLoaded(), - mode, - pixelRatio, - debugOptions, - timePoint, - transform.getState(), - style->impl->getGlyphURL(), - style->impl->spriteLoaded, - style->impl->getTransitionOptions(), - style->impl->getLight()->impl, - style->impl->getImageImpls(), - style->impl->getSourceImpls(), - style->impl->getLayerImpls(), - annotationManager.makeWeakPtr(), - fileSource, - prefetchZoomDelta, - bool(stillImageRequest), - crossSourceCollisions}; + UpdateParameters params = { + style->impl->isLoaded(), + mode, + pixelRatio, + debugOptions, + timePoint, + transform.getState(), + style->impl->getGlyphURL(), + style->impl->spriteLoaded, + style->impl->getTransitionOptions(), + style->impl->getLight()->impl, + style->impl->getImageImpls(), + style->impl->getSourceImpls(), + style->impl->getLayerImpls(), + annotationManager.makeWeakPtr(), + fileSource, + prefetchZoomDelta, + bool(stillImageRequest), + crossSourceCollisions}; rendererFrontend.update(std::make_shared(std::move(params))); } diff --git a/src/mbgl/map/map_impl.hpp b/src/mbgl/map/map_impl.hpp index 1705de7abf7..2a83afb7a35 100644 --- a/src/mbgl/map/map_impl.hpp +++ b/src/mbgl/map/map_impl.hpp @@ -24,8 +24,7 @@ class ShaderRegistry; struct StillImageRequest { StillImageRequest(Map::StillImageCallback&& callback_) - : callback(std::move(callback_)) { - } + : callback(std::move(callback_)) {} Map::StillImageCallback callback; }; @@ -65,7 +64,7 @@ class Map::Impl final : public style::Observer, public RendererObserver { const float pixelRatio; const bool crossSourceCollisions; - MapDebugOptions debugOptions { MapDebugOptions::NoDebug }; + MapDebugOptions debugOptions{MapDebugOptions::NoDebug}; std::shared_ptr fileSource; @@ -82,8 +81,8 @@ class Map::Impl final : public style::Observer, public RendererObserver { }; // Forward declaration of this method is required for the MapProjection class -CameraOptions cameraForLatLngs(const std::vector& latLngs, - const Transform& transform, - const EdgeInsets& padding); +CameraOptions cameraForLatLngs( + const std::vector& latLngs, const Transform& transform, const EdgeInsets& padding +); } // namespace mbgl diff --git a/src/mbgl/map/map_options.cpp b/src/mbgl/map/map_options.cpp index 4cebb6adabb..656d09a6506 100644 --- a/src/mbgl/map/map_options.cpp +++ b/src/mbgl/map/map_options.cpp @@ -9,12 +9,13 @@ class MapOptions::Impl { ViewportMode viewportMode = ViewportMode::Default; NorthOrientation orientation = NorthOrientation::Upwards; bool crossSourceCollisions = true; - Size size = { 64, 64 }; + Size size = {64, 64}; float pixelRatio = 1.0; }; // These requires the complete type of Impl. -MapOptions::MapOptions() : impl_(std::make_unique()) {} +MapOptions::MapOptions() + : impl_(std::make_unique()) {} MapOptions::~MapOptions() = default; MapOptions::MapOptions(MapOptions&&) noexcept = default; @@ -81,4 +82,4 @@ float MapOptions::pixelRatio() const { return impl_->pixelRatio; } -} // namespace mbgl +} // namespace mbgl diff --git a/src/mbgl/map/map_projection.cpp b/src/mbgl/map/map_projection.cpp index 9c2eda4dd39..b0566e68ac6 100644 --- a/src/mbgl/map/map_projection.cpp +++ b/src/mbgl/map/map_projection.cpp @@ -30,11 +30,10 @@ CameraOptions MapProjection::getCamera() const { return transform->getCameraOptions(std::nullopt); } -void MapProjection::setVisibleCoordinates(const std::vector& latLngs, - const EdgeInsets& padding) { +void MapProjection::setVisibleCoordinates(const std::vector& latLngs, const EdgeInsets& padding) { transform->jumpTo(mbgl::cameraForLatLngs(latLngs, *transform, padding) - .withBearing(util::rad2deg(-transform->getBearing())) - .withPitch(util::rad2deg(transform->getPitch()))); + .withBearing(util::rad2deg(-transform->getBearing())) + .withPitch(util::rad2deg(transform->getPitch()))); } } // namespace mbgl diff --git a/src/mbgl/map/transform.cpp b/src/mbgl/map/transform.cpp index fe853e0d77c..d464f4df404 100644 --- a/src/mbgl/map/transform.cpp +++ b/src/mbgl/map/transform.cpp @@ -18,9 +18,9 @@ namespace mbgl { -/** Converts the given angle (in radians) to be numerically close to the anchor angle, allowing it to be interpolated properly without sudden jumps. */ -static double _normalizeAngle(double angle, double anchorAngle) -{ +/** Converts the given angle (in radians) to be numerically close to the anchor angle, allowing it to be interpolated + * properly without sudden jumps. */ +static double _normalizeAngle(double angle, double anchorAngle) { if (std::isnan(angle) || std::isnan(anchorAngle)) { return 0; } @@ -38,11 +38,9 @@ static double _normalizeAngle(double angle, double anchorAngle) return angle; } -Transform::Transform(MapObserver& observer_, - ConstrainMode constrainMode, - ViewportMode viewportMode) - : observer(observer_), state(constrainMode, viewportMode) { -} +Transform::Transform(MapObserver& observer_, ConstrainMode constrainMode, ViewportMode viewportMode) + : observer(observer_), + state(constrainMode, viewportMode) {} // MARK: - Map View @@ -154,17 +152,20 @@ void Transform::easeTo(const CameraOptions& camera, const AnimationOptions& anim if (padding != startEdgeInsets) { // Interpolate edge insets EdgeInsets edgeInsets; - state.setEdgeInsets({util::interpolate(startEdgeInsets.top(), padding.top(), t), - util::interpolate(startEdgeInsets.left(), padding.left(), t), - util::interpolate(startEdgeInsets.bottom(), padding.bottom(), t), - util::interpolate(startEdgeInsets.right(), padding.right(), t)}); + state.setEdgeInsets( + {util::interpolate(startEdgeInsets.top(), padding.top(), t), + util::interpolate(startEdgeInsets.left(), padding.left(), t), + util::interpolate(startEdgeInsets.bottom(), padding.bottom(), t), + util::interpolate(startEdgeInsets.right(), padding.right(), t)} + ); } double maxPitch = getMaxPitchForEdgeInsets(state.getEdgeInsets()); if (pitch != startPitch || maxPitch < startPitch) { state.setPitch(std::min(maxPitch, util::interpolate(startPitch, pitch, t))); } }, - duration); + duration + ); } /** This method implements an “optimal path” animation, as detailed in: @@ -210,8 +211,10 @@ void Transform::flyTo(const CameraOptions& camera, const AnimationOptions& anima /// w₀: Initial visible span, measured in pixels at the initial scale. /// Known henceforth as a screenful. - double w0 = std::max(state.getSize().width - padding.left() - padding.right(), - state.getSize().height - padding.top() - padding.bottom()); + double w0 = std::max( + state.getSize().width - padding.left() - padding.right(), + state.getSize().height - padding.top() - padding.bottom() + ); /// w₁: Final visible span, measured in pixels with respect to the initial /// scale. double w1 = w0 / state.zoomScale(zoom - startZoom); @@ -260,19 +263,16 @@ void Transform::flyTo(const CameraOptions& camera, const AnimationOptions& anima Assumes an angular field of view of 2 arctan ½ ≈ 53°. */ auto w = [=](double s) { - return (isClose ? std::exp((w1 < w0 ? -1 : 1) * rho * s) - : (std::cosh(r0) / std::cosh(r0 + rho * s))); + return (isClose ? std::exp((w1 < w0 ? -1 : 1) * rho * s) : (std::cosh(r0) / std::cosh(r0 + rho * s))); }; /// u(s): Returns the distance along the flight path as projected onto the /// ground plane, measured in pixels from the world image origin at the /// initial scale. auto u = [=](double s) { - return (isClose ? 0. - : (w0 * (std::cosh(r0) * std::tanh(r0 + rho * s) - std::sinh(r0)) / rho2 / u1)); + return (isClose ? 0. : (w0 * (std::cosh(r0) * std::tanh(r0 + rho * s) - std::sinh(r0)) / rho2 / u1)); }; /// S: Total length of the flight path, measured in ρ-screenfuls. - double S = (isClose ? (std::abs(std::log(w1 / w0)) / rho) - : ((r1 - r0) / rho)); + double S = (isClose ? (std::abs(std::log(w1 / w0)) / rho) : ((r1 - r0) / rho)); Duration duration; if (animation.duration) { @@ -297,7 +297,9 @@ void Transform::flyTo(const CameraOptions& camera, const AnimationOptions& anima const double startScale = state.getScale(); state.setProperties( TransformStateProperties().withPanningInProgress(true).withScalingInProgress(true).withRotatingInProgress( - bearing != startBearing)); + bearing != startBearing + ) + ); const EdgeInsets startEdgeInsets = state.getEdgeInsets(); startTransition( @@ -311,8 +313,8 @@ void Transform::flyTo(const CameraOptions& camera, const AnimationOptions& anima // Calculate the current point and zoom level along the flight path. Point framePoint = util::interpolate(startPoint, endPoint, us); - double frameZoom = - linearZoomInterpolation ? util::interpolate(startZoom, zoom, k) : startZoom + state.scaleZoom(1 / w(s)); + double frameZoom = linearZoomInterpolation ? util::interpolate(startZoom, zoom, k) + : startZoom + state.scaleZoom(1 / w(s)); // Zoom can be NaN if size is empty. if (std::isnan(frameZoom)) { @@ -328,10 +330,12 @@ void Transform::flyTo(const CameraOptions& camera, const AnimationOptions& anima if (padding != startEdgeInsets) { // Interpolate edge insets - state.setEdgeInsets({util::interpolate(startEdgeInsets.top(), padding.top(), k), - util::interpolate(startEdgeInsets.left(), padding.left(), k), - util::interpolate(startEdgeInsets.bottom(), padding.bottom(), k), - util::interpolate(startEdgeInsets.right(), padding.right(), k)}); + state.setEdgeInsets( + {util::interpolate(startEdgeInsets.top(), padding.top(), k), + util::interpolate(startEdgeInsets.left(), padding.left(), k), + util::interpolate(startEdgeInsets.bottom(), padding.bottom(), k), + util::interpolate(startEdgeInsets.right(), padding.right(), k)} + ); } double maxPitch = getMaxPitchForEdgeInsets(state.getEdgeInsets()); @@ -339,15 +343,16 @@ void Transform::flyTo(const CameraOptions& camera, const AnimationOptions& anima state.setPitch(std::min(maxPitch, util::interpolate(startPitch, pitch, k))); } }, - duration); + duration + ); } // MARK: - Position void Transform::moveBy(const ScreenCoordinate& offset, const AnimationOptions& animation) { ScreenCoordinate centerOffset = {offset.x, offset.y}; - ScreenCoordinate pointOnScreen = - state.getEdgeInsets().getCenter(state.getSize().width, state.getSize().height) - centerOffset; + ScreenCoordinate pointOnScreen = state.getEdgeInsets().getCenter(state.getSize().width, state.getSize().height) - + centerOffset; // Use unwrapped LatLng to carry information about moveBy direction. easeTo(CameraOptions().withCenter(screenCoordinateToLatLng(pointOnScreen, LatLng::Unwrapped)), animation); } @@ -384,9 +389,11 @@ void Transform::setMaxZoom(const double maxZoom) { void Transform::setMinPitch(const double minPitch) { if (std::isnan(minPitch)) return; if (util::deg2rad(minPitch) < util::PITCH_MIN) { - Log::Warning(Event::General, - "Trying to set minimum pitch below the limit (" + std::to_string(util::rad2deg(util::PITCH_MIN)) + - " degrees), the value will be clamped."); + Log::Warning( + Event::General, + "Trying to set minimum pitch below the limit (" + std::to_string(util::rad2deg(util::PITCH_MIN)) + + " degrees), the value will be clamped." + ); } state.setMinPitch(util::deg2rad(minPitch)); } @@ -394,18 +401,20 @@ void Transform::setMinPitch(const double minPitch) { void Transform::setMaxPitch(const double maxPitch) { if (std::isnan(maxPitch)) return; if (util::deg2rad(maxPitch) > util::PITCH_MAX) { - Log::Warning(Event::General, - "Trying to set maximum pitch above the limit (" + std::to_string(util::rad2deg(util::PITCH_MAX)) + - " degrees), the value will be clamped."); + Log::Warning( + Event::General, + "Trying to set maximum pitch above the limit (" + std::to_string(util::rad2deg(util::PITCH_MAX)) + + " degrees), the value will be clamped." + ); } state.setMaxPitch(util::deg2rad(maxPitch)); } // MARK: - Bearing -void Transform::rotateBy(const ScreenCoordinate& first, - const ScreenCoordinate& second, - const AnimationOptions& animation) { +void Transform::rotateBy( + const ScreenCoordinate& first, const ScreenCoordinate& second, const AnimationOptions& animation +) { ScreenCoordinate center = state.getEdgeInsets().getCenter(state.getSize().width, state.getSize().height); const ScreenCoordinate offset = first - center; const double distance = std::sqrt(std::pow(2, offset.x) + std::pow(2, offset.y)); @@ -491,17 +500,20 @@ ProjectionMode Transform::getProjectionMode() const { // MARK: - Transition -void Transform::startTransition(const CameraOptions& camera, - const AnimationOptions& animation, - const std::function& frame, - const Duration& duration) { +void Transform::startTransition( + const CameraOptions& camera, + const AnimationOptions& animation, + const std::function& frame, + const Duration& duration +) { if (transitionFinishFn) { transitionFinishFn(); } bool isAnimated = duration != Duration::zero(); - observer.onCameraWillChange(isAnimated ? MapObserver::CameraChangeMode::Animated - : MapObserver::CameraChangeMode::Immediate); + observer.onCameraWillChange( + isAnimated ? MapObserver::CameraChangeMode::Animated : MapObserver::CameraChangeMode::Immediate + ); // Associate the anchor, if given, with a coordinate. // Anchor and center points are mutually exclusive, with preference for the @@ -543,12 +555,15 @@ void Transform::startTransition(const CameraOptions& camera, transitionFinishFn = [isAnimated, animation, this] { state.setProperties( TransformStateProperties().withPanningInProgress(false).withScalingInProgress(false).withRotatingInProgress( - false)); + false + ) + ); if (animation.transitionFinishFn) { animation.transitionFinishFn(); } - observer.onCameraDidChange(isAnimated ? MapObserver::CameraChangeMode::Animated - : MapObserver::CameraChangeMode::Immediate); + observer.onCameraDidChange( + isAnimated ? MapObserver::CameraChangeMode::Animated : MapObserver::CameraChangeMode::Immediate + ); }; if (!isAnimated) { @@ -568,7 +583,6 @@ bool Transform::inTransition() const { } void Transform::updateTransitions(const TimePoint& now) { - // Use a temporary function to ensure that the transitionFrameFn lambda is // called only once per update. diff --git a/src/mbgl/map/transform.hpp b/src/mbgl/map/transform.hpp index a1458bf8ccf..0a0dd48aaa7 100644 --- a/src/mbgl/map/transform.hpp +++ b/src/mbgl/map/transform.hpp @@ -18,11 +18,15 @@ namespace mbgl { class Transform : private util::noncopyable { public: - Transform(MapObserver& = MapObserver::nullObserver(), - ConstrainMode = ConstrainMode::HeightOnly, - ViewportMode = ViewportMode::Default); + Transform( + MapObserver& = MapObserver::nullObserver(), + ConstrainMode = ConstrainMode::HeightOnly, + ViewportMode = ViewportMode::Default + ); - Transform(const TransformState &state_) : observer(MapObserver::nullObserver()), state(state_) {} + Transform(const TransformState& state_) + : observer(MapObserver::nullObserver()), + state(state_) {} // Map view void resize(Size size); @@ -120,13 +124,11 @@ class Transform : private util::noncopyable { MapObserver& observer; TransformState state; - void startTransition(const CameraOptions&, - const AnimationOptions&, - const std::function&, - const Duration&); + void + startTransition(const CameraOptions&, const AnimationOptions&, const std::function&, const Duration&); // We don't want to show horizon: limit max pitch based on edge insets. - double getMaxPitchForEdgeInsets(const EdgeInsets &insets) const; + double getMaxPitchForEdgeInsets(const EdgeInsets& insets) const; TimePoint transitionStart; Duration transitionDuration; diff --git a/src/mbgl/map/transform_state.cpp b/src/mbgl/map/transform_state.cpp index f8ebacbe1b1..5f2d57770df 100644 --- a/src/mbgl/map/transform_state.cpp +++ b/src/mbgl/map/transform_state.cpp @@ -13,16 +13,17 @@ namespace mbgl { namespace { LatLng latLngFromMercator(Point mercatorCoordinate, LatLng::WrapMode wrapMode = LatLng::WrapMode::Unwrapped) { - return {util::rad2deg(2 * std::atan(std::exp(M_PI - mercatorCoordinate.y * util::M2PI)) - M_PI_2), - mercatorCoordinate.x * 360.0 - 180.0, - wrapMode}; + return { + util::rad2deg(2 * std::atan(std::exp(M_PI - mercatorCoordinate.y * util::M2PI)) - M_PI_2), + mercatorCoordinate.x * 360.0 - 180.0, + wrapMode}; } constexpr double kEpsilon = 1e-9; // To avoid flickering issue due to "zoom = 13.9999999..". double roundForAccuracy(double x) { double round_x = std::round(x); double diff = std::abs(round_x - x); - if (diff < kEpsilon && diff > 0 ){ + if (diff < kEpsilon && diff > 0) { return round_x; } else { return x; @@ -31,7 +32,9 @@ double roundForAccuracy(double x) { } // namespace TransformState::TransformState(ConstrainMode constrainMode_, ViewportMode viewportMode_) - : bounds(LatLngBounds()), constrainMode(constrainMode_), viewportMode(viewportMode_) {} + : bounds(LatLngBounds()), + constrainMode(constrainMode_), + viewportMode(viewportMode_) {} void TransformState::setProperties(const TransformStateProperties& properties) { if (properties.x) { @@ -91,11 +94,13 @@ void TransformState::matrixFor(mat4& matrix, const UnwrappedTileID& tileID) cons const double s = Projection::worldSize(scale) / tileScale; matrix::identity(matrix); - matrix::translate(matrix, - matrix, - int64_t(tileID.canonical.x + tileID.wrap * static_cast(tileScale)) * s, - int64_t(tileID.canonical.y) * s, - 0); + matrix::translate( + matrix, + matrix, + int64_t(tileID.canonical.x + tileID.wrap * static_cast(tileScale)) * s, + int64_t(tileID.canonical.y) * s, + 0 + ); matrix::scale(matrix, matrix, s / util::EXTENT, s / util::EXTENT, 1); } @@ -126,8 +131,9 @@ void TransformState::getProjMatrix(mat4& projMatrix, uint16_t nearZ, bool aligne updateCameraState(); mat4 worldToCamera = camera.getWorldToCamera(scale, viewportMode == ViewportMode::FlippedY); - mat4 cameraToClip = - camera.getCameraToClipPerspective(getFieldOfView(), static_cast(size.width) / size.height, nearZ, farZ); + mat4 cameraToClip = camera.getCameraToClipPerspective( + getFieldOfView(), static_cast(size.width) / size.height, nearZ, farZ + ); // Move the center of perspective to center of specified edgeInsets. // Values are in range [-1, 1] where the upper and lower range values @@ -198,9 +204,10 @@ void TransformState::updateCameraState() const { camera.setOrientation(getPitch(), getBearing()); const vec3 forward = camera.forward(); - const vec3 orbitPosition = {{-forward[0] * cameraToCenterDistance, - -forward[1] * cameraToCenterDistance, - -forward[2] * cameraToCenterDistance}}; + const vec3 orbitPosition = { + {-forward[0] * cameraToCenterDistance, + -forward[1] * cameraToCenterDistance, + -forward[2] * cameraToCenterDistance}}; vec3 cameraPosition = {{dx + orbitPosition[0], dy + orbitPosition[1], orbitPosition[2]}}; cameraPosition[0] /= worldSize; @@ -812,10 +819,10 @@ float TransformState::maxPitchScaleFactor() const { if (size.isEmpty()) { return {}; } - auto latLng = screenCoordinateToLatLng({ 0, static_cast(getSize().height) }); + auto latLng = screenCoordinateToLatLng({0, static_cast(getSize().height)}); Point pt = Projection::project(latLng, scale) / util::tileSize_D; - vec4 p = {{ pt.x, pt.y, 0, 1 }}; + vec4 p = {{pt.x, pt.y, 0, 1}}; vec4 topPoint; matrix::transformMat4(topPoint, p, getCoordMatrix()); return static_cast(topPoint[3]) / getCameraToCenterDistance(); diff --git a/src/mbgl/math/log2.cpp b/src/mbgl/math/log2.cpp index 222e67dbd71..33ec65953bc 100644 --- a/src/mbgl/math/log2.cpp +++ b/src/mbgl/math/log2.cpp @@ -5,9 +5,13 @@ namespace util { // From http://stackoverflow.com/questions/3272424/compute-fast-log-base-2-ceiling uint32_t ceil_log2(uint64_t x) { - static const uint64_t t[6] = {0xFFFFFFFF00000000, 0x00000000FFFF0000, - 0x000000000000FF00, 0x00000000000000F0, - 0x000000000000000C, 0x0000000000000002}; + static const uint64_t t[6] = { + 0xFFFFFFFF00000000, + 0x00000000FFFF0000, + 0x000000000000FF00, + 0x00000000000000F0, + 0x000000000000000C, + 0x0000000000000002}; uint32_t y = (((x & (x - 1)) == 0) ? 0 : 1); uint32_t j = 32; diff --git a/src/mbgl/platform/gl_functions.cpp b/src/mbgl/platform/gl_functions.cpp index 1ffbd47b486..7550db41700 100644 --- a/src/mbgl/platform/gl_functions.cpp +++ b/src/mbgl/platform/gl_functions.cpp @@ -9,10 +9,12 @@ namespace platform { #ifndef NDEBUG void glCheckError(const char* cmd, const char* file, int line) { if (GLenum err = glGetError()) { - Log::Warning(Event::OpenGL, "Error" + std::to_string(err) + ": " + cmd + " - " + file + ":" + std::to_string(line)); + Log::Warning( + Event::OpenGL, "Error" + std::to_string(err) + ": " + cmd + " - " + file + ":" + std::to_string(line) + ); } } #endif -} // namespace platform -} // namespace mbgl +} // namespace platform +} // namespace mbgl diff --git a/src/mbgl/platform/settings.cpp b/src/mbgl/platform/settings.cpp index 10c8d109c6c..17fc1285608 100644 --- a/src/mbgl/platform/settings.cpp +++ b/src/mbgl/platform/settings.cpp @@ -21,7 +21,8 @@ class Settings::Impl { std::mutex mutex; }; -Settings::Settings() : impl(std::make_unique()) {} +Settings::Settings() + : impl(std::make_unique()) {} Settings& Settings::getInstance() noexcept { static Settings instance; diff --git a/src/mbgl/programs/attributes.hpp b/src/mbgl/programs/attributes.hpp index 09d5eca8091..b6df1c145d6 100644 --- a/src/mbgl/programs/attributes.hpp +++ b/src/mbgl/programs/attributes.hpp @@ -16,7 +16,7 @@ MBGL_DEFINE_ATTRIBUTE(int16_t, 4, pixeloffset); MBGL_DEFINE_ATTRIBUTE(int16_t, 2, label_pos); MBGL_DEFINE_ATTRIBUTE(int16_t, 2, anchor_pos); MBGL_DEFINE_ATTRIBUTE(uint16_t, 2, texture_pos); -MBGL_DEFINE_ATTRIBUTE(int16_t, 4, normal_ed); +MBGL_DEFINE_ATTRIBUTE(int16_t, 4, normal_ed); MBGL_DEFINE_ATTRIBUTE(float, 1, fade_opacity); MBGL_DEFINE_ATTRIBUTE(uint8_t, 2, placed); MBGL_DEFINE_ATTRIBUTE(uint16_t, 3, size); @@ -26,9 +26,7 @@ MBGL_DEFINE_ATTRIBUTE(float, 2, shift); template struct data { using Type = gfx::AttributeType; - static constexpr auto name() { - return "data"; - } + static constexpr auto name() { return "data"; } }; // Paint attributes diff --git a/src/mbgl/programs/background_program.cpp b/src/mbgl/programs/background_program.cpp index 25e351260ab..728a6aff7d5 100644 --- a/src/mbgl/programs/background_program.cpp +++ b/src/mbgl/programs/background_program.cpp @@ -10,35 +10,41 @@ using namespace style; static_assert(sizeof(BackgroundLayoutVertex) == 4, "expected BackgroundLayoutVertex size"); -BackgroundPatternProgram::LayoutUniformValues -BackgroundPatternProgram::layoutUniformValues(mat4 matrix, - float opacity, - Size atlasSize, - const ImagePosition& a, - const ImagePosition& b, - const CrossfadeParameters& fading, - const UnwrappedTileID& tileID, - const TransformState& state) { - int32_t tileSizeAtNearestZoom = static_cast(util::tileSize_D * state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); - int32_t pixelX = static_cast(tileSizeAtNearestZoom * (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z))); +BackgroundPatternProgram::LayoutUniformValues BackgroundPatternProgram::layoutUniformValues( + mat4 matrix, + float opacity, + Size atlasSize, + const ImagePosition& a, + const ImagePosition& b, + const CrossfadeParameters& fading, + const UnwrappedTileID& tileID, + const TransformState& state +) { + int32_t tileSizeAtNearestZoom = + static_cast(util::tileSize_D * state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); + int32_t pixelX = static_cast( + tileSizeAtNearestZoom * (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z)) + ); int32_t pixelY = tileSizeAtNearestZoom * tileID.canonical.y; return { - uniforms::matrix::Value( matrix ), - uniforms::opacity::Value( opacity ), - uniforms::texsize::Value( atlasSize ), - uniforms::pattern_tl_a::Value( a.tl() ), - uniforms::pattern_br_a::Value( a.br() ), - uniforms::pattern_tl_b::Value( b.tl() ), - uniforms::pattern_br_b::Value( b.br() ), - uniforms::pattern_size_a::Value( a.displaySize() ), - uniforms::pattern_size_b::Value( b.displaySize() ), - uniforms::scale_a::Value( fading.fromScale ), - uniforms::scale_b::Value( fading.toScale ), - uniforms::mix::Value( fading.t ), - uniforms::pixel_coord_upper::Value( std::array {{ static_cast(pixelX >> 16), static_cast(pixelY >> 16) }}), - uniforms::pixel_coord_lower::Value( std::array {{ static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF)}}), - uniforms::tile_units_to_pixels::Value( 1.0f / tileID.pixelsToTileUnits(1.0f, state.getIntegerZoom()) ), + uniforms::matrix::Value(matrix), + uniforms::opacity::Value(opacity), + uniforms::texsize::Value(atlasSize), + uniforms::pattern_tl_a::Value(a.tl()), + uniforms::pattern_br_a::Value(a.br()), + uniforms::pattern_tl_b::Value(b.tl()), + uniforms::pattern_br_b::Value(b.br()), + uniforms::pattern_size_a::Value(a.displaySize()), + uniforms::pattern_size_b::Value(b.displaySize()), + uniforms::scale_a::Value(fading.fromScale), + uniforms::scale_b::Value(fading.toScale), + uniforms::mix::Value(fading.t), + uniforms::pixel_coord_upper::Value(std::array{ + {static_cast(pixelX >> 16), static_cast(pixelY >> 16)}}), + uniforms::pixel_coord_lower::Value(std::array{ + {static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF)}}), + uniforms::tile_units_to_pixels::Value(1.0f / tileID.pixelsToTileUnits(1.0f, state.getIntegerZoom())), }; } diff --git a/src/mbgl/programs/background_program.hpp b/src/mbgl/programs/background_program.hpp index beb2c2a0d8c..4fe559705d9 100644 --- a/src/mbgl/programs/background_program.hpp +++ b/src/mbgl/programs/background_program.hpp @@ -13,14 +13,12 @@ namespace mbgl { class ImagePosition; class UnwrappedTileID; class TransformState; -template class Faded; +template +class Faded; using BackgroundLayoutAttributes = PositionOnlyLayoutAttributes; -using BackgroundUniforms = TypeList< - uniforms::matrix, - uniforms::color, - uniforms::opacity>; +using BackgroundUniforms = TypeList; using BackgroundPatternUniforms = TypeList< uniforms::matrix, @@ -40,49 +38,36 @@ using BackgroundPatternUniforms = TypeList< uniforms::tile_units_to_pixels>; class BackgroundProgram final : public Program< - BackgroundProgram, - shaders::BuiltIn::BackgroundProgram, - gfx::PrimitiveType::Triangle, - BackgroundLayoutAttributes, - BackgroundUniforms, - TypeList<>, - style::Properties<>> -{ + BackgroundProgram, + shaders::BuiltIn::BackgroundProgram, + gfx::PrimitiveType::Triangle, + BackgroundLayoutAttributes, + BackgroundUniforms, + TypeList<>, + style::Properties<>> { public: static constexpr std::string_view Name{"BackgroundProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; class BackgroundPatternProgram final : public Program< - BackgroundPatternProgram, - shaders::BuiltIn::BackgroundPatternProgram, - gfx::PrimitiveType::Triangle, - BackgroundLayoutAttributes, - BackgroundPatternUniforms, - TypeList< - textures::image>, - style::Properties<>> -{ + BackgroundPatternProgram, + shaders::BuiltIn::BackgroundPatternProgram, + gfx::PrimitiveType::Triangle, + BackgroundLayoutAttributes, + BackgroundPatternUniforms, + TypeList, + style::Properties<>> { public: static constexpr std::string_view Name{"BackgroundPatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutUniformValues layoutUniformValues(mat4 matrix, - float opacity, - Size atlasSize, - const ImagePosition&, - const ImagePosition&, - const CrossfadeParameters&, - const UnwrappedTileID&, - const TransformState&); + static LayoutUniformValues + layoutUniformValues(mat4 matrix, float opacity, Size atlasSize, const ImagePosition&, const ImagePosition&, const CrossfadeParameters&, const UnwrappedTileID&, const TransformState&); }; using BackgroundLayoutVertex = BackgroundProgram::LayoutVertex; diff --git a/src/mbgl/programs/circle_program.hpp b/src/mbgl/programs/circle_program.hpp index 73d5064c654..387e6f883a4 100644 --- a/src/mbgl/programs/circle_program.hpp +++ b/src/mbgl/programs/circle_program.hpp @@ -13,26 +13,22 @@ MBGL_DEFINE_UNIFORM_SCALAR(bool, scale_with_map); } // namespace uniforms class CircleProgram final : public Program< - CircleProgram, - shaders::BuiltIn::CircleProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos>, - TypeList< - uniforms::matrix, - uniforms::scale_with_map, - uniforms::extrude_scale, - uniforms::device_pixel_ratio, - uniforms::camera_to_center_distance, - uniforms::pitch_with_map>, - TypeList<>, - style::CirclePaintProperties> -{ + CircleProgram, + shaders::BuiltIn::CircleProgram, + gfx::PrimitiveType::Triangle, + TypeList, + TypeList< + uniforms::matrix, + uniforms::scale_with_map, + uniforms::extrude_scale, + uniforms::device_pixel_ratio, + uniforms::camera_to_center_distance, + uniforms::pitch_with_map>, + TypeList<>, + style::CirclePaintProperties> { public: static constexpr std::string_view Name{"CircleProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; @@ -43,12 +39,8 @@ class CircleProgram final : public Program< * @param {number} ey extrude normal */ static LayoutVertex vertex(Point p, float ex, float ey) { - return LayoutVertex { - {{ - static_cast((p.x * 2) + ((ex + 1) / 2)), - static_cast((p.y * 2) + ((ey + 1) / 2)) - }} - }; + return LayoutVertex{ + {{static_cast((p.x * 2) + ((ex + 1) / 2)), static_cast((p.y * 2) + ((ey + 1) / 2))}}}; } }; diff --git a/src/mbgl/programs/clipping_mask_program.cpp b/src/mbgl/programs/clipping_mask_program.cpp index aca76050371..0e433806312 100644 --- a/src/mbgl/programs/clipping_mask_program.cpp +++ b/src/mbgl/programs/clipping_mask_program.cpp @@ -1,5 +1,3 @@ #include -namespace mbgl { - -} // namespace mbgl +namespace mbgl {} // namespace mbgl diff --git a/src/mbgl/programs/clipping_mask_program.hpp b/src/mbgl/programs/clipping_mask_program.hpp index 97a14aec296..d6ed544827e 100644 --- a/src/mbgl/programs/clipping_mask_program.hpp +++ b/src/mbgl/programs/clipping_mask_program.hpp @@ -8,20 +8,16 @@ namespace mbgl { class ClippingMaskProgram final : public Program< - ClippingMaskProgram, - shaders::BuiltIn::ClippingMaskProgram, - gfx::PrimitiveType::Triangle, - PositionOnlyLayoutAttributes, - TypeList< - uniforms::matrix>, - TypeList<>, - style::Properties<>> -{ + ClippingMaskProgram, + shaders::BuiltIn::ClippingMaskProgram, + gfx::PrimitiveType::Triangle, + PositionOnlyLayoutAttributes, + TypeList, + TypeList<>, + style::Properties<>> { public: static constexpr std::string_view Name{"ClippingMaskProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; diff --git a/src/mbgl/programs/collision_box_program.hpp b/src/mbgl/programs/collision_box_program.hpp index 2b913f06023..265a4fe8207 100644 --- a/src/mbgl/programs/collision_box_program.hpp +++ b/src/mbgl/programs/collision_box_program.hpp @@ -10,81 +10,63 @@ namespace mbgl { -using CollisionBoxLayoutAttributes = TypeList< - attributes::pos, - attributes::anchor_pos, - attributes::extrude>; +using CollisionBoxLayoutAttributes = TypeList; using CollisionBoxDynamicAttributes = TypeList; -class CollisionBoxProgram final : public Program< - CollisionBoxProgram, - shaders::BuiltIn::CollisionBoxProgram, - gfx::PrimitiveType::Line, - TypeListConcat, - TypeList< - uniforms::matrix, - uniforms::extrude_scale, - uniforms::camera_to_center_distance>, - TypeList<>, - style::Properties<>> -{ +class CollisionBoxProgram final + : public Program< + CollisionBoxProgram, + shaders::BuiltIn::CollisionBoxProgram, + gfx::PrimitiveType::Line, + TypeListConcat, + TypeList, + TypeList<>, + style::Properties<>> { public: static constexpr std::string_view Name{"CollisionBoxProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static gfx::Vertex layoutVertex(Point a, Point anchor, Point o) { return { - {{ - static_cast(a.x), - static_cast(a.y) - }}, - {{ - static_cast(anchor.x), - static_cast(anchor.y) - }}, - {{ - static_cast(::round(o.x)), - static_cast(::round(o.y)) - }} - }; + {{static_cast(a.x), static_cast(a.y)}}, + {{static_cast(anchor.x), static_cast(anchor.y)}}, + {{static_cast(::round(o.x)), static_cast(::round(o.y))}}}; } static gfx::Vertex dynamicVertex(bool placed, bool notUsed, Point shift) { - return { - {{ static_cast(placed), static_cast(notUsed) }}, - {{ shift.x, shift.y }} - }; + return {{{static_cast(placed), static_cast(notUsed)}}, {{shift.x, shift.y}}}; } - template - void draw(gfx::Context& context, - gfx::RenderPass& renderPass, - const DrawMode& drawMode, - const gfx::DepthMode& depthMode, - const gfx::StencilMode& stencilMode, - const gfx::ColorMode& colorMode, - const gfx::CullFaceMode& cullFaceMode, - const LayoutUniformValues& layoutUniformValues, - const gfx::VertexBuffer>& layoutVertexBuffer, - const gfx::VertexBuffer>& dynamicVertexBuffer, - const gfx::IndexBuffer& indexBuffer, - const SegmentVector& segments, - const Binders& paintPropertyBinders, - const typename PaintProperties::PossiblyEvaluated& currentProperties, - const TextureBindings& textureBindings, - float currentZoom, - const std::string& layerID) { - UniformValues uniformValues = layoutUniformValues - .concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); - - AttributeBindings allAttributeBindings = gfx::AttributeBindings(layoutVertexBuffer) - .concat(gfx::AttributeBindings(dynamicVertexBuffer)) - .concat(paintPropertyBinders.attributeBindings(currentProperties)); + template + void draw( + gfx::Context& context, + gfx::RenderPass& renderPass, + const DrawMode& drawMode, + const gfx::DepthMode& depthMode, + const gfx::StencilMode& stencilMode, + const gfx::ColorMode& colorMode, + const gfx::CullFaceMode& cullFaceMode, + const LayoutUniformValues& layoutUniformValues, + const gfx::VertexBuffer>& layoutVertexBuffer, + const gfx::VertexBuffer>& dynamicVertexBuffer, + const gfx::IndexBuffer& indexBuffer, + const SegmentVector& segments, + const Binders& paintPropertyBinders, + const typename PaintProperties::PossiblyEvaluated& currentProperties, + const TextureBindings& textureBindings, + float currentZoom, + const std::string& layerID + ) { + UniformValues uniformValues = + layoutUniformValues.concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); + + AttributeBindings allAttributeBindings = + gfx::AttributeBindings(layoutVertexBuffer) + .concat(gfx::AttributeBindings(dynamicVertexBuffer)) + .concat(paintPropertyBinders.attributeBindings(currentProperties)); assert(layoutVertexBuffer.elements == dynamicVertexBuffer.elements); @@ -95,87 +77,78 @@ class CollisionBoxProgram final : public Program< drawScopeIt = segment.drawScopes.emplace(layerID, context.createDrawScope()).first; } - program->draw(context, - renderPass, - drawMode, - depthMode, - stencilMode, - colorMode, - cullFaceMode, - uniformValues, - drawScopeIt->second, - allAttributeBindings.offset(segment.vertexOffset), - textureBindings, - indexBuffer, - segment.indexOffset, - segment.indexLength); + program->draw( + context, + renderPass, + drawMode, + depthMode, + stencilMode, + colorMode, + cullFaceMode, + uniformValues, + drawScopeIt->second, + allAttributeBindings.offset(segment.vertexOffset), + textureBindings, + indexBuffer, + segment.indexOffset, + segment.indexLength + ); } } }; - class CollisionCircleProgram final : public Program< - CollisionCircleProgram, - shaders::BuiltIn::CollisionCircleProgram, - gfx::PrimitiveType::Triangle, - TypeListConcat, - TypeList< - uniforms::matrix, - uniforms::extrude_scale, - uniforms::overscale_factor, - uniforms::camera_to_center_distance>, - TypeList<>, - style::Properties<>> -{ + CollisionCircleProgram, + shaders::BuiltIn::CollisionCircleProgram, + gfx::PrimitiveType::Triangle, + TypeListConcat, + TypeList< + uniforms::matrix, + uniforms::extrude_scale, + uniforms::overscale_factor, + uniforms::camera_to_center_distance>, + TypeList<>, + style::Properties<>> { public: static constexpr std::string_view Name{"CollisionCircleProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static gfx::Vertex vertex(Point a, Point anchor, Point o) { return { - {{ - static_cast(a.x), - static_cast(a.y) - }}, - {{ - static_cast(anchor.x), - static_cast(anchor.y) - }}, - {{ - static_cast(::round(o.x)), - static_cast(::round(o.y)) - }} - }; + {{static_cast(a.x), static_cast(a.y)}}, + {{static_cast(anchor.x), static_cast(anchor.y)}}, + {{static_cast(::round(o.x)), static_cast(::round(o.y))}}}; } template - void draw(gfx::Context& context, - gfx::RenderPass& renderPass, - const DrawMode& drawMode, - const gfx::DepthMode& depthMode, - const gfx::StencilMode& stencilMode, - const gfx::ColorMode& colorMode, - const gfx::CullFaceMode& cullFaceMode, - const LayoutUniformValues& layoutUniformValues, - const gfx::VertexBuffer>& layoutVertexBuffer, - const gfx::VertexBuffer>& dynamicVertexBuffer, - const gfx::IndexBuffer& indexBuffer, - const SegmentVector& segments, - const Binders& paintPropertyBinders, - const typename PaintProperties::PossiblyEvaluated& currentProperties, - const TextureBindings& textureBindings, - float currentZoom, - const std::string& layerID) { - UniformValues uniformValues = layoutUniformValues - .concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); - - AttributeBindings allAttributeBindings = gfx::AttributeBindings(layoutVertexBuffer) - .concat(gfx::AttributeBindings(dynamicVertexBuffer)) - .concat(paintPropertyBinders.attributeBindings(currentProperties)); + void draw( + gfx::Context& context, + gfx::RenderPass& renderPass, + const DrawMode& drawMode, + const gfx::DepthMode& depthMode, + const gfx::StencilMode& stencilMode, + const gfx::ColorMode& colorMode, + const gfx::CullFaceMode& cullFaceMode, + const LayoutUniformValues& layoutUniformValues, + const gfx::VertexBuffer>& layoutVertexBuffer, + const gfx::VertexBuffer>& dynamicVertexBuffer, + const gfx::IndexBuffer& indexBuffer, + const SegmentVector& segments, + const Binders& paintPropertyBinders, + const typename PaintProperties::PossiblyEvaluated& currentProperties, + const TextureBindings& textureBindings, + float currentZoom, + const std::string& layerID + ) { + UniformValues uniformValues = + layoutUniformValues.concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); + + AttributeBindings allAttributeBindings = + gfx::AttributeBindings(layoutVertexBuffer) + .concat(gfx::AttributeBindings(dynamicVertexBuffer)) + .concat(paintPropertyBinders.attributeBindings(currentProperties)); for (auto& segment : segments) { auto drawScopeIt = segment.drawScopes.find(layerID); @@ -184,20 +157,22 @@ class CollisionCircleProgram final : public Program< drawScopeIt = segment.drawScopes.emplace(layerID, context.createDrawScope()).first; } - program->draw(context, - renderPass, - drawMode, - depthMode, - stencilMode, - colorMode, - cullFaceMode, - uniformValues, - drawScopeIt->second, - allAttributeBindings.offset(segment.vertexOffset), - textureBindings, - indexBuffer, - segment.indexOffset, - segment.indexLength); + program->draw( + context, + renderPass, + drawMode, + depthMode, + stencilMode, + colorMode, + cullFaceMode, + uniformValues, + drawScopeIt->second, + allAttributeBindings.offset(segment.vertexOffset), + textureBindings, + indexBuffer, + segment.indexOffset, + segment.indexLength + ); } } }; diff --git a/src/mbgl/programs/debug_program.cpp b/src/mbgl/programs/debug_program.cpp index 3396e748724..5ef4dc378ae 100644 --- a/src/mbgl/programs/debug_program.cpp +++ b/src/mbgl/programs/debug_program.cpp @@ -1,5 +1,3 @@ #include -namespace mbgl { - -} // namespace mbgl +namespace mbgl {} // namespace mbgl diff --git a/src/mbgl/programs/debug_program.hpp b/src/mbgl/programs/debug_program.hpp index 68c1c5d12ce..a6394689559 100644 --- a/src/mbgl/programs/debug_program.hpp +++ b/src/mbgl/programs/debug_program.hpp @@ -12,19 +12,16 @@ namespace uniforms { MBGL_DEFINE_UNIFORM_SCALAR(float, overlay_scale); } class DebugProgram final : public Program< - DebugProgram, - shaders::BuiltIn::DebugProgram, - gfx::PrimitiveType::Line, - TypeList, - TypeList, - TypeList, - style::Properties<>> -{ + DebugProgram, + shaders::BuiltIn::DebugProgram, + gfx::PrimitiveType::Line, + TypeList, + TypeList, + TypeList, + style::Properties<>> { public: static constexpr std::string_view Name{"DebugProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; diff --git a/src/mbgl/programs/fill_extrusion_program.cpp b/src/mbgl/programs/fill_extrusion_program.cpp index e1bffa3ed70..22e21554f8e 100644 --- a/src/mbgl/programs/fill_extrusion_program.cpp +++ b/src/mbgl/programs/fill_extrusion_program.cpp @@ -13,7 +13,7 @@ static_assert(sizeof(FillExtrusionLayoutVertex) == 12, "expected FillExtrusionLa std::array lightColor(const EvaluatedLight& light) { const auto color = light.get(); - return {{ color.r, color.g, color.b }}; + return {{color.r, color.g, color.b}}; } std::array lightPosition(const EvaluatedLight& light, const TransformState& state) { @@ -32,47 +32,56 @@ float lightIntensity(const EvaluatedLight& light) { } FillExtrusionProgram::LayoutUniformValues FillExtrusionProgram::layoutUniformValues( - mat4 matrix, const TransformState& state, const float opacity, const EvaluatedLight& light, const float verticalGradient) { + mat4 matrix, + const TransformState& state, + const float opacity, + const EvaluatedLight& light, + const float verticalGradient +) { return { - uniforms::matrix::Value( matrix ), - uniforms::opacity::Value( opacity ), - uniforms::lightcolor::Value( lightColor(light) ), - uniforms::lightpos::Value( lightPosition(light, state) ), - uniforms::lightintensity::Value( lightIntensity(light) ), - uniforms::vertical_gradient::Value( verticalGradient ) - }; + uniforms::matrix::Value(matrix), + uniforms::opacity::Value(opacity), + uniforms::lightcolor::Value(lightColor(light)), + uniforms::lightpos::Value(lightPosition(light, state)), + uniforms::lightintensity::Value(lightIntensity(light)), + uniforms::vertical_gradient::Value(verticalGradient)}; } -FillExtrusionPatternProgram::LayoutUniformValues -FillExtrusionPatternProgram::layoutUniformValues(mat4 matrix, - Size atlasSize, - const CrossfadeParameters& crossfade, - const UnwrappedTileID& tileID, - const TransformState& state, - const float opacity, - const float heightFactor, - const float pixelRatio, - const EvaluatedLight& light, - const float verticalGradient) { +FillExtrusionPatternProgram::LayoutUniformValues FillExtrusionPatternProgram::layoutUniformValues( + mat4 matrix, + Size atlasSize, + const CrossfadeParameters& crossfade, + const UnwrappedTileID& tileID, + const TransformState& state, + const float opacity, + const float heightFactor, + const float pixelRatio, + const EvaluatedLight& light, + const float verticalGradient +) { const auto tileRatio = 1 / tileID.pixelsToTileUnits(1, state.getIntegerZoom()); - int32_t tileSizeAtNearestZoom = static_cast(util::tileSize_D * state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); - int32_t pixelX = static_cast(tileSizeAtNearestZoom * (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z))); + int32_t tileSizeAtNearestZoom = + static_cast(util::tileSize_D * state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); + int32_t pixelX = static_cast( + tileSizeAtNearestZoom * (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z)) + ); int32_t pixelY = tileSizeAtNearestZoom * tileID.canonical.y; return { - uniforms::matrix::Value( matrix ), - uniforms::opacity::Value( opacity ), - uniforms::scale::Value( {{pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale}} ), - uniforms::texsize::Value( atlasSize ), - uniforms::fade::Value( crossfade.t ), - uniforms::pixel_coord_upper::Value( std::array{{ static_cast(pixelX >> 16), static_cast(pixelY >> 16) }} ), - uniforms::pixel_coord_lower::Value( std::array{{ static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF) }} ), - uniforms::height_factor::Value( heightFactor ), - uniforms::lightcolor::Value( lightColor(light) ), - uniforms::lightpos::Value( lightPosition(light, state) ), - uniforms::lightintensity::Value( lightIntensity(light) ), - uniforms::vertical_gradient::Value( verticalGradient ) - }; + uniforms::matrix::Value(matrix), + uniforms::opacity::Value(opacity), + uniforms::scale::Value({{pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale}}), + uniforms::texsize::Value(atlasSize), + uniforms::fade::Value(crossfade.t), + uniforms::pixel_coord_upper::Value(std::array{ + {static_cast(pixelX >> 16), static_cast(pixelY >> 16)}}), + uniforms::pixel_coord_lower::Value(std::array{ + {static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF)}}), + uniforms::height_factor::Value(heightFactor), + uniforms::lightcolor::Value(lightColor(light)), + uniforms::lightpos::Value(lightPosition(light, state)), + uniforms::lightintensity::Value(lightIntensity(light)), + uniforms::vertical_gradient::Value(verticalGradient)}; } } // namespace mbgl diff --git a/src/mbgl/programs/fill_extrusion_program.hpp b/src/mbgl/programs/fill_extrusion_program.hpp index 82d24c0ac74..0fe17c6b56a 100644 --- a/src/mbgl/programs/fill_extrusion_program.hpp +++ b/src/mbgl/programs/fill_extrusion_program.hpp @@ -18,19 +18,18 @@ namespace mbgl { class ImagePosition; class UnwrappedTileID; class TransformState; -template class Faded; +template +class Faded; namespace uniforms { MBGL_DEFINE_UNIFORM_VECTOR(float, 3, lightpos); MBGL_DEFINE_UNIFORM_VECTOR(float, 3, lightcolor); -MBGL_DEFINE_UNIFORM_SCALAR(float, lightintensity); -MBGL_DEFINE_UNIFORM_SCALAR(float, vertical_gradient); -MBGL_DEFINE_UNIFORM_SCALAR(float, height_factor); +MBGL_DEFINE_UNIFORM_SCALAR(float, lightintensity); +MBGL_DEFINE_UNIFORM_SCALAR(float, vertical_gradient); +MBGL_DEFINE_UNIFORM_SCALAR(float, height_factor); } // namespace uniforms -using FillExtrusionLayoutAttributes = TypeList< - attributes::pos, - attributes::normal_ed>; +using FillExtrusionLayoutAttributes = TypeList; using FillExtrusionUniforms = TypeList< uniforms::matrix, @@ -55,74 +54,64 @@ using FillExtrusionPatternUniforms = TypeList< uniforms::vertical_gradient>; class FillExtrusionProgram final : public Program< - FillExtrusionProgram, - shaders::BuiltIn::FillExtrusionProgram, - gfx::PrimitiveType::Triangle, - FillExtrusionLayoutAttributes, - FillExtrusionUniforms, - TypeList<>, - style::FillExtrusionPaintProperties> -{ + FillExtrusionProgram, + shaders::BuiltIn::FillExtrusionProgram, + gfx::PrimitiveType::Triangle, + FillExtrusionLayoutAttributes, + FillExtrusionUniforms, + TypeList<>, + style::FillExtrusionPaintProperties> { public: static constexpr std::string_view Name{"FillExtrusionProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static LayoutVertex layoutVertex(Point p, double nx, double ny, double nz, unsigned short t, uint16_t e) { const auto factor = pow(2, 13); - return LayoutVertex { - {{ - p.x, - p.y - }}, - {{ - // Multiply normal vector components by 2^14 to pack them into integers - // We pack a bool (`t`) into the x component indicating whether it is an upper or lower vertex - static_cast(floor(nx * factor) * 2 + t), - static_cast(ny * factor * 2), - static_cast(nz * factor * 2), - // The edgedistance attribute is used for wrapping fill_extrusion patterns - static_cast(e) - }} - }; + return LayoutVertex{ + {{p.x, p.y}}, + {{// Multiply normal vector components by 2^14 to pack them into integers + // We pack a bool (`t`) into the x component indicating whether it is an upper or lower vertex + static_cast(floor(nx * factor) * 2 + t), + static_cast(ny * factor * 2), + static_cast(nz * factor * 2), + // The edgedistance attribute is used for wrapping fill_extrusion patterns + static_cast(e)}}}; } static LayoutUniformValues layoutUniformValues( - mat4, const TransformState&, float opacity, const EvaluatedLight&, float verticalGradient); + mat4, const TransformState&, float opacity, const EvaluatedLight&, float verticalGradient + ); }; class FillExtrusionPatternProgram final : public Program< - FillExtrusionPatternProgram, - shaders::BuiltIn::FillExtrusionPatternProgram, - gfx::PrimitiveType::Triangle, - FillExtrusionLayoutAttributes, - FillExtrusionPatternUniforms, - TypeList< - textures::image>, - style::FillExtrusionPaintProperties> -{ + FillExtrusionPatternProgram, + shaders::BuiltIn::FillExtrusionPatternProgram, + gfx::PrimitiveType::Triangle, + FillExtrusionLayoutAttributes, + FillExtrusionPatternUniforms, + TypeList, + style::FillExtrusionPaintProperties> { public: static constexpr std::string_view Name{"FillExtrusionPatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutUniformValues layoutUniformValues(mat4, - Size atlasSize, - const CrossfadeParameters&, - const UnwrappedTileID&, - const TransformState&, - float opacity, - float heightFactor, - float pixelRatio, - const EvaluatedLight&, - float verticalGradient); + static LayoutUniformValues layoutUniformValues( + mat4, + Size atlasSize, + const CrossfadeParameters&, + const UnwrappedTileID&, + const TransformState&, + float opacity, + float heightFactor, + float pixelRatio, + const EvaluatedLight&, + float verticalGradient + ); }; using FillExtrusionLayoutVertex = FillExtrusionProgram::LayoutVertex; diff --git a/src/mbgl/programs/fill_program.cpp b/src/mbgl/programs/fill_program.cpp index 51fb376cb7e..112a1331169 100644 --- a/src/mbgl/programs/fill_program.cpp +++ b/src/mbgl/programs/fill_program.cpp @@ -10,28 +10,33 @@ using namespace style; static_assert(sizeof(FillLayoutVertex) == 4, "expected FillLayoutVertex size"); -FillPatternProgram::LayoutUniformValues -FillPatternProgram::layoutUniformValues(mat4 matrix, - Size framebufferSize, - Size atlasSize, - const CrossfadeParameters& crossfade, - const UnwrappedTileID& tileID, - const TransformState& state, - const float pixelRatio) { +FillPatternProgram::LayoutUniformValues FillPatternProgram::layoutUniformValues( + mat4 matrix, + Size framebufferSize, + Size atlasSize, + const CrossfadeParameters& crossfade, + const UnwrappedTileID& tileID, + const TransformState& state, + const float pixelRatio +) { const auto tileRatio = 1 / tileID.pixelsToTileUnits(1, state.getIntegerZoom()); - int32_t tileSizeAtNearestZoom = static_cast(util::tileSize_D * state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); - int32_t pixelX = static_cast(tileSizeAtNearestZoom * (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z))); + int32_t tileSizeAtNearestZoom = + static_cast(util::tileSize_D * state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); + int32_t pixelX = static_cast( + tileSizeAtNearestZoom * (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z)) + ); int32_t pixelY = tileSizeAtNearestZoom * tileID.canonical.y; return { - uniforms::matrix::Value( matrix ), - uniforms::world::Value( framebufferSize ), - uniforms::texsize::Value( atlasSize ), - uniforms::scale::Value({ {pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale} } ), - uniforms::fade::Value( crossfade.t ), - uniforms::pixel_coord_upper::Value( std::array {{ static_cast(pixelX >> 16), static_cast(pixelY >> 16) }}), - uniforms::pixel_coord_lower::Value( std::array {{ static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF) }} ) - }; + uniforms::matrix::Value(matrix), + uniforms::world::Value(framebufferSize), + uniforms::texsize::Value(atlasSize), + uniforms::scale::Value({{pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale}}), + uniforms::fade::Value(crossfade.t), + uniforms::pixel_coord_upper::Value(std::array{ + {static_cast(pixelX >> 16), static_cast(pixelY >> 16)}}), + uniforms::pixel_coord_lower::Value(std::array{ + {static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF)}})}; } } // namespace mbgl diff --git a/src/mbgl/programs/fill_program.hpp b/src/mbgl/programs/fill_program.hpp index 0064b533dab..82d5174ccf7 100644 --- a/src/mbgl/programs/fill_program.hpp +++ b/src/mbgl/programs/fill_program.hpp @@ -16,13 +16,12 @@ namespace mbgl { class ImagePosition; class UnwrappedTileID; class TransformState; -template class Faded; +template +class Faded; using FillLayoutAttributes = PositionOnlyLayoutAttributes; -using FillUniforms = TypeList< - uniforms::matrix, - uniforms::world>; +using FillUniforms = TypeList; using FillPatternUniforms = TypeList< uniforms::matrix, @@ -34,92 +33,73 @@ using FillPatternUniforms = TypeList< uniforms::pixel_coord_lower>; class FillProgram final : public Program< - FillProgram, - shaders::BuiltIn::FillProgram, - gfx::PrimitiveType::Triangle, - FillLayoutAttributes, - FillUniforms, - TypeList<>, - style::FillPaintProperties> -{ + FillProgram, + shaders::BuiltIn::FillProgram, + gfx::PrimitiveType::Triangle, + FillLayoutAttributes, + FillUniforms, + TypeList<>, + style::FillPaintProperties> { public: static constexpr std::string_view Name{"FillProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutVertex layoutVertex(Point p) { - return LayoutVertex { - {{ - p.x, - p.y - }} - }; - } + static LayoutVertex layoutVertex(Point p) { return LayoutVertex{{{p.x, p.y}}}; } }; class FillPatternProgram final : public Program< - FillPatternProgram, - shaders::BuiltIn::FillPatternProgram, - gfx::PrimitiveType::Triangle, - FillLayoutAttributes, - FillPatternUniforms, - TypeList< - textures::image>, - style::FillPaintProperties> -{ + FillPatternProgram, + shaders::BuiltIn::FillPatternProgram, + gfx::PrimitiveType::Triangle, + FillLayoutAttributes, + FillPatternUniforms, + TypeList, + style::FillPaintProperties> { public: static constexpr std::string_view Name{"FillPatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutUniformValues layoutUniformValues(mat4 matrix, - Size framebufferSize, - Size atlasSize, - const CrossfadeParameters& crossfade, - const UnwrappedTileID&, - const TransformState&, - float pixelRatio); + static LayoutUniformValues layoutUniformValues( + mat4 matrix, + Size framebufferSize, + Size atlasSize, + const CrossfadeParameters& crossfade, + const UnwrappedTileID&, + const TransformState&, + float pixelRatio + ); }; class FillOutlineProgram final : public Program< - FillOutlineProgram, - shaders::BuiltIn::FillOutlineProgram, - gfx::PrimitiveType::Line, - FillLayoutAttributes, - FillUniforms, - TypeList<>, - style::FillPaintProperties> -{ + FillOutlineProgram, + shaders::BuiltIn::FillOutlineProgram, + gfx::PrimitiveType::Line, + FillLayoutAttributes, + FillUniforms, + TypeList<>, + style::FillPaintProperties> { public: static constexpr std::string_view Name{"FillOutlineProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; class FillOutlinePatternProgram final : public Program< - FillOutlinePatternProgram, - shaders::BuiltIn::FillOutlinePatternProgram, - gfx::PrimitiveType::Line, - FillLayoutAttributes, - FillPatternUniforms, - TypeList< - textures::image>, - style::FillPaintProperties> -{ + FillOutlinePatternProgram, + shaders::BuiltIn::FillOutlinePatternProgram, + gfx::PrimitiveType::Line, + FillLayoutAttributes, + FillPatternUniforms, + TypeList, + style::FillPaintProperties> { public: static constexpr std::string_view Name{"FillOutlinePatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; diff --git a/src/mbgl/programs/heatmap_program.hpp b/src/mbgl/programs/heatmap_program.hpp index 805a663298f..9cd8efe6d86 100644 --- a/src/mbgl/programs/heatmap_program.hpp +++ b/src/mbgl/programs/heatmap_program.hpp @@ -14,23 +14,16 @@ MBGL_DEFINE_UNIFORM_SCALAR(float, intensity); } // namespace uniforms class HeatmapProgram final : public Program< - HeatmapProgram, - shaders::BuiltIn::HeatmapProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos>, - TypeList< - uniforms::intensity, - uniforms::matrix, - uniforms::heatmap::extrude_scale>, - TypeList<>, - style::HeatmapPaintProperties> -{ + HeatmapProgram, + shaders::BuiltIn::HeatmapProgram, + gfx::PrimitiveType::Triangle, + TypeList, + TypeList, + TypeList<>, + style::HeatmapPaintProperties> { public: static constexpr std::string_view Name{"HeatmapProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; @@ -41,12 +34,8 @@ class HeatmapProgram final : public Program< * @param {number} ey extrude normal */ static LayoutVertex vertex(Point p, float ex, float ey) { - return LayoutVertex { - {{ - static_cast((p.x * 2) + ((ex + 1) / 2)), - static_cast((p.y * 2) + ((ey + 1) / 2)) - }} - }; + return LayoutVertex{ + {{static_cast((p.x * 2) + ((ex + 1) / 2)), static_cast((p.y * 2) + ((ey + 1) / 2))}}}; } }; diff --git a/src/mbgl/programs/heatmap_texture_program.hpp b/src/mbgl/programs/heatmap_texture_program.hpp index e3c55d17593..bb66fac7c3a 100644 --- a/src/mbgl/programs/heatmap_texture_program.hpp +++ b/src/mbgl/programs/heatmap_texture_program.hpp @@ -10,34 +10,20 @@ namespace mbgl { class HeatmapTextureProgram final : public Program< - HeatmapTextureProgram, - shaders::BuiltIn::HeatmapTextureProgram, - gfx::PrimitiveType::Triangle, - TypeList, - TypeList< - uniforms::matrix, - uniforms::world, - uniforms::opacity>, - TypeList< - textures::image, - textures::color_ramp>, - style::Properties<>> { + HeatmapTextureProgram, + shaders::BuiltIn::HeatmapTextureProgram, + gfx::PrimitiveType::Triangle, + TypeList, + TypeList, + TypeList, + style::Properties<>> { public: static constexpr std::string_view Name{"HeatmapTextureProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutVertex layoutVertex(Point p) { - return LayoutVertex{ - {{ - p.x, - p.y - }} - }; - } + static LayoutVertex layoutVertex(Point p) { return LayoutVertex{{{p.x, p.y}}}; } }; using HeatmapTextureLayoutVertex = HeatmapTextureProgram::LayoutVertex; diff --git a/src/mbgl/programs/hillshade_prepare_program.hpp b/src/mbgl/programs/hillshade_prepare_program.hpp index beb39088753..ef9d8aa4270 100644 --- a/src/mbgl/programs/hillshade_prepare_program.hpp +++ b/src/mbgl/programs/hillshade_prepare_program.hpp @@ -14,41 +14,23 @@ MBGL_DEFINE_UNIFORM_SCALAR(float, maxzoom); MBGL_DEFINE_UNIFORM_VECTOR(float, 4, unpack); } // namespace uniforms -class HillshadePrepareProgram final : public Program< - HillshadePrepareProgram, - shaders::BuiltIn::HillshadePrepareProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos, - attributes::texture_pos>, - TypeList< - uniforms::matrix, - uniforms::dimension, - uniforms::zoom, - uniforms::maxzoom, - uniforms::unpack>, - TypeList< - textures::image>, - style::Properties<>> { +class HillshadePrepareProgram final + : public Program< + HillshadePrepareProgram, + shaders::BuiltIn::HillshadePrepareProgram, + gfx::PrimitiveType::Triangle, + TypeList, + TypeList, + TypeList, + style::Properties<>> { public: static constexpr std::string_view Name{"HillshadePrepareProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static LayoutVertex layoutVertex(Point p, Point t) { - return LayoutVertex { - {{ - p.x, - p.y - }}, - {{ - t.x, - t.y - }} - }; + return LayoutVertex{{{p.x, p.y}}, {{t.x, t.y}}}; } }; diff --git a/src/mbgl/programs/hillshade_program.hpp b/src/mbgl/programs/hillshade_program.hpp index 5b4de3d3597..ec1356a7115 100644 --- a/src/mbgl/programs/hillshade_program.hpp +++ b/src/mbgl/programs/hillshade_program.hpp @@ -19,41 +19,27 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 2, latrange); } // namespace uniforms class HillshadeProgram final : public Program< - HillshadeProgram, - shaders::BuiltIn::HillshadeProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos, - attributes::texture_pos>, - TypeList< - uniforms::matrix, - uniforms::highlight, - uniforms::shadow, - uniforms::accent, - uniforms::light, - uniforms::latrange>, - TypeList< - textures::image>, - style::HillshadePaintProperties>{ + HillshadeProgram, + shaders::BuiltIn::HillshadeProgram, + gfx::PrimitiveType::Triangle, + TypeList, + TypeList< + uniforms::matrix, + uniforms::highlight, + uniforms::shadow, + uniforms::accent, + uniforms::light, + uniforms::latrange>, + TypeList, + style::HillshadePaintProperties> { public: static constexpr std::string_view Name{"HillshadeProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static LayoutVertex layoutVertex(Point p, Point t) { - return LayoutVertex { - {{ - p.x, - p.y - }}, - {{ - t.x, - t.y - }} - }; + return LayoutVertex{{{p.x, p.y}}, {{t.x, t.y}}}; } }; diff --git a/src/mbgl/programs/line_program.cpp b/src/mbgl/programs/line_program.cpp index a72e4765f74..072216e2bd3 100644 --- a/src/mbgl/programs/line_program.cpp +++ b/src/mbgl/programs/line_program.cpp @@ -12,64 +12,54 @@ using namespace style; static_assert(sizeof(LineLayoutVertex) == 8, "expected LineLayoutVertex size"); -template -Values makeValues(const style::LinePaintProperties::PossiblyEvaluated& properties, - const RenderTile& tile, - const TransformState& state, - const std::array& pixelsToGLUnits, - const float pixelRatio, - Args&&... args) { - - return Values { +template +Values makeValues( + const style::LinePaintProperties::PossiblyEvaluated& properties, + const RenderTile& tile, + const TransformState& state, + const std::array& pixelsToGLUnits, + const float pixelRatio, + Args&&... args +) { + return Values{ uniforms::matrix::Value( - tile.translatedMatrix(properties.get(), - properties.get(), - state) + tile.translatedMatrix(properties.get(), properties.get(), state) ), - uniforms::ratio::Value( 1.0f / tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom())) ), - uniforms::units_to_pixels::Value({ {1.0f / pixelsToGLUnits[0], 1.0f / pixelsToGLUnits[1]} }), - uniforms::device_pixel_ratio::Value( pixelRatio ), - std::forward(args)... - }; + uniforms::ratio::Value(1.0f / tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom()))), + uniforms::units_to_pixels::Value({{1.0f / pixelsToGLUnits[0], 1.0f / pixelsToGLUnits[1]}}), + uniforms::device_pixel_ratio::Value(pixelRatio), + std::forward(args)...}; } -LineProgram::LayoutUniformValues -LineProgram::layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated& properties, - const RenderTile& tile, - const TransformState& state, - const std::array& pixelsToGLUnits, - const float pixelRatio) { - return makeValues( - properties, - tile, - state, - pixelsToGLUnits, - pixelRatio - ); +LineProgram::LayoutUniformValues LineProgram::layoutUniformValues( + const style::LinePaintProperties::PossiblyEvaluated& properties, + const RenderTile& tile, + const TransformState& state, + const std::array& pixelsToGLUnits, + const float pixelRatio +) { + return makeValues(properties, tile, state, pixelsToGLUnits, pixelRatio); } -LineSDFProgram::LayoutUniformValues -LineSDFProgram::layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated& properties, - float pixelRatio, - const RenderTile& tile, - const TransformState& state, - const std::array& pixelsToGLUnits, - const LinePatternPos& posA, - const LinePatternPos& posB, - const CrossfadeParameters& crossfade, - float atlasWidth) { +LineSDFProgram::LayoutUniformValues LineSDFProgram::layoutUniformValues( + const style::LinePaintProperties::PossiblyEvaluated& properties, + float pixelRatio, + const RenderTile& tile, + const TransformState& state, + const std::array& pixelsToGLUnits, + const LinePatternPos& posA, + const LinePatternPos& posB, + const CrossfadeParameters& crossfade, + float atlasWidth +) { const float widthA = posA.width * crossfade.fromScale; const float widthB = posB.width * crossfade.toScale; - std::array scaleA {{ - 1.0f / tile.id.pixelsToTileUnits(widthA, state.getIntegerZoom()), - -posA.height / 2.0f - }}; + std::array scaleA{ + {1.0f / tile.id.pixelsToTileUnits(widthA, state.getIntegerZoom()), -posA.height / 2.0f}}; - std::array scaleB {{ - 1.0f / tile.id.pixelsToTileUnits(widthB, state.getIntegerZoom()), - -posB.height / 2.0f - }}; + std::array scaleB{ + {1.0f / tile.id.pixelsToTileUnits(widthB, state.getIntegerZoom()), -posB.height / 2.0f}}; return makeValues( properties, @@ -77,12 +67,12 @@ LineSDFProgram::layoutUniformValues(const style::LinePaintProperties::PossiblyEv state, pixelsToGLUnits, pixelRatio, - uniforms::patternscale_a::Value( scaleA ), - uniforms::patternscale_b::Value( scaleB ), - uniforms::tex_y_a::Value( posA.y ), - uniforms::tex_y_b::Value( posB.y ), - uniforms::mix::Value( crossfade.t ), - uniforms::sdfgamma::Value( atlasWidth / (std::min(widthA, widthB) * 256.0f * pixelRatio) / 2.0f ) + uniforms::patternscale_a::Value(scaleA), + uniforms::patternscale_b::Value(scaleB), + uniforms::tex_y_a::Value(posA.y), + uniforms::tex_y_b::Value(posB.y), + uniforms::mix::Value(crossfade.t), + uniforms::sdfgamma::Value(atlasWidth / (std::min(widthA, widthB) * 256.0f * pixelRatio) / 2.0f) ); } @@ -93,8 +83,8 @@ LinePatternProgram::LayoutUniformValues LinePatternProgram::layoutUniformValues( const std::array& pixelsToGLUnits, const float pixelRatio, const Size atlasSize, - const CrossfadeParameters& crossfade) { - + const CrossfadeParameters& crossfade +) { const auto tileRatio = 1 / tile.id.pixelsToTileUnits(1, state.getIntegerZoom()); return makeValues( @@ -103,9 +93,9 @@ LinePatternProgram::LayoutUniformValues LinePatternProgram::layoutUniformValues( state, pixelsToGLUnits, pixelRatio, - uniforms::scale::Value ({ {pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale} }), - uniforms::texsize::Value( atlasSize ), - uniforms::fade::Value( crossfade.t ) + uniforms::scale::Value({{pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale}}), + uniforms::texsize::Value(atlasSize), + uniforms::fade::Value(crossfade.t) ); } @@ -114,14 +104,9 @@ LineGradientProgram::LayoutUniformValues LineGradientProgram::layoutUniformValue const RenderTile& tile, const TransformState& state, const std::array& pixelsToGLUnits, - const float pixelRatio) { - return makeValues( - properties, - tile, - state, - pixelsToGLUnits, - pixelRatio - ); + const float pixelRatio +) { + return makeValues(properties, tile, state, pixelsToGLUnits, pixelRatio); } } // namespace mbgl diff --git a/src/mbgl/programs/line_program.hpp b/src/mbgl/programs/line_program.hpp index 59b550de850..9f94a139ee6 100644 --- a/src/mbgl/programs/line_program.hpp +++ b/src/mbgl/programs/line_program.hpp @@ -26,28 +26,20 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 2, patternscale_b); MBGL_DEFINE_UNIFORM_VECTOR(float, 2, units_to_pixels); } // namespace uniforms -using LineLayoutAttributes = TypeList< - attributes::pos_normal, - attributes::data>; - -class LineProgram final : public Program< - LineProgram, - shaders::BuiltIn::LineProgram, - gfx::PrimitiveType::Triangle, - LineLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::ratio, - uniforms::units_to_pixels, - uniforms::device_pixel_ratio>, - TypeList<>, - style::LinePaintProperties> -{ +using LineLayoutAttributes = TypeList>; + +class LineProgram final + : public Program< + LineProgram, + shaders::BuiltIn::LineProgram, + gfx::PrimitiveType::Triangle, + LineLayoutAttributes, + TypeList, + TypeList<>, + style::LinePaintProperties> { public: static constexpr std::string_view Name{"LineProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; @@ -58,31 +50,27 @@ class LineProgram final : public Program< * @param up whether the line normal points up or down * @param dir direction of the line cap (-1/0/1) */ - static LayoutVertex layoutVertex(Point p, Point e, bool round, bool up, int8_t dir, int32_t linesofar = 0) { - return LayoutVertex { - {{ - static_cast((p.x * 2) | (round ? 1 : 0)), - static_cast((p.y * 2) | (up ? 1 : 0)) - }}, - {{ - // add 128 to store a byte in an unsigned byte - static_cast(::round(extrudeScale * e.x) + 128), - static_cast(::round(extrudeScale * e.y) + 128), - - // Encode the -1/0/1 direction value into the first two bits of .z of a_data. - // Combine it with the lower 6 bits of `linesofar` (shifted by 2 bites to make - // room for the direction value). The upper 8 bits of `linesofar` are placed in - // the `w` component. `linesofar` is scaled down by `LINE_DISTANCE_SCALE` so that - // we can store longer distances while sacrificing precision. - - // Encode the -1/0/1 direction value into .zw coordinates of a_data, which is normally covered - // by linesofar, so we need to merge them. - // The z component's first bit, as well as the sign bit is reserved for the direction, - // so we need to shift the linesofar. - static_cast(((dir == 0 ? 0 : (dir < 0 ? -1 : 1 )) + 1) | ((linesofar & 0x3F) << 2)), - static_cast(linesofar >> 6) - }} - }; + static LayoutVertex layoutVertex( + Point p, Point e, bool round, bool up, int8_t dir, int32_t linesofar = 0 + ) { + return LayoutVertex{ + {{static_cast((p.x * 2) | (round ? 1 : 0)), static_cast((p.y * 2) | (up ? 1 : 0))}}, + {{// add 128 to store a byte in an unsigned byte + static_cast(::round(extrudeScale * e.x) + 128), + static_cast(::round(extrudeScale * e.y) + 128), + + // Encode the -1/0/1 direction value into the first two bits of .z of a_data. + // Combine it with the lower 6 bits of `linesofar` (shifted by 2 bites to make + // room for the direction value). The upper 8 bits of `linesofar` are placed in + // the `w` component. `linesofar` is scaled down by `LINE_DISTANCE_SCALE` so that + // we can store longer distances while sacrificing precision. + + // Encode the -1/0/1 direction value into .zw coordinates of a_data, which is normally covered + // by linesofar, so we need to merge them. + // The z component's first bit, as well as the sign bit is reserved for the direction, + // so we need to shift the linesofar. + static_cast(((dir == 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | ((linesofar & 0x3F) << 2)), + static_cast(linesofar >> 6)}}}; } /* @@ -94,114 +82,106 @@ class LineProgram final : public Program< */ static const int8_t extrudeScale = 63; - static LayoutUniformValues layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated&, - const RenderTile&, - const TransformState&, - const std::array& pixelsToGLUnits, - float pixelRatio); + static LayoutUniformValues layoutUniformValues( + const style::LinePaintProperties::PossiblyEvaluated&, + const RenderTile&, + const TransformState&, + const std::array& pixelsToGLUnits, + float pixelRatio + ); }; class LinePatternProgram final : public Program< - LinePatternProgram, - shaders::BuiltIn::LinePatternProgram, - gfx::PrimitiveType::Triangle, - LineLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::ratio, - uniforms::units_to_pixels, - uniforms::device_pixel_ratio, - uniforms::scale, - uniforms::texsize, - uniforms::fade>, - TypeList< - textures::image>, - style::LinePaintProperties> -{ + LinePatternProgram, + shaders::BuiltIn::LinePatternProgram, + gfx::PrimitiveType::Triangle, + LineLayoutAttributes, + TypeList< + uniforms::matrix, + uniforms::ratio, + uniforms::units_to_pixels, + uniforms::device_pixel_ratio, + uniforms::scale, + uniforms::texsize, + uniforms::fade>, + TypeList, + style::LinePaintProperties> { public: static constexpr std::string_view Name{"LinePatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutUniformValues layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated&, - const RenderTile&, - const TransformState&, - const std::array& pixelsToGLUnits, - float pixelRatio, - Size atlasSize, - const CrossfadeParameters& crossfade); + static LayoutUniformValues layoutUniformValues( + const style::LinePaintProperties::PossiblyEvaluated&, + const RenderTile&, + const TransformState&, + const std::array& pixelsToGLUnits, + float pixelRatio, + Size atlasSize, + const CrossfadeParameters& crossfade + ); }; class LineSDFProgram final : public Program< - LineSDFProgram, - shaders::BuiltIn::LineSDFProgram, - gfx::PrimitiveType::Triangle, - LineLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::ratio, - uniforms::units_to_pixels, - uniforms::device_pixel_ratio, - uniforms::patternscale_a, - uniforms::patternscale_b, - uniforms::tex_y_a, - uniforms::tex_y_b, - uniforms::mix, - uniforms::sdfgamma>, - TypeList< - textures::image>, - style::LinePaintProperties> -{ + LineSDFProgram, + shaders::BuiltIn::LineSDFProgram, + gfx::PrimitiveType::Triangle, + LineLayoutAttributes, + TypeList< + uniforms::matrix, + uniforms::ratio, + uniforms::units_to_pixels, + uniforms::device_pixel_ratio, + uniforms::patternscale_a, + uniforms::patternscale_b, + uniforms::tex_y_a, + uniforms::tex_y_b, + uniforms::mix, + uniforms::sdfgamma>, + TypeList, + style::LinePaintProperties> { public: static constexpr std::string_view Name{"LineSDFProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutUniformValues - layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated&, - float pixelRatio, - const RenderTile&, - const TransformState&, - const std::array& pixelsToGLUnits, - const LinePatternPos& posA, - const LinePatternPos& posB, - const CrossfadeParameters& crossfade, - float atlasWidth); + static LayoutUniformValues layoutUniformValues( + const style::LinePaintProperties::PossiblyEvaluated&, + float pixelRatio, + const RenderTile&, + const TransformState&, + const std::array& pixelsToGLUnits, + const LinePatternPos& posA, + const LinePatternPos& posB, + const CrossfadeParameters& crossfade, + float atlasWidth + ); }; -class LineGradientProgram final : public Program< - LineGradientProgram, - shaders::BuiltIn::LineGradientProgram, - gfx::PrimitiveType::Triangle, - LineLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::ratio, - uniforms::units_to_pixels, - uniforms::device_pixel_ratio>, - TypeList< - textures::image>, - style::LinePaintProperties> -{ +class LineGradientProgram final + : public Program< + LineGradientProgram, + shaders::BuiltIn::LineGradientProgram, + gfx::PrimitiveType::Triangle, + LineLayoutAttributes, + TypeList, + TypeList, + style::LinePaintProperties> { public: static constexpr std::string_view Name{"LineGradientProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutUniformValues layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated&, - const RenderTile&, - const TransformState&, - const std::array& pixelsToGLUnits, - float pixelRatio); + static LayoutUniformValues layoutUniformValues( + const style::LinePaintProperties::PossiblyEvaluated&, + const RenderTile&, + const TransformState&, + const std::array& pixelsToGLUnits, + float pixelRatio + ); }; using LineLayoutVertex = LineProgram::LayoutVertex; diff --git a/src/mbgl/programs/program.hpp b/src/mbgl/programs/program.hpp index 1e312f1bf8c..38f3b76bfd6 100644 --- a/src/mbgl/programs/program.hpp +++ b/src/mbgl/programs/program.hpp @@ -24,13 +24,14 @@ namespace gfx { class RenderPass; } // namespace gfx -template +template < + class Name, + shaders::BuiltIn ShaderSource, + gfx::PrimitiveType Primitive, + class LayoutAttributeList, + class LayoutUniformList, + class Textures, + class PaintProps> class Program : public gfx::Shader { public: using LayoutVertex = gfx::Vertex; @@ -56,12 +57,11 @@ class Program : public gfx::Shader { switch (gfx::Backend::GetType()) { #ifdef MBGL_RENDER_BACKEND_OPENGL case gfx::Backend::Type::OpenGL: { - program = std::make_unique>(programParameters - .withDefaultSource({ - gfx::Backend::Type::OpenGL, - shaders::ShaderSource::vertex, - shaders::ShaderSource::fragment - })); + program = std::make_unique>(programParameters.withDefaultSource( + {gfx::Backend::Type::OpenGL, + shaders::ShaderSource::vertex, + shaders::ShaderSource::fragment} + )); break; } #endif @@ -75,15 +75,16 @@ class Program : public gfx::Shader { const LayoutUniformValues& layoutUniformValues, const Binders& paintPropertyBinders, const typename PaintProperties::PossiblyEvaluated& currentProperties, - float currentZoom) { - return layoutUniformValues - .concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); + float currentZoom + ) { + return layoutUniformValues.concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); } static AttributeBindings computeAllAttributeBindings( const gfx::VertexBuffer& layoutVertexBuffer, const Binders& paintPropertyBinders, - const typename PaintProperties::PossiblyEvaluated& currentProperties) { + const typename PaintProperties::PossiblyEvaluated& currentProperties + ) { return gfx::AttributeBindings(layoutVertexBuffer) .concat(paintPropertyBinders.attributeBindings(currentProperties)); } @@ -93,19 +94,21 @@ class Program : public gfx::Shader { } template - void draw(gfx::Context& context, - gfx::RenderPass& renderPass, - const DrawMode& drawMode, - const gfx::DepthMode& depthMode, - const gfx::StencilMode& stencilMode, - const gfx::ColorMode& colorMode, - const gfx::CullFaceMode& cullFaceMode, - const gfx::IndexBuffer& indexBuffer, - const Segment& segment, - const UniformValues& uniformValues, - const AttributeBindings& allAttributeBindings, - const TextureBindings& textureBindings, - const std::string& layerID) { + void draw( + gfx::Context& context, + gfx::RenderPass& renderPass, + const DrawMode& drawMode, + const gfx::DepthMode& depthMode, + const gfx::StencilMode& stencilMode, + const gfx::ColorMode& colorMode, + const gfx::CullFaceMode& cullFaceMode, + const gfx::IndexBuffer& indexBuffer, + const Segment& segment, + const UniformValues& uniformValues, + const AttributeBindings& allAttributeBindings, + const TextureBindings& textureBindings, + const std::string& layerID + ) { static_assert(Primitive == gfx::PrimitiveTypeOf::value, "incompatible draw mode"); if (!program) { @@ -117,36 +120,40 @@ class Program : public gfx::Shader { drawScopeIt = segment.drawScopes.emplace(layerID, context.createDrawScope()).first; } - program->draw(context, - renderPass, - drawMode, - depthMode, - stencilMode, - colorMode, - cullFaceMode, - uniformValues, - drawScopeIt->second, - allAttributeBindings.offset(segment.vertexOffset), - textureBindings, - indexBuffer, - segment.indexOffset, - segment.indexLength); + program->draw( + context, + renderPass, + drawMode, + depthMode, + stencilMode, + colorMode, + cullFaceMode, + uniformValues, + drawScopeIt->second, + allAttributeBindings.offset(segment.vertexOffset), + textureBindings, + indexBuffer, + segment.indexOffset, + segment.indexLength + ); } template - void draw(gfx::Context& context, - gfx::RenderPass& renderPass, - const DrawMode& drawMode, - const gfx::DepthMode& depthMode, - const gfx::StencilMode& stencilMode, - const gfx::ColorMode& colorMode, - const gfx::CullFaceMode& cullFaceMode, - const gfx::IndexBuffer& indexBuffer, - const SegmentVector& segments, - const UniformValues& uniformValues, - const AttributeBindings& allAttributeBindings, - const TextureBindings& textureBindings, - const std::string& layerID) { + void draw( + gfx::Context& context, + gfx::RenderPass& renderPass, + const DrawMode& drawMode, + const gfx::DepthMode& depthMode, + const gfx::StencilMode& stencilMode, + const gfx::ColorMode& colorMode, + const gfx::CullFaceMode& cullFaceMode, + const gfx::IndexBuffer& indexBuffer, + const SegmentVector& segments, + const UniformValues& uniformValues, + const AttributeBindings& allAttributeBindings, + const TextureBindings& textureBindings, + const std::string& layerID + ) { static_assert(Primitive == gfx::PrimitiveTypeOf::value, "incompatible draw mode"); if (!program) { @@ -174,7 +181,8 @@ class Program : public gfx::Shader { textureBindings, indexBuffer, segment.indexOffset, - segment.indexLength); + segment.indexLength + ); } } }; diff --git a/src/mbgl/programs/program_parameters.cpp b/src/mbgl/programs/program_parameters.cpp index 28f10ecca4d..7ff1cc3bcc9 100644 --- a/src/mbgl/programs/program_parameters.cpp +++ b/src/mbgl/programs/program_parameters.cpp @@ -5,40 +5,32 @@ namespace mbgl { -ProgramParameters::ProgramParameters(const float pixelRatio, - const bool overdraw) +ProgramParameters::ProgramParameters(const float pixelRatio, const bool overdraw) : defines([&] { - std::string result; - result.reserve(32); - result += "#define DEVICE_PIXEL_RATIO "; - result += util::toString(pixelRatio, true); - result += '\n'; - if (overdraw) { - result += "#define OVERDRAW_INSPECTOR\n"; - } - return result; - }()) -{} + std::string result; + result.reserve(32); + result += "#define DEVICE_PIXEL_RATIO "; + result += util::toString(pixelRatio, true); + result += '\n'; + if (overdraw) { + result += "#define OVERDRAW_INSPECTOR\n"; + } + return result; + }()) {} -ProgramParameters ProgramParameters::withShaderSource( - const ProgramSource &source) const noexcept -{ +ProgramParameters ProgramParameters::withShaderSource(const ProgramSource& source) const noexcept { assert(gfx::Backend::Type::TYPE_MAX != source.backend); ProgramParameters params = *this; - params.userSources[static_cast(source.backend)] - = source; + params.userSources[static_cast(source.backend)] = source; return params; } -ProgramParameters ProgramParameters::withDefaultSource( - const ProgramSource &source) const noexcept -{ +ProgramParameters ProgramParameters::withDefaultSource(const ProgramSource& source) const noexcept { assert(gfx::Backend::Type::TYPE_MAX != source.backend); ProgramParameters params = *this; - params.defaultSources[static_cast(source.backend)] - = source; + params.defaultSources[static_cast(source.backend)] = source; return params; } @@ -46,8 +38,7 @@ const std::string& ProgramParameters::getDefines() const { return defines; } -const std::string& -ProgramParameters::vertexSource(gfx::Backend::Type backend) const { +const std::string& ProgramParameters::vertexSource(gfx::Backend::Type backend) const { assert(gfx::Backend::Type::TYPE_MAX != backend); if (userSources[static_cast(backend)].vertex.length() > 0) { @@ -59,8 +50,7 @@ ProgramParameters::vertexSource(gfx::Backend::Type backend) const { } } -const std::string& -ProgramParameters::fragmentSource(gfx::Backend::Type backend) const { +const std::string& ProgramParameters::fragmentSource(gfx::Backend::Type backend) const { assert(gfx::Backend::Type::TYPE_MAX != backend); if (userSources[static_cast(backend)].fragment.length() > 0) { diff --git a/src/mbgl/programs/program_parameters.hpp b/src/mbgl/programs/program_parameters.hpp index 01c40766b44..3bd165132a5 100644 --- a/src/mbgl/programs/program_parameters.hpp +++ b/src/mbgl/programs/program_parameters.hpp @@ -9,61 +9,59 @@ namespace mbgl { class ProgramParameters { - public: - struct ProgramSource { - gfx::Backend::Type backend{gfx::Backend::Type::TYPE_MAX}; - std::string vertex; - std::string fragment; +public: + struct ProgramSource { + gfx::Backend::Type backend{gfx::Backend::Type::TYPE_MAX}; + std::string vertex; + std::string fragment; - ProgramSource() = default; + ProgramSource() = default; - /// @brief Construct a new ProgramSource object - /// @param forBackend The provided source code is intended for use with the give - /// rendering backend. - /// @param vertex_ The vertex shader source code, or empty string if not provided. - /// @param fragment_ The fragment shader source code, or empty string if not provided. - ProgramSource(gfx::Backend::Type forBackend, const std::string& vertex_, - const std::string& fragment_) - : backend(forBackend), vertex(vertex_), fragment(fragment_) - { - assert(gfx::Backend::Type::TYPE_MAX != forBackend); - } - }; + /// @brief Construct a new ProgramSource object + /// @param forBackend The provided source code is intended for use with the give + /// rendering backend. + /// @param vertex_ The vertex shader source code, or empty string if not provided. + /// @param fragment_ The fragment shader source code, or empty string if not provided. + ProgramSource(gfx::Backend::Type forBackend, const std::string& vertex_, const std::string& fragment_) + : backend(forBackend), + vertex(vertex_), + fragment(fragment_) { + assert(gfx::Backend::Type::TYPE_MAX != forBackend); + } + }; - ProgramParameters(float pixelRatio, bool overdraw); - - /// @brief Provide custom shader code which overrides any default source present - /// @param source ProgramSource - /// @return Mutated ProgramParameters - ProgramParameters withShaderSource(const ProgramSource& source) const noexcept; + ProgramParameters(float pixelRatio, bool overdraw); - /// @brief Provide default shader source - /// @param source ProgramSource - /// @return Mutated ProgramParameters - ProgramParameters withDefaultSource(const ProgramSource& source) const noexcept; + /// @brief Provide custom shader code which overrides any default source present + /// @param source ProgramSource + /// @return Mutated ProgramParameters + ProgramParameters withShaderSource(const ProgramSource& source) const noexcept; - /// @brief Get a list of built-in shader preprocessor defines - /// @return Shader source string - /// @todo With the addition of future backends, defines should also be backend-aware - const std::string& getDefines() const; + /// @brief Provide default shader source + /// @param source ProgramSource + /// @return Mutated ProgramParameters + ProgramParameters withDefaultSource(const ProgramSource& source) const noexcept; - /// @brief Get source code for the vertex shader compatible with the requested backend - /// @param backend Backend type - /// @return Shader source string - const std::string& vertexSource(gfx::Backend::Type backend) const; + /// @brief Get a list of built-in shader preprocessor defines + /// @return Shader source string + /// @todo With the addition of future backends, defines should also be backend-aware + const std::string& getDefines() const; - /// @brief Get source code for the fragment shader compatible with the requested backend - /// @param backend Backend type - /// @return Shader source string - const std::string& fragmentSource(gfx::Backend::Type backend) const; + /// @brief Get source code for the vertex shader compatible with the requested backend + /// @param backend Backend type + /// @return Shader source string + const std::string& vertexSource(gfx::Backend::Type backend) const; - private: - std::string defines; + /// @brief Get source code for the fragment shader compatible with the requested backend + /// @param backend Backend type + /// @return Shader source string + const std::string& fragmentSource(gfx::Backend::Type backend) const; - std::array(gfx::Backend::Type::TYPE_MAX)> - defaultSources; - std::array(gfx::Backend::Type::TYPE_MAX)> - userSources; +private: + std::string defines; + + std::array(gfx::Backend::Type::TYPE_MAX)> defaultSources; + std::array(gfx::Backend::Type::TYPE_MAX)> userSources; }; } // namespace mbgl diff --git a/src/mbgl/programs/programs.cpp b/src/mbgl/programs/programs.cpp index 8d2035cdcc8..e37b7be93d9 100644 --- a/src/mbgl/programs/programs.cpp +++ b/src/mbgl/programs/programs.cpp @@ -24,25 +24,22 @@ Programs::~Programs() = default; /// @tparam ...T Type list parameter pack /// @param registry A shader registry instance /// programParameters_ ProgramParameters used to initialize each instance -template -void registerTypes(gfx::ShaderRegistry& registry, - const ProgramParameters& programParameters_) -{ +template +void registerTypes(gfx::ShaderRegistry& registry, const ProgramParameters& programParameters_) { /// The following fold expression will create a shared_ptr for every type /// in the parameter pack and register it with the shader registry. /// Registration calls are wrapped in a lambda that throws on registration /// failure, we shouldn't expect registration to faill unless the shader /// registry instance provided already has conflicting programs present. - ( [](bool expr) { - if (!expr) { - throw std::runtime_error( - "Failed to register " + - std::string(T::Name) + - " with shader registry!"); - } - }( registry.registerShader( - std::make_shared(programParameters_))), ... ); + ( + [](bool expr) { + if (!expr) { + throw std::runtime_error("Failed to register " + std::string(T::Name) + " with shader registry!"); + } + }(registry.registerShader(std::make_shared(programParameters_))), + ... + ); } void Programs::registerWith(gfx::ShaderRegistry& registry) { @@ -73,8 +70,7 @@ void Programs::registerWith(gfx::ShaderRegistry& registry) { CollisionBoxProgram, CollisionCircleProgram, DebugProgram, - ClippingMaskProgram - >(registry, programParameters); + ClippingMaskProgram>(registry, programParameters); } } // namespace mbgl diff --git a/src/mbgl/programs/raster_program.hpp b/src/mbgl/programs/raster_program.hpp index 434fe57a8e0..94facc9c11f 100644 --- a/src/mbgl/programs/raster_program.hpp +++ b/src/mbgl/programs/raster_program.hpp @@ -22,48 +22,32 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 2, tl_parent); } // namespace uniforms class RasterProgram final : public Program< - RasterProgram, - shaders::BuiltIn::RasterProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos, - attributes::texture_pos>, - TypeList< - uniforms::matrix, - uniforms::opacity, - uniforms::fade_t, - uniforms::brightness_low, - uniforms::brightness_high, - uniforms::saturation_factor, - uniforms::contrast_factor, - uniforms::spin_weights, - uniforms::buffer_scale, - uniforms::scale_parent, - uniforms::tl_parent>, - TypeList< - textures::image0, - textures::image1>, - style::RasterPaintProperties> -{ + RasterProgram, + shaders::BuiltIn::RasterProgram, + gfx::PrimitiveType::Triangle, + TypeList, + TypeList< + uniforms::matrix, + uniforms::opacity, + uniforms::fade_t, + uniforms::brightness_low, + uniforms::brightness_high, + uniforms::saturation_factor, + uniforms::contrast_factor, + uniforms::spin_weights, + uniforms::buffer_scale, + uniforms::scale_parent, + uniforms::tl_parent>, + TypeList, + style::RasterPaintProperties> { public: static constexpr std::string_view Name{"RasterProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static LayoutVertex layoutVertex(Point p, Point t) { - return LayoutVertex { - {{ - p.x, - p.y - }}, - {{ - t.x, - t.y - }} - }; + return LayoutVertex{{{p.x, p.y}}, {{t.x, t.y}}}; } }; diff --git a/src/mbgl/programs/segment.hpp b/src/mbgl/programs/segment.hpp index c263511f501..96bdf18cbcc 100644 --- a/src/mbgl/programs/segment.hpp +++ b/src/mbgl/programs/segment.hpp @@ -12,11 +12,13 @@ namespace mbgl { template class Segment { public: - Segment(std::size_t vertexOffset_, - std::size_t indexOffset_, - std::size_t vertexLength_ = 0, - std::size_t indexLength_ = 0, - float sortKey_ = 0.0f) + Segment( + std::size_t vertexOffset_, + std::size_t indexOffset_, + std::size_t vertexLength_ = 0, + std::size_t indexLength_ = 0, + float sortKey_ = 0.0f + ) : vertexOffset(vertexOffset_), indexOffset(indexOffset_), vertexLength(vertexLength_), diff --git a/src/mbgl/programs/symbol_program.cpp b/src/mbgl/programs/symbol_program.cpp index 76c266f039c..7d23154bb77 100644 --- a/src/mbgl/programs/symbol_program.cpp +++ b/src/mbgl/programs/symbol_program.cpp @@ -13,17 +13,17 @@ using namespace style; static_assert(sizeof(SymbolLayoutVertex) == 24, "expected SymbolLayoutVertex size"); -std::unique_ptr SymbolSizeBinder::create(const float tileZoom, - const style::PropertyValue& sizeProperty, - const float defaultValue) { +std::unique_ptr SymbolSizeBinder::create( + const float tileZoom, const style::PropertyValue& sizeProperty, const float defaultValue +) { return sizeProperty.match( - [&] (const Undefined& value) -> std::unique_ptr { + [&](const Undefined& value) -> std::unique_ptr { return std::make_unique(tileZoom, value, defaultValue); }, - [&] (float value) -> std::unique_ptr { + [&](float value) -> std::unique_ptr { return std::make_unique(tileZoom, value, defaultValue); }, - [&] (const style::PropertyExpression& expression) -> std::unique_ptr { + [&](const style::PropertyExpression& expression) -> std::unique_ptr { if (expression.isFeatureConstant()) { return std::make_unique(tileZoom, expression, defaultValue); } else if (expression.isZoomConstant()) { @@ -35,26 +35,27 @@ std::unique_ptr SymbolSizeBinder::create(const float tileZoom, ); } -template -Values makeValues(const bool isText, - const bool hasVariablePacement, - const style::SymbolPropertyValues& values, - const Size& texsize, - const std::array& pixelsToGLUnits, - const bool alongLine, - const RenderTile& tile, - const TransformState& state, - const float symbolFadeChange, - Args&&... args) { +template +Values makeValues( + const bool isText, + const bool hasVariablePacement, + const style::SymbolPropertyValues& values, + const Size& texsize, + const std::array& pixelsToGLUnits, + const bool alongLine, + const RenderTile& tile, + const TransformState& state, + const float symbolFadeChange, + Args&&... args +) { std::array extrudeScale; if (values.pitchAlignment == AlignmentType::Map) { extrudeScale.fill(tile.id.pixelsToTileUnits(1.f, static_cast(state.getZoom()))); } else { - extrudeScale = {{ - pixelsToGLUnits[0] * state.getCameraToCenterDistance(), - pixelsToGLUnits[1] * state.getCameraToCenterDistance() - }}; + extrudeScale = { + {pixelsToGLUnits[0] * state.getCameraToCenterDistance(), + pixelsToGLUnits[1] * state.getCameraToCenterDistance()}}; } const float pixelsToTileUnits = tile.id.pixelsToTileUnits(1.f, static_cast(state.getZoom())); @@ -77,68 +78,59 @@ Values makeValues(const bool isText, mat4 glCoordMatrix = getGlCoordMatrix(tile.matrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); - return Values { - uniforms::matrix::Value( tile.translatedMatrix(values.translate, - values.translateAnchor, - state) ), + return Values{ + uniforms::matrix::Value(tile.translatedMatrix(values.translate, values.translateAnchor, state)), uniforms::label_plane_matrix::Value(labelPlaneMatrix), - uniforms::coord_matrix::Value( tile.translateVtxMatrix(glCoordMatrix, - values.translate, - values.translateAnchor, - state, - true) ), - uniforms::extrude_scale::Value( extrudeScale ), - uniforms::texsize::Value( texsize ), - uniforms::fade_change::Value( symbolFadeChange ), - uniforms::is_text::Value( isText ), - uniforms::camera_to_center_distance::Value( state.getCameraToCenterDistance() ), - uniforms::pitch::Value( state.getPitch() ), - uniforms::pitch_with_map::Value( pitchWithMap ), - uniforms::rotate_symbol::Value( rotateInShader ), - uniforms::aspect_ratio::Value( state.getSize().aspectRatio() ), - std::forward(args)... - }; + uniforms::coord_matrix::Value( + tile.translateVtxMatrix(glCoordMatrix, values.translate, values.translateAnchor, state, true) + ), + uniforms::extrude_scale::Value(extrudeScale), + uniforms::texsize::Value(texsize), + uniforms::fade_change::Value(symbolFadeChange), + uniforms::is_text::Value(isText), + uniforms::camera_to_center_distance::Value(state.getCameraToCenterDistance()), + uniforms::pitch::Value(state.getPitch()), + uniforms::pitch_with_map::Value(pitchWithMap), + uniforms::rotate_symbol::Value(rotateInShader), + uniforms::aspect_ratio::Value(state.getSize().aspectRatio()), + std::forward(args)...}; } -SymbolIconProgram::LayoutUniformValues -SymbolIconProgram::layoutUniformValues(const bool isText, - const bool hasVariablePacement, - const style::SymbolPropertyValues& values, - const Size& texsize, - const std::array& pixelsToGLUnits, - const bool alongLine, - const RenderTile& tile, - const TransformState& state, - const float symbolFadeChange) { +SymbolIconProgram::LayoutUniformValues SymbolIconProgram::layoutUniformValues( + const bool isText, + const bool hasVariablePacement, + const style::SymbolPropertyValues& values, + const Size& texsize, + const std::array& pixelsToGLUnits, + const bool alongLine, + const RenderTile& tile, + const TransformState& state, + const float symbolFadeChange +) { return makeValues( - isText, - hasVariablePacement, - values, - texsize, - pixelsToGLUnits, - alongLine, - tile, - state, - symbolFadeChange + isText, hasVariablePacement, values, texsize, pixelsToGLUnits, alongLine, tile, state, symbolFadeChange ); } template typename SymbolSDFProgram::LayoutUniformValues -SymbolSDFProgram::layoutUniformValues(const bool isText, - const bool hasVariablePacement, - const style::SymbolPropertyValues& values, - const Size& texsize, - const std::array& pixelsToGLUnits, - const float pixelRatio, - const bool alongLine, - const RenderTile& tile, - const TransformState& state, - const float symbolFadeChange, - const SymbolSDFPart part) { - const float gammaScale = (values.pitchAlignment == AlignmentType::Map - ? static_cast(std::cos(state.getPitch())) * state.getCameraToCenterDistance() - : 1.0f); +SymbolSDFProgram::layoutUniformValues( + const bool isText, + const bool hasVariablePacement, + const style::SymbolPropertyValues& values, + const Size& texsize, + const std::array& pixelsToGLUnits, + const float pixelRatio, + const bool alongLine, + const RenderTile& tile, + const TransformState& state, + const float symbolFadeChange, + const SymbolSDFPart part +) { + const float gammaScale = + (values.pitchAlignment == AlignmentType::Map + ? static_cast(std::cos(state.getPitch())) * state.getCameraToCenterDistance() + : 1.0f); return makeValues::LayoutUniformValues>( isText, @@ -150,9 +142,9 @@ SymbolSDFProgram::layoutUniformValues(const tile, state, symbolFadeChange, - uniforms::gamma_scale::Value( gammaScale ), - uniforms::device_pixel_ratio::Value( pixelRatio ), - uniforms::is_halo::Value( part == SymbolSDFPart::Halo ) + uniforms::gamma_scale::Value(gammaScale), + uniforms::device_pixel_ratio::Value(pixelRatio), + uniforms::is_halo::Value(part == SymbolSDFPart::Halo) ); } @@ -167,24 +159,33 @@ SymbolTextAndIconProgram::LayoutUniformValues SymbolTextAndIconProgram::layoutUn const RenderTile& tile, const TransformState& state, const float symbolFadeChange, - const SymbolSDFPart part) { - return {SymbolSDFProgram - ::layoutUniformValues( - true, - hasVariablePacement, - values, - texsize, - pixelsToGLUnits, - pixelRatio, - alongLine, - tile, - state, - symbolFadeChange, - part) - .concat(gfx::UniformValues(uniforms::texsize::Value(texsize_icon)))}; + const SymbolSDFPart part +) { + return { + SymbolSDFProgram:: + layoutUniformValues( + true, + hasVariablePacement, + values, + texsize, + pixelsToGLUnits, + pixelRatio, + alongLine, + tile, + state, + symbolFadeChange, + part + ) + .concat(gfx::UniformValues(uniforms::texsize::Value(texsize_icon)))}; } -template class SymbolSDFProgram; -template class SymbolSDFProgram; +template class SymbolSDFProgram< + SymbolSDFIconProgram, + shaders::BuiltIn::SymbolSDFIconProgram, + style::IconPaintProperties>; +template class SymbolSDFProgram< + SymbolSDFTextProgram, + shaders::BuiltIn::SymbolSDFTextProgram, + style::TextPaintProperties>; } // namespace mbgl diff --git a/src/mbgl/programs/symbol_program.hpp b/src/mbgl/programs/symbol_program.hpp index 412b02b436b..bcb74e6f35b 100644 --- a/src/mbgl/programs/symbol_program.hpp +++ b/src/mbgl/programs/symbol_program.hpp @@ -71,51 +71,47 @@ class SymbolSizeBinder { public: virtual ~SymbolSizeBinder() = default; - using UniformList = TypeList< - uniforms::is_size_zoom_constant, - uniforms::is_size_feature_constant, - uniforms::size_t, - uniforms::size>; + using UniformList = + TypeList; using UniformValues = gfx::UniformValues; - static std::unique_ptr create(float tileZoom, - const style::PropertyValue& sizeProperty, - float defaultValue); + static std::unique_ptr create( + float tileZoom, const style::PropertyValue& sizeProperty, float defaultValue + ); virtual Range getVertexSizeData(const GeometryTileFeature& feature) = 0; virtual ZoomEvaluatedSize evaluateForZoom(float currentZoom) const = 0; UniformValues uniformValues(float currentZoom) const { const ZoomEvaluatedSize u = evaluateForZoom(currentZoom); - return UniformValues { - uniforms::is_size_zoom_constant::Value( u.isZoomConstant ), - uniforms::is_size_feature_constant::Value( u.isFeatureConstant), - uniforms::size_t::Value( u.sizeT ), - uniforms::size::Value( u.size ) - }; + return UniformValues{ + uniforms::is_size_zoom_constant::Value(u.isZoomConstant), + uniforms::is_size_feature_constant::Value(u.isFeatureConstant), + uniforms::size_t::Value(u.sizeT), + uniforms::size::Value(u.size)}; } }; - class ConstantSymbolSizeBinder final : public SymbolSizeBinder { public: ConstantSymbolSizeBinder(const float /*tileZoom*/, const float& size, const float /*defaultValue*/) - : layoutSize(size) {} + : layoutSize(size) {} ConstantSymbolSizeBinder(const float /*tileZoom*/, const style::Undefined&, const float defaultValue) - : layoutSize(defaultValue) {} + : layoutSize(defaultValue) {} - ConstantSymbolSizeBinder(const float tileZoom, const style::PropertyExpression& expression_, const float /*defaultValue*/) - : layoutSize(expression_.evaluate(tileZoom + 1)), - expression(expression_) { + ConstantSymbolSizeBinder( + const float tileZoom, const style::PropertyExpression& expression_, const float /*defaultValue*/ + ) + : layoutSize(expression_.evaluate(tileZoom + 1)), + expression(expression_) { const Range zoomLevels = expression_.getCoveringStops(tileZoom, tileZoom + 1); coveringRanges = std::make_tuple( - zoomLevels, - Range { expression_.evaluate(zoomLevels.min), expression_.evaluate(zoomLevels.max) } + zoomLevels, Range{expression_.evaluate(zoomLevels.min), expression_.evaluate(zoomLevels.max)} ); } - Range getVertexSizeData(const GeometryTileFeature&) override { return { 0.0f, 0.0f }; }; + Range getVertexSizeData(const GeometryTileFeature&) override { return {0.0f, 0.0f}; }; ZoomEvaluatedSize evaluateForZoom(float currentZoom) const override { float size = layoutSize; @@ -128,17 +124,14 @@ class ConstantSymbolSizeBinder final : public SymbolSizeBinder { // restriction on composite functions. const Range& zoomLevels = std::get<0>(*coveringRanges); const Range& sizeLevels = std::get<1>(*coveringRanges); - float t = util::clamp( - expression->interpolationFactor(zoomLevels, currentZoom), - 0.0f, 1.0f - ); + float t = util::clamp(expression->interpolationFactor(zoomLevels, currentZoom), 0.0f, 1.0f); size = sizeLevels.min + t * (sizeLevels.max - sizeLevels.min); } else if (expression) { size = expression->evaluate(currentZoom); } const float unused = 0.0f; - return { isZoomConstant, true, unused, size, layoutSize }; + return {isZoomConstant, true, unused, size, layoutSize}; } float layoutSize; @@ -148,19 +141,20 @@ class ConstantSymbolSizeBinder final : public SymbolSizeBinder { class SourceFunctionSymbolSizeBinder final : public SymbolSizeBinder { public: - SourceFunctionSymbolSizeBinder(const float /*tileZoom*/, style::PropertyExpression expression_, const float defaultValue_) + SourceFunctionSymbolSizeBinder( + const float /*tileZoom*/, style::PropertyExpression expression_, const float defaultValue_ + ) : expression(std::move(expression_)), - defaultValue(defaultValue_) { - } + defaultValue(defaultValue_) {} Range getVertexSizeData(const GeometryTileFeature& feature) override { const float size = expression.evaluate(feature, defaultValue); - return { size, size }; + return {size, size}; }; ZoomEvaluatedSize evaluateForZoom(float) const override { const float unused = 0.0f; - return { true, false, unused, unused, unused }; + return {true, false, unused, unused, unused}; } style::PropertyExpression expression; @@ -169,29 +163,27 @@ class SourceFunctionSymbolSizeBinder final : public SymbolSizeBinder { class CompositeFunctionSymbolSizeBinder final : public SymbolSizeBinder { public: - - CompositeFunctionSymbolSizeBinder(const float tileZoom, style::PropertyExpression expression_, const float defaultValue_) + CompositeFunctionSymbolSizeBinder( + const float tileZoom, style::PropertyExpression expression_, const float defaultValue_ + ) : expression(std::move(expression_)), defaultValue(defaultValue_), layoutZoom(tileZoom + 1), - coveringZoomStops(expression.getCoveringStops(tileZoom, tileZoom + 1)) - {} + coveringZoomStops(expression.getCoveringStops(tileZoom, tileZoom + 1)) {} Range getVertexSizeData(const GeometryTileFeature& feature) override { return { expression.evaluate(coveringZoomStops.min, feature, defaultValue), - expression.evaluate(coveringZoomStops.max, feature, defaultValue) - }; + expression.evaluate(coveringZoomStops.max, feature, defaultValue)}; }; ZoomEvaluatedSize evaluateForZoom(float currentZoom) const override { float sizeInterpolationT = util::clamp( - expression.interpolationFactor(coveringZoomStops, currentZoom), - 0.0f, 1.0f + expression.interpolationFactor(coveringZoomStops, currentZoom), 0.0f, 1.0f ); const float unused = 0.0f; - return { false, false, sizeInterpolationT, unused, unused }; + return {false, false, sizeInterpolationT, unused, unused}; } style::PropertyExpression expression; @@ -202,17 +194,20 @@ class CompositeFunctionSymbolSizeBinder final : public SymbolSizeBinder { class SymbolProgramBase : public gfx::Shader { public: - static gfx::Vertex layoutVertex(Point labelAnchor, - Point o, - float glyphOffsetY, - uint16_t tx, - uint16_t ty, - const Range& sizeData, - bool isSDF, - Point pixelOffset, - Point minFontScale) { - const uint16_t aSizeMin = - (std::min(MAX_PACKED_SIZE, static_cast(sizeData.min * SIZE_PACK_FACTOR)) << 1) + uint16_t(isSDF); + static gfx::Vertex layoutVertex( + Point labelAnchor, + Point o, + float glyphOffsetY, + uint16_t tx, + uint16_t ty, + const Range& sizeData, + bool isSDF, + Point pixelOffset, + Point minFontScale + ) { + const uint16_t aSizeMin = (std::min(MAX_PACKED_SIZE, static_cast(sizeData.min * SIZE_PACK_FACTOR)) + << 1) + + uint16_t(isSDF); const uint16_t aSizeMax = std::min(MAX_PACKED_SIZE, static_cast(sizeData.max * SIZE_PACK_FACTOR)); return { // combining pos and offset to reduce number of vertex attributes passed to shader (8 max for some devices) @@ -229,34 +224,28 @@ class SymbolProgramBase : public gfx::Shader { } static gfx::Vertex dynamicLayoutVertex(Point anchorPoint, float labelAngle) { - return { - {{ - anchorPoint.x, - anchorPoint.y, - labelAngle - }} - }; + return {{{anchorPoint.x, anchorPoint.y, labelAngle}}}; } static gfx::Vertex opacityVertex(bool placed, float opacity) { - return { - {{ static_cast((static_cast(opacity * 127) << 1) | static_cast(placed)) }} - }; + return {{{static_cast((static_cast(opacity * 127) << 1) | static_cast(placed))}}}; } }; -template +template < + class Name, + shaders::BuiltIn ShaderSource, + gfx::PrimitiveType Primitive, + class LayoutAttributeList, + class LayoutUniformList, + class Textures, + class PaintProps> class SymbolProgram : public SymbolProgramBase { public: using LayoutVertex = gfx::Vertex; - using LayoutAndSizeAttributeList = TypeListConcat; + using LayoutAndSizeAttributeList = + TypeListConcat; using PaintProperties = PaintProps; using Binders = PaintPropertyBinders; @@ -280,12 +269,11 @@ class SymbolProgram : public SymbolProgramBase { switch (gfx::Backend::GetType()) { #ifdef MBGL_RENDER_BACKEND_OPENGL case gfx::Backend::Type::OpenGL: { - program = std::make_unique>(programParameters - .withDefaultSource({ - gfx::Backend::Type::OpenGL, - shaders::ShaderSource::vertex, - shaders::ShaderSource::fragment - })); + program = std::make_unique>(programParameters.withDefaultSource( + {gfx::Backend::Type::OpenGL, + shaders::ShaderSource::vertex, + shaders::ShaderSource::fragment} + )); break; } #endif @@ -300,7 +288,8 @@ class SymbolProgram : public SymbolProgramBase { const SymbolSizeBinder& symbolSizeBinder, const Binders& paintPropertyBinders, const typename PaintProperties::PossiblyEvaluated& currentProperties, - float currentZoom) { + float currentZoom + ) { return layoutUniformValues.concat(symbolSizeBinder.uniformValues(currentZoom)) .concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); } @@ -310,9 +299,12 @@ class SymbolProgram : public SymbolProgramBase { const gfx::VertexBuffer>& dynamicLayoutVertexBuffer, const gfx::VertexBuffer>& opacityVertexBuffer, const Binders& paintPropertyBinders, - const typename PaintProperties::PossiblyEvaluated& currentProperties) { - assert(layoutVertexBuffer.elements == dynamicLayoutVertexBuffer.elements && - layoutVertexBuffer.elements == opacityVertexBuffer.elements); + const typename PaintProperties::PossiblyEvaluated& currentProperties + ) { + assert( + layoutVertexBuffer.elements == dynamicLayoutVertexBuffer.elements && + layoutVertexBuffer.elements == opacityVertexBuffer.elements + ); return gfx::AttributeBindings(layoutVertexBuffer) .concat(gfx::AttributeBindings(dynamicLayoutVertexBuffer)) .concat(gfx::AttributeBindings(opacityVertexBuffer)) @@ -324,19 +316,21 @@ class SymbolProgram : public SymbolProgramBase { } template - void draw(gfx::Context& context, - gfx::RenderPass& renderPass, - const DrawMode& drawMode, - const gfx::DepthMode& depthMode, - const gfx::StencilMode& stencilMode, - const gfx::ColorMode& colorMode, - const gfx::CullFaceMode& cullFaceMode, - const gfx::IndexBuffer& indexBuffer, - const Segment& segment, - const UniformValues& uniformValues, - const AttributeBindings& allAttributeBindings, - const TextureBindings& textureBindings, - const std::string& layerID) { + void draw( + gfx::Context& context, + gfx::RenderPass& renderPass, + const DrawMode& drawMode, + const gfx::DepthMode& depthMode, + const gfx::StencilMode& stencilMode, + const gfx::ColorMode& colorMode, + const gfx::CullFaceMode& cullFaceMode, + const gfx::IndexBuffer& indexBuffer, + const Segment& segment, + const UniformValues& uniformValues, + const AttributeBindings& allAttributeBindings, + const TextureBindings& textureBindings, + const std::string& layerID + ) { static_assert(Primitive == gfx::PrimitiveTypeOf::value, "incompatible draw mode"); if (!program) { @@ -362,23 +356,26 @@ class SymbolProgram : public SymbolProgramBase { textureBindings, indexBuffer, segment.indexOffset, - segment.indexLength); + segment.indexLength + ); } template - void draw(gfx::Context& context, - gfx::RenderPass& renderPass, - const DrawMode& drawMode, - const gfx::DepthMode& depthMode, - const gfx::StencilMode& stencilMode, - const gfx::ColorMode& colorMode, - const gfx::CullFaceMode& cullFaceMode, - const gfx::IndexBuffer& indexBuffer, - const SegmentVector& segments, - const UniformValues& uniformValues, - const AttributeBindings& allAttributeBindings, - const TextureBindings& textureBindings, - const std::string& layerID) { + void draw( + gfx::Context& context, + gfx::RenderPass& renderPass, + const DrawMode& drawMode, + const gfx::DepthMode& depthMode, + const gfx::StencilMode& stencilMode, + const gfx::ColorMode& colorMode, + const gfx::CullFaceMode& cullFaceMode, + const gfx::IndexBuffer& indexBuffer, + const SegmentVector& segments, + const UniformValues& uniformValues, + const AttributeBindings& allAttributeBindings, + const TextureBindings& textureBindings, + const std::string& layerID + ) { static_assert(Primitive == gfx::PrimitiveTypeOf::value, "incompatible draw mode"); if (!program) { @@ -386,62 +383,62 @@ class SymbolProgram : public SymbolProgramBase { } for (const auto& segment : segments) { - draw(context, - renderPass, - drawMode, - depthMode, - stencilMode, - colorMode, - cullFaceMode, - indexBuffer, - segment, - uniformValues, - allAttributeBindings, - textureBindings, - layerID); + draw( + context, + renderPass, + drawMode, + depthMode, + stencilMode, + colorMode, + cullFaceMode, + indexBuffer, + segment, + uniformValues, + allAttributeBindings, + textureBindings, + layerID + ); } } }; class SymbolIconProgram final : public SymbolProgram< - SymbolIconProgram, - shaders::BuiltIn::SymbolIconProgram, - gfx::PrimitiveType::Triangle, - SymbolLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::label_plane_matrix, - uniforms::coord_matrix, - uniforms::extrude_scale, - uniforms::texsize, - uniforms::fade_change, - uniforms::is_text, - uniforms::camera_to_center_distance, - uniforms::pitch, - uniforms::pitch_with_map, - uniforms::rotate_symbol, - uniforms::aspect_ratio>, - TypeList< - textures::texture>, - style::IconPaintProperties> -{ + SymbolIconProgram, + shaders::BuiltIn::SymbolIconProgram, + gfx::PrimitiveType::Triangle, + SymbolLayoutAttributes, + TypeList< + uniforms::matrix, + uniforms::label_plane_matrix, + uniforms::coord_matrix, + uniforms::extrude_scale, + uniforms::texsize, + uniforms::fade_change, + uniforms::is_text, + uniforms::camera_to_center_distance, + uniforms::pitch, + uniforms::pitch_with_map, + uniforms::rotate_symbol, + uniforms::aspect_ratio>, + TypeList, + style::IconPaintProperties> { public: static constexpr std::string_view Name{"SymbolIconProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using SymbolProgram::SymbolProgram; - static LayoutUniformValues layoutUniformValues(bool isText, - bool hasVariablePacement, - const style::SymbolPropertyValues&, - const Size& texsize, - const std::array& pixelsToGLUnits, - bool alongLine, - const RenderTile&, - const TransformState&, - float symbolFadeChange); + static LayoutUniformValues layoutUniformValues( + bool isText, + bool hasVariablePacement, + const style::SymbolPropertyValues&, + const Size& texsize, + const std::array& pixelsToGLUnits, + bool alongLine, + const RenderTile&, + const TransformState&, + float symbolFadeChange + ); }; enum class SymbolSDFPart { @@ -449,121 +446,121 @@ enum class SymbolSDFPart { Halo = 0 }; -using SymbolSDFProgramUniforms = TypeList; +using SymbolSDFProgramUniforms = TypeList< + uniforms::matrix, + uniforms::label_plane_matrix, + uniforms::coord_matrix, + uniforms::extrude_scale, + uniforms::texsize, + uniforms::fade_change, + uniforms::is_text, + uniforms::camera_to_center_distance, + uniforms::pitch, + uniforms::pitch_with_map, + uniforms::rotate_symbol, + uniforms::aspect_ratio, + uniforms::gamma_scale, + uniforms::device_pixel_ratio, + uniforms::is_halo>; template -class SymbolSDFProgram : public SymbolProgram, - PaintProperties> { +class SymbolSDFProgram : public SymbolProgram< + Name, + ShaderSource, + gfx::PrimitiveType::Triangle, + SymbolLayoutAttributes, + SymbolSDFProgramUniforms, + TypeList, + PaintProperties> { public: - using BaseProgram = SymbolProgram, - PaintProperties>; + using BaseProgram = SymbolProgram< + Name, + ShaderSource, + gfx::PrimitiveType::Triangle, + SymbolLayoutAttributes, + SymbolSDFProgramUniforms, + TypeList, + PaintProperties>; using LayoutUniformValues = typename BaseProgram::LayoutUniformValues; using BaseProgram::BaseProgram; - static LayoutUniformValues layoutUniformValues(bool isText, - bool hasVariablePacement, - const style::SymbolPropertyValues&, - const Size& texsize, - const std::array& pixelsToGLUnits, - float pixelRatio, - bool alongLine, - const RenderTile&, - const TransformState&, - float SymbolFadeChange, - SymbolSDFPart); + static LayoutUniformValues layoutUniformValues( + bool isText, + bool hasVariablePacement, + const style::SymbolPropertyValues&, + const Size& texsize, + const std::array& pixelsToGLUnits, + float pixelRatio, + bool alongLine, + const RenderTile&, + const TransformState&, + float SymbolFadeChange, + SymbolSDFPart + ); }; using SymbolTextAndIconProgramUniforms = TypeList; -class SymbolTextAndIconProgram final - : public SymbolProgram, - TypeList, - style::TextPaintProperties> { +class SymbolTextAndIconProgram final : public SymbolProgram< + SymbolTextAndIconProgram, + shaders::BuiltIn::SymbolTextAndIconProgram, + gfx::PrimitiveType::Triangle, + SymbolLayoutAttributes, + TypeListConcat, + TypeList, + style::TextPaintProperties> { public: static constexpr std::string_view Name{"SymbolTextAndIconProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } - using BaseProgram = SymbolProgram, - TypeList, - style::TextPaintProperties>; + using BaseProgram = SymbolProgram< + SymbolTextAndIconProgram, + shaders::BuiltIn::SymbolTextAndIconProgram, + gfx::PrimitiveType::Triangle, + SymbolLayoutAttributes, + TypeListConcat, + TypeList, + style::TextPaintProperties>; using LayoutUniformValues = typename BaseProgram::LayoutUniformValues; using BaseProgram::BaseProgram; - static LayoutUniformValues layoutUniformValues(bool hasVariablePacement, - const style::SymbolPropertyValues&, - const Size& texsize, - const Size& texsize_icon, - const std::array& pixelsToGLUnits, - float pixelRatio, - bool alongLine, - const RenderTile&, - const TransformState&, - float SymbolFadeChange, - SymbolSDFPart); + static LayoutUniformValues layoutUniformValues( + bool hasVariablePacement, + const style::SymbolPropertyValues&, + const Size& texsize, + const Size& texsize_icon, + const std::array& pixelsToGLUnits, + float pixelRatio, + bool alongLine, + const RenderTile&, + const TransformState&, + float SymbolFadeChange, + SymbolSDFPart + ); }; class SymbolSDFIconProgram final : public SymbolSDFProgram< - SymbolSDFIconProgram, - shaders::BuiltIn::SymbolSDFIconProgram, - style::IconPaintProperties> -{ + SymbolSDFIconProgram, + shaders::BuiltIn::SymbolSDFIconProgram, + style::IconPaintProperties> { public: static constexpr std::string_view Name{"SymbolSDFIconProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using SymbolSDFProgram::SymbolSDFProgram; }; class SymbolSDFTextProgram final : public SymbolSDFProgram< - SymbolSDFTextProgram, - shaders::BuiltIn::SymbolSDFTextProgram, - style::TextPaintProperties> -{ + SymbolSDFTextProgram, + shaders::BuiltIn::SymbolSDFTextProgram, + style::TextPaintProperties> { public: static constexpr std::string_view Name{"SymbolSDFTextProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using SymbolSDFProgram::SymbolSDFProgram; }; diff --git a/src/mbgl/renderer/backend_scope.cpp b/src/mbgl/renderer/backend_scope.cpp index f3d78714732..b34fde2228c 100644 --- a/src/mbgl/renderer/backend_scope.cpp +++ b/src/mbgl/renderer/backend_scope.cpp @@ -48,9 +48,8 @@ BackendScope::~BackendScope() { } void BackendScope::activate() { - if (scopeType == ScopeType::Explicit && - !(priorScope && this->backend == priorScope->backend) && - !(nextScope && this->backend == nextScope->backend)) { + if (scopeType == ScopeType::Explicit && !(priorScope && this->backend == priorScope->backend) && + !(nextScope && this->backend == nextScope->backend)) { // Only activate when set to Explicit and // only once per RenderBackend backend.activate(); @@ -59,8 +58,7 @@ void BackendScope::activate() { } void BackendScope::deactivate() { - if (activated && - !(nextScope && this->backend == nextScope->backend)) { + if (activated && !(nextScope && this->backend == nextScope->backend)) { // Only deactivate when set to Explicit and // only once per RenderBackend backend.deactivate(); diff --git a/src/mbgl/renderer/bucket.hpp b/src/mbgl/renderer/bucket.hpp index 68d6c46b7f8..f0547b134da 100644 --- a/src/mbgl/renderer/bucket.hpp +++ b/src/mbgl/renderer/bucket.hpp @@ -32,12 +32,8 @@ class Bucket { // Feature geometries are also used to populate the feature index. // Obtaining these is a costly operation, so we do it only once, and // pass-by-const-ref the geometries as a second parameter. - virtual void addFeature(const GeometryTileFeature&, - const GeometryCollection&, - const ImagePositions&, - const PatternLayerMap&, - std::size_t, - const CanonicalTileID&){}; + virtual void + addFeature(const GeometryTileFeature&, const GeometryCollection&, const ImagePositions&, const PatternLayerMap&, std::size_t, const CanonicalTileID&){}; virtual void update(const FeatureStates&, const GeometryTileLayer&, const std::string&, const ImagePositions&) {} @@ -47,14 +43,10 @@ class Bucket { virtual bool hasData() const = 0; - virtual float getQueryRadius(const RenderLayer&) const { - return 0; - }; + virtual float getQueryRadius(const RenderLayer&) const { return 0; }; + + bool needsUpload() const { return hasData() && !uploaded; } - bool needsUpload() const { - return hasData() && !uploaded; - } - // The following methods are implemented by buckets that require cross-tile indexing and placement. // Returns a pair, the first element of which is a bucket cross-tile id @@ -65,12 +57,13 @@ class Bucket { } // Places this bucket to the given placement. virtual void place(Placement&, const BucketPlacementData&, std::set&) {} - virtual void updateVertices( - const Placement&, bool /*updateOpacities*/, const TransformState&, const RenderTile&, std::set&) {} + virtual void + updateVertices(const Placement&, bool /*updateOpacities*/, const TransformState&, const RenderTile&, std::set&) { + } protected: Bucket() = default; - std::atomic uploaded { false }; + std::atomic uploaded{false}; }; } // namespace mbgl diff --git a/src/mbgl/renderer/bucket_parameters.cpp b/src/mbgl/renderer/bucket_parameters.cpp index 35b87bffea0..159a2aa1707 100644 --- a/src/mbgl/renderer/bucket_parameters.cpp +++ b/src/mbgl/renderer/bucket_parameters.cpp @@ -1,5 +1,3 @@ #include -namespace mbgl { - -} // namespace mbgl +namespace mbgl {} // namespace mbgl diff --git a/src/mbgl/renderer/bucket_parameters.hpp b/src/mbgl/renderer/bucket_parameters.hpp index 7547f4517bb..81c5bcfa4bd 100644 --- a/src/mbgl/renderer/bucket_parameters.hpp +++ b/src/mbgl/renderer/bucket_parameters.hpp @@ -5,7 +5,7 @@ namespace mbgl { namespace style { - struct LayerTypeInfo; +struct LayerTypeInfo; } // namespace style class BucketParameters { diff --git a/src/mbgl/renderer/buckets/circle_bucket.cpp b/src/mbgl/renderer/buckets/circle_bucket.cpp index 5a1184f5fd3..67bfcd9b6f6 100644 --- a/src/mbgl/renderer/buckets/circle_bucket.cpp +++ b/src/mbgl/renderer/buckets/circle_bucket.cpp @@ -10,14 +10,16 @@ namespace mbgl { using namespace style; -CircleBucket::CircleBucket(const std::map>& layerPaintProperties, - const MapMode mode_, - const float zoom) +CircleBucket::CircleBucket( + const std::map>& layerPaintProperties, const MapMode mode_, const float zoom +) : mode(mode_) { for (const auto& pair : layerPaintProperties) { - paintPropertyBinders.emplace(std::piecewise_construct, - std::forward_as_tuple(pair.first), - std::forward_as_tuple(getEvaluated(pair.second), zoom)); + paintPropertyBinders.emplace( + std::piecewise_construct, + std::forward_as_tuple(pair.first), + std::forward_as_tuple(getEvaluated(pair.second), zoom) + ); } } @@ -41,7 +43,11 @@ bool CircleBucket::hasData() const { } template -static float get(const CirclePaintProperties::PossiblyEvaluated& evaluated, const std::string& id, const std::map& paintPropertyBinders) { +static float get( + const CirclePaintProperties::PossiblyEvaluated& evaluated, + const std::string& id, + const std::map& paintPropertyBinders +) { auto it = paintPropertyBinders.find(id); if (it == paintPropertyBinders.end() || !it->second.statistics().max()) { return evaluated.get().constantOr(Property::defaultValue()); @@ -58,8 +64,12 @@ float CircleBucket::getQueryRadius(const RenderLayer& layer) const { return radius + stroke + util::length(translate[0], translate[1]); } -void CircleBucket::update(const FeatureStates& states, const GeometryTileLayer& layer, const std::string& layerID, - const ImagePositions& imagePositions) { +void CircleBucket::update( + const FeatureStates& states, + const GeometryTileLayer& layer, + const std::string& layerID, + const ImagePositions& imagePositions +) { auto it = paintPropertyBinders.find(layerID); if (it != paintPropertyBinders.end()) { it->second.updateVertexVectors(states, layer, imagePositions); diff --git a/src/mbgl/renderer/buckets/circle_bucket.hpp b/src/mbgl/renderer/buckets/circle_bucket.hpp index c1584ec5dac..ff585ef628f 100644 --- a/src/mbgl/renderer/buckets/circle_bucket.hpp +++ b/src/mbgl/renderer/buckets/circle_bucket.hpp @@ -17,9 +17,9 @@ class CircleBucket final : public Bucket { public: using PossiblyEvaluatedLayoutProperties = style::CircleLayoutProperties::PossiblyEvaluated; - CircleBucket(const std::map>& layerPaintProperties, - MapMode mode, - float zoom); + CircleBucket( + const std::map>& layerPaintProperties, MapMode mode, float zoom + ); ~CircleBucket() override; bool hasData() const override; diff --git a/src/mbgl/renderer/buckets/debug_bucket.cpp b/src/mbgl/renderer/buckets/debug_bucket.cpp index e752a1f1ce2..e011a9d37e9 100644 --- a/src/mbgl/renderer/buckets/debug_bucket.cpp +++ b/src/mbgl/renderer/buckets/debug_bucket.cpp @@ -9,21 +9,22 @@ namespace mbgl { -DebugBucket::DebugBucket(const OverscaledTileID& id, - const bool renderable_, - const bool complete_, - std::optional modified_, - std::optional expires_, - MapDebugOptions debugMode_) +DebugBucket::DebugBucket( + const OverscaledTileID& id, + const bool renderable_, + const bool complete_, + std::optional modified_, + std::optional expires_, + MapDebugOptions debugMode_ +) : renderable(renderable_), complete(complete_), modified(std::move(modified_)), expires(std::move(expires_)), debugMode(debugMode_) { - auto addText = [&] (const std::string& text, double left, double baseline, double scale) { + auto addText = [&](const std::string& text, double left, double baseline, double scale) { for (uint8_t c : text) { - if (c < 32 || c >= 127) - continue; + if (c < 32 || c >= 127) continue; std::optional> prev; @@ -32,16 +33,17 @@ DebugBucket::DebugBucket(const OverscaledTileID& id, if (glyph.data[j] == -1 && glyph.data[j + 1] == -1) { prev = {}; } else { - Point p { + Point p{ int16_t(::round(left + glyph.data[j] * scale)), - int16_t(::round(baseline - glyph.data[j + 1] * scale)) - }; + int16_t(::round(baseline - glyph.data[j + 1] * scale))}; vertices.emplace_back(FillProgram::layoutVertex(p)); if (prev) { - indices.emplace_back(static_cast(vertices.elements() - 2), - static_cast(vertices.elements() - 1)); + indices.emplace_back( + static_cast(vertices.elements() - 2), + static_cast(vertices.elements() - 1) + ); } prev = p; @@ -55,7 +57,9 @@ DebugBucket::DebugBucket(const OverscaledTileID& id, double baseline = 200; if (debugMode & MapDebugOptions::ParseStatus) { const std::string text = util::toString(id) + " - " + - (complete ? "complete" : renderable ? "renderable" : "pending"); + (complete ? "complete" + : renderable ? "renderable" + : "pending"); addText(text, 50, baseline, 5); baseline += 200; } diff --git a/src/mbgl/renderer/buckets/debug_bucket.hpp b/src/mbgl/renderer/buckets/debug_bucket.hpp index 34d6f9e8aba..7401b3d3fd6 100644 --- a/src/mbgl/renderer/buckets/debug_bucket.hpp +++ b/src/mbgl/renderer/buckets/debug_bucket.hpp @@ -15,12 +15,14 @@ class OverscaledTileID; class DebugBucket : private util::noncopyable { public: - DebugBucket(const OverscaledTileID& id, - bool renderable, - bool complete, - std::optional modified, - std::optional expires, - MapDebugOptions); + DebugBucket( + const OverscaledTileID& id, + bool renderable, + bool complete, + std::optional modified, + std::optional expires, + MapDebugOptions + ); void upload(gfx::UploadPass&); @@ -30,7 +32,6 @@ class DebugBucket : private util::noncopyable { const std::optional expires; const MapDebugOptions debugMode; - gfx::VertexVector vertices; gfx::IndexVector indices; diff --git a/src/mbgl/renderer/buckets/fill_bucket.cpp b/src/mbgl/renderer/buckets/fill_bucket.cpp index 6554cb2ab31..a2ddb581e65 100644 --- a/src/mbgl/renderer/buckets/fill_bucket.cpp +++ b/src/mbgl/renderer/buckets/fill_bucket.cpp @@ -20,11 +20,13 @@ namespace mapbox { namespace util { -template <> struct nth<0, mbgl::GeometryCoordinate> { +template <> +struct nth<0, mbgl::GeometryCoordinate> { static int64_t get(const mbgl::GeometryCoordinate& t) { return t.x; }; }; -template <> struct nth<1, mbgl::GeometryCoordinate> { +template <> +struct nth<1, mbgl::GeometryCoordinate> { static int64_t get(const mbgl::GeometryCoordinate& t) { return t.y; }; }; } // namespace util @@ -36,28 +38,31 @@ using namespace style; struct GeometryTooLongException : std::exception {}; -FillBucket::FillBucket(const FillBucket::PossiblyEvaluatedLayoutProperties&, - const std::map>& layerPaintProperties, - const float zoom, - const uint32_t) { +FillBucket::FillBucket( + const FillBucket::PossiblyEvaluatedLayoutProperties&, + const std::map>& layerPaintProperties, + const float zoom, + const uint32_t +) { for (const auto& pair : layerPaintProperties) { paintPropertyBinders.emplace( std::piecewise_construct, std::forward_as_tuple(pair.first), - std::forward_as_tuple( - getEvaluated(pair.second), - zoom)); + std::forward_as_tuple(getEvaluated(pair.second), zoom) + ); } } FillBucket::~FillBucket() = default; -void FillBucket::addFeature(const GeometryTileFeature& feature, - const GeometryCollection& geometry, - const ImagePositions& patternPositions, - const PatternLayerMap& patternDependencies, - std::size_t index, - const CanonicalTileID& canonical) { +void FillBucket::addFeature( + const GeometryTileFeature& feature, + const GeometryCollection& geometry, + const ImagePositions& patternPositions, + const PatternLayerMap& patternDependencies, + std::size_t index, + const CanonicalTileID& canonical +) { for (auto& polygon : classifyRings(geometry)) { // Optimize polygons with many interior rings for earcut tesselation. limitHoles(polygon, 500); @@ -66,8 +71,7 @@ void FillBucket::addFeature(const GeometryTileFeature& feature, for (const auto& ring : polygon) { totalVertices += ring.size(); - if (totalVertices > std::numeric_limits::max()) - throw GeometryTooLongException(); + if (totalVertices > std::numeric_limits::max()) throw GeometryTooLongException(); } std::size_t startVertices = vertices.elements(); @@ -75,10 +79,10 @@ void FillBucket::addFeature(const GeometryTileFeature& feature, for (const auto& ring : polygon) { std::size_t nVertices = ring.size(); - if (nVertices == 0) - continue; + if (nVertices == 0) continue; - if (lineSegments.empty() || lineSegments.back().vertexLength + nVertices > std::numeric_limits::max()) { + if (lineSegments.empty() || + lineSegments.back().vertexLength + nVertices > std::numeric_limits::max()) { lineSegments.emplace_back(vertices.elements(), lines.elements()); } @@ -103,7 +107,8 @@ void FillBucket::addFeature(const GeometryTileFeature& feature, std::size_t nIndicies = indices.size(); assert(nIndicies % 3 == 0); - if (triangleSegments.empty() || triangleSegments.back().vertexLength + totalVertices > std::numeric_limits::max()) { + if (triangleSegments.empty() || + triangleSegments.back().vertexLength + totalVertices > std::numeric_limits::max()) { triangleSegments.emplace_back(startVertices, triangles.elements()); } @@ -112,9 +117,9 @@ void FillBucket::addFeature(const GeometryTileFeature& feature, const auto triangleIndex = static_cast(triangleSegment.vertexLength); for (std::size_t i = 0; i < nIndicies; i += 3) { - triangles.emplace_back(triangleIndex + indices[i], - triangleIndex + indices[i + 1], - triangleIndex + indices[i + 2]); + triangles.emplace_back( + triangleIndex + indices[i], triangleIndex + indices[i + 1], triangleIndex + indices[i + 2] + ); } triangleSegment.vertexLength += totalVertices; @@ -125,7 +130,8 @@ void FillBucket::addFeature(const GeometryTileFeature& feature, const auto it = patternDependencies.find(pair.first); if (it != patternDependencies.end()) { pair.second.populateVertexVectors( - feature, vertices.elements(), index, patternPositions, it->second, canonical); + feature, vertices.elements(), index, patternPositions, it->second, canonical + ); } else { pair.second.populateVertexVectors(feature, vertices.elements(), index, patternPositions, {}, canonical); } @@ -136,8 +142,8 @@ void FillBucket::upload(gfx::UploadPass& uploadPass) { if (!uploaded) { vertexBuffer = uploadPass.createVertexBuffer(std::move(vertices)); lineIndexBuffer = uploadPass.createIndexBuffer(std::move(lines)); - triangleIndexBuffer = - triangles.empty() ? std::optional{} : uploadPass.createIndexBuffer(std::move(triangles)); + triangleIndexBuffer = triangles.empty() ? std::optional{} + : uploadPass.createIndexBuffer(std::move(triangles)); } for (auto& pair : paintPropertyBinders) { @@ -157,8 +163,12 @@ float FillBucket::getQueryRadius(const RenderLayer& layer) const { return util::length(translate[0], translate[1]); } -void FillBucket::update(const FeatureStates& states, const GeometryTileLayer& layer, const std::string& layerID, - const ImagePositions& imagePositions) { +void FillBucket::update( + const FeatureStates& states, + const GeometryTileLayer& layer, + const std::string& layerID, + const ImagePositions& imagePositions +) { auto it = paintPropertyBinders.find(layerID); if (it != paintPropertyBinders.end()) { it->second.updateVertexVectors(states, layer, imagePositions); diff --git a/src/mbgl/renderer/buckets/fill_bucket.hpp b/src/mbgl/renderer/buckets/fill_bucket.hpp index b3014da761e..2059ba79514 100644 --- a/src/mbgl/renderer/buckets/fill_bucket.hpp +++ b/src/mbgl/renderer/buckets/fill_bucket.hpp @@ -20,17 +20,16 @@ class FillBucket final : public Bucket { ~FillBucket() override; using PossiblyEvaluatedLayoutProperties = style::FillLayoutProperties::PossiblyEvaluated; - FillBucket(const PossiblyEvaluatedLayoutProperties& layout, - const std::map>& layerPaintProperties, - float zoom, - uint32_t overscaling); - - void addFeature(const GeometryTileFeature&, - const GeometryCollection&, - const mbgl::ImagePositions&, - const PatternLayerMap&, - std::size_t, - const CanonicalTileID&) override; + FillBucket( + const PossiblyEvaluatedLayoutProperties& layout, + const std::map>& layerPaintProperties, + float zoom, + uint32_t overscaling + ); + + void + addFeature(const GeometryTileFeature&, const GeometryCollection&, const mbgl::ImagePositions&, const PatternLayerMap&, std::size_t, const CanonicalTileID&) + override; bool hasData() const override; diff --git a/src/mbgl/renderer/buckets/fill_extrusion_bucket.cpp b/src/mbgl/renderer/buckets/fill_extrusion_bucket.cpp index fbf21d91207..cb3332042d6 100644 --- a/src/mbgl/renderer/buckets/fill_extrusion_bucket.cpp +++ b/src/mbgl/renderer/buckets/fill_extrusion_bucket.cpp @@ -23,16 +23,12 @@ namespace mapbox { namespace util { template <> struct nth<0, mbgl::GeometryCoordinate> { - static int64_t get(const mbgl::GeometryCoordinate& t) { - return t.x; - }; + static int64_t get(const mbgl::GeometryCoordinate& t) { return t.x; }; }; template <> struct nth<1, mbgl::GeometryCoordinate> { - static int64_t get(const mbgl::GeometryCoordinate& t) { - return t.y; - }; + static int64_t get(const mbgl::GeometryCoordinate& t) { return t.y; }; }; } // namespace util } // namespace mapbox @@ -43,28 +39,31 @@ using namespace style; struct GeometryTooLongException : std::exception {}; -FillExtrusionBucket::FillExtrusionBucket(const FillExtrusionBucket::PossiblyEvaluatedLayoutProperties&, - const std::map>& layerPaintProperties, - const float zoom, - const uint32_t) { +FillExtrusionBucket::FillExtrusionBucket( + const FillExtrusionBucket::PossiblyEvaluatedLayoutProperties&, + const std::map>& layerPaintProperties, + const float zoom, + const uint32_t +) { for (const auto& pair : layerPaintProperties) { paintPropertyBinders.emplace( std::piecewise_construct, std::forward_as_tuple(pair.first), - std::forward_as_tuple( - getEvaluated(pair.second), - zoom)); + std::forward_as_tuple(getEvaluated(pair.second), zoom) + ); } } FillExtrusionBucket::~FillExtrusionBucket() = default; -void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, - const GeometryCollection& geometry, - const ImagePositions& patternPositions, - const PatternLayerMap& patternDependencies, - std::size_t index, - const CanonicalTileID& canonical) { +void FillExtrusionBucket::addFeature( + const GeometryTileFeature& feature, + const GeometryCollection& geometry, + const ImagePositions& patternPositions, + const PatternLayerMap& patternDependencies, + std::size_t index, + const CanonicalTileID& canonical +) { for (auto& polygon : classifyRings(geometry)) { // Optimize polygons with many interior rings for earcut tesselation. limitHoles(polygon, 500); @@ -73,8 +72,7 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, for (const auto& ring : polygon) { totalVertices += ring.size(); - if (totalVertices > std::numeric_limits::max()) - throw GeometryTooLongException(); + if (totalVertices > std::numeric_limits::max()) throw GeometryTooLongException(); } if (totalVertices == 0) continue; @@ -84,9 +82,8 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, std::size_t startVertices = vertices.elements(); - if (triangleSegments.empty() || - triangleSegments.back().vertexLength + (5 * (totalVertices - 1) + 1) > - std::numeric_limits::max()) { + if (triangleSegments.empty() || triangleSegments.back().vertexLength + (5 * (totalVertices - 1) + 1) > + std::numeric_limits::max()) { triangleSegments.emplace_back(startVertices, triangles.elements()); } @@ -94,14 +91,12 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, assert(triangleSegment.vertexLength <= std::numeric_limits::max()); auto triangleIndex = static_cast(triangleSegment.vertexLength); - assert(triangleIndex + (5 * (totalVertices - 1) + 1) <= - std::numeric_limits::max()); + assert(triangleIndex + (5 * (totalVertices - 1) + 1) <= std::numeric_limits::max()); for (const auto& ring : polygon) { std::size_t nVertices = ring.size(); - if (nVertices == 0) - continue; + if (nVertices == 0) continue; std::size_t edgeDistance = 0; @@ -109,7 +104,8 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, const auto& p1 = ring[i]; vertices.emplace_back( - FillExtrusionProgram::layoutVertex(p1, 0, 0, 1, 1, static_cast(edgeDistance))); + FillExtrusionProgram::layoutVertex(p1, 0, 0, 1, 1, static_cast(edgeDistance)) + ); flatIndices.emplace_back(triangleIndex); triangleIndex++; @@ -121,22 +117,25 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, const Point perp = util::unit(util::perp(d1 - d2)); const size_t dist = util::dist(d1, d2); - if (edgeDistance + dist > - static_cast(std::numeric_limits::max())) { + if (edgeDistance + dist > static_cast(std::numeric_limits::max())) { edgeDistance = 0; } - vertices.emplace_back( - FillExtrusionProgram::layoutVertex(p1, perp.x, perp.y, 0, 0, static_cast(edgeDistance))); - vertices.emplace_back( - FillExtrusionProgram::layoutVertex(p1, perp.x, perp.y, 0, 1, static_cast(edgeDistance))); + vertices.emplace_back(FillExtrusionProgram::layoutVertex( + p1, perp.x, perp.y, 0, 0, static_cast(edgeDistance) + )); + vertices.emplace_back(FillExtrusionProgram::layoutVertex( + p1, perp.x, perp.y, 0, 1, static_cast(edgeDistance) + )); edgeDistance += dist; - vertices.emplace_back( - FillExtrusionProgram::layoutVertex(p2, perp.x, perp.y, 0, 0, static_cast(edgeDistance))); - vertices.emplace_back( - FillExtrusionProgram::layoutVertex(p2, perp.x, perp.y, 0, 1, static_cast(edgeDistance))); + vertices.emplace_back(FillExtrusionProgram::layoutVertex( + p2, perp.x, perp.y, 0, 0, static_cast(edgeDistance) + )); + vertices.emplace_back(FillExtrusionProgram::layoutVertex( + p2, perp.x, perp.y, 0, 1, static_cast(edgeDistance) + )); // ┌──────┐ // │ 0 1 │ Counter-Clockwise winding order. @@ -159,8 +158,7 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, for (std::size_t i = 0; i < nIndices; i += 3) { // Counter-Clockwise winding order. - triangles.emplace_back(flatIndices[indices[i]], flatIndices[indices[i + 2]], - flatIndices[indices[i + 1]]); + triangles.emplace_back(flatIndices[indices[i]], flatIndices[indices[i + 2]], flatIndices[indices[i + 1]]); } triangleSegment.vertexLength += totalVertices; @@ -169,9 +167,10 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, for (auto& pair : paintPropertyBinders) { const auto it = patternDependencies.find(pair.first); - if (it != patternDependencies.end()){ + if (it != patternDependencies.end()) { pair.second.populateVertexVectors( - feature, vertices.elements(), index, patternPositions, it->second, canonical); + feature, vertices.elements(), index, patternPositions, it->second, canonical + ); } else { pair.second.populateVertexVectors(feature, vertices.elements(), index, patternPositions, {}, canonical); } @@ -201,8 +200,12 @@ float FillExtrusionBucket::getQueryRadius(const RenderLayer& layer) const { return util::length(translate[0], translate[1]); } -void FillExtrusionBucket::update(const FeatureStates& states, const GeometryTileLayer& layer, - const std::string& layerID, const ImagePositions& imagePositions) { +void FillExtrusionBucket::update( + const FeatureStates& states, + const GeometryTileLayer& layer, + const std::string& layerID, + const ImagePositions& imagePositions +) { auto it = paintPropertyBinders.find(layerID); if (it != paintPropertyBinders.end()) { it->second.updateVertexVectors(states, layer, imagePositions); diff --git a/src/mbgl/renderer/buckets/fill_extrusion_bucket.hpp b/src/mbgl/renderer/buckets/fill_extrusion_bucket.hpp index da59981fbb0..067e0c56f59 100644 --- a/src/mbgl/renderer/buckets/fill_extrusion_bucket.hpp +++ b/src/mbgl/renderer/buckets/fill_extrusion_bucket.hpp @@ -19,17 +19,16 @@ class FillExtrusionBucket final : public Bucket { using PossiblyEvaluatedPaintProperties = style::FillExtrusionPaintProperties::PossiblyEvaluated; using PossiblyEvaluatedLayoutProperties = style::Properties<>::PossiblyEvaluated; - FillExtrusionBucket(const PossiblyEvaluatedLayoutProperties&, - const std::map>&, - float, - uint32_t); - - void addFeature(const GeometryTileFeature&, - const GeometryCollection&, - const mbgl::ImagePositions&, - const PatternLayerMap&, - std::size_t, - const CanonicalTileID&) override; + FillExtrusionBucket( + const PossiblyEvaluatedLayoutProperties&, + const std::map>&, + float, + uint32_t + ); + + void + addFeature(const GeometryTileFeature&, const GeometryCollection&, const mbgl::ImagePositions&, const PatternLayerMap&, std::size_t, const CanonicalTileID&) + override; bool hasData() const override; @@ -45,7 +44,7 @@ class FillExtrusionBucket final : public Bucket { std::optional> vertexBuffer; std::optional indexBuffer; - + std::unordered_map paintPropertyBinders; }; diff --git a/src/mbgl/renderer/buckets/heatmap_bucket.cpp b/src/mbgl/renderer/buckets/heatmap_bucket.cpp index 6689d759d02..3ff59e82baa 100644 --- a/src/mbgl/renderer/buckets/heatmap_bucket.cpp +++ b/src/mbgl/renderer/buckets/heatmap_bucket.cpp @@ -10,15 +10,16 @@ namespace mbgl { using namespace style; -HeatmapBucket::HeatmapBucket(const BucketParameters& parameters, const std::vector>& layers) +HeatmapBucket::HeatmapBucket( + const BucketParameters& parameters, const std::vector>& layers +) : mode(parameters.mode) { for (const auto& layer : layers) { paintPropertyBinders.emplace( std::piecewise_construct, std::forward_as_tuple(layer->baseImpl->id), - std::forward_as_tuple( - getEvaluated(layer), - parameters.tileID.overscaledZ)); + std::forward_as_tuple(getEvaluated(layer), parameters.tileID.overscaledZ) + ); } } @@ -39,16 +40,18 @@ bool HeatmapBucket::hasData() const { return !segments.empty(); } -void HeatmapBucket::addFeature(const GeometryTileFeature& feature, - const GeometryCollection& geometry, - const ImagePositions&, - const PatternLayerMap&, - std::size_t featureIndex, - const CanonicalTileID& canonical) { +void HeatmapBucket::addFeature( + const GeometryTileFeature& feature, + const GeometryCollection& geometry, + const ImagePositions&, + const PatternLayerMap&, + std::size_t featureIndex, + const CanonicalTileID& canonical +) { constexpr const uint16_t vertexLength = 4; for (auto& points : geometry) { - for(auto& point : points) { + for (auto& point : points) { auto x = point.x; auto y = point.y; @@ -57,7 +60,8 @@ void HeatmapBucket::addFeature(const GeometryTileFeature& feature, continue; } - if (segments.empty() || segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { + if (segments.empty() || + segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { // Move to a new segments because the old one can't hold the geometry. segments.emplace_back(vertices.elements(), triangles.elements()); } @@ -72,9 +76,9 @@ void HeatmapBucket::addFeature(const GeometryTileFeature& feature, // └─────────┘ // vertices.emplace_back(HeatmapProgram::vertex(point, -1, -1)); // 1 - vertices.emplace_back(HeatmapProgram::vertex(point, 1, -1)); // 2 - vertices.emplace_back(HeatmapProgram::vertex(point, 1, 1)); // 3 - vertices.emplace_back(HeatmapProgram::vertex(point, -1, 1)); // 4 + vertices.emplace_back(HeatmapProgram::vertex(point, 1, -1)); // 2 + vertices.emplace_back(HeatmapProgram::vertex(point, 1, 1)); // 3 + vertices.emplace_back(HeatmapProgram::vertex(point, -1, 1)); // 4 auto& segment = segments.back(); assert(segment.vertexLength <= std::numeric_limits::max()); diff --git a/src/mbgl/renderer/buckets/heatmap_bucket.hpp b/src/mbgl/renderer/buckets/heatmap_bucket.hpp index 33f99822a35..281121a9663 100644 --- a/src/mbgl/renderer/buckets/heatmap_bucket.hpp +++ b/src/mbgl/renderer/buckets/heatmap_bucket.hpp @@ -18,12 +18,9 @@ class HeatmapBucket final : public Bucket { HeatmapBucket(const BucketParameters&, const std::vector>&); ~HeatmapBucket() override; - void addFeature(const GeometryTileFeature&, - const GeometryCollection&, - const ImagePositions&, - const PatternLayerMap&, - std::size_t, - const CanonicalTileID&) override; + void + addFeature(const GeometryTileFeature&, const GeometryCollection&, const ImagePositions&, const PatternLayerMap&, std::size_t, const CanonicalTileID&) + override; bool hasData() const override; void upload(gfx::UploadPass&) override; diff --git a/src/mbgl/renderer/buckets/hillshade_bucket.cpp b/src/mbgl/renderer/buckets/hillshade_bucket.cpp index a2a3db8d1d9..c8b82e7c752 100644 --- a/src/mbgl/renderer/buckets/hillshade_bucket.cpp +++ b/src/mbgl/renderer/buckets/hillshade_bucket.cpp @@ -9,12 +9,10 @@ namespace mbgl { using namespace style; HillshadeBucket::HillshadeBucket(PremultipliedImage&& image_, Tileset::DEMEncoding encoding) - : demdata(image_, encoding) { -} + : demdata(image_, encoding) {} HillshadeBucket::HillshadeBucket(DEMData&& demdata_) - : demdata(std::move(demdata_)) { -} + : demdata(std::move(demdata_)) {} HillshadeBucket::~HillshadeBucket() = default; @@ -62,7 +60,7 @@ void HillshadeBucket::setMask(TileMask&& mask_) { mask = std::move(mask_); clear(); - if (mask == TileMask{ { 0, 0, 0 } }) { + if (mask == TileMask{{0, 0, 0}}) { // We want to render the full tile, and keeping the segments/vertices/indices empty means // using the global shared buffers for covering the entire tile. return; @@ -79,24 +77,28 @@ void HillshadeBucket::setMask(TileMask&& mask_) { // Create a quad for every masked tile. const int32_t vertexExtent = util::EXTENT >> id.z; - const Point tlVertex = { static_cast(id.x * vertexExtent), - static_cast(id.y * vertexExtent) }; - const Point brVertex = { static_cast(tlVertex.x + vertexExtent), - static_cast(tlVertex.y + vertexExtent) }; + const Point tlVertex = { + static_cast(id.x * vertexExtent), static_cast(id.y * vertexExtent)}; + const Point brVertex = { + static_cast(tlVertex.x + vertexExtent), static_cast(tlVertex.y + vertexExtent)}; if (segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { // Move to a new segments because the old one can't hold the geometry. segments.emplace_back(vertices.elements(), indices.elements()); } - vertices.emplace_back( - HillshadeProgram::layoutVertex({ tlVertex.x, tlVertex.y }, { static_cast(tlVertex.x), static_cast(tlVertex.y) })); - vertices.emplace_back( - HillshadeProgram::layoutVertex({ brVertex.x, tlVertex.y }, { static_cast(brVertex.x), static_cast(tlVertex.y) })); - vertices.emplace_back( - HillshadeProgram::layoutVertex({ tlVertex.x, brVertex.y }, { static_cast(tlVertex.x), static_cast(brVertex.y) })); - vertices.emplace_back( - HillshadeProgram::layoutVertex({ brVertex.x, brVertex.y }, { static_cast(brVertex.x), static_cast(brVertex.y) })); + vertices.emplace_back(HillshadeProgram::layoutVertex( + {tlVertex.x, tlVertex.y}, {static_cast(tlVertex.x), static_cast(tlVertex.y)} + )); + vertices.emplace_back(HillshadeProgram::layoutVertex( + {brVertex.x, tlVertex.y}, {static_cast(brVertex.x), static_cast(tlVertex.y)} + )); + vertices.emplace_back(HillshadeProgram::layoutVertex( + {tlVertex.x, brVertex.y}, {static_cast(tlVertex.x), static_cast(brVertex.y)} + )); + vertices.emplace_back(HillshadeProgram::layoutVertex( + {brVertex.x, brVertex.y}, {static_cast(brVertex.x), static_cast(brVertex.y)} + )); auto& segment = segments.back(); assert(segment.vertexLength <= std::numeric_limits::max()); @@ -116,5 +118,4 @@ bool HillshadeBucket::hasData() const { return demdata.getImage()->valid(); } - } // namespace mbgl diff --git a/src/mbgl/renderer/buckets/hillshade_bucket.hpp b/src/mbgl/renderer/buckets/hillshade_bucket.hpp index 5d5dfb72a7b..a2098a93e1b 100644 --- a/src/mbgl/renderer/buckets/hillshade_bucket.hpp +++ b/src/mbgl/renderer/buckets/hillshade_bucket.hpp @@ -30,18 +30,14 @@ class HillshadeBucket final : public Bucket { std::optional dem; std::optional texture; - TileMask mask{ { 0, 0, 0 } }; + TileMask mask{{0, 0, 0}}; const DEMData& getDEMData() const; DEMData& getDEMData(); - bool isPrepared() const { - return prepared; - } + bool isPrepared() const { return prepared; } - void setPrepared (bool preparedState) { - prepared = preparedState; - } + void setPrepared(bool preparedState) { prepared = preparedState; } // Raster-DEM Tile Sources use the default buffers from Painter gfx::VertexVector vertices; @@ -50,7 +46,8 @@ class HillshadeBucket final : public Bucket { std::optional> vertexBuffer; std::optional indexBuffer; -private: + +private: DEMData demdata; bool prepared = false; }; diff --git a/src/mbgl/renderer/buckets/line_bucket.cpp b/src/mbgl/renderer/buckets/line_bucket.cpp index 92e71f377f9..7f67eb2c38b 100644 --- a/src/mbgl/renderer/buckets/line_bucket.cpp +++ b/src/mbgl/renderer/buckets/line_bucket.cpp @@ -11,38 +11,44 @@ namespace mbgl { using namespace style; -LineBucket::LineBucket(LineBucket::PossiblyEvaluatedLayoutProperties layout_, - const std::map>& layerPaintProperties, - const float zoom_, - const uint32_t overscaling_) - : layout(std::move(layout_)), zoom(zoom_), overscaling(overscaling_) { +LineBucket::LineBucket( + LineBucket::PossiblyEvaluatedLayoutProperties layout_, + const std::map>& layerPaintProperties, + const float zoom_, + const uint32_t overscaling_ +) + : layout(std::move(layout_)), + zoom(zoom_), + overscaling(overscaling_) { for (const auto& pair : layerPaintProperties) { paintPropertyBinders.emplace( std::piecewise_construct, std::forward_as_tuple(pair.first), - std::forward_as_tuple( - getEvaluated(pair.second), - zoom)); + std::forward_as_tuple(getEvaluated(pair.second), zoom) + ); } } LineBucket::~LineBucket() = default; -void LineBucket::addFeature(const GeometryTileFeature& feature, - const GeometryCollection& geometryCollection, - const ImagePositions& patternPositions, - const PatternLayerMap& patternDependencies, - std::size_t index, - const CanonicalTileID& canonical) { +void LineBucket::addFeature( + const GeometryTileFeature& feature, + const GeometryCollection& geometryCollection, + const ImagePositions& patternPositions, + const PatternLayerMap& patternDependencies, + std::size_t index, + const CanonicalTileID& canonical +) { for (auto& line : geometryCollection) { addGeometry(line, feature, canonical); } for (auto& pair : paintPropertyBinders) { const auto it = patternDependencies.find(pair.first); - if (it != patternDependencies.end()){ + if (it != patternDependencies.end()) { pair.second.populateVertexVectors( - feature, vertices.elements(), index, patternPositions, it->second, canonical); + feature, vertices.elements(), index, patternPositions, it->second, canonical + ); } else { pair.second.populateVertexVectors(feature, vertices.elements(), index, patternPositions, {}, canonical); } @@ -80,7 +86,9 @@ const auto MAX_LINE_DISTANCE = static_cast(std::pow(2, LINE_DISTANCE_BUFF class LineBucket::Distances { public: Distances(double clipStart_, double clipEnd_, double total_) - : clipStart(clipStart_), clipEnd(clipEnd_), total(total_) {} + : clipStart(clipStart_), + clipEnd(clipEnd_), + total(total_) {} // Scale line distance from tile units to [0, 2^15). double scaleToMaxLineDistance(double tileDistance) const { @@ -98,9 +106,9 @@ class LineBucket::Distances { double total; }; -void LineBucket::addGeometry(const GeometryCoordinates& coordinates, - const GeometryTileFeature& feature, - const CanonicalTileID& canonical) { +void LineBucket::addGeometry( + const GeometryCoordinates& coordinates, const GeometryTileFeature& feature, const CanonicalTileID& canonical +) { const FeatureType type = feature.getType(); const std::size_t len = [&coordinates] { std::size_t l = coordinates.size(); @@ -127,7 +135,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, std::optional lineDistances; - const auto &props = feature.getProperties(); + const auto& props = feature.getProperties(); auto clip_start_it = props.find("mapbox_clip_start"); auto clip_end_it = props.find("mapbox_clip_end"); if (clip_start_it != props.end() && clip_end_it != props.end()) { @@ -147,8 +155,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const double sharpCornerOffset = overscaling == 0 ? SHARP_CORNER_OFFSET * (util::EXTENT / util::tileSize_D) - : (overscaling <= 16.0 ? SHARP_CORNER_OFFSET * (util::EXTENT / (util::tileSize_D * overscaling)) - : 0.0); + : (overscaling <= 16.0 ? SHARP_CORNER_OFFSET * (util::EXTENT / (util::tileSize_D * overscaling)) : 0.0); const GeometryCoordinate firstCoordinate = coordinates[first]; const LineCapType beginCap = layout.get(); @@ -203,7 +210,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // there is no next vertex, pretend that the line is continuing straight, // meaning that we are just using the previous normal. nextNormal = nextCoordinate ? util::perp(util::unit(convertPoint(*nextCoordinate - *currentCoordinate))) - : prevNormal; + : prevNormal; // If we still don't have a previous normal, this is the beginning of a // non-closed line, so we're doing a straight "join". @@ -238,8 +245,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // Calculate the length of the miter (the ratio of the miter to the width) // as the inverse of cosine of the angle between next and join normals. - const double miterLength = - cosHalfAngle != 0 ? 1 / cosHalfAngle : std::numeric_limits::infinity(); + const double miterLength = cosHalfAngle != 0 ? 1 / cosHalfAngle : std::numeric_limits::infinity(); // Approximate angle from cosine. const double approxAngle = 2 * std::sqrt(2 - 2 * cosHalfAngle); @@ -249,9 +255,15 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, if (isSharpCorner && i > first) { const auto prevSegmentLength = util::dist(*currentCoordinate, *prevCoordinate); if (prevSegmentLength > 2.0 * sharpCornerOffset) { - GeometryCoordinate newPrevVertex = *currentCoordinate - convertPoint(util::round(convertPoint(*currentCoordinate - *prevCoordinate) * (sharpCornerOffset / prevSegmentLength))); + GeometryCoordinate newPrevVertex = *currentCoordinate - + convertPoint(util::round( + convertPoint(*currentCoordinate - *prevCoordinate) * + (sharpCornerOffset / prevSegmentLength) + )); distance += util::dist(newPrevVertex, *prevCoordinate); - addCurrentVertex(newPrevVertex, distance, *prevNormal, 0, 0, false, startVertex, triangleStore, lineDistances); + addCurrentVertex( + newPrevVertex, distance, *prevNormal, 0, 0, false, startVertex, triangleStore, lineDistances + ); prevCoordinate = newPrevVertex; } } @@ -290,13 +302,13 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, } // Calculate how far along the line the currentVertex is - if (prevCoordinate) - distance += util::dist(*currentCoordinate, *prevCoordinate); + if (prevCoordinate) distance += util::dist(*currentCoordinate, *prevCoordinate); if (middleVertex && currentJoin == LineJoinType::Miter) { joinNormal = joinNormal * miterLength; - addCurrentVertex(*currentCoordinate, distance, joinNormal, 0, 0, false, startVertex, - triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, joinNormal, 0, 0, false, startVertex, triangleStore, lineDistances + ); } else if (middleVertex && currentJoin == LineJoinType::FlipBevel) { // miter is too big, flip the direction to make a beveled join @@ -307,15 +319,17 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, } else { const double direction = prevNormal->x * nextNormal->y - prevNormal->y * nextNormal->x > 0 ? -1 : 1; const double bevelLength = miterLength * util::mag(*prevNormal + *nextNormal) / - util::mag(*prevNormal - *nextNormal); + util::mag(*prevNormal - *nextNormal); joinNormal = util::perp(joinNormal) * bevelLength * direction; } - addCurrentVertex(*currentCoordinate, distance, joinNormal, 0, 0, false, startVertex, - triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, joinNormal, 0, 0, false, startVertex, triangleStore, lineDistances + ); - addCurrentVertex(*currentCoordinate, distance, joinNormal * -1.0, 0, 0, false, startVertex, - triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, joinNormal * -1.0, 0, 0, false, startVertex, triangleStore, lineDistances + ); } else if (middleVertex && (currentJoin == LineJoinType::Bevel || currentJoin == LineJoinType::FakeRound)) { const bool lineTurnsLeft = (prevNormal->x * nextNormal->y - prevNormal->y * nextNormal->x) > 0; const auto offset = static_cast(-std::sqrt(miterLength * miterLength - 1)); @@ -332,8 +346,17 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // Close previous segement with bevel if (!startOfLine) { - addCurrentVertex(*currentCoordinate, distance, *prevNormal, offsetA, offsetB, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, + distance, + *prevNormal, + offsetA, + offsetB, + false, + startVertex, + triangleStore, + lineDistances + ); } if (currentJoin == LineJoinType::FakeRound) { @@ -348,41 +371,62 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, for (unsigned m = 1; m < n; ++m) { double t = static_cast(m) / n; if (t != 0.5) { - // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp + // approximate spherical interpolation + // https://observablehq.com/@mourner/approximating-geometric-slerp const double t2 = t - 0.5; const double A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519)); const double B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638); t = t + t * t2 * (t - 1) * (A * t2 * t2 + B); } auto approxFractionalNormal = util::unit(*prevNormal * (1.0 - t) + *nextNormal * t); - addPieSliceVertex(*currentCoordinate, distance, approxFractionalNormal, lineTurnsLeft, startVertex, triangleStore, lineDistances); + addPieSliceVertex( + *currentCoordinate, + distance, + approxFractionalNormal, + lineTurnsLeft, + startVertex, + triangleStore, + lineDistances + ); } } // Start next segment if (nextCoordinate) { - addCurrentVertex(*currentCoordinate, distance, *nextNormal, -offsetA, -offsetB, - false, startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, + distance, + *nextNormal, + -offsetA, + -offsetB, + false, + startVertex, + triangleStore, + lineDistances + ); } } else if (!middleVertex && currentCap == LineCapType::Butt) { if (!startOfLine) { // Close previous segment with a butt - addCurrentVertex(*currentCoordinate, distance, *prevNormal, 0, 0, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *prevNormal, 0, 0, false, startVertex, triangleStore, lineDistances + ); } // Start next segment with a butt if (nextCoordinate) { - addCurrentVertex(*currentCoordinate, distance, *nextNormal, 0, 0, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *nextNormal, 0, 0, false, startVertex, triangleStore, lineDistances + ); } } else if (!middleVertex && currentCap == LineCapType::Square) { if (!startOfLine) { // Close previous segment with a square cap - addCurrentVertex(*currentCoordinate, distance, *prevNormal, 1, 1, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *prevNormal, 1, 1, false, startVertex, triangleStore, lineDistances + ); // The segment is done. Unset vertices to disconnect segments. e1 = e2 = -1; @@ -390,19 +434,22 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // Start next segment if (nextCoordinate) { - addCurrentVertex(*currentCoordinate, distance, *nextNormal, -1, -1, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *nextNormal, -1, -1, false, startVertex, triangleStore, lineDistances + ); } } else if (middleVertex ? currentJoin == LineJoinType::Round : currentCap == LineCapType::Round) { if (!startOfLine) { // Close previous segment with a butt - addCurrentVertex(*currentCoordinate, distance, *prevNormal, 0, 0, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *prevNormal, 0, 0, false, startVertex, triangleStore, lineDistances + ); // Add round cap or linejoin at end of segment - addCurrentVertex(*currentCoordinate, distance, *prevNormal, 1, 1, true, startVertex, - triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *prevNormal, 1, 1, true, startVertex, triangleStore, lineDistances + ); // The segment is done. Unset vertices to disconnect segments. e1 = e2 = -1; @@ -411,20 +458,28 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // Start next segment with a butt if (nextCoordinate) { // Add round cap before first segment - addCurrentVertex(*currentCoordinate, distance, *nextNormal, -1, -1, true, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *nextNormal, -1, -1, true, startVertex, triangleStore, lineDistances + ); - addCurrentVertex(*currentCoordinate, distance, *nextNormal, 0, 0, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *nextNormal, 0, 0, false, startVertex, triangleStore, lineDistances + ); } } if (isSharpCorner && i < len - 1) { const auto nextSegmentLength = util::dist(*currentCoordinate, *nextCoordinate); if (nextSegmentLength > 2 * sharpCornerOffset) { - GeometryCoordinate newCurrentVertex = *currentCoordinate + convertPoint(util::round(convertPoint(*nextCoordinate - *currentCoordinate) * (sharpCornerOffset / nextSegmentLength))); + GeometryCoordinate newCurrentVertex = *currentCoordinate + + convertPoint(util::round( + convertPoint(*nextCoordinate - *currentCoordinate) * + (sharpCornerOffset / nextSegmentLength) + )); distance += util::dist(newCurrentVertex, *currentCoordinate); - addCurrentVertex(newCurrentVertex, distance, *nextNormal, 0, 0, false, startVertex, triangleStore, lineDistances); + addCurrentVertex( + newCurrentVertex, distance, *nextNormal, 0, 0, false, startVertex, triangleStore, lineDistances + ); currentCoordinate = newCurrentVertex; } } @@ -451,21 +506,29 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, segment.indexLength += triangleStore.size() * 3; } -void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate, - double &distance, - const Point& normal, - double endLeft, - double endRight, - bool round, - std::size_t startVertex, - std::vector& triangleStore, - std::optional lineDistances) { +void LineBucket::addCurrentVertex( + const GeometryCoordinate& currentCoordinate, + double& distance, + const Point& normal, + double endLeft, + double endRight, + bool round, + std::size_t startVertex, + std::vector& triangleStore, + std::optional lineDistances +) { Point extrude = normal; double scaledDistance = lineDistances ? lineDistances->scaleToMaxLineDistance(distance) : distance; - if (endLeft) - extrude = extrude - (util::perp(normal) * endLeft); - vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, round, false, static_cast(endLeft), static_cast(scaledDistance * LINE_DISTANCE_SCALE))); + if (endLeft) extrude = extrude - (util::perp(normal) * endLeft); + vertices.emplace_back(LineProgram::layoutVertex( + currentCoordinate, + extrude, + round, + false, + static_cast(endLeft), + static_cast(scaledDistance * LINE_DISTANCE_SCALE) + )); e3 = vertices.elements() - 1 - startVertex; if (e1 >= 0 && e2 >= 0) { triangleStore.emplace_back(static_cast(e1), static_cast(e2), static_cast(e3)); @@ -474,9 +537,15 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate, e2 = e3; extrude = normal * -1.0; - if (endRight) - extrude = extrude - (util::perp(normal) * endRight); - vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, round, true, static_cast(-endRight), static_cast(scaledDistance * LINE_DISTANCE_SCALE))); + if (endRight) extrude = extrude - (util::perp(normal) * endRight); + vertices.emplace_back(LineProgram::layoutVertex( + currentCoordinate, + extrude, + round, + true, + static_cast(-endRight), + static_cast(scaledDistance * LINE_DISTANCE_SCALE) + )); e3 = vertices.elements() - 1 - startVertex; if (e1 >= 0 && e2 >= 0) { triangleStore.emplace_back(static_cast(e1), static_cast(e2), static_cast(e3)); @@ -490,23 +559,29 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate, // to `linesofar`. if (distance > MAX_LINE_DISTANCE / 2.0f && !lineDistances) { distance = 0.0; - addCurrentVertex(currentCoordinate, distance, normal, endLeft, endRight, round, startVertex, triangleStore, lineDistances); + addCurrentVertex( + currentCoordinate, distance, normal, endLeft, endRight, round, startVertex, triangleStore, lineDistances + ); } } -void LineBucket::addPieSliceVertex(const GeometryCoordinate& currentVertex, - double distance, - const Point& extrude, - bool lineTurnsLeft, - std::size_t startVertex, - std::vector& triangleStore, - std::optional lineDistances) { +void LineBucket::addPieSliceVertex( + const GeometryCoordinate& currentVertex, + double distance, + const Point& extrude, + bool lineTurnsLeft, + std::size_t startVertex, + std::vector& triangleStore, + std::optional lineDistances +) { Point flippedExtrude = extrude * (lineTurnsLeft ? -1.0 : 1.0); if (lineDistances) { distance = lineDistances->scaleToMaxLineDistance(distance); } - vertices.emplace_back(LineProgram::layoutVertex(currentVertex, flippedExtrude, false, lineTurnsLeft, 0, static_cast(distance * LINE_DISTANCE_SCALE))); + vertices.emplace_back(LineProgram::layoutVertex( + currentVertex, flippedExtrude, false, lineTurnsLeft, 0, static_cast(distance * LINE_DISTANCE_SCALE) + )); e3 = vertices.elements() - 1 - startVertex; if (e1 >= 0 && e2 >= 0) { triangleStore.emplace_back(static_cast(e1), static_cast(e2), static_cast(e3)); @@ -537,7 +612,11 @@ bool LineBucket::hasData() const { } template -static float get(const LinePaintProperties::PossiblyEvaluated& evaluated, const std::string& id, const std::map& paintPropertyBinders) { +static float get( + const LinePaintProperties::PossiblyEvaluated& evaluated, + const std::string& id, + const std::map& paintPropertyBinders +) { auto it = paintPropertyBinders.find(id); if (it == paintPropertyBinders.end() || !it->second.statistics().max()) { return evaluated.get().constantOr(Property::defaultValue()); @@ -559,8 +638,12 @@ float LineBucket::getQueryRadius(const RenderLayer& layer) const { return lineWidth / 2.0f + std::abs(offset) + util::length(translate[0], translate[1]); } -void LineBucket::update(const FeatureStates& states, const GeometryTileLayer& layer, const std::string& layerID, - const ImagePositions& imagePositions) { +void LineBucket::update( + const FeatureStates& states, + const GeometryTileLayer& layer, + const std::string& layerID, + const ImagePositions& imagePositions +) { auto it = paintPropertyBinders.find(layerID); if (it != paintPropertyBinders.end()) { it->second.updateVertexVectors(states, layer, imagePositions); diff --git a/src/mbgl/renderer/buckets/line_bucket.hpp b/src/mbgl/renderer/buckets/line_bucket.hpp index e3daa517705..6996f2b27bb 100644 --- a/src/mbgl/renderer/buckets/line_bucket.hpp +++ b/src/mbgl/renderer/buckets/line_bucket.hpp @@ -19,18 +19,17 @@ class LineBucket final : public Bucket { public: using PossiblyEvaluatedLayoutProperties = style::LineLayoutProperties::PossiblyEvaluated; - LineBucket(PossiblyEvaluatedLayoutProperties layout, - const std::map>& layerPaintProperties, - float zoom, - uint32_t overscaling); + LineBucket( + PossiblyEvaluatedLayoutProperties layout, + const std::map>& layerPaintProperties, + float zoom, + uint32_t overscaling + ); ~LineBucket() override; - void addFeature(const GeometryTileFeature&, - const GeometryCollection&, - const mbgl::ImagePositions& patternPositions, - const PatternLayerMap&, - std::size_t, - const CanonicalTileID&) override; + void + addFeature(const GeometryTileFeature&, const GeometryCollection&, const mbgl::ImagePositions& patternPositions, const PatternLayerMap&, std::size_t, const CanonicalTileID&) + override; bool hasData() const override; @@ -55,25 +54,35 @@ class LineBucket final : public Bucket { void addGeometry(const GeometryCoordinates&, const GeometryTileFeature&, const CanonicalTileID&); struct TriangleElement { - TriangleElement(uint16_t a_, uint16_t b_, uint16_t c_) : a(a_), b(b_), c(c_) {} + TriangleElement(uint16_t a_, uint16_t b_, uint16_t c_) + : a(a_), + b(b_), + c(c_) {} uint16_t a, b, c; }; class Distances; - void addCurrentVertex(const GeometryCoordinate& currentCoordinate, - double& distance, - const Point& normal, - double endLeft, - double endRight, - bool round, - std::size_t startVertex, - std::vector& triangleStore, - std::optional distances); - - void addPieSliceVertex(const GeometryCoordinate& currentVertex, double distance, - const Point& extrude, bool lineTurnsLeft, std::size_t startVertex, - std::vector& triangleStore, - std::optional distances); + void addCurrentVertex( + const GeometryCoordinate& currentCoordinate, + double& distance, + const Point& normal, + double endLeft, + double endRight, + bool round, + std::size_t startVertex, + std::vector& triangleStore, + std::optional distances + ); + + void addPieSliceVertex( + const GeometryCoordinate& currentVertex, + double distance, + const Point& extrude, + bool lineTurnsLeft, + std::size_t startVertex, + std::vector& triangleStore, + std::optional distances + ); std::ptrdiff_t e1; std::ptrdiff_t e2; diff --git a/src/mbgl/renderer/buckets/raster_bucket.cpp b/src/mbgl/renderer/buckets/raster_bucket.cpp index a877e6e17b3..24d699ead97 100644 --- a/src/mbgl/renderer/buckets/raster_bucket.cpp +++ b/src/mbgl/renderer/buckets/raster_bucket.cpp @@ -10,7 +10,8 @@ using namespace style; RasterBucket::RasterBucket(PremultipliedImage&& image_) : image(std::make_shared(std::move(image_))) {} -RasterBucket::RasterBucket(std::shared_ptr image_) : image(std::move(image_)) {} +RasterBucket::RasterBucket(std::shared_ptr image_) + : image(std::move(image_)) {} RasterBucket::~RasterBucket() = default; @@ -54,7 +55,7 @@ void RasterBucket::setMask(TileMask&& mask_) { mask = std::move(mask_); clear(); - if (mask == TileMask{ { 0, 0, 0 } }) { + if (mask == TileMask{{0, 0, 0}}) { // We want to render the full tile, and keeping the segments/vertices/indices empty means // using the global shared buffers for covering the entire tile. return; @@ -71,24 +72,28 @@ void RasterBucket::setMask(TileMask&& mask_) { // Create a quad for every masked tile. const int32_t vertexExtent = util::EXTENT >> id.z; - const Point tlVertex = { static_cast(id.x * vertexExtent), - static_cast(id.y * vertexExtent) }; - const Point brVertex = { static_cast(tlVertex.x + vertexExtent), - static_cast(tlVertex.y + vertexExtent) }; + const Point tlVertex = { + static_cast(id.x * vertexExtent), static_cast(id.y * vertexExtent)}; + const Point brVertex = { + static_cast(tlVertex.x + vertexExtent), static_cast(tlVertex.y + vertexExtent)}; if (segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { // Move to a new segments because the old one can't hold the geometry. segments.emplace_back(vertices.elements(), indices.elements()); } - vertices.emplace_back( - RasterProgram::layoutVertex({ tlVertex.x, tlVertex.y }, { static_cast(tlVertex.x), static_cast(tlVertex.y) })); - vertices.emplace_back( - RasterProgram::layoutVertex({ brVertex.x, tlVertex.y }, { static_cast(brVertex.x), static_cast(tlVertex.y) })); - vertices.emplace_back( - RasterProgram::layoutVertex({ tlVertex.x, brVertex.y }, { static_cast(tlVertex.x), static_cast(brVertex.y) })); - vertices.emplace_back( - RasterProgram::layoutVertex({ brVertex.x, brVertex.y }, { static_cast(brVertex.x), static_cast(brVertex.y) })); + vertices.emplace_back(RasterProgram::layoutVertex( + {tlVertex.x, tlVertex.y}, {static_cast(tlVertex.x), static_cast(tlVertex.y)} + )); + vertices.emplace_back(RasterProgram::layoutVertex( + {brVertex.x, tlVertex.y}, {static_cast(brVertex.x), static_cast(tlVertex.y)} + )); + vertices.emplace_back(RasterProgram::layoutVertex( + {tlVertex.x, brVertex.y}, {static_cast(tlVertex.x), static_cast(brVertex.y)} + )); + vertices.emplace_back(RasterProgram::layoutVertex( + {brVertex.x, brVertex.y}, {static_cast(brVertex.x), static_cast(brVertex.y)} + )); auto& segment = segments.back(); assert(segment.vertexLength <= std::numeric_limits::max()); @@ -108,5 +113,4 @@ bool RasterBucket::hasData() const { return !!image; } - } // namespace mbgl diff --git a/src/mbgl/renderer/buckets/raster_bucket.hpp b/src/mbgl/renderer/buckets/raster_bucket.hpp index eeb00afb6dc..76ee30c0d91 100644 --- a/src/mbgl/renderer/buckets/raster_bucket.hpp +++ b/src/mbgl/renderer/buckets/raster_bucket.hpp @@ -28,7 +28,7 @@ class RasterBucket final : public Bucket { std::shared_ptr image; std::optional texture; - TileMask mask{ { 0, 0, 0 } }; + TileMask mask{{0, 0, 0}}; // Bucket specific vertices are used for Image Sources only // Raster Tile Sources use the default buffers from Painter diff --git a/src/mbgl/renderer/buckets/symbol_bucket.cpp b/src/mbgl/renderer/buckets/symbol_bucket.cpp index 74d04ece7a3..6dc101b007c 100644 --- a/src/mbgl/renderer/buckets/symbol_bucket.cpp +++ b/src/mbgl/renderer/buckets/symbol_bucket.cpp @@ -16,20 +16,22 @@ namespace { std::atomic maxBucketInstanceId; } // namespace -SymbolBucket::SymbolBucket(Immutable layout_, - const std::map>& paintProperties_, - const style::PropertyValue& textSize, - const style::PropertyValue& iconSize, - float zoom, - bool iconsNeedLinear_, - bool sortFeaturesByY_, - std::string bucketName_, - const std::vector&& symbolInstances_, - const std::vector&& sortKeyRanges_, - float tilePixelRatio_, - bool allowVerticalPlacement_, - std::vector placementModes_, - bool iconsInText_) +SymbolBucket::SymbolBucket( + Immutable layout_, + const std::map>& paintProperties_, + const style::PropertyValue& textSize, + const style::PropertyValue& iconSize, + float zoom, + bool iconsNeedLinear_, + bool sortFeaturesByY_, + std::string bucketName_, + const std::vector&& symbolInstances_, + const std::vector&& sortKeyRanges_, + float tilePixelRatio_, + bool allowVerticalPlacement_, + std::vector placementModes_, + bool iconsInText_ +) : layout(std::move(layout_)), bucketLeaderID(std::move(bucketName_)), iconsNeedLinear(iconsNeedLinear_ || iconSize.isDataDriven() || !iconSize.isZoomConstant()), @@ -55,10 +57,10 @@ SymbolBucket::SymbolBucket(Immutable& triangles, const PlacedSymbol& placedSymbol) { auto endIndex = placedSymbol.vertexStartIndex + placedSymbol.glyphOffsets.size() * 4; for (auto vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) { - triangles.emplace_back(static_cast(vertexIndex + 0), static_cast(vertexIndex + 1), static_cast(vertexIndex + 2)); - triangles.emplace_back(static_cast(vertexIndex + 1), static_cast(vertexIndex + 2), static_cast(vertexIndex + 3)); + triangles.emplace_back( + static_cast(vertexIndex + 0), + static_cast(vertexIndex + 1), + static_cast(vertexIndex + 2) + ); + triangles.emplace_back( + static_cast(vertexIndex + 1), + static_cast(vertexIndex + 2), + static_cast(vertexIndex + 3) + ); } } @@ -288,7 +320,7 @@ SymbolInstanceReferences SymbolBucket::getSortedSymbols(const float angle) const if (aRotated != bRotated) { return aRotated < bRotated; } - return a.dataFeatureIndex > b.dataFeatureIndex; // aRotated == bRotated + return a.dataFeatureIndex > b.dataFeatureIndex; // aRotated == bRotated }); return result; @@ -305,13 +337,14 @@ SymbolInstanceReferences SymbolBucket::getSymbols(const std::optionalget()); + hasFormatSectionOverrides_ = SymbolLayerPaintPropertyOverrides::hasOverrides(layout->get()); } return *hasFormatSectionOverrides_; } -std::pair SymbolBucket::registerAtCrossTileIndex(CrossTileSymbolLayerIndex& index, - const RenderTile& renderTile) { +std::pair SymbolBucket::registerAtCrossTileIndex( + CrossTileSymbolLayerIndex& index, const RenderTile& renderTile +) { bool firstTimeAdded = index.addBucket(renderTile.getOverscaledTileID(), renderTile.matrix, *this); return std::make_pair(bucketInstanceId, firstTimeAdded); } @@ -320,11 +353,13 @@ void SymbolBucket::place(Placement& placement, const BucketPlacementData& data, placement.placeSymbolBucket(data, seenIds); } -void SymbolBucket::updateVertices(const Placement& placement, - bool updateOpacities, - const TransformState& state, - const RenderTile& tile, - std::set& seenIds) { +void SymbolBucket::updateVertices( + const Placement& placement, + bool updateOpacities, + const TransformState& state, + const RenderTile& tile, + std::set& seenIds +) { if (updateOpacities) { placement.updateBucketOpacities(*this, state, seenIds); placementChangesUploaded = false; diff --git a/src/mbgl/renderer/buckets/symbol_bucket.hpp b/src/mbgl/renderer/buckets/symbol_bucket.hpp index 9f091ac44bf..a86e3ffd2a1 100644 --- a/src/mbgl/renderer/buckets/symbol_bucket.hpp +++ b/src/mbgl/renderer/buckets/symbol_bucket.hpp @@ -21,15 +21,17 @@ class CrossTileSymbolLayerIndex; class PlacedSymbol { public: - PlacedSymbol(Point anchorPoint_, - std::size_t segment_, - float lowerSize_, - float upperSize_, - std::array lineOffset_, - WritingModeType writingModes_, - GeometryCoordinates line_, - std::vector tileDistances_, - std::optional placedIconIndex_ = std::nullopt) + PlacedSymbol( + Point anchorPoint_, + std::size_t segment_, + float lowerSize_, + float upperSize_, + std::array lineOffset_, + WritingModeType writingModes_, + GeometryCoordinates line_, + std::vector tileDistances_, + std::optional placedIconIndex_ = std::nullopt + ) : anchorPoint(anchorPoint_), segment(segment_), lowerSize(lowerSize_), @@ -65,28 +67,31 @@ class PlacedSymbol { class SymbolBucket final : public Bucket { public: - SymbolBucket(Immutable, - const std::map>&, - const style::PropertyValue& textSize, - const style::PropertyValue& iconSize, - float zoom, - bool iconsNeedLinear, - bool sortFeaturesByY, - std::string bucketName_, - const std::vector&&, - const std::vector&&, - float tilePixelRatio, - bool allowVerticalPlacement, - std::vector placementModes, - bool iconsInText); + SymbolBucket( + Immutable, + const std::map>&, + const style::PropertyValue& textSize, + const style::PropertyValue& iconSize, + float zoom, + bool iconsNeedLinear, + bool sortFeaturesByY, + std::string bucketName_, + const std::vector&&, + const std::vector&&, + float tilePixelRatio, + bool allowVerticalPlacement, + std::vector placementModes, + bool iconsInText + ); ~SymbolBucket() override; void upload(gfx::UploadPass&) override; bool hasData() const override; std::pair registerAtCrossTileIndex(CrossTileSymbolLayerIndex&, const RenderTile&) override; void place(Placement&, const BucketPlacementData&, std::set&) override; - void updateVertices( - const Placement&, bool updateOpacities, const TransformState&, const RenderTile&, std::set&) override; + void + updateVertices(const Placement&, bool updateOpacities, const TransformState&, const RenderTile&, std::set&) + override; bool hasTextData() const; bool hasIconData() const; bool hasSdfIconData() const; @@ -149,7 +154,7 @@ class SymbolBucket final : public Bucket { Buffer icon; Buffer sdfIcon; - + struct CollisionBuffer { gfx::VertexVector> vertices; gfx::VertexVector> dynamicVertices; diff --git a/src/mbgl/renderer/cross_faded_property_evaluator.cpp b/src/mbgl/renderer/cross_faded_property_evaluator.cpp index 65f5b31467b..9df0d4b2f8c 100644 --- a/src/mbgl/renderer/cross_faded_property_evaluator.cpp +++ b/src/mbgl/renderer/cross_faded_property_evaluator.cpp @@ -18,17 +18,17 @@ Faded CrossFadedPropertyEvaluator::operator()(const T& constant) const { template Faded CrossFadedPropertyEvaluator::operator()(const style::PropertyExpression& expression) const { - return calculate(expression.evaluate(parameters.z - 1.0f), - expression.evaluate(parameters.z), - expression.evaluate(parameters.z + 1.0f)); + return calculate( + expression.evaluate(parameters.z - 1.0f), + expression.evaluate(parameters.z), + expression.evaluate(parameters.z + 1.0f) + ); } template Faded CrossFadedPropertyEvaluator::calculate(const T& min, const T& mid, const T& max) const { const float z = parameters.z; - return z > parameters.zoomHistory.lastIntegerZoom - ? Faded { min, mid } - : Faded { max, mid }; + return z > parameters.zoomHistory.lastIntegerZoom ? Faded{min, mid} : Faded{max, mid}; } template class CrossFadedPropertyEvaluator; diff --git a/src/mbgl/renderer/cross_faded_property_evaluator.hpp b/src/mbgl/renderer/cross_faded_property_evaluator.hpp index e925b96fa3b..f0fe90f69ae 100644 --- a/src/mbgl/renderer/cross_faded_property_evaluator.hpp +++ b/src/mbgl/renderer/cross_faded_property_evaluator.hpp @@ -35,8 +35,7 @@ class CrossFadedPropertyEvaluator { namespace util { template -struct Interpolator> - : Uninterpolated {}; +struct Interpolator> : Uninterpolated {}; } // namespace util } // namespace mbgl diff --git a/src/mbgl/renderer/data_driven_property_evaluator.hpp b/src/mbgl/renderer/data_driven_property_evaluator.hpp index bd476ebe585..25b8bc8d10c 100644 --- a/src/mbgl/renderer/data_driven_property_evaluator.hpp +++ b/src/mbgl/renderer/data_driven_property_evaluator.hpp @@ -18,16 +18,12 @@ class DataDrivenPropertyEvaluator { : parameters(parameters_), defaultValue(std::move(defaultValue_)) {} - ResultType operator()(const style::Undefined&) const { - return ResultType(defaultValue); - } + ResultType operator()(const style::Undefined&) const { return ResultType(defaultValue); } - ResultType operator()(const T& constant) const { - return ResultType(constant); - } + ResultType operator()(const T& constant) const { return ResultType(constant); } ResultType operator()(const style::PropertyExpression& expression) const { - if (useIntegerZoom) { // Compiler will optimize out the unused branch. + if (useIntegerZoom) { // Compiler will optimize out the unused branch. if (!expression.isFeatureConstant() || !expression.isRuntimeConstant()) { auto returnExpression = expression; returnExpression.useIntegerZoom = true; @@ -53,14 +49,12 @@ class DataDrivenPropertyEvaluator> { using ResultType = PossiblyEvaluatedPropertyValue>; DataDrivenPropertyEvaluator(const PropertyEvaluationParameters& parameters_, T defaultValue_) - : parameters(parameters_), - defaultValue(std::move(defaultValue_)) {} + : parameters(parameters_), + defaultValue(std::move(defaultValue_)) {} - ResultType operator()(const T& constant) const { - return ResultType(calculate(constant, constant, constant)); - } + ResultType operator()(const T& constant) const { return ResultType(calculate(constant, constant, constant)); } - ResultType operator()(const style::Undefined& ) const { + ResultType operator()(const style::Undefined&) const { return ResultType(calculate(defaultValue, defaultValue, defaultValue)); } @@ -73,13 +67,10 @@ class DataDrivenPropertyEvaluator> { } } - private: Faded calculate(const T& min, const T& mid, const T& max) const { const float z = parameters.z; - return z > parameters.zoomHistory.lastIntegerZoom - ? Faded { min, mid } - : Faded { max, mid }; + return z > parameters.zoomHistory.lastIntegerZoom ? Faded{min, mid} : Faded{max, mid}; }; const PropertyEvaluationParameters& parameters; diff --git a/src/mbgl/renderer/image_atlas.cpp b/src/mbgl/renderer/image_atlas.cpp index 36da19bbce3..269e9a3968e 100644 --- a/src/mbgl/renderer/image_atlas.cpp +++ b/src/mbgl/renderer/image_atlas.cpp @@ -15,35 +15,29 @@ ImagePosition::ImagePosition(const mapbox::Bin& bin, const style::Image::Impl& i stretchY(image.stretchY), content(image.content) {} -const mapbox::Bin& _packImage(mapbox::ShelfPack& pack, const style::Image::Impl& image, ImageAtlas& resultImage, ImageType imageType) { - const mapbox::Bin& bin = *pack.packOne(-1, - image.image.size.width + 2 * padding, - image.image.size.height + 2 * padding); - - resultImage.image.resize({ - static_cast(pack.width()), - static_cast(pack.height()) - }); - - PremultipliedImage::copy(image.image, - resultImage.image, - { 0, 0 }, - { - bin.x + padding, - bin.y + padding - }, - image.image.size); +const mapbox::Bin& _packImage( + mapbox::ShelfPack& pack, const style::Image::Impl& image, ImageAtlas& resultImage, ImageType imageType +) { + const mapbox::Bin& bin = *pack.packOne( + -1, image.image.size.width + 2 * padding, image.image.size.height + 2 * padding + ); + + resultImage.image.resize({static_cast(pack.width()), static_cast(pack.height())}); + + PremultipliedImage::copy( + image.image, resultImage.image, {0, 0}, {bin.x + padding, bin.y + padding}, image.image.size + ); uint32_t x = bin.x + padding; uint32_t y = bin.y + padding; uint32_t w = image.image.size.width; uint32_t h = image.image.size.height; if (imageType == ImageType::Pattern) { - // Add 1 pixel wrapped padding on each side of the image. - PremultipliedImage::copy(image.image, resultImage.image, { 0, h - 1 }, { x, y - 1 }, { w, 1 }); // T - PremultipliedImage::copy(image.image, resultImage.image, { 0, 0 }, { x, y + h }, { w, 1 }); // B - PremultipliedImage::copy(image.image, resultImage.image, { w - 1, 0 }, { x - 1, y }, { 1, h }); // L - PremultipliedImage::copy(image.image, resultImage.image, { 0, 0 }, { x + w, y }, { 1, h }); // R + // Add 1 pixel wrapped padding on each side of the image. + PremultipliedImage::copy(image.image, resultImage.image, {0, h - 1}, {x, y - 1}, {w, 1}); // T + PremultipliedImage::copy(image.image, resultImage.image, {0, 0}, {x, y + h}, {w, 1}); // B + PremultipliedImage::copy(image.image, resultImage.image, {w - 1, 0}, {x - 1, y}, {1, h}); // L + PremultipliedImage::copy(image.image, resultImage.image, {0, 0}, {x + w, y}, {1, h}); // R } return bin; } @@ -51,9 +45,8 @@ const mapbox::Bin& _packImage(mapbox::ShelfPack& pack, const style::Image::Impl& namespace { void populateImagePatches( - ImagePositions& imagePositions, - const ImageManager& imageManager, - std::vector& /*out*/ patches) { + ImagePositions& imagePositions, const ImageManager& imageManager, std::vector& /*out*/ patches +) { for (auto& updatedImageVersion : imageManager.updatedImageVersions) { const std::string& name = updatedImageVersion.first; const uint32_t version = updatedImageVersion.second; @@ -80,7 +73,9 @@ std::vector ImageAtlas::getImagePatchesAndUpdateVersions(const Image return imagePatches; } -ImageAtlas makeImageAtlas(const ImageMap& icons, const ImageMap& patterns, const std::unordered_map& versionMap) { +ImageAtlas makeImageAtlas( + const ImageMap& icons, const ImageMap& patterns, const std::unordered_map& versionMap +) { ImageAtlas result; mapbox::ShelfPack::ShelfPackOptions options; @@ -92,7 +87,7 @@ ImageAtlas makeImageAtlas(const ImageMap& icons, const ImageMap& patterns, const const mapbox::Bin& bin = _packImage(pack, image, result, ImageType::Icon); auto it = versionMap.find(entry.first); auto version = it != versionMap.end() ? it->second : 0; - result.iconPositions.emplace(image.id, ImagePosition { bin, image, version }); + result.iconPositions.emplace(image.id, ImagePosition{bin, image, version}); } for (const auto& entry : patterns) { @@ -100,14 +95,11 @@ ImageAtlas makeImageAtlas(const ImageMap& icons, const ImageMap& patterns, const const mapbox::Bin& bin = _packImage(pack, image, result, ImageType::Pattern); auto it = versionMap.find(entry.first); auto version = it != versionMap.end() ? it->second : 0; - result.patternPositions.emplace(image.id, ImagePosition { bin, image, version }); + result.patternPositions.emplace(image.id, ImagePosition{bin, image, version}); } pack.shrink(); - result.image.resize({ - static_cast(pack.width()), - static_cast(pack.height()) - }); + result.image.resize({static_cast(pack.width()), static_cast(pack.height())}); return result; } diff --git a/src/mbgl/renderer/image_atlas.hpp b/src/mbgl/renderer/image_atlas.hpp index d8f021faf42..78544e75ec7 100644 --- a/src/mbgl/renderer/image_atlas.hpp +++ b/src/mbgl/renderer/image_atlas.hpp @@ -34,14 +34,15 @@ class ImagePosition { } std::array br() const { - return {{static_cast(paddedRect.x + paddedRect.w - padding), - static_cast(paddedRect.y + paddedRect.h - padding)}}; + return { + {static_cast(paddedRect.x + paddedRect.w - padding), + static_cast(paddedRect.y + paddedRect.h - padding)}}; } std::array tlbr() const { const auto _tl = tl(); const auto _br = br(); - return {{ _tl[0], _tl[1], _br[0], _br[1] }}; + return {{_tl[0], _tl[1], _br[0], _br[1]}}; } std::array displaySize() const { @@ -57,7 +58,8 @@ using ImagePositions = std::map; class ImagePatch { public: ImagePatch(Immutable image_, const Rect& paddedRect_) - : image(std::move(image_)), paddedRect(paddedRect_) {} + : image(std::move(image_)), + paddedRect(paddedRect_) {} Immutable image; Rect paddedRect; @@ -72,6 +74,8 @@ class ImageAtlas { std::vector getImagePatchesAndUpdateVersions(const ImageManager&); }; -ImageAtlas makeImageAtlas(const ImageMap&, const ImageMap&, const std::unordered_map& versionMap); +ImageAtlas makeImageAtlas( + const ImageMap&, const ImageMap&, const std::unordered_map& versionMap +); } // namespace mbgl diff --git a/src/mbgl/renderer/image_manager.cpp b/src/mbgl/renderer/image_manager.cpp index 62df741e196..61c714441eb 100644 --- a/src/mbgl/renderer/image_manager.cpp +++ b/src/mbgl/renderer/image_manager.cpp @@ -237,8 +237,9 @@ void ImageManager::checkMissingAndNotify(ImageRequestor& requestor, const ImageR req->removePendingRequest(missingImage); } }; - observer->onStyleImageMissing(missingImage, - Scheduler::GetCurrent()->bindOnce(std::move(removePendingRequests))); + observer->onStyleImageMissing( + missingImage, Scheduler::GetCurrent()->bindOnce(std::move(removePendingRequests)) + ); } } else { // Associate requestor with an image that was provided by the client. @@ -277,8 +278,8 @@ void ImageManager::dumpDebugLogs() const { Log::Info(Event::General, ss.str()); } -ImageRequestor::ImageRequestor(ImageManager& imageManager_) : imageManager(imageManager_) { -} +ImageRequestor::ImageRequestor(ImageManager& imageManager_) + : imageManager(imageManager_) {} ImageRequestor::~ImageRequestor() { imageManager.removeRequestor(*this); diff --git a/src/mbgl/renderer/image_manager.hpp b/src/mbgl/renderer/image_manager.hpp index fec19981f52..4d96df21a6b 100644 --- a/src/mbgl/renderer/image_manager.hpp +++ b/src/mbgl/renderer/image_manager.hpp @@ -75,7 +75,9 @@ class ImageRequestor { public: explicit ImageRequestor(ImageManager&); virtual ~ImageRequestor(); - virtual void onImagesAvailable(ImageMap icons, ImageMap patterns, ImageVersionMap versionMap, uint64_t imageCorrelationID) = 0; + virtual void onImagesAvailable( + ImageMap icons, ImageMap patterns, ImageVersionMap versionMap, uint64_t imageCorrelationID + ) = 0; void addPendingRequest(const std::string& imageId) { pendingRequests.insert(imageId); } bool hasPendingRequest(const std::string& imageId) const { return pendingRequests.count(imageId); } diff --git a/src/mbgl/renderer/layers/render_background_layer.cpp b/src/mbgl/renderer/layers/render_background_layer.cpp index 95537c0ffaf..6d440e3cbf7 100644 --- a/src/mbgl/renderer/layers/render_background_layer.cpp +++ b/src/mbgl/renderer/layers/render_background_layer.cpp @@ -31,24 +31,24 @@ RenderBackgroundLayer::RenderBackgroundLayer(Immutable( staticImmutableCast(baseImpl), parameters.getCrossfadeParameters(), - unevaluated.evaluate(parameters)); - - passes = properties->evaluated.get() == 0.0f - ? RenderPass::None - : (!unevaluated.get().isUndefined() - || properties->evaluated.get() < 1.0f - || properties->evaluated.get().a < 1.0f) - ? RenderPass::Translucent - // Supply both - evaluated based on opaquePassCutoff in render(). - : RenderPass::Opaque | RenderPass::Translucent; + unevaluated.evaluate(parameters) + ); + + passes = properties->evaluated.get() == 0.0f ? RenderPass::None + : (!unevaluated.get().isUndefined() || + properties->evaluated.get() < 1.0f || + properties->evaluated.get().a < 1.0f) + ? RenderPass::Translucent + // Supply both - evaluated based on opaquePassCutoff in render(). + : RenderPass::Opaque | RenderPass::Translucent; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -73,15 +73,14 @@ void RenderBackgroundLayer::render(PaintParameters& parameters) { const BackgroundProgram::Binders paintAttributeData(properties, 0); auto draw = [&](auto& program, auto&& uniformValues, const auto& textureBindings, const uint32_t id) { - const auto allUniformValues = - program.computeAllUniformValues(std::forward(uniformValues), - paintAttributeData, - properties, - static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = program.computeAllAttributeBindings( - *parameters.staticData.tileVertexBuffer, + const auto allUniformValues = program.computeAllUniformValues( + std::forward(uniformValues), paintAttributeData, - properties + properties, + static_cast(parameters.state.getZoom()) + ); + const auto allAttributeBindings = program.computeAllAttributeBindings( + *parameters.staticData.tileVertexBuffer, paintAttributeData, properties ); checkRenderability(parameters, program.activeBindingCount(allAttributeBindings)); @@ -91,8 +90,8 @@ void RenderBackgroundLayer::render(PaintParameters& parameters) { *parameters.renderPass, gfx::Triangles(), parameters.depthModeForSublayer( - 0, - parameters.pass == RenderPass::Opaque ? gfx::DepthMaskType::ReadWrite : gfx::DepthMaskType::ReadOnly), + 0, parameters.pass == RenderPass::Opaque ? gfx::DepthMaskType::ReadWrite : gfx::DepthMaskType::ReadOnly + ), gfx::StencilMode::disabled(), parameters.colorModeForRenderPass(), gfx::CullFaceMode::disabled(), @@ -101,7 +100,8 @@ void RenderBackgroundLayer::render(PaintParameters& parameters) { allUniformValues, allAttributeBindings, textureBindings, - util::toString(id)); + util::toString(id) + ); }; if (segments.empty()) { @@ -116,43 +116,50 @@ void RenderBackgroundLayer::render(PaintParameters& parameters) { std::optional imagePosB = parameters.patternAtlas.getPattern(evaluated.get().to.id()); - if (!imagePosA || !imagePosB) - return; + if (!imagePosA || !imagePosB) return; uint32_t i = 0; for (const auto& tileID : util::tileCover(parameters.state, parameters.state.getIntegerZoom())) { const UnwrappedTileID unwrappedTileID = tileID.toUnwrapped(); - draw(*backgroundPatternProgram, - BackgroundPatternProgram::layoutUniformValues(parameters.matrixForTile(unwrappedTileID), - evaluated.get(), - parameters.patternAtlas.getPixelSize(), - *imagePosA, - *imagePosB, - crossfade, - unwrappedTileID, - parameters.state), - BackgroundPatternProgram::TextureBindings{ - textures::image::Value{parameters.patternAtlas.textureBinding()}, - }, - i++); + draw( + *backgroundPatternProgram, + BackgroundPatternProgram::layoutUniformValues( + parameters.matrixForTile(unwrappedTileID), + evaluated.get(), + parameters.patternAtlas.getPixelSize(), + *imagePosA, + *imagePosB, + crossfade, + unwrappedTileID, + parameters.state + ), + BackgroundPatternProgram::TextureBindings{ + textures::image::Value{parameters.patternAtlas.textureBinding()}, + }, + i++ + ); } } else { - auto backgroundRenderPass = (evaluated.get().a >= 1.0f - && evaluated.get() >= 1.0f - && parameters.currentLayer >= parameters.opaquePassCutoff) ? RenderPass::Opaque : RenderPass::Translucent; + auto backgroundRenderPass = (evaluated.get().a >= 1.0f && + evaluated.get() >= 1.0f && + parameters.currentLayer >= parameters.opaquePassCutoff) + ? RenderPass::Opaque + : RenderPass::Translucent; if (parameters.pass != backgroundRenderPass) { return; } uint32_t i = 0; for (const auto& tileID : util::tileCover(parameters.state, parameters.state.getIntegerZoom())) { - draw(*backgroundProgram, - BackgroundProgram::LayoutUniformValues{ - uniforms::matrix::Value(parameters.matrixForTile(tileID.toUnwrapped())), - uniforms::color::Value(evaluated.get()), - uniforms::opacity::Value(evaluated.get()), - }, - BackgroundProgram::TextureBindings{}, - i++); + draw( + *backgroundProgram, + BackgroundProgram::LayoutUniformValues{ + uniforms::matrix::Value(parameters.matrixForTile(tileID.toUnwrapped())), + uniforms::color::Value(evaluated.get()), + uniforms::opacity::Value(evaluated.get()), + }, + BackgroundProgram::TextureBindings{}, + i++ + ); } } } @@ -163,7 +170,7 @@ std::optional RenderBackgroundLayer::getSolidBackground() const { return std::nullopt; } - return { evaluated.get() * evaluated.get() }; + return {evaluated.get() * evaluated.get()}; } namespace { @@ -172,14 +179,14 @@ void addPatternIfNeeded(const std::string& id, const LayerPrepareParameters& par if (auto* image = params.imageManager.getImage(id)) { params.patternAtlas.addPattern(*image); } - } + } } } // namespace void RenderBackgroundLayer::prepare(const LayerPrepareParameters& params) { const auto& evaluated = getEvaluated(evaluatedProperties); if (!evaluated.get().to.empty()) { - // Ensures that the pattern bitmap gets copied to atlas bitmap. + // Ensures that the pattern bitmap gets copied to atlas bitmap. // Atlas bitmap is uploaded to atlas texture in upload. addPatternIfNeeded(evaluated.get().from.id(), params); addPatternIfNeeded(evaluated.get().to.id(), params); diff --git a/src/mbgl/renderer/layers/render_circle_layer.cpp b/src/mbgl/renderer/layers/render_circle_layer.cpp index 28e9368ed16..c35dbac106e 100644 --- a/src/mbgl/renderer/layers/render_circle_layer.cpp +++ b/src/mbgl/renderer/layers/render_circle_layer.cpp @@ -19,11 +19,16 @@ using namespace style; namespace { struct RenderableSegment { - RenderableSegment(const Segment& segment_, - const RenderTile& tile_, - const LayerRenderData* renderData_, - float sortKey_) - : segment(segment_), tile(tile_), renderData(renderData_), sortKey(sortKey_) {} + RenderableSegment( + const Segment& segment_, + const RenderTile& tile_, + const LayerRenderData* renderData_, + float sortKey_ + ) + : segment(segment_), + tile(tile_), + renderData(renderData_), + sortKey(sortKey_) {} const Segment& segment; const RenderTile& tile; @@ -53,17 +58,18 @@ void RenderCircleLayer::transition(const TransitionParameters& parameters) { void RenderCircleLayer::evaluate(const PropertyEvaluationParameters& parameters) { auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); + staticImmutableCast(baseImpl), unevaluated.evaluate(parameters) + ); const auto& evaluated = properties->evaluated; passes = ((evaluated.get().constantOr(1) > 0 || - evaluated.get().constantOr(1) > 0) - && (evaluated.get().constantOr(Color::black()).a > 0 || - evaluated.get().constantOr(Color::black()).a > 0) - && (evaluated.get().constantOr(1) > 0 || - evaluated.get().constantOr(1) > 0)) - ? RenderPass::Translucent : RenderPass::None; + evaluated.get().constantOr(1) > 0) && + (evaluated.get().constantOr(Color::black()).a > 0 || + evaluated.get().constantOr(Color::black()).a > 0) && + (evaluated.get().constantOr(1) > 0 || + evaluated.get().constantOr(1) > 0)) + ? RenderPass::Translucent + : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -99,8 +105,10 @@ void RenderCircleLayer::render(PaintParameters& parameters) { parameters.state)), uniforms::scale_with_map::Value(scaleWithMap), uniforms::extrude_scale::Value( - pitchWithMap ? std::array{{tile.id.pixelsToTileUnits(1.0f, static_cast(parameters.state.getZoom())), - tile.id.pixelsToTileUnits(1.0f, static_cast(parameters.state.getZoom()))}} + pitchWithMap ? std::array{{tile.id.pixelsToTileUnits( + 1.0f, static_cast(parameters.state.getZoom())), + tile.id.pixelsToTileUnits( + 1.0f, static_cast(parameters.state.getZoom()))}} : parameters.pixelsToGLUnits), uniforms::device_pixel_ratio::Value(parameters.pixelRatio), uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance()), @@ -108,24 +116,27 @@ void RenderCircleLayer::render(PaintParameters& parameters) { paintPropertyBinders, evaluated, static_cast(parameters.state.getZoom())); - const auto& allAttributeBindings = - CircleProgram::computeAllAttributeBindings(*circleBucket.vertexBuffer, paintPropertyBinders, evaluated); + const auto& allAttributeBindings = CircleProgram::computeAllAttributeBindings( + *circleBucket.vertexBuffer, paintPropertyBinders, evaluated + ); checkRenderability(parameters, CircleProgram::activeBindingCount(allAttributeBindings)); - circleProgram->draw(parameters.context, - *parameters.renderPass, - gfx::Triangles(), - parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), - gfx::StencilMode::disabled(), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - *circleBucket.indexBuffer, - segments, - allUniformValues, - allAttributeBindings, - CircleProgram::TextureBindings{}, - getID()); + circleProgram->draw( + parameters.context, + *parameters.renderPass, + gfx::Triangles(), + parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), + gfx::StencilMode::disabled(), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + *circleBucket.indexBuffer, + segments, + allUniformValues, + allAttributeBindings, + CircleProgram::TextureBindings{}, + getID() + ); }; const bool sortFeaturesByKey = !impl_cast(baseImpl).layout.get().isUndefined(); @@ -154,15 +165,16 @@ void RenderCircleLayer::render(PaintParameters& parameters) { } GeometryCoordinate projectPoint(const GeometryCoordinate& p, const mat4& posMatrix, const Size& size) { - vec4 pos = {{ static_cast(p.x), static_cast(p.y), 0, 1 }}; + vec4 pos = {{static_cast(p.x), static_cast(p.y), 0, 1}}; matrix::transformMat4(pos, pos, posMatrix); return { static_cast((static_cast(pos[0] / pos[3]) + 1) * size.width * 0.5), - static_cast((static_cast(pos[1] / pos[3]) + 1) * size.height * 0.5) - }; + static_cast((static_cast(pos[1] / pos[3]) + 1) * size.height * 0.5)}; } -GeometryCoordinates projectQueryGeometry(const GeometryCoordinates& queryGeometry, const mat4& posMatrix, const Size& size) { +GeometryCoordinates projectQueryGeometry( + const GeometryCoordinates& queryGeometry, const mat4& posMatrix, const Size& size +) { GeometryCoordinates projectedGeometry; for (auto& p : queryGeometry) { projectedGeometry.push_back(projectPoint(p, posMatrix, size)); @@ -170,18 +182,25 @@ GeometryCoordinates projectQueryGeometry(const GeometryCoordinates& queryGeometr return projectedGeometry; } -bool RenderCircleLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float zoom, - const TransformState& transformState, const float pixelsToTileUnits, - const mat4& posMatrix, const FeatureState& featureState) const { +bool RenderCircleLayer::queryIntersectsFeature( + const GeometryCoordinates& queryGeometry, + const GeometryTileFeature& feature, + const float zoom, + const TransformState& transformState, + const float pixelsToTileUnits, + const mat4& posMatrix, + const FeatureState& featureState +) const { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; // Translate query geometry const GeometryCoordinates& translatedQueryGeometry = FeatureIndex::translateQueryGeometry( - queryGeometry, - evaluated.get(), - evaluated.get(), - static_cast(transformState.getBearing()), - pixelsToTileUnits).value_or(queryGeometry); + queryGeometry, + evaluated.get(), + evaluated.get(), + static_cast(transformState.getBearing()), + pixelsToTileUnits + ) + .value_or(queryGeometry); // Evaluate functions auto radius = evaluated.evaluate(zoom, feature, featureState); @@ -193,18 +212,20 @@ bool RenderCircleLayer::queryIntersectsFeature(const GeometryCoordinates& queryG // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance bool alignWithMap = evaluated.evaluate(zoom, feature) == AlignmentType::Map; - const GeometryCoordinates& transformedQueryGeometry = alignWithMap ? - translatedQueryGeometry : - projectQueryGeometry(translatedQueryGeometry, posMatrix, transformState.getSize()); + const GeometryCoordinates& transformedQueryGeometry = + alignWithMap ? translatedQueryGeometry + : projectQueryGeometry(translatedQueryGeometry, posMatrix, transformState.getSize()); auto transformedSize = alignWithMap ? size * pixelsToTileUnits : size; const auto& geometry = feature.getGeometries(); for (auto& ring : geometry) { for (auto& point : ring) { - const GeometryCoordinate& transformedPoint = alignWithMap ? point : projectPoint(point, posMatrix, transformState.getSize()); + const GeometryCoordinate& transformedPoint = alignWithMap + ? point + : projectPoint(point, posMatrix, transformState.getSize()); float adjustedSize = transformedSize; - vec4 center = {{ static_cast(point.x), static_cast(point.y), 0, 1 }}; + vec4 center = {{static_cast(point.x), static_cast(point.y), 0, 1}}; matrix::transformMat4(center, center, posMatrix); auto pitchScale = evaluated.evaluate(zoom, feature); auto pitchAlignment = evaluated.evaluate(zoom, feature); @@ -214,7 +235,8 @@ bool RenderCircleLayer::queryIntersectsFeature(const GeometryCoordinates& queryG adjustedSize *= static_cast(transformState.getCameraToCenterDistance() / center[3]); } - if (util::polygonIntersectsBufferedPoint(transformedQueryGeometry, transformedPoint, adjustedSize)) return true; + if (util::polygonIntersectsBufferedPoint(transformedQueryGeometry, transformedPoint, adjustedSize)) + return true; } } diff --git a/src/mbgl/renderer/layers/render_circle_layer.hpp b/src/mbgl/renderer/layers/render_circle_layer.hpp index ccf4d40b786..f6d08fa41f8 100644 --- a/src/mbgl/renderer/layers/render_circle_layer.hpp +++ b/src/mbgl/renderer/layers/render_circle_layer.hpp @@ -20,13 +20,9 @@ class RenderCircleLayer final : public RenderLayer { bool hasCrossfade() const override; void render(PaintParameters&) override; - bool queryIntersectsFeature(const GeometryCoordinates&, - const GeometryTileFeature&, - float, - const TransformState&, - float, - const mat4&, - const FeatureState&) const override; + bool + queryIntersectsFeature(const GeometryCoordinates&, const GeometryTileFeature&, float, const TransformState&, float, const mat4&, const FeatureState&) + const override; // Paint properties style::CirclePaintProperties::Unevaluated unevaluated; diff --git a/src/mbgl/renderer/layers/render_fill_extrusion_layer.cpp b/src/mbgl/renderer/layers/render_fill_extrusion_layer.cpp index b6f4d9641a8..bb9ed3921f9 100644 --- a/src/mbgl/renderer/layers/render_fill_extrusion_layer.cpp +++ b/src/mbgl/renderer/layers/render_fill_extrusion_layer.cpp @@ -45,7 +45,8 @@ void RenderFillExtrusionLayer::evaluate(const PropertyEvaluationParameters& para auto properties = makeMutable( staticImmutableCast(baseImpl), parameters.getCrossfadeParameters(), - unevaluated.evaluate(parameters)); + unevaluated.evaluate(parameters) + ); passes = (properties->evaluated.get() > 0) ? (RenderPass::Translucent | RenderPass::Pass3D) @@ -98,15 +99,10 @@ void RenderFillExtrusionLayer::render(PaintParameters& parameters) { paintPropertyBinders.setPatternParameters(patternPositionA, patternPositionB, crossfade_); const auto allUniformValues = programInstance.computeAllUniformValues( - uniformValues, - paintPropertyBinders, - evaluated_, - static_cast(parameters.state.getZoom()) + uniformValues, paintPropertyBinders, evaluated_, static_cast(parameters.state.getZoom()) ); const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *tileBucket.vertexBuffer, - paintPropertyBinders, - evaluated_ + *tileBucket.vertexBuffer, paintPropertyBinders, evaluated_ ); checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); @@ -124,41 +120,45 @@ void RenderFillExtrusionLayer::render(PaintParameters& parameters) { allUniformValues, allAttributeBindings, textureBindings, - getID() + "/" + uniqueName); + getID() + "/" + uniqueName + ); }; if (unevaluated.get().isUndefined()) { // Draw solid color extrusions - auto drawTiles = [&](const gfx::StencilMode& stencilMode_, const gfx::ColorMode& colorMode_, const std::string& name) { - for (const RenderTile& tile : *renderTiles) { - const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); - if (!renderData) { - continue; + auto drawTiles = + [&](const gfx::StencilMode& stencilMode_, const gfx::ColorMode& colorMode_, const std::string& name) { + for (const RenderTile& tile : *renderTiles) { + const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); + if (!renderData) { + continue; + } + auto& bucket = static_cast(*renderData->bucket); + draw( + *fillExtrusionProgram, + evaluated, + crossfade, + stencilMode_, + colorMode_, + bucket, + FillExtrusionProgram::layoutUniformValues( + tile.translatedClipMatrix( + evaluated.get(), + evaluated.get(), + parameters.state + ), + parameters.state, + evaluated.get(), + parameters.evaluatedLight, + evaluated.get() + ), + {}, + {}, + FillExtrusionProgram::TextureBindings{}, + name + ); } - auto& bucket = static_cast(*renderData->bucket); - draw( - *fillExtrusionProgram, - evaluated, - crossfade, - stencilMode_, - colorMode_, - bucket, - FillExtrusionProgram::layoutUniformValues( - tile.translatedClipMatrix(evaluated.get(), - evaluated.get(), - parameters.state), - parameters.state, - evaluated.get(), - parameters.evaluatedLight, - evaluated.get() - ), - {}, - {}, - FillExtrusionProgram::TextureBindings{}, - name - ); - } - }; + }; if (evaluated.get() == 1) { // Draw opaque extrusions @@ -175,48 +175,52 @@ void RenderFillExtrusionLayer::render(PaintParameters& parameters) { } } else { // Draw textured extrusions - const auto fillPatternValue = - evaluated.get().constantOr(mbgl::Faded{"", ""}); - auto drawTiles = [&](const gfx::StencilMode& stencilMode_, const gfx::ColorMode& colorMode_, const std::string& name) { - for (const RenderTile& tile : *renderTiles) { - const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); - if (!renderData) { - continue; - } - auto& bucket = static_cast(*renderData->bucket); - std::optional patternPosA = tile.getPattern(fillPatternValue.from.id()); - std::optional patternPosB = tile.getPattern(fillPatternValue.to.id()); - - draw( - *fillExtrusionPatternProgram, - evaluated, - crossfade, - stencilMode_, - colorMode_, - bucket, - FillExtrusionPatternProgram::layoutUniformValues( - tile.translatedClipMatrix(evaluated.get(), - evaluated.get(), - parameters.state), - tile.getIconAtlasTexture().size, + const auto fillPatternValue = evaluated.get().constantOr(mbgl::Faded{ + "", ""}); + auto drawTiles = + [&](const gfx::StencilMode& stencilMode_, const gfx::ColorMode& colorMode_, const std::string& name) { + for (const RenderTile& tile : *renderTiles) { + const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); + if (!renderData) { + continue; + } + auto& bucket = static_cast(*renderData->bucket); + std::optional patternPosA = tile.getPattern(fillPatternValue.from.id()); + std::optional patternPosB = tile.getPattern(fillPatternValue.to.id()); + + draw( + *fillExtrusionPatternProgram, + evaluated, crossfade, - tile.id, - parameters.state, - evaluated.get(), - static_cast(-std::pow(2, tile.id.canonical.z) / util::tileSize_D / 8.0), - parameters.pixelRatio, - parameters.evaluatedLight, - evaluated.get() - ), - patternPosA, - patternPosB, - FillExtrusionPatternProgram::TextureBindings{ - textures::image::Value{ tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear }, - }, - name - ); - } - }; + stencilMode_, + colorMode_, + bucket, + FillExtrusionPatternProgram::layoutUniformValues( + tile.translatedClipMatrix( + evaluated.get(), + evaluated.get(), + parameters.state + ), + tile.getIconAtlasTexture().size, + crossfade, + tile.id, + parameters.state, + evaluated.get(), + static_cast(-std::pow(2, tile.id.canonical.z) / util::tileSize_D / 8.0), + parameters.pixelRatio, + parameters.evaluatedLight, + evaluated.get() + ), + patternPosA, + patternPosB, + FillExtrusionPatternProgram::TextureBindings{ + textures::image::Value{ + tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear}, + }, + name + ); + } + }; // Draw transparent buildings in two passes so that only the closest surface is drawn. // First draw all the extrusions into only the depth buffer. No colors are drawn. @@ -229,20 +233,21 @@ void RenderFillExtrusionLayer::render(PaintParameters& parameters) { } } -bool RenderFillExtrusionLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float, - const TransformState& transformState, - const float pixelsToTileUnits, const mat4&, - const FeatureState&) const { +bool RenderFillExtrusionLayer:: + queryIntersectsFeature(const GeometryCoordinates& queryGeometry, const GeometryTileFeature& feature, const float, const TransformState& transformState, const float pixelsToTileUnits, const mat4&, const FeatureState&) + const { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry( - queryGeometry, - evaluated.get(), - evaluated.get(), - static_cast(transformState.getBearing()), - pixelsToTileUnits); - - return util::polygonIntersectsMultiPolygon(translatedQueryGeometry.value_or(queryGeometry), feature.getGeometries()); + queryGeometry, + evaluated.get(), + evaluated.get(), + static_cast(transformState.getBearing()), + pixelsToTileUnits + ); + + return util::polygonIntersectsMultiPolygon( + translatedQueryGeometry.value_or(queryGeometry), feature.getGeometries() + ); } } // namespace mbgl diff --git a/src/mbgl/renderer/layers/render_fill_extrusion_layer.hpp b/src/mbgl/renderer/layers/render_fill_extrusion_layer.hpp index 62fbac0c9da..0c4380eb439 100644 --- a/src/mbgl/renderer/layers/render_fill_extrusion_layer.hpp +++ b/src/mbgl/renderer/layers/render_fill_extrusion_layer.hpp @@ -23,13 +23,9 @@ class RenderFillExtrusionLayer final : public RenderLayer { bool is3D() const override; void render(PaintParameters&) override; - bool queryIntersectsFeature(const GeometryCoordinates&, - const GeometryTileFeature&, - float, - const TransformState&, - float, - const mat4&, - const FeatureState&) const override; + bool + queryIntersectsFeature(const GeometryCoordinates&, const GeometryTileFeature&, float, const TransformState&, float, const mat4&, const FeatureState&) + const override; // Paint properties style::FillExtrusionPaintProperties::Unevaluated unevaluated; diff --git a/src/mbgl/renderer/layers/render_fill_layer.cpp b/src/mbgl/renderer/layers/render_fill_layer.cpp index c3baae8bd59..4ddcb442e99 100644 --- a/src/mbgl/renderer/layers/render_fill_layer.cpp +++ b/src/mbgl/renderer/layers/render_fill_layer.cpp @@ -45,7 +45,8 @@ void RenderFillLayer::evaluate(const PropertyEvaluationParameters& parameters) { auto properties = makeMutable( staticImmutableCast(baseImpl), parameters.getCrossfadeParameters(), - unevaluated.evaluate(parameters)); + unevaluated.evaluate(parameters) + ); auto& evaluated = properties->evaluated; if (unevaluated.get().isUndefined()) { @@ -54,9 +55,9 @@ void RenderFillLayer::evaluate(const PropertyEvaluationParameters& parameters) { passes = RenderPass::Translucent; - if (!(!unevaluated.get().isUndefined() - || evaluated.get().constantOr(Color()).a < 1.0f - || evaluated.get().constantOr(0) < 1.0f)) { + if (!(!unevaluated.get().isUndefined() || + evaluated.get().constantOr(Color()).a < 1.0f || + evaluated.get().constantOr(0) < 1.0f)) { // Supply both - evaluated based on opaquePassCutoff in render(). passes |= RenderPass::Opaque; } @@ -90,73 +91,79 @@ void RenderFillLayer::render(PaintParameters& parameters) { auto& bucket = static_cast(*renderData->bucket); const auto& evaluated = getEvaluated(renderData->layerProperties); - auto draw = [&] (auto& programInstance, - const auto& drawMode, - const auto& depthMode, - const auto& indexBuffer, - const auto& segments, - auto&& textureBindings) { + auto draw = [&](auto& programInstance, + const auto& drawMode, + const auto& depthMode, + const auto& indexBuffer, + const auto& segments, + auto&& textureBindings) { const auto& paintPropertyBinders = bucket.paintPropertyBinders.at(getID()); const auto allUniformValues = programInstance.computeAllUniformValues( - FillProgram::LayoutUniformValues { - uniforms::matrix::Value( - tile.translatedMatrix(evaluated.get(), - evaluated.get(), - parameters.state) - ), - uniforms::world::Value( parameters.backend.getDefaultRenderable().getSize() ), + FillProgram::LayoutUniformValues{ + uniforms::matrix::Value(tile.translatedMatrix( + evaluated.get(), evaluated.get(), parameters.state + )), + uniforms::world::Value(parameters.backend.getDefaultRenderable().getSize()), }, paintPropertyBinders, evaluated, static_cast(parameters.state.getZoom()) ); const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *bucket.vertexBuffer, - paintPropertyBinders, - evaluated + *bucket.vertexBuffer, paintPropertyBinders, evaluated ); checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); - programInstance.draw(parameters.context, - *parameters.renderPass, - drawMode, - depthMode, - parameters.stencilModeForClipping(tile.id), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - indexBuffer, - segments, - allUniformValues, - allAttributeBindings, - std::forward(textureBindings), - getID()); + programInstance.draw( + parameters.context, + *parameters.renderPass, + drawMode, + depthMode, + parameters.stencilModeForClipping(tile.id), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + indexBuffer, + segments, + allUniformValues, + allAttributeBindings, + std::forward(textureBindings), + getID() + ); }; - auto fillRenderPass = (evaluated.get().constantOr(Color()).a >= 1.0f - && evaluated.get().constantOr(0) >= 1.0f - && parameters.currentLayer >= parameters.opaquePassCutoff) ? RenderPass::Opaque : RenderPass::Translucent; + auto fillRenderPass = (evaluated.get().constantOr(Color()).a >= 1.0f && + evaluated.get().constantOr(0) >= 1.0f && + parameters.currentLayer >= parameters.opaquePassCutoff) + ? RenderPass::Opaque + : RenderPass::Translucent; if (bucket.triangleIndexBuffer && parameters.pass == fillRenderPass) { - draw(*fillProgram, - gfx::Triangles(), - parameters.depthModeForSublayer(1, parameters.pass == RenderPass::Opaque - ? gfx::DepthMaskType::ReadWrite - : gfx::DepthMaskType::ReadOnly), - *bucket.triangleIndexBuffer, - bucket.triangleSegments, - FillProgram::TextureBindings{}); + draw( + *fillProgram, + gfx::Triangles(), + parameters.depthModeForSublayer( + 1, + parameters.pass == RenderPass::Opaque ? gfx::DepthMaskType::ReadWrite + : gfx::DepthMaskType::ReadOnly + ), + *bucket.triangleIndexBuffer, + bucket.triangleSegments, + FillProgram::TextureBindings{} + ); } if (evaluated.get() && parameters.pass == RenderPass::Translucent) { - draw(*fillOutlineProgram, - gfx::Lines{ 2.0f }, - parameters.depthModeForSublayer( - unevaluated.get().isUndefined() ? 2 : 0, - gfx::DepthMaskType::ReadOnly), - *bucket.lineIndexBuffer, - bucket.lineSegments, - FillOutlineProgram::TextureBindings{}); + draw( + *fillOutlineProgram, + gfx::Lines{2.0f}, + parameters.depthModeForSublayer( + unevaluated.get().isUndefined() ? 2 : 0, gfx::DepthMaskType::ReadOnly + ), + *bucket.lineIndexBuffer, + bucket.lineSegments, + FillOutlineProgram::TextureBindings{} + ); } } } else { @@ -179,20 +186,20 @@ void RenderFillLayer::render(PaintParameters& parameters) { std::optional patternPosA = tile.getPattern(fillPatternValue.from.id()); std::optional patternPosB = tile.getPattern(fillPatternValue.to.id()); - auto draw = [&] (auto& programInstance, - const auto& drawMode, - const auto& depthMode, - const auto& indexBuffer, - const auto& segments, - auto&& textureBindings) { + auto draw = [&](auto& programInstance, + const auto& drawMode, + const auto& depthMode, + const auto& indexBuffer, + const auto& segments, + auto&& textureBindings) { const auto& paintPropertyBinders = bucket.paintPropertyBinders.at(getID()); paintPropertyBinders.setPatternParameters(patternPosA, patternPosB, crossfade); const auto allUniformValues = programInstance.computeAllUniformValues( FillPatternProgram::layoutUniformValues( - tile.translatedMatrix(evaluated.get(), - evaluated.get(), - parameters.state), + tile.translatedMatrix( + evaluated.get(), evaluated.get(), parameters.state + ), parameters.backend.getDefaultRenderable().getSize(), tile.getIconAtlasTexture().size, crossfade, @@ -205,65 +212,73 @@ void RenderFillLayer::render(PaintParameters& parameters) { static_cast(parameters.state.getZoom()) ); const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *bucket.vertexBuffer, - paintPropertyBinders, - evaluated + *bucket.vertexBuffer, paintPropertyBinders, evaluated ); checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); - programInstance.draw(parameters.context, - *parameters.renderPass, - drawMode, - depthMode, - parameters.stencilModeForClipping(tile.id), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - indexBuffer, - segments, - allUniformValues, - allAttributeBindings, - std::forward(textureBindings), - getID()); + programInstance.draw( + parameters.context, + *parameters.renderPass, + drawMode, + depthMode, + parameters.stencilModeForClipping(tile.id), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + indexBuffer, + segments, + allUniformValues, + allAttributeBindings, + std::forward(textureBindings), + getID() + ); }; if (bucket.triangleIndexBuffer) { - draw(*fillPatternProgram, - gfx::Triangles(), - parameters.depthModeForSublayer(1, gfx::DepthMaskType::ReadWrite), - *bucket.triangleIndexBuffer, - bucket.triangleSegments, - FillPatternProgram::TextureBindings{ - textures::image::Value{ tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear }, - }); + draw( + *fillPatternProgram, + gfx::Triangles(), + parameters.depthModeForSublayer(1, gfx::DepthMaskType::ReadWrite), + *bucket.triangleIndexBuffer, + bucket.triangleSegments, + FillPatternProgram::TextureBindings{ + textures::image::Value{ + tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear}, + } + ); } if (evaluated.get() && unevaluated.get().isUndefined()) { - draw(*fillOutlinePatternProgram, - gfx::Lines { 2.0f }, - parameters.depthModeForSublayer(2, gfx::DepthMaskType::ReadOnly), - *bucket.lineIndexBuffer, - bucket.lineSegments, - FillOutlinePatternProgram::TextureBindings{ - textures::image::Value{ tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear }, - }); + draw( + *fillOutlinePatternProgram, + gfx::Lines{2.0f}, + parameters.depthModeForSublayer(2, gfx::DepthMaskType::ReadOnly), + *bucket.lineIndexBuffer, + bucket.lineSegments, + FillOutlinePatternProgram::TextureBindings{ + textures::image::Value{ + tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear}, + } + ); } } } } -bool RenderFillLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float, - const TransformState& transformState, const float pixelsToTileUnits, - const mat4&, const FeatureState&) const { +bool RenderFillLayer:: + queryIntersectsFeature(const GeometryCoordinates& queryGeometry, const GeometryTileFeature& feature, const float, const TransformState& transformState, const float pixelsToTileUnits, const mat4&, const FeatureState&) + const { const auto& evaluated = getEvaluated(evaluatedProperties); auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry( - queryGeometry, - evaluated.get(), - evaluated.get(), - static_cast(transformState.getBearing()), - pixelsToTileUnits); - - return util::polygonIntersectsMultiPolygon(translatedQueryGeometry.value_or(queryGeometry), feature.getGeometries()); + queryGeometry, + evaluated.get(), + evaluated.get(), + static_cast(transformState.getBearing()), + pixelsToTileUnits + ); + + return util::polygonIntersectsMultiPolygon( + translatedQueryGeometry.value_or(queryGeometry), feature.getGeometries() + ); } } // namespace mbgl diff --git a/src/mbgl/renderer/layers/render_fill_layer.hpp b/src/mbgl/renderer/layers/render_fill_layer.hpp index 864500b0950..ba92f3afdcb 100644 --- a/src/mbgl/renderer/layers/render_fill_layer.hpp +++ b/src/mbgl/renderer/layers/render_fill_layer.hpp @@ -25,13 +25,9 @@ class RenderFillLayer final : public RenderLayer { bool hasCrossfade() const override; void render(PaintParameters&) override; - bool queryIntersectsFeature(const GeometryCoordinates&, - const GeometryTileFeature&, - float, - const TransformState&, - float, - const mat4&, - const FeatureState&) const override; + bool + queryIntersectsFeature(const GeometryCoordinates&, const GeometryTileFeature&, float, const TransformState&, float, const mat4&, const FeatureState&) + const override; // Paint properties style::FillPaintProperties::Unevaluated unevaluated; diff --git a/src/mbgl/renderer/layers/render_heatmap_layer.cpp b/src/mbgl/renderer/layers/render_heatmap_layer.cpp index b652991d1e4..a2870c0d56b 100644 --- a/src/mbgl/renderer/layers/render_heatmap_layer.cpp +++ b/src/mbgl/renderer/layers/render_heatmap_layer.cpp @@ -41,12 +41,11 @@ void RenderHeatmapLayer::transition(const TransitionParameters& parameters) { void RenderHeatmapLayer::evaluate(const PropertyEvaluationParameters& parameters) { auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); + staticImmutableCast(baseImpl), unevaluated.evaluate(parameters) + ); - passes = (properties->evaluated.get() > 0) - ? (RenderPass::Translucent | RenderPass::Pass3D) - : RenderPass::None; + passes = (properties->evaluated.get() > 0) ? (RenderPass::Translucent | RenderPass::Pass3D) + : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -61,8 +60,7 @@ bool RenderHeatmapLayer::hasCrossfade() const { void RenderHeatmapLayer::upload(gfx::UploadPass& uploadPass) { if (!colorRampTexture) { - colorRampTexture = - uploadPass.createTexture(colorRamp, gfx::TextureChannelDataType::UnsignedByte); + colorRampTexture = uploadPass.createTexture(colorRamp, gfx::TextureChannelDataType::UnsignedByte); } } @@ -86,7 +84,8 @@ void RenderHeatmapLayer::render(PaintParameters& parameters) { } auto renderPass = parameters.encoder->createRenderPass( - "heatmap texture", { *renderTexture, Color{ 0.0f, 0.0f, 0.0f, 1.0f }, {}, {} }); + "heatmap texture", {*renderTexture, Color{0.0f, 0.0f, 0.0f, 1.0f}, {}, {}} + ); for (const RenderTile& tile : *renderTiles) { const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); @@ -107,25 +106,29 @@ void RenderHeatmapLayer::render(PaintParameters& parameters) { uniforms::heatmap::extrude_scale::Value(extrudeScale)}, paintPropertyBinders, evaluated, - static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = - HeatmapProgram::computeAllAttributeBindings(*bucket.vertexBuffer, paintPropertyBinders, evaluated); + static_cast(parameters.state.getZoom()) + ); + const auto allAttributeBindings = HeatmapProgram::computeAllAttributeBindings( + *bucket.vertexBuffer, paintPropertyBinders, evaluated + ); checkRenderability(parameters, HeatmapProgram::activeBindingCount(allAttributeBindings)); - heatmapProgram->draw(parameters.context, - *renderPass, - gfx::Triangles(), - gfx::DepthMode::disabled(), - gfx::StencilMode::disabled(), - gfx::ColorMode::additive(), - gfx::CullFaceMode::disabled(), - *bucket.indexBuffer, - bucket.segments, - allUniformValues, - allAttributeBindings, - HeatmapProgram::TextureBindings{}, - getID()); + heatmapProgram->draw( + parameters.context, + *renderPass, + gfx::Triangles(), + gfx::DepthMode::disabled(), + gfx::StencilMode::disabled(), + gfx::ColorMode::additive(), + gfx::CullFaceMode::disabled(), + *bucket.indexBuffer, + bucket.segments, + allUniformValues, + allAttributeBindings, + HeatmapProgram::TextureBindings{}, + getID() + ); } } else if (parameters.pass == RenderPass::Translucent) { @@ -135,19 +138,21 @@ void RenderHeatmapLayer::render(PaintParameters& parameters) { matrix::ortho(viewportMat, 0, size.width, size.height, 0, 0, 1); const Properties<>::PossiblyEvaluated properties; - const HeatmapTextureProgram::Binders paintAttributeData{ properties, 0 }; + const HeatmapTextureProgram::Binders paintAttributeData{properties, 0}; const auto allUniformValues = HeatmapTextureProgram::computeAllUniformValues( HeatmapTextureProgram::LayoutUniformValues{ uniforms::matrix::Value(viewportMat), uniforms::world::Value(size), - uniforms::opacity::Value( - getEvaluated(evaluatedProperties).get())}, + uniforms::opacity::Value(getEvaluated(evaluatedProperties).get() + )}, paintAttributeData, properties, - static_cast(parameters.state.getZoom())); + static_cast(parameters.state.getZoom()) + ); const auto allAttributeBindings = HeatmapTextureProgram::computeAllAttributeBindings( - *parameters.staticData.heatmapTextureVertexBuffer, paintAttributeData, properties); + *parameters.staticData.heatmapTextureVertexBuffer, paintAttributeData, properties + ); checkRenderability(parameters, HeatmapTextureProgram::activeBindingCount(allAttributeBindings)); @@ -171,7 +176,8 @@ void RenderHeatmapLayer::render(PaintParameters& parameters) { textures::image::Value{renderTexture->getTexture().getResource(), gfx::TextureFilterType::Linear}, textures::color_ramp::Value{colorRampTexture->getResource(), gfx::TextureFilterType::Linear}, }, - getID()); + getID() + ); } } @@ -196,14 +202,13 @@ void RenderHeatmapLayer::updateColorRamp() { } } -bool RenderHeatmapLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float zoom, - const TransformState&, const float pixelsToTileUnits, const mat4&, - const FeatureState&) const { - (void) queryGeometry; - (void) feature; - (void) zoom; - (void) pixelsToTileUnits; +bool RenderHeatmapLayer:: + queryIntersectsFeature(const GeometryCoordinates& queryGeometry, const GeometryTileFeature& feature, const float zoom, const TransformState&, const float pixelsToTileUnits, const mat4&, const FeatureState&) + const { + (void)queryGeometry; + (void)feature; + (void)zoom; + (void)pixelsToTileUnits; return false; } diff --git a/src/mbgl/renderer/layers/render_heatmap_layer.hpp b/src/mbgl/renderer/layers/render_heatmap_layer.hpp index 94be5c5dab4..c5ba0246796 100644 --- a/src/mbgl/renderer/layers/render_heatmap_layer.hpp +++ b/src/mbgl/renderer/layers/render_heatmap_layer.hpp @@ -24,13 +24,9 @@ class RenderHeatmapLayer final : public RenderLayer { void upload(gfx::UploadPass&) override; void render(PaintParameters&) override; - bool queryIntersectsFeature(const GeometryCoordinates&, - const GeometryTileFeature&, - float, - const TransformState&, - float, - const mat4&, - const FeatureState&) const override; + bool + queryIntersectsFeature(const GeometryCoordinates&, const GeometryTileFeature&, float, const TransformState&, float, const mat4&, const FeatureState&) + const override; void updateColorRamp(); // Paint properties diff --git a/src/mbgl/renderer/layers/render_hillshade_layer.cpp b/src/mbgl/renderer/layers/render_hillshade_layer.cpp index 6f925005c82..c1dee8a6d71 100644 --- a/src/mbgl/renderer/layers/render_hillshade_layer.cpp +++ b/src/mbgl/renderer/layers/render_hillshade_layer.cpp @@ -43,7 +43,8 @@ std::array RenderHillshadeLayer::getLatRange(const UnwrappedTileID& id std::array RenderHillshadeLayer::getLight(const PaintParameters& parameters) { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; float azimuthal = util::deg2radf(evaluated.get()); - if (evaluated.get() == HillshadeIlluminationAnchorType::Viewport) azimuthal = azimuthal - static_cast(parameters.state.getBearing()); + if (evaluated.get() == HillshadeIlluminationAnchorType::Viewport) + azimuthal = azimuthal - static_cast(parameters.state.getBearing()); return {{evaluated.get(), azimuthal}}; } @@ -53,9 +54,9 @@ void RenderHillshadeLayer::transition(const TransitionParameters& parameters) { void RenderHillshadeLayer::evaluate(const PropertyEvaluationParameters& parameters) { auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); - passes = (properties->evaluated.get() > 0) + staticImmutableCast(baseImpl), unevaluated.evaluate(parameters) + ); + passes = (properties->evaluated.get() > 0) ? (RenderPass::Translucent | RenderPass::Pass3D) : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); @@ -77,20 +78,19 @@ void RenderHillshadeLayer::prepare(const LayerPrepareParameters& params) { void RenderHillshadeLayer::render(PaintParameters& parameters) { assert(renderTiles); - if (parameters.pass != RenderPass::Translucent && parameters.pass != RenderPass::Pass3D) - return; + if (parameters.pass != RenderPass::Translucent && parameters.pass != RenderPass::Pass3D) return; if (!parameters.shaders.populate(hillshadeProgram)) return; if (!parameters.shaders.populate(hillshadePrepareProgram)) return; - const auto& evaluated = static_cast(*evaluatedProperties).evaluated; - auto draw = [&] (const mat4& matrix, - const auto& vertexBuffer, - const auto& indexBuffer, - const auto& segments, - const UnwrappedTileID& id, - const auto& textureBindings) { - const HillshadeProgram::Binders paintAttributeData{ evaluated, 0 }; + const auto& evaluated = static_cast(*evaluatedProperties).evaluated; + auto draw = [&](const mat4& matrix, + const auto& vertexBuffer, + const auto& indexBuffer, + const auto& segments, + const UnwrappedTileID& id, + const auto& textureBindings) { + const HillshadeProgram::Binders paintAttributeData{evaluated, 0}; const auto allUniformValues = HillshadeProgram::computeAllUniformValues( HillshadeProgram::LayoutUniformValues{ @@ -103,25 +103,29 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { }, paintAttributeData, evaluated, - static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = - HillshadeProgram::computeAllAttributeBindings(vertexBuffer, paintAttributeData, evaluated); + static_cast(parameters.state.getZoom()) + ); + const auto allAttributeBindings = HillshadeProgram::computeAllAttributeBindings( + vertexBuffer, paintAttributeData, evaluated + ); checkRenderability(parameters, HillshadeProgram::activeBindingCount(allAttributeBindings)); - hillshadeProgram->draw(parameters.context, - *parameters.renderPass, - gfx::Triangles(), - parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), - gfx::StencilMode::disabled(), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - indexBuffer, - segments, - allUniformValues, - allAttributeBindings, - textureBindings, - getID()); + hillshadeProgram->draw( + parameters.context, + *parameters.renderPass, + gfx::Triangles(), + parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), + gfx::StencilMode::disabled(), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + indexBuffer, + segments, + allUniformValues, + allAttributeBindings, + textureBindings, + getID() + ); }; mat4 mat; @@ -135,7 +139,7 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { } auto& bucket = static_cast(*bucket_); - if (!bucket.hasData()){ + if (!bucket.hasData()) { continue; } @@ -143,14 +147,16 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { assert(bucket.dem); const uint16_t stride = bucket.getDEMData().stride; const uint16_t tilesize = bucket.getDEMData().dim; - auto view = parameters.context.createOffscreenTexture({tilesize, tilesize}, - gfx::TextureChannelDataType::UnsignedByte); + auto view = parameters.context.createOffscreenTexture( + {tilesize, tilesize}, gfx::TextureChannelDataType::UnsignedByte + ); auto renderPass = parameters.encoder->createRenderPass( - "hillshade prepare", { *view, Color{ 0.0f, 0.0f, 0.0f, 0.0f }, {}, {} }); + "hillshade prepare", {*view, Color{0.0f, 0.0f, 0.0f, 0.0f}, {}, {}} + ); const Properties<>::PossiblyEvaluated properties; - const HillshadePrepareProgram::Binders paintAttributeData{ properties, 0 }; + const HillshadePrepareProgram::Binders paintAttributeData{properties, 0}; const auto allUniformValues = HillshadePrepareProgram::computeAllUniformValues( HillshadePrepareProgram::LayoutUniformValues{ @@ -162,30 +168,34 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { }, paintAttributeData, properties, - static_cast(parameters.state.getZoom())); + static_cast(parameters.state.getZoom()) + ); const auto allAttributeBindings = HillshadePrepareProgram::computeAllAttributeBindings( - *parameters.staticData.rasterVertexBuffer, paintAttributeData, properties); + *parameters.staticData.rasterVertexBuffer, paintAttributeData, properties + ); checkRenderability(parameters, HillshadePrepareProgram::activeBindingCount(allAttributeBindings)); // Copy over the segments so that we can create our own DrawScopes that get destroyed // after this draw call. auto segments = RenderStaticData::rasterSegments(); - hillshadePrepareProgram->draw(parameters.context, - *renderPass, - gfx::Triangles(), - parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), - gfx::StencilMode::disabled(), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - *parameters.staticData.quadTriangleIndexBuffer, - segments, - allUniformValues, - allAttributeBindings, - HillshadePrepareProgram::TextureBindings{ - textures::image::Value{bucket.dem->getResource()}, - }, - "prepare"); + hillshadePrepareProgram->draw( + parameters.context, + *renderPass, + gfx::Triangles(), + parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), + gfx::StencilMode::disabled(), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + *parameters.staticData.quadTriangleIndexBuffer, + segments, + allUniformValues, + allAttributeBindings, + HillshadePrepareProgram::TextureBindings{ + textures::image::Value{bucket.dem->getResource()}, + }, + "prepare" + ); bucket.texture = std::move(view->getTexture()); bucket.setPrepared(true); } else if (parameters.pass == RenderPass::Translucent) { @@ -193,32 +203,34 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { if (bucket.vertexBuffer && bucket.indexBuffer) { // Draw only the parts of the tile that aren't drawn by another tile in the layer. - draw(parameters.matrixForTile(tile.id, true), - *bucket.vertexBuffer, - *bucket.indexBuffer, - bucket.segments, - tile.id, - HillshadeProgram::TextureBindings{ - textures::image::Value{ bucket.texture->getResource(), gfx::TextureFilterType::Linear }, - }); + draw( + parameters.matrixForTile(tile.id, true), + *bucket.vertexBuffer, + *bucket.indexBuffer, + bucket.segments, + tile.id, + HillshadeProgram::TextureBindings{ + textures::image::Value{bucket.texture->getResource(), gfx::TextureFilterType::Linear}, + } + ); } else { // Draw the full tile. if (bucket.segments.empty()) { // Copy over the segments so that we can create our own DrawScopes. bucket.segments = RenderStaticData::rasterSegments(); } - draw(parameters.matrixForTile(tile.id, true), - *parameters.staticData.rasterVertexBuffer, - *parameters.staticData.quadTriangleIndexBuffer, - bucket.segments, - tile.id, - HillshadeProgram::TextureBindings{ - textures::image::Value{bucket.texture->getResource(), gfx::TextureFilterType::Linear}, - }); + draw( + parameters.matrixForTile(tile.id, true), + *parameters.staticData.rasterVertexBuffer, + *parameters.staticData.quadTriangleIndexBuffer, + bucket.segments, + tile.id, + HillshadeProgram::TextureBindings{ + textures::image::Value{bucket.texture->getResource(), gfx::TextureFilterType::Linear}, + } + ); } } - - } } diff --git a/src/mbgl/renderer/layers/render_hillshade_layer.hpp b/src/mbgl/renderer/layers/render_hillshade_layer.hpp index 1f21892c222..97bf807ce86 100644 --- a/src/mbgl/renderer/layers/render_hillshade_layer.hpp +++ b/src/mbgl/renderer/layers/render_hillshade_layer.hpp @@ -10,7 +10,7 @@ namespace mbgl { class HillshadeProgram; class HillshadePrepareProgram; -class RenderHillshadeLayer: public RenderLayer { +class RenderHillshadeLayer : public RenderLayer { public: explicit RenderHillshadeLayer(Immutable); ~RenderHillshadeLayer() override; diff --git a/src/mbgl/renderer/layers/render_line_layer.cpp b/src/mbgl/renderer/layers/render_line_layer.cpp index 8dc72bab92f..ecba15fab91 100644 --- a/src/mbgl/renderer/layers/render_line_layer.cpp +++ b/src/mbgl/renderer/layers/render_line_layer.cpp @@ -46,13 +46,15 @@ void RenderLineLayer::evaluate(const PropertyEvaluationParameters& parameters) { auto properties = makeMutable( staticImmutableCast(baseImpl), parameters.getCrossfadeParameters(), - unevaluated.evaluate(parameters)); + unevaluated.evaluate(parameters) + ); auto& evaluated = properties->evaluated; - passes = (evaluated.get().constantOr(1.0) > 0 - && evaluated.get().constantOr(Color::black()).a > 0 - && evaluated.get().constantOr(1.0) > 0) - ? RenderPass::Translucent : RenderPass::None; + passes = (evaluated.get().constantOr(1.0) > 0 && + evaluated.get().constantOr(Color::black()).a > 0 && + evaluated.get().constantOr(1.0) > 0) + ? RenderPass::Translucent + : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -75,11 +77,12 @@ void RenderLineLayer::prepare(const LayerPrepareParameters& params) { if (evaluated.get().from.empty()) continue; auto& bucket = static_cast(*renderData->bucket); - const LinePatternCap cap = bucket.layout.get() == LineCapType::Round - ? LinePatternCap::Round : LinePatternCap::Square; + const LinePatternCap cap = bucket.layout.get() == LineCapType::Round ? LinePatternCap::Round + : LinePatternCap::Square; // Ensures that the dash data gets added to the atlas. params.lineAtlas.getDashPatternTexture( - evaluated.get().from, evaluated.get().to, cap); + evaluated.get().from, evaluated.get().to, cap + ); } } @@ -114,60 +117,67 @@ void RenderLineLayer::render(PaintParameters& parameters) { auto draw = [&](auto& programInstance, auto&& uniformValues, const std::optional& patternPositionA, - const std::optional& patternPositionB, auto&& textureBindings) { + const std::optional& patternPositionB, + auto&& textureBindings) { const auto& paintPropertyBinders = bucket.paintPropertyBinders.at(getID()); paintPropertyBinders.setPatternParameters(patternPositionA, patternPositionB, crossfade); - const auto allUniformValues = - programInstance.computeAllUniformValues(std::forward(uniformValues), - paintPropertyBinders, - evaluated, - static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *bucket.vertexBuffer, + const auto allUniformValues = programInstance.computeAllUniformValues( + std::forward(uniformValues), paintPropertyBinders, - evaluated + evaluated, + static_cast(parameters.state.getZoom()) + ); + const auto allAttributeBindings = programInstance.computeAllAttributeBindings( + *bucket.vertexBuffer, paintPropertyBinders, evaluated ); checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); - programInstance.draw(parameters.context, - *parameters.renderPass, - gfx::Triangles(), - parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), - parameters.stencilModeForClipping(tile.id), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - *bucket.indexBuffer, - bucket.segments, - allUniformValues, - allAttributeBindings, - std::forward(textureBindings), - getID()); + programInstance.draw( + parameters.context, + *parameters.renderPass, + gfx::Triangles(), + parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), + parameters.stencilModeForClipping(tile.id), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + *bucket.indexBuffer, + bucket.segments, + allUniformValues, + allAttributeBindings, + std::forward(textureBindings), + getID() + ); }; if (!evaluated.get().from.empty()) { - const LinePatternCap cap = - bucket.layout.get() == LineCapType::Round ? LinePatternCap::Round : LinePatternCap::Square; + const LinePatternCap cap = bucket.layout.get() == LineCapType::Round ? LinePatternCap::Round + : LinePatternCap::Square; const auto& dashPatternTexture = parameters.lineAtlas.getDashPatternTexture( - evaluated.get().from, evaluated.get().to, cap); - - draw(*lineSDFProgram, - LineSDFProgram::layoutUniformValues(evaluated, - parameters.pixelRatio, - tile, - parameters.state, - parameters.pixelsToGLUnits, - dashPatternTexture.getFrom(), - dashPatternTexture.getTo(), - crossfade, - static_cast(dashPatternTexture.getSize().width)), - {}, - {}, - LineSDFProgram::TextureBindings{ - dashPatternTexture.textureBinding(), - }); + evaluated.get().from, evaluated.get().to, cap + ); + + draw( + *lineSDFProgram, + LineSDFProgram::layoutUniformValues( + evaluated, + parameters.pixelRatio, + tile, + parameters.state, + parameters.pixelsToGLUnits, + dashPatternTexture.getFrom(), + dashPatternTexture.getTo(), + crossfade, + static_cast(dashPatternTexture.getSize().width) + ), + {}, + {}, + LineSDFProgram::TextureBindings{ + dashPatternTexture.textureBinding(), + } + ); } else if (!unevaluated.get().isUndefined()) { const auto& linePatternValue = evaluated.get().constantOr(Faded{"", ""}); @@ -176,46 +186,47 @@ void RenderLineLayer::render(PaintParameters& parameters) { std::optional posA = tile.getPattern(linePatternValue.from.id()); std::optional posB = tile.getPattern(linePatternValue.to.id()); - draw(*linePatternProgram, - LinePatternProgram::layoutUniformValues( - evaluated, - tile, - parameters.state, - parameters.pixelsToGLUnits, - parameters.pixelRatio, - texsize, - crossfade), - posA, - posB, - LinePatternProgram::TextureBindings{ - textures::image::Value{ tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear }, - }); - } else if (!unevaluated.get().getValue().isUndefined()) { - assert(colorRampTexture); - - draw(*lineGradientProgram, - LineGradientProgram::layoutUniformValues( + draw( + *linePatternProgram, + LinePatternProgram::layoutUniformValues( evaluated, tile, parameters.state, parameters.pixelsToGLUnits, - parameters.pixelRatio), - {}, - {}, - LineGradientProgram::TextureBindings{ - textures::image::Value{ colorRampTexture->getResource(), gfx::TextureFilterType::Linear }, - }); + parameters.pixelRatio, + texsize, + crossfade + ), + posA, + posB, + LinePatternProgram::TextureBindings{ + textures::image::Value{tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear}, + } + ); + } else if (!unevaluated.get().getValue().isUndefined()) { + assert(colorRampTexture); + + draw( + *lineGradientProgram, + LineGradientProgram::layoutUniformValues( + evaluated, tile, parameters.state, parameters.pixelsToGLUnits, parameters.pixelRatio + ), + {}, + {}, + LineGradientProgram::TextureBindings{ + textures::image::Value{colorRampTexture->getResource(), gfx::TextureFilterType::Linear}, + } + ); } else { - draw(*lineProgram, - LineProgram::layoutUniformValues( - evaluated, - tile, - parameters.state, - parameters.pixelsToGLUnits, - parameters.pixelRatio), - {}, - {}, - LineProgram::TextureBindings{}); + draw( + *lineProgram, + LineProgram::layoutUniformValues( + evaluated, tile, parameters.state, parameters.pixelsToGLUnits, parameters.pixelRatio + ), + {}, + {}, + LineProgram::TextureBindings{} + ); } } } @@ -238,12 +249,9 @@ GeometryCollection offsetLine(const GeometryCollection& rings, double offset) { for (auto i = ring.begin(); i != ring.end(); ++i) { auto& p = *i; - Point aToB = i == ring.begin() ? - zero : - util::perp(util::unit(convertPoint(p - *(i - 1)))); - Point bToC = i + 1 == ring.end() ? - zero : - util::perp(util::unit(convertPoint(*(i + 1) - p))); + Point aToB = i == ring.begin() ? zero : util::perp(util::unit(convertPoint(p - *(i - 1)))); + Point bToC = i + 1 == ring.end() ? zero + : util::perp(util::unit(convertPoint(*(i + 1) - p))); Point extrude = util::unit(aToB + bToC); const double cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y; @@ -258,38 +266,43 @@ GeometryCollection offsetLine(const GeometryCollection& rings, double offset) { } // namespace -bool RenderLineLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float zoom, - const TransformState& transformState, const float pixelsToTileUnits, - const mat4&, const FeatureState& featureState) const { +bool RenderLineLayer::queryIntersectsFeature( + const GeometryCoordinates& queryGeometry, + const GeometryTileFeature& feature, + const float zoom, + const TransformState& transformState, + const float pixelsToTileUnits, + const mat4&, + const FeatureState& featureState +) const { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; // Translate query geometry auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry( - queryGeometry, - evaluated.get(), - evaluated.get(), - static_cast(transformState.getBearing()), - pixelsToTileUnits); + queryGeometry, + evaluated.get(), + evaluated.get(), + static_cast(transformState.getBearing()), + pixelsToTileUnits + ); // Evaluate function - auto offset = - evaluated.get().evaluate(feature, zoom, featureState, style::LineOffset::defaultValue()) * - pixelsToTileUnits; + auto offset = evaluated.get().evaluate( + feature, zoom, featureState, style::LineOffset::defaultValue() + ) * + pixelsToTileUnits; // Test intersection const auto halfWidth = static_cast(getLineWidth(feature, zoom, featureState) / 2.0 * pixelsToTileUnits); // Apply offset to geometry if (offset != 0.0f && !feature.getGeometries().empty()) { return util::polygonIntersectsBufferedMultiLine( - translatedQueryGeometry.value_or(queryGeometry), - offsetLine(feature.getGeometries(), offset), - halfWidth); + translatedQueryGeometry.value_or(queryGeometry), offsetLine(feature.getGeometries(), offset), halfWidth + ); } return util::polygonIntersectsBufferedMultiLine( - translatedQueryGeometry.value_or(queryGeometry), - feature.getGeometries(), - halfWidth); + translatedQueryGeometry.value_or(queryGeometry), feature.getGeometries(), halfWidth + ); } void RenderLineLayer::updateColorRamp() { @@ -313,13 +326,16 @@ void RenderLineLayer::updateColorRamp() { } } -float RenderLineLayer::getLineWidth(const GeometryTileFeature& feature, const float zoom, - const FeatureState& featureState) const { +float RenderLineLayer::getLineWidth( + const GeometryTileFeature& feature, const float zoom, const FeatureState& featureState +) const { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; - float lineWidth = - evaluated.get().evaluate(feature, zoom, featureState, style::LineWidth::defaultValue()); - float gapWidth = - evaluated.get().evaluate(feature, zoom, featureState, style::LineGapWidth::defaultValue()); + float lineWidth = evaluated.get().evaluate( + feature, zoom, featureState, style::LineWidth::defaultValue() + ); + float gapWidth = evaluated.get().evaluate( + feature, zoom, featureState, style::LineGapWidth::defaultValue() + ); if (gapWidth) { return gapWidth + 2 * lineWidth; } else { diff --git a/src/mbgl/renderer/layers/render_line_layer.hpp b/src/mbgl/renderer/layers/render_line_layer.hpp index 88f794f0f73..ad1dc5acc53 100644 --- a/src/mbgl/renderer/layers/render_line_layer.hpp +++ b/src/mbgl/renderer/layers/render_line_layer.hpp @@ -29,13 +29,9 @@ class RenderLineLayer final : public RenderLayer { void upload(gfx::UploadPass&) override; void render(PaintParameters&) override; - bool queryIntersectsFeature(const GeometryCoordinates&, - const GeometryTileFeature&, - float, - const TransformState&, - float, - const mat4&, - const FeatureState&) const override; + bool + queryIntersectsFeature(const GeometryCoordinates&, const GeometryTileFeature&, float, const TransformState&, float, const mat4&, const FeatureState&) + const override; // Paint properties style::LinePaintProperties::Unevaluated unevaluated; diff --git a/src/mbgl/renderer/layers/render_location_indicator_layer.cpp b/src/mbgl/renderer/layers/render_location_indicator_layer.cpp index 14b55c63b23..4abed6f4e55 100644 --- a/src/mbgl/renderer/layers/render_location_indicator_layer.cpp +++ b/src/mbgl/renderer/layers/render_location_indicator_layer.cpp @@ -40,7 +40,8 @@ namespace mbgl { struct LocationIndicatorRenderParameters { LocationIndicatorRenderParameters() = default; - explicit LocationIndicatorRenderParameters(const TransformParameters& tp) : state(&tp.state) {} + explicit LocationIndicatorRenderParameters(const TransformParameters& tp) + : state(&tp.state) {} LocationIndicatorRenderParameters(const LocationIndicatorRenderParameters& o) = default; LocationIndicatorRenderParameters& operator=(const LocationIndicatorRenderParameters& o) = default; @@ -76,9 +77,13 @@ class RenderLocationIndicatorImpl { GLfloat x = 0.0f; GLfloat y = 0.0f; - vec2(GLfloat x_, GLfloat y_) : x(x_), y(y_) {} + vec2(GLfloat x_, GLfloat y_) + : x(x_), + y(y_) {} vec2() = default; - explicit vec2(const Point& p) : x(static_cast(p.x)), y(static_cast(p.y)) {} + explicit vec2(const Point& p) + : x(static_cast(p.x)), + y(static_cast(p.y)) {} vec2(const vec2& o) = default; vec2(vec2&& o) = default; vec2& operator=(vec2&& o) = default; @@ -103,7 +108,9 @@ class RenderLocationIndicatorImpl { const vec2 norm = normalized(); // From theta to bearing - return util::rad2degf(util::wrap(static_cast(M_PI_2) - std::atan2(-norm.y, norm.x), 0.0f, static_cast(M_PI * 2.0))); + return util::rad2degf(util::wrap( + static_cast(M_PI_2) - std::atan2(-norm.y, norm.x), 0.0f, static_cast(M_PI * 2.0) + )); } Point toPoint() const { return {x, y}; } @@ -308,15 +315,17 @@ void main() { if (!sharedImage || !image || !image->valid()) { MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr)); } else { - MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, - 0, - GL_RGBA, - image->size.width, - image->size.height, - 0, - GL_RGBA, - GL_UNSIGNED_BYTE, - image->data.get())); + MBGL_CHECK_ERROR(glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA, + image->size.width, + image->size.height, + 0, + GL_RGBA, + GL_UNSIGNED_BYTE, + image->data.get() + )); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); @@ -376,10 +385,11 @@ void main() { if (hasAnisotropicFiltering()) anisotropicFilteringAvailable = true; simpleShader.initialize(); texturedShader.initialize(); - texCoords = {{{0.0f, 1.0f}, - {0.0f, 0.0f}, - {1.0f, 0.0f}, - {1.0f, 1.0f}}}; // Quads will be drawn as triangle fans. so bl, tl, tr, br + texCoords = { + {{0.0f, 1.0f}, + {0.0f, 0.0f}, + {1.0f, 0.0f}, + {1.0f, 1.0f}}}; // Quads will be drawn as triangle fans. so bl, tl, tr, br texCoordsBuffer.upload(texCoords); } @@ -407,8 +417,9 @@ void main() { if (params.projectionMatrix != oldParams.projectionMatrix) positionChanged = true; if (params.puckPosition != oldParams.puckPosition) { positionChanged = true; - ruler = mapbox::cheap_ruler::CheapRuler(params.puckPosition.latitude(), - mapbox::cheap_ruler::CheapRuler::Meters); + ruler = mapbox::cheap_ruler::CheapRuler( + params.puckPosition.latitude(), mapbox::cheap_ruler::CheapRuler::Meters + ); } else if (params.puckBearing != oldParams.puckBearing || params.puckLayersDisplacement != oldParams.puckLayersDisplacement || params.perspectiveCompensation != oldParams.perspectiveCompensation || @@ -448,8 +459,8 @@ void main() { featureEnvelope->clear(); if (!texPuck || !texPuck->isValid()) return; - feature->geometry = - mapbox::geometry::point{oldParams.puckPosition.latitude(), oldParams.puckPosition.longitude()}; + feature->geometry = mapbox::geometry::point{ + oldParams.puckPosition.latitude(), oldParams.puckPosition.longitude()}; mapbox::geometry::linear_ring border; for (const auto& v : puckGeometry) { vec4 p{{v.x, v.y, 0, 1}}; @@ -484,7 +495,8 @@ void main() { void updateRadius(const mbgl::LocationIndicatorRenderParameters& params) { const TransformState& s = *params.state; const auto numVtxCircumference = static_cast(circle.size() - 1); - const float bearingStep = 360.0f / static_cast(numVtxCircumference - 1); // first and last points are the same + const float bearingStep = 360.0f / + static_cast(numVtxCircumference - 1); // first and last points are the same const mapbox::cheap_ruler::point centerPoint(params.puckPosition.longitude(), params.puckPosition.latitude()); Point center = project(params.puckPosition, s); circle[0] = {0, 0}; @@ -529,8 +541,9 @@ void main() { return res.normalized(); } - static Point hatShadowShiftVector(const LatLng& position, - const mbgl::LocationIndicatorRenderParameters& params) { + static Point hatShadowShiftVector( + const LatLng& position, const mbgl::LocationIndicatorRenderParameters& params + ) { const TransformState& s = *params.state; ScreenCoordinate posScreen = latLngToScreenCoordinate(position, s); posScreen.y = params.height - 1; // moving it to bottom @@ -597,8 +610,7 @@ void main() { for (unsigned long i = 0; i < 4; ++i) { const auto b = util::wrap(static_cast(params.puckBearing) + bearings[i], 0.0f, 360.0f); - const Point cornerDirection{std::sin(util::deg2rad(b)), - -std::cos(util::deg2rad(b))}; + const Point cornerDirection{std::sin(util::deg2rad(b)), -std::cos(util::deg2rad(b))}; Point shadowOffset = cornerDirection * shadowRadius; Point puckOffset = cornerDirection * puckRadius; @@ -658,23 +670,31 @@ void main() { texturedShader.detach(); } - void drawShadow() { drawQuad(shadowBuffer, shadowGeometry, texShadow); } + void drawShadow() { + drawQuad(shadowBuffer, shadowGeometry, texShadow); + } - void drawPuck() { drawQuad(puckBuffer, puckGeometry, texPuck); } + void drawPuck() { + drawQuad(puckBuffer, puckGeometry, texPuck); + } - void drawHat() { drawQuad(hatBuffer, hatGeometry, texPuckHat); } + void drawHat() { + drawQuad(hatBuffer, hatGeometry, texPuckHat); + } - static LatLng screenCoordinateToLatLng(const ScreenCoordinate& p, - const TransformState& s, - LatLng::WrapMode wrapMode = LatLng::Wrapped) { + static LatLng screenCoordinateToLatLng( + const ScreenCoordinate& p, const TransformState& s, LatLng::WrapMode wrapMode = LatLng::Wrapped + ) { ScreenCoordinate flippedPoint = p; flippedPoint.y = s.getSize().height - flippedPoint.y; return s.screenCoordinateToLatLng(flippedPoint, wrapMode); } - bool setTextureFromImageID(const std::string& imagePath, - std::shared_ptr& texture, - const mbgl::LocationIndicatorRenderParameters& params) { + bool setTextureFromImageID( + const std::string& imagePath, + std::shared_ptr& texture, + const mbgl::LocationIndicatorRenderParameters& params + ) { bool updated = false; if (textures.find(imagePath) == textures.end()) { std::shared_ptr tx = std::make_shared(); @@ -765,7 +785,8 @@ void RenderLocationIndicatorLayer::transition(const TransitionParameters& parame void RenderLocationIndicatorLayer::evaluate(const PropertyEvaluationParameters& parameters) { passes = RenderPass::Translucent; auto properties = makeMutable( - staticImmutableCast(baseImpl), unevaluated.evaluate(parameters)); + staticImmutableCast(baseImpl), unevaluated.evaluate(parameters) + ); const auto& evaluated = properties->evaluated; auto& layout = impl(baseImpl).layout; diff --git a/src/mbgl/renderer/layers/render_raster_layer.cpp b/src/mbgl/renderer/layers/render_raster_layer.cpp index 4aeff8f136b..9492e0f3698 100644 --- a/src/mbgl/renderer/layers/render_raster_layer.cpp +++ b/src/mbgl/renderer/layers/render_raster_layer.cpp @@ -36,8 +36,8 @@ void RenderRasterLayer::transition(const TransitionParameters& parameters) { void RenderRasterLayer::evaluate(const PropertyEvaluationParameters& parameters) { auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); + staticImmutableCast(baseImpl), unevaluated.evaluate(parameters) + ); passes = properties->evaluated.get() > 0 ? RenderPass::Translucent : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); @@ -71,11 +71,8 @@ static std::array spinWeights(float spin) { spin = util::deg2radf(spin); float s = std::sin(spin); float c = std::cos(spin); - std::array spin_weights = {{ - (2 * c + 1) / 3, - (-std::sqrt(3.0f) * s - c + 1) / 3, - (std::sqrt(3.0f) * s - c + 1) / 3 - }}; + std::array spin_weights = { + {(2 * c + 1) / 3, (-std::sqrt(3.0f) * s - c + 1) / 3, (std::sqrt(3.0f) * s - c + 1) / 3}}; return spin_weights; } @@ -94,14 +91,14 @@ void RenderRasterLayer::render(PaintParameters& parameters) { if (!parameters.shaders.populate(rasterProgram)) return; const auto& evaluated = static_cast(*evaluatedProperties).evaluated; - RasterProgram::Binders paintAttributeData{ evaluated, 0 }; - - auto draw = [&] (const mat4& matrix, - const auto& vertexBuffer, - const auto& indexBuffer, - const auto& segments, - const auto& textureBindings, - const std::string& drawScopeID) { + RasterProgram::Binders paintAttributeData{evaluated, 0}; + + auto draw = [&](const mat4& matrix, + const auto& vertexBuffer, + const auto& indexBuffer, + const auto& segments, + const auto& textureBindings, + const std::string& drawScopeID) { const auto allUniformValues = RasterProgram::computeAllUniformValues( RasterProgram::LayoutUniformValues{ uniforms::matrix::Value(matrix), @@ -118,9 +115,11 @@ void RenderRasterLayer::render(PaintParameters& parameters) { }, paintAttributeData, evaluated, - static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = - RasterProgram::computeAllAttributeBindings(vertexBuffer, paintAttributeData, evaluated); + static_cast(parameters.state.getZoom()) + ); + const auto allAttributeBindings = RasterProgram::computeAllAttributeBindings( + vertexBuffer, paintAttributeData, evaluated + ); checkRenderability(parameters, RasterProgram::activeBindingCount(allAttributeBindings)); @@ -141,7 +140,9 @@ void RenderRasterLayer::render(PaintParameters& parameters) { ); }; - const gfx::TextureFilterType filter = evaluated.get() == RasterResamplingType::Nearest ? gfx::TextureFilterType::Nearest : gfx::TextureFilterType::Linear; + const gfx::TextureFilterType filter = evaluated.get() == RasterResamplingType::Nearest + ? gfx::TextureFilterType::Nearest + : gfx::TextureFilterType::Linear; if (imageData && !imageData->bucket->needsUpload()) { RasterBucket& bucket = *imageData->bucket; @@ -149,15 +150,17 @@ void RenderRasterLayer::render(PaintParameters& parameters) { size_t i = 0; for (const auto& matrix_ : imageData->matrices) { - draw(matrix_, - *bucket.vertexBuffer, - *bucket.indexBuffer, - bucket.segments, - RasterProgram::TextureBindings{ - textures::image0::Value{bucket.texture->getResource(), filter}, - textures::image1::Value{bucket.texture->getResource(), filter}, - }, - std::to_string(i++)); + draw( + matrix_, + *bucket.vertexBuffer, + *bucket.indexBuffer, + bucket.segments, + RasterProgram::TextureBindings{ + textures::image0::Value{bucket.texture->getResource(), filter}, + textures::image1::Value{bucket.texture->getResource(), filter}, + }, + std::to_string(i++) + ); } } else if (renderTiles) { for (const RenderTile& tile : *renderTiles) { @@ -167,36 +170,39 @@ void RenderRasterLayer::render(PaintParameters& parameters) { } auto& bucket = static_cast(*bucket_); - if (!bucket.hasData()) - continue; + if (!bucket.hasData()) continue; assert(bucket.texture); if (bucket.vertexBuffer && bucket.indexBuffer) { // Draw only the parts of the tile that aren't drawn by another tile in the layer. - draw(parameters.matrixForTile(tile.id, !parameters.state.isChanging()), - *bucket.vertexBuffer, - *bucket.indexBuffer, - bucket.segments, - RasterProgram::TextureBindings{ - textures::image0::Value{bucket.texture->getResource(), filter}, - textures::image1::Value{bucket.texture->getResource(), filter}, - }, - "image"); + draw( + parameters.matrixForTile(tile.id, !parameters.state.isChanging()), + *bucket.vertexBuffer, + *bucket.indexBuffer, + bucket.segments, + RasterProgram::TextureBindings{ + textures::image0::Value{bucket.texture->getResource(), filter}, + textures::image1::Value{bucket.texture->getResource(), filter}, + }, + "image" + ); } else { // Draw the full tile. if (bucket.segments.empty()) { // Copy over the segments so that we can create our own DrawScopes. bucket.segments = RenderStaticData::rasterSegments(); } - draw(parameters.matrixForTile(tile.id, !parameters.state.isChanging()), - *parameters.staticData.rasterVertexBuffer, - *parameters.staticData.quadTriangleIndexBuffer, - bucket.segments, - RasterProgram::TextureBindings{ - textures::image0::Value{bucket.texture->getResource(), filter}, - textures::image1::Value{bucket.texture->getResource(), filter}, - }, - "image"); + draw( + parameters.matrixForTile(tile.id, !parameters.state.isChanging()), + *parameters.staticData.rasterVertexBuffer, + *parameters.staticData.quadTriangleIndexBuffer, + bucket.segments, + RasterProgram::TextureBindings{ + textures::image0::Value{bucket.texture->getResource(), filter}, + textures::image1::Value{bucket.texture->getResource(), filter}, + }, + "image" + ); } } } diff --git a/src/mbgl/renderer/layers/render_symbol_layer.cpp b/src/mbgl/renderer/layers/render_symbol_layer.cpp index c8af678d64f..71bd6c7fe58 100644 --- a/src/mbgl/renderer/layers/render_symbol_layer.cpp +++ b/src/mbgl/renderer/layers/render_symbol_layer.cpp @@ -27,33 +27,34 @@ namespace mbgl { using namespace style; namespace { -style::SymbolPropertyValues iconPropertyValues(const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_, - const style::SymbolLayoutProperties::PossiblyEvaluated& layout_) { - return style::SymbolPropertyValues { - layout_.get(), - layout_.get(), - layout_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get().constantOr(Color::black()).a > 0 && +style::SymbolPropertyValues iconPropertyValues( + const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_, + const style::SymbolLayoutProperties::PossiblyEvaluated& layout_ +) { + return style::SymbolPropertyValues{ + layout_.get(), + layout_.get(), + layout_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get().constantOr(Color::black()).a > 0 && evaluated_.get().constantOr(1), - evaluated_.get().constantOr(Color::black()).a > 0 - }; + evaluated_.get().constantOr(Color::black()).a > 0}; } - -style::SymbolPropertyValues textPropertyValues(const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_, - const style::SymbolLayoutProperties::PossiblyEvaluated& layout_) { - return style::SymbolPropertyValues { - layout_.get(), - layout_.get(), - layout_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get().constantOr(Color::black()).a > 0 && +style::SymbolPropertyValues textPropertyValues( + const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_, + const style::SymbolLayoutProperties::PossiblyEvaluated& layout_ +) { + return style::SymbolPropertyValues{ + layout_.get(), + layout_.get(), + layout_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get().constantOr(Color::black()).a > 0 && evaluated_.get().constantOr(1), - evaluated_.get().constantOr(Color::black()).a > 0 - }; + evaluated_.get().constantOr(Color::black()).a > 0}; } using SegmentWrapper = std::reference_wrapper>; @@ -61,12 +62,14 @@ using SegmentVectorWrapper = std::reference_wrapper; struct RenderableSegment { - RenderableSegment(SegmentWrapper segment_, - const RenderTile& tile_, - const LayerRenderData& renderData_, - const SymbolBucket::PaintProperties& bucketPaintProperties_, - float sortKey_, - const SymbolType type_) + RenderableSegment( + SegmentWrapper segment_, + const RenderTile& tile_, + const LayerRenderData& renderData_, + const SymbolBucket::PaintProperties& bucketPaintProperties_, + float sortKey_, + const SymbolType type_ + ) : segment(segment_), tile(tile_), renderData(renderData_), @@ -81,7 +84,7 @@ struct RenderableSegment { float sortKey; SymbolType type; - friend bool operator < (const RenderableSegment& lhs, const RenderableSegment& rhs) { + friend bool operator<(const RenderableSegment& lhs, const RenderableSegment& rhs) { // Sort renderable segments by a sort key. if (lhs.sortKey < rhs.sortKey) { return true; @@ -94,7 +97,7 @@ struct RenderableSegment { return true; } - if (lhs.type == rhs.type) { + if (lhs.type == rhs.type) { return lhs.tile.id < rhs.tile.id; } } @@ -104,14 +107,16 @@ struct RenderableSegment { }; template -void drawIcon(const RenderSymbolLayer::Programs& programs, - const DrawFn& draw, - const RenderTile& tile, - const LayerRenderData& renderData, - SegmentsWrapper iconSegments, - const SymbolBucket::PaintProperties& bucketPaintProperties, - const PaintParameters& parameters, - const bool sdfIcons) { +void drawIcon( + const RenderSymbolLayer::Programs& programs, + const DrawFn& draw, + const RenderTile& tile, + const LayerRenderData& renderData, + SegmentsWrapper iconSegments, + const SymbolBucket::PaintProperties& bucketPaintProperties, + const PaintParameters& parameters, + const bool sdfIcons +) { auto& bucket = static_cast(*renderData.bucket); const auto& evaluated = getEvaluated(renderData.layerProperties); const auto& layout = *bucket.layout; @@ -119,72 +124,106 @@ void drawIcon(const RenderSymbolLayer::Programs& programs, const auto& paintPropertyValues = RenderSymbolLayer::iconPaintProperties(evaluated); const bool alongLine = layout.get() != SymbolPlacementType::Point && - layout.get() == AlignmentType::Map; + layout.get() == AlignmentType::Map; const bool iconScaled = layout.get().constantOr(1.0) != 1.0 || bucket.iconsNeedLinear; const bool iconTransformed = values.rotationAlignment == AlignmentType::Map || parameters.state.getPitch() != 0; - const gfx::TextureBinding textureBinding{ tile.getIconAtlasTexture().getResource(), - sdfIcons || - parameters.state.isChanging() || - iconScaled || iconTransformed - ? gfx::TextureFilterType::Linear - : gfx::TextureFilterType::Nearest }; + const gfx::TextureBinding textureBinding{ + tile.getIconAtlasTexture().getResource(), + sdfIcons || parameters.state.isChanging() || iconScaled || iconTransformed ? gfx::TextureFilterType::Linear + : gfx::TextureFilterType::Nearest}; const Size& iconSize = tile.getIconAtlasTexture().size; const bool variablePlacedIcon = bucket.hasVariablePlacement && layout.get() != IconTextFitType::None; if (sdfIcons) { if (values.hasHalo) { - draw(*programs.symbolSDFIconProgram, - SymbolSDFIconProgram::layoutUniformValues(false, variablePlacedIcon, values, iconSize, parameters.pixelsToGLUnits, parameters.pixelRatio, alongLine, tile, parameters.state, parameters.symbolFadeChange, SymbolSDFPart::Halo), + draw( + *programs.symbolSDFIconProgram, + SymbolSDFIconProgram::layoutUniformValues( + false, + variablePlacedIcon, + values, + iconSize, + parameters.pixelsToGLUnits, + parameters.pixelRatio, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange, + SymbolSDFPart::Halo + ), bucket.sdfIcon, iconSegments, bucket.iconSizeBinder, bucketPaintProperties.iconBinders, paintPropertyValues, - SymbolSDFIconProgram::TextureBindings{ - textureBinding - }, - "halo"); + SymbolSDFIconProgram::TextureBindings{textureBinding}, + "halo" + ); } if (values.hasFill) { - draw(*programs.symbolSDFIconProgram, - SymbolSDFIconProgram::layoutUniformValues(false, variablePlacedIcon, values, iconSize, parameters.pixelsToGLUnits, parameters.pixelRatio, alongLine, tile, parameters.state, parameters.symbolFadeChange, SymbolSDFPart::Fill), + draw( + *programs.symbolSDFIconProgram, + SymbolSDFIconProgram::layoutUniformValues( + false, + variablePlacedIcon, + values, + iconSize, + parameters.pixelsToGLUnits, + parameters.pixelRatio, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange, + SymbolSDFPart::Fill + ), bucket.sdfIcon, iconSegments, bucket.iconSizeBinder, bucketPaintProperties.iconBinders, paintPropertyValues, - SymbolSDFIconProgram::TextureBindings{ - textureBinding - }, - "fill"); + SymbolSDFIconProgram::TextureBindings{textureBinding}, + "fill" + ); } } else { - draw(*programs.symbolIconProgram, - SymbolIconProgram::layoutUniformValues(false, variablePlacedIcon, values, iconSize, parameters.pixelsToGLUnits, alongLine, tile, parameters.state, parameters.symbolFadeChange), + draw( + *programs.symbolIconProgram, + SymbolIconProgram::layoutUniformValues( + false, + variablePlacedIcon, + values, + iconSize, + parameters.pixelsToGLUnits, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange + ), bucket.icon, iconSegments, bucket.iconSizeBinder, bucketPaintProperties.iconBinders, paintPropertyValues, - SymbolIconProgram::TextureBindings{ - textureBinding - }, - "icon"); + SymbolIconProgram::TextureBindings{textureBinding}, + "icon" + ); } } template -void drawText(const RenderSymbolLayer::Programs& programs, - const DrawFn& draw, - const RenderTile& tile, - const LayerRenderData& renderData, - SegmentsWrapper textSegments, - const SymbolBucket::PaintProperties& bucketPaintProperties, - const PaintParameters& parameters) { +void drawText( + const RenderSymbolLayer::Programs& programs, + const DrawFn& draw, + const RenderTile& tile, + const LayerRenderData& renderData, + SegmentsWrapper textSegments, + const SymbolBucket::PaintProperties& bucketPaintProperties, + const PaintParameters& parameters +) { auto& bucket = static_cast(*renderData.bucket); const auto& evaluated = getEvaluated(renderData.layerProperties); const auto& layout = *bucket.layout; @@ -193,22 +232,24 @@ void drawText(const RenderSymbolLayer::Programs& programs, const auto& paintPropertyValues = RenderSymbolLayer::textPaintProperties(evaluated); const bool alongLine = layout.get() != SymbolPlacementType::Point && - layout.get() == AlignmentType::Map; + layout.get() == AlignmentType::Map; const Size& glyphTexSize = tile.getGlyphAtlasTexture().size; - const gfx::TextureBinding glyphTextureBinding{tile.getGlyphAtlasTexture().getResource(), - gfx::TextureFilterType::Linear}; + const gfx::TextureBinding glyphTextureBinding{ + tile.getGlyphAtlasTexture().getResource(), gfx::TextureFilterType::Linear}; const auto drawGlyphs = [&](auto& program, const auto& uniforms, const auto& textures, SymbolSDFPart part) { - draw(program, - uniforms, - bucket.text, - textSegments, - bucket.textSizeBinder, - bucketPaintProperties.textBinders, - paintPropertyValues, - textures, - (part == SymbolSDFPart::Halo) ? "halo" : "fill"); + draw( + program, + uniforms, + bucket.text, + textSegments, + bucket.textSizeBinder, + bucketPaintProperties.textBinders, + paintPropertyValues, + textures, + (part == SymbolSDFPart::Halo) ? "halo" : "fill" + ); }; if (bucket.iconsInText) { @@ -222,71 +263,87 @@ void drawText(const RenderSymbolLayer::Programs& programs, ? gfx::TextureFilterType::Linear : gfx::TextureFilterType::Nearest}; if (values.hasHalo) { - drawGlyphs(*programs.symbolTextAndIconProgram, - SymbolTextAndIconProgram::layoutUniformValues(bucket.hasVariablePlacement, - values, - glyphTexSize, - iconTexSize, - parameters.pixelsToGLUnits, - parameters.pixelRatio, - alongLine, - tile, - parameters.state, - parameters.symbolFadeChange, - SymbolSDFPart::Halo), - SymbolTextAndIconProgram::TextureBindings{glyphTextureBinding, iconTextureBinding}, - SymbolSDFPart::Halo); + drawGlyphs( + *programs.symbolTextAndIconProgram, + SymbolTextAndIconProgram::layoutUniformValues( + bucket.hasVariablePlacement, + values, + glyphTexSize, + iconTexSize, + parameters.pixelsToGLUnits, + parameters.pixelRatio, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange, + SymbolSDFPart::Halo + ), + SymbolTextAndIconProgram::TextureBindings{glyphTextureBinding, iconTextureBinding}, + SymbolSDFPart::Halo + ); } if (values.hasFill) { - drawGlyphs(*programs.symbolTextAndIconProgram, - SymbolTextAndIconProgram::layoutUniformValues(bucket.hasVariablePlacement, - values, - glyphTexSize, - iconTexSize, - parameters.pixelsToGLUnits, - parameters.pixelRatio, - alongLine, - tile, - parameters.state, - parameters.symbolFadeChange, - SymbolSDFPart::Fill), - SymbolTextAndIconProgram::TextureBindings{glyphTextureBinding, iconTextureBinding}, - SymbolSDFPart::Fill); + drawGlyphs( + *programs.symbolTextAndIconProgram, + SymbolTextAndIconProgram::layoutUniformValues( + bucket.hasVariablePlacement, + values, + glyphTexSize, + iconTexSize, + parameters.pixelsToGLUnits, + parameters.pixelRatio, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange, + SymbolSDFPart::Fill + ), + SymbolTextAndIconProgram::TextureBindings{glyphTextureBinding, iconTextureBinding}, + SymbolSDFPart::Fill + ); } } else { if (values.hasHalo) { - drawGlyphs(*programs.symbolSDFTextProgram, - SymbolSDFTextProgram::layoutUniformValues(true, - bucket.hasVariablePlacement, - values, - glyphTexSize, - parameters.pixelsToGLUnits, - parameters.pixelRatio, - alongLine, - tile, - parameters.state, - parameters.symbolFadeChange, - SymbolSDFPart::Halo), - SymbolSDFTextProgram::TextureBindings{glyphTextureBinding}, - SymbolSDFPart::Halo); + drawGlyphs( + *programs.symbolSDFTextProgram, + SymbolSDFTextProgram::layoutUniformValues( + true, + bucket.hasVariablePlacement, + values, + glyphTexSize, + parameters.pixelsToGLUnits, + parameters.pixelRatio, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange, + SymbolSDFPart::Halo + ), + SymbolSDFTextProgram::TextureBindings{glyphTextureBinding}, + SymbolSDFPart::Halo + ); } if (values.hasFill) { - drawGlyphs(*programs.symbolSDFTextProgram, - SymbolSDFTextProgram::layoutUniformValues(true, - bucket.hasVariablePlacement, - values, - glyphTexSize, - parameters.pixelsToGLUnits, - parameters.pixelRatio, - alongLine, - tile, - parameters.state, - parameters.symbolFadeChange, - SymbolSDFPart::Fill), - SymbolSDFTextProgram::TextureBindings{glyphTextureBinding}, - SymbolSDFPart::Fill); + drawGlyphs( + *programs.symbolSDFTextProgram, + SymbolSDFTextProgram::layoutUniformValues( + true, + bucket.hasVariablePlacement, + values, + glyphTexSize, + parameters.pixelsToGLUnits, + parameters.pixelRatio, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange, + SymbolSDFPart::Fill + ), + SymbolSDFTextProgram::TextureBindings{glyphTextureBinding}, + SymbolSDFPart::Fill + ); } } } @@ -312,8 +369,8 @@ void RenderSymbolLayer::transition(const TransitionParameters& parameters) { void RenderSymbolLayer::evaluate(const PropertyEvaluationParameters& parameters) { auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); + staticImmutableCast(baseImpl), unevaluated.evaluate(parameters) + ); auto& evaluated = properties->evaluated; auto& layout = impl_cast(baseImpl).layout; @@ -326,9 +383,10 @@ void RenderSymbolLayer::evaluate(const PropertyEvaluationParameters& parameters) auto hasTextOpacity = evaluated.get().constantOr(Color::black()).a > 0 || evaluated.get().constantOr(Color::black()).a > 0; - passes = ((evaluated.get().constantOr(1) > 0 && hasIconOpacity && iconSize > 0) - || (evaluated.get().constantOr(1) > 0 && hasTextOpacity && textSize > 0)) - ? RenderPass::Translucent : RenderPass::None; + passes = ((evaluated.get().constantOr(1) > 0 && hasIconOpacity && iconSize > 0) || + (evaluated.get().constantOr(1) > 0 && hasTextOpacity && textSize > 0)) + ? RenderPass::Translucent + : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -357,29 +415,23 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { const bool sortFeaturesByKey = !impl_cast(baseImpl).layout.get().isUndefined(); std::multiset renderableSegments; - const auto draw = [¶meters, this] (auto& programInstance, - const auto& uniformValues, - const auto& buffers, - auto& segments, - const auto& symbolSizeBinder, - const auto& binders, - const auto& paintProperties, - const auto& textureBindings, - const std::string& suffix) { + const auto draw = [¶meters, this]( + auto& programInstance, + const auto& uniformValues, + const auto& buffers, + auto& segments, + const auto& symbolSizeBinder, + const auto& binders, + const auto& paintProperties, + const auto& textureBindings, + const std::string& suffix + ) { const auto allUniformValues = programInstance.computeAllUniformValues( - uniformValues, - *symbolSizeBinder, - binders, - paintProperties, - static_cast(parameters.state.getZoom()) + uniformValues, *symbolSizeBinder, binders, paintProperties, static_cast(parameters.state.getZoom()) ); const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *buffers.vertexBuffer, - *buffers.dynamicVertexBuffer, - *buffers.opacityVertexBuffer, - binders, - paintProperties + *buffers.vertexBuffer, *buffers.dynamicVertexBuffer, *buffers.opacityVertexBuffer, binders, paintProperties ); this->checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); @@ -435,25 +487,54 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { // Prevent a flickering issue when a symbol is moved. // bucket.justReloaded = false; - auto addRenderables = [&renderableSegments, &tile, renderData, &bucketPaintProperties, it = renderableSegments.begin()] (auto& segments, const SymbolType type) mutable { - for (auto& segment : segments) { - it = renderableSegments.emplace_hint(it, SegmentWrapper{std::ref(segment)}, tile, *renderData, bucketPaintProperties, segment.sortKey, type); - } - }; + auto addRenderables = + [&renderableSegments, &tile, renderData, &bucketPaintProperties, it = renderableSegments.begin()]( + auto& segments, const SymbolType type + ) mutable { + for (auto& segment : segments) { + it = renderableSegments.emplace_hint( + it, + SegmentWrapper{std::ref(segment)}, + tile, + *renderData, + bucketPaintProperties, + segment.sortKey, + type + ); + } + }; if (bucket.hasIconData()) { if (sortFeaturesByKey) { addRenderables(bucket.icon.segments, SymbolType::IconRGBA); } else { - drawIcon(programs, draw, tile, *renderData, std::ref(bucket.icon.segments), bucketPaintProperties, parameters, false /*sdfIcon*/); + drawIcon( + programs, + draw, + tile, + *renderData, + std::ref(bucket.icon.segments), + bucketPaintProperties, + parameters, + false /*sdfIcon*/ + ); } } - + if (bucket.hasSdfIconData()) { if (sortFeaturesByKey) { addRenderables(bucket.sdfIcon.segments, SymbolType::IconSDF); } else { - drawIcon(programs, draw, tile, *renderData, std::ref(bucket.sdfIcon.segments), bucketPaintProperties, parameters, true /*sdfIcon*/); + drawIcon( + programs, + draw, + tile, + *renderData, + std::ref(bucket.sdfIcon.segments), + bucketPaintProperties, + parameters, + true /*sdfIcon*/ + ); } } @@ -461,25 +542,27 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { if (sortFeaturesByKey) { addRenderables(bucket.text.segments, SymbolType::Text); } else { - drawText(programs, draw, tile, *renderData, std::ref(bucket.text.segments), bucketPaintProperties, parameters); + drawText( + programs, draw, tile, *renderData, std::ref(bucket.text.segments), bucketPaintProperties, parameters + ); } } - const auto drawCollisonData = [&](const bool isText, const bool hasCollisionBox, const bool hasCollisionCircle) { + const auto drawCollisonData = [&](const bool isText, const bool hasCollisionBox, const bool hasCollisionCircle + ) { if (!hasCollisionBox && !hasCollisionCircle) return; static const style::Properties<>::PossiblyEvaluated properties{}; static const CollisionBoxProgram::Binders paintAttributeData(properties, 0); const auto pixelRatio = tile.id.pixelsToTileUnits(1.0f, static_cast(parameters.state.getZoom())); - const auto scale = static_cast(std::pow(2, parameters.state.getZoom() - tile.getOverscaledTileID().overscaledZ)); - std::array extrudeScale = - {{ - parameters.pixelsToGLUnits[0] / (pixelRatio * scale), - parameters.pixelsToGLUnits[1] / (pixelRatio * scale) - }}; + const auto scale = + static_cast(std::pow(2, parameters.state.getZoom() - tile.getOverscaledTileID().overscaledZ)); + std::array extrudeScale = { + {parameters.pixelsToGLUnits[0] / (pixelRatio * scale), + parameters.pixelsToGLUnits[1] / (pixelRatio * scale)}}; const auto& evaluated = getEvaluated(renderData->layerProperties); const auto& layout = *bucket.layout; - const auto values = isText ? textPropertyValues(evaluated, layout): iconPropertyValues(evaluated, layout); + const auto values = isText ? textPropertyValues(evaluated, layout) : iconPropertyValues(evaluated, layout); const bool needTranslate = values.translate[0] != 0 || values.translate[1] != 0; if (hasCollisionBox) { @@ -487,18 +570,19 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { programs.collisionBoxProgram->draw( parameters.context, *parameters.renderPass, - gfx::Lines{ 1.0f }, + gfx::Lines{1.0f}, gfx::DepthMode::disabled(), gfx::StencilMode::disabled(), parameters.colorModeForRenderPass(), gfx::CullFaceMode::disabled(), - CollisionBoxProgram::LayoutUniformValues { - uniforms::matrix::Value((needTranslate + CollisionBoxProgram::LayoutUniformValues{ + uniforms::matrix::Value( + (needTranslate ? tile.translatedMatrix(values.translate, values.translateAnchor, parameters.state) - : tile.matrix)), + : tile.matrix) + ), uniforms::extrude_scale::Value(extrudeScale), - uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance()) - }, + uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance())}, *collisionBox->vertexBuffer, *collisionBox->dynamicVertexBuffer, *collisionBox->indexBuffer, @@ -507,7 +591,8 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { properties, CollisionBoxProgram::TextureBindings{}, static_cast(parameters.state.getZoom()), - getID()); + getID() + ); } if (hasCollisionCircle) { const auto& collisionCircle = isText ? bucket.textCollisionCircle : bucket.iconCollisionCircle; @@ -519,14 +604,16 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { gfx::StencilMode::disabled(), parameters.colorModeForRenderPass(), gfx::CullFaceMode::disabled(), - CollisionCircleProgram::LayoutUniformValues { - uniforms::matrix::Value((needTranslate + CollisionCircleProgram::LayoutUniformValues{ + uniforms::matrix::Value( + (needTranslate ? tile.translatedMatrix(values.translate, values.translateAnchor, parameters.state) - : tile.matrix)), + : tile.matrix) + ), uniforms::extrude_scale::Value(extrudeScale), - uniforms::overscale_factor::Value(static_cast(tile.getOverscaledTileID().overscaleFactor())), - uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance()) - }, + uniforms::overscale_factor::Value(static_cast(tile.getOverscaledTileID().overscaleFactor( + ))), + uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance())}, *collisionCircle->vertexBuffer, *collisionCircle->dynamicVertexBuffer, *collisionCircle->indexBuffer, @@ -535,7 +622,8 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { properties, CollisionCircleProgram::TextureBindings{}, static_cast(parameters.state.getZoom()), - getID()); + getID() + ); } }; drawCollisonData(false /*isText*/, bucket.hasIconCollisionBoxData(), bucket.hasIconCollisionCircleData()); @@ -545,38 +633,57 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { if (sortFeaturesByKey) { for (auto& renderable : renderableSegments) { if (renderable.type == SymbolType::Text) { - drawText(programs, draw, renderable.tile, renderable.renderData, renderable.segment, renderable.bucketPaintProperties, parameters); + drawText( + programs, + draw, + renderable.tile, + renderable.renderData, + renderable.segment, + renderable.bucketPaintProperties, + parameters + ); } else { - drawIcon(programs, draw, renderable.tile, renderable.renderData, renderable.segment, renderable.bucketPaintProperties, parameters, renderable.type == SymbolType::IconSDF); + drawIcon( + programs, + draw, + renderable.tile, + renderable.renderData, + renderable.segment, + renderable.bucketPaintProperties, + parameters, + renderable.type == SymbolType::IconSDF + ); } } } } // static -style::IconPaintProperties::PossiblyEvaluated RenderSymbolLayer::iconPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_) { - return style::IconPaintProperties::PossiblyEvaluated { - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get() - }; +style::IconPaintProperties::PossiblyEvaluated RenderSymbolLayer::iconPaintProperties( + const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_ +) { + return style::IconPaintProperties::PossiblyEvaluated{ + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get()}; } // static -style::TextPaintProperties::PossiblyEvaluated RenderSymbolLayer::textPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_) { - return style::TextPaintProperties::PossiblyEvaluated { - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get() - }; +style::TextPaintProperties::PossiblyEvaluated RenderSymbolLayer::textPaintProperties( + const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_ +) { + return style::TextPaintProperties::PossiblyEvaluated{ + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get()}; } void RenderSymbolLayer::prepare(const LayerPrepareParameters& params) { @@ -601,10 +708,14 @@ void RenderSymbolLayer::prepare(const LayerPrepareParameters& params) { for (const auto& sortKeyRange : bucket->sortKeyRanges) { BucketPlacementData layerData{*bucket, renderTile, featureIndex, baseImpl->source, sortKeyRange}; auto sortPosition = std::upper_bound( - placementData.cbegin(), placementData.cend(), layerData, [](const auto& lhs, const auto& rhs) { + placementData.cbegin(), + placementData.cend(), + layerData, + [](const auto& lhs, const auto& rhs) { assert(lhs.sortKeyRange && rhs.sortKeyRange); return lhs.sortKeyRange->sortKey < rhs.sortKeyRange->sortKey; - }); + } + ); placementData.insert(sortPosition, std::move(layerData)); } } diff --git a/src/mbgl/renderer/layers/render_symbol_layer.hpp b/src/mbgl/renderer/layers/render_symbol_layer.hpp index 83df195a168..3b712c603bd 100644 --- a/src/mbgl/renderer/layers/render_symbol_layer.hpp +++ b/src/mbgl/renderer/layers/render_symbol_layer.hpp @@ -14,24 +14,22 @@ namespace style { // Since each program deals either with icons or text, using a smaller property set // lets us avoid unnecessarily binding attributes for properties the program wouldn't use. class IconPaintProperties : public Properties< - IconOpacity, - IconColor, - IconHaloColor, - IconHaloWidth, - IconHaloBlur, - IconTranslate, - IconTranslateAnchor -> {}; + IconOpacity, + IconColor, + IconHaloColor, + IconHaloWidth, + IconHaloBlur, + IconTranslate, + IconTranslateAnchor> {}; class TextPaintProperties : public Properties< - TextOpacity, - TextColor, - TextHaloColor, - TextHaloWidth, - TextHaloBlur, - TextTranslate, - TextTranslateAnchor -> {}; + TextOpacity, + TextColor, + TextHaloColor, + TextHaloWidth, + TextHaloBlur, + TextTranslate, + TextTranslateAnchor> {}; // Repackaging evaluated values from SymbolLayoutProperties + SymbolPaintProperties // for genericity over icons vs. text. @@ -65,7 +63,7 @@ class SymbolTextAndIconProgram; class CollisionBoxProgram; class CollisionCircleProgram; -class RenderSymbolLayer final: public RenderLayer { +class RenderSymbolLayer final : public RenderLayer { public: struct Programs { std::shared_ptr symbolIconProgram; @@ -80,8 +78,10 @@ class RenderSymbolLayer final: public RenderLayer { explicit RenderSymbolLayer(Immutable); ~RenderSymbolLayer() override; - static style::IconPaintProperties::PossiblyEvaluated iconPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated&); - static style::TextPaintProperties::PossiblyEvaluated textPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated&); + static style::IconPaintProperties::PossiblyEvaluated + iconPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated&); + static style::TextPaintProperties::PossiblyEvaluated + textPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated&); private: void transition(const TransitionParameters&) override; diff --git a/src/mbgl/renderer/paint_parameters.cpp b/src/mbgl/renderer/paint_parameters.cpp index caa44e1890b..0fdd200d1e6 100644 --- a/src/mbgl/renderer/paint_parameters.cpp +++ b/src/mbgl/renderer/paint_parameters.cpp @@ -26,38 +26,39 @@ TransformParameters::TransformParameters(const TransformState& state_) state.getProjMatrix(nearClippedProjMatrix, static_cast(0.1 * state.getCameraToCenterDistance())); } -PaintParameters::PaintParameters(gfx::Context& context_, - float pixelRatio_, - gfx::RendererBackend& backend_, - const EvaluatedLight& evaluatedLight_, - MapMode mode_, - MapDebugOptions debugOptions_, - TimePoint timePoint_, - const TransformParameters& transformParams_, - RenderStaticData& staticData_, - LineAtlas& lineAtlas_, - PatternAtlas& patternAtlas_) +PaintParameters::PaintParameters( + gfx::Context& context_, + float pixelRatio_, + gfx::RendererBackend& backend_, + const EvaluatedLight& evaluatedLight_, + MapMode mode_, + MapDebugOptions debugOptions_, + TimePoint timePoint_, + const TransformParameters& transformParams_, + RenderStaticData& staticData_, + LineAtlas& lineAtlas_, + PatternAtlas& patternAtlas_ +) : context(context_), - backend(backend_), - encoder(context.createCommandEncoder()), - transformParams(transformParams_), - state(transformParams_.state), - evaluatedLight(evaluatedLight_), - staticData(staticData_), - lineAtlas(lineAtlas_), - patternAtlas(patternAtlas_), - mapMode(mode_), - debugOptions(debugOptions_), - timePoint(timePoint_), - pixelRatio(pixelRatio_), + backend(backend_), + encoder(context.createCommandEncoder()), + transformParams(transformParams_), + state(transformParams_.state), + evaluatedLight(evaluatedLight_), + staticData(staticData_), + lineAtlas(lineAtlas_), + patternAtlas(patternAtlas_), + mapMode(mode_), + debugOptions(debugOptions_), + timePoint(timePoint_), + pixelRatio(pixelRatio_), #ifndef NDEBUG - programs((debugOptions & MapDebugOptions::Overdraw) ? staticData_.overdrawPrograms : staticData_.programs), + programs((debugOptions & MapDebugOptions::Overdraw) ? staticData_.overdrawPrograms : staticData_.programs), #else - programs(staticData_.programs), + programs(staticData_.programs), #endif - shaders(*staticData_.shaders) -{ - pixelsToGLUnits = {{ 2.0f / state.getSize().width, -2.0f / state.getSize().height }}; + shaders(*staticData_.shaders) { + pixelsToGLUnits = {{2.0f / state.getSize().width, -2.0f / state.getSize().height}}; if (state.getViewportMode() == ViewportMode::FlippedY) { pixelsToGLUnits[1] *= -1; @@ -78,13 +79,11 @@ gfx::DepthMode PaintParameters::depthModeForSublayer(uint8_t n, gfx::DepthMaskTy return gfx::DepthMode::disabled(); } float depth = depthRangeSize + ((1 + currentLayer) * numSublayers + n) * depthEpsilon; - return gfx::DepthMode { gfx::DepthFunctionType::LessEqual, mask, { depth, depth } }; + return gfx::DepthMode{gfx::DepthFunctionType::LessEqual, mask, {depth, depth}}; } gfx::DepthMode PaintParameters::depthModeFor3D() const { - return gfx::DepthMode{ gfx::DepthFunctionType::LessEqual, - gfx::DepthMaskType::ReadWrite, - { 0.0, depthRangeSize } }; + return gfx::DepthMode{gfx::DepthFunctionType::LessEqual, gfx::DepthMaskType::ReadWrite, {0.0, depthRangeSize}}; } void PaintParameters::clearStencil() { @@ -95,16 +94,20 @@ void PaintParameters::clearStencil() { namespace { // Detects a difference in keys of renderTiles and tileClippingMaskIDs -bool tileIDsIdentical(const RenderTiles& renderTiles, - const std::map& tileClippingMaskIDs) { +bool tileIDsIdentical(const RenderTiles& renderTiles, const std::map& tileClippingMaskIDs) { assert(renderTiles); - assert(std::is_sorted(renderTiles->begin(), renderTiles->end(), - [](const RenderTile& a, const RenderTile& b) { return a.id < b.id; })); + assert(std::is_sorted(renderTiles->begin(), renderTiles->end(), [](const RenderTile& a, const RenderTile& b) { + return a.id < b.id; + })); if (renderTiles->size() != tileClippingMaskIDs.size()) { return false; } - return std::equal(renderTiles->begin(), renderTiles->end(), tileClippingMaskIDs.begin(), - [](const RenderTile& a, const auto& b) { return a.id == b.first; }); + return std::equal( + renderTiles->begin(), + renderTiles->end(), + tileClippingMaskIDs.begin(), + [](const RenderTile& a, const auto& b) { return a.id == b.first; } + ); } } // namespace @@ -126,39 +129,44 @@ void PaintParameters::renderTileClippingMasks(const RenderTiles& renderTiles) { if (!program) { return; } - - const style::Properties<>::PossiblyEvaluated properties {}; + + const style::Properties<>::PossiblyEvaluated properties{}; const ClippingMaskProgram::Binders paintAttributeData(properties, 0); for (const RenderTile& renderTile : *renderTiles) { const int32_t stencilID = nextStencilID++; tileClippingMaskIDs.emplace(renderTile.id, stencilID); - program->draw(context, - *renderPass, - gfx::Triangles(), - gfx::DepthMode::disabled(), - gfx::StencilMode{gfx::StencilMode::Always{}, - stencilID, - 0b11111111, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Replace}, - gfx::ColorMode::disabled(), - gfx::CullFaceMode::disabled(), - *staticData.quadTriangleIndexBuffer, - staticData.clippingMaskSegments, - ClippingMaskProgram::computeAllUniformValues( - ClippingMaskProgram::LayoutUniformValues{ - uniforms::matrix::Value(matrixForTile(renderTile.id)), - }, - paintAttributeData, - properties, - static_cast(state.getZoom())), - ClippingMaskProgram::computeAllAttributeBindings( - *staticData.tileVertexBuffer, paintAttributeData, properties), - ClippingMaskProgram::TextureBindings{}, - "clipping/" + util::toString(stencilID)); + program->draw( + context, + *renderPass, + gfx::Triangles(), + gfx::DepthMode::disabled(), + gfx::StencilMode{ + gfx::StencilMode::Always{}, + stencilID, + 0b11111111, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Replace}, + gfx::ColorMode::disabled(), + gfx::CullFaceMode::disabled(), + *staticData.quadTriangleIndexBuffer, + staticData.clippingMaskSegments, + ClippingMaskProgram::computeAllUniformValues( + ClippingMaskProgram::LayoutUniformValues{ + uniforms::matrix::Value(matrixForTile(renderTile.id)), + }, + paintAttributeData, + properties, + static_cast(state.getZoom()) + ), + ClippingMaskProgram::computeAllAttributeBindings( + *staticData.tileVertexBuffer, paintAttributeData, properties + ), + ClippingMaskProgram::TextureBindings{}, + "clipping/" + util::toString(stencilID) + ); } } @@ -166,12 +174,13 @@ gfx::StencilMode PaintParameters::stencilModeForClipping(const UnwrappedTileID& auto it = tileClippingMaskIDs.find(tileID); assert(it != tileClippingMaskIDs.end()); const int32_t id = it != tileClippingMaskIDs.end() ? it->second : 0b00000000; - return gfx::StencilMode{ gfx::StencilMode::Equal{ 0b11111111 }, - id, - 0b00000000, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Replace }; + return gfx::StencilMode{ + gfx::StencilMode::Equal{0b11111111}, + id, + 0b00000000, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Replace}; } gfx::StencilMode PaintParameters::stencilModeFor3D() { @@ -184,25 +193,22 @@ gfx::StencilMode PaintParameters::stencilModeFor3D() { tileClippingMaskIDs.clear(); const int32_t id = nextStencilID++; - return gfx::StencilMode{ gfx::StencilMode::NotEqual{ 0b11111111 }, - id, - 0b11111111, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Replace }; + return gfx::StencilMode{ + gfx::StencilMode::NotEqual{0b11111111}, + id, + 0b11111111, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Replace}; } gfx::ColorMode PaintParameters::colorModeForRenderPass() const { if (debugOptions & MapDebugOptions::Overdraw) { const float overdraw = 1.0f / 8.0f; - return gfx::ColorMode { - gfx::ColorMode::Add { - gfx::ColorBlendFactorType::ConstantColor, - gfx::ColorBlendFactorType::One - }, - Color { overdraw, overdraw, overdraw, 0.0f }, - gfx::ColorMode::Mask { true, true, true, true } - }; + return gfx::ColorMode{ + gfx::ColorMode::Add{gfx::ColorBlendFactorType::ConstantColor, gfx::ColorBlendFactorType::One}, + Color{overdraw, overdraw, overdraw, 0.0f}, + gfx::ColorMode::Mask{true, true, true, true}}; } else if (pass == RenderPass::Translucent) { return gfx::ColorMode::alphaBlended(); } else { diff --git a/src/mbgl/renderer/paint_parameters.hpp b/src/mbgl/renderer/paint_parameters.hpp index 75c28c17e29..c442c010865 100644 --- a/src/mbgl/renderer/paint_parameters.hpp +++ b/src/mbgl/renderer/paint_parameters.hpp @@ -33,7 +33,6 @@ class RenderPass; class ShaderRegistry; } // namespace gfx - class TransformParameters { public: TransformParameters(const TransformState&); @@ -45,17 +44,7 @@ class TransformParameters { class PaintParameters { public: - PaintParameters(gfx::Context&, - float pixelRatio, - gfx::RendererBackend&, - const EvaluatedLight&, - MapMode, - MapDebugOptions, - TimePoint, - const TransformParameters&, - RenderStaticData&, - LineAtlas&, - PatternAtlas&); + PaintParameters(gfx::Context&, float pixelRatio, gfx::RendererBackend&, const EvaluatedLight&, MapMode, MapDebugOptions, TimePoint, const TransformParameters&, RenderStaticData&, LineAtlas&, PatternAtlas&); ~PaintParameters(); gfx::Context& context; diff --git a/src/mbgl/renderer/paint_property_binder.hpp b/src/mbgl/renderer/paint_property_binder.hpp index 14d23881aa4..a05204ecdc0 100644 --- a/src/mbgl/renderer/paint_property_binder.hpp +++ b/src/mbgl/renderer/paint_property_binder.hpp @@ -35,10 +35,11 @@ using FeatureVertexRangeMap = std::map -using ZoomInterpolatedAttributeType = gfx::AttributeType; +using ZoomInterpolatedAttributeType = + gfx::AttributeType; inline std::array attributeValue(float v) { - return {{ v }}; + return {{v}}; } /* @@ -55,22 +56,23 @@ inline uint16_t packUint8Pair(T a, T b) { Encode a four-component color value into a pair of floats. Since csscolorparser uses 8-bit precision for each color component, for each float we use the upper 8 bits for one component (e.g. (color.r * 255) * 256), and the lower 8 for another. - + Also note that colors come in as floats 0..1, so we scale by 255. */ inline std::array attributeValue(const Color& color) { - return {{ - static_cast(packUint8Pair(255 * color.r, 255 * color.g)), - static_cast(packUint8Pair(255 * color.b, 255 * color.a)) - }}; + return { + {static_cast(packUint8Pair(255 * color.r, 255 * color.g)), + static_cast(packUint8Pair(255 * color.b, 255 * color.a))}}; } template -std::array zoomInterpolatedAttributeValue(const std::array& min, const std::array& max) { - std::array result; +std::array zoomInterpolatedAttributeValue( + const std::array& min, const std::array& max +) { + std::array result; for (size_t i = 0; i < N; i++) { - result[i] = min[i]; - result[i+N] = max[i]; + result[i] = min[i]; + result[i + N] = max[i]; } return result; } @@ -102,26 +104,24 @@ std::array zoomInterpolatedAttributeValue(const std::array template class PaintPropertyBinder { public: - virtual ~PaintPropertyBinder() = default; - virtual void populateVertexVector(const GeometryTileFeature& feature, - std::size_t length, - std::size_t index, - const ImagePositions&, - const std::optional&, - const CanonicalTileID& canonical, - const style::expression::Value&) = 0; + virtual void + populateVertexVector(const GeometryTileFeature& feature, std::size_t length, std::size_t index, const ImagePositions&, const std::optional&, const CanonicalTileID& canonical, const style::expression::Value&) = 0; virtual void updateVertexVectors(const FeatureStates&, const GeometryTileLayer&, const ImagePositions&) {} virtual void updateVertexVector(std::size_t, std::size_t, const GeometryTileFeature&, const FeatureState&) = 0; virtual void upload(gfx::UploadPass&) = 0; - virtual void setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) = 0; - virtual std::tuple>...> attributeBinding(const PossiblyEvaluatedType& currentValue) const = 0; + virtual void + setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) = 0; + virtual std::tuple>...> attributeBinding( + const PossiblyEvaluatedType& currentValue + ) const = 0; virtual std::tuple...> interpolationFactor(float currentZoom) const = 0; - virtual std::tuple...> uniformValue(const PossiblyEvaluatedType& currentValue) const = 0; + virtual std::tuple...> uniformValue(const PossiblyEvaluatedType& currentValue + ) const = 0; static std::unique_ptr create(const PossiblyEvaluatedType& value, float zoom, T defaultValue); @@ -132,30 +132,26 @@ template class ConstantPaintPropertyBinder : public PaintPropertyBinder, A> { public: ConstantPaintPropertyBinder(T constant_) - : constant(std::move(constant_)) { - } + : constant(std::move(constant_)) {} - void populateVertexVector(const GeometryTileFeature&, - std::size_t, - std::size_t, - const ImagePositions&, - const std::optional&, - const CanonicalTileID&, - const style::expression::Value&) override {} + void + populateVertexVector(const GeometryTileFeature&, std::size_t, std::size_t, const ImagePositions&, const std::optional&, const CanonicalTileID&, const style::expression::Value&) + override {} void updateVertexVector(std::size_t, std::size_t, const GeometryTileFeature&, const FeatureState&) override {} void upload(gfx::UploadPass&) override {} - void setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) override {}; + void + setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) + override{}; - std::tuple> attributeBinding(const PossiblyEvaluatedPropertyValue&) const override { + std::tuple> attributeBinding(const PossiblyEvaluatedPropertyValue&) + const override { return {}; } - std::tuple interpolationFactor(float) const override { - return std::tuple { 0.0f }; - } + std::tuple interpolationFactor(float) const override { return std::tuple{0.0f}; } std::tuple uniformValue(const PossiblyEvaluatedPropertyValue& currentValue) const override { - return std::tuple { currentValue.constantOr(constant) }; + return std::tuple{currentValue.constantOr(constant)}; } private: @@ -163,27 +159,27 @@ class ConstantPaintPropertyBinder : public PaintPropertyBinder -class ConstantCrossFadedPaintPropertyBinder final : public PaintPropertyBinder,PossiblyEvaluatedPropertyValue>, As...> { +class ConstantCrossFadedPaintPropertyBinder final + : public PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, As...> { public: ConstantCrossFadedPaintPropertyBinder(Faded constant_) - : constant(std::move(constant_)), constantPatternPositions({}) { - } + : constant(std::move(constant_)), + constantPatternPositions({}) {} - void populateVertexVector(const GeometryTileFeature&, - std::size_t, - std::size_t, - const ImagePositions&, - const std::optional&, - const CanonicalTileID&, - const style::expression::Value&) override {} + void + populateVertexVector(const GeometryTileFeature&, std::size_t, std::size_t, const ImagePositions&, const std::optional&, const CanonicalTileID&, const style::expression::Value&) + override {} void updateVertexVector(std::size_t, std::size_t, const GeometryTileFeature&, const FeatureState&) override {} void upload(gfx::UploadPass&) override {} - void setPatternParameters(const std::optional& posA, const std::optional& posB, const CrossfadeParameters&) override { + void + setPatternParameters(const std::optional& posA, const std::optional& posB, const CrossfadeParameters&) + override { if (!posA || !posB) { return; } else { - constantPatternPositions = std::tuple, std::array> { posB->tlbr(), posA->tlbr() }; + constantPatternPositions = std::tuple, std::array>{ + posB->tlbr(), posA->tlbr()}; } } @@ -192,11 +188,10 @@ class ConstantCrossFadedPaintPropertyBinder final : public PaintPropertyBinder interpolationFactor(float) const override { - return std::tuple { 0.0f, 0.0f }; - } + std::tuple interpolationFactor(float) const override { return std::tuple{0.0f, 0.0f}; } - std::tuple, std::array> uniformValue(const PossiblyEvaluatedPropertyValue>&) const override { + std::tuple, std::array> + uniformValue(const PossiblyEvaluatedPropertyValue>&) const override { return constantPatternPositions; } @@ -215,25 +210,29 @@ class SourceFunctionPaintPropertyBinder final : public PaintPropertyBinder expression_, T defaultValue_) : expression(std::move(expression_)), - defaultValue(std::move(defaultValue_)) { - } - void setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) override {}; - void populateVertexVector(const GeometryTileFeature& feature, - std::size_t length, - std::size_t index, - const ImagePositions&, - const std::optional&, - const CanonicalTileID& canonical, - const style::expression::Value& formattedSection) override { + defaultValue(std::move(defaultValue_)) {} + void + setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) + override{}; + void populateVertexVector( + const GeometryTileFeature& feature, + std::size_t length, + std::size_t index, + const ImagePositions&, + const std::optional&, + const CanonicalTileID& canonical, + const style::expression::Value& formattedSection + ) override { using style::expression::EvaluationContext; auto evaluated = expression.evaluate( EvaluationContext(&feature).withFormattedSection(&formattedSection).withCanonicalTileID(&canonical), - defaultValue); + defaultValue + ); this->statistics.add(evaluated); auto value = attributeValue(evaluated); auto elements = vertexVector.elements(); for (std::size_t i = elements; i < length; ++i) { - vertexVector.emplace_back(BaseVertex { value }); + vertexVector.emplace_back(BaseVertex{value}); } std::optional idStr = featureIDtoString(feature.getID()); if (idStr) { @@ -241,8 +240,8 @@ class SourceFunctionPaintPropertyBinder final : public PaintPropertyBinder> attributeBinding(const PossiblyEvaluatedPropertyValue& currentValue) const override { + std::tuple> attributeBinding( + const PossiblyEvaluatedPropertyValue& currentValue + ) const override { if (currentValue.isConstant()) { return {}; } else { - return std::tuple>{ - gfx::attributeBinding(*vertexBuffer) - }; + return std::tuple>{gfx::attributeBinding(*vertexBuffer)}; } } - std::tuple interpolationFactor(float) const override { - return std::tuple { 0.0f }; - } + std::tuple interpolationFactor(float) const override { return std::tuple{0.0f}; } std::tuple uniformValue(const PossiblyEvaluatedPropertyValue& currentValue) const override { if (currentValue.isConstant()) { - return std::tuple{ *currentValue.constant() }; + return std::tuple{*currentValue.constant()}; } else { // Uniform values for vertex attribute arrays are unused. return {}; @@ -306,9 +304,9 @@ class SourceFunctionPaintPropertyBinder final : public PaintPropertyBinder -class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder, A> { +class CompositeFunctionPaintPropertyBinder final + : public PaintPropertyBinder, A> { public: - using AttributeType = ZoomInterpolatedAttributeType; using AttributeValue = typename AttributeType::Value; using Vertex = gfx::VertexType; @@ -316,35 +314,40 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder expression_, float zoom, T defaultValue_) : expression(std::move(expression_)), defaultValue(std::move(defaultValue_)), - zoomRange({zoom, zoom + 1}) { - } - void setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) override {}; - void populateVertexVector(const GeometryTileFeature& feature, - std::size_t length, - std::size_t index, - const ImagePositions&, - const std::optional&, - const CanonicalTileID& canonical, - const style::expression::Value& formattedSection) override { + zoomRange({zoom, zoom + 1}) {} + void + setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) + override{}; + void populateVertexVector( + const GeometryTileFeature& feature, + std::size_t length, + std::size_t index, + const ImagePositions&, + const std::optional&, + const CanonicalTileID& canonical, + const style::expression::Value& formattedSection + ) override { using style::expression::EvaluationContext; Range range = { - expression.evaluate(EvaluationContext(zoomRange.min, &feature) - .withFormattedSection(&formattedSection) - .withCanonicalTileID(&canonical), - defaultValue), - expression.evaluate(EvaluationContext(zoomRange.max, &feature) - .withFormattedSection(&formattedSection) - .withCanonicalTileID(&canonical), - defaultValue), + expression.evaluate( + EvaluationContext(zoomRange.min, &feature) + .withFormattedSection(&formattedSection) + .withCanonicalTileID(&canonical), + defaultValue + ), + expression.evaluate( + EvaluationContext(zoomRange.max, &feature) + .withFormattedSection(&formattedSection) + .withCanonicalTileID(&canonical), + defaultValue + ), }; this->statistics.add(range.min); this->statistics.add(range.max); - AttributeValue value = zoomInterpolatedAttributeValue( - attributeValue(range.min), - attributeValue(range.max)); + AttributeValue value = zoomInterpolatedAttributeValue(attributeValue(range.min), attributeValue(range.max)); auto elements = vertexVector.elements(); for (std::size_t i = elements; i < length; ++i) { - vertexVector.emplace_back(Vertex { value }); + vertexVector.emplace_back(Vertex{value}); } std::optional idStr = featureIDtoString(feature.getID()); if (idStr) { @@ -352,8 +355,8 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder range = { expression.evaluate(EvaluationContext(zoomRange.min, &feature, &state), defaultValue), @@ -389,13 +393,13 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder> attributeBinding(const PossiblyEvaluatedPropertyValue& currentValue) const override { + std::tuple> attributeBinding( + const PossiblyEvaluatedPropertyValue& currentValue + ) const override { if (currentValue.isConstant()) { return {}; } else { - return std::tuple>{ - gfx::attributeBinding(*vertexBuffer) - }; + return std::tuple>{gfx::attributeBinding(*vertexBuffer)}; } } @@ -408,7 +412,7 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder uniformValue(const PossiblyEvaluatedPropertyValue& currentValue) const override { if (currentValue.isConstant()) { - return std::tuple { *currentValue.constant() }; + return std::tuple{*currentValue.constant()}; } else { // Uniform values for vertex attribute arrays are unused. return {}; @@ -425,7 +429,8 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder -class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2> { +class CompositeCrossFadedPaintPropertyBinder final + : public PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2> { public: using AttributeType = ZoomInterpolatedAttributeType; using AttributeType2 = ZoomInterpolatedAttributeType; @@ -439,28 +444,26 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< CompositeCrossFadedPaintPropertyBinder(style::PropertyExpression expression_, float zoom, T defaultValue_) : expression(std::move(expression_)), defaultValue(std::move(defaultValue_)), - zoomRange({zoom, zoom + 1}) { - } + zoomRange({zoom, zoom + 1}) {} - void setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters& crossfade_) override { + void setPatternParameters( + const std::optional&, const std::optional&, const CrossfadeParameters& crossfade_ + ) override { crossfade = crossfade_; }; - void populateVertexVector(const GeometryTileFeature&, - std::size_t length, - std::size_t /* index */, - const ImagePositions& patternPositions, - const std::optional& patternDependencies, - const CanonicalTileID&, - const style::expression::Value&) override { - if (!patternDependencies || patternDependencies->mid.empty()) { - // Unlike other propperties with expressions that evaluate to null, the default value for `*-pattern` properties is an empty - // string and will not have a valid entry in patternPositions. We still need to populate the attribute buffers to avoid crashes - // when we try to draw the layer because we don't know at draw time if all features were evaluated to valid pattern dependencies. + void + populateVertexVector(const GeometryTileFeature&, std::size_t length, std::size_t /* index */, const ImagePositions& patternPositions, const std::optional& patternDependencies, const CanonicalTileID&, const style::expression::Value&) + override { + if (!patternDependencies || patternDependencies->mid.empty()) { + // Unlike other propperties with expressions that evaluate to null, the default value for `*-pattern` + // properties is an empty string and will not have a valid entry in patternPositions. We still need to + // populate the attribute buffers to avoid crashes when we try to draw the layer because we don't know at + // draw time if all features were evaluated to valid pattern dependencies. for (std::size_t i = zoomInVertexVector.elements(); i < length; ++i) { - patternToVertexVector.emplace_back(Vertex { std::array{{0, 0, 0, 0}} }); - zoomInVertexVector.emplace_back(Vertex2 { std::array{{0, 0, 0, 0}} } ); - zoomOutVertexVector.emplace_back(Vertex2 { std::array{{0, 0, 0, 0}} }); + patternToVertexVector.emplace_back(Vertex{std::array{{0, 0, 0, 0}}}); + zoomInVertexVector.emplace_back(Vertex2{std::array{{0, 0, 0, 0}}}); + zoomOutVertexVector.emplace_back(Vertex2{std::array{{0, 0, 0, 0}}}); } } else if (!patternPositions.empty()) { const auto min = patternPositions.find(patternDependencies->min); @@ -475,9 +478,9 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< const ImagePosition imageMax = max->second; for (std::size_t i = zoomInVertexVector.elements(); i < length; ++i) { - patternToVertexVector.emplace_back(Vertex { imageMid.tlbr() }); - zoomInVertexVector.emplace_back(Vertex2 { imageMin.tlbr() }); - zoomOutVertexVector.emplace_back(Vertex2 { imageMax.tlbr() }); + patternToVertexVector.emplace_back(Vertex{imageMid.tlbr()}); + zoomInVertexVector.emplace_back(Vertex2{imageMin.tlbr()}); + zoomOutVertexVector.emplace_back(Vertex2{imageMax.tlbr()}); } } } @@ -494,7 +497,9 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< } } - std::tuple, std::optional> attributeBinding(const PossiblyEvaluatedPropertyValue>& currentValue) const override { + std::tuple, std::optional> attributeBinding( + const PossiblyEvaluatedPropertyValue>& currentValue + ) const override { if (currentValue.isConstant()) { return {}; } else { @@ -503,19 +508,18 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< assert(zoomOutVertexBuffer); return std::tuple, std::optional>{ gfx::attributeBinding(*patternToVertexBuffer), - gfx::attributeBinding(crossfade.fromScale == 2 ? *zoomInVertexBuffer : *zoomOutVertexBuffer) - }; + gfx::attributeBinding(crossfade.fromScale == 2 ? *zoomInVertexBuffer : *zoomOutVertexBuffer)}; } - return std::tuple, std::optional>{std::nullopt, std::nullopt}; + return std::tuple, std::optional>{ + std::nullopt, std::nullopt}; } } - std::tuple interpolationFactor(float) const override { - return std::tuple { 0.0f, 0.0f }; - } + std::tuple interpolationFactor(float) const override { return std::tuple{0.0f, 0.0f}; } - std::tuple, std::array> uniformValue(const PossiblyEvaluatedPropertyValue>& ) const override { + std::tuple, std::array> + uniformValue(const PossiblyEvaluatedPropertyValue>&) const override { // Uniform values for vertex attribute arrays are unused. return {}; } @@ -536,12 +540,15 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< template struct CreateBinder { template - static std::unique_ptr> create(const PossiblyEvaluatedType& value, float zoom, T defaultValue) { + static std::unique_ptr> create( + const PossiblyEvaluatedType& value, float zoom, T defaultValue + ) { return value.match( - [&] (const T& constant) -> std::unique_ptr> { + [&](const T& constant) -> std::unique_ptr> { return std::make_unique>(constant); }, - [&] (const style::PropertyExpression& expression) -> std::unique_ptr> { + [&](const style::PropertyExpression& expression + ) -> std::unique_ptr> { if (expression.isZoomConstant()) { return std::make_unique>(expression, defaultValue); } else { @@ -555,21 +562,31 @@ struct CreateBinder { template struct CreateBinder>> { template - static std::unique_ptr, PossiblyEvaluatedPropertyValue>, A1, A2>> create(const PossiblyEvaluatedPropertyValue>& value, float zoom, T defaultValue) { + static std::unique_ptr< + PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2>> + create(const PossiblyEvaluatedPropertyValue>& value, float zoom, T defaultValue) { return value.match( - [&] (const Faded& constant) -> std::unique_ptr, PossiblyEvaluatedPropertyValue>, A1, A2>> { + [&](const Faded& constant) + -> std::unique_ptr< + PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2>> { return std::make_unique>(constant); }, - [&] (const style::PropertyExpression& expression) -> std::unique_ptr, PossiblyEvaluatedPropertyValue>, A1, A2>> { - return std::make_unique>(expression, zoom, defaultValue); + [&](const style::PropertyExpression& expression) + -> std::unique_ptr< + PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2>> { + return std::make_unique>( + expression, zoom, defaultValue + ); } ); } }; template -std::unique_ptr> -PaintPropertyBinder::create(const PossiblyEvaluatedType& value, float zoom, T defaultValue) { +std::unique_ptr> +PaintPropertyBinder::create( + const PossiblyEvaluatedType& value, float zoom, T defaultValue +) { return CreateBinder::template create(value, zoom, defaultValue); } @@ -581,9 +598,7 @@ struct ZoomInterpolatedAttribute : public Attr { template struct InterpolationUniform { using Value = float; - static constexpr auto name() { - return concat_literals<&Attr::name, &string_literal<'_', 't'>::value>::value(); - } + static constexpr auto name() { return concat_literals<&Attr::name, &string_literal<'_', 't'>::value>::value(); } }; template @@ -603,15 +618,17 @@ class PaintPropertyBinders> { }; template - using Property = Detail; + using Property = Detail< + typename P::Type, + typename P::Uniform::Value, + typename P::PossiblyEvaluatedType, + typename P::AttributeList>; public: template using Binder = typename Property

::Binder; - using Binders = IndexedTuple< - TypeList, - TypeList>...>>; + using Binders = IndexedTuple, TypeList>...>>; template PaintPropertyBinders(const EvaluatedProperties& properties, float z) @@ -622,34 +639,38 @@ class PaintPropertyBinders> { PaintPropertyBinders(PaintPropertyBinders&&) noexcept = default; PaintPropertyBinders(const PaintPropertyBinders&) = delete; - void populateVertexVectors(const GeometryTileFeature& feature, - std::size_t length, - std::size_t index, - const ImagePositions& patternPositions, - const std::optional& patternDependencies, - const CanonicalTileID& canonical, - const style::expression::Value& formattedSection = {}) { - util::ignore({(binders.template get()->populateVertexVector( - feature, length, index, patternPositions, patternDependencies, canonical, formattedSection), - 0)...}); + void populateVertexVectors( + const GeometryTileFeature& feature, + std::size_t length, + std::size_t index, + const ImagePositions& patternPositions, + const std::optional& patternDependencies, + const CanonicalTileID& canonical, + const style::expression::Value& formattedSection = {} + ) { + util::ignore( + {(binders.template get()->populateVertexVector( + feature, length, index, patternPositions, patternDependencies, canonical, formattedSection + ), + 0)...} + ); } - void updateVertexVectors(const FeatureStates& states, const GeometryTileLayer& layer, - const ImagePositions& imagePositions) { + void updateVertexVectors( + const FeatureStates& states, const GeometryTileLayer& layer, const ImagePositions& imagePositions + ) { util::ignore({(binders.template get()->updateVertexVectors(states, layer, imagePositions), 0)...}); } - void setPatternParameters(const std::optional& posA, const std::optional& posB, const CrossfadeParameters& crossfade) const { - util::ignore({ - (binders.template get()->setPatternParameters(posA, posB, crossfade), 0)... - }); + void setPatternParameters( + const std::optional& posA, + const std::optional& posB, + const CrossfadeParameters& crossfade + ) const { + util::ignore({(binders.template get()->setPatternParameters(posA, posB, crossfade), 0)...}); } - void upload(gfx::UploadPass& uploadPass) { - util::ignore({ - (binders.template get()->upload(uploadPass), 0)... - }); - } + void upload(gfx::UploadPass& uploadPass) { util::ignore({(binders.template get()->upload(uploadPass), 0)...}); } template using ZoomInterpolatedAttributeList = typename Property

::ZoomInterpolatedAttributeList; @@ -661,9 +682,8 @@ class PaintPropertyBinders> { template AttributeBindings attributeBindings(const EvaluatedProperties& currentProperties) const { - return AttributeBindings { std::tuple_cat( - binders.template get()->attributeBinding(currentProperties.template get())... - ) }; + return AttributeBindings{ + std::tuple_cat(binders.template get()->attributeBinding(currentProperties.template get())...)}; } using UniformList = TypeListConcat..., typename Ps::UniformList...>; @@ -672,13 +692,12 @@ class PaintPropertyBinders> { template UniformValues uniformValues(float currentZoom, EvaluatedProperties& currentProperties) const { (void)currentZoom; // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56958 - return UniformValues ( - std::tuple_cat( - // interpolation uniform values - binders.template get()->interpolationFactor(currentZoom)..., - // uniform values - binders.template get()->uniformValue(currentProperties.template get())...) - ); + return UniformValues(std::tuple_cat( + // interpolation uniform values + binders.template get()->interpolationFactor(currentZoom)..., + // uniform values + binders.template get()->uniformValue(currentProperties.template get())... + )); } template diff --git a/src/mbgl/renderer/paint_property_statistics.hpp b/src/mbgl/renderer/paint_property_statistics.hpp index 2533c4c4f34..295afeea99d 100644 --- a/src/mbgl/renderer/paint_property_statistics.hpp +++ b/src/mbgl/renderer/paint_property_statistics.hpp @@ -15,13 +15,9 @@ class PaintPropertyStatistics { template <> class PaintPropertyStatistics { public: - std::optional max() const { - return _max; - } + std::optional max() const { return _max; } - void add(float value) { - _max = _max ? std::max(*_max, value) : value; - } + void add(float value) { _max = _max ? std::max(*_max, value) : value; } private: std::optional _max; diff --git a/src/mbgl/renderer/pattern_atlas.cpp b/src/mbgl/renderer/pattern_atlas.cpp index 0c2c7a8b3e5..0fe03b6e637 100644 --- a/src/mbgl/renderer/pattern_atlas.cpp +++ b/src/mbgl/renderer/pattern_atlas.cpp @@ -20,8 +20,7 @@ mapbox::ShelfPack::ShelfPackOptions shelfPackOptions() { } // namespace PatternAtlas::PatternAtlas() - : shelfPack(64, 64, shelfPackOptions()) { -} + : shelfPack(64, 64, shelfPackOptions()) {} PatternAtlas::~PatternAtlas() = default; @@ -54,17 +53,17 @@ std::optional PatternAtlas::addPattern(const style::Image::Impl& const uint32_t w = src.size.width; const uint32_t h = src.size.height; - PremultipliedImage::copy(src, atlasImage, { 0, 0 }, { x, y }, { w, h }); + PremultipliedImage::copy(src, atlasImage, {0, 0}, {x, y}, {w, h}); // Add 1 pixel wrapped padding on each side of the image. - PremultipliedImage::copy(src, atlasImage, { 0, h - 1 }, { x, y - 1 }, { w, 1 }); // T - PremultipliedImage::copy(src, atlasImage, { 0, 0 }, { x, y + h }, { w, 1 }); // B - PremultipliedImage::copy(src, atlasImage, { w - 1, 0 }, { x - 1, y }, { 1, h }); // L - PremultipliedImage::copy(src, atlasImage, { 0, 0 }, { x + w, y }, { 1, h }); // R + PremultipliedImage::copy(src, atlasImage, {0, h - 1}, {x, y - 1}, {w, 1}); // T + PremultipliedImage::copy(src, atlasImage, {0, 0}, {x, y + h}, {w, 1}); // B + PremultipliedImage::copy(src, atlasImage, {w - 1, 0}, {x - 1, y}, {1, h}); // L + PremultipliedImage::copy(src, atlasImage, {0, 0}, {x + w, y}, {1, h}); // R dirty = true; - return patterns.emplace(image.id, Pattern { bin, { *bin, image } }).first->second.position; + return patterns.emplace(image.id, Pattern{bin, {*bin, image}}).first->second.position; } void PatternAtlas::removePattern(const std::string& id) { @@ -75,7 +74,7 @@ void PatternAtlas::removePattern(const std::string& id) { const uint32_t y = it->second.bin->y; const uint32_t w = it->second.bin->w; const uint32_t h = it->second.bin->h; - PremultipliedImage::clear(atlasImage, { x, y }, { w, h }); + PremultipliedImage::clear(atlasImage, {x, y}, {w, h}); shelfPack.unref(*it->second.bin); patterns.erase(it); @@ -83,10 +82,7 @@ void PatternAtlas::removePattern(const std::string& id) { } Size PatternAtlas::getPixelSize() const { - return { - static_cast(shelfPack.width()), - static_cast(shelfPack.height()) - }; + return {static_cast(shelfPack.width()), static_cast(shelfPack.height())}; } void PatternAtlas::upload(gfx::UploadPass& uploadPass) { @@ -102,7 +98,7 @@ void PatternAtlas::upload(gfx::UploadPass& uploadPass) { gfx::TextureBinding PatternAtlas::textureBinding() const { assert(atlasTexture); assert(!dirty); - return { atlasTexture->getResource(), gfx::TextureFilterType::Linear }; + return {atlasTexture->getResource(), gfx::TextureFilterType::Linear}; } } // namespace mbgl diff --git a/src/mbgl/renderer/pattern_atlas.hpp b/src/mbgl/renderer/pattern_atlas.hpp index 14c4432c366..de225eb0cef 100644 --- a/src/mbgl/renderer/pattern_atlas.hpp +++ b/src/mbgl/renderer/pattern_atlas.hpp @@ -34,9 +34,7 @@ class PatternAtlas { void upload(gfx::UploadPass&); Size getPixelSize() const; - const PremultipliedImage& getAtlasImageForTests() const { - return atlasImage; - } + const PremultipliedImage& getAtlasImageForTests() const { return atlasImage; } bool isEmpty() const { return patterns.empty(); } @@ -51,5 +49,5 @@ class PatternAtlas { std::optional atlasTexture; bool dirty = true; }; - + } // namespace mbgl diff --git a/src/mbgl/renderer/possibly_evaluated_property_value.hpp b/src/mbgl/renderer/possibly_evaluated_property_value.hpp index cf706ba3bf8..b38e5bebaad 100644 --- a/src/mbgl/renderer/possibly_evaluated_property_value.hpp +++ b/src/mbgl/renderer/possibly_evaluated_property_value.hpp @@ -12,9 +12,7 @@ namespace mbgl { template class PossiblyEvaluatedPropertyValue { private: - using Value = variant< - T, - style::PropertyExpression>; + using Value = variant>; Value value; @@ -23,19 +21,15 @@ class PossiblyEvaluatedPropertyValue { PossiblyEvaluatedPropertyValue(Value v) : value(std::move(v)) {} - bool isConstant() const { - return value.template is(); - } + bool isConstant() const { return value.template is(); } std::optional constant() const { return value.match( - [&] (const T& t) { return std::optional(t); }, - [&] (const auto&) { return std::optional(); }); + [&](const T& t) { return std::optional(t); }, [&](const auto&) { return std::optional(); } + ); } - T constantOr(const T& t) const { - return constant().value_or(t); - } + T constantOr(const T& t) const { return constant().value_or(t); } template auto match(Ts&&... ts) const { @@ -45,8 +39,8 @@ class PossiblyEvaluatedPropertyValue { template T evaluate(const Feature& feature, float zoom, T defaultValue) const { return this->match( - [&] (const T& constant_) { return constant_; }, - [&] (const style::PropertyExpression& expression) { + [&](const T& constant_) { return constant_; }, + [&](const style::PropertyExpression& expression) { return expression.evaluate(zoom, feature, defaultValue); } ); @@ -54,27 +48,29 @@ class PossiblyEvaluatedPropertyValue { template T evaluate(const Feature& feature, float zoom, const CanonicalTileID& canonical, T defaultValue) const { - return this->match([&](const T& constant_) { return constant_; }, - [&](const style::PropertyExpression& expression) { - return expression.evaluate(zoom, feature, canonical, defaultValue); - }); + return this->match( + [&](const T& constant_) { return constant_; }, + [&](const style::PropertyExpression& expression) { + return expression.evaluate(zoom, feature, canonical, defaultValue); + } + ); } template T evaluate(const Feature& feature, float zoom, const FeatureState& featureState, T defaultValue) const { - return this->match([&](const T& constant_) { return constant_; }, - [&](const style::PropertyExpression& expression) { - return expression.evaluate(zoom, feature, featureState, defaultValue); - }); + return this->match( + [&](const T& constant_) { return constant_; }, + [&](const style::PropertyExpression& expression) { + return expression.evaluate(zoom, feature, featureState, defaultValue); + } + ); } }; template class PossiblyEvaluatedPropertyValue> { private: - using Value = variant< - Faded, - style::PropertyExpression>; + using Value = variant, style::PropertyExpression>; Value value; @@ -83,19 +79,16 @@ class PossiblyEvaluatedPropertyValue> { PossiblyEvaluatedPropertyValue(Value v) : value(std::move(v)) {} - bool isConstant() const { - return value.template is>(); - } + bool isConstant() const { return value.template is>(); } std::optional> constant() const { return value.match( - [&] (const Faded& t) { return std::optional>(t); }, - [&] (const auto&) { return std::optional>(); }); + [&](const Faded& t) { return std::optional>(t); }, + [&](const auto&) { return std::optional>(); } + ); } - Faded constantOr(const Faded& t) const { - return constant().value_or(t); - } + Faded constantOr(const Faded& t) const { return constant().value_or(t); } template auto match(Ts&&... ts) const { @@ -103,51 +96,54 @@ class PossiblyEvaluatedPropertyValue> { } template - Faded evaluate(const Feature& feature, - float zoom, - const std::set& availableImages, - const CanonicalTileID& canonical, - T defaultValue) const { + Faded evaluate( + const Feature& feature, + float zoom, + const std::set& availableImages, + const CanonicalTileID& canonical, + T defaultValue + ) const { return this->match( - [&] (const Faded& constant_) { return constant_; }, - [&] (const style::PropertyExpression& expression) { + [&](const Faded& constant_) { return constant_; }, + [&](const style::PropertyExpression& expression) { if (!expression.isZoomConstant()) { - const T min = - expression.evaluate(std::floor(zoom), feature, availableImages, canonical, defaultValue); - const T max = - expression.evaluate(std::floor(zoom) + 1, feature, availableImages, canonical, defaultValue); - return Faded {min, max}; + const T min = expression.evaluate( + std::floor(zoom), feature, availableImages, canonical, defaultValue + ); + const T max = expression.evaluate( + std::floor(zoom) + 1, feature, availableImages, canonical, defaultValue + ); + return Faded{min, max}; } else { const T evaluated = expression.evaluate(feature, availableImages, defaultValue); - return Faded {evaluated, evaluated}; + return Faded{evaluated, evaluated}; } } ); } }; - namespace util { template struct Interpolator> { - PossiblyEvaluatedPropertyValue operator()(const PossiblyEvaluatedPropertyValue& a, - const PossiblyEvaluatedPropertyValue& b, - const double t) const { + PossiblyEvaluatedPropertyValue operator()( + const PossiblyEvaluatedPropertyValue& a, const PossiblyEvaluatedPropertyValue& b, const double t + ) const { if (a.isConstant() && b.isConstant()) { - return { interpolate(*a.constant(), *b.constant(), t) }; + return {interpolate(*a.constant(), *b.constant(), t)}; } else { - return { a }; + return {a}; } } - PossiblyEvaluatedPropertyValue operator()(const PossiblyEvaluatedPropertyValue& a, - const PossiblyEvaluatedPropertyValue& b, - const float t) const { + PossiblyEvaluatedPropertyValue operator()( + const PossiblyEvaluatedPropertyValue& a, const PossiblyEvaluatedPropertyValue& b, const float t + ) const { if (a.isConstant() && b.isConstant()) { - return { interpolate(*a.constant(), *b.constant(), t) }; + return {interpolate(*a.constant(), *b.constant(), t)}; } else { - return { a }; + return {a}; } } }; diff --git a/src/mbgl/renderer/property_evaluation_parameters.hpp b/src/mbgl/renderer/property_evaluation_parameters.hpp index d6cbf9d159f..d4e35c5b24c 100644 --- a/src/mbgl/renderer/property_evaluation_parameters.hpp +++ b/src/mbgl/renderer/property_evaluation_parameters.hpp @@ -21,18 +21,20 @@ class PropertyEvaluationParameters { defaultFadeDuration(0) {} PropertyEvaluationParameters(ZoomHistory zoomHistory_, TimePoint now_, Duration defaultFadeDuration_) - : z(zoomHistory_.lastZoom), now(now_), zoomHistory(zoomHistory_), defaultFadeDuration(defaultFadeDuration_) {} + : z(zoomHistory_.lastZoom), + now(now_), + zoomHistory(zoomHistory_), + defaultFadeDuration(defaultFadeDuration_) {} CrossfadeParameters getCrossfadeParameters() const { const float fraction = z - std::floor(z); const std::chrono::duration d = defaultFadeDuration; const float t = d != std::chrono::duration::zero() - ? std::min((now - zoomHistory.lastIntegerZoomTime) / d, 1.0f) - : 1.0f; + ? std::min((now - zoomHistory.lastIntegerZoomTime) / d, 1.0f) + : 1.0f; - return z > zoomHistory.lastIntegerZoom - ? CrossfadeParameters { 2.0f, 1.0f, fraction + (1.0f - fraction) * t } - : CrossfadeParameters { 0.5f, 1.0f, 1 - (1 - t) * fraction }; + return z > zoomHistory.lastIntegerZoom ? CrossfadeParameters{2.0f, 1.0f, fraction + (1.0f - fraction) * t} + : CrossfadeParameters{0.5f, 1.0f, 1 - (1 - t) * fraction}; } float z; diff --git a/src/mbgl/renderer/render_layer.cpp b/src/mbgl/renderer/render_layer.cpp index 27289f4d650..55c6d526a46 100644 --- a/src/mbgl/renderer/render_layer.cpp +++ b/src/mbgl/renderer/render_layer.cpp @@ -14,8 +14,7 @@ using namespace style; RenderLayer::RenderLayer(Immutable properties) : evaluatedProperties(std::move(properties)), - baseImpl(evaluatedProperties->baseImpl) { -} + baseImpl(evaluatedProperties->baseImpl) {} void RenderLayer::transition(const TransitionParameters& parameters, Immutable newImpl) { baseImpl = std::move(newImpl); @@ -23,8 +22,8 @@ void RenderLayer::transition(const TransitionParameters& parameters, ImmutablegetTypeInfo()->crossTileIndex == style::LayerTypeInfo::CrossTileIndex::Required - && !placementData.empty(); + return baseImpl->getTypeInfo()->crossTileIndex == style::LayerTypeInfo::CrossTileIndex::Required && + !placementData.empty(); } const std::string& RenderLayer::getID() const { @@ -36,8 +35,7 @@ bool RenderLayer::hasRenderPass(RenderPass pass) const { } bool RenderLayer::needsRendering() const { - return passes != RenderPass::None - && baseImpl->visibility != style::VisibilityType::None; + return passes != RenderPass::None && baseImpl->visibility != style::VisibilityType::None; } bool RenderLayer::supportsZoom(float zoom) const { @@ -60,27 +58,34 @@ void RenderLayer::markContextDestroyed() { // no-op } -void RenderLayer::checkRenderability(const PaintParameters& parameters, - const uint32_t activeBindingCount) { +void RenderLayer::checkRenderability(const PaintParameters& parameters, const uint32_t activeBindingCount) { // Only warn once for every layer. if (hasRenderFailures) { return; } if (activeBindingCount > parameters.context.maximumVertexBindingCount) { - Log::Error(Event::OpenGL, - "The layer '" + getID() + "' uses more data-driven properties than the current device " - "supports, and will have rendering errors. To ensure compatibility with this " - "device, use " + std::to_string(activeBindingCount - gfx::Context::minimumRequiredVertexBindingCount) + - " fewer data driven properties in this layer."); + Log::Error( + Event::OpenGL, + "The layer '" + getID() + + "' uses more data-driven properties than the current device " + "supports, and will have rendering errors. To ensure compatibility with this " + "device, use " + + std::to_string(activeBindingCount - gfx::Context::minimumRequiredVertexBindingCount) + + " fewer data driven properties in this layer." + ); hasRenderFailures = true; } else if (activeBindingCount > gfx::Context::minimumRequiredVertexBindingCount) { - Log::Warning(Event::OpenGL, - "The layer '" + getID() + "' uses more data-driven properties than some devices may support. " - "Though it will render correctly on this device, it may have rendering errors " - "on other devices. To ensure compatibility with all devices, use " + - std::to_string(activeBindingCount - gfx::Context::minimumRequiredVertexBindingCount) + "fewer " - "data-driven properties in this layer."); + Log::Warning( + Event::OpenGL, + "The layer '" + getID() + + "' uses more data-driven properties than some devices may support. " + "Though it will render correctly on this device, it may have rendering errors " + "on other devices. To ensure compatibility with all devices, use " + + std::to_string(activeBindingCount - gfx::Context::minimumRequiredVertexBindingCount) + + "fewer " + "data-driven properties in this layer." + ); hasRenderFailures = true; } } @@ -101,5 +106,4 @@ const LayerRenderData* RenderLayer::getRenderDataForPass(const RenderTile& tile, return nullptr; } -} //namespace mbgl - +} // namespace mbgl diff --git a/src/mbgl/renderer/render_layer.hpp b/src/mbgl/renderer/render_layer.hpp index b4ea90e2754..f3b3f14e286 100644 --- a/src/mbgl/renderer/render_layer.hpp +++ b/src/mbgl/renderer/render_layer.hpp @@ -102,8 +102,9 @@ class RenderLayer { // Check wether the given geometry intersects // with the feature - virtual bool queryIntersectsFeature(const GeometryCoordinates&, const GeometryTileFeature&, const float, - const TransformState&, const float, const mat4&, const FeatureState&) const { + virtual bool + queryIntersectsFeature(const GeometryCoordinates&, const GeometryTileFeature&, const float, const TransformState&, const float, const mat4&, const FeatureState&) + const { return false; }; diff --git a/src/mbgl/renderer/render_light.cpp b/src/mbgl/renderer/render_light.cpp index 85768cff474..a3946b329c4 100644 --- a/src/mbgl/renderer/render_light.cpp +++ b/src/mbgl/renderer/render_light.cpp @@ -4,8 +4,7 @@ namespace mbgl { RenderLight::RenderLight(Immutable impl_) : impl(std::move(impl_)), - transitioning(impl->properties.untransitioned()) { -} + transitioning(impl->properties.untransitioned()) {} void RenderLight::transition(const TransitionParameters& parameters) { transitioning = impl->properties.transitioned(parameters, std::move(transitioning)); diff --git a/src/mbgl/renderer/render_light.hpp b/src/mbgl/renderer/render_light.hpp index f13f925318d..42b49b05d46 100644 --- a/src/mbgl/renderer/render_light.hpp +++ b/src/mbgl/renderer/render_light.hpp @@ -9,7 +9,7 @@ class TransitionParameters; class PropertyEvaluationParameters; using TransitioningLight = style::LightProperties::Unevaluated; -using EvaluatedLight = style::LightProperties::PossiblyEvaluated; +using EvaluatedLight = style::LightProperties::PossiblyEvaluated; class RenderLight { public: diff --git a/src/mbgl/renderer/render_orchestrator.cpp b/src/mbgl/renderer/render_orchestrator.cpp index 4a2b018bd2a..2708869cae9 100644 --- a/src/mbgl/renderer/render_orchestrator.cpp +++ b/src/mbgl/renderer/render_orchestrator.cpp @@ -41,7 +41,9 @@ namespace { class LayerRenderItem final : public RenderItem { public: LayerRenderItem(RenderLayer& layer_, RenderSource* source_, uint32_t index_) - : layer(layer_), source(source_), index(index_) {} + : layer(layer_), + source(source_), + index(index_) {} bool operator<(const LayerRenderItem& other) const { return index < other.index; } std::reference_wrapper layer; @@ -57,14 +59,16 @@ class LayerRenderItem final : public RenderItem { class RenderTreeImpl final : public RenderTree { public: - RenderTreeImpl(std::unique_ptr parameters_, - std::set layerRenderItems_, - std::vector> sourceRenderItems_, - LineAtlas& lineAtlas_, - PatternAtlas& patternAtlas_, - RenderLayerReferences layersNeedPlacement_, - Immutable placement_, - bool updateSymbolOpacities_) + RenderTreeImpl( + std::unique_ptr parameters_, + std::set layerRenderItems_, + std::vector> sourceRenderItems_, + LineAtlas& lineAtlas_, + PatternAtlas& patternAtlas_, + RenderLayerReferences layersNeedPlacement_, + Immutable placement_, + bool updateSymbolOpacities_ + ) : RenderTree(std::move(parameters_)), layerRenderItems(std::move(layerRenderItems_)), sourceRenderItems(std::move(sourceRenderItems_)), @@ -80,9 +84,7 @@ class RenderTreeImpl final : public RenderTree { } } - RenderItems getLayerRenderItems() const override { - return { layerRenderItems.begin(), layerRenderItems.end() }; - } + RenderItems getLayerRenderItems() const override { return {layerRenderItems.begin(), layerRenderItems.end()}; } RenderItems getSourceRenderItems() const override { RenderItems result; result.reserve(sourceRenderItems.size()); @@ -101,7 +103,7 @@ class RenderTreeImpl final : public RenderTree { bool updateSymbolOpacities; }; -} // namespace +} // namespace RenderOrchestrator::RenderOrchestrator(bool backgroundLayerAsColor_, const std::optional& localFontFamily_) : observer(&nullObserver()), @@ -136,7 +138,8 @@ void RenderOrchestrator::setObserver(RendererObserver* observer_) { } std::unique_ptr RenderOrchestrator::createRenderTree( - const std::shared_ptr& updateParameters) { + const std::shared_ptr& updateParameters +) { const bool isMapModeContinuous = updateParameters->mode == MapMode::Continuous; if (!isMapModeContinuous) { // Reset zoom history state. @@ -150,29 +153,32 @@ std::unique_ptr RenderOrchestrator::createRenderTree( } } - const bool zoomChanged = - zoomHistory.update(static_cast(updateParameters->transformState.getZoom()), updateParameters->timePoint); + const bool zoomChanged = zoomHistory.update( + static_cast(updateParameters->transformState.getZoom()), updateParameters->timePoint + ); - const TransitionOptions transitionOptions = - isMapModeContinuous ? updateParameters->transitionOptions : TransitionOptions(); + const TransitionOptions transitionOptions = isMapModeContinuous ? updateParameters->transitionOptions + : TransitionOptions(); const TransitionParameters transitionParameters{updateParameters->timePoint, transitionOptions}; const PropertyEvaluationParameters evaluationParameters{ zoomHistory, updateParameters->timePoint, - transitionOptions.duration.value_or(isMapModeContinuous ? util::DEFAULT_TRANSITION_DURATION - : Duration::zero())}; - - const TileParameters tileParameters{updateParameters->pixelRatio, - updateParameters->debugOptions, - updateParameters->transformState, - updateParameters->fileSource, - updateParameters->mode, - updateParameters->annotationManager, - *imageManager, - *glyphManager, - updateParameters->prefetchZoomDelta}; + transitionOptions.duration.value_or( + isMapModeContinuous ? util::DEFAULT_TRANSITION_DURATION : Duration::zero() + )}; + + const TileParameters tileParameters{ + updateParameters->pixelRatio, + updateParameters->debugOptions, + updateParameters->transformState, + updateParameters->fileSource, + updateParameters->mode, + updateParameters->annotationManager, + *imageManager, + *glyphManager, + updateParameters->prefetchZoomDelta}; glyphManager->setURL(updateParameters->glyphURL); @@ -191,7 +197,8 @@ std::unique_ptr RenderOrchestrator::createRenderTree( const ImageDifference imageDiff = diffImages(imageImpls, updateParameters->images); imageImpls = updateParameters->images; - // Only trigger tile reparse for changed images. Changed images only need a relayout when they have a different size. + // Only trigger tile reparse for changed images. Changed images only need a relayout when they have a different + // size. bool hasImageDiff = !imageDiff.removed.empty(); // Remove removed images from sprite atlas. @@ -284,11 +291,13 @@ std::unique_ptr RenderOrchestrator::createRenderTree( const bool tiltedView = transformState.getPitch() != 0.0f; // Create parameters for the render tree. - auto renderTreeParameters = std::make_unique(updateParameters->transformState, - updateParameters->mode, - updateParameters->debugOptions, - updateParameters->timePoint, - renderLight.getEvaluated()); + auto renderTreeParameters = std::make_unique( + updateParameters->transformState, + updateParameters->mode, + updateParameters->debugOptions, + updateParameters->timePoint, + renderLight.getEvaluated() + ); std::set layerRenderItems; layersNeedPlacement.clear(); @@ -315,14 +324,16 @@ std::unique_ptr RenderOrchestrator::createRenderTree( if (layerInfo->source != LayerTypeInfo::Source::NotRequired) { if (layer.baseImpl->source == sourceImpl->id) { const std::string& layerId = layer.getID(); - sourceNeedsRelayout = (sourceNeedsRelayout || hasImageDiff || constantsMaskChanged.count(layerId) || - hasLayoutDifference(layerDiff, layerId)); + sourceNeedsRelayout = + (sourceNeedsRelayout || hasImageDiff || constantsMaskChanged.count(layerId) || + hasLayoutDifference(layerDiff, layerId)); if (layerIsVisible) { filteredLayersForSource.push_back(layer.evaluatedProperties); if (zoomFitsLayer) { sourceNeedsRendering = true; - renderItemsEmplaceHint = - layerRenderItems.emplace_hint(renderItemsEmplaceHint, layer, source, static_cast(index)); + renderItemsEmplaceHint = layerRenderItems.emplace_hint( + renderItemsEmplaceHint, layer, source, static_cast(index) + ); } } } @@ -339,14 +350,12 @@ std::unique_ptr RenderOrchestrator::createRenderTree( // items. } } - renderItemsEmplaceHint = layerRenderItems.emplace_hint(renderItemsEmplaceHint, layer, nullptr, static_cast(index)); + renderItemsEmplaceHint = layerRenderItems.emplace_hint( + renderItemsEmplaceHint, layer, nullptr, static_cast(index) + ); } } - source->update(sourceImpl, - filteredLayersForSource, - sourceNeedsRendering, - sourceNeedsRelayout, - tileParameters); + source->update(sourceImpl, filteredLayersForSource, sourceNeedsRendering, sourceNeedsRelayout, tileParameters); filteredLayersForSource.clear(); } @@ -358,8 +367,8 @@ std::unique_ptr RenderOrchestrator::createRenderTree( // Prepare. Update all matrices and generate data that we should upload to the GPU. for (const auto& entry : renderSources) { if (entry.second->isEnabled()) { - entry.second->prepare( - {renderTreeParameters->transformParams, updateParameters->debugOptions, *imageManager}); + entry.second->prepare({renderTreeParameters->transformParams, updateParameters->debugOptions, *imageManager} + ); } } @@ -367,7 +376,8 @@ std::unique_ptr RenderOrchestrator::createRenderTree( for (auto& renderItem : layerRenderItems) { RenderLayer& renderLayer = renderItem.layer; renderLayer.prepare( - {renderItem.source, *imageManager, *patternAtlas, *lineAtlas, updateParameters->transformState}); + {renderItem.source, *imageManager, *patternAtlas, *lineAtlas, updateParameters->transformState} + ); if (renderLayer.needsPlacement()) { layersNeedPlacement.emplace_back(renderLayer); } @@ -407,7 +417,10 @@ std::unique_ptr RenderOrchestrator::createRenderTree( } renderTreeParameters->placementChanged = !placementController.placementIsRecent( - updateParameters->timePoint, static_cast(updateParameters->transformState.getZoom()), placementUpdatePeriodOverride); + updateParameters->timePoint, + static_cast(updateParameters->transformState.getZoom()), + placementUpdatePeriodOverride + ); symbolBucketsChanged |= renderTreeParameters->placementChanged; if (renderTreeParameters->placementChanged) { Mutable placement = Placement::create(updateParameters, placementController.getPlacement()); @@ -449,17 +462,21 @@ std::unique_ptr RenderOrchestrator::createRenderTree( } } - return std::make_unique(std::move(renderTreeParameters), - std::move(layerRenderItems), - std::move(sourceRenderItems), - *lineAtlas, - *patternAtlas, - std::move(layersNeedPlacement), - placementController.getPlacement(), - symbolBucketsChanged); + return std::make_unique( + std::move(renderTreeParameters), + std::move(layerRenderItems), + std::move(sourceRenderItems), + *lineAtlas, + *patternAtlas, + std::move(layersNeedPlacement), + placementController.getPlacement(), + symbolBucketsChanged + ); } -std::vector RenderOrchestrator::queryRenderedFeatures(const ScreenLineString& geometry, const RenderedQueryOptions& options) const { +std::vector RenderOrchestrator::queryRenderedFeatures( + const ScreenLineString& geometry, const RenderedQueryOptions& options +) const { std::unordered_map layers; if (options.layerIDs) { for (const auto& layerID : *options.layerIDs) { @@ -476,19 +493,23 @@ std::vector RenderOrchestrator::queryRenderedFeatures(const ScreenLineS return queryRenderedFeatures(geometry, options, layers); } -void RenderOrchestrator::queryRenderedSymbols(std::unordered_map>& resultsByLayer, - const ScreenLineString& geometry, - const std::unordered_map& layers, - const RenderedQueryOptions& options) const { - const auto hasCrossTileIndex = [] (const auto& pair) { +void RenderOrchestrator::queryRenderedSymbols( + std::unordered_map>& resultsByLayer, + const ScreenLineString& geometry, + const std::unordered_map& layers, + const RenderedQueryOptions& options +) const { + const auto hasCrossTileIndex = [](const auto& pair) { return pair.second->baseImpl->getTypeInfo()->crossTileIndex == style::LayerTypeInfo::CrossTileIndex::Required; }; std::unordered_map crossTileSymbolIndexLayers; - std::copy_if(layers.begin(), - layers.end(), - std::inserter(crossTileSymbolIndexLayers, crossTileSymbolIndexLayers.begin()), - hasCrossTileIndex); + std::copy_if( + layers.begin(), + layers.end(), + std::inserter(crossTileSymbolIndexLayers, crossTileSymbolIndexLayers.begin()), + hasCrossTileIndex + ); if (crossTileSymbolIndexLayers.empty()) { return; @@ -502,19 +523,24 @@ void RenderOrchestrator::queryRenderedSymbols(std::unordered_maplookupSymbolFeatures(renderedSymbols[queryData.bucketInstanceId], - options, - crossTileSymbolIndexLayers, - queryData.tileID, - queryData.featureSortOrder); + auto bucketSymbols = queryData.featureIndex->lookupSymbolFeatures( + renderedSymbols[queryData.bucketInstanceId], + options, + crossTileSymbolIndexLayers, + queryData.tileID, + queryData.featureSortOrder + ); for (auto layer : bucketSymbols) { auto& resultFeatures = resultsByLayer[layer.first]; @@ -523,7 +549,11 @@ void RenderOrchestrator::queryRenderedSymbols(std::unordered_map RenderOrchestrator::queryRenderedFeatures(const ScreenLineString& geometry, const RenderedQueryOptions& options, const std::unordered_map& layers) const { +std::vector RenderOrchestrator::queryRenderedFeatures( + const ScreenLineString& geometry, + const RenderedQueryOptions& options, + const std::unordered_map& layers +) const { std::unordered_set sourceIDs; std::unordered_map filteredLayers; for (const auto& pair : layers) { @@ -540,8 +570,12 @@ std::vector RenderOrchestrator::queryRenderedFeatures(const ScreenLineS std::unordered_map> resultsByLayer; for (const auto& sourceID : sourceIDs) { if (RenderSource* renderSource = getRenderSource(sourceID)) { - auto sourceResults = renderSource->queryRenderedFeatures(geometry, transformState, filteredLayers, options, projMatrix); - std::move(sourceResults.begin(), sourceResults.end(), std::inserter(resultsByLayer, resultsByLayer.begin())); + auto sourceResults = renderSource->queryRenderedFeatures( + geometry, transformState, filteredLayers, options, projMatrix + ); + std::move( + sourceResults.begin(), sourceResults.end(), std::inserter(resultsByLayer, resultsByLayer.begin()) + ); } } @@ -575,8 +609,13 @@ std::vector RenderOrchestrator::queryShapeAnnotations(const ScreenLineS std::unordered_map shapeAnnotationLayers; RenderedQueryOptions options; for (const auto& layerImpl : *layerImpls) { - if (std::mismatch(layerImpl->id.begin(), layerImpl->id.end(), - AnnotationManager::ShapeLayerID.begin(), AnnotationManager::ShapeLayerID.end()).second == AnnotationManager::ShapeLayerID.end()) { + if (std::mismatch( + layerImpl->id.begin(), + layerImpl->id.end(), + AnnotationManager::ShapeLayerID.begin(), + AnnotationManager::ShapeLayerID.end() + ) + .second == AnnotationManager::ShapeLayerID.end()) { if (const RenderLayer* layer = getRenderLayer(layerImpl->id)) { shapeAnnotationLayers.emplace(layer->getID(), layer); } @@ -586,42 +625,56 @@ std::vector RenderOrchestrator::queryShapeAnnotations(const ScreenLineS return queryRenderedFeatures(geometry, options, shapeAnnotationLayers); } -std::vector RenderOrchestrator::querySourceFeatures(const std::string& sourceID, const SourceQueryOptions& options) const { +std::vector RenderOrchestrator::querySourceFeatures( + const std::string& sourceID, const SourceQueryOptions& options +) const { const RenderSource* source = getRenderSource(sourceID); if (!source) return {}; return source->querySourceFeatures(options); } -FeatureExtensionValue RenderOrchestrator::queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const { +FeatureExtensionValue RenderOrchestrator::queryFeatureExtensions( + const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args +) const { if (RenderSource* renderSource = getRenderSource(sourceID)) { return renderSource->queryFeatureExtensions(feature, extension, extensionField, args); } return {}; } -void RenderOrchestrator::setFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::string& featureID, const FeatureState& state) { +void RenderOrchestrator::setFeatureState( + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID, + const FeatureState& state +) { if (RenderSource* renderSource = getRenderSource(sourceID)) { renderSource->setFeatureState(sourceLayerID, featureID, state); } } -void RenderOrchestrator::getFeatureState(FeatureState& state, const std::string& sourceID, - const std::optional& sourceLayerID, - const std::string& featureID) const { +void RenderOrchestrator::getFeatureState( + FeatureState& state, + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID +) const { if (RenderSource* renderSource = getRenderSource(sourceID)) { renderSource->getFeatureState(state, sourceLayerID, featureID); } } -void RenderOrchestrator::removeFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::optional& featureID, - const std::optional& stateKey) { +void RenderOrchestrator::removeFeatureState( + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::optional& featureID, + const std::optional& stateKey +) { if (RenderSource* renderSource = getRenderSource(sourceID)) { renderSource->removeFeatureState(sourceLayerID, featureID, stateKey); } @@ -692,7 +745,7 @@ bool RenderOrchestrator::hasTransitions(TimePoint timePoint) const { } bool RenderOrchestrator::isLoaded() const { - for (const auto& entry: renderSources) { + for (const auto& entry : renderSources) { if (!entry.second->isLoaded()) { return false; } @@ -718,14 +771,23 @@ void RenderOrchestrator::clearData() { glyphManager->evict(fontStacks(*layerImpls)); } -void RenderOrchestrator::onGlyphsError(const FontStack& fontStack, const GlyphRange& glyphRange, std::exception_ptr error) { - Log::Error(Event::Style, "Failed to load glyph range " + std::to_string(glyphRange.first) + "-" + std::to_string(glyphRange.second) + - " for font stack " + fontStackToString(fontStack) + ": " + util::toString(error)); +void RenderOrchestrator::onGlyphsError( + const FontStack& fontStack, const GlyphRange& glyphRange, std::exception_ptr error +) { + Log::Error( + Event::Style, + "Failed to load glyph range " + std::to_string(glyphRange.first) + "-" + std::to_string(glyphRange.second) + + " for font stack " + fontStackToString(fontStack) + ": " + util::toString(error) + ); observer->onResourceError(error); } void RenderOrchestrator::onTileError(RenderSource& source, const OverscaledTileID& tileID, std::exception_ptr error) { - Log::Error(Event::Style, "Failed to load tile " + util::toString(tileID) + " for source " + source.baseImpl->id + ": " + util::toString(error)); + Log::Error( + Event::Style, + "Failed to load tile " + util::toString(tileID) + " for source " + source.baseImpl->id + ": " + + util::toString(error) + ); observer->onResourceError(error); } diff --git a/src/mbgl/renderer/render_orchestrator.hpp b/src/mbgl/renderer/render_orchestrator.hpp index 95887e6ffb9..7f1894e4d20 100644 --- a/src/mbgl/renderer/render_orchestrator.hpp +++ b/src/mbgl/renderer/render_orchestrator.hpp @@ -33,19 +33,15 @@ class CrossTileSymbolIndex; class RenderTree; namespace style { - class LayerProperties; +class LayerProperties; } // namespace style -class RenderOrchestrator final : public GlyphManagerObserver, - public ImageManagerObserver, - public RenderSourceObserver { +class RenderOrchestrator final : public GlyphManagerObserver, public ImageManagerObserver, public RenderSourceObserver { public: RenderOrchestrator(bool backgroundLayerAsColor_, const std::optional& localFontFamily_); ~RenderOrchestrator() override; - void markContextLost() { - contextLost = true; - }; + void markContextLost() { contextLost = true; }; // TODO: Introduce RenderOrchestratorObserver. void setObserver(RendererObserver*); @@ -55,20 +51,34 @@ class RenderOrchestrator final : public GlyphManagerObserver, std::vector querySourceFeatures(const std::string& sourceID, const SourceQueryOptions&) const; std::vector queryShapeAnnotations(const ScreenLineString&) const; - FeatureExtensionValue queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const; - - void setFeatureState(const std::string& sourceID, const std::optional& layerID, - const std::string& featureID, const FeatureState& state); - - void getFeatureState(FeatureState& state, const std::string& sourceID, const std::optional& layerID, - const std::string& featureID) const; - - void removeFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::optional& featureID, const std::optional& stateKey); + FeatureExtensionValue queryFeatureExtensions( + const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args + ) const; + + void setFeatureState( + const std::string& sourceID, + const std::optional& layerID, + const std::string& featureID, + const FeatureState& state + ); + + void getFeatureState( + FeatureState& state, + const std::string& sourceID, + const std::optional& layerID, + const std::string& featureID + ) const; + + void removeFeatureState( + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::optional& featureID, + const std::optional& stateKey + ); void reduceMemoryUse(); void dumpDebugLogs(); @@ -82,15 +92,19 @@ class RenderOrchestrator final : public GlyphManagerObserver, RenderSource* getRenderSource(const std::string& id) const; - RenderLayer* getRenderLayer(const std::string& id); + RenderLayer* getRenderLayer(const std::string& id); const RenderLayer* getRenderLayer(const std::string& id) const; - - void queryRenderedSymbols(std::unordered_map>& resultsByLayer, - const ScreenLineString& geometry, - const std::unordered_map& layers, - const RenderedQueryOptions& options) const; - - std::vector queryRenderedFeatures(const ScreenLineString&, const RenderedQueryOptions&, const std::unordered_map&) const; + + void queryRenderedSymbols( + std::unordered_map>& resultsByLayer, + const ScreenLineString& geometry, + const std::unordered_map& layers, + const RenderedQueryOptions& options + ) const; + + std::vector + queryRenderedFeatures(const ScreenLineString&, const RenderedQueryOptions&, const std::unordered_map&) + const; // GlyphManagerObserver implementation. void onGlyphsError(const FontStack&, const GlyphRange&, std::exception_ptr) override; diff --git a/src/mbgl/renderer/render_source.cpp b/src/mbgl/renderer/render_source.cpp index f39d3089d7c..624d89073e0 100644 --- a/src/mbgl/renderer/render_source.cpp +++ b/src/mbgl/renderer/render_source.cpp @@ -20,28 +20,28 @@ using namespace style; std::unique_ptr RenderSource::create(const Immutable& impl) { switch (impl->type) { - case SourceType::Vector: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::Raster: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::RasterDEM: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::GeoJSON: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::Video: - assert(false); - return nullptr; - case SourceType::Annotations: - if (LayerManager::annotationsEnabled) { - return std::make_unique(staticImmutableCast(impl)); - } else { + case SourceType::Vector: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::Raster: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::RasterDEM: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::GeoJSON: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::Video: assert(false); return nullptr; - } - case SourceType::Image: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::CustomVector: - return std::make_unique(staticImmutableCast(impl)); + case SourceType::Annotations: + if (LayerManager::annotationsEnabled) { + return std::make_unique(staticImmutableCast(impl)); + } else { + assert(false); + return nullptr; + } + case SourceType::Image: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::CustomVector: + return std::make_unique(staticImmutableCast(impl)); } // Not reachable, but placate GCC. @@ -53,8 +53,7 @@ static RenderSourceObserver nullObserver; RenderSource::RenderSource(Immutable impl) : baseImpl(std::move(impl)), - observer(&nullObserver) { -} + observer(&nullObserver) {} RenderSource::~RenderSource() = default; @@ -74,7 +73,7 @@ bool RenderSource::isEnabled() const { return enabled; } -uint8_t RenderSource::getMaxZoom() const { +uint8_t RenderSource::getMaxZoom() const { assert(false); return util::TERRAIN_RGB_MAXZOOM; } diff --git a/src/mbgl/renderer/render_source.hpp b/src/mbgl/renderer/render_source.hpp index 4ed1253f966..bf7ebe5d2a0 100644 --- a/src/mbgl/renderer/render_source.hpp +++ b/src/mbgl/renderer/render_source.hpp @@ -53,11 +53,8 @@ class RenderSource : protected TileObserver { bool isEnabled() const; virtual bool isLoaded() const = 0; - virtual void update(Immutable, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) = 0; + virtual void + update(Immutable, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) = 0; // Note: calling of this method might reset the contained render data. virtual std::unique_ptr createRenderItem() = 0; // Creates the render data to be passed to the render item. @@ -75,21 +72,19 @@ class RenderSource : protected TileObserver { virtual const ImageSourceRenderData* getImageRenderData() const { return nullptr; } virtual const Tile* getRenderedTile(const UnwrappedTileID&) const { return nullptr; } - virtual std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const = 0; + virtual std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix + ) const = 0; - virtual std::vector - querySourceFeatures(const SourceQueryOptions&) const = 0; + virtual std::vector querySourceFeatures(const SourceQueryOptions&) const = 0; virtual FeatureExtensionValue - queryFeatureExtensions(const Feature&, - const std::string&, - const std::string&, - const std::optional>&) const { + queryFeatureExtensions(const Feature&, const std::string&, const std::string&, const std::optional>&) + const { return {}; } @@ -97,8 +92,9 @@ class RenderSource : protected TileObserver { virtual void getFeatureState(FeatureState&, const std::optional&, const std::string&) const {} - virtual void removeFeatureState(const std::optional&, const std::optional&, - const std::optional&) {} + virtual void + removeFeatureState(const std::optional&, const std::optional&, const std::optional&) { + } virtual void reduceMemoryUse() = 0; diff --git a/src/mbgl/renderer/render_static_data.cpp b/src/mbgl/renderer/render_static_data.cpp index 2522cbaed91..9f48cfcefef 100644 --- a/src/mbgl/renderer/render_static_data.cpp +++ b/src/mbgl/renderer/render_static_data.cpp @@ -7,10 +7,10 @@ namespace mbgl { static gfx::VertexVector> tileVertices() { gfx::VertexVector> result; - result.emplace_back(gfx::Vertex({{{ 0, 0 }}})); - result.emplace_back(gfx::Vertex({{{ util::EXTENT, 0 }}})); - result.emplace_back(gfx::Vertex({{{ 0, util::EXTENT }}})); - result.emplace_back(gfx::Vertex({{{ util::EXTENT, util::EXTENT }}})); + result.emplace_back(gfx::Vertex({{{0, 0}}})); + result.emplace_back(gfx::Vertex({{{util::EXTENT, 0}}})); + result.emplace_back(gfx::Vertex({{{0, util::EXTENT}}})); + result.emplace_back(gfx::Vertex({{{util::EXTENT, util::EXTENT}}})); return result; } @@ -33,24 +33,23 @@ static gfx::IndexVector tileLineStripIndices() { static gfx::VertexVector rasterVertices() { gfx::VertexVector result; - result.emplace_back(RasterProgram::layoutVertex({ 0, 0 }, { 0, 0 })); - result.emplace_back(RasterProgram::layoutVertex({ util::EXTENT, 0 }, { util::EXTENT, 0 })); - result.emplace_back(RasterProgram::layoutVertex({ 0, util::EXTENT }, { 0, util::EXTENT })); - result.emplace_back(RasterProgram::layoutVertex({ util::EXTENT, util::EXTENT }, { util::EXTENT, util::EXTENT })); + result.emplace_back(RasterProgram::layoutVertex({0, 0}, {0, 0})); + result.emplace_back(RasterProgram::layoutVertex({util::EXTENT, 0}, {util::EXTENT, 0})); + result.emplace_back(RasterProgram::layoutVertex({0, util::EXTENT}, {0, util::EXTENT})); + result.emplace_back(RasterProgram::layoutVertex({util::EXTENT, util::EXTENT}, {util::EXTENT, util::EXTENT})); return result; } static gfx::VertexVector heatmapTextureVertices() { gfx::VertexVector result; - result.emplace_back(HeatmapTextureProgram::layoutVertex({ 0, 0 })); - result.emplace_back(HeatmapTextureProgram::layoutVertex({ 1, 0 })); - result.emplace_back(HeatmapTextureProgram::layoutVertex({ 0, 1 })); - result.emplace_back(HeatmapTextureProgram::layoutVertex({ 1, 1 })); + result.emplace_back(HeatmapTextureProgram::layoutVertex({0, 0})); + result.emplace_back(HeatmapTextureProgram::layoutVertex({1, 0})); + result.emplace_back(HeatmapTextureProgram::layoutVertex({0, 1})); + result.emplace_back(HeatmapTextureProgram::layoutVertex({1, 1})); return result; } -RenderStaticData::RenderStaticData(float pixelRatio, - std::unique_ptr&& shaders_) +RenderStaticData::RenderStaticData(float pixelRatio, std::unique_ptr&& shaders_) : programs(ProgramParameters{pixelRatio, false}), shaders(std::move(shaders_)), clippingMaskSegments(tileTriangleSegments()) diff --git a/src/mbgl/renderer/render_tile.cpp b/src/mbgl/renderer/render_tile.cpp index 92a18022b53..153a5586c53 100644 --- a/src/mbgl/renderer/render_tile.cpp +++ b/src/mbgl/renderer/render_tile.cpp @@ -16,53 +16,65 @@ namespace mbgl { using namespace style; -RenderTile::RenderTile(UnwrappedTileID id_, Tile& tile_) : id(id_), tile(tile_) {} +RenderTile::RenderTile(UnwrappedTileID id_, Tile& tile_) + : id(id_), + tile(tile_) {} RenderTile::~RenderTile() = default; -mat4 RenderTile::translateVtxMatrix(const mat4& tileMatrix, - const std::array& translation, - TranslateAnchorType anchor, - const TransformState& state, - const bool inViewportPixelUnits) const { +mat4 RenderTile::translateVtxMatrix( + const mat4& tileMatrix, + const std::array& translation, + TranslateAnchorType anchor, + const TransformState& state, + const bool inViewportPixelUnits +) const { if (translation[0] == 0 && translation[1] == 0) { return tileMatrix; } mat4 vtxMatrix; - const float angle = inViewportPixelUnits ? - (anchor == TranslateAnchorType::Map ? static_cast(state.getBearing()) : 0.0f) : - (anchor == TranslateAnchorType::Viewport ? static_cast(-state.getBearing()) : 0.0f); + const float angle = inViewportPixelUnits + ? (anchor == TranslateAnchorType::Map ? static_cast(state.getBearing()) : 0.0f) + : (anchor == TranslateAnchorType::Viewport ? static_cast(-state.getBearing()) : 0.0f + ); - Point translate = util::rotate(Point{ translation[0], translation[1] }, angle); + Point translate = util::rotate(Point{translation[0], translation[1]}, angle); if (inViewportPixelUnits) { matrix::translate(vtxMatrix, tileMatrix, translate.x, translate.y, 0); } else { - matrix::translate(vtxMatrix, tileMatrix, - id.pixelsToTileUnits(translate.x, static_cast(state.getZoom())), - id.pixelsToTileUnits(translate.y, static_cast(state.getZoom())), - 0); + matrix::translate( + vtxMatrix, + tileMatrix, + id.pixelsToTileUnits(translate.x, static_cast(state.getZoom())), + id.pixelsToTileUnits(translate.y, static_cast(state.getZoom())), + 0 + ); } return vtxMatrix; } -mat4 RenderTile::translatedMatrix(const std::array& translation, - TranslateAnchorType anchor, - const TransformState& state) const { +mat4 RenderTile::translatedMatrix( + const std::array& translation, TranslateAnchorType anchor, const TransformState& state +) const { return translateVtxMatrix(matrix, translation, anchor, state, false); } -mat4 RenderTile::translatedClipMatrix(const std::array& translation, - TranslateAnchorType anchor, - const TransformState& state) const { +mat4 RenderTile::translatedClipMatrix( + const std::array& translation, TranslateAnchorType anchor, const TransformState& state +) const { return translateVtxMatrix(nearClippedMatrix, translation, anchor, state, false); } -const OverscaledTileID& RenderTile::getOverscaledTileID() const { return tile.id; } -bool RenderTile::holdForFade() const { return tile.holdForFade(); } +const OverscaledTileID& RenderTile::getOverscaledTileID() const { + return tile.id; +} +bool RenderTile::holdForFade() const { + return tile.holdForFade(); +} Bucket* RenderTile::getBucket(const style::Layer::Impl& impl) const { assert(renderData); @@ -106,14 +118,12 @@ void RenderTile::prepare(const SourcePrepareParameters& parameters) { needsRendering = tile.usedByRenderedLayers; if (parameters.debugOptions != MapDebugOptions::NoDebug && - (!debugBucket || debugBucket->renderable != tile.isRenderable() || - debugBucket->complete != tile.isComplete() || - !(debugBucket->modified == tile.modified) || - !(debugBucket->expires == tile.expires) || + (!debugBucket || debugBucket->renderable != tile.isRenderable() || debugBucket->complete != tile.isComplete() || + !(debugBucket->modified == tile.modified) || !(debugBucket->expires == tile.expires) || debugBucket->debugMode != parameters.debugOptions)) { debugBucket = std::make_unique( - tile.id, tile.isRenderable(), tile.isComplete(), tile.modified, tile.expires, - parameters.debugOptions); + tile.id, tile.isRenderable(), tile.isComplete(), tile.modified, tile.expires, parameters.debugOptions + ); } else if (parameters.debugOptions == MapDebugOptions::NoDebug) { debugBucket.reset(); } @@ -128,10 +138,9 @@ void RenderTile::prepare(const SourcePrepareParameters& parameters) { } void RenderTile::finishRender(PaintParameters& parameters) const { - if (!needsRendering || parameters.debugOptions == MapDebugOptions::NoDebug) - return; + if (!needsRendering || parameters.debugOptions == MapDebugOptions::NoDebug) return; - static const style::Properties<>::PossiblyEvaluated properties {}; + static const style::Properties<>::PossiblyEvaluated properties{}; static const DebugProgram::Binders paintAttributeData(properties, 0); auto program = parameters.shaders.get(); @@ -141,48 +150,57 @@ void RenderTile::finishRender(PaintParameters& parameters) const { if (parameters.debugOptions & (MapDebugOptions::Timestamps | MapDebugOptions::ParseStatus)) { assert(debugBucket); - const auto allAttributeBindings = - DebugProgram::computeAllAttributeBindings(*debugBucket->vertexBuffer, paintAttributeData, properties); - - program->draw(parameters.context, - *parameters.renderPass, - gfx::Lines{4.0f * parameters.pixelRatio}, - gfx::DepthMode::disabled(), - gfx::StencilMode::disabled(), - gfx::ColorMode::unblended(), - gfx::CullFaceMode::disabled(), - *debugBucket->indexBuffer, - debugBucket->segments, - DebugProgram::computeAllUniformValues( - DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), - uniforms::color::Value(Color::white()), - uniforms::overlay_scale::Value(1.0f)}, - paintAttributeData, - properties, - static_cast(parameters.state.getZoom())), - allAttributeBindings, - DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, - "text-outline"); - - program->draw(parameters.context, - *parameters.renderPass, - gfx::Lines{2.0f * parameters.pixelRatio}, - gfx::DepthMode::disabled(), - gfx::StencilMode::disabled(), - gfx::ColorMode::unblended(), - gfx::CullFaceMode::disabled(), - *debugBucket->indexBuffer, - debugBucket->segments, - DebugProgram::computeAllUniformValues( - DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), - uniforms::color::Value(Color::black()), - uniforms::overlay_scale::Value(1.0f)}, - paintAttributeData, - properties, - static_cast(parameters.state.getZoom())), - allAttributeBindings, - DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, - "text"); + const auto allAttributeBindings = DebugProgram::computeAllAttributeBindings( + *debugBucket->vertexBuffer, paintAttributeData, properties + ); + + program->draw( + parameters.context, + *parameters.renderPass, + gfx::Lines{4.0f * parameters.pixelRatio}, + gfx::DepthMode::disabled(), + gfx::StencilMode::disabled(), + gfx::ColorMode::unblended(), + gfx::CullFaceMode::disabled(), + *debugBucket->indexBuffer, + debugBucket->segments, + DebugProgram::computeAllUniformValues( + DebugProgram::LayoutUniformValues{ + uniforms::matrix::Value(matrix), + uniforms::color::Value(Color::white()), + uniforms::overlay_scale::Value(1.0f)}, + paintAttributeData, + properties, + static_cast(parameters.state.getZoom()) + ), + allAttributeBindings, + DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, + "text-outline" + ); + + program->draw( + parameters.context, + *parameters.renderPass, + gfx::Lines{2.0f * parameters.pixelRatio}, + gfx::DepthMode::disabled(), + gfx::StencilMode::disabled(), + gfx::ColorMode::unblended(), + gfx::CullFaceMode::disabled(), + *debugBucket->indexBuffer, + debugBucket->segments, + DebugProgram::computeAllUniformValues( + DebugProgram::LayoutUniformValues{ + uniforms::matrix::Value(matrix), + uniforms::color::Value(Color::black()), + uniforms::overlay_scale::Value(1.0f)}, + paintAttributeData, + properties, + static_cast(parameters.state.getZoom()) + ), + allAttributeBindings, + DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, + "text" + ); } if (parameters.debugOptions & MapDebugOptions::TileBorders) { @@ -201,16 +219,20 @@ void RenderTile::finishRender(PaintParameters& parameters) const { *parameters.staticData.tileBorderIndexBuffer, debugBucket->tileBorderSegments, DebugProgram::computeAllUniformValues( - DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), - uniforms::color::Value(Color::red()), - uniforms::overlay_scale::Value(1.0f)}, + DebugProgram::LayoutUniformValues{ + uniforms::matrix::Value(matrix), + uniforms::color::Value(Color::red()), + uniforms::overlay_scale::Value(1.0f)}, paintAttributeData, properties, - static_cast(parameters.state.getZoom())), + static_cast(parameters.state.getZoom()) + ), DebugProgram::computeAllAttributeBindings( - *parameters.staticData.tileVertexBuffer, paintAttributeData, properties), + *parameters.staticData.tileVertexBuffer, paintAttributeData, properties + ), DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, - "border"); + "border" + ); } } diff --git a/src/mbgl/renderer/render_tile.hpp b/src/mbgl/renderer/render_tile.hpp index 9f4dc0db2e5..28d7277a7d5 100644 --- a/src/mbgl/renderer/render_tile.hpp +++ b/src/mbgl/renderer/render_tile.hpp @@ -41,13 +41,13 @@ class RenderTile final { // Contains the tile ID string for painting debug information. std::unique_ptr debugBucket; - mat4 translatedMatrix(const std::array& translation, - style::TranslateAnchorType anchor, - const TransformState&) const; + mat4 + translatedMatrix(const std::array& translation, style::TranslateAnchorType anchor, const TransformState&) + const; - mat4 translatedClipMatrix(const std::array& translation, - style::TranslateAnchorType anchor, - const TransformState&) const; + mat4 + translatedClipMatrix(const std::array& translation, style::TranslateAnchorType anchor, const TransformState&) + const; const OverscaledTileID& getOverscaledTileID() const; bool holdForFade() const; @@ -62,11 +62,13 @@ class RenderTile final { void prepare(const SourcePrepareParameters&); void finishRender(PaintParameters&) const; - mat4 translateVtxMatrix(const mat4& tileMatrix, - const std::array& translation, - style::TranslateAnchorType anchor, - const TransformState& state, - bool inViewportPixelUnits) const; + mat4 translateVtxMatrix( + const mat4& tileMatrix, + const std::array& translation, + style::TranslateAnchorType anchor, + const TransformState& state, + bool inViewportPixelUnits + ) const; void setFeatureState(const LayerFeatureStates&); diff --git a/src/mbgl/renderer/render_tree.hpp b/src/mbgl/renderer/render_tree.hpp index 4c505995db8..0665ba7b989 100644 --- a/src/mbgl/renderer/render_tree.hpp +++ b/src/mbgl/renderer/render_tree.hpp @@ -23,18 +23,20 @@ class RenderItem { virtual void upload(gfx::UploadPass&) const = 0; virtual void render(PaintParameters&) const = 0; virtual bool hasRenderPass(RenderPass) const = 0; - virtual const std::string& getName() const = 0; + virtual const std::string& getName() const = 0; }; using RenderItems = std::vector>; class RenderTreeParameters { public: - explicit RenderTreeParameters(const TransformState& state_, - MapMode mapMode_, - MapDebugOptions debugOptions_, - TimePoint timePoint_, - EvaluatedLight light_) + explicit RenderTreeParameters( + const TransformState& state_, + MapMode mapMode_, + MapDebugOptions debugOptions_, + TimePoint timePoint_, + EvaluatedLight light_ + ) : transformParams(state_), mapMode(mapMode_), debugOptions(debugOptions_), @@ -65,9 +67,8 @@ class RenderTree { virtual LineAtlas& getLineAtlas() const = 0; virtual PatternAtlas& getPatternAtlas() const = 0; // Parameters - const RenderTreeParameters& getParameters() const { - return *parameters; - } + const RenderTreeParameters& getParameters() const { return *parameters; } + protected: RenderTree(std::unique_ptr parameters_) : parameters(std::move(parameters_)) { @@ -76,5 +77,4 @@ class RenderTree { std::unique_ptr parameters; }; - } // namespace mbgl diff --git a/src/mbgl/renderer/renderer.cpp b/src/mbgl/renderer/renderer.cpp index 5a2110b32f7..9ee23162f72 100644 --- a/src/mbgl/renderer/renderer.cpp +++ b/src/mbgl/renderer/renderer.cpp @@ -12,7 +12,7 @@ Renderer::Renderer(gfx::RendererBackend& backend, float pixelRatio_, const std:: : impl(std::make_unique(backend, pixelRatio_, localFontFamily_)) {} Renderer::~Renderer() { - gfx::BackendScope guard { impl->backend }; + gfx::BackendScope guard{impl->backend}; impl.reset(); } @@ -33,24 +33,20 @@ void Renderer::render(const std::shared_ptr& updateParameters) } } -std::vector Renderer::queryRenderedFeatures(const ScreenLineString& geometry, const RenderedQueryOptions& options) const { +std::vector Renderer::queryRenderedFeatures( + const ScreenLineString& geometry, const RenderedQueryOptions& options +) const { return impl->orchestrator.queryRenderedFeatures(geometry, options); } -std::vector Renderer::queryRenderedFeatures(const ScreenCoordinate& point, const RenderedQueryOptions& options) const { - return impl->orchestrator.queryRenderedFeatures({ point }, options); +std::vector Renderer::queryRenderedFeatures(const ScreenCoordinate& point, const RenderedQueryOptions& options) + const { + return impl->orchestrator.queryRenderedFeatures({point}, options); } std::vector Renderer::queryRenderedFeatures(const ScreenBox& box, const RenderedQueryOptions& options) const { return impl->orchestrator.queryRenderedFeatures( - { - box.min, - {box.max.x, box.min.y}, - box.max, - {box.min.x, box.max.y}, - box.min - }, - options + {box.min, {box.max.x, box.min.y}, box.max, {box.min.x, box.max.y}, box.min}, options ); } @@ -59,7 +55,7 @@ AnnotationIDs Renderer::queryPointAnnotations(const ScreenBox& box) const { return {}; } RenderedQueryOptions options; - options.layerIDs = {{ AnnotationManager::PointLayerID }}; + options.layerIDs = {{AnnotationManager::PointLayerID}}; auto features = queryRenderedFeatures(box, options); return getAnnotationIDs(features); } @@ -68,22 +64,18 @@ AnnotationIDs Renderer::queryShapeAnnotations(const ScreenBox& box) const { if (!LayerManager::annotationsEnabled) { return {}; } - auto features = impl->orchestrator.queryShapeAnnotations({ - box.min, - {box.max.x, box.min.y}, - box.max, - {box.min.x, box.max.y}, - box.min - }); + auto features = impl->orchestrator.queryShapeAnnotations( + {box.min, {box.max.x, box.min.y}, box.max, {box.min.x, box.max.y}, box.min} + ); return getAnnotationIDs(features); } - + AnnotationIDs Renderer::getAnnotationIDs(const std::vector& features) const { if (!LayerManager::annotationsEnabled) { return {}; } std::set set; - for (auto &feature : features) { + for (auto& feature : features) { assert(feature.id.is()); assert(feature.id.get() <= std::numeric_limits::max()); set.insert(static_cast(feature.id.get())); @@ -94,30 +86,45 @@ AnnotationIDs Renderer::getAnnotationIDs(const std::vector& features) c return ids; } -std::vector Renderer::querySourceFeatures(const std::string& sourceID, const SourceQueryOptions& options) const { +std::vector Renderer::querySourceFeatures(const std::string& sourceID, const SourceQueryOptions& options) + const { return impl->orchestrator.querySourceFeatures(sourceID, options); } -FeatureExtensionValue Renderer::queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const { +FeatureExtensionValue Renderer::queryFeatureExtensions( + const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args +) const { return impl->orchestrator.queryFeatureExtensions(sourceID, feature, extension, extensionField, args); } -void Renderer::setFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::string& featureID, const FeatureState& state) { +void Renderer::setFeatureState( + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID, + const FeatureState& state +) { impl->orchestrator.setFeatureState(sourceID, sourceLayerID, featureID, state); } -void Renderer::getFeatureState(FeatureState& state, const std::string& sourceID, - const std::optional& sourceLayerID, const std::string& featureID) const { +void Renderer::getFeatureState( + FeatureState& state, + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID +) const { impl->orchestrator.getFeatureState(state, sourceID, sourceLayerID, featureID); } -void Renderer::removeFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::optional& featureID, const std::optional& stateKey) { +void Renderer::removeFeatureState( + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::optional& featureID, + const std::optional& stateKey +) { impl->orchestrator.removeFeatureState(sourceID, sourceLayerID, featureID, stateKey); } @@ -134,7 +141,7 @@ const std::vector& Renderer::getPlacedSymbolsData() const { } void Renderer::reduceMemoryUse() { - gfx::BackendScope guard { impl->backend }; + gfx::BackendScope guard{impl->backend}; impl->reduceMemoryUse(); impl->orchestrator.reduceMemoryUse(); } diff --git a/src/mbgl/renderer/renderer_impl.cpp b/src/mbgl/renderer/renderer_impl.cpp index 1c1fe7f973c..ce25b0eb127 100644 --- a/src/mbgl/renderer/renderer_impl.cpp +++ b/src/mbgl/renderer/renderer_impl.cpp @@ -25,7 +25,9 @@ static RendererObserver& nullObserver() { return observer; } -Renderer::Impl::Impl(gfx::RendererBackend& backend_, float pixelRatio_, const std::optional& localFontFamily_) +Renderer::Impl::Impl( + gfx::RendererBackend& backend_, float pixelRatio_, const std::optional& localFontFamily_ +) : orchestrator(!backend_.contextIsShared(), localFontFamily_), backend(backend_), observer(&nullObserver()), @@ -48,8 +50,7 @@ void Renderer::Impl::render(const RenderTree& renderTree) { const auto& renderTreeParameters = renderTree.getParameters(); if (!staticData) { - staticData = std::make_unique(pixelRatio, - std::make_unique()); + staticData = std::make_unique(pixelRatio, std::make_unique()); staticData->programs.registerWith(*staticData->shaders); observer->onRegisterShaders(*staticData->shaders); } @@ -60,7 +61,7 @@ void Renderer::Impl::render(const RenderTree& renderTree) { // Blocks execution until the renderable is available. backend.getDefaultRenderable().wait(); - PaintParameters parameters { + PaintParameters parameters{ context, pixelRatio, backend, @@ -71,8 +72,7 @@ void Renderer::Impl::render(const RenderTree& renderTree) { renderTreeParameters.transformParams, *staticData, renderTree.getLineAtlas(), - renderTree.getPatternAtlas() - }; + renderTree.getPatternAtlas()}; parameters.symbolFadeChange = renderTreeParameters.symbolFadeChange; parameters.opaquePassCutoff = renderTreeParameters.opaquePassCutOff; @@ -108,7 +108,9 @@ void Renderer::Impl::render(const RenderTree& renderTree) { if (!parameters.staticData.depthRenderbuffer || parameters.staticData.depthRenderbuffer->getSize() != parameters.staticData.backendSize) { parameters.staticData.depthRenderbuffer = - parameters.context.createRenderbuffer(parameters.staticData.backendSize); + parameters.context.createRenderbuffer( + parameters.staticData.backendSize + ); } parameters.staticData.depthRenderbuffer->setShouldClear(true); @@ -133,7 +135,9 @@ void Renderer::Impl::render(const RenderTree& renderTree) { } else if (!backend.contextIsShared()) { color = renderTreeParameters.backgroundColor; } - parameters.renderPass = parameters.encoder->createRenderPass("main buffer", { parameters.backend.getDefaultRenderable(), color, 1.0f, 0 }); + parameters.renderPass = parameters.encoder->createRenderPass( + "main buffer", {parameters.backend.getDefaultRenderable(), color, 1.0f, 0} + ); } // Actually render the layers diff --git a/src/mbgl/renderer/renderer_impl.hpp b/src/mbgl/renderer/renderer_impl.hpp index 4057864a779..ca137d9b376 100644 --- a/src/mbgl/renderer/renderer_impl.hpp +++ b/src/mbgl/renderer/renderer_impl.hpp @@ -23,7 +23,7 @@ class Renderer::Impl { private: friend class Renderer; - + void setObserver(RendererObserver*); void render(const RenderTree&); diff --git a/src/mbgl/renderer/source_state.cpp b/src/mbgl/renderer/source_state.cpp index 1c734225a68..58a326599db 100644 --- a/src/mbgl/renderer/source_state.cpp +++ b/src/mbgl/renderer/source_state.cpp @@ -5,8 +5,9 @@ namespace mbgl { -void SourceFeatureState::updateState(const std::optional& sourceLayerID, const std::string& featureID, - const FeatureState& newState) { +void SourceFeatureState::updateState( + const std::optional& sourceLayerID, const std::string& featureID, const FeatureState& newState +) { std::string sourceLayer = sourceLayerID.value_or(std::string()); for (const auto& state : newState) { auto& layerStates = stateChanges[sourceLayer]; @@ -15,8 +16,9 @@ void SourceFeatureState::updateState(const std::optional& sourceLay } } -void SourceFeatureState::getState(FeatureState& result, const std::optional& sourceLayerID, - const std::string& featureID) const { +void SourceFeatureState::getState( + FeatureState& result, const std::optional& sourceLayerID, const std::string& featureID +) const { std::string sourceLayer = sourceLayerID.value_or(std::string()); FeatureState current; FeatureState changes; @@ -101,8 +103,11 @@ void SourceFeatureState::coalesceChanges(std::vector& tiles) { } } -void SourceFeatureState::removeState(const std::optional& sourceLayerID, const std::optional& featureID, - const std::optional& stateKey) { +void SourceFeatureState::removeState( + const std::optional& sourceLayerID, + const std::optional& featureID, + const std::optional& stateKey +) { std::string sourceLayer = sourceLayerID.value_or(std::string()); bool sourceLayerDeleted = (deletedStates.count(sourceLayer) > 0) && deletedStates[sourceLayer].empty(); @@ -115,8 +120,8 @@ void SourceFeatureState::removeState(const std::optional& sourceLay deletedStates[sourceLayer][*featureID][*stateKey] = {}; } } else if (featureID) { - bool updateInQueue = - (stateChanges.count(sourceLayer) != 0U) && (stateChanges[sourceLayer].count(*featureID) != 0U); + bool updateInQueue = (stateChanges.count(sourceLayer) != 0U) && + (stateChanges[sourceLayer].count(*featureID) != 0U); if (updateInQueue) { for (const auto& changeEntry : stateChanges[sourceLayer][*featureID]) { deletedStates[sourceLayer][*featureID][changeEntry.first] = {}; diff --git a/src/mbgl/renderer/source_state.hpp b/src/mbgl/renderer/source_state.hpp index ff775fa2f86..bda09b1ce35 100644 --- a/src/mbgl/renderer/source_state.hpp +++ b/src/mbgl/renderer/source_state.hpp @@ -12,11 +12,16 @@ class SourceFeatureState { SourceFeatureState() = default; ~SourceFeatureState() = default; - void updateState(const std::optional& sourceLayerID, const std::string& featureID, - const FeatureState& newState); - void getState(FeatureState& result, const std::optional& sourceLayerID, const std::string& featureID) const; - void removeState(const std::optional& sourceLayerID, const std::optional& featureID, - const std::optional& stateKey); + void updateState( + const std::optional& sourceLayerID, const std::string& featureID, const FeatureState& newState + ); + void getState(FeatureState& result, const std::optional& sourceLayerID, const std::string& featureID) + const; + void removeState( + const std::optional& sourceLayerID, + const std::optional& featureID, + const std::optional& stateKey + ); void coalesceChanges(std::vector& tiles); diff --git a/src/mbgl/renderer/sources/render_custom_geometry_source.cpp b/src/mbgl/renderer/sources/render_custom_geometry_source.cpp index 841e3f363fc..5d413cd7b67 100644 --- a/src/mbgl/renderer/sources/render_custom_geometry_source.cpp +++ b/src/mbgl/renderer/sources/render_custom_geometry_source.cpp @@ -16,11 +16,13 @@ const style::CustomGeometrySource::Impl& RenderCustomGeometrySource::impl() cons return static_cast(*baseImpl); } -void RenderCustomGeometrySource::update(Immutable baseImpl_, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) { +void RenderCustomGeometrySource::update( + Immutable baseImpl_, + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters +) { if (baseImpl != baseImpl_) { std::swap(baseImpl, baseImpl_); @@ -40,18 +42,21 @@ void RenderCustomGeometrySource::update(Immutable baseImpl_ return; } - tilePyramid.update(layers, - needsRendering, - needsRelayout, - parameters, - *baseImpl, - util::tileSize_I, - impl().getZoomRange(), - {}, - [&](const OverscaledTileID& tileID) { - return std::make_unique( - tileID, impl().id, parameters, impl().getTileOptions(), *tileLoader); - }); + tilePyramid.update( + layers, + needsRendering, + needsRelayout, + parameters, + *baseImpl, + util::tileSize_I, + impl().getZoomRange(), + {}, + [&](const OverscaledTileID& tileID) { + return std::make_unique( + tileID, impl().id, parameters, impl().getTileOptions(), *tileLoader + ); + } + ); } } // namespace mbgl diff --git a/src/mbgl/renderer/sources/render_custom_geometry_source.hpp b/src/mbgl/renderer/sources/render_custom_geometry_source.hpp index e94af0473f0..04781d3b03a 100644 --- a/src/mbgl/renderer/sources/render_custom_geometry_source.hpp +++ b/src/mbgl/renderer/sources/render_custom_geometry_source.hpp @@ -9,12 +9,10 @@ class RenderCustomGeometrySource final : public RenderTileSource { public: explicit RenderCustomGeometrySource(Immutable); - void update(Immutable, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) override; - + void + update(Immutable, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) + override; + private: const style::CustomGeometrySource::Impl& impl() const; }; diff --git a/src/mbgl/renderer/sources/render_geojson_source.cpp b/src/mbgl/renderer/sources/render_geojson_source.cpp index e0cb9f3b494..74de95fb212 100644 --- a/src/mbgl/renderer/sources/render_geojson_source.cpp +++ b/src/mbgl/renderer/sources/render_geojson_source.cpp @@ -12,7 +12,7 @@ using namespace style; namespace { -template +template std::optional getProperty(const C& cont, const typename C::key_type& name) { const auto it = cont.find(name); if (it == cont.end() || !(it->second.template is())) { @@ -21,30 +21,30 @@ std::optional getProperty(const C& cont, const typename C::key_type& name) { return it->second.template get(); } -using FeatureExtensionGetterPtr = FeatureExtensionValue (*)(std::shared_ptr, - std::uint32_t, - const std::optional>&); +using FeatureExtensionGetterPtr = + FeatureExtensionValue (*)(std::shared_ptr, std::uint32_t, const std::optional>&); // NOLINTNEXTLINE(performance-unnecessary-value-param) -FeatureExtensionValue getChildren(std::shared_ptr clusterData, - std::uint32_t clusterID, - const std::optional>&) { +FeatureExtensionValue +getChildren(std::shared_ptr clusterData, std::uint32_t clusterID, const std::optional>&) { return clusterData->getChildren(clusterID); } // NOLINTNEXTLINE(performance-unnecessary-value-param) -FeatureExtensionValue getLeaves(std::shared_ptr clusterData, - std::uint32_t clusterID, - const std::optional>& args) { +FeatureExtensionValue getLeaves( + std::shared_ptr clusterData, + std::uint32_t clusterID, + const std::optional>& args +) { if (args) { const auto limit = getProperty(*args, "limit"); const auto offset = getProperty(*args, "offset"); // Offset cannot be set without limit. if (limit) { if (offset) { - return clusterData->getLeaves(clusterID, - static_cast(*limit), - static_cast(*offset)); + return clusterData->getLeaves( + clusterID, static_cast(*limit), static_cast(*offset) + ); } return clusterData->getLeaves(clusterID, static_cast(*limit), 0u); } @@ -54,23 +54,20 @@ FeatureExtensionValue getLeaves(std::shared_ptr clusterData, } // NOLINTNEXTLINE(performance-unnecessary-value-param) -FeatureExtensionValue getClusterExpansionZoom(std::shared_ptr clusterData, - std::uint32_t clusterID, - const std::optional>&) { +FeatureExtensionValue +getClusterExpansionZoom(std::shared_ptr clusterData, std::uint32_t clusterID, const std::optional>&) { return Value{static_cast(clusterData->getClusterExpansionZoom(clusterID))}; } -MAPBOX_ETERNAL_CONSTEXPR const auto extensionGetters = mapbox::eternal::hash_map({ - {"children", &getChildren}, - {"leaves", &getLeaves}, - {"expansion-zoom", &getClusterExpansionZoom} -}); +MAPBOX_ETERNAL_CONSTEXPR const auto extensionGetters = + mapbox::eternal::hash_map( + {{"children", &getChildren}, {"leaves", &getLeaves}, {"expansion-zoom", &getClusterExpansionZoom}} + ); } // namespace RenderGeoJSONSource::RenderGeoJSONSource(Immutable impl_) - : RenderTileSource(std::move(impl_)) { -} + : RenderTileSource(std::move(impl_)) {} RenderGeoJSONSource::~RenderGeoJSONSource() = default; @@ -78,11 +75,13 @@ const style::GeoJSONSource::Impl& RenderGeoJSONSource::impl() const { return static_cast(*baseImpl); } -void RenderGeoJSONSource::update(Immutable baseImpl_, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) { +void RenderGeoJSONSource::update( + Immutable baseImpl_, + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters +) { std::swap(baseImpl, baseImpl_); enabled = needsRendering; @@ -106,24 +105,27 @@ void RenderGeoJSONSource::update(Immutable baseImpl_, if (!data_) return; - tilePyramid.update(layers, - needsRendering, - needsRelayout, - parameters, - *baseImpl, - util::tileSize_I, - impl().getZoomRange(), - std::optional{}, - [&, data_](const OverscaledTileID& tileID) { - return std::make_unique(tileID, impl().id, parameters, data_); - }); + tilePyramid.update( + layers, + needsRendering, + needsRelayout, + parameters, + *baseImpl, + util::tileSize_I, + impl().getZoomRange(), + std::optional{}, + [&, data_](const OverscaledTileID& tileID) { + return std::make_unique(tileID, impl().id, parameters, data_); + } + ); } -mapbox::util::variant -RenderGeoJSONSource::queryFeatureExtensions(const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const { +mapbox::util::variant RenderGeoJSONSource::queryFeatureExtensions( + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args +) const { if (extension != "supercluster") { return {}; } diff --git a/src/mbgl/renderer/sources/render_geojson_source.hpp b/src/mbgl/renderer/sources/render_geojson_source.hpp index 8d3061444de..ac61dc5e329 100644 --- a/src/mbgl/renderer/sources/render_geojson_source.hpp +++ b/src/mbgl/renderer/sources/render_geojson_source.hpp @@ -14,17 +14,16 @@ class RenderGeoJSONSource final : public RenderTileSource { explicit RenderGeoJSONSource(Immutable); ~RenderGeoJSONSource() override; - void update(Immutable, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) override; - - FeatureExtensionValue - queryFeatureExtensions(const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const override; + void + update(Immutable, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) + override; + + FeatureExtensionValue queryFeatureExtensions( + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args + ) const override; private: const style::GeoJSONSource::Impl& impl() const; diff --git a/src/mbgl/renderer/sources/render_image_source.cpp b/src/mbgl/renderer/sources/render_image_source.cpp index ce865374d1c..b511d57ad72 100644 --- a/src/mbgl/renderer/sources/render_image_source.cpp +++ b/src/mbgl/renderer/sources/render_image_source.cpp @@ -36,7 +36,7 @@ void ImageSourceRenderData::render(PaintParameters& parameters) const { return; } assert(debugTexture); - static const style::Properties<>::PossiblyEvaluated properties {}; + static const style::Properties<>::PossiblyEvaluated properties{}; static const DebugProgram::Binders paintAttributeData(properties, 0); auto programInstance = parameters.shaders.get(); @@ -45,32 +45,36 @@ void ImageSourceRenderData::render(PaintParameters& parameters) const { } for (auto matrix : matrices) { - programInstance->draw(parameters.context, - *parameters.renderPass, - gfx::LineStrip{4.0f * parameters.pixelRatio}, - gfx::DepthMode::disabled(), - gfx::StencilMode::disabled(), - gfx::ColorMode::unblended(), - gfx::CullFaceMode::disabled(), - *parameters.staticData.tileBorderIndexBuffer, - RenderStaticData::tileBorderSegments(), - DebugProgram::computeAllUniformValues( - DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), - uniforms::color::Value(Color::red()), - uniforms::overlay_scale::Value(1.0f)}, - paintAttributeData, - properties, - static_cast(parameters.state.getZoom())), - DebugProgram::computeAllAttributeBindings( - *parameters.staticData.tileVertexBuffer, paintAttributeData, properties), - DebugProgram::TextureBindings{textures::image::Value{debugTexture->getResource()}}, - "image"); + programInstance->draw( + parameters.context, + *parameters.renderPass, + gfx::LineStrip{4.0f * parameters.pixelRatio}, + gfx::DepthMode::disabled(), + gfx::StencilMode::disabled(), + gfx::ColorMode::unblended(), + gfx::CullFaceMode::disabled(), + *parameters.staticData.tileBorderIndexBuffer, + RenderStaticData::tileBorderSegments(), + DebugProgram::computeAllUniformValues( + DebugProgram::LayoutUniformValues{ + uniforms::matrix::Value(matrix), + uniforms::color::Value(Color::red()), + uniforms::overlay_scale::Value(1.0f)}, + paintAttributeData, + properties, + static_cast(parameters.state.getZoom()) + ), + DebugProgram::computeAllAttributeBindings( + *parameters.staticData.tileVertexBuffer, paintAttributeData, properties + ), + DebugProgram::TextureBindings{textures::image::Value{debugTexture->getResource()}}, + "image" + ); } } RenderImageSource::RenderImageSource(Immutable impl_) - : RenderSource(std::move(impl_)) { -} + : RenderSource(std::move(impl_)) {} RenderImageSource::~RenderImageSource() = default; @@ -105,24 +109,23 @@ void RenderImageSource::prepare(const SourcePrepareParameters& parameters) { renderData = std::make_unique(bucket, std::move(matrices), baseImpl->id); } -std::unordered_map> -RenderImageSource::queryRenderedFeatures(const ScreenLineString&, - const TransformState&, - const std::unordered_map&, - const RenderedQueryOptions&, - const mat4&) const { - return std::unordered_map> {}; +std::unordered_map> RenderImageSource:: + queryRenderedFeatures(const ScreenLineString&, const TransformState&, const std::unordered_map&, const RenderedQueryOptions&, const mat4&) + const { + return std::unordered_map>{}; } std::vector RenderImageSource::querySourceFeatures(const SourceQueryOptions&) const { return {}; } -void RenderImageSource::update(Immutable baseImpl_, - const std::vector>&, - const bool needsRendering, - const bool, - const TileParameters& parameters) { +void RenderImageSource::update( + Immutable baseImpl_, + const std::vector>&, + const bool needsRendering, + const bool, + const TileParameters& parameters +) { enabled = needsRendering; if (!needsRendering) { return; @@ -140,8 +143,8 @@ void RenderImageSource::update(Immutable baseImpl_, } // Compute the z0 tile coordinates for the given LatLngs - TileCoordinatePoint nePoint = { -INFINITY, -INFINITY }; - TileCoordinatePoint swPoint = { INFINITY, INFINITY }; + TileCoordinatePoint nePoint = {-INFINITY, -INFINITY}; + TileCoordinatePoint swPoint = {INFINITY, INFINITY}; std::vector tileCoordinates; for (LatLng latLng : coords) { auto point = TileCoordinate::fromLatLng(0, latLng).p; @@ -150,7 +153,7 @@ void RenderImageSource::update(Immutable baseImpl_, nePoint.x = std::max(nePoint.x, point.x); swPoint.y = std::min(swPoint.y, point.y); nePoint.y = std::max(nePoint.y, point.y); - } + } // Calculate the optimum zoom level to determine the tile ids to use for transforms const auto dx = nePoint.x - swPoint.x; @@ -182,11 +185,9 @@ void RenderImageSource::update(Immutable baseImpl_, if (tile.wrap != 0 && tileCover[0].canonical.isChildOf(tile.canonical)) { tileIds.emplace_back(tile.wrap, tileCover[0].canonical); hasVisibleTile = true; - } - else if (!hasVisibleTile) { - for (auto coveringTile: tileCover) { - if(coveringTile.canonical == tile.canonical || - coveringTile.canonical.isChildOf(tile.canonical) || + } else if (!hasVisibleTile) { + for (auto coveringTile : tileCover) { + if (coveringTile.canonical == tile.canonical || coveringTile.canonical.isChildOf(tile.canonical) || tile.canonical.isChildOf(coveringTile.canonical)) { hasVisibleTile = true; } @@ -215,14 +216,12 @@ void RenderImageSource::update(Immutable baseImpl_, } // Set Bucket Vertices, Indices, and segments + bucket->vertices.emplace_back(RasterProgram::layoutVertex({geomCoords[0].x, geomCoords[0].y}, {0, 0})); + bucket->vertices.emplace_back(RasterProgram::layoutVertex({geomCoords[1].x, geomCoords[1].y}, {util::EXTENT, 0})); + bucket->vertices.emplace_back(RasterProgram::layoutVertex({geomCoords[3].x, geomCoords[3].y}, {0, util::EXTENT})); bucket->vertices.emplace_back( - RasterProgram::layoutVertex({ geomCoords[0].x, geomCoords[0].y }, { 0, 0 })); - bucket->vertices.emplace_back( - RasterProgram::layoutVertex({ geomCoords[1].x, geomCoords[1].y }, { util::EXTENT, 0 })); - bucket->vertices.emplace_back( - RasterProgram::layoutVertex({ geomCoords[3].x, geomCoords[3].y }, { 0, util::EXTENT })); - bucket->vertices.emplace_back( - RasterProgram::layoutVertex({ geomCoords[2].x, geomCoords[2].y }, { util::EXTENT, util::EXTENT })); + RasterProgram::layoutVertex({geomCoords[2].x, geomCoords[2].y}, {util::EXTENT, util::EXTENT}) + ); bucket->indices.emplace_back(0, 1, 2); bucket->indices.emplace_back(1, 2, 3); diff --git a/src/mbgl/renderer/sources/render_image_source.hpp b/src/mbgl/renderer/sources/render_image_source.hpp index 41b6e02fb59..86466b8724e 100644 --- a/src/mbgl/renderer/sources/render_image_source.hpp +++ b/src/mbgl/renderer/sources/render_image_source.hpp @@ -11,9 +11,7 @@ class RasterBucket; class ImageSourceRenderData final : public RenderItem { public: - ImageSourceRenderData(std::shared_ptr bucket_, - std::vector matrices_, - std::string name_) + ImageSourceRenderData(std::shared_ptr bucket_, std::vector matrices_, std::string name_) : bucket(std::move(bucket_)), matrices(std::move(matrices_)), name(std::move(name_)) {} @@ -42,27 +40,23 @@ class RenderImageSource final : public RenderSource { void updateFadingTiles() final {} bool hasFadingTiles() const final { return false; } - void update(Immutable, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) final; + void + update(Immutable, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) + final; - const ImageSourceRenderData* getImageRenderData() const override { - return renderData.get(); - } + const ImageSourceRenderData* getImageRenderData() const override { return renderData.get(); } - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const final; + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix + ) const final; std::vector querySourceFeatures(const SourceQueryOptions&) const final; - void reduceMemoryUse() final { - } + void reduceMemoryUse() final {} void dumpDebugLogs() const final; private: diff --git a/src/mbgl/renderer/sources/render_raster_dem_source.cpp b/src/mbgl/renderer/sources/render_raster_dem_source.cpp index fd2a3e9f1d2..8afb321ab0f 100644 --- a/src/mbgl/renderer/sources/render_raster_dem_source.cpp +++ b/src/mbgl/renderer/sources/render_raster_dem_source.cpp @@ -11,8 +11,7 @@ namespace mbgl { using namespace style; RenderRasterDEMSource::RenderRasterDEMSource(Immutable impl_) - : RenderTileSetSource(std::move(impl_)) { -} + : RenderTileSetSource(std::move(impl_)) {} const style::RasterSource::Impl& RenderRasterDEMSource::impl() const { return static_cast(*baseImpl); @@ -22,11 +21,13 @@ const std::optional& RenderRasterDEMSource::getTileset() const { return impl().tileset; } -void RenderRasterDEMSource::updateInternal(const Tileset& tileset, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) { +void RenderRasterDEMSource::updateInternal( + const Tileset& tileset, + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters +) { tilePyramid.update( layers, needsRendering, @@ -36,23 +37,23 @@ void RenderRasterDEMSource::updateInternal(const Tileset& tileset, impl().getTileSize(), tileset.zoomRange, tileset.bounds, - [&](const OverscaledTileID& tileID) { return std::make_unique(tileID, parameters, tileset); }); + [&](const OverscaledTileID& tileID) { return std::make_unique(tileID, parameters, tileset); } + ); algorithm::updateTileMasks(tilePyramid.getRenderedTiles()); } -void RenderRasterDEMSource::onTileChanged(Tile& tile){ +void RenderRasterDEMSource::onTileChanged(Tile& tile) { auto& demtile = static_cast(tile); std::map opposites = { - { DEMTileNeighbors::Left, DEMTileNeighbors::Right }, - { DEMTileNeighbors::Right, DEMTileNeighbors::Left }, - { DEMTileNeighbors::TopLeft, DEMTileNeighbors::BottomRight }, - { DEMTileNeighbors::TopCenter, DEMTileNeighbors::BottomCenter }, - { DEMTileNeighbors::TopRight, DEMTileNeighbors::BottomLeft }, - { DEMTileNeighbors::BottomRight, DEMTileNeighbors::TopLeft }, - { DEMTileNeighbors::BottomCenter, DEMTileNeighbors:: TopCenter }, - { DEMTileNeighbors::BottomLeft, DEMTileNeighbors::TopRight } - }; + {DEMTileNeighbors::Left, DEMTileNeighbors::Right}, + {DEMTileNeighbors::Right, DEMTileNeighbors::Left}, + {DEMTileNeighbors::TopLeft, DEMTileNeighbors::BottomRight}, + {DEMTileNeighbors::TopCenter, DEMTileNeighbors::BottomCenter}, + {DEMTileNeighbors::TopRight, DEMTileNeighbors::BottomLeft}, + {DEMTileNeighbors::BottomRight, DEMTileNeighbors::TopLeft}, + {DEMTileNeighbors::BottomCenter, DEMTileNeighbors::TopCenter}, + {DEMTileNeighbors::BottomLeft, DEMTileNeighbors::TopRight}}; if (tile.isRenderable() && demtile.neighboringTiles != DEMTileNeighbors::Complete) { const CanonicalTileID canonical = tile.id.canonical; @@ -62,30 +63,30 @@ void RenderRasterDEMSource::onTileChanged(Tile& tile){ const uint32_t nx = (canonical.x + 1 + dim) % dim; const int nxw = (canonical.x + 1 == dim) ? tile.id.wrap + 1 : tile.id.wrap; - auto getNeighbor = [&] (DEMTileNeighbors mask){ - if (mask == DEMTileNeighbors::Left){ + auto getNeighbor = [&](DEMTileNeighbors mask) { + if (mask == DEMTileNeighbors::Left) { return OverscaledTileID(tile.id.overscaledZ, pxw, canonical.z, px, canonical.y); - } else if (mask == DEMTileNeighbors::Right){ + } else if (mask == DEMTileNeighbors::Right) { return OverscaledTileID(tile.id.overscaledZ, nxw, canonical.z, nx, canonical.y); - } else if (mask == DEMTileNeighbors::TopLeft){ + } else if (mask == DEMTileNeighbors::TopLeft) { return OverscaledTileID(tile.id.overscaledZ, pxw, canonical.z, px, canonical.y - 1); - } else if (mask == DEMTileNeighbors::TopCenter){ + } else if (mask == DEMTileNeighbors::TopCenter) { return OverscaledTileID(tile.id.overscaledZ, tile.id.wrap, canonical.z, canonical.x, canonical.y - 1); - } else if (mask == DEMTileNeighbors::TopRight){ + } else if (mask == DEMTileNeighbors::TopRight) { return OverscaledTileID(tile.id.overscaledZ, nxw, canonical.z, nx, canonical.y - 1); - } else if (mask == DEMTileNeighbors::BottomLeft){ + } else if (mask == DEMTileNeighbors::BottomLeft) { return OverscaledTileID(tile.id.overscaledZ, pxw, canonical.z, px, canonical.y + 1); - } else if (mask == DEMTileNeighbors::BottomCenter){ + } else if (mask == DEMTileNeighbors::BottomCenter) { return OverscaledTileID(tile.id.overscaledZ, tile.id.wrap, canonical.z, canonical.x, canonical.y + 1); - } else if (mask == DEMTileNeighbors::BottomRight){ + } else if (mask == DEMTileNeighbors::BottomRight) { return OverscaledTileID(tile.id.overscaledZ, nxw, canonical.z, nx, canonical.y + 1); - } else{ + } else { throw std::runtime_error("mask is not a valid tile neighbor"); } }; for (uint8_t i = 0; i < 8; i++) { - auto mask = DEMTileNeighbors(std::pow(2,i)); + auto mask = DEMTileNeighbors(std::pow(2, i)); // only backfill if this neighbor has not been previously backfilled if ((demtile.neighboringTiles & mask) != mask) { OverscaledTileID neighborid = getNeighbor(mask); @@ -97,9 +98,9 @@ void RenderRasterDEMSource::onTileChanged(Tile& tile){ // if the border tile has not been backfilled by a previous instance of the main // tile, backfill its corresponding neighbor as well. const DEMTileNeighbors& borderMask = opposites[mask]; - if ((borderTile.neighboringTiles & borderMask) != borderMask){ + if ((borderTile.neighboringTiles & borderMask) != borderMask) { borderTile.backfillBorder(demtile, borderMask); - } + } } } } @@ -107,12 +108,9 @@ void RenderRasterDEMSource::onTileChanged(Tile& tile){ RenderTileSource::onTileChanged(tile); } -std::unordered_map> -RenderRasterDEMSource::queryRenderedFeatures(const ScreenLineString&, - const TransformState&, - const std::unordered_map&, - const RenderedQueryOptions&, - const mat4&) const { +std::unordered_map> RenderRasterDEMSource:: + queryRenderedFeatures(const ScreenLineString&, const TransformState&, const std::unordered_map&, const RenderedQueryOptions&, const mat4&) + const { return std::unordered_map>{}; } @@ -120,5 +118,4 @@ std::vector RenderRasterDEMSource::querySourceFeatures(const SourceQuer return {}; } - } // namespace mbgl diff --git a/src/mbgl/renderer/sources/render_raster_dem_source.hpp b/src/mbgl/renderer/sources/render_raster_dem_source.hpp index 6e6d25c6746..b35413ee769 100644 --- a/src/mbgl/renderer/sources/render_raster_dem_source.hpp +++ b/src/mbgl/renderer/sources/render_raster_dem_source.hpp @@ -9,23 +9,21 @@ class RenderRasterDEMSource final : public RenderTileSetSource { public: explicit RenderRasterDEMSource(Immutable); - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const override; + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix + ) const override; - std::vector - querySourceFeatures(const SourceQueryOptions&) const override; + std::vector querySourceFeatures(const SourceQueryOptions&) const override; private: // RenderTileSetSource overrides - void updateInternal(const Tileset&, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) override; + void + updateInternal(const Tileset&, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) + override; const std::optional& getTileset() const override; const style::RasterSource::Impl& impl() const; diff --git a/src/mbgl/renderer/sources/render_raster_source.cpp b/src/mbgl/renderer/sources/render_raster_source.cpp index 6f491d6967a..87f9dbd2bf4 100644 --- a/src/mbgl/renderer/sources/render_raster_source.cpp +++ b/src/mbgl/renderer/sources/render_raster_source.cpp @@ -9,8 +9,7 @@ namespace mbgl { using namespace style; RenderRasterSource::RenderRasterSource(Immutable impl_) - : RenderTileSetSource(std::move(impl_)) { -} + : RenderTileSetSource(std::move(impl_)) {} inline const style::RasterSource::Impl& RenderRasterSource::impl() const { return static_cast(*baseImpl); @@ -20,11 +19,13 @@ const std::optional& RenderRasterSource::getTileset() const { return impl().tileset; } -void RenderRasterSource::updateInternal(const Tileset& tileset, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) { +void RenderRasterSource::updateInternal( + const Tileset& tileset, + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters +) { tilePyramid.update( layers, needsRendering, @@ -34,7 +35,8 @@ void RenderRasterSource::updateInternal(const Tileset& tileset, impl().getTileSize(), tileset.zoomRange, tileset.bounds, - [&](const OverscaledTileID& tileID) { return std::make_unique(tileID, parameters, tileset); }); + [&](const OverscaledTileID& tileID) { return std::make_unique(tileID, parameters, tileset); } + ); algorithm::updateTileMasks(tilePyramid.getRenderedTiles()); } @@ -42,12 +44,9 @@ void RenderRasterSource::prepare(const SourcePrepareParameters& parameters) { RenderTileSource::prepare(parameters); } -std::unordered_map> -RenderRasterSource::queryRenderedFeatures(const ScreenLineString&, - const TransformState&, - const std::unordered_map&, - const RenderedQueryOptions&, - const mat4&) const { +std::unordered_map> RenderRasterSource:: + queryRenderedFeatures(const ScreenLineString&, const TransformState&, const std::unordered_map&, const RenderedQueryOptions&, const mat4&) + const { return std::unordered_map>{}; } @@ -55,5 +54,4 @@ std::vector RenderRasterSource::querySourceFeatures(const SourceQueryOp return {}; } - } // namespace mbgl diff --git a/src/mbgl/renderer/sources/render_raster_source.hpp b/src/mbgl/renderer/sources/render_raster_source.hpp index 7675e264403..3e40eefd395 100644 --- a/src/mbgl/renderer/sources/render_raster_source.hpp +++ b/src/mbgl/renderer/sources/render_raster_source.hpp @@ -12,22 +12,20 @@ class RenderRasterSource final : public RenderTileSetSource { private: void prepare(const SourcePrepareParameters&) final; - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const override; + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix + ) const override; - std::vector - querySourceFeatures(const SourceQueryOptions&) const override; + std::vector querySourceFeatures(const SourceQueryOptions&) const override; // RenderTileSetSource overrides - void updateInternal(const Tileset&, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) override; + void + updateInternal(const Tileset&, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) + override; const std::optional& getTileset() const override; const style::RasterSource::Impl& impl() const; diff --git a/src/mbgl/renderer/sources/render_tile_source.cpp b/src/mbgl/renderer/sources/render_tile_source.cpp index 6d24f29f729..204d8f4836a 100644 --- a/src/mbgl/renderer/sources/render_tile_source.cpp +++ b/src/mbgl/renderer/sources/render_tile_source.cpp @@ -17,8 +17,8 @@ using namespace style; class TileSourceRenderItem : public RenderItem { public: TileSourceRenderItem(Immutable> renderTiles_, std::string name_) - : renderTiles(std::move(renderTiles_)) - , name(std::move(name_)) {} + : renderTiles(std::move(renderTiles_)), + name(std::move(name_)) {} private: void upload(gfx::UploadPass&) const override; @@ -43,8 +43,8 @@ void TileSourceRenderItem::render(PaintParameters& parameters) const { } RenderTileSource::RenderTileSource(Immutable impl_) - : RenderSource(std::move(impl_)) - , renderTiles(makeMutable>()) { + : RenderSource(std::move(impl_)), + renderTiles(makeMutable>()) { tilePyramid.setObserver(this); } @@ -121,12 +121,13 @@ const Tile* RenderTileSource::getRenderedTile(const UnwrappedTileID& tileID) con return tilePyramid.getRenderedTile(tileID); } -std::unordered_map> -RenderTileSource::queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const { +std::unordered_map> RenderTileSource::queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix +) const { return tilePyramid.queryRenderedFeatures(geometry, transformState, layers, options, projMatrix, featureState); } @@ -134,19 +135,23 @@ std::vector RenderTileSource::querySourceFeatures(const SourceQueryOpti return tilePyramid.querySourceFeatures(options); } -void RenderTileSource::setFeatureState(const std::optional& sourceLayerID, const std::string& featureID, - const FeatureState& state) { +void RenderTileSource::setFeatureState( + const std::optional& sourceLayerID, const std::string& featureID, const FeatureState& state +) { featureState.updateState(sourceLayerID, featureID, state); } -void RenderTileSource::getFeatureState(FeatureState& state, const std::optional& sourceLayerID, - const std::string& featureID) const { +void RenderTileSource::getFeatureState( + FeatureState& state, const std::optional& sourceLayerID, const std::string& featureID +) const { featureState.getState(state, sourceLayerID, featureID); } -void RenderTileSource::removeFeatureState(const std::optional& sourceLayerID, - const std::optional& featureID, - const std::optional& stateKey) { +void RenderTileSource::removeFeatureState( + const std::optional& sourceLayerID, + const std::optional& featureID, + const std::optional& stateKey +) { featureState.removeState(sourceLayerID, featureID, stateKey); } @@ -161,8 +166,7 @@ void RenderTileSource::dumpDebugLogs() const { // RenderTileSetSource implementation RenderTileSetSource::RenderTileSetSource(Immutable impl_) - : RenderTileSource(std::move(impl_)) { -} + : RenderTileSource(std::move(impl_)) {} RenderTileSetSource::~RenderTileSetSource() = default; @@ -170,11 +174,13 @@ uint8_t RenderTileSetSource::getMaxZoom() const { return cachedTileset ? cachedTileset->zoomRange.max : util::TERRAIN_RGB_MAXZOOM; } -void RenderTileSetSource::update(Immutable baseImpl_, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) { +void RenderTileSetSource::update( + Immutable baseImpl_, + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters +) { std::swap(baseImpl, baseImpl_); enabled = needsRendering; diff --git a/src/mbgl/renderer/sources/render_tile_source.hpp b/src/mbgl/renderer/sources/render_tile_source.hpp index bd929678ff7..a407a99c754 100644 --- a/src/mbgl/renderer/sources/render_tile_source.hpp +++ b/src/mbgl/renderer/sources/render_tile_source.hpp @@ -25,22 +25,23 @@ class RenderTileSource : public RenderSource { RenderTiles getRenderTilesSortedByYPosition() const override; const Tile* getRenderedTile(const UnwrappedTileID&) const override; - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const override; + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix + ) const override; - std::vector - querySourceFeatures(const SourceQueryOptions&) const override; + std::vector querySourceFeatures(const SourceQueryOptions&) const override; void setFeatureState(const std::optional&, const std::string&, const FeatureState&) override; void getFeatureState(FeatureState& state, const std::optional&, const std::string&) const override; - void removeFeatureState(const std::optional&, const std::optional&, - const std::optional&) override; + void + removeFeatureState(const std::optional&, const std::optional&, const std::optional&) + override; void reduceMemoryUse() override; void dumpDebugLogs() const override; @@ -65,21 +66,16 @@ class RenderTileSetSource : public RenderTileSource { RenderTileSetSource(Immutable); ~RenderTileSetSource() override; - virtual void updateInternal(const Tileset&, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) = 0; + virtual void + updateInternal(const Tileset&, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) = 0; // Returns tileset from the current impl. virtual const std::optional& getTileset() const = 0; private: uint8_t getMaxZoom() const final; - void update(Immutable, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) final; + void + update(Immutable, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) + final; std::optional cachedTileset; }; diff --git a/src/mbgl/renderer/sources/render_vector_source.cpp b/src/mbgl/renderer/sources/render_vector_source.cpp index ca60d575b01..db00ec7eb29 100644 --- a/src/mbgl/renderer/sources/render_vector_source.cpp +++ b/src/mbgl/renderer/sources/render_vector_source.cpp @@ -9,29 +9,32 @@ namespace mbgl { using namespace style; RenderVectorSource::RenderVectorSource(Immutable impl_) - : RenderTileSetSource(std::move(impl_)) { -} + : RenderTileSetSource(std::move(impl_)) {} const std::optional& RenderVectorSource::getTileset() const { return static_cast(*baseImpl).tileset; } -void RenderVectorSource::updateInternal(const Tileset& tileset, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) { - tilePyramid.update(layers, - needsRendering, - needsRelayout, - parameters, - *baseImpl, - util::tileSize_I, - tileset.zoomRange, - tileset.bounds, - [&](const OverscaledTileID& tileID) { - return std::make_unique(tileID, baseImpl->id, parameters, tileset); - }); +void RenderVectorSource::updateInternal( + const Tileset& tileset, + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters +) { + tilePyramid.update( + layers, + needsRendering, + needsRelayout, + parameters, + *baseImpl, + util::tileSize_I, + tileset.zoomRange, + tileset.bounds, + [&](const OverscaledTileID& tileID) { + return std::make_unique(tileID, baseImpl->id, parameters, tileset); + } + ); } } // namespace mbgl diff --git a/src/mbgl/renderer/sources/render_vector_source.hpp b/src/mbgl/renderer/sources/render_vector_source.hpp index 19c39e719b3..cdbd67a930f 100644 --- a/src/mbgl/renderer/sources/render_vector_source.hpp +++ b/src/mbgl/renderer/sources/render_vector_source.hpp @@ -9,12 +9,11 @@ namespace mbgl { class RenderVectorSource final : public RenderTileSetSource { public: explicit RenderVectorSource(Immutable); + private: - void updateInternal(const Tileset&, - const std::vector>&, - bool needsRendering, - bool needsRelayout, - const TileParameters&) override; + void + updateInternal(const Tileset&, const std::vector>&, bool needsRendering, bool needsRelayout, const TileParameters&) + override; const std::optional& getTileset() const override; }; diff --git a/src/mbgl/renderer/style_diff.cpp b/src/mbgl/renderer/style_diff.cpp index 270c4483cdd..1c97b8dc2af 100644 --- a/src/mbgl/renderer/style_diff.cpp +++ b/src/mbgl/renderer/style_diff.cpp @@ -7,9 +7,7 @@ namespace mbgl { template -StyleDifference diff(const Immutable>& a, - const Immutable>& b, - const Eq& eq) { +StyleDifference diff(const Immutable>& a, const Immutable>& b, const Eq& eq) { StyleDifference result; if (a == b) { @@ -33,7 +31,7 @@ StyleDifference diff(const Immutable>& a, bIt++; } else { if (aIt->get() != bIt->get()) { - result.changed.emplace((*bIt)->id, StyleChange { *aIt, *bIt }); + result.changed.emplace((*bIt)->id, StyleChange{*aIt, *bIt}); } aIt++; bIt++; @@ -44,34 +42,32 @@ StyleDifference diff(const Immutable>& a, return result; } -ImageDifference diffImages(const Immutable>& a, - const Immutable>& b) { - return diff(a, b, [] (const ImmutableImage& lhs, const ImmutableImage& rhs) { - return lhs->id == rhs->id; - }); +ImageDifference diffImages( + const Immutable>& a, const Immutable>& b +) { + return diff(a, b, [](const ImmutableImage& lhs, const ImmutableImage& rhs) { return lhs->id == rhs->id; }); } -SourceDifference diffSources(const Immutable>& a, - const Immutable>& b) { - return diff(a, b, [] (const ImmutableSource& lhs, const ImmutableSource& rhs) { - return std::tie(lhs->id, lhs->type) - == std::tie(rhs->id, rhs->type); +SourceDifference diffSources( + const Immutable>& a, const Immutable>& b +) { + return diff(a, b, [](const ImmutableSource& lhs, const ImmutableSource& rhs) { + return std::tie(lhs->id, lhs->type) == std::tie(rhs->id, rhs->type); }); } -LayerDifference diffLayers(const Immutable>& a, - const Immutable>& b) { - return diff(a, b, [] (const ImmutableLayer& lhs, const ImmutableLayer& rhs) { +LayerDifference diffLayers( + const Immutable>& a, const Immutable>& b +) { + return diff(a, b, [](const ImmutableLayer& lhs, const ImmutableLayer& rhs) { return (lhs->id == rhs->id) && (lhs->getTypeInfo() == rhs->getTypeInfo()); }); } bool hasLayoutDifference(const LayerDifference& layerDiff, const std::string& layerID) { - if (layerDiff.added.count(layerID)) - return true; + if (layerDiff.added.count(layerID)) return true; const auto it = layerDiff.changed.find(layerID); - if (it == layerDiff.changed.end()) - return false; + if (it == layerDiff.changed.end()) return false; return it->second.before->hasLayoutDifference(*it->second.after); } diff --git a/src/mbgl/renderer/style_diff.hpp b/src/mbgl/renderer/style_diff.hpp index a5b42fc6620..5b4f9bba22a 100644 --- a/src/mbgl/renderer/style_diff.hpp +++ b/src/mbgl/renderer/style_diff.hpp @@ -28,20 +28,20 @@ class StyleDifference { using ImmutableImage = Immutable; using ImageDifference = StyleDifference; -ImageDifference diffImages(const Immutable>&, - const Immutable>&); +ImageDifference +diffImages(const Immutable>&, const Immutable>&); using ImmutableSource = Immutable; using SourceDifference = StyleDifference; -SourceDifference diffSources(const Immutable>&, - const Immutable>&); +SourceDifference +diffSources(const Immutable>&, const Immutable>&); using ImmutableLayer = Immutable; using LayerDifference = StyleDifference; -LayerDifference diffLayers(const Immutable>&, - const Immutable>&); +LayerDifference +diffLayers(const Immutable>&, const Immutable>&); bool hasLayoutDifference(const LayerDifference&, const std::string& layerID); diff --git a/src/mbgl/renderer/tile_pyramid.cpp b/src/mbgl/renderer/tile_pyramid.cpp index b4d2e5512f4..b265fc3527b 100644 --- a/src/mbgl/renderer/tile_pyramid.cpp +++ b/src/mbgl/renderer/tile_pyramid.cpp @@ -24,8 +24,7 @@ using namespace style; static TileObserver nullObserver; TilePyramid::TilePyramid() - : observer(&nullObserver) { -} + : observer(&nullObserver) {} TilePyramid::~TilePyramid() = default; @@ -49,15 +48,17 @@ const Tile* TilePyramid::getRenderedTile(const UnwrappedTileID& tileID) const { return it != renderedTiles.end() ? &it->second.get() : nullptr; } -void TilePyramid::update(const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters, - const style::Source::Impl& sourceImpl, - const uint16_t tileSize, - const Range zoomRange, - std::optional bounds, - std::function(const OverscaledTileID&)> createTile) { +void TilePyramid::update( + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters, + const style::Source::Impl& sourceImpl, + const uint16_t tileSize, + const Range zoomRange, + std::optional bounds, + std::function(const OverscaledTileID&)> createTile +) { // If we need a relayout, abandon any cached tiles; they're now stale. if (needsRelayout) { cache.clear(); @@ -101,18 +102,18 @@ void TilePyramid::update(const std::vector>& l if (overscaledZoom >= zoomRange.min) { int32_t idealZoom = std::min(zoomRange.max, overscaledZoom); - // Make sure we're not reparsing overzoomed raster tiles. if (type == SourceType::Raster) { tileZoom = idealZoom; } // Only attempt prefetching in continuous mode. - if (parameters.mode == MapMode::Continuous && type != style::SourceType::GeoJSON && type != style::SourceType::Annotations) { + if (parameters.mode == MapMode::Continuous && type != style::SourceType::GeoJSON && + type != style::SourceType::Annotations) { // Request lower zoom level tiles (if configured to do so) in an attempt // to show something on the screen faster at the cost of a little of bandwidth. - const uint8_t prefetchZoomDelta = - sourcePrefetchZoomDelta ? *sourcePrefetchZoomDelta : parameters.prefetchZoomDelta; + const uint8_t prefetchZoomDelta = sourcePrefetchZoomDelta ? *sourcePrefetchZoomDelta + : parameters.prefetchZoomDelta; if (prefetchZoomDelta) { panZoom = std::max(tileZoom - prefetchZoomDelta, zoomRange.min); } @@ -125,9 +126,11 @@ void TilePyramid::update(const std::vector>& l idealTiles = util::tileCover(parameters.transformState, idealZoom, tileZoom); if (parameters.mode == MapMode::Tile && type != SourceType::Raster && type != SourceType::RasterDEM && idealTiles.size() > 1) { - mbgl::Log::Warning(mbgl::Event::General, - "Provided camera options returned " + std::to_string(idealTiles.size()) + - " tiles, only " + util::toString(idealTiles[0]) + " is taken in Tile mode."); + mbgl::Log::Warning( + mbgl::Event::General, + "Provided camera options returned " + std::to_string(idealTiles.size()) + " tiles, only " + + util::toString(idealTiles[0]) + " is taken in Tile mode." + ); idealTiles = {idealTiles[0]}; } } @@ -159,7 +162,8 @@ void TilePyramid::update(const std::vector>& l std::optional tileRange = std::nullopt; if (bounds) { tileRange = util::TileRange::fromLatLngBounds( - *bounds, zoomRange.min, std::min(tileZoom, static_cast(zoomRange.max))); + *bounds, zoomRange.min, std::min(tileZoom, static_cast(zoomRange.max)) + ); } auto createTileFn = [&](const OverscaledTileID& tileID) -> Tile* { if (tileRange && !tileRange->contains(tileID.canonical)) { @@ -194,11 +198,13 @@ void TilePyramid::update(const std::vector>& l [](const UnwrappedTileID&, Tile&) {}, panTiles, zoomRange, - maxParentTileOverscaleFactor); + maxParentTileOverscaleFactor + ); } algorithm::updateRenderables( - getTileFn, createTileFn, retainTileFn, renderTileFn, idealTiles, zoomRange, maxParentTileOverscaleFactor); + getTileFn, createTileFn, retainTileFn, renderTileFn, idealTiles, zoomRange, maxParentTileOverscaleFactor + ); for (auto previouslyRenderedTile : previouslyRenderedTiles) { Tile& tile = previouslyRenderedTile.second; @@ -303,9 +309,13 @@ void TilePyramid::handleWrapJump(float lng) { } std::unordered_map> TilePyramid::queryRenderedFeatures( - const ScreenLineString& geometry, const TransformState& transformState, - const std::unordered_map& layers, const RenderedQueryOptions& options, - const mat4& projMatrix, const SourceFeatureState& featureState) const { + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix, + const SourceFeatureState& featureState +) const { std::unordered_map> result; if (renderedTiles.empty() || geometry.empty()) { return result; @@ -315,18 +325,20 @@ std::unordered_map> TilePyramid::queryRendered queryGeometry.reserve(geometry.size()); for (const auto& p : geometry) { - queryGeometry.push_back(TileCoordinate::fromScreenCoordinate( - transformState, 0, { p.x, transformState.getSize().height - p.y }).p); + queryGeometry.push_back( + TileCoordinate::fromScreenCoordinate(transformState, 0, {p.x, transformState.getSize().height - p.y}).p + ); } mapbox::geometry::box box = mapbox::geometry::envelope(queryGeometry); auto cmp = [](const UnwrappedTileID& a, const UnwrappedTileID& b) { return std::tie(a.canonical.z, a.canonical.y, a.wrap, a.canonical.x) < - std::tie(b.canonical.z, b.canonical.y, b.wrap, b.canonical.x); + std::tie(b.canonical.z, b.canonical.y, b.wrap, b.canonical.x); }; - std::map, decltype(cmp)> sortedTiles{renderedTiles.begin(), renderedTiles.end(), cmp}; + std::map, decltype(cmp)> sortedTiles{ + renderedTiles.begin(), renderedTiles.end(), cmp}; auto maxPitchScaleFactor = transformState.maxPitchScaleFactor(); @@ -334,11 +346,15 @@ std::unordered_map> TilePyramid::queryRendered const UnwrappedTileID& id = entry.first; Tile& tile = entry.second; - const auto scale = static_cast(transformState.getScale() / (1 << id.canonical.z)); // equivalent to std::pow(2, transformState.getZoom() - id.canonical.z); - auto queryPadding = maxPitchScaleFactor * tile.getQueryPadding(layers) * util::EXTENT / util::tileSize_D / scale; + const auto scale = static_cast( + transformState.getScale() / (1 << id.canonical.z) + ); // equivalent to std::pow(2, transformState.getZoom() - id.canonical.z); + auto queryPadding = maxPitchScaleFactor * tile.getQueryPadding(layers) * util::EXTENT / util::tileSize_D / + scale; GeometryCoordinate tileSpaceBoundsMin = TileCoordinate::toGeometryCoordinate(id, box.min); - if (tileSpaceBoundsMin.x - queryPadding >= util::EXTENT || tileSpaceBoundsMin.y - queryPadding >= util::EXTENT) { + if (tileSpaceBoundsMin.x - queryPadding >= util::EXTENT || + tileSpaceBoundsMin.y - queryPadding >= util::EXTENT) { continue; } @@ -353,8 +369,9 @@ std::unordered_map> TilePyramid::queryRendered tileSpaceQueryGeometry.push_back(TileCoordinate::toGeometryCoordinate(id, c)); } - tile.queryRenderedFeatures(result, tileSpaceQueryGeometry, transformState, layers, options, projMatrix, - featureState); + tile.queryRenderedFeatures( + result, tileSpaceQueryGeometry, transformState, layers, options, projMatrix, featureState + ); } return result; diff --git a/src/mbgl/renderer/tile_pyramid.hpp b/src/mbgl/renderer/tile_pyramid.hpp index b04d2c6bb7d..3db19e2f6ca 100644 --- a/src/mbgl/renderer/tile_pyramid.hpp +++ b/src/mbgl/renderer/tile_pyramid.hpp @@ -34,15 +34,17 @@ class TilePyramid { bool isLoaded() const; - void update(const std::vector>& visibleLayers, - bool needsRendering, - bool needsRelayout, - const TileParameters&, - const style::Source::Impl&, - uint16_t tileSize, - Range zoomRange, - std::optional bounds, - std::function(const OverscaledTileID&)> createTile); + void update( + const std::vector>& visibleLayers, + bool needsRendering, + bool needsRelayout, + const TileParameters&, + const style::Source::Impl&, + uint16_t tileSize, + Range zoomRange, + std::optional bounds, + std::function(const OverscaledTileID&)> createTile + ); const std::map>& getRenderedTiles() const { return renderedTiles; } Tile* getTile(const OverscaledTileID&); @@ -51,9 +53,13 @@ class TilePyramid { void handleWrapJump(float lng); std::unordered_map> queryRenderedFeatures( - const ScreenLineString& geometry, const TransformState& transformState, - const std::unordered_map&, const RenderedQueryOptions& options, - const mat4& projMatrix, const mbgl::SourceFeatureState& featureState) const; + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map&, + const RenderedQueryOptions& options, + const mat4& projMatrix, + const mbgl::SourceFeatureState& featureState + ) const; std::vector querySourceFeatures(const SourceQueryOptions&) const; diff --git a/src/mbgl/renderer/tile_render_data.cpp b/src/mbgl/renderer/tile_render_data.cpp index 5f8c2498bf7..f0845381c5e 100644 --- a/src/mbgl/renderer/tile_render_data.cpp +++ b/src/mbgl/renderer/tile_render_data.cpp @@ -5,8 +5,7 @@ namespace mbgl { TileRenderData::TileRenderData() = default; TileRenderData::TileRenderData(std::shared_ptr atlasTextures_) - : atlasTextures(std::move(atlasTextures_)) { -} + : atlasTextures(std::move(atlasTextures_)) {} TileRenderData::~TileRenderData() = default; diff --git a/src/mbgl/renderer/tile_render_data.hpp b/src/mbgl/renderer/tile_render_data.hpp index 85b26754e45..b4f3de1505f 100644 --- a/src/mbgl/renderer/tile_render_data.hpp +++ b/src/mbgl/renderer/tile_render_data.hpp @@ -18,7 +18,7 @@ class LayerRenderData; class SourcePrepareParameters; class TileAtlasTextures { -public: +public: std::optional glyph; std::optional icon; }; @@ -49,9 +49,7 @@ class SharedBucketTileRenderData final : public TileRenderData { private: // TileRenderData overrides. - Bucket* getBucket(const style::Layer::Impl&) const override { - return bucket ? bucket.get() : nullptr; - } + Bucket* getBucket(const style::Layer::Impl&) const override { return bucket ? bucket.get() : nullptr; } void upload(gfx::UploadPass& uploadPass) override { if (bucket) bucket->upload(uploadPass); } diff --git a/src/mbgl/renderer/update_parameters.hpp b/src/mbgl/renderer/update_parameters.hpp index 47192b9940c..a16a2801f0b 100644 --- a/src/mbgl/renderer/update_parameters.hpp +++ b/src/mbgl/renderer/update_parameters.hpp @@ -39,7 +39,7 @@ class UpdateParameters { std::shared_ptr fileSource; const uint8_t prefetchZoomDelta; - + // For still image requests, render requested const bool stillImageRequest; diff --git a/src/mbgl/renderer/upload_parameters.hpp b/src/mbgl/renderer/upload_parameters.hpp index 74fb6a8c862..b8c6d4e91b6 100644 --- a/src/mbgl/renderer/upload_parameters.hpp +++ b/src/mbgl/renderer/upload_parameters.hpp @@ -10,11 +10,9 @@ class LineAtlas; class UploadParameters { public: - UploadParameters(const TransformState& state_, - LineAtlas& lineAtlas_) + UploadParameters(const TransformState& state_, LineAtlas& lineAtlas_) : state(state_), - lineAtlas(lineAtlas_) { - } + lineAtlas(lineAtlas_) {} const TransformState& state; LineAtlas& lineAtlas; diff --git a/src/mbgl/sprite/sprite_loader.cpp b/src/mbgl/sprite/sprite_loader.cpp index da057142429..61f5fb47a07 100644 --- a/src/mbgl/sprite/sprite_loader.cpp +++ b/src/mbgl/sprite/sprite_loader.cpp @@ -27,7 +27,9 @@ struct SpriteLoader::Data { }; SpriteLoader::SpriteLoader(float pixelRatio_) - : pixelRatio(pixelRatio_), observer(&nullObserver), threadPool(Scheduler::GetBackground()) {} + : pixelRatio(pixelRatio_), + observer(&nullObserver), + threadPool(Scheduler::GetBackground()) {} SpriteLoader::~SpriteLoader() = default; diff --git a/src/mbgl/sprite/sprite_parser.cpp b/src/mbgl/sprite/sprite_parser.cpp index 3ac93d3358d..160ce76f18b 100644 --- a/src/mbgl/sprite/sprite_parser.cpp +++ b/src/mbgl/sprite/sprite_parser.cpp @@ -16,28 +16,28 @@ namespace mbgl { -std::unique_ptr createStyleImage(const std::string& id, - const PremultipliedImage& image, - const int32_t srcX, - const int32_t srcY, - const int32_t width, - const int32_t height, - const double ratio, - const bool sdf, - style::ImageStretches&& stretchX, - style::ImageStretches&& stretchY, - const std::optional& content) { +std::unique_ptr createStyleImage( + const std::string& id, + const PremultipliedImage& image, + const int32_t srcX, + const int32_t srcY, + const int32_t width, + const int32_t height, + const double ratio, + const bool sdf, + style::ImageStretches&& stretchX, + style::ImageStretches&& stretchY, + const std::optional& content +) { // Disallow invalid parameter configurations. if (width <= 0 || height <= 0 || width > 1024 || height > 1024 || ratio <= 0 || ratio > 10 || srcX < 0 || srcY < 0 || srcX >= static_cast(image.size.width) || srcY >= static_cast(image.size.height) || srcX + width > static_cast(image.size.width) || srcY + height > static_cast(image.size.height)) { std::ostringstream ss; - ss << "Can't create image with invalid metrics: " - << width << "x" << height << "@" << srcX << "," << srcY - << " in " << image.size.width << "x" << image.size.height - << "@" << util::toString(ratio) << "x" - << " sprite"; + ss << "Can't create image with invalid metrics: " << width << "x" << height << "@" << srcX << "," << srcY + << " in " << image.size.width << "x" << image.size.height << "@" << util::toString(ratio) << "x" + << " sprite"; Log::Error(Event::Sprite, ss.str()); return nullptr; } @@ -50,7 +50,8 @@ std::unique_ptr createStyleImage(const std::string& id, try { return std::make_unique( - id, std::move(dstImage), static_cast(ratio), sdf, std::move(stretchX), std::move(stretchY), content); + id, std::move(dstImage), static_cast(ratio), sdf, std::move(stretchX), std::move(stretchY), content + ); } catch (const util::StyleImageException& ex) { Log::Error(Event::Sprite, std::string("Can't create image with invalid metadata: ") + ex.what()); return nullptr; @@ -65,8 +66,11 @@ uint16_t getUInt16(const JSValue& value, const char* property, const char* name, if (v.IsUint() && v.GetUint() <= std::numeric_limits::max()) { return v.GetUint(); } else { - Log::Warning(Event::Sprite, - std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be an integer between 0 and 65535"); + Log::Warning( + Event::Sprite, + std::string("Invalid sprite image '") + name + "': value of '" + property + + "' must be an integer between 0 and 65535" + ); } } @@ -79,7 +83,10 @@ double getDouble(const JSValue& value, const char* property, const char* name, c if (v.IsNumber()) { return v.GetDouble(); } else { - Log::Warning(Event::Sprite, std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be a number"); + Log::Warning( + Event::Sprite, + std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be a number" + ); } } @@ -92,7 +99,10 @@ bool getBoolean(const JSValue& value, const char* property, const char* name, co if (v.IsBool()) { return v.GetBool(); } else { - Log::Warning(Event::Sprite, std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be a boolean"); + Log::Warning( + Event::Sprite, + std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be a boolean" + ); } } @@ -109,15 +119,21 @@ style::ImageStretches getStretches(const JSValue& value, const char* property, c const JSValue& stretch = v[i]; if (stretch.IsArray() && stretch.Size() == 2 && stretch[rapidjson::SizeType(0)].IsNumber() && stretch[rapidjson::SizeType(1)].IsNumber()) { - stretches.emplace_back(style::ImageStretch{stretch[rapidjson::SizeType(0)].GetFloat(), - stretch[rapidjson::SizeType(1)].GetFloat()}); + stretches.emplace_back(style::ImageStretch{ + stretch[rapidjson::SizeType(0)].GetFloat(), stretch[rapidjson::SizeType(1)].GetFloat()}); } else { - Log::Warning(Event::Sprite, - "Invalid sprite image '" + std::string(name) + "': members of '" + property + "' must be an array of two numbers"); + Log::Warning( + Event::Sprite, + "Invalid sprite image '" + std::string(name) + "': members of '" + property + + "' must be an array of two numbers" + ); } } } else { - Log::Warning(Event::Sprite, "Invalid sprite image '" + std::string(name) + "': value of '" + property + "' must be an array"); + Log::Warning( + Event::Sprite, + "Invalid sprite image '" + std::string(name) + "': value of '" + property + "' must be an array" + ); } } @@ -130,13 +146,17 @@ std::optional getContent(const JSValue& value, const char* if (content.IsArray() && content.Size() == 4 && content[rapidjson::SizeType(0)].IsNumber() && content[rapidjson::SizeType(1)].IsNumber() && content[rapidjson::SizeType(2)].IsNumber() && content[rapidjson::SizeType(3)].IsNumber()) { - return style::ImageContent{content[rapidjson::SizeType(0)].GetFloat(), - content[rapidjson::SizeType(1)].GetFloat(), - content[rapidjson::SizeType(2)].GetFloat(), - content[rapidjson::SizeType(3)].GetFloat()}; + return style::ImageContent{ + content[rapidjson::SizeType(0)].GetFloat(), + content[rapidjson::SizeType(1)].GetFloat(), + content[rapidjson::SizeType(2)].GetFloat(), + content[rapidjson::SizeType(3)].GetFloat()}; } else { - Log::Warning(Event::Sprite, - "Invalid sprite image '" + std::string(name) + "': value of '" + property + "' must be an array of four numbers"); + Log::Warning( + Event::Sprite, + "Invalid sprite image '" + std::string(name) + "': value of '" + property + + "' must be an array of four numbers" + ); } } @@ -177,7 +197,8 @@ std::vector> parseSprite(const std::string& encode std::optional content = getContent(value, "content", name.c_str()); auto image = createStyleImage( - name, raster, x, y, width, height, pixelRatio, sdf, std::move(stretchX), std::move(stretchY), content); + name, raster, x, y, width, height, pixelRatio, sdf, std::move(stretchX), std::move(stretchY), content + ); if (image) { images.push_back(std::move(image->baseImpl)); } diff --git a/src/mbgl/sprite/sprite_parser.hpp b/src/mbgl/sprite/sprite_parser.hpp index 54a0746cbcb..b706a62aaab 100644 --- a/src/mbgl/sprite/sprite_parser.hpp +++ b/src/mbgl/sprite/sprite_parser.hpp @@ -7,17 +7,19 @@ namespace mbgl { // Extracts an individual image from a spritesheet from the given location. -std::unique_ptr createStyleImage(const std::string& id, - const PremultipliedImage&, - int32_t srcX, - int32_t srcY, - int32_t srcWidth, - int32_t srcHeight, - double ratio, - bool sdf, - style::ImageStretches&& stretchX = {}, - style::ImageStretches&& stretchY = {}, - const std::optional& content = std::nullopt); +std::unique_ptr createStyleImage( + const std::string& id, + const PremultipliedImage&, + int32_t srcX, + int32_t srcY, + int32_t srcWidth, + int32_t srcHeight, + double ratio, + bool sdf, + style::ImageStretches&& stretchX = {}, + style::ImageStretches&& stretchY = {}, + const std::optional& content = std::nullopt +); // Parses an image and an associated JSON file and returns the sprite objects. std::vector> parseSprite(const std::string& image, const std::string& json); diff --git a/src/mbgl/storage/asset_file_source.hpp b/src/mbgl/storage/asset_file_source.hpp index 6d9ee3bb524..8db775592d1 100644 --- a/src/mbgl/storage/asset_file_source.hpp +++ b/src/mbgl/storage/asset_file_source.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace util { -template class Thread; +template +class Thread; } // namespace util class AssetFileSource : public FileSource { diff --git a/src/mbgl/storage/file_source_manager.cpp b/src/mbgl/storage/file_source_manager.cpp index 6e24d721089..b14bf635faa 100644 --- a/src/mbgl/storage/file_source_manager.cpp +++ b/src/mbgl/storage/file_source_manager.cpp @@ -13,7 +13,9 @@ namespace mbgl { struct FileSourceInfo { FileSourceInfo(FileSourceType type_, std::string id_, std::weak_ptr fileSource_) - : type(type_), id(std::move(id_)), fileSource(std::move(fileSource_)) {} + : type(type_), + id(std::move(id_)), + fileSource(std::move(fileSource_)) {} FileSourceType type; std::string id; @@ -27,11 +29,14 @@ class FileSourceManager::Impl { std::recursive_mutex mutex; }; -FileSourceManager::FileSourceManager() : impl(std::make_unique()) {} +FileSourceManager::FileSourceManager() + : impl(std::make_unique()) {} FileSourceManager::~FileSourceManager() = default; -std::shared_ptr FileSourceManager::getFileSource(FileSourceType type, const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) noexcept { +std::shared_ptr FileSourceManager::getFileSource( + FileSourceType type, const ResourceOptions& resourceOptions, const ClientOptions& clientOptions +) noexcept { std::lock_guard lock(impl->mutex); // Remove released file sources. @@ -41,8 +46,8 @@ std::shared_ptr FileSourceManager::getFileSource(FileSourceType typ const auto context = reinterpret_cast(resourceOptions.platformContext()); std::string baseURL = resourceOptions.tileServerOptions().baseURL(); - std::string id = - baseURL + '|' + resourceOptions.apiKey() + '|' + resourceOptions.cachePath() + '|' + util::toString(context); + std::string id = baseURL + '|' + resourceOptions.apiKey() + '|' + resourceOptions.cachePath() + '|' + + util::toString(context); std::shared_ptr fileSource; auto fileSourceIt = std::find_if(impl->fileSources.begin(), impl->fileSources.end(), [type, &id](const auto& info) { diff --git a/src/mbgl/storage/local_file_source.hpp b/src/mbgl/storage/local_file_source.hpp index 3595db6499b..79a90de6720 100644 --- a/src/mbgl/storage/local_file_source.hpp +++ b/src/mbgl/storage/local_file_source.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace util { -template class Thread; +template +class Thread; } // namespace util class LocalFileSource : public FileSource { diff --git a/src/mbgl/storage/mbtiles_file_source.hpp b/src/mbgl/storage/mbtiles_file_source.hpp index a31f9002ef2..876d348c653 100644 --- a/src/mbgl/storage/mbtiles_file_source.hpp +++ b/src/mbgl/storage/mbtiles_file_source.hpp @@ -5,7 +5,6 @@ #include #include - namespace mbgl { // File source for supporting .mbtiles maps. // can only load resource URLS that are absolute paths to local files @@ -14,7 +13,7 @@ class MBTilesFileSource : public FileSource { MBTilesFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions); ~MBTilesFileSource() override; - std::unique_ptr request(const Resource &, Callback) override; + std::unique_ptr request(const Resource&, Callback) override; bool canRequest(const Resource&) const override; void setResourceOptions(ResourceOptions) override; @@ -25,7 +24,7 @@ class MBTilesFileSource : public FileSource { private: class Impl; - std::unique_ptr > thread; //impl + std::unique_ptr> thread; // impl }; } // namespace mbgl diff --git a/src/mbgl/storage/network_status.cpp b/src/mbgl/storage/network_status.cpp index 646bbf40be5..3de82340879 100644 --- a/src/mbgl/storage/network_status.cpp +++ b/src/mbgl/storage/network_status.cpp @@ -24,7 +24,7 @@ NetworkStatus::Status NetworkStatus::Get() { void NetworkStatus::Set(Status status) { if (status == Status::Offline) { online = false; - } else if(!online) { + } else if (!online) { online = true; Reachable(); } diff --git a/src/mbgl/storage/resource.cpp b/src/mbgl/storage/resource.cpp index 7461364a84f..9031bb2de2e 100644 --- a/src/mbgl/storage/resource.cpp +++ b/src/mbgl/storage/resource.cpp @@ -35,49 +35,43 @@ static std::string getTileBBox(int32_t x, int32_t y, int8_t z) { auto min = getMercCoord(x * 256, y * 256, z); auto max = getMercCoord((x + 1) * 256, (y + 1) * 256, z); - return (util::toString(min.x) + "," + util::toString(min.y) + "," + - util::toString(max.x) + "," + util::toString(max.y)); + return ( + util::toString(min.x) + "," + util::toString(min.y) + "," + util::toString(max.x) + "," + util::toString(max.y) + ); } Resource Resource::style(const std::string& url) { - return Resource { - Resource::Kind::Style, - url - }; + return Resource{Resource::Kind::Style, url}; } Resource Resource::source(const std::string& url) { - return Resource { - Resource::Kind::Source, - url - }; + return Resource{Resource::Kind::Source, url}; } Resource Resource::image(const std::string& url) { - return Resource { - Resource::Kind::Image, - url - }; + return Resource{Resource::Kind::Image, url}; } Resource Resource::spriteImage(const std::string& base, float pixelRatio) { util::URL url(base); - return Resource{ Resource::Kind::SpriteImage, - base.substr(0, url.path.first + url.path.second) + - (pixelRatio > 1 ? "@2x" : "") + ".png" + - base.substr(url.query.first, url.query.second)}; + return Resource{ + Resource::Kind::SpriteImage, + base.substr(0, url.path.first + url.path.second) + (pixelRatio > 1 ? "@2x" : "") + ".png" + + base.substr(url.query.first, url.query.second)}; } Resource Resource::spriteJSON(const std::string& base, float pixelRatio) { util::URL url(base); - return Resource{ Resource::Kind::SpriteJSON, - base.substr(0, url.path.first + url.path.second) + - (pixelRatio > 1 ? "@2x" : "") + ".json" + - base.substr(url.query.first, url.query.second)}; + return Resource{ + Resource::Kind::SpriteJSON, + base.substr(0, url.path.first + url.path.second) + (pixelRatio > 1 ? "@2x" : "") + ".json" + + base.substr(url.query.first, url.query.second)}; } -Resource Resource::glyphs(const std::string& urlTemplate, const FontStack& fontStack, const std::pair& glyphRange) { - return Resource { +Resource Resource::glyphs( + const std::string& urlTemplate, const FontStack& fontStack, const std::pair& glyphRange +) { + return Resource{ Resource::Kind::Glyphs, util::replaceTokens(urlTemplate, [&](const std::string& token) -> std::optional { if (token == "fontstack") { @@ -87,54 +81,51 @@ Resource Resource::glyphs(const std::string& urlTemplate, const FontStack& fontS } else { return {}; } - }) - }; + })}; } -Resource Resource::tile(const std::string& urlTemplate, - float pixelRatio, - int32_t x, - int32_t y, - int8_t z, - Tileset::Scheme scheme, - LoadingMethod loadingMethod) { +Resource Resource::tile( + const std::string& urlTemplate, + float pixelRatio, + int32_t x, + int32_t y, + int8_t z, + Tileset::Scheme scheme, + LoadingMethod loadingMethod +) { bool supportsRatio = urlTemplate.find("{ratio}") != std::string::npos; if (scheme == Tileset::Scheme::TMS) { y = (1 << z) - y - 1; } - return Resource { + return Resource{ Resource::Kind::Tile, - util::replaceTokens(urlTemplate, [&](const std::string& token) -> std::optional { - if (token == "z") { - return util::toString(z); - } else if (token == "x") { - return util::toString(x); - } else if (token == "y") { - return util::toString(y); - } else if (token == "quadkey") { - return getQuadKey(x, y, z); - } else if (token == "bbox-epsg-3857") { - return getTileBBox(x, y, z); - } else if (token == "prefix") { - return {{ - "0123456789abcdef"[x % 16], - "0123456789abcdef"[y % 16], - }}; - } else if (token == "ratio") { - return std::string(pixelRatio > 1.0 ? "@2x" : ""); - } else { - return {}; - } - }), - Resource::TileData { + util::replaceTokens( urlTemplate, - uint8_t(supportsRatio && pixelRatio > 1.0 ? 2 : 1), - x, - y, - z - }, - loadingMethod - }; + [&](const std::string& token) -> std::optional { + if (token == "z") { + return util::toString(z); + } else if (token == "x") { + return util::toString(x); + } else if (token == "y") { + return util::toString(y); + } else if (token == "quadkey") { + return getQuadKey(x, y, z); + } else if (token == "bbox-epsg-3857") { + return getTileBBox(x, y, z); + } else if (token == "prefix") { + return {{ + "0123456789abcdef"[x % 16], + "0123456789abcdef"[y % 16], + }}; + } else if (token == "ratio") { + return std::string(pixelRatio > 1.0 ? "@2x" : ""); + } else { + return {}; + } + } + ), + Resource::TileData{urlTemplate, uint8_t(supportsRatio && pixelRatio > 1.0 ? 2 : 1), x, y, z}, + loadingMethod}; } } // namespace mbgl diff --git a/src/mbgl/storage/resource_options.cpp b/src/mbgl/storage/resource_options.cpp index f1e1275d595..99bc22d2245 100644 --- a/src/mbgl/storage/resource_options.cpp +++ b/src/mbgl/storage/resource_options.cpp @@ -15,12 +15,20 @@ class ResourceOptions::Impl { }; // These requires the complete type of Impl. -ResourceOptions::ResourceOptions() : impl_(std::make_unique()) {} +ResourceOptions::ResourceOptions() + : impl_(std::make_unique()) {} ResourceOptions::~ResourceOptions() = default; ResourceOptions::ResourceOptions(ResourceOptions&&) noexcept = default; -ResourceOptions::ResourceOptions(const ResourceOptions& other) : impl_(std::make_unique(*other.impl_)) {} -ResourceOptions& ResourceOptions::operator=(const ResourceOptions& other) {impl_ = std::make_unique(*other.impl_); return *this; } -ResourceOptions& ResourceOptions::operator=(ResourceOptions&& options) {swap(impl_, options.impl_); return *this; } +ResourceOptions::ResourceOptions(const ResourceOptions& other) + : impl_(std::make_unique(*other.impl_)) {} +ResourceOptions& ResourceOptions::operator=(const ResourceOptions& other) { + impl_ = std::make_unique(*other.impl_); + return *this; +} +ResourceOptions& ResourceOptions::operator=(ResourceOptions&& options) { + swap(impl_, options.impl_); + return *this; +} ResourceOptions ResourceOptions::clone() const { return ResourceOptions(*this); @@ -81,8 +89,9 @@ void* ResourceOptions::platformContext() const { } ResourceOptions ResourceOptions::Default() { - ResourceOptions resourceOptions = ResourceOptions().withTileServerOptions(TileServerOptions::DefaultConfiguration()); + ResourceOptions resourceOptions = ResourceOptions().withTileServerOptions(TileServerOptions::DefaultConfiguration() + ); return resourceOptions; } -} // namespace mbgl +} // namespace mbgl diff --git a/src/mbgl/storage/resource_transform.cpp b/src/mbgl/storage/resource_transform.cpp index eaf10c93fdd..b2b4208643b 100644 --- a/src/mbgl/storage/resource_transform.cpp +++ b/src/mbgl/storage/resource_transform.cpp @@ -2,7 +2,8 @@ namespace mbgl { -ResourceTransform::ResourceTransform(TransformCallback callback) : transformCallback(std::move(callback)) {} +ResourceTransform::ResourceTransform(TransformCallback callback) + : transformCallback(std::move(callback)) {} void ResourceTransform::transform(Resource::Kind kind, const std::string& url, FinishedCallback finished) { assert(finished); diff --git a/src/mbgl/storage/response.cpp b/src/mbgl/storage/response.cpp index 1922d319c84..9bc6958caf9 100644 --- a/src/mbgl/storage/response.cpp +++ b/src/mbgl/storage/response.cpp @@ -19,7 +19,8 @@ Response& Response::operator=(const Response& res) { } Response::Error::Error(Reason reason_, std::string message_, std::optional retryAfter_) - : reason(reason_), message(std::move(message_)), retryAfter(std::move(retryAfter_)) { -} + : reason(reason_), + message(std::move(message_)), + retryAfter(std::move(retryAfter_)) {} } // namespace mbgl diff --git a/src/mbgl/style/collection.hpp b/src/mbgl/style/collection.hpp index 36d5176d4c4..65dc0ddadc6 100644 --- a/src/mbgl/style/collection.hpp +++ b/src/mbgl/style/collection.hpp @@ -90,8 +90,9 @@ class Collection : public CollectionBase { private: std::size_t implsIndex(const std::string& id) const { const auto& impls_ = *Base::impls; - auto it = std::lower_bound( - impls_.begin(), impls_.end(), id, [](const auto& a, const std::string& b) { return a->id < b; }); + auto it = std::lower_bound(impls_.begin(), impls_.end(), id, [](const auto& a, const std::string& b) { + return a->id < b; + }); return it - impls_.begin(); } }; @@ -99,7 +100,8 @@ template using CollectionWithPersistentOrder = Collection; template -CollectionBase::CollectionBase() : impls(makeMutable>>()) {} +CollectionBase::CollectionBase() + : impls(makeMutable>>()) {} template std::size_t CollectionBase::size() const { @@ -108,9 +110,8 @@ std::size_t CollectionBase::size() const { template std::size_t CollectionBase::index(const std::string& id) const { - return std::find_if(wrappers.begin(), wrappers.end(), [&](const auto& e) { - return e->getID() == id; - }) - wrappers.begin(); + return std::find_if(wrappers.begin(), wrappers.end(), [&](const auto& e) { return e->getID() == id; }) - + wrappers.begin(); } template @@ -133,9 +134,7 @@ std::vector CollectionBase::getWrappers() const { template void CollectionBase::clear() { - mutate(impls, [&] (auto& impls_) { - impls_.clear(); - }); + mutate(impls, [&](auto& impls_) { impls_.clear(); }); wrappers.clear(); } diff --git a/src/mbgl/style/conversion/color_ramp_property_value.cpp b/src/mbgl/style/conversion/color_ramp_property_value.cpp index f31ad47b602..c144864c49b 100644 --- a/src/mbgl/style/conversion/color_ramp_property_value.cpp +++ b/src/mbgl/style/conversion/color_ramp_property_value.cpp @@ -10,7 +10,9 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator()(const Convertible& value, Error& error, bool, bool) const { +std::optional Converter::operator()( + const Convertible& value, Error& error, bool, bool +) const { using namespace mbgl::style::expression; if (isUndefined(value)) { return ColorRampPropertyValue(); diff --git a/src/mbgl/style/conversion/constant.cpp b/src/mbgl/style/conversion/constant.cpp index 6e82047ac2d..eddc337d844 100644 --- a/src/mbgl/style/conversion/constant.cpp +++ b/src/mbgl/style/conversion/constant.cpp @@ -33,7 +33,9 @@ std::optional Converter::operator()(const Convertible& } template -std::optional Converter>>::operator()(const Convertible& value, Error& error) const { +std::optional Converter>>::operator()( + const Convertible& value, Error& error +) const { std::optional string = toString(value); if (!string) { error.message = "value must be a string"; @@ -50,7 +52,9 @@ std::optional Converter>>::ope } template -auto Converter, typename std::enable_if_t>>::operator()(const Convertible& value, Error& error) const -> std::optional> { +auto Converter, typename std::enable_if_t>>::operator()( + const Convertible& value, Error& error +) const -> std::optional> { if (!isArray(value)) { error.message = "value must be an array"; return std::nullopt; @@ -71,22 +75,29 @@ auto Converter, typename std::enable_if_t>>::op } template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; +template std::optional Converter::operator()(const Convertible&, Error&) + const; +template std::optional +Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; +template std::optional Converter::operator()(const Convertible&, Error&) + const; template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; +template std::optional Converter::operator()(const Convertible&, Error&) + const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; +template std::optional Converter::operator()(const Convertible&, Error&) + const; template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional> Converter>::operator()(const Convertible&, Error&) const; -template std::optional> Converter>::operator()(const Convertible&, Error&) const; +template std::optional> +Converter>::operator()(const Convertible&, Error&) const; +template std::optional> +Converter>::operator()(const Convertible&, Error&) const; std::optional Converter::operator()(const Convertible& value, Error& error) const { std::optional string = toString(value); @@ -105,7 +116,8 @@ std::optional Converter::operator()(const Convertible& value, Erro } template -std::optional> Converter>::operator()(const Convertible& value, Error& error) const { +std::optional> Converter>::operator()(const Convertible& value, Error& error) + const { if (!isArray(value) || arrayLength(value) != N) { error.message = "value must be an array of " + util::toString(N) + " numbers"; return std::nullopt; @@ -123,13 +135,17 @@ std::optional> Converter>::operator()( return result; } -template std::optional> Converter>::operator()(const Convertible&, Error&) const; -template std::optional> Converter>::operator()(const Convertible&, Error&) const; -template std::optional> Converter>::operator()(const Convertible&, Error&) const; +template std::optional> Converter>::operator()(const Convertible&, Error&) + const; +template std::optional> Converter>::operator()(const Convertible&, Error&) + const; +template std::optional> Converter>::operator()(const Convertible&, Error&) + const; template -std::optional> Converter>::operator()(const Convertible& value, - Error& error) const { +std::optional> Converter>::operator()( + const Convertible& value, Error& error +) const { if (!isArray(value) || arrayLength(value) != N) { error.message = "value must be an array of " + util::toString(N) + " numbers"; return std::nullopt; @@ -147,9 +163,11 @@ std::optional> Converter>::operator( return result; } -template std::optional> Converter>::operator()(const Convertible&, Error&) const; +template std::optional> Converter>::operator()(const Convertible&, Error&) + const; -std::optional> Converter>::operator()(const Convertible& value, Error& error) const { +std::optional> Converter>::operator()(const Convertible& value, Error& error) + const { if (!isArray(value)) { error.message = "value must be an array"; return std::nullopt; @@ -170,7 +188,9 @@ std::optional> Converter>::operator()(cons return result; } -std::optional> Converter>::operator()(const Convertible& value, Error& error) const { +std::optional> Converter>::operator()( + const Convertible& value, Error& error +) const { if (!isArray(value)) { error.message = "value must be an array"; return std::nullopt; diff --git a/src/mbgl/style/conversion/coordinate.cpp b/src/mbgl/style/conversion/coordinate.cpp index 9f554518b4d..dde8fdea51f 100644 --- a/src/mbgl/style/conversion/coordinate.cpp +++ b/src/mbgl/style/conversion/coordinate.cpp @@ -5,12 +5,12 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator() (const Convertible& value, Error& error) const { - if (!isArray(value) || arrayLength(value) < 2 ) { +std::optional Converter::operator()(const Convertible& value, Error& error) const { + if (!isArray(value) || arrayLength(value) < 2) { error.message = "coordinate array must contain numeric longitude and latitude values"; return std::nullopt; } - //Style spec uses GeoJSON convention for specifying coordinates + // Style spec uses GeoJSON convention for specifying coordinates std::optional latitude = toDouble(arrayMember(value, 1)); std::optional longitude = toDouble(arrayMember(value, 0)); @@ -18,7 +18,7 @@ std::optional Converter::operator() (const Convertible& value, E error.message = "coordinate array must contain numeric longitude and latitude values"; return std::nullopt; } - if (*latitude < -90 || *latitude > 90 ){ + if (*latitude < -90 || *latitude > 90) { error.message = "coordinate latitude must be between -90 and 90"; return std::nullopt; } diff --git a/src/mbgl/style/conversion/custom_geometry_source_options.cpp b/src/mbgl/style/conversion/custom_geometry_source_options.cpp index 4b0f715c03d..fab8fb44fd0 100644 --- a/src/mbgl/style/conversion/custom_geometry_source_options.cpp +++ b/src/mbgl/style/conversion/custom_geometry_source_options.cpp @@ -5,7 +5,9 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator()(const Convertible& value, Error& error) const { +std::optional Converter::operator()( + const Convertible& value, Error& error +) const { CustomGeometrySource::Options options; const auto minzoomValue = objectMember(value, "minzoom"); diff --git a/src/mbgl/style/conversion/filter.cpp b/src/mbgl/style/conversion/filter.cpp index d354d23e846..a0372f4b636 100644 --- a/src/mbgl/style/conversion/filter.cpp +++ b/src/mbgl/style/conversion/filter.cpp @@ -26,7 +26,7 @@ std::optional Converter::operator()(const Convertible& value, Er error.message = parsingContext.getCombinedErrors(); return std::nullopt; } else { - return { Filter(std::move(parseResult)) }; + return {Filter(std::move(parseResult))}; } } else { ParseResult expression = convertLegacyFilter(value, error); @@ -79,13 +79,11 @@ bool isExpression(const Convertible& filter) { } } -ParseResult createExpression(const std::string& op, - std::optional>> args, - Error& error) { +ParseResult createExpression( + const std::string& op, std::optional>> args, Error& error +) { if (!args) return {}; - assert(std::all_of(args->begin(), args->end(), [](const std::unique_ptr &e) { - return bool(e.get()); - })); + assert(std::all_of(args->begin(), args->end(), [](const std::unique_ptr& e) { return bool(e.get()); })); if (op == "any") { return {std::make_unique(std::move(*args))}; @@ -124,7 +122,9 @@ ParseResult convertLiteral(const Convertible& convertible, Error& error) { } } -std::optional>> convertLiteralArray(const Convertible &input, Error& error, std::size_t startIndex = 0) { +std::optional>> convertLiteralArray( + const Convertible& input, Error& error, std::size_t startIndex = 0 +) { std::vector> output; output.reserve(arrayLength(input)); for (std::size_t i = startIndex; i < arrayLength(input); ++i) { @@ -137,9 +137,9 @@ std::optional>> convertLiteralArray(cons return {std::move(output)}; } -ParseResult convertLegacyComparisonFilter(const Convertible& values, - Error& error, - const std::optional& opOverride = std::nullopt) { +ParseResult convertLegacyComparisonFilter( + const Convertible& values, Error& error, const std::optional& opOverride = std::nullopt +) { auto op = opOverride ? opOverride : toString(arrayMember(values, 0)); auto property = toString(arrayMember(values, 1)); @@ -187,7 +187,9 @@ ParseResult convertLegacyInFilter(const Convertible& values, Error& error) { } } -std::optional>> convertLegacyFilterArray(const Convertible &input, Error& error, std::size_t startIndex = 0) { +std::optional>> convertLegacyFilterArray( + const Convertible& input, Error& error, std::size_t startIndex = 0 +) { std::vector> output; output.reserve(arrayLength(input)); for (std::size_t i = startIndex; i < arrayLength(input); ++i) { @@ -206,8 +208,8 @@ ParseResult convertLegacyFilter(const Convertible& values, Error& error) { } if (!isArray(values) || arrayLength(values) == 0) { - error.message = "filter value must be a non empty array"; - return std::nullopt; + error.message = "filter value must be a non empty array"; + return std::nullopt; } std::optional op = toString(arrayMember(values, 0)); @@ -222,21 +224,19 @@ ParseResult convertLegacyFilter(const Convertible& values, Error& error) { return ctx.parseExpression(values); } else { return { - *op == "==" || - *op == "<" || - *op == ">" || - *op == "<=" || - *op == ">=" ? convertLegacyComparisonFilter(values, error) : - *op == "!=" ? createExpression("!", convertLegacyComparisonFilter(values, error, {"=="}), error) : - *op == "any" ? createExpression("any", convertLegacyFilterArray(values, error, 1), error) : - *op == "all" ? createExpression("all", convertLegacyFilterArray(values, error, 1), error) : - *op == "none" ? createExpression("!", createExpression("any", convertLegacyFilterArray(values, error, 1), error), error) : - *op == "in" ? convertLegacyInFilter(values, error) : - *op == "!in" ? createExpression("!", convertLegacyInFilter(values, error), error) : - *op == "has" ? convertLegacyHasFilter(values, error) : - *op == "!has" ? createExpression("!", convertLegacyHasFilter(values, error), error) : - ParseResult(std::make_unique(true)) - }; + *op == "==" || *op == "<" || *op == ">" || *op == "<=" || *op == ">=" + ? convertLegacyComparisonFilter(values, error) + : *op == "!=" ? createExpression("!", convertLegacyComparisonFilter(values, error, {"=="}), error) + : *op == "any" ? createExpression("any", convertLegacyFilterArray(values, error, 1), error) + : *op == "all" ? createExpression("all", convertLegacyFilterArray(values, error, 1), error) + : *op == "none" ? createExpression( + "!", createExpression("any", convertLegacyFilterArray(values, error, 1), error), error + ) + : *op == "in" ? convertLegacyInFilter(values, error) + : *op == "!in" ? createExpression("!", convertLegacyInFilter(values, error), error) + : *op == "has" ? convertLegacyHasFilter(values, error) + : *op == "!has" ? createExpression("!", convertLegacyHasFilter(values, error), error) + : ParseResult(std::make_unique(true))}; } } diff --git a/src/mbgl/style/conversion/function.cpp b/src/mbgl/style/conversion/function.cpp index 8824aeed8fb..7a242c5d43c 100644 --- a/src/mbgl/style/conversion/function.cpp +++ b/src/mbgl/style/conversion/function.cpp @@ -30,9 +30,9 @@ bool hasTokens(const std::string& source) { while (pos != end) { auto brace = std::find(pos, end, '{'); - if (brace == end) - return false; - for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++); + if (brace == end) return false; + for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++) + ; if (brace != end && *brace == '}') { return true; } @@ -41,7 +41,7 @@ bool hasTokens(const std::string& source) { return false; } - + std::unique_ptr convertTokenStringToFormatExpression(const std::string& source) { auto textExpression = convertTokenStringToExpression(source); std::vector sections{FormatExpressionSection(std::move(textExpression))}; @@ -65,7 +65,8 @@ std::unique_ptr convertTokenStringToExpression(const std::string& so } pos = brace; if (pos != end) { - for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++); + for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++) + ; if (brace != end && *brace == '}') { inputs.push_back(get(literal(std::string(pos + 1, brace)))); pos = brace + 1; @@ -77,18 +78,22 @@ std::unique_ptr convertTokenStringToExpression(const std::string& so } switch (inputs.size()) { - case 0: - return literal(source); - case 1: - return expression::dsl::toString(std::move(inputs[0])); - default: - return concat(std::move(inputs)); + case 0: + return literal(source); + case 1: + return expression::dsl::toString(std::move(inputs[0])); + default: + return concat(std::move(inputs)); } } template -std::optional> convertFunctionToExpression(const Convertible& value, Error& error, bool convertTokens) { - auto expression = convertFunctionToExpression(expression::valueTypeToExpressionType(), value, error, convertTokens); +std::optional> convertFunctionToExpression( + const Convertible& value, Error& error, bool convertTokens +) { + auto expression = convertFunctionToExpression( + expression::valueTypeToExpressionType(), value, error, convertTokens + ); if (!expression) { return std::nullopt; } @@ -107,60 +112,78 @@ std::optional> convertFunctionToExpression(const Convertib return PropertyExpression(std::move(*expression), defaultValue); } -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); -template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); +convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional>> convertFunctionToExpression>( + const Convertible&, Error&, bool +); +template std::optional>> convertFunctionToExpression>( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional>> convertFunctionToExpression>( + const Convertible&, Error&, bool +); template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); +convertFunctionToExpression>(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); +convertFunctionToExpression>(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); +convertFunctionToExpression>(const Convertible&, Error&, bool); template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool +); // Ad-hoc Converters for double and int64_t. We should replace float with double wholesale, // and promote the int64_t Converter to general use (and it should check that the input is @@ -197,22 +220,16 @@ enum class FunctionType { static bool interpolatable(type::Type type) { return type.match( - [&] (const type::NumberType&) { - return true; - }, - [&] (const type::ColorType&) { - return true; - }, - [&] (const type::Array& array) { - return array.N && array.itemType == type::Number; - }, - [&] (const auto&) { - return false; - } + [&](const type::NumberType&) { return true; }, + [&](const type::ColorType&) { return true; }, + [&](const type::Array& array) { return array.N && array.itemType == type::Number; }, + [&](const auto&) { return false; } ); } -static std::optional> convertLiteral(type::Type type, const Convertible& value, Error& error, bool convertTokens = false) { +static std::optional> convertLiteral( + type::Type type, const Convertible& value, Error& error, bool convertTokens = false +) { return type.match( [&](const type::NumberType&) -> std::optional> { auto result = convert(value, error); @@ -252,7 +269,7 @@ static std::optional> convertLiteral(type::Type type return std::nullopt; } return array.itemType.match( - [&] (const type::NumberType&) -> std::optional> { + [&](const type::NumberType&) -> std::optional> { std::vector result; result.reserve(arrayLength(value)); for (std::size_t i = 0; i < arrayLength(value); ++i) { @@ -265,7 +282,7 @@ static std::optional> convertLiteral(type::Type type } return literal(result); }, - [&] (const type::StringType&) -> std::optional> { + [&](const type::StringType&) -> std::optional> { std::vector result; result.reserve(arrayLength(value)); for (std::size_t i = 0; i < arrayLength(value); ++i) { @@ -278,7 +295,7 @@ static std::optional> convertLiteral(type::Type type } return literal(result); }, - [&] (const auto&) -> std::optional> { + [&](const auto&) -> std::optional> { assert(false); // No properties use this type. return std::nullopt; } @@ -309,9 +326,7 @@ static std::optional> convertLiteral(type::Type type if (!result) { return std::nullopt; } - return convertTokens ? - convertTokenStringToFormatExpression(*result) : - literal(Formatted(result->c_str())); + return convertTokens ? convertTokenStringToFormatExpression(*result) : literal(Formatted(result->c_str())); }, [&](const type::ImageType&) -> std::optional> { auto result = convert(value, error); @@ -320,13 +335,13 @@ static std::optional> convertLiteral(type::Type type } return convertTokens ? std::make_unique(convertTokenStringToImageExpression(*result)) : literal(Image(result->c_str())); - }); + } + ); } -static std::optional>> convertStops(const type::Type& type, - const Convertible& value, - Error& error, - bool convertTokens) { +static std::optional>> convertStops( + const type::Type& type, const Convertible& value, Error& error, bool convertTokens +) { auto stopsValue = objectMember(value, "stops"); if (!stopsValue) { error.message = "function value must specify stops"; @@ -362,7 +377,9 @@ static std::optional>> convertStops return std::nullopt; } - std::optional> e = convertLiteral(type, arrayMember(stopValue, 1), error, convertTokens); + std::optional> e = convertLiteral( + type, arrayMember(stopValue, 1), error, convertTokens + ); if (!e) { return std::nullopt; } @@ -370,7 +387,7 @@ static std::optional>> convertStops stops.emplace(*t, std::move(*e)); } - return { std::move(stops) }; + return {std::move(stops)}; } static void omitFirstStop(std::map>& stops) { @@ -385,9 +402,9 @@ static void omitFirstStop(std::map>& stops) } template -std::optional>> convertBranches(const type::Type& type, - const Convertible& value, - Error& error) { +std::optional>> convertBranches( + const type::Type& type, const Convertible& value, Error& error +) { auto stopsValue = objectMember(value, "stops"); if (!stopsValue) { error.message = "function value must specify stops"; @@ -423,7 +440,7 @@ std::optional>> convertBranches(const ty return std::nullopt; } - std::optional> e = convertLiteral(type, arrayMember(stopValue, 1), error); + std::optional> e = convertLiteral(type, arrayMember(stopValue, 1), error); if (!e) { return std::nullopt; } @@ -431,7 +448,7 @@ std::optional>> convertBranches(const ty stops.emplace(*t, std::move(*e)); } - return { std::move(stops) }; + return {std::move(stops)}; } static std::optional convertBase(const Convertible& value, Error& error) { @@ -450,13 +467,18 @@ static std::optional convertBase(const Convertible& value, Error& error) return *base; } -static std::unique_ptr step(const type::Type& type, - std::unique_ptr input, - std::map> stops) { +static std::unique_ptr step( + const type::Type& type, std::unique_ptr input, std::map> stops +) { return std::make_unique(type, std::move(input), std::move(stops)); } -static std::unique_ptr interpolate(type::Type type, Interpolator interpolator, std::unique_ptr input, std::map> stops) { +static std::unique_ptr interpolate( + type::Type type, + Interpolator interpolator, + std::unique_ptr input, + std::map> stops +) { ParsingContext ctx; auto result = createInterpolate(std::move(type), std::move(interpolator), std::move(input), std::move(stops), ctx); if (!result) { @@ -467,54 +489,60 @@ static std::unique_ptr interpolate(type::Type type, Interpolator int } template -std::unique_ptr categorical(const type::Type& type, - const std::string& property, - std::map> branches, - std::unique_ptr def) { +std::unique_ptr categorical( + const type::Type& type, + const std::string& property, + std::map> branches, + std::unique_ptr def +) { std::unordered_map> convertedBranches; for (auto& b : branches) { convertedBranches[b.first] = std::move(b.second); } - return std::make_unique>(type, - get(literal(property)), - std::move(convertedBranches), - def ? std::move(def) : error("replaced with default")); + return std::make_unique>( + type, + get(literal(property)), + std::move(convertedBranches), + def ? std::move(def) : error("replaced with default") + ); } template <> -std::unique_ptr categorical(const type::Type& type, - const std::string& property, - std::map> branches, - std::unique_ptr def) { +std::unique_ptr categorical( + const type::Type& type, + const std::string& property, + std::map> branches, + std::unique_ptr def +) { auto it = branches.find(true); - std::unique_ptr trueCase = it == branches.end() ? - error("replaced with default") : - std::move(it->second); + std::unique_ptr trueCase = it == branches.end() ? error("replaced with default") + : std::move(it->second); it = branches.find(false); - std::unique_ptr falseCase = it == branches.end() ? - error("replaced with default") : - std::move(it->second); + std::unique_ptr falseCase = it == branches.end() ? error("replaced with default") + : std::move(it->second); std::vector convertedBranches; convertedBranches.emplace_back(eq(get(literal(property)), literal(Value(true))), std::move(trueCase)); convertedBranches.emplace_back(eq(get(literal(property)), literal(Value(false))), std::move(falseCase)); - return std::make_unique(type, std::move(convertedBranches), - def ? std::move(def) : error("replaced with default")); + return std::make_unique( + type, std::move(convertedBranches), def ? std::move(def) : error("replaced with default") + ); } -static std::unique_ptr numberOrDefault(const type::Type& type, - std::unique_ptr get, - std::unique_ptr expr, - std::unique_ptr def) { +static std::unique_ptr numberOrDefault( + const type::Type& type, + std::unique_ptr get, + std::unique_ptr expr, + std::unique_ptr def +) { if (!def) { return expr; } std::vector branches; - branches.emplace_back(eq(compound("typeof", std::move(get)), literal("number")), - std::move(expr)); + branches.emplace_back(eq(compound("typeof", std::move(get)), literal("number")), std::move(expr)); return std::make_unique(type, std::move(branches), std::move(def)); } @@ -524,17 +552,15 @@ static std::optional> convertIntervalFunction( Error& error, const std::function(bool)>& makeInput, std::unique_ptr def, - bool convertTokens = false) { + bool convertTokens = false +) { auto stops = convertStops(type, value, error, convertTokens); if (!stops) { return std::nullopt; } omitFirstStop(*stops); - return numberOrDefault(type, - makeInput(false), - step(type, makeInput(true), std::move(*stops)), - std::move(def)); + return numberOrDefault(type, makeInput(false), step(type, makeInput(true), std::move(*stops)), std::move(def)); } static std::optional> convertExponentialFunction( @@ -543,7 +569,8 @@ static std::optional> convertExponentialFunction( Error& error, const std::function(bool)>& makeInput, std::unique_ptr def, - bool convertTokens = false) { + bool convertTokens = false +) { auto stops = convertStops(type, value, error, convertTokens); if (!stops) { return std::nullopt; @@ -553,17 +580,21 @@ static std::optional> convertExponentialFunction( return std::nullopt; } - return numberOrDefault(type, - makeInput(false), - interpolate(type, exponential(*base), makeInput(true), std::move(*stops)), - std::move(def)); + return numberOrDefault( + type, + makeInput(false), + interpolate(type, exponential(*base), makeInput(true), std::move(*stops)), + std::move(def) + ); } -static std::optional> convertCategoricalFunction(const type::Type& type, - const Convertible& value, - Error& err, - const std::string& property, - std::unique_ptr def) { +static std::optional> convertCategoricalFunction( + const type::Type& type, + const Convertible& value, + Error& err, + const std::string& property, + std::unique_ptr def +) { auto stopsValue = objectMember(value, "stops"); if (!stopsValue) { err.message = "function value must specify stops"; @@ -621,10 +652,9 @@ static std::optional> convertCategoricalFunction(con } template -std::optional> composite(type::Type type, - const Convertible& value, - Error& error, - const Fn& makeInnerExpression) { +std::optional> composite( + type::Type type, const Convertible& value, Error& error, const Fn& makeInnerExpression +) { auto base = convertBase(value, error); if (!base) { return std::nullopt; @@ -701,10 +731,9 @@ std::optional> composite(type::Type type, } } -std::optional> convertFunctionToExpression(type::Type type, - const Convertible& value, - Error& err, - bool convertTokens) { +std::optional> convertFunctionToExpression( + type::Type type, const Convertible& value, Error& err, bool convertTokens +) { if (!isObject(value)) { err.message = "function must be an object"; return std::nullopt; @@ -718,14 +747,10 @@ std::optional> convertFunctionToExpression(type::Typ } else { auto string = toString(*typeValue); if (string) { - if (*string == "interval") - functionType = FunctionType::Interval; - if (*string == "exponential" && interpolatable(type)) - functionType = FunctionType::Exponential; - if (*string == "categorical") - functionType = FunctionType::Categorical; - if (*string == "identity") - functionType = FunctionType::Identity; + if (*string == "interval") functionType = FunctionType::Interval; + if (*string == "exponential" && interpolatable(type)) functionType = FunctionType::Exponential; + if (*string == "categorical") functionType = FunctionType::Categorical; + if (*string == "identity") functionType = FunctionType::Identity; } } @@ -743,13 +768,17 @@ std::optional> convertFunctionToExpression(type::Typ if (!objectMember(value, "property")) { // Camera function. switch (functionType) { - case FunctionType::Interval: - return convertIntervalFunction(type, value, err, [](bool) { return zoom(); }, defaultExpr(), convertTokens); - case FunctionType::Exponential: - return convertExponentialFunction(type, value, err, [](bool) { return zoom(); }, defaultExpr(), convertTokens); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Interval: + return convertIntervalFunction( + type, value, err, [](bool) { return zoom(); }, defaultExpr(), convertTokens + ); + case FunctionType::Exponential: + return convertExponentialFunction( + type, value, err, [](bool) { return zoom(); }, defaultExpr(), convertTokens + ); + default: + err.message = "unsupported function type"; + return std::nullopt; } } @@ -791,7 +820,8 @@ std::optional> convertFunctionToExpression(type::Typ [&](const auto&) -> std::optional> { assert(false); // No properties use this type. return std::nullopt; - }); + } + ); } auto stopsValue = objectMember(value, "stops"); @@ -835,15 +865,15 @@ std::optional> convertFunctionToExpression(type::Typ if (!isObject(stop)) { // Source function. switch (functionType) { - case FunctionType::Interval: - return convertIntervalFunction(type, value, err, getProperty, defaultExpr()); - case FunctionType::Exponential: - return convertExponentialFunction(type, value, err, getProperty, defaultExpr()); - case FunctionType::Categorical: - return convertCategoricalFunction(type, value, err, *property, defaultExpr()); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Interval: + return convertIntervalFunction(type, value, err, getProperty, defaultExpr()); + case FunctionType::Exponential: + return convertExponentialFunction(type, value, err, getProperty, defaultExpr()); + case FunctionType::Categorical: + return convertCategoricalFunction(type, value, err, *property, defaultExpr()); + default: + err.message = "unsupported function type"; + return std::nullopt; } } else { // Composite function. @@ -855,71 +885,81 @@ std::optional> convertFunctionToExpression(type::Typ if (toBool(*sourceValue)) { switch (functionType) { - case FunctionType::Categorical: - return composite( - type, - value, - err, - [&](const type::Type& type_, double, std::map> stops) { - return categorical(type_, *property, std::move(stops), defaultExpr()); - }); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Categorical: + return composite( + type, + value, + err, + [&](const type::Type& type_, double, std::map> stops) { + return categorical(type_, *property, std::move(stops), defaultExpr()); + } + ); + default: + err.message = "unsupported function type"; + return std::nullopt; } } if (toNumber(*sourceValue)) { switch (functionType) { - case FunctionType::Interval: - return composite( - type, - value, - err, - [&](const type::Type& type_, double, std::map> stops) { - omitFirstStop(stops); - return numberOrDefault( - type, getProperty(false), step(type_, getProperty(true), std::move(stops)), defaultExpr()); - }); - case FunctionType::Exponential: - return composite( - type, - value, - err, - [&](type::Type type_, double base, std::map> stops) { - return numberOrDefault( - type, - getProperty(false), - interpolate(std::move(type_), exponential(base), getProperty(true), std::move(stops)), - defaultExpr()); - }); - case FunctionType::Categorical: - return composite( - type, - value, - err, - [&](const type::Type& type_, double, std::map> stops) { - return categorical(type_, *property, std::move(stops), defaultExpr()); - }); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Interval: + return composite( + type, + value, + err, + [&](const type::Type& type_, double, std::map> stops) { + omitFirstStop(stops); + return numberOrDefault( + type, + getProperty(false), + step(type_, getProperty(true), std::move(stops)), + defaultExpr() + ); + } + ); + case FunctionType::Exponential: + return composite( + type, + value, + err, + [&](type::Type type_, double base, std::map> stops) { + return numberOrDefault( + type, + getProperty(false), + interpolate(std::move(type_), exponential(base), getProperty(true), std::move(stops)), + defaultExpr() + ); + } + ); + case FunctionType::Categorical: + return composite( + type, + value, + err, + [&](const type::Type& type_, double, std::map> stops) { + return categorical(type_, *property, std::move(stops), defaultExpr()); + } + ); + default: + err.message = "unsupported function type"; + return std::nullopt; } } if (toString(*sourceValue)) { switch (functionType) { - case FunctionType::Categorical: - return composite( - type, - value, - err, - [&](const type::Type& type_, double, std::map> stops) { - return categorical(type_, *property, std::move(stops), defaultExpr()); - }); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Categorical: + return composite( + type, + value, + err, + [&](const type::Type& type_, double, std::map> stops) { + return categorical(type_, *property, std::move(stops), defaultExpr()); + } + ); + default: + err.message = "unsupported function type"; + return std::nullopt; } } diff --git a/src/mbgl/style/conversion/geojson_options.cpp b/src/mbgl/style/conversion/geojson_options.cpp index 6aad28d15ac..723c46acb88 100644 --- a/src/mbgl/style/conversion/geojson_options.cpp +++ b/src/mbgl/style/conversion/geojson_options.cpp @@ -8,8 +8,7 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator()(const Convertible& value, - Error& error) const { +std::optional Converter::operator()(const Convertible& value, Error& error) const { GeoJSONOptions options; const auto minzoomValue = objectMember(value, "minzoom"); @@ -107,14 +106,12 @@ std::optional Converter::operator()(const Conver // Each property shall be formed as ["key" : [operator, [mapExpression]]] // or ["key" : [[operator, ['accumulated'], ['get', key]], [mapExpression]]] if (!isArray(v) || arrayLength(v) != 2) { - error.message = - "GeoJSON source clusterProperties member must be an array with length of 2"; + error.message = "GeoJSON source clusterProperties member must be an array with length of 2"; return std::nullopt; } auto map = expression::dsl::createExpression(arrayMember(v, 1)); if (!map) { - error.message = - "Failed to convert GeoJSON source clusterProperties map expression"; + error.message = "Failed to convert GeoJSON source clusterProperties map expression"; return std::nullopt; } std::unique_ptr reduce; @@ -123,8 +120,7 @@ std::optional Converter::operator()(const Conver } else { auto reduceOp = toString(arrayMember(v, 0)); if (!reduceOp) { - error.message = - "GeoJSON source clusterProperties member must contain a valid operator"; + error.message = "GeoJSON source clusterProperties member must contain a valid operator"; return std::nullopt; } std::stringstream ss; @@ -132,26 +128,25 @@ std::optional Converter::operator()(const Conver // The reason to create expression via parsing string instead of invoking function // createCompoundExpression is due to expression type disunity can’t be resolved // with current logic of createCompoundExpression - ss << std::string(R"([")") << *reduceOp - << std::string(R"(", ["accumulated"], ["get", ")") << k + ss << std::string(R"([")") << *reduceOp << std::string(R"(", ["accumulated"], ["get", ")") << k << std::string(R"("]])"); reduce = expression::dsl::createExpression(ss.str().c_str()); } if (!reduce) { - error.message = - "Failed to convert GeoJSON source clusterProperties reduce expression"; + error.message = "Failed to convert GeoJSON source clusterProperties reduce expression"; return std::nullopt; } result.emplace(k, std::make_pair(std::move(map), std::move(reduce))); return std::nullopt; - }); + } + ); if (!error.message.empty()) { return std::nullopt; } options.clusterProperties = std::move(result); } - return { std::move(options) }; + return {std::move(options)}; } } // namespace conversion diff --git a/src/mbgl/style/conversion/get_json_type.cpp b/src/mbgl/style/conversion/get_json_type.cpp index cef5fa985e9..6ea718b6e23 100644 --- a/src/mbgl/style/conversion/get_json_type.cpp +++ b/src/mbgl/style/conversion/get_json_type.cpp @@ -23,9 +23,11 @@ std::string getJSONType(const Convertible& value) { // conversion succeeds. assert(v); - return v->match([&](const std::string&) { return "string"; }, - [&](bool) { return "boolean"; }, - [&](const auto&) { return "number"; }); + return v->match( + [&](const std::string&) { return "string"; }, + [&](bool) { return "boolean"; }, + [&](const auto&) { return "number"; } + ); } } // namespace conversion diff --git a/src/mbgl/style/conversion/json.hpp b/src/mbgl/style/conversion/json.hpp index f10da67abf4..f9858b017e7 100644 --- a/src/mbgl/style/conversion/json.hpp +++ b/src/mbgl/style/conversion/json.hpp @@ -9,13 +9,13 @@ namespace mbgl { namespace style { namespace conversion { -template -std::optional convertJSON(const std::string& json, Error& error, Args&&...args) { +template +std::optional convertJSON(const std::string& json, Error& error, Args&&... args) { JSDocument document; document.Parse<0>(json.c_str()); if (document.HasParseError()) { - error = { formatJSONParseError(document) }; + error = {formatJSONParseError(document)}; return {}; } diff --git a/src/mbgl/style/conversion/layer.cpp b/src/mbgl/style/conversion/layer.cpp index 8842cc2ac11..2e462de5665 100644 --- a/src/mbgl/style/conversion/layer.cpp +++ b/src/mbgl/style/conversion/layer.cpp @@ -27,12 +27,14 @@ std::optional setPaintProperties(Layer& layer, const Convertible& value) return std::nullopt; } if (!isObject(*paintValue)) { - return { { "paint must be an object" } }; + return {{"paint must be an object"}}; } return eachMember(*paintValue, [&](const std::string& k, const Convertible& v) { return layer.setProperty(k, v); }); } -std::optional> Converter>::operator()(const Convertible& value, Error& error) const { +std::optional> Converter>::operator()( + const Convertible& value, Error& error +) const { if (!isObject(value)) { error.message = "layer must be an object"; return std::nullopt; @@ -78,8 +80,9 @@ std::optional> Converter>::operato error.message = "layout must be an object"; return std::nullopt; } - auto error_ = eachMember( - *layoutValue, [&](const std::string& k, const Convertible& v) { return layer->setProperty(k, v); }); + auto error_ = eachMember(*layoutValue, [&](const std::string& k, const Convertible& v) { + return layer->setProperty(k, v); + }); if (error_) { error = *error_; return std::nullopt; diff --git a/src/mbgl/style/conversion/light.cpp b/src/mbgl/style/conversion/light.cpp index e003ea05279..33759b57ad1 100644 --- a/src/mbgl/style/conversion/light.cpp +++ b/src/mbgl/style/conversion/light.cpp @@ -99,7 +99,7 @@ std::optional Converter::operator()(const Convertible& value, Erro } } - return { std::move(light) }; + return {std::move(light)}; } } // namespace conversion diff --git a/src/mbgl/style/conversion/property_value.cpp b/src/mbgl/style/conversion/property_value.cpp index 2357a304083..c9629cd3f32 100644 --- a/src/mbgl/style/conversion/property_value.cpp +++ b/src/mbgl/style/conversion/property_value.cpp @@ -8,7 +8,9 @@ namespace style { namespace conversion { template -std::optional> Converter>::operator()(const Convertible& value, Error& error, bool allowDataExpressions, bool convertTokens) const { +std::optional> Converter>::operator()( + const Convertible& value, Error& error, bool allowDataExpressions, bool convertTokens +) const { using namespace mbgl::style::expression; if (isUndefined(value)) { @@ -40,12 +42,11 @@ std::optional> Converter>::operator()(const Co } else if (!allowDataExpressions && !(*expression).isFeatureConstant()) { error.message = "data expressions not supported"; return std::nullopt; - } else if (!(*expression).isFeatureConstant() || !(*expression).isZoomConstant() || - !(*expression).isRuntimeConstant()) { - return { std::move(*expression) }; + } else if (!(*expression).isFeatureConstant() || !(*expression).isZoomConstant() || !(*expression).isRuntimeConstant()) { + return {std::move(*expression)}; } else if ((*expression).getExpression().getKind() == Kind::Literal) { - std::optional constant = fromExpressionValue( - static_cast((*expression).getExpression()).getValue()); + std::optional constant = + fromExpressionValue(static_cast((*expression).getExpression()).getValue()); if (!constant) { return std::nullopt; } @@ -57,43 +58,98 @@ std::optional> Converter>::operator()(const Co } } -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional>> Converter>>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional>> Converter>>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional>> Converter>>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional>> +Converter>>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> +Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional>> +Converter>>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional> +Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; +template std::optional>> +Converter>>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; template std::optional> -Converter>::operator()(conversion::Convertible const&, - conversion::Error&, - bool, - bool) const; +Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool +) const; std::optional>> -mbgl::style::conversion::Converter>, void>::operator()(const Convertible& value, - Error& error, - bool, - bool) const { +mbgl::style::conversion::Converter>, void>::operator()( + const Convertible& value, Error& error, bool, bool +) const { std::optional> a = convert>(value, error); if (!a) { @@ -109,7 +165,8 @@ mbgl::style::conversion::Converter>, void>:: } template std::optional> Converter>::operator()( - conversion::Convertible const&, conversion::Error&, bool, bool) const; + conversion::Convertible const&, conversion::Error&, bool, bool +) const; } // namespace conversion } // namespace style diff --git a/src/mbgl/style/conversion/source.cpp b/src/mbgl/style/conversion/source.cpp index 55223a2a9a7..c1000cc9ba7 100644 --- a/src/mbgl/style/conversion/source.cpp +++ b/src/mbgl/style/conversion/source.cpp @@ -23,7 +23,7 @@ static std::optional> convertURLOrTileset(const Co if (!tileset) { return std::nullopt; } - return { *tileset }; + return {*tileset}; } std::optional url = toString(*urlVal); @@ -32,12 +32,12 @@ static std::optional> convertURLOrTileset(const Co return std::nullopt; } - return { *url }; + return {*url}; } -static std::optional> convertRasterSource(const std::string& id, - const Convertible& value, - Error& error) { +static std::optional> convertRasterSource( + const std::string& id, const Convertible& value, Error& error +) { std::optional> urlOrTileset = convertURLOrTileset(value, error); if (!urlOrTileset) { return std::nullopt; @@ -54,12 +54,12 @@ static std::optional> convertRasterSource(const std::str tileSize = static_cast(*size); } - return { std::make_unique(id, std::move(*urlOrTileset), tileSize) }; + return {std::make_unique(id, std::move(*urlOrTileset), tileSize)}; } -static std::optional> convertRasterDEMSource(const std::string& id, - const Convertible& value, - Error& error) { +static std::optional> convertRasterDEMSource( + const std::string& id, const Convertible& value, Error& error +) { std::optional> urlOrTileset = convertURLOrTileset(value, error); if (!urlOrTileset) { return std::nullopt; @@ -76,12 +76,12 @@ static std::optional> convertRasterDEMSource(const std:: tileSize = static_cast(*size); } - return { std::make_unique(id, std::move(*urlOrTileset), tileSize) }; + return {std::make_unique(id, std::move(*urlOrTileset), tileSize)}; } -static std::optional> convertVectorSource(const std::string& id, - const Convertible& value, - Error& error) { +static std::optional> convertVectorSource( + const std::string& id, const Convertible& value, Error& error +) { std::optional> urlOrTileset = convertURLOrTileset(value, error); if (!urlOrTileset) { return std::nullopt; @@ -107,9 +107,9 @@ static std::optional> convertVectorSource(const std::str return {std::make_unique(id, std::move(*urlOrTileset), std::move(maxzoom), std::move(minzoom))}; } -static std::optional> convertGeoJSONSource(const std::string& id, - const Convertible& value, - Error& error) { +static std::optional> convertGeoJSONSource( + const std::string& id, const Convertible& value, Error& error +) { auto dataValue = objectMember(value, "data"); if (!dataValue) { error.message = "GeoJSON source must have a data value"; @@ -136,12 +136,12 @@ static std::optional> convertGeoJSONSource(const std::st return std::nullopt; } - return { std::move(result) }; + return {std::move(result)}; } -static std::optional> convertImageSource(const std::string& id, - const Convertible& value, - Error& error) { +static std::optional> convertImageSource( + const std::string& id, const Convertible& value, Error& error +) { auto urlValue = objectMember(value, "url"); if (!urlValue) { error.message = "Image source must have a url value"; @@ -166,8 +166,8 @@ static std::optional> convertImageSource(const std::stri } std::array coordinates; - for (std::size_t i=0; i < 4; i++) { - auto latLng = conversion::convert(arrayMember(*coordinatesValue,i), error); + for (std::size_t i = 0; i < 4; i++) { + auto latLng = conversion::convert(arrayMember(*coordinatesValue, i), error); if (!latLng) { return std::nullopt; } @@ -176,10 +176,12 @@ static std::optional> convertImageSource(const std::stri auto result = std::make_unique(id, coordinates); result->setURL(*urlString); - return { std::move(result) }; + return {std::move(result)}; } -std::optional> Converter>::operator()(const Convertible& value, Error& error, const std::string& id) const { +std::optional> Converter>::operator()( + const Convertible& value, Error& error, const std::string& id +) const { if (!isObject(value)) { error.message = "source must be an object"; return std::nullopt; diff --git a/src/mbgl/style/conversion/stringify.hpp b/src/mbgl/style/conversion/stringify.hpp index b3072b4dbac..cd7c968b58f 100644 --- a/src/mbgl/style/conversion/stringify.hpp +++ b/src/mbgl/style/conversion/stringify.hpp @@ -109,39 +109,40 @@ void stringify(Writer& writer, const std::unordered_map& m) { template void stringify(Writer& writer, const Value& v) { - Value::visit(v, [&] (const auto& v_) { stringify(writer, v_); }); + Value::visit(v, [&](const auto& v_) { stringify(writer, v_); }); } template void stringify(Writer& writer, FeatureType type) { switch (type) { - case FeatureType::Unknown: - writer.String("Unknown"); - break; - case FeatureType::Point: - writer.String("Point"); - break; - case FeatureType::LineString: - writer.String("LineString"); - break; - case FeatureType::Polygon: - writer.String("Polygon"); - break; + case FeatureType::Unknown: + writer.String("Unknown"); + break; + case FeatureType::Point: + writer.String("Point"); + break; + case FeatureType::LineString: + writer.String("LineString"); + break; + case FeatureType::Polygon: + writer.String("Polygon"); + break; } } template void stringify(Writer& writer, const FeatureIdentifier& id) { - FeatureIdentifier::visit(id, [&] (const auto& id_) { stringify(writer, id_); }); + FeatureIdentifier::visit(id, [&](const auto& id_) { stringify(writer, id_); }); } template void stringify(Writer& writer, const Filter& filter) { - if (!filter.expression) writer.Null(); - else stringify(writer, (*filter.expression)->serialize()); + if (!filter.expression) + writer.Null(); + else + stringify(writer, (*filter.expression)->serialize()); } - - + template void stringify(Writer& writer, const expression::Formatted& v) { // Convert to mbgl::Value and then use the existing stringify @@ -168,7 +169,7 @@ void stringify(Writer& writer, const PropertyExpression& fn) { template void stringify(Writer& writer, const PropertyValue& v) { - v.evaluate([&] (const auto& v_) { stringify(writer, v_); }); + v.evaluate([&](const auto& v_) { stringify(writer, v_); }); } template diff --git a/src/mbgl/style/conversion/tileset.cpp b/src/mbgl/style/conversion/tileset.cpp index a64f2f9617f..3fe114e1603 100644 --- a/src/mbgl/style/conversion/tileset.cpp +++ b/src/mbgl/style/conversion/tileset.cpp @@ -96,18 +96,18 @@ std::optional Converter::operator()(const Convertible& value, bottom = util::clamp(*bottom, -90.0, 90.0); top = util::clamp(*top, -90.0, 90.0); - if (*top < *bottom){ + if (*top < *bottom) { error.message = "bounds bottom latitude must be less than or equal to top latitude"; return std::nullopt; } - if(*left > *right) { + if (*left > *right) { error.message = "bounds left longitude must be less than or equal to right longitude"; return std::nullopt; } left = util::max(-180.0, *left); right = util::min(180.0, *right); - result.bounds = LatLngBounds::hull({ *bottom, *left }, { *top, *right }); + result.bounds = LatLngBounds::hull({*bottom, *left}, {*top, *right}); } return result; diff --git a/src/mbgl/style/conversion/transition_options.cpp b/src/mbgl/style/conversion/transition_options.cpp index f41e138006a..e86826ab91d 100644 --- a/src/mbgl/style/conversion/transition_options.cpp +++ b/src/mbgl/style/conversion/transition_options.cpp @@ -5,7 +5,8 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator()(const Convertible& value, Error& error) const { +std::optional Converter::operator()(const Convertible& value, Error& error) + const { if (!isObject(value)) { error.message = "transition must be an object"; return std::nullopt; @@ -20,7 +21,7 @@ std::optional Converter::operator()(const error.message = "duration must be a number"; return std::nullopt; } - result->duration = { std::chrono::milliseconds(int64_t(*number)) }; + result->duration = {std::chrono::milliseconds(int64_t(*number))}; } auto delay = objectMember(value, "delay"); @@ -30,7 +31,7 @@ std::optional Converter::operator()(const error.message = "delay must be a number"; return std::nullopt; } - result->delay = { std::chrono::milliseconds(int64_t(*number)) }; + result->delay = {std::chrono::milliseconds(int64_t(*number))}; } return result; diff --git a/src/mbgl/style/custom_tile_loader.cpp b/src/mbgl/style/custom_tile_loader.cpp index eb17640dc89..a86635e4a73 100644 --- a/src/mbgl/style/custom_tile_loader.cpp +++ b/src/mbgl/style/custom_tile_loader.cpp @@ -19,10 +19,10 @@ void CustomTileLoader::fetchTile(const OverscaledTileID& tileID, const ActorRef< auto tileCallbacks = tileCallbackMap.find(tileID.canonical); if (tileCallbacks == tileCallbackMap.end()) { auto tuple = std::make_tuple(tileID.overscaledZ, tileID.wrap, tileRef); - tileCallbackMap.insert({ tileID.canonical, std::vector(1, tuple) }); + tileCallbackMap.insert({tileID.canonical, std::vector(1, tuple)}); } else { for (auto& iter : tileCallbacks->second) { - if (std::get<0>(iter) == tileID.overscaledZ && std::get<1>(iter) == tileID.wrap ) { + if (std::get<0>(iter) == tileID.overscaledZ && std::get<1>(iter) == tileID.wrap) { std::get<2>(iter) = tileRef; return; } @@ -46,7 +46,7 @@ void CustomTileLoader::removeTile(const OverscaledTileID& tileID) { auto tileCallbacks = tileCallbackMap.find(tileID.canonical); if (tileCallbacks == tileCallbackMap.end()) return; for (auto iter = tileCallbacks->second.begin(); iter != tileCallbacks->second.end(); iter++) { - if (std::get<0>(*iter) == tileID.overscaledZ && std::get<1>(*iter) == tileID.wrap ) { + if (std::get<0>(*iter) == tileID.overscaledZ && std::get<1>(*iter) == tileID.wrap) { tileCallbacks->second.erase(iter); invokeTileCancel(tileID.canonical); break; @@ -73,7 +73,9 @@ void CustomTileLoader::setTileData(const CanonicalTileID& tileID, const GeoJSON& void CustomTileLoader::invalidateTile(const CanonicalTileID& tileID) { std::lock_guard guard(dataMutex); auto tileCallbacks = tileCallbackMap.find(tileID); - if (tileCallbacks == tileCallbackMap.end()) { return; } + if (tileCallbacks == tileCallbackMap.end()) { + return; + } for (auto& iter : tileCallbacks->second) { auto actor = std::get<2>(iter); actor.invoke(&CustomGeometryTile::invalidateTileData); @@ -83,13 +85,13 @@ void CustomTileLoader::invalidateTile(const CanonicalTileID& tileID) { dataCache.erase(tileID); } -void CustomTileLoader::invalidateRegion(const LatLngBounds& bounds, Range ) { +void CustomTileLoader::invalidateRegion(const LatLngBounds& bounds, Range) { std::lock_guard guard(dataMutex); std::map tileRanges; for (auto& idtuple : tileCallbackMap) { auto zoom = idtuple.first.z; auto tileRange = tileRanges.find(zoom); - if(tileRange == tileRanges.end()) { + if (tileRange == tileRanges.end()) { tileRange = tileRanges.emplace(std::make_pair(zoom, util::TileRange::fromLatLngBounds(bounds, zoom))).first; } if (tileRange->second.contains(idtuple.first)) { diff --git a/src/mbgl/style/expression/assertion.cpp b/src/mbgl/style/expression/assertion.cpp index 982557aed9c..e05a5af3a1d 100644 --- a/src/mbgl/style/expression/assertion.cpp +++ b/src/mbgl/style/expression/assertion.cpp @@ -10,7 +10,8 @@ namespace expression { using namespace mbgl::style::conversion; Assertion::Assertion(type::Type type_, std::vector> inputs_) - : Expression(Kind::Assertion, std::move(type_)), inputs(std::move(inputs_)) { + : Expression(Kind::Assertion, std::move(type_)), + inputs(std::move(inputs_)) { assert(!inputs.empty()); } @@ -39,10 +40,7 @@ ParseResult Assertion::parse(const Convertible& value, ParsingContext& ctx) { std::optional itemTypeName = toString(arrayMember(value, 1)); auto it = itemTypeName ? types.find(*itemTypeName) : types.end(); if (it == types.end() || it->second == type::Object) { - ctx.error( - R"(The item type argument of "array" must be one of string, number, boolean)", - 1 - ); + ctx.error(R"(The item type argument of "array" must be one of string, number, boolean)", 1); return ParseResult(); } itemType = it->second; @@ -55,12 +53,8 @@ ParseResult Assertion::parse(const Convertible& value, ParsingContext& ctx) { if (length > 3) { auto m = arrayMember(value, 2); std::optional n = toNumber(m); - if (!isUndefined(m) && - (!n || *n < 0 || *n != std::floor(*n))) { - ctx.error( - R"(The length argument to "array" must be a positive integer literal.)", - 2 - ); + if (!isUndefined(m) && (!n || *n < 0 || *n != std::floor(*n))) { + ctx.error(R"(The length argument to "array" must be a positive integer literal.)", 2); return ParseResult(); } if (n) { @@ -96,19 +90,18 @@ EvaluationResult Assertion::evaluate(const EvaluationContext& params) const { if (!type::checkSubtype(getType(), typeOf(*value))) { return value; } else if (i == inputs.size() - 1) { - return EvaluationError { - "Expected value to be of type " + toString(getType()) + - ", but found " + toString(typeOf(*value)) + " instead." - }; + return EvaluationError{ + "Expected value to be of type " + toString(getType()) + ", but found " + toString(typeOf(*value)) + + " instead."}; } } assert(false); - return EvaluationError { "Unreachable" }; + return EvaluationError{"Unreachable"}; }; void Assertion::eachChild(const std::function& visit) const { - for(const std::unique_ptr& input : inputs) { + for (const std::unique_ptr& input : inputs) { visit(*input); } }; @@ -137,9 +130,8 @@ mbgl::Value Assertion::serialize() const { if (getType().is()) { const auto array = getType().get(); - if (array.itemType.is() - || array.itemType.is() - || array.itemType.is()) { + if (array.itemType.is() || array.itemType.is() || + array.itemType.is()) { serialized.emplace_back(type::toString(array.itemType)); if (array.N) { serialized.emplace_back(uint64_t(*array.N)); @@ -159,5 +151,3 @@ mbgl::Value Assertion::serialize() const { } // namespace expression } // namespace style } // namespace mbgl - - diff --git a/src/mbgl/style/expression/at.cpp b/src/mbgl/style/expression/at.cpp index 648f247830f..4bb7a3326e8 100644 --- a/src/mbgl/style/expression/at.cpp +++ b/src/mbgl/style/expression/at.cpp @@ -2,7 +2,6 @@ #include #include - namespace mbgl { namespace style { namespace expression { @@ -16,26 +15,20 @@ EvaluationResult At::evaluate(const EvaluationContext& params) const { if (!evaluatedInput) { return evaluatedInput.error(); } - + const auto i = evaluatedIndex->get(); const auto inputArray = evaluatedInput->get>(); - + if (i < 0) { - return EvaluationError { - "Array index out of bounds: " + util::toString(i) + " < 0." - }; + return EvaluationError{"Array index out of bounds: " + util::toString(i) + " < 0."}; } - + if (i >= inputArray.size()) { - return EvaluationError { - "Array index out of bounds: " + util::toString(i) + - " > " + util::toString(inputArray.size() - 1) + "." - }; + return EvaluationError{ + "Array index out of bounds: " + util::toString(i) + " > " + util::toString(inputArray.size() - 1) + "."}; } if (i != std::floor(i)) { - return EvaluationError { - "Array index must be an integer, but found " + util::toString(i) + " instead." - }; + return EvaluationError{"Array index must be an integer, but found " + util::toString(i) + " instead."}; } return inputArray[static_cast(i)]; } @@ -56,14 +49,13 @@ ParseResult At::parse(const Convertible& value, ParsingContext& ctx) { } ParseResult index = ctx.parse(arrayMember(value, 1), 1, {type::Number}); - + type::Type inputType = type::Array(ctx.getExpected() ? *ctx.getExpected() : type::Value); ParseResult input = ctx.parse(arrayMember(value, 2), 2, {inputType}); if (!index || !input) return ParseResult(); return ParseResult(std::make_unique(std::move(*index), std::move(*input))); - } } // namespace expression diff --git a/src/mbgl/style/expression/boolean_operator.cpp b/src/mbgl/style/expression/boolean_operator.cpp index 37ebc02c7b4..ea2a75af15a 100644 --- a/src/mbgl/style/expression/boolean_operator.cpp +++ b/src/mbgl/style/expression/boolean_operator.cpp @@ -29,10 +29,9 @@ bool Any::operator==(const Expression& e) const { } std::vector> Any::possibleOutputs() const { - return {{ true }, { false }}; + return {{true}, {false}}; } - EvaluationResult All::evaluate(const EvaluationContext& params) const { for (const auto& input : inputs) { EvaluationResult result = input->evaluate(params); @@ -57,29 +56,28 @@ bool All::operator==(const Expression& e) const { } std::vector> All::possibleOutputs() const { - return {{ true }, { false }}; + return {{true}, {false}}; } using namespace mbgl::style::conversion; template ParseResult parseBooleanOp(const Convertible& value, ParsingContext& ctx) { - assert(isArray(value)); auto length = arrayLength(value); - + std::vector> parsedInputs; - + parsedInputs.reserve(length - 1); for (std::size_t i = 1; i < length; i++) { auto parsed = ctx.parse(arrayMember(value, i), i, {type::Boolean}); if (!parsed) { return parsed; } - + parsedInputs.push_back(std::move(*parsed)); } - + return ParseResult(std::make_unique(std::move(parsedInputs))); } @@ -91,8 +89,6 @@ ParseResult All::parse(const Convertible& value, ParsingContext& ctx) { return parseBooleanOp(value, ctx); } - } // namespace expression } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/expression/case.cpp b/src/mbgl/style/expression/case.cpp index e8e7c64b7cf..90818a3d950 100644 --- a/src/mbgl/style/expression/case.cpp +++ b/src/mbgl/style/expression/case.cpp @@ -16,7 +16,7 @@ EvaluationResult Case::evaluate(const EvaluationContext& params) const { return branch.second->evaluate(params); } } - + return otherwise->evaluate(params); } @@ -81,7 +81,7 @@ ParseResult Case::parse(const Convertible& value, ParsingContext& ctx) { if (!output) { return output; } - + if (!outputType) { outputType = (*output)->getType(); } @@ -96,9 +96,7 @@ ParseResult Case::parse(const Convertible& value, ParsingContext& ctx) { return otherwise; } - return ParseResult(std::make_unique(*outputType, - std::move(branches), - std::move(*otherwise))); + return ParseResult(std::make_unique(*outputType, std::move(branches), std::move(*otherwise))); } } // namespace expression diff --git a/src/mbgl/style/expression/check_subtype.cpp b/src/mbgl/style/expression/check_subtype.cpp index 9f868676505..fcb3f7a57bc 100644 --- a/src/mbgl/style/expression/check_subtype.cpp +++ b/src/mbgl/style/expression/check_subtype.cpp @@ -12,9 +12,9 @@ std::string errorMessage(const Type& expected, const Type& t) { std::optional checkSubtype(const Type& expected, const Type& t) { if (t.is()) return {}; - + std::optional result = expected.match( - [&] (const Array& expectedArray) -> std::optional { + [&](const Array& expectedArray) -> std::optional { if (!t.is()) { return {errorMessage(expected, t)}; } @@ -22,15 +22,15 @@ std::optional checkSubtype(const Type& expected, const Type& t) { if (!actualArray.N || *actualArray.N != 0 || actualArray.itemType != type::Value) { const auto err = checkSubtype(expectedArray.itemType, actualArray.itemType); if (err) { - return { errorMessage(expected, t) }; + return {errorMessage(expected, t)}; } } if (expectedArray.N && expectedArray.N != actualArray.N) { - return { errorMessage(expected, t) }; + return {errorMessage(expected, t)}; } return {}; }, - [&] (const ValueType&) -> std::optional { + [&](const ValueType&) -> std::optional { if (t.is()) return {}; const Type members[] = {Null, Boolean, Number, String, Object, Color, Formatted, Image, Array(Value)}; @@ -41,16 +41,16 @@ std::optional checkSubtype(const Type& expected, const Type& t) { return {}; } } - return { errorMessage(expected, t) }; + return {errorMessage(expected, t)}; }, - [&] (const auto&) -> std::optional { + [&](const auto&) -> std::optional { if (expected != t) { - return { errorMessage(expected, t) }; + return {errorMessage(expected, t)}; } return {}; } ); - + return result; } diff --git a/src/mbgl/style/expression/coalesce.cpp b/src/mbgl/style/expression/coalesce.cpp index 71cb9ae0ed4..aff148c24b9 100644 --- a/src/mbgl/style/expression/coalesce.cpp +++ b/src/mbgl/style/expression/coalesce.cpp @@ -61,7 +61,7 @@ ParseResult Coalesce::parse(const Convertible& value, ParsingContext& ctx) { ctx.error("Expected at least one argument."); return ParseResult(); } - + std::optional outputType; std::optional expectedType = ctx.getExpected(); if (expectedType && *expectedType != type::Value) { @@ -87,10 +87,9 @@ ParseResult Coalesce::parse(const Convertible& value, ParsingContext& ctx) { // preempt the desired null-coalescing behavior. // Thus, if any of our arguments would have needed an annotation, we // need to wrap the enclosing coalesce expression with it instead. - bool needsAnnotation = expectedType && - std::any_of(args.begin(), args.end(), [&] (const auto& arg) { - return type::checkSubtype(*expectedType, arg->getType()); - }); + bool needsAnnotation = expectedType && std::any_of(args.begin(), args.end(), [&](const auto& arg) { + return type::checkSubtype(*expectedType, arg->getType()); + }); return ParseResult(std::make_unique(needsAnnotation ? type::Value : *outputType, std::move(args))); } diff --git a/src/mbgl/style/expression/coercion.cpp b/src/mbgl/style/expression/coercion.cpp index e04a86d0383..74ce2c560fa 100644 --- a/src/mbgl/style/expression/coercion.cpp +++ b/src/mbgl/style/expression/coercion.cpp @@ -9,12 +9,14 @@ namespace style { namespace expression { EvaluationResult toBoolean(const Value& v) { - return v.match([&](double f) { return static_cast(f); }, - [&](const std::string& s) { return s.length() > 0; }, - [&](bool b) { return b; }, - [&](const NullValue&) { return false; }, - [&](const Image& i) { return i.isAvailable(); }, - [&](const auto&) { return true; }); + return v.match( + [&](double f) { return static_cast(f); }, + [&](const std::string& s) { return s.length() > 0; }, + [&](bool b) { return b; }, + [&](const NullValue&) { return false; }, + [&](const Image& i) { return i.isAvailable(); }, + [&](const auto&) { return true; } + ); } EvaluationResult toNumber(const Value& v) { @@ -31,26 +33,20 @@ EvaluationResult toNumber(const Value& v) { [](const auto&) { return std::optional(); } ); if (!result) { - return EvaluationError { - "Could not convert " + stringify(v) + " to number." - }; + return EvaluationError{"Could not convert " + stringify(v) + " to number."}; } return *result; } EvaluationResult toColor(const Value& colorValue) { return colorValue.match( - [&](const Color& color) -> EvaluationResult { - return color; - }, + [&](const Color& color) -> EvaluationResult { return color; }, [&](const std::string& colorString) -> EvaluationResult { const std::optional result = Color::parse(colorString); if (result) { return *result; } else { - return EvaluationError{ - "Could not parse color from value '" + colorString + "'" - }; + return EvaluationError{"Could not parse color from value '" + colorString + "'"}; } }, [&colorValue](const std::vector& components) -> EvaluationResult { @@ -69,14 +65,12 @@ EvaluationResult toColor(const Value& colorValue) { return *c; } else { return EvaluationError{ - "Invalid rbga value " + stringify(colorValue) + ": expected an array containing either three or four numeric values." - }; + "Invalid rbga value " + stringify(colorValue) + + ": expected an array containing either three or four numeric values."}; } }, [&](const auto&) -> EvaluationResult { - return EvaluationError{ - "Could not parse color from value '" + stringify(colorValue) + "'" - }; + return EvaluationError{"Could not parse color from value '" + stringify(colorValue) + "'"}; } ); } @@ -89,10 +83,9 @@ EvaluationResult toImage(const Value& imageValue) { return Image(toString(imageValue).c_str()); } -Coercion::Coercion(type::Type type_, std::vector> inputs_) : - Expression(Kind::Coercion, std::move(type_)), - inputs(std::move(inputs_)) -{ +Coercion::Coercion(type::Type type_, std::vector> inputs_) + : Expression(Kind::Coercion, std::move(type_)), + inputs(std::move(inputs_)) { assert(!inputs.empty()); type::Type t = getType(); if (t.is()) { @@ -102,7 +95,9 @@ Coercion::Coercion(type::Type type_, std::vector> in } else if (t.is()) { coerceSingleValue = toNumber; } else if (t.is()) { - coerceSingleValue = [] (const Value& v) -> EvaluationResult { return toString(v); }; + coerceSingleValue = [](const Value& v) -> EvaluationResult { + return toString(v); + }; } else if (t.is()) { coerceSingleValue = toFormatted; } else if (t.is()) { @@ -116,7 +111,7 @@ mbgl::Value Coercion::serialize() const { if (getType().is()) { // Since there's no explicit "to-formatted" coercion, the only coercions should be created // by string expressions that get implicitly coerced to "formatted". - std::vector serialized{{ std::string("format") }}; + std::vector serialized{{std::string("format")}}; serialized.push_back(inputs[0]->serialize()); serialized.emplace_back(std::unordered_map()); return serialized; @@ -126,24 +121,27 @@ mbgl::Value Coercion::serialize() const { return Expression::serialize(); } }; - + std::string Coercion::getOperator() const { return getType().match( - [](const type::BooleanType&) { return "to-boolean"; }, - [](const type::ColorType&) { return "to-color"; }, - [](const type::NumberType&) { return "to-number"; }, - [](const type::StringType&) { return "to-string"; }, - [](const auto&) { assert(false); return ""; }); + [](const type::BooleanType&) { return "to-boolean"; }, + [](const type::ColorType&) { return "to-color"; }, + [](const type::NumberType&) { return "to-number"; }, + [](const type::StringType&) { return "to-string"; }, + [](const auto&) { + assert(false); + return ""; + } + ); } using namespace mbgl::style::conversion; ParseResult Coercion::parse(const Convertible& value, ParsingContext& ctx) { - static std::unordered_map types { + static std::unordered_map types{ {"to-boolean", type::Boolean}, {"to-color", type::Color}, {"to-number", type::Number}, - {"to-string", type::String} - }; + {"to-string", type::String}}; std::size_t length = arrayLength(value); @@ -190,11 +188,11 @@ EvaluationResult Coercion::evaluate(const EvaluationContext& params) const { } assert(false); - return EvaluationError { "Unreachable" }; + return EvaluationError{"Unreachable"}; }; void Coercion::eachChild(const std::function& visit) const { - for(const std::unique_ptr& input : inputs) { + for (const std::unique_ptr& input : inputs) { visit(*input); } }; diff --git a/src/mbgl/style/expression/collator_expression.cpp b/src/mbgl/style/expression/collator_expression.cpp index 5e489c51402..d2af3edd3c9 100644 --- a/src/mbgl/style/expression/collator_expression.cpp +++ b/src/mbgl/style/expression/collator_expression.cpp @@ -7,15 +7,16 @@ namespace mbgl { namespace style { namespace expression { - -CollatorExpression::CollatorExpression(std::unique_ptr caseSensitive_, - std::unique_ptr diacriticSensitive_, - std::optional> locale_) - : Expression(Kind::CollatorExpression, type::Collator) - , caseSensitive(std::move(caseSensitive_)) - , diacriticSensitive(std::move(diacriticSensitive_)) - , locale(std::move(locale_)) -{} + +CollatorExpression::CollatorExpression( + std::unique_ptr caseSensitive_, + std::unique_ptr diacriticSensitive_, + std::optional> locale_ +) + : Expression(Kind::CollatorExpression, type::Collator), + caseSensitive(std::move(caseSensitive_)), + diacriticSensitive(std::move(diacriticSensitive_)), + locale(std::move(locale_)) {} using namespace mbgl::style::conversion; @@ -30,13 +31,13 @@ ParseResult CollatorExpression::parse(const Convertible& value, ParsingContext& ctx.error("Collator options argument must be an object."); return ParseResult(); } - + const std::optional caseSensitiveOption = objectMember(options, "case-sensitive"); ParseResult caseSensitive; if (caseSensitiveOption) { caseSensitive = ctx.parse(*caseSensitiveOption, 1, {type::Boolean}); } else { - caseSensitive = { std::make_unique(false) }; + caseSensitive = {std::make_unique(false)}; } if (!caseSensitive) { return ParseResult(); @@ -47,12 +48,12 @@ ParseResult CollatorExpression::parse(const Convertible& value, ParsingContext& if (diacriticSensitiveOption) { diacriticSensitive = ctx.parse(*diacriticSensitiveOption, 1, {type::Boolean}); } else { - diacriticSensitive = { std::make_unique(false) }; + diacriticSensitive = {std::make_unique(false)}; } if (!diacriticSensitive) { return ParseResult(); } - + const std::optional localeOption = objectMember(options, "locale"); ParseResult locale; if (localeOption) { @@ -61,10 +62,12 @@ ParseResult CollatorExpression::parse(const Convertible& value, ParsingContext& return ParseResult(); } } - - return ParseResult(std::make_unique(std::move(*caseSensitive), std::move(*diacriticSensitive), std::move(locale))); + + return ParseResult(std::make_unique( + std::move(*caseSensitive), std::move(*diacriticSensitive), std::move(locale) + )); } - + void CollatorExpression::eachChild(const std::function& fn) const { fn(*caseSensitive); fn(*diacriticSensitive); @@ -72,16 +75,14 @@ void CollatorExpression::eachChild(const std::function& fn(**locale); } } - + bool CollatorExpression::operator==(const Expression& e) const { if (e.getKind() == Kind::CollatorExpression) { auto rhs = static_cast(&e); - if ((locale && (!rhs->locale || **locale != **(rhs->locale))) || - (!locale && rhs->locale)) { + if ((locale && (!rhs->locale || **locale != **(rhs->locale))) || (!locale && rhs->locale)) { return false; } - return *caseSensitive == *(rhs->caseSensitive) && - *diacriticSensitive == *(rhs->diacriticSensitive); + return *caseSensitive == *(rhs->caseSensitive) && *diacriticSensitive == *(rhs->diacriticSensitive); } return false; } @@ -93,9 +94,9 @@ mbgl::Value CollatorExpression::serialize() const { if (locale) { options["locale"] = (*locale)->serialize(); } - return std::vector{{ std::string("collator"), options }}; + return std::vector{{std::string("collator"), options}}; } - + EvaluationResult CollatorExpression::evaluate(const EvaluationContext& params) const { auto caseSensitiveResult = caseSensitive->evaluate(params); if (!caseSensitiveResult) { @@ -105,13 +106,15 @@ EvaluationResult CollatorExpression::evaluate(const EvaluationContext& params) c if (!diacriticSensitiveResult) { return diacriticSensitiveResult.error(); } - + if (locale) { auto localeResult = (*locale)->evaluate(params); if (!localeResult) { return localeResult.error(); } - return Collator(caseSensitiveResult->get(), diacriticSensitiveResult->get(), localeResult->get()); + return Collator( + caseSensitiveResult->get(), diacriticSensitiveResult->get(), localeResult->get() + ); } else { return Collator(caseSensitiveResult->get(), diacriticSensitiveResult->get()); } diff --git a/src/mbgl/style/expression/comparison.cpp b/src/mbgl/style/expression/comparison.cpp index 4fe4c5899f1..aa14f337cf7 100644 --- a/src/mbgl/style/expression/comparison.cpp +++ b/src/mbgl/style/expression/comparison.cpp @@ -10,15 +10,10 @@ namespace expression { static bool isComparableType(const std::string& op, const type::Type& type) { if (op == "==" || op == "!=") { - return type == type::String || - type == type::Number || - type == type::Boolean || - type == type::Null || - type == type::Value; + return type == type::String || type == type::Number || type == type::Boolean || type == type::Null || + type == type::Value; } else { - return type == type::String || - type == type::Number || - type == type::Value; + return type == type::String || type == type::Number || type == type::Value; } } @@ -32,28 +27,40 @@ bool lt(const Value& lhs, const Value& rhs) { return lhs.match( [&](const std::string& a) { return a < rhs.get(); }, [&](double a) { return a < rhs.get(); }, - [&](const auto&) { assert(false); return false; } + [&](const auto&) { + assert(false); + return false; + } ); } bool gt(const Value& lhs, const Value& rhs) { return lhs.match( [&](const std::string& a) { return a > rhs.get(); }, [&](double a) { return a > rhs.get(); }, - [&](const auto&) { assert(false); return false; } + [&](const auto&) { + assert(false); + return false; + } ); } bool lteq(const Value& lhs, const Value& rhs) { return lhs.match( [&](const std::string& a) { return a <= rhs.get(); }, [&](double a) { return a <= rhs.get(); }, - [&](const auto&) { assert(false); return false; } + [&](const auto&) { + assert(false); + return false; + } ); } bool gteq(const Value& lhs, const Value& rhs) { return lhs.match( [&](const std::string& a) { return a >= rhs.get(); }, [&](double a) { return a >= rhs.get(); }, - [&](const auto&) { assert(false); return false; } + [&](const auto&) { + assert(false); + return false; + } ); } @@ -77,33 +84,40 @@ bool gteqCollate(const std::string& a, const std::string& b, const Collator& c) } static BasicComparison::CompareFunctionType getBasicCompareFunction(const std::string& op) { - if (op == "==") return eq; - else if (op == "!=") return neq; - else if (op == ">") return gt; - else if (op == "<") return lt; - else if (op == ">=") return gteq; - else if (op == "<=") return lteq; + if (op == "==") + return eq; + else if (op == "!=") + return neq; + else if (op == ">") + return gt; + else if (op == "<") + return lt; + else if (op == ">=") + return gteq; + else if (op == "<=") + return lteq; assert(false); return nullptr; } static CollatorComparison::CompareFunctionType getCollatorComparisonFunction(const std::string& op) { - if (op == "==") return eqCollate; - else if (op == "!=") return neqCollate; - else if (op == ">") return gtCollate; - else if (op == "<") return ltCollate; - else if (op == ">=") return gteqCollate; - else if (op == "<=") return lteqCollate; + if (op == "==") + return eqCollate; + else if (op == "!=") + return neqCollate; + else if (op == ">") + return gtCollate; + else if (op == "<") + return ltCollate; + else if (op == ">=") + return gteqCollate; + else if (op == "<=") + return lteqCollate; assert(false); return nullptr; - } - -BasicComparison::BasicComparison( - std::string op_, - std::unique_ptr lhs_, - std::unique_ptr rhs_) +BasicComparison::BasicComparison(std::string op_, std::unique_ptr lhs_, std::unique_ptr rhs_) : Expression(Kind::Comparison, type::Boolean), op(std::move(op_)), compare(getBasicCompareFunction(op)), @@ -111,9 +125,9 @@ BasicComparison::BasicComparison( rhs(std::move(rhs_)) { assert(isComparableType(op, lhs->getType()) && isComparableType(op, rhs->getType())); assert(lhs->getType() == rhs->getType() || lhs->getType() == type::Value || rhs->getType() == type::Value); - + needsRuntimeTypeCheck = (op != "==" && op != "!=") && - (lhs->getType() == type::Value || rhs->getType() == type::Value); + (lhs->getType() == type::Value || rhs->getType() == type::Value); } EvaluationResult BasicComparison::evaluate(const EvaluationContext& params) const { @@ -122,20 +136,19 @@ EvaluationResult BasicComparison::evaluate(const EvaluationContext& params) cons EvaluationResult rhsResult = rhs->evaluate(params); if (!rhsResult) return rhsResult; - + if (needsRuntimeTypeCheck) { type::Type lhsType = typeOf(*lhsResult); type::Type rhsType = typeOf(*rhsResult); // check that type is string or number, and equal if (lhsType != rhsType || !(lhsType == type::String || lhsType == type::Number)) { - return EvaluationError { + return EvaluationError{ R"(Expected arguments for ")" + op + R"(")" + " to be (string, string) or (number, number), but found (" + toString(lhsType) + ", " + - toString(rhsType) + ") instead." - }; + toString(rhsType) + ") instead."}; } } - + return compare(*lhsResult, *rhsResult); } @@ -144,27 +157,28 @@ void BasicComparison::eachChild(const std::function& vi visit(*rhs); } -std::string BasicComparison::getOperator() const { return op; } +std::string BasicComparison::getOperator() const { + return op; +} bool BasicComparison::operator==(const Expression& e) const { if (e.getKind() == Kind::Comparison) { auto comp = static_cast(&e); - return comp->op == op && - *comp->lhs == *lhs && - *comp->rhs == *rhs; + return comp->op == op && *comp->lhs == *lhs && *comp->rhs == *rhs; } return false; } std::vector> BasicComparison::possibleOutputs() const { - return {{ true }, { false }}; + return {{true}, {false}}; } CollatorComparison::CollatorComparison( - std::string op_, - std::unique_ptr lhs_, - std::unique_ptr rhs_, - std::unique_ptr collator_) + std::string op_, + std::unique_ptr lhs_, + std::unique_ptr rhs_, + std::unique_ptr collator_ +) : Expression(Kind::Comparison, type::Boolean), op(std::move(op_)), compare(getCollatorComparisonFunction(op)), @@ -175,7 +189,7 @@ CollatorComparison::CollatorComparison( assert(lhs->getType() == rhs->getType() || lhs->getType() == type::Value || rhs->getType() == type::Value); needsRuntimeTypeCheck = (op == "==" || op == "!=") && - (lhs->getType() == type::Value || rhs->getType() == type::Value); + (lhs->getType() == type::Value || rhs->getType() == type::Value); } EvaluationResult CollatorComparison::evaluate(const EvaluationContext& params) const { @@ -184,16 +198,16 @@ EvaluationResult CollatorComparison::evaluate(const EvaluationContext& params) c EvaluationResult rhsResult = rhs->evaluate(params); if (!rhsResult) return lhsResult; - + if (needsRuntimeTypeCheck) { if (typeOf(*lhsResult) != type::String || typeOf(*rhsResult) != type::String) { return getBasicCompareFunction(op)(*lhsResult, *rhsResult); } } - + auto collatorResult = collator->evaluate(params); if (!collatorResult) return collatorResult; - + const Collator& c = collatorResult->get(); return compare(lhsResult->get(), rhsResult->get(), c); } @@ -204,21 +218,20 @@ void CollatorComparison::eachChild(const std::function& visit(*collator); } -std::string CollatorComparison::getOperator() const { return op; } +std::string CollatorComparison::getOperator() const { + return op; +} bool CollatorComparison::operator==(const Expression& e) const { if (e.getKind() == Kind::Comparison) { auto comp = static_cast(&e); - return comp->op == op && - *comp->collator == *collator && - *comp->lhs == *lhs && - *comp->rhs == *rhs; + return comp->op == op && *comp->collator == *collator && *comp->lhs == *lhs && *comp->rhs == *rhs; } return false; } std::vector> CollatorComparison::possibleOutputs() const { - return {{ true }, { false }}; + return {{true}, {false}}; } using namespace mbgl::style::conversion; @@ -229,9 +242,9 @@ ParseResult parseComparison(const Convertible& value, ParsingContext& ctx) { ctx.error("Expected two or three arguments."); return ParseResult(); } - + std::string op = *toString(arrayMember(value, 0)); - + assert(getBasicCompareFunction(op)); ParseResult lhs = ctx.parse(arrayMember(value, 1), 1, {type::Value}); @@ -250,15 +263,11 @@ ParseResult parseComparison(const Convertible& value, ParsingContext& ctx) { return ParseResult(); } - if ( - lhsType != rhsType && - lhsType != type::Value && - rhsType != type::Value - ) { + if (lhsType != rhsType && lhsType != type::Value && rhsType != type::Value) { ctx.error("Cannot compare types '" + toString(lhsType) + "' and '" + toString(rhsType) + "'."); return ParseResult(); } - + if (op != "==" && op != "!=") { // typing rules specific to less/greater than operators if (lhsType == type::Value && rhsType != type::Value) { @@ -269,22 +278,19 @@ ParseResult parseComparison(const Convertible& value, ParsingContext& ctx) { rhs = dsl::assertion(lhsType, std::move(*rhs)); } } - + if (length == 4) { - if ( - lhsType != type::String && - rhsType != type::String && - lhsType != type::Value && - rhsType != type::Value - ) { + if (lhsType != type::String && rhsType != type::String && lhsType != type::Value && rhsType != type::Value) { ctx.error("Cannot use collator to compare non-string types."); return ParseResult(); } ParseResult collatorParseResult = ctx.parse(arrayMember(value, 3), 3, {type::Collator}); if (!collatorParseResult) return ParseResult(); - return ParseResult(std::make_unique(op, std::move(*lhs), std::move(*rhs), std::move(*collatorParseResult))); + return ParseResult( + std::make_unique(op, std::move(*lhs), std::move(*rhs), std::move(*collatorParseResult)) + ); } - + return ParseResult(std::make_unique(op, std::move(*lhs), std::move(*rhs))); } diff --git a/src/mbgl/style/expression/compound_expression.cpp b/src/mbgl/style/expression/compound_expression.cpp index a814343c911..5e88acd6cbc 100644 --- a/src/mbgl/style/expression/compound_expression.cpp +++ b/src/mbgl/style/expression/compound_expression.cpp @@ -25,7 +25,9 @@ namespace expression { Represents the parameter list for an expression that takes an arbitrary number of arguments (of a specific type). */ -struct VarargsType { type::Type type; }; +struct VarargsType { + type::Type type; +}; bool operator==(const VarargsType& lhs, const VarargsType& rhs) { return lhs.type == rhs.type; @@ -34,7 +36,8 @@ bool operator==(const VarargsType& lhs, const VarargsType& rhs) { template struct Varargs : std::vector { template - explicit Varargs(Args&&... args) : std::vector(std::forward(args)...) {} + explicit Varargs(Args&&... args) + : std::vector(std::forward(args)...) {} }; namespace detail { @@ -44,11 +47,10 @@ namespace detail { struct SignatureBase { using Args = std::vector>; - SignatureBase(type::Type result_, variant, VarargsType> params_, std::string name_) : - result(std::move(result_)), - params(std::move(params_)), - name(std::move(name_)) - {} + SignatureBase(type::Type result_, variant, VarargsType> params_, std::string name_) + : result(std::move(result_)), + params(std::move(params_)), + name(std::move(name_)) {} virtual ~SignatureBase() = default; virtual EvaluationResult apply(const EvaluationContext&, const Args&) const = 0; @@ -62,20 +64,20 @@ struct SignatureBase { The Signature structs are wrappers around an "evaluate()" function whose purpose is to extract the necessary Type data from the evaluate function's type. There are three key (partial) specializations: - + Signature: Wraps a simple evaluate function (const T0&, const T1&, ...) -> Result - + Signature&)>: Wraps an evaluate function that takes an arbitrary number of arguments (via a Varargs, which is just an alias for std::vector). - + Signature: Wraps an evaluate function that needs to access the expression evaluation parameters in addition to its subexpressions, i.e., (const EvaluationParams&, const T0&, const T1&, ...) -> Result. Needed for expressions like ["zoom"], ["get", key], etc. - + In each of the above evaluate signatures, T0, T1, etc. are the types of the successfully evaluated subexpressions. */ @@ -84,11 +86,13 @@ struct Signature; // Simple evaluate function (const T0&, const T1&, ...) -> Result template -struct Signature : SignatureBase { +struct Signature : SignatureBase { Signature(R (*evaluate_)(Params...), const std::string& name_) - : SignatureBase(valueTypeToExpressionType>(), - std::vector{valueTypeToExpressionType>()...}, - name_), + : SignatureBase( + valueTypeToExpressionType>(), + std::vector{valueTypeToExpressionType>()...}, + name_ + ), evaluate(evaluate_) {} EvaluationResult apply(const EvaluationContext& evaluationParameters, const Args& args) const override { @@ -98,8 +102,9 @@ struct Signature : SignatureBase { R (*evaluate)(Params...); private: - template - EvaluationResult applyImpl(const EvaluationContext& evaluationParameters, const Args& args, std::index_sequence) const { + template + EvaluationResult + applyImpl(const EvaluationContext& evaluationParameters, const Args& args, std::index_sequence) const { std::array evaluated; for (int i = 0; i < int(sizeof...(Params)); ++i) { const EvaluationResult evaluatedArg = args.at(i)->evaluate(evaluationParameters); @@ -114,11 +119,13 @@ struct Signature : SignatureBase { // Varargs evaluate function (const Varargs&) -> Result template -struct Signature&)> : SignatureBase { +struct Signature&)> : SignatureBase { Signature(R (*evaluate_)(const Varargs&), const std::string& name_) - : SignatureBase(valueTypeToExpressionType>(), - VarargsType{valueTypeToExpressionType()}, - name_), + : SignatureBase( + valueTypeToExpressionType>(), + VarargsType{valueTypeToExpressionType()}, + name_ + ), evaluate(evaluate_) {} EvaluationResult apply(const EvaluationContext& evaluationParameters, const Args& args) const override { @@ -126,7 +133,7 @@ struct Signature&)> : SignatureBase { evaluated.reserve(args.size()); for (const auto& arg : args) { const EvaluationResult evaluatedArg = arg->evaluate(evaluationParameters); - if(!evaluatedArg) return evaluatedArg.error(); + if (!evaluatedArg) return evaluatedArg.error(); evaluated.push_back(*fromExpressionValue>(*evaluatedArg)); } const R value = evaluate(evaluated); @@ -140,11 +147,13 @@ struct Signature&)> : SignatureBase { // Evaluate function needing parameter access, // (const EvaluationParams&, const T0&, const T1&, ...) -> Result template -struct Signature : SignatureBase { +struct Signature : SignatureBase { Signature(R (*evaluate_)(const EvaluationContext&, Params...), const std::string& name_) - : SignatureBase(valueTypeToExpressionType>(), - std::vector{valueTypeToExpressionType>()...}, - name_), + : SignatureBase( + valueTypeToExpressionType>(), + std::vector{valueTypeToExpressionType>()...}, + name_ + ), evaluate(evaluate_) {} EvaluationResult apply(const EvaluationContext& evaluationParameters, const Args& args) const override { @@ -152,8 +161,9 @@ struct Signature : SignatureBase { } private: - template - EvaluationResult applyImpl(const EvaluationContext& evaluationParameters, const Args& args, std::index_sequence) const { + template + EvaluationResult + applyImpl(const EvaluationContext& evaluationParameters, const Args& args, std::index_sequence) const { std::array evaluated; for (int i = 0; i < int(sizeof...(Params)); ++i) { const EvaluationResult evaluatedArg = args.at(i)->evaluate(evaluationParameters); @@ -167,15 +177,17 @@ struct Signature : SignatureBase { R (*evaluate)(const EvaluationContext&, Params...); }; - + // Evaluate function needing EvaluationContext and Varargs // (const EvaluationContext&, const Varargs&) -> Result template -struct Signature&)> : SignatureBase { +struct Signature&)> : SignatureBase { Signature(R (*evaluate_)(const EvaluationContext&, const Varargs&), const std::string& name_) - : SignatureBase(valueTypeToExpressionType>(), - VarargsType{valueTypeToExpressionType()}, - name_), + : SignatureBase( + valueTypeToExpressionType>(), + VarargsType{valueTypeToExpressionType()}, + name_ + ), evaluate(evaluate_) {} EvaluationResult apply(const EvaluationContext& evaluationParameters, const Args& args) const override { @@ -183,7 +195,7 @@ struct Signature&)> : SignatureBas evaluated.reserve(args.size()); for (const auto& arg : args) { const EvaluationResult evaluatedArg = arg->evaluate(evaluationParameters); - if(!evaluatedArg) return evaluatedArg.error(); + if (!evaluatedArg) return evaluatedArg.error(); evaluated.push_back(*fromExpressionValue>(*evaluatedArg)); } const R value = evaluate(evaluationParameters, evaluated); @@ -199,12 +211,14 @@ template struct SignatureType; template -struct SignatureType -{ using Type = R (Params...); }; +struct SignatureType { + using Type = R(Params...); +}; template -struct SignatureType>> -{ using Type = typename SignatureType::Type; }; +struct SignatureType>> { + using Type = typename SignatureType::Type; +}; template static std::unique_ptr makeSignature(std::string name, Fn evaluateFunction) { @@ -217,9 +231,7 @@ Value featureIdAsExpressionValue(const EvaluationContext& params) { assert(params.feature); auto id = params.feature->getID(); if (id.is()) return Null; - return id.match([](const auto& idid) { - return toExpressionValue(mbgl::Value(idid)); - }); + return id.match([](const auto& idid) { return toExpressionValue(mbgl::Value(idid)); }); }; std::optional featurePropertyAsExpressionValue(const EvaluationContext& params, const std::string& key) { @@ -229,17 +241,17 @@ std::optional featurePropertyAsExpressionValue(const EvaluationContext& p }; std::optional featureTypeAsString(FeatureType type) { - switch(type) { - case FeatureType::Point: - return std::optional("Point"); - case FeatureType::LineString: - return std::optional("LineString"); - case FeatureType::Polygon: - return std::optional("Polygon"); - case FeatureType::Unknown: - return std::optional("Unknown"); - default: - return {}; + switch (type) { + case FeatureType::Point: + return std::optional("Point"); + case FeatureType::LineString: + return std::optional("LineString"); + case FeatureType::Polygon: + return std::optional("Polygon"); + case FeatureType::Unknown: + return std::optional("Unknown"); + default: + return {}; } }; @@ -247,27 +259,32 @@ std::optional featurePropertyAsDouble(const EvaluationContext& params, c assert(params.feature); auto property = params.feature->getValue(key); if (!property) return {}; - return property->match([](double value) { return value; }, - [](uint64_t value) -> std::optional { return {static_cast(value)}; }, - [](int64_t value) -> std::optional { return {static_cast(value)}; }, - [](const auto&) -> std::optional { return std::nullopt; }); + return property->match( + [](double value) { return value; }, + [](uint64_t value) -> std::optional { return {static_cast(value)}; }, + [](int64_t value) -> std::optional { return {static_cast(value)}; }, + [](const auto&) -> std::optional { return std::nullopt; } + ); }; std::optional featurePropertyAsString(const EvaluationContext& params, const std::string& key) { assert(params.feature); auto property = params.feature->getValue(key); if (!property) return {}; - return property->match([](std::string value) { return value; }, - [](const auto&) { return std::optional(); }); + return property->match( + [](std::string value) { return value; }, [](const auto&) { return std::optional(); } + ); }; std::optional featureIdAsDouble(const EvaluationContext& params) { assert(params.feature); auto id = params.feature->getID(); - return id.match([](double value) { return value; }, - [](uint64_t value) -> std::optional { return {static_cast(value)}; }, - [](int64_t value) -> std::optional { return {static_cast(value)}; }, - [](const auto&) -> std::optional { return std::nullopt; }); + return id.match( + [](double value) { return value; }, + [](uint64_t value) -> std::optional { return {static_cast(value)}; }, + [](int64_t value) -> std::optional { return {static_cast(value)}; }, + [](const auto&) -> std::optional { return std::nullopt; } + ); }; std::optional featureIdAsString(const EvaluationContext& params) { @@ -292,7 +309,9 @@ const auto& ln2CompoundExpression() { } const auto& typeofCompoundExpression() { - static auto signature = detail::makeSignature("typeof", [](const Value& v) -> Result { return toString(typeOf(v)); }); + static auto signature = detail::makeSignature("typeof", [](const Value& v) -> Result { + return toString(typeOf(v)); + }); return signature; } @@ -304,21 +323,23 @@ const auto& toRgbaCompoundExpression() { } const auto& rgbaCompoundExpression() { - static auto signature = detail::makeSignature("rgba", [](double r, double g, double b, double a) { return rgba(r, g, b, a); }); + static auto signature = detail::makeSignature("rgba", [](double r, double g, double b, double a) { + return rgba(r, g, b, a); + }); return signature; } const auto& rgbCompoundExpression() { - static auto signature = detail::makeSignature("rgb", [](double r, double g, double b) { return rgba(r, g, b, 1.0f); }); + static auto signature = detail::makeSignature("rgb", [](double r, double g, double b) { + return rgba(r, g, b, 1.0f); + }); return signature; } const auto& zoomCompoundExpression() { static auto signature = detail::makeSignature("zoom", [](const EvaluationContext& params) -> Result { if (!params.zoom) { - return EvaluationError { - "The 'zoom' expression is unavailable in the current evaluation context." - }; + return EvaluationError{"The 'zoom' expression is unavailable in the current evaluation context."}; } return *(params.zoom); }); @@ -326,142 +347,140 @@ const auto& zoomCompoundExpression() { } const auto& heatmapDensityCompoundExpression() { - static auto signature = detail::makeSignature("heatmap-density", [](const EvaluationContext& params) -> Result { - if (!params.colorRampParameter) { - return EvaluationError { - "The 'heatmap-density' expression is unavailable in the current evaluation context." - }; - } - return *(params.colorRampParameter); - }); + static auto signature = + detail::makeSignature("heatmap-density", [](const EvaluationContext& params) -> Result { + if (!params.colorRampParameter) { + return EvaluationError{ + "The 'heatmap-density' expression is unavailable in the current evaluation context."}; + } + return *(params.colorRampParameter); + }); return signature; } const auto& lineProgressCompoundExpression() { - static auto signature = detail::makeSignature("line-progress", [](const EvaluationContext& params) -> Result { - if (!params.colorRampParameter) { - return EvaluationError { - "The 'line-progress' expression is unavailable in the current evaluation context." - }; - } - return *(params.colorRampParameter); - }); + static auto signature = + detail::makeSignature("line-progress", [](const EvaluationContext& params) -> Result { + if (!params.colorRampParameter) { + return EvaluationError{ + "The 'line-progress' expression is unavailable in the current evaluation context."}; + } + return *(params.colorRampParameter); + }); return signature; } const auto& accumulatedCompoundExpression() { - const static auto signature = detail::makeSignature("accumulated", [](const EvaluationContext& params) -> Result { - if (!params.accumulated) { - return EvaluationError { - "The 'accumulated' expression is unavailable in the current evaluation context." - }; - } - return Value(toExpressionValue(*params.accumulated)); - }); + const static auto signature = + detail::makeSignature("accumulated", [](const EvaluationContext& params) -> Result { + if (!params.accumulated) { + return EvaluationError{ + "The 'accumulated' expression is unavailable in the current evaluation context."}; + } + return Value(toExpressionValue(*params.accumulated)); + }); return signature; } - + const auto& hasContextCompoundExpression() { - static auto signature = detail::makeSignature("has", [](const EvaluationContext& params, const std::string& key) -> Result { - if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; - } + static auto signature = + detail::makeSignature("has", [](const EvaluationContext& params, const std::string& key) -> Result { + if (!params.feature) { + return EvaluationError{"Feature data is unavailable in the current evaluation context."}; + } - return static_cast(params.feature->getValue(key)); - }); + return static_cast(params.feature->getValue(key)); + }); return signature; } const auto& hasObjectCompoundExpression() { - static auto signature = detail::makeSignature("has", [](const std::string& key, const std::unordered_map& object) -> Result { - return object.find(key) != object.end(); - }); + static auto signature = detail::makeSignature( + "has", + [](const std::string& key, const std::unordered_map& object) -> Result { + return object.find(key) != object.end(); + } + ); return signature; } const auto& getContextCompoundExpression() { - static auto signature = detail::makeSignature("get", [](const EvaluationContext& params, const std::string& key) -> Result { - if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; - } + static auto signature = + detail::makeSignature("get", [](const EvaluationContext& params, const std::string& key) -> Result { + if (!params.feature) { + return EvaluationError{"Feature data is unavailable in the current evaluation context."}; + } - auto propertyValue = params.feature->getValue(key); - if (!propertyValue) { - return Null; - } - return Value(toExpressionValue(*propertyValue)); - }); + auto propertyValue = params.feature->getValue(key); + if (!propertyValue) { + return Null; + } + return Value(toExpressionValue(*propertyValue)); + }); return signature; } const auto& getObjectCompoundExpression() { - static auto signature = detail::makeSignature("get", [](const std::string& key, const std::unordered_map& object) -> Result { - if (object.find(key) == object.end()) { - return Null; + static auto signature = detail::makeSignature( + "get", + [](const std::string& key, const std::unordered_map& object) -> Result { + if (object.find(key) == object.end()) { + return Null; + } + return object.at(key); } - return object.at(key); - }); + ); return signature; } const auto& propertiesCompoundExpression() { - static auto signature = detail::makeSignature("properties", [](const EvaluationContext& params) -> Result> { - if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; - } - std::unordered_map result; - const PropertyMap& properties = params.feature->getProperties(); - result.reserve(properties.size()); - for (const auto& entry : properties) { - result[entry.first] = toExpressionValue(entry.second); + static auto signature = detail::makeSignature( + "properties", + [](const EvaluationContext& params) -> Result> { + if (!params.feature) { + return EvaluationError{"Feature data is unavailable in the current evaluation context."}; + } + std::unordered_map result; + const PropertyMap& properties = params.feature->getProperties(); + result.reserve(properties.size()); + for (const auto& entry : properties) { + result[entry.first] = toExpressionValue(entry.second); + } + return result; } - return result; - }); + ); return signature; } const auto& geometryTypeCompoundExpression() { - static auto signature = detail::makeSignature("geometry-type", [](const EvaluationContext& params) -> Result { - if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; - } + static auto signature = + detail::makeSignature("geometry-type", [](const EvaluationContext& params) -> Result { + if (!params.feature) { + return EvaluationError{"Feature data is unavailable in the current evaluation context."}; + } - auto type = params.feature->getType(); - if (type == FeatureType::Point) { - return "Point"; - } else if (type == FeatureType::LineString) { - return "LineString"; - } else if (type == FeatureType::Polygon) { - return "Polygon"; - } else { - return "Unknown"; - } - }); + auto type = params.feature->getType(); + if (type == FeatureType::Point) { + return "Point"; + } else if (type == FeatureType::LineString) { + return "LineString"; + } else if (type == FeatureType::Polygon) { + return "Polygon"; + } else { + return "Unknown"; + } + }); return signature; } const auto& idCompoundExpression() { static auto signature = detail::makeSignature("id", [](const EvaluationContext& params) -> Result { if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; + return EvaluationError{"Feature data is unavailable in the current evaluation context."}; } auto id = params.feature->getID(); - return id.match( - [](const auto& idValue) { - return toExpressionValue(mbgl::Value(idValue)); - } - ); + return id.match([](const auto& idValue) { return toExpressionValue(mbgl::Value(idValue)); }); }); return signature; } @@ -651,22 +670,23 @@ const auto& concatCompoundExpression() { } const auto& resolvedLocaleCompoundExpression() { - static auto signature = detail::makeSignature("resolved-locale", [](const Collator& collator) -> Result { - return collator.resolvedLocale(); - }); + static auto signature = detail::makeSignature( + "resolved-locale", [](const Collator& collator) -> Result { return collator.resolvedLocale(); } + ); return signature; } const auto& errorCompoundExpression() { static auto signature = detail::makeSignature("error", [](const std::string& input) -> Result { - return EvaluationError { input }; + return EvaluationError{input}; }); return signature; } const auto& featureStateCompoundExpression() { static auto signature = detail::makeSignature( - "feature-state", [](const EvaluationContext& params, const std::string& key) -> Result { + "feature-state", + [](const EvaluationContext& params, const std::string& key) -> Result { mbgl::Value state; if (params.featureState != nullptr) { auto it = params.featureState->find(key); @@ -675,39 +695,50 @@ const auto& featureStateCompoundExpression() { } } return toExpressionValue(state); - }); + } + ); return signature; } // Legacy Filters const auto& filterEqualsCompoundExpression() { - static auto signature = detail::makeSignature("filter-==", [](const EvaluationContext& params, const std::string& key, const Value &lhs) -> Result { - const auto rhs = featurePropertyAsExpressionValue(params, key); - return rhs ? lhs == *rhs : false; - }); + static auto signature = detail::makeSignature( + "filter-==", + [](const EvaluationContext& params, const std::string& key, const Value& lhs) -> Result { + const auto rhs = featurePropertyAsExpressionValue(params, key); + return rhs ? lhs == *rhs : false; + } + ); return signature; } const auto& filterIdEqualsCompoundExpression() { - static auto signature = detail::makeSignature("filter-id-==", [](const EvaluationContext& params, const Value &lhs) -> Result { - return lhs == featureIdAsExpressionValue(params); - }); + static auto signature = + detail::makeSignature("filter-id-==", [](const EvaluationContext& params, const Value& lhs) -> Result { + return lhs == featureIdAsExpressionValue(params); + }); return signature; } const auto& filterTypeEqualsCompoundExpression() { - static auto signature = detail::makeSignature("filter-type-==", [](const EvaluationContext& params, const std::string &lhs) -> Result { - if (!params.feature) return false; - return featureTypeAsString(params.feature->getType()) == lhs; - }); + static auto signature = detail::makeSignature( + "filter-type-==", + [](const EvaluationContext& params, const std::string& lhs) -> Result { + if (!params.feature) return false; + return featureTypeAsString(params.feature->getType()) == lhs; + } + ); return signature; } const auto& filterLessThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-<", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { - auto rhs = featurePropertyAsDouble(params, key); - return rhs ? rhs < lhs : false; - }); + static auto signature = detail::makeSignature( + "filter-<", + [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { + auto rhs = featurePropertyAsDouble(params, key); + return rhs ? rhs < lhs : false; + } + ); return signature; } @@ -717,32 +748,39 @@ const auto& filterLessThanStringCompoundExpression() { [](const EvaluationContext& params, const std::string& key, const std::string& lhs) -> Result { auto rhs = featurePropertyAsString(params, key); return rhs ? rhs < lhs : false; - }); + } + ); return signature; } const auto& filterIdLessThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-id-<", [](const EvaluationContext& params, double lhs) -> Result { - auto rhs = featureIdAsDouble(params); - return rhs ? rhs < lhs : false; - }); + static auto signature = + detail::makeSignature("filter-id-<", [](const EvaluationContext& params, double lhs) -> Result { + auto rhs = featureIdAsDouble(params); + return rhs ? rhs < lhs : false; + }); return signature; } const auto& filterIdLessThanStringCompoundExpression() { static auto signature = detail::makeSignature( - "filter-id-<", [](const EvaluationContext& params, const std::string& lhs) -> Result { + "filter-id-<", + [](const EvaluationContext& params, const std::string& lhs) -> Result { auto rhs = featureIdAsString(params); return rhs ? rhs < lhs : false; - }); + } + ); return signature; } const auto& filterMoreThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter->", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { - auto rhs = featurePropertyAsDouble(params, key); - return rhs ? rhs > lhs : false; - }); + static auto signature = detail::makeSignature( + "filter->", + [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { + auto rhs = featurePropertyAsDouble(params, key); + return rhs ? rhs > lhs : false; + } + ); return signature; } @@ -752,32 +790,39 @@ const auto& filterMoreThanStringCompoundExpression() { [](const EvaluationContext& params, const std::string& key, const std::string& lhs) -> Result { auto rhs = featurePropertyAsString(params, key); return rhs ? rhs > lhs : false; - }); + } + ); return signature; } const auto& filterIdMoreThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-id->", [](const EvaluationContext& params, double lhs) -> Result { - auto rhs = featureIdAsDouble(params); - return rhs ? rhs > lhs : false; - }); + static auto signature = + detail::makeSignature("filter-id->", [](const EvaluationContext& params, double lhs) -> Result { + auto rhs = featureIdAsDouble(params); + return rhs ? rhs > lhs : false; + }); return signature; } const auto& filterIdMoreThanStringCompoundExpression() { static auto signature = detail::makeSignature( - "filter-id->", [](const EvaluationContext& params, const std::string& lhs) -> Result { + "filter-id->", + [](const EvaluationContext& params, const std::string& lhs) -> Result { auto rhs = featureIdAsString(params); return rhs ? rhs > lhs : false; - }); + } + ); return signature; } const auto& filterLessOrEqualThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-<=", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { - auto rhs = featurePropertyAsDouble(params, key); - return rhs ? rhs <= lhs : false; - }); + static auto signature = detail::makeSignature( + "filter-<=", + [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { + auto rhs = featurePropertyAsDouble(params, key); + return rhs ? rhs <= lhs : false; + } + ); return signature; } @@ -787,32 +832,39 @@ const auto& filterLessOrEqualThanStringCompoundExpression() { [](const EvaluationContext& params, const std::string& key, const std::string& lhs) -> Result { auto rhs = featurePropertyAsString(params, key); return rhs ? rhs <= lhs : false; - }); + } + ); return signature; } const auto& filterIdLessOrEqualThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-id-<=", [](const EvaluationContext& params, double lhs) -> Result { - auto rhs = featureIdAsDouble(params); - return rhs ? rhs <= lhs : false; - }); + static auto signature = + detail::makeSignature("filter-id-<=", [](const EvaluationContext& params, double lhs) -> Result { + auto rhs = featureIdAsDouble(params); + return rhs ? rhs <= lhs : false; + }); return signature; } const auto& filterIdLessOrEqualThanStringCompoundExpression() { static auto signature = detail::makeSignature( - "filter-id-<=", [](const EvaluationContext& params, const std::string& lhs) -> Result { + "filter-id-<=", + [](const EvaluationContext& params, const std::string& lhs) -> Result { auto rhs = featureIdAsString(params); return rhs ? rhs <= lhs : false; - }); + } + ); return signature; } const auto& filterGreaterOrEqualThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter->=", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { - auto rhs = featurePropertyAsDouble(params, key); - return rhs ? rhs >= lhs : false; - }); + static auto signature = detail::makeSignature( + "filter->=", + [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { + auto rhs = featurePropertyAsDouble(params, key); + return rhs ? rhs >= lhs : false; + } + ); return signature; } @@ -822,32 +874,39 @@ const auto& filterGreaterOrEqualThanStringCompoundExpression() { [](const EvaluationContext& params, const std::string& key, const std::string& lhs) -> Result { auto rhs = featurePropertyAsString(params, key); return rhs ? rhs >= lhs : false; - }); + } + ); return signature; } const auto& filterIdGreaterOrEqualThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-id->=", [](const EvaluationContext& params, double lhs) -> Result { - auto rhs = featureIdAsDouble(params); - return rhs ? rhs >= lhs : false; - }); + static auto signature = + detail::makeSignature("filter-id->=", [](const EvaluationContext& params, double lhs) -> Result { + auto rhs = featureIdAsDouble(params); + return rhs ? rhs >= lhs : false; + }); return signature; } const auto& filterIdGreaterOrEqualThanStringCompoundExpression() { static auto signature = detail::makeSignature( - "filter-id->=", [](const EvaluationContext& params, const std::string& lhs) -> Result { + "filter-id->=", + [](const EvaluationContext& params, const std::string& lhs) -> Result { auto rhs = featureIdAsString(params); return rhs ? rhs >= lhs : false; - }); + } + ); return signature; } const auto& filterHasCompoundExpression() { - static auto signature = detail::makeSignature("filter-has", [](const EvaluationContext& params, const std::string& key) -> Result { - assert(params.feature); - return bool(params.feature->getValue(key)); - }); + static auto signature = detail::makeSignature( + "filter-has", + [](const EvaluationContext& params, const std::string& key) -> Result { + assert(params.feature); + return bool(params.feature->getValue(key)); + } + ); return signature; } @@ -860,30 +919,38 @@ const auto& filterHasIdCompoundExpression() { } const auto& filterTypeInCompoundExpression() { - static auto signature = detail::makeSignature("filter-type-in", [](const EvaluationContext& params, const Varargs& types) -> Result { - assert(params.feature); - std::optional type = featureTypeAsString(params.feature->getType()); - return std::find(types.begin(), types.end(), type) != types.end(); - }); + static auto signature = detail::makeSignature( + "filter-type-in", + [](const EvaluationContext& params, const Varargs& types) -> Result { + assert(params.feature); + std::optional type = featureTypeAsString(params.feature->getType()); + return std::find(types.begin(), types.end(), type) != types.end(); + } + ); return signature; } const auto& filterIdInCompoundExpression() { - static auto signature = detail::makeSignature("filter-id-in", [](const EvaluationContext& params, const Varargs& ids) -> Result { - auto id = featureIdAsExpressionValue(params); - return std::find(ids.begin(), ids.end(), id) != ids.end(); - }); + static auto signature = detail::makeSignature( + "filter-id-in", + [](const EvaluationContext& params, const Varargs& ids) -> Result { + auto id = featureIdAsExpressionValue(params); + return std::find(ids.begin(), ids.end(), id) != ids.end(); + } + ); return signature; } - const auto& filterInCompoundExpression() { - static auto signature = detail::makeSignature("filter-in", [](const EvaluationContext& params, const Varargs& varargs) -> Result { - if (varargs.size() < 2) return false; - assert(varargs[0].is()); - auto value = featurePropertyAsExpressionValue(params, varargs[0].get()); - return value ? std::find(varargs.begin() + 1, varargs.end(), *value) != varargs.end() : false; - }); + static auto signature = detail::makeSignature( + "filter-in", + [](const EvaluationContext& params, const Varargs& varargs) -> Result { + if (varargs.size() < 2) return false; + assert(varargs[0].is()); + auto value = featurePropertyAsExpressionValue(params, varargs[0].get()); + return value ? std::find(varargs.begin() + 1, varargs.end(), *value) != varargs.end() : false; + } + ); return signature; } @@ -971,38 +1038,36 @@ using namespace mbgl::style::conversion; using DefinitionIterator = decltype(compoundExpressionRegistry)::const_iterator; using Definitions = std::pair; -std::string expectedTypesError(const Definitions& definitions, - const std::vector>& args) { +std::string expectedTypesError(const Definitions& definitions, const std::vector>& args) { std::vector availableOverloads; // Only used if there are no overloads with matching number of args std::vector overloads; for (auto it = definitions.first; it != definitions.second; ++it) { const auto& signature = it->second(); signature->params.match( - [&](const VarargsType& varargs) { - std::string overload = "(" + toString(varargs.type) + ")"; - overloads.push_back(overload); - }, - [&](const std::vector& params) { - std::string overload = "("; - bool first = true; - for (const type::Type& param : params) { - if (!first) overload += ", "; - overload += toString(param); - first = false; - } - overload += ")"; - if (params.size() == args.size()) { + [&](const VarargsType& varargs) { + std::string overload = "(" + toString(varargs.type) + ")"; overloads.push_back(overload); - } else { - availableOverloads.push_back(overload); + }, + [&](const std::vector& params) { + std::string overload = "("; + bool first = true; + for (const type::Type& param : params) { + if (!first) overload += ", "; + overload += toString(param); + first = false; + } + overload += ")"; + if (params.size() == args.size()) { + overloads.push_back(overload); + } else { + availableOverloads.push_back(overload); + } } - } ); } - std::string signatures = overloads.empty() ? - boost::algorithm::join(availableOverloads, " | ") : - boost::algorithm::join(overloads, " | "); - + std::string signatures = overloads.empty() ? boost::algorithm::join(availableOverloads, " | ") + : boost::algorithm::join(overloads, " | "); + std::string actualTypes; for (const auto& arg : args) { if (!actualTypes.empty()) { @@ -1010,14 +1075,13 @@ std::string expectedTypesError(const Definitions& definitions, } actualTypes += toString(arg->getType()); } - + return "Expected arguments of type " + signatures + ", but found (" + actualTypes + ") instead."; } -static ParseResult createCompoundExpression(const Definitions& definitions, - std::vector> args, - ParsingContext& ctx) -{ +static ParseResult createCompoundExpression( + const Definitions& definitions, std::vector> args, ParsingContext& ctx +) { ParsingContext signatureContext(ctx.getKey()); for (auto it = definitions.first; it != definitions.second; ++it) { @@ -1028,8 +1092,8 @@ static ParseResult createCompoundExpression(const Definitions& definitions, const std::vector& params = signature->params.get>(); if (params.size() != args.size()) { signatureContext.error( - "Expected " + util::toString(params.size()) + - " arguments, but found " + util::toString(args.size()) + " instead." + "Expected " + util::toString(params.size()) + " arguments, but found " + + util::toString(args.size()) + " instead." ); continue; } @@ -1071,22 +1135,17 @@ ParseResult parseCompoundExpression(const std::string& name, const Convertible& const auto definitions = compoundExpressionRegistry.equal_range(name.c_str()); if (definitions.first == definitions.second) { - ctx.error( - R"(Unknown expression ")" + name + R"(". If you wanted a literal array, use ["literal", [...]].)", - 0 - ); + ctx.error(R"(Unknown expression ")" + name + R"(". If you wanted a literal array, use ["literal", [...]].)", 0); return ParseResult(); } auto length = arrayLength(value); - + for (auto it = definitions.first; it != definitions.second; ++it) { const auto& signature = it->second(); - if ( - signature->params.is() || - signature->params.get>().size() == length - 1 - ) { + if (signature->params.is() || + signature->params.get>().size() == length - 1) { // First parse all the args, potentially coercing to the // types expected by this overload. ctx.clearErrors(); @@ -1124,7 +1183,7 @@ ParseResult parseCompoundExpression(const std::string& name, const Convertible& ctx.clearErrors(); std::vector> args; args.reserve(length - 1); - + for (std::size_t i = 1; i < length; i++) { auto parsed = ctx.parse(arrayMember(value, i), i); if (!parsed) { @@ -1138,18 +1197,18 @@ ParseResult parseCompoundExpression(const std::string& name, const Convertible& return ParseResult(); } -ParseResult createCompoundExpression(const std::string& name, - std::vector> args, - ParsingContext& ctx) -{ +ParseResult createCompoundExpression( + const std::string& name, std::vector> args, ParsingContext& ctx +) { return createCompoundExpression(compoundExpressionRegistry.equal_range(name.c_str()), std::move(args), ctx); } -CompoundExpression::CompoundExpression(const detail::SignatureBase& signature_, std::vector> args_) : - Expression(Kind::CompoundExpression, signature_.result), - signature(signature_), - args(std::move(args_)) -{} +CompoundExpression::CompoundExpression( + const detail::SignatureBase& signature_, std::vector> args_ +) + : Expression(Kind::CompoundExpression, signature_.result), + signature(signature_), + args(std::move(args_)) {} std::string CompoundExpression::getOperator() const { return signature.name; @@ -1160,12 +1219,14 @@ EvaluationResult CompoundExpression::evaluate(const EvaluationContext& evaluatio } std::optional CompoundExpression::getParameterCount() const { - return signature.params.match([&](const VarargsType&) -> std::optional { return std::nullopt; }, - [&](const std::vector& p) -> std::optional { return p.size(); }); + return signature.params.match( + [&](const VarargsType&) -> std::optional { return std::nullopt; }, + [&](const std::vector& p) -> std::optional { return p.size(); } + ); } std::vector> CompoundExpression::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } void CompoundExpression::eachChild(const std::function& visit) const { @@ -1177,10 +1238,8 @@ void CompoundExpression::eachChild(const std::function& bool CompoundExpression::operator==(const Expression& e) const { if (e.getKind() == Kind::CompoundExpression) { auto rhs = static_cast(&e); - return signature.name == rhs->signature.name && - signature.result == rhs->signature.result && - signature.params == rhs->signature.params && - Expression::childrenEqual(args, rhs->args); + return signature.name == rhs->signature.name && signature.result == rhs->signature.result && + signature.params == rhs->signature.params && Expression::childrenEqual(args, rhs->args); } return false; } diff --git a/src/mbgl/style/expression/distance.cpp b/src/mbgl/style/expression/distance.cpp index d5cbdfd9ff0..bff4c2f7c59 100644 --- a/src/mbgl/style/expression/distance.cpp +++ b/src/mbgl/style/expression/distance.cpp @@ -127,9 +127,9 @@ bool isPolygonValid(const mapbox::geometry::polygon& polygon) { // Calculate the distance between two bounding boxes. // Calculate the delta in x and y direction, and use two fake points {0.0, 0.0} and {dx, dy} to calculate the distance. // Distance will be 0.0 if bounding box are overlapping. -double bboxToBBoxDistance(const DistanceBBox& bbox1, - const DistanceBBox& bbox2, - mapbox::cheap_ruler::CheapRuler& ruler) { +double bboxToBBoxDistance( + const DistanceBBox& bbox1, const DistanceBBox& bbox2, mapbox::cheap_ruler::CheapRuler& ruler +) { if (bbox1 == DefaultDistanceBBox || bbox2 == DefaultDistanceBBox) { return InvalidDistance; } @@ -154,31 +154,41 @@ double bboxToBBoxDistance(const DistanceBBox& bbox1, return ruler.distance(mapbox::geometry::point{0.0, 0.0}, mapbox::geometry::point{dx, dy}); } -double pointToLineDistance(const mapbox::geometry::point& point, - const mapbox::geometry::line_string& line, - mapbox::cheap_ruler::CheapRuler& ruler) { +double pointToLineDistance( + const mapbox::geometry::point& point, + const mapbox::geometry::line_string& line, + mapbox::cheap_ruler::CheapRuler& ruler +) { const auto nearestPoint = std::get<0>(ruler.pointOnLine(line, point)); return ruler.distance(point, nearestPoint); } // precondition is two segments are not intersecting with each other -double segmentToSegmentDistance(const mapbox::geometry::point& p1, - const mapbox::geometry::point& p2, - const mapbox::geometry::point& q1, - const mapbox::geometry::point& q2, - mapbox::cheap_ruler::CheapRuler& ruler) { - auto dist1 = std::min(pointToLineDistance(p1, mapbox::geometry::line_string{q1, q2}, ruler), - pointToLineDistance(p2, mapbox::geometry::line_string{q1, q2}, ruler)); - auto dist2 = std::min(pointToLineDistance(q1, mapbox::geometry::line_string{p1, p2}, ruler), - pointToLineDistance(q2, mapbox::geometry::line_string{p1, p2}, ruler)); +double segmentToSegmentDistance( + const mapbox::geometry::point& p1, + const mapbox::geometry::point& p2, + const mapbox::geometry::point& q1, + const mapbox::geometry::point& q2, + mapbox::cheap_ruler::CheapRuler& ruler +) { + auto dist1 = std::min( + pointToLineDistance(p1, mapbox::geometry::line_string{q1, q2}, ruler), + pointToLineDistance(p2, mapbox::geometry::line_string{q1, q2}, ruler) + ); + auto dist2 = std::min( + pointToLineDistance(q1, mapbox::geometry::line_string{p1, p2}, ruler), + pointToLineDistance(q2, mapbox::geometry::line_string{p1, p2}, ruler) + ); return std::min(dist1, dist2); } -double lineToLineDistance(const mapbox::geometry::line_string& line1, - IndexRange& range1, - const mapbox::geometry::line_string& line2, - IndexRange& range2, - mapbox::cheap_ruler::CheapRuler& ruler) { +double lineToLineDistance( + const mapbox::geometry::line_string& line1, + IndexRange& range1, + const mapbox::geometry::line_string& line2, + IndexRange& range2, + mapbox::cheap_ruler::CheapRuler& ruler +) { bool rangeSafe = isRangeSafe(range1, line1.size()) && isRangeSafe(range2, line2.size()); if (!rangeSafe) return InvalidDistance; double dist = InfiniteDistance; @@ -195,11 +205,13 @@ double lineToLineDistance(const mapbox::geometry::line_string& line1, return dist; } -double pointsToPointsDistance(const mapbox::geometry::multi_point& points1, - IndexRange& range1, - const mapbox::geometry::multi_point& points2, - IndexRange& range2, - mapbox::cheap_ruler::CheapRuler& ruler) { +double pointsToPointsDistance( + const mapbox::geometry::multi_point& points1, + IndexRange& range1, + const mapbox::geometry::multi_point& points2, + IndexRange& range2, + mapbox::cheap_ruler::CheapRuler& ruler +) { bool rangeSafe = isRangeSafe(range1, points1.size()) && isRangeSafe(range2, points2.size()); if (!rangeSafe) return InvalidDistance; double dist = InfiniteDistance; @@ -212,16 +224,19 @@ double pointsToPointsDistance(const mapbox::geometry::multi_point& point return dist; } -double pointToPolygonDistance(const mapbox::geometry::point& point, - const mapbox::geometry::polygon& polygon, - mapbox::cheap_ruler::CheapRuler& ruler) { +double pointToPolygonDistance( + const mapbox::geometry::point& point, + const mapbox::geometry::polygon& polygon, + mapbox::cheap_ruler::CheapRuler& ruler +) { if (pointWithinPolygon(point, polygon, true /*trueOnBoundary*/)) return 0.0; double dist = InfiniteDistance; for (const auto& ring : polygon) { if (ring.front() != ring.back()) { dist = std::min( dist, - pointToLineDistance(point, mapbox::geometry::line_string{ring.back(), ring.front()}, ruler)); + pointToLineDistance(point, mapbox::geometry::line_string{ring.back(), ring.front()}, ruler) + ); if (dist == 0.0) return dist; } const auto nearestPoint = std::get<0>(ruler.pointOnLine(ring, point)); @@ -231,10 +246,12 @@ double pointToPolygonDistance(const mapbox::geometry::point& point, return dist; } -double lineToPolygonDistance(const mapbox::geometry::line_string& line, - const IndexRange& range, - const mapbox::geometry::polygon& polygon, - mapbox::cheap_ruler::CheapRuler& ruler) { +double lineToPolygonDistance( + const mapbox::geometry::line_string& line, + const IndexRange& range, + const mapbox::geometry::polygon& polygon, + mapbox::cheap_ruler::CheapRuler& ruler +) { if (!isRangeSafe(range, line.size())) return InvalidDistance; for (std::size_t i = range.first; i <= range.second; ++i) { if (pointWithinPolygon(line[i], polygon, true /*trueOnBoundary*/)) return 0.0; @@ -257,10 +274,12 @@ double lineToPolygonDistance(const mapbox::geometry::line_string& line, } // TODO: Currently the time complexity for polygon to polygon distance is quadratic, performance improvement is needed. -double polygonToPolygonDistance(const mapbox::geometry::polygon& polygon1, - const mapbox::geometry::polygon& polygon2, - mapbox::cheap_ruler::CheapRuler& ruler, - double currentMiniDist = InfiniteDistance) { +double polygonToPolygonDistance( + const mapbox::geometry::polygon& polygon1, + const mapbox::geometry::polygon& polygon2, + mapbox::cheap_ruler::CheapRuler& ruler, + double currentMiniDist = InfiniteDistance +) { const auto bbox1 = getBBox(polygon1); const auto bbox2 = getBBox(polygon2); if (currentMiniDist != InfiniteDistance && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) { @@ -310,10 +329,12 @@ using DistQueue = std::priority_queue, Comparator // Divide and conquer, the time complexity is O(n*lgn), faster than Brute force O(n*n) // Most of the time, use index for in-place processing. -double pointsToPolygonDistance(const mapbox::geometry::multi_point& points, - const mapbox::geometry::polygon& polygon, - mapbox::cheap_ruler::CheapRuler& ruler, - double currentMiniDist = InfiniteDistance) { +double pointsToPolygonDistance( + const mapbox::geometry::multi_point& points, + const mapbox::geometry::polygon& polygon, + mapbox::cheap_ruler::CheapRuler& ruler, + double currentMiniDist = InfiniteDistance +) { auto miniDist = std::min(ruler.distance(points[0], polygon[0][0]), currentMiniDist); if (miniDist == 0.0) return miniDist; DistQueue distQueue; @@ -355,10 +376,12 @@ double pointsToPolygonDistance(const mapbox::geometry::multi_point& poin return miniDist; } -double lineToPolygonDistance(const mapbox::geometry::line_string& line, - const mapbox::geometry::polygon& polygon, - mapbox::cheap_ruler::CheapRuler& ruler, - double currentMiniDist = InfiniteDistance) { +double lineToPolygonDistance( + const mapbox::geometry::line_string& line, + const mapbox::geometry::polygon& polygon, + mapbox::cheap_ruler::CheapRuler& ruler, + double currentMiniDist = InfiniteDistance +) { auto miniDist = std::min(ruler.distance(line[0], polygon[0][0]), currentMiniDist); if (miniDist == 0.0) return miniDist; DistQueue distQueue; @@ -379,15 +402,15 @@ double lineToPolygonDistance(const mapbox::geometry::line_string& line, if (miniDist == 0.0) return 0.0; } else { auto newRangesA = splitRange(range, true /*isLine*/); - const auto updateQueue = - [&distQueue, &miniDist, &ruler, &line, &polyBBox](std::optional& rangeA) { - if (!rangeA) return; - auto tempDist = bboxToBBoxDistance(getBBox(line, *rangeA), polyBBox, ruler); - // Insert new pair to the queue if the bbox distance is less than miniDist, - // The pair with biggest distance will be at the top - if (tempDist < miniDist) - distQueue.push(std::make_tuple(tempDist, std::move(*rangeA), IndexRange(0, 0))); - }; + const auto updateQueue = [&distQueue, &miniDist, &ruler, &line, &polyBBox](std::optional& rangeA + ) { + if (!rangeA) return; + auto tempDist = bboxToBBoxDistance(getBBox(line, *rangeA), polyBBox, ruler); + // Insert new pair to the queue if the bbox distance is less than miniDist, + // The pair with biggest distance will be at the top + if (tempDist < miniDist) + distQueue.push(std::make_tuple(tempDist, std::move(*rangeA), IndexRange(0, 0))); + }; updateQueue(newRangesA.first); updateQueue(newRangesA.second); } @@ -395,10 +418,12 @@ double lineToPolygonDistance(const mapbox::geometry::line_string& line, return miniDist; } -double lineToLineDistance(const mapbox::geometry::line_string& line1, - const mapbox::geometry::line_string& line2, - mapbox::cheap_ruler::CheapRuler& ruler, - double currentMiniDist = InfiniteDistance) { +double lineToLineDistance( + const mapbox::geometry::line_string& line1, + const mapbox::geometry::line_string& line2, + mapbox::cheap_ruler::CheapRuler& ruler, + double currentMiniDist = InfiniteDistance +) { auto miniDist = std::min(ruler.distance(line1[0], line2[0]), currentMiniDist); if (miniDist == 0.0) return miniDist; DistQueue distQueue; @@ -421,7 +446,8 @@ double lineToLineDistance(const mapbox::geometry::line_string& line1, auto newRangesA = splitRange(rangeA, true /*isLine*/); auto newRangesB = splitRange(rangeB, true /*isLine*/); const auto updateQueue = [&distQueue, &miniDist, &ruler, &line1, &line2]( - std::optional& range1, std::optional& range2) { + std::optional& range1, std::optional& range2 + ) { if (!range1 || !range2) return; auto tempDist = bboxToBBoxDistance(getBBox(line1, *range1), getBBox(line2, *range2), ruler); // Insert new pair to the queue if the bbox distance is less than miniDist, @@ -438,9 +464,11 @@ double lineToLineDistance(const mapbox::geometry::line_string& line1, return miniDist; } -double pointsToPointsDistance(const mapbox::geometry::multi_point& pointSet1, - const mapbox::geometry::multi_point& pointSet2, - mapbox::cheap_ruler::CheapRuler& ruler) { +double pointsToPointsDistance( + const mapbox::geometry::multi_point& pointSet1, + const mapbox::geometry::multi_point& pointSet2, + mapbox::cheap_ruler::CheapRuler& ruler +) { auto miniDist = ruler.distance(pointSet1[0], pointSet2[0]); if (miniDist == 0.0) return miniDist; DistQueue distQueue; @@ -465,7 +493,8 @@ double pointsToPointsDistance(const mapbox::geometry::multi_point& point auto newRangesA = splitRange(rangeA, false /*isLine*/); auto newRangesB = splitRange(rangeB, false /*isLine*/); const auto updateQueue = [&distQueue, &miniDist, &ruler, &pointSet1, &pointSet2]( - std::optional& range1, std::optional& range2) { + std::optional& range1, std::optional& range2 + ) { if (!range1 || !range2) return; auto tempDist = bboxToBBoxDistance(getBBox(pointSet1, *range1), getBBox(pointSet2, *range2), ruler); // Insert new pair to the queue if the bbox distance is less than miniDist, @@ -482,10 +511,12 @@ double pointsToPointsDistance(const mapbox::geometry::multi_point& point return miniDist; } -double pointsToLineDistance(const mapbox::geometry::multi_point& points, - const mapbox::geometry::line_string& line, - mapbox::cheap_ruler::CheapRuler& ruler, - double currentMiniDist = InfiniteDistance) { +double pointsToLineDistance( + const mapbox::geometry::multi_point& points, + const mapbox::geometry::line_string& line, + mapbox::cheap_ruler::CheapRuler& ruler, + double currentMiniDist = InfiniteDistance +) { auto miniDist = std::min(currentMiniDist, ruler.distance(points[0], line[0])); if (miniDist == 0.0) return miniDist; DistQueue distQueue; @@ -505,8 +536,9 @@ double pointsToLineDistance(const mapbox::geometry::multi_point& points, mbgl::Log::Error(mbgl::Event::Style, "Index is out of range"); return InvalidDistance; } - auto subLine = - mapbox::geometry::multi_point(line.begin() + rangeB.first, line.begin() + rangeB.second + 1); + auto subLine = mapbox::geometry::multi_point( + line.begin() + rangeB.first, line.begin() + rangeB.second + 1 + ); for (std::size_t i = rangeA.first; i <= rangeA.second; ++i) { miniDist = std::min(miniDist, pointToLineDistance(points[i], subLine, ruler)); if (miniDist == 0.0) return 0.0; @@ -515,7 +547,8 @@ double pointsToLineDistance(const mapbox::geometry::multi_point& points, auto newRangesA = splitRange(rangeA, false /*isLine*/); auto newRangesB = splitRange(rangeB, true /*isLine*/); const auto updateQueue = [&distQueue, &miniDist, &ruler, &points, &line]( - std::optional& range1, std::optional& range2) { + std::optional& range1, std::optional& range2 + ) { if (!range1 || !range2) return; auto tempDist = bboxToBBoxDistance(getBBox(points, *range1), getBBox(line, *range2), ruler); // Insert new pair to the queue if the bbox distance is less than miniDist, @@ -532,9 +565,11 @@ double pointsToLineDistance(const mapbox::geometry::multi_point& points, return miniDist; } -double pointsToLinesDistance(const mapbox::geometry::multi_point& points, - const mapbox::geometry::multi_line_string& lines, - mapbox::cheap_ruler::CheapRuler& ruler) { +double pointsToLinesDistance( + const mapbox::geometry::multi_point& points, + const mapbox::geometry::multi_line_string& lines, + mapbox::cheap_ruler::CheapRuler& ruler +) { double dist = InfiniteDistance; for (const auto& line : lines) { dist = std::min(dist, pointsToLineDistance(points, line, ruler, dist)); @@ -543,9 +578,11 @@ double pointsToLinesDistance(const mapbox::geometry::multi_point& points return dist; } -double lineToLinesDistance(const mapbox::geometry::line_string& line, - const mapbox::geometry::multi_line_string& lines, - mapbox::cheap_ruler::CheapRuler& ruler) { +double lineToLinesDistance( + const mapbox::geometry::line_string& line, + const mapbox::geometry::multi_line_string& lines, + mapbox::cheap_ruler::CheapRuler& ruler +) { double dist = InfiniteDistance; for (const auto& l : lines) { dist = std::min(dist, lineToLineDistance(line, l, ruler, dist)); @@ -554,8 +591,9 @@ double lineToLinesDistance(const mapbox::geometry::line_string& line, return dist; } -double pointsToGeometryDistance(const mapbox::geometry::multi_point& points, - const Feature::geometry_type& geoSet) { +double pointsToGeometryDistance( + const mapbox::geometry::multi_point& points, const Feature::geometry_type& geoSet +) { if (!isMultiPointValid(points)) return InvalidDistance; mapbox::cheap_ruler::CheapRuler ruler(points.front().y, UnitInMeters); return geoSet.match( @@ -591,7 +629,8 @@ double pointsToGeometryDistance(const mapbox::geometry::multi_point& poi } return dist; }, - [](const auto&) { return InvalidDistance; }); + [](const auto&) { return InvalidDistance; } + ); } double lineToGeometryDistance(const mapbox::geometry::line_string& line, const Feature::geometry_type& geoSet) { @@ -630,11 +669,13 @@ double lineToGeometryDistance(const mapbox::geometry::line_string& line, } return dist; }, - [](const auto&) { return InvalidDistance; }); + [](const auto&) { return InvalidDistance; } + ); } -double polygonToGeometryDistance(const mapbox::geometry::polygon& polygon, - const Feature::geometry_type& geoSet) { +double polygonToGeometryDistance( + const mapbox::geometry::polygon& polygon, const Feature::geometry_type& geoSet +) { if (!isPolygonValid(polygon)) return InvalidDistance; mapbox::cheap_ruler::CheapRuler ruler(polygon.front().front().y, UnitInMeters); return geoSet.match( @@ -675,12 +716,13 @@ double polygonToGeometryDistance(const mapbox::geometry::polygon& polygo } return dist; }, - [](const auto&) { return InvalidDistance; }); + [](const auto&) { return InvalidDistance; } + ); } -double calculateDistance(const GeometryTileFeature& feature, - const CanonicalTileID& canonical, - const Feature::geometry_type& geoSet) { +double calculateDistance( + const GeometryTileFeature& feature, const CanonicalTileID& canonical, const Feature::geometry_type& geoSet +) { return convertGeometry(feature, canonical) .match( [&geoSet](const mapbox::geometry::point& point) -> double { @@ -715,7 +757,8 @@ double calculateDistance(const GeometryTileFeature& feature, } return dist; }, - [](const auto&) -> double { return InvalidDistance; }); + [](const auto&) -> double { return InvalidDistance; } + ); } std::optional parseValue(const style::conversion::Convertible& value, style::expression::ParsingContext& ctx) { @@ -723,8 +766,10 @@ std::optional parseValue(const style::conversion::Convertible& value, s // object value, quoted with ["distance", GeoJSONObj] auto length = arrayLength(value); if (length != 2) { - ctx.error("'distance' expression requires one argument, but found " + - util::toString(arrayLength(value) - 1) + " instead."); + ctx.error( + "'distance' expression requires one argument, but found " + util::toString(arrayLength(value) - 1) + + " instead." + ); return std::nullopt; } @@ -743,13 +788,16 @@ std::optional parseValue(const style::conversion::Convertible& value, s return std::nullopt; } -std::optional getGeometry(const Feature& feature, mbgl::style::expression::ParsingContext& ctx) { +std::optional getGeometry( + const Feature& feature, mbgl::style::expression::ParsingContext& ctx +) { const auto type = apply_visitor(ToFeatureType(), feature.geometry); if (type == FeatureType::Point || type == FeatureType::LineString || type == FeatureType::Polygon) { return feature.geometry; } ctx.error( - "'distance' expression requires valid geojson object with valid geometry type: Point, LineString or Polygon."); + "'distance' expression requires valid geojson object with valid geometry type: Point, LineString or Polygon." + ); return std::nullopt; } } // namespace @@ -758,7 +806,9 @@ namespace style { namespace expression { Distance::Distance(GeoJSON geojson, Feature::geometry_type geometries_) - : Expression(Kind::Distance, type::Number), geoJSONSource(std::move(geojson)), geometries(std::move(geometries_)) {} + : Expression(Kind::Distance, type::Number), + geoJSONSource(std::move(geojson)), + geometries(std::move(geometries_)) {} Distance::~Distance() = default; @@ -808,10 +858,11 @@ ParseResult Distance::parse(const Convertible& value, ParsingContext& ctx) { return ParseResult(); }, [&ctx](const auto&) { - ctx.error( - "'distance' expression requires valid geojson that contains Point/LineString/Polygon geometries."); + ctx.error("'distance' expression requires valid geojson that contains Point/LineString/Polygon geometries." + ); return ParseResult(); - }); + } + ); return ParseResult(); } @@ -856,8 +907,9 @@ mbgl::Value Distance::serialize() const { serialized.emplace(m.name.GetString(), convertValue(m.value)); } } else { - mbgl::Log::Error(mbgl::Event::Style, - "Failed to serialize 'distance' expression, converted rapidJSON is not an object"); + mbgl::Log::Error( + mbgl::Event::Style, "Failed to serialize 'distance' expression, converted rapidJSON is not an object" + ); } return std::vector{{getOperator(), serialized}}; } @@ -871,7 +923,7 @@ bool Distance::operator==(const Expression& e) const { } std::vector> Distance::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } std::string Distance::getOperator() const { diff --git a/src/mbgl/style/expression/dsl.cpp b/src/mbgl/style/expression/dsl.cpp index d8c105633f9..2aefa5e1ae2 100644 --- a/src/mbgl/style/expression/dsl.cpp +++ b/src/mbgl/style/expression/dsl.cpp @@ -23,11 +23,11 @@ namespace dsl { std::unique_ptr compound(const char* op, std::vector> args) { ParsingContext ctx; - ParseResult result = createCompoundExpression(op, std::move(args), ctx); + ParseResult result = createCompoundExpression(op, std::move(args), ctx); assert(result); return std::move(*result); } - + std::unique_ptr createExpression(const char* expr) { using JSValue = rapidjson::GenericValue, rapidjson::CrtAllocator>; rapidjson::GenericDocument, rapidjson::CrtAllocator> document; @@ -36,8 +36,7 @@ std::unique_ptr createExpression(const char* expr) { const JSValue* expression = &document; expression::ParsingContext ctx; - expression::ParseResult parsed = - ctx.parseExpression(mbgl::style::conversion::Convertible(expression)); + expression::ParseResult parsed = ctx.parseExpression(mbgl::style::conversion::Convertible(expression)); return parsed ? std::move(*parsed) : nullptr; } @@ -67,7 +66,7 @@ std::unique_ptr literal(std::initializer_list value) { return literal(values); } -std::unique_ptr literal(std::initializer_list value) { +std::unique_ptr literal(std::initializer_list value) { std::vector values; for (auto i : value) { values.emplace_back(std::string(i)); @@ -75,34 +74,31 @@ std::unique_ptr literal(std::initializer_list value) { return literal(values); } -std::unique_ptr assertion(const type::Type& type, - std::unique_ptr value, - std::unique_ptr def) { - std::vector> v = vec(std::move(value)); +std::unique_ptr assertion( + const type::Type& type, std::unique_ptr value, std::unique_ptr def +) { + std::vector> v = vec(std::move(value)); if (def) { v.push_back(std::move(def)); } return std::make_unique(type, std::move(v)); } -std::unique_ptr number(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr number(std::unique_ptr value, std::unique_ptr def) { return assertion(type::Number, std::move(value), std::move(def)); } -std::unique_ptr string(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr string(std::unique_ptr value, std::unique_ptr def) { return assertion(type::String, std::move(value), std::move(def)); } -std::unique_ptr boolean(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr boolean(std::unique_ptr value, std::unique_ptr def) { return assertion(type::Boolean, std::move(value), std::move(def)); } -std::unique_ptr coercion(const type::Type& type, - std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr coercion( + const type::Type& type, std::unique_ptr value, std::unique_ptr def +) { std::vector> v = vec(std::move(value)); if (def) { v.push_back(std::move(def)); @@ -110,18 +106,15 @@ std::unique_ptr coercion(const type::Type& type, return std::make_unique(type, std::move(v)); } -std::unique_ptr toColor(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr toColor(std::unique_ptr value, std::unique_ptr def) { return coercion(type::Color, std::move(value), std::move(def)); } -std::unique_ptr toString(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr toString(std::unique_ptr value, std::unique_ptr def) { return coercion(type::String, std::move(value), std::move(def)); } -std::unique_ptr toFormatted(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr toFormatted(std::unique_ptr value, std::unique_ptr def) { return coercion(type::Formatted, std::move(value), std::move(def)); } @@ -145,29 +138,28 @@ std::unique_ptr zoom() { return compound("zoom"); } -std::unique_ptr eq(std::unique_ptr lhs, - std::unique_ptr rhs) { +std::unique_ptr eq(std::unique_ptr lhs, std::unique_ptr rhs) { return std::make_unique("==", std::move(lhs), std::move(rhs)); } -std::unique_ptr ne(std::unique_ptr lhs, - std::unique_ptr rhs) { +std::unique_ptr ne(std::unique_ptr lhs, std::unique_ptr rhs) { return std::make_unique("!=", std::move(lhs), std::move(rhs)); } -std::unique_ptr gt(std::unique_ptr lhs, - std::unique_ptr rhs) { +std::unique_ptr gt(std::unique_ptr lhs, std::unique_ptr rhs) { return std::make_unique(">", std::move(lhs), std::move(rhs)); } -std::unique_ptr lt(std::unique_ptr lhs, - std::unique_ptr rhs) { +std::unique_ptr lt(std::unique_ptr lhs, std::unique_ptr rhs) { return std::make_unique("<", std::move(lhs), std::move(rhs)); } -std::unique_ptr step(std::unique_ptr input, - std::unique_ptr output0, - double input1, std::unique_ptr output1) { +std::unique_ptr step( + std::unique_ptr input, + std::unique_ptr output0, + double input1, + std::unique_ptr output1 +) { type::Type type = output0->getType(); std::map> stops; stops[-std::numeric_limits::infinity()] = std::move(output0); @@ -187,9 +179,9 @@ Interpolator cubicBezier(double x1, double y1, double x2, double y2) { return CubicBezierInterpolator(x1, y1, x2, y2); } -std::unique_ptr interpolate(Interpolator interpolator, - std::unique_ptr input, - double input1, std::unique_ptr output1) { +std::unique_ptr interpolate( + Interpolator interpolator, std::unique_ptr input, double input1, std::unique_ptr output1 +) { type::Type type = output1->getType(); std::map> stops; stops[input1] = std::move(output1); @@ -199,10 +191,14 @@ std::unique_ptr interpolate(Interpolator interpolator, return std::move(*result); } -std::unique_ptr interpolate(Interpolator interpolator, - std::unique_ptr input, - double input1, std::unique_ptr output1, - double input2, std::unique_ptr output2) { +std::unique_ptr interpolate( + Interpolator interpolator, + std::unique_ptr input, + double input1, + std::unique_ptr output1, + double input2, + std::unique_ptr output2 +) { type::Type type = output1->getType(); std::map> stops; stops[input1] = std::move(output1); @@ -213,11 +209,16 @@ std::unique_ptr interpolate(Interpolator interpolator, return std::move(*result); } -std::unique_ptr interpolate(Interpolator interpolator, - std::unique_ptr input, - double input1, std::unique_ptr output1, - double input2, std::unique_ptr output2, - double input3, std::unique_ptr output3) { +std::unique_ptr interpolate( + Interpolator interpolator, + std::unique_ptr input, + double input1, + std::unique_ptr output1, + double input2, + std::unique_ptr output2, + double input3, + std::unique_ptr output3 +) { type::Type type = output1->getType(); std::map> stops; stops[input1] = std::move(output1); diff --git a/src/mbgl/style/expression/expression.cpp b/src/mbgl/style/expression/expression.cpp index ce07d46436d..0fd8f6e2173 100644 --- a/src/mbgl/style/expression/expression.cpp +++ b/src/mbgl/style/expression/expression.cpp @@ -12,8 +12,10 @@ class GeoJSONFeature : public GeometryTileFeature { const Feature& feature; mutable std::optional geometry; - explicit GeoJSONFeature(const Feature& feature_) : feature(feature_) {} - GeoJSONFeature(const Feature& feature_, const CanonicalTileID& canonical) : feature(feature_) { + explicit GeoJSONFeature(const Feature& feature_) + : feature(feature_) {} + GeoJSONFeature(const Feature& feature_, const CanonicalTileID& canonical) + : feature(feature_) { geometry = convertGeometry(feature.geometry, canonical); // https://github.com/mapbox/geojson-vt-cpp/issues/44 if (getTypeImpl() == FeatureType::Polygon) { @@ -42,27 +44,32 @@ class GeoJSONFeature : public GeometryTileFeature { FeatureType getTypeImpl() const { return apply_visitor(ToFeatureType(), feature.geometry); } }; -EvaluationResult Expression::evaluate(std::optional zoom, - const Feature& feature, - std::optional colorRampParameter) const { +EvaluationResult Expression::evaluate( + std::optional zoom, const Feature& feature, std::optional colorRampParameter +) const { GeoJSONFeature f(feature); return this->evaluate(EvaluationContext(std::move(zoom), &f, std::move(colorRampParameter))); } -EvaluationResult Expression::evaluate(std::optional zoom, - const Feature& feature, - std::optional colorRampParameter, - const std::set& availableImages) const { +EvaluationResult Expression::evaluate( + std::optional zoom, + const Feature& feature, + std::optional colorRampParameter, + const std::set& availableImages +) const { GeoJSONFeature f(feature); return this->evaluate( - EvaluationContext(std::move(zoom), &f, std::move(colorRampParameter)).withAvailableImages(&availableImages)); + EvaluationContext(std::move(zoom), &f, std::move(colorRampParameter)).withAvailableImages(&availableImages) + ); } -EvaluationResult Expression::evaluate(std::optional zoom, - const Feature& feature, - std::optional colorRampParameter, - const std::set& availableImages, - const CanonicalTileID& canonical) const { +EvaluationResult Expression::evaluate( + std::optional zoom, + const Feature& feature, + std::optional colorRampParameter, + const std::set& availableImages, + const CanonicalTileID& canonical +) const { GeoJSONFeature f(feature, canonical); return this->evaluate(EvaluationContext(std::move(zoom), &f, std::move(colorRampParameter)) .withAvailableImages(&availableImages) diff --git a/src/mbgl/style/expression/find_zoom_curve.cpp b/src/mbgl/style/expression/find_zoom_curve.cpp index d888272dd46..7eaed46ba6a 100644 --- a/src/mbgl/style/expression/find_zoom_curve.cpp +++ b/src/mbgl/style/expression/find_zoom_curve.cpp @@ -14,65 +14,64 @@ namespace expression { std::optional> findZoomCurve(const expression::Expression* e) { std::optional> result; - + switch (e->getKind()) { - case Kind::Let: { - auto let = static_cast(e); - result = findZoomCurve(let->getResult()); - break; - } - case Kind::Coalesce: { - auto coalesce = static_cast(e); - std::size_t length = coalesce->getLength(); - for (std::size_t i = 0; i < length; i++) { - result = findZoomCurve(coalesce->getChild(i)); - if (result) { - break; + case Kind::Let: { + auto let = static_cast(e); + result = findZoomCurve(let->getResult()); + break; + } + case Kind::Coalesce: { + auto coalesce = static_cast(e); + std::size_t length = coalesce->getLength(); + for (std::size_t i = 0; i < length; i++) { + result = findZoomCurve(coalesce->getChild(i)); + if (result) { + break; + } } + break; } - break; - } - case Kind::Interpolate: { - auto curve = static_cast(e); - if (curve->getInput()->getKind() == Kind::CompoundExpression) { - auto z = static_cast(curve->getInput().get()); - if (z && z->getOperator() == "zoom") { - result = {curve}; + case Kind::Interpolate: { + auto curve = static_cast(e); + if (curve->getInput()->getKind() == Kind::CompoundExpression) { + auto z = static_cast(curve->getInput().get()); + if (z && z->getOperator() == "zoom") { + result = {curve}; + } } + break; } - break; - } - case Kind::Step: { - auto step = static_cast(e); - if (step->getInput()->getKind() == Kind::CompoundExpression) { - auto z = static_cast(step->getInput().get()); - if (z && z->getOperator() == "zoom") { - result = {step}; + case Kind::Step: { + auto step = static_cast(e); + if (step->getInput()->getKind() == Kind::CompoundExpression) { + auto z = static_cast(step->getInput().get()); + if (z && z->getOperator() == "zoom") { + result = {step}; + } } + break; } - break; + default: + break; } - default: - break; - } - + if (result && result->is()) { return result; } - + e->eachChild([&](const Expression& child) { std::optional> childResult(findZoomCurve(&child)); if (childResult) { if (childResult->is()) { result = childResult; } else if (!result && childResult) { - result = {ParsingError { - R"("zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.)", "" - }}; + result = {ParsingError{ + R"("zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.)", + ""}}; } else if (result && childResult && result != childResult) { - result = {ParsingError { - R"(Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.)", "" - }}; + result = {ParsingError{ + R"(Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.)", ""}}; } } }); @@ -89,9 +88,7 @@ variant findZoomCurveChecked(co assert(false); return nullptr; }, - [](auto zoomCurve) -> variant { - return zoomCurve; - } + [](auto zoomCurve) -> variant { return zoomCurve; } ); } diff --git a/src/mbgl/style/expression/format_expression.cpp b/src/mbgl/style/expression/format_expression.cpp index f88096f844e..79eae49f0df 100644 --- a/src/mbgl/style/expression/format_expression.cpp +++ b/src/mbgl/style/expression/format_expression.cpp @@ -6,11 +6,14 @@ namespace mbgl { namespace style { namespace expression { -FormatExpressionSection::FormatExpressionSection(std::unique_ptr content_) : content(std::move(content_)) {} - -void FormatExpressionSection::setTextSectionOptions(std::optional> fontScale_, - std::optional> textFont_, - std::optional> textColor_) { +FormatExpressionSection::FormatExpressionSection(std::unique_ptr content_) + : content(std::move(content_)) {} + +void FormatExpressionSection::setTextSectionOptions( + std::optional> fontScale_, + std::optional> textFont_, + std::optional> textColor_ +) { if (fontScale_) { assert(*fontScale_); fontScale = std::shared_ptr(std::move(*fontScale_)); @@ -28,9 +31,8 @@ void FormatExpressionSection::setTextSectionOptions(std::optional sections_) - : Expression(Kind::FormatExpression, type::Formatted) - , sections(std::move(sections_)) -{} + : Expression(Kind::FormatExpression, type::Formatted), + sections(std::move(sections_)) {} using namespace mbgl::style::conversion; @@ -142,7 +144,7 @@ bool FormatExpression::operator==(const Expression& e) const { } mbgl::Value FormatExpression::serialize() const { - std::vector serialized{{ getOperator() }}; + std::vector serialized{{getOperator()}}; for (const auto& section : sections) { serialized.push_back(section.content->serialize()); std::unordered_map options; @@ -201,7 +203,7 @@ EvaluationResult FormatExpression::evaluate(const EvaluationContext& params) con } auto textFontValue = ValueConverter>::fromExpressionValue(*textFontResult); if (!textFontValue) { - return EvaluationError { "Format text-font option must evaluate to an array of strings" }; + return EvaluationError{"Format text-font option must evaluate to an array of strings"}; } evaluatedTextFont = *textFontValue; } @@ -215,7 +217,7 @@ EvaluationResult FormatExpression::evaluate(const EvaluationContext& params) con evaluatedTextColor = fromExpressionValue(*textColorResult); if (!evaluatedTextColor) { - return EvaluationError { "Format text-color option must evaluate to Color" }; + return EvaluationError{"Format text-color option must evaluate to Color"}; } } evaluatedSections.emplace_back(*evaluatedText, evaluatedFontScale, evaluatedTextFont, evaluatedTextColor); @@ -226,4 +228,3 @@ EvaluationResult FormatExpression::evaluate(const EvaluationContext& params) con } // namespace expression } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/expression/formatted.cpp b/src/mbgl/style/expression/formatted.cpp index 5ad34a578cf..a88763cc04f 100644 --- a/src/mbgl/style/expression/formatted.cpp +++ b/src/mbgl/style/expression/formatted.cpp @@ -77,7 +77,7 @@ mbgl::Value Formatted::toObject() const { } // namespace expression namespace conversion { - + using namespace mbgl::style::expression; std::optional Converter::operator()(const Convertible& value, Error& error) const { @@ -180,4 +180,3 @@ std::optional Converter::operator()(const Convertible& val } // namespace conversion } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/expression/get_covering_stops.cpp b/src/mbgl/style/expression/get_covering_stops.cpp index c9f87d93ac5..b90ef8282fe 100644 --- a/src/mbgl/style/expression/get_covering_stops.cpp +++ b/src/mbgl/style/expression/get_covering_stops.cpp @@ -4,8 +4,9 @@ namespace mbgl { namespace style { namespace expression { -Range getCoveringStops(const std::map>& stops, - const double lower, const double upper) { +Range getCoveringStops( + const std::map>& stops, const double lower, const double upper +) { assert(!stops.empty()); auto minIt = stops.lower_bound(lower); auto maxIt = stops.lower_bound(upper); @@ -15,10 +16,9 @@ Range getCoveringStops(const std::map if (minIt != stops.begin() && minIt != stops.end() && minIt->first > lower) { minIt--; } - return Range { + return Range{ static_cast(minIt == stops.end() ? stops.rbegin()->first : minIt->first), - static_cast(maxIt == stops.end() ? stops.rbegin()->first : maxIt->first) - }; + static_cast(maxIt == stops.end() ? stops.rbegin()->first : maxIt->first)}; } } // namespace expression diff --git a/src/mbgl/style/expression/image.cpp b/src/mbgl/style/expression/image.cpp index d8c5d98188a..79b3ac6c997 100644 --- a/src/mbgl/style/expression/image.cpp +++ b/src/mbgl/style/expression/image.cpp @@ -6,11 +6,15 @@ namespace mbgl { namespace style { namespace expression { -Image::Image(std::string imageID_, bool available_) : imageID(std::move(imageID_)), available(available_) {} +Image::Image(std::string imageID_, bool available_) + : imageID(std::move(imageID_)), + available(available_) {} -Image::Image(std::string imageID_) : Image(std::move(imageID_), false) {} +Image::Image(std::string imageID_) + : Image(std::move(imageID_), false) {} -Image::Image(const char* imageID_) : Image(std::string(imageID_)) { +Image::Image(const char* imageID_) + : Image(std::string(imageID_)) { assert(imageID_); } diff --git a/src/mbgl/style/expression/image_expression.cpp b/src/mbgl/style/expression/image_expression.cpp index ed3a4f3bd0c..b49a195511d 100644 --- a/src/mbgl/style/expression/image_expression.cpp +++ b/src/mbgl/style/expression/image_expression.cpp @@ -7,7 +7,8 @@ namespace style { namespace expression { ImageExpression::ImageExpression(std::unique_ptr imageID_) - : Expression(Kind::ImageExpression, type::Image), imageID(std::move(imageID_)) { + : Expression(Kind::ImageExpression, type::Image), + imageID(std::move(imageID_)) { assert(imageID); } diff --git a/src/mbgl/style/expression/in.cpp b/src/mbgl/style/expression/in.cpp index 2fa1a69d3bf..09ee9a0d106 100644 --- a/src/mbgl/style/expression/in.cpp +++ b/src/mbgl/style/expression/in.cpp @@ -29,7 +29,9 @@ bool isSearchableRuntimeType(const type::Type& type) { } // namespace In::In(std::unique_ptr needle_, std::unique_ptr haystack_) - : Expression(Kind::In, type::Boolean), needle(std::move(needle_)), haystack(std::move(haystack_)) { + : Expression(Kind::In, type::Boolean), + needle(std::move(needle_)), + haystack(std::move(haystack_)) { assert(isComparableType(needle->getType())); assert(isSearchableType(haystack->getType())); } @@ -47,14 +49,16 @@ EvaluationResult In::evaluate(const EvaluationContext& params) const { type::Type evaluatedNeedleType = typeOf(*evaluatedNeedle); if (!isComparableRuntimeType(evaluatedNeedleType)) { - return EvaluationError{"Expected first argument to be of type boolean, string or number, but found " + - toString(evaluatedNeedleType) + " instead."}; + return EvaluationError{ + "Expected first argument to be of type boolean, string or number, but found " + + toString(evaluatedNeedleType) + " instead."}; } type::Type evaluatedHaystackType = typeOf(*evaluatedHaystack); if (!isSearchableRuntimeType(evaluatedHaystackType)) { - return EvaluationError{"Expected second argument to be of type array or string, but found " + - toString(evaluatedHaystackType) + " instead."}; + return EvaluationError{ + "Expected second argument to be of type array or string, but found " + toString(evaluatedHaystackType) + + " instead."}; } if (evaluatedNeedleType == type::Null || evaluatedHaystackType == type::Null) { @@ -67,8 +71,9 @@ EvaluationResult In::evaluate(const EvaluationContext& params) const { return EvaluationResult(haystackString.find(needleString) != std::string::npos); } else { const auto haystackArray = evaluatedHaystack->get>(); - return EvaluationResult(std::find(haystackArray.begin(), haystackArray.end(), *evaluatedNeedle) != - haystackArray.end()); + return EvaluationResult( + std::find(haystackArray.begin(), haystackArray.end(), *evaluatedNeedle) != haystackArray.end() + ); } } @@ -97,14 +102,17 @@ ParseResult In::parse(const Convertible& value, ParsingContext& ctx) { type::Type haystackType = (*haystack)->getType(); if (!isComparableType(needleType)) { - ctx.error("Expected first argument to be of type boolean, string or number, but found " + toString(needleType) + - " instead."); + ctx.error( + "Expected first argument to be of type boolean, string or number, but found " + toString(needleType) + + " instead." + ); return ParseResult(); } if (!isSearchableType(haystackType)) { - ctx.error("Expected second argument to be of type array or string, but found " + toString(haystackType) + - " instead."); + ctx.error( + "Expected second argument to be of type array or string, but found " + toString(haystackType) + " instead." + ); return ParseResult(); } return ParseResult(std::make_unique(std::move(*needle), std::move(*haystack))); diff --git a/src/mbgl/style/expression/interpolate.cpp b/src/mbgl/style/expression/interpolate.cpp index cec6e941429..0e513433aca 100644 --- a/src/mbgl/style/expression/interpolate.cpp +++ b/src/mbgl/style/expression/interpolate.cpp @@ -11,11 +11,13 @@ using namespace mbgl::style::conversion; template class InterpolateImpl : public Interpolate { public: - InterpolateImpl(const type::Type& type_, - const Interpolator& interpolator_, - std::unique_ptr input_, - // NOLINTNEXTLINE(performance-unnecessary-value-param) - std::map> stops_) + InterpolateImpl( + const type::Type& type_, + const Interpolator& interpolator_, + std::unique_ptr input_, + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::map> stops_ + ) : Interpolate(type_, interpolator_, std::move(input_), std::move(stops_)) { static_assert(util::Interpolatable::value, "Interpolate expression requires an interpolatable value type."); } @@ -28,11 +30,11 @@ class InterpolateImpl : public Interpolate { float x = *fromExpressionValue(*evaluatedInput); if (std::isnan(x)) { - return EvaluationError { "Input is not a number." }; + return EvaluationError{"Input is not a number."}; } if (stops.empty()) { - return EvaluationError { "No stops in exponential curve." }; + return EvaluationError{"No stops in exponential curve."}; } auto it = stops.upper_bound(x); @@ -41,7 +43,7 @@ class InterpolateImpl : public Interpolate { } else if (it == stops.begin()) { return stops.begin()->second->evaluate(params); } else { - double t = interpolationFactor({ std::prev(it)->first, it->first }, x); + double t = interpolationFactor({std::prev(it)->first, it->first}, x); if (t == 0.0) { return std::prev(it)->second->evaluate(params); @@ -60,17 +62,15 @@ class InterpolateImpl : public Interpolate { } if (!lower->is()) { - return EvaluationError { - "Expected value to be of type " + toString(valueTypeToExpressionType()) + - ", but found " + toString(typeOf(*lower)) + " instead." - }; + return EvaluationError{ + "Expected value to be of type " + toString(valueTypeToExpressionType()) + ", but found " + + toString(typeOf(*lower)) + " instead."}; } if (!upper->is()) { - return EvaluationError { - "Expected value to be of type " + toString(valueTypeToExpressionType()) + - ", but found " + toString(typeOf(*upper)) + " instead." - }; + return EvaluationError{ + "Expected value to be of type " + toString(valueTypeToExpressionType()) + ", but found " + + toString(typeOf(*upper)) + " instead."}; } return util::interpolate(lower->get(), upper->get(), t); } @@ -94,7 +94,7 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { } std::optional interpolator; - + const std::optional interpName = toString(arrayMember(interp, 0)); if (interpName && *interpName == "linear") { interpolator = {ExponentialInterpolator(1.0)}; @@ -119,37 +119,31 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { x2 = toDouble(arrayMember(interp, 3)); y2 = toDouble(arrayMember(interp, 4)); } - if ( - !x1 || !y1 || !x2 || !y2 || - *x1 < 0 || *x1 > 1 || - *y1 < 0 || *y1 > 1 || - *x2 < 0 || *x2 > 1 || - *y2 < 0 || *y2 > 1 - ) { + if (!x1 || !y1 || !x2 || !y2 || *x1 < 0 || *x1 > 1 || *y1 < 0 || *y1 > 1 || *x2 < 0 || *x2 > 1 || *y2 < 0 || + *y2 > 1) { ctx.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.", 1); return ParseResult(); - } interpolator = {CubicBezierInterpolator(*x1, *y1, *x2, *y2)}; } - + if (!interpolator) { ctx.error("Unknown interpolation type " + (interpName ? *interpName : ""), 1, 0); return ParseResult(); } - + std::size_t minArgs = 4; if (length - 1 < minArgs) { ctx.error("Expected at least 4 arguments, but found only " + util::toString(length - 1) + "."); return ParseResult(); } - + // [interpolation, interp_type, input, 2 * (n pairs)...] if ((length - 1) % 2 != 0) { ctx.error("Expected an even number of arguments."); return ParseResult(); } - + ParseResult input = ctx.parse(arrayMember(value, 2), 2, {type::Number}); if (!input) { return input; @@ -160,9 +154,9 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { if (ctx.getExpected() && *ctx.getExpected() != type::Value) { outputType = ctx.getExpected(); } - - double previous = - std::numeric_limits::infinity(); - + + double previous = -std::numeric_limits::infinity(); + for (std::size_t i = 3; i + 1 < length; i += 2) { const std::optional labelValue = toValue(arrayMember(value, i)); std::optional label; @@ -194,12 +188,15 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { ); } if (!label) { - ctx.error(labelError ? *labelError : - R"(Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.)", - i); + ctx.error( + labelError + ? *labelError + : R"(Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.)", + i + ); return ParseResult(); } - + if (*label <= previous) { ctx.error( R"(Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.)", @@ -208,7 +205,7 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { return ParseResult(); } previous = *label; - + auto output = ctx.parse(arrayMember(value, i + 1), i + 1, outputType); if (!output) { return ParseResult(); @@ -219,31 +216,29 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { stops.emplace(*label, std::move(*output)); } - + assert(outputType); - return createInterpolate(*outputType, - *interpolator, - std::move(*input), - std::move(stops), - ctx); + return createInterpolate(*outputType, *interpolator, std::move(*input), std::move(stops), ctx); } -ParseResult createInterpolate(type::Type type, - Interpolator interpolator, - std::unique_ptr input, - std::map> stops, - ParsingContext& ctx) { +ParseResult createInterpolate( + type::Type type, + Interpolator interpolator, + std::unique_ptr input, + std::map> stops, + ParsingContext& ctx +) { return type.match( [&](const type::NumberType&) -> ParseResult { - return ParseResult(std::make_unique>( - type, interpolator, std::move(input), std::move(stops) - )); + return ParseResult( + std::make_unique>(type, interpolator, std::move(input), std::move(stops)) + ); }, [&](const type::ColorType&) -> ParseResult { - return ParseResult(std::make_unique>( - type, interpolator, std::move(input), std::move(stops) - )); + return ParseResult( + std::make_unique>(type, interpolator, std::move(input), std::move(stops)) + ); }, [&](const type::Array& arrayType) -> ParseResult { if (arrayType.itemType != type::Number || !arrayType.N) { @@ -261,14 +256,16 @@ ParseResult createInterpolate(type::Type type, ); } -Interpolate::Interpolate(const type::Type& type_, - Interpolator interpolator_, - std::unique_ptr input_, - std::map> stops_) - : Expression(Kind::Interpolate, type_), - interpolator(std::move(interpolator_)), - input(std::move(input_)), - stops(std::move(stops_)) { +Interpolate::Interpolate( + const type::Type& type_, + Interpolator interpolator_, + std::unique_ptr input_, + std::map> stops_ +) + : Expression(Kind::Interpolate, type_), + interpolator(std::move(interpolator_)), + input(std::move(input_)), + stops(std::move(stops_)) { assert(input->getType() == type::Number); } @@ -285,20 +282,21 @@ std::vector> Interpolate::possibleOutputs() const { mbgl::Value Interpolate::serialize() const { std::vector serialized; serialized.emplace_back(getOperator()); - + interpolator.match( [&](const ExponentialInterpolator& exponential) { if (exponential.base == 1) { - serialized.emplace_back(std::vector{{ std::string("linear") }}); + serialized.emplace_back(std::vector{{std::string("linear")}}); } else { - serialized.emplace_back(std::vector{{ std::string("exponential"), exponential.base }}); + serialized.emplace_back(std::vector{{std::string("exponential"), exponential.base}}); } }, [&](const CubicBezierInterpolator& cubicBezier) { static const std::string cubicBezierTag("cubic-bezier"); auto p1 = cubicBezier.ub.getP1(); auto p2 = cubicBezier.ub.getP2(); - serialized.emplace_back(std::vector{{ cubicBezierTag, p1.first, p1.second, p2.first, p2.second }}); + serialized.emplace_back(std::vector{{cubicBezierTag, p1.first, p1.second, p2.first, p2.second}} + ); } ); serialized.emplace_back(input->serialize()); diff --git a/src/mbgl/style/expression/is_constant.cpp b/src/mbgl/style/expression/is_constant.cpp index 4ae2c182922..1c946230cbe 100644 --- a/src/mbgl/style/expression/is_constant.cpp +++ b/src/mbgl/style/expression/is_constant.cpp @@ -1,7 +1,6 @@ #include #include - namespace mbgl { namespace style { namespace expression { diff --git a/src/mbgl/style/expression/is_expression.cpp b/src/mbgl/style/expression/is_expression.cpp index 245dd38313b..d071edd3a73 100644 --- a/src/mbgl/style/expression/is_expression.cpp +++ b/src/mbgl/style/expression/is_expression.cpp @@ -15,11 +15,10 @@ bool isExpression(const Convertible& value) { if (!isArray(value) || arrayLength(value) == 0) return false; std::optional name = toString(arrayMember(value, 0)); if (!name) return false; - + return isExpression(*name) || CompoundExpression::exists(*name); } - } // namespace expression } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/expression/length.cpp b/src/mbgl/style/expression/length.cpp index 2ce7fa90155..8e9249fee94 100644 --- a/src/mbgl/style/expression/length.cpp +++ b/src/mbgl/style/expression/length.cpp @@ -8,22 +8,19 @@ namespace expression { Length::Length(std::unique_ptr input_) : Expression(Kind::Length, type::Number), - input(std::move(input_)) { -} + input(std::move(input_)) {} EvaluationResult Length::evaluate(const EvaluationContext& params) const { EvaluationResult value = input->evaluate(params); if (!value) return value; return value->match( - [] (const std::string& s) { - return EvaluationResult { static_cast(s.size()) }; - }, - [] (const std::vector& v) { - return EvaluationResult { static_cast(v.size()) }; - }, - [&] (const auto&) -> EvaluationResult { - return EvaluationError { "Expected value to be of type string or array, but found " + toString(typeOf(*value)) + " instead." }; - }); + [](const std::string& s) { return EvaluationResult{static_cast(s.size())}; }, + [](const std::vector& v) { return EvaluationResult{static_cast(v.size())}; }, + [&](const auto&) -> EvaluationResult { + return EvaluationError{ + "Expected value to be of type string or array, but found " + toString(typeOf(*value)) + " instead."}; + } + ); } void Length::eachChild(const std::function& visit) const { @@ -39,7 +36,7 @@ bool Length::operator==(const Expression& e) const { } std::vector> Length::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } using namespace mbgl::style::conversion; diff --git a/src/mbgl/style/expression/let.cpp b/src/mbgl/style/expression/let.cpp index cb3ca68c39c..ee44bee9e4a 100644 --- a/src/mbgl/style/expression/let.cpp +++ b/src/mbgl/style/expression/let.cpp @@ -35,13 +35,13 @@ ParseResult Let::parse(const Convertible& value, ParsingContext& ctx) { } std::map> bindings_; - for(std::size_t i = 1; i < length - 1; i += 2) { + for (std::size_t i = 1; i < length - 1; i += 2) { std::optional name = toString(arrayMember(value, i)); if (!name) { ctx.error("Expected string, but found " + getJSONType(arrayMember(value, i)) + " instead.", i); return ParseResult(); } - + bool isValidName = std::all_of(name->begin(), name->end(), [](unsigned char c) { return ::isalnum(c) || c == '_'; }); @@ -49,12 +49,12 @@ ParseResult Let::parse(const Convertible& value, ParsingContext& ctx) { ctx.error("Variable names must contain only alphanumeric characters or '_'.", 1); return ParseResult(); } - + ParseResult bindingValue = ctx.parse(arrayMember(value, i + 1), i + 1); if (!bindingValue) { return ParseResult(); } - + bindings_.emplace(*name, std::move(*bindingValue)); } @@ -84,7 +84,7 @@ EvaluationResult Var::evaluate(const EvaluationContext& params) const { void Var::eachChild(const std::function&) const {} std::vector> Var::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } ParseResult Var::parse(const Convertible& value_, ParsingContext& ctx) { @@ -99,8 +99,11 @@ ParseResult Var::parse(const Convertible& value_, ParsingContext& ctx) { std::optional> bindingValue = ctx.getBinding(name_); if (!bindingValue) { - ctx.error(R"(Unknown variable ")" + name_ + R"(". Make sure ")" + - name_ + R"(" has been bound in an enclosing "let" expression before using it.)", 1); + ctx.error( + R"(Unknown variable ")" + name_ + R"(". Make sure ")" + name_ + + R"(" has been bound in an enclosing "let" expression before using it.)", + 1 + ); return ParseResult(); } @@ -108,7 +111,7 @@ ParseResult Var::parse(const Convertible& value_, ParsingContext& ctx) { } mbgl::Value Var::serialize() const { - return std::vector{{ getOperator(), name }}; + return std::vector{{getOperator(), name}}; } } // namespace expression diff --git a/src/mbgl/style/expression/literal.cpp b/src/mbgl/style/expression/literal.cpp index 9b07131404a..41967bd9672 100644 --- a/src/mbgl/style/expression/literal.cpp +++ b/src/mbgl/style/expression/literal.cpp @@ -21,24 +21,28 @@ std::optional parseValue(const Convertible& value, ParsingContext& ctx) { if (isObject(value)) { std::unordered_map result; bool error = false; - eachMember(value, [&] (const std::string& k, const mbgl::style::conversion::Convertible& v) -> std::optional { - if (!error) { - std::optional memberValue = parseValue(v, ctx); - if (memberValue) { - result.emplace(k, *memberValue); - } else { - error = true; + eachMember( + value, + [&](const std::string& k, + const mbgl::style::conversion::Convertible& v) -> std::optional { + if (!error) { + std::optional memberValue = parseValue(v, ctx); + if (memberValue) { + result.emplace(k, *memberValue); + } else { + error = true; + } } + return {}; } - return {}; - }); + ); return error ? std::optional() : std::optional(result); } - + if (isArray(value)) { std::vector result; const auto length = arrayLength(value); - for(std::size_t i = 0; i < length; i++) { + for (std::size_t i = 0; i < length; i++) { std::optional item = parseValue(arrayMember(value, i), ctx); if (item) { result.emplace_back(*item); @@ -48,19 +52,17 @@ std::optional parseValue(const Convertible& value, ParsingContext& ctx) { } return std::optional(result); } - + std::optional v = toValue(value); // since value represents a JSON value, if it's not undefined, object, or // array, it must be convertible to mbgl::Value assert(v); - + return v->match( [&](uint64_t n) { return checkNumber(n); }, [&](int64_t n) { return checkNumber(n); }, [&](double n) { return checkNumber(n); }, - [&](const auto&) { - return std::optional(toExpressionValue(*v)); - } + [&](const auto&) { return std::optional(toExpressionValue(*v)); } ); } @@ -71,30 +73,28 @@ ParseResult Literal::parse(const Convertible& value, ParsingContext& ctx) { } else if (isArray(value)) { // object or array value, quoted with ["literal", value] if (arrayLength(value) != 2) { - ctx.error("'literal' expression requires exactly one argument, but found " + util::toString(arrayLength(value) - 1) + " instead."); + ctx.error( + "'literal' expression requires exactly one argument, but found " + + util::toString(arrayLength(value) - 1) + " instead." + ); return ParseResult(); } const std::optional parsedValue = parseValue(arrayMember(value, 1), ctx); if (!parsedValue) { return ParseResult(); } - + // special case: infer the item type if possible for zero-length arrays - if ( - ctx.getExpected() && - ctx.getExpected()->template is() && - parsedValue->template is>() - ) { + if (ctx.getExpected() && ctx.getExpected()->template is() && + parsedValue->template is>()) { auto type = typeOf(*parsedValue).template get(); auto expected = ctx.getExpected()->template get(); - if ( - type.N && (*type.N == 0) && - (!expected.N || (*expected.N == 0)) - ) { - return ParseResult(std::make_unique(expected, parsedValue->template get>())); + if (type.N && (*type.N == 0) && (!expected.N || (*expected.N == 0))) { + return ParseResult(std::make_unique(expected, parsedValue->template get>()) + ); } } - + return ParseResult(std::make_unique(*parsedValue)); } else { // bare primitive value (string, number, boolean, null) @@ -105,7 +105,7 @@ ParseResult Literal::parse(const Convertible& value, ParsingContext& ctx) { mbgl::Value Literal::serialize() const { if (getType().is() || getType().is()) { - return std::vector{{ getOperator(), *fromExpressionValue(value) }}; + return std::vector{{getOperator(), *fromExpressionValue(value)}}; } else { return *fromExpressionValue(value); } diff --git a/src/mbgl/style/expression/match.cpp b/src/mbgl/style/expression/match.cpp index e2a825c1764..4134745648d 100644 --- a/src/mbgl/style/expression/match.cpp +++ b/src/mbgl/style/expression/match.cpp @@ -21,9 +21,10 @@ template bool Match::operator==(const Expression& e) const { if (e.getKind() == Kind::Match) { auto rhs = static_cast(&e); - return (*input == *(rhs->input) && - *otherwise == *(rhs->otherwise) && - Expression::childrenEqual(branches, rhs->branches)); + return ( + *input == *(rhs->input) && *otherwise == *(rhs->otherwise) && + Expression::childrenEqual(branches, rhs->branches) + ); } return false; } @@ -47,7 +48,7 @@ mbgl::Value Match::serialize() const { std::vector serialized; serialized.emplace_back(getOperator()); serialized.emplace_back(input->serialize()); - + // Sort so serialization has an arbitrary defined order, even though branch order doesn't affect evaluation std::map> sortedBranches(branches.begin(), branches.end()); @@ -66,20 +67,20 @@ mbgl::Value Match::serialize() const { groupedByOutput[outputIndex->second].second.emplace_back(entry.first); } }; - + for (auto& entry : groupedByOutput) { entry.second.size() == 1 - ? serialized.emplace_back(entry.second[0]) // Only a single label matches this output expression - : serialized.emplace_back(entry.second); // Array of literal labels pointing to this output expression - serialized.emplace_back(entry.first->serialize()); // The output expression itself + ? serialized.emplace_back(entry.second[0]) // Only a single label matches this output expression + : serialized.emplace_back(entry.second); // Array of literal labels pointing to this output expression + serialized.emplace_back(entry.first->serialize()); // The output expression itself } - + serialized.emplace_back(otherwise->serialize()); return serialized; } - -template<> EvaluationResult Match::evaluate(const EvaluationContext& params) const { +template <> +EvaluationResult Match::evaluate(const EvaluationContext& params) const { const EvaluationResult inputValue = input->evaluate(params); if (!inputValue) { return inputValue.error(); @@ -97,7 +98,8 @@ template<> EvaluationResult Match::evaluate(const EvaluationContext return otherwise->evaluate(params); } -template<> EvaluationResult Match::evaluate(const EvaluationContext& params) const { +template <> +EvaluationResult Match::evaluate(const EvaluationContext& params) const { const EvaluationResult inputValue = input->evaluate(params); if (!inputValue) { return inputValue.error(); @@ -115,7 +117,7 @@ template<> EvaluationResult Match::evaluate(const EvaluationContext& pa return (*it).second->evaluate(params); } } - + return otherwise->evaluate(params); } @@ -125,7 +127,9 @@ template class Match; using InputType = variant; using namespace mbgl::style::conversion; -std::optional parseInputValue(const Convertible& input, ParsingContext& parentContext, std::size_t index, std::optional& inputType) { +std::optional parseInputValue( + const Convertible& input, ParsingContext& parentContext, std::size_t index, std::optional& inputType +) { using namespace mbgl::style::conversion; std::optional result; std::optional type; @@ -134,25 +138,37 @@ std::optional parseInputValue(const Convertible& input, ParsingContex if (value) { value->match( - [&] (uint64_t n) { + [&](uint64_t n) { if (!Value::isSafeInteger(n)) { - parentContext.error("Branch labels must be integers no larger than " + util::toString(Value::maxSafeInteger()) + ".", index); + parentContext.error( + "Branch labels must be integers no larger than " + util::toString(Value::maxSafeInteger()) + + ".", + index + ); } else { type = {type::Number}; result = std::optional{static_cast(n)}; } }, - [&] (int64_t n) { + [&](int64_t n) { if (!Value::isSafeInteger(n)) { - parentContext.error("Branch labels must be integers no larger than " + util::toString(Value::maxSafeInteger()) + ".", index); + parentContext.error( + "Branch labels must be integers no larger than " + util::toString(Value::maxSafeInteger()) + + ".", + index + ); } else { type = {type::Number}; result = std::optional{n}; } }, - [&] (double n) { + [&](double n) { if (!Value::isSafeInteger(n)) { - parentContext.error("Branch labels must be integers no larger than " + util::toString(Value::maxSafeInteger()) + ".", index); + parentContext.error( + "Branch labels must be integers no larger than " + util::toString(Value::maxSafeInteger()) + + ".", + index + ); } else if (n != std::floor(n)) { parentContext.error("Numeric branch labels must be integer values.", index); } else { @@ -160,13 +176,11 @@ std::optional parseInputValue(const Convertible& input, ParsingContex result = std::optional{static_cast(n)}; } }, - [&] (const std::string& s) { + [&](const std::string& s) { type = {type::String}; result = {s}; }, - [&] (const auto&) { - parentContext.error("Branch labels must be numbers or strings.", index); - } + [&](const auto&) { parentContext.error("Branch labels must be numbers or strings.", index); } ); } else { parentContext.error("Branch labels must be numbers or strings.", index); @@ -190,19 +204,19 @@ std::optional parseInputValue(const Convertible& input, ParsingContex } template -static ParseResult create(type::Type outputType, - std::unique_ptrinput, - std::vector, - std::unique_ptr>> branches, - std::unique_ptr otherwise, - ParsingContext& ctx) { +static ParseResult create( + type::Type outputType, + std::unique_ptr input, + std::vector, std::unique_ptr>> branches, + std::unique_ptr otherwise, + ParsingContext& ctx +) { typename Match::Branches typedBranches; - + std::size_t index = 2; typedBranches.reserve(branches.size()); - for (std::pair, - std::unique_ptr>& pair : branches) { + for (std::pair, std::unique_ptr>& pair : branches) { std::shared_ptr result = std::move(pair.second); for (const InputType& label : pair.first) { const auto& typedLabel = label.template get(); @@ -212,24 +226,19 @@ static ParseResult create(type::Type outputType, } typedBranches.emplace(typedLabel, result); } - + index += 2; } - return ParseResult(std::make_unique>( - outputType, - std::move(input), - std::move(typedBranches), - std::move(otherwise) - )); + return ParseResult( + std::make_unique>(outputType, std::move(input), std::move(typedBranches), std::move(otherwise)) + ); } ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { assert(isArray(value)); auto length = arrayLength(value); if (length < 5) { - ctx.error( - "Expected at least 4 arguments, but found only " + util::toString(length - 1) + "." - ); + ctx.error("Expected at least 4 arguments, but found only " + util::toString(length - 1) + "."); return ParseResult(); } @@ -245,8 +254,7 @@ ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { outputType = ctx.getExpected(); } - std::vector, - std::unique_ptr>> branches; + std::vector, std::unique_ptr>> branches; branches.reserve((length - 3) / 2); for (size_t i = 2; i + 1 < length; i += 2) { @@ -261,7 +269,7 @@ ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { ctx.error("Expected at least one branch label.", i); return ParseResult(); } - + labels.reserve(groupLength); for (size_t j = 0; j < groupLength; j++) { const std::optional inputValue = parseInputValue(arrayMember(label, j), ctx, i, inputType); @@ -277,16 +285,16 @@ ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { } labels.push_back(*inputValue); } - + ParseResult output = ctx.parse(arrayMember(value, i + 1), i + 1, outputType); if (!output) { return ParseResult(); } - + if (!outputType) { outputType = (*output)->getType(); } - + branches.emplace_back(std::move(labels), std::move(*output)); } diff --git a/src/mbgl/style/expression/number_format.cpp b/src/mbgl/style/expression/number_format.cpp index 13082fffc2e..da6847a8a04 100644 --- a/src/mbgl/style/expression/number_format.cpp +++ b/src/mbgl/style/expression/number_format.cpp @@ -11,18 +11,19 @@ const char currencyKey[] = "currency"; const char minFractionDigitsKey[] = "min-fraction-digits"; const char maxFractionDigitsKey[] = "max-fraction-digits"; -NumberFormat::NumberFormat(std::unique_ptr number_, - std::unique_ptr locale_, - std::unique_ptr currency_, - std::unique_ptr minFractionDigits_, - std::unique_ptr maxFractionDigits_) +NumberFormat::NumberFormat( + std::unique_ptr number_, + std::unique_ptr locale_, + std::unique_ptr currency_, + std::unique_ptr minFractionDigits_, + std::unique_ptr maxFractionDigits_ +) : Expression(Kind::NumberFormat, type::String), number(std::move(number_)), locale(std::move(locale_)), currency(std::move(currency_)), minFractionDigits(std::move(minFractionDigits_)), - maxFractionDigits(std::move(maxFractionDigits_)) -{} + maxFractionDigits(std::move(maxFractionDigits_)) {} NumberFormat::~NumberFormat() = default; @@ -32,7 +33,7 @@ EvaluationResult NumberFormat::evaluate(const EvaluationContext& params) const { return numberResult.error(); } double evaluatedNumber = numberResult->get(); - + std::string evaluatedLocale; if (locale) { auto localeResult = locale->evaluate(params); @@ -70,11 +71,9 @@ EvaluationResult NumberFormat::evaluate(const EvaluationContext& params) const { } std::string output; - output = platform::formatNumber(evaluatedNumber, - evaluatedLocale, - evaluatedCurrency, - evaluatedMinFractionDigits, - evaluatedMaxFractionDigits); + output = platform::formatNumber( + evaluatedNumber, evaluatedLocale, evaluatedCurrency, evaluatedMinFractionDigits, evaluatedMaxFractionDigits + ); return output; } @@ -89,12 +88,10 @@ void NumberFormat::eachChild(const std::function& visit bool NumberFormat::operator==(const Expression& e) const { if (e.getKind() == Kind::NumberFormat) { auto rhs = static_cast(&e); - if ((locale && (!rhs->locale || *locale != *rhs->locale)) || - (!locale && rhs->locale)) { + if ((locale && (!rhs->locale || *locale != *rhs->locale)) || (!locale && rhs->locale)) { return false; } - if ((currency && (!rhs->currency || *currency != *rhs->currency)) || - (!currency && rhs->currency)) { + if ((currency && (!rhs->currency || *currency != *rhs->currency)) || (!currency && rhs->currency)) { return false; } if ((minFractionDigits && (!rhs->minFractionDigits || *minFractionDigits != *rhs->minFractionDigits)) || @@ -111,7 +108,7 @@ bool NumberFormat::operator==(const Expression& e) const { } std::vector> NumberFormat::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } using namespace mbgl::style::conversion; @@ -181,15 +178,17 @@ ParseResult NumberFormat::parse(const Convertible& value, ParsingContext& ctx) { } } - return ParseResult(std::make_unique(std::move(*numberResult), - localeResult ? std::move(*localeResult) : nullptr, - currencyResult? std::move(*currencyResult) : nullptr, - minFractionDigitsResult ? std::move(*minFractionDigitsResult) : nullptr, - maxFractionDigitsResult ? std::move(*maxFractionDigitsResult) : nullptr)); + return ParseResult(std::make_unique( + std::move(*numberResult), + localeResult ? std::move(*localeResult) : nullptr, + currencyResult ? std::move(*currencyResult) : nullptr, + minFractionDigitsResult ? std::move(*minFractionDigitsResult) : nullptr, + maxFractionDigitsResult ? std::move(*maxFractionDigitsResult) : nullptr + )); } mbgl::Value NumberFormat::serialize() const { - std::vector serialized{{ getOperator() }}; + std::vector serialized{{getOperator()}}; serialized.emplace_back(number->serialize()); std::unordered_map options; diff --git a/src/mbgl/style/expression/parsing_context.cpp b/src/mbgl/style/expression/parsing_context.cpp index 47d98ade08a..f798ea697ca 100644 --- a/src/mbgl/style/expression/parsing_context.cpp +++ b/src/mbgl/style/expression/parsing_context.cpp @@ -54,9 +54,8 @@ bool isConstant(const Expression& expression) { } } - bool isTypeAnnotation = expression.getKind() == Kind::Coercion || - expression.getKind() == Kind::Assertion; - + bool isTypeAnnotation = expression.getKind() == Kind::Coercion || expression.getKind() == Kind::Assertion; + bool childrenConstant = true; expression.eachChild([&](const Expression& child) { // We can _almost_ assume that if `expressions` children are constant, @@ -75,32 +74,37 @@ bool isConstant(const Expression& expression) { if (!childrenConstant) { return false; } - + return isFeatureConstant(expression) && - isGlobalPropertyConstant(expression, std::array{{"zoom", "heatmap-density"}}) && - isGlobalPropertyConstant(expression, std::array{{"zoom", "line-progress"}}) && - isGlobalPropertyConstant(expression, std::array{{"zoom", "accumulated"}}); + isGlobalPropertyConstant(expression, std::array{{"zoom", "heatmap-density"}}) && + isGlobalPropertyConstant(expression, std::array{{"zoom", "line-progress"}}) && + isGlobalPropertyConstant(expression, std::array{{"zoom", "accumulated"}}); } using namespace mbgl::style::conversion; -ParseResult ParsingContext::parse(const Convertible& value, - std::size_t index_, - std::optional expected_, - const std::optional& typeAnnotationOption) { - ParsingContext child(key + "[" + util::toString(index_) + "]", - errors, - std::move(expected_), - scope); +ParseResult ParsingContext::parse( + const Convertible& value, + std::size_t index_, + std::optional expected_, + const std::optional& typeAnnotationOption +) { + ParsingContext child(key + "[" + util::toString(index_) + "]", errors, std::move(expected_), scope); return child.parse(value, typeAnnotationOption); } -ParseResult ParsingContext::parse(const Convertible& value, std::size_t index_, std::optional expected_, - const std::map>& bindings) { - ParsingContext child(key + "[" + util::toString(index_) + "]", - errors, - std::move(expected_), - std::make_shared(bindings, scope)); +ParseResult ParsingContext::parse( + const Convertible& value, + std::size_t index_, + std::optional expected_, + const std::map>& bindings +) { + ParsingContext child( + key + "[" + util::toString(index_) + "]", + errors, + std::move(expected_), + std::make_shared(bindings, scope) + ); return child.parse(value); } @@ -147,17 +151,19 @@ bool isExpression(const std::string& name) { return expressionRegistry.contains(name.c_str()); } -ParseResult ParsingContext::parse(const Convertible& value, - const std::optional& typeAnnotationOption) { +ParseResult ParsingContext::parse( + const Convertible& value, const std::optional& typeAnnotationOption +) { ParseResult parsed; - + if (isArray(value)) { const std::size_t length = arrayLength(value); if (length == 0) { - error(R"(Expected an array with at least one element. If you wanted a literal array, use ["literal", []].)"); + error(R"(Expected an array with at least one element. If you wanted a literal array, use ["literal", []].)" + ); return ParseResult(); } - + const std::optional op = toString(arrayMember(value, 0)); if (!op) { error( @@ -167,7 +173,7 @@ ParseResult ParsingContext::parse(const Convertible& value, ); return ParseResult(); } - + auto parseFunction = expressionRegistry.find(op->c_str()); if (parseFunction != expressionRegistry.end()) { parsed = parseFunction->second(value, *this); @@ -202,11 +208,14 @@ ParseResult ParsingContext::parse(const Convertible& value, if (expected) { const type::Type actual = (*parsed)->getType(); - if ((*expected == type::String || *expected == type::Number || *expected == type::Boolean || *expected == type::Object || expected->is()) && actual == type::Value) { - parsed = { annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::assert)) }; - } else if ((*expected == type::Color || *expected == type::Formatted || *expected == type::Image) && - (actual == type::Value || actual == type::String)) { - parsed = { annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::coerce)) }; + if ((*expected == type::String || *expected == type::Number || *expected == type::Boolean || + *expected == type::Object || expected->is()) && + actual == type::Value) { + parsed = { + annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::assert))}; + } else if ((*expected == type::Color || *expected == type::Formatted || *expected == type::Image) && (actual == type::Value || actual == type::String)) { + parsed = { + annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::coerce))}; } else { checkType((*parsed)->getType()); if (!errors->empty()) { @@ -226,14 +235,12 @@ ParseResult ParsingContext::parse(const Convertible& value, error(evaluated.error().message); return ParseResult(); } - + const type::Type type = (*parsed)->getType(); if (type.is()) { // keep the original expression's array type, even if the evaluated // type is more specific. - return ParseResult(std::make_unique( - type.get(), - evaluated->get>()) + return ParseResult(std::make_unique(type.get(), evaluated->get>()) ); } else { return ParseResult(std::make_unique(*evaluated)); @@ -243,8 +250,9 @@ ParseResult ParsingContext::parse(const Convertible& value, return parsed; } -ParseResult ParsingContext::parseExpression(const Convertible& value, - const std::optional& typeAnnotationOption) { +ParseResult ParsingContext::parseExpression( + const Convertible& value, const std::optional& typeAnnotationOption +) { return parse(value, typeAnnotationOption); } diff --git a/src/mbgl/style/expression/step.cpp b/src/mbgl/style/expression/step.cpp index 7f75135e180..f501d5fa2c7 100644 --- a/src/mbgl/style/expression/step.cpp +++ b/src/mbgl/style/expression/step.cpp @@ -9,13 +9,12 @@ namespace mbgl { namespace style { namespace expression { -Step::Step(const type::Type& type_, - std::unique_ptr input_, - std::map> stops_) - : Expression(Kind::Step, type_), - input(std::move(input_)), - stops(std::move(stops_)) -{ +Step::Step( + const type::Type& type_, std::unique_ptr input_, std::map> stops_ +) + : Expression(Kind::Step, type_), + input(std::move(input_)), + stops(std::move(stops_)) { assert(input->getType() == type::Number); } @@ -27,11 +26,11 @@ EvaluationResult Step::evaluate(const EvaluationContext& params) const { float x = *fromExpressionValue(*evaluatedInput); if (std::isnan(x)) { - return EvaluationError { "Input is not a number." }; + return EvaluationError{"Input is not a number."}; } if (stops.empty()) { - return EvaluationError { "No stops in step curve." }; + return EvaluationError{"No stops in step curve."}; } auto it = stops.upper_bound(x); @@ -79,7 +78,6 @@ Range Step::getCoveringStops(const double lower, const double upper) cons return ::mbgl::style::expression::getCoveringStops(stops, lower, upper); } - ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx) { assert(isArray(value)); @@ -89,26 +87,26 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi ctx.error("Expected at least 4 arguments, but found only " + util::toString(length - 1) + "."); return ParseResult(); } - + // [step, input, firstOutput_value, 2 * (n pairs)...] if ((length - 1) % 2 != 0) { ctx.error("Expected an even number of arguments."); return ParseResult(); } - + ParseResult input = ctx.parse(arrayMember(value, 1), 1, {type::Number}); if (!input) { return input; } - + std::map> stops; std::optional outputType; if (ctx.getExpected() && *ctx.getExpected() != type::Value) { outputType = ctx.getExpected(); } - - double previous = - std::numeric_limits::infinity(); - + + double previous = -std::numeric_limits::infinity(); + // consume the first output value, which doesn't have a corresponding input value, // before proceeding into the "stops" loop below. auto firstOutput = ctx.parse(arrayMember(value, 2), 2, outputType); @@ -119,8 +117,7 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi outputType = (*firstOutput)->getType(); } stops.emplace(-std::numeric_limits::infinity(), std::move(*firstOutput)); - - + for (std::size_t i = 3; i + 1 < length; i += 2) { const auto labelValue = toValue(arrayMember(value, i)); std::optional label; @@ -151,10 +148,13 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi ); } if (!label) { - ctx.error(R"(Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.)", i); + ctx.error( + R"(Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.)", + i + ); return ParseResult(); } - + if (*label <= previous) { ctx.error( R"(Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.)", @@ -163,7 +163,7 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi return ParseResult(); } previous = *label; - + auto output = ctx.parse(arrayMember(value, i + 1), i + 1, outputType); if (!output) { return ParseResult(); @@ -174,9 +174,9 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi stops.emplace(*label, std::move(*output)); } - + assert(outputType); - + return ParseResult(std::make_unique(*outputType, std::move(*input), std::move(stops))); } @@ -196,4 +196,3 @@ mbgl::Value Step::serialize() const { } // namespace expression } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/expression/util.cpp b/src/mbgl/style/expression/util.cpp index f1a8117b341..ba6ceb61bf9 100644 --- a/src/mbgl/style/expression/util.cpp +++ b/src/mbgl/style/expression/util.cpp @@ -6,30 +6,23 @@ namespace style { namespace expression { std::string stringifyColor(double r, double g, double b, double a) { - return stringify(r) + ", " + - stringify(g) + ", " + - stringify(b) + ", " + - stringify(a); + return stringify(r) + ", " + stringify(g) + ", " + stringify(b) + ", " + stringify(a); } Result rgba(double r, double g, double b, double a) { - if ( - r < 0 || r > 255 || - g < 0 || g > 255 || - b < 0 || b > 255 - ) { - return EvaluationError { - "Invalid rgba value [" + stringifyColor(r, g, b, a) + - "]: 'r', 'g', and 'b' must be between 0 and 255." - }; + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { + return EvaluationError{ + "Invalid rgba value [" + stringifyColor(r, g, b, a) + "]: 'r', 'g', and 'b' must be between 0 and 255."}; } if (a < 0 || a > 1) { - return EvaluationError { - "Invalid rgba value [" + stringifyColor(r, g, b, a) + - "]: 'a' must be between 0 and 1." - }; + return EvaluationError{"Invalid rgba value [" + stringifyColor(r, g, b, a) + "]: 'a' must be between 0 and 1."}; } - return Color(static_cast(r / 255 * a), static_cast(g / 255 * a), static_cast(b / 255 * a), static_cast(a)); + return Color( + static_cast(r / 255 * a), + static_cast(g / 255 * a), + static_cast(b / 255 * a), + static_cast(a) + ); } } // namespace expression diff --git a/src/mbgl/style/expression/value.cpp b/src/mbgl/style/expression/value.cpp index 1955a626ef9..58e1e8fa128 100644 --- a/src/mbgl/style/expression/value.cpp +++ b/src/mbgl/style/expression/value.cpp @@ -8,78 +8,84 @@ namespace style { namespace expression { type::Type typeOf(const Value& value) { - return value.match([&](bool) -> type::Type { return type::Boolean; }, - [&](double) -> type::Type { return type::Number; }, - [&](const std::string&) -> type::Type { return type::String; }, - [&](const Color&) -> type::Type { return type::Color; }, - [&](const Collator&) -> type::Type { return type::Collator; }, - [&](const Formatted&) -> type::Type { return type::Formatted; }, - [&](const Image&) -> type::Type { return type::Image; }, - [&](const NullValue&) -> type::Type { return type::Null; }, - [&](const std::unordered_map&) -> type::Type { return type::Object; }, - [&](const std::vector& arr) -> type::Type { - std::optional itemType; - for (const auto& item : arr) { - const type::Type t = typeOf(item); - if (!itemType) { - itemType = {t}; - } else if (*itemType == t) { - continue; - } else { - itemType = {type::Value}; - break; - } - } - - return type::Array(itemType.value_or(type::Value), arr.size()); - }); + return value.match( + [&](bool) -> type::Type { return type::Boolean; }, + [&](double) -> type::Type { return type::Number; }, + [&](const std::string&) -> type::Type { return type::String; }, + [&](const Color&) -> type::Type { return type::Color; }, + [&](const Collator&) -> type::Type { return type::Collator; }, + [&](const Formatted&) -> type::Type { return type::Formatted; }, + [&](const Image&) -> type::Type { return type::Image; }, + [&](const NullValue&) -> type::Type { return type::Null; }, + [&](const std::unordered_map&) -> type::Type { return type::Object; }, + [&](const std::vector& arr) -> type::Type { + std::optional itemType; + for (const auto& item : arr) { + const type::Type t = typeOf(item); + if (!itemType) { + itemType = {t}; + } else if (*itemType == t) { + continue; + } else { + itemType = {type::Value}; + break; + } + } + + return type::Array(itemType.value_or(type::Value), arr.size()); + } + ); } std::string toString(const Value& value) { - return value.match([](const NullValue&) { return std::string(); }, - [](const Color& c) { return c.stringify(); }, // avoid quoting - [](const Formatted& f) { return f.toString(); }, - [](const Image& i) { return i.id(); }, - [](const std::string& s) { return s; }, // avoid quoting - [](const auto& v_) { return stringify(v_); }); + return value.match( + [](const NullValue&) { return std::string(); }, + [](const Color& c) { return c.stringify(); }, // avoid quoting + [](const Formatted& f) { return f.toString(); }, + [](const Image& i) { return i.id(); }, + [](const std::string& s) { return s; }, // avoid quoting + [](const auto& v_) { return stringify(v_); } + ); } void writeJSON(rapidjson::Writer& writer, const Value& value) { - value.match([&](const NullValue&) { writer.Null(); }, - [&](bool b) { writer.Bool(b); }, - [&](double f) { - // make sure integer values are stringified without trailing ".0". - f == std::floor(f) ? writer.Int(static_cast(f)) : writer.Double(f); - }, - [&](const std::string& s) { writer.String(s); }, - [&](const Color& c) { writer.String(c.stringify()); }, - [&](const Collator&) { - // Collators are excluded from constant folding and there's no Literal parser - // for them so there shouldn't be any way to serialize this value. - assert(false); - }, - [&](const Formatted& f) { - // `stringify` in turns calls ValueConverter::fromExpressionValue below - // Serialization strategy for Formatted objects is to return the constant - // expression that would generate them. - mbgl::style::conversion::stringify(writer, f); - }, - [&](const Image& i) { mbgl::style::conversion::stringify(writer, i); }, - [&](const std::vector& arr) { - writer.StartArray(); - for (const auto& item : arr) { - writeJSON(writer, item); - } - writer.EndArray(); - }, - [&](const std::unordered_map& obj) { - writer.StartObject(); - for (const auto& entry : obj) { - writer.Key(entry.first.c_str()); - writeJSON(writer, entry.second); - } - writer.EndObject(); - }); + value.match( + [&](const NullValue&) { writer.Null(); }, + [&](bool b) { writer.Bool(b); }, + [&](double f) { + // make sure integer values are stringified without trailing ".0". + f == std::floor(f) ? writer.Int(static_cast(f)) : writer.Double(f); + }, + [&](const std::string& s) { writer.String(s); }, + [&](const Color& c) { writer.String(c.stringify()); }, + [&](const Collator&) { + // Collators are excluded from constant folding and there's no Literal parser + // for them so there shouldn't be any way to serialize this value. + assert(false); + }, + [&](const Formatted& f) { + // `stringify` in turns calls ValueConverter::fromExpressionValue below + // Serialization strategy for Formatted objects is to return the constant + // expression that would generate them. + mbgl::style::conversion::stringify(writer, f); + }, + [&](const Image& i) { mbgl::style::conversion::stringify(writer, i); }, + [&](const std::vector& arr) { + writer.StartArray(); + for (const auto& item : arr) { + writeJSON(writer, item); + } + writer.EndArray(); + }, + [&](const std::unordered_map& obj) { + writer.StartObject(); + for (const auto& entry : obj) { + writer.Key(entry.first.c_str()); + writeJSON(writer, entry.second); + } + writer.EndObject(); + } + ); } std::string stringify(const Value& value) { @@ -93,31 +99,27 @@ struct FromMBGLValue { Value operator()(const std::vector& v) { std::vector result; result.reserve(v.size()); - for(const auto& item : v) { + for (const auto& item : v) { result.emplace_back(toExpressionValue(item)); } return result; } - + Value operator()(const std::unordered_map& v) { std::unordered_map result; result.reserve(v.size()); - for(const auto& entry : v) { + for (const auto& entry : v) { result.emplace(entry.first, toExpressionValue(entry.second)); } return result; } - + Value operator()(const std::string& s) { return s; } Value operator()(const bool b) { return b; } Value operator()(const NullValue) { return Null; } Value operator()(const double v) { return v; } - Value operator()(const uint64_t& v) { - return static_cast(v); - } - Value operator()(const int64_t& v) { - return static_cast(v); - } + Value operator()(const uint64_t& v) { return static_cast(v); } + Value operator()(const int64_t& v) { return static_cast(v); } }; Value ValueConverter::toExpressionValue(const mbgl::Value& value) { @@ -147,7 +149,7 @@ mbgl::Value ValueConverter::fromExpressionValue(const Value& value) serialized.emplace_back(section.text); std::unordered_map options; - + if (section.fontScale) { options.emplace("font-scale", *section.fontScale); } @@ -157,7 +159,7 @@ mbgl::Value ValueConverter::fromExpressionValue(const Value& value) for (const auto& font : *section.fontStack) { fontStack.emplace_back(font); } - options.emplace("text-font", std::vector{ std::string("literal"), fontStack }); + options.emplace("text-font", std::vector{std::string("literal"), fontStack}); } if (section.textColor) { @@ -180,12 +182,13 @@ mbgl::Value ValueConverter::fromExpressionValue(const Value& value) [&](const std::unordered_map& values) -> mbgl::Value { std::unordered_map converted; converted.reserve(values.size()); - for(const auto& entry : values) { + for (const auto& entry : values) { converted.emplace(entry.first, fromExpressionValue(entry.second)); } return converted; }, - [&](const auto& a) -> mbgl::Value { return a; }); + [&](const auto& a) -> mbgl::Value { return a; } + ); } Value ValueConverter::toExpressionValue(const float value) { @@ -193,12 +196,9 @@ Value ValueConverter::toExpressionValue(const float value) { } std::optional ValueConverter::fromExpressionValue(const Value& value) { - return value.template is() - ? static_cast(value.template get()) - : std::optional(); + return value.template is() ? static_cast(value.template get()) : std::optional(); } - template std::vector toArrayValue(const Container& value) { std::vector result; @@ -217,25 +217,24 @@ Value ValueConverter>::toExpressionValue(const std::array template std::optional> ValueConverter>::fromExpressionValue(const Value& value) { return value.match( - [&] (const std::vector& v) -> std::optional> { + [&](const std::vector& v) -> std::optional> { if (v.size() != N) return std::optional>(); - std::array result; - auto it = result.begin(); - for(const Value& item : v) { - std::optional convertedItem = ValueConverter::fromExpressionValue(item); - if (!convertedItem) { - return std::optional>(); - } - *it = *convertedItem; - it = std::next(it); + std::array result; + auto it = result.begin(); + for (const Value& item : v) { + std::optional convertedItem = ValueConverter::fromExpressionValue(item); + if (!convertedItem) { + return std::optional>(); } - return result; + *it = *convertedItem; + it = std::next(it); + } + return result; }, - [&] (const auto&) { return std::optional>(); } + [&](const auto&) { return std::optional>(); } ); } - template Value ValueConverter>::toExpressionValue(const std::vector& value) { return toArrayValue(value); @@ -244,10 +243,10 @@ Value ValueConverter>::toExpressionValue(const std::vector& va template std::optional> ValueConverter>::fromExpressionValue(const Value& value) { return value.match( - [&] (const std::vector& v) -> std::optional> { + [&](const std::vector& v) -> std::optional> { std::vector result; result.reserve(v.size()); - for(const Value& item : v) { + for (const Value& item : v) { std::optional convertedItem = ValueConverter::fromExpressionValue(item); if (!convertedItem) { return std::optional>(); @@ -256,7 +255,7 @@ std::optional> ValueConverter>::fromExpressionValu } return result; }, - [&] (const auto&) { return std::optional>(); } + [&](const auto&) { return std::optional>(); } ); } @@ -279,15 +278,14 @@ std::optional ValueConverter::fromExpressionValue(const Valu } template -Value ValueConverter>>::toExpressionValue(const T& value) { +Value ValueConverter>>::toExpressionValue(const T& value) { return std::string(Enum::toString(value)); } template std::optional ValueConverter>>::fromExpressionValue(const Value& value) { return value.match( - [&] (const std::string& v) { return Enum::toEnum(v); }, - [&] (const auto&) { return std::optional(); } + [&](const std::string& v) { return Enum::toEnum(v); }, [&](const auto&) { return std::optional(); } ); } @@ -296,24 +294,56 @@ type::Type valueTypeToExpressionType() { return ValueConverter::expressionType(); } -template <> type::Type valueTypeToExpressionType() { return type::Value; } -template <> type::Type valueTypeToExpressionType() { return type::Null; } -template <> type::Type valueTypeToExpressionType() { return type::Boolean; } -template <> type::Type valueTypeToExpressionType() { return type::Number; } -template <> type::Type valueTypeToExpressionType() { return type::String; } -template <> type::Type valueTypeToExpressionType() { return type::Color; } -template <> type::Type valueTypeToExpressionType() { return type::Collator; } -template <> type::Type valueTypeToExpressionType() { return type::Formatted; } +template <> +type::Type valueTypeToExpressionType() { + return type::Value; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Null; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Boolean; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Number; +} +template <> +type::Type valueTypeToExpressionType() { + return type::String; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Color; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Collator; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Formatted; +} template <> type::Type valueTypeToExpressionType() { return type::Image; } -template <> type::Type valueTypeToExpressionType>() { return type::Object; } -template <> type::Type valueTypeToExpressionType>() { return type::Array(type::Value); } +template <> +type::Type valueTypeToExpressionType>() { + return type::Object; +} +template <> +type::Type valueTypeToExpressionType>() { + return type::Array(type::Value); +} // used only for the special (and private) "error" expression -template <> type::Type valueTypeToExpressionType() { return type::Error; } - +template <> +type::Type valueTypeToExpressionType() { + return type::Error; +} // for to_rgba expression template type::Type valueTypeToExpressionType>(); @@ -360,7 +390,7 @@ template struct ValueConverter; template type::Type valueTypeToExpressionType(); template struct ValueConverter; - + template type::Type valueTypeToExpressionType(); template struct ValueConverter; diff --git a/src/mbgl/style/expression/within.cpp b/src/mbgl/style/expression/within.cpp index f56e95aa160..7f4b9309adc 100644 --- a/src/mbgl/style/expression/within.cpp +++ b/src/mbgl/style/expression/within.cpp @@ -20,21 +20,25 @@ Point latLonToTileCoodinates(const Point& point, const mbgl::Ca const double size = util::EXTENT * std::pow(2, canonical.z); auto x = (point.x + util::LONGITUDE_MAX) * size / util::DEGREES_MAX; - auto y = - (util::LONGITUDE_MAX - util::rad2deg(std::log(std::tan(point.y * M_PI / util::DEGREES_MAX + M_PI / 4.0)))) * - size / util::DEGREES_MAX; + auto y = (util::LONGITUDE_MAX - util::rad2deg(std::log(std::tan(point.y * M_PI / util::DEGREES_MAX + M_PI / 4.0))) + ) * + size / util::DEGREES_MAX; Point p; - p.x = (util::clamp(static_cast(x), std::numeric_limits::min(), std::numeric_limits::max())); - p.y = (util::clamp(static_cast(y), std::numeric_limits::min(), std::numeric_limits::max())); + p.x = (util::clamp( + static_cast(x), std::numeric_limits::min(), std::numeric_limits::max() + )); + p.y = (util::clamp( + static_cast(y), std::numeric_limits::min(), std::numeric_limits::max() + )); return p; }; using WithinBBox = GeometryBBox; -Polygon getTilePolygon(const Polygon& polygon, - const mbgl::CanonicalTileID& canonical, - WithinBBox& bbox) { +Polygon getTilePolygon( + const Polygon& polygon, const mbgl::CanonicalTileID& canonical, WithinBBox& bbox +) { Polygon result; result.reserve(polygon.size()); for (const auto& ring : polygon) { @@ -50,9 +54,9 @@ Polygon getTilePolygon(const Polygon& polygon, return result; } -MultiPolygon getTilePolygons(const Feature::geometry_type& polygonGeoSet, - const mbgl::CanonicalTileID& canonical, - WithinBBox& bbox) { +MultiPolygon getTilePolygons( + const Feature::geometry_type& polygonGeoSet, const mbgl::CanonicalTileID& canonical, WithinBBox& bbox +) { return polygonGeoSet.match( [&canonical, &bbox](const mapbox::geometry::multi_polygon& polygons) { MultiPolygon result; @@ -67,7 +71,8 @@ MultiPolygon getTilePolygons(const Feature::geometry_type& polygonGeoSe result.push_back(getTilePolygon(polygon, canonical, bbox)); return result; }, - [](const auto&) { return MultiPolygon(); }); + [](const auto&) { return MultiPolygon(); } + ); } void updatePoint(Point& p, WithinBBox& bbox, const WithinBBox& polyBBox, const int64_t worldSize) { @@ -89,10 +94,12 @@ void updatePoint(Point& p, WithinBBox& bbox, const WithinBBox& polyBBox updateBBox(bbox, p); } -MultiPoint getTilePoints(const GeometryCoordinates& points, - const mbgl::CanonicalTileID& canonical, - WithinBBox& bbox, - const WithinBBox& polyBBox) { +MultiPoint getTilePoints( + const GeometryCoordinates& points, + const mbgl::CanonicalTileID& canonical, + WithinBBox& bbox, + const WithinBBox& polyBBox +) { const int64_t xShift = util::EXTENT * canonical.x; const int64_t yShift = util::EXTENT * canonical.y; const auto worldSize = static_cast(util::EXTENT * std::pow(2, canonical.z)); @@ -107,10 +114,12 @@ MultiPoint getTilePoints(const GeometryCoordinates& points, return results; } -MultiLineString getTileLines(const GeometryCollection& lines, - const mbgl::CanonicalTileID& canonical, - WithinBBox& bbox, - const WithinBBox& polyBBox) { +MultiLineString getTileLines( + const GeometryCollection& lines, + const mbgl::CanonicalTileID& canonical, + WithinBBox& bbox, + const WithinBBox& polyBBox +) { const int64_t xShift = util::EXTENT * canonical.x; const int64_t yShift = util::EXTENT * canonical.y; MultiLineString results; @@ -138,9 +147,9 @@ MultiLineString getTileLines(const GeometryCollection& lines, return results; } -bool featureWithinPolygons(const GeometryTileFeature& feature, - const CanonicalTileID& canonical, - const Feature::geometry_type& polygonGeoSet) { +bool featureWithinPolygons( + const GeometryTileFeature& feature, const CanonicalTileID& canonical, const Feature::geometry_type& polygonGeoSet +) { WithinBBox polyBBox = DefaultWithinBBox; const auto polygons = getTilePolygons(polygonGeoSet, canonical, polyBBox); assert(!polygons.empty()); @@ -170,8 +179,9 @@ bool featureWithinPolygons(const GeometryTileFeature& feature, }; } -std::optional parseValue(const mbgl::style::conversion::Convertible& value_, - mbgl::style::expression::ParsingContext& ctx) { +std::optional parseValue( + const mbgl::style::conversion::Convertible& value_, mbgl::style::expression::ParsingContext& ctx +) { if (isObject(value_)) { mbgl::style::conversion::Error error; auto geojson = toGeoJSON(value_, error); @@ -185,8 +195,9 @@ std::optional parseValue(const mbgl::style::conversion::Convertib return std::nullopt; } -std::optional getPolygonInfo(const Feature& polyFeature, - mbgl::style::expression::ParsingContext& ctx) { +std::optional getPolygonInfo( + const Feature& polyFeature, mbgl::style::expression::ParsingContext& ctx +) { const auto type = apply_visitor(ToFeatureType(), polyFeature.geometry); if (type == FeatureType::Polygon) { return polyFeature.geometry; @@ -200,7 +211,9 @@ namespace style { namespace expression { Within::Within(GeoJSON geojson, Feature::geometry_type geometries_) - : Expression(Kind::Within, type::Boolean), geoJSONSource(std::move(geojson)), geometries(std::move(geometries_)) {} + : Expression(Kind::Within, type::Boolean), + geoJSONSource(std::move(geojson)), + geometries(std::move(geometries_)) {} Within::~Within() = default; @@ -215,8 +228,9 @@ EvaluationResult Within::evaluate(const EvaluationContext& params) const { if (geometryType == FeatureType::Point || geometryType == FeatureType::LineString) { return featureWithinPolygons(*params.feature, *params.canonical, geometries); } - mbgl::Log::Warning(mbgl::Event::General, - "within expression currently only support Point/LineString geometry type."); + mbgl::Log::Warning( + mbgl::Event::General, "within expression currently only support Point/LineString geometry type." + ); return false; } @@ -225,8 +239,10 @@ ParseResult Within::parse(const Convertible& value, ParsingContext& ctx) { if (isArray(value)) { // object value, quoted with ["within", value] if (arrayLength(value) != 2) { - ctx.error("'within' expression requires exactly one argument, but found " + - util::toString(arrayLength(value) - 1) + " instead."); + ctx.error( + "'within' expression requires exactly one argument, but found " + + util::toString(arrayLength(value) - 1) + " instead." + ); return ParseResult(); } @@ -259,7 +275,8 @@ ParseResult Within::parse(const Convertible& value, ParsingContext& ctx) { [&ctx](const auto&) { ctx.error("'within' expression requires valid geojson source that contains polygon geometry type."); return ParseResult(); - }); + } + ); } ctx.error("'within' expression needs to be an array with exactly one argument."); return ParseResult(); @@ -305,8 +322,9 @@ mbgl::Value Within::serialize() const { serialized.emplace(m.name.GetString(), valueConverter(m.value)); } } else { - mbgl::Log::Error(mbgl::Event::General, - "Failed to serialize 'within' expression, converted rapidJSON is not an object"); + mbgl::Log::Error( + mbgl::Event::General, "Failed to serialize 'within' expression, converted rapidJSON is not an object" + ); } return std::vector{{getOperator(), serialized}}; } diff --git a/src/mbgl/style/filter.cpp b/src/mbgl/style/filter.cpp index 7b5ad8d9fc3..ba97cda252e 100644 --- a/src/mbgl/style/filter.cpp +++ b/src/mbgl/style/filter.cpp @@ -5,9 +5,8 @@ namespace mbgl { namespace style { bool Filter::operator()(const expression::EvaluationContext &context) const { - if (!this->expression) return true; - + const expression::EvaluationResult result = (*this->expression)->evaluate(context); if (result) { const std::optional typed = expression::fromExpressionValue(*result); diff --git a/src/mbgl/style/image.cpp b/src/mbgl/style/image.cpp index ea4c8ee8d7e..4cc2099fd2c 100644 --- a/src/mbgl/style/image.cpp +++ b/src/mbgl/style/image.cpp @@ -5,15 +5,18 @@ namespace mbgl { namespace style { -Image::Image(std::string id, - PremultipliedImage&& image, - const float pixelRatio, - bool sdf, - ImageStretches stretchX, - ImageStretches stretchY, - const std::optional& content) +Image::Image( + std::string id, + PremultipliedImage&& image, + const float pixelRatio, + bool sdf, + ImageStretches stretchX, + ImageStretches stretchY, + const std::optional& content +) : baseImpl(makeMutable( - std::move(id), std::move(image), pixelRatio, sdf, std::move(stretchX), std::move(stretchY), content)) {} + std::move(id), std::move(image), pixelRatio, sdf, std::move(stretchX), std::move(stretchY), content + )) {} std::string Image::getID() const { return baseImpl->id; diff --git a/src/mbgl/style/image_impl.cpp b/src/mbgl/style/image_impl.cpp index 3f60ae09ce3..cc18d1bfe86 100644 --- a/src/mbgl/style/image_impl.cpp +++ b/src/mbgl/style/image_impl.cpp @@ -32,13 +32,15 @@ bool validateContent(const ImageContent& content, const Size& size) { } // namespace -Image::Impl::Impl(std::string id_, - PremultipliedImage&& image_, - const float pixelRatio_, - bool sdf_, - ImageStretches stretchX_, - ImageStretches stretchY_, - std::optional content_) +Image::Impl::Impl( + std::string id_, + PremultipliedImage&& image_, + const float pixelRatio_, + bool sdf_, + ImageStretches stretchX_, + ImageStretches stretchY_, + std::optional content_ +) : id(std::move(id_)), image(std::move(image_)), pixelRatio(pixelRatio_), diff --git a/src/mbgl/style/image_impl.hpp b/src/mbgl/style/image_impl.hpp index bd47397ca4c..5a69eba161b 100644 --- a/src/mbgl/style/image_impl.hpp +++ b/src/mbgl/style/image_impl.hpp @@ -12,13 +12,15 @@ namespace style { class Image::Impl { public: - Impl(std::string id, - PremultipliedImage&&, - float pixelRatio, - bool sdf = false, - ImageStretches stretchX = {}, - ImageStretches stretchY = {}, - std::optional content = std::nullopt); + Impl( + std::string id, + PremultipliedImage&&, + float pixelRatio, + bool sdf = false, + ImageStretches stretchX = {}, + ImageStretches stretchY = {}, + std::optional content = std::nullopt + ); const std::string id; diff --git a/src/mbgl/style/layer.cpp b/src/mbgl/style/layer.cpp index 348edcff93d..acbcefcb65e 100644 --- a/src/mbgl/style/layer.cpp +++ b/src/mbgl/style/layer.cpp @@ -12,19 +12,24 @@ namespace mbgl { namespace style { -static_assert(mbgl::underlying_type(Tile::Kind::Geometry) == mbgl::underlying_type(LayerTypeInfo::TileKind::Geometry), - "tile kind error"); -static_assert(mbgl::underlying_type(Tile::Kind::Raster) == mbgl::underlying_type(LayerTypeInfo::TileKind::Raster), - "tile kind error"); -static_assert(mbgl::underlying_type(Tile::Kind::RasterDEM) == mbgl::underlying_type(LayerTypeInfo::TileKind::RasterDEM), - "tile kind error"); +static_assert( + mbgl::underlying_type(Tile::Kind::Geometry) == mbgl::underlying_type(LayerTypeInfo::TileKind::Geometry), + "tile kind error" +); +static_assert( + mbgl::underlying_type(Tile::Kind::Raster) == mbgl::underlying_type(LayerTypeInfo::TileKind::Raster), + "tile kind error" +); +static_assert( + mbgl::underlying_type(Tile::Kind::RasterDEM) == mbgl::underlying_type(LayerTypeInfo::TileKind::RasterDEM), + "tile kind error" +); static LayerObserver nullObserver; Layer::Layer(Immutable impl) : baseImpl(std::move(impl)), - observer(&nullObserver) { -} + observer(&nullObserver) {} Layer::~Layer() = default; @@ -71,8 +76,7 @@ VisibilityType Layer::getVisibility() const { } void Layer::setVisibility(VisibilityType value) { - if (value == getVisibility()) - return; + if (value == getVisibility()) return; auto impl_ = mutableBaseImpl(); impl_->visibility = value; baseImpl = std::move(impl_); @@ -178,9 +182,12 @@ std::optional Layer::setProperty(const std::string& name, con } else if (name == "source-layer") { if (auto sourceLayer = convert(value, *error)) { if (getTypeInfo()->source != LayerTypeInfo::Source::Required) { - Log::Warning(mbgl::Event::General, - "'source-layer' property cannot be set to" - "the layer " + baseImpl->id); + Log::Warning( + mbgl::Event::General, + "'source-layer' property cannot be set to" + "the layer " + + baseImpl->id + ); return std::nullopt; } setSourceLayer(*sourceLayer); @@ -189,9 +196,12 @@ std::optional Layer::setProperty(const std::string& name, con } else if (name == "source") { if (auto sourceID = convert(value, *error)) { if (getTypeInfo()->source != LayerTypeInfo::Source::Required) { - Log::Warning(mbgl::Event::General, - "'source' property cannot be set to" - "the layer " + baseImpl->id); + Log::Warning( + mbgl::Event::General, + "'source' property cannot be set to" + "the layer " + + baseImpl->id + ); return std::nullopt; } setSourceID(*sourceID); diff --git a/src/mbgl/style/layer_impl.cpp b/src/mbgl/style/layer_impl.cpp index b6ab1450124..7b59ead8442 100644 --- a/src/mbgl/style/layer_impl.cpp +++ b/src/mbgl/style/layer_impl.cpp @@ -5,8 +5,7 @@ namespace style { Layer::Impl::Impl(std::string layerID, std::string sourceID) : id(std::move(layerID)), - source(std::move(sourceID)) { -} + source(std::move(sourceID)) {} void Layer::Impl::populateFontStack(std::set&) const {} diff --git a/src/mbgl/style/layer_impl.hpp b/src/mbgl/style/layer_impl.hpp index 53dd1320bde..01cdfc4e774 100644 --- a/src/mbgl/style/layer_impl.hpp +++ b/src/mbgl/style/layer_impl.hpp @@ -58,9 +58,11 @@ class Layer::Impl { }; // To be used in the inherited classes. -#define DECLARE_LAYER_TYPE_INFO \ -const LayerTypeInfo* getTypeInfo() const noexcept final { return staticTypeInfo(); } \ -static const LayerTypeInfo* staticTypeInfo() noexcept +#define DECLARE_LAYER_TYPE_INFO \ + const LayerTypeInfo* getTypeInfo() const noexcept final { \ + return staticTypeInfo(); \ + } \ + static const LayerTypeInfo* staticTypeInfo() noexcept } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp b/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp index 18eea1f7fca..8452c7b1f55 100644 --- a/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp +++ b/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp @@ -6,9 +6,7 @@ namespace style { bool FillExtrusionLayer::Impl::hasLayoutDifference(const Layer::Impl& other) const { assert(other.getTypeInfo() == getTypeInfo()); const auto& impl = static_cast(other); - return filter != impl.filter || - visibility != impl.visibility || - paint.hasDataDrivenPropertyDifference(impl.paint); + return filter != impl.filter || visibility != impl.visibility || paint.hasDataDrivenPropertyDifference(impl.paint); } } // namespace style diff --git a/src/mbgl/style/layers/heatmap_layer_impl.cpp b/src/mbgl/style/layers/heatmap_layer_impl.cpp index dd5baaeb449..48deee27e3a 100644 --- a/src/mbgl/style/layers/heatmap_layer_impl.cpp +++ b/src/mbgl/style/layers/heatmap_layer_impl.cpp @@ -6,9 +6,7 @@ namespace style { bool HeatmapLayer::Impl::hasLayoutDifference(const Layer::Impl& other) const { assert(other.getTypeInfo() == getTypeInfo()); const auto& impl = static_cast(other); - return filter != impl.filter || - visibility != impl.visibility || - paint.hasDataDrivenPropertyDifference(impl.paint); + return filter != impl.filter || visibility != impl.visibility || paint.hasDataDrivenPropertyDifference(impl.paint); } } // namespace style diff --git a/src/mbgl/style/layers/line_layer_impl.cpp b/src/mbgl/style/layers/line_layer_impl.cpp index b5183ba9aee..e459c7d3b4d 100644 --- a/src/mbgl/style/layers/line_layer_impl.cpp +++ b/src/mbgl/style/layers/line_layer_impl.cpp @@ -6,9 +6,7 @@ namespace style { bool LineLayer::Impl::hasLayoutDifference(const Layer::Impl& other) const { assert(other.getTypeInfo() == getTypeInfo()); const auto& impl = static_cast(other); - return filter != impl.filter || - visibility != impl.visibility || - layout != impl.layout || + return filter != impl.filter || visibility != impl.visibility || layout != impl.layout || paint.hasDataDrivenPropertyDifference(impl.paint); } diff --git a/src/mbgl/style/layers/symbol_layer_impl.cpp b/src/mbgl/style/layers/symbol_layer_impl.cpp index 18e5f1cd857..b42103bee63 100644 --- a/src/mbgl/style/layers/symbol_layer_impl.cpp +++ b/src/mbgl/style/layers/symbol_layer_impl.cpp @@ -14,11 +14,10 @@ bool SymbolLayer::Impl::hasFormatSectionOverrides() const { bool SymbolLayer::Impl::hasLayoutDifference(const Layer::Impl& other) const { assert(other.getTypeInfo() == getTypeInfo()); const auto& impl = static_cast(other); - return filter != impl.filter || - visibility != impl.visibility || - layout != impl.layout || + return filter != impl.filter || visibility != impl.visibility || layout != impl.layout || paint.hasDataDrivenPropertyDifference(impl.paint) || - (hasFormatSectionOverrides() && SymbolLayerPaintPropertyOverrides::hasPaintPropertyDifference(paint, impl.paint)); + (hasFormatSectionOverrides() && + SymbolLayerPaintPropertyOverrides::hasPaintPropertyDifference(paint, impl.paint)); } void SymbolLayer::Impl::populateFontStack(std::set& fontStack) const { @@ -36,11 +35,17 @@ void SymbolLayer::Impl::populateFontStack(std::set& fontStack) const if (value) { fontStack.insert(*value); } else { - Log::Warning(Event::ParseStyle, "Layer '" + id + "' has an invalid value for text-font and will not render text. Output values must be contained as literals within the expression."); + Log::Warning( + Event::ParseStyle, + "Layer '" + id + + "' has an invalid value for text-font and will not render text. Output values " + "must be contained as literals within the expression." + ); break; } } - }); + } + ); } } // namespace style diff --git a/src/mbgl/style/layers/symbol_layer_impl.hpp b/src/mbgl/style/layers/symbol_layer_impl.hpp index 826f444e173..d79ce10a8eb 100644 --- a/src/mbgl/style/layers/symbol_layer_impl.hpp +++ b/src/mbgl/style/layers/symbol_layer_impl.hpp @@ -12,77 +12,74 @@ namespace mbgl { namespace style { -template +template struct FormatSectionOverrides; -template +template struct FormatSectionOverrides> { - template + template static void setOverride(const T& overrides, U& overridable) { if (hasOverride(overrides.template get())) { - auto override = - std::make_unique>(Property::expressionType(), - std::move(overridable.template get()), - Property::name()); + auto override = std::make_unique>( + Property::expressionType(), std::move(overridable.template get()), Property::name() + ); PropertyExpression expr(std::move(override)); - overridable.template get() = PossiblyEvaluatedPropertyValue(std::move(expr)); + overridable.template get( + ) = PossiblyEvaluatedPropertyValue(std::move(expr)); } } - template + template static void setOverrides(const T& overrides, U& overridable) { util::ignore({(setOverride(overrides, overridable), 0)...}); } - template + template static void updateOverride(T& evaluated, U& updated) { auto property = evaluated.template get(); if (!property.isConstant()) { const bool hasFormatSectionOverride = property.match( - [] (const style::PropertyExpression& e) { - return e.getExpression().getKind() == expression::Kind::FormatSectionOverride; - }, - [] (const auto&) { - return false; - }); + [](const style::PropertyExpression& e) { + return e.getExpression().getKind() == expression::Kind::FormatSectionOverride; + }, + [](const auto&) { return false; } + ); if (hasFormatSectionOverride) { updated.template get() = std::move(property); } } } - template + template static void updateOverrides(T& evaluated, U& updated) { util::ignore({(updateOverride(evaluated, updated), 0)...}); } - template + template static bool hasOverride(const FormattedProperty& formatted) { - - const auto checkLiteral = [] (const TextField::Type& literal) { + const auto checkLiteral = [](const TextField::Type& literal) { for (const auto& section : literal.sections) { - if (Property::hasOverride(section)) { - return true; - } + if (Property::hasOverride(section)) { + return true; + } } return false; }; return formatted.match( - [&checkLiteral] (const TextField::Type& literal) { - return checkLiteral(literal); - }, - [&checkLiteral] (const PropertyExpression& property) { - bool expressionHasOverrides = false; - const std::function checkExpression = [&](const expression::Expression& e) { + [&checkLiteral](const TextField::Type& literal) { return checkLiteral(literal); }, + [&checkLiteral](const PropertyExpression& property) { + bool expressionHasOverrides = false; + const std::function checkExpression = + [&](const expression::Expression& e) { if (expressionHasOverrides) { return; } - if (e.getKind() == expression::Kind::Literal && - e.getType() == expression::type::Formatted) { + if (e.getKind() == expression::Kind::Literal && e.getType() == expression::type::Formatted) { const auto* literalExpr = static_cast(&e); - const auto formattedValue = expression::fromExpressionValue(literalExpr->getValue()); + const auto formattedValue = + expression::fromExpressionValue(literalExpr->getValue()); if (formattedValue && checkLiteral(*formattedValue)) { expressionHasOverrides = true; } @@ -100,28 +97,29 @@ struct FormatSectionOverrides> { } }; - checkExpression(property.getExpression()); - return expressionHasOverrides; - }, - [] (const auto&) { - return false; - } - ); + checkExpression(property.getExpression()); + return expressionHasOverrides; + }, + [](const auto&) { return false; } + ); } template static bool hasOverrides(const FormattedProperty& formatted) { bool result = false; - util::ignore({ (result |= hasOverride(formatted))... }); + util::ignore({(result |= hasOverride(formatted))...}); return result; } template static bool hasPaintPropertyDifference(const PaintProperties& lhs, const PaintProperties& rhs) { bool result = false; - util::ignore({ (result |= lhs.template get().value.isConstant() && - rhs.template get().value.isConstant() && - (lhs.template get().value.asConstant() != rhs.template get().value.asConstant()))... }); + util::ignore( + {(result |= lhs.template get().value.isConstant() && + rhs.template get().value.isConstant() && + (lhs.template get().value.asConstant() != + rhs.template get().value.asConstant()))...} + ); return result; } }; diff --git a/src/mbgl/style/light.cpp b/src/mbgl/style/light.cpp index bd46474391d..629d72cc08f 100644 --- a/src/mbgl/style/light.cpp +++ b/src/mbgl/style/light.cpp @@ -19,9 +19,12 @@ namespace style { static LightObserver nullObserver; -Light::Light(Immutable impl_) : impl(std::move(impl_)), observer(&nullObserver) {} +Light::Light(Immutable impl_) + : impl(std::move(impl_)), + observer(&nullObserver) {} -Light::Light() : Light(makeMutable()) {} +Light::Light() + : Light(makeMutable()) {} Light::~Light() = default; @@ -61,96 +64,94 @@ MAPBOX_ETERNAL_CONSTEXPR const auto properties = mapbox::eternal::hash_map Light::setProperty(const std::string& name, const Convertible& value) { const auto it = properties.find(name.c_str()); if (it == properties.end()) { - return Error { "light doesn't support this property" }; + return Error{"light doesn't support this property"}; } auto property = static_cast(it->second); - if (property == Property::Anchor) { Error error; - std::optional> typedValue = convert>(value, error, false, false); + std::optional> typedValue = convert>( + value, error, false, false + ); if (!typedValue) { return error; } - + setAnchor(*typedValue); return std::nullopt; - } - + if (property == Property::Color) { Error error; std::optional> typedValue = convert>(value, error, false, false); if (!typedValue) { return error; } - + setColor(*typedValue); return std::nullopt; - } - + if (property == Property::Intensity) { Error error; std::optional> typedValue = convert>(value, error, false, false); if (!typedValue) { return error; } - + setIntensity(*typedValue); return std::nullopt; - } - + if (property == Property::Position) { Error error; - std::optional> typedValue = convert>(value, error, false, false); + std::optional> typedValue = convert>( + value, error, false, false + ); if (!typedValue) { return error; } - + setPosition(*typedValue); return std::nullopt; - } - Error error; std::optional transition = convert(value, error); if (!transition) { return error; } - + if (property == Property::AnchorTransition) { setAnchorTransition(*transition); return std::nullopt; } - + if (property == Property::ColorTransition) { setColorTransition(*transition); return std::nullopt; } - + if (property == Property::IntensityTransition) { setIntensityTransition(*transition); return std::nullopt; } - + if (property == Property::PositionTransition) { setPositionTransition(*transition); return std::nullopt; } - - return Error { "light doesn't support this property" }; + return Error{"light doesn't support this property"}; } StyleProperty Light::getProperty(const std::string& name) const { @@ -284,6 +285,5 @@ TransitionOptions Light::getPositionTransition() const { return impl->properties.template get().options; } - } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/light_impl.cpp b/src/mbgl/style/light_impl.cpp index 619d115f02d..6f21185c104 100644 --- a/src/mbgl/style/light_impl.cpp +++ b/src/mbgl/style/light_impl.cpp @@ -1,7 +1,5 @@ #include namespace mbgl { -namespace style { - -} // namespace style +namespace style {} // namespace style } // namespace mbgl diff --git a/src/mbgl/style/light_impl.hpp b/src/mbgl/style/light_impl.hpp index db75db84ff5..7c066848a40 100644 --- a/src/mbgl/style/light_impl.hpp +++ b/src/mbgl/style/light_impl.hpp @@ -25,28 +25,22 @@ class LightProperty { }; struct LightAnchor : LightProperty { - static LightAnchorType defaultValue() { - return LightAnchorType::Viewport; - } + static LightAnchorType defaultValue() { return LightAnchorType::Viewport; } }; struct LightPosition : LightProperty { static Position defaultValue() { - std::array default_ = { { 1.15f, 210.f, 30.f } }; - return Position{ { default_ } }; + std::array default_ = {{1.15f, 210.f, 30.f}}; + return Position{{default_}}; } }; struct LightColor : LightProperty { - static Color defaultValue() { - return Color::white(); - } + static Color defaultValue() { return Color::white(); } }; struct LightIntensity : LightProperty { - static float defaultValue() { - return 0.5; - } + static float defaultValue() { return 0.5; } }; using LightProperties = Properties; diff --git a/src/mbgl/style/parser.cpp b/src/mbgl/style/parser.cpp index 4dbaaa15256..4b1f045f2b6 100644 --- a/src/mbgl/style/parser.cpp +++ b/src/mbgl/style/parser.cpp @@ -40,14 +40,18 @@ StyleParseResult Parser::parse(const std::string& json) { const JSValue& versionValue = document["version"]; const int version = versionValue.IsNumber() ? versionValue.GetInt() : 0; if (version != 8) { - Log::Warning(Event::ParseStyle, "current renderer implementation only supports style spec version 8; using an outdated style will cause rendering errors"); + Log::Warning( + Event::ParseStyle, + "current renderer implementation only supports style spec version 8; using an outdated style " + "will cause rendering errors" + ); } } if (document.HasMember("name")) { const JSValue& value = document["name"]; if (value.IsString()) { - name = { value.GetString(), value.GetStringLength() }; + name = {value.GetString(), value.GetStringLength()}; } } @@ -102,14 +106,14 @@ StyleParseResult Parser::parse(const std::string& json) { if (document.HasMember("sprite")) { const JSValue& sprite = document["sprite"]; if (sprite.IsString()) { - spriteURL = { sprite.GetString(), sprite.GetStringLength() }; + spriteURL = {sprite.GetString(), sprite.GetStringLength()}; } } if (document.HasMember("glyphs")) { const JSValue& glyphs = document["glyphs"]; if (glyphs.IsString()) { - glyphURL = { glyphs.GetString(), glyphs.GetStringLength() }; + glyphURL = {glyphs.GetString(), glyphs.GetStringLength()}; } } @@ -148,11 +152,12 @@ void Parser::parseSources(const JSValue& value) { } for (const auto& property : value.GetObject()) { - std::string id { property.name.GetString(), property.name.GetStringLength() }; + std::string id{property.name.GetString(), property.name.GetStringLength()}; conversion::Error error; - std::optional> source = - conversion::convert>(property.value, error, id); + std::optional> source = conversion::convert>( + property.value, error, id + ); if (!source) { Log::Warning(Event::ParseStyle, error.message); continue; @@ -187,22 +192,20 @@ void Parser::parseLayers(const JSValue& value) { continue; } - const std::string layerID = { id.GetString(), id.GetStringLength() }; + const std::string layerID = {id.GetString(), id.GetStringLength()}; if (layersMap.find(layerID) != layersMap.end()) { Log::Warning(Event::ParseStyle, "duplicate layer id " + layerID); continue; } - layersMap.emplace(layerID, std::pair> { layerValue, nullptr }); + layersMap.emplace(layerID, std::pair>{layerValue, nullptr}); ids.push_back(layerID); } for (const auto& id : ids) { auto it = layersMap.find(id); - parseLayer(it->first, - it->second.first, - it->second.second); + parseLayer(it->first, it->second.first, it->second.second); } for (const auto& id : ids) { @@ -230,11 +233,11 @@ void Parser::parseLayer(const std::string& id, const JSValue& value, std::unique // This layer is referencing another layer. Recursively parse that layer. const JSValue& refVal = value["ref"]; if (!refVal.IsString()) { - Log::Warning(Event::ParseStyle, "layer ref of '" + id + "' must be a string"); + Log::Warning(Event::ParseStyle, "layer ref of '" + id + "' must be a string"); return; } - const std::string ref { refVal.GetString(), refVal.GetStringLength() }; + const std::string ref{refVal.GetString(), refVal.GetStringLength()}; auto it = layersMap.find(ref); if (it == layersMap.end()) { Log::Warning(Event::ParseStyle, "layer '" + id + "' references unknown layer " + ref); @@ -243,9 +246,7 @@ void Parser::parseLayer(const std::string& id, const JSValue& value, std::unique // Recursively parse the referenced layer. stack.push_front(id); - parseLayer(it->first, - it->second.first, - it->second.second); + parseLayer(it->first, it->second.first, it->second.second); stack.pop_front(); Layer* reference = it->second.second.get(); diff --git a/src/mbgl/style/parser.hpp b/src/mbgl/style/parser.hpp index f25e85fbf7c..ab9d2df7387 100644 --- a/src/mbgl/style/parser.hpp +++ b/src/mbgl/style/parser.hpp @@ -33,7 +33,7 @@ class Parser { std::vector> sources; std::vector> layers; - TransitionOptions transition { { util::DEFAULT_TRANSITION_DURATION } }; + TransitionOptions transition{{util::DEFAULT_TRANSITION_DURATION}}; Light light; std::string name; diff --git a/src/mbgl/style/properties.hpp b/src/mbgl/style/properties.hpp index 7860dd3d9ef..8ef39b44eca 100644 --- a/src/mbgl/style/properties.hpp +++ b/src/mbgl/style/properties.hpp @@ -22,15 +22,14 @@ class Transitioning { Transitioning() = default; explicit Transitioning(Value value_) - : value(std::move(value_)) { - } + : value(std::move(value_)) {} Transitioning(Value value_, Transitioning prior_, const TransitionOptions& transition, TimePoint now) : begin(now + transition.delay.value_or(Duration::zero())), end(begin + transition.duration.value_or(Duration::zero())), value(std::move(value_)) { if (transition.isDefined()) { - prior = { std::move(prior_) }; + prior = {std::move(prior_)}; } } @@ -56,22 +55,19 @@ class Transitioning { } else { // Interpolate between recursively-calculated prior value and final. float t = std::chrono::duration(now - begin) / (end - begin); - return util::interpolate(prior->get().evaluate(evaluator, now), finalValue, - static_cast(util::DEFAULT_TRANSITION_EASE.solve(t, 0.001))); + return util::interpolate( + prior->get().evaluate(evaluator, now), + finalValue, + static_cast(util::DEFAULT_TRANSITION_EASE.solve(t, 0.001)) + ); } } - bool hasTransition() const { - return bool(prior); - } + bool hasTransition() const { return bool(prior); } - bool isUndefined() const { - return value.isUndefined(); - } + bool isUndefined() const { return value.isUndefined(); } - const Value& getValue() const { - return value; - } + const Value& getValue() const { return value; } private: mutable std::optional>> prior; @@ -87,10 +83,7 @@ class Transitionable { TransitionOptions options; Transitioning transition(const TransitionParameters& params, Transitioning prior) const { - return Transitioning(value, - std::move(prior), - options.reverseMerge(params.transition), - params.now); + return Transitioning(value, std::move(prior), options.reverseMerge(params.transition), params.now); } }; @@ -107,11 +100,8 @@ template struct ConstantsMask> { template static unsigned long getMask(const Properties& properties) { - std::bitset result; - util::ignore({ - result.set(TypeIndex::value, - properties.template get().isConstant())... - }); + std::bitset result; + util::ignore({result.set(TypeIndex::value, properties.template get().isConstant())...}); return result.to_ulong(); } }; @@ -132,11 +122,11 @@ class Properties { functions, though it's more of a historical accident than a purposeful optimization. */ - using PropertyTypes = TypeList; - using TransitionableTypes = TypeList; - using UnevaluatedTypes = TypeList; + using PropertyTypes = TypeList; + using TransitionableTypes = TypeList; + using UnevaluatedTypes = TypeList; using PossiblyEvaluatedTypes = TypeList; - using EvaluatedTypes = TypeList; + using EvaluatedTypes = TypeList; using DataDrivenProperties = FilteredTypeList; using OverridableProperties = FilteredTypeList; @@ -148,16 +138,14 @@ class Properties { public: template Evaluated(Us&&... us) - : Tuple(std::forward(us)...) { - } + : Tuple(std::forward(us)...) {} }; class PossiblyEvaluated : public Tuple { public: template PossiblyEvaluated(Us&&... us) - : Tuple(std::forward(us)...) { - } + : Tuple(std::forward(us)...) {} template static T evaluate(float, const GeometryTileFeature&, const T& t, const T&) { @@ -170,59 +158,75 @@ class Properties { } template - static T evaluate(float z, - const GeometryTileFeature& feature, - const PossiblyEvaluatedPropertyValue& v, - const T& defaultValue) { + static T evaluate( + float z, + const GeometryTileFeature& feature, + const PossiblyEvaluatedPropertyValue& v, + const T& defaultValue + ) { return v.match( - [&] (const T& t) { - return t; - }, - [&] (const PropertyExpression& t) { - return t.evaluate(z, feature, defaultValue); - }); + [&](const T& t) { return t; }, + [&](const PropertyExpression& t) { return t.evaluate(z, feature, defaultValue); } + ); } template - static T evaluate(float z, - const GeometryTileFeature& feature, - const PossiblyEvaluatedPropertyValue& v, - const T& defaultValue, - const std::set& availableImages) { + static T evaluate( + float z, + const GeometryTileFeature& feature, + const PossiblyEvaluatedPropertyValue& v, + const T& defaultValue, + const std::set& availableImages + ) { return v.match( [&](const T& t) { return t; }, - [&](const PropertyExpression& t) { return t.evaluate(z, feature, availableImages, defaultValue); }); + [&](const PropertyExpression& t) { return t.evaluate(z, feature, availableImages, defaultValue); } + ); } template - static T evaluate(float z, - const GeometryTileFeature& feature, - const PossiblyEvaluatedPropertyValue& v, - const T& defaultValue, - const std::set& availableImages, - const CanonicalTileID& canonical) { - return v.match([&](const T& t) { return t; }, - [&](const PropertyExpression& t) { - return t.evaluate(z, feature, availableImages, canonical, defaultValue); - }); + static T evaluate( + float z, + const GeometryTileFeature& feature, + const PossiblyEvaluatedPropertyValue& v, + const T& defaultValue, + const std::set& availableImages, + const CanonicalTileID& canonical + ) { + return v.match( + [&](const T& t) { return t; }, + [&](const PropertyExpression& t) { + return t.evaluate(z, feature, availableImages, canonical, defaultValue); + } + ); } template - static T evaluate(float z, - const GeometryTileFeature& feature, - const CanonicalTileID& canonical, - const PossiblyEvaluatedPropertyValue& v, - const T& defaultValue) { + static T evaluate( + float z, + const GeometryTileFeature& feature, + const CanonicalTileID& canonical, + const PossiblyEvaluatedPropertyValue& v, + const T& defaultValue + ) { return v.match( [&](const T& t) { return t; }, - [&](const PropertyExpression& t) { return t.evaluate(z, feature, canonical, defaultValue); }); + [&](const PropertyExpression& t) { return t.evaluate(z, feature, canonical, defaultValue); } + ); } template - static T evaluate(float z, const GeometryTileFeature& feature, const FeatureState& state, - const PossiblyEvaluatedPropertyValue& v, const T& defaultValue) { - return v.match([&](const T& t) { return t; }, - [&](const PropertyExpression& t) { return t.evaluate(z, feature, state, defaultValue); }); + static T evaluate( + float z, + const GeometryTileFeature& feature, + const FeatureState& state, + const PossiblyEvaluatedPropertyValue& v, + const T& defaultValue + ) { + return v.match( + [&](const T& t) { return t; }, + [&](const PropertyExpression& t) { return t.evaluate(z, feature, state, defaultValue); } + ); } template @@ -246,54 +250,48 @@ class Properties { } template - auto evaluate(float z, - const GeometryTileFeature& feature, - const std::set& availableImages, - const CanonicalTileID& canonical) const { + auto evaluate( + float z, + const GeometryTileFeature& feature, + const std::set& availableImages, + const CanonicalTileID& canonical + ) const { return evaluate(z, feature, this->template get

(), P::defaultValue(), availableImages, canonical); } Evaluated evaluate(float z, const GeometryTileFeature& feature) const { - return Evaluated { - evaluate(z, feature)... - }; + return Evaluated{evaluate(z, feature)...}; } - unsigned long constantsMask() const { - return ConstantsMask::getMask(*this); - } + unsigned long constantsMask() const { return ConstantsMask::getMask(*this); } }; class Unevaluated : public Tuple { public: template Unevaluated(Us&&... us) - : Tuple(std::forward(us)...) { - } + : Tuple(std::forward(us)...) {} bool hasTransition() const { bool result = false; - util::ignore({ result |= this->template get().hasTransition()... }); + util::ignore({result |= this->template get().hasTransition()...}); return result; } template auto evaluate(const PropertyEvaluationParameters& parameters) const { using Evaluator = typename P::EvaluatorType; - return this->template get

() - .evaluate(Evaluator(parameters, P::defaultValue()), parameters.now); + return this->template get

().evaluate(Evaluator(parameters, P::defaultValue()), parameters.now); } PossiblyEvaluated evaluate(const PropertyEvaluationParameters& parameters) const { - return PossiblyEvaluated { - evaluate(parameters)... - }; + return PossiblyEvaluated{evaluate(parameters)...}; } template void stringify(Writer& writer) const { writer.StartObject(); - util::ignore({ (conversion::stringify(writer, this->template get()), 0)... }); + util::ignore({(conversion::stringify(writer, this->template get()), 0)...}); writer.EndObject(); } }; @@ -302,25 +300,21 @@ class Properties { public: template Transitionable(Us&&... us) - : Tuple(std::forward(us)...) { - } + : Tuple(std::forward(us)...) {} Unevaluated transitioned(const TransitionParameters& parameters, Unevaluated&& prior) const { - return Unevaluated { - this->template get() - .transition(parameters, std::move(prior.template get()))... - }; + return Unevaluated{this->template get().transition(parameters, std::move(prior.template get()))...}; } Unevaluated untransitioned() const { - return Unevaluated { - typename Ps::UnevaluatedType(this->template get().value)... - }; + return Unevaluated{typename Ps::UnevaluatedType(this->template get().value)...}; } bool hasDataDrivenPropertyDifference(const Transitionable& other) const { bool result = false; - util::ignore({ (result |= this->template get().value.hasDataDrivenPropertyDifference(other.template get().value))... }); + util::ignore({( + result |= this->template get().value.hasDataDrivenPropertyDifference(other.template get().value) + )...}); return result; } }; diff --git a/src/mbgl/style/property_expression.cpp b/src/mbgl/style/property_expression.cpp index 290009514ee..fcbe3236cc3 100644 --- a/src/mbgl/style/property_expression.cpp +++ b/src/mbgl/style/property_expression.cpp @@ -23,18 +23,17 @@ bool PropertyExpressionBase::isRuntimeConstant() const noexcept { return isRuntimeConstant_; } -float PropertyExpressionBase::interpolationFactor(const Range& inputLevels, const float inputValue) const noexcept { +float PropertyExpressionBase::interpolationFactor(const Range& inputLevels, const float inputValue) + const noexcept { return zoomCurve.match( [](std::nullptr_t) { assert(false); return 0.0f; }, [&](const expression::Interpolate* z) { - return z->interpolationFactor(Range { inputLevels.min, inputLevels.max }, inputValue); + return z->interpolationFactor(Range{inputLevels.min, inputLevels.max}, inputValue); }, - [](const expression::Step*) { - return 0.0f; - } + [](const expression::Step*) { return 0.0f; } ); } @@ -44,7 +43,8 @@ Range PropertyExpressionBase::getCoveringStops(const float lower, const f assert(false); return {0.0f, 0.0f}; }, - [&](auto z) { return z->getCoveringStops(lower, upper); }); + [&](auto z) { return z->getCoveringStops(lower, upper); } + ); } const expression::Expression& PropertyExpressionBase::getExpression() const noexcept { diff --git a/src/mbgl/style/rapidjson_conversion.hpp b/src/mbgl/style/rapidjson_conversion.hpp index 2e34376a610..faa956f2a8c 100644 --- a/src/mbgl/style/rapidjson_conversion.hpp +++ b/src/mbgl/style/rapidjson_conversion.hpp @@ -13,27 +13,17 @@ namespace conversion { template <> class ConversionTraits { public: - static bool isUndefined(const JSValue* value) { - return value->IsNull(); - } + static bool isUndefined(const JSValue* value) { return value->IsNull(); } - static bool isArray(const JSValue* value) { - return value->IsArray(); - } + static bool isArray(const JSValue* value) { return value->IsArray(); } - static std::size_t arrayLength(const JSValue* value) { - return value->Size(); - } + static std::size_t arrayLength(const JSValue* value) { return value->Size(); } - static const JSValue* arrayMember(const JSValue* value, std::size_t i) { - return &(*value)[rapidjson::SizeType(i)]; - } + static const JSValue* arrayMember(const JSValue* value, std::size_t i) { return &(*value)[rapidjson::SizeType(i)]; } - static bool isObject(const JSValue* value) { - return value->IsObject(); - } + static bool isObject(const JSValue* value) { return value->IsObject(); } - static std::optional objectMember(const JSValue* value, const char * name) { + static std::optional objectMember(const JSValue* value, const char* name) { if (!value->HasMember(name)) { return {}; } @@ -45,8 +35,9 @@ class ConversionTraits { static std::optional eachMember(const JSValue* value, Fn&& fn) { assert(value->IsObject()); for (const auto& property : value->GetObject()) { - std::optional result = - fn({ property.name.GetString(), property.name.GetStringLength() }, &property.value); + std::optional result = fn( + {property.name.GetString(), property.name.GetStringLength()}, &property.value + ); if (result) { return result; } @@ -79,25 +70,25 @@ class ConversionTraits { if (!value->IsString()) { return {}; } - return {{ value->GetString(), value->GetStringLength() }}; + return {{value->GetString(), value->GetStringLength()}}; } static std::optional toValue(const JSValue* value) { switch (value->GetType()) { case rapidjson::kNullType: case rapidjson::kFalseType: - return { false }; + return {false}; case rapidjson::kTrueType: - return { true }; + return {true}; case rapidjson::kStringType: - return { std::string { value->GetString(), value->GetStringLength() } }; + return {std::string{value->GetString(), value->GetStringLength()}}; case rapidjson::kNumberType: - if (value->IsUint64()) return { value->GetUint64() }; - if (value->IsInt64()) return { value->GetInt64() }; - return { value->GetDouble() }; + if (value->IsUint64()) return {value->GetUint64()}; + if (value->IsInt64()) return {value->GetInt64()}; + return {value->GetDouble()}; default: return {}; @@ -108,18 +99,17 @@ class ConversionTraits { try { return mapbox::geojson::convert(*value); } catch (const std::exception& ex) { - error = { ex.what() }; + error = {ex.what()}; return {}; } } }; -template -std::optional convert(const JSValue& value, Error& error, Args&&...args) { +template +std::optional convert(const JSValue& value, Error& error, Args&&... args) { return convert(Convertible(&value), error, std::forward(args)...); } } // namespace conversion } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/source.cpp b/src/mbgl/style/source.cpp index 1a8efc08b70..0574125a40f 100644 --- a/src/mbgl/style/source.cpp +++ b/src/mbgl/style/source.cpp @@ -10,8 +10,7 @@ static SourceObserver nullObserver; Source::Source(Immutable impl) : baseImpl(std::move(impl)), - observer(&nullObserver) { -} + observer(&nullObserver) {} Source::~Source() = default; diff --git a/src/mbgl/style/source_impl.cpp b/src/mbgl/style/source_impl.cpp index 0407b730cc5..72c95784a25 100644 --- a/src/mbgl/style/source_impl.cpp +++ b/src/mbgl/style/source_impl.cpp @@ -6,18 +6,21 @@ namespace mbgl { namespace style { namespace { -void WarnIfOverscaleFactorCapsPrefetchDelta(const std::optional& overscale, const std::optional& prefetch) { +void WarnIfOverscaleFactorCapsPrefetchDelta( + const std::optional& overscale, const std::optional& prefetch +) { const uint8_t prefetchDelta = std::max(util::DEFAULT_PREFETCH_ZOOM_DELTA, prefetch.value_or(0u)); if (overscale && *overscale < prefetchDelta) { - Log::Warning(Event::Style, "Parent tile overscale factor will cap prefetch delta to " + std::to_string(int(*overscale))); + Log::Warning( + Event::Style, "Parent tile overscale factor will cap prefetch delta to " + std::to_string(int(*overscale)) + ); } } } // namespace Source::Impl::Impl(SourceType type_, std::string id_) : type(type_), - id(std::move(id_)) { -} + id(std::move(id_)) {} void Source::Impl::setPrefetchZoomDelta(std::optional delta) noexcept { prefetchZoomDelta = std::move(delta); diff --git a/src/mbgl/style/sources/custom_geometry_source.cpp b/src/mbgl/style/sources/custom_geometry_source.cpp index 9d3a58c1511..325b720b14c 100644 --- a/src/mbgl/style/sources/custom_geometry_source.cpp +++ b/src/mbgl/style/sources/custom_geometry_source.cpp @@ -17,7 +17,8 @@ namespace style { CustomGeometrySource::CustomGeometrySource(std::string id, const CustomGeometrySource::Options& options) : Source(makeMutable(std::move(id), options)), loader(std::make_unique>( - Scheduler::GetBackground(), options.fetchTileFunction, options.cancelTileFunction)) {} + Scheduler::GetBackground(), options.fetchTileFunction, options.cancelTileFunction + )) {} CustomGeometrySource::~CustomGeometrySource() = default; @@ -35,8 +36,7 @@ bool CustomGeometrySource::supportsLayerType(const mbgl::style::LayerTypeInfo* i return mbgl::underlying_type(Tile::Kind::Geometry) == mbgl::underlying_type(info->tileKind); } -void CustomGeometrySource::setTileData(const CanonicalTileID& tileID, - const GeoJSON& data) { +void CustomGeometrySource::setTileData(const CanonicalTileID& tileID, const GeoJSON& data) { loader->self().invoke(&CustomTileLoader::setTileData, tileID, data); } diff --git a/src/mbgl/style/sources/custom_geometry_source_impl.cpp b/src/mbgl/style/sources/custom_geometry_source_impl.cpp index fbaa2521743..026e14540ea 100644 --- a/src/mbgl/style/sources/custom_geometry_source_impl.cpp +++ b/src/mbgl/style/sources/custom_geometry_source_impl.cpp @@ -11,7 +11,10 @@ CustomGeometrySource::Impl::Impl(std::string id_, const CustomGeometrySource::Op loaderRef({}) {} CustomGeometrySource::Impl::Impl(const Impl& impl, const ActorRef& loaderRef_) - : Source::Impl(impl), tileOptions(impl.tileOptions), zoomRange(impl.zoomRange), loaderRef(loaderRef_) {} + : Source::Impl(impl), + tileOptions(impl.tileOptions), + zoomRange(impl.zoomRange), + loaderRef(loaderRef_) {} bool CustomGeometrySource::Impl::operator!=(const Impl& other) const noexcept { return tileOptions != other.tileOptions || zoomRange != other.zoomRange || bool(loaderRef) != bool(other.loaderRef); diff --git a/src/mbgl/style/sources/geojson_source.cpp b/src/mbgl/style/sources/geojson_source.cpp index 86c504f940a..bd6fa7c80c2 100644 --- a/src/mbgl/style/sources/geojson_source.cpp +++ b/src/mbgl/style/sources/geojson_source.cpp @@ -20,7 +20,8 @@ Immutable GeoJSONOptions::defaultOptions() { } GeoJSONSource::GeoJSONSource(std::string id, Immutable options) - : Source(makeMutable(std::move(id), std::move(options))), threadPool(Scheduler::GetBackground()) {} + : Source(makeMutable(std::move(id), std::move(options))), + threadPool(Scheduler::GetBackground()) {} GeoJSONSource::~GeoJSONSource() = default; @@ -41,8 +42,9 @@ void GeoJSONSource::setURL(const std::string& url_) { namespace { -inline std::shared_ptr createGeoJSONData(const mapbox::geojson::geojson& geoJSON, - const GeoJSONSource::Impl& impl) { +inline std::shared_ptr createGeoJSONData( + const mapbox::geojson::geojson& geoJSON, const GeoJSONSource::Impl& impl +) { if (auto data = impl.getData().lock()) { return GeoJSONData::create(geoJSON, impl.getOptions(), data->getScheduler()); } @@ -81,13 +83,11 @@ void GeoJSONSource::loadDescription(FileSource& fileSource) { req = fileSource.request(Resource::source(*url), [this](const Response& res) { if (res.error) { - observer->onSourceError( - *this, std::make_exception_ptr(std::runtime_error(res.error->message))); + observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error(res.error->message))); } else if (res.notModified) { return; } else if (res.noContent) { - observer->onSourceError( - *this, std::make_exception_ptr(std::runtime_error("unexpectedly empty GeoJSON"))); + observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error("unexpectedly empty GeoJSON"))); } else { auto makeImplInBackground = [currentImpl = baseImpl, data = res.data]() -> Immutable { assert(data); diff --git a/src/mbgl/style/sources/geojson_source_impl.cpp b/src/mbgl/style/sources/geojson_source_impl.cpp index 42f273c02ce..769b4eea71f 100644 --- a/src/mbgl/style/sources/geojson_source_impl.cpp +++ b/src/mbgl/style/sources/geojson_source_impl.cpp @@ -26,24 +26,24 @@ class GeoJSONVTData final : public GeoJSONData { void getTile(const CanonicalTileID& id, const std::function& fn) final { assert(fn); scheduler->scheduleAndReplyValue( - [id, impl = this->impl]() -> TileFeatures { return impl->getTile(id.z, id.x, id.y).features; }, fn); + [id, impl = this->impl]() -> TileFeatures { return impl->getTile(id.z, id.x, id.y).features; }, fn + ); } Features getChildren(const std::uint32_t) final { return {}; } Features getLeaves(const std::uint32_t, const std::uint32_t, const std::uint32_t) final { return {}; } - std::uint8_t getClusterExpansionZoom(std::uint32_t) final { - return 0; - } + std::uint8_t getClusterExpansionZoom(std::uint32_t) final { return 0; } std::shared_ptr getScheduler() final { return scheduler; } friend GeoJSONData; - GeoJSONVTData(const GeoJSON& geoJSON, - const mapbox::geojsonvt::Options& options, - std::shared_ptr scheduler_) - : impl(std::make_shared(geoJSON, options)), scheduler(std::move(scheduler_)) { + GeoJSONVTData( + const GeoJSON& geoJSON, const mapbox::geojsonvt::Options& options, std::shared_ptr scheduler_ + ) + : impl(std::make_shared(geoJSON, options)), + scheduler(std::move(scheduler_)) { assert(scheduler); } @@ -74,9 +74,11 @@ class SuperclusterData final : public GeoJSONData { }; template -T evaluateFeature(const mapbox::feature::feature& f, - const std::shared_ptr& expression, - std::optional accumulated = std::nullopt) { +T evaluateFeature( + const mapbox::feature::feature& f, + const std::shared_ptr& expression, + std::optional accumulated = std::nullopt +) { const expression::EvaluationResult result = expression->evaluate(accumulated, f); if (result) { std::optional typed = expression::fromExpressionValue(*result); @@ -88,9 +90,9 @@ T evaluateFeature(const mapbox::feature::feature& f, } // static -std::shared_ptr GeoJSONData::create(const GeoJSON& geoJSON, - const Immutable& options, - std::shared_ptr scheduler) { +std::shared_ptr GeoJSONData::create( + const GeoJSON& geoJSON, const Immutable& options, std::shared_ptr scheduler +) { constexpr double scale = util::EXTENT / util::tileSize_D; if (options->cluster && geoJSON.is() && !geoJSON.get().empty()) { mapbox::supercluster::Options clusterOptions; @@ -131,10 +133,13 @@ std::shared_ptr GeoJSONData::create(const GeoJSON& geoJSON, } GeoJSONSource::Impl::Impl(std::string id_, Immutable options_) - : Source::Impl(SourceType::GeoJSON, std::move(id_)), options(std::move(options_)) {} + : Source::Impl(SourceType::GeoJSON, std::move(id_)), + options(std::move(options_)) {} GeoJSONSource::Impl::Impl(const GeoJSONSource::Impl& other, std::shared_ptr data_) - : Source::Impl(other), options(other.options), data(std::move(data_)) {} + : Source::Impl(other), + options(other.options), + data(std::move(data_)) {} GeoJSONSource::Impl::~Impl() = default; diff --git a/src/mbgl/style/sources/image_source.cpp b/src/mbgl/style/sources/image_source.cpp index dd64d155c2d..3f0aa43951a 100644 --- a/src/mbgl/style/sources/image_source.cpp +++ b/src/mbgl/style/sources/image_source.cpp @@ -12,8 +12,7 @@ namespace mbgl { namespace style { ImageSource::ImageSource(std::string id, const std::array coords_) - : Source(makeMutable(std::move(id), coords_)) { -} + : Source(makeMutable(std::move(id), coords_)) {} ImageSource::~ImageSource() = default; @@ -59,10 +58,10 @@ void ImageSource::loadDescription(FileSource& fileSource) { loaded = true; } - if (req || loaded) { + if (req || loaded) { return; } - const Resource imageResource { Resource::Image, *url, {} }; + const Resource imageResource{Resource::Image, *url, {}}; req = fileSource.request(imageResource, [this](const Response& res) { if (res.error) { diff --git a/src/mbgl/style/sources/image_source_impl.cpp b/src/mbgl/style/sources/image_source_impl.cpp index 176bbd70a98..1031a3c1d81 100644 --- a/src/mbgl/style/sources/image_source_impl.cpp +++ b/src/mbgl/style/sources/image_source_impl.cpp @@ -4,16 +4,18 @@ namespace mbgl { namespace style { ImageSource::Impl::Impl(std::string id_, std::array coords_) - : Source::Impl(SourceType::Image, std::move(id_)), coords(coords_) {} + : Source::Impl(SourceType::Image, std::move(id_)), + coords(coords_) {} ImageSource::Impl::Impl(const Impl& other, std::array coords_) - : Source::Impl(other), coords(coords_), image(other.image) {} + : Source::Impl(other), + coords(coords_), + image(other.image) {} ImageSource::Impl::Impl(const Impl& rhs, PremultipliedImage&& image_) : Source::Impl(rhs), - coords(rhs.coords), - image(std::make_shared(std::move(image_))) { -} + coords(rhs.coords), + image(std::make_shared(std::move(image_))) {} ImageSource::Impl::~Impl() = default; diff --git a/src/mbgl/style/sources/image_source_impl.hpp b/src/mbgl/style/sources/image_source_impl.hpp index 4bf1472ca1e..bf55be6fcd3 100644 --- a/src/mbgl/style/sources/image_source_impl.hpp +++ b/src/mbgl/style/sources/image_source_impl.hpp @@ -23,6 +23,7 @@ class ImageSource::Impl final : public Source::Impl { std::array getCoordinates() const; std::optional getAttribution() const final; + private: std::array coords; std::shared_ptr image; diff --git a/src/mbgl/style/sources/raster_source.cpp b/src/mbgl/style/sources/raster_source.cpp index 415e5152b65..9e1fffbeb19 100644 --- a/src/mbgl/style/sources/raster_source.cpp +++ b/src/mbgl/style/sources/raster_source.cpp @@ -13,10 +13,11 @@ namespace mbgl { namespace style { -RasterSource::RasterSource(std::string id, variant urlOrTileset_, uint16_t tileSize, SourceType sourceType) +RasterSource::RasterSource( + std::string id, variant urlOrTileset_, uint16_t tileSize, SourceType sourceType +) : Source(makeMutable(sourceType, std::move(id), tileSize)), - urlOrTileset(std::move(urlOrTileset_)) { -} + urlOrTileset(std::move(urlOrTileset_)) {} RasterSource::~RasterSource() = default; @@ -54,7 +55,7 @@ void RasterSource::loadDescription(FileSource& fileSource) { const auto& rawURL = urlOrTileset.get(); const auto& url = util::mapbox::canonicalizeSourceURL(fileSource.getResourceOptions().tileServerOptions(), rawURL); - + req = fileSource.request(Resource::source(url), [this, url, &fileSource](const Response& res) { if (res.error) { observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error(res.error->message))); diff --git a/src/mbgl/style/sources/raster_source_impl.cpp b/src/mbgl/style/sources/raster_source_impl.cpp index 62fa71710d0..6836507925f 100644 --- a/src/mbgl/style/sources/raster_source_impl.cpp +++ b/src/mbgl/style/sources/raster_source_impl.cpp @@ -5,14 +5,12 @@ namespace style { RasterSource::Impl::Impl(SourceType sourceType, std::string id_, uint16_t tileSize_) : Source::Impl(sourceType, std::move(id_)), - tileSize(tileSize_) { -} + tileSize(tileSize_) {} RasterSource::Impl::Impl(const Impl& other, Tileset tileset_) : Source::Impl(other), tileset(std::move(tileset_)), - tileSize(other.tileSize) { -} + tileSize(other.tileSize) {} uint16_t RasterSource::Impl::getTileSize() const { return tileSize; diff --git a/src/mbgl/style/sources/vector_source.cpp b/src/mbgl/style/sources/vector_source.cpp index 35b656c5b8a..4b3c8134207 100644 --- a/src/mbgl/style/sources/vector_source.cpp +++ b/src/mbgl/style/sources/vector_source.cpp @@ -14,8 +14,12 @@ namespace mbgl { namespace style { -VectorSource::VectorSource(std::string id, variant urlOrTileset_, std::optional maxZoom_, - std::optional minZoom_) +VectorSource::VectorSource( + std::string id, + variant urlOrTileset_, + std::optional maxZoom_, + std::optional minZoom_ +) : Source(makeMutable(std::move(id))), urlOrTileset(std::move(urlOrTileset_)), maxZoom(std::move(maxZoom_)), @@ -53,7 +57,7 @@ void VectorSource::loadDescription(FileSource& fileSource) { const auto& rawURL = urlOrTileset.get(); const auto& url = util::mapbox::canonicalizeSourceURL(fileSource.getResourceOptions().tileServerOptions(), rawURL); - + req = fileSource.request(Resource::source(url), [this, url, &fileSource](const Response& res) { if (res.error) { observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error(res.error->message))); diff --git a/src/mbgl/style/sources/vector_source_impl.cpp b/src/mbgl/style/sources/vector_source_impl.cpp index c46dab20696..3f202d0e14a 100644 --- a/src/mbgl/style/sources/vector_source_impl.cpp +++ b/src/mbgl/style/sources/vector_source_impl.cpp @@ -4,13 +4,11 @@ namespace mbgl { namespace style { VectorSource::Impl::Impl(std::string id_) - : Source::Impl(SourceType::Vector, std::move(id_)) { -} + : Source::Impl(SourceType::Vector, std::move(id_)) {} VectorSource::Impl::Impl(const Impl& other, Tileset tileset_) : Source::Impl(other), - tileset(std::move(tileset_)) { -} + tileset(std::move(tileset_)) {} std::optional VectorSource::Impl::getAttribution() const { if (!tileset) { diff --git a/src/mbgl/style/style_impl.cpp b/src/mbgl/style/style_impl.cpp index 8bba8220c44..87cb2a115b5 100644 --- a/src/mbgl/style/style_impl.cpp +++ b/src/mbgl/style/style_impl.cpp @@ -52,7 +52,8 @@ void Style::Impl::loadJSON(const std::string& json_) { void Style::Impl::loadURL(const std::string& url_) { if (!fileSource) { observer->onStyleError( - std::make_exception_ptr(util::StyleLoadException("Unable to find resource provider for style url."))); + std::make_exception_ptr(util::StyleLoadException("Unable to find resource provider for style url.")) + ); return; } @@ -161,7 +162,7 @@ void Style::Impl::addSource(std::unique_ptr source) { std::unique_ptr Style::Impl::removeSource(const std::string& id) { // Check if source is in use - for (const auto& layer: layers) { + for (const auto& layer : layers) { if (layer->getSourceID() == id) { Log::Warning(Event::General, "Source '" + id + "' is in use, cannot remove"); return nullptr; @@ -264,7 +265,7 @@ bool Style::Impl::isLoaded() const { return false; } - for (const auto& source: sources) { + for (const auto& source : sources) { if (!source->loaded) { return false; } @@ -291,8 +292,9 @@ void Style::Impl::addImage(std::unique_ptr image) { void Style::Impl::removeImage(const std::string& id) { auto newImages = makeMutable(*images); - auto found = - std::find_if(newImages->begin(), newImages->end(), [&id](const auto& image) { return image->id == id; }); + auto found = std::find_if(newImages->begin(), newImages->end(), [&id](const auto& image) { + return image->id == id; + }); if (found == newImages->end()) { Log::Warning(Event::General, "Image '" + id + "' is not present in style, cannot remove"); return; @@ -355,7 +357,8 @@ void Style::Impl::onSpriteLoaded(std::vector> imag } newImages->insert( - newImages->end(), std::make_move_iterator(images_.begin()), std::make_move_iterator(images_.end())); + newImages->end(), std::make_move_iterator(images_.begin()), std::make_move_iterator(images_.end()) + ); std::sort(newImages->begin(), newImages->end()); images = std::move(newImages); spriteLoaded = true; diff --git a/src/mbgl/style/style_impl.hpp b/src/mbgl/style/style_impl.hpp index 69e82f530be..ed943e24054 100644 --- a/src/mbgl/style/style_impl.hpp +++ b/src/mbgl/style/style_impl.hpp @@ -49,18 +49,16 @@ class Style::Impl : public SpriteLoaderObserver, bool isLoaded() const; - std::exception_ptr getLastError() const { - return lastError; - } + std::exception_ptr getLastError() const { return lastError; } - std::vector< Source*> getSources(); + std::vector getSources(); std::vector getSources() const; Source* getSource(const std::string& id) const; void addSource(std::unique_ptr); std::unique_ptr removeSource(const std::string& sourceID); - std::vector< Layer*> getLayers(); + std::vector getLayers(); std::vector getLayers() const; Layer* getLayer(const std::string& id) const; diff --git a/src/mbgl/style/types.cpp b/src/mbgl/style/types.cpp index c4a7b76b664..8dc994e27b9 100644 --- a/src/mbgl/style/types.cpp +++ b/src/mbgl/style/types.cpp @@ -5,118 +5,156 @@ namespace mbgl { using namespace style; -MBGL_DEFINE_ENUM(SourceType, { - { SourceType::Vector, "vector" }, - { SourceType::Raster, "raster" }, - { SourceType::GeoJSON, "geojson" }, - { SourceType::Video, "video" }, - { SourceType::Annotations, "annotations" }, - { SourceType::Image, "image" }, - { SourceType::CustomVector, "customvector" } -}); - -MBGL_DEFINE_ENUM(VisibilityType, { - { VisibilityType::Visible, "visible" }, - { VisibilityType::None, "none" }, -}); - -MBGL_DEFINE_ENUM(TranslateAnchorType, { - { TranslateAnchorType::Map, "map" }, - { TranslateAnchorType::Viewport, "viewport" }, -}); - -MBGL_DEFINE_ENUM(RasterResamplingType, { - { RasterResamplingType::Linear, "linear" }, - { RasterResamplingType::Nearest, "nearest" }, -}); - -MBGL_DEFINE_ENUM(HillshadeIlluminationAnchorType, { - { HillshadeIlluminationAnchorType::Map, "map" }, - { HillshadeIlluminationAnchorType::Viewport, "viewport" }, -}); - -MBGL_DEFINE_ENUM(RotateAnchorType, { - { RotateAnchorType::Map, "map" }, - { RotateAnchorType::Viewport, "viewport" }, -}); - -MBGL_DEFINE_ENUM(CirclePitchScaleType, { - { CirclePitchScaleType::Map, "map" }, - { CirclePitchScaleType::Viewport, "viewport" }, -}); - -MBGL_DEFINE_ENUM(LineCapType, { - { LineCapType::Round, "round" }, - { LineCapType::Butt, "butt" }, - { LineCapType::Square, "square" }, -}); - -MBGL_DEFINE_ENUM(LineJoinType, { - { LineJoinType::Miter, "miter" }, - { LineJoinType::Bevel, "bevel" }, - { LineJoinType::Round, "round" }, - { LineJoinType::FakeRound, "fakeround" }, - { LineJoinType::FlipBevel, "flipbevel" }, -}); - -MBGL_DEFINE_ENUM(SymbolPlacementType, { - { SymbolPlacementType::Point, "point" }, - { SymbolPlacementType::Line, "line" }, - { SymbolPlacementType::LineCenter, "line-center" }, -}); - -MBGL_DEFINE_ENUM(SymbolAnchorType, { - { SymbolAnchorType::Center, "center" }, - { SymbolAnchorType::Left, "left" }, - { SymbolAnchorType::Right, "right" }, - { SymbolAnchorType::Top, "top" }, - { SymbolAnchorType::Bottom, "bottom" }, - { SymbolAnchorType::TopLeft, "top-left" }, - { SymbolAnchorType::TopRight, "top-right" }, - { SymbolAnchorType::BottomLeft, "bottom-left" }, - { SymbolAnchorType::BottomRight, "bottom-right" } -}); - -MBGL_DEFINE_ENUM(SymbolZOrderType, { - { SymbolZOrderType::Auto, "auto" }, - { SymbolZOrderType::ViewportY, "viewport-y" }, - { SymbolZOrderType::Source, "source" } -}); - -MBGL_DEFINE_ENUM(TextJustifyType, { - { TextJustifyType::Auto, "auto" }, - { TextJustifyType::Center, "center" }, - { TextJustifyType::Left, "left" }, - { TextJustifyType::Right, "right" }, -}); - -MBGL_DEFINE_ENUM(TextTransformType, { - { TextTransformType::None, "none" }, - { TextTransformType::Uppercase, "uppercase" }, - { TextTransformType::Lowercase, "lowercase" }, -}); - -MBGL_DEFINE_ENUM(TextWritingModeType, { - { TextWritingModeType::Horizontal, "horizontal" }, - { TextWritingModeType::Vertical, "vertical" } -}); - -MBGL_DEFINE_ENUM(AlignmentType, { - { AlignmentType::Map, "map" }, - { AlignmentType::Viewport, "viewport" }, - { AlignmentType::Auto, "auto" }, -}); - -MBGL_DEFINE_ENUM(IconTextFitType, { - { IconTextFitType::None, "none" }, - { IconTextFitType::Both, "both" }, - { IconTextFitType::Width, "width" }, - { IconTextFitType::Height, "height" }, -}); - -MBGL_DEFINE_ENUM(LightAnchorType, { - { LightAnchorType::Map, "map" }, - { LightAnchorType::Viewport, "viewport" } -}); +MBGL_DEFINE_ENUM( + SourceType, + {{SourceType::Vector, "vector"}, + {SourceType::Raster, "raster"}, + {SourceType::GeoJSON, "geojson"}, + {SourceType::Video, "video"}, + {SourceType::Annotations, "annotations"}, + {SourceType::Image, "image"}, + {SourceType::CustomVector, "customvector"}} +); + +MBGL_DEFINE_ENUM( + VisibilityType, + { + {VisibilityType::Visible, "visible"}, + {VisibilityType::None, "none"}, + } +); + +MBGL_DEFINE_ENUM( + TranslateAnchorType, + { + {TranslateAnchorType::Map, "map"}, + {TranslateAnchorType::Viewport, "viewport"}, + } +); + +MBGL_DEFINE_ENUM( + RasterResamplingType, + { + {RasterResamplingType::Linear, "linear"}, + {RasterResamplingType::Nearest, "nearest"}, + } +); + +MBGL_DEFINE_ENUM( + HillshadeIlluminationAnchorType, + { + {HillshadeIlluminationAnchorType::Map, "map"}, + {HillshadeIlluminationAnchorType::Viewport, "viewport"}, + } +); + +MBGL_DEFINE_ENUM( + RotateAnchorType, + { + {RotateAnchorType::Map, "map"}, + {RotateAnchorType::Viewport, "viewport"}, + } +); + +MBGL_DEFINE_ENUM( + CirclePitchScaleType, + { + {CirclePitchScaleType::Map, "map"}, + {CirclePitchScaleType::Viewport, "viewport"}, + } +); + +MBGL_DEFINE_ENUM( + LineCapType, + { + {LineCapType::Round, "round"}, + {LineCapType::Butt, "butt"}, + {LineCapType::Square, "square"}, + } +); + +MBGL_DEFINE_ENUM( + LineJoinType, + { + {LineJoinType::Miter, "miter"}, + {LineJoinType::Bevel, "bevel"}, + {LineJoinType::Round, "round"}, + {LineJoinType::FakeRound, "fakeround"}, + {LineJoinType::FlipBevel, "flipbevel"}, + } +); + +MBGL_DEFINE_ENUM( + SymbolPlacementType, + { + {SymbolPlacementType::Point, "point"}, + {SymbolPlacementType::Line, "line"}, + {SymbolPlacementType::LineCenter, "line-center"}, + } +); + +MBGL_DEFINE_ENUM( + SymbolAnchorType, + {{SymbolAnchorType::Center, "center"}, + {SymbolAnchorType::Left, "left"}, + {SymbolAnchorType::Right, "right"}, + {SymbolAnchorType::Top, "top"}, + {SymbolAnchorType::Bottom, "bottom"}, + {SymbolAnchorType::TopLeft, "top-left"}, + {SymbolAnchorType::TopRight, "top-right"}, + {SymbolAnchorType::BottomLeft, "bottom-left"}, + {SymbolAnchorType::BottomRight, "bottom-right"}} +); + +MBGL_DEFINE_ENUM( + SymbolZOrderType, + {{SymbolZOrderType::Auto, "auto"}, + {SymbolZOrderType::ViewportY, "viewport-y"}, + {SymbolZOrderType::Source, "source"}} +); + +MBGL_DEFINE_ENUM( + TextJustifyType, + { + {TextJustifyType::Auto, "auto"}, + {TextJustifyType::Center, "center"}, + {TextJustifyType::Left, "left"}, + {TextJustifyType::Right, "right"}, + } +); + +MBGL_DEFINE_ENUM( + TextTransformType, + { + {TextTransformType::None, "none"}, + {TextTransformType::Uppercase, "uppercase"}, + {TextTransformType::Lowercase, "lowercase"}, + } +); + +MBGL_DEFINE_ENUM( + TextWritingModeType, {{TextWritingModeType::Horizontal, "horizontal"}, {TextWritingModeType::Vertical, "vertical"}} +); + +MBGL_DEFINE_ENUM( + AlignmentType, + { + {AlignmentType::Map, "map"}, + {AlignmentType::Viewport, "viewport"}, + {AlignmentType::Auto, "auto"}, + } +); + +MBGL_DEFINE_ENUM( + IconTextFitType, + { + {IconTextFitType::None, "none"}, + {IconTextFitType::Both, "both"}, + {IconTextFitType::Width, "width"}, + {IconTextFitType::Height, "height"}, + } +); + +MBGL_DEFINE_ENUM(LightAnchorType, {{LightAnchorType::Map, "map"}, {LightAnchorType::Viewport, "viewport"}}); } // namespace mbgl diff --git a/src/mbgl/text/bidi.hpp b/src/mbgl/text/bidi.hpp index 5ce2887db86..1f03ab91d56 100644 --- a/src/mbgl/text/bidi.hpp +++ b/src/mbgl/text/bidi.hpp @@ -19,7 +19,7 @@ std::u16string applyArabicShaping(const std::u16string&); // The data structure is intended to accomodate the reordering/interleaving // of formatting that can happen when BiDi rearranges inputs using StyledText = std::pair>; - + class BiDi : private util::noncopyable { public: BiDi(); diff --git a/src/mbgl/text/check_max_angle.cpp b/src/mbgl/text/check_max_angle.cpp index 75267d4e98c..74a3061dee4 100644 --- a/src/mbgl/text/check_max_angle.cpp +++ b/src/mbgl/text/check_max_angle.cpp @@ -4,25 +4,28 @@ #include -namespace mbgl{ +namespace mbgl { struct Corner { - Corner(float _distance, float _angleDelta) : - distance(_distance), angleDelta(_angleDelta) {} + Corner(float _distance, float _angleDelta) + : distance(_distance), + angleDelta(_angleDelta) {} float distance; float angleDelta; }; -bool checkMaxAngle(const GeometryCoordinates& line, - const Anchor& anchor, - const float labelLength, - const float windowSize, - const float maxAngle) { +bool checkMaxAngle( + const GeometryCoordinates& line, + const Anchor& anchor, + const float labelLength, + const float windowSize, + const float maxAngle +) { // horizontal labels always pass if (!anchor.segment) return true; GeometryCoordinate anchorPoint = convertPoint(anchor.point); - GeometryCoordinate &p = anchorPoint; + GeometryCoordinate& p = anchorPoint; std::size_t index = *anchor.segment + 1; float anchorDistance = 0; @@ -43,9 +46,8 @@ bool checkMaxAngle(const GeometryCoordinates& line, std::queue recentCorners; float recentAngleDelta = 0; - // move forwards by the length of the label and check angles along the way + // move forwards by the length of the label and check angles along the way while (anchorDistance < labelLength / 2) { - // there isn't enough room for the label before the end of the line if (index + 1 >= line.size()) return false; @@ -58,7 +60,7 @@ bool checkMaxAngle(const GeometryCoordinates& line, angleDelta = std::fabs(std::fmod(angleDelta + 3 * M_PI, M_PI * 2) - M_PI); recentCorners.emplace(anchorDistance, static_cast(angleDelta)); - recentAngleDelta += static_cast(angleDelta); + recentAngleDelta += static_cast(angleDelta); // remove corners that are far enough away from the list of recent anchors while (anchorDistance - recentCorners.front().distance > windowSize) { diff --git a/src/mbgl/text/check_max_angle.hpp b/src/mbgl/text/check_max_angle.hpp index d08d8f0cce4..99dffe065d5 100644 --- a/src/mbgl/text/check_max_angle.hpp +++ b/src/mbgl/text/check_max_angle.hpp @@ -7,6 +7,7 @@ namespace mbgl { class Anchor; bool checkMaxAngle( - const GeometryCoordinates& line, const Anchor& anchor, float labelLength, float windowSize, float maxAngle); + const GeometryCoordinates& line, const Anchor& anchor, float labelLength, float windowSize, float maxAngle +); } // namespace mbgl diff --git a/src/mbgl/text/collision_feature.cpp b/src/mbgl/text/collision_feature.cpp index f5201596e3f..dca0dc819ea 100644 --- a/src/mbgl/text/collision_feature.cpp +++ b/src/mbgl/text/collision_feature.cpp @@ -5,20 +5,23 @@ namespace mbgl { -CollisionFeature::CollisionFeature(const GeometryCoordinates& line, - const Anchor& anchor, - const float top, - const float bottom, - const float left, - const float right, - const std::optional& collisionPadding, - const float boxScale, - const float padding, - const style::SymbolPlacementType placement, - IndexedSubfeature indexedFeature_, - const float overscaling, - const float rotate) - : indexedFeature(std::move(indexedFeature_)), alongLine(placement != style::SymbolPlacementType::Point) { +CollisionFeature::CollisionFeature( + const GeometryCoordinates& line, + const Anchor& anchor, + const float top, + const float bottom, + const float left, + const float right, + const std::optional& collisionPadding, + const float boxScale, + const float padding, + const style::SymbolPlacementType placement, + IndexedSubfeature indexedFeature_, + const float overscaling, + const float rotate +) + : indexedFeature(std::move(indexedFeature_)), + alongLine(placement != style::SymbolPlacementType::Point) { if (top == 0 && bottom == 0 && left == 0 && right == 0) return; float y1 = top * boxScale - padding; @@ -53,7 +56,7 @@ CollisionFeature::CollisionFeature(const GeometryCoordinates& line, const Point tr = util::rotate(Point(x2, y1), rotateRadians); const Point bl = util::rotate(Point(x1, y2), rotateRadians); const Point br = util::rotate(Point(x2, y2), rotateRadians); - + // Collision features require an "on-axis" geometry, // so take the envelope of the rotated geometry // (may be quite large for wide labels rotated 45 degrees) @@ -61,7 +64,7 @@ CollisionFeature::CollisionFeature(const GeometryCoordinates& line, const float xMax = std::max({tl.x, tr.x, bl.x, br.x}); const float yMin = std::min({tl.y, tr.y, bl.y, br.y}); const float yMax = std::max({tl.y, tr.y, bl.y, br.y}); - + boxes.emplace_back(anchor.point, xMin, yMin, xMax, yMax); } else { boxes.emplace_back(anchor.point, x1, y1, x2, y2); @@ -69,12 +72,14 @@ CollisionFeature::CollisionFeature(const GeometryCoordinates& line, } } -void CollisionFeature::bboxifyLabel(const GeometryCoordinates& line, - GeometryCoordinate& anchorPoint, - std::size_t segment, - const float labelLength, - const float boxSize, - const float overscaling) { +void CollisionFeature::bboxifyLabel( + const GeometryCoordinates& line, + GeometryCoordinate& anchorPoint, + std::size_t segment, + const float labelLength, + const float boxSize, + const float overscaling +) { const float step = boxSize / 2; const int nBoxes = std::max(static_cast(std::floor(labelLength / step)), 1); @@ -93,7 +98,7 @@ void CollisionFeature::bboxifyLabel(const GeometryCoordinates& line, // box is at the edge of the label. const float firstBoxOffset = -boxSize / 2; - GeometryCoordinate &p = anchorPoint; + GeometryCoordinate& p = anchorPoint; std::size_t index = segment + 1; float anchorDistance = firstBoxOffset; const float labelStartDistance = -labelLength / 2; @@ -126,9 +131,9 @@ void CollisionFeature::bboxifyLabel(const GeometryCoordinates& line, const float boxOffset = i * step; float boxDistanceToAnchor = labelStartDistance + boxOffset; - // make the distance between pitch padding boxes bigger - if (boxOffset < 0) boxDistanceToAnchor += boxOffset; - if (boxOffset > labelLength) boxDistanceToAnchor += boxOffset - labelLength; + // make the distance between pitch padding boxes bigger + if (boxOffset < 0) boxDistanceToAnchor += boxOffset; + if (boxOffset > labelLength) boxDistanceToAnchor += boxOffset - labelLength; if (boxDistanceToAnchor < anchorDistance) { // The line doesn't extend far enough back for this box, skip it @@ -155,16 +160,15 @@ void CollisionFeature::bboxifyLabel(const GeometryCoordinates& line, Point boxAnchor = { p0.x + segmentBoxDistance / segmentLength * (p1.x - p0.x), - p0.y + segmentBoxDistance / segmentLength * (p1.y - p0.y) - }; - + p0.y + segmentBoxDistance / segmentLength * (p1.y - p0.y)}; + // If the box is within boxSize of the anchor, force the box to be used // (so even 0-width labels use at least one box) // Otherwise, the .8 multiplication gives us a little bit of conservative // padding in choosing which boxes to use (see CollisionIndex#placedCollisionCircles) - const float paddedAnchorDistance = std::abs(boxDistanceToAnchor - firstBoxOffset) < step ? - 0.0f : - (boxDistanceToAnchor - firstBoxOffset) * 0.8f; + const float paddedAnchorDistance = std::abs(boxDistanceToAnchor - firstBoxOffset) < step + ? 0.0f + : (boxDistanceToAnchor - firstBoxOffset) * 0.8f; boxes.emplace_back(boxAnchor, -boxSize / 2, -boxSize / 2, boxSize / 2, boxSize / 2, paddedAnchorDistance); } diff --git a/src/mbgl/text/collision_feature.hpp b/src/mbgl/text/collision_feature.hpp index 9fe6fa97755..0ae6c7d1afd 100644 --- a/src/mbgl/text/collision_feature.hpp +++ b/src/mbgl/text/collision_feature.hpp @@ -18,8 +18,12 @@ class ProjectedCollisionBox { }; ProjectedCollisionBox() = default; - ProjectedCollisionBox(float x1, float y1, float x2, float y2) : geometry(x1, y1, x2, y2), type(Type::Box) {} - ProjectedCollisionBox(float x, float y, float r) : geometry(x, y, r), type(Type::Circle) {} + ProjectedCollisionBox(float x1, float y1, float x2, float y2) + : geometry(x1, y1, x2, y2), + type(Type::Box) {} + ProjectedCollisionBox(float x, float y, float r) + : geometry(x, y, r), + type(Type::Circle) {} const mapbox::geometry::box& box() const { assert(isBox()); @@ -38,8 +42,10 @@ class ProjectedCollisionBox { union Geometry { // NOLINTNEXTLINE(modernize-use-equals-default) Geometry() {} - Geometry(float x1, float y1, float x2, float y2) : box({x1, y1}, {x2, y2}) {} - Geometry(float x, float y, float r) : circle({x, y}, r) {} + Geometry(float x1, float y1, float x2, float y2) + : box({x1, y1}, {x2, y2}) {} + Geometry(float x, float y, float r) + : circle({x, y}, r) {} mapbox::geometry::box box; geometry::circle circle; } geometry; @@ -49,7 +55,12 @@ class ProjectedCollisionBox { class CollisionBox { public: CollisionBox(Point _anchor, float _x1, float _y1, float _x2, float _y2, float _signedDistanceFromAnchor = 0) - : anchor(_anchor), x1(_x1), y1(_y1), x2(_x2), y2(_y2), signedDistanceFromAnchor(_signedDistanceFromAnchor) {} + : anchor(_anchor), + x1(_x1), + y1(_y1), + x2(_x2), + y2(_y2), + signedDistanceFromAnchor(_signedDistanceFromAnchor) {} // the box is centered around the anchor point Point anchor; @@ -69,30 +80,33 @@ class CollisionBox { class CollisionFeature { public: - // for text - CollisionFeature(const GeometryCoordinates& line, - const Anchor& anchor, - const Shaping& shapedText, - const float boxScale, - const float padding, - const style::SymbolPlacementType placement, - const IndexedSubfeature& indexedFeature_, - const float overscaling, - const float rotate) - : CollisionFeature(line, - anchor, - shapedText.top, - shapedText.bottom, - shapedText.left, - shapedText.right, - std::nullopt, - boxScale, - padding, - placement, - indexedFeature_, - overscaling, - rotate) {} + CollisionFeature( + const GeometryCoordinates& line, + const Anchor& anchor, + const Shaping& shapedText, + const float boxScale, + const float padding, + const style::SymbolPlacementType placement, + const IndexedSubfeature& indexedFeature_, + const float overscaling, + const float rotate + ) + : CollisionFeature( + line, + anchor, + shapedText.top, + shapedText.bottom, + shapedText.left, + shapedText.right, + std::nullopt, + boxScale, + padding, + placement, + indexedFeature_, + overscaling, + rotate + ) {} // for icons // Icons collision features are always SymbolPlacementType::Point, which means the collision feature @@ -100,52 +114,60 @@ class CollisionFeature { // _or_ `symbol-placement: line`). We're relying on most icons being "close enough" to square that having // incorrect rotation alignment doesn't throw off collision detection too much. // See: https://github.com/mapbox/mapbox-gl-js/issues/4861 - CollisionFeature(const GeometryCoordinates& line, - const Anchor& anchor, - std::optional shapedIcon, - const float boxScale, - const float padding, - const IndexedSubfeature& indexedFeature_, - const float rotate) - : CollisionFeature(line, - anchor, - (shapedIcon ? shapedIcon->top() : 0), - (shapedIcon ? shapedIcon->bottom() : 0), - (shapedIcon ? shapedIcon->left() : 0), - (shapedIcon ? shapedIcon->right() : 0), - (shapedIcon ? shapedIcon->collisionPadding() : std::optional{std::nullopt}), - boxScale, - padding, - style::SymbolPlacementType::Point, - indexedFeature_, - 1, - rotate) {} - - CollisionFeature(const GeometryCoordinates& line, - const Anchor&, - float top, - float bottom, - float left, - float right, - const std::optional& collisionPadding, - float boxScale, - float padding, - style::SymbolPlacementType, - IndexedSubfeature, - float overscaling, - float rotate); + CollisionFeature( + const GeometryCoordinates& line, + const Anchor& anchor, + std::optional shapedIcon, + const float boxScale, + const float padding, + const IndexedSubfeature& indexedFeature_, + const float rotate + ) + : CollisionFeature( + line, + anchor, + (shapedIcon ? shapedIcon->top() : 0), + (shapedIcon ? shapedIcon->bottom() : 0), + (shapedIcon ? shapedIcon->left() : 0), + (shapedIcon ? shapedIcon->right() : 0), + (shapedIcon ? shapedIcon->collisionPadding() : std::optional{std::nullopt}), + boxScale, + padding, + style::SymbolPlacementType::Point, + indexedFeature_, + 1, + rotate + ) {} + + CollisionFeature( + const GeometryCoordinates& line, + const Anchor&, + float top, + float bottom, + float left, + float right, + const std::optional& collisionPadding, + float boxScale, + float padding, + style::SymbolPlacementType, + IndexedSubfeature, + float overscaling, + float rotate + ); std::vector boxes; IndexedSubfeature indexedFeature; bool alongLine; private: - void bboxifyLabel(const GeometryCoordinates& line, - GeometryCoordinate& anchorPoint, - std::size_t segment, - float length, - float boxSize, - float overscaling); + void bboxifyLabel( + const GeometryCoordinates& line, + GeometryCoordinate& anchorPoint, + std::size_t segment, + float length, + float boxSize, + float overscaling + ); }; } // namespace mbgl diff --git a/src/mbgl/text/collision_index.cpp b/src/mbgl/text/collision_index.cpp index 4d8295ab12e..ff6478c2373 100644 --- a/src/mbgl/text/collision_index.cpp +++ b/src/mbgl/text/collision_index.cpp @@ -37,28 +37,36 @@ inline float findViewportPadding(const TransformState& transformState, MapMode m CollisionIndex::CollisionIndex(const TransformState& transformState_, MapMode mapMode) : transformState(transformState_), viewportPadding(findViewportPadding(transformState_, mapMode)), - collisionGrid(transformState.getSize().width + 2 * viewportPadding, - transformState.getSize().height + 2 * viewportPadding, - 25), - ignoredGrid(transformState.getSize().width + 2 * viewportPadding, - transformState.getSize().height + 2 * viewportPadding, - 25), + collisionGrid( + transformState.getSize().width + 2 * viewportPadding, + transformState.getSize().height + 2 * viewportPadding, + 25 + ), + ignoredGrid( + transformState.getSize().width + 2 * viewportPadding, + transformState.getSize().height + 2 * viewportPadding, + 25 + ), screenRightBoundary(transformState.getSize().width + viewportPadding), screenBottomBoundary(transformState.getSize().height + viewportPadding), gridRightBoundary(transformState.getSize().width + 2 * viewportPadding), gridBottomBoundary(transformState.getSize().height + 2 * viewportPadding), - pitchFactor(static_cast(std::cos(transformState.getPitch()) * transformState.getCameraToCenterDistance())) {} - -float CollisionIndex::approximateTileDistance(const TileDistance& tileDistance, - const float lastSegmentAngle, - const float pixelsToTileUnits, - const float cameraToAnchorDistance, - const bool pitchWithMap) { + pitchFactor(static_cast(std::cos(transformState.getPitch()) * transformState.getCameraToCenterDistance()) + ) {} + +float CollisionIndex::approximateTileDistance( + const TileDistance& tileDistance, + const float lastSegmentAngle, + const float pixelsToTileUnits, + const float cameraToAnchorDistance, + const bool pitchWithMap +) { // This is a quick and dirty solution for chosing which collision circles to use (since collision circles are // laid out in tile units). Ideally, I think we should generate collision circles on the fly in viewport coordinates // at the time we do collision detection. - // incidenceStretch is the ratio of how much y space a label takes up on a tile while drawn perpendicular to the viewport vs + // incidenceStretch is the ratio of how much y space a label takes up on a tile while drawn perpendicular to the + // viewport vs // how much space it would take up if it were drawn flat on the tile // Using law of sines, camera_to_anchor/sin(ground_angle) = camera_to_center/sin(incidence_angle) // Incidence angle 90 -> head on, sin(incidence_angle) = 1, no stretch @@ -68,9 +76,8 @@ float CollisionIndex::approximateTileDistance(const TileDistance& tileDistance, const float incidenceStretch = pitchWithMap ? 1 : cameraToAnchorDistance / pitchFactor; const float lastSegmentTile = tileDistance.lastSegmentViewportDistance * pixelsToTileUnits; - return tileDistance.prevTileDistance + - lastSegmentTile + - (incidenceStretch - 1) * lastSegmentTile * std::abs(std::sin(lastSegmentAngle)); + return tileDistance.prevTileDistance + lastSegmentTile + + (incidenceStretch - 1) * lastSegmentTile * std::abs(std::sin(lastSegmentAngle)); } bool CollisionIndex::isOffscreen(const CollisionBoundaries& boundaries) const { @@ -84,31 +91,35 @@ bool CollisionIndex::isInsideGrid(const CollisionBoundaries& boundaries) const { } CollisionBoundaries CollisionIndex::projectTileBoundaries(const mat4& posMatrix) const { - Point topLeft = projectPoint(posMatrix, { 0, 0 }); - Point bottomRight = projectPoint(posMatrix, { util::EXTENT, util::EXTENT }); + Point topLeft = projectPoint(posMatrix, {0, 0}); + Point bottomRight = projectPoint(posMatrix, {util::EXTENT, util::EXTENT}); - return {{ topLeft.x, topLeft.y, bottomRight.x, bottomRight.y }}; + return {{topLeft.x, topLeft.y, bottomRight.x, bottomRight.y}}; } // The tile border checks below are only well defined when the tile boundaries are axis-aligned // We are relying on it only being used in MapMode::Tile, where that is always the case -inline bool CollisionIndex::isInsideTile(const CollisionBoundaries& boundaries, - const CollisionBoundaries& tileBoundaries) const { +inline bool CollisionIndex::isInsideTile( + const CollisionBoundaries& boundaries, const CollisionBoundaries& tileBoundaries +) const { return boundaries[0] >= tileBoundaries[0] && boundaries[1] >= tileBoundaries[1] && boundaries[2] < tileBoundaries[2] && boundaries[3] < tileBoundaries[3]; } -inline bool CollisionIndex::overlapsTile(const CollisionBoundaries& boundaries, - const CollisionBoundaries& tileBoundaries) const { +inline bool CollisionIndex::overlapsTile( + const CollisionBoundaries& boundaries, const CollisionBoundaries& tileBoundaries +) const { return boundaries[0] < tileBoundaries[2] && boundaries[2] > tileBoundaries[0] && boundaries[1] < tileBoundaries[3] && boundaries[3] > tileBoundaries[1]; } -IntersectStatus CollisionIndex::intersectsTileEdges(const CollisionBox& box, - Point shift, - const mat4& posMatrix, - const float textPixelRatio, - const CollisionBoundaries& tileEdges) const { +IntersectStatus CollisionIndex::intersectsTileEdges( + const CollisionBox& box, + Point shift, + const mat4& posMatrix, + const float textPixelRatio, + const CollisionBoundaries& tileEdges +) const { auto boundaries = getProjectedCollisionBoundaries(posMatrix, shift, textPixelRatio, box); IntersectStatus result; const float x1 = boundaries[0]; @@ -156,21 +167,37 @@ std::pair CollisionIndex::placeFeature( const bool collisionDebug, const std::optional& avoidEdges, const std::optional>& collisionGroupPredicate, - std::vector& projectedBoxes) { + std::vector& projectedBoxes +) { assert(projectedBoxes.empty()); if (!feature.alongLine) { const CollisionBox& box = feature.boxes.front(); auto collisionBoundaries = getProjectedCollisionBoundaries(posMatrix, shift, textPixelRatio, box); projectedBoxes.emplace_back( - collisionBoundaries[0], collisionBoundaries[1], collisionBoundaries[2], collisionBoundaries[3]); + collisionBoundaries[0], collisionBoundaries[1], collisionBoundaries[2], collisionBoundaries[3] + ); if ((avoidEdges && !isInsideTile(collisionBoundaries, *avoidEdges)) || !isInsideGrid(collisionBoundaries) || (!allowOverlap && collisionGrid.hitTest(projectedBoxes.back().box(), collisionGroupPredicate))) { - return { false, false }; + return {false, false}; } return {true, isOffscreen(collisionBoundaries)}; } else { - return placeLineFeature(feature, posMatrix, labelPlaneMatrix, textPixelRatio, symbol, scale, fontSize, allowOverlap, pitchWithMap, collisionDebug, avoidEdges, collisionGroupPredicate, projectedBoxes); + return placeLineFeature( + feature, + posMatrix, + labelPlaneMatrix, + textPixelRatio, + symbol, + scale, + fontSize, + allowOverlap, + pitchWithMap, + collisionDebug, + avoidEdges, + collisionGroupPredicate, + projectedBoxes + ); } } @@ -187,7 +214,8 @@ std::pair CollisionIndex::placeLineFeature( const bool collisionDebug, const std::optional& avoidEdges, const std::optional>& collisionGroupPredicate, - std::vector& projectedBoxes) { + std::vector& projectedBoxes +) { assert(feature.alongLine); assert(projectedBoxes.empty()); const auto tileUnitAnchorPoint = symbol.anchorPoint; @@ -208,7 +236,8 @@ std::pair CollisionIndex::placeLineFeature( tileUnitAnchorPoint, symbol, labelPlaneMatrix, - /*return tile distance*/ true); + /*return tile distance*/ true + ); bool collisionDetected = false; bool inGrid = false; @@ -223,8 +252,20 @@ std::pair CollisionIndex::placeLineFeature( float firstTileDistance = 0.f; float lastTileDistance = 0.f; if (firstAndLastGlyph) { - firstTileDistance = approximateTileDistance(*(firstAndLastGlyph->first.tileDistance), firstAndLastGlyph->first.angle, pixelsToTileUnits, projectedAnchor.second, pitchWithMap); - lastTileDistance = approximateTileDistance(*(firstAndLastGlyph->second.tileDistance), firstAndLastGlyph->second.angle, pixelsToTileUnits, projectedAnchor.second, pitchWithMap); + firstTileDistance = approximateTileDistance( + *(firstAndLastGlyph->first.tileDistance), + firstAndLastGlyph->first.angle, + pixelsToTileUnits, + projectedAnchor.second, + pitchWithMap + ); + lastTileDistance = approximateTileDistance( + *(firstAndLastGlyph->second.tileDistance), + firstAndLastGlyph->second.angle, + pixelsToTileUnits, + projectedAnchor.second, + pitchWithMap + ); } bool previousCirclePlaced = false; @@ -232,8 +273,7 @@ std::pair CollisionIndex::placeLineFeature( for (size_t i = 0; i < feature.boxes.size(); i++) { const CollisionBox& circle = feature.boxes[i]; const float boxSignedDistanceFromAnchor = circle.signedDistanceFromAnchor; - if (!firstAndLastGlyph || - (boxSignedDistanceFromAnchor < -firstTileDistance) || + if (!firstAndLastGlyph || (boxSignedDistanceFromAnchor < -firstTileDistance) || (boxSignedDistanceFromAnchor > lastTileDistance)) { // The label either doesn't fit on its line or we // don't need to use this circle because the label @@ -265,7 +305,7 @@ std::pair CollisionIndex::placeLineFeature( const CollisionBox& nextCircle = feature.boxes[i + 1]; const float nextBoxDistanceFromAnchor = nextCircle.signedDistanceFromAnchor; if ((nextBoxDistanceFromAnchor > -firstTileDistance) && - (nextBoxDistanceFromAnchor < lastTileDistance)) { + (nextBoxDistanceFromAnchor < lastTileDistance)) { // Hide significantly overlapping circles, unless this is the last one we can // use, in which case we want to keep it in place even if it's tightly packed // with the one before it. @@ -278,10 +318,11 @@ std::pair CollisionIndex::placeLineFeature( previousCirclePlaced = true; - CollisionBoundaries collisionBoundaries{{projectedPoint.x - radius, - projectedPoint.y - radius, - projectedPoint.x + radius, - projectedPoint.y + radius}}; + CollisionBoundaries collisionBoundaries{ + {projectedPoint.x - radius, + projectedPoint.y - radius, + projectedPoint.x + radius, + projectedPoint.y + radius}}; projectedBoxes[i] = ProjectedCollisionBox{projectedPoint.x, projectedPoint.y, radius}; @@ -303,7 +344,13 @@ std::pair CollisionIndex::placeLineFeature( return {!collisionDetected && firstAndLastGlyph && inGrid, entirelyOffscreen}; } -void CollisionIndex::insertFeature(const CollisionFeature& feature, const std::vector& projectedBoxes, bool ignorePlacement, uint32_t bucketInstanceId, uint16_t collisionGroupId) { +void CollisionIndex::insertFeature( + const CollisionFeature& feature, + const std::vector& projectedBoxes, + bool ignorePlacement, + uint32_t bucketInstanceId, + uint16_t collisionGroupId +) { if (feature.alongLine) { for (auto& circle : projectedBoxes) { if (!circle.isCircle()) { @@ -312,13 +359,11 @@ void CollisionIndex::insertFeature(const CollisionFeature& feature, const std::v if (ignorePlacement) { ignoredGrid.insert( - IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), - circle.circle() + IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), circle.circle() ); } else { collisionGrid.insert( - IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), - circle.circle() + IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), circle.circle() ); } } @@ -328,13 +373,11 @@ void CollisionIndex::insertFeature(const CollisionFeature& feature, const std::v assert(box.isBox()); if (ignorePlacement) { ignoredGrid.insert( - IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), - box.box() + IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), box.box() ); } else { collisionGrid.insert( - IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), - box.box() + IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), box.box() ); } } @@ -352,14 +395,14 @@ bool polygonIntersectsBox(const LineString& polygon, const GridIndex(bbox.min.y); auto maxX1 = static_cast(bbox.max.x); - auto bboxPoints = GeometryCoordinates { - { minX1, minY1 }, { maxX1, minY1 }, { maxX1, maxY1 }, { minX1, maxY1 } - }; - + auto bboxPoints = GeometryCoordinates{{minX1, minY1}, {maxX1, minY1}, {maxX1, maxY1}, {minX1, maxY1}}; + return util::polygonIntersectsPolygon(integerPolygon, bboxPoints); } -std::unordered_map> CollisionIndex::queryRenderedSymbols(const ScreenLineString& queryGeometry) const { +std::unordered_map> CollisionIndex::queryRenderedSymbols( + const ScreenLineString& queryGeometry +) const { std::unordered_map> result; if (queryGeometry.empty() || (collisionGrid.empty() && ignoredGrid.empty())) { return result; @@ -367,27 +410,28 @@ std::unordered_map> CollisionIndex::que LineString gridQuery; for (const auto& point : queryGeometry) { - gridQuery.emplace_back(static_cast(point.x) + viewportPadding, static_cast(point.y) + viewportPadding); + gridQuery.emplace_back( + static_cast(point.x) + viewportPadding, static_cast(point.y) + viewportPadding + ); } - + auto envelope = mapbox::geometry::envelope(gridQuery); - + using QueryResult = std::pair::BBox>; - + std::vector features = collisionGrid.queryWithBoxes(envelope); std::vector ignoredFeatures = ignoredGrid.queryWithBoxes(envelope); features.insert(features.end(), ignoredFeatures.begin(), ignoredFeatures.end()); std::unordered_map> seenBuckets; - for (auto& queryResult : features) { + for (auto& queryResult : features) { auto& feature = queryResult.first; auto& bbox = queryResult.second; // Skip already seen features. auto& seenFeatures = seenBuckets[feature.bucketInstanceId]; - if (seenFeatures.find(feature.index) != seenFeatures.end()) - continue; - + if (seenFeatures.find(feature.index) != seenFeatures.end()) continue; + if (!polygonIntersectsBox(gridQuery, bbox)) { continue; } @@ -397,20 +441,20 @@ std::unordered_map> CollisionIndex::que } return result; - } -std::pair CollisionIndex::projectAnchor(const mat4& posMatrix, const Point& point) const { - vec4 p = {{ point.x, point.y, 0, 1 }}; +std::pair CollisionIndex::projectAnchor(const mat4& posMatrix, const Point& point) const { + vec4 p = {{point.x, point.y, 0, 1}}; matrix::transformMat4(p, p, posMatrix); return std::make_pair( - 0.5f + 0.5f * (transformState.getCameraToCenterDistance() / static_cast(p[3])), - static_cast(p[3]) + 0.5f + 0.5f * (transformState.getCameraToCenterDistance() / static_cast(p[3])), static_cast(p[3]) ); } -std::pair,float> CollisionIndex::projectAndGetPerspectiveRatio(const mat4& posMatrix, const Point& point) const { - vec4 p = {{ point.x, point.y, 0, 1 }}; +std::pair, float> CollisionIndex::projectAndGetPerspectiveRatio( + const mat4& posMatrix, const Point& point +) const { + vec4 p = {{point.x, point.y, 0, 1}}; matrix::transformMat4(p, p, posMatrix); auto size = transformState.getSize(); return std::make_pair( @@ -426,18 +470,17 @@ std::pair,float> CollisionIndex::projectAndGetPerspectiveRatio(cons } Point CollisionIndex::projectPoint(const mat4& posMatrix, const Point& point) const { - vec4 p = {{ point.x, point.y, 0, 1 }}; + vec4 p = {{point.x, point.y, 0, 1}}; matrix::transformMat4(p, p, posMatrix); auto size = transformState.getSize(); - return Point { + return Point{ static_cast((((p[0] / p[3] + 1) / 2) * size.width) + viewportPadding), - static_cast((((-p[1] / p[3] + 1) / 2) * size.height) + viewportPadding) }; + static_cast((((-p[1] / p[3] + 1) / 2) * size.height) + viewportPadding)}; } -CollisionBoundaries CollisionIndex::getProjectedCollisionBoundaries(const mat4& posMatrix, - Point shift, - float textPixelRatio, - const CollisionBox& box) const { +CollisionBoundaries CollisionIndex::getProjectedCollisionBoundaries( + const mat4& posMatrix, Point shift, float textPixelRatio, const CollisionBox& box +) const { const auto projectedPoint = projectAndGetPerspectiveRatio(posMatrix, box.anchor); const float tileToViewport = textPixelRatio * projectedPoint.second; return CollisionBoundaries{{ diff --git a/src/mbgl/text/collision_index.hpp b/src/mbgl/text/collision_index.hpp index b90242bb452..ef93a2648be 100644 --- a/src/mbgl/text/collision_index.hpp +++ b/src/mbgl/text/collision_index.hpp @@ -16,7 +16,11 @@ struct TileDistance; using CollisionBoundaries = std::array; // [x1, y1, x2, y2] struct IntersectStatus { - enum Flags : uint8_t { None = 0, HorizontalBorders = 1 << 0, VerticalBorders = 1 << 1 }; + enum Flags : uint8_t { + None = 0, + HorizontalBorders = 1 << 0, + VerticalBorders = 1 << 1 + }; Flags flags = None; // Assuming tile border divides box in two sections int minSectionLength = 0; @@ -26,11 +30,13 @@ class CollisionIndex { using CollisionGrid = GridIndex; explicit CollisionIndex(const TransformState&, MapMode); - IntersectStatus intersectsTileEdges(const CollisionBox&, - Point shift, - const mat4& posMatrix, - float textPixelRatio, - const CollisionBoundaries& tileEdges) const; + IntersectStatus intersectsTileEdges( + const CollisionBox&, + Point shift, + const mat4& posMatrix, + float textPixelRatio, + const CollisionBoundaries& tileEdges + ) const; std::pair placeFeature( const CollisionFeature& feature, Point shift, @@ -45,9 +51,16 @@ class CollisionIndex { bool collisionDebug, const std::optional& avoidEdges, const std::optional>& collisionGroupPredicate, - std::vector& /*out*/); + std::vector& /*out*/ + ); - void insertFeature(const CollisionFeature& feature, const std::vector&, bool ignorePlacement, uint32_t bucketInstanceId, uint16_t collisionGroupId); + void insertFeature( + const CollisionFeature& feature, + const std::vector&, + bool ignorePlacement, + uint32_t bucketInstanceId, + uint16_t collisionGroupId + ); std::unordered_map> queryRenderedSymbols(const ScreenLineString&) const; @@ -76,33 +89,36 @@ class CollisionIndex { bool collisionDebug, const std::optional& avoidEdges, const std::optional>& collisionGroupPredicate, - std::vector& /*out*/); - - float approximateTileDistance(const TileDistance& tileDistance, - float lastSegmentAngle, - float pixelsToTileUnits, - float cameraToAnchorDistance, - bool pitchWithMap); - - std::pair projectAnchor(const mat4& posMatrix, const Point& point) const; - std::pair,float> projectAndGetPerspectiveRatio(const mat4& posMatrix, const Point& point) const; + std::vector& /*out*/ + ); + + float approximateTileDistance( + const TileDistance& tileDistance, + float lastSegmentAngle, + float pixelsToTileUnits, + float cameraToAnchorDistance, + bool pitchWithMap + ); + + std::pair projectAnchor(const mat4& posMatrix, const Point& point) const; + std::pair, float> projectAndGetPerspectiveRatio(const mat4& posMatrix, const Point& point) + const; Point projectPoint(const mat4& posMatrix, const Point& point) const; - CollisionBoundaries getProjectedCollisionBoundaries(const mat4& posMatrix, - Point shift, - float textPixelRatio, - const CollisionBox& box) const; + CollisionBoundaries getProjectedCollisionBoundaries( + const mat4& posMatrix, Point shift, float textPixelRatio, const CollisionBox& box + ) const; const TransformState transformState; const float viewportPadding; CollisionGrid collisionGrid; CollisionGrid ignoredGrid; - + const float screenRightBoundary; const float screenBottomBoundary; const float gridRightBoundary; const float gridBottomBoundary; - + const float pitchFactor; }; diff --git a/src/mbgl/text/cross_tile_symbol_index.cpp b/src/mbgl/text/cross_tile_symbol_index.cpp index f2785dd1203..482688a370d 100644 --- a/src/mbgl/text/cross_tile_symbol_index.cpp +++ b/src/mbgl/text/cross_tile_symbol_index.cpp @@ -6,34 +6,45 @@ namespace mbgl { -TileLayerIndex::TileLayerIndex(OverscaledTileID coord_, - std::vector& symbolInstances, - uint32_t bucketInstanceId_, - std::string bucketLeaderId_) - : coord(coord_), bucketInstanceId(bucketInstanceId_), bucketLeaderId(std::move(bucketLeaderId_)) { +TileLayerIndex::TileLayerIndex( + OverscaledTileID coord_, + std::vector& symbolInstances, + uint32_t bucketInstanceId_, + std::string bucketLeaderId_ +) + : coord(coord_), + bucketInstanceId(bucketInstanceId_), + bucketLeaderId(std::move(bucketLeaderId_)) { for (SymbolInstance& symbolInstance : symbolInstances) { if (symbolInstance.crossTileID == SymbolInstance::invalidCrossTileID()) continue; - indexedSymbolInstances[symbolInstance.key].emplace_back(symbolInstance.crossTileID, - getScaledCoordinates(symbolInstance, coord)); + indexedSymbolInstances[symbolInstance.key].emplace_back( + symbolInstance.crossTileID, getScaledCoordinates(symbolInstance, coord) + ); } } -Point TileLayerIndex::getScaledCoordinates(SymbolInstance& symbolInstance, - const OverscaledTileID& childTileCoord) const { +Point TileLayerIndex::getScaledCoordinates( + SymbolInstance& symbolInstance, const OverscaledTileID& childTileCoord +) const { // Round anchor positions to roughly 4 pixel grid const double roundingFactor = 512.0 / util::EXTENT / 2.0; const double scale = roundingFactor / std::pow(2, childTileCoord.canonical.z - coord.canonical.z); return { - static_cast(std::floor((childTileCoord.canonical.x * util::EXTENT + symbolInstance.anchor.point.x) * scale)), - static_cast(std::floor((childTileCoord.canonical.y * util::EXTENT + symbolInstance.anchor.point.y) * scale)) - }; + static_cast( + std::floor((childTileCoord.canonical.x * util::EXTENT + symbolInstance.anchor.point.x) * scale) + ), + static_cast( + std::floor((childTileCoord.canonical.y * util::EXTENT + symbolInstance.anchor.point.y) * scale) + )}; } -void TileLayerIndex::findMatches(SymbolBucket& bucket, - const OverscaledTileID& newCoord, - std::set& zoomCrossTileIDs) const { +void TileLayerIndex::findMatches( + SymbolBucket& bucket, const OverscaledTileID& newCoord, std::set& zoomCrossTileIDs +) const { auto& symbolInstances = bucket.symbolInstances; - float tolerance = coord.canonical.z < newCoord.canonical.z ? 1.0f : static_cast(std::pow(2, coord.canonical.z - newCoord.canonical.z)); + float tolerance = coord.canonical.z < newCoord.canonical.z + ? 1.0f + : static_cast(std::pow(2, coord.canonical.z - newCoord.canonical.z)); if (bucket.bucketLeaderID != bucketLeaderId) return; @@ -68,7 +79,8 @@ void TileLayerIndex::findMatches(SymbolBucket& bucket, } } -CrossTileSymbolLayerIndex::CrossTileSymbolLayerIndex(uint32_t& maxCrossTileID_) : maxCrossTileID(maxCrossTileID_) {} +CrossTileSymbolLayerIndex::CrossTileSymbolLayerIndex(uint32_t& maxCrossTileID_) + : maxCrossTileID(maxCrossTileID_) {} /* * Sometimes when a user pans across the antimeridian the longitude value gets wrapped. @@ -78,9 +90,9 @@ CrossTileSymbolLayerIndex::CrossTileSymbolLayerIndex(uint32_t& maxCrossTileID_) void CrossTileSymbolLayerIndex::handleWrapJump(float newLng) { const auto wrapDelta = static_cast(std::round((newLng - lng) / 360.0f)); if (wrapDelta != 0) { - std::map> newIndexes; + std::map> newIndexes; for (auto& zoomIndex : indexes) { - std::map newZoomIndex; + std::map newZoomIndex; for (auto& index : zoomIndex.second) { // change the tileID's wrap and move its index index.second.coord = index.second.coord.unwrapTo(index.second.coord.wrap + wrapDelta); @@ -111,9 +123,9 @@ bool isInVewport(const mat4& posMatrix, const Point& point) { } // namespace -bool CrossTileSymbolLayerIndex::addBucket(const OverscaledTileID& tileID, - const mat4& tileMatrix, - SymbolBucket& bucket) { +bool CrossTileSymbolLayerIndex::addBucket( + const OverscaledTileID& tileID, const mat4& tileMatrix, SymbolBucket& bucket +) { auto& thisZoomIndexes = indexes[tileID.overscaledZ]; auto previousIndex = thisZoomIndexes.find(tileID); if (previousIndex != thisZoomIndexes.end()) { @@ -179,7 +191,8 @@ bool CrossTileSymbolLayerIndex::addBucket(const OverscaledTileID& tileID, thisZoomIndexes.emplace( std::piecewise_construct, std::forward_as_tuple(tileID), - std::forward_as_tuple(tileID, bucket.symbolInstances, bucket.bucketInstanceId, bucket.bucketLeaderID)); + std::forward_as_tuple(tileID, bucket.symbolInstances, bucket.bucketInstanceId, bucket.bucketLeaderID) + ); return true; } @@ -213,9 +226,11 @@ auto CrossTileSymbolIndex::addLayer(const RenderLayer& layer, float lng) -> AddL auto found = layerIndexes.find(layer.getID()); if (found == layerIndexes.end()) { found = layerIndexes - .emplace(std::piecewise_construct, - std::forward_as_tuple(layer.getID()), - std::forward_as_tuple(maxCrossTileID)) + .emplace( + std::piecewise_construct, + std::forward_as_tuple(layer.getID()), + std::forward_as_tuple(maxCrossTileID) + ) .first; } auto& layerIndex = found->second; @@ -254,4 +269,3 @@ void CrossTileSymbolIndex::reset() { } } // namespace mbgl - diff --git a/src/mbgl/text/cross_tile_symbol_index.hpp b/src/mbgl/text/cross_tile_symbol_index.hpp index 50d91123976..4d28dde1b7d 100644 --- a/src/mbgl/text/cross_tile_symbol_index.hpp +++ b/src/mbgl/text/cross_tile_symbol_index.hpp @@ -22,8 +22,8 @@ class SymbolBucket; class IndexedSymbolInstance { public: IndexedSymbolInstance(uint32_t crossTileID_, Point coord_) - : crossTileID(crossTileID_), coord(coord_) - {} + : crossTileID(crossTileID_), + coord(coord_) {} uint32_t crossTileID; Point coord; @@ -31,10 +31,9 @@ class IndexedSymbolInstance { class TileLayerIndex { public: - TileLayerIndex(OverscaledTileID coord, - std::vector&, - uint32_t bucketInstanceId, - std::string bucketLeaderId); + TileLayerIndex( + OverscaledTileID coord, std::vector&, uint32_t bucketInstanceId, std::string bucketLeaderId + ); Point getScaledCoordinates(SymbolInstance&, const OverscaledTileID&) const; void findMatches(SymbolBucket&, const OverscaledTileID&, std::set&) const; @@ -42,7 +41,7 @@ class TileLayerIndex { OverscaledTileID coord; uint32_t bucketInstanceId; std::string bucketLeaderId; - std::map> indexedSymbolInstances; + std::map> indexedSymbolInstances; }; class CrossTileSymbolLayerIndex { @@ -51,10 +50,11 @@ class CrossTileSymbolLayerIndex { bool addBucket(const OverscaledTileID&, const mat4& tileMatrix, SymbolBucket&); bool removeStaleBuckets(const std::unordered_set& currentIDs); void handleWrapJump(float newLng); + private: void removeBucketCrossTileIDs(uint8_t zoom, const TileLayerIndex& removedBucket); - std::map> indexes; + std::map> indexes; std::map> usedCrossTileIDs; float lng = 0; uint32_t& maxCrossTileID; @@ -74,6 +74,7 @@ class CrossTileSymbolIndex { void pruneUnusedLayers(const std::set&); void reset(); + private: std::map layerIndexes; uint32_t maxCrossTileID = 0; diff --git a/src/mbgl/text/get_anchors.cpp b/src/mbgl/text/get_anchors.cpp index ab2abc1bdba..0fc263b99cb 100644 --- a/src/mbgl/text/get_anchors.cpp +++ b/src/mbgl/text/get_anchors.cpp @@ -7,11 +7,9 @@ #include namespace mbgl { - + float getAngleWindowSize(const float textLeft, const float textRight, const float glyphSize, const float boxScale) { - return (textLeft - textRight) != 0.0f ? - 3.0f / 5.0f * glyphSize * boxScale : - 0; + return (textLeft - textRight) != 0.0f ? 3.0f / 5.0f * glyphSize * boxScale : 0; } float getLineLength(const GeometryCoordinates& line) { @@ -22,14 +20,16 @@ float getLineLength(const GeometryCoordinates& line) { return lineLength; } -static Anchors resample(const GeometryCoordinates& line, - const float offset, - const float spacing, - const float angleWindowSize, - const float maxAngle, - const float labelLength, - const bool continuedLine, - const bool placeAtMiddle) { +static Anchors resample( + const GeometryCoordinates& line, + const float offset, + const float spacing, + const float angleWindowSize, + const float maxAngle, + const float labelLength, + const bool continuedLine, + const bool placeAtMiddle +) { const float halfLabelLength = labelLength / 2.0f; const float lineLength = getLineLength(line); @@ -58,9 +58,8 @@ static Anchors resample(const GeometryCoordinates& line, // Check that the point is within the tile boundaries and that // the label would fit before the beginning and end of the line // if placed at this point. - if (x >= 0 && x < util::EXTENT && y >= 0 && y < util::EXTENT && - markedDistance - halfLabelLength >= 0.0f && - markedDistance + halfLabelLength <= lineLength) { + if (x >= 0 && x < util::EXTENT && y >= 0 && y < util::EXTENT && markedDistance - halfLabelLength >= 0.0f && + markedDistance + halfLabelLength <= lineLength) { Anchor anchor(std::round(x), std::round(y), angle, i); if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { @@ -84,16 +83,18 @@ static Anchors resample(const GeometryCoordinates& line, return anchors; } -Anchors getAnchors(const GeometryCoordinates& line, - float spacing, - const float maxAngle, - const float textLeft, - const float textRight, - const float iconLeft, - const float iconRight, - const float glyphSize, - const float boxScale, - const float overscaling) { +Anchors getAnchors( + const GeometryCoordinates& line, + float spacing, + const float maxAngle, + const float textLeft, + const float textRight, + const float iconLeft, + const float iconRight, + const float glyphSize, + const float boxScale, + const float overscaling +) { if (line.empty()) { return {}; } @@ -108,7 +109,8 @@ Anchors getAnchors(const GeometryCoordinates& line, const float labelLength = shapedLabelLength * boxScale; // Is the line continued from outside the tile boundary? - const bool continuedLine = (line[0].x == 0 || line[0].x == util::EXTENT || line[0].y == 0 || line[0].y == util::EXTENT); + const bool continuedLine = + (line[0].x == 0 || line[0].x == util::EXTENT || line[0].y == 0 || line[0].y == util::EXTENT); // Is the label long, relative to the spacing? // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges. @@ -123,25 +125,27 @@ Anchors getAnchors(const GeometryCoordinates& line, // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections. const float fixedExtraOffset = glyphSize * 2; - const float offset = !continuedLine ? - std::fmod((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling, spacing) : - std::fmod(spacing / 2 * overscaling, spacing); + const float offset = !continuedLine + ? std::fmod((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling, spacing) + : std::fmod(spacing / 2 * overscaling, spacing); return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, continuedLine, false); } -std::optional getCenterAnchor(const GeometryCoordinates& line, - const float maxAngle, - const float textLeft, - const float textRight, - const float iconLeft, - const float iconRight, - const float glyphSize, - const float boxScale) { +std::optional getCenterAnchor( + const GeometryCoordinates& line, + const float maxAngle, + const float textLeft, + const float textRight, + const float iconLeft, + const float iconRight, + const float glyphSize, + const float boxScale +) { if (line.empty()) { return {}; } - + const float angleWindowSize = getAngleWindowSize(textLeft, textRight, glyphSize, boxScale); const float labelLength = std::fmax(textRight - textLeft, iconRight - iconLeft) * boxScale; @@ -152,9 +156,9 @@ std::optional getCenterAnchor(const GeometryCoordinates& line, for (auto it = line.begin(), end = line.end() - 1; it != end; it++, i++) { const GeometryCoordinate& a = *(it); const GeometryCoordinate& b = *(it + 1); - + const auto segmentDistance = util::dist(a, b); - + if (prevDistance + segmentDistance > centerDistance) { // The center is on this segment float t = (centerDistance - prevDistance) / segmentDistance; @@ -169,7 +173,7 @@ std::optional getCenterAnchor(const GeometryCoordinates& line, return std::nullopt; } - + prevDistance += segmentDistance; } return {}; diff --git a/src/mbgl/text/get_anchors.hpp b/src/mbgl/text/get_anchors.hpp index 357ece3dfdf..44673a65d86 100644 --- a/src/mbgl/text/get_anchors.hpp +++ b/src/mbgl/text/get_anchors.hpp @@ -6,24 +6,28 @@ namespace mbgl { -Anchors getAnchors(const GeometryCoordinates& line, - float spacing, - float maxAngle, - float textLeft, - float textRight, - float iconLeft, - float iconRight, - float glyphSize, - float boxScale, - float overscaling); +Anchors getAnchors( + const GeometryCoordinates& line, + float spacing, + float maxAngle, + float textLeft, + float textRight, + float iconLeft, + float iconRight, + float glyphSize, + float boxScale, + float overscaling +); -std::optional getCenterAnchor(const GeometryCoordinates& line, - float maxAngle, - float textLeft, - float textRight, - float iconLeft, - float iconRight, - float glyphSize, - float boxScale); +std::optional getCenterAnchor( + const GeometryCoordinates& line, + float maxAngle, + float textLeft, + float textRight, + float iconLeft, + float iconRight, + float glyphSize, + float boxScale +); } // namespace mbgl diff --git a/src/mbgl/text/glyph.cpp b/src/mbgl/text/glyph.cpp index 74863d7435c..8c879cbe4dd 100644 --- a/src/mbgl/text/glyph.cpp +++ b/src/mbgl/text/glyph.cpp @@ -4,11 +4,11 @@ namespace mbgl { // Note: this only works for the BMP GlyphRange getGlyphRange(GlyphID glyph) { - unsigned start = (glyph/256) * 256; + unsigned start = (glyph / 256) * 256; unsigned end = (start + 255); if (start > 65280) start = 65280; if (end > 65535) end = 65535; - return { start, end }; + return {start, end}; } } // namespace mbgl diff --git a/src/mbgl/text/glyph.hpp b/src/mbgl/text/glyph.hpp index d1d1bd4cb41..13b419864e0 100644 --- a/src/mbgl/text/glyph.hpp +++ b/src/mbgl/text/glyph.hpp @@ -32,11 +32,8 @@ struct GlyphMetrics { }; inline bool operator==(const GlyphMetrics& lhs, const GlyphMetrics& rhs) { - return lhs.width == rhs.width && - lhs.height == rhs.height && - lhs.left == rhs.left && - lhs.top == rhs.top && - lhs.advance == rhs.advance; + return lhs.width == rhs.width && lhs.height == rhs.height && lhs.left == rhs.left && lhs.top == rhs.top && + lhs.advance == rhs.advance; } class Glyph { @@ -59,16 +56,18 @@ using GlyphMap = std::map; class PositionedGlyph { public: - explicit PositionedGlyph(GlyphID glyph_, - float x_, - float y_, - bool vertical_, - FontStackHash font_, - float scale_, - Rect rect_, - GlyphMetrics metrics_, - std::optional imageID_, - std::size_t sectionIndex_ = 0) + explicit PositionedGlyph( + GlyphID glyph_, + float x_, + float y_, + bool vertical_, + FontStackHash font_, + float scale_, + Rect rect_, + GlyphMetrics metrics_, + std::optional imageID_, + std::size_t sectionIndex_ = 0 + ) : glyph(glyph_), x(x_), y(y_), @@ -101,10 +100,14 @@ struct PositionedLine { }; class Shaping { - public: +public: Shaping() = default; explicit Shaping(float x, float y, WritingModeType writingMode_) - : top(y), bottom(y), left(x), right(x), writingMode(writingMode_) {} + : top(y), + bottom(y), + left(x), + right(x), + writingMode(writingMode_) {} std::vector positionedLines; float top = 0; float bottom = 0; diff --git a/src/mbgl/text/glyph_atlas.cpp b/src/mbgl/text/glyph_atlas.cpp index da65aea8a9d..b5f15eaf375 100644 --- a/src/mbgl/text/glyph_atlas.cpp +++ b/src/mbgl/text/glyph_atlas.cpp @@ -21,43 +21,32 @@ GlyphAtlas makeGlyphAtlas(const GlyphMap& glyphs) { if (entry.second && (*entry.second)->bitmap.valid()) { const Glyph& glyph = **entry.second; - const mapbox::Bin& bin = *pack.packOne(-1, - glyph.bitmap.size.width + 2 * padding, - glyph.bitmap.size.height + 2 * padding); - - result.image.resize({ - static_cast(pack.width()), - static_cast(pack.height()) - }); - - AlphaImage::copy(glyph.bitmap, - result.image, - { 0, 0 }, - { - bin.x + padding, - bin.y + padding - }, - glyph.bitmap.size); - - positions.emplace(glyph.id, - GlyphPosition { - Rect { - static_cast(bin.x), - static_cast(bin.y), - static_cast(bin.w), - static_cast(bin.h) - }, - glyph.metrics - }); + const mapbox::Bin& bin = *pack.packOne( + -1, glyph.bitmap.size.width + 2 * padding, glyph.bitmap.size.height + 2 * padding + ); + + result.image.resize({static_cast(pack.width()), static_cast(pack.height())}); + + AlphaImage::copy( + glyph.bitmap, result.image, {0, 0}, {bin.x + padding, bin.y + padding}, glyph.bitmap.size + ); + + positions.emplace( + glyph.id, + GlyphPosition{ + Rect{ + static_cast(bin.x), + static_cast(bin.y), + static_cast(bin.w), + static_cast(bin.h)}, + glyph.metrics} + ); } } } pack.shrink(); - result.image.resize({ - static_cast(pack.width()), - static_cast(pack.height()) - }); + result.image.resize({static_cast(pack.width()), static_cast(pack.height())}); return result; } diff --git a/src/mbgl/text/glyph_manager.cpp b/src/mbgl/text/glyph_manager.cpp index 924e931521d..a581b919cfd 100644 --- a/src/mbgl/text/glyph_manager.cpp +++ b/src/mbgl/text/glyph_manager.cpp @@ -14,8 +14,7 @@ static GlyphManagerObserver nullObserver; GlyphManager::GlyphManager(std::unique_ptr localGlyphRasterizer_) : observer(&nullObserver), - localGlyphRasterizer(std::move(localGlyphRasterizer_)) { -} + localGlyphRasterizer(std::move(localGlyphRasterizer_)) {} GlyphManager::~GlyphManager() = default; @@ -65,14 +64,17 @@ Glyph GlyphManager::generateLocalSDF(const FontStack& fontStack, GlyphID glyphID return local; } -void GlyphManager::requestRange(GlyphRequest& request, const FontStack& fontStack, const GlyphRange& range, FileSource& fileSource) { +void GlyphManager::requestRange( + GlyphRequest& request, const FontStack& fontStack, const GlyphRange& range, FileSource& fileSource +) { if (request.req) { return; } - request.req = - fileSource.request(Resource::glyphs(glyphURL, fontStack, range), - [this, fontStack, range](const Response& res) { processResponse(res, fontStack, range); }); + request.req = fileSource.request( + Resource::glyphs(glyphURL, fontStack, range), + [this, fontStack, range](const Response& res) { processResponse(res, fontStack, range); } + ); } void GlyphManager::processResponse(const Response& res, const FontStack& fontStack, const GlyphRange& range) { @@ -158,9 +160,7 @@ void GlyphManager::removeRequestor(GlyphRequestor& requestor) { } void GlyphManager::evict(const std::set& keep) { - util::erase_if(entries, [&] (const auto& entry) { - return keep.count(entry.first) == 0; - }); + util::erase_if(entries, [&](const auto& entry) { return keep.count(entry.first) == 0; }); } } // namespace mbgl diff --git a/src/mbgl/text/glyph_manager.hpp b/src/mbgl/text/glyph_manager.hpp index a53636d0a76..8354e076fc2 100644 --- a/src/mbgl/text/glyph_manager.hpp +++ b/src/mbgl/text/glyph_manager.hpp @@ -28,7 +28,9 @@ class GlyphManager { public: GlyphManager(const GlyphManager&) = delete; GlyphManager& operator=(const GlyphManager&) = delete; - explicit GlyphManager(std::unique_ptr = std::make_unique(std::optional())); + explicit GlyphManager( + std::unique_ptr = std::make_unique(std::optional()) + ); ~GlyphManager(); // Workers send a `getGlyphs` message to the main thread once they have determined @@ -39,9 +41,7 @@ class GlyphManager { void getGlyphs(GlyphRequestor&, GlyphDependencies, FileSource&); void removeRequestor(GlyphRequestor&); - void setURL(const std::string& url) { - glyphURL = url; - } + void setURL(const std::string& url) { glyphURL = url; } void setObserver(GlyphManagerObserver*); @@ -68,9 +68,9 @@ class GlyphManager { void requestRange(GlyphRequest&, const FontStack&, const GlyphRange&, FileSource& fileSource); void processResponse(const Response&, const FontStack&, const GlyphRange&); void notify(GlyphRequestor&, const GlyphDependencies&); - + GlyphManagerObserver* observer = nullptr; - + std::unique_ptr localGlyphRasterizer; }; diff --git a/src/mbgl/text/glyph_pbf.cpp b/src/mbgl/text/glyph_pbf.cpp index c1cd3292926..b08c5a3e642 100644 --- a/src/mbgl/text/glyph_pbf.cpp +++ b/src/mbgl/text/glyph_pbf.cpp @@ -27,36 +27,36 @@ std::vector parseGlyphPBF(const GlyphRange& glyphRange, const std::string while (glyph_pbf.next()) { switch (glyph_pbf.tag()) { - case 1: // id - glyph.id = glyph_pbf.get_uint32(); - hasID = true; - break; - case 2: // bitmap - glyphData = glyph_pbf.get_view(); - break; - case 3: // width - glyph.metrics.width = glyph_pbf.get_uint32(); - hasWidth = true; - break; - case 4: // height - glyph.metrics.height = glyph_pbf.get_uint32(); - hasHeight = true; - break; - case 5: // left - glyph.metrics.left = glyph_pbf.get_sint32(); - hasLeft = true; - break; - case 6: // top - glyph.metrics.top = glyph_pbf.get_sint32(); - hasTop = true; - break; - case 7: // advance - glyph.metrics.advance = glyph_pbf.get_uint32(); - hasAdvance = true; - break; - default: - glyph_pbf.skip(); - break; + case 1: // id + glyph.id = glyph_pbf.get_uint32(); + hasID = true; + break; + case 2: // bitmap + glyphData = glyph_pbf.get_view(); + break; + case 3: // width + glyph.metrics.width = glyph_pbf.get_uint32(); + hasWidth = true; + break; + case 4: // height + glyph.metrics.height = glyph_pbf.get_uint32(); + hasHeight = true; + break; + case 5: // left + glyph.metrics.left = glyph_pbf.get_sint32(); + hasLeft = true; + break; + case 6: // top + glyph.metrics.top = glyph_pbf.get_sint32(); + hasTop = true; + break; + case 7: // advance + glyph.metrics.advance = glyph_pbf.get_uint32(); + hasAdvance = true; + break; + default: + glyph_pbf.skip(); + break; } } @@ -64,11 +64,9 @@ std::vector parseGlyphPBF(const GlyphRange& glyphRange, const std::string // needs to satisfy a few metrics conditions that ensure that the glyph isn't bogus. // All other glyphs are malformed. We're also discarding all glyphs that are outside // the expected glyph range. - if (!hasID || !hasWidth || !hasHeight || !hasLeft || !hasTop || !hasAdvance || - glyph.metrics.width >= 256 || glyph.metrics.height >= 256 || - glyph.metrics.left < -128 || glyph.metrics.left >= 128 || - glyph.metrics.top < -128 || glyph.metrics.top >= 128 || - glyph.metrics.advance >= 256 || + if (!hasID || !hasWidth || !hasHeight || !hasLeft || !hasTop || !hasAdvance || glyph.metrics.width >= 256 || + glyph.metrics.height >= 256 || glyph.metrics.left < -128 || glyph.metrics.left >= 128 || + glyph.metrics.top < -128 || glyph.metrics.top >= 128 || glyph.metrics.advance >= 256 || glyph.id < glyphRange.first || glyph.id > glyphRange.second) { continue; } @@ -76,10 +74,8 @@ std::vector parseGlyphPBF(const GlyphRange& glyphRange, const std::string // If the area of width/height is non-zero, we need to adjust the expected size // with the implicit border size, otherwise we expect there to be no bitmap at all. if (glyph.metrics.width && glyph.metrics.height) { - const Size size { - glyph.metrics.width + 2 * Glyph::borderSize, - glyph.metrics.height + 2 * Glyph::borderSize - }; + const Size size{ + glyph.metrics.width + 2 * Glyph::borderSize, glyph.metrics.height + 2 * Glyph::borderSize}; if (size.area() != glyphData.size()) { continue; diff --git a/src/mbgl/text/glyph_range.hpp b/src/mbgl/text/glyph_range.hpp index 17dc8c82725..14c704d0e17 100644 --- a/src/mbgl/text/glyph_range.hpp +++ b/src/mbgl/text/glyph_range.hpp @@ -20,9 +20,7 @@ namespace std { template <> struct hash { - std::size_t operator()(const mbgl::GlyphRange& range) const { - return mbgl::util::hash(range.first, range.second); - } + std::size_t operator()(const mbgl::GlyphRange& range) const { return mbgl::util::hash(range.first, range.second); } }; } // namespace std diff --git a/src/mbgl/text/language_tag.cpp b/src/mbgl/text/language_tag.cpp index 02f01c3d69b..bbffa62138d 100644 --- a/src/mbgl/text/language_tag.cpp +++ b/src/mbgl/text/language_tag.cpp @@ -2,7 +2,7 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4828) +#pragma warning(disable : 4828) #endif #include @@ -100,80 +100,56 @@ namespace phoenix = boost::phoenix; namespace ascii = boost::spirit::ascii; template -struct bcp47_parser : qi::grammar -{ - bcp47_parser() : bcp47_parser::base_type(start) - { - using qi::lit; - using qi::repeat; - using qi::inf; - using qi::eoi; - using ascii::char_; - using ascii::no_case; - using ascii::digit; +struct bcp47_parser : qi::grammar { + bcp47_parser() + : bcp47_parser::base_type(start) { using ascii::alnum; using ascii::alpha; + using ascii::char_; + using ascii::digit; + using ascii::no_case; + using qi::eoi; + using qi::inf; + using qi::lit; + using qi::repeat; using boost::spirit::qi::_1; start %= no_case[langtag | privateuse | grandfathered]; - langtag %= (language) [phoenix::ref(languageTag.language) = _1] - >> -("-" >> (script)[phoenix::ref(languageTag.script) = _1]) - >> -("-" >> (region)[phoenix::ref(languageTag.region) = _1]) - >> *("-" >> variant) - >> *("-" >> extension) - >> -("-" >> privateuse); + langtag %= (language)[phoenix::ref(languageTag.language) = _1] >> + -("-" >> (script)[phoenix::ref(languageTag.script) = _1]) >> + -("-" >> (region)[phoenix::ref(languageTag.region) = _1]) >> *("-" >> variant) >> + *("-" >> extension) >> -("-" >> privateuse); - language %= (repeat(2,3)[alpha] >> -("-" >> extlang)) // shortest ISO 639 code - // sometimes followed by extended language subtags - | repeat(4)[alpha] // or reserved for future use - | repeat(5,8)[alpha]; // or registered language subtag + language %= (repeat(2, 3)[alpha] >> -("-" >> extlang)) // shortest ISO 639 code + // sometimes followed by extended language subtags + | repeat(4)[alpha] // or reserved for future use + | repeat(5, 8)[alpha]; // or registered language subtag // We add lookaheads for "-"/eoi so that spurious matches on subtags don't prevent backtracking - extlang = repeat(3)[alpha] >> (&lit('-') | eoi) >> repeat(0,2)["-" >> repeat(3)[alpha] >> (&lit('-') | eoi)]; + extlang = repeat(3)[alpha] >> (&lit('-') | eoi) >> repeat(0, 2)["-" >> repeat(3)[alpha] >> (&lit('-') | eoi)]; script = repeat(4)[alpha] >> (&lit('-') | eoi); region = (repeat(2)[alpha] | repeat(3)[digit]) >> (&lit('-') | eoi); - variant = (repeat(5,8)[alnum] | (digit >> repeat(3,inf)[alnum])) >> (&lit('-') | eoi); + variant = (repeat(5, 8)[alnum] | (digit >> repeat(3, inf)[alnum])) >> (&lit('-') | eoi); - extension = singleton >> +("-" >> repeat(2,8)[alnum]) >> (&lit('-') | eoi); + extension = singleton >> +("-" >> repeat(2, 8)[alnum]) >> (&lit('-') | eoi); - singleton = digit | char_('a','w') | char_('y','z'); // "no-case" handles A-W and Y-Z + singleton = digit | char_('a', 'w') | char_('y', 'z'); // "no-case" handles A-W and Y-Z - privateuse = "x" >> +("-" >> repeat(1,8)[alnum]) >> (&lit('-') | eoi); + privateuse = "x" >> +("-" >> repeat(1, 8)[alnum]) >> (&lit('-') | eoi); grandfathered = regular | irregular; - irregular = lit("en-GB-oed") - | "i-ami" - | "i-bnn" - | "i-default" - | "i-enochian" - | "i-hak" - | "i-klingon" - | "i-lux" - | "i-mingo" - | "i-navajo" - | "i-pwn" - | "i-tao" - | "i-tay" - | "i-tsu" - | "sgn-BE-FR" - | "sgn-BE-NL" - | "sgn-CH-DE"; - - regular = lit("art-lojban") - | "cel-gaulish" - | "no-bok" - | "no-nyn" - | "zh-guoyu" - | "zh-hakka" - | "zh-min" - | "zh-min-nan" - | "zh-xiang"; + irregular = lit("en-GB-oed") | "i-ami" | "i-bnn" | "i-default" | "i-enochian" | "i-hak" | "i-klingon" | + "i-lux" | "i-mingo" | "i-navajo" | "i-pwn" | "i-tao" | "i-tay" | "i-tsu" | "sgn-BE-FR" | + "sgn-BE-NL" | "sgn-CH-DE"; + + regular = lit("art-lojban") | "cel-gaulish" | "no-bok" | "no-nyn" | "zh-guoyu" | "zh-hakka" | "zh-min" | + "zh-min-nan" | "zh-xiang"; } qi::rule start; @@ -209,11 +185,12 @@ LanguageTag LanguageTag::fromBCP47(const std::string& bcp47Tag) { } } -LanguageTag::LanguageTag(std::optional language_, std::optional script_, std::optional region_) - : language(std::move(language_)) - , script(std::move(script_)) - , region(std::move(region_)) -{} +LanguageTag::LanguageTag( + std::optional language_, std::optional script_, std::optional region_ +) + : language(std::move(language_)), + script(std::move(script_)), + region(std::move(region_)) {} std::string LanguageTag::toBCP47() const { std::stringstream bcp47; diff --git a/src/mbgl/text/language_tag.hpp b/src/mbgl/text/language_tag.hpp index a499cd32179..4e0457134d1 100644 --- a/src/mbgl/text/language_tag.hpp +++ b/src/mbgl/text/language_tag.hpp @@ -30,7 +30,9 @@ namespace mbgl { struct LanguageTag { LanguageTag() = default; - LanguageTag(std::optional language_, std::optional script_, std::optional region_); + LanguageTag( + std::optional language_, std::optional script_, std::optional region_ + ); static LanguageTag fromBCP47(const std::string& bcp47Tag); std::string toBCP47() const; diff --git a/src/mbgl/text/local_glyph_rasterizer.hpp b/src/mbgl/text/local_glyph_rasterizer.hpp index 4cc0c6a1820..69550b3ed8e 100644 --- a/src/mbgl/text/local_glyph_rasterizer.hpp +++ b/src/mbgl/text/local_glyph_rasterizer.hpp @@ -10,7 +10,7 @@ namespace mbgl { then generate a matching glyph object with a greyscale rasterization of the glyph and appropriate metrics. GlyphManager will then use TinySDF to transform the rasterized bitmap into an SDF. - + The JS equivalent of this functionality will only generate glyphs in the 'CJK Unified Ideographs' and 'Hangul Syllables' ranges, for which it can get away with rendering a fixed 30px square image and GlyphMetrics of: @@ -23,10 +23,10 @@ namespace mbgl { The JS equivalent also uses heuristic evaluation of the font stack name to control the font-weight it uses during rasterization. - + It is left to platform-specific implementation to decide how best to map a FontStack to a particular rasterization. - + The default implementation simply refuses to rasterize any glyphs. */ @@ -38,6 +38,7 @@ class LocalGlyphRasterizer { // virtual so that test harness can override platform-specific behavior virtual bool canRasterizeGlyph(const FontStack&, GlyphID); virtual Glyph rasterizeGlyph(const FontStack&, GlyphID); + private: class Impl; std::unique_ptr impl; diff --git a/src/mbgl/text/placement.cpp b/src/mbgl/text/placement.cpp index 0249aec59de..ff235b53d49 100644 --- a/src/mbgl/text/placement.cpp +++ b/src/mbgl/text/placement.cpp @@ -13,31 +13,31 @@ namespace mbgl { OpacityState::OpacityState(bool placed_, bool skipFade) - : opacity((skipFade && placed_) ? 1.0f : 0.0f) - , placed(placed_) -{ -} + : opacity((skipFade && placed_) ? 1.0f : 0.0f), + placed(placed_) {} -OpacityState::OpacityState(const OpacityState& prevState, float increment, bool placed_) : - opacity(std::fmax(0.0f, std::fmin(1.0f, prevState.opacity + (prevState.placed ? increment : -increment)))), - placed(placed_) {} +OpacityState::OpacityState(const OpacityState& prevState, float increment, bool placed_) + : opacity(std::fmax(0.0f, std::fmin(1.0f, prevState.opacity + (prevState.placed ? increment : -increment)))), + placed(placed_) {} bool OpacityState::isHidden() const { return opacity == 0 && !placed; } -JointOpacityState::JointOpacityState(bool placedText, bool placedIcon, bool skipFade) : - icon(OpacityState(placedIcon, skipFade)), - text(OpacityState(placedText, skipFade)) {} +JointOpacityState::JointOpacityState(bool placedText, bool placedIcon, bool skipFade) + : icon(OpacityState(placedIcon, skipFade)), + text(OpacityState(placedText, skipFade)) {} -JointOpacityState::JointOpacityState(const JointOpacityState& prevOpacityState, float increment, bool placedText, bool placedIcon) : - icon(OpacityState(prevOpacityState.icon, increment, placedIcon)), - text(OpacityState(prevOpacityState.text, increment, placedText)) {} +JointOpacityState::JointOpacityState( + const JointOpacityState& prevOpacityState, float increment, bool placedText, bool placedIcon +) + : icon(OpacityState(prevOpacityState.icon, increment, placedIcon)), + text(OpacityState(prevOpacityState.text, increment, placedText)) {} bool JointOpacityState::isHidden() const { return icon.isHidden() && text.isHidden(); } - + const CollisionGroups::CollisionGroup& CollisionGroups::get(const std::string& sourceID) { // The predicate/groupID mechanism allows for arbitrary grouping, // but the current interface defines one source == one group when @@ -45,12 +45,14 @@ const CollisionGroups::CollisionGroup& CollisionGroups::get(const std::string& s if (!crossSourceCollisions) { if (collisionGroups.find(sourceID) == collisionGroups.end()) { uint16_t nextGroupID = ++maxGroupID; - collisionGroups.emplace(sourceID, CollisionGroup( - nextGroupID, - std::optional([nextGroupID](const IndexedSubfeature& feature) -> bool { - return feature.collisionGroupId == nextGroupID; - }) - )); + collisionGroups.emplace( + sourceID, + CollisionGroup( + nextGroupID, std::optional([nextGroupID](const IndexedSubfeature& feature) -> bool { + return feature.collisionGroupId == nextGroupID; + }) + ) + ); } return collisionGroups[sourceID]; } else { @@ -68,12 +70,14 @@ class PlacementContext { std::reference_wrapper state; public: - PlacementContext(const SymbolBucket& bucket_, - const RenderTile& renderTile_, - const TransformState& state_, - float placementZoom, - CollisionGroups::CollisionGroup collisionGroup_, - std::optional avoidEdges_ = std::nullopt) + PlacementContext( + const SymbolBucket& bucket_, + const RenderTile& renderTile_, + const TransformState& state_, + float placementZoom, + CollisionGroups::CollisionGroup collisionGroup_, + std::optional avoidEdges_ = std::nullopt + ) : bucket(bucket_), renderTile(renderTile_), state(state_), @@ -107,13 +111,15 @@ class PlacementContext { bool pitchIconWithMap = getLayout().get() == AlignmentType::Map; SymbolPlacementType placementType = getLayout().get(); - mat4 textLabelPlaneMatrix = - getLabelPlaneMatrix(renderTile.get().matrix, pitchTextWithMap, rotateTextWithMap, state, pixelsToTileUnits); + mat4 textLabelPlaneMatrix = getLabelPlaneMatrix( + renderTile.get().matrix, pitchTextWithMap, rotateTextWithMap, state, pixelsToTileUnits + ); mat4 iconLabelPlaneMatrix = (rotateTextWithMap == rotateIconWithMap && pitchTextWithMap == pitchIconWithMap) ? textLabelPlaneMatrix : getLabelPlaneMatrix( - renderTile.get().matrix, pitchIconWithMap, rotateIconWithMap, state, pixelsToTileUnits); + renderTile.get().matrix, pitchIconWithMap, rotateIconWithMap, state, pixelsToTileUnits + ); CollisionGroups::CollisionGroup collisionGroup; ZoomEvaluatedSize partiallyEvaluatedTextSize; @@ -135,11 +141,11 @@ class PlacementContext { // This is the reverse of our normal policy of "fade in on pan", but should look like any other // collision and hopefully not be too noticeable. // See https://github.com/mapbox/mapbox-gl-native/issues/12683 - bool alwaysShowText = - textAllowOverlap && (iconAllowOverlap || !(getBucket().hasIconData() || getBucket().hasSdfIconData()) || - getLayout().get()); - bool alwaysShowIcon = - iconAllowOverlap && (textAllowOverlap || !getBucket().hasTextData() || getLayout().get()); + bool alwaysShowText = textAllowOverlap && + (iconAllowOverlap || !(getBucket().hasIconData() || getBucket().hasSdfIconData()) || + getLayout().get()); + bool alwaysShowIcon = iconAllowOverlap && + (textAllowOverlap || !getBucket().hasTextData() || getLayout().get()); bool hasIconTextFit = getLayout().get() != IconTextFitType::None; @@ -148,14 +154,16 @@ class PlacementContext { // PlacementController implemenation -PlacementController::PlacementController() : placement(makeMutable()) {} +PlacementController::PlacementController() + : placement(makeMutable()) {} void PlacementController::setPlacement(Immutable placement_) { placement = std::move(placement_); stale = false; } -bool PlacementController::placementIsRecent(TimePoint now, const float zoom, std::optional periodOverride) const { +bool PlacementController::placementIsRecent(TimePoint now, const float zoom, std::optional periodOverride) + const { if (!placement->transitionsEnabled()) return false; auto updatePeriod = periodOverride ? *periodOverride : placement->getUpdatePeriod(zoom); @@ -173,8 +181,9 @@ bool PlacementController::hasTransitions(TimePoint now) const { // Placement implementation -Placement::Placement(std::shared_ptr updateParameters_, - std::optional> prevPlacement_) +Placement::Placement( + std::shared_ptr updateParameters_, std::optional> prevPlacement_ +) : updateParameters(std::move(updateParameters_)), collisionIndex(updateParameters->transformState, updateParameters->mode), transitionOptions(updateParameters->transitionOptions), @@ -188,7 +197,9 @@ Placement::Placement(std::shared_ptr updateParameters_, } } -Placement::Placement() : collisionIndex({}, MapMode::Static), collisionGroups(true) {} +Placement::Placement() + : collisionIndex({}, MapMode::Static), + collisionGroups(true) {} Placement::~Placement() = default; @@ -208,14 +219,16 @@ void Placement::placeLayer(const RenderLayer& layer, std::set& seenCro } namespace { -Point calculateVariableLayoutOffset(style::SymbolAnchorType anchor, - float width, - float height, - std::array offset, - float textBoxScale, - bool rotateWithMap, - bool pitchWithMap, - float bearing) { +Point calculateVariableLayoutOffset( + style::SymbolAnchorType anchor, + float width, + float height, + std::array offset, + float textBoxScale, + bool rotateWithMap, + bool pitchWithMap, + float bearing +) { AnchorAlignment alignment = AnchorAlignment::getAnchorAlignment(anchor); float shiftX = -(alignment.horizontalAlign - 0.5f) * width; float shiftY = -(alignment.verticalAlign - 0.5f) * height; @@ -232,12 +245,13 @@ void Placement::placeSymbolBucket(const BucketPlacementData& params, std::set(params.bucket.get()); const RenderTile& renderTile = params.tile; - PlacementContext ctx{symbolBucket, - params.tile, - collisionIndex.getTransformState(), - placementZoom, - collisionGroups.get(params.sourceId), - getAvoidEdges(symbolBucket, renderTile.matrix)}; + PlacementContext ctx{ + symbolBucket, + params.tile, + collisionIndex.getTransformState(), + placementZoom, + collisionGroups.get(params.sourceId), + getAvoidEdges(symbolBucket, renderTile.matrix)}; for (const SymbolInstance& symbol : getSortedSymbols(params, ctx.pixelRatio)) { if (seenCrossTileIDs.count(symbol.crossTileID) != 0u) continue; placeSymbol(symbol, ctx); @@ -245,7 +259,7 @@ void Placement::placeSymbolBucket(const BucketPlacementData& params, std::set{false, false}; }; @@ -357,8 +375,7 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons placeText = placed.first; offscreen &= placed.second; - } else if (!symbolInstance.textCollisionFeature.alongLine && - !symbolInstance.textCollisionFeature.boxes.empty()) { + } else if (!symbolInstance.textCollisionFeature.alongLine && !symbolInstance.textCollisionFeature.boxes.empty()) { // If this symbol was in the last placement, shift the previously used // anchor to the front of the anchor list, only if the previous anchor // is still in the anchor list. @@ -381,8 +398,8 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons } } - const bool doVariableIconPlacement = - ctx.hasIconTextFit && !ctx.iconAllowOverlap && symbolInstance.placedIconIndex; + const bool doVariableIconPlacement = ctx.hasIconTextFit && !ctx.iconAllowOverlap && + symbolInstance.placedIconIndex; const auto placeFeatureForVariableAnchors = [&](const CollisionFeature& textCollisionFeature, style::TextWritingModeType orientation, const CollisionFeature& iconCollisionFeature) { @@ -398,51 +415,57 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons // NOLINTNEXTLINE(clang-analyzer-core.DivideZero) auto anchor = variableTextAnchors[i % anchorsSize]; const bool allowOverlap = (i >= anchorsSize); - shift = calculateVariableLayoutOffset(anchor, - width, - height, - symbolInstance.variableTextOffset, - textBoxScale, - ctx.rotateTextWithMap, - ctx.pitchTextWithMap, - static_cast(ctx.getTransformState().getBearing())); + shift = calculateVariableLayoutOffset( + anchor, + width, + height, + symbolInstance.variableTextOffset, + textBoxScale, + ctx.rotateTextWithMap, + ctx.pitchTextWithMap, + static_cast(ctx.getTransformState().getBearing()) + ); textBoxes.clear(); if (!canPlaceAtVariableAnchor( - textBox, anchor, shift, variableTextAnchors, posMatrix, ctx.pixelRatio)) { + textBox, anchor, shift, variableTextAnchors, posMatrix, ctx.pixelRatio + )) { continue; } - placedFeature = collisionIndex.placeFeature(textCollisionFeature, - shift, - posMatrix, - mat4(), - ctx.pixelRatio, - placedSymbol, - ctx.scale, - fontSize, - allowOverlap, - ctx.pitchTextWithMap, - showCollisionBoxes, - ctx.avoidEdges, - collisionGroup.second, - textBoxes); + placedFeature = collisionIndex.placeFeature( + textCollisionFeature, + shift, + posMatrix, + mat4(), + ctx.pixelRatio, + placedSymbol, + ctx.scale, + fontSize, + allowOverlap, + ctx.pitchTextWithMap, + showCollisionBoxes, + ctx.avoidEdges, + collisionGroup.second, + textBoxes + ); if (doVariableIconPlacement) { - auto placedIconFeature = - collisionIndex.placeFeature(iconCollisionFeature, - shift, - posMatrix, - ctx.iconLabelPlaneMatrix, - ctx.pixelRatio, - placedSymbol, - ctx.scale, - fontSize, - ctx.iconAllowOverlap, - ctx.pitchTextWithMap, // TODO: shall it be pitchIconWithMap? - showCollisionBoxes, - ctx.avoidEdges, - collisionGroup.second, - iconBoxes); + auto placedIconFeature = collisionIndex.placeFeature( + iconCollisionFeature, + shift, + posMatrix, + ctx.iconLabelPlaneMatrix, + ctx.pixelRatio, + placedSymbol, + ctx.scale, + fontSize, + ctx.iconAllowOverlap, + ctx.pitchTextWithMap, // TODO: shall it be pitchIconWithMap? + showCollisionBoxes, + ctx.avoidEdges, + collisionGroup.second, + iconBoxes + ); iconBoxes.clear(); if (!placedIconFeature.first) continue; } @@ -466,7 +489,8 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons variableOffsets.insert(std::make_pair( symbolInstance.crossTileID, VariableOffset{ - symbolInstance.variableTextOffset, width, height, anchor, textBoxScale, prevAnchor})); + symbolInstance.variableTextOffset, width, height, anchor, textBoxScale, prevAnchor} + )); if (bucket.allowVerticalPlacement) { placedOrientations.emplace(symbolInstance.crossTileID, orientation); @@ -479,18 +503,21 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons }; const auto placeHorizontal = [&] { - return placeFeatureForVariableAnchors(symbolInstance.textCollisionFeature, - style::TextWritingModeType::Horizontal, - symbolInstance.iconCollisionFeature); + return placeFeatureForVariableAnchors( + symbolInstance.textCollisionFeature, + style::TextWritingModeType::Horizontal, + symbolInstance.iconCollisionFeature + ); }; const auto placeVertical = [&] { if (bucket.allowVerticalPlacement && !placed.first && symbolInstance.verticalTextCollisionFeature) { - return placeFeatureForVariableAnchors(*symbolInstance.verticalTextCollisionFeature, - style::TextWritingModeType::Vertical, - symbolInstance.verticalIconCollisionFeature - ? *symbolInstance.verticalIconCollisionFeature - : symbolInstance.iconCollisionFeature); + return placeFeatureForVariableAnchors( + *symbolInstance.verticalTextCollisionFeature, + style::TextWritingModeType::Vertical, + symbolInstance.verticalIconCollisionFeature ? *symbolInstance.verticalIconCollisionFeature + : symbolInstance.iconCollisionFeature + ); } return std::pair{false, false}; }; @@ -522,20 +549,22 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons const PlacedSymbol& placedSymbol = iconBuffer.placedSymbols.at(*symbolInstance.placedIconIndex); const float fontSize = evaluateSizeForFeature(ctx.partiallyEvaluatedIconSize, placedSymbol); const auto& placeIconFeature = [&](const CollisionFeature& collisionFeature) { - return collisionIndex.placeFeature(collisionFeature, - shift, - posMatrix, - ctx.iconLabelPlaneMatrix, - ctx.pixelRatio, - placedSymbol, - ctx.scale, - fontSize, - ctx.iconAllowOverlap, - ctx.pitchTextWithMap, - showCollisionBoxes, - ctx.avoidEdges, - collisionGroup.second, - iconBoxes); + return collisionIndex.placeFeature( + collisionFeature, + shift, + posMatrix, + ctx.iconLabelPlaneMatrix, + ctx.pixelRatio, + placedSymbol, + ctx.scale, + fontSize, + ctx.iconAllowOverlap, + ctx.pitchTextWithMap, + showCollisionBoxes, + ctx.avoidEdges, + collisionGroup.second, + iconBoxes + ); }; std::pair placedIcon = {false, false}; @@ -562,33 +591,41 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons if (placeText) { if (placedVerticalText.first && symbolInstance.verticalTextCollisionFeature) { - collisionIndex.insertFeature(*symbolInstance.verticalTextCollisionFeature, - textBoxes, - ctx.getLayout().get(), - bucket.bucketInstanceId, - collisionGroup.first); + collisionIndex.insertFeature( + *symbolInstance.verticalTextCollisionFeature, + textBoxes, + ctx.getLayout().get(), + bucket.bucketInstanceId, + collisionGroup.first + ); } else { - collisionIndex.insertFeature(symbolInstance.textCollisionFeature, - textBoxes, - ctx.getLayout().get(), - bucket.bucketInstanceId, - collisionGroup.first); + collisionIndex.insertFeature( + symbolInstance.textCollisionFeature, + textBoxes, + ctx.getLayout().get(), + bucket.bucketInstanceId, + collisionGroup.first + ); } } if (placeIcon) { if (placedVerticalIcon.first && symbolInstance.verticalIconCollisionFeature) { - collisionIndex.insertFeature(*symbolInstance.verticalIconCollisionFeature, - iconBoxes, - ctx.getLayout().get(), - bucket.bucketInstanceId, - collisionGroup.first); + collisionIndex.insertFeature( + *symbolInstance.verticalIconCollisionFeature, + iconBoxes, + ctx.getLayout().get(), + bucket.bucketInstanceId, + collisionGroup.first + ); } else { - collisionIndex.insertFeature(symbolInstance.iconCollisionFeature, - iconBoxes, - ctx.getLayout().get(), - bucket.bucketInstanceId, - collisionGroup.first); + collisionIndex.insertFeature( + symbolInstance.iconCollisionFeature, + iconBoxes, + ctx.getLayout().get(), + bucket.bucketInstanceId, + collisionGroup.first + ); } } @@ -611,7 +648,8 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons } JointPlacement result( - placeText || ctx.alwaysShowText, placeIcon || ctx.alwaysShowIcon, offscreen || bucket.justReloaded); + placeText || ctx.alwaysShowText, placeIcon || ctx.alwaysShowIcon, offscreen || bucket.justReloaded + ); placements.emplace(symbolInstance.crossTileID, result); newSymbolPlaced(symbolInstance, ctx, result, ctx.placementType, textBoxes, iconBoxes); return result; @@ -619,9 +657,9 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons namespace { -SymbolInstanceReferences getBucketSymbols(const SymbolBucket& bucket, - const std::optional& sortKeyRange, - double bearing) { +SymbolInstanceReferences getBucketSymbols( + const SymbolBucket& bucket, const std::optional& sortKeyRange, double bearing +) { if (bucket.layout->get() == style::SymbolZOrderType::ViewportY) { auto sortedSymbols = bucket.getSortedSymbols(static_cast(bearing)); // Place in the reverse order than draw i.e., starting from the foreground elements. @@ -635,8 +673,9 @@ SymbolInstanceReferences getBucketSymbols(const SymbolBucket& bucket, SymbolInstanceReferences Placement::getSortedSymbols(const BucketPlacementData& params, float) { const auto& bucket = static_cast(params.bucket.get()); - SymbolInstanceReferences sortedSymbols = - getBucketSymbols(bucket, params.sortKeyRange, collisionIndex.getTransformState().getBearing()); + SymbolInstanceReferences sortedSymbols = getBucketSymbols( + bucket, params.sortKeyRange, collisionIndex.getTransformState().getBearing() + ); auto* previousPlacement = getPrevPlacement(); if (previousPlacement && isTiltedView()) { std::stable_sort( @@ -655,7 +694,8 @@ SymbolInstanceReferences Placement::getSortedSymbols(const BucketPlacementData& } // a < b, if 'a' was shown and 'b' was hidden. return aPlacement->placed() && !bPlacement->placed(); - }); + } + ); } return sortedSymbols; } @@ -670,17 +710,27 @@ void Placement::commit() { for (auto& jointPlacement : placements) { auto prevOpacity = getPrevPlacement()->opacities.find(jointPlacement.first); if (prevOpacity != getPrevPlacement()->opacities.end()) { - opacities.emplace(jointPlacement.first, JointOpacityState(prevOpacity->second, increment, jointPlacement.second.text, jointPlacement.second.icon)); - placementChanged = placementChanged || - jointPlacement.second.icon != prevOpacity->second.icon.placed || - jointPlacement.second.text != prevOpacity->second.text.placed; + opacities.emplace( + jointPlacement.first, + JointOpacityState( + prevOpacity->second, increment, jointPlacement.second.text, jointPlacement.second.icon + ) + ); + placementChanged = placementChanged || jointPlacement.second.icon != prevOpacity->second.icon.placed || + jointPlacement.second.text != prevOpacity->second.text.placed; } else { - opacities.emplace(jointPlacement.first, JointOpacityState(jointPlacement.second.text, jointPlacement.second.icon, jointPlacement.second.skipFade)); + opacities.emplace( + jointPlacement.first, + JointOpacityState( + jointPlacement.second.text, jointPlacement.second.icon, jointPlacement.second.skipFade + ) + ); placementChanged = placementChanged || jointPlacement.second.icon || jointPlacement.second.text; } } - // copy and update values from the previous placement that aren't in the current placement but haven't finished fading + // copy and update values from the previous placement that aren't in the current placement but haven't finished + // fading for (auto& prevOpacity : getPrevPlacement()->opacities) { if (opacities.find(prevOpacity.first) == opacities.end()) { JointOpacityState jointOpacity(prevOpacity.second, increment, false, false); @@ -695,7 +745,8 @@ void Placement::commit() { const uint32_t crossTileID = prevOffset.first; auto foundOffset = variableOffsets.find(crossTileID); auto foundOpacity = opacities.find(crossTileID); - if (foundOffset == variableOffsets.end() && foundOpacity != opacities.end() && !foundOpacity->second.isHidden()) { + if (foundOffset == variableOffsets.end() && foundOpacity != opacities.end() && + !foundOpacity->second.isHidden()) { variableOffsets[prevOffset.first] = prevOffset.second; } } @@ -704,7 +755,8 @@ void Placement::commit() { const uint32_t crossTileID = prevOrientation.first; auto foundOrientation = placedOrientations.find(crossTileID); auto foundOpacity = opacities.find(crossTileID); - if (foundOrientation == placedOrientations.end() && foundOpacity != opacities.end() && !foundOpacity->second.isHidden()) { + if (foundOrientation == placedOrientations.end() && foundOpacity != opacities.end() && + !foundOpacity->second.isHidden()) { placedOrientations[prevOrientation.first] = prevOrientation.second; } } @@ -722,22 +774,33 @@ void Placement::updateLayerBuckets(const RenderLayer& layer, const TransformStat } namespace { -Point calculateVariableRenderShift(style::SymbolAnchorType anchor, float width, float height, std::array textOffset, float textBoxScale, float renderTextSize) { +Point calculateVariableRenderShift( + style::SymbolAnchorType anchor, + float width, + float height, + std::array textOffset, + float textBoxScale, + float renderTextSize +) { AnchorAlignment alignment = AnchorAlignment::getAnchorAlignment(anchor); float shiftX = -(alignment.horizontalAlign - 0.5f) * width; float shiftY = -(alignment.verticalAlign - 0.5f) * height; auto variablOffset = SymbolLayout::evaluateVariableOffset(anchor, textOffset); - return { (shiftX / textBoxScale + variablOffset[0]) * renderTextSize, - (shiftY / textBoxScale + variablOffset[1]) * renderTextSize }; + return { + (shiftX / textBoxScale + variablOffset[0]) * renderTextSize, + (shiftY / textBoxScale + variablOffset[1]) * renderTextSize}; } } // namespace -bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const TransformState& state, const RenderTile& tile) const { +bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const TransformState& state, const RenderTile& tile) + const { using namespace style; const auto& layout = *bucket.layout; const bool alongLine = layout.get() != SymbolPlacementType::Point; const bool hasVariableAnchors = !layout.get().empty() && bucket.hasTextData(); - const bool updateTextFitIcon = layout.get() != IconTextFitType::None && (bucket.allowVerticalPlacement || hasVariableAnchors) && (bucket.hasIconData() || bucket.hasSdfIconData()); + const bool updateTextFitIcon = layout.get() != IconTextFitType::None && + (bucket.allowVerticalPlacement || hasVariableAnchors) && + (bucket.hasIconData() || bucket.hasSdfIconData()); bool result = false; if (alongLine) { @@ -745,15 +808,31 @@ bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const Transfor const bool pitchWithMap = layout.get() == style::AlignmentType::Map; const bool keepUpright = layout.get(); if (bucket.hasSdfIconData()) { - reprojectLineLabels(bucket.sdfIcon.dynamicVertices, bucket.sdfIcon.placedSymbols, - tile.matrix, pitchWithMap, true /*rotateWithMap*/, keepUpright, - tile, *bucket.iconSizeBinder, state); + reprojectLineLabels( + bucket.sdfIcon.dynamicVertices, + bucket.sdfIcon.placedSymbols, + tile.matrix, + pitchWithMap, + true /*rotateWithMap*/, + keepUpright, + tile, + *bucket.iconSizeBinder, + state + ); result = true; } if (bucket.hasIconData()) { - reprojectLineLabels(bucket.icon.dynamicVertices, bucket.icon.placedSymbols, - tile.matrix, pitchWithMap, true /*rotateWithMap*/, keepUpright, - tile, *bucket.iconSizeBinder, state); + reprojectLineLabels( + bucket.icon.dynamicVertices, + bucket.icon.placedSymbols, + tile.matrix, + pitchWithMap, + true /*rotateWithMap*/, + keepUpright, + tile, + *bucket.iconSizeBinder, + state + ); result = true; } } @@ -761,9 +840,17 @@ bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const Transfor if (bucket.hasTextData() && layout.get() == AlignmentType::Map) { const bool pitchWithMap = layout.get() == style::AlignmentType::Map; const bool keepUpright = layout.get(); - reprojectLineLabels(bucket.text.dynamicVertices, bucket.text.placedSymbols, - tile.matrix, pitchWithMap, true /*rotateWithMap*/, keepUpright, - tile, *bucket.textSizeBinder, state); + reprojectLineLabels( + bucket.text.dynamicVertices, + bucket.text.placedSymbols, + tile.matrix, + pitchWithMap, + true /*rotateWithMap*/, + keepUpright, + tile, + *bucket.textSizeBinder, + state + ); result = true; } } else if (hasVariableAnchors) { @@ -771,11 +858,14 @@ bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const Transfor bucket.hasVariablePlacement = false; const auto partiallyEvaluatedSize = bucket.textSizeBinder->evaluateForZoom(static_cast(state.getZoom())); - const auto tileScale = static_cast(std::pow(2, state.getZoom() - tile.getOverscaledTileID().overscaledZ)); + const auto tileScale = static_cast(std::pow(2, state.getZoom() - tile.getOverscaledTileID().overscaledZ) + ); const bool rotateWithMap = layout.get() == AlignmentType::Map; const bool pitchWithMap = layout.get() == AlignmentType::Map; const float pixelsToTileUnits = tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom())); - const auto labelPlaneMatrix = getLabelPlaneMatrix(tile.matrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); + const auto labelPlaneMatrix = getLabelPlaneMatrix( + tile.matrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits + ); std::unordered_map>> placedTextShifts; for (std::size_t i = 0; i < bucket.text.placedSymbols.size(); ++i) { @@ -797,40 +887,44 @@ bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const Transfor } else { const Point tileAnchor = symbol.anchorPoint; const auto projectedAnchor = project(tileAnchor, pitchWithMap ? tile.matrix : labelPlaneMatrix); - const float perspectiveRatio = 0.5f + 0.5f * (state.getCameraToCenterDistance() / projectedAnchor.second); - float renderTextSize = evaluateSizeForFeature(partiallyEvaluatedSize, symbol) * perspectiveRatio / util::ONE_EM; + const float perspectiveRatio = 0.5f + + 0.5f * (state.getCameraToCenterDistance() / projectedAnchor.second); + float renderTextSize = evaluateSizeForFeature(partiallyEvaluatedSize, symbol) * perspectiveRatio / + util::ONE_EM; if (pitchWithMap) { // Go from size in pixels to equivalent size in tile units renderTextSize *= bucket.tilePixelRatio / tileScale; } auto shift = calculateVariableRenderShift( - (*variableOffset).anchor, - (*variableOffset).width, - (*variableOffset).height, - (*variableOffset).offset, - (*variableOffset).textBoxScale, - renderTextSize); + (*variableOffset).anchor, + (*variableOffset).width, + (*variableOffset).height, + (*variableOffset).offset, + (*variableOffset).textBoxScale, + renderTextSize + ); // Usual case is that we take the projected anchor and add the pixel-based shift // calculated above. In the (somewhat weird) case of pitch-aligned text, we add an equivalent // tile-unit based shift to the anchor before projecting to the label plane. Point shiftedAnchor; if (pitchWithMap) { - shiftedAnchor = project(Point(tileAnchor.x + shift.x, tileAnchor.y + shift.y), - labelPlaneMatrix).first; + shiftedAnchor = + project(Point(tileAnchor.x + shift.x, tileAnchor.y + shift.y), labelPlaneMatrix).first; } else if (rotateWithMap) { auto rotated = util::rotate(shift, -state.getPitch()); - shiftedAnchor = Point(projectedAnchor.first.x + rotated.x, - projectedAnchor.first.y + rotated.y); + shiftedAnchor = Point( + projectedAnchor.first.x + rotated.x, projectedAnchor.first.y + rotated.y + ); } else { - shiftedAnchor = Point(projectedAnchor.first.x + shift.x, - projectedAnchor.first.y + shift.y); + shiftedAnchor = Point(projectedAnchor.first.x + shift.x, projectedAnchor.first.y + shift.y); } if (updateTextFitIcon && symbol.placedIconIndex) { - placedTextShifts.emplace(*symbol.placedIconIndex, - std::pair>{i, shiftedAnchor}); + placedTextShifts.emplace( + *symbol.placedIconIndex, std::pair>{i, shiftedAnchor} + ); } for (std::size_t j = 0; j < symbol.glyphOffsets.size(); ++j) { @@ -890,9 +984,9 @@ bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const Transfor return result; } -void Placement::updateBucketOpacities(SymbolBucket& bucket, - const TransformState& state, - std::set& seenCrossTileIDs) const { +void Placement::updateBucketOpacities( + SymbolBucket& bucket, const TransformState& state, std::set& seenCrossTileIDs +) const { if (bucket.hasTextData()) bucket.text.opacityVertices.clear(); if (bucket.hasIconData()) bucket.icon.opacityVertices.clear(); if (bucket.hasSdfIconData()) bucket.sdfIcon.opacityVertices.clear(); @@ -916,9 +1010,13 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, // See https://github.com/mapbox/mapbox-gl-native/issues/12483 // Prevent a flickering issue when showing a symbol allowing overlap. const JointOpacityState defaultOpacityState( - bucket.justReloaded && textAllowOverlap && (iconAllowOverlap || !(bucket.hasIconData() || bucket.hasSdfIconData()) || bucket.layout->get()), - bucket.justReloaded && iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || bucket.layout->get()), - true); + bucket.justReloaded && textAllowOverlap && + (iconAllowOverlap || !(bucket.hasIconData() || bucket.hasSdfIconData()) || + bucket.layout->get()), + bucket.justReloaded && iconAllowOverlap && + (textAllowOverlap || !bucket.hasTextData() || bucket.layout->get()), + true + ); for (SymbolInstance& symbolInstance : bucket.symbolInstances) { bool isDuplicate = seenCrossTileIDs.count(symbolInstance.crossTileID) > 0; @@ -935,7 +1033,9 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, if (symbolInstance.hasText()) { size_t textOpacityVerticesSize = 0u; - const auto& opacityVertex = SymbolSDFTextProgram::opacityVertex(opacityState.text.placed, opacityState.text.opacity); + const auto& opacityVertex = SymbolSDFTextProgram::opacityVertex( + opacityState.text.placed, opacityState.text.opacity + ); if (symbolInstance.placedRightTextIndex) { textOpacityVerticesSize += symbolInstance.rightJustifiedGlyphQuadsSize * 4; PlacedSymbol& placed = bucket.text.placedSymbols[*symbolInstance.placedRightTextIndex]; @@ -974,10 +1074,11 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, } if (symbolInstance.hasIcon()) { size_t iconOpacityVerticesSize = 0u; - const auto& opacityVertex = - SymbolIconProgram::opacityVertex(opacityState.icon.placed, opacityState.icon.opacity); + const auto& opacityVertex = SymbolIconProgram::opacityVertex( + opacityState.icon.placed, opacityState.icon.opacity + ); auto& iconBuffer = symbolInstance.hasSdfIcon() ? bucket.sdfIcon : bucket.icon; - + if (symbolInstance.placedIconIndex) { iconOpacityVerticesSize += symbolInstance.iconQuadsSize * 4; iconBuffer.placedSymbols[*symbolInstance.placedIconIndex].hidden = opacityState.isHidden(); @@ -1001,7 +1102,8 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, auto updateTextCollisionBox = [this, &bucket, &symbolInstance, &state, variablePlacement, rotateWithMap, pitchWithMap]( - const auto& feature, const bool placed) { + const auto& feature, const bool placed + ) { Point shift{0.0f, 0.0f}; if (feature.alongLine) { return shift; @@ -1015,14 +1117,16 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, // successfully placed position (so you can visualize what collision // just made the symbol disappear, and the most likely place for the // symbol to come back) - shift = calculateVariableLayoutOffset(variableOffset.anchor, - variableOffset.width, - variableOffset.height, - variableOffset.offset, - variableOffset.textBoxScale, - rotateWithMap, - pitchWithMap, - static_cast(state.getBearing())); + shift = calculateVariableLayoutOffset( + variableOffset.anchor, + variableOffset.width, + variableOffset.height, + variableOffset.offset, + variableOffset.textBoxScale, + rotateWithMap, + pitchWithMap, + static_cast(state.getBearing()) + ); } else { // No offset -> this symbol hasn't been placed since coming on-screen // No single box is particularly meaningful and all of them would be too noisy @@ -1043,14 +1147,14 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, if (circles != collisionCircles.end()) { for (const auto& circle : circles->second) { const auto& dynamicVertex = CollisionBoxProgram::dynamicVertex(placed, !circle.isCircle(), {}); - isText ? bucket.textCollisionCircle->dynamicVertices.extend(4, dynamicVertex): - bucket.iconCollisionCircle->dynamicVertices.extend(4, dynamicVertex); + isText ? bucket.textCollisionCircle->dynamicVertices.extend(4, dynamicVertex) + : bucket.iconCollisionCircle->dynamicVertices.extend(4, dynamicVertex); } } else { // This feature was not placed, because it was not loaded or from a fading tile. Apply default values. static const auto dynamicVertex = CollisionBoxProgram::dynamicVertex(placed, false /*not used*/, {}); - isText ? bucket.textCollisionCircle->dynamicVertices.extend(4 * feature.boxes.size(), dynamicVertex): - bucket.iconCollisionCircle->dynamicVertices.extend(4 * feature.boxes.size(), dynamicVertex); + isText ? bucket.textCollisionCircle->dynamicVertices.extend(4 * feature.boxes.size(), dynamicVertex) + : bucket.iconCollisionCircle->dynamicVertices.extend(4 * feature.boxes.size(), dynamicVertex); } }; Point textShift{0.0f, 0.0f}; @@ -1058,13 +1162,23 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, if (bucket.hasTextCollisionBoxData()) { textShift = updateTextCollisionBox(symbolInstance.textCollisionFeature, opacityState.text.placed); if (bucket.allowVerticalPlacement && symbolInstance.verticalTextCollisionFeature) { - verticalTextShift = updateTextCollisionBox(*symbolInstance.verticalTextCollisionFeature, opacityState.text.placed); + verticalTextShift = updateTextCollisionBox( + *symbolInstance.verticalTextCollisionFeature, opacityState.text.placed + ); } } if (bucket.hasIconCollisionBoxData()) { - updateIconCollisionBox(symbolInstance.iconCollisionFeature, opacityState.icon.placed, hasIconTextFit ? textShift : Point{0.0f, 0.0f}); + updateIconCollisionBox( + symbolInstance.iconCollisionFeature, + opacityState.icon.placed, + hasIconTextFit ? textShift : Point{0.0f, 0.0f} + ); if (bucket.allowVerticalPlacement && symbolInstance.verticalIconCollisionFeature) { - updateIconCollisionBox(*symbolInstance.verticalIconCollisionFeature, opacityState.text.placed, hasIconTextFit ? verticalTextShift : Point{0.0f, 0.0f}); + updateIconCollisionBox( + *symbolInstance.verticalIconCollisionFeature, + opacityState.text.placed, + hasIconTextFit ? verticalTextShift : Point{0.0f, 0.0f} + ); } } @@ -1084,17 +1198,23 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, } namespace { -std::optional justificationToIndex(style::TextJustifyType justify, const SymbolInstance& symbolInstance, style::TextWritingModeType orientation) { +std::optional justificationToIndex( + style::TextJustifyType justify, const SymbolInstance& symbolInstance, style::TextWritingModeType orientation +) { // Vertical symbol has just one justification, style::TextJustifyType::Left. if (orientation == style::TextWritingModeType::Vertical) { return symbolInstance.placedVerticalTextIndex; } - switch(justify) { - case style::TextJustifyType::Right: return symbolInstance.placedRightTextIndex; - case style::TextJustifyType::Center: return symbolInstance.placedCenterTextIndex; - case style::TextJustifyType::Left: return symbolInstance.placedLeftTextIndex; - case style::TextJustifyType::Auto: break; + switch (justify) { + case style::TextJustifyType::Right: + return symbolInstance.placedRightTextIndex; + case style::TextJustifyType::Center: + return symbolInstance.placedCenterTextIndex; + case style::TextJustifyType::Left: + return symbolInstance.placedLeftTextIndex; + case style::TextJustifyType::Auto: + break; } assert(false); return std::nullopt; @@ -1103,12 +1223,14 @@ std::optional justificationToIndex(style::TextJustifyType justify, const const style::TextJustifyType justifyTypes[] = { style::TextJustifyType::Right, style::TextJustifyType::Center, style::TextJustifyType::Left}; -} // namespace +} // namespace -void Placement::markUsedJustification(SymbolBucket& bucket, - style::TextVariableAnchorType placedAnchor, - const SymbolInstance& symbolInstance, - style::TextWritingModeType orientation) const { +void Placement::markUsedJustification( + SymbolBucket& bucket, + style::TextVariableAnchorType placedAnchor, + const SymbolInstance& symbolInstance, + style::TextWritingModeType orientation +) const { style::TextJustifyType anchorJustify = getAnchorJustification(placedAnchor); assert(anchorJustify != style::TextJustifyType::Auto); const std::optional& autoIndex = justificationToIndex(anchorJustify, symbolInstance, orientation); @@ -1128,13 +1250,15 @@ void Placement::markUsedJustification(SymbolBucket& bucket, } } -void Placement::markUsedOrientation(SymbolBucket& bucket, - style::TextWritingModeType orientation, - const SymbolInstance& symbolInstance) const { - auto horizontal = orientation == style::TextWritingModeType::Horizontal ? - std::optional(orientation) : std::nullopt; - auto vertical = orientation == style::TextWritingModeType::Vertical ? - std::optional(orientation) : std::nullopt; +void Placement::markUsedOrientation( + SymbolBucket& bucket, style::TextWritingModeType orientation, const SymbolInstance& symbolInstance +) const { + auto horizontal = orientation == style::TextWritingModeType::Horizontal + ? std::optional(orientation) + : std::nullopt; + auto vertical = orientation == style::TextWritingModeType::Vertical + ? std::optional(orientation) + : std::nullopt; if (symbolInstance.placedRightTextIndex) { bucket.text.placedSymbols.at(*symbolInstance.placedRightTextIndex).placedOrientation = horizontal; @@ -1169,7 +1293,9 @@ bool Placement::isTiltedView() const { float Placement::symbolFadeChange(TimePoint now) const { if (transitionsEnabled() && transitionOptions.duration.value_or(util::DEFAULT_TRANSITION_DURATION) > Milliseconds(0)) { - return std::chrono::duration(now - commitTime) / transitionOptions.duration.value_or(util::DEFAULT_TRANSITION_DURATION) + prevZoomAdjustment; + return std::chrono::duration(now - commitTime) / + transitionOptions.duration.value_or(util::DEFAULT_TRANSITION_DURATION) + + prevZoomAdjustment; } return 1.0; } @@ -1191,8 +1317,9 @@ const JointPlacement* Placement::getSymbolPlacement(const SymbolInstance& symbol Duration Placement::getUpdatePeriod(const float zoom) const { // Even if transitionOptions.duration is set to a value < 300ms, we still wait for this default transition duration // before attempting another placement operation. - const auto fadeDuration = std::max(util::DEFAULT_TRANSITION_DURATION, - transitionOptions.duration.value_or(util::DEFAULT_TRANSITION_DURATION)); + const auto fadeDuration = std::max( + util::DEFAULT_TRANSITION_DURATION, transitionOptions.duration.value_or(util::DEFAULT_TRANSITION_DURATION) + ); return std::chrono::duration_cast(fadeDuration * (1.0 - zoomAdjustment(zoom))); } @@ -1214,7 +1341,7 @@ const std::vector& Placement::getPlacedSymbolsData() const { const CollisionIndex& Placement::getCollisionIndex() const { return collisionIndex; } - + const RetainedQueryData& Placement::getQueryData(uint32_t bucketInstanceId) const { auto it = retainedQueryData.find(bucketInstanceId); if (it == retainedQueryData.end()) { @@ -1241,7 +1368,8 @@ void StaticPlacement::commit() { for (auto& jointPlacement : placements) { opacities.emplace( jointPlacement.first, - JointOpacityState(jointPlacement.second.text, jointPlacement.second.icon, jointPlacement.second.skipFade)); + JointOpacityState(jointPlacement.second.text, jointPlacement.second.icon, jointPlacement.second.skipFade) + ); } } @@ -1249,7 +1377,10 @@ void StaticPlacement::commit() { struct Intersection { Intersection(const SymbolInstance& symbol_, PlacementContext ctx_, IntersectStatus status_, std::size_t priority_) - : symbol(symbol_), ctx(std::move(ctx_)), status(status_), priority(priority_) {} + : symbol(symbol_), + ctx(std::move(ctx_)), + status(status_), + priority(priority_) {} std::reference_wrapper symbol; PlacementContext ctx; IntersectStatus status; @@ -1268,18 +1399,17 @@ class TilePlacement : public StaticPlacement { const std::vector& getPlacedSymbolsData() const override { return placedSymbolsData; } std::optional getAvoidEdges(const SymbolBucket&, const mat4&) override; - bool canPlaceAtVariableAnchor(const CollisionBox& box, - TextVariableAnchorType anchor, - Point shift, - std::vector& anchors, - const mat4& posMatrix, - float textPixelRatio) override; - void newSymbolPlaced(const SymbolInstance&, - const PlacementContext&, - const JointPlacement&, - style::SymbolPlacementType, - const std::vector&, - const std::vector&) override; + bool canPlaceAtVariableAnchor( + const CollisionBox& box, + TextVariableAnchorType anchor, + Point shift, + std::vector& anchors, + const mat4& posMatrix, + float textPixelRatio + ) override; + void + newSymbolPlaced(const SymbolInstance&, const PlacementContext&, const JointPlacement&, style::SymbolPlacementType, const std::vector&, const std::vector&) + override; bool shouldRetryPlacement(const JointPlacement&, const PlacementContext&); @@ -1366,25 +1496,29 @@ void TilePlacement::placeSymbolBucket(const BucketPlacementData& params, std::se return; } const RenderTile& renderTile = params.tile; - PlacementContext ctx{bucket, - params.tile, - collisionIndex.getTransformState(), - placementZoom, - collisionGroups.get(params.sourceId), - getAvoidEdges(bucket, renderTile.matrix)}; + PlacementContext ctx{ + bucket, + params.tile, + collisionIndex.getTransformState(), + placementZoom, + collisionGroups.get(params.sourceId), + getAvoidEdges(bucket, renderTile.matrix)}; const auto& variableTextAnchors = ctx.getVariableTextAnchors(); // In this case we first try to place symbols, which intersects the tile borders, so that // those symbols will remain even if each tile is handled independently. - SymbolInstanceReferences symbolInstances = - getBucketSymbols(bucket, params.sortKeyRange, collisionIndex.getTransformState().getBearing()); + SymbolInstanceReferences symbolInstances = getBucketSymbols( + bucket, params.sortKeyRange, collisionIndex.getTransformState().getBearing() + ); std::optional variableAnchor; if (!variableTextAnchors.empty()) variableAnchor = variableTextAnchors.front(); // Keeps the data necessary to find a feature location according to a tile. struct NeighborTileData { NeighborTileData(const CollisionIndex& collisionIndex, UnwrappedTileID id_, Point shift_) - : id(id_), shift(shift_), matrix() { + : id(id_), + shift(shift_), + matrix() { collisionIndex.getTransformState().matrixFor(matrix, id); matrix::multiply(matrix, collisionIndex.getTransformState().getProjectionMatrix(), matrix); borders = collisionIndex.projectTileBoundaries(matrix); @@ -1399,165 +1533,177 @@ void TilePlacement::placeSymbolBucket(const BucketPlacementData& params, std::se uint8_t z = renderTile.id.canonical.z; uint32_t x = renderTile.id.canonical.x; uint32_t y = renderTile.id.canonical.y; - const std::array neighbours{{ - {collisionIndex, UnwrappedTileID(z, x, y - 1), {0.0f, util::EXTENT}}, // top - {collisionIndex, UnwrappedTileID(z, x, y + 1), {0.0f, -util::EXTENT}}, // bottom - {collisionIndex, UnwrappedTileID(z, x - 1, y), {util::EXTENT, 0.0f}}, // left - {collisionIndex, UnwrappedTileID(z, x + 1, y), {-util::EXTENT, 0.0f}} // right - }}; - - auto collisionBoxIntersectsTileEdges = [&](const CollisionBox& collisionBox, - Point shift) noexcept->IntersectStatus { - IntersectStatus intersects = - collisionIndex.intersectsTileEdges(collisionBox, shift, renderTile.matrix, ctx.pixelRatio, *tileBorders); - // Check if this symbol intersects the neighbor tile borders. If so, it also shall be placed with priority. - for (const auto& neighbor : neighbours) { - if (intersects.flags != IntersectStatus::None) break; - intersects = collisionIndex.intersectsTileEdges( - collisionBox, shift + neighbor.shift, neighbor.matrix, ctx.pixelRatio, neighbor.borders); - } - return intersects; - }; + const std::array neighbours { + { + {collisionIndex, UnwrappedTileID(z, x, y - 1), {0.0f, util::EXTENT}}, // top + {collisionIndex, UnwrappedTileID(z, x, y + 1), {0.0f, -util::EXTENT}}, // bottom + {collisionIndex, UnwrappedTileID(z, x - 1, y), {util::EXTENT, 0.0f}}, // left + {collisionIndex, UnwrappedTileID(z, x + 1, y), {-util::EXTENT, 0.0f}} // right} + }; - auto symbolIntersectsTileEdges = [ - &collisionBoxIntersectsTileEdges, - variableAnchor, - pitchTextWithMap = ctx.pitchTextWithMap, - rotateTextWithMap = ctx.rotateTextWithMap, - variableIconPlacement = ctx.hasIconTextFit && !ctx.iconAllowOverlap, - bearing = static_cast(ctx.getTransformState().getBearing()) - ](const SymbolInstance& symbol) noexcept->IntersectStatus { - IntersectStatus result; - if (!symbol.textCollisionFeature.boxes.empty()) { - const auto& textCollisionBox = symbol.textCollisionFeature.boxes.front(); - - Point offset{}; - if (variableAnchor) { - float width = textCollisionBox.x2 - textCollisionBox.x1; - float height = textCollisionBox.y2 - textCollisionBox.y1; - offset = calculateVariableLayoutOffset(*variableAnchor, - width, - height, - symbol.variableTextOffset, - symbol.textBoxScale, - rotateTextWithMap, - pitchTextWithMap, - bearing); + auto collisionBoxIntersectsTileEdges = [&](const CollisionBox& collisionBox, + Point shift) noexcept -> IntersectStatus { + IntersectStatus intersects = collisionIndex.intersectsTileEdges( + collisionBox, shift, renderTile.matrix, ctx.pixelRatio, *tileBorders + ); + // Check if this symbol intersects the neighbor tile borders. If so, it also shall be placed with priority. + for (const auto& neighbor : neighbours) { + if (intersects.flags != IntersectStatus::None) break; + intersects = collisionIndex.intersectsTileEdges( + collisionBox, shift + neighbor.shift, neighbor.matrix, ctx.pixelRatio, neighbor.borders + ); } - result = collisionBoxIntersectsTileEdges(textCollisionBox, offset); - } + return intersects; + }; - if (!symbol.iconCollisionFeature.boxes.empty()) { - const auto& iconCollisionBox = symbol.iconCollisionFeature.boxes.front(); - Point offset{}; - if (variableAnchor && variableIconPlacement) { - float width = iconCollisionBox.x2 - iconCollisionBox.x1; - float height = iconCollisionBox.y2 - iconCollisionBox.y1; - offset = calculateVariableLayoutOffset(*variableAnchor, - width, - height, - symbol.variableTextOffset, - symbol.textBoxScale, - rotateTextWithMap, - pitchTextWithMap, - bearing); + auto symbolIntersectsTileEdges = [&collisionBoxIntersectsTileEdges, + variableAnchor, + pitchTextWithMap = ctx.pitchTextWithMap, + rotateTextWithMap = ctx.rotateTextWithMap, + variableIconPlacement = ctx.hasIconTextFit && !ctx.iconAllowOverlap, + bearing = static_cast(ctx.getTransformState().getBearing() + )](const SymbolInstance& symbol) noexcept -> IntersectStatus { + IntersectStatus result; + if (!symbol.textCollisionFeature.boxes.empty()) { + const auto& textCollisionBox = symbol.textCollisionFeature.boxes.front(); + + Point offset{}; + if (variableAnchor) { + float width = textCollisionBox.x2 - textCollisionBox.x1; + float height = textCollisionBox.y2 - textCollisionBox.y1; + offset = calculateVariableLayoutOffset( + *variableAnchor, + width, + height, + symbol.variableTextOffset, + symbol.textBoxScale, + rotateTextWithMap, + pitchTextWithMap, + bearing + ); + } + result = collisionBoxIntersectsTileEdges(textCollisionBox, offset); } - auto iconIntersects = collisionBoxIntersectsTileEdges(iconCollisionBox, offset); - result.flags |= iconIntersects.flags; - result.minSectionLength = std::max(result.minSectionLength, iconIntersects.minSectionLength); - } - return result; - }; - - for (const SymbolInstance& symbol : symbolInstances) { - auto intersectStatus = symbolIntersectsTileEdges(symbol); - if (intersectStatus.flags == IntersectStatus::None) continue; - intersections.emplace_back(symbol, ctx, intersectStatus, currentIntersectionPriority); - } + if (!symbol.iconCollisionFeature.boxes.empty()) { + const auto& iconCollisionBox = symbol.iconCollisionFeature.boxes.front(); + Point offset{}; + if (variableAnchor && variableIconPlacement) { + float width = iconCollisionBox.x2 - iconCollisionBox.x1; + float height = iconCollisionBox.y2 - iconCollisionBox.y1; + offset = calculateVariableLayoutOffset( + *variableAnchor, + width, + height, + symbol.variableTextOffset, + symbol.textBoxScale, + rotateTextWithMap, + pitchTextWithMap, + bearing + ); + } + auto iconIntersects = collisionBoxIntersectsTileEdges(iconCollisionBox, offset); + result.flags |= iconIntersects.flags; + result.minSectionLength = std::max(result.minSectionLength, iconIntersects.minSectionLength); + } - ++currentIntersectionPriority; -} + return result; + }; -bool TilePlacement::canPlaceAtVariableAnchor(const CollisionBox& box, - TextVariableAnchorType anchor, - Point shift, - std::vector& anchors, - const mat4& posMatrix, - float textPixelRatio) { - assert(tileBorders); - if (populateIntersections) { - // A variable label is only allowed to intersect tile border with the first anchor. - if (anchor == anchors.front()) { - // Check, that the label would intersect the tile borders even without shift, otherwise intersection - // is not allowed (preventing cut-offs in case the shift is lager than the buffer size). - auto status = collisionIndex.intersectsTileEdges(box, {}, posMatrix, textPixelRatio, *tileBorders); - if (status.flags != IntersectStatus::None) return true; + for (const SymbolInstance& symbol : symbolInstances) { + auto intersectStatus = symbolIntersectsTileEdges(symbol); + if (intersectStatus.flags == IntersectStatus::None) continue; + intersections.emplace_back(symbol, ctx, intersectStatus, currentIntersectionPriority); } - // The most important labels shall be placed first anyway, so we continue trying - // the following variable anchors for them; less priority labels - // will wait for the second round (when `populateIntersections` is `false`). - if (currentIntersectionPriority > 0u) return false; - } - // Can be placed, if it does not intersect tile borders. - auto status = collisionIndex.intersectsTileEdges(box, shift, posMatrix, textPixelRatio, *tileBorders); - return (status.flags == IntersectStatus::None); -} -void TilePlacement::newSymbolPlaced(const SymbolInstance& symbol, - const PlacementContext& ctx, - const JointPlacement& placement, - style::SymbolPlacementType placementType, - const std::vector& textCollisionBoxes, - const std::vector& iconCollisionBoxes) { - if (!collectData || placementType != style::SymbolPlacementType::Point || shouldRetryPlacement(placement, ctx)) - return; + ++currentIntersectionPriority; + } - std::optional> textCollisionBox; - if (!textCollisionBoxes.empty()) { - assert(textCollisionBoxes.size() == 1u); - auto& box = textCollisionBoxes.front(); - assert(box.isBox()); - textCollisionBox = box.box(); + bool TilePlacement::canPlaceAtVariableAnchor( + const CollisionBox& box, + TextVariableAnchorType anchor, + Point shift, + std::vector& anchors, + const mat4& posMatrix, + float textPixelRatio + ) { + assert(tileBorders); + if (populateIntersections) { + // A variable label is only allowed to intersect tile border with the first anchor. + if (anchor == anchors.front()) { + // Check, that the label would intersect the tile borders even without shift, otherwise intersection + // is not allowed (preventing cut-offs in case the shift is lager than the buffer size). + auto status = collisionIndex.intersectsTileEdges(box, {}, posMatrix, textPixelRatio, *tileBorders); + if (status.flags != IntersectStatus::None) return true; + } + // The most important labels shall be placed first anyway, so we continue trying + // the following variable anchors for them; less priority labels + // will wait for the second round (when `populateIntersections` is `false`). + if (currentIntersectionPriority > 0u) return false; + } + // Can be placed, if it does not intersect tile borders. + auto status = collisionIndex.intersectsTileEdges(box, shift, posMatrix, textPixelRatio, *tileBorders); + return (status.flags == IntersectStatus::None); } - std::optional> iconCollisionBox; - if (!iconCollisionBoxes.empty()) { - assert(iconCollisionBoxes.size() == 1u); - auto& box = iconCollisionBoxes.front(); - assert(box.isBox()); - iconCollisionBox = box.box(); + + void TilePlacement::newSymbolPlaced( + const SymbolInstance& symbol, + const PlacementContext& ctx, + const JointPlacement& placement, + style::SymbolPlacementType placementType, + const std::vector& textCollisionBoxes, + const std::vector& iconCollisionBoxes + ) { + if (!collectData || placementType != style::SymbolPlacementType::Point || shouldRetryPlacement(placement, ctx)) + return; + + std::optional> textCollisionBox; + if (!textCollisionBoxes.empty()) { + assert(textCollisionBoxes.size() == 1u); + auto& box = textCollisionBoxes.front(); + assert(box.isBox()); + textCollisionBox = box.box(); + } + std::optional> iconCollisionBox; + if (!iconCollisionBoxes.empty()) { + assert(iconCollisionBoxes.size() == 1u); + auto& box = iconCollisionBoxes.front(); + assert(box.isBox()); + iconCollisionBox = box.box(); + } + PlacedSymbolData symbolData{ + symbol.key, + textCollisionBox, + iconCollisionBox, + placement.text, + placement.icon, + !placement.skipFade && populateIntersections, + collisionIndex.getViewportPadding(), + ctx.getBucket().bucketLeaderID}; + placedSymbolsData.emplace_back(std::move(symbolData)); } - PlacedSymbolData symbolData{symbol.key, - textCollisionBox, - iconCollisionBox, - placement.text, - placement.icon, - !placement.skipFade && populateIntersections, - collisionIndex.getViewportPadding(), - ctx.getBucket().bucketLeaderID}; - placedSymbolsData.emplace_back(std::move(symbolData)); -} -bool TilePlacement::shouldRetryPlacement(const JointPlacement& placement, const PlacementContext& ctx) { - // We re-try the placement to try out remaining variable anchors. - return populateIntersections && !placement.placed() && !ctx.getVariableTextAnchors().empty(); -} + bool TilePlacement::shouldRetryPlacement(const JointPlacement& placement, const PlacementContext& ctx) { + // We re-try the placement to try out remaining variable anchors. + return populateIntersections && !placement.placed() && !ctx.getVariableTextAnchors().empty(); + } -// static -Mutable Placement::create(std::shared_ptr updateParameters_, - std::optional> prevPlacement) { - assert(updateParameters_); - switch (updateParameters_->mode) { - case MapMode::Continuous: - assert(prevPlacement); - return makeMutable(std::move(updateParameters_), std::move(prevPlacement)); - case MapMode::Static: - return staticMutableCast(makeMutable(std::move(updateParameters_))); - case MapMode::Tile: - return staticMutableCast(makeMutable(std::move(updateParameters_))); + // static + Mutable Placement::create( + std::shared_ptr updateParameters_, std::optional> prevPlacement + ) { + assert(updateParameters_); + switch (updateParameters_->mode) { + case MapMode::Continuous: + assert(prevPlacement); + return makeMutable(std::move(updateParameters_), std::move(prevPlacement)); + case MapMode::Static: + return staticMutableCast(makeMutable(std::move(updateParameters_))); + case MapMode::Tile: + return staticMutableCast(makeMutable(std::move(updateParameters_))); + } + assert(false); + return makeMutable(); } - assert(false); - return makeMutable(); -} } // namespace mbgl diff --git a/src/mbgl/text/placement.hpp b/src/mbgl/text/placement.hpp index 25ebbebf918..427f29599ee 100644 --- a/src/mbgl/text/placement.hpp +++ b/src/mbgl/text/placement.hpp @@ -48,8 +48,9 @@ class VariableOffset { class JointPlacement { public: JointPlacement(bool text_, bool icon_, bool skipFade_) - : text(text_), icon(icon_), skipFade(skipFade_) - {} + : text(text_), + icon(icon_), + skipFade(skipFade_) {} bool placed() const { return text || icon; } @@ -61,7 +62,7 @@ class JointPlacement { // visible right away. const bool skipFade; }; - + struct RetainedQueryData { uint32_t bucketInstanceId; std::shared_ptr featureIndex; @@ -69,21 +70,22 @@ struct RetainedQueryData { mutable FeatureSortOrder featureSortOrder; RetainedQueryData(uint32_t bucketInstanceId_, std::shared_ptr featureIndex_, OverscaledTileID tileID_) - : bucketInstanceId(bucketInstanceId_), featureIndex(std::move(featureIndex_)), tileID(tileID_) {} + : bucketInstanceId(bucketInstanceId_), + featureIndex(std::move(featureIndex_)), + tileID(tileID_) {} }; - + class CollisionGroups { public: using Predicate = std::function; using CollisionGroup = std::pair>; - + CollisionGroups(const bool crossSourceCollisions_) - : maxGroupID(0) - , crossSourceCollisions(crossSourceCollisions_) - {} - + : maxGroupID(0), + crossSourceCollisions(crossSourceCollisions_) {} + const CollisionGroup& get(const std::string& sourceID); - + private: std::map collisionGroups; uint16_t maxGroupID; @@ -114,8 +116,10 @@ class Placement { * Different placement implementations are created based on `updateParameters->mapMode`. * In Continuous map mode, `prevPlacement` must be provided. */ - static Mutable create(std::shared_ptr updateParameters, - std::optional> prevPlacement = std::nullopt); + static Mutable create( + std::shared_ptr updateParameters, + std::optional> prevPlacement = std::nullopt + ); virtual ~Placement(); virtual void placeLayers(const RenderLayerReferences&); @@ -145,33 +149,36 @@ class Placement { JointPlacement placeSymbol(const SymbolInstance& symbolInstance, const PlacementContext&); void placeLayer(const RenderLayer&, std::set&); virtual void commit(); - virtual void newSymbolPlaced(const SymbolInstance&, - const PlacementContext&, - const JointPlacement&, - style::SymbolPlacementType, - const std::vector& /*textBoxes*/, - const std::vector& /*iconBoxes*/) {} + virtual void newSymbolPlaced( + const SymbolInstance&, + const PlacementContext&, + const JointPlacement&, + style::SymbolPlacementType, + const std::vector& /*textBoxes*/, + const std::vector& /*iconBoxes*/ + ) {} // Implentation specific hooks, which get called during a symbol bucket placement. virtual std::optional getAvoidEdges(const SymbolBucket&, const mat4& /*posMatrix*/) { return std::nullopt; } SymbolInstanceReferences getSortedSymbols(const BucketPlacementData&, float pixelRatio); - virtual bool canPlaceAtVariableAnchor(const CollisionBox&, - style::TextVariableAnchorType, - Point /*shift*/, - std::vector&, - const mat4& /*posMatrix*/, - float /*textPixelRatio*/) { + virtual bool canPlaceAtVariableAnchor( + const CollisionBox&, + style::TextVariableAnchorType, + Point /*shift*/, + std::vector&, + const mat4& /*posMatrix*/, + float /*textPixelRatio*/ + ) { return true; } // Returns `true` if bucket vertices were updated; returns `false` otherwise. bool updateBucketDynamicVertices(SymbolBucket&, const TransformState&, const RenderTile& tile) const; void updateBucketOpacities(SymbolBucket&, const TransformState&, std::set&) const; - void markUsedJustification(SymbolBucket&, - style::TextVariableAnchorType, - const SymbolInstance&, - style::TextWritingModeType orientation) const; + void markUsedJustification( + SymbolBucket&, style::TextVariableAnchorType, const SymbolInstance&, style::TextWritingModeType orientation + ) const; void markUsedOrientation(SymbolBucket&, style::TextWritingModeType, const SymbolInstance&) const; const Placement* getPrevPlacement() const { return prevPlacement ? prevPlacement->get() : nullptr; } bool isTiltedView() const; diff --git a/src/mbgl/text/quads.cpp b/src/mbgl/text/quads.cpp index 6bf2afcae24..f8765cd277e 100644 --- a/src/mbgl/text/quads.cpp +++ b/src/mbgl/text/quads.cpp @@ -62,10 +62,9 @@ Cuts stretchZonesToCuts(const ImageStretches& stretchZones, const float fixedSiz return cuts; } -SymbolQuads getIconQuads(const PositionedIcon& shapedIcon, - const float iconRotate, - const SymbolContent iconType, - const bool hasIconTextFit) { +SymbolQuads getIconQuads( + const PositionedIcon& shapedIcon, const float iconRotate, const SymbolContent iconType, const bool hasIconTextFit +) { SymbolQuads quads; const ImagePosition& image = shapedIcon.image(); @@ -116,22 +115,27 @@ SymbolQuads getIconQuads(const PositionedIcon& shapedIcon, } auto makeBox = [&](Cut left, Cut top, Cut right, Cut bottom) { - const float leftEm = - getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left()); + const float leftEm = getEmOffset( + left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left() + ); const float leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); - const float topEm = - getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top()); + const float topEm = getEmOffset( + top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top() + ); const float topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); - const float rightEm = - getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left()); + const float rightEm = getEmOffset( + right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left() + ); const float rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); - const float bottomEm = - getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top()); - const float bottomPx = - getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); + const float bottomEm = getEmOffset( + bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top() + ); + const float bottomPx = getPxOffset( + bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight + ); Point tl(leftEm, topEm); Point tr(rightEm, topEm); @@ -153,26 +157,29 @@ SymbolQuads getIconQuads(const PositionedIcon& shapedIcon, const float y2 = bottom.stretch + bottom.fixed; // TODO: consider making texture coordinates float instead of uint16_t - const Rect subRect{static_cast(image.paddedRect.x + border + x1), - static_cast(image.paddedRect.y + border + y1), - static_cast(x2 - x1), - static_cast(y2 - y1)}; + const Rect subRect{ + static_cast(image.paddedRect.x + border + x1), + static_cast(image.paddedRect.y + border + y1), + static_cast(x2 - x1), + static_cast(y2 - y1)}; const float minFontScaleX = fixedContentWidth / pixelRatio / iconWidth; const float minFontScaleY = fixedContentHeight / pixelRatio / iconHeight; // Icon quad is padded, so texture coordinates also need to be padded. - quads.emplace_back(tl, - tr, - bl, - br, - subRect, - WritingModeType::None, - Point{0.0f, 0.0f}, - iconType == SymbolContent::IconSDF, - pixelOffsetTL, - pixelOffsetBR, - Point{minFontScaleX, minFontScaleY}); + quads.emplace_back( + tl, + tr, + bl, + br, + subRect, + WritingModeType::None, + Point{0.0f, 0.0f}, + iconType == SymbolContent::IconSDF, + pixelOffsetTL, + pixelOffsetBR, + Point{minFontScaleX, minFontScaleY} + ); }; if (!hasIconTextFit || (image.stretchX.empty() && image.stretchY.empty())) { @@ -195,14 +202,17 @@ SymbolQuads getIconQuads(const PositionedIcon& shapedIcon, return quads; } -SymbolQuads getGlyphQuads(const Shaping& shapedText, - const std::array textOffset, - const SymbolLayoutProperties::Evaluated& layout, - const style::SymbolPlacementType placement, - const ImageMap& imageMap, - bool allowVerticalPlacement) { +SymbolQuads getGlyphQuads( + const Shaping& shapedText, + const std::array textOffset, + const SymbolLayoutProperties::Evaluated& layout, + const style::SymbolPlacementType placement, + const ImageMap& imageMap, + bool allowVerticalPlacement +) { const float textRotate = util::deg2radf(layout.get()); - const bool alongLine = layout.get() == AlignmentType::Map && placement != SymbolPlacementType::Point; + const bool alongLine = layout.get() == AlignmentType::Map && + placement != SymbolPlacementType::Point; SymbolQuads quads; @@ -237,12 +247,14 @@ SymbolQuads getGlyphQuads(const Shaping& shapedText, isSDF = image->second->sdf; } - const Point glyphOffset = - alongLine ? Point{positionedGlyph.x + halfAdvance, positionedGlyph.y} : Point{0.0f, 0.0f}; + const Point glyphOffset = alongLine + ? Point{positionedGlyph.x + halfAdvance, positionedGlyph.y} + : Point{0.0f, 0.0f}; Point builtInOffset = alongLine ? Point{0.0f, 0.0f} - : Point{positionedGlyph.x + halfAdvance + textOffset[0], - positionedGlyph.y + textOffset[1] - lineOffset}; + : Point{ + positionedGlyph.x + halfAdvance + textOffset[0], + positionedGlyph.y + textOffset[1] - lineOffset}; Point verticalizedLabelOffset = {0.0f, 0.0f}; if (rotateVerticalGlyph) { @@ -253,8 +265,8 @@ SymbolQuads getGlyphQuads(const Shaping& shapedText, builtInOffset = {0.0f, 0.0f}; } - const float x1 = - (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset.x; + const float x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + + builtInOffset.x; const float y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset.y; const float x2 = x1 + rect.w * positionedGlyph.scale / pixelRatio; const float y2 = y1 + rect.h * positionedGlyph.scale / pixelRatio; @@ -282,8 +294,8 @@ SymbolQuads getGlyphQuads(const Shaping& shapedText, // advance, should be 0 for full-width glyphs and will pull up half-width glyphs. const float xHalfWidhtOffsetcorrection = util::ONE_EM / 2.f - halfAdvance; const float yImageOffsetCorrection = positionedGlyph.imageID ? xHalfWidhtOffsetcorrection : 0.0f; - const Point xOffsetCorrection{5.0f - Shaping::yOffset - xHalfWidhtOffsetcorrection, - -yImageOffsetCorrection}; + const Point xOffsetCorrection{ + 5.0f - Shaping::yOffset - xHalfWidhtOffsetcorrection, -yImageOffsetCorrection}; tl = util::rotate(tl - center, verticalRotation) + center + xOffsetCorrection + verticalizedLabelOffset; tr = util::rotate(tr - center, verticalRotation) + center + xOffsetCorrection + verticalizedLabelOffset; @@ -307,18 +319,20 @@ SymbolQuads getGlyphQuads(const Shaping& shapedText, Point pixelOffsetBR; Point minFontScale; - quads.emplace_back(tl, - tr, - bl, - br, - rect, - shapedText.writingMode, - glyphOffset, - isSDF, - pixelOffsetTL, - pixelOffsetBR, - minFontScale, - positionedGlyph.sectionIndex); + quads.emplace_back( + tl, + tr, + bl, + br, + rect, + shapedText.writingMode, + glyphOffset, + isSDF, + pixelOffsetTL, + pixelOffsetBR, + minFontScale, + positionedGlyph.sectionIndex + ); } } diff --git a/src/mbgl/text/quads.hpp b/src/mbgl/text/quads.hpp index 74c5d346cd9..e6f067edb46 100644 --- a/src/mbgl/text/quads.hpp +++ b/src/mbgl/text/quads.hpp @@ -16,18 +16,20 @@ enum class SymbolContent : uint8_t; class SymbolQuad { public: - SymbolQuad(Point tl_, - Point tr_, - Point bl_, - Point br_, - Rect tex_, - WritingModeType writingMode_, - Point glyphOffset_, - bool isSDF_, - Point pixelOffsetTL_, - Point pixelOffsetBR_, - Point minFontScale_, - size_t sectionIndex_ = 0) + SymbolQuad( + Point tl_, + Point tr_, + Point bl_, + Point br_, + Rect tex_, + WritingModeType writingMode_, + Point glyphOffset_, + bool isSDF_, + Point pixelOffsetTL_, + Point pixelOffsetBR_, + Point minFontScale_, + size_t sectionIndex_ = 0 + ) : tl(tl_), tr(tr_), bl(bl_), @@ -57,16 +59,17 @@ class SymbolQuad { using SymbolQuads = std::vector; -SymbolQuads getIconQuads(const PositionedIcon& shapedIcon, - float iconRotate, - SymbolContent iconType, - bool hasIconTextFit); +SymbolQuads getIconQuads( + const PositionedIcon& shapedIcon, float iconRotate, SymbolContent iconType, bool hasIconTextFit +); -SymbolQuads getGlyphQuads(const Shaping& shapedText, - std::array textOffset, - const style::SymbolLayoutProperties::Evaluated&, - style::SymbolPlacementType placement, - const ImageMap& imageMap, - bool allowVerticalPlacement); +SymbolQuads getGlyphQuads( + const Shaping& shapedText, + std::array textOffset, + const style::SymbolLayoutProperties::Evaluated&, + style::SymbolPlacementType placement, + const ImageMap& imageMap, + bool allowVerticalPlacement +); } // namespace mbgl diff --git a/src/mbgl/text/shaping.cpp b/src/mbgl/text/shaping.cpp index 9f83cea7d23..5192d89ab4b 100644 --- a/src/mbgl/text/shaping.cpp +++ b/src/mbgl/text/shaping.cpp @@ -10,8 +10,8 @@ #include namespace { - // Zero width space that is used to suggest break points for Japanese labels. - char16_t ZWSP = u'\u200b'; +// Zero width space that is used to suggest break points for Japanese labels. +char16_t ZWSP = u'\u200b'; } // namespace namespace mbgl { @@ -21,33 +21,33 @@ AnchorAlignment AnchorAlignment::getAnchorAlignment(style::SymbolAnchorType anch AnchorAlignment result(0.5f, 0.5f); switch (anchor) { - case style::SymbolAnchorType::Right: - case style::SymbolAnchorType::TopRight: - case style::SymbolAnchorType::BottomRight: - result.horizontalAlign = 1.0f; - break; - case style::SymbolAnchorType::Left: - case style::SymbolAnchorType::TopLeft: - case style::SymbolAnchorType::BottomLeft: - result.horizontalAlign = 0.0f; - break; - default: - break; + case style::SymbolAnchorType::Right: + case style::SymbolAnchorType::TopRight: + case style::SymbolAnchorType::BottomRight: + result.horizontalAlign = 1.0f; + break; + case style::SymbolAnchorType::Left: + case style::SymbolAnchorType::TopLeft: + case style::SymbolAnchorType::BottomLeft: + result.horizontalAlign = 0.0f; + break; + default: + break; } switch (anchor) { - case style::SymbolAnchorType::Bottom: - case style::SymbolAnchorType::BottomLeft: - case style::SymbolAnchorType::BottomRight: - result.verticalAlign = 1.0f; - break; - case style::SymbolAnchorType::Top: - case style::SymbolAnchorType::TopLeft: - case style::SymbolAnchorType::TopRight: - result.verticalAlign = 0.0f; - break; - default: - break; + case style::SymbolAnchorType::Bottom: + case style::SymbolAnchorType::BottomLeft: + case style::SymbolAnchorType::BottomRight: + result.verticalAlign = 1.0f; + break; + case style::SymbolAnchorType::Top: + case style::SymbolAnchorType::TopLeft: + case style::SymbolAnchorType::TopRight: + result.verticalAlign = 0.0f; + break; + default: + break; } return result; @@ -55,22 +55,22 @@ AnchorAlignment AnchorAlignment::getAnchorAlignment(style::SymbolAnchorType anch style::TextJustifyType getAnchorJustification(style::SymbolAnchorType anchor) { switch (anchor) { - case style::SymbolAnchorType::Right: - case style::SymbolAnchorType::TopRight: - case style::SymbolAnchorType::BottomRight: - return style::TextJustifyType::Right; - case style::SymbolAnchorType::Left: - case style::SymbolAnchorType::TopLeft: - case style::SymbolAnchorType::BottomLeft: - return style::TextJustifyType::Left; - default: - return style::TextJustifyType::Center; + case style::SymbolAnchorType::Right: + case style::SymbolAnchorType::TopRight: + case style::SymbolAnchorType::BottomRight: + return style::TextJustifyType::Right; + case style::SymbolAnchorType::Left: + case style::SymbolAnchorType::TopLeft: + case style::SymbolAnchorType::BottomLeft: + return style::TextJustifyType::Left; + default: + return style::TextJustifyType::Center; } } -PositionedIcon PositionedIcon::shapeIcon(const ImagePosition& image, - const std::array& iconOffset, - style::SymbolAnchorType iconAnchor) { +PositionedIcon PositionedIcon::shapeIcon( + const ImagePosition& image, const std::array& iconOffset, style::SymbolAnchorType iconAnchor +) { AnchorAlignment anchorAlign = AnchorAlignment::getAnchorAlignment(iconAnchor); float dx = iconOffset[0]; float dy = iconOffset[1]; @@ -92,11 +92,13 @@ PositionedIcon PositionedIcon::shapeIcon(const ImagePosition& image, return PositionedIcon{image, top, bottom, left, right, collisionPadding}; } -void PositionedIcon::fitIconToText(const Shaping& shapedText, - const style::IconTextFitType textFit, - const std::array& padding, - const std::array& iconOffset, - const float fontScale) { +void PositionedIcon::fitIconToText( + const Shaping& shapedText, + const style::IconTextFitType textFit, + const std::array& padding, + const std::array& iconOffset, + const float fontScale +) { assert(textFit != style::IconTextFitType::None); assert(shapedText); @@ -130,15 +132,17 @@ void PositionedIcon::fitIconToText(const Shaping& shapedText, } } -void align(Shaping& shaping, - float justify, - float horizontalAlign, - float verticalAlign, - float maxLineLength, - float maxLineHeight, - float lineHeight, - float blockHeight, - std::size_t lineCount) { +void align( + Shaping& shaping, + float justify, + float horizontalAlign, + float verticalAlign, + float maxLineLength, + float maxLineHeight, + float lineHeight, + float blockHeight, + std::size_t lineCount +) { const float shiftX = (justify - horizontalAlign) * maxLineLength; float shiftY = 0.0f; @@ -171,12 +175,14 @@ void justifyLine(std::vector& positionedGlyphs, float justify, } } -float getGlyphAdvance(char16_t codePoint, - const SectionOptions& section, - const GlyphMap& glyphMap, - const ImagePositions& imagePositions, - float layoutTextSize, - float spacing) { +float getGlyphAdvance( + char16_t codePoint, + const SectionOptions& section, + const GlyphMap& glyphMap, + const ImagePositions& imagePositions, + float layoutTextSize, + float spacing +) { if (!section.imageID) { auto glyphs = glyphMap.find(section.fontStackHash); if (glyphs == glyphMap.end()) { @@ -192,24 +198,27 @@ float getGlyphAdvance(char16_t codePoint, if (image == imagePositions.end()) { return 0.0f; } - return image->second.displaySize()[0] * static_cast(section.scale) * util::ONE_EM / layoutTextSize + spacing; + return image->second.displaySize()[0] * static_cast(section.scale) * util::ONE_EM / layoutTextSize + + spacing; } } -float determineAverageLineWidth(const TaggedString& logicalInput, - float spacing, - float maxWidth, - const GlyphMap& glyphMap, - const ImagePositions& imagePositions, - float layoutTextSize) { +float determineAverageLineWidth( + const TaggedString& logicalInput, + float spacing, + float maxWidth, + const GlyphMap& glyphMap, + const ImagePositions& imagePositions, + float layoutTextSize +) { float totalWidth = 0; - + for (std::size_t i = 0; i < logicalInput.length(); i++) { const SectionOptions& section = logicalInput.getSection(i); char16_t codePoint = logicalInput.getCharCodeAt(i); totalWidth += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, layoutTextSize, spacing); } - + auto targetLineCount = static_cast(::fmax(1, std::ceil(totalWidth / maxWidth))); return totalWidth / targetLineCount; } @@ -241,7 +250,7 @@ float calculatePenalty(char16_t codePoint, char16_t nextCodePoint, bool penaliza if (codePoint == 0x28 || codePoint == 0xff08) { penalty += 50; } - + // Penalize close parenthesis at beginning of line if (nextCodePoint == 0x29 || nextCodePoint == 0xff09) { penalty += 50; @@ -257,29 +266,38 @@ float calculatePenalty(char16_t codePoint, char16_t nextCodePoint, bool penaliza } struct PotentialBreak { - PotentialBreak(const std::size_t p_index, const float p_x, const PotentialBreak* p_priorBreak, const float p_badness) - : index(p_index), x(p_x), priorBreak(p_priorBreak), badness(p_badness) - {} - + PotentialBreak( + const std::size_t p_index, const float p_x, const PotentialBreak* p_priorBreak, const float p_badness + ) + : index(p_index), + x(p_x), + priorBreak(p_priorBreak), + badness(p_badness) {} + const std::size_t index; const float x; const PotentialBreak* priorBreak; const float badness; }; - -PotentialBreak evaluateBreak(const std::size_t breakIndex, const float breakX, const float targetWidth, const std::list& potentialBreaks, const float penalty, const bool isLastBreak) { +PotentialBreak evaluateBreak( + const std::size_t breakIndex, + const float breakX, + const float targetWidth, + const std::list& potentialBreaks, + const float penalty, + const bool isLastBreak +) { // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth // ...but in fact we allow lines longer than maxWidth (if there's no break points) // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give // more lopsided results. - + const PotentialBreak* bestPriorBreak = nullptr; float bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak); for (const auto& potentialBreak : potentialBreaks) { const float lineWidth = breakX - potentialBreak.x; - float breakBadness = - calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; + float breakBadness = calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; if (breakBadness <= bestBreakBadness) { bestPriorBreak = &potentialBreak; bestBreakBadness = breakBadness; @@ -290,7 +308,7 @@ PotentialBreak evaluateBreak(const std::size_t breakIndex, const float breakX, c } std::set leastBadBreaks(const PotentialBreak& lastLineBreak) { - std::set leastBadBreaks = { lastLineBreak.index }; + std::set leastBadBreaks = {lastLineBreak.index}; const PotentialBreak* priorBreak = lastLineBreak.priorBreak; while (priorBreak) { leastBadBreaks.insert(priorBreak->index); @@ -299,30 +317,32 @@ std::set leastBadBreaks(const PotentialBreak& lastLineBreak) { return leastBadBreaks; } - // We determine line breaks based on shaped text in logical order. Working in visual order would be // more intuitive, but we can't do that because the visual order may be changed by line breaks! -std::set determineLineBreaks(const TaggedString& logicalInput, - const float spacing, - float maxWidth, - const GlyphMap& glyphMap, - const ImagePositions& imagePositions, - float layoutTextSize) { +std::set determineLineBreaks( + const TaggedString& logicalInput, + const float spacing, + float maxWidth, + const GlyphMap& glyphMap, + const ImagePositions& imagePositions, + float layoutTextSize +) { if (!maxWidth) { return {}; } - + if (logicalInput.empty()) { return {}; } - const float targetWidth = - determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); + const float targetWidth = determineAverageLineWidth( + logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize + ); std::list potentialBreaks; float currentX = 0; // Find first occurance of zero width space (ZWSP) character. - const bool hasServerSuggestedBreaks = logicalInput.rawText().find_first_of(ZWSP) != std::string::npos; + const bool hasServerSuggestedBreaks = logicalInput.rawText().find_first_of(ZWSP) != std::string::npos; for (std::size_t i = 0; i < logicalInput.length(); i++) { const SectionOptions& section = logicalInput.getSection(i); @@ -338,41 +358,49 @@ std::set determineLineBreaks(const TaggedString& logicalInput, if (section.imageID || allowsIdeographicBreak || util::i18n::allowsWordBreaking(codePoint)) { const bool penalizableIdeographicBreak = allowsIdeographicBreak && hasServerSuggestedBreaks; const std::size_t nextIndex = i + 1; - potentialBreaks.push_back(evaluateBreak(nextIndex, currentX, targetWidth, potentialBreaks, - calculatePenalty(codePoint, logicalInput.getCharCodeAt(nextIndex), penalizableIdeographicBreak), - false)); + potentialBreaks.push_back(evaluateBreak( + nextIndex, + currentX, + targetWidth, + potentialBreaks, + calculatePenalty(codePoint, logicalInput.getCharCodeAt(nextIndex), penalizableIdeographicBreak), + false + )); } } } - + return leastBadBreaks(evaluateBreak(logicalInput.length(), currentX, targetWidth, potentialBreaks, 0, true)); } -void shapeLines(Shaping& shaping, - std::vector& lines, - const float spacing, - const float lineHeight, - const style::SymbolAnchorType textAnchor, - const style::TextJustifyType textJustify, - const WritingModeType writingMode, - const GlyphMap& glyphMap, - const GlyphPositions& glyphPositions, - const ImagePositions& imagePositions, - float layoutTextSize, - bool allowVerticalPlacement) { +void shapeLines( + Shaping& shaping, + std::vector& lines, + const float spacing, + const float lineHeight, + const style::SymbolAnchorType textAnchor, + const style::TextJustifyType textJustify, + const WritingModeType writingMode, + const GlyphMap& glyphMap, + const GlyphPositions& glyphPositions, + const ImagePositions& imagePositions, + float layoutTextSize, + bool allowVerticalPlacement +) { float x = 0.0f; float y = Shaping::yOffset; float maxLineLength = 0.0f; float maxLineHeight = 0.0f; - const float justify = - textJustify == style::TextJustifyType::Right ? 1.0f : textJustify == style::TextJustifyType::Left ? 0.0f : 0.5f; + const float justify = textJustify == style::TextJustifyType::Right ? 1.0f + : textJustify == style::TextJustifyType::Left ? 0.0f + : 0.5f; for (TaggedString& line : lines) { // Collapse whitespace so it doesn't throw off justification line.trim(); - + const double lineMaxScale = line.getMaxScale(); const double maxLineOffset = (lineMaxScale - 1.0) * util::ONE_EM; double lineOffset = 0.0; @@ -384,7 +412,7 @@ void shapeLines(Shaping& shaping, y += lineHeight; // Still need a line feed after empty line continue; } - + for (std::size_t i = 0; i < line.length(); i++) { const std::size_t sectionIndex = line.getSectionIndex(i); const SectionOptions& section = line.sectionAt(sectionIndex); @@ -460,36 +488,40 @@ void shapeLines(Shaping& shaping, // Difference between height of an image and one EM at max line scale. // Pushes current line down if an image size is over 1 EM at max line scale. - double offset = - (vertical ? displaySize[0] : displaySize[1]) * sectionScale - util::ONE_EM * lineMaxScale; + double offset = (vertical ? displaySize[0] : displaySize[1]) * sectionScale - + util::ONE_EM * lineMaxScale; if (offset > 0.0 && offset > lineOffset) { lineOffset = offset; } } if (!vertical) { - positionedGlyphs.emplace_back(codePoint, - x, - y + static_cast(baselineOffset), - vertical, - section.fontStackHash, - static_cast(sectionScale), - rect, - metrics, - section.imageID, - sectionIndex); + positionedGlyphs.emplace_back( + codePoint, + x, + y + static_cast(baselineOffset), + vertical, + section.fontStackHash, + static_cast(sectionScale), + rect, + metrics, + section.imageID, + sectionIndex + ); x += advance * static_cast(sectionScale) + spacing; } else { - positionedGlyphs.emplace_back(codePoint, - x, - y + static_cast(baselineOffset), - vertical, - section.fontStackHash, - static_cast(sectionScale), - rect, - metrics, - section.imageID, - sectionIndex); + positionedGlyphs.emplace_back( + codePoint, + x, + y + static_cast(baselineOffset), + vertical, + section.fontStackHash, + static_cast(sectionScale), + rect, + metrics, + section.imageID, + sectionIndex + ); x += verticalAdvance * static_cast(sectionScale) + spacing; shaping.verticalizable |= true; } @@ -511,15 +543,17 @@ void shapeLines(Shaping& shaping, auto anchorAlign = AnchorAlignment::getAnchorAlignment(textAnchor); const float height = y - Shaping::yOffset; - align(shaping, - justify, - anchorAlign.horizontalAlign, - anchorAlign.verticalAlign, - maxLineLength, - maxLineHeight, - lineHeight, - height, - lines.size()); + align( + shaping, + justify, + anchorAlign.horizontalAlign, + anchorAlign.verticalAlign, + maxLineLength, + maxLineHeight, + lineHeight, + height, + lines.size() + ); // Calculate the bounding box shaping.top += -anchorAlign.verticalAlign * height; @@ -528,51 +562,57 @@ void shapeLines(Shaping& shaping, shaping.right = shaping.left + maxLineLength; } -Shaping getShaping(const TaggedString& formattedString, - const float maxWidth, - const float lineHeight, - const style::SymbolAnchorType textAnchor, - const style::TextJustifyType textJustify, - const float spacing, - const std::array& translate, - const WritingModeType writingMode, - BiDi& bidi, - const GlyphMap& glyphMap, - const GlyphPositions& glyphPositions, - const ImagePositions& imagePositions, - float layoutTextSize, - float layoutTextSizeAtBucketZoomLevel, - bool allowVerticalPlacement) { +Shaping getShaping( + const TaggedString& formattedString, + const float maxWidth, + const float lineHeight, + const style::SymbolAnchorType textAnchor, + const style::TextJustifyType textJustify, + const float spacing, + const std::array& translate, + const WritingModeType writingMode, + BiDi& bidi, + const GlyphMap& glyphMap, + const GlyphPositions& glyphPositions, + const ImagePositions& imagePositions, + float layoutTextSize, + float layoutTextSizeAtBucketZoomLevel, + bool allowVerticalPlacement +) { assert(layoutTextSize); std::vector reorderedLines; if (formattedString.sectionCount() == 1) { auto untaggedLines = bidi.processText( formattedString.rawText(), - determineLineBreaks(formattedString, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + determineLineBreaks(formattedString, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) + ); for (const auto& line : untaggedLines) { reorderedLines.emplace_back(line, formattedString.sectionAt(0)); } } else { auto processedLines = bidi.processStyledText( formattedString.getStyledText(), - determineLineBreaks(formattedString, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + determineLineBreaks(formattedString, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) + ); for (const auto& line : processedLines) { reorderedLines.emplace_back(line, formattedString.getSections()); } } Shaping shaping(translate[0], translate[1], writingMode); - shapeLines(shaping, - reorderedLines, - spacing, - lineHeight, - textAnchor, - textJustify, - writingMode, - glyphMap, - glyphPositions, - imagePositions, - layoutTextSizeAtBucketZoomLevel, - allowVerticalPlacement); + shapeLines( + shaping, + reorderedLines, + spacing, + lineHeight, + textAnchor, + textJustify, + writingMode, + glyphMap, + glyphPositions, + imagePositions, + layoutTextSizeAtBucketZoomLevel, + allowVerticalPlacement + ); return shaping; } diff --git a/src/mbgl/text/shaping.hpp b/src/mbgl/text/shaping.hpp index 1043aad6bfe..691e6ee4a70 100644 --- a/src/mbgl/text/shaping.hpp +++ b/src/mbgl/text/shaping.hpp @@ -13,8 +13,8 @@ namespace mbgl { struct AnchorAlignment { AnchorAlignment(float horizontal, float vertical) - : horizontalAlign(horizontal), verticalAlign(vertical) { - } + : horizontalAlign(horizontal), + verticalAlign(vertical) {} static AnchorAlignment getAnchorAlignment(style::SymbolAnchorType anchor); @@ -45,7 +45,8 @@ class Padding { class PositionedIcon { private: PositionedIcon( - ImagePosition image_, float top_, float bottom_, float left_, float right_, const Padding& collisionPadding_) + ImagePosition image_, float top_, float bottom_, float left_, float right_, const Padding& collisionPadding_ + ) : _image(std::move(image_)), _top(top_), _bottom(bottom_), @@ -61,17 +62,19 @@ class PositionedIcon { Padding _collisionPadding; public: - static PositionedIcon shapeIcon(const ImagePosition&, - const std::array& iconOffset, - style::SymbolAnchorType iconAnchor); + static PositionedIcon shapeIcon( + const ImagePosition&, const std::array& iconOffset, style::SymbolAnchorType iconAnchor + ); // Updates shaped icon's bounds based on shaped text's bounds and provided // layout properties. - void fitIconToText(const Shaping& shapedText, - style::IconTextFitType textFit, - const std::array& padding, - const std::array& iconOffset, - float fontScale); + void fitIconToText( + const Shaping& shapedText, + style::IconTextFitType textFit, + const std::array& padding, + const std::array& iconOffset, + float fontScale + ); const ImagePosition& image() const { return _image; } float top() const { return _top; } @@ -81,20 +84,22 @@ class PositionedIcon { const Padding& collisionPadding() const { return _collisionPadding; } }; -Shaping getShaping(const TaggedString& string, - float maxWidth, - float lineHeight, - style::SymbolAnchorType textAnchor, - style::TextJustifyType textJustify, - float spacing, - const std::array& translate, - WritingModeType, - BiDi& bidi, - const GlyphMap& glyphMap, - const GlyphPositions& glyphPositions, - const ImagePositions& imagePositions, - float layoutTextSize, - float layoutTextSizeAtBucketZoomLevel, - bool allowVerticalPlacement); +Shaping getShaping( + const TaggedString& string, + float maxWidth, + float lineHeight, + style::SymbolAnchorType textAnchor, + style::TextJustifyType textJustify, + float spacing, + const std::array& translate, + WritingModeType, + BiDi& bidi, + const GlyphMap& glyphMap, + const GlyphPositions& glyphPositions, + const ImagePositions& imagePositions, + float layoutTextSize, + float layoutTextSizeAtBucketZoomLevel, + bool allowVerticalPlacement +); } // namespace mbgl diff --git a/src/mbgl/text/tagged_string.cpp b/src/mbgl/text/tagged_string.cpp index 4fc5139775f..7f822845b93 100644 --- a/src/mbgl/text/tagged_string.cpp +++ b/src/mbgl/text/tagged_string.cpp @@ -10,10 +10,9 @@ char16_t PUAend = u'\uF8FF'; namespace mbgl { -void TaggedString::addTextSection(const std::u16string& sectionText, - double scale, - const FontStack& fontStack, - std::optional textColor) { +void TaggedString::addTextSection( + const std::u16string& sectionText, double scale, const FontStack& fontStack, std::optional textColor +) { styledText.first += sectionText; sections.emplace_back(scale, fontStack, std::move(textColor)); styledText.second.resize(styledText.first.size(), static_cast(sections.size() - 1)); @@ -55,7 +54,9 @@ void TaggedString::trim() { std::size_t trailingWhitespace = styledText.first.find_last_not_of(u" \t\n\v\f\r") + 1; styledText.first = styledText.first.substr(beginningWhitespace, trailingWhitespace - beginningWhitespace); - styledText.second = std::vector(styledText.second.begin() + beginningWhitespace, styledText.second.begin() + trailingWhitespace); + styledText.second = std::vector( + styledText.second.begin() + beginningWhitespace, styledText.second.begin() + trailingWhitespace + ); } } @@ -66,7 +67,7 @@ double TaggedString::getMaxScale() const { } return maxScale; } - + void TaggedString::verticalizePunctuation() { // Relies on verticalization changing characters in place so that style indices don't need updating styledText.first = util::i18n::verticalizePunctuation(styledText.first); diff --git a/src/mbgl/text/tagged_string.hpp b/src/mbgl/text/tagged_string.hpp index 0ff92307ecb..bb938f3cf7f 100644 --- a/src/mbgl/text/tagged_string.hpp +++ b/src/mbgl/text/tagged_string.hpp @@ -13,10 +13,11 @@ struct SectionOptions { : scale(scale_), fontStackHash(FontStackHasher()(fontStack_)), fontStack(std::move(fontStack_)), - textColor(std::move(textColor_)) - {} + textColor(std::move(textColor_)) {} - explicit SectionOptions(std::string imageID_) : scale(1.0), imageID(std::move(imageID_)) {} + explicit SectionOptions(std::string imageID_) + : scale(1.0), + imageID(std::move(imageID_)) {} double scale; FontStackHash fontStackHash; @@ -44,66 +45,46 @@ struct TaggedString { TaggedString() = default; TaggedString(std::u16string text_, SectionOptions options) - : styledText(std::move(text_), - std::vector(text_.size(), 0)) { + : styledText(std::move(text_), std::vector(text_.size(), 0)) { sections.push_back(std::move(options)); } - + TaggedString(StyledText styledText_, std::vector sections_) - : styledText(std::move(styledText_)) - , sections(std::move(sections_)) { - } + : styledText(std::move(styledText_)), + sections(std::move(sections_)) {} - std::size_t length() const { - return styledText.first.length(); - } - - std::size_t sectionCount() const { - return sections.size(); - } - - bool empty() const { - return styledText.first.empty(); - } - - const SectionOptions& getSection(std::size_t index) const { - return sections.at(styledText.second.at(index)); - } - - char16_t getCharCodeAt(std::size_t index) const { - return styledText.first[index]; - } - - const std::u16string& rawText() const { - return styledText.first; - } - - const StyledText& getStyledText() const { - return styledText; - } + std::size_t length() const { return styledText.first.length(); } + + std::size_t sectionCount() const { return sections.size(); } + + bool empty() const { return styledText.first.empty(); } - void addTextSection(const std::u16string& text, - double scale, - const FontStack& fontStack, - std::optional textColor_ = std::nullopt); + const SectionOptions& getSection(std::size_t index) const { return sections.at(styledText.second.at(index)); } + + char16_t getCharCodeAt(std::size_t index) const { return styledText.first[index]; } + + const std::u16string& rawText() const { return styledText.first; } + + const StyledText& getStyledText() const { return styledText; } + + void addTextSection( + const std::u16string& text, + double scale, + const FontStack& fontStack, + std::optional textColor_ = std::nullopt + ); void addImageSection(const std::string& imageID); - const SectionOptions& sectionAt(std::size_t index) const { - return sections.at(index); - } - - const std::vector& getSections() const { - return sections; - } - - uint8_t getSectionIndex(std::size_t characterIndex) const { - return styledText.second.at(characterIndex); - } - + const SectionOptions& sectionAt(std::size_t index) const { return sections.at(index); } + + const std::vector& getSections() const { return sections; } + + uint8_t getSectionIndex(std::size_t characterIndex) const { return styledText.second.at(characterIndex); } + double getMaxScale() const; void trim(); - + void verticalizePunctuation(); bool allowsVerticalWritingMode(); diff --git a/src/mbgl/tile/custom_geometry_tile.cpp b/src/mbgl/tile/custom_geometry_tile.cpp index e24d2d8dd51..e38017b2ff8 100644 --- a/src/mbgl/tile/custom_geometry_tile.cpp +++ b/src/mbgl/tile/custom_geometry_tile.cpp @@ -14,11 +14,13 @@ namespace mbgl { -CustomGeometryTile::CustomGeometryTile(const OverscaledTileID& overscaledTileID, - std::string sourceID_, - const TileParameters& parameters, - Immutable options_, - ActorRef loader_) +CustomGeometryTile::CustomGeometryTile( + const OverscaledTileID& overscaledTileID, + std::string sourceID_, + const TileParameters& parameters, + Immutable options_, + ActorRef loader_ +) : GeometryTile(overscaledTileID, std::move(sourceID_), parameters), necessity(TileNecessity::Optional), options(std::move(options_)), @@ -31,7 +33,6 @@ CustomGeometryTile::~CustomGeometryTile() { } void CustomGeometryTile::setTileData(const GeoJSON& geoJSON) { - auto featureData = mapbox::feature::feature_collection(); if (geoJSON.is() && !geoJSON.get().empty()) { auto scale = util::EXTENT / options->tileSize; @@ -43,7 +44,8 @@ void CustomGeometryTile::setTileData(const GeoJSON& geoJSON) { vtOptions.tolerance = scale * options->tolerance; featureData = mapbox::geojsonvt::geoJSONToTile( - geoJSON, id.canonical.z, id.canonical.x, id.canonical.y, vtOptions, options->wrap, options->clip) + geoJSON, id.canonical.z, id.canonical.x, id.canonical.y, vtOptions, options->wrap, options->clip + ) .features; } setData(std::make_unique(std::move(featureData))); @@ -54,11 +56,11 @@ void CustomGeometryTile::invalidateTileData() { observer->onTileChanged(*this); } -//Fetching tile data for custom sources is assumed to be an expensive operation. -// Only required tiles make fetchTile requests. Attempt to cancel a tile -// that is no longer required. +// Fetching tile data for custom sources is assumed to be an expensive operation. +// Only required tiles make fetchTile requests. Attempt to cancel a tile +// that is no longer required. void CustomGeometryTile::setNecessity(TileNecessity newNecessity) { - if (newNecessity != necessity || stale ) { + if (newNecessity != necessity || stale) { necessity = newNecessity; if (necessity == TileNecessity::Required) { loader.invoke(&style::CustomTileLoader::fetchTile, id, actorRef); @@ -69,10 +71,7 @@ void CustomGeometryTile::setNecessity(TileNecessity newNecessity) { } } -void CustomGeometryTile::querySourceFeatures( - std::vector& result, - const SourceQueryOptions& queryOptions) { - +void CustomGeometryTile::querySourceFeatures(std::vector& result, const SourceQueryOptions& queryOptions) { // Ignore the sourceLayer, there is only one auto layer = getData()->getLayer({}); @@ -82,7 +81,8 @@ void CustomGeometryTile::querySourceFeatures( auto feature = layer->getFeature(i); // Apply filter, if any - if (queryOptions.filter && !(*queryOptions.filter)(style::expression::EvaluationContext { static_cast(id.overscaledZ), feature.get() })) { + if (queryOptions.filter && !(*queryOptions.filter)(style::expression::EvaluationContext{ + static_cast(id.overscaledZ), feature.get()})) { continue; } diff --git a/src/mbgl/tile/custom_geometry_tile.hpp b/src/mbgl/tile/custom_geometry_tile.hpp index 06952871271..255c34889c5 100644 --- a/src/mbgl/tile/custom_geometry_tile.hpp +++ b/src/mbgl/tile/custom_geometry_tile.hpp @@ -14,13 +14,15 @@ namespace style { class CustomTileLoader; } // namespace style -class CustomGeometryTile: public GeometryTile { +class CustomGeometryTile : public GeometryTile { public: - CustomGeometryTile(const OverscaledTileID&, - std::string sourceID, - const TileParameters&, - Immutable, - ActorRef loader); + CustomGeometryTile( + const OverscaledTileID&, + std::string sourceID, + const TileParameters&, + Immutable, + ActorRef loader + ); ~CustomGeometryTile() override; void setTileData(const GeoJSON& geoJSON); @@ -28,9 +30,7 @@ class CustomGeometryTile: public GeometryTile { void setNecessity(TileNecessity) final; - void querySourceFeatures( - std::vector& result, - const SourceQueryOptions&) override; + void querySourceFeatures(std::vector& result, const SourceQueryOptions&) override; private: bool stale = true; diff --git a/src/mbgl/tile/geojson_tile.cpp b/src/mbgl/tile/geojson_tile.cpp index 0b37510978c..6545537db9a 100644 --- a/src/mbgl/tile/geojson_tile.cpp +++ b/src/mbgl/tile/geojson_tile.cpp @@ -6,10 +6,12 @@ #include namespace mbgl { -GeoJSONTile::GeoJSONTile(const OverscaledTileID& overscaledTileID, - std::string sourceID_, - const TileParameters& parameters, - std::shared_ptr data_) +GeoJSONTile::GeoJSONTile( + const OverscaledTileID& overscaledTileID, + std::string sourceID_, + const TileParameters& parameters, + std::shared_ptr data_ +) : GeometryTile(overscaledTileID, std::move(sourceID_), parameters) { updateData(std::move(data_), false /*needsRelayout*/); } @@ -25,13 +27,11 @@ void GeoJSONTile::updateData(std::shared_ptr data_, bool nee if (data.get() != capturedData) return; auto tileData = std::make_unique(std::move(features)); setData(std::move(tileData)); - }); + } + ); } -void GeoJSONTile::querySourceFeatures( - std::vector& result, - const SourceQueryOptions& options) { - +void GeoJSONTile::querySourceFeatures(std::vector& result, const SourceQueryOptions& options) { // Ignore the sourceLayer, there is only one if (auto tileData = getData()) { if (auto layer = tileData->getLayer({})) { @@ -40,7 +40,8 @@ void GeoJSONTile::querySourceFeatures( auto feature = layer->getFeature(i); // Apply filter, if any - if (options.filter && !(*options.filter)(style::expression::EvaluationContext { static_cast(this->id.overscaledZ), feature.get() })) { + if (options.filter && !(*options.filter)(style::expression::EvaluationContext{ + static_cast(this->id.overscaledZ), feature.get()})) { continue; } diff --git a/src/mbgl/tile/geojson_tile.hpp b/src/mbgl/tile/geojson_tile.hpp index 240b23e9bce..c6270474312 100644 --- a/src/mbgl/tile/geojson_tile.hpp +++ b/src/mbgl/tile/geojson_tile.hpp @@ -12,16 +12,11 @@ class TileParameters; class GeoJSONTile : public GeometryTile { public: - GeoJSONTile(const OverscaledTileID&, - std::string sourceID, - const TileParameters&, - std::shared_ptr); + GeoJSONTile(const OverscaledTileID&, std::string sourceID, const TileParameters&, std::shared_ptr); void updateData(std::shared_ptr data, bool needsRelayout = false); - void querySourceFeatures( - std::vector& result, - const SourceQueryOptions&) override; + void querySourceFeatures(std::vector& result, const SourceQueryOptions&) override; private: std::shared_ptr data; diff --git a/src/mbgl/tile/geojson_tile_data.hpp b/src/mbgl/tile/geojson_tile_data.hpp index 6353b7151dc..3c6e970acd7 100644 --- a/src/mbgl/tile/geojson_tile_data.hpp +++ b/src/mbgl/tile/geojson_tile_data.hpp @@ -11,20 +11,13 @@ class GeoJSONTileFeature : public GeometryTileFeature { const mapbox::feature::feature& feature; GeoJSONTileFeature(const mapbox::feature::feature& feature_) - : feature(feature_) { - } + : feature(feature_) {} - FeatureType getType() const override { - return apply_visitor(ToFeatureType(), feature.geometry); - } + FeatureType getType() const override { return apply_visitor(ToFeatureType(), feature.geometry); } - const PropertyMap& getProperties() const override { - return feature.properties; - } + const PropertyMap& getProperties() const override { return feature.properties; } - FeatureIdentifier getID() const override { - return feature.id; - } + FeatureIdentifier getID() const override { return feature.id; } const GeometryCollection& getGeometries() const override { if (!geometry) { @@ -53,20 +46,15 @@ class GeoJSONTileFeature : public GeometryTileFeature { class GeoJSONTileLayer : public GeometryTileLayer { public: GeoJSONTileLayer(std::shared_ptr> features_) - : features(std::move(features_)) { - } + : features(std::move(features_)) {} - std::size_t featureCount() const override { - return features->size(); - } + std::size_t featureCount() const override { return features->size(); } std::unique_ptr getFeature(std::size_t i) const override { return std::make_unique((*features)[i]); } - std::string getName() const override { - return ""; - } + std::string getName() const override { return ""; } private: std::shared_ptr> features; @@ -75,23 +63,17 @@ class GeoJSONTileLayer : public GeometryTileLayer { class GeoJSONTileData : public GeometryTileData { public: GeoJSONTileData(mapbox::feature::feature_collection features_) - : features(std::make_shared>( - std::move(features_))) { - } + : features(std::make_shared>(std::move(features_))) {} GeoJSONTileData(std::shared_ptr> features_) - : features(std::move(features_)) { - } + : features(std::move(features_)) {} - std::unique_ptr clone() const override { - return std::make_unique(features); - } + std::unique_ptr clone() const override { return std::make_unique(features); } std::unique_ptr getLayer(const std::string&) const override { return std::make_unique(features); } - private: std::shared_ptr> features; }; diff --git a/src/mbgl/tile/geometry_tile.cpp b/src/mbgl/tile/geometry_tile.cpp index d3f72582e22..799227712bf 100644 --- a/src/mbgl/tile/geometry_tile.cpp +++ b/src/mbgl/tile/geometry_tile.cpp @@ -36,17 +36,16 @@ LayerRenderData* GeometryTile::LayoutResult::getLayerRenderData(const style::Lay // Layer data might be outdated, see issue #12432. return nullptr; } - return &result; + return &result; } class GeometryTileRenderData final : public TileRenderData { public: GeometryTileRenderData( - std::shared_ptr layoutResult_, - std::shared_ptr atlasTextures_) - : TileRenderData(std::move(atlasTextures_)) - , layoutResult(std::move(layoutResult_)) { - } + std::shared_ptr layoutResult_, std::shared_ptr atlasTextures_ + ) + : TileRenderData(std::move(atlasTextures_)), + layoutResult(std::move(layoutResult_)) {} private: // TileRenderData overrides. @@ -76,7 +75,7 @@ std::optional GeometryTileRenderData::getPattern(const std::strin void GeometryTileRenderData::upload(gfx::UploadPass& uploadPass) { if (!layoutResult) return; - auto uploadFn = [&] (Bucket& bucket) { + auto uploadFn = [&](Bucket& bucket) { if (bucket.needsUpload()) { bucket.upload(uploadPass); } @@ -100,10 +99,12 @@ void GeometryTileRenderData::upload(gfx::UploadPass& uploadPass) { if (atlasTextures->icon && !imagePatches.empty()) { for (const auto& imagePatch : imagePatches) { // patch updated images. - uploadPass.updateTextureSub(*atlasTextures->icon, - imagePatch.image->image, - imagePatch.paddedRect.x + ImagePosition::padding, - imagePatch.paddedRect.y + ImagePosition::padding); + uploadPass.updateTextureSub( + *atlasTextures->icon, + imagePatch.image->image, + imagePatch.paddedRect.x + ImagePosition::padding, + imagePatch.paddedRect.y + ImagePosition::padding + ); } imagePatches.clear(); } @@ -116,14 +117,13 @@ void GeometryTileRenderData::prepare(const SourcePrepareParameters& parameters) Bucket* GeometryTileRenderData::getBucket(const Layer::Impl& layer) const { const LayerRenderData* data = getLayerRenderData(layer); - return data ? data->bucket.get() : nullptr; + return data ? data->bucket.get() : nullptr; } const LayerRenderData* GeometryTileRenderData::getLayerRenderData(const style::Layer::Impl& layerImpl) const { return layoutResult ? layoutResult->getLayerRenderData(layerImpl) : nullptr; } - /* Correlation between GeometryTile and GeometryTileWorker is safeguarded by two correlation schemes: @@ -140,27 +140,26 @@ const LayerRenderData* GeometryTileRenderData::getLayerRenderData(const style::L that could flag the tile as non-pending too early. */ -GeometryTile::GeometryTile(const OverscaledTileID& id_, - std::string sourceID_, - const TileParameters& parameters) +GeometryTile::GeometryTile(const OverscaledTileID& id_, std::string sourceID_, const TileParameters& parameters) : Tile(Kind::Geometry, id_), ImageRequestor(parameters.imageManager), sourceID(std::move(sourceID_)), mailbox(std::make_shared(*Scheduler::GetCurrent())), - worker(Scheduler::GetBackground(), - ActorRef(*this, mailbox), - id_, - sourceID, - obsolete, - parameters.mode, - parameters.pixelRatio, - parameters.debugOptions & MapDebugOptions::Collision), + worker( + Scheduler::GetBackground(), + ActorRef(*this, mailbox), + id_, + sourceID, + obsolete, + parameters.mode, + parameters.pixelRatio, + parameters.debugOptions & MapDebugOptions::Collision + ), fileSource(parameters.fileSource), glyphManager(parameters.glyphManager), imageManager(parameters.imageManager), mode(parameters.mode), - showCollisionBoxes(parameters.debugOptions & MapDebugOptions::Collision) { -} + showCollisionBoxes(parameters.debugOptions & MapDebugOptions::Collision) {} GeometryTile::~GeometryTile() { glyphManager.removeRequestor(*this); @@ -187,7 +186,8 @@ void GeometryTile::setData(std::unique_ptr data_) { ++correlationID; worker.self().invoke( - &GeometryTileWorker::setData, std::move(data_), imageManager.getAvailableImages(), correlationID); + &GeometryTileWorker::setData, std::move(data_), imageManager.getAvailableImages(), correlationID + ); } void GeometryTile::reset() { @@ -217,8 +217,7 @@ void GeometryTile::setLayers(const std::vector>& laye assert(layerImpl.getTypeInfo()->source != LayerTypeInfo::Source::NotRequired); assert(layerImpl.source == sourceID); assert(layerImpl.visibility != VisibilityType::None); - if (id.overscaledZ < std::floor(layerImpl.minZoom) || - id.overscaledZ >= std::ceil(layerImpl.maxZoom)) { + if (id.overscaledZ < std::floor(layerImpl.minZoom) || id.overscaledZ >= std::ceil(layerImpl.maxZoom)) { continue; } @@ -227,7 +226,8 @@ void GeometryTile::setLayers(const std::vector>& laye ++correlationID; worker.self().invoke( - &GeometryTileWorker::setLayers, std::move(impls), imageManager.getAvailableImages(), correlationID); + &GeometryTileWorker::setLayers, std::move(impls), imageManager.getAvailableImages(), correlationID + ); } void GeometryTile::setShowCollisionBoxes(const bool showCollisionBoxes_) { @@ -247,9 +247,9 @@ void GeometryTile::onLayout(std::shared_ptr result, const uint64_t layoutResult = std::move(result); if (!atlasTextures) { - atlasTextures = std::make_shared(); + atlasTextures = std::make_shared(); } - + observer->onTileChanged(*this); } @@ -260,7 +260,7 @@ void GeometryTile::onError(std::exception_ptr err, const uint64_t resultCorrelat } observer->onTileError(*this, std::move(err)); } - + void GeometryTile::onGlyphsAvailable(GlyphMap glyphs) { worker.self().invoke(&GeometryTileWorker::onGlyphsAvailable, std::move(glyphs)); } @@ -271,8 +271,16 @@ void GeometryTile::getGlyphs(GlyphDependencies glyphDependencies) { } } -void GeometryTile::onImagesAvailable(ImageMap images, ImageMap patterns, ImageVersionMap versionMap, uint64_t imageCorrelationID) { - worker.self().invoke(&GeometryTileWorker::onImagesAvailable, std::move(images), std::move(patterns), std::move(versionMap), imageCorrelationID); +void GeometryTile::onImagesAvailable( + ImageMap images, ImageMap patterns, ImageVersionMap versionMap, uint64_t imageCorrelationID +) { + worker.self().invoke( + &GeometryTileWorker::onImagesAvailable, + std::move(images), + std::move(patterns), + std::move(versionMap), + imageCorrelationID + ); } void GeometryTile::getImages(ImageRequestPair pair) { @@ -299,7 +307,7 @@ bool GeometryTile::layerPropertiesUpdated(const ImmutablefeatureIndex) { - return nullptr; + return nullptr; } return layoutResult->featureIndex->getData(); } @@ -319,11 +327,15 @@ float GeometryTile::getQueryPadding(const std::unordered_map>& result, - const GeometryCoordinates& queryGeometry, const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, const mat4& projMatrix, - const SourceFeatureState& featureState) { +void GeometryTile::queryRenderedFeatures( + std::unordered_map>& result, + const GeometryCoordinates& queryGeometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix, + const SourceFeatureState& featureState +) { if (!getData()) return; const float queryPadding = getQueryPadding(layers); @@ -332,21 +344,27 @@ void GeometryTile::queryRenderedFeatures(std::unordered_mapfeatureIndex->query(result, queryGeometry, transformState, posMatrix, - util::tileSize_D * id.overscaleFactor(), - std::pow(2, transformState.getZoom() - id.overscaledZ), options, id.toUnwrapped(), - layers, queryPadding * transformState.maxPitchScaleFactor(), featureState); -} - -void GeometryTile::querySourceFeatures( - std::vector& result, - const SourceQueryOptions& options) { - + layoutResult->featureIndex->query( + result, + queryGeometry, + transformState, + posMatrix, + util::tileSize_D * id.overscaleFactor(), + std::pow(2, transformState.getZoom() - id.overscaledZ), + options, + id.toUnwrapped(), + layers, + queryPadding * transformState.maxPitchScaleFactor(), + featureState + ); +} + +void GeometryTile::querySourceFeatures(std::vector& result, const SourceQueryOptions& options) { // Data not yet available, or tile is empty if (!getData()) { return; } - + // No source layers, specified, nothing to do if (!options.sourceLayers) { Log::Warning(Event::General, "At least one sourceLayer required"); @@ -357,14 +375,15 @@ void GeometryTile::querySourceFeatures( // Go throught all sourceLayers, if any // to gather all the features auto layer = getData()->getLayer(sourceLayer); - + if (layer) { auto featureCount = layer->featureCount(); for (std::size_t i = 0; i < featureCount; i++) { auto feature = layer->getFeature(i); // Apply filter, if any - if (options.filter && !(*options.filter)(style::expression::EvaluationContext { static_cast(this->id.overscaledZ), feature.get() })) { + if (options.filter && !(*options.filter)(style::expression::EvaluationContext{ + static_cast(this->id.overscaledZ), feature.get()})) { continue; } diff --git a/src/mbgl/tile/geometry_tile.hpp b/src/mbgl/tile/geometry_tile.hpp index 769bce3f5c8..a067daf624c 100644 --- a/src/mbgl/tile/geometry_tile.hpp +++ b/src/mbgl/tile/geometry_tile.hpp @@ -27,9 +27,7 @@ class TileAtlasTextures; class GeometryTile : public Tile, public GlyphRequestor, public ImageRequestor { public: - GeometryTile(const OverscaledTileID&, - std::string sourceID, - const TileParameters&); + GeometryTile(const OverscaledTileID&, std::string sourceID, const TileParameters&); ~GeometryTile() override; @@ -45,21 +43,23 @@ class GeometryTile : public Tile, public GlyphRequestor, public ImageRequestor { void onGlyphsAvailable(GlyphMap) override; void onImagesAvailable(ImageMap, ImageMap, ImageVersionMap versionMap, uint64_t imageCorrelationID) override; - + void getGlyphs(GlyphDependencies); void getImages(ImageRequestPair); bool layerPropertiesUpdated(const Immutable&) override; - void queryRenderedFeatures(std::unordered_map>& result, - const GeometryCoordinates& queryGeometry, const TransformState&, - const std::unordered_map& layers, - const RenderedQueryOptions& options, const mat4& projMatrix, - const SourceFeatureState& featureState) override; + void queryRenderedFeatures( + std::unordered_map>& result, + const GeometryCoordinates& queryGeometry, + const TransformState&, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix, + const SourceFeatureState& featureState + ) override; - void querySourceFeatures( - std::vector& result, - const SourceQueryOptions&) override; + void querySourceFeatures(std::vector& result, const SourceQueryOptions&) override; float getQueryPadding(const std::unordered_map&) override; @@ -74,10 +74,12 @@ class GeometryTile : public Tile, public GlyphRequestor, public ImageRequestor { LayerRenderData* getLayerRenderData(const style::Layer::Impl&); - LayoutResult(std::unordered_map renderData_, - std::unique_ptr featureIndex_, - std::optional glyphAtlasImage_, - ImageAtlas iconAtlas_) + LayoutResult( + std::unordered_map renderData_, + std::unique_ptr featureIndex_, + std::optional glyphAtlasImage_, + ImageAtlas iconAtlas_ + ) : layerRenderData(std::move(renderData_)), featureIndex(std::move(featureIndex_)), glyphAtlasImage(std::move(glyphAtlasImage_)), @@ -105,7 +107,7 @@ class GeometryTile : public Tile, public GlyphRequestor, public ImageRequestor { void markObsolete(); // Used to signal the worker that it should abandon parsing this tile as soon as possible. - std::atomic obsolete { false }; + std::atomic obsolete{false}; std::shared_ptr mailbox; Actor worker; @@ -120,9 +122,9 @@ class GeometryTile : public Tile, public GlyphRequestor, public ImageRequestor { std::shared_ptr atlasTextures; const MapMode mode; - + bool showCollisionBoxes; - + enum class FadeState { Loaded, NeedsFirstPlacement, diff --git a/src/mbgl/tile/geometry_tile_data.cpp b/src/mbgl/tile/geometry_tile_data.cpp index 9062ebad4c3..e97ec747cd2 100644 --- a/src/mbgl/tile/geometry_tile_data.cpp +++ b/src/mbgl/tile/geometry_tile_data.cpp @@ -99,12 +99,12 @@ std::vector classifyRings(const GeometryCollection& rings) { void limitHoles(GeometryCollection& polygon, uint32_t maxHoles) { if (polygon.size() > 1 + maxHoles) { - std::nth_element(polygon.begin() + 1, - polygon.begin() + 1 + maxHoles, - polygon.end(), - [] (const auto& a, const auto& b) { - return std::fabs(signedArea(a)) > std::fabs(signedArea(b)); - }); + std::nth_element( + polygon.begin() + 1, + polygon.begin() + 1 + maxHoles, + polygon.end(), + [](const auto& a, const auto& b) { return std::fabs(signedArea(a)) > std::fabs(signedArea(b)); } + ); polygon.resize(1 + maxHoles); } } @@ -114,12 +114,9 @@ Feature::geometry_type convertGeometry(const GeometryTileFeature& geometryTileFe const double x0 = util::EXTENT * static_cast(tileID.x); const double y0 = util::EXTENT * static_cast(tileID.y); - auto tileCoordinatesToLatLng = [&] (const Point& p) { + auto tileCoordinatesToLatLng = [&](const Point& p) { double y2 = 180 - (p.y + y0) * 360 / size; - return Point( - (p.x + x0) * 360 / size - 180, - std::atan(std::exp(y2 * M_PI / 180)) * 360.0 / M_PI - 90.0 - ); + return Point((p.x + x0) * 360 / size - 180, std::atan(std::exp(y2 * M_PI / 180)) * 360.0 / M_PI - 90.0); }; const GeometryCollection& geometries = geometryTileFeature.getGeometries(); @@ -192,12 +189,14 @@ GeometryCollection convertGeometry(const Feature::geometry_type& geometryTileFea Point p; auto x = (c.x + 180.0) * size / 360.0 - x0; - p.x = - int16_t(util::clamp(static_cast(x), std::numeric_limits::min(), std::numeric_limits::max())); + p.x = int16_t(util::clamp( + static_cast(x), std::numeric_limits::min(), std::numeric_limits::max() + )); auto y = (180 - (std::log(std::tan((c.y + 90) * M_PI / 360.0)) * 180 / M_PI)) * size / 360 - y0; - p.y = - int16_t(util::clamp(static_cast(y), std::numeric_limits::min(), std::numeric_limits::max())); + p.y = int16_t(util::clamp( + static_cast(y), std::numeric_limits::min(), std::numeric_limits::max() + )); return p; }; @@ -261,11 +260,12 @@ GeometryCollection convertGeometry(const Feature::geometry_type& geometryTileFea } return result; }, - [](const auto&) -> GeometryCollection { return GeometryCollection(); }); + [](const auto&) -> GeometryCollection { return GeometryCollection(); } + ); } Feature convertFeature(const GeometryTileFeature& geometryTileFeature, const CanonicalTileID& tileID) { - Feature feature { convertGeometry(geometryTileFeature, tileID) }; + Feature feature{convertGeometry(geometryTileFeature, tileID)}; feature.properties = geometryTileFeature.getProperties(); feature.id = geometryTileFeature.getID(); return feature; diff --git a/src/mbgl/tile/geometry_tile_data.hpp b/src/mbgl/tile/geometry_tile_data.hpp index 1b8cc3fdc2f..a1657b9fea9 100644 --- a/src/mbgl/tile/geometry_tile_data.hpp +++ b/src/mbgl/tile/geometry_tile_data.hpp @@ -23,8 +23,10 @@ class GeometryCoordinates : public std::vector { using coordinate_type = int16_t; template - GeometryCoordinates(Args&&... args) : std::vector(std::forward(args)...) {} - GeometryCoordinates(std::initializer_list args) : std::vector(args) {} + GeometryCoordinates(Args&&... args) + : std::vector(std::forward(args)...) {} + GeometryCoordinates(std::initializer_list args) + : std::vector(args) {} GeometryCoordinates() = default; }; @@ -32,8 +34,10 @@ class GeometryCollection : public std::vector { public: using coordinate_type = int16_t; template - GeometryCollection(Args&&... args) : std::vector(std::forward(args)...) {} - GeometryCollection(std::initializer_list args) : std::vector(args) {} + GeometryCollection(Args&&... args) + : std::vector(std::forward(args)...) {} + GeometryCollection(std::initializer_list args) + : std::vector(args) {} GeometryCollection(GeometryCollection&&) = default; GeometryCollection& operator=(GeometryCollection&&) = default; GeometryCollection() = default; @@ -50,7 +54,7 @@ class GeometryTileFeature { virtual FeatureType getType() const = 0; virtual std::optional getValue(const std::string& key) const = 0; virtual const PropertyMap& getProperties() const; - virtual FeatureIdentifier getID() const { return NullValue {}; } + virtual FeatureIdentifier getID() const { return NullValue{}; } virtual const GeometryCollection& getGeometries() const; }; @@ -94,18 +98,10 @@ Feature convertFeature(const GeometryTileFeature&, const CanonicalTileID&); GeometryCollection fixupPolygons(const GeometryCollection&); struct ToGeometryCollection { - GeometryCollection operator()(const mapbox::geometry::empty&) const { - return GeometryCollection(); - } - GeometryCollection operator()(const mapbox::geometry::point& geom) const { - return { { geom } }; - } - GeometryCollection operator()(const mapbox::geometry::multi_point& geom) const { - return { geom }; - } - GeometryCollection operator()(const mapbox::geometry::line_string& geom) const { - return { geom }; - } + GeometryCollection operator()(const mapbox::geometry::empty&) const { return GeometryCollection(); } + GeometryCollection operator()(const mapbox::geometry::point& geom) const { return {{geom}}; } + GeometryCollection operator()(const mapbox::geometry::multi_point& geom) const { return {geom}; } + GeometryCollection operator()(const mapbox::geometry::line_string& geom) const { return {geom}; } GeometryCollection operator()(const mapbox::geometry::multi_line_string& geom) const { GeometryCollection collection; collection.reserve(geom.size()); diff --git a/src/mbgl/tile/geometry_tile_worker.cpp b/src/mbgl/tile/geometry_tile_worker.cpp index 7025392b10d..3776b13d024 100644 --- a/src/mbgl/tile/geometry_tile_worker.cpp +++ b/src/mbgl/tile/geometry_tile_worker.cpp @@ -27,14 +27,16 @@ namespace mbgl { using namespace style; -GeometryTileWorker::GeometryTileWorker(ActorRef self_, - ActorRef parent_, - OverscaledTileID id_, - std::string sourceID_, - const std::atomic& obsolete_, - const MapMode mode_, - const float pixelRatio_, - const bool showCollisionBoxes_) +GeometryTileWorker::GeometryTileWorker( + ActorRef self_, + ActorRef parent_, + OverscaledTileID id_, + std::string sourceID_, + const std::atomic& obsolete_, + const MapMode mode_, + const float pixelRatio_, + const bool showCollisionBoxes_ +) : self(std::move(self_)), parent(std::move(parent_)), id(id_), @@ -79,11 +81,11 @@ GeometryTileWorker::~GeometryTileWorker() = default; At the end of processing, we self-send "coalesced", read all the queued messages until we get to "coalesced", and then re-parse if there were one or more "set"s or return to the [idle] state if not. - + One important goal of the design is to prevent starvation. Under heavy load new requests for tiles should not prevent in progress request from completing. It is nevertheless possible to restart an in-progress request: - + - [Idle] setData -> parse() sends getGlyphs, hasPendingDependencies() is true enters [Coalescing], sends coalesced @@ -96,17 +98,17 @@ GeometryTileWorker::~GeometryTileWorker() = default; - [NeedsSymbolLayout] coalesced -> finalizeLayout() Generates result depending on whether dependencies are met -> [Idle] - + In this situation, we are counting on the idea that even with rapid changes to the tile's data, the set of glyphs/images it requires will not keep growing without limit. - + Although parsing (which populates all non-symbol buckets and requests dependencies for symbol buckets) is internally separate from symbol layout, we only return results to the foreground when we have completed both steps. Because we _move_ the result buckets to the foreground, it is necessary to re-generate all buckets from scratch for `setShowCollisionBoxes`, even though it only affects symbol layers. - + The GL JS equivalent (in worker_tile.js and vector_tile_worker_source.js) is somewhat simpler because it relies on getGlyphs/getImages calls that transfer an entire set of glyphs/images on every tile load, while the native logic @@ -116,52 +118,52 @@ GeometryTileWorker::~GeometryTileWorker() = default; completed parse. */ -void GeometryTileWorker::setData(std::unique_ptr data_, - std::set availableImages_, - uint64_t correlationID_) { +void GeometryTileWorker::setData( + std::unique_ptr data_, std::set availableImages_, uint64_t correlationID_ +) { try { data = std::move(data_); correlationID = correlationID_; availableImages = std::move(availableImages_); switch (state) { - case Idle: - parse(); - coalesce(); - break; + case Idle: + parse(); + coalesce(); + break; - case Coalescing: - case NeedsParse: - case NeedsSymbolLayout: - state = NeedsParse; - break; + case Coalescing: + case NeedsParse: + case NeedsSymbolLayout: + state = NeedsParse; + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); } } -void GeometryTileWorker::setLayers(std::vector> layers_, - std::set availableImages_, - uint64_t correlationID_) { +void GeometryTileWorker::setLayers( + std::vector> layers_, std::set availableImages_, uint64_t correlationID_ +) { try { layers = std::move(layers_); correlationID = correlationID_; availableImages = std::move(availableImages_); switch (state) { - case Idle: - parse(); - coalesce(); - break; + case Idle: + parse(); + coalesce(); + break; - case Coalescing: - case NeedsSymbolLayout: - state = NeedsParse; - break; + case Coalescing: + case NeedsSymbolLayout: + state = NeedsParse; + break; - case NeedsParse: - break; + case NeedsParse: + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); @@ -190,22 +192,22 @@ void GeometryTileWorker::setShowCollisionBoxes(bool showCollisionBoxes_, uint64_ correlationID = correlationID_; switch (state) { - case Idle: - if (!hasPendingParseResult()) { - // Trigger parse if nothing is in flight, otherwise symbol layout will automatically - // pick up the change - parse(); - coalesce(); - } - break; + case Idle: + if (!hasPendingParseResult()) { + // Trigger parse if nothing is in flight, otherwise symbol layout will automatically + // pick up the change + parse(); + coalesce(); + } + break; - case Coalescing: - state = NeedsSymbolLayout; - break; + case Coalescing: + state = NeedsSymbolLayout; + break; - case NeedsSymbolLayout: - case NeedsParse: - break; + case NeedsSymbolLayout: + case NeedsParse: + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); @@ -215,25 +217,25 @@ void GeometryTileWorker::setShowCollisionBoxes(bool showCollisionBoxes_, uint64_ void GeometryTileWorker::symbolDependenciesChanged() { try { switch (state) { - case Idle: - if (!layouts.empty()) { - // Layouts are created only by parsing and the parse result can only be - // cleared by performLayout, which also clears the layouts. - assert(hasPendingParseResult()); - finalizeLayout(); - coalesce(); - } - break; + case Idle: + if (!layouts.empty()) { + // Layouts are created only by parsing and the parse result can only be + // cleared by performLayout, which also clears the layouts. + assert(hasPendingParseResult()); + finalizeLayout(); + coalesce(); + } + break; - case Coalescing: - if (!layouts.empty()) { - state = NeedsSymbolLayout; - } - break; + case Coalescing: + if (!layouts.empty()) { + state = NeedsSymbolLayout; + } + break; - case NeedsSymbolLayout: - case NeedsParse: - break; + case NeedsSymbolLayout: + case NeedsParse: + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); @@ -243,26 +245,26 @@ void GeometryTileWorker::symbolDependenciesChanged() { void GeometryTileWorker::coalesced() { try { switch (state) { - case Idle: - assert(false); - break; + case Idle: + assert(false); + break; - case Coalescing: - state = Idle; - break; + case Coalescing: + state = Idle; + break; - case NeedsParse: - parse(); - coalesce(); - break; + case NeedsParse: + parse(); + coalesce(); + break; - case NeedsSymbolLayout: - // We may have entered NeedsSymbolLayout while coalescing - // after a performLayout. In that case, we need to - // start over with parsing in order to do another layout. - hasPendingParseResult() ? finalizeLayout() : parse(); - coalesce(); - break; + case NeedsSymbolLayout: + // We may have entered NeedsSymbolLayout while coalescing + // after a performLayout. In that case, we need to + // start over with parsing in order to do another layout. + hasPendingParseResult() ? finalizeLayout() : parse(); + coalesce(); + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); @@ -300,7 +302,9 @@ void GeometryTileWorker::onGlyphsAvailable(GlyphMap newGlyphMap) { symbolDependenciesChanged(); } -void GeometryTileWorker::onImagesAvailable(ImageMap newIconMap, ImageMap newPatternMap, ImageVersionMap newVersionMap, uint64_t imageCorrelationID_) { +void GeometryTileWorker::onImagesAvailable( + ImageMap newIconMap, ImageMap newPatternMap, ImageVersionMap newVersionMap, uint64_t imageCorrelationID_ +) { if (imageCorrelationID != imageCorrelationID_) { return; // Ignore outdated image request replies. } @@ -367,7 +371,7 @@ void GeometryTileWorker::parse() { } const style::Layer::Impl& leaderImpl = *(group.at(0)->baseImpl); - BucketParameters parameters { id, mode, pixelRatio, leaderImpl.getTypeInfo() }; + BucketParameters parameters{id, mode, pixelRatio, leaderImpl.getTypeInfo()}; auto geometryLayer = (*data)->getLayer(leaderImpl.sourceLayer); if (!geometryLayer) { @@ -381,13 +385,14 @@ void GeometryTileWorker::parse() { featureIndex->setBucketLayerIDs(leaderImpl.id, layerIDs); - // Symbol layers and layers that support pattern properties have an extra step at layout time to figure out what images/glyphs - // are needed to render the layer. They use the intermediate Layout data structure to accomplish this, - // and either immediately create a bucket if no images/glyphs are used, or the Layout is stored until - // the images/glyphs are available to add the features to the buckets. + // Symbol layers and layers that support pattern properties have an extra step at layout time to figure out what + // images/glyphs are needed to render the layer. They use the intermediate Layout data structure to accomplish + // this, and either immediately create a bucket if no images/glyphs are used, or the Layout is stored until the + // images/glyphs are available to add the features to the buckets. if (leaderImpl.getTypeInfo()->layout == LayerTypeInfo::Layout::Required) { std::unique_ptr layout = LayerManager::get()->createLayout( - {parameters, glyphDependencies, imageDependencies, availableImages}, std::move(geometryLayer), group); + {parameters, glyphDependencies, imageDependencies, availableImages}, std::move(geometryLayer), group + ); if (layout->hasDependencies()) { layouts.push_back(std::move(layout)); } else { @@ -423,11 +428,13 @@ void GeometryTileWorker::parse() { requestNewGlyphs(glyphDependencies); requestNewImages(imageDependencies); - MBGL_TIMING_FINISH(watch, - " Action: " << "Parsing," << - " SourceID: " << sourceID.c_str() << - " Canonical: " << static_cast(id.canonical.z) << "/" << id.canonical.x << "/" << id.canonical.y << - " Time"); + MBGL_TIMING_FINISH( + watch, + " Action: " + << "Parsing," + << " SourceID: " << sourceID.c_str() << " Canonical: " << static_cast(id.canonical.z) << "/" + << id.canonical.x << "/" << id.canonical.y << " Time" + ); finalizeLayout(); } @@ -439,7 +446,7 @@ bool GeometryTileWorker::hasPendingDependencies() const { } return !pendingImageDependencies.empty(); } - + bool GeometryTileWorker::hasPendingParseResult() const { return bool(featureIndex); } @@ -448,7 +455,7 @@ void GeometryTileWorker::finalizeLayout() { if (!data || !layers || !hasPendingParseResult() || hasPendingDependencies()) { return; } - + MBGL_TIMING_START(watch) std::optional glyphAtlasImage; ImageAtlas iconAtlas = makeImageAtlas(imageMap, patternMap, versionMap); @@ -469,26 +476,30 @@ void GeometryTileWorker::finalizeLayout() { // layout adds the bucket to buckets layout->createBucket( - iconAtlas.patternPositions, featureIndex, renderData, firstLoad, showCollisionBoxes, id.canonical); + iconAtlas.patternPositions, featureIndex, renderData, firstLoad, showCollisionBoxes, id.canonical + ); } } layouts.clear(); firstLoad = false; - - MBGL_TIMING_FINISH(watch, - " Action: " << "SymbolLayout," << - " SourceID: " << sourceID.c_str() << - " Canonical: " << static_cast(id.canonical.z) << "/" << id.canonical.x << "/" << id.canonical.y << - " Time"); - - parent.invoke(&GeometryTile::onLayout, std::make_shared( - std::move(renderData), - std::move(featureIndex), - std::move(glyphAtlasImage), - std::move(iconAtlas) - ), correlationID); + + MBGL_TIMING_FINISH( + watch, + " Action: " + << "SymbolLayout," + << " SourceID: " << sourceID.c_str() << " Canonical: " << static_cast(id.canonical.z) << "/" + << id.canonical.x << "/" << id.canonical.y << " Time" + ); + + parent.invoke( + &GeometryTile::onLayout, + std::make_shared( + std::move(renderData), std::move(featureIndex), std::move(glyphAtlasImage), std::move(iconAtlas) + ), + correlationID + ); } } // namespace mbgl diff --git a/src/mbgl/tile/geometry_tile_worker.hpp b/src/mbgl/tile/geometry_tile_worker.hpp index 9dacf2ea968..8f3159e7907 100644 --- a/src/mbgl/tile/geometry_tile_worker.hpp +++ b/src/mbgl/tile/geometry_tile_worker.hpp @@ -27,41 +27,42 @@ class Layer; class GeometryTileWorker { public: - GeometryTileWorker(ActorRef self, - ActorRef parent, - OverscaledTileID, - std::string, - const std::atomic&, - MapMode, - float pixelRatio, - bool showCollisionBoxes_); + GeometryTileWorker( + ActorRef self, + ActorRef parent, + OverscaledTileID, + std::string, + const std::atomic&, + MapMode, + float pixelRatio, + bool showCollisionBoxes_ + ); ~GeometryTileWorker(); - void setLayers(std::vector>, - std::set availableImages, - uint64_t correlationID); - void setData(std::unique_ptr, - std::set availableImages, - uint64_t correlationID); + void setLayers( + std::vector>, std::set availableImages, uint64_t correlationID + ); + void setData( + std::unique_ptr, std::set availableImages, uint64_t correlationID + ); void reset(uint64_t correlationID_); void setShowCollisionBoxes(bool showCollisionBoxes_, uint64_t correlationID_); void onGlyphsAvailable(GlyphMap newGlyphMap); - void onImagesAvailable(ImageMap newIconMap, - ImageMap newPatternMap, - ImageVersionMap versionMap, - uint64_t imageCorrelationID); + void onImagesAvailable( + ImageMap newIconMap, ImageMap newPatternMap, ImageVersionMap versionMap, uint64_t imageCorrelationID + ); private: void coalesced(); void parse(); void finalizeLayout(); - + void coalesce(); void requestNewGlyphs(const GlyphDependencies&); void requestNewImages(const ImageDependencies&); - + void symbolDependenciesChanged(); bool hasPendingDependencies() const; bool hasPendingParseResult() const; @@ -76,7 +77,7 @@ class GeometryTileWorker { const std::atomic& obsolete; const MapMode mode; const float pixelRatio; - + std::unique_ptr featureIndex; std::unordered_map renderData; diff --git a/src/mbgl/tile/raster_dem_tile.cpp b/src/mbgl/tile/raster_dem_tile.cpp index 19160c10ef4..cb968aa0ecf 100644 --- a/src/mbgl/tile/raster_dem_tile.cpp +++ b/src/mbgl/tile/raster_dem_tile.cpp @@ -14,22 +14,18 @@ namespace mbgl { -RasterDEMTile::RasterDEMTile(const OverscaledTileID& id_, - const TileParameters& parameters, - const Tileset& tileset) +RasterDEMTile::RasterDEMTile(const OverscaledTileID& id_, const TileParameters& parameters, const Tileset& tileset) : Tile(Kind::RasterDEM, id_), loader(*this, id_, parameters, tileset), mailbox(std::make_shared(*Scheduler::GetCurrent())), - worker(Scheduler::GetBackground(), - ActorRef(*this, mailbox)) { - + worker(Scheduler::GetBackground(), ActorRef(*this, mailbox)) { encoding = tileset.encoding; - if ( id.canonical.y == 0 ){ + if (id.canonical.y == 0) { // this tile doesn't have upper neighboring tiles so marked those as backfilled neighboringTiles = neighboringTiles | DEMTileNeighbors::NoUpper; } - if (id.canonical.y + 1 == std::pow(2, id.canonical.z)){ + if (id.canonical.y + 1 == std::pow(2, id.canonical.z)) { // this tile doesn't have lower neighboring tiles so marked those as backfilled neighboringTiles = neighboringTiles | DEMTileNeighbors::NoLower; } diff --git a/src/mbgl/tile/raster_dem_tile.hpp b/src/mbgl/tile/raster_dem_tile.hpp index 21f189556ed..337dd370101 100644 --- a/src/mbgl/tile/raster_dem_tile.hpp +++ b/src/mbgl/tile/raster_dem_tile.hpp @@ -12,35 +12,35 @@ class TileParameters; class HillshadeBucket; enum class DEMTileNeighbors : uint8_t { - // 0b00000000 - Empty = 0 << 1, - - // 0b00000001 - Left = 1 << 0, - // 0b00000010 - Right = 1 << 1, - // 0b00000100 - TopLeft = 1 << 2, - // 0b00001000 - TopCenter = 1 << 3, - // 0b00010000 - TopRight = 1 << 4, - // 0b00100000 - BottomLeft = 1 << 5, - // 0b01000000 - BottomCenter = 1 << 6, - // 0b10000000 - BottomRight = 1 << 7, - - // helper enums for tiles with no upper/lower neighbors - // and completely backfilled tiles - - // 0b00011100 - NoUpper = 0b00011100, - // 0b11100000 - NoLower = 0b11100000, - // 0b11111111 - Complete = 0b11111111 + // 0b00000000 + Empty = 0 << 1, + + // 0b00000001 + Left = 1 << 0, + // 0b00000010 + Right = 1 << 1, + // 0b00000100 + TopLeft = 1 << 2, + // 0b00001000 + TopCenter = 1 << 3, + // 0b00010000 + TopRight = 1 << 4, + // 0b00100000 + BottomLeft = 1 << 5, + // 0b01000000 + BottomCenter = 1 << 6, + // 0b10000000 + BottomRight = 1 << 7, + + // helper enums for tiles with no upper/lower neighbors + // and completely backfilled tiles + + // 0b00011100 + NoUpper = 0b00011100, + // 0b11100000 + NoLower = 0b11100000, + // 0b11111111 + Complete = 0b11111111 }; inline DEMTileNeighbors operator|(DEMTileNeighbors a, DEMTileNeighbors b) { @@ -61,9 +61,7 @@ class Layer; class RasterDEMTile final : public Tile { public: - RasterDEMTile(const OverscaledTileID&, - const TileParameters&, - const Tileset&); + RasterDEMTile(const OverscaledTileID&, const TileParameters&, const Tileset&); ~RasterDEMTile() override; std::unique_ptr createRenderData() override; @@ -82,7 +80,7 @@ class RasterDEMTile final : public Tile { // neighboringTiles is a bitmask for which neighboring tiles have been backfilled // there are max 8 possible neighboring tiles, so each bit represents one neighbor DEMTileNeighbors neighboringTiles = DEMTileNeighbors::Empty; - + void setMask(TileMask&&) override; void onParsed(std::unique_ptr result, uint64_t correlationID); @@ -93,14 +91,13 @@ class RasterDEMTile final : public Tile { std::shared_ptr mailbox; Actor worker; - + uint64_t correlationID = 0; Tileset::DEMEncoding encoding; // Contains the Bucket object for the tile. Buckets are render // objects and they get added by tile parsing operations. std::shared_ptr bucket; - }; } // namespace mbgl diff --git a/src/mbgl/tile/raster_dem_tile_worker.cpp b/src/mbgl/tile/raster_dem_tile_worker.cpp index 92fe3d919a2..edb52ac37ad 100644 --- a/src/mbgl/tile/raster_dem_tile_worker.cpp +++ b/src/mbgl/tile/raster_dem_tile_worker.cpp @@ -9,9 +9,9 @@ namespace mbgl { RasterDEMTileWorker::RasterDEMTileWorker(const ActorRef&, ActorRef parent_) : parent(std::move(parent_)) {} -void RasterDEMTileWorker::parse(const std::shared_ptr& data, - uint64_t correlationID, - Tileset::DEMEncoding encoding) { +void RasterDEMTileWorker::parse( + const std::shared_ptr& data, uint64_t correlationID, Tileset::DEMEncoding encoding +) { if (!data) { parent.invoke(&RasterDEMTile::onParsed, nullptr, correlationID); // No data; empty tile. return; diff --git a/src/mbgl/tile/raster_tile.cpp b/src/mbgl/tile/raster_tile.cpp index 371eb3b48b7..58192e5e047 100644 --- a/src/mbgl/tile/raster_tile.cpp +++ b/src/mbgl/tile/raster_tile.cpp @@ -14,15 +14,11 @@ namespace mbgl { -RasterTile::RasterTile(const OverscaledTileID& id_, - const TileParameters& parameters, - const Tileset& tileset) +RasterTile::RasterTile(const OverscaledTileID& id_, const TileParameters& parameters, const Tileset& tileset) : Tile(Kind::Raster, id_), loader(*this, id_, parameters, tileset), mailbox(std::make_shared(*Scheduler::GetCurrent())), - worker(Scheduler::GetBackground(), - ActorRef(*this, mailbox)) { -} + worker(Scheduler::GetBackground(), ActorRef(*this, mailbox)) {} RasterTile::~RasterTile() = default; diff --git a/src/mbgl/tile/raster_tile.hpp b/src/mbgl/tile/raster_tile.hpp index bf5ea7152ac..b0cc46e253e 100644 --- a/src/mbgl/tile/raster_tile.hpp +++ b/src/mbgl/tile/raster_tile.hpp @@ -17,9 +17,7 @@ class Layer; class RasterTile final : public Tile { public: - RasterTile(const OverscaledTileID&, - const TileParameters&, - const Tileset&); + RasterTile(const OverscaledTileID&, const TileParameters&, const Tileset&); ~RasterTile() override; std::unique_ptr createRenderData() override; diff --git a/src/mbgl/tile/tile.cpp b/src/mbgl/tile/tile.cpp index eda0367f04f..131a35b3213 100644 --- a/src/mbgl/tile/tile.cpp +++ b/src/mbgl/tile/tile.cpp @@ -8,7 +8,10 @@ namespace mbgl { static TileObserver nullObserver; -Tile::Tile(Kind kind_, OverscaledTileID id_) : kind(kind_), id(id_), observer(&nullObserver) {} +Tile::Tile(Kind kind_, OverscaledTileID id_) + : kind(kind_), + id(id_), + observer(&nullObserver) {} Tile::~Tile() = default; @@ -16,8 +19,7 @@ void Tile::setObserver(TileObserver* observer_) { observer = observer_; } -void Tile::cancel() { -} +void Tile::cancel() {} void Tile::setTriedCache() { triedOptional = true; @@ -27,10 +29,18 @@ void Tile::setTriedCache() { void Tile::dumpDebugLogs() const { std::string kindString; switch (kind) { - case Kind::Geometry: kindString = "Geometry"; break; - case Kind::Raster: kindString = "Raster"; break; - case Kind::RasterDEM: kindString = "RasterDEM"; break; - default: kindString = "Unknown"; break; + case Kind::Geometry: + kindString = "Geometry"; + break; + case Kind::Raster: + kindString = "Raster"; + break; + case Kind::RasterDEM: + kindString = "RasterDEM"; + break; + default: + kindString = "Unknown"; + break; } Log::Info(Event::General, "Tile::Kind: " + kindString); Log::Info(Event::General, "Tile::id: " + util::toString(id)); @@ -39,16 +49,14 @@ void Tile::dumpDebugLogs() const { Log::Info(Event::General, "Tile::loaded: " + std::string(isLoaded() ? "yes" : "no")); } -void Tile::queryRenderedFeatures(std::unordered_map>&, const GeometryCoordinates&, - const TransformState&, const std::unordered_map&, - const RenderedQueryOptions&, const mat4&, const SourceFeatureState&) {} +void Tile:: + queryRenderedFeatures(std::unordered_map>&, const GeometryCoordinates&, const TransformState&, const std::unordered_map&, const RenderedQueryOptions&, const mat4&, const SourceFeatureState&) { +} float Tile::getQueryPadding(const std::unordered_map&) { return 0; } -void Tile::querySourceFeatures( - std::vector&, - const SourceQueryOptions&) {} +void Tile::querySourceFeatures(std::vector&, const SourceQueryOptions&) {} } // namespace mbgl diff --git a/src/mbgl/tile/tile.hpp b/src/mbgl/tile/tile.hpp index 3ab008fc8ce..48d4977b330 100644 --- a/src/mbgl/tile/tile.hpp +++ b/src/mbgl/tile/tile.hpp @@ -74,7 +74,7 @@ class Tile { // // Tile implementation should update the contained layer // render data with the given properties. - // + // // Returns `true` if the corresponding render layer data is present in this tile (and i.e. it // was succesfully updated); returns `false` otherwise. virtual bool layerPropertiesUpdated(const Immutable& layerProperties) = 0; @@ -82,15 +82,17 @@ class Tile { virtual void setLayers(const std::vector>&) {} virtual void setMask(TileMask&&) {} - virtual void queryRenderedFeatures(std::unordered_map>& result, - const GeometryCoordinates& queryGeometry, const TransformState&, - const std::unordered_map&, - const RenderedQueryOptions& options, const mat4& projMatrix, - const SourceFeatureState& featureState); + virtual void queryRenderedFeatures( + std::unordered_map>& result, + const GeometryCoordinates& queryGeometry, + const TransformState&, + const std::unordered_map&, + const RenderedQueryOptions& options, + const mat4& projMatrix, + const SourceFeatureState& featureState + ); - virtual void querySourceFeatures( - std::vector& result, - const SourceQueryOptions&); + virtual void querySourceFeatures(std::vector& result, const SourceQueryOptions&); virtual float getQueryPadding(const std::unordered_map&); @@ -98,38 +100,28 @@ class Tile { // Returns true when the tile source has received a first response, regardless of whether a load // error occurred or actual data was loaded. - bool hasTriedCache() const { - return triedOptional; - } + bool hasTriedCache() const { return triedOptional; } // Tile data considered "Renderable" can be used for rendering. Data in // partial state is still waiting for network resources but can also // be rendered, although layers will be missing. - bool isRenderable() const { - return renderable; - } + bool isRenderable() const { return renderable; } // A tile is "Loaded" when we have received a response from a FileSource, and have attempted to // parse the tile (if applicable). Tile implementations should set this to true when a load // error occurred, or after the tile was parsed successfully. - bool isLoaded() const { - return loaded; - } + bool isLoaded() const { return loaded; } // "Completion" of a tile means that we have attempted to load it, and parsed it completely, // i.e. no parsing or placement operations are pending for that tile. // Completeness doesn't mean that the tile can be rendered, but merely that we have exhausted // all options to get this tile to a renderable state. Some tiles may not be renderable, but // complete, e.g. when a raster tile couldn't be loaded, or parsing failed. - bool isComplete() const { - return loaded && !pending; - } - + bool isComplete() const { return loaded && !pending; } + // "holdForFade" is used to keep tiles in the render tree after they're no longer // ideal tiles in order to allow symbols to fade out - virtual bool holdForFade() const { - return false; - } + virtual bool holdForFade() const { return false; } // Set whenever this tile is used as an ideal tile virtual void markRenderedIdeal() {} // Set when the tile is removed from the ideal render set but may still be held for fading @@ -157,7 +149,6 @@ class Tile { bool pending = false; bool loaded = false; - TileObserver* observer = nullptr; }; diff --git a/src/mbgl/tile/tile_cache.cpp b/src/mbgl/tile/tile_cache.cpp index 272ecdfee58..09bfb928a8c 100644 --- a/src/mbgl/tile/tile_cache.cpp +++ b/src/mbgl/tile/tile_cache.cpp @@ -47,7 +47,6 @@ Tile* TileCache::get(const OverscaledTileID& key) { } std::unique_ptr TileCache::pop(const OverscaledTileID& key) { - std::unique_ptr tile; auto it = tiles.find(key); diff --git a/src/mbgl/tile/tile_cache.hpp b/src/mbgl/tile/tile_cache.hpp index f893124aa4e..d5b295cd9ed 100644 --- a/src/mbgl/tile/tile_cache.hpp +++ b/src/mbgl/tile/tile_cache.hpp @@ -3,7 +3,6 @@ #include #include - #include #include #include @@ -12,7 +11,8 @@ namespace mbgl { class TileCache { public: - TileCache(size_t size_ = 0) : size(size_) {} + TileCache(size_t size_ = 0) + : size(size_) {} void setSize(size_t); size_t getSize() const { return size; }; diff --git a/src/mbgl/tile/tile_loader.hpp b/src/mbgl/tile/tile_loader.hpp index 99d9047f8d4..d894056fe4d 100644 --- a/src/mbgl/tile/tile_loader.hpp +++ b/src/mbgl/tile/tile_loader.hpp @@ -16,10 +16,7 @@ class TileLoader { public: TileLoader(const TileLoader&) = delete; TileLoader& operator=(const TileLoader&) = delete; - TileLoader(T&, - const OverscaledTileID&, - const TileParameters&, - const Tileset&); + TileLoader(T&, const OverscaledTileID&, const TileParameters&, const Tileset&); ~TileLoader(); void setNecessity(TileNecessity newNecessity); diff --git a/src/mbgl/tile/tile_loader_impl.hpp b/src/mbgl/tile/tile_loader_impl.hpp index 3a8094e6306..8fc8c7b8411 100644 --- a/src/mbgl/tile/tile_loader_impl.hpp +++ b/src/mbgl/tile/tile_loader_impl.hpp @@ -15,20 +15,20 @@ inline std::exception_ptr getCantLoadTileError() { } template -TileLoader::TileLoader(T& tile_, - const OverscaledTileID& id, - const TileParameters& parameters, - const Tileset& tileset) +TileLoader::TileLoader( + T& tile_, const OverscaledTileID& id, const TileParameters& parameters, const Tileset& tileset +) : tile(tile_), necessity(TileNecessity::Optional), resource(Resource::tile( - tileset.tiles.at(0), - parameters.pixelRatio, - id.canonical.x, - id.canonical.y, - id.canonical.z, - tileset.scheme, - Resource::LoadingMethod::CacheOnly)), + tileset.tiles.at(0), + parameters.pixelRatio, + id.canonical.x, + id.canonical.y, + id.canonical.z, + tileset.scheme, + Resource::LoadingMethod::CacheOnly + )), fileSource(parameters.fileSource) { assert(!request); if (!fileSource) { @@ -160,8 +160,8 @@ void TileLoader::loadFromNetwork() { // NetworkOnly request. resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.minimumUpdateInterval = updateParameters.minimumUpdateInterval; - resource.storagePolicy = - updateParameters.isVolatile ? Resource::StoragePolicy::Volatile : Resource::StoragePolicy::Permanent; + resource.storagePolicy = updateParameters.isVolatile ? Resource::StoragePolicy::Volatile + : Resource::StoragePolicy::Permanent; request = fileSource->request(resource, [this](const Response& res) { loadedData(res); }); } diff --git a/src/mbgl/tile/vector_tile.cpp b/src/mbgl/tile/vector_tile.cpp index cff6e473132..83bffc592c8 100644 --- a/src/mbgl/tile/vector_tile.cpp +++ b/src/mbgl/tile/vector_tile.cpp @@ -6,11 +6,11 @@ namespace mbgl { -VectorTile::VectorTile(const OverscaledTileID& id_, - std::string sourceID_, - const TileParameters& parameters, - const Tileset& tileset) - : GeometryTile(id_, std::move(sourceID_), parameters), loader(*this, id_, parameters, tileset) {} +VectorTile::VectorTile( + const OverscaledTileID& id_, std::string sourceID_, const TileParameters& parameters, const Tileset& tileset +) + : GeometryTile(id_, std::move(sourceID_), parameters), + loader(*this, id_, parameters, tileset) {} void VectorTile::setNecessity(TileNecessity necessity) { loader.setNecessity(necessity); diff --git a/src/mbgl/tile/vector_tile.hpp b/src/mbgl/tile/vector_tile.hpp index 817c0c25d86..d703a3b7067 100644 --- a/src/mbgl/tile/vector_tile.hpp +++ b/src/mbgl/tile/vector_tile.hpp @@ -10,10 +10,7 @@ class TileParameters; class VectorTile : public GeometryTile { public: - VectorTile(const OverscaledTileID&, - std::string sourceID, - const TileParameters&, - const Tileset&); + VectorTile(const OverscaledTileID&, std::string sourceID, const TileParameters&, const Tileset&); void setNecessity(TileNecessity) final; void setUpdateParameters(const TileUpdateParameters&) final; diff --git a/src/mbgl/tile/vector_tile_data.cpp b/src/mbgl/tile/vector_tile_data.cpp index a6139b412e8..fb86a4af0bb 100644 --- a/src/mbgl/tile/vector_tile_data.cpp +++ b/src/mbgl/tile/vector_tile_data.cpp @@ -4,21 +4,19 @@ namespace mbgl { -VectorTileFeature::VectorTileFeature(const mapbox::vector_tile::layer& layer, - const protozero::data_view& view) - : feature(view, layer) { -} +VectorTileFeature::VectorTileFeature(const mapbox::vector_tile::layer& layer, const protozero::data_view& view) + : feature(view, layer) {} FeatureType VectorTileFeature::getType() const { switch (feature.getType()) { - case mapbox::vector_tile::GeomType::POINT: - return FeatureType::Point; - case mapbox::vector_tile::GeomType::LINESTRING: - return FeatureType::LineString; - case mapbox::vector_tile::GeomType::POLYGON: - return FeatureType::Polygon; - default: - return FeatureType::Unknown; + case mapbox::vector_tile::GeomType::POINT: + return FeatureType::Point; + case mapbox::vector_tile::GeomType::LINESTRING: + return FeatureType::LineString; + case mapbox::vector_tile::GeomType::POLYGON: + return FeatureType::Polygon; + default: + return FeatureType::Unknown; } } @@ -44,8 +42,7 @@ const GeometryCollection& VectorTileFeature::getGeometries() const { try { lines = feature.getGeometries(scale); - } - catch(const std::runtime_error& ex) { + } catch (const std::runtime_error& ex) { Log::Error(Event::ParseTile, "Could not get geometries: " + std::string(ex.what())); lines = GeometryCollection(); } @@ -57,10 +54,9 @@ const GeometryCollection& VectorTileFeature::getGeometries() const { return *lines; } -VectorTileLayer::VectorTileLayer(std::shared_ptr data_, - const protozero::data_view& view) - : data(std::move(data_)), layer(view) { -} +VectorTileLayer::VectorTileLayer(std::shared_ptr data_, const protozero::data_view& view) + : data(std::move(data_)), + layer(view) {} std::size_t VectorTileLayer::featureCount() const { return layer.featureCount(); @@ -74,8 +70,8 @@ std::string VectorTileLayer::getName() const { return layer.getName(); } -VectorTileData::VectorTileData(std::shared_ptr data_) : data(std::move(data_)) { -} +VectorTileData::VectorTileData(std::shared_ptr data_) + : data(std::move(data_)) {} std::unique_ptr VectorTileData::clone() const { return std::make_unique(data); diff --git a/src/mbgl/util/bounding_volumes.cpp b/src/mbgl/util/bounding_volumes.cpp index b8e1d2d8d84..d4013e2e82e 100644 --- a/src/mbgl/util/bounding_volumes.cpp +++ b/src/mbgl/util/bounding_volumes.cpp @@ -33,14 +33,19 @@ Point ProjectPointsToAxis(const std::array& points, const vec3& namespace util { -AABB::AABB() : min({{0, 0, 0}}), max({{0, 0, 0}}) {} +AABB::AABB() + : min({{0, 0, 0}}), + max({{0, 0, 0}}) {} -AABB::AABB(const vec3& min_, const vec3& max_) : min(min_), max(max_) {} +AABB::AABB(const vec3& min_, const vec3& max_) + : min(min_), + max(max_) {} vec3 AABB::closestPoint(const vec3& point) const { - return {{std::max(std::min(max[0], point[0]), min[0]), - std::max(std::min(max[1], point[1]), min[1]), - std::max(std::min(max[2], point[2]), min[2])}}; + return { + {std::max(std::min(max[0], point[0]), min[0]), + std::max(std::min(max[1], point[1]), min[1]), + std::max(std::min(max[2], point[2]), min[2])}}; } vec3 AABB::distanceXYZ(const vec3& point) const { @@ -102,7 +107,8 @@ enum { }; Frustum::Frustum(const std::array& points_, const std::array& planes_) - : points(points_), planes(planes_) { + : points(points_), + planes(planes_) { const Point xBounds = ProjectPointsToAxis(points, {{0, 0, 0}}, {{1, 0, 0}}); const Point yBounds = ProjectPointsToAxis(points, {{0, 0, 0}}, {{0, 1, 0}}); const Point zBounds = ProjectPointsToAxis(points, {{0, 0, 0}}, {{0, 0, 1}}); @@ -111,12 +117,13 @@ Frustum::Frustum(const std::array& points_, const std::array& // Precompute a set of separating axis candidates for precise intersection tests. // Remaining axes not covered in basic intersection tests are: axis[] = (edges of aabb) x (edges of frustum) - std::array frustumEdges = {{vec3Sub(points[near_br], points[near_bl]), - vec3Sub(points[near_tl], points[near_bl]), - vec3Sub(points[far_tl], points[near_tl]), - vec3Sub(points[far_tr], points[near_tr]), - vec3Sub(points[far_br], points[near_br]), - vec3Sub(points[far_bl], points[near_bl])}}; + std::array frustumEdges = { + {vec3Sub(points[near_br], points[near_bl]), + vec3Sub(points[near_tl], points[near_bl]), + vec3Sub(points[far_tl], points[near_tl]), + vec3Sub(points[far_tr], points[near_tr]), + vec3Sub(points[far_br], points[near_br]), + vec3Sub(points[far_bl], points[near_bl])}}; for (size_t i = 0; i < frustumEdges.size(); i++) { // Cross product [1, 0, 0] x [a, b, c] == [0, -c, b] @@ -131,14 +138,15 @@ Frustum::Frustum(const std::array& points_, const std::array& Frustum Frustum::fromInvProjMatrix(const mat4& invProj, double worldSize, double zoom, bool flippedY) { // Define frustum corner points in normalized clip space - std::array cornerCoords = {{vec4{{-1.0, 1.0, -1.0, 1.0}}, - vec4{{1.0, 1.0, -1.0, 1.0}}, - vec4{{1.0, -1.0, -1.0, 1.0}}, - vec4{{-1.0, -1.0, -1.0, 1.0}}, - vec4{{-1.0, 1.0, 1.0, 1.0}}, - vec4{{1.0, 1.0, 1.0, 1.0}}, - vec4{{1.0, -1.0, 1.0, 1.0}}, - vec4{{-1.0, -1.0, 1.0, 1.0}}}}; + std::array cornerCoords = { + {vec4{{-1.0, 1.0, -1.0, 1.0}}, + vec4{{1.0, 1.0, -1.0, 1.0}}, + vec4{{1.0, -1.0, -1.0, 1.0}}, + vec4{{-1.0, -1.0, -1.0, 1.0}}, + vec4{{-1.0, 1.0, 1.0, 1.0}}, + vec4{{1.0, 1.0, 1.0, 1.0}}, + vec4{{1.0, -1.0, 1.0, 1.0}}, + vec4{{-1.0, -1.0, 1.0, 1.0}}}}; const double scale = std::pow(2.0, zoom); @@ -148,14 +156,15 @@ Frustum Frustum::fromInvProjMatrix(const mat4& invProj, double worldSize, double for (auto& component : coord) component *= 1.0 / coord[3] / worldSize * scale; } - std::array frustumPlanePointIndices = {{ - vec3i{{near_bl, near_br, far_br}}, // bottom - vec3i{{near_tl, near_bl, far_bl}}, // left - vec3i{{near_br, near_tr, far_tr}}, // right - vec3i{{near_tl, far_tl, far_tr}}, // top - vec3i{{near_tl, near_tr, near_br}}, // near - vec3i{{far_br, far_tr, far_tl}} // far - }}; + std::array frustumPlanePointIndices = { + { + vec3i{{near_bl, near_br, far_br}}, // bottom + vec3i{{near_tl, near_bl, far_bl}}, // left + vec3i{{near_br, near_tr, far_tr}}, // right + vec3i{{near_tl, far_tl, far_tr}}, // top + vec3i{{near_tl, near_tr, near_br}}, // near + vec3i{{far_br, far_tr, far_tl}} // far} + }; if (flippedY) { std::for_each(frustumPlanePointIndices.begin(), frustumPlanePointIndices.end(), [](vec3i& tri) { @@ -232,10 +241,11 @@ IntersectionResult Frustum::intersectsPrecise(const AABB& aabb, bool edgeCasesOn if (result == IntersectionResult::Separate) return result; } - const std::array aabbPoints = {{vec3{{aabb.min[0], aabb.min[1], 0.0}}, - vec3{{aabb.max[0], aabb.min[1], 0.0}}, - vec3{{aabb.max[0], aabb.max[1], 0.0}}, - vec3{{aabb.min[0], aabb.max[1], 0.0}}}}; + const std::array aabbPoints = { + {vec3{{aabb.min[0], aabb.min[1], 0.0}}, + vec3{{aabb.max[0], aabb.min[1], 0.0}}, + vec3{{aabb.max[0], aabb.max[1], 0.0}}, + vec3{{aabb.min[0], aabb.max[1], 0.0}}}}; // For a precise SAT-test all edge cases needs to be covered // Projections of the frustum on separating axis candidates have been precomputed already diff --git a/src/mbgl/util/camera.cpp b/src/mbgl/util/camera.cpp index e6a85dcfc0d..3f9705842f9 100644 --- a/src/mbgl/util/camera.cpp +++ b/src/mbgl/util/camera.cpp @@ -56,9 +56,10 @@ static vec3 toMercator(const LatLng& location, double altitudeMeters) { const double pixelsPerMeter = 1.0 / Projection::getMetersPerPixelAtLatitude(location.latitude(), 0.0); const double worldSize = Projection::worldSize(std::pow(2.0, 0.0)); - return {{mercatorXfromLng(location.longitude()), - mercatorYfromLat(location.latitude()), - altitudeMeters * pixelsPerMeter / worldSize}}; + return { + {mercatorXfromLng(location.longitude()), + mercatorYfromLat(location.latitude()), + altitudeMeters * pixelsPerMeter / worldSize}}; } static Quaternion orientationFromPitchBearing(double pitch, double bearing) { @@ -89,7 +90,8 @@ static void updateTransform(mat4& transform, const vec3& position) { getColumn(transform, 3)[2] = position[2]; } -Camera::Camera() : orientation(Quaternion::identity) { +Camera::Camera() + : orientation(Quaternion::identity) { matrix::identity(transform); } @@ -120,7 +122,8 @@ mat4 Camera::getWorldToCamera(double scale, bool flippedY) const { mat4 result = orientation.conjugate().toRotationMatrix(); matrix::translate( - result, result, -transform[12] * worldSize, -transform[13] * worldSize, -transform[14] * worldSize); + result, result, -transform[12] * worldSize, -transform[13] * worldSize, -transform[14] * worldSize + ); if (!flippedY) { // Pre-multiply y diff --git a/src/mbgl/util/chrono.cpp b/src/mbgl/util/chrono.cpp index 03e97eedf58..f2732e76499 100644 --- a/src/mbgl/util/chrono.cpp +++ b/src/mbgl/util/chrono.cpp @@ -15,8 +15,7 @@ namespace mbgl { namespace util { static const char *week[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; -static const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; +static const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; std::string rfc1123(Timestamp timestamp) { std::time_t time = std::chrono::system_clock::to_time_t(timestamp); @@ -28,8 +27,18 @@ std::string rfc1123(Timestamp timestamp) { // complaining about the buffer size might be too small. Inceasing the buffer to 32 fixes // the warning. char buffer[32]; - snprintf(buffer, 32, "%s, %02d %s %4d %02d:%02d:%02d GMT", week[info.tm_wday], info.tm_mday, - months[info.tm_mon], 1900 + info.tm_year, info.tm_hour, info.tm_min, info.tm_sec); + snprintf( + buffer, + 32, + "%s, %02d %s %4d %02d:%02d:%02d GMT", + week[info.tm_wday], + info.tm_mday, + months[info.tm_mon], + 1900 + info.tm_year, + info.tm_hour, + info.tm_min, + info.tm_sec + ); return buffer; } @@ -42,7 +51,7 @@ std::string iso8601(Timestamp timestamp) { return buffer; } -Timestamp parseTimestamp(const char* timestamp) { +Timestamp parseTimestamp(const char *timestamp) { return std::chrono::time_point_cast(std::chrono::system_clock::from_time_t(parse_date(timestamp))); } diff --git a/src/mbgl/util/client_options.cpp b/src/mbgl/util/client_options.cpp index c5651278d65..0ce667d595e 100644 --- a/src/mbgl/util/client_options.cpp +++ b/src/mbgl/util/client_options.cpp @@ -9,12 +9,20 @@ class ClientOptions::Impl { }; // These requires the complete type of Impl. -ClientOptions::ClientOptions() : impl_(std::make_unique()) {} +ClientOptions::ClientOptions() + : impl_(std::make_unique()) {} ClientOptions::~ClientOptions() = default; ClientOptions::ClientOptions(ClientOptions&&) noexcept = default; -ClientOptions::ClientOptions(const ClientOptions& other) : impl_(std::make_unique(*other.impl_)) {} -ClientOptions& ClientOptions::operator=(const ClientOptions& other) {impl_ = std::make_unique(*other.impl_); return *this; } -ClientOptions& ClientOptions::operator=(ClientOptions&& options) {swap(impl_, options.impl_); return *this; } +ClientOptions::ClientOptions(const ClientOptions& other) + : impl_(std::make_unique(*other.impl_)) {} +ClientOptions& ClientOptions::operator=(const ClientOptions& other) { + impl_ = std::make_unique(*other.impl_); + return *this; +} +ClientOptions& ClientOptions::operator=(ClientOptions&& options) { + swap(impl_, options.impl_); + return *this; +} ClientOptions ClientOptions::clone() const { return ClientOptions(*this); @@ -38,4 +46,4 @@ const std::string& ClientOptions::version() const { return impl_->version; } -} // namespace mbgl +} // namespace mbgl diff --git a/src/mbgl/util/color.cpp b/src/mbgl/util/color.cpp index a94d4800b38..9ec39cefe4e 100644 --- a/src/mbgl/util/color.cpp +++ b/src/mbgl/util/color.cpp @@ -11,12 +11,7 @@ std::optional Color::parse(const std::string& s) { // Premultiply the color. if (css_color) { const float factor = css_color->a / 255; - return {{ - css_color->r * factor, - css_color->g * factor, - css_color->b * factor, - css_color->a - }}; + return {{css_color->r * factor, css_color->g * factor, css_color->b * factor, css_color->a}}; } else { return {}; } @@ -24,39 +19,41 @@ std::optional Color::parse(const std::string& s) { std::string Color::stringify() const { std::array array = toArray(); - return "rgba(" + - util::toString(array[0]) + "," + - util::toString(array[1]) + "," + - util::toString(array[2]) + "," + - util::toString(array[3]) + ")"; + return "rgba(" + util::toString(array[0]) + "," + util::toString(array[1]) + "," + util::toString(array[2]) + "," + + util::toString(array[3]) + ")"; } std::array Color::toArray() const { if (a == 0) { - return {{ 0, 0, 0, 0 }}; + return {{0, 0, 0, 0}}; } else { - return {{ - r * 255 / a, - g * 255 / a, - b * 255 / a, - floor(a * 100 + .5) / 100 // round to 2 decimal places - }}; + return { + { + r * 255 / a, + g * 255 / a, + b * 255 / a, + floor(a * 100 + .5) / 100 // round to 2 decimal places} + }; + } } -} -mbgl::Value Color::toObject() const { - return mapbox::base::ValueObject{{"r", static_cast(r)}, {"g", static_cast(g)}, {"b", static_cast(b)}, {"a", static_cast(a)}}; -} + mbgl::Value Color::toObject() const { + return mapbox::base::ValueObject{ + {"r", static_cast(r)}, + {"g", static_cast(g)}, + {"b", static_cast(b)}, + {"a", static_cast(a)}}; + } -mbgl::Value Color::serialize() const { - std::array array = toArray(); - return std::vector{ - std::string("rgba"), - array[0], - array[1], - array[2], - array[3], - }; -} + mbgl::Value Color::serialize() const { + std::array array = toArray(); + return std::vector{ + std::string("rgba"), + array[0], + array[1], + array[2], + array[3], + }; + } } // namespace mbgl diff --git a/src/mbgl/util/default_style.cpp b/src/mbgl/util/default_style.cpp index b1f2d2f4326..2eb455aee4c 100644 --- a/src/mbgl/util/default_style.cpp +++ b/src/mbgl/util/default_style.cpp @@ -3,9 +3,10 @@ namespace mbgl { namespace util { -DefaultStyle::DefaultStyle(std::string url_, std::string name_, int version_): - url(url_), name(name_), currentVersion(version_) - {} +DefaultStyle::DefaultStyle(std::string url_, std::string name_, int version_) + : url(url_), + name(name_), + currentVersion(version_) {} const std::string& DefaultStyle::getUrl() const { return url; diff --git a/src/mbgl/util/event.cpp b/src/mbgl/util/event.cpp index 0c08d72a8cf..a70f687ac98 100644 --- a/src/mbgl/util/event.cpp +++ b/src/mbgl/util/event.cpp @@ -3,33 +3,39 @@ namespace mbgl { -MBGL_DEFINE_ENUM(EventSeverity, { - { EventSeverity::Debug, "DEBUG" }, - { EventSeverity::Info, "INFO" }, - { EventSeverity::Warning, "WARNING" }, - { EventSeverity::Error, "ERROR" }, - { EventSeverity(-1), "UNKNOWN" }, -}); +MBGL_DEFINE_ENUM( + EventSeverity, + { + {EventSeverity::Debug, "DEBUG"}, + {EventSeverity::Info, "INFO"}, + {EventSeverity::Warning, "WARNING"}, + {EventSeverity::Error, "ERROR"}, + {EventSeverity(-1), "UNKNOWN"}, + } +); -MBGL_DEFINE_ENUM(Event, { - { Event::General, "General" }, - { Event::Setup, "Setup" }, - { Event::Shader, "Shader" }, - { Event::ParseStyle, "ParseStyle" }, - { Event::ParseTile, "ParseTile" }, - { Event::Render, "Render" }, - { Event::Style, "Style" }, - { Event::Database, "Database" }, - { Event::HttpRequest, "HttpRequest" }, - { Event::Sprite, "Sprite" }, - { Event::Image, "Image" }, - { Event::OpenGL, "OpenGL" }, - { Event::JNI, "JNI" }, - { Event::Android, "Android" }, - { Event::Crash, "Crash" }, - { Event::Glyph, "Glyph" }, - { Event::Timing, "Timing" }, - { Event(-1), "Unknown" }, -}); +MBGL_DEFINE_ENUM( + Event, + { + {Event::General, "General"}, + {Event::Setup, "Setup"}, + {Event::Shader, "Shader"}, + {Event::ParseStyle, "ParseStyle"}, + {Event::ParseTile, "ParseTile"}, + {Event::Render, "Render"}, + {Event::Style, "Style"}, + {Event::Database, "Database"}, + {Event::HttpRequest, "HttpRequest"}, + {Event::Sprite, "Sprite"}, + {Event::Image, "Image"}, + {Event::OpenGL, "OpenGL"}, + {Event::JNI, "JNI"}, + {Event::Android, "Android"}, + {Event::Crash, "Crash"}, + {Event::Glyph, "Glyph"}, + {Event::Timing, "Timing"}, + {Event(-1), "Unknown"}, + } +); } // namespace mbgl diff --git a/src/mbgl/util/geo.cpp b/src/mbgl/util/geo.cpp index 649bd8f7d38..0f5d10c5027 100644 --- a/src/mbgl/util/geo.cpp +++ b/src/mbgl/util/geo.cpp @@ -22,18 +22,17 @@ double lon_(const uint8_t z, const int64_t x) { } // end namespace -LatLng::LatLng(const CanonicalTileID& id) : lat(lat_(id.z, id.y)), lon(lon_(id.z, id.x)) { -} +LatLng::LatLng(const CanonicalTileID& id) + : lat(lat_(id.z, id.y)), + lon(lon_(id.z, id.x)) {} LatLng::LatLng(const UnwrappedTileID& id) : lat(lat_(id.canonical.z, id.canonical.y)), - lon(lon_(id.canonical.z, id.canonical.x) + id.wrap * util::DEGREES_MAX) { -} + lon(lon_(id.canonical.z, id.canonical.x) + id.wrap * util::DEGREES_MAX) {} LatLngBounds::LatLngBounds(const CanonicalTileID& id) - : sw({ lat_(id.z, id.y + 1), lon_(id.z, id.x) }), - ne({ lat_(id.z, id.y), lon_(id.z, id.x + 1) }) { -} + : sw({lat_(id.z, id.y + 1), lon_(id.z, id.x)}), + ne({lat_(id.z, id.y), lon_(id.z, id.x + 1)}) {} bool LatLngBounds::contains(const CanonicalTileID& tileID) const { return util::TileRange::fromLatLngBounds(*this, tileID.z).contains(tileID); @@ -50,7 +49,7 @@ bool LatLngBounds::contains(const LatLngBounds& area, LatLng::WrapMode wrap /*= } bool containsUnwrapped = area.east() <= east() && area.west() >= west(); - if(containsUnwrapped) { + if (containsUnwrapped) { return true; } else if (wrap == LatLng::Wrapped) { LatLngBounds wrapped(sw.wrapped(), ne.wrapped()); @@ -78,15 +77,11 @@ bool LatLngBounds::intersects(const LatLngBounds area, LatLng::WrapMode wrap /*= LatLngBounds wrapped(sw.wrapped(), ne.wrapped()); LatLngBounds other(area.sw.wrapped(), area.ne.wrapped()); if (crossesAntimeridian()) { - return area.crossesAntimeridian() || - other.east() > wrapped.west() || - other.west() < wrapped.east(); - } else if (other.crossesAntimeridian()){ - return other.east() > wrapped.west() || - other.west() < wrapped.east(); + return area.crossesAntimeridian() || other.east() > wrapped.west() || other.west() < wrapped.east(); + } else if (other.crossesAntimeridian()) { + return other.east() > wrapped.west() || other.west() < wrapped.east(); } else { - return other.east() > wrapped.west() && - other.west() < wrapped.east(); + return other.east() > wrapped.west() && other.west() < wrapped.east(); } } return false; @@ -108,7 +103,7 @@ LatLng LatLngBounds::constrain(const LatLng& p) const { lng = util::clamp(lng, west(), east()); } - return LatLng { lat, lng }; + return LatLng{lat, lng}; } bool LatLngBounds::containsLatitude(double latitude) const { diff --git a/src/mbgl/util/geometry_util.cpp b/src/mbgl/util/geometry_util.cpp index f354359f7f5..dcd9efa6bfb 100644 --- a/src/mbgl/util/geometry_util.cpp +++ b/src/mbgl/util/geometry_util.cpp @@ -43,7 +43,9 @@ bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2) template bool segmentIntersectSegment(const Point& a, const Point& b, const Point& c, const Point& d) { // a, b are end points for line segment1, c and d are end points for line segment2 - const auto perp = [](const Point& v1, const Point& v2) { return (v1.x * v2.y - v1.y * v2.x); }; + const auto perp = [](const Point& v1, const Point& v2) { + return (v1.x * v2.y - v1.y * v2.x); + }; // check if two segments are parallel or not // precondition is end point a, b is inside polygon, if line a->b is @@ -140,30 +142,24 @@ bool lineStringWithinPolygons(const LineString& line, const MultiPolygon& template void updateBBox(GeometryBBox& bbox, const Point& p); template bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2); -template bool segmentIntersectSegment(const Point& a, - const Point& b, - const Point& c, - const Point& d); +template bool segmentIntersectSegment( + const Point& a, const Point& b, const Point& c, const Point& d +); template bool rayIntersect(const Point& p, const Point& p1, const Point& p2); template bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2); template bool lineIntersectPolygon(const Point& p1, const Point& p2, const Polygon& polygon); -template bool pointWithinPolygon(const Point& point, - const Polygon& polygon, - bool trueOnBoundary); -template bool pointWithinPolygons(const Point& point, - const MultiPolygon& polygons, - bool trueOnBoundary); +template bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary); +template bool pointWithinPolygons( + const Point& point, const MultiPolygon& polygons, bool trueOnBoundary +); template bool lineStringWithinPolygon(const LineString& line, const Polygon& polygon); template bool lineStringWithinPolygons(const LineString& line, const MultiPolygon& polygons); template void updateBBox(GeometryBBox& bbox, const Point& p); template bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2); -template bool segmentIntersectSegment(const Point& a, - const Point& b, - const Point& c, - const Point& d); -template bool pointWithinPolygon(const Point& point, - const Polygon& polygon, - bool trueOnBoundary); +template bool segmentIntersectSegment( + const Point& a, const Point& b, const Point& c, const Point& d +); +template bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary); } // namespace mbgl diff --git a/src/mbgl/util/geometry_util.hpp b/src/mbgl/util/geometry_util.hpp index 528f0639652..17a82cd2334 100644 --- a/src/mbgl/util/geometry_util.hpp +++ b/src/mbgl/util/geometry_util.hpp @@ -9,15 +9,17 @@ namespace mbgl { // contains minX, minY, maxX, maxY template using GeometryBBox = std::array; -const GeometryBBox DefaultWithinBBox = std::array{{std::numeric_limits::max(), - std::numeric_limits::max(), - std::numeric_limits::min(), - std::numeric_limits::min()}}; - -const GeometryBBox DefaultDistanceBBox = std::array{{std::numeric_limits::infinity(), - std::numeric_limits::infinity(), - -std::numeric_limits::infinity(), - -std::numeric_limits::infinity()}}; +const GeometryBBox DefaultWithinBBox = std::array{ + {std::numeric_limits::max(), + std::numeric_limits::max(), + std::numeric_limits::min(), + std::numeric_limits::min()}}; + +const GeometryBBox DefaultDistanceBBox = std::array{ + {std::numeric_limits::infinity(), + std::numeric_limits::infinity(), + -std::numeric_limits::infinity(), + -std::numeric_limits::infinity()}}; template void updateBBox(GeometryBBox& bbox, const Point& p); diff --git a/src/mbgl/util/grid_index.cpp b/src/mbgl/util/grid_index.cpp index cb197ef320a..1a5c5fe6cf6 100644 --- a/src/mbgl/util/grid_index.cpp +++ b/src/mbgl/util/grid_index.cpp @@ -7,21 +7,19 @@ namespace mbgl { - template -GridIndex::GridIndex(const float width_, const float height_, const uint32_t cellSize_) : - width(width_), - height(height_), - xCellCount(static_cast(std::ceil(width / cellSize_))), - yCellCount(static_cast(std::ceil(height / cellSize_))), - xScale(xCellCount / width), - yScale(yCellCount / height) - { - assert(width > 0.0f); - assert(height > 0.0f); - boxCells.resize(xCellCount * yCellCount); - circleCells.resize(xCellCount * yCellCount); - } +GridIndex::GridIndex(const float width_, const float height_, const uint32_t cellSize_) + : width(width_), + height(height_), + xCellCount(static_cast(std::ceil(width / cellSize_))), + yCellCount(static_cast(std::ceil(height / cellSize_))), + xScale(xCellCount / width), + yScale(yCellCount / height) { + assert(width > 0.0f); + assert(height > 0.0f); + boxCells.resize(xCellCount * yCellCount); + circleCells.resize(xCellCount * yCellCount); +} template void GridIndex::insert(T&& t, const BBox& bbox) { @@ -127,15 +125,16 @@ bool GridIndex::completeIntersection(const BBox& queryBBox) const { template typename GridIndex::BBox GridIndex::convertToBox(const BCircle& circle) const { - return BBox{{circle.center.x - circle.radius, circle.center.y - circle.radius}, - {circle.center.x + circle.radius, circle.center.y + circle.radius}}; + return BBox{ + {circle.center.x - circle.radius, circle.center.y - circle.radius}, + {circle.center.x + circle.radius, circle.center.y + circle.radius}}; } template -void GridIndex::query(const BBox& queryBBox, std::function resultFn) const { +void GridIndex::query(const BBox& queryBBox, std::function resultFn) const { std::unordered_set seenBoxes; std::unordered_set seenCircles; - + if (noIntersection(queryBBox)) { return; } else if (completeIntersection(queryBBox)) { @@ -177,7 +176,7 @@ void GridIndex::query(const BBox& queryBBox, std::function::query(const BBox& queryBBox, std::function -void GridIndex::query(const BCircle& queryBCircle, std::function resultFn) const { +void GridIndex::query(const BCircle& queryBCircle, std::function resultFn) const { std::unordered_set seenBoxes; std::unordered_set seenCircles; @@ -242,7 +241,7 @@ void GridIndex::query(const BCircle& queryBCircle, std::function::convertToYCellCoord(const float y) const { template bool GridIndex::boxesCollide(const BBox& first, const BBox& second) const { - return first.min.x <= second.max.x && - first.min.y <= second.max.y && - first.max.x >= second.min.x && + return first.min.x <= second.max.x && first.min.y <= second.max.y && first.max.x >= second.min.x && first.max.y >= second.min.y; } @@ -315,7 +312,6 @@ bool GridIndex::empty() const { return boxElements.empty() && circleElements.empty(); } - template class GridIndex; } // namespace mbgl diff --git a/src/mbgl/util/grid_index.hpp b/src/mbgl/util/grid_index.hpp index daad43cb4ef..455ca19685f 100644 --- a/src/mbgl/util/grid_index.hpp +++ b/src/mbgl/util/grid_index.hpp @@ -14,33 +14,29 @@ namespace mbgl { namespace geometry { template -struct circle -{ +struct circle { using point_type = mapbox::geometry::point; constexpr circle(point_type const& center_, T const& radius_) - : center(center_), radius(radius_) - {} + : center(center_), + radius(radius_) {} point_type center; T radius; }; template -constexpr bool operator==(circle const& lhs, circle const& rhs) -{ +constexpr bool operator==(circle const& lhs, circle const& rhs) { return lhs.center == rhs.center && lhs.radius == rhs.radius; } template -constexpr bool operator!=(circle const& lhs, circle const& rhs) -{ +constexpr bool operator!=(circle const& lhs, circle const& rhs) { return lhs.center != rhs.center || lhs.radius != rhs.radius; } } // namespace geometry - /* GridIndex is a data structure for testing the intersection of circles and rectangles in a 2d plane. @@ -63,13 +59,13 @@ class GridIndex { void insert(T&& t, const BBox&); void insert(T&& t, const BCircle&); - + std::vector query(const BBox&) const; - std::vector> queryWithBoxes(const BBox&) const; - + std::vector> queryWithBoxes(const BBox&) const; + bool hitTest(const BBox&, std::optional> predicate = std::nullopt) const; bool hitTest(const BCircle&, std::optional> predicate = std::nullopt) const; - + bool empty() const; private: @@ -77,8 +73,8 @@ class GridIndex { bool completeIntersection(const BBox& queryBBox) const; BBox convertToBox(const BCircle& circle) const; - void query(const BBox&, std::function) const; - void query(const BCircle&, std::function) const; + void query(const BBox&, std::function) const; + void query(const BCircle&, std::function) const; std::size_t convertToXCellCoord(float x) const; std::size_t convertToYCellCoord(float y) const; @@ -89,7 +85,7 @@ class GridIndex { const float width; const float height; - + const std::size_t xCellCount; const std::size_t yCellCount; const double xScale; @@ -97,10 +93,9 @@ class GridIndex { std::vector> boxElements; std::vector> circleElements; - + std::vector> boxCells; std::vector> circleCells; - }; } // namespace mbgl diff --git a/src/mbgl/util/hash.hpp b/src/mbgl/util/hash.hpp index 89aba00f72f..cb92fe9bed6 100644 --- a/src/mbgl/util/hash.hpp +++ b/src/mbgl/util/hash.hpp @@ -15,7 +15,7 @@ void hash_combine(std::size_t& seed, const T& v) { template std::size_t hash(Args&&... args) { std::size_t seed = 0; - ignore({ (hash_combine(seed, args), 0)... }); + ignore({(hash_combine(seed, args), 0)...}); return seed; } diff --git a/src/mbgl/util/http_header.cpp b/src/mbgl/util/http_header.cpp index 89a3c016021..6b183e303bd 100644 --- a/src/mbgl/util/http_header.cpp +++ b/src/mbgl/util/http_header.cpp @@ -5,7 +5,7 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4828) +#pragma warning(disable : 4828) #endif #include @@ -24,11 +24,15 @@ CacheControl CacheControl::parse(const std::string& value) { namespace phoenix = boost::phoenix; CacheControl result; - qi::phrase_parse(value.begin(), value.end(), ( - (qi::lit("must-revalidate") [ phoenix::ref(result.mustRevalidate) = true ]) | - (qi::lit("max-age") >> '=' >> qi::ulong_long [ phoenix::ref(result.maxAge) = qi::_1 ]) | - (*(('"' >> *(('\\' >> qi::char_) | (qi::char_ - '"')) >> '"') | (qi::char_ - '"' - ','))) - ) % ',', qi::ascii::space); + qi::phrase_parse( + value.begin(), + value.end(), + ((qi::lit("must-revalidate")[phoenix::ref(result.mustRevalidate) = true]) | + (qi::lit("max-age") >> '=' >> qi::ulong_long[phoenix::ref(result.maxAge) = qi::_1]) | + (*(('"' >> *(('\\' >> qi::char_) | (qi::char_ - '"')) >> '"') | (qi::char_ - '"' - ',')))) % + ',', + qi::ascii::space + ); return result; } @@ -36,8 +40,9 @@ std::optional CacheControl::toTimePoint() const { return maxAge ? util::now() + Seconds(*maxAge) : std::optional{}; } -std::optional parseRetryHeaders(const std::optional& retryAfter, - const std::optional& xRateLimitReset) { +std::optional parseRetryHeaders( + const std::optional& retryAfter, const std::optional& xRateLimitReset +) { if (retryAfter) { try { auto secs = std::chrono::seconds(std::stoi(*retryAfter)); diff --git a/src/mbgl/util/http_header.hpp b/src/mbgl/util/http_header.hpp index 614ddc10104..4c9879d3b59 100644 --- a/src/mbgl/util/http_header.hpp +++ b/src/mbgl/util/http_header.hpp @@ -18,8 +18,9 @@ class CacheControl { std::optional toTimePoint() const; }; -std::optional parseRetryHeaders(const std::optional& retryAfter, - const std::optional& xRateLimitReset); +std::optional parseRetryHeaders( + const std::optional& retryAfter, const std::optional& xRateLimitReset +); } // namespace http } // namespace mbgl diff --git a/src/mbgl/util/http_timeout.cpp b/src/mbgl/util/http_timeout.cpp index 07d9b79f3fc..63f7fcebf63 100644 --- a/src/mbgl/util/http_timeout.cpp +++ b/src/mbgl/util/http_timeout.cpp @@ -7,8 +7,9 @@ namespace mbgl { namespace http { -Duration errorRetryTimeout(Response::Error::Reason failedRequestReason, uint32_t failedRequests, std::optional retryAfter) { - +Duration errorRetryTimeout( + Response::Error::Reason failedRequestReason, uint32_t failedRequests, std::optional retryAfter +) { if (failedRequestReason == Response::Error::Reason::Server) { // Retry after one second three times, then start exponential backoff. return Seconds(failedRequests <= 3 ? 1 : 1u << std::min(failedRequests - 3, 31u)); diff --git a/src/mbgl/util/http_timeout.hpp b/src/mbgl/util/http_timeout.hpp index 23db9300fa4..99461ff0ba5 100644 --- a/src/mbgl/util/http_timeout.hpp +++ b/src/mbgl/util/http_timeout.hpp @@ -8,7 +8,11 @@ namespace mbgl { namespace http { -Duration errorRetryTimeout(Response::Error::Reason failedRequestReason, uint32_t failedRequests, std::optional retryAfter = std::nullopt); +Duration errorRetryTimeout( + Response::Error::Reason failedRequestReason, + uint32_t failedRequests, + std::optional retryAfter = std::nullopt +); Duration expirationTimeout(std::optional expires, uint32_t expiredRequests); diff --git a/src/mbgl/util/i18n.cpp b/src/mbgl/util/i18n.cpp index 246f918f01f..86148cc3b4a 100644 --- a/src/mbgl/util/i18n.cpp +++ b/src/mbgl/util/i18n.cpp @@ -12,8 +12,10 @@ namespace { @param first The first codepoint in the block, inclusive. @param last The last codepoint in the block, inclusive. */ -#define DEFINE_IS_IN_UNICODE_BLOCK(name, first, last) \ - inline bool isIn##name(char16_t codepoint) { return codepoint >= (first) && codepoint <= (last); } +#define DEFINE_IS_IN_UNICODE_BLOCK(name, first, last) \ + inline bool isIn##name(char16_t codepoint) { \ + return codepoint >= (first) && codepoint <= (last); \ + } // The following table comes from . // Keep it synchronized with . @@ -320,23 +322,18 @@ DEFINE_IS_IN_UNICODE_BLOCK(HalfwidthandFullwidthForms, 0xFF00, 0xFFEF) // DEFINE_IS_IN_UNICODE_BLOCK(SupplementaryPrivateUseAreaB, 0x100000, 0x10FFFF) MAPBOX_ETERNAL_CONSTEXPR const auto verticalPunctuation = mapbox::eternal::map({ - { u'!', u'︕' }, { u'#', u'#' }, { u'$', u'$' }, { u'%', u'%' }, { u'&', u'&' }, - { u'(', u'︵' }, { u')', u'︶' }, { u'*', u'*' }, { u'+', u'+' }, { u',', u'︐' }, - { u'-', u'︲' }, { u'.', u'・' }, { u'/', u'/' }, { u':', u'︓' }, { u';', u'︔' }, - { u'<', u'︿' }, { u'=', u'=' }, { u'>', u'﹀' }, { u'?', u'︖' }, { u'@', u'@' }, - { u'[', u'﹇' }, { u'\\', u'\' }, { u']', u'﹈' }, { u'^', u'^' }, { u'_', u'︳' }, - { u'`', u'`' }, { u'{', u'︷' }, { u'|', u'―' }, { u'}', u'︸' }, { u'~', u'~' }, - { u'¢', u'¢' }, { u'£', u'£' }, { u'¥', u'¥' }, { u'¦', u'¦' }, { u'¬', u'¬' }, - { u'¯', u' ̄' }, { u'–', u'︲' }, { u'—', u'︱' }, { u'‘', u'﹃' }, { u'’', u'﹄' }, - { u'“', u'﹁' }, { u'”', u'﹂' }, { u'…', u'︙' }, { u'‧', u'・' }, { u'₩', u'₩' }, - { u'、', u'︑' }, { u'。', u'︒' }, { u'〈', u'︿' }, { u'〉', u'﹀' }, { u'《', u'︽' }, - { u'》', u'︾' }, { u'「', u'﹁' }, { u'」', u'﹂' }, { u'『', u'﹃' }, { u'』', u'﹄' }, - { u'【', u'︻' }, { u'】', u'︼' }, { u'〔', u'︹' }, { u'〕', u'︺' }, { u'〖', u'︗' }, - { u'〗', u'︘' }, { u'!', u'︕' }, { u'(', u'︵' }, { u')', u'︶' }, { u',', u'︐' }, - { u'-', u'︲' }, { u'.', u'・' }, { u':', u'︓' }, { u';', u'︔' }, { u'<', u'︿' }, - { u'>', u'﹀' }, { u'?', u'︖' }, { u'[', u'﹇' }, { u']', u'﹈' }, { u'_', u'︳' }, - { u'{', u'︷' }, { u'|', u'―' }, { u'}', u'︸' }, { u'⦅', u'︵' }, { u'⦆', u'︶' }, - { u'。', u'︒' }, { u'「', u'﹁' }, { u'」', u'﹂' }, + {u'!', u'︕'}, {u'#', u'#'}, {u'$', u'$'}, {u'%', u'%'}, {u'&', u'&'}, {u'(', u'︵'}, {u')', u'︶'}, + {u'*', u'*'}, {u'+', u'+'}, {u',', u'︐'}, {u'-', u'︲'}, {u'.', u'・'}, {u'/', u'/'}, {u':', u'︓'}, + {u';', u'︔'}, {u'<', u'︿'}, {u'=', u'='}, {u'>', u'﹀'}, {u'?', u'︖'}, {u'@', u'@'}, {u'[', u'﹇'}, + {u'\\', u'\'}, {u']', u'﹈'}, {u'^', u'^'}, {u'_', u'︳'}, {u'`', u'`'}, {u'{', u'︷'}, {u'|', u'―'}, + {u'}', u'︸'}, {u'~', u'~'}, {u'¢', u'¢'}, {u'£', u'£'}, {u'¥', u'¥'}, {u'¦', u'¦'}, {u'¬', u'¬'}, + {u'¯', u' ̄'}, {u'–', u'︲'}, {u'—', u'︱'}, {u'‘', u'﹃'}, {u'’', u'﹄'}, {u'“', u'﹁'}, {u'”', u'﹂'}, + {u'…', u'︙'}, {u'‧', u'・'}, {u'₩', u'₩'}, {u'、', u'︑'}, {u'。', u'︒'}, {u'〈', u'︿'}, {u'〉', u'﹀'}, + {u'《', u'︽'}, {u'》', u'︾'}, {u'「', u'﹁'}, {u'」', u'﹂'}, {u'『', u'﹃'}, {u'』', u'﹄'}, {u'【', u'︻'}, + {u'】', u'︼'}, {u'〔', u'︹'}, {u'〕', u'︺'}, {u'〖', u'︗'}, {u'〗', u'︘'}, {u'!', u'︕'}, {u'(', u'︵'}, + {u')', u'︶'}, {u',', u'︐'}, {u'-', u'︲'}, {u'.', u'・'}, {u':', u'︓'}, {u';', u'︔'}, {u'<', u'︿'}, + {u'>', u'﹀'}, {u'?', u'︖'}, {u'[', u'﹇'}, {u']', u'﹈'}, {u'_', u'︳'}, {u'{', u'︷'}, {u'|', u'―'}, + {u'}', u'︸'}, {u'⦅', u'︵'}, {u'⦆', u'︶'}, {u'。', u'︒'}, {u'「', u'﹁'}, {u'」', u'﹂'}, }); } // namespace @@ -346,23 +343,28 @@ namespace util { namespace i18n { bool allowsWordBreaking(char16_t chr) { - return (chr == 0x0a /* newline */ - || chr == 0x20 /* space */ - || chr == 0x26 /* ampersand */ - || chr == 0x28 /* open parenthesis */ - || chr == 0x29 /* close parenthesis */ - || chr == 0x2b /* plus sign */ - || chr == 0x2d /* hyphen-minus */ - || chr == 0x2f /* solidus */ - || chr == 0xad /* soft hyphen */ - || chr == 0xb7 /* middle dot */ - || chr == 0x200b /* zero-width space */ - || chr == 0x2010 /* hyphen */ - || chr == 0x2013 /* en dash */); + return ( + chr == 0x0a /* newline */ + || chr == 0x20 /* space */ + || chr == 0x26 /* ampersand */ + || chr == 0x28 /* open parenthesis */ + || chr == 0x29 /* close parenthesis */ + || chr == 0x2b /* plus sign */ + || chr == 0x2d /* hyphen-minus */ + || chr == 0x2f /* solidus */ + || chr == 0xad /* soft hyphen */ + || chr == 0xb7 /* middle dot */ + || chr == 0x200b /* zero-width space */ + || chr == 0x2010 /* hyphen */ + || chr == 0x2013 /* en dash */ + ); } bool charAllowsLetterSpacing(char16_t chr) { - return !(isInArabic(chr) || isInArabicSupplement(chr) || isInArabicExtendedA(chr) || isInArabicPresentationFormsA(chr) || isInArabicPresentationFormsB(chr)); + return !( + isInArabic(chr) || isInArabicSupplement(chr) || isInArabicExtendedA(chr) || isInArabicPresentationFormsA(chr) || + isInArabicPresentationFormsB(chr) + ); } bool allowsLetterSpacing(const std::u16string& string) { @@ -380,22 +382,19 @@ bool allowsIdeographicBreaking(const std::u16string& string) { bool allowsIdeographicBreaking(char16_t chr) { // Allow U+2027 "Interpunct" for hyphenation of Chinese words - if (chr == 0x2027) - return true; + if (chr == 0x2027) return true; // Return early for characters outside all ideographic ranges. - if (chr < 0x2E80) - return false; - - return (isInBopomofo(chr) || isInBopomofoExtended(chr) || isInCJKCompatibility(chr) || - isInCJKCompatibilityForms(chr) || isInCJKCompatibilityIdeographs(chr) || - isInCJKRadicalsSupplement(chr) || isInCJKStrokes(chr) || - isInCJKSymbolsandPunctuation(chr) || isInCJKUnifiedIdeographs(chr) || - isInCJKUnifiedIdeographsExtensionA(chr) || isInEnclosedCJKLettersandMonths(chr) || - isInHalfwidthandFullwidthForms(chr) || isInHiragana(chr) || - isInIdeographicDescriptionCharacters(chr) || isInKangxiRadicals(chr) || - isInKatakana(chr) || isInKatakanaPhoneticExtensions(chr) || isInVerticalForms(chr) || - isInYiRadicals(chr) || isInYiSyllables(chr)); + if (chr < 0x2E80) return false; + + return ( + isInBopomofo(chr) || isInBopomofoExtended(chr) || isInCJKCompatibility(chr) || isInCJKCompatibilityForms(chr) || + isInCJKCompatibilityIdeographs(chr) || isInCJKRadicalsSupplement(chr) || isInCJKStrokes(chr) || + isInCJKSymbolsandPunctuation(chr) || isInCJKUnifiedIdeographs(chr) || isInCJKUnifiedIdeographsExtensionA(chr) || + isInEnclosedCJKLettersandMonths(chr) || isInHalfwidthandFullwidthForms(chr) || isInHiragana(chr) || + isInIdeographicDescriptionCharacters(chr) || isInKangxiRadicals(chr) || isInKatakana(chr) || + isInKatakanaPhoneticExtensions(chr) || isInVerticalForms(chr) || isInYiRadicals(chr) || isInYiSyllables(chr) + ); // The following blocks also allow ideographic breaking; however, for other // reasons, Mapbox GL lacks support for codepoints beyond U+FFFF. @@ -415,8 +414,7 @@ bool allowsIdeographicBreaking(char16_t chr) { bool allowsFixedWidthGlyphGeneration(char16_t chr) { // Mirrors conservative set of characters used in glyph_manager.js/_tinySDF - return isInCJKUnifiedIdeographs(chr) || isInHangulSyllables(chr) - || isInKatakana(chr) || isInHiragana(chr); + return isInCJKUnifiedIdeographs(chr) || isInHangulSyllables(chr) || isInKatakana(chr) || isInHiragana(chr); } bool allowsVerticalWritingMode(const std::u16string& string) { @@ -437,52 +435,42 @@ bool allowsVerticalWritingMode(const std::u16string& string) { // “neutral” characters. bool hasUprightVerticalOrientation(char16_t chr) { - if (chr == u'˪' || chr == u'˫') - return true; + if (chr == u'˪' || chr == u'˫') return true; // Return early for characters outside all ranges whose characters remain // upright in vertical writing mode. - if (chr < 0x1100) - return false; + if (chr < 0x1100) return false; - if (isInBopomofo(chr) || isInBopomofoExtended(chr)) - return true; + if (isInBopomofo(chr) || isInBopomofoExtended(chr)) return true; if (isInCJKCompatibilityForms(chr)) { - if (!(chr >= u'﹉' && chr <= u'﹏')) - return true; + if (!(chr >= u'﹉' && chr <= u'﹏')) return true; } - if (isInCJKCompatibility(chr) || isInCJKCompatibilityIdeographs(chr) || - isInCJKRadicalsSupplement(chr) || isInCJKStrokes(chr)) + if (isInCJKCompatibility(chr) || isInCJKCompatibilityIdeographs(chr) || isInCJKRadicalsSupplement(chr) || + isInCJKStrokes(chr)) return true; if (isInCJKSymbolsandPunctuation(chr)) { - if (!(chr >= u'〈' && chr <= u'】') && !(chr >= u'〔' && chr <= u'〟') && chr != u'〰') - return true; + if (!(chr >= u'〈' && chr <= u'】') && !(chr >= u'〔' && chr <= u'〟') && chr != u'〰') return true; } if (isInCJKUnifiedIdeographs(chr) || isInCJKUnifiedIdeographsExtensionA(chr) || - isInEnclosedCJKLettersandMonths(chr) || isInHangulCompatibilityJamo(chr) || - isInHangulJamo(chr) || isInHangulJamoExtendedA(chr) || isInHangulJamoExtendedB(chr) || - isInHangulSyllables(chr) || isInHiragana(chr) || + isInEnclosedCJKLettersandMonths(chr) || isInHangulCompatibilityJamo(chr) || isInHangulJamo(chr) || + isInHangulJamoExtendedA(chr) || isInHangulJamoExtendedB(chr) || isInHangulSyllables(chr) || isInHiragana(chr) || isInIdeographicDescriptionCharacters(chr) || isInKanbun(chr) || isInKangxiRadicals(chr)) return true; if (isInKatakana(chr)) { - if (chr != u'ー') - return true; + if (chr != u'ー') return true; } - if (isInKatakanaPhoneticExtensions(chr)) - return true; + if (isInKatakanaPhoneticExtensions(chr)) return true; if (isInHalfwidthandFullwidthForms(chr)) { - if (chr != u'(' && chr != u')' && chr != u'-' && !(chr >= u':' && chr <= u'>') && - chr != u'[' && chr != u']' && chr != u'_' && !(chr >= u'{' && chr <= 0xFFDF) && - chr != u' ̄' && !(chr >= u'│' && chr <= 0xFFEF)) + if (chr != u'(' && chr != u')' && chr != u'-' && !(chr >= u':' && chr <= u'>') && chr != u'[' && + chr != u']' && chr != u'_' && !(chr >= u'{' && chr <= 0xFFDF) && chr != u' ̄' && + !(chr >= u'│' && chr <= 0xFFEF)) return true; } if (isInSmallFormVariants(chr)) { - if (!(chr >= u'﹘' && chr <= u'﹞') && !(chr >= u'﹣' && chr <= u'﹦')) - return true; + if (!(chr >= u'﹘' && chr <= u'﹞') && !(chr >= u'﹣' && chr <= u'﹦')) return true; } - if (isInUnifiedCanadianAboriginalSyllabics(chr) || - isInUnifiedCanadianAboriginalSyllabicsExtended(chr) || isInVerticalForms(chr) || - isInYijingHexagramSymbols(chr) || isInYiSyllables(chr) || isInYiRadicals(chr)) + if (isInUnifiedCanadianAboriginalSyllabics(chr) || isInUnifiedCanadianAboriginalSyllabicsExtended(chr) || + isInVerticalForms(chr) || isInYijingHexagramSymbols(chr) || isInYiSyllables(chr) || isInYiRadicals(chr)) return true; // https://github.com/mapbox/mapbox-gl/issues/29 @@ -526,15 +514,14 @@ bool hasUprightVerticalOrientation(char16_t chr) { bool hasNeutralVerticalOrientation(char16_t chr) { if (isInLatin1Supplement(chr)) { - if (chr == u'§' || chr == u'©' || chr == u'®' || chr == u'±' || chr == u'¼' || - chr == u'½' || chr == u'¾' || chr == u'×' || chr == u'÷') { + if (chr == u'§' || chr == u'©' || chr == u'®' || chr == u'±' || chr == u'¼' || chr == u'½' || chr == u'¾' || + chr == u'×' || chr == u'÷') { return true; } } if (isInGeneralPunctuation(chr)) { - if (chr == u'‖' || chr == u'†' || chr == u'‡' || chr == u'‰' || chr == u'‱' || - chr == u'※' || chr == u'‼' || chr == u'⁂' || chr == u'⁇' || chr == u'⁈' || - chr == u'⁉' || chr == u'⁑') { + if (chr == u'‖' || chr == u'†' || chr == u'‡' || chr == u'‰' || chr == u'‱' || chr == u'※' || chr == u'‼' || + chr == u'⁂' || chr == u'⁇' || chr == u'⁈' || chr == u'⁉' || chr == u'⁑') { return true; } } @@ -542,32 +529,27 @@ bool hasNeutralVerticalOrientation(char16_t chr) { return true; } if (isInMiscellaneousTechnical(chr)) { - if ((chr >= u'⌀' && chr <= u'⌇') || (chr >= u'⌌' && chr <= u'⌟') || - (chr >= u'⌤' && chr <= u'⌨') || chr == u'⌫' || (chr >= u'⍽' && chr <= u'⎚') || - (chr >= u'⎾' && chr <= u'⏍') || chr == u'⏏' || (chr >= u'⏑' && chr <= u'⏛') || - (chr >= u'⏢' && chr <= 0x23FF)) { + if ((chr >= u'⌀' && chr <= u'⌇') || (chr >= u'⌌' && chr <= u'⌟') || (chr >= u'⌤' && chr <= u'⌨') || + chr == u'⌫' || (chr >= u'⍽' && chr <= u'⎚') || (chr >= u'⎾' && chr <= u'⏍') || chr == u'⏏' || + (chr >= u'⏑' && chr <= u'⏛') || (chr >= u'⏢' && chr <= 0x23FF)) { return true; } } - if (isInControlPictures(chr) || isInOpticalCharacterRecognition(chr) || - isInEnclosedAlphanumerics(chr) || isInGeometricShapes(chr)) { + if (isInControlPictures(chr) || isInOpticalCharacterRecognition(chr) || isInEnclosedAlphanumerics(chr) || + isInGeometricShapes(chr)) { return true; } if (isInMiscellaneousSymbols(chr)) { - if ((chr >= u'⬒' && chr <= u'⬯') || - (chr >= u'⭐' && chr <= 0x2B59 /* heavy circled saltire */) || - (chr >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && - chr <= 0x2BEB)) { + if ((chr >= u'⬒' && chr <= u'⬯') || (chr >= u'⭐' && chr <= 0x2B59 /* heavy circled saltire */) || + (chr >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && chr <= 0x2BEB)) { return true; } } if (isInCJKSymbolsandPunctuation(chr) || isInKatakana(chr) || isInPrivateUseArea(chr) || - isInCJKCompatibilityForms(chr) || isInSmallFormVariants(chr) || - isInHalfwidthandFullwidthForms(chr)) { + isInCJKCompatibilityForms(chr) || isInSmallFormVariants(chr) || isInHalfwidthandFullwidthForms(chr)) { return true; } - if (chr == u'∞' || chr == u'∴' || chr == u'∵' || - (chr >= 0x2700 /* black safety scissors */ && chr <= u'❧') || + if (chr == u'∞' || chr == u'∴' || chr == u'∵' || (chr >= 0x2700 /* black safety scissors */ && chr <= u'❧') || (chr >= u'❶' && chr <= u'➓') || chr == 0xFFFC /* object replacement character */ || chr == 0xFFFD /* replacement character */) { return true; @@ -590,10 +572,10 @@ std::u16string verticalizePunctuation(const std::u16string& input) { char16_t prevCharCode = i ? input[i - 1] : 0; bool canReplacePunctuation = - ((!nextCharCode || !hasRotatedVerticalOrientation(nextCharCode) || - verticalPunctuation.count(input[i + 1])) && - (!prevCharCode || !hasRotatedVerticalOrientation(prevCharCode) || - verticalPunctuation.count(input[i - 1]))); + ((!nextCharCode || !hasRotatedVerticalOrientation(nextCharCode) || verticalPunctuation.count(input[i + 1]) + ) && + (!prevCharCode || !hasRotatedVerticalOrientation(prevCharCode) || verticalPunctuation.count(input[i - 1])) + ); if (char16_t repl = canReplacePunctuation ? verticalizePunctuation(input[i]) : 0) { output += repl; @@ -608,7 +590,7 @@ std::u16string verticalizePunctuation(const std::u16string& input) { char16_t verticalizePunctuation(char16_t chr) { return verticalPunctuation.count(chr) ? verticalPunctuation.at(chr) : 0; } - + bool charInSupportedScript(char16_t chr) { // This is a rough heuristic: whether we "can render" a script // actually depends on the properties of the font being used @@ -622,13 +604,15 @@ bool charInSupportedScript(char16_t chr) { // complex text shaping, based on unicode script metadata: // http://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt // where "Web Rank <= 32" "Shaping Required = YES" - return !((chr >= 0x0900 && chr <= 0x0DFF) || - // Main blocks for Indic scripts and Sinhala - (chr >= 0x0F00 && chr <= 0x109F) || - // Main blocks for Tibetan and Myanmar - isInKhmer(chr)); + return !( + (chr >= 0x0900 && chr <= 0x0DFF) || + // Main blocks for Indic scripts and Sinhala + (chr >= 0x0F00 && chr <= 0x109F) || + // Main blocks for Tibetan and Myanmar + isInKhmer(chr) + ); } - + bool isStringInSupportedScript(const std::string& input) { auto u16string = util::convertUTF8ToUTF16(input); for (char16_t chr : u16string) { @@ -640,11 +624,8 @@ bool isStringInSupportedScript(const std::string& input) { } bool isCharInComplexShapingScript(char16_t chr) { - return isInArabic(chr) || - isInArabicSupplement(chr) || - isInArabicExtendedA(chr) || - isInArabicPresentationFormsA(chr) || - isInArabicPresentationFormsB(chr); + return isInArabic(chr) || isInArabicSupplement(chr) || isInArabicExtendedA(chr) || + isInArabicPresentationFormsA(chr) || isInArabicPresentationFormsB(chr); } bool isWhitespace(char16_t chr) { diff --git a/src/mbgl/util/i18n.hpp b/src/mbgl/util/i18n.hpp index 7e75aa06f76..9a33ad02852 100644 --- a/src/mbgl/util/i18n.hpp +++ b/src/mbgl/util/i18n.hpp @@ -72,7 +72,7 @@ std::u16string verticalizePunctuation(const std::u16string& input); @return The character’s specialized vertical form; 0 if not applicable. */ char16_t verticalizePunctuation(char16_t chr); - + bool isStringInSupportedScript(const std::string& input); bool isCharInComplexShapingScript(char16_t chr); diff --git a/src/mbgl/util/intersection_tests.cpp b/src/mbgl/util/intersection_tests.cpp index eb2f38c64ba..8ed7b5e2862 100644 --- a/src/mbgl/util/intersection_tests.cpp +++ b/src/mbgl/util/intersection_tests.cpp @@ -9,7 +9,9 @@ bool polygonContainsPoint(const GeometryCoordinates& ring, const GeometryCoordin for (auto i = ring.begin(), j = ring.end() - 1; i != ring.end(); j = i++) { auto& p1 = *i; auto& p2 = *j; - if (((p1.y > p.y) != (p2.y > p.y)) && (p.x < static_cast(p2.x - p1.x) * static_cast(p.y - p1.y) / static_cast(p2.y - p1.y) + p1.x)) { + if (((p1.y > p.y) != (p2.y > p.y)) && + (p.x < static_cast(p2.x - p1.x) * static_cast(p.y - p1.y) / static_cast(p2.y - p1.y) + + p1.x)) { c = !c; } } @@ -47,9 +49,14 @@ bool isCounterClockwise(const GeometryCoordinate& a, const GeometryCoordinate& b return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); } -bool lineSegmentIntersectsLineSegment(const GeometryCoordinate& a0, const GeometryCoordinate& a1, const GeometryCoordinate& b0, const GeometryCoordinate& b1) { +bool lineSegmentIntersectsLineSegment( + const GeometryCoordinate& a0, + const GeometryCoordinate& a1, + const GeometryCoordinate& b0, + const GeometryCoordinate& b1 +) { return isCounterClockwise(a0, b0, b1) != isCounterClockwise(a1, b0, b1) && - isCounterClockwise(a0, a1, b0) != isCounterClockwise(a0, a1, b1); + isCounterClockwise(a0, a1, b0) != isCounterClockwise(a0, a1, b1); } bool lineIntersectsLine(const GeometryCoordinates& lineA, const GeometryCoordinates& lineB) { if (lineA.empty() || lineB.empty()) return false; @@ -88,7 +95,9 @@ bool polygonIntersectsBufferedPoint(const GeometryCoordinates& polygon, const Ge return false; } -bool polygonIntersectsBufferedMultiPoint(const GeometryCoordinates& polygon, const GeometryCollection& rings, float radius) { +bool polygonIntersectsBufferedMultiPoint( + const GeometryCoordinates& polygon, const GeometryCollection& rings, float radius +) { for (auto& ring : rings) { for (auto& point : ring) { if (polygonIntersectsBufferedPoint(polygon, point, radius)) return true; @@ -97,7 +106,9 @@ bool polygonIntersectsBufferedMultiPoint(const GeometryCoordinates& polygon, con return false; } -bool polygonIntersectsBufferedMultiLine(const GeometryCoordinates& polygon, const GeometryCollection& multiLine, float radius) { +bool polygonIntersectsBufferedMultiLine( + const GeometryCoordinates& polygon, const GeometryCollection& multiLine, float radius +) { for (auto& line : multiLine) { if (polygon.size() >= 3) { for (auto& p : line) { diff --git a/src/mbgl/util/io.cpp b/src/mbgl/util/io.cpp index 7c6fefe7629..68b7dfa64b0 100644 --- a/src/mbgl/util/io.cpp +++ b/src/mbgl/util/io.cpp @@ -16,9 +16,9 @@ namespace mbgl { namespace util { -IOException::IOException(int err, const std::string& msg) - : std::runtime_error(msg + ": " + std::strerror(errno)), code(err) { -} +IOException::IOException(int err, const std::string &msg) + : std::runtime_error(msg + ": " + std::strerror(errno)), + code(err) {} void write_file(const std::string &filename, const std::string &data) { FILE *fd = fopen(filename.c_str(), MBGL_FOPEN_MODE_WBE); @@ -51,14 +51,14 @@ std::optional readFile(const std::string &filename) { return {}; } -void deleteFile(const std::string& filename) { +void deleteFile(const std::string &filename) { const int ret = std::remove(filename.c_str()); if (ret != 0 && errno != ENOENT) { throw IOException(errno, "Could not delete file " + filename); } } -void copyFile(const std::string& destination, const std::string& source) { +void copyFile(const std::string &destination, const std::string &source) { std::ifstream src(source, std::ios::binary); if (!src.good()) { throw IOException(errno, "Cannot read file " + source); diff --git a/src/mbgl/util/io.hpp b/src/mbgl/util/io.hpp index f4f7ddeb6b1..7e57b312798 100644 --- a/src/mbgl/util/io.hpp +++ b/src/mbgl/util/io.hpp @@ -12,10 +12,10 @@ struct IOException : std::runtime_error { const int code = 0; }; -void write_file(const std::string &filename, const std::string &data); -std::string read_file(const std::string &filename); +void write_file(const std::string& filename, const std::string& data); +std::string read_file(const std::string& filename); -std::optional readFile(const std::string &filename); +std::optional readFile(const std::string& filename); void deleteFile(const std::string& filename); void copyFile(const std::string& destination, const std::string& source); diff --git a/src/mbgl/util/literal.hpp b/src/mbgl/util/literal.hpp index d4fec49b35f..6bbff94887a 100644 --- a/src/mbgl/util/literal.hpp +++ b/src/mbgl/util/literal.hpp @@ -9,11 +9,9 @@ namespace mbgl { template struct string_literal { - static constexpr const char chars[] = { Cs..., 0 }; + static constexpr const char chars[] = {Cs..., 0}; - static constexpr const char* value() { - return chars; - } + static constexpr const char* value() { return chars; } }; template @@ -35,23 +33,17 @@ struct concat_literals; template <> struct concat_literals<> { - static constexpr auto value() { - return ""; - } + static constexpr auto value() { return ""; } }; template struct concat_literals, string_literal, Rest...> { - static constexpr auto value() { - return concat_literals, Rest...>::value(); - } + static constexpr auto value() { return concat_literals, Rest...>::value(); } }; template struct concat_literals> { - static constexpr auto value() { - return string_literal::value(); - } + static constexpr auto value() { return string_literal::value(); } }; } // namespace detail @@ -60,7 +52,8 @@ template struct concat_literals { static constexpr auto value() { return detail::concat_literals( - std::make_index_sequence()))...>::value(); + std::make_index_sequence() + ))...>::value(); } }; diff --git a/src/mbgl/util/logging.cpp b/src/mbgl/util/logging.cpp index 92884bc7f11..060aa068e4c 100644 --- a/src/mbgl/util/logging.cpp +++ b/src/mbgl/util/logging.cpp @@ -20,7 +20,8 @@ std::mutex mutex; class Log::Impl { public: - Impl() : scheduler(Scheduler::GetSequenced()) {} + Impl() + : scheduler(Scheduler::GetSequenced()) {} void record(EventSeverity severity, Event event, int64_t code, const std::string& msg) { if (useThread) { @@ -35,7 +36,8 @@ class Log::Impl { const std::shared_ptr scheduler; }; -Log::Log() : impl(std::make_unique()) {} +Log::Log() + : impl(std::make_unique()) {} Log::~Log() = default; @@ -60,22 +62,23 @@ std::unique_ptr Log::removeObserver() { return observer; } -void Log::record(EventSeverity severity, Event event, const std::string &msg) { +void Log::record(EventSeverity severity, Event event, const std::string& msg) { get()->impl->record(severity, event, -1, msg); } -void Log::record(EventSeverity severity, Event event, int64_t code, const std::string &msg) { +void Log::record(EventSeverity severity, Event event, int64_t code, const std::string& msg) { get()->impl->record(severity, event, code, msg); } -void Log::record(EventSeverity severity, - Event event, - int64_t code, - const std::string& msg, - const std::optional& threadName) { +void Log::record( + EventSeverity severity, + Event event, + int64_t code, + const std::string& msg, + const std::optional& threadName +) { std::lock_guard lock(mutex); - if (currentObserver && severity != EventSeverity::Debug && - currentObserver->onRecord(severity, event, code, msg)) { + if (currentObserver && severity != EventSeverity::Debug && currentObserver->onRecord(severity, event, code, msg)) { return; } diff --git a/src/mbgl/util/longest_common_subsequence.hpp b/src/mbgl/util/longest_common_subsequence.hpp index 522b5a86b1c..04487c4510c 100644 --- a/src/mbgl/util/longest_common_subsequence.hpp +++ b/src/mbgl/util/longest_common_subsequence.hpp @@ -24,10 +24,7 @@ namespace mbgl { TODO: implement the O(N) space refinement presented in the paper. */ template -OutIt longest_common_subsequence(InIt a, InIt endA, - InIt b, InIt endB, - OutIt outIt, - Equal eq) { +OutIt longest_common_subsequence(InIt a, InIt endA, InIt b, InIt endB, OutIt outIt, Equal eq) { const std::ptrdiff_t N = endA - a; const std::ptrdiff_t M = endB - b; const std::ptrdiff_t D = N + M; @@ -39,7 +36,7 @@ OutIt longest_common_subsequence(InIt a, InIt endA, std::vector> vs; // Self-executing lambda to allow `return` to break from inner loop, and avoid shadowing `v`. - [&] () { + [&]() { std::vector v; v.resize(2 * D + 1); v[1] = 0; @@ -50,8 +47,8 @@ OutIt longest_common_subsequence(InIt a, InIt endA, for (std::ptrdiff_t d = 0; d <= D; ++d) { for (std::ptrdiff_t k = -d; k <= d; k += 2) { std::ptrdiff_t x = (k == -d || (k != d && v.at(k - 1 + D) < v.at(k + 1 + D))) - ? v.at(k + 1 + D) // moving down - : v.at(k - 1 + D) + 1; // moving right + ? v.at(k + 1 + D) // moving down + : v.at(k - 1 + D) + 1; // moving right std::ptrdiff_t y = x - k; @@ -96,10 +93,8 @@ OutIt longest_common_subsequence(InIt a, InIt endA, return std::copy(lcsReverse.rbegin(), lcsReverse.rend(), outIt); } -template < typename InIt, typename OutIt > -OutIt longest_common_subsequence(InIt a, InIt endA, - InIt b, InIt endB, - OutIt outIt) { +template +OutIt longest_common_subsequence(InIt a, InIt endA, InIt b, InIt endB, OutIt outIt) { return longest_common_subsequence(a, endA, b, endB, outIt, std::equal_to<>()); } diff --git a/src/mbgl/util/mapbox.cpp b/src/mbgl/util/mapbox.cpp index 17d5534254d..366f157ef52 100644 --- a/src/mbgl/util/mapbox.cpp +++ b/src/mbgl/util/mapbox.cpp @@ -24,98 +24,96 @@ inline int nthOccurrenceFromEnd(const std::string& str, const std::string& searc size_t pos = str.length(); int cnt = 0; - while (cnt != nth){ - pos-=1; + while (cnt != nth) { + pos -= 1; pos = str.rfind(search, pos); - if ( pos == std::string::npos ) - return -1; + if (pos == std::string::npos) return -1; cnt++; } return static_cast(pos); } inline void replace(std::string& str, const std::string& search, const std::string& replacement) { - std::string::size_type pos = 0u; - while((pos = str.find(search, pos)) != std::string::npos){ - str.replace(pos, search.length(), replacement); - pos += replacement.length(); - } + std::string::size_type pos = 0u; + while ((pos = str.find(search, pos)) != std::string::npos) { + str.replace(pos, search.length(), replacement); + pos += replacement.length(); + } } bool isCanonicalURL(const TileServerOptions& tileServerOptions, const std::string& url) { if (tileServerOptions.uriSchemeAlias().empty() || tileServerOptions.baseURL().empty()) { return false; } - + const auto& protocol = tileServerOptions.uriSchemeAlias() + "://"; return url.compare(0, protocol.length(), protocol) == 0; } std::map createTokenMap(const std::string& urlTemplate, const std::string& url) { const URL parsedUrl(url); - + // e.g. tiles/satellite/tiles.json auto path = url.substr(parsedUrl.path.first, parsedUrl.path.second); - + // --- find tokens in the urlTemplate (such as {path}, ...) std::regex r(R"(\{(domain|path|directory|filename|extension)\})"); std::vector> tokenList; - for(std::sregex_iterator i = std::sregex_iterator(urlTemplate.begin(), urlTemplate.end(), r); - i != std::sregex_iterator(); - ++i) - { + for (std::sregex_iterator i = std::sregex_iterator(urlTemplate.begin(), urlTemplate.end(), r); + i != std::sregex_iterator(); + ++i) { const std::smatch& m = *i; if (m.size() > 0) { auto captureGroupValue = m[1].str(); - if (!captureGroupValue.empty()){ + if (!captureGroupValue.empty()) { std::pair tokenInfo; tokenInfo.first = captureGroupValue; tokenList.push_back(tokenInfo); } } } - + // --- extract token values // /tiles{path}/tiles.json in tiles/satellite/tiles.json // e.g. path = /satelite - std::regex tokenPattern (R"(\{domain\}|\{path\}|\{directory\}|\{filename\}|\{extension\})"); - std::string templatePattern = std::regex_replace (urlTemplate, tokenPattern, "(.+)", std::regex_constants::match_any); + std::regex tokenPattern(R"(\{domain\}|\{path\}|\{directory\}|\{filename\}|\{extension\})"); + std::string templatePattern = std::regex_replace( + urlTemplate, tokenPattern, "(.+)", std::regex_constants::match_any + ); std::regex r2(templatePattern); int idx = 0; - for(std::sregex_iterator i = std::sregex_iterator(path.begin(), path.end(), r2); - i != std::sregex_iterator(); - ++i) - { + for (std::sregex_iterator i = std::sregex_iterator(path.begin(), path.end(), r2); i != std::sregex_iterator(); + ++i) { const std::smatch& m = *i; if (m.size() > 0) { auto captureGroupValue = m[1].str(); - if (!captureGroupValue.empty()){ + if (!captureGroupValue.empty()) { tokenList[idx].second = captureGroupValue; idx++; } } } - + std::map tokenMap; - std::copy(tokenList.begin(), tokenList.end(), - std::inserter(tokenMap, tokenMap.begin())); - + std::copy(tokenList.begin(), tokenList.end(), std::inserter(tokenMap, tokenMap.begin())); + return tokenMap; } bool isNormalizedSourceURL(const std::string& baseURL, const std::string& urlTemplate, const std::string& url) { - if (baseURL.empty() || urlTemplate.empty()){ + if (baseURL.empty() || urlTemplate.empty()) { return false; } - - std::regex tokenPattern (R"(\{.+\})"); - std::string urlPattern = std::regex_replace (urlTemplate, tokenPattern, "(.+)", std::regex_constants::match_any)+"(.*)"; - std::string pattern (baseURL + urlPattern); - - if (std::regex_match (url, std::regex(pattern))){ + + std::regex tokenPattern(R"(\{.+\})"); + std::string urlPattern = std::regex_replace(urlTemplate, tokenPattern, "(.+)", std::regex_constants::match_any) + + "(.*)"; + std::string pattern(baseURL + urlPattern); + + if (std::regex_match(url, std::regex(pattern))) { return true; } - + return false; } @@ -125,35 +123,36 @@ bool isNormalizedURL(const TileServerOptions& tileServerOptions, const std::stri // Make sure that we are dealing with a valid tile URL. // Has to be with the tile template prefix, with a valid filename + extension - + if (tileServerOptions.uriSchemeAlias() == "mapbox") { const URL baseURL(tileServerOptions.baseURL()); auto domain = str.substr(url.domain.first, url.domain.second); - + replace(domain, ".cn", ".com"); // hack for mapbox china - + auto refDomain = tileServerOptions.baseURL().substr(baseURL.domain.first, baseURL.domain.second); const auto refDomainIdx = nthOccurrenceFromEnd(refDomain, ".", 2); refDomain = refDomain.substr(refDomainIdx + 1, refDomain.length() - refDomainIdx - 1); - + if (!endsWith(domain, refDomain) || path.filename.second == 0 || path.extension.second <= 1) { // Not a proper tile URL. return false; } - } - else { + } else { if (path.filename.second == 0 || path.extension.second <= 1) { // Not a proper tile URL. return false; } } - + return true; } std::string makeQueryString(const TileServerOptions& tileServerOptions, const std::string& apiKey) { - std::string queryString = (!tileServerOptions.requiresApiKey() || tileServerOptions.apiKeyParameterName().empty() || apiKey.empty()) ? - "" : "?" + tileServerOptions.apiKeyParameterName() + "=" + apiKey; + std::string queryString = (!tileServerOptions.requiresApiKey() || tileServerOptions.apiKeyParameterName().empty() || + apiKey.empty()) + ? "" + : "?" + tileServerOptions.apiKeyParameterName() + "=" + apiKey; return queryString; } @@ -161,15 +160,14 @@ static bool equals(const std::string& str, const URL::Segment& segment, std::str return str.compare(segment.first, segment.second, ref) == 0; } -std::string normalizeSourceURL(const TileServerOptions& tileServerOptions, - const std::string& str, - const std::string& apiKey) { +std::string normalizeSourceURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +) { if (!isCanonicalURL(tileServerOptions, str)) { return str; } if (tileServerOptions.requiresApiKey() && apiKey.empty()) { - throw std::runtime_error( - "You must provide API key for tile sources"); + throw std::runtime_error("You must provide API key for tile sources"); } std::string suffix = ""; @@ -182,14 +180,15 @@ std::string normalizeSourceURL(const TileServerOptions& tileServerOptions, Log::Error(Event::ParseStyle, "Invalid source URL"); return str; } - - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.sourceVersionPrefix().value_or("") + tileServerOptions.sourceTemplate() + makeQueryString(tileServerOptions, apiKey) + suffix; + + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.sourceVersionPrefix().value_or("") + + tileServerOptions.sourceTemplate() + makeQueryString(tileServerOptions, apiKey) + suffix; return transformURL(tpl, str, url); } -std::string normalizeStyleURL(const TileServerOptions& tileServerOptions, - const std::string& str, - const std::string& apiKey) { +std::string normalizeStyleURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +) { if (!isCanonicalURL(tileServerOptions, str)) { return str; } @@ -200,16 +199,16 @@ std::string normalizeStyleURL(const TileServerOptions& tileServerOptions, Log::Error(Event::ParseStyle, "Invalid style URL"); return str; } - - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.styleVersionPrefix().value_or("") + tileServerOptions.styleTemplate() + makeQueryString(tileServerOptions, apiKey); - + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.styleVersionPrefix().value_or("") + + tileServerOptions.styleTemplate() + makeQueryString(tileServerOptions, apiKey); + return transformURL(tpl, str, url); } -std::string normalizeSpriteURL(const TileServerOptions& tileServerOptions, - const std::string& str, - const std::string& apiKey) { +std::string normalizeSpriteURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +) { if (!isCanonicalURL(tileServerOptions, str)) { return str; } @@ -221,13 +220,14 @@ std::string normalizeSpriteURL(const TileServerOptions& tileServerOptions, return str; } - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.spritesVersionPrefix().value_or("") + tileServerOptions.spritesTemplate() + makeQueryString(tileServerOptions, apiKey); + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.spritesVersionPrefix().value_or("") + + tileServerOptions.spritesTemplate() + makeQueryString(tileServerOptions, apiKey); return transformURL(tpl, str, url); } -std::string normalizeGlyphsURL(const TileServerOptions& tileServerOptions, - const std::string& str, - const std::string& apiKey) { +std::string normalizeGlyphsURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +) { if (!isCanonicalURL(tileServerOptions, str)) { return str; } @@ -239,17 +239,18 @@ std::string normalizeGlyphsURL(const TileServerOptions& tileServerOptions, return str; } - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.glyphsVersionPrefix().value_or("") + tileServerOptions.glyphsTemplate() + makeQueryString(tileServerOptions, apiKey); + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.glyphsVersionPrefix().value_or("") + + tileServerOptions.glyphsTemplate() + makeQueryString(tileServerOptions, apiKey); return transformURL(tpl, str, url); } -std::string normalizeTileURL(const TileServerOptions& tileServerOptions, - const std::string& str, - const std::string& apiKey) { +std::string normalizeTileURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +) { if (!isCanonicalURL(tileServerOptions, str)) { return str; } - + const URL url(str); auto domainName = tileServerOptions.tileDomainName(); if (!equals(str, url.domain, domainName)) { @@ -257,28 +258,32 @@ std::string normalizeTileURL(const TileServerOptions& tileServerOptions, return str; } - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.tileVersionPrefix().value_or("") + tileServerOptions.tileTemplate() + makeQueryString(tileServerOptions, apiKey); + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.tileVersionPrefix().value_or("") + + tileServerOptions.tileTemplate() + makeQueryString(tileServerOptions, apiKey); return transformURL(tpl, str, url); } -std::string -canonicalizeTileURL(const TileServerOptions& tileServerOptions, const std::string& str, const style::SourceType type, const uint16_t tileSize) { - - if (!isNormalizedURL(tileServerOptions, str)){ +std::string canonicalizeTileURL( + const TileServerOptions& tileServerOptions, + const std::string& str, + const style::SourceType type, + const uint16_t tileSize +) { + if (!isNormalizedURL(tileServerOptions, str)) { return str; } std::string result = tileServerOptions.uriSchemeAlias() + "://" + tileServerOptions.tileDomainName(); - + const URL url(str); const Path path(str, url.path.first, url.path.second); - + int versionPrefixLen = 0; const auto& versionPrefix = tileServerOptions.tileVersionPrefix(); - if (versionPrefix.has_value()){ + if (versionPrefix.has_value()) { versionPrefixLen = static_cast(versionPrefix.value().length()); } - + result.append(str, path.directory.first + versionPrefixLen, path.directory.second - versionPrefixLen); result.append(str, path.filename.first, path.filename.second); if (type == style::SourceType::Raster || type == style::SourceType::RasterDEM) { @@ -296,8 +301,7 @@ canonicalizeTileURL(const TileServerOptions& tileServerOptions, const std::strin const auto& apiKey = tileServerOptions.apiKeyParameterName() + "="; if (str.compare(idx, apiKey.length(), apiKey) != 0) { result.append(1, hasQuery ? '&' : '?'); - result.append(str, idx, ampersandIdx != std::string::npos ? ampersandIdx - idx - : std::string::npos); + result.append(str, idx, ampersandIdx != std::string::npos ? ampersandIdx - idx : std::string::npos); hasQuery = true; } idx = ampersandIdx; @@ -307,8 +311,13 @@ canonicalizeTileURL(const TileServerOptions& tileServerOptions, const std::strin return result; } -void canonicalizeTileset(const TileServerOptions& tileServerOptions, Tileset& tileset, - const std::string& sourceURL, style::SourceType type, uint16_t tileSize) { +void canonicalizeTileset( + const TileServerOptions& tileServerOptions, + Tileset& tileset, + const std::string& sourceURL, + style::SourceType type, + uint16_t tileSize +) { if (isCanonicalURL(tileServerOptions, sourceURL) || isNormalizedSourceURL(tileServerOptions.baseURL(), tileServerOptions.sourceTemplate(), sourceURL)) { for (auto& url : tileset.tiles) { @@ -317,21 +326,21 @@ void canonicalizeTileset(const TileServerOptions& tileServerOptions, Tileset& ti } } -std::string canonicalizeSourceURL(const TileServerOptions& tileServerOptions, const std::string& url){ - if (url.empty()) - return url; - +std::string canonicalizeSourceURL(const TileServerOptions& tileServerOptions, const std::string& url) { + if (url.empty()) return url; + if (isNormalizedSourceURL(tileServerOptions.baseURL(), tileServerOptions.sourceTemplate(), url)) { auto tokenMap = createTokenMap(tileServerOptions.sourceTemplate(), url); - + auto retVal = tileServerOptions.uriSchemeAlias() + "://"; if (tokenMap.find("domain") != tokenMap.end()) { retVal += tokenMap.at("domain"); } else { if (!tileServerOptions.sourceDomainName().empty()) retVal += tileServerOptions.sourceDomainName(); } - - if (tileServerOptions.sourceVersionPrefix().has_value()) retVal += tileServerOptions.sourceVersionPrefix().value(); + + if (tileServerOptions.sourceVersionPrefix().has_value()) + retVal += tileServerOptions.sourceVersionPrefix().value(); if (tokenMap.find("path") != tokenMap.end()) { retVal += tokenMap.at("path"); @@ -340,28 +349,28 @@ std::string canonicalizeSourceURL(const TileServerOptions& tileServerOptions, co if (tokenMap.find("filename") != tokenMap.end()) retVal += tokenMap.at("filename"); if (tokenMap.find("extension") != tokenMap.end()) retVal += tokenMap.at("extension"); } - + return retVal; } return url; } -std::string canonicalizeSpriteURL(const TileServerOptions& tileServerOptions, const std::string& url){ - if (url.empty()) - return url; - +std::string canonicalizeSpriteURL(const TileServerOptions& tileServerOptions, const std::string& url) { + if (url.empty()) return url; + if (isNormalizedSourceURL(tileServerOptions.baseURL(), tileServerOptions.spritesTemplate(), url)) { auto tokenMap = createTokenMap(tileServerOptions.spritesTemplate(), url); - + auto retVal = tileServerOptions.uriSchemeAlias() + "://"; if (tokenMap.find("domain") != tokenMap.end()) { retVal += tokenMap.at("domain"); } else { if (!tileServerOptions.spritesDomainName().empty()) retVal += tileServerOptions.spritesDomainName(); } - - if (tileServerOptions.spritesVersionPrefix().has_value()) retVal += tileServerOptions.spritesVersionPrefix().value(); - + + if (tileServerOptions.spritesVersionPrefix().has_value()) + retVal += tileServerOptions.spritesVersionPrefix().value(); + if (tokenMap.find("path") != tokenMap.end()) { retVal += tokenMap.at("path"); } else { @@ -369,30 +378,30 @@ std::string canonicalizeSpriteURL(const TileServerOptions& tileServerOptions, co if (tokenMap.find("filename") != tokenMap.end()) retVal += tokenMap.at("filename"); if (tokenMap.find("extension") != tokenMap.end()) retVal += tokenMap.at("extension"); } - + return retVal; } - + return url; } -std::string canonicalizeGlyphURL(const TileServerOptions& tileServerOptions, const std::string& url){ - if (url.empty()) - return url; - +std::string canonicalizeGlyphURL(const TileServerOptions& tileServerOptions, const std::string& url) { + if (url.empty()) return url; + // "https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key=uwvyvzaF2P7UWbyOEvjU" if (isNormalizedSourceURL(tileServerOptions.baseURL(), tileServerOptions.glyphsTemplate(), url)) { auto tokenMap = createTokenMap(tileServerOptions.glyphsTemplate(), url); - + auto retVal = tileServerOptions.uriSchemeAlias() + "://"; if (tokenMap.find("domain") != tokenMap.end()) { retVal += tokenMap.at("domain"); } else { if (!tileServerOptions.glyphsDomainName().empty()) retVal += tileServerOptions.glyphsDomainName(); } - - if (tileServerOptions.glyphsVersionPrefix().has_value()) retVal += tileServerOptions.glyphsVersionPrefix().value(); - + + if (tileServerOptions.glyphsVersionPrefix().has_value()) + retVal += tileServerOptions.glyphsVersionPrefix().value(); + if (tokenMap.find("path") != tokenMap.end()) { retVal += tokenMap.at("path"); } else { @@ -400,11 +409,10 @@ std::string canonicalizeGlyphURL(const TileServerOptions& tileServerOptions, con if (tokenMap.find("filename") != tokenMap.end()) retVal += tokenMap.at("filename"); if (tokenMap.find("extension") != tokenMap.end()) retVal += tokenMap.at("extension"); } - + return retVal; } - - + return url; } diff --git a/src/mbgl/util/mapbox.hpp b/src/mbgl/util/mapbox.hpp index 57d46810cc2..c0b2c408236 100644 --- a/src/mbgl/util/mapbox.hpp +++ b/src/mbgl/util/mapbox.hpp @@ -11,22 +11,36 @@ class Tileset; namespace util { namespace mapbox { -bool isCanonicalURL(const TileServerOptions& tileServerOptions,const std::string& url); - -std::string normalizeSourceURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); -std::string normalizeStyleURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); -std::string normalizeSpriteURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); -std::string normalizeGlyphsURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); -std::string normalizeTileURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); +bool isCanonicalURL(const TileServerOptions& tileServerOptions, const std::string& url); + +std::string normalizeSourceURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +); +std::string normalizeStyleURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +); +std::string normalizeSpriteURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +); +std::string normalizeGlyphsURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +); +std::string normalizeTileURL( + const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey +); // Return a "mapbox://tiles/..." URL (suitable for normalizeTileURL) for the given Mapbox tile URL. -std::string canonicalizeTileURL(const TileServerOptions& tileServerOptions, const std::string& str, style::SourceType, uint16_t tileSize); +std::string canonicalizeTileURL( + const TileServerOptions& tileServerOptions, const std::string& str, style::SourceType, uint16_t tileSize +); std::string canonicalizeSourceURL(const TileServerOptions& tileServerOptions, const std::string& url); std::string canonicalizeSpriteURL(const TileServerOptions& tileServerOptions, const std::string& url); std::string canonicalizeGlyphURL(const TileServerOptions& tileServerOptions, const std::string& url); // Replace URL templates with "mapbox://tiles/..." URLs (suitable for normalizeTileURL). -void canonicalizeTileset(const TileServerOptions& tileServerOptions, Tileset&, const std::string& url, style::SourceType, uint16_t tileSize); +void canonicalizeTileset( + const TileServerOptions& tileServerOptions, Tileset&, const std::string& url, style::SourceType, uint16_t tileSize +); extern const uint64_t DEFAULT_OFFLINE_TILE_COUNT_LIMIT; diff --git a/src/mbgl/util/mat2.cpp b/src/mbgl/util/mat2.cpp index 89617d8449e..1d0f1585de1 100644 --- a/src/mbgl/util/mat2.cpp +++ b/src/mbgl/util/mat2.cpp @@ -40,8 +40,8 @@ void matrix::rotate(mat2& out, const mat2& a, double rad) { double a3 = a[3]; double s = std::sin(rad); double c = std::cos(rad); - out[0] = a0 * c + a2 * s; - out[1] = a1 * c + a3 * s; + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; out[2] = a0 * -s + a2 * c; out[3] = a1 * -s + a3 * c; } diff --git a/src/mbgl/util/mat4.cpp b/src/mbgl/util/mat4.cpp index 9909b7e3eee..b69eb3262d1 100644 --- a/src/mbgl/util/mat4.cpp +++ b/src/mbgl/util/mat4.cpp @@ -186,13 +186,31 @@ void translate(mat4& out, const mat4& a, double x, double y, double z) { double a22; double a23; - a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; - a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; - a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; - - out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03; - out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13; - out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23; + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a03; + out[4] = a10; + out[5] = a11; + out[6] = a12; + out[7] = a13; + out[8] = a20; + out[9] = a21; + out[10] = a22; + out[11] = a23; out[12] = a00 * x + a10 * y + a20 * z + a[12]; out[13] = a01 * x + a11 * y + a21 * z + a[13]; @@ -214,10 +232,10 @@ void rotate_x(mat4& out, const mat4& a, double rad) { double a23 = a[11]; if (&a != &out) { // If the source and destination differ, copy the unchanged rows - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; @@ -248,10 +266,10 @@ void rotate_y(mat4& out, const mat4& a, double rad) { double a23 = a[11]; if (&a != &out) { // If the source and destination differ, copy the unchanged rows - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; @@ -282,8 +300,8 @@ void rotate_z(mat4& out, const mat4& a, double rad) { double a13 = a[7]; if (&a != &out) { // If the source and destination differ, copy the unchanged last row - out[8] = a[8]; - out[9] = a[9]; + out[8] = a[8]; + out[9] = a[9]; out[10] = a[10]; out[11] = a[11]; out[12] = a[12]; @@ -350,19 +368,28 @@ void multiply(mat4& out, const mat4& a, const mat4& b) { out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; diff --git a/src/mbgl/util/math.hpp b/src/mbgl/util/math.hpp index d7350337429..40f3015e7fb 100644 --- a/src/mbgl/util/math.hpp +++ b/src/mbgl/util/math.hpp @@ -26,10 +26,7 @@ T angle_to(const Point& a, const Point& b) { // Reflect an angle around 0 degrees template std::array flip(const std::array& c) { - return {{ - static_cast(2 * M_PI - c[0]), - static_cast(2 * M_PI - c[1]) - }}; + return {{static_cast(2 * M_PI - c[0]), static_cast(2 * M_PI - c[1])}}; } template @@ -37,7 +34,7 @@ Point normal(const S1& a, const S2& b) { T dx = b.x - a.x; T dy = b.y - a.y; T c = std::sqrt(dx * dx + dy * dy); - return { dx / c, dy / c }; + return {dx / c, dy / c}; } template diff --git a/src/mbgl/util/premultiply.cpp b/src/mbgl/util/premultiply.cpp index 02c045fbb40..130d3ba4936 100644 --- a/src/mbgl/util/premultiply.cpp +++ b/src/mbgl/util/premultiply.cpp @@ -9,7 +9,7 @@ PremultipliedImage premultiply(UnassociatedImage&& src) { PremultipliedImage dst; dst.size = src.size; - src.size = { 0, 0 }; + src.size = {0, 0}; dst.data = std::move(src.data); uint8_t* data = dst.data.get(); @@ -30,7 +30,7 @@ UnassociatedImage unpremultiply(PremultipliedImage&& src) { UnassociatedImage dst; dst.size = src.size; - src.size = { 0, 0 }; + src.size = {0, 0}; dst.data = std::move(src.data); uint8_t* data = dst.data.get(); diff --git a/src/mbgl/util/quaternion.hpp b/src/mbgl/util/quaternion.hpp index b2ae40eaf76..0a62217ed09 100644 --- a/src/mbgl/util/quaternion.hpp +++ b/src/mbgl/util/quaternion.hpp @@ -13,9 +13,15 @@ struct Quaternion { }; }; - Quaternion() : Quaternion(0.0, 0.0, 0.0, 0.0) {} - Quaternion(double x_, double y_, double z_, double w_) : x(x_), y(y_), z(z_), w(w_) {} - Quaternion(const vec4& vec) : m(vec) {} + Quaternion() + : Quaternion(0.0, 0.0, 0.0, 0.0) {} + Quaternion(double x_, double y_, double z_, double w_) + : x(x_), + y(y_), + z(z_), + w(w_) {} + Quaternion(const vec4& vec) + : m(vec) {} Quaternion conjugate() const; Quaternion normalized() const; diff --git a/src/mbgl/util/rapidjson.cpp b/src/mbgl/util/rapidjson.cpp index 32a3c0b929e..d63afd58712 100644 --- a/src/mbgl/util/rapidjson.cpp +++ b/src/mbgl/util/rapidjson.cpp @@ -4,10 +4,8 @@ namespace mbgl { std::string formatJSONParseError(const JSDocument& doc) { - return std::string{ rapidjson::GetParseError_En(doc.GetParseError()) } + " at offset " + + return std::string{rapidjson::GetParseError_En(doc.GetParseError())} + " at offset " + util::toString(doc.GetErrorOffset()); } } // namespace mbgl - - diff --git a/src/mbgl/util/rect.hpp b/src/mbgl/util/rect.hpp index f5937f5c94e..7e76a9f7ad8 100644 --- a/src/mbgl/util/rect.hpp +++ b/src/mbgl/util/rect.hpp @@ -5,12 +5,16 @@ namespace mbgl { template struct Rect { Rect() = default; - Rect(T x_, T y_, T w_, T h_) : x(x_), y(y_), w(w_), h(h_) {} + Rect(T x_, T y_, T w_, T h_) + : x(x_), + y(y_), + w(w_), + h(h_) {} T x = 0, y = 0; T w = 0, h = 0; template - Rect operator *(Number value) const { + Rect operator*(Number value) const { return Rect(x * value, y * value, w * value, h * value); } diff --git a/src/mbgl/util/stopwatch.cpp b/src/mbgl/util/stopwatch.cpp index 68534039939..ded599ef1e2 100644 --- a/src/mbgl/util/stopwatch.cpp +++ b/src/mbgl/util/stopwatch.cpp @@ -10,21 +10,31 @@ namespace mbgl { namespace util { stopwatch::stopwatch(Event event_) - : event(event_), start(Clock::now()) {} + : event(event_), + start(Clock::now()) {} stopwatch::stopwatch(EventSeverity severity_, Event event_) - : severity(severity_), event(event_), start(Clock::now()) {} + : severity(severity_), + event(event_), + start(Clock::now()) {} stopwatch::stopwatch(std::string name_, Event event_) - : name(std::move(name_)), event(event_), start(Clock::now()) {} + : name(std::move(name_)), + event(event_), + start(Clock::now()) {} stopwatch::stopwatch(std::string name_, EventSeverity severity_, Event event_) - : name(std::move(name_)), severity(severity_), event(event_), start(Clock::now()) {} + : name(std::move(name_)), + severity(severity_), + event(event_), + start(Clock::now()) {} void stopwatch::report(const std::string &name_) { Duration duration = Clock::now() - start; - const auto logMsg = name_ + ": " + std::to_string(std::chrono::duration(duration).count()); + const auto logMsg = name_ + ": " + + std::to_string(std::chrono::duration(duration).count() + ); Log::Record(severity, event, logMsg); start += duration; diff --git a/src/mbgl/util/stopwatch.hpp b/src/mbgl/util/stopwatch.hpp index daa313f7024..3e29122c0ab 100644 --- a/src/mbgl/util/stopwatch.hpp +++ b/src/mbgl/util/stopwatch.hpp @@ -11,14 +11,15 @@ namespace mbgl { namespace util { - + #ifdef MBGL_TIMING -// Declare 'watch' as a shared_ptr so it can be captured by value in a lambda function -#define MBGL_TIMING_START(watch) std::shared_ptr watch = std::make_unique(Event::Timing); -#define MBGL_TIMING_FINISH(watch, message) \ - do { \ - std::stringstream messageStream; \ - messageStream << message; \ +// Declare 'watch' as a shared_ptr so it can be captured by value in a lambda function +#define MBGL_TIMING_START(watch) \ + std::shared_ptr watch = std::make_unique(Event::Timing); +#define MBGL_TIMING_FINISH(watch, message) \ + do { \ + std::stringstream messageStream; \ + messageStream << message; \ watch->report(messageStream.str()); \ } while (0); #else diff --git a/src/mbgl/util/thread_local.hpp b/src/mbgl/util/thread_local.hpp index cf5579a2ba9..8b96dd3080c 100644 --- a/src/mbgl/util/thread_local.hpp +++ b/src/mbgl/util/thread_local.hpp @@ -25,17 +25,11 @@ class ThreadLocal : public impl::ThreadLocalBase { public: ThreadLocal() = default; - ThreadLocal(T* val) { - set(val); - } + ThreadLocal(T* val) { set(val); } - T* get() { - return reinterpret_cast(impl::ThreadLocalBase::get()); - } + T* get() { return reinterpret_cast(impl::ThreadLocalBase::get()); } - void set(T* ptr) { - impl::ThreadLocalBase::set(ptr); - } + void set(T* ptr) { impl::ThreadLocalBase::set(ptr); } }; } // namespace util diff --git a/src/mbgl/util/tile_coordinate.hpp b/src/mbgl/util/tile_coordinate.hpp index f0acc2c33a3..2916eb6fe39 100644 --- a/src/mbgl/util/tile_coordinate.hpp +++ b/src/mbgl/util/tile_coordinate.hpp @@ -21,29 +21,34 @@ class TileCoordinate { static TileCoordinate fromLatLng(double zoom, const LatLng& latLng) { const double scale = std::pow(2.0, zoom); - return { Projection::project(latLng, scale) / util::tileSize_D, zoom }; + return {Projection::project(latLng, scale) / util::tileSize_D, zoom}; } - static TileCoordinate fromScreenCoordinate(const TransformState& state, uint8_t zoom, const ScreenCoordinate& screenCoordinate) { + static TileCoordinate fromScreenCoordinate( + const TransformState& state, uint8_t zoom, const ScreenCoordinate& screenCoordinate + ) { return state.screenCoordinateToTileCoordinate(screenCoordinate, zoom); } TileCoordinate zoomTo(double zoom) const { const double scaleDiff = std::pow(2.0, zoom - z); - return { p * scaleDiff, zoom }; + return {p * scaleDiff, zoom}; } static GeometryCoordinate toGeometryCoordinate(const UnwrappedTileID& tileID, const TileCoordinatePoint& point) { const double scale = std::pow(2.0, tileID.canonical.z); - auto zoomed = TileCoordinate { point, 0 }.zoomTo(tileID.canonical.z); + auto zoomed = TileCoordinate{point, 0}.zoomTo(tileID.canonical.z); return { - int16_t(util::clamp(static_cast((zoomed.p.x - tileID.canonical.x - tileID.wrap * scale) * util::EXTENT), - std::numeric_limits::min(), - std::numeric_limits::max())), - int16_t(util::clamp(static_cast((zoomed.p.y - tileID.canonical.y) * util::EXTENT), - std::numeric_limits::min(), - std::numeric_limits::max())) - }; + int16_t(util::clamp( + static_cast((zoomed.p.x - tileID.canonical.x - tileID.wrap * scale) * util::EXTENT), + std::numeric_limits::min(), + std::numeric_limits::max() + )), + int16_t(util::clamp( + static_cast((zoomed.p.y - tileID.canonical.y) * util::EXTENT), + std::numeric_limits::min(), + std::numeric_limits::max() + ))}; } }; diff --git a/src/mbgl/util/tile_cover.cpp b/src/mbgl/util/tile_cover.cpp index afd5974542b..e6f28440e90 100644 --- a/src/mbgl/util/tile_cover.cpp +++ b/src/mbgl/util/tile_cover.cpp @@ -40,9 +40,8 @@ void scanSpans(edge e0, edge e1, int32_t ymin, int32_t ymax, ScanLine& scanLine) double y1 = ::fmin(ymax, std::ceil(e1.y1)); // sort edges by x-coordinate - if ((e0.x0 == e1.x0 && e0.y0 == e1.y0) ? - (e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) : - (e0.x1 - e1.dy / e0.dy * e0.dx < e1.x0)) { + if ((e0.x0 == e1.x0 && e0.y0 == e1.y0) ? (e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) + : (e0.x1 - e1.dy / e0.dy * e0.dx < e1.x0)) { std::swap(e0, e1); } @@ -59,20 +58,28 @@ void scanSpans(edge e0, edge e1, int32_t ymin, int32_t ymax, ScanLine& scanLine) } // scan-line conversion -void scanTriangle(const Point& a, - const Point& b, - const Point& c, - int32_t ymin, - int32_t ymax, - ScanLine& scanLine) { +void scanTriangle( + const Point& a, + const Point& b, + const Point& c, + int32_t ymin, + int32_t ymax, + ScanLine& scanLine +) { edge ab = edge(a, b); edge bc = edge(b, c); edge ca = edge(c, a); // sort edges by y-length - if (ab.dy > bc.dy) { std::swap(ab, bc); } - if (ab.dy > ca.dy) { std::swap(ab, ca); } - if (bc.dy > ca.dy) { std::swap(bc, ca); } + if (ab.dy > bc.dy) { + std::swap(ab, bc); + } + if (ab.dy > ca.dy) { + std::swap(ab, ca); + } + if (bc.dy > ca.dy) { + std::swap(bc, ca); + } // scan span! scan span! if (ab.dy) scanSpans(ca, ab, ymin, ymax, scanLine); @@ -85,12 +92,14 @@ namespace util { namespace { -std::vector tileCover(const Point& tl, - const Point& tr, - const Point& br, - const Point& bl, - const Point& c, - uint8_t z) { +std::vector tileCover( + const Point& tl, + const Point& tr, + const Point& br, + const Point& bl, + const Point& c, + uint8_t z +) { const int32_t tiles = 1 << z; struct ID { @@ -106,7 +115,7 @@ std::vector tileCover(const Point& tl, for (x = x0; x < x1; ++x) { const auto dx = x + 0.5 - c.x; const auto dy = y + 0.5 - c.y; - t.emplace_back(ID{ x, y, dx * dx + dy * dy }); + t.emplace_back(ID{x, y, dx * dx + dy * dy}); } } }; @@ -124,9 +133,9 @@ std::vector tileCover(const Point& tl, }); // Erase duplicate tile IDs (they typically occur at the common side of both triangles). - t.erase(std::unique(t.begin(), t.end(), [](const ID& a, const ID& b) { - return a.x == b.x && a.y == b.y; - }), t.end()); + t.erase( + std::unique(t.begin(), t.end(), [](const ID& a, const ID& b) { return a.x == b.x && a.y == b.y; }), t.end() + ); std::vector result; result.reserve(t.size()); @@ -147,7 +156,9 @@ int32_t coveringZoomLevel(double zoom, style::SourceType type, uint16_t size) { } } -std::vector tileCover(const TransformState& state, uint8_t z, const std::optional& overscaledZ) { +std::vector tileCover( + const TransformState& state, uint8_t z, const std::optional& overscaledZ +) { struct Node { AABB aabb; uint8_t zoom; @@ -179,12 +190,13 @@ std::vector tileCover(const TransformState& state, uint8_t z, const double radiusOfMaxLvlLodInTiles = 3; const auto newRootTile = [&](int16_t wrap) -> Node { - return {AABB({{wrap * numTiles, 0.0, 0.0}}, {{(wrap + 1) * numTiles, numTiles, 0.0}}), - uint8_t(0), - uint16_t(0), - uint16_t(0), - wrap, - false}; + return { + AABB({{wrap * numTiles, 0.0, 0.0}}, {{(wrap + 1) * numTiles, numTiles, 0.0}}), + uint8_t(0), + uint16_t(0), + uint16_t(0), + wrap, + false}; }; // Perform depth-first traversal on tile tree to find visible tiles @@ -256,8 +268,9 @@ std::vector tileCover(const TransformState& state, uint8_t z, } // Sort results by distance - std::sort( - result.begin(), result.end(), [](const ResultTile& a, const ResultTile& b) { return a.sqrDist < b.sqrDist; }); + std::sort(result.begin(), result.end(), [](const ResultTile& a, const ResultTile& b) { + return a.sqrDist < b.sqrDist; + }); std::vector ids; ids.reserve(result.size()); @@ -270,15 +283,14 @@ std::vector tileCover(const TransformState& state, uint8_t z, } std::vector tileCover(const LatLngBounds& bounds_, uint8_t z) { - if (bounds_.isEmpty() || - bounds_.south() > util::LATITUDE_MAX || - bounds_.north() < -util::LATITUDE_MAX) { + if (bounds_.isEmpty() || bounds_.south() > util::LATITUDE_MAX || bounds_.north() < -util::LATITUDE_MAX) { return {}; } LatLngBounds bounds = LatLngBounds::hull( - { std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west() }, - { std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east() }); + {std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west()}, + {std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east()} + ); return tileCover( Projection::project(bounds.northwest(), z), @@ -286,7 +298,8 @@ std::vector tileCover(const LatLngBounds& bounds_, uint8_t z) { Projection::project(bounds.southeast(), z), Projection::project(bounds.southwest(), z), Projection::project(bounds.center(), z), - z); + z + ); } std::vector tileCover(const Geometry& geometry, uint8_t z) { @@ -302,7 +315,7 @@ std::vector tileCover(const Geometry& geometry, uint8_t // Taken from https://github.com/mapbox/sphericalmercator#xyzbbox-zoom-tms_style-srs // Computes the projected tiles for the lower left and upper right points of the bounds // and uses that to compute the tile cover count -uint64_t tileCount(const LatLngBounds& bounds, uint8_t zoom){ +uint64_t tileCount(const LatLngBounds& bounds, uint8_t zoom) { if (zoom == 0) { return 1; } @@ -329,14 +342,13 @@ uint64_t tileCount(const Geometry& geometry, uint8_t z) { return tileCount; } -TileCover::TileCover(const LatLngBounds&bounds_, uint8_t z) { +TileCover::TileCover(const LatLngBounds& bounds_, uint8_t z) { LatLngBounds bounds = LatLngBounds::hull( - { std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west() }, - { std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east() }); + {std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west()}, + {std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east()} + ); - if (bounds.isEmpty() || - bounds.south() > util::LATITUDE_MAX || - bounds.north() < -util::LATITUDE_MAX) { + if (bounds.isEmpty() || bounds.south() > util::LATITUDE_MAX || bounds.north() < -util::LATITUDE_MAX) { bounds = LatLngBounds::world(); } @@ -345,13 +357,12 @@ TileCover::TileCover(const LatLngBounds&bounds_, uint8_t z) { auto se = Projection::project(bounds.southeast(), z); auto nw = Projection::project(bounds.northwest(), z); - Polygon p({ {sw, nw, ne, se, sw} }); + Polygon p({{sw, nw, ne, se, sw}}); impl = std::make_unique(z, p, false); } -TileCover::TileCover(const Geometry& geom, uint8_t z, bool project/* = true*/) - : impl( std::make_unique(z, geom, project)) { -} +TileCover::TileCover(const Geometry& geom, uint8_t z, bool project /* = true*/) + : impl(std::make_unique(z, geom, project)) {} TileCover::~TileCover() = default; diff --git a/src/mbgl/util/tile_cover.hpp b/src/mbgl/util/tile_cover.hpp index d3f8cbf04c8..9e2247d44fe 100644 --- a/src/mbgl/util/tile_cover.hpp +++ b/src/mbgl/util/tile_cover.hpp @@ -33,9 +33,9 @@ class TileCover { int32_t coveringZoomLevel(double z, style::SourceType type, uint16_t tileSize); -std::vector tileCover(const TransformState&, - uint8_t z, - const std::optional& overscaledZ = std::nullopt); +std::vector tileCover( + const TransformState&, uint8_t z, const std::optional& overscaledZ = std::nullopt +); std::vector tileCover(const LatLngBounds&, uint8_t z); std::vector tileCover(const Geometry&, uint8_t z); diff --git a/src/mbgl/util/tile_cover_impl.cpp b/src/mbgl/util/tile_cover_impl.cpp index 9cf2d109c87..30a7a03cbe3 100644 --- a/src/mbgl/util/tile_cover_impl.cpp +++ b/src/mbgl/util/tile_cover_impl.cpp @@ -24,18 +24,18 @@ void start_list_on_local_minimum(PointList& points) { auto pt = points.begin(); auto next_pt = std::next(pt); while (pt != points.end()) { - if ((pt->y <= prev_pt->y) && - (pt->y < next_pt->y)) { + if ((pt->y <= prev_pt->y) && (pt->y < next_pt->y)) { break; } prev_pt = pt; pt++; next_pt++; - if (next_pt == points.end()) { next_pt = std::next(points.begin()); } + if (next_pt == points.end()) { + next_pt = std::next(points.begin()); + } } - if (pt == points.end()) - return; - //Re-close linear rings with first_pt = last_pt + if (pt == points.end()) return; + // Re-close linear rings with first_pt = last_pt if (points.back() == points.front()) { points.pop_back(); } @@ -43,18 +43,23 @@ void start_list_on_local_minimum(PointList& points) { points.push_back(*points.begin()); } -//Create a bound towards a local maximum point, starting from pt. -// Traverse from current pt until the next pt changes y-direction, and copy -// all points from start to end (inclusive) into a Bound. +// Create a bound towards a local maximum point, starting from pt. +// Traverse from current pt until the next pt changes y-direction, and copy +// all points from start to end (inclusive) into a Bound. Bound create_bound_towards_maximum(PointList& points, PointList::iterator& pt) { - if (std::distance(pt, points.end()) < 2) { return {}; } + if (std::distance(pt, points.end()) < 2) { + return {}; + } const auto begin = pt; auto next_pt = std::next(begin); while (pt->y <= next_pt->y) { pt++; next_pt++; - if (next_pt == points.end()) { pt++; break; } + if (next_pt == points.end()) { + pt++; + break; + } } const auto pt_distance = std::distance(begin, next_pt); @@ -69,18 +74,23 @@ Bound create_bound_towards_maximum(PointList& points, PointList::iterator& pt) { return bnd; } -//Create a bound towards a local minimum point, starting from pt. -// Traverse from current pt until the next pt changes y-direction, and copy -// all points from start to end (inclusive) into a Bound. +// Create a bound towards a local minimum point, starting from pt. +// Traverse from current pt until the next pt changes y-direction, and copy +// all points from start to end (inclusive) into a Bound. Bound create_bound_towards_minimum(PointList& points, PointList::iterator& pt) { - if (std::distance(pt, points.end()) < 2) { return {}; } + if (std::distance(pt, points.end()) < 2) { + return {}; + } auto begin = pt; auto next_pt = std::next(begin); while (pt->y > next_pt->y) { pt++; next_pt++; - if (next_pt == points.end()) { pt++; break; } + if (next_pt == points.end()) { + pt++; + break; + } } const auto pt_distance = std::distance(begin, next_pt); @@ -89,7 +99,7 @@ Bound create_bound_towards_minimum(PointList& points, PointList::iterator& pt) { } Bound bnd; bnd.points.reserve(static_cast(std::distance(begin, next_pt))); - //For bounds that start at a max, reverse copy so that all bounds start at a min + // For bounds that start at a max, reverse copy so that all bounds start at a min std::reverse_copy(begin, next_pt, std::back_inserter(bnd.points)); bnd.winding = false; return bnd; @@ -101,8 +111,8 @@ Bound create_bound_towards_minimum(PointList& points, PointList::iterator& pt) { // of each Bound. void build_bounds_map(PointList& points, uint32_t maxTile, BoundsMap& et, bool closed = false) { if (points.size() < 2) return; - //While traversing closed rings, start the bounds at a local minimum. - // (For linestrings the starting point is always a local maxima/minima) + // While traversing closed rings, start the bounds at a local minimum. + // (For linestrings the starting point is always a local maxima/minima) if (closed) { start_list_on_local_minimum(points); } @@ -141,8 +151,8 @@ std::vector scan_row(uint32_t y, Bounds& activeBounds) { std::vector tile_range; tile_range.reserve(activeBounds.size()); - for(Bound& b: activeBounds) { - TileSpan xp = { INT_MAX, 0, b.winding }; + for (Bound& b : activeBounds) { + TileSpan xp = {INT_MAX, 0, b.winding}; double x; const auto numEdges = b.points.size() - 1; while (b.currentPoint < numEdges) { @@ -152,8 +162,8 @@ std::vector scan_row(uint32_t y, Bounds& activeBounds) { // If this edge ends beyond the current row, find the x-intercept where // it exits the row auto& p1 = b.points[b.currentPoint + 1]; - if (p1.y > y+1) { - x = b.interpolate(y+1); + if (p1.y > y + 1) { + x = b.interpolate(y + 1); update_span(xp, x); break; } else if (b.currentPoint == numEdges - 1) { @@ -169,15 +179,14 @@ std::vector scan_row(uint32_t y, Bounds& activeBounds) { // or there are no more edges auto bound = activeBounds.begin(); while (bound != activeBounds.end()) { - if ( bound->currentPoint == bound->points.size() - 1 && - bound->points[bound->currentPoint].y <= y+1) { + if (bound->currentPoint == bound->points.size() - 1 && bound->points[bound->currentPoint].y <= y + 1) { bound = activeBounds.erase(bound); } else { bound++; } } // Sort the X-extents of each crossing bound by x_min, x_max - std::sort(tile_range.begin(), tile_range.end(), [] (TileSpan& a, TileSpan& b) { + std::sort(tile_range.begin(), tile_range.end(), [](TileSpan& a, TileSpan& b) { return std::tie(a.xmin, a.xmax) < std::tie(b.xmin, b.xmax); }); @@ -187,15 +196,16 @@ std::vector scan_row(uint32_t y, Bounds& activeBounds) { struct BuildBoundsMap { int32_t zoom; bool project = false; - BuildBoundsMap(int32_t z, bool p): zoom(z), project(p) {} + BuildBoundsMap(int32_t z, bool p) + : zoom(z), + project(p) {} void buildTable(const std::vector>& points, BoundsMap& et, bool closed = false) const { PointList projectedPoints; if (project) { projectedPoints.reserve(points.size()); - for(const auto&p : points) { - projectedPoints.push_back( - Projection::project(LatLng{ p.y, p.x }, zoom)); + for (const auto& p : points) { + projectedPoints.push_back(Projection::project(LatLng{p.y, p.x}, zoom)); } } else { projectedPoints.insert(projectedPoints.end(), points.begin(), points.end()); @@ -204,15 +214,13 @@ struct BuildBoundsMap { } void buildPolygonTable(const Polygon& polygon, BoundsMap& et) const { - for(const auto&ring : polygon) { + for (const auto& ring : polygon) { buildTable(ring, et, true); } } - BoundsMap operator()(const EmptyGeometry&) const { - return {}; - } + BoundsMap operator()(const EmptyGeometry&) const { return {}; } - BoundsMap operator()(const Point&p) const { + BoundsMap operator()(const Point& p) const { Bound bnd; auto point = p; if (project) { @@ -228,7 +236,7 @@ struct BuildBoundsMap { BoundsMap operator()(const MultiPoint& points) const { BoundsMap et; - for (const Point& p: points) { + for (const Point& p : points) { Bound bnd; auto point = p; if (project) { @@ -250,7 +258,7 @@ struct BuildBoundsMap { BoundsMap operator()(const MultiLineString& lines) const { BoundsMap et; - for(const auto&line : lines) { + for (const auto& line : lines) { buildTable(line, et); } return et; @@ -264,19 +272,17 @@ struct BuildBoundsMap { BoundsMap operator()(const MultiPolygon& polygons) const { BoundsMap et; - for(const auto& polygon: polygons) { + for (const auto& polygon : polygons) { buildPolygonTable(polygon, et); } return et; } - BoundsMap operator()(const mapbox::geometry::geometry_collection&) const { - return {}; - } + BoundsMap operator()(const mapbox::geometry::geometry_collection&) const { return {}; } }; TileCover::Impl::Impl(int32_t z, const Geometry& geom, bool project) - : zoom(z) { + : zoom(z) { ToFeatureType toFeatureType; isClosed = apply_visitor(toFeatureType, geom) == FeatureType::Polygon; @@ -284,7 +290,7 @@ TileCover::Impl::Impl(int32_t z, const Geometry& geom, bool project) boundsMap = apply_visitor(toBoundsMap, geom); if (boundsMap.empty()) return; - //Iniitalize the active edge table, and current row span + // Iniitalize the active edge table, and current row span currentBounds = boundsMap.begin(); tileY = 0; nextRow(); @@ -302,16 +308,15 @@ void TileCover::Impl::nextRow() { // Update activeBounds for next row if (currentBounds != boundsMap.end()) { if (activeBounds.empty() && currentBounds->first > tileY) { - //For multi-geoms: use the next row with an edge table starting point + // For multi-geoms: use the next row with an edge table starting point tileY = currentBounds->first; } if (tileY == currentBounds->first) { - std::move(currentBounds->second.begin(), currentBounds->second.end(), - std::back_inserter(activeBounds)); + std::move(currentBounds->second.begin(), currentBounds->second.end(), std::back_inserter(activeBounds)); currentBounds++; } } - //Scan the active bounds and update currentRange with x_min, x_max pairs + // Scan the active bounds and update currentRange with x_min, x_max pairs auto xps = util::scan_row(tileY, activeBounds); if (xps.empty()) { return; @@ -335,9 +340,7 @@ void TileCover::Impl::nextRow() { } bool TileCover::Impl::hasNext() const { - return (!tileXSpans.empty() - && tileX < tileXSpans.front().second - && tileY < (1u << zoom)); + return (!tileXSpans.empty() && tileX < tileXSpans.front().second && tileY < (1u << zoom)); } std::optional TileCover::Impl::next() { diff --git a/src/mbgl/util/tile_cover_impl.hpp b/src/mbgl/util/tile_cover_impl.hpp index fdb7ce16b1e..2ad6f4f93c6 100644 --- a/src/mbgl/util/tile_cover_impl.hpp +++ b/src/mbgl/util/tile_cover_impl.hpp @@ -49,7 +49,7 @@ struct Bound { auto x = p0.x; if (dx == 0) { return x; - } else if (dy == 0){ + } else if (dy == 0) { return y <= p0.y ? p0.x : p1.x; } if (y < p0.y) return x; diff --git a/src/mbgl/util/tile_range.hpp b/src/mbgl/util/tile_range.hpp index bfd62f706b1..9f8da359631 100644 --- a/src/mbgl/util/tile_range.hpp +++ b/src/mbgl/util/tile_range.hpp @@ -21,21 +21,19 @@ class TileRange { auto swProj = Projection::project(bounds.southwest().wrapped(), maxZoom); auto ne = bounds.northeast(); - auto neProj = Projection::project(ne.longitude() > util::LONGITUDE_MAX ? ne.wrapped() : ne , maxZoom); + auto neProj = Projection::project(ne.longitude() > util::LONGITUDE_MAX ? ne.wrapped() : ne, maxZoom); const auto maxTile = std::pow(2.0, maxZoom); const auto minX = static_cast(std::floor(swProj.x)); const auto maxX = static_cast(std::floor(neProj.x)); - const auto minY = static_cast(util::clamp(std::floor(neProj.y), 0.0 , maxTile)); + const auto minY = static_cast(util::clamp(std::floor(neProj.y), 0.0, maxTile)); const auto maxY = static_cast(util::clamp(std::floor(swProj.y), 0.0, maxTile)); return {{{minX, minY}, {maxX, maxY}}, {minZoom, maxZoom}}; } // Compute the range of tiles covered by the bounds. - static TileRange fromLatLngBounds(const LatLngBounds& bounds, uint8_t z) { - return fromLatLngBounds(bounds, z, z); - } + static TileRange fromLatLngBounds(const LatLngBounds& bounds, uint8_t z) { return fromLatLngBounds(bounds, z, z); } bool contains(const CanonicalTileID& tileID) { if (tileID.z <= zoomRange.max && tileID.z >= zoomRange.min) { @@ -47,20 +45,18 @@ class TileRange { auto x1 = range.max.x >> dz; auto y0 = range.min.y >> dz; auto y1 = range.max.y >> dz; - return (range.min.x > range.max.x ? //For wrapped bounds - tileID.x >= x0 || tileID.x <= x1 : - tileID.x <= x1 && tileID.x >= x0) && - tileID.y <= y1 && - tileID.y >= y0; + return (range.min.x > range.max.x ? // For wrapped bounds + tileID.x >= x0 || tileID.x <= x1 + : tileID.x <= x1 && tileID.x >= x0) && + tileID.y <= y1 && tileID.y >= y0; } return false; } private: TileRange(Range> range_, Range z_) - : range(range_), - zoomRange(z_) { - } + : range(range_), + zoomRange(z_) {} }; } // namespace util diff --git a/src/mbgl/util/tile_server_options.cpp b/src/mbgl/util/tile_server_options.cpp index 5e5918a246f..c4ef4b3eb84 100644 --- a/src/mbgl/util/tile_server_options.cpp +++ b/src/mbgl/util/tile_server_options.cpp @@ -2,282 +2,288 @@ namespace mbgl { - class TileServerOptions::Impl { - public: - std::string baseURL; - std::optional versionPrefix; - std::string uriSchemeAlias; - - std::string sourceTemplate; - std::string sourceDomainName; - std::optional sourceVersionPrefix; - - std::string styleTemplate; - std::string styleDomainName; - std::optional styleVersionPrefix; - - std::string spritesTemplate; - std::string spritesDomainName; - std::optional spritesVersionPrefix; - - std::string glyphsTemplate; - std::string glyphsDomainName; - std::optional glyphsVersionPrefix; - - std::string tileTemplate; - std::string tileDomainName; - std::optional tileVersionPrefix; - - std::string apiKeyParameterName; - bool apiKeyRequired; - - std::vector defaultStyles; - std::string defaultStyle; - }; - - - TileServerOptions::TileServerOptions() : impl_(std::make_unique()) {} - TileServerOptions::~TileServerOptions() = default; - - // movable - TileServerOptions::TileServerOptions(TileServerOptions &&) noexcept = default; - TileServerOptions& TileServerOptions::operator=(TileServerOptions &&) noexcept = default; - - // copyable - TileServerOptions::TileServerOptions(const TileServerOptions& options) - : impl_(std::make_unique(*options.impl_)) {} - - TileServerOptions TileServerOptions::clone() const { - return TileServerOptions(*this); - } - - TileServerOptions& TileServerOptions::withBaseURL(std::string url) { - impl_->baseURL = std::move(url); - return *this; - } - - const std::string& TileServerOptions::baseURL() const { - return impl_->baseURL; - } - - TileServerOptions& TileServerOptions::withUriSchemeAlias(std::string alias) { - impl_->uriSchemeAlias = std::move(alias); - return *this; - } - - const std::string& TileServerOptions::uriSchemeAlias() const { - return impl_->uriSchemeAlias; - } - - TileServerOptions& TileServerOptions::withSourceTemplate(std::string sourceTemplate, std::string domainName, std::optional versionPrefix) { - impl_->sourceTemplate = std::move(sourceTemplate); - impl_->sourceVersionPrefix = std::move(versionPrefix); - impl_->sourceDomainName = std::move(domainName); - return *this; - } - - const std::string& TileServerOptions::sourceTemplate() const { - return impl_->sourceTemplate; - } - - const std::string& TileServerOptions::sourceDomainName() const { - return impl_->sourceDomainName; - } - - const std::optional& TileServerOptions::sourceVersionPrefix() const { - return impl_->sourceVersionPrefix; - } - - TileServerOptions& TileServerOptions::withStyleTemplate(std::string styleTemplate, std::string domainName, std::optional versionPrefix) { - impl_->styleTemplate = std::move(styleTemplate); - impl_->styleDomainName = std::move(domainName); - impl_->styleVersionPrefix = std::move(versionPrefix); - return *this; - } - - const std::string& TileServerOptions::styleTemplate() const { - return impl_->styleTemplate; - } - - const std::string& TileServerOptions::styleDomainName() const { - return impl_->styleDomainName; - } - - const std::optional& TileServerOptions::styleVersionPrefix() const { - return impl_->styleVersionPrefix; - } - - TileServerOptions& TileServerOptions::withSpritesTemplate(std::string spritesTemplate, std::string domainName, std::optional versionPrefix) { - impl_->spritesTemplate = std::move(spritesTemplate); - impl_->spritesDomainName = std::move(domainName); - impl_->spritesVersionPrefix = std::move(versionPrefix); - return *this; - } - - const std::string& TileServerOptions::spritesTemplate() const { - return impl_->spritesTemplate; - } - - const std::string& TileServerOptions::spritesDomainName() const { - return impl_->spritesDomainName; - } - - const std::optional& TileServerOptions::spritesVersionPrefix() const { - return impl_->spritesVersionPrefix; - } - - TileServerOptions& TileServerOptions::withGlyphsTemplate(std::string glyphsTemplate, std::string domainName, std::optional versionPrefix) { - impl_->glyphsTemplate = std::move(glyphsTemplate); - impl_->glyphsDomainName = std::move(domainName); - impl_->glyphsVersionPrefix = std::move(versionPrefix); - return *this; - } - - const std::string& TileServerOptions::glyphsTemplate() const { - return impl_->glyphsTemplate; - } - - const std::string& TileServerOptions::glyphsDomainName() const { - return impl_->glyphsDomainName; - } - - const std::optional& TileServerOptions::glyphsVersionPrefix() const { - return impl_->glyphsVersionPrefix; - } - - TileServerOptions& TileServerOptions::withTileTemplate(std::string tileTemplate, std::string domainName, std::optional versionPrefix) { - impl_->tileTemplate = std::move(tileTemplate); - impl_->tileDomainName = std::move(domainName); - impl_->tileVersionPrefix = std::move(versionPrefix); - return *this; - } - - const std::string& TileServerOptions::tileTemplate() const { - return impl_->tileTemplate; - } - - const std::string& TileServerOptions::tileDomainName() const { - return impl_->tileDomainName; - } - - const std::optional& TileServerOptions::tileVersionPrefix() const { - return impl_->tileVersionPrefix; - } - - TileServerOptions& TileServerOptions::withApiKeyParameterName(std::string apiKeyParameterName) { - impl_->apiKeyParameterName = std::move(apiKeyParameterName); - return *this; - } - - const std::string& TileServerOptions::apiKeyParameterName() const { - return impl_->apiKeyParameterName; - } - - TileServerOptions& TileServerOptions::setRequiresApiKey(bool apiKeyRequired) { - impl_->apiKeyRequired = apiKeyRequired; - return *this; - } - - bool TileServerOptions::requiresApiKey() const { - return impl_->apiKeyRequired; - } - - const std::vector TileServerOptions::defaultStyles() const { - return impl_->defaultStyles; - } - - TileServerOptions& TileServerOptions::withDefaultStyles(std::vector styles) { - impl_->defaultStyles = std::move(styles); - return *this; - } - - TileServerOptions& TileServerOptions::withDefaultStyle(std::string defaultStyle) { - impl_->defaultStyle = std::move(defaultStyle); - return *this; - } - - const std::string& TileServerOptions::defaultStyle() const { - return impl_->defaultStyle; - } - - TileServerOptions TileServerOptions::DefaultConfiguration() { - return MapLibreConfiguration(); - } - - TileServerOptions TileServerOptions::MapLibreConfiguration() { - std::vector styles { - // https://demotiles.maplibre.org/style.json - mbgl::util::DefaultStyle("maplibre://maps/style", "Basic", 1) - }; - - TileServerOptions options = TileServerOptions() - .withBaseURL("https://demotiles.maplibre.org") - .withUriSchemeAlias("maplibre") - .withApiKeyParameterName("") - .withSourceTemplate("/tiles/{domain}.json", "", {}) - .withStyleTemplate("{path}.json", "maps", {}) - .withSpritesTemplate("/{path}/sprite{scale}.{format}", "", {}) - .withGlyphsTemplate("/font/{fontstack}/{start}-{end}.pbf", "fonts", {}) - .withTileTemplate("/{path}", "tiles", {}) - .withDefaultStyles(styles) - .withDefaultStyle("Basic") - .setRequiresApiKey(false); - return options; - } - - // - - TileServerOptions TileServerOptions::MapboxConfiguration() { - std::vector styles { - mbgl::util::DefaultStyle("mapbox://styles/mapbox/streets-v11", "Streets", 11), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/outdoors-v11", "Outdoors", 11), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/light-v10", "Light", 10), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/dark-v10", "Dark", 10), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/satellite-v9", "Satellite", 9), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/satellite-streets-v11", - "Satellite Streets", 11) - }; - - TileServerOptions options = TileServerOptions() - .withBaseURL("https://api.mapbox.com") - .withUriSchemeAlias("mapbox") - .withApiKeyParameterName("access_token") - .withSourceTemplate("/{domain}.json", "", {"/v4"}) - .withStyleTemplate("/styles/v1{path}", "styles", {}) - .withSpritesTemplate("/styles/v1{directory}{filename}/sprite{extension}", "sprites", {}) - .withGlyphsTemplate("/fonts/v1{path}", "fonts", {}) - .withTileTemplate("{path}", "tiles", {"/v4"}) - .withDefaultStyles(styles) - .withDefaultStyle("Streets") - .setRequiresApiKey(true); - return options; - } - - TileServerOptions TileServerOptions::MapTilerConfiguration() { - - std::vector styles{ - mbgl::util::DefaultStyle("maptiler://maps/streets", "Streets", 1), - mbgl::util::DefaultStyle("maptiler://maps/outdoor", "Outdoor", 1), - mbgl::util::DefaultStyle("maptiler://maps/basic", "Basic", 1), - mbgl::util::DefaultStyle("maptiler://maps/bright", "Bright", 1), - mbgl::util::DefaultStyle("maptiler://maps/pastel", "Pastel", 1), - mbgl::util::DefaultStyle("maptiler://maps/hybrid", "Satellite Hybrid", 1), - mbgl::util::DefaultStyle("maptiler://maps/topo", "Satellite Topo", 1) - }; - - TileServerOptions options = TileServerOptions() - .withBaseURL("https://api.maptiler.com") - .withUriSchemeAlias("maptiler") - .withApiKeyParameterName("key") - .withSourceTemplate("/tiles{path}/tiles.json", "sources", {}) - .withStyleTemplate("/maps{path}/style.json", "maps", {}) - .withSpritesTemplate("/maps{path}", "sprites", {}) - .withGlyphsTemplate("/fonts{path}", "fonts", {}) - .withTileTemplate("{path}", "tiles", {}) - .withDefaultStyles(styles) - .withDefaultStyle("Streets") - .setRequiresApiKey(true); - return options; - } - -} // namespace mbgl +class TileServerOptions::Impl { +public: + std::string baseURL; + std::optional versionPrefix; + std::string uriSchemeAlias; + + std::string sourceTemplate; + std::string sourceDomainName; + std::optional sourceVersionPrefix; + + std::string styleTemplate; + std::string styleDomainName; + std::optional styleVersionPrefix; + + std::string spritesTemplate; + std::string spritesDomainName; + std::optional spritesVersionPrefix; + + std::string glyphsTemplate; + std::string glyphsDomainName; + std::optional glyphsVersionPrefix; + + std::string tileTemplate; + std::string tileDomainName; + std::optional tileVersionPrefix; + + std::string apiKeyParameterName; + bool apiKeyRequired; + + std::vector defaultStyles; + std::string defaultStyle; +}; + +TileServerOptions::TileServerOptions() + : impl_(std::make_unique()) {} +TileServerOptions::~TileServerOptions() = default; + +// movable +TileServerOptions::TileServerOptions(TileServerOptions&&) noexcept = default; +TileServerOptions& TileServerOptions::operator=(TileServerOptions&&) noexcept = default; + +// copyable +TileServerOptions::TileServerOptions(const TileServerOptions& options) + : impl_(std::make_unique(*options.impl_)) {} + +TileServerOptions TileServerOptions::clone() const { + return TileServerOptions(*this); +} + +TileServerOptions& TileServerOptions::withBaseURL(std::string url) { + impl_->baseURL = std::move(url); + return *this; +} + +const std::string& TileServerOptions::baseURL() const { + return impl_->baseURL; +} + +TileServerOptions& TileServerOptions::withUriSchemeAlias(std::string alias) { + impl_->uriSchemeAlias = std::move(alias); + return *this; +} + +const std::string& TileServerOptions::uriSchemeAlias() const { + return impl_->uriSchemeAlias; +} + +TileServerOptions& TileServerOptions::withSourceTemplate( + std::string sourceTemplate, std::string domainName, std::optional versionPrefix +) { + impl_->sourceTemplate = std::move(sourceTemplate); + impl_->sourceVersionPrefix = std::move(versionPrefix); + impl_->sourceDomainName = std::move(domainName); + return *this; +} + +const std::string& TileServerOptions::sourceTemplate() const { + return impl_->sourceTemplate; +} + +const std::string& TileServerOptions::sourceDomainName() const { + return impl_->sourceDomainName; +} + +const std::optional& TileServerOptions::sourceVersionPrefix() const { + return impl_->sourceVersionPrefix; +} + +TileServerOptions& TileServerOptions::withStyleTemplate( + std::string styleTemplate, std::string domainName, std::optional versionPrefix +) { + impl_->styleTemplate = std::move(styleTemplate); + impl_->styleDomainName = std::move(domainName); + impl_->styleVersionPrefix = std::move(versionPrefix); + return *this; +} + +const std::string& TileServerOptions::styleTemplate() const { + return impl_->styleTemplate; +} + +const std::string& TileServerOptions::styleDomainName() const { + return impl_->styleDomainName; +} + +const std::optional& TileServerOptions::styleVersionPrefix() const { + return impl_->styleVersionPrefix; +} + +TileServerOptions& TileServerOptions::withSpritesTemplate( + std::string spritesTemplate, std::string domainName, std::optional versionPrefix +) { + impl_->spritesTemplate = std::move(spritesTemplate); + impl_->spritesDomainName = std::move(domainName); + impl_->spritesVersionPrefix = std::move(versionPrefix); + return *this; +} + +const std::string& TileServerOptions::spritesTemplate() const { + return impl_->spritesTemplate; +} + +const std::string& TileServerOptions::spritesDomainName() const { + return impl_->spritesDomainName; +} + +const std::optional& TileServerOptions::spritesVersionPrefix() const { + return impl_->spritesVersionPrefix; +} + +TileServerOptions& TileServerOptions::withGlyphsTemplate( + std::string glyphsTemplate, std::string domainName, std::optional versionPrefix +) { + impl_->glyphsTemplate = std::move(glyphsTemplate); + impl_->glyphsDomainName = std::move(domainName); + impl_->glyphsVersionPrefix = std::move(versionPrefix); + return *this; +} + +const std::string& TileServerOptions::glyphsTemplate() const { + return impl_->glyphsTemplate; +} + +const std::string& TileServerOptions::glyphsDomainName() const { + return impl_->glyphsDomainName; +} + +const std::optional& TileServerOptions::glyphsVersionPrefix() const { + return impl_->glyphsVersionPrefix; +} + +TileServerOptions& TileServerOptions::withTileTemplate( + std::string tileTemplate, std::string domainName, std::optional versionPrefix +) { + impl_->tileTemplate = std::move(tileTemplate); + impl_->tileDomainName = std::move(domainName); + impl_->tileVersionPrefix = std::move(versionPrefix); + return *this; +} + +const std::string& TileServerOptions::tileTemplate() const { + return impl_->tileTemplate; +} + +const std::string& TileServerOptions::tileDomainName() const { + return impl_->tileDomainName; +} + +const std::optional& TileServerOptions::tileVersionPrefix() const { + return impl_->tileVersionPrefix; +} + +TileServerOptions& TileServerOptions::withApiKeyParameterName(std::string apiKeyParameterName) { + impl_->apiKeyParameterName = std::move(apiKeyParameterName); + return *this; +} + +const std::string& TileServerOptions::apiKeyParameterName() const { + return impl_->apiKeyParameterName; +} + +TileServerOptions& TileServerOptions::setRequiresApiKey(bool apiKeyRequired) { + impl_->apiKeyRequired = apiKeyRequired; + return *this; +} + +bool TileServerOptions::requiresApiKey() const { + return impl_->apiKeyRequired; +} + +const std::vector TileServerOptions::defaultStyles() const { + return impl_->defaultStyles; +} + +TileServerOptions& TileServerOptions::withDefaultStyles(std::vector styles) { + impl_->defaultStyles = std::move(styles); + return *this; +} + +TileServerOptions& TileServerOptions::withDefaultStyle(std::string defaultStyle) { + impl_->defaultStyle = std::move(defaultStyle); + return *this; +} + +const std::string& TileServerOptions::defaultStyle() const { + return impl_->defaultStyle; +} + +TileServerOptions TileServerOptions::DefaultConfiguration() { + return MapLibreConfiguration(); +} + +TileServerOptions TileServerOptions::MapLibreConfiguration() { + std::vector styles{// https://demotiles.maplibre.org/style.json + mbgl::util::DefaultStyle("maplibre://maps/style", "Basic", 1)}; + + TileServerOptions options = TileServerOptions() + .withBaseURL("https://demotiles.maplibre.org") + .withUriSchemeAlias("maplibre") + .withApiKeyParameterName("") + .withSourceTemplate("/tiles/{domain}.json", "", {}) + .withStyleTemplate("{path}.json", "maps", {}) + .withSpritesTemplate("/{path}/sprite{scale}.{format}", "", {}) + .withGlyphsTemplate("/font/{fontstack}/{start}-{end}.pbf", "fonts", {}) + .withTileTemplate("/{path}", "tiles", {}) + .withDefaultStyles(styles) + .withDefaultStyle("Basic") + .setRequiresApiKey(false); + return options; +} + +// + +TileServerOptions TileServerOptions::MapboxConfiguration() { + std::vector styles{ + mbgl::util::DefaultStyle("mapbox://styles/mapbox/streets-v11", "Streets", 11), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/outdoors-v11", "Outdoors", 11), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/light-v10", "Light", 10), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/dark-v10", "Dark", 10), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/satellite-v9", "Satellite", 9), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/satellite-streets-v11", "Satellite Streets", 11)}; + + TileServerOptions options = TileServerOptions() + .withBaseURL("https://api.mapbox.com") + .withUriSchemeAlias("mapbox") + .withApiKeyParameterName("access_token") + .withSourceTemplate("/{domain}.json", "", {"/v4"}) + .withStyleTemplate("/styles/v1{path}", "styles", {}) + .withSpritesTemplate( + "/styles/v1{directory}{filename}/sprite{extension}", "sprites", {} + ) + .withGlyphsTemplate("/fonts/v1{path}", "fonts", {}) + .withTileTemplate("{path}", "tiles", {"/v4"}) + .withDefaultStyles(styles) + .withDefaultStyle("Streets") + .setRequiresApiKey(true); + return options; +} + +TileServerOptions TileServerOptions::MapTilerConfiguration() { + std::vector styles{ + mbgl::util::DefaultStyle("maptiler://maps/streets", "Streets", 1), + mbgl::util::DefaultStyle("maptiler://maps/outdoor", "Outdoor", 1), + mbgl::util::DefaultStyle("maptiler://maps/basic", "Basic", 1), + mbgl::util::DefaultStyle("maptiler://maps/bright", "Bright", 1), + mbgl::util::DefaultStyle("maptiler://maps/pastel", "Pastel", 1), + mbgl::util::DefaultStyle("maptiler://maps/hybrid", "Satellite Hybrid", 1), + mbgl::util::DefaultStyle("maptiler://maps/topo", "Satellite Topo", 1)}; + + TileServerOptions options = TileServerOptions() + .withBaseURL("https://api.maptiler.com") + .withUriSchemeAlias("maptiler") + .withApiKeyParameterName("key") + .withSourceTemplate("/tiles{path}/tiles.json", "sources", {}) + .withStyleTemplate("/maps{path}/style.json", "maps", {}) + .withSpritesTemplate("/maps{path}", "sprites", {}) + .withGlyphsTemplate("/fonts{path}", "fonts", {}) + .withTileTemplate("{path}", "tiles", {}) + .withDefaultStyles(styles) + .withDefaultStyle("Streets") + .setRequiresApiKey(true); + return options; +} + +} // namespace mbgl diff --git a/src/mbgl/util/tiny_sdf.cpp b/src/mbgl/util/tiny_sdf.cpp index 3a7ef999861..7070ed2e5ea 100644 --- a/src/mbgl/util/tiny_sdf.cpp +++ b/src/mbgl/util/tiny_sdf.cpp @@ -12,11 +12,9 @@ namespace tinysdf { static const double INF = 1e20; // 1D squared distance transform -void edt1d(std::vector& f, - std::vector& d, - std::vector& v, - std::vector& z, - uint32_t n) { +void edt1d( + std::vector& f, std::vector& d, std::vector& v, std::vector& z, uint32_t n +) { v[0] = 0; z[0] = -INF; z[1] = +INF; @@ -39,15 +37,16 @@ void edt1d(std::vector& f, } } - // 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/dt/ -void edt(std::vector& data, - uint32_t width, - uint32_t height, - std::vector& f, - std::vector& d, - std::vector& v, - std::vector& z) { +void edt( + std::vector& data, + uint32_t width, + uint32_t height, + std::vector& f, + std::vector& d, + std::vector& v, + std::vector& z +) { for (uint32_t x = 0; x < width; x++) { for (uint32_t y = 0; y < height; y++) { f[y] = data[y * width + x]; @@ -73,9 +72,9 @@ void edt(std::vector& data, AlphaImage transformRasterToSDF(const AlphaImage& rasterInput, double radius, double cutoff) { uint32_t size = rasterInput.size.width * rasterInput.size.height; uint32_t maxDimension = std::max(rasterInput.size.width, rasterInput.size.height); - + AlphaImage sdf(rasterInput.size); - + // temporary arrays for the distance transform std::vector gridOuter(size); std::vector gridInner(size); @@ -83,7 +82,7 @@ AlphaImage transformRasterToSDF(const AlphaImage& rasterInput, double radius, do std::vector d(maxDimension); std::vector z(maxDimension + 1); std::vector v(maxDimension); - + for (uint32_t i = 0; i < size; i++) { double a = static_cast(rasterInput.data[i]) / 255; // alpha value gridOuter[i] = a == 1.0 ? 0.0 : a == 0.0 ? tinysdf::INF : std::pow(std::max(0.0, 0.5 - a), 2.0); @@ -95,7 +94,8 @@ AlphaImage transformRasterToSDF(const AlphaImage& rasterInput, double radius, do for (uint32_t i = 0; i < size; i++) { double distance = gridOuter[i] - gridInner[i]; - sdf.data[i] = static_cast(std::max(0l, std::min(255l, ::lround(255.0 - 255.0 * (distance / radius + cutoff))))); + sdf.data[i] = + static_cast(std::max(0l, std::min(255l, ::lround(255.0 - 255.0 * (distance / radius + cutoff))))); } return sdf; diff --git a/src/mbgl/util/tiny_sdf.hpp b/src/mbgl/util/tiny_sdf.hpp index 33c9280cbdf..43a6df2b227 100644 --- a/src/mbgl/util/tiny_sdf.hpp +++ b/src/mbgl/util/tiny_sdf.hpp @@ -10,7 +10,7 @@ namespace util { Felzenszwalb/Huttenlocher distance transform paper (https://cs.brown.edu/~pff/papers/dt-final.pdf). Note there exists an alternative C++ implementation from the paper’s authors at https://cs.brown.edu/~pff/dt/, which this implementation is not based on. - + Takes an alpha channel raster input and transforms it into an alpha channel Signed Distance Field (SDF) output of the same dimensions. */ diff --git a/src/mbgl/util/token.hpp b/src/mbgl/util/token.hpp index f2fc334cc48..05e295ad077 100644 --- a/src/mbgl/util/token.hpp +++ b/src/mbgl/util/token.hpp @@ -24,9 +24,10 @@ std::string replaceTokens(const std::string &source, const Lookup &lookup) { result.append(pos, brace); pos = brace; if (pos != end) { - for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++); + for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++) + ; if (brace != end && *brace == '}') { - std::string key { pos + 1, brace }; + std::string key{pos + 1, brace}; if (std::optional replacement = lookup(key)) { result.append(*replacement); } else { diff --git a/src/mbgl/util/url.cpp b/src/mbgl/util/url.cpp index 9dbefaebcb8..8d29374cddd 100644 --- a/src/mbgl/util/url.cpp +++ b/src/mbgl/util/url.cpp @@ -73,15 +73,15 @@ URL::URL(const std::string& str) const auto hashPos = str.find('#'); const auto queryPos = str.find('?'); if (queryPos == std::string::npos || hashPos < queryPos) { - return { hashPos != std::string::npos ? hashPos : str.size(), 0 }; + return {hashPos != std::string::npos ? hashPos : str.size(), 0}; } - return { queryPos, (hashPos != std::string::npos ? hashPos : str.size()) - queryPos }; + return {queryPos, (hashPos != std::string::npos ? hashPos : str.size()) - queryPos}; }()), scheme([&]() -> Segment { - if (str.empty() || !isAlphaCharacter(str.front())) return { 0, 0 }; + if (str.empty() || !isAlphaCharacter(str.front())) return {0, 0}; size_t schemeEnd = 0; while (schemeEnd < query.first && isSchemeCharacter(str[schemeEnd])) ++schemeEnd; - return { 0, str[schemeEnd] == ':' ? schemeEnd : 0 }; + return {0, str[schemeEnd] == ':' ? schemeEnd : 0}; }()), domain([&]() -> Segment { auto domainPos = scheme.first + scheme.second; @@ -90,7 +90,7 @@ URL::URL(const std::string& str) } const bool isData = str.compare(scheme.first, scheme.second, "data") == 0; const auto endPos = str.find(isData ? ',' : '/', domainPos); - return { domainPos, std::min(query.first, endPos) - domainPos }; + return {domainPos, std::min(query.first, endPos) - domainPos}; }()), path([&]() -> Segment { auto pathPos = domain.first + domain.second; @@ -99,16 +99,15 @@ URL::URL(const std::string& str) // Skip comma pathPos++; } - return { pathPos, query.first - pathPos }; - }()) { -} + return {pathPos, query.first - pathPos}; + }()) {} Path::Path(const std::string& str, const size_t pos, const size_t count) : directory([&]() -> Segment { // Finds the string between pos and the first /, if it exists const auto endPos = count == std::string::npos ? str.size() : pos + count; const auto slashPos = str.rfind('/', endPos); - return { pos, slashPos == std::string::npos || slashPos < pos ? 0 : slashPos + 1 - pos }; + return {pos, slashPos == std::string::npos || slashPos < pos ? 0 : slashPos + 1 - pos}; }()), extension([&]() -> Segment { auto dotPos = str.rfind('.', pos + count); @@ -116,20 +115,18 @@ Path::Path(const std::string& str, const size_t pos, const size_t count) // Count a preceding @2x to the file extension as well. const char* factor = "@2x"; const size_t factorLen = strlen(factor); - if (dotPos >= factorLen && dotPos < endPos && - str.compare(dotPos - factorLen, factorLen, factor) == 0) { + if (dotPos >= factorLen && dotPos < endPos && str.compare(dotPos - factorLen, factorLen, factor) == 0) { dotPos -= factorLen; } if (dotPos == std::string::npos || dotPos < directory.first + directory.second) { - return { endPos, 0 }; + return {endPos, 0}; } - return { dotPos, endPos - dotPos }; + return {dotPos, endPos - dotPos}; }()), filename([&]() -> Segment { const auto filePos = directory.first + directory.second; - return { filePos, extension.first - filePos }; - }()) { -} + return {filePos, extension.first - filePos}; + }()) {} std::string transformURL(const std::string& tpl, const std::string& str, const URL& url) { auto result = util::replaceTokens(tpl, [&](const std::string& token) -> std::optional { diff --git a/src/mbgl/util/work_request.cpp b/src/mbgl/util/work_request.cpp index eb84df7bf2c..635e480fbf8 100644 --- a/src/mbgl/util/work_request.cpp +++ b/src/mbgl/util/work_request.cpp @@ -6,7 +6,8 @@ namespace mbgl { -WorkRequest::WorkRequest(Task task_) : task(std::move(task_)) { +WorkRequest::WorkRequest(Task task_) + : task(std::move(task_)) { assert(task); } diff --git a/test/actor/actor.test.cpp b/test/actor/actor.test.cpp index 5b395074ed0..6672185d1e9 100644 --- a/test/actor/actor.test.cpp +++ b/test/actor/actor.test.cpp @@ -26,7 +26,8 @@ TEST(Actor, Construction) { TEST(Actor, Destruction) { struct TestActor { - TestActor(ActorRef, bool& destructed_) : destructed(destructed_){}; + TestActor(ActorRef, bool& destructed_) + : destructed(destructed_){}; ~TestActor() { destructed = true; } bool& destructed; @@ -47,7 +48,9 @@ TEST(Actor, DestructionBlocksOnReceive) { std::atomic waited; TestActor(ActorRef, std::promise promise_, std::future future_) - : promise(std::move(promise_)), future(std::move(future_)), waited(false) {} + : promise(std::move(promise_)), + future(std::move(future_)), + waited(false) {} ~TestActor() { EXPECT_TRUE(waited.load()); } @@ -84,12 +87,9 @@ TEST(Actor, DestructionBlocksOnSend) { TestScheduler(std::promise promise_, std::future future_) : promise(std::move(promise_)), future(std::move(future_)), - waited(false) { - } + waited(false) {} - ~TestScheduler() override { - EXPECT_TRUE(waited.load()); - } + ~TestScheduler() override { EXPECT_TRUE(waited.load()); } void schedule(std::function) final { promise.set_value(); @@ -133,9 +133,7 @@ TEST(Actor, DestructionAllowedInReceiveOnSameThread) { struct TestActor { TestActor(ActorRef){}; - void callMeBack(std::function callback) { - callback(); - } + void callMeBack(std::function callback) { callback(); } }; std::promise callbackFiredPromise; @@ -161,9 +159,7 @@ TEST(Actor, SelfDestructionDoesntCrashWaitingReceivingThreads) { struct TestActor { TestActor(ActorRef){}; - void callMeBack(std::function callback) { - callback(); - } + void callMeBack(std::function callback) { callback(); } }; std::promise actorClosedPromise; @@ -171,7 +167,7 @@ TEST(Actor, SelfDestructionDoesntCrashWaitingReceivingThreads) { auto closingActor = std::make_unique>(Scheduler::GetBackground()); auto waitingActor = std::make_unique>(Scheduler::GetBackground()); - std::atomic waitingMessageProcessed {false}; + std::atomic waitingMessageProcessed{false}; // Callback (triggered while mutex is locked in Mailbox::receive()) closingActor->self().invoke(&TestActor::callMeBack, [&]() { @@ -187,10 +183,7 @@ TEST(Actor, SelfDestructionDoesntCrashWaitingReceivingThreads) { }); // Wait for the message to be queued - ASSERT_EQ( - messageQueuedPromise.get_future().wait_for(std::chrono::seconds(1)), - std::future_status::ready - ); + ASSERT_EQ(messageQueuedPromise.get_future().wait_for(std::chrono::seconds(1)), std::future_status::ready); // Destroy the Actor/Mailbox in the same thread closingActor.reset(); @@ -209,16 +202,15 @@ TEST(Actor, OrderedMailbox) { int last = 0; std::promise promise; - TestActor(ActorRef, std::promise promise_) : promise(std::move(promise_)) {} + TestActor(ActorRef, std::promise promise_) + : promise(std::move(promise_)) {} void receive(int i) { EXPECT_EQ(i, last + 1); last = i; } - void end() { - promise.set_value(); - } + void end() { promise.set_value(); } }; std::promise endedPromise; @@ -240,7 +232,8 @@ TEST(Actor, NonConcurrentMailbox) { int last = 0; std::promise promise; - TestActor(ActorRef, std::promise promise_) : promise(std::move(promise_)) {} + TestActor(ActorRef, std::promise promise_) + : promise(std::move(promise_)) {} void receive(int i) { EXPECT_EQ(i, last + 1); @@ -248,9 +241,7 @@ TEST(Actor, NonConcurrentMailbox) { std::this_thread::sleep_for(1ms); } - void end() { - promise.set_value(); - } + void end() { promise.set_value(); } }; std::promise endedPromise; @@ -271,9 +262,7 @@ TEST(Actor, Ask) { struct TestActor { TestActor(ActorRef) {} - int doubleIt(int i) { - return i * 2; - } + int doubleIt(int i) { return i * 2; } }; Actor test(Scheduler::GetBackground()); @@ -293,11 +282,10 @@ TEST(Actor, AskVoid) { struct TestActor { bool& executed; - TestActor(bool& executed_) : executed(executed_) {} + TestActor(bool& executed_) + : executed(executed_) {} - void doIt() { - executed = true; - } + void doIt() { executed = true; } }; bool executed = false; @@ -315,18 +303,14 @@ TEST(Actor, NoSelfActorRef) { Actor trivial(Scheduler::GetBackground()); - // With arguments struct WithArguments { std::promise promise; WithArguments(std::promise promise_) - : promise(std::move(promise_)) { - } + : promise(std::move(promise_)) {} - void receive() { - promise.set_value(); - } + void receive() { promise.set_value(); } }; std::promise promise; @@ -343,17 +327,14 @@ TEST(Actor, TwoPhaseConstruction) { // for the target thread to be up and running. struct TestActor { - TestActor(ActorRef, std::shared_ptr destroyed_) : destroyed(std::move(destroyed_)){}; + TestActor(ActorRef, std::shared_ptr destroyed_) + : destroyed(std::move(destroyed_)){}; ~TestActor() { *destroyed = true; } - void callMe(std::promise p) { - p.set_value(); - } + void callMe(std::promise p) { p.set_value(); } - void stop() { - util::RunLoop::Get()->stop(); - } + void stop() { util::RunLoop::Get()->stop(); } std::shared_ptr destroyed; }; @@ -368,10 +349,7 @@ TEST(Actor, TwoPhaseConstruction) { parent.self().invoke(&TestActor::callMe, std::move(queueExecuted)); parent.self().invoke(&TestActor::stop); - auto thread = std::thread([ - capturedArgs = std::make_tuple(destroyed), - &parent - ] () mutable { + auto thread = std::thread([capturedArgs = std::make_tuple(destroyed), &parent]() mutable { util::RunLoop loop(util::RunLoop::Type::New); EstablishedActor test(loop, parent, capturedArgs); loop.run(); @@ -383,5 +361,3 @@ TEST(Actor, TwoPhaseConstruction) { EXPECT_TRUE(*destroyed); } - - diff --git a/test/actor/actor_ref.test.cpp b/test/actor/actor_ref.test.cpp index 59917060317..5ef2adaf457 100644 --- a/test/actor/actor_ref.test.cpp +++ b/test/actor/actor_ref.test.cpp @@ -14,13 +14,12 @@ TEST(ActorRef, CanOutliveActor) { struct TestActorRef { bool& died; - TestActorRef(ActorRef, bool& died_) : died(died_) {} + TestActorRef(ActorRef, bool& died_) + : died(died_) {} ~TestActorRef() { died = true; } - void receive() { - FAIL(); - } + void receive() { FAIL(); } }; bool died = false; @@ -39,13 +38,9 @@ TEST(ActorRef, Ask) { struct TestActorRef { TestActorRef(ActorRef) {} - int gimme() { - return 20; - } + int gimme() { return 20; } - int echo(int i) { - return i; - } + int echo(int i) { return i; } }; Actor actor(Scheduler::GetBackground()); @@ -61,11 +56,10 @@ TEST(ActorRef, AskVoid) { struct TestActorRef { bool& executed; - TestActorRef(bool& executed_) : executed(executed_) {} + TestActorRef(bool& executed_) + : executed(executed_) {} - void doIt() { - executed = true; - } + void doIt() { executed = true; } }; bool executed = false; @@ -83,13 +77,12 @@ TEST(ActorRef, AskOnDestroyedActor) { struct TestActorRef { bool& died; - TestActorRef(ActorRef, bool& died_) : died(died_) {} + TestActorRef(ActorRef, bool& died_) + : died(died_) {} ~TestActorRef() { died = true; } - int receive() { - return 1; - } + int receive() { return 1; } }; bool died = false; diff --git a/test/algorithm/update_renderables.test.cpp b/test/algorithm/update_renderables.test.cpp index bca04ab6614..4ed69a8903a 100644 --- a/test/algorithm/update_renderables.test.cpp +++ b/test/algorithm/update_renderables.test.cpp @@ -17,29 +17,24 @@ struct GetTileDataAction { const OverscaledTileID tileID; const LookupResult found; - bool operator==(const GetTileDataAction& rhs) const { - return tileID == rhs.tileID && found == rhs.found; - } + bool operator==(const GetTileDataAction& rhs) const { return tileID == rhs.tileID && found == rhs.found; } }; std::ostream& operator<<(std::ostream& os, const GetTileDataAction& action) { return os << "GetTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) << ", { " << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " - << action.tileID.canonical.y << " } }, " - << (action.found == Found ? "Found" : "NotFound") << " }\n"; + << action.tileID.canonical.y << " } }, " << (action.found == Found ? "Found" : "NotFound") << " }\n"; } struct CreateTileDataAction { const OverscaledTileID tileID; - bool operator==(const CreateTileDataAction& rhs) const { - return tileID == rhs.tileID; - } + bool operator==(const CreateTileDataAction& rhs) const { return tileID == rhs.tileID; } }; std::ostream& operator<<(std::ostream& os, const CreateTileDataAction& action) { - return os << "CreateTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) << ", { " - << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " + return os << "CreateTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) + << ", { " << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " << action.tileID.canonical.y << " } } }\n"; } @@ -53,8 +48,8 @@ struct RetainTileDataAction { }; std::ostream& operator<<(std::ostream& os, const RetainTileDataAction& action) { - return os << "RetainTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) << ", { " - << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " + return os << "RetainTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) + << ", { " << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " << action.tileID.canonical.y << " } }, " << (action.necessity == TileNecessity::Required ? "Required" : "Optional") << " }\n"; } @@ -63,31 +58,25 @@ struct RenderTileAction { const UnwrappedTileID tileID; const MockTileData& tileData; - bool operator==(const RenderTileAction& rhs) const { - return tileID == rhs.tileID && &tileData == &rhs.tileData; - } + bool operator==(const RenderTileAction& rhs) const { return tileID == rhs.tileID && &tileData == &rhs.tileData; } }; std::ostream& operator<<(std::ostream& os, const RenderTileAction& action) { - const int64_t x = - (1ul << action.tileID.canonical.z) * action.tileID.wrap + action.tileID.canonical.x; + const int64_t x = (1ul << action.tileID.canonical.z) * action.tileID.wrap + action.tileID.canonical.x; return os << "RenderTileAction{ { " << int(action.tileID.canonical.z) << ", " << x << ", " - << action.tileID.canonical.y << " }, *tile_" - << int(action.tileData.tileID.overscaledZ) << "_" - << int(action.tileData.tileID.canonical.z) << "_" - << action.tileData.tileID.canonical.x << "_" << action.tileData.tileID.canonical.y - << " }\n"; + << action.tileID.canonical.y << " }, *tile_" << int(action.tileData.tileID.overscaledZ) << "_" + << int(action.tileData.tileID.canonical.z) << "_" << action.tileData.tileID.canonical.x << "_" + << action.tileData.tileID.canonical.y << " }\n"; } -using ActionLogEntry = - variant; +using ActionLogEntry = variant; using ActionLog = std::vector; template auto getTileDataFn(ActionLog& log, const T& dataTiles) { return [&](const auto& id) { auto it = dataTiles.find(id); - log.emplace_back(GetTileDataAction{ id, it != dataTiles.end() ? Found : NotFound }); + log.emplace_back(GetTileDataAction{id, it != dataTiles.end() ? Found : NotFound}); return (it != dataTiles.end()) ? it->second.get() : nullptr; }; } @@ -95,7 +84,7 @@ auto getTileDataFn(ActionLog& log, const T& dataTiles) { template auto createTileDataFn(ActionLog& log, T& dataTiles) { return [&](const auto& id) { - log.emplace_back(CreateTileDataAction{ id }); + log.emplace_back(CreateTileDataAction{id}); return (dataTiles[id] = std::make_unique(id)).get(); }; } @@ -103,14 +92,14 @@ auto createTileDataFn(ActionLog& log, T& dataTiles) { template auto retainTileDataFn(ActionLog& log) { return [&](auto& tileData, TileNecessity necessity) { - log.emplace_back(RetainTileDataAction{ tileData.tileID, necessity }); + log.emplace_back(RetainTileDataAction{tileData.tileID, necessity}); }; } template auto renderTileFn(ActionLog& log) { return [&](const auto& id, auto& tileData) { - log.emplace_back(RenderTileAction{ id, tileData }); + log.emplace_back(RenderTileAction{id, tileData}); }; } @@ -125,137 +114,158 @@ TEST(UpdateRenderables, SingleTile) { source.idealTiles.emplace(OverscaledTileID{1, 1, 1}); // Make sure that we're getting the tile back. - auto tile_1_1_1_1 = source.createTileData(OverscaledTileID{ 1, 1, 1 }); + auto tile_1_1_1_1 = source.createTileData(OverscaledTileID{1, 1, 1}); tile_1_1_1_1->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // found ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render ideal tile - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // found ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render ideal tile + }), + log + ); // Check a repeated render with the same data. log.clear(); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // found ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render ideal tile - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // found ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render ideal tile + }), + log + ); // Insert a tile we don't have data for. log.clear(); source.idealTiles.emplace(OverscaledTileID{1, 0, 1}); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 1, 0, { 1, 0, 1 } } }, // create ideal tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 2 } }, NotFound }, // four child tiles - GetTileDataAction{ { 2, 0, { 2, 0, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 3 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // parent tile - - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // found ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render found tile - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 1}}, NotFound}, // missing ideal tile + CreateTileDataAction{{1, 0, {1, 0, 1}}}, // create ideal tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 2}}, NotFound}, // four child tiles + GetTileDataAction{{2, 0, {2, 0, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 3}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // parent tile + + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // found ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render found tile + }), + log + ); // Mark the created tile as having the optional request tried. log.clear(); - source.dataTiles[{ 1, 0, { 1, 0, 1 } }]->triedOptional = true; + source.dataTiles[{1, 0, {1, 0, 1}}]->triedOptional = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // missing ideal tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 2 } }, NotFound }, // four child tiles - GetTileDataAction{ { 2, 0, { 2, 0, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 3 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // parent tile - CreateTileDataAction{ { 0, 0, { 0, 0, 0 } } }, // load parent tile - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // found ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render found tile - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // missing ideal tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 2}}, NotFound}, // four child tiles + GetTileDataAction{{2, 0, {2, 0, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 3}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // parent tile + CreateTileDataAction{{0, 0, {0, 0, 0}}}, // load parent tile + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // found ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render found tile + }), + log + ); // Now insert the missing tile and check that we're rendering it. log.clear(); - auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{ 1, 0, 1 }); + auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{1, 0, 1}); tile_1_1_0_1->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // newly added tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // render ideal tile - - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render found tile - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // newly added tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // render ideal tile + + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render found tile + }), + log + ); // Insert another tile, and another bucket that has a different name and check that we're not // using it. log.clear(); source.idealTiles.emplace(OverscaledTileID{1, 0, 0}); - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, 0 }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, 0}); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // found tile, not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // four child tiles - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - // optional parent tile was already created before, but is not renderable - - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // render ideal tile - - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render ideal tile - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // found tile, not ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // four child tiles + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + // optional parent tile was already created before, but is not renderable + + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // render ideal tile + + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render ideal tile + }), + log + ); // Then, add the bucket and check that it's getting used. log.clear(); tile_1_1_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // found tile, now ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, // - - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // - - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // found tile, now ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, // + + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // + + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // + }), + log + ); } TEST(UpdateRenderables, UseParentTile) { @@ -271,37 +281,40 @@ TEST(UpdateRenderables, UseParentTile) { source.idealTiles.emplace(OverscaledTileID{1, 1, 1}); // Make sure that we're getting the tile back. - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 1, 0, { 1, 0, 1 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 2 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 0, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 3 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent found! - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // render parent - GetTileDataAction{ { 1, 0, { 1, 1, 0 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 1, 0, { 1, 1, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 2, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 2, 1 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 3, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 3, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, NotFound }, // missing tile - CreateTileDataAction{ { 1, 0, { 1, 1, 1 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 2, 2 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 2, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 3, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 3, 3 } }, NotFound }, // ... - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 1}}, NotFound}, // missing ideal tile + CreateTileDataAction{{1, 0, {1, 0, 1}}}, // + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 2}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 0, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 3}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent found! + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // render parent + GetTileDataAction{{1, 0, {1, 1, 0}}, NotFound}, // missing ideal tile + CreateTileDataAction{{1, 0, {1, 1, 0}}}, // + RetainTileDataAction{{1, 0, {1, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 2, 0}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 2, 1}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 3, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 3, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 1, 1}}, NotFound}, // missing tile + CreateTileDataAction{{1, 0, {1, 1, 1}}}, // + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 2, 2}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 2, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 3, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 3, 3}}, NotFound}, // ... + }), + log + ); } TEST(UpdateRenderables, DontUseWrongParentTile) { @@ -314,71 +327,80 @@ TEST(UpdateRenderables, DontUseWrongParentTile) { source.idealTiles.emplace(OverscaledTileID{2, 0, 0}); - auto tile_1_1_1_0 = source.createTileData(OverscaledTileID{ 1, 1, 0 }); + auto tile_1_1_1_0 = source.createTileData(OverscaledTileID{1, 1, 0}); tile_1_1_1_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // parent tile, missing - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // parent tile, missing - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // missing ideal tile + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // parent tile, missing + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // parent tile, missing + }), + log + ); // Now mark the created tile as having the optional request tried. log.clear(); - source.dataTiles[{ 2, 0, { 2, 0, 0 } }]->triedOptional = true; + source.dataTiles[{2, 0, {2, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // non-ready ideal tile - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // parent tile, missing - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // find optional parent - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // parent tile, missing - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // non-ready ideal tile + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // parent tile, missing + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // find optional parent + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // parent tile, missing + }), + log + ); // Add a new child tile and check that it is now used. log.clear(); source.idealTiles.emplace(OverscaledTileID{2, 2, 0}); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // non-ready ideal tile - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - // this tile was added by the previous invocation of updateRenderables - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // parent tile not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // missing parent tile - - GetTileDataAction{ { 2, 0, { 2, 2, 0 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 2, 0, { 2, 2, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 2, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 4, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 3, 0, { 3, 4, 1 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 5, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 5, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 1, 0 } }, Found }, // found parent tile - RetainTileDataAction{ { 1, 0, { 1, 1, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 1, 0 }, *tile_1_1_1_0 }, // render parent tile - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // non-ready ideal tile + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + // this tile was added by the previous invocation of updateRenderables + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // parent tile not ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // missing parent tile + + GetTileDataAction{{2, 0, {2, 2, 0}}, NotFound}, // missing ideal tile + CreateTileDataAction{{2, 0, {2, 2, 0}}}, // + RetainTileDataAction{{2, 0, {2, 2, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 4, 0}}, NotFound}, // child tile + GetTileDataAction{{3, 0, {3, 4, 1}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 5, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 5, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 1, 0}}, Found}, // found parent tile + RetainTileDataAction{{1, 0, {1, 1, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 1, 0}, *tile_1_1_1_0}, // render parent tile + }), + log + ); } TEST(UpdateRenderables, UseParentTileWhenChildNotReady) { @@ -391,39 +413,45 @@ TEST(UpdateRenderables, UseParentTileWhenChildNotReady) { source.idealTiles.emplace(OverscaledTileID{1, 0, 1}); - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; - auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{ 1, 0, 1 }); + auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{1, 0, 1}); // Don't create bucket. // Make sure that it renders the parent tile. algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // found, but not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 2 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 0, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 3 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile, ready - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // render parent tile - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // found, but not ready + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 2}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 0, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 3}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile, ready + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // render parent tile + }), + log + ); // Now insert the bucket and make sure we're now using the matching tile log.clear(); tile_1_1_0_1->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // found and ready - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // render ideal tile - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // found and ready + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // render ideal tile + }), + log + ); } TEST(UpdateRenderables, UseOverlappingParentTile) { @@ -437,31 +465,34 @@ TEST(UpdateRenderables, UseOverlappingParentTile) { source.idealTiles.emplace(OverscaledTileID{1, 0, 0}); source.idealTiles.emplace(OverscaledTileID{1, 0, 1}); - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; - auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{ 1, 0, 1 }); + auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{1, 0, 1}); tile_1_1_0_1->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ideal tile not found - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile found - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // - - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // ideal tile found - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ideal tile not found + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile found + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // + + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // ideal tile found + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // + }), + log + ); } TEST(UpdateRenderables, UseChildTiles) { @@ -474,28 +505,31 @@ TEST(UpdateRenderables, UseChildTiles) { source.idealTiles.emplace(OverscaledTileID{0, 0, 0}); - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, 0 }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, 0}); tile_1_1_0_0->renderable = true; - auto tile_1_1_1_0 = source.createTileData(OverscaledTileID{ 1, 1, 0 }); + auto tile_1_1_1_0 = source.createTileData(OverscaledTileID{1, 1, 0}); tile_1_1_1_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 0, 0, { 0, 0, 0 } } }, // - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // child tile found - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, // render child tile - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, NotFound }, // child tile not found - GetTileDataAction{ { 1, 0, { 1, 1, 0 } }, Found }, // child tile found - RetainTileDataAction{ { 1, 0, { 1, 1, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 1, 0 }, *tile_1_1_1_0 }, // render child tile - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, NotFound }, // child tile not found - // no parent tile of 0 to consider - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{0, 0, {0, 0, 0}}}, // + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // child tile found + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, // render child tile + GetTileDataAction{{1, 0, {1, 0, 1}}, NotFound}, // child tile not found + GetTileDataAction{{1, 0, {1, 1, 0}}, Found}, // child tile found + RetainTileDataAction{{1, 0, {1, 1, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 1, 0}, *tile_1_1_1_0}, // render child tile + GetTileDataAction{{1, 0, {1, 1, 1}}, NotFound}, // child tile not found + // no parent tile of 0 to consider + }), + log + ); } TEST(UpdateRenderables, PreferChildTiles) { @@ -508,103 +542,115 @@ TEST(UpdateRenderables, PreferChildTiles) { source.idealTiles.emplace(OverscaledTileID{1, 0, 0}); - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, 0 }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, 0}); tile_2_2_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ideal tile, not found - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile, found - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // child tile, not found - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile, found - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ideal tile, not found + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile, found + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // child tile, not found + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile, found + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // + }), + log + ); // Now add more children to cover the ideal tile fully, until it is covered fully, and verify // that the parent doesn't get rendered. log.clear(); - auto tile_2_2_0_1 = source.createTileData(OverscaledTileID{ 2, 0, 1 }); + auto tile_2_2_0_1 = source.createTileData(OverscaledTileID{2, 0, 1}); tile_2_2_0_1->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // ideal tile, not ready - // ideal tile was added in previous invocation, but is not yet ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile, found - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 0, 1 } }, TileNecessity::Optional }, // ... - RenderTileAction{ { 2, 0, 1 }, *tile_2_2_0_1 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // child tile, not found - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile, found - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // ideal tile, not ready + // ideal tile was added in previous invocation, but is not yet ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile, found + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 0, 1}}, TileNecessity::Optional}, // ... + RenderTileAction{{2, 0, 1}, *tile_2_2_0_1}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // child tile, not found + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile, found + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // + }), + log + ); log.clear(); - auto tile_2_2_1_0 = source.createTileData(OverscaledTileID{ 2, 1, 0 }); + auto tile_2_2_1_0 = source.createTileData(OverscaledTileID{2, 1, 0}); tile_2_2_1_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // ideal tile, not ready - // ideal tile was added in first invocation, but is not yet ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile, found - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 0, 1 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 1 }, *tile_2_2_0_1 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 1, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 1, 0 }, *tile_2_2_1_0 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // child tile, not found - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile, found - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // ideal tile, not ready + // ideal tile was added in first invocation, but is not yet ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile, found + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 0, 1}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 1}, *tile_2_2_0_1}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 1, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 1, 0}, *tile_2_2_1_0}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // child tile, not found + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile, found + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // + }), + log + ); // Adding the last child tile covers 1/0/0 fully, so we don't need 0/0/0 anymore. log.clear(); - auto tile_2_2_1_1 = source.createTileData(OverscaledTileID{ 2, 1, 1 }); + auto tile_2_2_1_1 = source.createTileData(OverscaledTileID{2, 1, 1}); tile_2_2_1_1->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // ideal tile, not ready - // ideal tile was added in first invocation, but is not yet ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile, found - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 0, 1 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 1 }, *tile_2_2_0_1 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 1, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 1, 0 }, *tile_2_2_1_0 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 1, 1 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 1, 1 }, *tile_2_2_1_1 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // ideal tile, not ready + // ideal tile was added in first invocation, but is not yet ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile, found + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 0, 1}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 1}, *tile_2_2_0_1}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 1, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 1, 0}, *tile_2_2_1_0}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 1, 1}}, TileNecessity::Optional}, // + RenderTileAction{{2, 1, 1}, *tile_2_2_1_1}, // + }), + log + ); } TEST(UpdateRenderables, UseParentAndChildTiles) { @@ -617,47 +663,53 @@ TEST(UpdateRenderables, UseParentAndChildTiles) { source.idealTiles.emplace(OverscaledTileID{1, 0, 0}); - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, 0 }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, 0}); tile_2_2_0_0->renderable = true; // Check that it uses the child tile and the parent tile to cover the rest. algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // + }), + log + ); // Then, remove the child tile and check that it now only the parent tile. log.clear(); - source.dataTiles.erase(OverscaledTileID{ 2, 0, 0 }); + source.dataTiles.erase(OverscaledTileID{2, 0, 0}); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // + }), + log + ); } TEST(UpdateRenderables, DontUseTilesLowerThanMinzoom) { @@ -671,22 +723,25 @@ TEST(UpdateRenderables, DontUseTilesLowerThanMinzoom) { source.zoomRange.min = 2; source.idealTiles.emplace(OverscaledTileID{2, 0, 0}); - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, 0 }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, 0}); tile_1_1_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // - // no requests for zoom 1 tiles - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // + // no requests for zoom 1 tiles + }), + log + ); } TEST(UpdateRenderables, UseOverzoomedTileAfterMaxzoom) { @@ -701,100 +756,116 @@ TEST(UpdateRenderables, UseOverzoomedTileAfterMaxzoom) { source.idealTiles.emplace(OverscaledTileID{2, 0, 0}); // Add a child tile (that should never occur in practice) and make sure it's not selected. - auto tile_3_3_0_0 = source.createTileData(OverscaledTileID{ 3, 0, 0 }); + auto tile_3_3_0_0 = source.createTileData(OverscaledTileID{3, 0, 0}); tile_3_3_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); EXPECT_EQ( ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, NotFound }, // overzoomed tile, not children! - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {2, 0, 0}}, NotFound}, // overzoomed tile, not children! + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // }), - log); + log + ); // Mark the created tile as having tried the optional request. log.clear(); - source.dataTiles[{ 2, 0, { 2, 0, 0 } }]->triedOptional = true; + source.dataTiles[{2, 0, {2, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); EXPECT_EQ( ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // ideal tile, missing - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, NotFound }, // overzoomed tile, not children! - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // ideal tile, missing + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {2, 0, 0}}, NotFound}, // overzoomed tile, not children! + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // }), - log); + log + ); // Switch to overzoomed tile and only add a non-overzoomed ("parent") tile at first. log.clear(); source.idealTiles.clear(); source.idealTiles.emplace(OverscaledTileID{3, 0, {2, 0, 0}}); - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 3, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{3, 0, {2, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{3, 0, {2, 0, 0}}}, // + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{4, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + }), + log + ); // Then add the overzoomed tile matching the zoom level we're rendering. log.clear(); - auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{ 3, 0, { 2, 0, 0 } }); + auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{3, 0, {2, 0, 0}}); tile_3_2_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - RenderTileAction{ { 2, 0, 0 }, *tile_3_2_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + RenderTileAction{{2, 0, 0}, *tile_3_2_0_0}, // + }), + log + ); // Check that it's switching back to the tile that has the matching overzoom value. log.clear(); source.idealTiles.clear(); source.idealTiles.emplace(OverscaledTileID{2, 0, 0}); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + }), + log + ); // Now remove the best match. log.clear(); - source.dataTiles.erase(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + source.dataTiles.erase(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0 = nullptr; // Use the overzoomed tile even though it doesn't match the zoom level. algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // use overzoomed tile! - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_3_2_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // use overzoomed tile! + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_3_2_0_0}, // + }), + log + ); } TEST(UpdateRenderables, AscendToNonOverzoomedTiles) { @@ -809,72 +880,84 @@ TEST(UpdateRenderables, AscendToNonOverzoomedTiles) { source.idealTiles.emplace(OverscaledTileID{3, 0, {2, 0, 0}}); // Add a matching overzoomed tile and make sure it gets selected. - auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{ 3, 0, { 2, 0, 0 } }); + auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{3, 0, {2, 0, 0}}); tile_3_2_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - RenderTileAction{ { 2, 0, 0 }, *tile_3_2_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + RenderTileAction{{2, 0, 0}, *tile_3_2_0_0}, // + }), + log + ); // Then, swap it with a non-overzoomed tile. log.clear(); - source.dataTiles.erase(OverscaledTileID{ 3, 0, { 2, 0, 0 } }); + source.dataTiles.erase(OverscaledTileID{3, 0, {2, 0, 0}}); tile_3_2_0_0 = nullptr; - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, NotFound }, // - CreateTileDataAction{ { 3, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, NotFound }, // prefer using a child first - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{3, 0, {2, 0, 0}}, NotFound}, // + CreateTileDataAction{{3, 0, {2, 0, 0}}}, // + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{4, 0, {2, 0, 0}}, NotFound}, // prefer using a child first + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + }), + log + ); // Then, swap it with a parent tile. log.clear(); - source.dataTiles.erase(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + source.dataTiles.erase(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0 = nullptr; - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, { 1, 0, 0 } }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, {1, 0, 0}}); tile_1_1_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{4, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, // + }), + log + ); // Now, mark the created tile as found. log.clear(); - source.dataTiles[{ 3, 0, { 2, 0, 0 } }]->triedOptional = true; + source.dataTiles[{3, 0, {2, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{4, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, // + }), + log + ); } TEST(UpdateRenderables, DoNotAscendMultipleTimesIfNotFound) { @@ -889,65 +972,71 @@ TEST(UpdateRenderables, DoNotAscendMultipleTimesIfNotFound) { source.idealTiles.emplace(OverscaledTileID{8, 1, 0}); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 8, 0, { 8, 0, 0 } }, NotFound }, // ideal tile - CreateTileDataAction{ { 8, 0, { 8, 0, 0 } } }, // - RetainTileDataAction{ { 8, 0, { 8, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 9, 0, { 9, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 9, 0, { 9, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // ascent - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - - GetTileDataAction{ { 8, 0, { 8, 1, 0 } }, NotFound }, // ideal tile - CreateTileDataAction{ { 8, 0, { 8, 1, 0 } } }, // - RetainTileDataAction{ { 8, 0, { 8, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 9, 0, { 9, 2, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 9, 0, { 9, 2, 1 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 3, 0 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 3, 1 } }, NotFound }, // ... - // no second ascent to 0 - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{8, 0, {8, 0, 0}}, NotFound}, // ideal tile + CreateTileDataAction{{8, 0, {8, 0, 0}}}, // + RetainTileDataAction{{8, 0, {8, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{9, 0, {9, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{9, 0, {9, 0, 1}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 1, 0}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 1, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{6, 0, {6, 0, 0}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ... + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + + GetTileDataAction{{8, 0, {8, 1, 0}}, NotFound}, // ideal tile + CreateTileDataAction{{8, 0, {8, 1, 0}}}, // + RetainTileDataAction{{8, 0, {8, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{9, 0, {9, 2, 0}}, NotFound}, // child tile + GetTileDataAction{{9, 0, {9, 2, 1}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 3, 0}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 3, 1}}, NotFound}, // ... + // no second ascent to 0 + }), + log + ); // Now add a mid-level tile that stops the ascent log.clear(); - auto tile_4_0_0_0 = source.createTileData(OverscaledTileID{ 4, 0, { 4, 0, 0 } }); + auto tile_4_0_0_0 = source.createTileData(OverscaledTileID{4, 0, {4, 0, 0}}); tile_4_0_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 8, 0, { 8, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 8, 0, { 8, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 9, 0, { 9, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 9, 0, { 9, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // ascent - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, Found }, // stops ascent - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 4, 0, 0 }, *tile_4_0_0_0 }, // - - GetTileDataAction{ { 8, 0, { 8, 1, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 8, 0, { 8, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 9, 0, { 9, 2, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 9, 0, { 9, 2, 1 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 3, 0 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 3, 1 } }, NotFound }, // ... - // no second ascent to 0 - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{8, 0, {8, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{8, 0, {8, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{9, 0, {9, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{9, 0, {9, 0, 1}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 1, 0}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 1, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{6, 0, {6, 0, 0}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ... + GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // stops ascent + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{4, 0, 0}, *tile_4_0_0_0}, // + + GetTileDataAction{{8, 0, {8, 1, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{8, 0, {8, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{9, 0, {9, 2, 0}}, NotFound}, // child tile + GetTileDataAction{{9, 0, {9, 2, 1}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 3, 0}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 3, 1}}, NotFound}, // ... + // no second ascent to 0 + }), + log + ); } TEST(UpdateRenderables, DontRetainUnusedNonIdealTiles) { @@ -960,23 +1049,26 @@ TEST(UpdateRenderables, DontRetainUnusedNonIdealTiles) { source.idealTiles.emplace(OverscaledTileID{2, 0, 0}); - source.createTileData(OverscaledTileID{ 1, 0, 0 }); - source.createTileData(OverscaledTileID{ 2, 0, 0 }); + source.createTileData(OverscaledTileID{1, 0, 0}); + source.createTileData(OverscaledTileID{2, 0, 0}); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // parent tile, not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // parent tile, not ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // + }), + log + ); } TEST(UpdateRenderables, WrappedTiles) { @@ -998,51 +1090,54 @@ TEST(UpdateRenderables, WrappedTiles) { source.idealTiles.emplace(OverscaledTileID{1, id.wrap, id.canonical}); } - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, { 0, 0, 0 } }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, {0, 0, 0}}); tile_0_0_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, -1, { 1, 1, 0 } }, NotFound }, // ideal tile 1/-1/0 (wrapped to -1) - CreateTileDataAction{ { 1, -1, { 1, 1, 0 } } }, // - RetainTileDataAction{ { 1, -1, { 1, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, -1, { 2, 2, 0 } }, NotFound }, // - GetTileDataAction{ { 2, -1, { 2, 2, 1 } }, NotFound }, // - GetTileDataAction{ { 2, -1, { 2, 3, 0 } }, NotFound }, // - GetTileDataAction{ { 2, -1, { 2, 3, 1 } }, NotFound }, // - GetTileDataAction{ { 0, -1, { 0, 0, 0 } }, NotFound }, // { 0, 0, 0 } exists, but not the version wrapped to -1 - - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ideal tile 1/0/0 - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // - - GetTileDataAction{ { 1, 0, { 1, 1, 0 } }, NotFound }, // ideal tile 1/1/0, doesn't match 1/-/1/0 - CreateTileDataAction{ { 1, 0, { 1, 1, 0 } } }, - RetainTileDataAction{ { 1, 0, { 1, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 2, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 2, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 3, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 3, 1 } }, NotFound }, // - // do not ascent; 0/0/0 has been rendered already for 1/0/0 - - GetTileDataAction{ { 1, 1, { 1, 0, 0 } }, NotFound }, // ideal tile 1/2/0 (wrapped to 1) - CreateTileDataAction{ { 1, 1, { 1, 0, 0 } } }, - RetainTileDataAction{ { 1, 1, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 1, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 1, { 2, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 1, { 2, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 1, { 2, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 0, 1, { 0, 0, 0 } }, NotFound }, // { 0, 0, 0 } exists, but not the version wrapped to -1 - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, -1, {1, 1, 0}}, NotFound}, // ideal tile 1/-1/0 (wrapped to -1) + CreateTileDataAction{{1, -1, {1, 1, 0}}}, // + RetainTileDataAction{{1, -1, {1, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, -1, {2, 2, 0}}, NotFound}, // + GetTileDataAction{{2, -1, {2, 2, 1}}, NotFound}, // + GetTileDataAction{{2, -1, {2, 3, 0}}, NotFound}, // + GetTileDataAction{{2, -1, {2, 3, 1}}, NotFound}, // + GetTileDataAction{{0, -1, {0, 0, 0}}, NotFound}, // { 0, 0, 0 } exists, but not the version wrapped to -1 + + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ideal tile 1/0/0 + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // + + GetTileDataAction{{1, 0, {1, 1, 0}}, NotFound}, // ideal tile 1/1/0, doesn't match 1/-/1/0 + CreateTileDataAction{{1, 0, {1, 1, 0}}}, + RetainTileDataAction{{1, 0, {1, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 2, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 2, 1}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 3, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 3, 1}}, NotFound}, // + // do not ascent; 0/0/0 has been rendered already for 1/0/0 + + GetTileDataAction{{1, 1, {1, 0, 0}}, NotFound}, // ideal tile 1/2/0 (wrapped to 1) + CreateTileDataAction{{1, 1, {1, 0, 0}}}, + RetainTileDataAction{{1, 1, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 1, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 1, {2, 0, 1}}, NotFound}, // + GetTileDataAction{{2, 1, {2, 1, 0}}, NotFound}, // + GetTileDataAction{{2, 1, {2, 1, 1}}, NotFound}, // + GetTileDataAction{{0, 1, {0, 0, 0}}, NotFound}, // { 0, 0, 0 } exists, but not the version wrapped to -1 + }), + log + ); } TEST(UpdateRenderables, RepeatedRenderWithMissingOptionals) { @@ -1056,185 +1151,209 @@ TEST(UpdateRenderables, RepeatedRenderWithMissingOptionals) { source.idealTiles.emplace(OverscaledTileID{6, 0, 0}); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, NotFound }, // ideal tile, not found - CreateTileDataAction{ { 6, 0, { 6, 0, 0 } } }, // - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ascent - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{6, 0, {6, 0, 0}}, NotFound}, // ideal tile, not found + CreateTileDataAction{{6, 0, {6, 0, 0}}}, // + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + }), + log + ); // Repeat. log.clear(); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ascent - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + }), + log + ); // Mark next level has having tried optional. log.clear(); - source.dataTiles[{ 6, 0, { 6, 0, 0 } }]->triedOptional = true; + source.dataTiles[{6, 0, {6, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ascent - CreateTileDataAction{ { 5, 0, { 5, 0, 0 } } }, // - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ascent + CreateTileDataAction{{5, 0, {5, 0, 0}}}, // + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + }), + log + ); // Repeat. log.clear(); algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + }), + log + ); // Mark next level has having tried optional. log.clear(); - source.dataTiles[{ 5, 0, { 5, 0, 0 } }]->triedOptional = true; + source.dataTiles[{5, 0, {5, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - CreateTileDataAction{ { 4, 0, { 4, 0, 0 } } }, // - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + CreateTileDataAction{{4, 0, {4, 0, 0}}}, // + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + }), + log + ); // Mark next level has having tried optional. log.clear(); - source.dataTiles[{ 4, 0, { 4, 0, 0 } }]->triedOptional = true; + source.dataTiles[{4, 0, {4, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - CreateTileDataAction{ { 3, 0, { 3, 0, 0 } } }, // - RetainTileDataAction{ { 3, 0, { 3, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // ... + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + CreateTileDataAction{{3, 0, {3, 0, 0}}}, // + RetainTileDataAction{{3, 0, {3, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + }), + log + ); // Mark next level has having tried optional. log.clear(); - source.dataTiles[{ 3, 0, { 3, 0, 0 } }]->triedOptional = true; + source.dataTiles[{3, 0, {3, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 3, 0, { 3, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // ... + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, Found}, // ... + RetainTileDataAction{{3, 0, {3, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + }), + log + ); // Mark as found log.clear(); - auto tile_3_3_0_0 = source.dataTiles[{ 3, 0, { 3, 0, 0 } }].get(); + auto tile_3_3_0_0 = source.dataTiles[{3, 0, {3, 0, 0}}].get(); tile_3_3_0_0->renderable = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 3, 0, { 3, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 3, 0, 0 }, *tile_3_3_0_0 }, // - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // ... + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, Found}, // ... + RetainTileDataAction{{3, 0, {3, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{3, 0, 0}, *tile_3_3_0_0}, // + }), + log + ); } TEST(UpdateRenderables, LoadRequiredIfIdealTileCantBeFound) { @@ -1248,26 +1367,29 @@ TEST(UpdateRenderables, LoadRequiredIfIdealTileCantBeFound) { source.zoomRange.max = 6; source.idealTiles.emplace(OverscaledTileID{6, 0, 0}); - auto tile_6_6_0_0 = source.createTileData(OverscaledTileID{ 6, 0, { 6, 0, 0 } }); + auto tile_6_6_0_0 = source.createTileData(OverscaledTileID{6, 0, {6, 0, 0}}); tile_6_6_0_0->triedOptional = true; tile_6_6_0_0->loaded = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not found - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 6, 0, 0 } }, NotFound }, // overzoomed child - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ascent - CreateTileDataAction{ { 5, 0, { 5, 0, 0 } } }, - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Required }, - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not found + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {6, 0, 0}}, NotFound}, // overzoomed child + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ascent + CreateTileDataAction{{5, 0, {5, 0, 0}}}, + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + }), + log + ); } // Tests overzooming a 0/0/0 tile to zoom level 4, when the maxzoom is 2. @@ -1282,42 +1404,45 @@ TEST(UpdateRenderables, LoadOverscaledMaxZoomTile) { source.zoomRange.max = 2; source.idealTiles.emplace(OverscaledTileID{4, 0, {2, 0, 0}}); - auto tile_4_2_0_0 = source.createTileData(OverscaledTileID{ 4, 0, { 2, 0, 0 } }); + auto tile_4_2_0_0 = source.createTileData(OverscaledTileID{4, 0, {2, 0, 0}}); tile_4_2_0_0->renderable = false; tile_4_2_0_0->triedOptional = true; tile_4_2_0_0->loaded = true; - auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{ 3, 0, { 2, 0, 0 } }); + auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{3, 0, {2, 0, 0}}); tile_3_2_0_0->renderable = false; tile_3_2_0_0->triedOptional = true; tile_3_2_0_0->loaded = true; - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0->renderable = false; tile_2_2_0_0->triedOptional = true; tile_2_2_0_0->loaded = true; // Tile level 1 won't be overscaled. - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, { 1, 0, 0 } }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, {1, 0, 0}}); tile_1_1_0_0->renderable = true; tile_1_1_0_0->triedOptional = true; tile_1_1_0_0->loaded = true; algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, Found }, - RetainTileDataAction{ { 4, 0, { 2, 0, 0 } }, TileNecessity::Required }, - GetTileDataAction{ { 5, 0, { 2, 0, 0 } }, NotFound }, - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, - }), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange + ); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{4, 0, {2, 0, 0}}, Found}, + RetainTileDataAction{{4, 0, {2, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{5, 0, {2, 0, 0}}, NotFound}, + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, + }), + log + ); } TEST(UpdateRenderables, MaxParentOverscaleFactor) { @@ -1336,49 +1461,57 @@ TEST(UpdateRenderables, MaxParentOverscaleFactor) { // Set max parent overscale factor to 4, so that tile 0,0,0 would be rendered algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange, 4); - EXPECT_EQ(ActionLog({GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ideal tile - CreateTileDataAction{{4, 0, {4, 0, 0}}}, - RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Required}, - GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // child tiles - GetTileDataAction{{5, 0, {5, 0, 1}}, NotFound}, - GetTileDataAction{{5, 0, {5, 1, 0}}, NotFound}, - GetTileDataAction{{5, 0, {5, 1, 1}}, NotFound}, - GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ascent - GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, - GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, - GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, - RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, - RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // render tile 0,0,0 - GetTileDataAction{{4, 0, {4, 1, 0}}, NotFound}, // ideal tile - CreateTileDataAction{{4, 0, {4, 1, 0}}}, - RetainTileDataAction{{4, 0, {4, 1, 0}}, TileNecessity::Required}, - GetTileDataAction{{5, 0, {5, 2, 0}}, NotFound}, // child tiles - GetTileDataAction{{5, 0, {5, 2, 1}}, NotFound}, - GetTileDataAction{{5, 0, {5, 3, 0}}, NotFound}, - GetTileDataAction{{5, 0, {5, 3, 1}}, NotFound}}), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange, 4 + ); + EXPECT_EQ( + ActionLog({GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ideal tile + CreateTileDataAction{{4, 0, {4, 0, 0}}}, + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // child tiles + GetTileDataAction{{5, 0, {5, 0, 1}}, NotFound}, + GetTileDataAction{{5, 0, {5, 1, 0}}, NotFound}, + GetTileDataAction{{5, 0, {5, 1, 1}}, NotFound}, + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // render tile 0,0,0 + GetTileDataAction{{4, 0, {4, 1, 0}}, NotFound}, // ideal tile + CreateTileDataAction{{4, 0, {4, 1, 0}}}, + RetainTileDataAction{{4, 0, {4, 1, 0}}, TileNecessity::Required}, + GetTileDataAction{{5, 0, {5, 2, 0}}, NotFound}, // child tiles + GetTileDataAction{{5, 0, {5, 2, 1}}, NotFound}, + GetTileDataAction{{5, 0, {5, 3, 0}}, NotFound}, + GetTileDataAction{{5, 0, {5, 3, 1}}, NotFound}}), + log + ); log.clear(); // Set max parent overscale factor to 3. // Parent tile 0,0,0 should not be requested / rendered. algorithm::updateRenderables( - getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange, 3); - EXPECT_EQ(ActionLog({GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // ideal tile - RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Required}, - GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // child tiles - GetTileDataAction{{5, 0, {5, 0, 1}}, NotFound}, - GetTileDataAction{{5, 0, {5, 1, 0}}, NotFound}, - GetTileDataAction{{5, 0, {5, 1, 1}}, NotFound}, - GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ascent - GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, - GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, - GetTileDataAction{{4, 0, {4, 1, 0}}, Found}, // ideal tile - RetainTileDataAction{{4, 0, {4, 1, 0}}, TileNecessity::Required}, - GetTileDataAction{{5, 0, {5, 2, 0}}, NotFound}, // child tiles - GetTileDataAction{{5, 0, {5, 2, 1}}, NotFound}, - GetTileDataAction{{5, 0, {5, 3, 0}}, NotFound}, - GetTileDataAction{{5, 0, {5, 3, 1}}, NotFound}}), - log); + getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange, 3 + ); + EXPECT_EQ( + ActionLog( + {GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // ideal tile + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // child tiles + GetTileDataAction{{5, 0, {5, 0, 1}}, NotFound}, + GetTileDataAction{{5, 0, {5, 1, 0}}, NotFound}, + GetTileDataAction{{5, 0, {5, 1, 1}}, NotFound}, + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, + GetTileDataAction{{4, 0, {4, 1, 0}}, Found}, // ideal tile + RetainTileDataAction{{4, 0, {4, 1, 0}}, TileNecessity::Required}, + GetTileDataAction{{5, 0, {5, 2, 0}}, NotFound}, // child tiles + GetTileDataAction{{5, 0, {5, 2, 1}}, NotFound}, + GetTileDataAction{{5, 0, {5, 3, 0}}, NotFound}, + GetTileDataAction{{5, 0, {5, 3, 1}}, NotFound}} + ), + log + ); } diff --git a/test/algorithm/update_tile_masks.test.cpp b/test/algorithm/update_tile_masks.test.cpp index 5c14ec650b9..034e646e9c2 100644 --- a/test/algorithm/update_tile_masks.test.cpp +++ b/test/algorithm/update_tile_masks.test.cpp @@ -8,11 +8,8 @@ namespace { class FakeTile { public: FakeTile(TileMask mask_) - : mask(std::move(mask_)) { - } - void setMask(TileMask mask_) { - mask = std::move(mask_); - } + : mask(std::move(mask_)) {} + void setMask(TileMask mask_) { mask = std::move(mask_); } const bool usedByRenderedLayers = true; TileMask mask; @@ -26,91 +23,95 @@ bool operator==(const FakeTile& lhs, const FakeTile& rhs) { void validate(std::map expected) { auto actual = expected; - std::for_each(actual.begin(), actual.end(), - [](auto& renderable) { renderable.second.mask.clear(); }); + std::for_each(actual.begin(), actual.end(), [](auto& renderable) { renderable.second.mask.clear(); }); algorithm::updateTileMasks(actual); EXPECT_EQ(expected, actual); } TEST(UpdateTileMasks, NoChildren) { - validate({ - { UnwrappedTileID{ 0, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } } - }); + validate({{UnwrappedTileID{0, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}}); validate({ - { UnwrappedTileID{ 4, 3, 8 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{4, 3, 8}, TileMask{CanonicalTileID{0, 0, 0}}}, }); validate({ - { UnwrappedTileID{ 1, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 1, 1, 1 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{1, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{1, 1, 1}, TileMask{CanonicalTileID{0, 0, 0}}}, }); validate({ - { UnwrappedTileID{ 1, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 2, 2, 3 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{1, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{2, 2, 3}, TileMask{CanonicalTileID{0, 0, 0}}}, }); } TEST(UpdateTileMasks, ParentAndFourChildren) { validate({ // Mask is empty (== not rendered!) because we have four covering children. - { UnwrappedTileID{ 0, 0, 0 }, TileMask{} }, + {UnwrappedTileID{0, 0, 0}, TileMask{}}, // All four covering children - { UnwrappedTileID{ 1, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 1, 0, 1 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 1, 1, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 1, 1, 1 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{1, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{1, 0, 1}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{1, 1, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{1, 1, 1}, TileMask{CanonicalTileID{0, 0, 0}}}, }); } TEST(UpdateTileMasks, OneChild) { validate({ - { UnwrappedTileID{ 0, 0, 0 }, - // Only render the three children that aren't covering the other tile. - TileMask{ CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 1, 1, 1 } } }, - { UnwrappedTileID{ 1, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{0, 0, 0}, + // Only render the three children that aren't covering the other tile. + TileMask{CanonicalTileID{1, 0, 1}, CanonicalTileID{1, 1, 0}, CanonicalTileID{1, 1, 1}}}, + {UnwrappedTileID{1, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, }); } TEST(UpdateTileMasks, Complex) { validate({ - { UnwrappedTileID{ 0, 0, 0 }, - TileMask{ CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 2, 2, 3 }, CanonicalTileID{ 2, 3, 2 }, - CanonicalTileID{ 3, 6, 7 }, CanonicalTileID{ 3, 7, 6 } } }, - { UnwrappedTileID{ 0, { 1, 0, 0 } }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 0, { 2, 2, 2 } }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 0, { 3, 7, 7 } }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 0, { 3, 6, 6 } }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{0, 0, 0}, + TileMask{ + CanonicalTileID{1, 0, 1}, + CanonicalTileID{1, 1, 0}, + CanonicalTileID{2, 2, 3}, + CanonicalTileID{2, 3, 2}, + CanonicalTileID{3, 6, 7}, + CanonicalTileID{3, 7, 6}}}, + {UnwrappedTileID{0, {1, 0, 0}}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{0, {2, 2, 2}}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{0, {3, 7, 7}}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{0, {3, 6, 6}}, TileMask{CanonicalTileID{0, 0, 0}}}, }); validate({ - { UnwrappedTileID{ 0, 0, 0 }, - TileMask{ CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 1, 1, 1 }, CanonicalTileID{ 2, 0, 0 }, - CanonicalTileID{ 2, 0, 1 }, CanonicalTileID{ 2, 1, 0 }, - CanonicalTileID{ 3, 2, 3 }, CanonicalTileID{ 3, 3, 2 }, - CanonicalTileID{ 3, 3, 3 }, CanonicalTileID{ 4, 4, 5 }, - CanonicalTileID{ 4, 5, 4 }, CanonicalTileID{ 4, 5, 5 } } }, - { UnwrappedTileID{ 4, 4, 4 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{0, 0, 0}, + TileMask{ + CanonicalTileID{1, 0, 1}, + CanonicalTileID{1, 1, 0}, + CanonicalTileID{1, 1, 1}, + CanonicalTileID{2, 0, 0}, + CanonicalTileID{2, 0, 1}, + CanonicalTileID{2, 1, 0}, + CanonicalTileID{3, 2, 3}, + CanonicalTileID{3, 3, 2}, + CanonicalTileID{3, 3, 3}, + CanonicalTileID{4, 4, 5}, + CanonicalTileID{4, 5, 4}, + CanonicalTileID{4, 5, 5}}}, + {UnwrappedTileID{4, 4, 4}, TileMask{CanonicalTileID{0, 0, 0}}}, }); validate({ - { UnwrappedTileID{ 12, 1028, 1456 }, - TileMask{ CanonicalTileID{ 1, 1, 1 }, CanonicalTileID{ 2, 3, 0 }, - CanonicalTileID{ 2, 3, 1 } } }, - { UnwrappedTileID{ 13, 2056, 2912 }, - TileMask{ CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 1, 1, 1 } } }, - { UnwrappedTileID{ 13, 2056, 2913 }, - TileMask{ CanonicalTileID{ 1, 0, 0 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 1, 1, 1 } } }, - { UnwrappedTileID{ 14, 4112, 5824 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 14, 4112, 5827 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 14, 4114, 5824 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 14, 4114, 5825 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{12, 1028, 1456}, + TileMask{CanonicalTileID{1, 1, 1}, CanonicalTileID{2, 3, 0}, CanonicalTileID{2, 3, 1}}}, + {UnwrappedTileID{13, 2056, 2912}, + TileMask{CanonicalTileID{1, 0, 1}, CanonicalTileID{1, 1, 0}, CanonicalTileID{1, 1, 1}}}, + {UnwrappedTileID{13, 2056, 2913}, + TileMask{CanonicalTileID{1, 0, 0}, CanonicalTileID{1, 1, 0}, CanonicalTileID{1, 1, 1}}}, + {UnwrappedTileID{14, 4112, 5824}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{14, 4112, 5827}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{14, 4114, 5824}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{14, 4114, 5825}, TileMask{CanonicalTileID{0, 0, 0}}}, }); } diff --git a/test/api/annotations.test.cpp b/test/api/annotations.test.cpp index ca4c0ecfe6f..b8064704c6b 100644 --- a/test/api/annotations.test.cpp +++ b/test/api/annotations.test.cpp @@ -27,12 +27,15 @@ std::unique_ptr namedMarker(const std::string& name) { class AnnotationTest { public: util::RunLoop loop; - HeadlessFrontend frontend { 1 }; + HeadlessFrontend frontend{1}; - MapAdapter map { frontend, MapObserver::nullObserver(), std::make_shared(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())}; + MapAdapter map{ + frontend, + MapObserver::nullObserver(), + std::make_shared(), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())}; - void checkRendering(const char * name) { + void checkRendering(const char* name) { test::checkImage(std::string("test/fixtures/annotations/") + name, frontend.render(map).image, 0.0002, 0.1); } }; @@ -44,26 +47,26 @@ TEST(Annotations, SymbolAnnotation) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point(0, 0), "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point(0, 0), "default_marker"}); test.checkRendering("point_annotation"); -// auto size = test.frontend.getSize(); -// auto screenBox = ScreenBox { {}, { double(size.width), double(size.height) } }; -// for (uint8_t zoom = test.map.getMinZoom(); zoom <= test.map.getMaxZoom(); ++zoom) { -// test.map.jumpTo(CameraOptions().withZoom(zoom)); -// test.checkRendering("point_annotation"); -// EXPECT_EQ(test.map.queryPointAnnotations(screenBox).size(), 1u); -// } + // auto size = test.frontend.getSize(); + // auto screenBox = ScreenBox { {}, { double(size.width), double(size.height) } }; + // for (uint8_t zoom = test.map.getMinZoom(); zoom <= test.map.getMaxZoom(); ++zoom) { + // test.map.jumpTo(CameraOptions().withZoom(zoom)); + // test.checkRendering("point_annotation"); + // EXPECT_EQ(test.map.queryPointAnnotations(screenBox).size(), 1u); + // } } TEST(Annotations, SymbolAnnotationTileBoundary) { // Almost exactly the same as SymbolAnnotation test above, but offset my fractions of a degree // tests precision issue from https://github.com/mapbox/mapbox-gl-native/issues/12472 AnnotationTest test; - + test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point(0.000000000000001, 0.00000000000001), "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point(0.000000000000001, 0.00000000000001), "default_marker"}); test.map.jumpTo(CameraOptions().withZoom(10)); test.checkRendering("point_annotation"); } @@ -71,10 +74,10 @@ TEST(Annotations, SymbolAnnotationTileBoundary) { TEST(Annotations, LineAnnotation) { AnnotationTest test; - LineString line = {{ { 0, 0 }, { 45, 45 }, { 30, 0 } }}; - LineAnnotation annotation { line }; + LineString line = {{{0, 0}, {45, 45}, {30, 0}}}; + LineAnnotation annotation{line}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotation(annotation); @@ -87,8 +90,8 @@ TEST(Annotations, LineAnnotation) { TEST(Annotations, FillAnnotation) { AnnotationTest test; - Polygon polygon = { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} }; - FillAnnotation annotation { polygon }; + Polygon polygon = {{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}; + FillAnnotation annotation{polygon}; annotation.color = Color::red(); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); @@ -103,17 +106,17 @@ TEST(Annotations, AntimeridianAnnotationSmall) { AnnotationTest test; double antimeridian = 180; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 0, antimeridian }).withZoom(0.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{0, antimeridian}).withZoom(0.0)); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); - LineString line = {{ { antimeridian, 20 }, { antimeridian, -20 } }}; - LineAnnotation lineAnnotation { line }; + LineString line = {{{antimeridian, 20}, {antimeridian, -20}}}; + LineAnnotation lineAnnotation{line}; lineAnnotation.color = Color::red(); - lineAnnotation.width = { 2 }; + lineAnnotation.width = {2}; test.map.addAnnotation(lineAnnotation); - Polygon polygon = { {{ { antimeridian+10, 0 }, { antimeridian - 10, 10 }, { antimeridian-10, -10 } }} }; - FillAnnotation polygonAnnotation { polygon }; + Polygon polygon = {{{{antimeridian + 10, 0}, {antimeridian - 10, 10}, {antimeridian - 10, -10}}}}; + FillAnnotation polygonAnnotation{polygon}; polygonAnnotation.color = Color::blue(); test.map.addAnnotation(polygonAnnotation); @@ -127,14 +130,14 @@ TEST(Annotations, AntimeridianAnnotationLarge) { test.map.jumpTo(CameraOptions().withCenter(mbgl::LatLng(0.0, antimeridian)).withZoom(0.0)); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); - LineString line = {{ { antimeridian, 20 }, { antimeridian, -20 } }}; - LineAnnotation lineAnnotation { line }; + LineString line = {{{antimeridian, 20}, {antimeridian, -20}}}; + LineAnnotation lineAnnotation{line}; lineAnnotation.color = Color::red(); - lineAnnotation.width = { 2 }; + lineAnnotation.width = {2}; test.map.addAnnotation(lineAnnotation); - Polygon polygon = { {{ { antimeridian-10, 0 }, { -antimeridian+10, 10 }, { -antimeridian+10, -10 } }} }; - FillAnnotation polygonAnnotation { polygon }; + Polygon polygon = {{{{antimeridian - 10, 0}, {-antimeridian + 10, 10}, {-antimeridian + 10, -10}}}}; + FillAnnotation polygonAnnotation{polygon}; polygonAnnotation.color = Color::blue(); test.map.addAnnotation(polygonAnnotation); @@ -144,10 +147,10 @@ TEST(Annotations, AntimeridianAnnotationLarge) { TEST(Annotations, OverlappingFillAnnotation) { AnnotationTest test; - Polygon polygon = { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} }; - FillAnnotation underlaidAnnotation { polygon }; + Polygon polygon = {{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}; + FillAnnotation underlaidAnnotation{polygon}; underlaidAnnotation.color = Color::green(); - FillAnnotation overlaidAnnotation { polygon }; + FillAnnotation overlaidAnnotation{polygon}; overlaidAnnotation.color = Color::red(); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); @@ -161,11 +164,11 @@ TEST(Annotations, AddMultiple) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point { -10, 0 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{-10, 0}, "default_marker"}); test.frontend.render(test.map); - test.map.addAnnotation(SymbolAnnotation { Point { 10, 0 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{10, 0}, "default_marker"}); test.checkRendering("add_multiple"); } @@ -175,8 +178,8 @@ TEST(Annotations, NonImmediateAdd) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.frontend.render(test.map); - Polygon polygon = { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} }; - FillAnnotation annotation { polygon }; + Polygon polygon = {{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}; + FillAnnotation annotation{polygon}; annotation.color = Color::red(); test.map.addAnnotation(annotation); @@ -189,11 +192,11 @@ TEST(Annotations, UpdateSymbolAnnotationGeometry) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); test.map.addAnnotationImage(namedMarker("flipped_marker")); - AnnotationID point = test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + AnnotationID point = test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); - test.map.updateAnnotation(point, SymbolAnnotation { Point { -10, 0 }, "default_marker" }); + test.map.updateAnnotation(point, SymbolAnnotation{Point{-10, 0}, "default_marker"}); test.checkRendering("update_point"); } @@ -203,27 +206,27 @@ TEST(Annotations, UpdateSymbolAnnotationIcon) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); test.map.addAnnotationImage(namedMarker("flipped_marker")); - AnnotationID point = test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + AnnotationID point = test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); - test.map.updateAnnotation(point, SymbolAnnotation { Point { 0, 0 }, "flipped_marker" }); + test.map.updateAnnotation(point, SymbolAnnotation{Point{0, 0}, "flipped_marker"}); test.checkRendering("update_icon"); } TEST(Annotations, UpdateLineAnnotationGeometry) { AnnotationTest test; - LineAnnotation annotation { LineString {{ { 0, 0 }, { 45, 45 }, { 30, 0 } }} }; + LineAnnotation annotation{LineString{{{0, 0}, {45, 45}, {30, 0}}}}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); AnnotationID line = test.map.addAnnotation(annotation); test.frontend.render(test.map); - annotation.geometry = LineString {{ { 0, 0 }, { -45, -45 } }}; + annotation.geometry = LineString{{{0, 0}, {-45, -45}}}; test.map.updateAnnotation(line, annotation); test.checkRendering("update_line_geometry"); } @@ -231,9 +234,9 @@ TEST(Annotations, UpdateLineAnnotationGeometry) { TEST(Annotations, UpdateLineAnnotationStyle) { AnnotationTest test; - LineAnnotation annotation { LineString {{ { 0, 0 }, { 45, 45 }, { 30, 0 } }} }; + LineAnnotation annotation{LineString{{{0, 0}, {45, 45}, {30, 0}}}}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); AnnotationID line = test.map.addAnnotation(annotation); @@ -241,7 +244,7 @@ TEST(Annotations, UpdateLineAnnotationStyle) { test.frontend.render(test.map); annotation.color = Color::green(); - annotation.width = { 2 }; + annotation.width = {2}; test.map.updateAnnotation(line, annotation); test.checkRendering("update_line_style"); } @@ -249,7 +252,7 @@ TEST(Annotations, UpdateLineAnnotationStyle) { TEST(Annotations, UpdateFillAnnotationGeometry) { AnnotationTest test; - FillAnnotation annotation { Polygon { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} } }; + FillAnnotation annotation{Polygon{{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}}; annotation.color = Color::red(); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); @@ -257,7 +260,7 @@ TEST(Annotations, UpdateFillAnnotationGeometry) { test.frontend.render(test.map); - annotation.geometry = Polygon { {{ { 0, 0 }, { 0, 45 }, { 45, 0 } }} }; + annotation.geometry = Polygon{{{{0, 0}, {0, 45}, {45, 0}}}}; test.map.updateAnnotation(fill, annotation); test.checkRendering("update_fill_geometry"); } @@ -265,8 +268,8 @@ TEST(Annotations, UpdateFillAnnotationGeometry) { TEST(Annotations, UpdateFillAnnotationStyle) { AnnotationTest test; - Polygon polygon = { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} }; - FillAnnotation annotation { polygon }; + Polygon polygon = {{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}; + FillAnnotation annotation{polygon}; annotation.color = Color::red(); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); @@ -284,7 +287,7 @@ TEST(Annotations, RemovePoint) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - AnnotationID point = test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + AnnotationID point = test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); @@ -295,10 +298,10 @@ TEST(Annotations, RemovePoint) { TEST(Annotations, RemoveShape) { AnnotationTest test; - LineString line = {{ { 0, 0 }, { 45, 45 } }}; - LineAnnotation annotation { line }; + LineString line = {{{0, 0}, {45, 45}}}; + LineAnnotation annotation{line}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); AnnotationID shape = test.map.addAnnotation(annotation); @@ -312,7 +315,7 @@ TEST(Annotations, RemoveShape) { TEST(Annotations, ImmediateRemoveShape) { AnnotationTest test; - test.map.removeAnnotation(test.map.addAnnotation(LineAnnotation { LineString() })); + test.map.removeAnnotation(test.map.addAnnotation(LineAnnotation{LineString()})); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.frontend.render(test.map); @@ -323,7 +326,7 @@ TEST(Annotations, SwitchStyle) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); @@ -336,7 +339,7 @@ TEST(Annotations, ReaddImage) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); @@ -349,8 +352,8 @@ TEST(Annotations, QueryRenderedFeatures) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); - test.map.addAnnotation(SymbolAnnotation { Point { 0, 50 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); + test.map.addAnnotation(SymbolAnnotation{Point{0, 50}, "default_marker"}); test.frontend.render(test.map); @@ -381,7 +384,7 @@ TEST(Annotations, QueryFractionalZoomLevels) { AnnotationTest test; auto viewSize = test.frontend.getSize(); - auto box = ScreenBox { {}, { double(viewSize.width), double(viewSize.height) } }; + auto box = ScreenBox{{}, {double(viewSize.width), double(viewSize.height)}}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); @@ -389,7 +392,8 @@ TEST(Annotations, QueryFractionalZoomLevels) { std::vector ids; for (int longitude = 0; longitude < 10; longitude += 2) { for (int latitude = 0; latitude < 10; latitude += 2) { - ids.push_back(test.map.addAnnotation(SymbolAnnotation { { double(latitude), double(longitude) }, "default_marker" })); + ids.push_back(test.map.addAnnotation(SymbolAnnotation{ + {double(latitude), double(longitude)}, "default_marker"})); } } @@ -401,8 +405,12 @@ TEST(Annotations, QueryFractionalZoomLevels) { // Filter out repeated features. // See 'edge-cases/null-island' query-test for reference. - auto sortID = [](const Feature& lhs, const Feature& rhs) { return lhs.id < rhs.id; }; - auto sameID = [](const Feature& lhs, const Feature& rhs) { return lhs.id == rhs.id; }; + auto sortID = [](const Feature& lhs, const Feature& rhs) { + return lhs.id < rhs.id; + }; + auto sameID = [](const Feature& lhs, const Feature& rhs) { + return lhs.id == rhs.id; + }; std::sort(features.begin(), features.end(), sortID); features.erase(std::unique(features.begin(), features.end(), sameID), features.end()); EXPECT_EQ(features.size(), ids.size()); @@ -413,7 +421,7 @@ TEST(Annotations, VisibleFeatures) { AnnotationTest test; auto viewSize = test.frontend.getSize(); - auto box = ScreenBox { {}, { double(viewSize.width), double(viewSize.height) } }; + auto box = ScreenBox{{}, {double(viewSize.width), double(viewSize.height)}}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); @@ -422,7 +430,8 @@ TEST(Annotations, VisibleFeatures) { std::vector ids; for (int longitude = 0; longitude < 10; longitude += 2) { for (int latitude = 0; latitude <= 10; latitude += 2) { - ids.push_back(test.map.addAnnotation(SymbolAnnotation { { double(latitude), double(longitude) }, "default_marker" })); + ids.push_back(test.map.addAnnotation(SymbolAnnotation{ + {double(latitude), double(longitude)}, "default_marker"})); } } @@ -431,8 +440,12 @@ TEST(Annotations, VisibleFeatures) { test.frontend.render(test.map); auto features = test.frontend.getRenderer()->queryRenderedFeatures(box, {}); - auto sortID = [](const Feature& lhs, const Feature& rhs) { return lhs.id < rhs.id; }; - auto sameID = [](const Feature& lhs, const Feature& rhs) { return lhs.id == rhs.id; }; + auto sortID = [](const Feature& lhs, const Feature& rhs) { + return lhs.id < rhs.id; + }; + auto sameID = [](const Feature& lhs, const Feature& rhs) { + return lhs.id == rhs.id; + }; std::sort(features.begin(), features.end(), sortID); features.erase(std::unique(features.begin(), features.end(), sameID), features.end()); EXPECT_EQ(features.size(), ids.size()); @@ -457,19 +470,20 @@ TEST(Annotations, ViewFrustumCulling) { AnnotationTest test; auto viewSize = test.frontend.getSize(); - auto box = ScreenBox { {}, { double(viewSize.width), double(viewSize.height) } }; + auto box = ScreenBox{{}, {double(viewSize.width), double(viewSize.height)}}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - const LatLng center = { 5.0, 5.0 }; + const LatLng center = {5.0, 5.0}; test.map.jumpTo(CameraOptions().withCenter(center).withZoom(3.0)); // Batch conversion of pixels to latLngs - const std::vector batchLatLngs = - test.map.latLngsForPixels({ScreenCoordinate(0, 0), - ScreenCoordinate(viewSize.width, viewSize.height), - ScreenCoordinate(viewSize.width, 0), - ScreenCoordinate(0, viewSize.height)}); + const std::vector batchLatLngs = test.map.latLngsForPixels( + {ScreenCoordinate(0, 0), + ScreenCoordinate(viewSize.width, viewSize.height), + ScreenCoordinate(viewSize.width, 0), + ScreenCoordinate(0, viewSize.height)} + ); ASSERT_EQ(4, batchLatLngs.size()); // Single conversion of pixel to latLng @@ -493,28 +507,29 @@ TEST(Annotations, ViewFrustumCulling) { std::vector ids; for (auto latLng : latLngs) { - ids.push_back( - test.map.addAnnotation(SymbolAnnotation{{latLng.longitude(), latLng.latitude()}, "default_marker"})); + ids.push_back(test.map.addAnnotation(SymbolAnnotation{{latLng.longitude(), latLng.latitude()}, "default_marker"} + )); } std::vector>> expectedVisibleForCamera = { // Start with all markers visible. - { CameraOptions(), { 0, 1, 2, 3, 4 } }, + {CameraOptions(), {0, 1, 2, 3, 4}}, // Move center to topLeft: only former center and top left (now center) are visible. - { CameraOptions().withCenter(tl), { 0, 4 } }, + {CameraOptions().withCenter(tl), {0, 4}}, // Reset center. With pitch: only top row markers and center are visible. - { CameraOptions().withCenter(center).withPitch(45), { 0, 1, 4 } }, + {CameraOptions().withCenter(center).withPitch(45), {0, 1, 4}}, // Reset pitch, and use padding to move viewport center: only topleft and center are visible. - { CameraOptions().withPitch(0).withPadding(EdgeInsets { viewSize.height * 0.5, viewSize.width * 0.5, 0, 0 }), { 0, 4 } }, + {CameraOptions().withPitch(0).withPadding(EdgeInsets{viewSize.height * 0.5, viewSize.width * 0.5, 0, 0}), + {0, 4}}, // Use opposite padding to move viewport center: only bottom right and center are visible. - { CameraOptions().withPitch(0).withPadding(EdgeInsets { 0, 0, viewSize.height * 0.5, viewSize.width * 0.5 }), { 3, 4 } }, + {CameraOptions().withPitch(0).withPadding(EdgeInsets{0, 0, viewSize.height * 0.5, viewSize.width * 0.5}), + {3, 4}}, // Use top padding to move viewport center: top row and center are visible. - { CameraOptions().withPitch(0).withPadding(EdgeInsets { viewSize.height * 0.5, 0, 0, 0 }), { 0, 1, 4 } }, + {CameraOptions().withPitch(0).withPadding(EdgeInsets{viewSize.height * 0.5, 0, 0, 0}), {0, 1, 4}}, // Use bottom padding: only bottom right and center are visible. - { CameraOptions().withPitch(0).withPadding(EdgeInsets { 0, 0, viewSize.height * 0.5, 0 }), { 2, 3, 4 } }, + {CameraOptions().withPitch(0).withPadding(EdgeInsets{0, 0, viewSize.height * 0.5, 0}), {2, 3, 4}}, // Left padding and pitch: top left, bottom left and center are visible. - { CameraOptions().withPitch(45).withPadding(EdgeInsets { 0, viewSize.width * 0.5, 0, 0 }), { 0, 2, 4 } } - }; + {CameraOptions().withPitch(45).withPadding(EdgeInsets{0, viewSize.width * 0.5, 0, 0}), {0, 2, 4}}}; for (unsigned i = 0; i < expectedVisibleForCamera.size(); i++) { auto testCase = expectedVisibleForCamera[i]; @@ -522,9 +537,15 @@ TEST(Annotations, ViewFrustumCulling) { test.frontend.render(test.map); auto features = test.frontend.getRenderer()->queryRenderedFeatures(box, {}); for (uint64_t id : testCase.second) { // testCase.second is vector of ids expected. - EXPECT_NE(std::find_if(features.begin(), features.end(), [&id](auto feature) { - return id == feature.id.template get(); - }), features.end()) << "Point with id " << id << " is missing in test case " << i; + EXPECT_NE( + std::find_if( + features.begin(), + features.end(), + [&id](auto feature) { return id == feature.id.template get(); } + ), + features.end() + ) << "Point with id " + << id << " is missing in test case " << i; EXPECT_EQ(features.size(), testCase.second.size()) << " in test case " << i; } } @@ -550,7 +571,6 @@ TEST(Annotations, DebugEmpty) { test.checkRendering("debug_empty"); } - TEST(Annotations, DebugSparse) { if (gfx::Backend::GetType() != gfx::Backend::Type::OpenGL) { return; @@ -564,7 +584,7 @@ TEST(Annotations, DebugSparse) { test.map.setDebug(MapDebugOptions::TileBorders); test.map.jumpTo(CameraOptions().withZoom(1.0)); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point(10, 10), "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point(10, 10), "default_marker"}); test.checkRendering("debug_sparse"); } @@ -572,10 +592,10 @@ TEST(Annotations, DebugSparse) { TEST(Annotations, ChangeMaxZoom) { AnnotationTest test; - LineString line = {{ { 0, 0 }, { 45, 45 }, { 30, 0 } }}; - LineAnnotation annotation { line }; + LineString line = {{{0, 0}, {45, 45}, {30, 0}}}; + LineAnnotation annotation{line}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.setBounds(BoundOptions().withMaxZoom(6)); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); diff --git a/test/api/api_misuse.test.cpp b/test/api/api_misuse.test.cpp index 549f26c8d42..01cd1e2d2b9 100644 --- a/test/api/api_misuse.test.cpp +++ b/test/api/api_misuse.test.cpp @@ -13,23 +13,25 @@ using namespace mbgl; - TEST(API, RenderWithoutCallback) { FixtureLog log; util::RunLoop loop; - HeadlessFrontend frontend { 1 }; + HeadlessFrontend frontend{1}; - auto map = std::make_unique(frontend, MapObserver::nullObserver(), - std::make_shared(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())); + auto map = std::make_unique( + frontend, + MapObserver::nullObserver(), + std::make_shared(), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()) + ); map->renderStill(nullptr); // Force Map thread to join. map.reset(); - const FixtureLogObserver::LogMessage logMessage { + const FixtureLogObserver::LogMessage logMessage{ EventSeverity::Error, Event::General, int64_t(-1), diff --git a/test/api/custom_geometry_source.test.cpp b/test/api/custom_geometry_source.test.cpp index 93cf6ba56e1..660c58144bf 100644 --- a/test/api/custom_geometry_source.test.cpp +++ b/test/api/custom_geometry_source.test.cpp @@ -19,20 +19,24 @@ using namespace mbgl::style; TEST(CustomGeometrySource, Grid) { util::RunLoop loop; - HeadlessFrontend frontend { 1 }; - Map map(frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), - ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets")); + HeadlessFrontend frontend{1}; + Map map( + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), + ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets") + ); map.getStyle().loadJSON(util::read_file("test/fixtures/api/water.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 37.8, -122.5 }).withZoom(10.0)); + map.jumpTo(CameraOptions().withCenter(LatLng{37.8, -122.5}).withZoom(10.0)); CustomGeometrySource::Options options; options.fetchTileFunction = [&map](const mbgl::CanonicalTileID& tileID) { double gridSpacing = 0.1; FeatureCollection features; const LatLngBounds bounds(tileID); - for (double y = ceil(bounds.north() / gridSpacing) * gridSpacing; y >= floor(bounds.south() / gridSpacing) * gridSpacing; y -= gridSpacing) { - + for (double y = ceil(bounds.north() / gridSpacing) * gridSpacing; + y >= floor(bounds.south() / gridSpacing) * gridSpacing; + y -= gridSpacing) { mapbox::geojson::line_string gridLine; gridLine.emplace_back(bounds.west(), y); gridLine.emplace_back(bounds.east(), y); @@ -40,14 +44,16 @@ TEST(CustomGeometrySource, Grid) { features.emplace_back(gridLine); } - for (double x = floor(bounds.west() / gridSpacing) * gridSpacing; x <= ceil(bounds.east() / gridSpacing) * gridSpacing; x += gridSpacing) { + for (double x = floor(bounds.west() / gridSpacing) * gridSpacing; + x <= ceil(bounds.east() / gridSpacing) * gridSpacing; + x += gridSpacing) { mapbox::geojson::line_string gridLine; gridLine.emplace_back(x, bounds.south()); gridLine.emplace_back(x, bounds.north()); - + features.emplace_back(gridLine); } - auto source = static_cast(map.getStyle().getSource("custom")); + auto source = static_cast(map.getStyle().getSource("custom")); if (source) { source->setTileData(tileID, features); } @@ -57,11 +63,11 @@ TEST(CustomGeometrySource, Grid) { auto fillLayer = std::make_unique("landcover", "mapbox"); fillLayer->setSourceLayer("landcover"); - fillLayer->setFillColor(Color{ 1.0, 1.0, 0.0, 1.0 }); + fillLayer->setFillColor(Color{1.0, 1.0, 0.0, 1.0}); map.getStyle().addLayer(std::move(fillLayer)); auto layer = std::make_unique("grid", "custom"); - layer->setLineColor(Color{ 1.0, 1.0, 1.0, 1.0 }); + layer->setLineColor(Color{1.0, 1.0, 1.0, 1.0}); map.getStyle().addLayer(std::move(layer)); test::checkImage("test/fixtures/custom_geometry_source/grid", frontend.render(map).image, 0.0006, 0.1); diff --git a/test/api/custom_layer.test.cpp b/test/api/custom_layer.test.cpp index 2cfa7bf4004..e6c50b3ba66 100644 --- a/test/api/custom_layer.test.cpp +++ b/test/api/custom_layer.test.cpp @@ -52,7 +52,7 @@ class TestLayer : public mbgl::style::CustomLayerHost { MBGL_CHECK_ERROR(glLinkProgram(program)); a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); - GLfloat triangle[] = { 0, 0.5, 0.5, -0.5, -0.5, -0.5 }; + GLfloat triangle[] = {0, 0.5, 0.5, -0.5, -0.5, -0.5}; MBGL_CHECK_ERROR(glGenBuffers(1, &buffer)); MBGL_CHECK_ERROR(glBindBuffer(GL_ARRAY_BUFFER, buffer)); MBGL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(GLfloat), triangle, GL_STATIC_DRAW)); @@ -69,14 +69,14 @@ class TestLayer : public mbgl::style::CustomLayerHost { void contextLost() override {} void deinitialize() override { - if (program) { - MBGL_CHECK_ERROR(glDeleteBuffers(1, &buffer)); - MBGL_CHECK_ERROR(glDetachShader(program, vertexShader)); - MBGL_CHECK_ERROR(glDetachShader(program, fragmentShader)); - MBGL_CHECK_ERROR(glDeleteShader(vertexShader)); - MBGL_CHECK_ERROR(glDeleteShader(fragmentShader)); - MBGL_CHECK_ERROR(glDeleteProgram(program)); - } + if (program) { + MBGL_CHECK_ERROR(glDeleteBuffers(1, &buffer)); + MBGL_CHECK_ERROR(glDetachShader(program, vertexShader)); + MBGL_CHECK_ERROR(glDetachShader(program, fragmentShader)); + MBGL_CHECK_ERROR(glDeleteShader(vertexShader)); + MBGL_CHECK_ERROR(glDeleteShader(fragmentShader)); + MBGL_CHECK_ERROR(glDeleteProgram(program)); + } } GLuint program = 0; @@ -93,19 +93,20 @@ TEST(CustomLayer, Basic) { util::RunLoop loop; - HeadlessFrontend frontend { 1 }; - Map map(frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), - ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets")); + HeadlessFrontend frontend{1}; + Map map( + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), + ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets") + ); map.getStyle().loadJSON(util::read_file("test/fixtures/api/water.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 37.8, -122.5 }).withZoom(10.0)); - map.getStyle().addLayer(std::make_unique( - "custom", - std::make_unique())); + map.jumpTo(CameraOptions().withCenter(LatLng{37.8, -122.5}).withZoom(10.0)); + map.getStyle().addLayer(std::make_unique("custom", std::make_unique())); auto layer = std::make_unique("landcover", "mapbox"); layer->setSourceLayer("landcover"); - layer->setFillColor(Color{ 1.0, 1.0, 0.0, 1.0 }); + layer->setFillColor(Color{1.0, 1.0, 0.0, 1.0}); map.getStyle().addLayer(std::move(layer)); test::checkImage("test/fixtures/custom_layer/basic", frontend.render(map).image, 0.0006, 0.1); diff --git a/test/api/query.test.cpp b/test/api/query.test.cpp index 44724d7fdaa..57cac0f9b05 100644 --- a/test/api/query.test.cpp +++ b/test/api/query.test.cpp @@ -26,21 +26,25 @@ class QueryTest { public: QueryTest() { map.getStyle().loadJSON(util::read_file("test/fixtures/api/query_style.json")); - map.getStyle().addImage(std::make_unique("test-icon", - decodeImage(util::read_file("test/fixtures/sprites/default_marker.png")), 1.0f)); + map.getStyle().addImage(std::make_unique( + "test-icon", decodeImage(util::read_file("test/fixtures/sprites/default_marker.png")), 1.0f + )); frontend.render(map); } util::RunLoop loop; std::shared_ptr fileSource = std::make_shared(); - HeadlessFrontend frontend { 1 }; - MapAdapter map { frontend, MapObserver::nullObserver(), fileSource, - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())}; + HeadlessFrontend frontend{1}; + MapAdapter map{ + frontend, + MapObserver::nullObserver(), + fileSource, + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())}; }; std::vector getTopClusterFeature(QueryTest& test) { - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://url"s, resource.url); Response response; response.data = std::make_unique(util::read_file("test/fixtures/supercluster/places.json"s)); @@ -65,9 +69,8 @@ std::vector getTopClusterFeature(QueryTest& test) { test.frontend.render(test.map); auto screenCoordinate = test.map.pixelForLatLng(coordinate); - const RenderedQueryOptions queryOptions({{{ "cluster_layer"s}}, {}}); - return test.frontend.getRenderer()->queryRenderedFeatures(screenCoordinate, - queryOptions); + const RenderedQueryOptions queryOptions({{{"cluster_layer"s}}, {}}); + return test.frontend.getRenderer()->queryRenderedFeatures(screenCoordinate, queryOptions); } } // end namespace @@ -97,18 +100,18 @@ TEST(Query, QueryRenderedFeatures) { TEST(Query, QueryRenderedFeaturesFilterLayer) { QueryTest test; - auto zz = test.map.pixelForLatLng({ 0, 0 }); + auto zz = test.map.pixelForLatLng({0, 0}); - auto features1 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "layer1"}}, {}}); + auto features1 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"layer1"}}, {}}); EXPECT_EQ(features1.size(), 1u); - auto features2 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "layer1", "layer2" }}, {}}); + auto features2 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"layer1", "layer2"}}, {}}); EXPECT_EQ(features2.size(), 2u); - auto features3 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "foobar" }}, {}}); + auto features3 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"foobar"}}, {}}); EXPECT_EQ(features3.size(), 0u); - auto features4 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "foobar", "layer3" }}, {}}); + auto features4 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"foobar", "layer3"}}, {}}); EXPECT_EQ(features4.size(), 1u); } @@ -116,18 +119,18 @@ TEST(Query, QueryRenderedFeaturesFilter) { using namespace mbgl::style::expression::dsl; QueryTest test; - auto zz = test.map.pixelForLatLng({ 0, 0 }); + auto zz = test.map.pixelForLatLng({0, 0}); const Filter eqFilter(eq(get("key1"), literal("value1"))); - auto features1 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{}, { eqFilter }}); + auto features1 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{}, {eqFilter}}); EXPECT_EQ(features1.size(), 1u); const Filter idNotEqFilter(ne(id(), literal("feature1"))); - auto features2 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "layer4" }}, { idNotEqFilter }}); + auto features2 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"layer4"}}, {idNotEqFilter}}); EXPECT_EQ(features2.size(), 0u); const Filter gtFilter(gt(number(get("key2")), literal(1.0))); - auto features3 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{ }, { gtFilter }}); + auto features3 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{}, {gtFilter}}); EXPECT_EQ(features3.size(), 1u); } @@ -164,7 +167,7 @@ TEST(Query, QuerySourceFeaturesOptionValidation) { // VectorSource, requires a layer id features = test.frontend.getRenderer()->querySourceFeatures("source5"); ASSERT_EQ(features.size(), 0u); - + // RasterSource, not supported features = test.frontend.getRenderer()->querySourceFeatures("source6"); ASSERT_EQ(features.size(), 0u); @@ -176,25 +179,22 @@ TEST(Query, QuerySourceFeaturesFilter) { QueryTest test; const Filter eqFilter(eq(get("key1"), literal("value1"))); - auto features1 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, { eqFilter }}); + auto features1 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, {eqFilter}}); EXPECT_EQ(features1.size(), 1u); const Filter idNotEqFilter(ne(id(), literal("feature1"))); - auto features2 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, { idNotEqFilter }}); + auto features2 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, {idNotEqFilter}}); EXPECT_EQ(features2.size(), 0u); const Filter gtFilter(gt(number(get("key2")), literal(1.0))); - auto features3 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, { gtFilter }}); + auto features3 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, {gtFilter}}); EXPECT_EQ(features3.size(), 1u); } TEST(Query, QueryFeatureExtensionsInvalidExtension) { QueryTest test; - auto unknownExt = test.frontend.getRenderer()->queryFeatureExtensions("source4"s, - {}, - "unknown"s, - "children"s); + auto unknownExt = test.frontend.getRenderer()->queryFeatureExtensions("source4"s, {}, "unknown"s, "children"s); auto unknownValue = unknownExt.get(); EXPECT_TRUE(unknownValue.is()); } @@ -206,14 +206,13 @@ TEST(Query, QueryFeatureExtensionsSuperclusterChildren) { EXPECT_EQ(topClusterFeature.size(), 1u); const auto featureProps = topClusterFeature[0].properties; auto clusterId = featureProps.find("cluster_id"s); - auto cluster = featureProps.find("cluster"s); + auto cluster = featureProps.find("cluster"s); EXPECT_TRUE(clusterId != featureProps.end()); EXPECT_TRUE(cluster != featureProps.end()); - auto queryChildren = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "children"s); + auto queryChildren = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "children"s + ); EXPECT_TRUE(queryChildren.is()); auto children = queryChildren.get(); @@ -235,22 +234,18 @@ TEST(Query, QueryFeatureExtensionsSuperclusterExpansionZoom) { auto topClusterFeature = getTopClusterFeature(test); EXPECT_EQ(topClusterFeature.size(), 1u); - auto queryChildren = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "children"s); + auto queryChildren = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "children"s + ); auto children = queryChildren.get(); + auto queryExpansionZoom1 = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "expansion-zoom"s + ); - auto queryExpansionZoom1 = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "expansion-zoom"s); - - auto queryExpansionZoom2 = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - children[3], - "supercluster"s, - "expansion-zoom"s); + auto queryExpansionZoom2 = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, children[3], "supercluster"s, "expansion-zoom"s + ); auto zoomValue1 = queryExpansionZoom1.get(); auto zoomValue2 = queryExpansionZoom2.get(); EXPECT_TRUE(zoomValue1.is()); @@ -265,21 +260,18 @@ TEST(Query, QueryFeatureExtensionsSuperclusterLeaves) { EXPECT_EQ(topClusterFeature.size(), 1u); // Get leaves for cluster 1, with default limit 10, offset 0. - auto queryClusterLeaves = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "leaves"s); + auto queryClusterLeaves = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "leaves"s + ); EXPECT_TRUE(queryClusterLeaves.is()); auto leaves = queryClusterLeaves.get(); EXPECT_EQ(leaves.size(), 10u); // Get leaves for cluster 1, with limit 3, offset 0. - const std::map limitOpts = { {"limit"s, static_cast(3u)} }; - auto queryClusterLeavesLimit3 = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "leaves"s, - limitOpts); + const std::map limitOpts = {{"limit"s, static_cast(3u)}}; + auto queryClusterLeavesLimit3 = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "leaves"s, limitOpts + ); auto limitLeaves3 = queryClusterLeavesLimit3.get(); EXPECT_EQ(limitLeaves3.size(), 3u); @@ -288,13 +280,11 @@ TEST(Query, QueryFeatureExtensionsSuperclusterLeaves) { EXPECT_EQ(limitLeaves3[2].properties["name"].get(), "Cape Fear"s); // Get leaves for cluster 1, with limit 3, offset 3. - const std::map offsetOpts = { {"limit"s, static_cast(3u)}, - {"offset"s, static_cast(3u)} }; - auto queryClusterLeavesOffset3 = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "leaves"s, - offsetOpts); + const std::map offsetOpts = { + {"limit"s, static_cast(3u)}, {"offset"s, static_cast(3u)}}; + auto queryClusterLeavesOffset3 = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "leaves"s, offsetOpts + ); auto offsetLeaves3 = queryClusterLeavesOffset3.get(); EXPECT_EQ(offsetLeaves3.size(), 3u); EXPECT_EQ(offsetLeaves3[0].properties["name"].get(), "Cape Hatteras"s); diff --git a/test/api/recycle_map.cpp b/test/api/recycle_map.cpp index bfccaff757d..d406366d163 100644 --- a/test/api/recycle_map.cpp +++ b/test/api/recycle_map.cpp @@ -18,28 +18,32 @@ using namespace mbgl; using namespace mbgl::style; - TEST(API, RecycleMapUpdateImages) { util::RunLoop loop; - HeadlessFrontend frontend { 1 }; - auto map = std::make_unique(frontend, MapObserver::nullObserver(), - std::make_shared(ResourceOptions::Default(), ClientOptions()), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())); + HeadlessFrontend frontend{1}; + auto map = std::make_unique( + frontend, + MapObserver::nullObserver(), + std::make_shared(ResourceOptions::Default(), ClientOptions()), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()) + ); EXPECT_TRUE(map); auto loadStyle = [&](auto markerName, auto markerPath) { auto source = std::make_unique("geometry"); - source->setGeoJSON( Geometry{ Point{ 0, 0 } } ); + source->setGeoJSON(Geometry{Point{0, 0}}); auto layer = std::make_unique("geometry", "geometry"); - layer->setIconImage({ markerName }); + layer->setIconImage({markerName}); map->getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); map->getStyle().addSource(std::move(source)); map->getStyle().addLayer(std::move(layer)); - map->getStyle().addImage(std::make_unique(markerName, decodeImage(util::read_file(markerPath)), 1.0f)); + map->getStyle().addImage( + std::make_unique(markerName, decodeImage(util::read_file(markerPath)), 1.0f) + ); }; // default marker diff --git a/test/geometry/dem_data.test.cpp b/test/geometry/dem_data.test.cpp index 24893d16edf..329df192db2 100644 --- a/test/geometry/dem_data.test.cpp +++ b/test/geometry/dem_data.test.cpp @@ -9,8 +9,8 @@ using namespace mbgl; auto fakeImage = [](Size s) { PremultipliedImage img = PremultipliedImage(s); - for (size_t i = 0; i < img.bytes(); i ++) { - img.data[i] = (i+1) % 4 == 0 ? 1 : std::rand() % 255; + for (size_t i = 0; i < img.bytes(); i++) { + img.data[i] = (i + 1) % 4 == 0 ? 1 : std::rand() % 255; } return img; }; @@ -21,7 +21,7 @@ TEST(DEMData, ConstructorMapbox) { EXPECT_EQ(demdata.dim, 16); EXPECT_EQ(demdata.stride, 18); - EXPECT_EQ(demdata.getImage()->bytes(), size_t(18*18*4)); + EXPECT_EQ(demdata.getImage()->bytes(), size_t(18 * 18 * 4)); }; TEST(DEMData, ConstructorTerrarium) { @@ -30,19 +30,18 @@ TEST(DEMData, ConstructorTerrarium) { EXPECT_EQ(demdata.dim, 16); EXPECT_EQ(demdata.stride, 18); - EXPECT_EQ(demdata.getImage()->bytes(), size_t(18*18*4)); + EXPECT_EQ(demdata.getImage()->bytes(), size_t(18 * 18 * 4)); }; TEST(DEMData, InitialBackfill) { - PremultipliedImage image1 = fakeImage({4, 4}); DEMData dem1(image1, Tileset::DEMEncoding::Mapbox); bool nonempty = true; // checking that a 1 px border around the fake image has been populated // with a non-empty pixel value - for (int x = -1; x < 5; x++){ - for (int y = -1; y < 5; y ++) { + for (int x = -1; x < 5; x++) { + for (int y = -1; y < 5; y++) { if (dem1.get(x, y) == -65536) { nonempty = false; break; @@ -75,7 +74,7 @@ TEST(DEMData, InitialBackfill) { } } } - //horizontal border of DEM data is initially equal to next row of data + // horizontal border of DEM data is initially equal to next row of data EXPECT_TRUE(horizontalBorderMatch); // -1, 1 corner initially equal to closest corner data @@ -100,7 +99,6 @@ TEST(DEMData, BackfillNeighbor) { // dx = -1, dy = 0, so the left edge of dem1 should equal the right edge of dem0 // backfills Left neighbor EXPECT_TRUE(dem0.get(-1, y) == dem1.get(3, y)); - } dem0.backfillBorder(dem1, 0, -1); diff --git a/test/geometry/line_atlas.test.cpp b/test/geometry/line_atlas.test.cpp index 1d817220e15..f4f3f5920f9 100644 --- a/test/geometry/line_atlas.test.cpp +++ b/test/geometry/line_atlas.test.cpp @@ -22,8 +22,8 @@ TEST(LineAtlas, Random) { for (size_t i = 0; i < count; i++) { dasharray.push_back(lengthDistribution(generator)); } - const LinePatternCap patternCap = - capStyleDistribution(generator) > 0 ? LinePatternCap::Round : LinePatternCap::Square; + const LinePatternCap patternCap = capStyleDistribution(generator) > 0 ? LinePatternCap::Round + : LinePatternCap::Square; atlas.getDashPatternTexture(dasharray, dasharray, patternCap); } diff --git a/test/gl/bucket.test.cpp b/test/gl/bucket.test.cpp index fd8644bfbcb..373f57c56a9 100644 --- a/test/gl/bucket.test.cpp +++ b/test/gl/bucket.test.cpp @@ -43,22 +43,24 @@ PropertyMap properties; } // namespace TEST(Buckets, CircleBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; - gl::Context context{ backend }; + gl::Context context{backend}; CircleBucket bucket{{}, MapMode::Static, 1.0}; ASSERT_FALSE(bucket.hasData()); ASSERT_FALSE(bucket.needsUpload()); // CircleBucket::addFeature() is a no-op. - GeometryCollection point { { { 0, 0 } } }; - bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::Point, point, properties}, - point, - {}, - PatternLayerMap(), - 0, - CanonicalTileID(0, 0, 0)); + GeometryCollection point{{{0, 0}}}; + bucket.addFeature( + StubGeometryTileFeature{{}, FeatureType::Point, point, properties}, + point, + {}, + PatternLayerMap(), + 0, + CanonicalTileID(0, 0, 0) + ); ASSERT_FALSE(bucket.hasData()); ASSERT_FALSE(bucket.needsUpload()); @@ -74,22 +76,24 @@ TEST(Buckets, CircleBucket) { } TEST(Buckets, FillBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; FillBucket::PossiblyEvaluatedLayoutProperties layout; - gl::Context context{ backend }; - FillBucket bucket { layout, {}, 5.0f, 1}; + gl::Context context{backend}; + FillBucket bucket{layout, {}, 5.0f, 1}; ASSERT_FALSE(bucket.hasData()); ASSERT_FALSE(bucket.needsUpload()); - GeometryCollection polygon { { { 0, 0 }, { 0, 1 }, { 1, 1 } } }; - bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::Polygon, polygon, properties}, - polygon, - {}, - PatternLayerMap(), - 0, - CanonicalTileID(0, 0, 0)); + GeometryCollection polygon{{{0, 0}, {0, 1}, {1, 1}}}; + bucket.addFeature( + StubGeometryTileFeature{{}, FeatureType::Polygon, polygon, properties}, + polygon, + {}, + PatternLayerMap(), + 0, + CanonicalTileID(0, 0, 0) + ); ASSERT_TRUE(bucket.hasData()); ASSERT_TRUE(bucket.needsUpload()); @@ -100,32 +104,36 @@ TEST(Buckets, FillBucket) { } TEST(Buckets, LineBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; LineBucket::PossiblyEvaluatedLayoutProperties layout; - gl::Context context{ backend }; - LineBucket bucket { layout, {}, 10.0f, 1 }; + gl::Context context{backend}; + LineBucket bucket{layout, {}, 10.0f, 1}; ASSERT_FALSE(bucket.hasData()); ASSERT_FALSE(bucket.needsUpload()); // Ignore invalid feature type. - GeometryCollection point { { { 0, 0 } } }; - bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::Point, point, properties}, - point, - {}, - PatternLayerMap(), - 0, - CanonicalTileID(0, 0, 0)); + GeometryCollection point{{{0, 0}}}; + bucket.addFeature( + StubGeometryTileFeature{{}, FeatureType::Point, point, properties}, + point, + {}, + PatternLayerMap(), + 0, + CanonicalTileID(0, 0, 0) + ); ASSERT_FALSE(bucket.hasData()); - GeometryCollection line { { { 0, 0 }, { 1, 1 } } }; - bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::LineString, line, properties}, - line, - {}, - PatternLayerMap(), - 1, - CanonicalTileID(0, 0, 0)); + GeometryCollection line{{{0, 0}, {1, 1}}}; + bucket.addFeature( + StubGeometryTileFeature{{}, FeatureType::LineString, line, properties}, + line, + {}, + PatternLayerMap(), + 1, + CanonicalTileID(0, 0, 0) + ); ASSERT_TRUE(bucket.hasData()); ASSERT_TRUE(bucket.needsUpload()); @@ -136,8 +144,8 @@ TEST(Buckets, LineBucket) { } TEST(Buckets, SymbolBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; auto layout = makeMutable(); bool iconsNeedLinear = false; @@ -146,21 +154,22 @@ TEST(Buckets, SymbolBucket) { std::vector symbolInstances; std::vector symbolRanges; - gl::Context context{ backend }; - SymbolBucket bucket{std::move(layout), - {}, - 16.0f, - 1.0f, - 0, - iconsNeedLinear, - sortFeaturesByY, - bucketLeaderID, - std::move(symbolInstances), - std::move(symbolRanges), - 1.0f, - false, - {}, - false /*iconsInText*/}; + gl::Context context{backend}; + SymbolBucket bucket{ + std::move(layout), + {}, + 16.0f, + 1.0f, + 0, + iconsNeedLinear, + sortFeaturesByY, + bucketLeaderID, + std::move(symbolInstances), + std::move(symbolRanges), + 1.0f, + false, + {}, + false /*iconsInText*/}; ASSERT_FALSE(bucket.hasIconData()); ASSERT_FALSE(bucket.hasSdfIconData()); ASSERT_FALSE(bucket.hasTextData()); @@ -172,13 +181,15 @@ TEST(Buckets, SymbolBucket) { ASSERT_FALSE(bucket.needsUpload()); // SymbolBucket::addFeature() is a no-op. - GeometryCollection point { { { 0, 0 } } }; - bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::Point, std::move(point), properties}, - point, - {}, - PatternLayerMap(), - 0, - CanonicalTileID(0, 0, 0)); + GeometryCollection point{{{0, 0}}}; + bucket.addFeature( + StubGeometryTileFeature{{}, FeatureType::Point, std::move(point), properties}, + point, + {}, + PatternLayerMap(), + 0, + CanonicalTileID(0, 0, 0) + ); ASSERT_FALSE(bucket.hasData()); ASSERT_FALSE(bucket.needsUpload()); @@ -194,14 +205,14 @@ TEST(Buckets, SymbolBucket) { } TEST(Buckets, RasterBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; - gl::Context context{ backend }; - PremultipliedImage rgba({ 1, 1 }); + gl::Context context{backend}; + PremultipliedImage rgba({1, 1}); // RasterBucket::hasData() is always true. - RasterBucket bucket = { std::move(rgba) }; + RasterBucket bucket = {std::move(rgba)}; ASSERT_TRUE(bucket.hasData()); ASSERT_TRUE(bucket.needsUpload()); @@ -215,7 +226,7 @@ TEST(Buckets, RasterBucket) { } TEST(Buckets, RasterBucketMaskEmpty) { - RasterBucket bucket{ nullptr }; + RasterBucket bucket{nullptr}; bucket.setMask({}); EXPECT_EQ((std::vector{}), bucket.vertices.vector()); EXPECT_EQ((std::vector{}), bucket.indices.vector()); @@ -225,8 +236,8 @@ TEST(Buckets, RasterBucketMaskEmpty) { } TEST(Buckets, RasterBucketMaskNoChildren) { - RasterBucket bucket{ nullptr }; - bucket.setMask({ CanonicalTileID{ 0, 0, 0 } }); + RasterBucket bucket{nullptr}; + bucket.setMask({CanonicalTileID{0, 0, 0}}); // A mask of 0/0/0 doesn't produce buffers since we're instead using the global shared buffers. EXPECT_EQ((std::vector{}), bucket.vertices.vector()); @@ -234,121 +245,159 @@ TEST(Buckets, RasterBucketMaskNoChildren) { EXPECT_EQ((SegmentVector{}), bucket.segments); } - TEST(Buckets, RasterBucketMaskTwoChildren) { - RasterBucket bucket{ nullptr }; - bucket.setMask( - { CanonicalTileID{ 1, 0, 0 }, CanonicalTileID{ 1, 1, 1 } }); - - EXPECT_EQ( - (std::vector{ - // 1/0/1 - RasterProgram::layoutVertex({ 0, 0 }, { 0, 0 }), - RasterProgram::layoutVertex({ 4096, 0 }, { 4096, 0 }), - RasterProgram::layoutVertex({ 0, 4096 }, { 0, 4096 }), - RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }), - - // 1/1/1 - RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }), - RasterProgram::layoutVertex({ 8192, 4096 }, { 8192, 4096 }), - RasterProgram::layoutVertex({ 4096, 8192 }, { 4096, 8192 }), - RasterProgram::layoutVertex({ 8192, 8192 }, { 8192, 8192 }), - }), - bucket.vertices.vector()); - - EXPECT_EQ( - (std::vector{ - // 1/0/1 - 0, 1, 2, - 1, 2, 3, - - // 1/1/1 - 4, 5, 6, - 5, 6, 7, - }), - bucket.indices.vector()); - - - SegmentVector expectedSegments; - expectedSegments.emplace_back(0, 0, 8, 12); - EXPECT_EQ(expectedSegments, bucket.segments); - } - - TEST(Buckets, RasterBucketMaskComplex) { - RasterBucket bucket{ nullptr }; - bucket.setMask( - { CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, CanonicalTileID{ 2, 2, 3 }, - CanonicalTileID{ 2, 3, 2 }, CanonicalTileID{ 3, 6, 7 }, CanonicalTileID{ 3, 7, 6 } }); - - EXPECT_EQ( - (std::vector{ - // 1/0/1 - RasterProgram::layoutVertex({ 0, 4096 }, { 0, 4096 }), - RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }), - RasterProgram::layoutVertex({ 0, 8192 }, { 0, 8192 }), - RasterProgram::layoutVertex({ 4096, 8192 }, { 4096, 8192 }), - - // 1/1/0 - RasterProgram::layoutVertex({ 4096, 0 }, { 4096, 0 }), - RasterProgram::layoutVertex({ 8192, 0 }, { 8192, 0 }), - RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }), - RasterProgram::layoutVertex({ 8192, 4096 }, { 8192, 4096 }), - - // 2/2/3 - RasterProgram::layoutVertex({ 4096, 6144 }, { 4096, 6144 }), - RasterProgram::layoutVertex({ 6144, 6144 }, { 6144, 6144 }), - RasterProgram::layoutVertex({ 4096, 8192 }, { 4096, 8192 }), - RasterProgram::layoutVertex({ 6144, 8192 }, { 6144, 8192 }), - - // 2/3/2 - RasterProgram::layoutVertex({ 6144, 4096 }, { 6144, 4096 }), - RasterProgram::layoutVertex({ 8192, 4096 }, { 8192, 4096 }), - RasterProgram::layoutVertex({ 6144, 6144 }, { 6144, 6144 }), - RasterProgram::layoutVertex({ 8192, 6144 }, { 8192, 6144 }), - - // 3/6/7 - RasterProgram::layoutVertex({ 6144, 7168 }, { 6144, 7168 }), - RasterProgram::layoutVertex({ 7168, 7168 }, { 7168, 7168 }), - RasterProgram::layoutVertex({ 6144, 8192 }, { 6144, 8192 }), - RasterProgram::layoutVertex({ 7168, 8192 }, { 7168, 8192 }), - - // 3/7/6 - RasterProgram::layoutVertex({ 7168, 6144 }, { 7168, 6144 }), - RasterProgram::layoutVertex({ 8192, 6144 }, { 8192, 6144 }), - RasterProgram::layoutVertex({ 7168, 7168 }, { 7168, 7168 }), - RasterProgram::layoutVertex({ 8192, 7168 }, { 8192, 7168 }), - }), - bucket.vertices.vector()); - - EXPECT_EQ( - (std::vector{ - // 1/0/1 - 0, 1, 2, - 1, 2, 3, - - // 1/1/0 - 4, 5, 6, - 5, 6, 7, - - // 2/2/3 - 8, 9, 10, - 9, 10, 11, - - // 2/3/2 - 12, 13, 14, - 13, 14, 15, - - // 3/6/7 - 16, 17, 18, - 17, 18, 19, - - // 3/7/6 - 20, 21, 22, - 21, 22, 23, - }), - bucket.indices.vector()); - - - SegmentVector expectedSegments; - expectedSegments.emplace_back(0, 0, 24, 36); - EXPECT_EQ(expectedSegments, bucket.segments); - } +TEST(Buckets, RasterBucketMaskTwoChildren) { + RasterBucket bucket{nullptr}; + bucket.setMask({CanonicalTileID{1, 0, 0}, CanonicalTileID{1, 1, 1}}); + + EXPECT_EQ( + (std::vector{ + // 1/0/1 + RasterProgram::layoutVertex({0, 0}, {0, 0}), + RasterProgram::layoutVertex({4096, 0}, {4096, 0}), + RasterProgram::layoutVertex({0, 4096}, {0, 4096}), + RasterProgram::layoutVertex({4096, 4096}, {4096, 4096}), + + // 1/1/1 + RasterProgram::layoutVertex({4096, 4096}, {4096, 4096}), + RasterProgram::layoutVertex({8192, 4096}, {8192, 4096}), + RasterProgram::layoutVertex({4096, 8192}, {4096, 8192}), + RasterProgram::layoutVertex({8192, 8192}, {8192, 8192}), + }), + bucket.vertices.vector() + ); + + EXPECT_EQ( + (std::vector{ + // 1/0/1 + 0, + 1, + 2, + 1, + 2, + 3, + + // 1/1/1 + 4, + 5, + 6, + 5, + 6, + 7, + }), + bucket.indices.vector() + ); + + SegmentVector expectedSegments; + expectedSegments.emplace_back(0, 0, 8, 12); + EXPECT_EQ(expectedSegments, bucket.segments); +} + +TEST(Buckets, RasterBucketMaskComplex) { + RasterBucket bucket{nullptr}; + bucket.setMask( + {CanonicalTileID{1, 0, 1}, + CanonicalTileID{1, 1, 0}, + CanonicalTileID{2, 2, 3}, + CanonicalTileID{2, 3, 2}, + CanonicalTileID{3, 6, 7}, + CanonicalTileID{3, 7, 6}} + ); + + EXPECT_EQ( + (std::vector{ + // 1/0/1 + RasterProgram::layoutVertex({0, 4096}, {0, 4096}), + RasterProgram::layoutVertex({4096, 4096}, {4096, 4096}), + RasterProgram::layoutVertex({0, 8192}, {0, 8192}), + RasterProgram::layoutVertex({4096, 8192}, {4096, 8192}), + + // 1/1/0 + RasterProgram::layoutVertex({4096, 0}, {4096, 0}), + RasterProgram::layoutVertex({8192, 0}, {8192, 0}), + RasterProgram::layoutVertex({4096, 4096}, {4096, 4096}), + RasterProgram::layoutVertex({8192, 4096}, {8192, 4096}), + + // 2/2/3 + RasterProgram::layoutVertex({4096, 6144}, {4096, 6144}), + RasterProgram::layoutVertex({6144, 6144}, {6144, 6144}), + RasterProgram::layoutVertex({4096, 8192}, {4096, 8192}), + RasterProgram::layoutVertex({6144, 8192}, {6144, 8192}), + + // 2/3/2 + RasterProgram::layoutVertex({6144, 4096}, {6144, 4096}), + RasterProgram::layoutVertex({8192, 4096}, {8192, 4096}), + RasterProgram::layoutVertex({6144, 6144}, {6144, 6144}), + RasterProgram::layoutVertex({8192, 6144}, {8192, 6144}), + + // 3/6/7 + RasterProgram::layoutVertex({6144, 7168}, {6144, 7168}), + RasterProgram::layoutVertex({7168, 7168}, {7168, 7168}), + RasterProgram::layoutVertex({6144, 8192}, {6144, 8192}), + RasterProgram::layoutVertex({7168, 8192}, {7168, 8192}), + + // 3/7/6 + RasterProgram::layoutVertex({7168, 6144}, {7168, 6144}), + RasterProgram::layoutVertex({8192, 6144}, {8192, 6144}), + RasterProgram::layoutVertex({7168, 7168}, {7168, 7168}), + RasterProgram::layoutVertex({8192, 7168}, {8192, 7168}), + }), + bucket.vertices.vector() + ); + + EXPECT_EQ( + (std::vector{ + // 1/0/1 + 0, + 1, + 2, + 1, + 2, + 3, + + // 1/1/0 + 4, + 5, + 6, + 5, + 6, + 7, + + // 2/2/3 + 8, + 9, + 10, + 9, + 10, + 11, + + // 2/3/2 + 12, + 13, + 14, + 13, + 14, + 15, + + // 3/6/7 + 16, + 17, + 18, + 17, + 18, + 19, + + // 3/7/6 + 20, + 21, + 22, + 21, + 22, + 23, + }), + bucket.indices.vector() + ); + + SegmentVector expectedSegments; + expectedSegments.emplace_back(0, 0, 24, 36); + EXPECT_EQ(expectedSegments, bucket.segments); +} diff --git a/test/gl/context.test.cpp b/test/gl/context.test.cpp index 2135ed98620..f00aecfc8fe 100644 --- a/test/gl/context.test.cpp +++ b/test/gl/context.test.cpp @@ -73,13 +73,10 @@ struct Buffer { Buffer(std::vector data) { MBGL_CHECK_ERROR(glGenBuffers(1, &buffer)); MBGL_CHECK_ERROR(glBindBuffer(GL_ARRAY_BUFFER, buffer)); - MBGL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), - GL_STATIC_DRAW)); + MBGL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), GL_STATIC_DRAW)); } - ~Buffer() { - MBGL_CHECK_ERROR(glDeleteBuffers(1, &buffer)); - } + ~Buffer() { MBGL_CHECK_ERROR(glDeleteBuffers(1, &buffer)); } GLuint buffer = 0; }; @@ -93,25 +90,27 @@ TEST(GLContextMode, Shared) { HeadlessFrontend frontend{1, gfx::HeadlessBackend::SwapBehaviour::NoFlush, gfx::ContextMode::Shared}; - Map map(frontend, - MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), - ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets")); + Map map( + frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), + ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets") + ); map.getStyle().loadJSON(util::read_file("test/fixtures/api/water.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 37.8, -122.5 }).withZoom(10.0)); + map.jumpTo(CameraOptions().withCenter(LatLng{37.8, -122.5}).withZoom(10.0)); // Set transparent background layer. auto layer = map.getStyle().getLayer("background"); ASSERT_STREQ("background", layer->getTypeInfo()->type); - static_cast(layer)->setBackgroundColor( { { 1.0f, 0.0f, 0.0f, 0.5f } } ); + static_cast(layer)->setBackgroundColor({{1.0f, 0.0f, 0.0f, 0.5f}}); { // Custom rendering outside of GL Native render loop. - gfx::BackendScope scope { *frontend.getBackend() }; + gfx::BackendScope scope{*frontend.getBackend()}; frontend.getBackend()->getDefaultRenderable().getResource().bind(); Shader paintShader(vertexShaderSource, fragmentShaderSource); - Buffer triangleBuffer({ 0, 0.5, 0.5, -0.5, -0.5, -0.5 }); + Buffer triangleBuffer({0, 0.5, 0.5, -0.5, -0.5, -0.5}); MBGL_CHECK_ERROR(glUseProgram(paintShader.program)); MBGL_CHECK_ERROR(glBindBuffer(GL_ARRAY_BUFFER, triangleBuffer.buffer)); MBGL_CHECK_ERROR(glEnableVertexAttribArray(paintShader.a_pos)); diff --git a/test/gl/gl_functions.test.cpp b/test/gl/gl_functions.test.cpp index 762146ca908..229be216409 100644 --- a/test/gl/gl_functions.test.cpp +++ b/test/gl/gl_functions.test.cpp @@ -5,7 +5,6 @@ using namespace mbgl::platform; TEST(GLFunctions, OpenGLES) { - /* OpenGL ES 2.0 */ EXPECT_NE(glActiveTexture, nullptr); diff --git a/test/gl/object.test.cpp b/test/gl/object.test.cpp index 2e53b12a80a..2eceba84805 100644 --- a/test/gl/object.test.cpp +++ b/test/gl/object.test.cpp @@ -18,7 +18,10 @@ static bool setFlag = false; struct MockGLObject { using Type = bool; static const Type Default; - static Type Get() { getFlag = true; return true; } + static Type Get() { + getFlag = true; + return true; + } static void Set(const Type&) { setFlag = true; } }; @@ -45,10 +48,10 @@ TEST(GLObject, Value) { } TEST(GLObject, Store) { - gl::HeadlessBackend backend { { 256, 256 } }; - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend{{256, 256}}; + gfx::BackendScope scope{backend}; - gl::Context context{ backend }; + gl::Context context{backend}; EXPECT_TRUE(context.empty()); gl::UniqueTexture texture = context.createUniqueTexture(); diff --git a/test/include/mbgl/test/util.hpp b/test/include/mbgl/test/util.hpp index 2d8e5d62849..11f161142e1 100644 --- a/test/include/mbgl/test/util.hpp +++ b/test/include/mbgl/test/util.hpp @@ -13,33 +13,33 @@ #endif #if TARGET_OS_SIMULATOR - #define TEST_IS_SIMULATOR 1 +#define TEST_IS_SIMULATOR 1 #else - #define TEST_IS_SIMULATOR 0 +#define TEST_IS_SIMULATOR 0 #endif #if !TEST_IS_SIMULATOR && !CI_BUILD #define TEST_REQUIRES_ACCURATE_TIMING(name) name #else -#define TEST_REQUIRES_ACCURATE_TIMING(name) DISABLED_ ## name +#define TEST_REQUIRES_ACCURATE_TIMING(name) DISABLED_##name #endif #if !TEST_READ_ONLY #define TEST_REQUIRES_WRITE(name) name #else -#define TEST_REQUIRES_WRITE(name) DISABLED_ ## name +#define TEST_REQUIRES_WRITE(name) DISABLED_##name #endif #if TEST_HAS_SERVER #define TEST_REQUIRES_SERVER(name) name #else -#define TEST_REQUIRES_SERVER(name) DISABLED_ ## name +#define TEST_REQUIRES_SERVER(name) DISABLED_##name #endif #if !CI_BUILD #define TEST_DISABLED_ON_CI(name) name #else -#define TEST_DISABLED_ON_CI(name) DISABLED_ ## name +#define TEST_DISABLED_ON_CI(name) DISABLED_##name #endif #include @@ -68,10 +68,9 @@ class HttpServer { std::thread serverThread; }; -void checkImage(const std::string& base, - const PremultipliedImage& actual, - double imageThreshold = 0, - double pixelThreshold = 0); +void checkImage( + const std::string& base, const PremultipliedImage& actual, double imageThreshold = 0, double pixelThreshold = 0 +); } // namespace test } // namespace mbgl diff --git a/test/map/map.test.cpp b/test/map/map.test.cpp index b03d2aee188..b55d7b94498 100644 --- a/test/map/map.test.cpp +++ b/test/map/map.test.cpp @@ -51,9 +51,11 @@ class MapTest { MapAdapter map; MapTest(float pixelRatio = 1, MapMode mode = MapMode::Static) - : fileSource(std::make_shared(ResourceOptions::Default(), ClientOptions())) - , frontend(pixelRatio) - , map(frontend, observer, fileSource, + : fileSource(std::make_shared(ResourceOptions::Default(), ClientOptions())), + frontend(pixelRatio), + map(frontend, + observer, + fileSource, MapOptions().withMapMode(mode).withSize(frontend.getSize()).withPixelRatio(pixelRatio)) {} explicit MapTest(MapOptions options) @@ -62,23 +64,29 @@ class MapTest { map(frontend, observer, fileSource, options.withSize(frontend.getSize())) {} template - MapTest(const std::string& cachePath, - const std::string& assetPath, - float pixelRatio = 1, - MapMode mode = MapMode::Static, - typename std::enable_if_t>* = nullptr) - : fileSource(std::make_shared(ResourceOptions().withCachePath(cachePath).withAssetPath(assetPath), ClientOptions())), + MapTest( + const std::string& cachePath, + const std::string& assetPath, + float pixelRatio = 1, + MapMode mode = MapMode::Static, + typename std::enable_if_t>* = nullptr + ) + : fileSource( + std::make_shared(ResourceOptions().withCachePath(cachePath).withAssetPath(assetPath), ClientOptions()) + ), frontend(pixelRatio), map(frontend, observer, fileSource, MapOptions().withMapMode(mode).withSize(frontend.getSize()).withPixelRatio(pixelRatio)) {} - + template - MapTest(const ResourceOptions& resourceOptions, - const ClientOptions& clientOptions = ClientOptions(), - float pixelRatio = 1, - MapMode mode = MapMode::Static) + MapTest( + const ResourceOptions& resourceOptions, + const ClientOptions& clientOptions = ClientOptions(), + float pixelRatio = 1, + MapMode mode = MapMode::Static + ) : fileSource(std::make_shared(resourceOptions, clientOptions)), frontend(pixelRatio), map(frontend, @@ -94,13 +102,15 @@ TEST(Map, RendererState) { CameraOptions nullOptions; ASSERT_EQ(test.frontend.getCameraOptions(), nullOptions); - LatLng coordinate { 1, 1 }; + LatLng coordinate{1, 1}; double zoom = 12.0; double pitchInDegrees = 45.0; double bearingInDegrees = 30.0; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); - test.map.jumpTo(CameraOptions().withCenter(coordinate).withZoom(zoom).withPitch(pitchInDegrees).withBearing(bearingInDegrees)); + test.map.jumpTo( + CameraOptions().withCenter(coordinate).withZoom(zoom).withPitch(pitchInDegrees).withBearing(bearingInDegrees) + ); test.runLoop.runOnce(); test.frontend.render(test.map); @@ -114,7 +124,7 @@ TEST(Map, RendererState) { EXPECT_NEAR(*options.bearing, bearingInDegrees, 1e-7); { - const LatLng& latLng = test.frontend.latLngForPixel(ScreenCoordinate { 0, 0 }); + const LatLng& latLng = test.frontend.latLngForPixel(ScreenCoordinate{0, 0}); const ScreenCoordinate& point = test.frontend.pixelForLatLng(coordinate); EXPECT_NEAR(coordinate.latitude(), latLng.latitude(), 1e-1); EXPECT_NEAR(coordinate.longitude(), latLng.longitude(), 1e-1); @@ -124,7 +134,9 @@ TEST(Map, RendererState) { } // RendererState::hasImage - test.map.getStyle().addImage(std::make_unique("default_marker", decodeImage(util::read_file("test/fixtures/sprites/default_marker.png")), 1.0f)); + test.map.getStyle().addImage(std::make_unique( + "default_marker", decodeImage(util::read_file("test/fixtures/sprites/default_marker.png")), 1.0f + )); // The frontend has not yet been notified about the newly-added image. EXPECT_FALSE(test.frontend.hasImage("default_marker")); @@ -136,7 +148,7 @@ TEST(Map, RendererState) { // RendererState::hasSource auto source = std::make_unique("GeoJSONSource"); - source->setGeoJSON( Geometry{ Point{ 0, 0 } } ); + source->setGeoJSON(Geometry{Point{0, 0}}); test.map.getStyle().addSource(std::move(source)); // The frontend has not yet been notified about the newly-added source. @@ -162,10 +174,10 @@ TEST(Map, RendererState) { TEST(Map, LatLngBehavior) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 1.0, 1.0 }).withZoom(0.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{1.0, 1.0}).withZoom(0.0)); auto latLng1 = *test.map.getCameraOptions().center; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 1.0, 1.0 })); + test.map.jumpTo(CameraOptions().withCenter(LatLng{1.0, 1.0})); auto latLng2 = *test.map.getCameraOptions().center; ASSERT_DOUBLE_EQ(latLng1.latitude(), latLng2.latitude()); @@ -175,9 +187,9 @@ TEST(Map, LatLngBehavior) { TEST(Map, LatLngBoundsToCamera) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 40.712730, -74.005953 }).withZoom(16.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{40.712730, -74.005953}).withZoom(16.0)); - LatLngBounds bounds = LatLngBounds::hull({15.68169,73.499857}, {53.560711, 134.77281}); + LatLngBounds bounds = LatLngBounds::hull({15.68169, 73.499857}, {53.560711, 134.77281}); CameraOptions virtualCamera = test.map.cameraForLatLngBounds(bounds, {}); ASSERT_TRUE(bounds.contains(*virtualCamera.center)); @@ -187,9 +199,9 @@ TEST(Map, LatLngBoundsToCamera) { TEST(Map, LatLngBoundsToCameraWithExcessivePadding) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 40.712730, -74.005953 }).withZoom(16.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{40.712730, -74.005953}).withZoom(16.0)); - LatLngBounds bounds = LatLngBounds::hull({15.68169,73.499857}, {53.560711, 134.77281}); + LatLngBounds bounds = LatLngBounds::hull({15.68169, 73.499857}, {53.560711, 134.77281}); CameraOptions virtualCamera = test.map.cameraForLatLngBounds(bounds, {500, 0, 1200, 0}); ASSERT_TRUE(bounds.contains(*virtualCamera.center)); @@ -199,9 +211,9 @@ TEST(Map, LatLngBoundsToCameraWithExcessivePadding) { TEST(Map, LatLngBoundsToCameraWithBearing) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 40.712730, -74.005953 }).withZoom(16.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{40.712730, -74.005953}).withZoom(16.0)); - LatLngBounds bounds = LatLngBounds::hull({15.68169,73.499857}, {53.560711, 134.77281}); + LatLngBounds bounds = LatLngBounds::hull({15.68169, 73.499857}, {53.560711, 134.77281}); CameraOptions virtualCamera = test.map.cameraForLatLngBounds(bounds, {}, 35.0); ASSERT_TRUE(bounds.contains(*virtualCamera.center)); @@ -211,11 +223,11 @@ TEST(Map, LatLngBoundsToCameraWithBearing) { TEST(Map, LatLngBoundsToCameraWithBearingPitchAndPadding) { MapTest<> test; - - test.map.jumpTo(CameraOptions().withCenter(LatLng { 40.712730, -74.005953 }).withZoom(16.0)); - - LatLngBounds bounds = LatLngBounds::hull({15.68169,73.499857}, {53.560711, 134.77281}); - + + test.map.jumpTo(CameraOptions().withCenter(LatLng{40.712730, -74.005953}).withZoom(16.0)); + + LatLngBounds bounds = LatLngBounds::hull({15.68169, 73.499857}, {53.560711, 134.77281}); + CameraOptions virtualCamera = test.map.cameraForLatLngBounds(bounds, {}, 35, 20); ASSERT_TRUE(bounds.contains(*virtualCamera.center)); EXPECT_NEAR(*virtualCamera.zoom, 13.66272, 1e-5); @@ -229,8 +241,10 @@ TEST(Map, LatLngBoundsToCameraWithBearingPitchAndPadding) { ASSERT_DOUBLE_EQ(virtualCameraPadded.center->longitude(), virtualCamera.center->longitude()); const Size size = test.map.getMapOptions().size(); - const auto scaleChange = std::min((size.width - padding.left() - padding.right()) / size.width, - (size.height - padding.top() - padding.bottom()) / size.height); + const auto scaleChange = std::min( + (size.width - padding.left() - padding.right()) / size.width, + (size.height - padding.top() - padding.bottom()) / size.height + ); ASSERT_DOUBLE_EQ(*virtualCameraPadded.zoom, *virtualCamera.zoom + util::log2(scaleChange)); ASSERT_DOUBLE_EQ(*virtualCameraPadded.pitch, *virtualCamera.pitch); ASSERT_DOUBLE_EQ(*virtualCameraPadded.bearing, *virtualCamera.bearing); @@ -239,7 +253,7 @@ TEST(Map, LatLngBoundsToCameraWithBearingPitchAndPadding) { TEST(Map, LatLngsToCamera) { MapTest<> test; - std::vector latLngs{{ 40.712730, 74.005953 }, {15.68169,73.499857}, {30.82678, 83.4082}}; + std::vector latLngs{{40.712730, 74.005953}, {15.68169, 73.499857}, {30.82678, 83.4082}}; CameraOptions virtualCamera = test.map.cameraForLatLngs(latLngs, {}, 23.0); EXPECT_NEAR(virtualCamera.bearing.value_or(0), 23.0, 1e-5); @@ -250,9 +264,9 @@ TEST(Map, LatLngsToCamera) { TEST(Map, LatLngsToCameraWithBearingAndPitch) { MapTest<> test; - - std::vector latLngs{{ 40.712730, 74.005953 }, {15.68169,73.499857}, {30.82678, 83.4082}}; - + + std::vector latLngs{{40.712730, 74.005953}, {15.68169, 73.499857}, {30.82678, 83.4082}}; + CameraOptions virtualCamera = test.map.cameraForLatLngs(latLngs, {}, 23, 20); EXPECT_NEAR(virtualCamera.bearing.value_or(0), 23.0, 1e-5); EXPECT_NEAR(virtualCamera.zoom.value_or(0), 3.04378, 1e-5); @@ -290,12 +304,12 @@ TEST(Map, LatLngsToCameraWithBearingAndPitchMinMax) { TEST(Map, CameraToLatLngBounds) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 45, 90 }).withZoom(16.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{45, 90}).withZoom(16.0)); const Size size = test.map.getMapOptions().size(); LatLngBounds bounds = LatLngBounds::hull( - test.map.latLngForPixel({}), - test.map.latLngForPixel({ double(size.width), double(size.height) })); + test.map.latLngForPixel({}), test.map.latLngForPixel({double(size.width), double(size.height)}) + ); CameraOptions camera = test.map.getCameraOptions(); @@ -319,13 +333,17 @@ TEST(Map, CameraToLatLngBoundsUnwrappedWithRotation) { ASSERT_TRUE(test.map.latLngBoundsForCameraUnwrapped(camera).contains(test.map.latLngForPixel({}))); ASSERT_TRUE( - test.map.latLngBoundsForCameraUnwrapped(camera).contains(test.map.latLngForPixel({0.0, double(size.height)}))); + test.map.latLngBoundsForCameraUnwrapped(camera).contains(test.map.latLngForPixel({0.0, double(size.height)})) + ); ASSERT_TRUE( - test.map.latLngBoundsForCameraUnwrapped(camera).contains(test.map.latLngForPixel({double(size.width), 0.0}))); + test.map.latLngBoundsForCameraUnwrapped(camera).contains(test.map.latLngForPixel({double(size.width), 0.0})) + ); ASSERT_TRUE(test.map.latLngBoundsForCameraUnwrapped(camera).contains( - test.map.latLngForPixel({double(size.width), double(size.height)}))); + test.map.latLngForPixel({double(size.width), double(size.height)}) + )); ASSERT_TRUE(test.map.latLngBoundsForCameraUnwrapped(camera).contains( - test.map.latLngForPixel({double(size.width) / 2, double(size.height) / 2}))); + test.map.latLngForPixel({double(size.width) / 2, double(size.height) / 2}) + )); } TEST(Map, CameraToLatLngBoundsUnwrappedCrossDateLine) { @@ -339,13 +357,17 @@ TEST(Map, CameraToLatLngBoundsUnwrappedCrossDateLine) { ASSERT_TRUE(test.map.latLngBoundsForCameraUnwrapped(camera).contains(test.map.latLngForPixel({}), LatLng::Wrapped)); ASSERT_TRUE(test.map.latLngBoundsForCameraUnwrapped(camera).contains( - test.map.latLngForPixel({0.0, double(size.height)}), LatLng::Wrapped)); + test.map.latLngForPixel({0.0, double(size.height)}), LatLng::Wrapped + )); ASSERT_TRUE(test.map.latLngBoundsForCameraUnwrapped(camera).contains( - test.map.latLngForPixel({double(size.width), 0.0}), LatLng::Wrapped)); + test.map.latLngForPixel({double(size.width), 0.0}), LatLng::Wrapped + )); ASSERT_TRUE(test.map.latLngBoundsForCameraUnwrapped(camera).contains( - test.map.latLngForPixel({double(size.width), double(size.height)}), LatLng::Wrapped)); + test.map.latLngForPixel({double(size.width), double(size.height)}), LatLng::Wrapped + )); ASSERT_TRUE(test.map.latLngBoundsForCameraUnwrapped(camera).contains( - test.map.latLngForPixel({double(size.width) / 2, double(size.height) / 2}))); + test.map.latLngForPixel({double(size.width) / 2, double(size.height) / 2}) + )); ASSERT_TRUE(test.map.latLngBoundsForCameraUnwrapped(camera).crossesAntimeridian()); } @@ -353,27 +375,32 @@ TEST(Map, CameraToLatLngBoundsUnwrappedCrossDateLine) { TEST(Map, Offline) { MapTest test{":memory:", "."}; - auto expiredItem = [] (const std::string& path) { + auto expiredItem = [](const std::string& path) { Response response; response.data = std::make_shared(util::read_file("test/fixtures/map/offline/"s + path)); - response.expires = Timestamp{ Seconds(0) }; + response.expires = Timestamp{Seconds(0)}; return response; }; NetworkStatus::Set(NetworkStatus::Status::Offline); const std::string prefix = "http://127.0.0.1:3000/"; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{} + ); dbfs->forward(Resource::style(prefix + "style.json"), expiredItem("style.json"), [] {}); dbfs->forward(Resource::source(prefix + "streets.json"), expiredItem("streets.json"), [] {}); dbfs->forward(Resource::spriteJSON(prefix + "sprite", 1.0), expiredItem("sprite.json"), [] {}); dbfs->forward(Resource::spriteImage(prefix + "sprite", 1.0), expiredItem("sprite.png"), [] {}); - dbfs->forward(Resource::tile(prefix + "{z}-{x}-{y}.vector.pbf", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), - expiredItem("0-0-0.vector.pbf"), - [] {}); - dbfs->forward(Resource::glyphs(prefix + "{fontstack}/{range}.pbf", {{"Helvetica"}}, {0, 255}), - expiredItem("glyph.pbf"), - [&] { test.map.getStyle().loadURL(prefix + "style.json"); }); + dbfs->forward( + Resource::tile(prefix + "{z}-{x}-{y}.vector.pbf", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), + expiredItem("0-0-0.vector.pbf"), + [] {} + ); + dbfs->forward( + Resource::glyphs(prefix + "{fontstack}/{range}.pbf", {{"Helvetica"}}, {0, 255}), + expiredItem("glyph.pbf"), + [&] { test.map.getStyle().loadURL(prefix + "style.json"); } + ); #if ANDROID test::checkImage("test/fixtures/map/offline", test.frontend.render(test.map).image, 0.0046, 0.1); @@ -390,7 +417,7 @@ TEST(Map, SetStyleDefaultCamera) { EXPECT_DOUBLE_EQ(*camera.zoom, 0.0); EXPECT_DOUBLE_EQ(*camera.pitch, 0.0); EXPECT_DOUBLE_EQ(*camera.bearing, 0.0); - EXPECT_EQ(*camera.center, LatLng {}); + EXPECT_EQ(*camera.center, LatLng{}); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty-zoomed.json")); camera = test.map.getCameraOptions(); @@ -439,13 +466,13 @@ TEST(Map, DefaultBoundOptions) { } TEST(Map, MapOptions) { - float pixelRatio { 2 }; - MapTest<> test { pixelRatio, MapMode::Continuous }; + float pixelRatio{2}; + MapTest<> test{pixelRatio, MapMode::Continuous}; test.map.setNorthOrientation(NorthOrientation::Rightwards); test.map.setConstrainMode(ConstrainMode::None); test.map.setViewportMode(ViewportMode::FlippedY); - Size size = { 512, 512 }; + Size size = {512, 512}; test.map.setSize(size); auto options = test.map.getMapOptions(); @@ -488,8 +515,10 @@ TEST(Map, SetStyleInvalidJSON) { auto observer = Log::removeObserver(); auto flo = static_cast(observer.get()); - EXPECT_EQ(1u, flo->count({ EventSeverity::Error, Event::ParseStyle, -1, - "Failed to parse style: Invalid value. at offset 0" })); + EXPECT_EQ( + 1u, + flo->count({EventSeverity::Error, Event::ParseStyle, -1, "Failed to parse style: Invalid value. at offset 0"}) + ); auto unchecked = flo->unchecked(); EXPECT_TRUE(unchecked.empty()) << unchecked; } @@ -497,11 +526,9 @@ TEST(Map, SetStyleInvalidJSON) { TEST(Map, SetStyleInvalidURL) { MapTest<> test; - test.fileSource->styleResponse = [] (const Resource&) { + test.fileSource->styleResponse = [](const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; @@ -590,7 +617,7 @@ TEST(Map, StyleExpiredWithAnnotations) { test.fileSource->respond(Resource::Style, response); EXPECT_EQ(1u, test.fileSource->requests.size()); - test.map.addAnnotation(LineAnnotation { LineString {{ { 0, 0 }, { 10, 10 } }} }); + test.map.addAnnotation(LineAnnotation{LineString{{{0, 0}, {10, 10}}}}); EXPECT_EQ(1u, test.fileSource->requests.size()); test.fileSource->respond(Resource::Style, response); @@ -649,7 +676,7 @@ TEST(Map, MapLoadingSignal) { } TEST(Map, MapLoadedSignal) { - MapTest<> test { 1, MapMode::Continuous }; + MapTest<> test{1, MapMode::Continuous}; test.observer.didFinishLoadingMapCallback = [&]() { test.runLoop.stop(); @@ -703,9 +730,7 @@ TEST(Map, TEST_REQUIRES_SERVER(StyleNotFound)) { }; test.observer.didFailLoadingMapCallback = [&]() { - timer.start(Milliseconds(1100), 0s, [&] { - test.runLoop.stop(); - }); + timer.start(Milliseconds(1100), 0s, [&] { test.runLoop.stop(); }); }; test.runLoop.run(); @@ -721,7 +746,7 @@ TEST(Map, AddLayer) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); auto layer = std::make_unique("background"); - layer->setBackgroundColor({ { 1, 0, 0, 1 } }); + layer->setBackgroundColor({{1, 0, 0, 1}}); test.map.getStyle().addLayer(std::move(layer)); test::checkImage("test/fixtures/map/add_layer", test.frontend.render(test.map).image); @@ -733,7 +758,7 @@ TEST(Map, RemoveLayer) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); auto layer = std::make_unique("background"); - layer->setBackgroundColor({{ 1, 0, 0, 1 }}); + layer->setBackgroundColor({{1, 0, 0, 1}}); test.map.getStyle().addLayer(std::move(layer)); test.map.getStyle().removeLayer("background"); @@ -744,11 +769,11 @@ TEST(Map, DisabledSources) { MapTest<> test; // Always load the same image tile for raster layers. - test.fileSource->response = [] (const Resource& res) -> std::optional { + test.fileSource->response = [](const Resource& res) -> std::optional { if (res.url == "asset://tile.png") { Response response; - response.data = std::make_shared( - util::read_file("test/fixtures/map/disabled_layers/tile.png")); + response.data = std::make_shared(util::read_file("test/fixtures/map/disabled_layers/tile.png") + ); return {std::move(response)}; } return {}; @@ -829,8 +854,8 @@ TEST(Map, DontLoadUnneededTiles) { std::unordered_map referenceTiles = { // Since the layer's minzoom is 0.3, we shouldn't load tiles before z0.3 - { 0.3, { "a/0/0/0" } }, - { 1.0, { "a/1/1/0", "a/1/0/1", "a/1/0/0", "a/1/1/1" } }, + {0.3, {"a/0/0/0"}}, + {1.0, {"a/1/1/0", "a/1/0/1", "a/1/0/0", "a/1/1/1"}}, // Since the layer's maxzoom is 1.6, we should never load z2 or z3 tiles. }; @@ -863,18 +888,19 @@ TEST(Map, TEST_DISABLED_ON_CI(ContinuousRendering)) { HeadlessFrontend frontend(1); StubMapObserver observer; - observer.didFinishRenderingFrameCallback = [&] (MapObserver::RenderFrameStatus) { + observer.didFinishRenderingFrameCallback = [&](MapObserver::RenderFrameStatus) { // Start a timer that ends the test one second from now. If we are continuing to render // indefinitely, the timer will be constantly restarted and never trigger. Instead, the // emergency shutoff above will trigger, failing the test. - timer.start(1s, 0s, [&] { - runLoop.stop(); - }); + timer.start(1s, 0s, [&] { runLoop.stop(); }); }; - Map map(frontend, observer, - MapOptions().withMapMode(MapMode::Continuous).withSize(frontend.getSize()), - ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets")); + Map map( + frontend, + observer, + MapOptions().withMapMode(MapMode::Continuous).withSize(frontend.getSize()), + ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets") + ); map.getStyle().loadJSON(util::read_file("test/fixtures/api/water.json")); runLoop.run(); @@ -889,10 +915,13 @@ TEST(Map, NoContentTiles) { Response response; response.noContent = true; response.expires = util::now() + 1h; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{} + ); dbfs->forward( - Resource::tile("http://example.com/{z}-{x}-{y}.vector.pbf", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), response, [&] { + Resource::tile("http://example.com/{z}-{x}-{y}.vector.pbf", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), + response, + [&] { test.map.getStyle().loadJSON(R"STYLE({ "version": 8, "name": "Water", @@ -915,13 +944,14 @@ TEST(Map, NoContentTiles) { "source-layer": "water" }] })STYLE"); - }); + } + ); test::checkImage("test/fixtures/map/nocontent", test.frontend.render(test.map).image, 0.0015, 0.1); } // https://github.com/mapbox/mapbox-gl-native/issues/12432 TEST(Map, Issue12432) { - MapTest<> test { 1, MapMode::Continuous }; + MapTest<> test{1, MapMode::Continuous}; test.fileSource->tileResponse = [&](const Resource&) { Response result; @@ -970,7 +1000,7 @@ TEST(Map, Issue12432) { // https://github.com/mapbox/mapbox-gl-native/issues/15216 TEST(Map, Issue15216) { - MapTest<> test { 1.0f, MapMode::Continuous }; + MapTest<> test{1.0f, MapMode::Continuous}; test.map.getStyle().addSource(std::make_unique("ImageSource", std::array())); test.map.getStyle().addLayer(std::make_unique("RasterLayer", "ImageSource")); // Passes, if there is no assertion hit. @@ -980,7 +1010,7 @@ TEST(Map, Issue15216) { // https://github.com/mapbox/mapbox-gl-native/issues/15342 // Tests the fix for constant repaint caused by `RenderSource::hasFadingTiles()` returning `true` all the time. TEST(Map, Issue15342) { - MapTest<> test { 1, MapMode::Continuous }; + MapTest<> test{1, MapMode::Continuous}; test.fileSource->tileResponse = [&](const Resource&) { Response result; @@ -1016,7 +1046,7 @@ TEST(Map, Issue15342) { "layers": [] })STYLE"); test.map.jumpTo(CameraOptions().withZoom(20.0)); - test.observer.didFinishRenderingFrameCallback = [&] (MapObserver::RenderFrameStatus status) { + test.observer.didFinishRenderingFrameCallback = [&](MapObserver::RenderFrameStatus status) { if (!status.needsRepaint) { test.runLoop.stop(); } @@ -1187,7 +1217,8 @@ TEST(Map, PrefetchDeltaOverride) { "minzoom": 0, "maxzoom": 24 }] - })STYLE"); + })STYLE" + ); // Vector source auto vectorSource = std::make_unique("vector", Tileset{{"a/{z}/{x}/{y}"}}); @@ -1204,7 +1235,8 @@ TEST(Map, PrefetchDeltaOverride) { // Custom source CustomGeometrySource::Options options; - options.cancelTileFunction = [](const CanonicalTileID&) {}; + options.cancelTileFunction = [](const CanonicalTileID&) { + }; options.fetchTileFunction = [&requestedTiles, &test](const CanonicalTileID& tileID) { ++requestedTiles; auto* customSrc = static_cast(test.map.getStyle().getSource("custom")); @@ -1217,7 +1249,9 @@ TEST(Map, PrefetchDeltaOverride) { test.map.getStyle().addSource(std::move(customSource)); test.map.jumpTo(CameraOptions().withZoom(double(16))); - test.observer.didFinishLoadingMapCallback = [&] { test.runLoop.stop(); }; + test.observer.didFinishLoadingMapCallback = [&] { + test.runLoop.stop(); + }; test.runLoop.run(); // 2 sources x 4 tiles EXPECT_EQ(8, requestedTiles); @@ -1254,13 +1288,15 @@ TEST(Map, PrefetchDeltaOverrideCustomSource) { "minzoom": 0, "maxzoom": 24 }] - })STYLE"); + })STYLE" + ); std::atomic_int requestedTiles(0); auto makeCustomSource = [&requestedTiles, &test] { CustomGeometrySource::Options options; - options.cancelTileFunction = [](const CanonicalTileID&) {}; + options.cancelTileFunction = [](const CanonicalTileID&) { + }; options.fetchTileFunction = [&requestedTiles, &test](const CanonicalTileID& tileID) { ++requestedTiles; auto* source = static_cast(test.map.getStyle().getSource("custom")); @@ -1276,7 +1312,9 @@ TEST(Map, PrefetchDeltaOverrideCustomSource) { test.map.getStyle().addSource(std::move(customSource)); test.map.jumpTo(CameraOptions().withZoom(double(16))); - test.observer.didFinishLoadingMapCallback = [&] { test.runLoop.stop(); }; + test.observer.didFinishLoadingMapCallback = [&] { + test.runLoop.stop(); + }; test.runLoop.run(); EXPECT_EQ(4, requestedTiles); requestedTiles = 0; @@ -1330,20 +1368,25 @@ TEST(Map, TEST_REQUIRES_SERVER(ExpiredSpriteSheet)) { NetworkStatus::Set(NetworkStatus::Status::Online); - test.observer.didBecomeIdleCallback = [&test] { test.runLoop.stop(); }; + test.observer.didBecomeIdleCallback = [&test] { + test.runLoop.stop(); + }; }; NetworkStatus::Set(NetworkStatus::Status::Offline); const std::string prefix = "http://127.0.0.1:3000/online/"; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{} + ); dbfs->forward(Resource::style(prefix + "style.json"), makeResponse("style.json"), [] {}); dbfs->forward(Resource::source(prefix + "streets.json"), makeResponse("streets.json"), [] {}); dbfs->forward(Resource::spriteJSON(prefix + "sprite", 1.0), makeResponse("sprite.json", true), [] {}); dbfs->forward(Resource::spriteImage(prefix + "sprite", 1.0), makeResponse("sprite.png", true), [] {}); - dbfs->forward(Resource::tile(prefix + "{z}-{x}-{y}.vector.pbf", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), - makeResponse("0-0-0.vector.pbf"), - [&] { test.map.getStyle().loadURL(prefix + "style.json"); }); + dbfs->forward( + Resource::tile(prefix + "{z}-{x}-{y}.vector.pbf", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), + makeResponse("0-0-0.vector.pbf"), + [&] { test.map.getStyle().loadURL(prefix + "style.json"); } + ); test.runLoop.run(); } @@ -1367,7 +1410,8 @@ TEST(Map, SourceMinimumUpdateIntervalOverride) { "minzoom": 0, "maxzoom": 24 }] - })STYLE"); + })STYLE" + ); // Vector source auto vectorSourceA = std::make_unique("source-a", Tileset{{"a/{z}/{x}/{y}"}}); @@ -1398,7 +1442,9 @@ TEST(Map, SourceMinimumUpdateIntervalOverride) { }; test.map.jumpTo(CameraOptions().withZoom(double(16))); - test.observer.didFinishLoadingMapCallback = [&] { test.runLoop.stop(); }; + test.observer.didFinishLoadingMapCallback = [&] { + test.runLoop.stop(); + }; test.runLoop.run(); EXPECT_EQ(8, requestedTilesA); @@ -1473,7 +1519,7 @@ TEST(Map, DISABLED_PlacedSymbolData) { // Camera options will give exactly one tile (12/1171/1566) test.map.jumpTo(CameraOptions().withZoom(16).withCenter(LatLng{50.072317, 14.444827})); - + test.map.getStyle().loadURL("maptiler://maps/streets"); Size viewportSize = test.frontend.getSize(); test.frontend.getRenderer()->collectPlacedSymbolData(true); @@ -1558,7 +1604,9 @@ TEST(Map, VolatileSource) { test.map.getStyle().addSource(std::move(source)); test.map.jumpTo(CameraOptions().withZoom(16.0)); - test.observer.didFinishLoadingMapCallback = [&] { test.runLoop.stop(); }; + test.observer.didFinishLoadingMapCallback = [&] { + test.runLoop.stop(); + }; test.runLoop.run(); EXPECT_EQ(8, requestedTiles); } @@ -1573,10 +1621,10 @@ TEST(Map, ObserveShaderRegistration) { test.map.jumpTo(CameraOptions().withZoom(10)); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); - + test.frontend.render(test.map); EXPECT_EQ(observedRegistry, true); - + // Should not see it again observedRegistry = false; test.frontend.render(test.map); diff --git a/test/map/map_snapshotter.test.cpp b/test/map/map_snapshotter.test.cpp index 0ea31c5bbab..b09b6a8dd1f 100644 --- a/test/map/map_snapshotter.test.cpp +++ b/test/map/map_snapshotter.test.cpp @@ -33,11 +33,13 @@ TEST(MapSnapshotter, setStyleJSON) { }] })JSON"); - snapshotter.snapshot([&runLoop](std::exception_ptr ptr, - mbgl::PremultipliedImage image, - mbgl::MapSnapshotter::Attributions, - mbgl::MapSnapshotter::PointForFn, - mbgl::MapSnapshotter::LatLngForFn) { + snapshotter.snapshot([&runLoop]( + std::exception_ptr ptr, + mbgl::PremultipliedImage image, + mbgl::MapSnapshotter::Attributions, + mbgl::MapSnapshotter::PointForFn, + mbgl::MapSnapshotter::LatLngForFn + ) { EXPECT_EQ(nullptr, ptr); EXPECT_EQ(32, image.size.width); EXPECT_EQ(16, image.size.height); @@ -61,11 +63,13 @@ TEST(MapSnapshotter, setSize) { snapshotter.setSize(Size{16, 32}); - snapshotter.snapshot([&runLoop](std::exception_ptr ptr, - mbgl::PremultipliedImage image, - mbgl::MapSnapshotter::Attributions, - mbgl::MapSnapshotter::PointForFn, - mbgl::MapSnapshotter::LatLngForFn) { + snapshotter.snapshot([&runLoop]( + std::exception_ptr ptr, + mbgl::PremultipliedImage image, + mbgl::MapSnapshotter::Attributions, + mbgl::MapSnapshotter::PointForFn, + mbgl::MapSnapshotter::LatLngForFn + ) { EXPECT_EQ(nullptr, ptr); EXPECT_EQ(16, image.size.width); EXPECT_EQ(32, image.size.height); @@ -79,11 +83,13 @@ TEST(MapSnapshotter, TEST_REQUIRES_SERVER(setStyleURL)) { util::RunLoop runLoop; MapSnapshotter snapshotter(Size{64, 32}, 1.0f, ResourceOptions()); snapshotter.setStyleURL("http://127.0.0.1:3000/online/style.json"); - snapshotter.snapshot([&runLoop](std::exception_ptr ptr, - mbgl::PremultipliedImage image, - mbgl::MapSnapshotter::Attributions, - mbgl::MapSnapshotter::PointForFn, - mbgl::MapSnapshotter::LatLngForFn) { + snapshotter.snapshot([&runLoop]( + std::exception_ptr ptr, + mbgl::PremultipliedImage image, + mbgl::MapSnapshotter::Attributions, + mbgl::MapSnapshotter::PointForFn, + mbgl::MapSnapshotter::LatLngForFn + ) { EXPECT_EQ(nullptr, ptr); EXPECT_EQ(64, image.size.width); EXPECT_EQ(32, image.size.height); @@ -122,11 +128,13 @@ TEST(MapSnapshotter, TEST_REQUIRES_SERVER(runtimeStyling)) { fillLayer->setSourceLayer("water"); fillLayer->setFillColor(Color(0.25f, 0.88f, 0.82f, 1.0f)); snapshotter.getStyle().addLayer(std::move(fillLayer)); - snapshotter.snapshot([&runLoop](std::exception_ptr ptr, - mbgl::PremultipliedImage image, - mbgl::MapSnapshotter::Attributions, - mbgl::MapSnapshotter::PointForFn, - mbgl::MapSnapshotter::LatLngForFn) { + snapshotter.snapshot([&runLoop]( + std::exception_ptr ptr, + mbgl::PremultipliedImage image, + mbgl::MapSnapshotter::Attributions, + mbgl::MapSnapshotter::PointForFn, + mbgl::MapSnapshotter::LatLngForFn + ) { EXPECT_EQ(nullptr, ptr); EXPECT_EQ(256, image.size.width); EXPECT_EQ(128, image.size.height); diff --git a/test/map/prefetch.test.cpp b/test/map/prefetch.test.cpp index 1d5b387f5d7..e71ef19ff22 100644 --- a/test/map/prefetch.test.cpp +++ b/test/map/prefetch.test.cpp @@ -30,17 +30,18 @@ TEST(Map, PrefetchTiles) { }); StubMapObserver observer; - observer.didFinishLoadingMapCallback = [&] () { + observer.didFinishLoadingMapCallback = [&]() { runLoop.stop(); }; - HeadlessFrontend frontend { { 512, 512 }, 1 }; - MapAdapter map(frontend, observer, fileSource, - MapOptions().withMapMode(MapMode::Continuous).withSize(frontend.getSize())); + HeadlessFrontend frontend{{512, 512}, 1}; + MapAdapter map( + frontend, observer, fileSource, MapOptions().withMapMode(MapMode::Continuous).withSize(frontend.getSize()) + ); std::vector tiles; - fileSource->response = [&] (const Resource& res) -> std::optional { + fileSource->response = [&](const Resource& res) -> std::optional { static std::string tile = util::read_file("test/fixtures/map/prefetch/tile.png"); auto zoom = std::stoi(res.url); @@ -57,7 +58,7 @@ TEST(Map, PrefetchTiles) { // Force tile reloading. map.getStyle().loadJSON(util::read_file("test/fixtures/map/prefetch/empty.json")); map.getStyle().loadJSON(util::read_file("test/fixtures/map/prefetch/style.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 40.726989, -73.992857 }).withZoom(zoom)); // Manhattan + map.jumpTo(CameraOptions().withCenter(LatLng{40.726989, -73.992857}).withZoom(zoom)); // Manhattan runLoop.run(); ASSERT_EQ(tiles.size(), expected.size()); @@ -66,7 +67,7 @@ TEST(Map, PrefetchTiles) { // Check defaults, should be 4. ASSERT_EQ(map.getPrefetchZoomDelta(), 4); - checkTilesForZoom(12, { 13, 13, 13, 13, 13, 13, 13, 13, 13, 9 }); + checkTilesForZoom(12, {13, 13, 13, 13, 13, 13, 13, 13, 13, 9}); // Setting it to 0 disables prefetching. map.setPrefetchZoomDelta(0); @@ -75,16 +76,16 @@ TEST(Map, PrefetchTiles) { // tiles instead of the actual zoom level, that is // why the zoom levels for non-prefetched tiles are // not the same. - checkTilesForZoom(10, { 11, 11, 11, 11, 11, 11, 11, 11, 11 }); + checkTilesForZoom(10, {11, 11, 11, 11, 11, 11, 11, 11, 11}); map.setPrefetchZoomDelta(5); - checkTilesForZoom(12, { 13, 13, 13, 13, 13, 13, 13, 13, 13, 8 }); + checkTilesForZoom(12, {13, 13, 13, 13, 13, 13, 13, 13, 13, 8}); // Should clamp at `minzoom`. map.setPrefetchZoomDelta(20); - checkTilesForZoom(10, { 11, 11, 11, 11, 11, 11, 11, 11, 11, 0 }); + checkTilesForZoom(10, {11, 11, 11, 11, 11, 11, 11, 11, 11, 0}); // Disabled again. map.setPrefetchZoomDelta(0); - checkTilesForZoom(13, { 14, 14, 14, 14, 14, 14, 14, 14, 14 }); + checkTilesForZoom(13, {14, 14, 14, 14, 14, 14, 14, 14, 14}); } diff --git a/test/map/transform.test.cpp b/test/map/transform.test.cpp index 3d7931d4aed..4148c35b039 100644 --- a/test/map/transform.test.cpp +++ b/test/map/transform.test.cpp @@ -40,16 +40,16 @@ TEST(Transform, InvalidZoom) { // Executing flyTo with an empty size causes frameZoom to be NaN. transform.flyTo(CameraOptions() - .withCenter(LatLng{ util::LATITUDE_MAX, util::LONGITUDE_MAX }) + .withCenter(LatLng{util::LATITUDE_MAX, util::LONGITUDE_MAX}) .withZoom(transform.getState().getMaxZoom())); transform.updateTransitions(transform.getTransitionStart() + transform.getTransitionDuration()); ASSERT_DOUBLE_EQ(transform.getZoom(), transform.getState().getMaxZoom()); // Executing flyTo with maximum zoom level to the same zoom level causes // frameZoom to be bigger than maximum zoom. - transform.resize(Size { 100, 100 }); + transform.resize(Size{100, 100}); transform.flyTo(CameraOptions() - .withCenter(LatLng{ util::LATITUDE_MAX, util::LONGITUDE_MAX }) + .withCenter(LatLng{util::LATITUDE_MAX, util::LONGITUDE_MAX}) .withZoom(transform.getState().getMaxZoom())); transform.updateTransitions(transform.getTransitionStart() + transform.getTransitionDuration()); @@ -106,10 +106,10 @@ TEST(Transform, PerspectiveProjection) { LatLng loc; Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); // 0.9 rad ~ 51.56620156 deg - transform.jumpTo(CameraOptions().withCenter(LatLng { 38.0, -77.0 }).withZoom(10.0).withPitch(51.56620156)); + transform.jumpTo(CameraOptions().withCenter(LatLng{38.0, -77.0}).withZoom(10.0).withPitch(51.56620156)); // expected values are from maplibre-gl-js @@ -117,11 +117,11 @@ TEST(Transform, PerspectiveProjection) { ASSERT_DOUBLE_EQ(-77, loc.longitude()); ASSERT_DOUBLE_EQ(38, loc.latitude()); - loc = transform.getState().screenCoordinateToLatLng({ 0, 1000 }); + loc = transform.getState().screenCoordinateToLatLng({0, 1000}); ASSERT_NEAR(-77.59198961199148, loc.longitude(), 1e-6); ASSERT_NEAR(38.74661326302018, loc.latitude(), 1e-6); - loc = transform.getState().screenCoordinateToLatLng({ 1000, 0 }); + loc = transform.getState().screenCoordinateToLatLng({1000, 0}); ASSERT_NEAR(-76.75823239205641, loc.longitude(), 1e-6); ASSERT_NEAR(37.692872969426375, loc.latitude(), 1e-6); @@ -146,10 +146,10 @@ TEST(Transform, PerspectiveProjection) { TEST(Transform, UnwrappedLatLng) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); // 0.9 rad ~ 51.56620156 deg - transform.jumpTo(CameraOptions().withCenter(LatLng { 38.0, -77.0 }).withZoom(10.0).withPitch(51.56620156)); + transform.jumpTo(CameraOptions().withCenter(LatLng{38.0, -77.0}).withZoom(10.0).withPitch(51.56620156)); const TransformState& state = transform.getState(); @@ -157,17 +157,17 @@ TEST(Transform, UnwrappedLatLng) { ASSERT_DOUBLE_EQ(fromGetLatLng.latitude(), 38.0); ASSERT_DOUBLE_EQ(fromGetLatLng.longitude(), -77.0); - LatLng fromScreenCoordinate = state.screenCoordinateToLatLng({ 500, 500 }); + LatLng fromScreenCoordinate = state.screenCoordinateToLatLng({500, 500}); ASSERT_NEAR(fromScreenCoordinate.latitude(), 38.0, 1e-8); ASSERT_NEAR(fromScreenCoordinate.longitude(), -77.0, 1e-8); - LatLng wrappedRightwards = state.screenCoordinateToLatLng(state.latLngToScreenCoordinate({ 38, 283 })); + LatLng wrappedRightwards = state.screenCoordinateToLatLng(state.latLngToScreenCoordinate({38, 283})); ASSERT_NEAR(wrappedRightwards.latitude(), 38.0, 1e-8); ASSERT_NEAR(wrappedRightwards.longitude(), 283.0, 1e-8); wrappedRightwards.wrap(); ASSERT_NEAR(wrappedRightwards.longitude(), -77.0, 1e-8); - LatLng wrappedLeftwards = state.screenCoordinateToLatLng(state.latLngToScreenCoordinate({ 38, -437 })); + LatLng wrappedLeftwards = state.screenCoordinateToLatLng(state.latLngToScreenCoordinate({38, -437})); ASSERT_DOUBLE_EQ(wrappedLeftwards.latitude(), wrappedRightwards.latitude()); ASSERT_NEAR(wrappedLeftwards.longitude(), -437.0, 1e-8); wrappedLeftwards.wrap(); @@ -176,7 +176,7 @@ TEST(Transform, UnwrappedLatLng) { TEST(Transform, ConstrainHeightOnly) { Transform transform(MapObserver::nullObserver(), ConstrainMode::HeightOnly); - transform.resize({ 2, 2 }); + transform.resize({2, 2}); transform.jumpTo(CameraOptions().withCenter(LatLngBounds::world().southwest()).withZoom(util::MAX_ZOOM)); ASSERT_NEAR(-util::LATITUDE_MAX, transform.getLatLng().latitude(), 1e-7); @@ -189,7 +189,7 @@ TEST(Transform, ConstrainHeightOnly) { TEST(Transform, ConstrainWidthAndHeight) { Transform transform(MapObserver::nullObserver(), ConstrainMode::WidthAndHeight); - transform.resize({ 2, 2 }); + transform.resize({2, 2}); transform.jumpTo(CameraOptions().withCenter(LatLngBounds::world().southwest()).withZoom(util::MAX_ZOOM)); ASSERT_NEAR(-util::LATITUDE_MAX, transform.getLatLng().latitude(), 1e-7); @@ -202,10 +202,10 @@ TEST(Transform, ConstrainWidthAndHeight) { TEST(Transform, Anchor) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); - const LatLng latLng { 10, -100 }; - const ScreenCoordinate anchorPoint = { 150, 150 }; + const LatLng latLng{10, -100}; + const ScreenCoordinate anchorPoint = {150, 150}; transform.jumpTo(CameraOptions().withCenter(latLng).withZoom(10.0)); ASSERT_DOUBLE_EQ(latLng.latitude(), transform.getLatLng().latitude()); @@ -299,11 +299,11 @@ TEST(Transform, Anchor) { TEST(Transform, Padding) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); ASSERT_DOUBLE_EQ(0, transform.getLatLng().latitude()); ASSERT_DOUBLE_EQ(0, transform.getLatLng().longitude()); - CameraOptions nonPaddedCameraOptions = CameraOptions().withCenter(LatLng { 10, -100 }).withZoom(10.0); + CameraOptions nonPaddedCameraOptions = CameraOptions().withCenter(LatLng{10, -100}).withZoom(10.0); transform.jumpTo(nonPaddedCameraOptions); const LatLng trueCenter = transform.getLatLng(); @@ -349,7 +349,7 @@ TEST(Transform, Padding) { TEST(Transform, MoveBy) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); transform.jumpTo(CameraOptions().withCenter(LatLng()).withZoom(10.0)); @@ -362,8 +362,8 @@ TEST(Transform, MoveBy) { bool odd = x % 2; bool forward = x % 10; - LatLng coordinate = transform.screenCoordinateToLatLng({ odd ? 400. : 600., forward ? 400. : 600 }); - transform.moveBy({ odd ? 100. : -100., forward ? 100. : -100 }); + LatLng coordinate = transform.screenCoordinateToLatLng({odd ? 400. : 600., forward ? 400. : 600}); + transform.moveBy({odd ? 100. : -100., forward ? 100. : -100}); trueCenter = transform.getLatLng(); ASSERT_NEAR(coordinate.latitude(), trueCenter.latitude(), 1e-8); @@ -377,17 +377,17 @@ TEST(Transform, MoveBy) { TEST(Transform, Antimeridian) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); transform.jumpTo(CameraOptions().withCenter(LatLng()).withZoom(1.0)); // San Francisco - const LatLng coordinateSanFrancisco { 37.7833, -122.4167 }; + const LatLng coordinateSanFrancisco{37.7833, -122.4167}; ScreenCoordinate pixelSF = transform.latLngToScreenCoordinate(coordinateSanFrancisco); ASSERT_DOUBLE_EQ(151.79249437176432, pixelSF.x); ASSERT_DOUBLE_EQ(383.76720782527661, pixelSF.y); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, -181.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, -181.0})); ScreenCoordinate pixelSFLongest = transform.latLngToScreenCoordinate(coordinateSanFrancisco); ASSERT_DOUBLE_EQ(-357.36306616412816, pixelSFLongest.x); @@ -399,19 +399,19 @@ TEST(Transform, Antimeridian) { ASSERT_DOUBLE_EQ(666.63694385219173, pixelSFShortest.x); ASSERT_DOUBLE_EQ(pixelSF.y, pixelSFShortest.y); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, 179.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, 179.0})); pixelSFShortest = transform.latLngToScreenCoordinate(coordinateSanFrancisco); ASSERT_DOUBLE_EQ(pixelSFLongest.x, pixelSFShortest.x); ASSERT_DOUBLE_EQ(pixelSFLongest.y, pixelSFShortest.y); // Waikiri - const LatLng coordinateWaikiri{ -16.9310, 179.9787 }; + const LatLng coordinateWaikiri{-16.9310, 179.9787}; transform.jumpTo(CameraOptions().withCenter(coordinateWaikiri).withZoom(10.0)); ScreenCoordinate pixelWaikiri = transform.latLngToScreenCoordinate(coordinateWaikiri); ASSERT_DOUBLE_EQ(500, pixelWaikiri.x); ASSERT_DOUBLE_EQ(500, pixelWaikiri.y); - transform.jumpTo(CameraOptions().withCenter(LatLng { coordinateWaikiri.latitude(), 180.0213 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{coordinateWaikiri.latitude(), 180.0213})); ScreenCoordinate pixelWaikiriLongest = transform.latLngToScreenCoordinate(coordinateWaikiri); ASSERT_DOUBLE_EQ(524725.96438108233, pixelWaikiriLongest.x); ASSERT_DOUBLE_EQ(pixelWaikiri.y, pixelWaikiriLongest.y); @@ -423,31 +423,31 @@ TEST(Transform, Antimeridian) { ASSERT_DOUBLE_EQ(pixelWaikiri.y, pixelWaikiriShortest.y); LatLng coordinateFromPixel = transform.screenCoordinateToLatLng(pixelWaikiriLongest); - ASSERT_NEAR(coordinateWaikiri.latitude(), coordinateFromPixel.latitude(), 1e-4); + ASSERT_NEAR(coordinateWaikiri.latitude(), coordinateFromPixel.latitude(), 1e-4); ASSERT_NEAR(coordinateWaikiri.longitude(), coordinateFromPixel.longitude(), 1e-4); - transform.jumpTo(CameraOptions().withCenter(LatLng { coordinateWaikiri.latitude(), 180.0213 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{coordinateWaikiri.latitude(), 180.0213})); pixelWaikiriShortest = transform.latLngToScreenCoordinate(coordinateWaikiri); ASSERT_DOUBLE_EQ(pixelWaikiriLongest.x, pixelWaikiriShortest.x); ASSERT_DOUBLE_EQ(pixelWaikiriLongest.y, pixelWaikiriShortest.y); coordinateFromPixel = transform.screenCoordinateToLatLng(pixelWaikiriShortest); - ASSERT_NEAR(coordinateWaikiri.latitude(), coordinateFromPixel.latitude(), 1e-4); + ASSERT_NEAR(coordinateWaikiri.latitude(), coordinateFromPixel.latitude(), 1e-4); ASSERT_NEAR(coordinateWaikiri.longitude(), coordinateFromPixel.longitude(), 1e-4); } TEST(Transform, Camera) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); - const LatLng latLng1 { 45, 135 }; + const LatLng latLng1{45, 135}; CameraOptions cameraOptions1 = CameraOptions().withCenter(latLng1).withZoom(20.0); transform.jumpTo(cameraOptions1); ASSERT_DOUBLE_EQ(latLng1.latitude(), transform.getLatLng().latitude()); ASSERT_DOUBLE_EQ(latLng1.longitude(), transform.getLatLng().longitude()); ASSERT_DOUBLE_EQ(20, transform.getZoom()); - const LatLng latLng2 { -45, -135 }; + const LatLng latLng2{-45, -135}; CameraOptions cameraOptions2 = CameraOptions().withCenter(latLng2).withZoom(10.0); transform.jumpTo(cameraOptions2); ASSERT_DOUBLE_EQ(latLng2.latitude(), transform.getLatLng().latitude()); @@ -498,8 +498,8 @@ TEST(Transform, Camera) { // Anchor and center points are mutually exclusive. CameraOptions camera; - camera.center = LatLng { 0, 0 }; - camera.anchor = ScreenCoordinate { 0, 0 }; // top-left + camera.center = LatLng{0, 0}; + camera.anchor = ScreenCoordinate{0, 0}; // top-left camera.zoom = transform.getState().getMaxZoom(); transform.easeTo(camera, AnimationOptions(Seconds(1))); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(250)); @@ -521,8 +521,7 @@ TEST(Transform, ProjectionMode) { EXPECT_EQ(*options.ySkew, 0.0); } -TEST(Transform, IsPanning) -{ +TEST(Transform, IsPanning) { Transform transform; AnimationOptions easeOptions(Seconds(1)); @@ -530,7 +529,7 @@ TEST(Transform, IsPanning) ASSERT_TRUE(transform.getState().isPanning()); }; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); transform.easeTo(CameraOptions().withCenter(LatLng(0, 360.0)), easeOptions); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(250)); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(500)); @@ -540,13 +539,9 @@ TEST(Transform, IsPanning) TEST(Transform, DefaultTransform) { struct TransformObserver : public mbgl::MapObserver { - void onCameraWillChange(MapObserver::CameraChangeMode) final { - cameraWillChangeCallback(); - }; + void onCameraWillChange(MapObserver::CameraChangeMode) final { cameraWillChangeCallback(); }; - void onCameraDidChange(MapObserver::CameraChangeMode) final { - cameraDidChangeCallback(); - }; + void onCameraDidChange(MapObserver::CameraChangeMode) final { cameraDidChangeCallback(); }; std::function cameraWillChangeCallback; std::function cameraDidChangeCallback; @@ -556,8 +551,12 @@ TEST(Transform, DefaultTransform) { uint32_t cameraDidChangeCount = 0; TransformObserver observer; - observer.cameraWillChangeCallback = [&cameraWillChangeCount]() { cameraWillChangeCount++; }; - observer.cameraDidChangeCallback = [&cameraDidChangeCount]() { cameraDidChangeCount++; }; + observer.cameraWillChangeCallback = [&cameraWillChangeCount]() { + cameraWillChangeCount++; + }; + observer.cameraDidChangeCallback = [&cameraDidChangeCount]() { + cameraDidChangeCount++; + }; Transform transform(observer); const TransformState& state = transform.getState(); @@ -569,7 +568,7 @@ TEST(Transform, DefaultTransform) { const uint32_t max = 65535; // Cannot assign invalid sizes. - std::vector invalidSizes = { {}, { min, max }, { max, min } }; + std::vector invalidSizes = {{}, {min, max}, {max, min}}; for (const Size& size : invalidSizes) { try { transform.resize(size); @@ -579,7 +578,7 @@ TEST(Transform, DefaultTransform) { } } - Size validSize { max, max }; + Size validSize{max, max}; ASSERT_FALSE(validSize.isEmpty()); try { @@ -601,7 +600,7 @@ TEST(Transform, DefaultTransform) { ASSERT_TRUE(false) << "Should not throw"; } - center = { max / 2., max / 2. }; + center = {max / 2., max / 2.}; latLng = state.screenCoordinateToLatLng(center); ASSERT_NEAR(latLng.latitude(), nullIsland.latitude(), 1e-8); ASSERT_NEAR(latLng.longitude(), nullIsland.longitude(), 1e-8); @@ -612,11 +611,11 @@ TEST(Transform, DefaultTransform) { } TEST(Transform, LatLngBounds) { - const LatLng nullIsland {}; - const LatLng sanFrancisco { 37.7749, -122.4194 }; + const LatLng nullIsland{}; + const LatLng sanFrancisco{37.7749, -122.4194}; Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); transform.jumpTo(CameraOptions().withCenter(LatLng()).withZoom(transform.getState().getMaxZoom())); @@ -646,17 +645,17 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ┃▓▓▓│▓▓▓┃ │ │ // └───┴───┸───┴───┸───┴───┘ - transform.setLatLngBounds(LatLngBounds::hull({ -90.0, -180.0 }, { 0.0, 180.0 })); + transform.setLatLngBounds(LatLngBounds::hull({-90.0, -180.0}, {0.0, 180.0})); transform.jumpTo(CameraOptions().withCenter(sanFrancisco)); ASSERT_EQ(transform.getLatLng().latitude(), 0.0); ASSERT_EQ(transform.getLatLng().longitude(), sanFrancisco.longitude()); // Try crossing the antimeridian from the left. - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, -200.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, -200.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -180.0); // Try crossing the antimeridian from the right. - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, 200.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, 200.0})); ASSERT_DOUBLE_EQ(transform.getLatLng(LatLng::Unwrapped).longitude(), 180.0); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -180.0); @@ -666,7 +665,7 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ┃ │▓▓▓┃ │ │ // └───┴───┸───┴───┸───┴───┘ - transform.setLatLngBounds(LatLngBounds::hull({ -90.0, 0.0 }, { 90.0, 180.0 })); + transform.setLatLngBounds(LatLngBounds::hull({-90.0, 0.0}, {90.0, 180.0})); transform.jumpTo(CameraOptions().withCenter(sanFrancisco)); ASSERT_NEAR(transform.getLatLng().latitude(), sanFrancisco.latitude(), 1e-8); ASSERT_EQ(transform.getLatLng().longitude(), 0.0); @@ -677,7 +676,7 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ┃ │▓▓▓┃ │ │ // └───┴───┸───┴───┸───┴───┘ - transform.setLatLngBounds(LatLngBounds::hull({ -90.0, 0.0 }, { 0.0, 180.0 })); + transform.setLatLngBounds(LatLngBounds::hull({-90.0, 0.0}, {0.0, 180.0})); transform.jumpTo(CameraOptions().withCenter(sanFrancisco)); ASSERT_EQ(transform.getLatLng().latitude(), 0.0); ASSERT_EQ(transform.getLatLng().longitude(), 0.0); @@ -688,34 +687,34 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ┃ │ ┃ │ │ // └───┴───┸───┴───┸───┴───┘ - LatLng inside { 45.0, 150.0 }; - transform.setLatLngBounds(LatLngBounds::hull({ 0.0, 120.0 }, { 90.0, 240.0 })); + LatLng inside{45.0, 150.0}; + transform.setLatLngBounds(LatLngBounds::hull({0.0, 120.0}, {90.0, 240.0})); transform.jumpTo(CameraOptions().withCenter(inside)); ASSERT_EQ(transform.getLatLng().latitude(), inside.latitude()); ASSERT_EQ(transform.getLatLng().longitude(), inside.longitude()); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, 140.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, 140.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 140.0); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, 160.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, 160.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 160.0); // Constrain latitude only. - transform.jumpTo(CameraOptions().withCenter(LatLng { -45.0, inside.longitude() })); + transform.jumpTo(CameraOptions().withCenter(LatLng{-45.0, inside.longitude()})); ASSERT_EQ(transform.getLatLng().latitude(), 0.0); ASSERT_EQ(transform.getLatLng().longitude(), inside.longitude()); // Crossing the antimeridian, within bounds. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), 181.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), 181.0})); ASSERT_EQ(transform.getLatLng().longitude(), -179.0); // Crossing the antimeridian, outside bounds. transform.jumpTo(CameraOptions().withCenter(inside)); - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), 250.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), 250.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -120.0); // Constrain to the left edge. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), 119.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), 119.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 120.0); // Simulate swipe to the left. @@ -726,7 +725,7 @@ TEST(Transform, LatLngBounds) { easeOptions.transitionFinishFn = [&]() { ASSERT_NEAR(transform.getLatLng().longitude(), 120.0, 1e-4); }; - transform.moveBy(ScreenCoordinate { -500, -500 }, easeOptions); + transform.moveBy(ScreenCoordinate{-500, -500}, easeOptions); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(0)); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(250)); @@ -735,7 +734,7 @@ TEST(Transform, LatLngBounds) { transform.updateTransitions(transform.getTransitionStart() + transform.getTransitionDuration()); // Constrain to the right edge. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), 241.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), 241.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -120.0); // Simulate swipe to the right. @@ -745,7 +744,7 @@ TEST(Transform, LatLngBounds) { easeOptions.transitionFinishFn = [&]() { ASSERT_NEAR(transform.getLatLng().longitude(), -120.0, 1e-4); }; - transform.moveBy(ScreenCoordinate { 500, 500 }, easeOptions); + transform.moveBy(ScreenCoordinate{500, 500}, easeOptions); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(0)); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(250)); @@ -759,45 +758,45 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ▓┃▓ │ ┃ │ │ // └───┴───┸───┴───┸───┴───┘ - inside = LatLng{ -45.0, -150.0 }; - transform.setLatLngBounds(LatLngBounds::hull({ -90.0, -240.0 }, { 0.0, -120.0 })); + inside = LatLng{-45.0, -150.0}; + transform.setLatLngBounds(LatLngBounds::hull({-90.0, -240.0}, {0.0, -120.0})); transform.jumpTo(CameraOptions().withCenter(inside)); ASSERT_DOUBLE_EQ(transform.getLatLng().latitude(), inside.latitude()); ASSERT_EQ(transform.getLatLng().longitude(), inside.longitude()); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, -140.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, -140.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -140.0); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, -160.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, -160.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -160.0); // Constrain latitude only. - transform.jumpTo(CameraOptions().withCenter(LatLng { 45.0, inside.longitude() })); + transform.jumpTo(CameraOptions().withCenter(LatLng{45.0, inside.longitude()})); ASSERT_EQ(transform.getLatLng().latitude(), 0.0); ASSERT_EQ(transform.getLatLng().longitude(), inside.longitude()); // Crossing the antimeridian, within bounds. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), -181.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), -181.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().latitude(), inside.latitude()); ASSERT_EQ(transform.getLatLng().longitude(), 179.0); // Crossing the antimeridian, outside bounds. transform.jumpTo(CameraOptions().withCenter(inside)); - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), -250.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), -250.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 120.0); // Constrain to the left edge. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), -119.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), -119.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -120.0); - transform.moveBy(ScreenCoordinate { -500, 0 }); + transform.moveBy(ScreenCoordinate{-500, 0}); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -120.0); // Constrain to the right edge. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), -241.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), -241.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 120.0); - transform.moveBy(ScreenCoordinate { 500, 0 }); + transform.moveBy(ScreenCoordinate{500, 0}); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 120.0); } @@ -996,7 +995,8 @@ TEST(Transform, FreeCameraOptionsSetOrientation) { static std::tuple rotatedFrame(const std::array& quaternion) { Quaternion q(quaternion); return std::make_tuple( - q.transform({{1.0, 0.0, 0.0}}), q.transform({{0.0, -1.0, 0.0}}), q.transform({{0.0, 0.0, -1.0}})); + q.transform({{1.0, 0.0, 0.0}}), q.transform({{0.0, -1.0, 0.0}}), q.transform({{0.0, 0.0, -1.0}}) + ); } TEST(Transform, FreeCameraOptionsClampPitch) { @@ -1034,8 +1034,9 @@ TEST(Transform, FreeCameraOptionsClampToBounds) { vec3 right, up, forward; std::tie(right, up, forward) = rotatedFrame(transform.getFreeCameraOptions().orientation.value()); - EXPECT_THAT(transform.getFreeCameraOptions().position.value(), - Vec3NearEquals1E5(vec3{{0.0976562, 0.304816, 0.20716}})); + EXPECT_THAT( + transform.getFreeCameraOptions().position.value(), Vec3NearEquals1E5(vec3{{0.0976562, 0.304816, 0.20716}}) + ); EXPECT_THAT(right, Vec3NearEquals1E5(vec3{{1.0, 0.0, 0.0}})); EXPECT_THAT(up, Vec3NearEquals1E5(vec3{{0, -0.707107, 0.707107}})); EXPECT_THAT(forward, Vec3NearEquals1E5(vec3{{0, -0.707107, -0.707107}})); @@ -1090,17 +1091,21 @@ TEST(Transform, FreeCameraOptionsStateSynchronization) { EXPECT_THAT(forward, Vec3NearEquals1E5(vec3{{0.0, 0.0, -1.0}})); transform.jumpTo(CameraOptions().withCenter(LatLng{60.1699, 24.9384})); - EXPECT_THAT(transform.getFreeCameraOptions().position.value(), - Vec3NearEquals1E5(vec3{{0.569273, 0.289453, 0.292969}})); + EXPECT_THAT( + transform.getFreeCameraOptions().position.value(), Vec3NearEquals1E5(vec3{{0.569273, 0.289453, 0.292969}}) + ); transform.jumpTo(CameraOptions().withPitch(20.0).withBearing(77.0).withCenter(LatLng{-20.0, 20.0})); - EXPECT_THAT(transform.getFreeCameraOptions().position.value(), Vec3NearEquals1E5(vec3{{0.457922, 0.57926, 0.275301}})); + EXPECT_THAT( + transform.getFreeCameraOptions().position.value(), Vec3NearEquals1E5(vec3{{0.457922, 0.57926, 0.275301}}) + ); // Invalid pitch transform.jumpTo(CameraOptions().withPitch(-10.0).withBearing(0.0)); std::tie(right, up, forward) = rotatedFrame(transform.getFreeCameraOptions().orientation.value()); - EXPECT_THAT(transform.getFreeCameraOptions().position.value(), - Vec3NearEquals1E5(vec3{{0.555556, 0.556719, 0.292969}})); + EXPECT_THAT( + transform.getFreeCameraOptions().position.value(), Vec3NearEquals1E5(vec3{{0.555556, 0.556719, 0.292969}}) + ); EXPECT_THAT(right, Vec3NearEquals1E5(vec3{{1.0, 0.0, 0.0}})); EXPECT_THAT(up, Vec3NearEquals1E5(vec3{{0.0, -1.0, 0.0}})); EXPECT_THAT(forward, Vec3NearEquals1E5(vec3{{0.0, 0.0, -1.0}})); diff --git a/test/platform/settings.test.cpp b/test/platform/settings.test.cpp index 46a8fc7ef9c..36cb234630a 100644 --- a/test/platform/settings.test.cpp +++ b/test/platform/settings.test.cpp @@ -20,28 +20,32 @@ TEST(Settings, SetAndGet) { Value networkPrioValue{-20.0}; Value databasePrioValue{-10.0}; - Object multipleValues{{EXPERIMENTAL_THREAD_PRIORITY_DATABASE, databasePrioValue}, - {EXPERIMENTAL_THREAD_PRIORITY_NETWORK, networkPrioValue}}; + Object multipleValues{ + {EXPERIMENTAL_THREAD_PRIORITY_DATABASE, databasePrioValue}, + {EXPERIMENTAL_THREAD_PRIORITY_NETWORK, networkPrioValue}}; settings.set(std::move(multipleValues)); - std::vector keys{EXPERIMENTAL_THREAD_PRIORITY_WORKER, - EXPERIMENTAL_THREAD_PRIORITY_DATABASE, - EXPERIMENTAL_THREAD_PRIORITY_NETWORK, - EXPERIMENTAL_THREAD_PRIORITY_FILE}; + std::vector keys{ + EXPERIMENTAL_THREAD_PRIORITY_WORKER, + EXPERIMENTAL_THREAD_PRIORITY_DATABASE, + EXPERIMENTAL_THREAD_PRIORITY_NETWORK, + EXPERIMENTAL_THREAD_PRIORITY_FILE}; auto object = settings.get(keys); - Object values{{EXPERIMENTAL_THREAD_PRIORITY_WORKER, lowPrioValue}, - {EXPERIMENTAL_THREAD_PRIORITY_DATABASE, databasePrioValue}, - {EXPERIMENTAL_THREAD_PRIORITY_NETWORK, networkPrioValue}, - {EXPERIMENTAL_THREAD_PRIORITY_FILE, Value{}}}; + Object values{ + {EXPERIMENTAL_THREAD_PRIORITY_WORKER, lowPrioValue}, + {EXPERIMENTAL_THREAD_PRIORITY_DATABASE, databasePrioValue}, + {EXPERIMENTAL_THREAD_PRIORITY_NETWORK, networkPrioValue}, + {EXPERIMENTAL_THREAD_PRIORITY_FILE, Value{}}}; EXPECT_EQ(values, object); - values = Object{{EXPERIMENTAL_THREAD_PRIORITY_WORKER, Value{}}, - {EXPERIMENTAL_THREAD_PRIORITY_DATABASE, Value{}}, - {EXPERIMENTAL_THREAD_PRIORITY_NETWORK, Value{}}, - {EXPERIMENTAL_THREAD_PRIORITY_FILE, Value{}}}; + values = Object{ + {EXPERIMENTAL_THREAD_PRIORITY_WORKER, Value{}}, + {EXPERIMENTAL_THREAD_PRIORITY_DATABASE, Value{}}, + {EXPERIMENTAL_THREAD_PRIORITY_NETWORK, Value{}}, + {EXPERIMENTAL_THREAD_PRIORITY_FILE, Value{}}}; settings.set(values); EXPECT_EQ(values, settings.get(keys)); diff --git a/test/programs/symbol_program.test.cpp b/test/programs/symbol_program.test.cpp index 28d734c21a8..ec8c89a0780 100644 --- a/test/programs/symbol_program.test.cpp +++ b/test/programs/symbol_program.test.cpp @@ -13,55 +13,51 @@ TEST(SymbolProgram, SymbolSizeBinder) { EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), 12.0f); - binder = SymbolSizeBinder::create(1.0f, style::PropertyExpression( - interpolate( - linear(), - zoom(), - 0., literal(8.), - 10., literal(18.))), 0.0f); + binder = SymbolSizeBinder::create( + 1.0f, style::PropertyExpression(interpolate(linear(), zoom(), 0., literal(8.), 10., literal(18.))), 0.0f + ); uniformValues = binder->uniformValues(1.5f); EXPECT_EQ(uniformValues.get(), false); EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), 9.5f); - - binder = SymbolSizeBinder::create(0.0f, style::PropertyExpression( - interpolate( - linear(), - zoom(), - 1., literal(8.), - 11., literal(18.))), 0.0f); + + binder = SymbolSizeBinder::create( + 0.0f, style::PropertyExpression(interpolate(linear(), zoom(), 1., literal(8.), 11., literal(18.))), 0.0f + ); uniformValues = binder->uniformValues(0.5f); EXPECT_EQ(uniformValues.get(), false); EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), 8.0f); - - binder = SymbolSizeBinder::create(12.0f, style::PropertyExpression( - interpolate( - linear(), - zoom(), - 1., literal(8.), - 11., literal(18.))), 0.0f); + + binder = SymbolSizeBinder::create( + 12.0f, style::PropertyExpression(interpolate(linear(), zoom(), 1., literal(8.), 11., literal(18.))), 0.0f + ); uniformValues = binder->uniformValues(12.5f); EXPECT_EQ(uniformValues.get(), false); EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), 18.0f); - - binder = SymbolSizeBinder::create(0.0f, style::PropertyExpression( - interpolate( - linear(), - number(get("x")), - 1., literal(8.), - 11., literal(18.))), 0.0f); + + binder = SymbolSizeBinder::create( + 0.0f, + style::PropertyExpression(interpolate(linear(), number(get("x")), 1., literal(8.), 11., literal(18.))), + 0.0f + ); uniformValues = binder->uniformValues(12.5f); EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), false); - binder = SymbolSizeBinder::create(5.0f, style::PropertyExpression( - interpolate( + binder = SymbolSizeBinder::create( + 5.0f, + style::PropertyExpression(interpolate( linear(), zoom(), - 1., interpolate(linear(), number(get("x")), 0., literal(8.), 100., literal(18.)), - 11., interpolate(linear(), number(get("x")), 0., literal(12.), 100., literal(24.9)))), 0.0f); + 1., + interpolate(linear(), number(get("x")), 0., literal(8.), 100., literal(18.)), + 11., + interpolate(linear(), number(get("x")), 0., literal(12.), 100., literal(24.9)) + )), + 0.0f + ); uniformValues = binder->uniformValues(5.5f); EXPECT_EQ(uniformValues.get(), false); EXPECT_EQ(uniformValues.get(), false); diff --git a/test/renderer/backend_scope.test.cpp b/test/renderer/backend_scope.test.cpp index 3646afce489..18b13091363 100644 --- a/test/renderer/backend_scope.test.cpp +++ b/test/renderer/backend_scope.test.cpp @@ -9,8 +9,8 @@ using namespace mbgl; class StubRendererBackend : public gl::RendererBackend { public: - StubRendererBackend() : gl::RendererBackend(gfx::ContextMode::Unique) { - } + StubRendererBackend() + : gl::RendererBackend(gfx::ContextMode::Unique) {} void activate() override { if (activateFunction) activateFunction(); @@ -34,9 +34,9 @@ class StubRendererBackend : public gl::RendererBackend { return reinterpret_cast(*this); } - std::function activateFunction; - std::function deactivateFunction; - std::function updateAssumedStateFunction; + std::function activateFunction; + std::function deactivateFunction; + std::function updateAssumedStateFunction; }; // A scope should activate on construction @@ -47,12 +47,14 @@ TEST(BackendScope, SingleScope) { bool deactivated; StubRendererBackend backend; - backend.activateFunction = [&] { activated = true; }; - backend.deactivateFunction = [&] { deactivated = true; }; + backend.activateFunction = [&] { + activated = true; + }; + backend.deactivateFunction = [&] { + deactivated = true; + }; - { - gfx::BackendScope test { backend }; - } + { gfx::BackendScope test{backend}; } ASSERT_TRUE(activated); ASSERT_TRUE(deactivated); @@ -65,14 +67,18 @@ TEST(BackendScope, NestedScopes) { int deactivated = 0; StubRendererBackend backend; - backend.activateFunction = [&] { activated++; }; - backend.deactivateFunction = [&] { deactivated++; }; + backend.activateFunction = [&] { + activated++; + }; + backend.deactivateFunction = [&] { + deactivated++; + }; { - gfx::BackendScope outer { backend }; + gfx::BackendScope outer{backend}; ASSERT_EQ(1, activated); { - gfx::BackendScope inner { backend }; + gfx::BackendScope inner{backend}; ASSERT_EQ(1, activated); } ASSERT_EQ(0, deactivated); @@ -90,18 +96,26 @@ TEST(BackendScope, ChainedScopes) { bool activatedB = false; StubRendererBackend backendA; - backendA.activateFunction = [&] { activatedA = true; }; - backendA.deactivateFunction = [&] { activatedA = false; }; + backendA.activateFunction = [&] { + activatedA = true; + }; + backendA.deactivateFunction = [&] { + activatedA = false; + }; StubRendererBackend backendB; - backendB.activateFunction = [&] { activatedB = true; }; - backendB.deactivateFunction = [&] { activatedB = false; }; + backendB.activateFunction = [&] { + activatedB = true; + }; + backendB.deactivateFunction = [&] { + activatedB = false; + }; { - gfx::BackendScope scopeA { backendA }; + gfx::BackendScope scopeA{backendA}; ASSERT_TRUE(activatedA); { - gfx::BackendScope scopeB { backendB }; + gfx::BackendScope scopeB{backendB}; ASSERT_FALSE(activatedA); ASSERT_TRUE(activatedB); } diff --git a/test/renderer/image_manager.test.cpp b/test/renderer/image_manager.test.cpp index 13050605505..f94667ea9c8 100644 --- a/test/renderer/image_manager.test.cpp +++ b/test/renderer/image_manager.test.cpp @@ -24,8 +24,10 @@ TEST(ImageManager, Basic) { FixtureLog log; ImageManager imageManager; - auto images = parseSprite(util::read_file("test/fixtures/annotations/emerald.png"), - util::read_file("test/fixtures/annotations/emerald.json")); + auto images = parseSprite( + util::read_file("test/fixtures/annotations/emerald.png"), + util::read_file("test/fixtures/annotations/emerald.json") + ); for (auto& image : images) { imageManager.addImage(image); auto* stored = imageManager.getImage(image->id); @@ -38,9 +40,9 @@ TEST(ImageManager, AddRemove) { FixtureLog log; ImageManager imageManager; - imageManager.addImage(makeMutable("one", PremultipliedImage({ 16, 16 }), 2.0f)); - imageManager.addImage(makeMutable("two", PremultipliedImage({ 16, 16 }), 2.0f)); - imageManager.addImage(makeMutable("three", PremultipliedImage({ 16, 16 }), 2.0f)); + imageManager.addImage(makeMutable("one", PremultipliedImage({16, 16}), 2.0f)); + imageManager.addImage(makeMutable("two", PremultipliedImage({16, 16}), 2.0f)); + imageManager.addImage(makeMutable("three", PremultipliedImage({16, 16}), 2.0f)); imageManager.removeImage("one"); imageManager.removeImage("two"); @@ -54,9 +56,9 @@ TEST(ImageManager, Update) { FixtureLog log; ImageManager imageManager; - imageManager.addImage(makeMutable("one", PremultipliedImage({ 16, 16 }), 2.0f)); + imageManager.addImage(makeMutable("one", PremultipliedImage({16, 16}), 2.0f)); EXPECT_EQ(0, imageManager.updatedImageVersions.size()); - imageManager.updateImage(makeMutable("one", PremultipliedImage({ 16, 16 }), 2.0f)); + imageManager.updateImage(makeMutable("one", PremultipliedImage({16, 16}), 2.0f)); EXPECT_EQ(1, imageManager.updatedImageVersions.size()); imageManager.removeImage("one"); EXPECT_EQ(0, imageManager.updatedImageVersions.size()); @@ -66,25 +68,31 @@ TEST(ImageManager, RemoveReleasesBinPackRect) { FixtureLog log; ImageManager imageManager; - imageManager.addImage(makeMutable("big", PremultipliedImage({ 32, 32 }), 1.0f)); + imageManager.addImage(makeMutable("big", PremultipliedImage({32, 32}), 1.0f)); EXPECT_TRUE(imageManager.getImage("big")); imageManager.removeImage("big"); - imageManager.addImage(makeMutable("big", PremultipliedImage({ 32, 32 }), 1.0f)); + imageManager.addImage(makeMutable("big", PremultipliedImage({32, 32}), 1.0f)); EXPECT_TRUE(imageManager.getImage("big")); EXPECT_TRUE(log.empty()); } class StubImageRequestor : public ImageRequestor { public: - StubImageRequestor(ImageManager& imageManager_) : ImageRequestor(imageManager_) {} - - void onImagesAvailable(ImageMap icons, ImageMap patterns, std::unordered_map versionMap, uint64_t imageCorrelationID_) final { + StubImageRequestor(ImageManager& imageManager_) + : ImageRequestor(imageManager_) {} + + void onImagesAvailable( + ImageMap icons, + ImageMap patterns, + std::unordered_map versionMap, + uint64_t imageCorrelationID_ + ) final { if (imagesAvailable && imageCorrelationID == imageCorrelationID_) imagesAvailable(icons, patterns, versionMap); } - std::function)> imagesAvailable; + std::function)> imagesAvailable; uint64_t imageCorrelationID = 0; }; @@ -97,7 +105,7 @@ TEST(ImageManager, NotifiesRequestorWhenSpriteIsLoaded) { ImageManagerObserver observer; imageManager.setObserver(&observer); - requestor.imagesAvailable = [&] (ImageMap, ImageMap, std::unordered_map) { + requestor.imagesAvailable = [&](ImageMap, ImageMap, std::unordered_map) { notified = true; }; @@ -122,31 +130,32 @@ TEST(ImageManager, NotifiesRequestorImmediatelyIfDependenciesAreSatisfied) { StubImageRequestor requestor(imageManager); bool notified = false; - requestor.imagesAvailable = [&] (ImageMap, ImageMap, std::unordered_map) { + requestor.imagesAvailable = [&](ImageMap, ImageMap, std::unordered_map) { notified = true; }; uint64_t imageCorrelationID = 0; ImageDependencies dependencies; dependencies.emplace("one", ImageType::Icon); - imageManager.addImage(makeMutable("one", PremultipliedImage({ 16, 16 }), 2.0f)); + imageManager.addImage(makeMutable("one", PremultipliedImage({16, 16}), 2.0f)); imageManager.getImages(requestor, std::make_pair(dependencies, imageCorrelationID)); ASSERT_TRUE(notified); } - class StubImageManagerObserver : public ImageManagerObserver { - public: +public: int count = 0; - std::function imageMissing = [](const std::string&){}; + std::function imageMissing = [](const std::string&) { + }; void onStyleImageMissing(const std::string& id, const std::function& done) override { count++; imageMissing(id); done(); } - std::function&)> removeUnusedStyleImages = [](const std::vector&){}; + std::function&)> removeUnusedStyleImages = [](const std::vector&) { + }; void onRemoveUnusedStyleImages(const std::vector& unusedImageIDs) override { removeUnusedStyleImages(unusedImageIDs); } @@ -162,7 +171,7 @@ TEST(ImageManager, OnStyleImageMissingBeforeSpriteLoaded) { bool notified = false; - requestor.imagesAvailable = [&] (ImageMap, ImageMap, std::unordered_map) { + requestor.imagesAvailable = [&](ImageMap, ImageMap, std::unordered_map) { notified = true; }; @@ -217,7 +226,7 @@ TEST(ImageManager, OnStyleImageMissingAfterSpriteLoaded) { bool notified = false; - requestor.imagesAvailable = [&] (ImageMap, ImageMap, std::unordered_map) { + requestor.imagesAvailable = [&](ImageMap, ImageMap, std::unordered_map) { notified = true; }; @@ -250,11 +259,11 @@ TEST(ImageManager, RemoveUnusedStyleImages) { imageManager.setObserver(&observer); imageManager.setLoaded(true); - observer.imageMissing = [&imageManager] (const std::string& id) { + observer.imageMissing = [&imageManager](const std::string& id) { if (id == "1024px") { - imageManager.addImage(makeMutable(id, PremultipliedImage({ 1024, 1024 }), 1.0f)); + imageManager.addImage(makeMutable(id, PremultipliedImage({1024, 1024}), 1.0f)); } else { - imageManager.addImage(makeMutable(id, PremultipliedImage({ 16, 16 }), 1.0f)); + imageManager.addImage(makeMutable(id, PremultipliedImage({16, 16}), 1.0f)); } }; @@ -266,7 +275,7 @@ TEST(ImageManager, RemoveUnusedStyleImages) { }; // Style sprite. - imageManager.addImage(makeMutable("sprite", PremultipliedImage({ 16, 16 }), 1.0f)); + imageManager.addImage(makeMutable("sprite", PremultipliedImage({16, 16}), 1.0f)); // Single requestor { @@ -326,7 +335,10 @@ TEST(ImageManager, RemoveUnusedStyleImages) { std::unique_ptr requestor = std::make_unique(imageManager); { std::unique_ptr requestor1 = std::make_unique(imageManager); - imageManager.getImages(*requestor, std::make_pair(ImageDependencies{{"missing", ImageType::Icon}, {"1024px", ImageType::Icon}}, 0ull)); + imageManager.getImages( + *requestor, + std::make_pair(ImageDependencies{{"missing", ImageType::Icon}, {"1024px", ImageType::Icon}}, 0ull) + ); imageManager.getImages(*requestor1, std::make_pair(ImageDependencies{{"missing", ImageType::Icon}}, 1ull)); runLoop.runOnce(); EXPECT_EQ(observer.count, 5); diff --git a/test/renderer/pattern_atlas.test.cpp b/test/renderer/pattern_atlas.test.cpp index 52c04b9e0d9..a1c78a2e49c 100644 --- a/test/renderer/pattern_atlas.test.cpp +++ b/test/renderer/pattern_atlas.test.cpp @@ -18,8 +18,10 @@ TEST(PatternAtlas, Basic) { FixtureLog log; PatternAtlas patternAtlas; - auto images = parseSprite(util::read_file("test/fixtures/annotations/emerald.png"), - util::read_file("test/fixtures/annotations/emerald.json")); + auto images = parseSprite( + util::read_file("test/fixtures/annotations/emerald.png"), + util::read_file("test/fixtures/annotations/emerald.json") + ); for (auto& image : images) { if (image->id == "metro") { ASSERT_TRUE(patternAtlas.addPattern(*image)); @@ -44,7 +46,7 @@ TEST(PatternAtlas, Basic) { TEST(PatternAtlas, Updates) { PatternAtlas patternAtlas; - PremultipliedImage imageA({ 16, 12 }); + PremultipliedImage imageA({16, 12}); imageA.fill(255); auto added = patternAtlas.addPattern(*makeMutable("one", std::move(imageA), 1.0f)); @@ -63,12 +65,12 @@ TEST(PatternAtlas, Updates) { EXPECT_EQ(1.0f, a.pixelRatio); test::checkImage("test/fixtures/image_manager/updates_before", patternAtlas.getAtlasImageForTests()); - auto imageB = makeMutable("one", PremultipliedImage({ 5, 5 }), 1.0f); + auto imageB = makeMutable("one", PremultipliedImage({5, 5}), 1.0f); EXPECT_FALSE(patternAtlas.addPattern(*imageB)); // Already added. patternAtlas.removePattern("one"); ASSERT_FALSE(patternAtlas.getPattern("one")); - EXPECT_TRUE(patternAtlas.addPattern(*imageB)); + EXPECT_TRUE(patternAtlas.addPattern(*imageB)); auto b = *patternAtlas.getPattern("one"); EXPECT_EQ(1, b.tl()[0]); diff --git a/test/renderer/shader_registry.test.cpp b/test/renderer/shader_registry.test.cpp index 68e449ca7d0..ef77a0b2146 100644 --- a/test/renderer/shader_registry.test.cpp +++ b/test/renderer/shader_registry.test.cpp @@ -28,81 +28,70 @@ using namespace mbgl; namespace { class MapInstance { +public: + class ShaderAndStyleObserver : public MapObserver { public: - class ShaderAndStyleObserver : public MapObserver { - public: - public: - void onDidFinishLoadingStyle() override { - styleLoaded(); - } - - void onRegisterShaders(gfx::ShaderRegistry& registry) override { - registerShaders(registry); - }; - - std::function styleLoaded; - std::function registerShaders; - }; - - MapInstance(float pixelRatio, MapObserver& observer) : - frontend(pixelRatio), - adapter(frontend, observer, std::make_shared( - ResourceOptions() - .withCachePath(":memory:") - .withAssetPath("test/fixtures/api/assets"), - ClientOptions() - ), - MapOptions() - .withMapMode(MapMode::Static) - .withSize(frontend.getSize()) - .withPixelRatio(pixelRatio)) - {} - public: - HeadlessFrontend frontend; - MapAdapter adapter; + void onDidFinishLoadingStyle() override { styleLoaded(); } + + void onRegisterShaders(gfx::ShaderRegistry& registry) override { registerShaders(registry); }; + + std::function styleLoaded; + std::function registerShaders; + }; + + MapInstance(float pixelRatio, MapObserver& observer) + : frontend(pixelRatio), + adapter( + frontend, + observer, + std::make_shared( + ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets"), ClientOptions() + ), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()).withPixelRatio(pixelRatio) + ) {} + +public: + HeadlessFrontend frontend; + MapAdapter adapter; }; -template +template class StubProgramBase : public gfx::Shader { - public: - static constexpr auto Token = token_value; - virtual uint32_t draw() { return token; } +public: + static constexpr auto Token = token_value; + virtual uint32_t draw() { return token; } - protected: - uint32_t token{token_value}; +protected: + uint32_t token{token_value}; }; class StubProgram_1 final : public StubProgramBase<10> { - public: - static constexpr std::string_view Name{"StubProgram_1"}; - const std::string_view typeName() const noexcept override { - return Name; - } +public: + static constexpr std::string_view Name{"StubProgram_1"}; + const std::string_view typeName() const noexcept override { return Name; } - void setToken(uint32_t tok) { token = tok; } + void setToken(uint32_t tok) { token = tok; } }; class StubProgram_2 final : public StubProgramBase<20> { - public: - static constexpr std::string_view Name{"StubProgram_2"}; - const std::string_view typeName() const noexcept override { - return Name; - } +public: + static constexpr std::string_view Name{"StubProgram_2"}; + const std::string_view typeName() const noexcept override { return Name; } }; class StubShaderConsumer { - public: - template - uint32_t useShader(gfx::ShaderRegistry& registry) { - auto program = registry.get(); - return program ? program->draw() : 0; - } +public: + template + uint32_t useShader(gfx::ShaderRegistry& registry) { + auto program = registry.get(); + return program ? program->draw() : 0; + } }; } // namespace -// Ensure we can register a gfx::Shader-based type with a registry object +// Ensure we can register a gfx::Shader-based type with a registry object TEST(ShaderRegistry, RegisterShader) { gfx::ShaderRegistry registry; @@ -170,16 +159,13 @@ TEST(ShaderRegistry, MultiRegister) { gfx::ShaderRegistry registry; ASSERT_TRUE(registry.registerShader(std::make_shared())); - ASSERT_TRUE(registry.registerShader(std::make_shared(), - "SecondProgram")); - + ASSERT_TRUE(registry.registerShader(std::make_shared(), "SecondProgram")); + // Default option, register as the type name ASSERT_NE(registry.get(), nullptr); // Register with an explicit name ASSERT_NE(registry.get("SecondProgram"), nullptr); - ASSERT_NE( - registry.get(), - registry.get("SecondProgram")); + ASSERT_NE(registry.get(), registry.get("SecondProgram")); } // Test fetching @@ -187,9 +173,8 @@ TEST(ShaderRegistry, RegistryFetch) { gfx::ShaderRegistry registry; ASSERT_TRUE(registry.registerShader(std::make_shared())); - ASSERT_TRUE(registry.registerShader(std::make_shared(), - "SecondProgram")); - + ASSERT_TRUE(registry.registerShader(std::make_shared(), "SecondProgram")); + std::shared_ptr progA; std::shared_ptr progB; @@ -205,21 +190,19 @@ TEST(ShaderRegistry, NamedReplace) { gfx::ShaderRegistry registry; // Register - ASSERT_TRUE(registry.registerShader(std::make_shared(), - "CustomName")); - + ASSERT_TRUE(registry.registerShader(std::make_shared(), "CustomName")); + std::shared_ptr progA; ASSERT_TRUE(registry.populate(progA, "CustomName")); ASSERT_NE(progA, nullptr); // Replace it with a new instance - ASSERT_TRUE(registry.replaceShader(std::make_shared(), - "CustomName")); - + ASSERT_TRUE(registry.replaceShader(std::make_shared(), "CustomName")); + std::shared_ptr progB; ASSERT_TRUE(registry.populate(progB, "CustomName")); ASSERT_NE(progB, nullptr); - + // Should be different instances ASSERT_NE(progA, progB); } @@ -232,9 +215,7 @@ TEST(ShaderRegistry, GLSLReplacement_NoOp) { // Just replace with a default instance observer.registerShaders = [&](gfx::ShaderRegistry& registry) { - if (!registry.replaceShader(std::make_shared( - ProgramParameters(1.0f, false)))) - { + if (!registry.replaceShader(std::make_shared(ProgramParameters(1.0f, false)))) { throw std::runtime_error("Failed to register shader!"); } }; @@ -260,20 +241,18 @@ TEST(ShaderRegistry, GLSLReplacement1) { // Replace with an instance that only renders blue observer.registerShaders = [&](gfx::ShaderRegistry& registry) { - if (!registry.replaceShader(std::make_shared( - ProgramParameters(1.0f, false).withShaderSource( - ProgramParameters::ProgramSource( - gfx::Backend::Type::OpenGL, - "", - R"( + if (!registry.replaceShader( + std::make_shared(ProgramParameters(1.0f, false) + .withShaderSource(ProgramParameters::ProgramSource( + gfx::Backend::Type::OpenGL, + "", + R"( void main() { fragColor = vec4(0.0, 0.0, 1.0, 1.0); } )" - ) - ) - ))) - { + ))) + )) { throw std::runtime_error("Failed to register shader!"); } }; @@ -299,12 +278,12 @@ TEST(ShaderRegistry, GLSLReplacement2) { // Replace with an instance that adds some red and green observer.registerShaders = [&](gfx::ShaderRegistry& registry) { - if (!registry.replaceShader(std::make_shared( - ProgramParameters(1.0f, false).withShaderSource( - ProgramParameters::ProgramSource( - gfx::Backend::Type::OpenGL, - "", - R"( + if (!registry.replaceShader( + std::make_shared(ProgramParameters(1.0f, false) + .withShaderSource(ProgramParameters::ProgramSource( + gfx::Backend::Type::OpenGL, + "", + R"( #ifndef HAS_UNIFORM_u_color varying highp vec4 color; #else @@ -333,10 +312,8 @@ void main() { #endif } )" - ) - ) - ))) - { + ))) + )) { throw std::runtime_error("Failed to register shader!"); } }; diff --git a/test/sprite/sprite_loader.test.cpp b/test/sprite/sprite_loader.test.cpp index 2c37e687e36..8b5ad25d9cf 100644 --- a/test/sprite/sprite_loader.test.cpp +++ b/test/sprite/sprite_loader.test.cpp @@ -26,7 +26,7 @@ class StubSpriteLoaderObserver : public SpriteLoaderObserver { } std::function>)> spriteLoaded; - std::function spriteError; + std::function spriteError; }; class SpriteLoaderTest { @@ -36,7 +36,7 @@ class SpriteLoaderTest { util::RunLoop loop; StubFileSource fileSource; StubSpriteLoaderObserver observer; - SpriteLoader spriteLoader{ 1 }; + SpriteLoader spriteLoader{1}; void run() { // Squelch logging. @@ -48,9 +48,7 @@ class SpriteLoaderTest { loop.run(); } - void end() { - loop.stop(); - } + void end() { loop.stop(); } }; Response successfulSpriteImageResponse(const Resource& resource) { @@ -69,9 +67,7 @@ Response successfulSpriteJSONResponse(const Resource& resource) { Response failedSpriteResponse(const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; } @@ -87,7 +83,7 @@ TEST(SpriteLoader, LoadingSuccess) { test.fileSource.spriteImageResponse = successfulSpriteImageResponse; test.fileSource.spriteJSONResponse = successfulSpriteJSONResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { FAIL() << util::toString(error); test.end(); }; @@ -106,7 +102,7 @@ TEST(SpriteLoader, JSONLoadingFail) { test.fileSource.spriteImageResponse = successfulSpriteImageResponse; test.fileSource.spriteJSONResponse = failedSpriteResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { EXPECT_TRUE(error != nullptr); EXPECT_EQ("Failed by the test case", util::toString(error)); test.end(); @@ -121,7 +117,7 @@ TEST(SpriteLoader, ImageLoadingFail) { test.fileSource.spriteImageResponse = failedSpriteResponse; test.fileSource.spriteJSONResponse = successfulSpriteJSONResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { EXPECT_TRUE(error != nullptr); EXPECT_EQ("Failed by the test case", util::toString(error)); test.end(); @@ -136,7 +132,7 @@ TEST(SpriteLoader, JSONLoadingCorrupted) { test.fileSource.spriteImageResponse = successfulSpriteImageResponse; test.fileSource.spriteJSONResponse = corruptSpriteResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { EXPECT_TRUE(error != nullptr); EXPECT_EQ("Failed to parse JSON: Invalid value. at offset 0", util::toString(error)); test.end(); @@ -151,7 +147,7 @@ TEST(SpriteLoader, ImageLoadingCorrupted) { test.fileSource.spriteImageResponse = corruptSpriteResponse; test.fileSource.spriteJSONResponse = successfulSpriteJSONResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { EXPECT_TRUE(error != nullptr); // Not asserting on platform-specific error text. test.end(); @@ -163,8 +159,7 @@ TEST(SpriteLoader, ImageLoadingCorrupted) { TEST(SpriteLoader, LoadingCancel) { SpriteLoaderTest test; - test.fileSource.spriteImageResponse = - test.fileSource.spriteJSONResponse = [&] (const Resource&) { + test.fileSource.spriteImageResponse = test.fileSource.spriteJSONResponse = [&](const Resource&) { test.end(); return std::optional(); }; diff --git a/test/sprite/sprite_parser.test.cpp b/test/sprite/sprite_parser.test.cpp index 0579604b8f3..3030fa68e90 100644 --- a/test/sprite/sprite_parser.test.cpp +++ b/test/sprite/sprite_parser.test.cpp @@ -29,158 +29,189 @@ TEST(Sprite, SpriteImageCreationInvalid) { ASSERT_EQ(299u, image_1x.size.height); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, 0, 16, 1, false)); // width == 0 - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 0x16@0,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 0x16@0,0 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, 16, 0, 1, false)); // height == 0 - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 16x0@0,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 16x0@0,0 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, -1, 16, 1, false)); // width < 0 - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: -1x16@0,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: -1x16@0,0 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, 16, -1, 1, false)); // height < 0 - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 16x-1@0,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 16x-1@0,0 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, 1, 1, 0, false)); // ratio == 0 - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 1x1@0,0 in 200x299@0x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 1x1@0,0 in 200x299@0x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, 1, 1, -1, false)); // ratio < 0 - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 1x1@0,0 in 200x299@-1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 1x1@0,0 in 200x299@-1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, 1, 1, 23, false)); // ratio too large - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 1x1@0,0 in 200x299@23x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 1x1@0,0 in 200x299@23x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, 2048, 16, 1, false)); // too wide - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 2048x16@0,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 2048x16@0,0 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, 16, 1025, 1, false)); // too tall - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 16x1025@0,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 16x1025@0,0 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, -1, 0, 16, 16, 1, false)); // srcX < 0 - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 16x16@-1,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 16x16@-1,0 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, -1, 16, 16, 1, false)); // srcY < 0 - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 16x16@0,-1 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 16x16@0,-1 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ( - nullptr, - createStyleImage("test", image_1x, 0, 0, image_1x.size.width + 1, 16, 1, false)); // right edge out of bounds - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 201x16@0,0 in 200x299@1x sprite", - })); + nullptr, createStyleImage("test", image_1x, 0, 0, image_1x.size.width + 1, 16, 1, false) + ); // right edge out of bounds + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 201x16@0,0 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ( - nullptr, - createStyleImage("test", image_1x, 0, 0, 16, image_1x.size.height + 1, 1, false)); // bottom edge out of bounds - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 16x300@0,0 in 200x299@1x sprite", - })); + nullptr, createStyleImage("test", image_1x, 0, 0, 16, image_1x.size.height + 1, 1, false) + ); // bottom edge out of bounds + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 16x300@0,0 in 200x299@1x sprite", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); ASSERT_EQ(nullptr, createStyleImage("test", image_1x, 0, 0, 16, 16, 1, false, {{-1.0f, 3.0f}})); - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metadata: stretchX is out of bounds or overlapping", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metadata: stretchX is out of bounds or overlapping", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); - ASSERT_EQ(nullptr, - createStyleImage("test", image_1x, 0, 0, 16, 16, 1, false, {}, {}, style::ImageContent{14, 14, 12, 10})); - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metadata: content area is invalid", - })); + ASSERT_EQ( + nullptr, createStyleImage("test", image_1x, 0, 0, 16, 16, 1, false, {}, {}, style::ImageContent{14, 14, 12, 10}) + ); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metadata: content area is invalid", + }) + ); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -196,8 +227,7 @@ TEST(Sprite, SpriteImageCreation1x) { EXPECT_EQ(18u, sprite->getImage().size.width); EXPECT_EQ(18u, sprite->getImage().size.height); EXPECT_EQ(1, sprite->getPixelRatio()); - EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation1x-museum.png"), - sprite->getImage()); + EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation1x-museum.png"), sprite->getImage()); } } @@ -210,8 +240,7 @@ TEST(Sprite, SpriteImageCreation2x) { EXPECT_EQ(36u, sprite->getImage().size.width); EXPECT_EQ(36u, sprite->getImage().size.height); EXPECT_EQ(2, sprite->getPixelRatio()); - EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation2x.png"), - sprite->getImage()); + EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation2x.png"), sprite->getImage()); } TEST(Sprite, SpriteImageCreation1_5x) { @@ -223,8 +252,7 @@ TEST(Sprite, SpriteImageCreation1_5x) { EXPECT_EQ(36u, sprite->getImage().size.width); EXPECT_EQ(36u, sprite->getImage().size.height); EXPECT_EQ(1.5, sprite->getPixelRatio()); - EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation1_5x-museum.png"), - sprite->getImage()); + EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation1_5x-museum.png"), sprite->getImage()); // "hospital_icon":{"x":314,"y":518,"width":36,"height":36,"pixelRatio":2,"sdf":false} const auto sprite2 = createStyleImage("test", image_2x, 314, 518, 35, 35, 1.5, false); @@ -232,8 +260,7 @@ TEST(Sprite, SpriteImageCreation1_5x) { EXPECT_EQ(35u, sprite2->getImage().size.width); EXPECT_EQ(35u, sprite2->getImage().size.height); EXPECT_EQ(1.5, sprite2->getPixelRatio()); - EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation1_5x-hospital.png"), - sprite2->getImage()); + EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation1_5x-hospital.png"), sprite2->getImage()); } TEST(Sprite, SpriteParsing) { @@ -243,87 +270,93 @@ TEST(Sprite, SpriteParsing) { const auto images = parseSprite(image_1x, json_1x); std::set names; - std::transform( - images.begin(), images.end(), std::inserter(names, names.begin()), [](const auto& image) { return image->id; }); - - EXPECT_EQ(std::set({ "airfield_icon", - "airport_icon", - "background", - "cemetery_icon", - "college_icon", - "default_1", - "default_2", - "default_3", - "default_4", - "default_5", - "default_6", - "default_marker", - "dlr", - "dlr.london-overground.london-underground.national-rail", - "dlr.london-underground", - "dlr.london-underground.national-rail", - "dlr.national-rail", - "dot", - "embassy_icon", - "fire-station_icon", - "generic-metro", - "generic-rail", - "generic_icon", - "golf_icon", - "government_icon", - "grass_pattern", - "harbor_icon", - "hospital_icon", - "hospital_striped", - "interstate_1", - "interstate_2", - "interstate_3", - "library_icon", - "london-overground", - "london-overground.london-underground", - "london-overground.london-underground.national-rail", - "london-overground.national-rail", - "london-underground", - "london-underground.national-rail", - "marker_icon", - "metro", - "metro.rer", - "monument_icon", - "moscow-metro", - "museum_icon", - "national-rail", - "oneway_motorway", - "oneway_road", - "park_icon", - "police_icon", - "post_icon", - "prison_icon", - "religious-christian_icon", - "religious-jewish_icon", - "religious-muslim_icon", - "rer", - "rer.transilien", - "s-bahn", - "s-bahn.u-bahn", - "sand_noise", - "school_icon", - "school_striped", - "secondary_marker", - "u-bahn", - "us_highway_1", - "us_highway_2", - "us_highway_3", - "us_state_1", - "us_state_2", - "us_state_3", - "washington-metro", - "wiener-linien", - "zoo_icon" }), - names); + std::transform(images.begin(), images.end(), std::inserter(names, names.begin()), [](const auto& image) { + return image->id; + }); + + EXPECT_EQ( + std::set( + {"airfield_icon", + "airport_icon", + "background", + "cemetery_icon", + "college_icon", + "default_1", + "default_2", + "default_3", + "default_4", + "default_5", + "default_6", + "default_marker", + "dlr", + "dlr.london-overground.london-underground.national-rail", + "dlr.london-underground", + "dlr.london-underground.national-rail", + "dlr.national-rail", + "dot", + "embassy_icon", + "fire-station_icon", + "generic-metro", + "generic-rail", + "generic_icon", + "golf_icon", + "government_icon", + "grass_pattern", + "harbor_icon", + "hospital_icon", + "hospital_striped", + "interstate_1", + "interstate_2", + "interstate_3", + "library_icon", + "london-overground", + "london-overground.london-underground", + "london-overground.london-underground.national-rail", + "london-overground.national-rail", + "london-underground", + "london-underground.national-rail", + "marker_icon", + "metro", + "metro.rer", + "monument_icon", + "moscow-metro", + "museum_icon", + "national-rail", + "oneway_motorway", + "oneway_road", + "park_icon", + "police_icon", + "post_icon", + "prison_icon", + "religious-christian_icon", + "religious-jewish_icon", + "religious-muslim_icon", + "rer", + "rer.transilien", + "s-bahn", + "s-bahn.u-bahn", + "sand_noise", + "school_icon", + "school_striped", + "secondary_marker", + "u-bahn", + "us_highway_1", + "us_highway_2", + "us_highway_3", + "us_state_1", + "us_state_2", + "us_state_3", + "washington-metro", + "wiener-linien", + "zoo_icon"} + ), + names + ); { - auto& sprite = - *std::find_if(images.begin(), images.end(), [](const auto& image) { return image->id == "generic-metro"; }); + auto& sprite = *std::find_if(images.begin(), images.end(), [](const auto& image) { + return image->id == "generic-metro"; + }); EXPECT_EQ(18u, sprite->image.size.width); EXPECT_EQ(18u, sprite->image.size.height); EXPECT_EQ(1, sprite->pixelRatio); @@ -339,9 +372,7 @@ TEST(Sprite, SpriteParsingInvalidJSON) { parseSprite(image_1x, json_1x); FAIL() << "Expected exception"; } catch (std::runtime_error& err) { - EXPECT_STREQ( - "Failed to parse JSON: Missing a closing quotation mark in string. at offset 14", - err.what()); + EXPECT_STREQ("Failed to parse JSON: Missing a closing quotation mark in string. at offset 14", err.what()); } } @@ -360,11 +391,15 @@ TEST(Sprite, SpriteParsingInvalidStretches) { "stretchX": {} } })JSON"); - EXPECT_EQ(1u, - log.count({EventSeverity::Warning, - Event::Sprite, - int64_t(-1), - "Invalid sprite image 'interstate_1': value of 'stretchX' must be an array"})); + EXPECT_EQ( + 1u, + log.count( + {EventSeverity::Warning, + Event::Sprite, + int64_t(-1), + "Invalid sprite image 'interstate_1': value of 'stretchX' must be an array"} + ) + ); EXPECT_EQ(0u, log.uncheckedCount()); parseSprite(image_1x, R"JSON({ @@ -379,10 +414,13 @@ TEST(Sprite, SpriteParsingInvalidStretches) { })JSON"); EXPECT_EQ( 1u, - log.count({EventSeverity::Warning, - Event::Sprite, - int64_t(-1), - "Invalid sprite image 'interstate_1': members of 'stretchX' must be an array of two numbers"})); + log.count( + {EventSeverity::Warning, + Event::Sprite, + int64_t(-1), + "Invalid sprite image 'interstate_1': members of 'stretchX' must be an array of two numbers"} + ) + ); EXPECT_EQ(0u, log.uncheckedCount()); parseSprite(image_1x, R"JSON({ @@ -397,10 +435,13 @@ TEST(Sprite, SpriteParsingInvalidStretches) { })JSON"); EXPECT_EQ( 1u, - log.count({EventSeverity::Warning, - Event::Sprite, - int64_t(-1), - "Invalid sprite image 'interstate_1': members of 'stretchX' must be an array of two numbers"})); + log.count( + {EventSeverity::Warning, + Event::Sprite, + int64_t(-1), + "Invalid sprite image 'interstate_1': members of 'stretchX' must be an array of two numbers"} + ) + ); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -419,11 +460,15 @@ TEST(Sprite, SpriteParsingInvalidContent) { "content": [] } })JSON"); - EXPECT_EQ(1u, - log.count({EventSeverity::Warning, - Event::Sprite, - int64_t(-1), - "Invalid sprite image 'interstate_1': value of 'content' must be an array of four numbers"})); + EXPECT_EQ( + 1u, + log.count( + {EventSeverity::Warning, + Event::Sprite, + int64_t(-1), + "Invalid sprite image 'interstate_1': value of 'content' must be an array of four numbers"} + ) + ); EXPECT_EQ(0u, log.uncheckedCount()); parseSprite(image_1x, R"JSON({ @@ -436,11 +481,15 @@ TEST(Sprite, SpriteParsingInvalidContent) { "content": [4, 4, 4, true] } })JSON"); - EXPECT_EQ(1u, - log.count({EventSeverity::Warning, - Event::Sprite, - int64_t(-1), - "Invalid sprite image 'interstate_1': value of 'content' must be an array of four numbers"})); + EXPECT_EQ( + 1u, + log.count( + {EventSeverity::Warning, + Event::Sprite, + int64_t(-1), + "Invalid sprite image 'interstate_1': value of 'content' must be an array of four numbers"} + ) + ); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -477,13 +526,15 @@ TEST(Sprite, SpriteParsingEmptyImage) { const auto images = parseSprite(image_1x, json_1x); EXPECT_EQ(0u, images.size()); - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 0x0@0,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 0x0@0,0 in 200x299@1x sprite", + }) + ); } TEST(Sprite, SpriteParsingSimpleWidthHeight) { @@ -505,20 +556,24 @@ TEST(Sprite, SpriteParsingWidthTooBig) { const auto images = parseSprite(image_1x, json_1x); EXPECT_EQ(0u, images.size()); - EXPECT_EQ(1u, - log.count({ - EventSeverity::Warning, - Event::Sprite, - int64_t(-1), - "Invalid sprite image 'image': value of 'width' must be an integer between 0 and 65535", - })); - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 0x32@0,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Warning, + Event::Sprite, + int64_t(-1), + "Invalid sprite image 'image': value of 'width' must be an integer between 0 and 65535", + }) + ); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 0x32@0,0 in 200x299@1x sprite", + }) + ); } TEST(Sprite, SpriteParsingNegativeWidth) { @@ -530,20 +585,24 @@ TEST(Sprite, SpriteParsingNegativeWidth) { const auto images = parseSprite(image_1x, json_1x); EXPECT_EQ(0u, images.size()); - EXPECT_EQ(1u, - log.count({ - EventSeverity::Warning, - Event::Sprite, - int64_t(-1), - "Invalid sprite image 'image': value of 'width' must be an integer between 0 and 65535", - })); - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 0x32@0,0 in 200x299@1x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Warning, + Event::Sprite, + int64_t(-1), + "Invalid sprite image 'image': value of 'width' must be an integer between 0 and 65535", + }) + ); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 0x32@0,0 in 200x299@1x sprite", + }) + ); } TEST(Sprite, SpriteParsingNullRatio) { @@ -555,11 +614,13 @@ TEST(Sprite, SpriteParsingNullRatio) { const auto images = parseSprite(image_1x, json_1x); EXPECT_EQ(0u, images.size()); - EXPECT_EQ(1u, - log.count({ - EventSeverity::Error, - Event::Sprite, - int64_t(-1), - "Can't create image with invalid metrics: 32x32@0,0 in 200x299@0x sprite", - })); + EXPECT_EQ( + 1u, + log.count({ + EventSeverity::Error, + Event::Sprite, + int64_t(-1), + "Can't create image with invalid metrics: 32x32@0,0 in 200x299@0x sprite", + }) + ); } diff --git a/test/src/mbgl/test/fake_file_source.hpp b/test/src/mbgl/test/fake_file_source.hpp index 276ebb895d1..03dd4eaab0a 100644 --- a/test/src/mbgl/test/fake_file_source.hpp +++ b/test/src/mbgl/test/fake_file_source.hpp @@ -10,7 +10,6 @@ #include #include - namespace mbgl { /* @@ -35,17 +34,16 @@ class FakeFileSource : public FileSource { : resource(std::move(resource_)), callback(std::move(callback_)), list(list_), - link((list.push_back(this), std::prev(list.end()))) { - } + link((list.push_back(this), std::prev(list.end()))) {} - ~FakeFileRequest() override { - list.erase(link); - } + ~FakeFileRequest() override { list.erase(link); } }; FakeFileSource(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()) {} - FakeFileSource() : FakeFileSource(ResourceOptions::Default(), ClientOptions()) {} + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} + FakeFileSource() + : FakeFileSource(ResourceOptions::Default(), ClientOptions()) {} std::unique_ptr request(const Resource& resource, Callback callback) override { return std::make_unique(resource, callback, requests); @@ -54,7 +52,7 @@ class FakeFileSource : public FileSource { bool canRequest(const Resource&) const override { return true; } bool respond(Resource::Kind kind, const Response& response) { - auto it = std::find_if(requests.begin(), requests.end(), [&] (FakeFileRequest* fakeRequest) { + auto it = std::find_if(requests.begin(), requests.end(), [&](FakeFileRequest* fakeRequest) { return fakeRequest->resource.kind == kind; }); @@ -71,19 +69,11 @@ class FakeFileSource : public FileSource { std::list requests; - void setResourceOptions(ResourceOptions options) override { - resourceOptions = options; - } - ResourceOptions getResourceOptions() override { - return resourceOptions.clone(); - } + void setResourceOptions(ResourceOptions options) override { resourceOptions = options; } + ResourceOptions getResourceOptions() override { return resourceOptions.clone(); } - void setClientOptions(ClientOptions options) override { - clientOptions = options; - } - ClientOptions getClientOptions() override { - return clientOptions.clone(); - } + void setClientOptions(ClientOptions options) override { clientOptions = options; } + ClientOptions getClientOptions() override { return clientOptions.clone(); } private: ResourceOptions resourceOptions; @@ -92,7 +82,8 @@ class FakeFileSource : public FileSource { class FakeOnlineFileSource : public FakeFileSource { public: - FakeOnlineFileSource() : FakeOnlineFileSource(ResourceOptions::Default(), ClientOptions()) {} + FakeOnlineFileSource() + : FakeOnlineFileSource(ResourceOptions::Default(), ClientOptions()) {} FakeOnlineFileSource(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) : FakeFileSource(resourceOptions_, clientOptions_) {} @@ -100,15 +91,15 @@ class FakeOnlineFileSource : public FakeFileSource { return FakeFileSource::request(resource, callback); } - bool respond(Resource::Kind kind, const Response& response) { - return FakeFileSource::respond(kind, response); - } + bool respond(Resource::Kind kind, const Response& response) { return FakeFileSource::respond(kind, response); } mapbox::base::Value getProperty(const std::string& property) const override { return onlineFs->getProperty(property); } - std::unique_ptr onlineFs = std::make_unique(ResourceOptions::Default(), ClientOptions()); + std::unique_ptr onlineFs = std::make_unique( + ResourceOptions::Default(), ClientOptions() + ); }; } // namespace mbgl diff --git a/test/src/mbgl/test/fixture_log_observer.cpp b/test/src/mbgl/test/fixture_log_observer.cpp index b27795abb45..e78705e04ae 100644 --- a/test/src/mbgl/test/fixture_log_observer.cpp +++ b/test/src/mbgl/test/fixture_log_observer.cpp @@ -4,20 +4,19 @@ namespace mbgl { -FixtureLog::Message::Message(EventSeverity severity_, - Event event_, - int64_t code_, - std::string msg_) - : severity(severity_), event(event_), code(code_), msg(std::move(msg_)) { -} +FixtureLog::Message::Message(EventSeverity severity_, Event event_, int64_t code_, std::string msg_) + : severity(severity_), + event(event_), + code(code_), + msg(std::move(msg_)) {} bool FixtureLog::Message::matches(const Message& rhs, bool substring) const { return severity == rhs.severity && event == rhs.event && code == rhs.code && (substring ? msg.find(rhs.msg) != std::string::npos : msg == rhs.msg); } -FixtureLog::Observer::Observer(FixtureLog* log_) : log(log_) { -} +FixtureLog::Observer::Observer(FixtureLog* log_) + : log(log_) {} FixtureLog::Observer::~Observer() { if (log) { @@ -26,10 +25,7 @@ FixtureLog::Observer::~Observer() { std::cerr << unchecked(); } -bool FixtureLog::Observer::onRecord(EventSeverity severity, - Event event, - int64_t code, - const std::string& msg) { +bool FixtureLog::Observer::onRecord(EventSeverity severity, Event event, int64_t code, const std::string& msg) { std::lock_guard lock(messagesMutex); if (severity != EventSeverity::Debug) { @@ -58,7 +54,8 @@ size_t FixtureLog::Observer::count(const Message& message, bool substring) const return message_count; } -FixtureLog::FixtureLog() : observer(new FixtureLogObserver(this)) { +FixtureLog::FixtureLog() + : observer(new FixtureLogObserver(this)) { Log::setObserver(std::unique_ptr(observer)); Log::useLogThread(false); } diff --git a/test/src/mbgl/test/fixture_log_observer.hpp b/test/src/mbgl/test/fixture_log_observer.hpp index 791337584d1..8454c875fe7 100644 --- a/test/src/mbgl/test/fixture_log_observer.hpp +++ b/test/src/mbgl/test/fixture_log_observer.hpp @@ -17,10 +17,10 @@ class FixtureLog { bool matches(const Message& rhs, bool substring = false) const; - const EventSeverity severity {}; - const Event event {}; - const int64_t code {}; - const std::string msg {}; + const EventSeverity severity{}; + const Event event{}; + const int64_t code{}; + const std::string msg{}; mutable bool checked = false; }; @@ -33,10 +33,7 @@ class FixtureLog { ~Observer() override; // Log::Observer implementation - bool onRecord(EventSeverity severity, - Event event, - int64_t code, - const std::string& msg) override; + bool onRecord(EventSeverity severity, Event event, int64_t code, const std::string& msg) override; bool empty() const; size_t uncheckedCount() const; @@ -61,9 +58,8 @@ class FixtureLog { Observer* observer; }; -::std::ostream &operator<<(::std::ostream &os, - const std::vector &messages); -::std::ostream &operator<<(::std::ostream &os, const FixtureLog::Observer::LogMessage &message); +::std::ostream& operator<<(::std::ostream& os, const std::vector& messages); +::std::ostream& operator<<(::std::ostream& os, const FixtureLog::Observer::LogMessage& message); using FixtureLogObserver = FixtureLog::Observer; diff --git a/test/src/mbgl/test/getrss.cpp b/test/src/mbgl/test/getrss.cpp index c21b653eaaa..9becc5c0826 100644 --- a/test/src/mbgl/test/getrss.cpp +++ b/test/src/mbgl/test/getrss.cpp @@ -18,41 +18,39 @@ namespace test { * memory use) measured in bytes, or zero if the value cannot be * determined on this OS. */ -size_t getPeakRSS( ) -{ +size_t getPeakRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.PeakWorkingSetSize; + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.PeakWorkingSetSize; -#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) - /* AIX and Solaris ------------------------------------------ */ - struct psinfo psinfo; - int fd = -1; - if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 ) - return (size_t)0L; /* Can't open? */ - if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) ) - { - close( fd ); - return (size_t)0L; /* Can't read? */ - } - close( fd ); - return (size_t)(psinfo.pr_rssize * 1024L); +#elif (defined(_AIX) || defined(__TOS__AIX__)) || \ + (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) + /* AIX and Solaris ------------------------------------------ */ + struct psinfo psinfo; + int fd = -1; + if ((fd = open("/proc/self/psinfo", O_RDONLY)) == -1) return (size_t)0L; /* Can't open? */ + if (read(fd, &psinfo, sizeof(psinfo)) != sizeof(psinfo)) { + close(fd); + return (size_t)0L; /* Can't read? */ + } + close(fd); + return (size_t)(psinfo.pr_rssize * 1024L); #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) - /* BSD, Linux, and OSX -------------------------------------- */ - struct rusage rusage; - getrusage( RUSAGE_SELF, &rusage ); + /* BSD, Linux, and OSX -------------------------------------- */ + struct rusage rusage; + getrusage(RUSAGE_SELF, &rusage); #if defined(__APPLE__) && defined(__MACH__) - return (size_t)rusage.ru_maxrss; + return (size_t)rusage.ru_maxrss; #else - return (size_t)(rusage.ru_maxrss * 1024L); + return (size_t)(rusage.ru_maxrss * 1024L); #endif #else - /* Unknown OS ----------------------------------------------- */ - return (size_t)0L; /* Unsupported. */ + /* Unknown OS ----------------------------------------------- */ + return (size_t)0L; /* Unsupported. */ #endif } @@ -60,43 +58,38 @@ size_t getPeakRSS( ) * Returns the current resident set size (physical memory use) measured * in bytes, or zero if the value cannot be determined on this OS. */ -size_t getCurrentRSS( ) -{ +size_t getCurrentRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.WorkingSetSize; + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.WorkingSetSize; #elif defined(__APPLE__) && defined(__MACH__) - /* OSX ------------------------------------------------------ */ - struct mach_task_basic_info info; - mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; - if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, - (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) - return (size_t)0L; /* Can't access? */ - return (size_t)info.resident_size; + /* OSX ------------------------------------------------------ */ + struct mach_task_basic_info info; + mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &infoCount) != KERN_SUCCESS) + return (size_t)0L; /* Can't access? */ + return (size_t)info.resident_size; #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) - /* Linux ---------------------------------------------------- */ - long rss = 0L; - FILE* fp = nullptr; - if ( (fp = fopen( "/proc/self/statm", "r" )) == nullptr ) - return (size_t)0L; /* Can't open? */ - if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) - { - fclose( fp ); - return (size_t)0L; /* Can't read? */ - } - fclose( fp ); - return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE); + /* Linux ---------------------------------------------------- */ + long rss = 0L; + FILE* fp = nullptr; + if ((fp = fopen("/proc/self/statm", "r")) == nullptr) return (size_t)0L; /* Can't open? */ + if (fscanf(fp, "%*s%ld", &rss) != 1) { + fclose(fp); + return (size_t)0L; /* Can't read? */ + } + fclose(fp); + return (size_t)rss * (size_t)sysconf(_SC_PAGESIZE); #else - /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ - return (size_t)0L; /* Unsupported. */ + /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ + return (size_t)0L; /* Unsupported. */ #endif } } // namespace test } // namespace mbgl - diff --git a/test/src/mbgl/test/getrss.hpp b/test/src/mbgl/test/getrss.hpp index 27b538b0240..82b4fff6f0b 100644 --- a/test/src/mbgl/test/getrss.hpp +++ b/test/src/mbgl/test/getrss.hpp @@ -8,10 +8,11 @@ #if defined(__APPLE__) && defined(__MACH__) #include -#include // for mach_port_t +#include // for mach_port_t #include -#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) +#elif (defined(_AIX) || defined(__TOS__AIX__)) || \ + (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) #include #include @@ -26,7 +27,6 @@ namespace mbgl { namespace test { - /** * Returns the peak (maximum so far) resident set size (physical diff --git a/test/src/mbgl/test/http_server.cpp b/test/src/mbgl/test/http_server.cpp index 2c48cf7faac..5679b1188be 100644 --- a/test/src/mbgl/test/http_server.cpp +++ b/test/src/mbgl/test/http_server.cpp @@ -205,6 +205,5 @@ HttpServer::~HttpServer() { serverThread.join(); } - } // namespace test } // namespace mbgl diff --git a/test/src/mbgl/test/map_adapter.hpp b/test/src/mbgl/test/map_adapter.hpp index d4af579ae15..5682215b255 100644 --- a/test/src/mbgl/test/map_adapter.hpp +++ b/test/src/mbgl/test/map_adapter.hpp @@ -10,10 +10,12 @@ class FileSource; // Non-public version of mbgl::Map that accepts a file source as parameter. class MapAdapter : public Map { public: - explicit MapAdapter(RendererFrontend& frontend, - MapObserver& observer, - std::shared_ptr fileSource, - const MapOptions& options) + explicit MapAdapter( + RendererFrontend& frontend, + MapObserver& observer, + std::shared_ptr fileSource, + const MapOptions& options + ) : Map(std::make_unique(frontend, observer, std::move(fileSource), options)) {} }; diff --git a/test/src/mbgl/test/mock.hpp b/test/src/mbgl/test/mock.hpp index c61cdf56f4e..418c3eaf4d6 100644 --- a/test/src/mbgl/test/mock.hpp +++ b/test/src/mbgl/test/mock.hpp @@ -12,7 +12,7 @@ struct MockTileData; struct MockSource { - mbgl::Range zoomRange { 0, 16 }; + mbgl::Range zoomRange{0, 16}; std::map> dataTiles; std::set idealTiles; @@ -22,21 +22,15 @@ struct MockSource { struct MockBucket {}; - struct MockTileData { - MockTileData(const mbgl::OverscaledTileID& tileID_) : tileID(tileID_) {} + MockTileData(const mbgl::OverscaledTileID& tileID_) + : tileID(tileID_) {} - bool hasTriedCache() const { - return triedOptional; - } + bool hasTriedCache() const { return triedOptional; } - bool isRenderable() const { - return renderable; - } + bool isRenderable() const { return renderable; } - bool isLoaded() const { - return loaded; - } + bool isLoaded() const { return loaded; } bool renderable = false; bool triedOptional = false; diff --git a/test/src/mbgl/test/sqlite3_test_fs.cpp b/test/src/mbgl/test/sqlite3_test_fs.cpp index 068ae9e1cfc..e4ec9e776e1 100644 --- a/test/src/mbgl/test/sqlite3_test_fs.cpp +++ b/test/src/mbgl/test/sqlite3_test_fs.cpp @@ -216,7 +216,7 @@ static int sqlite3_test_fs_open(sqlite3_vfs* vfs, const char* zName, sqlite3_fil return status; } -static int sqlite3_test_fs_delete(sqlite3_vfs* vfs, const char *zPath, int dirSync) { +static int sqlite3_test_fs_delete(sqlite3_vfs* vfs, const char* zPath, int dirSync) { if (sqlite3_test_fs_debug) { fprintf(stderr, "SQLite3: delete(name=%s, sync=%d)\n", zPath, dirSync); } @@ -227,7 +227,7 @@ static int sqlite3_test_fs_delete(sqlite3_vfs* vfs, const char *zPath, int dirSy return unix_fs->xDelete(unix_fs, zPath, dirSync); } -static int sqlite3_test_fs_access(sqlite3_vfs* vfs, const char *zPath, int flags, int *pResOut) { +static int sqlite3_test_fs_access(sqlite3_vfs* vfs, const char* zPath, int flags, int* pResOut) { if (sqlite3_test_fs_debug) { fprintf(stderr, "SQLite3: access(name=%s, flags=%d)\n", zPath, flags); } diff --git a/test/src/mbgl/test/sqlite3_test_fs.hpp b/test/src/mbgl/test/sqlite3_test_fs.hpp index 00351f49ac2..dd3b93dd7d1 100644 --- a/test/src/mbgl/test/sqlite3_test_fs.hpp +++ b/test/src/mbgl/test/sqlite3_test_fs.hpp @@ -16,21 +16,21 @@ class SQLite3TestFS { // Allow any type of I/O. Will fail with SQLITE_AUTH if set to false. This is useful to simulate // scenarios where the OS blocks an entire app's I/O, e.g. when it's in the background. void allowIO(bool); - + // Allow files to be opened. Will fail with SQLITE_CANTOPEN if set to false. void allowFileOpen(bool); - + // Allow files to be created. Will fail with SQLITE_CANTOPEN if set to false. void allowFileCreate(bool); - + // Allow N bytes to be read, then fail reads with SQLITE_IOERR. -1 == unlimited // This limit is global, not per file. void setReadLimit(int64_t); - + // Allow N bytes to be written, then fail writes with SQLITE_FULL. -1 == unlimited // This limit is global, not per file. void setWriteLimit(int64_t); - + // Reset all restrictions. void reset(); }; diff --git a/test/src/mbgl/test/stub_file_source.cpp b/test/src/mbgl/test/stub_file_source.cpp index 8b89e9581c1..13fec3c9e19 100644 --- a/test/src/mbgl/test/stub_file_source.cpp +++ b/test/src/mbgl/test/stub_file_source.cpp @@ -10,21 +10,24 @@ using namespace std::chrono_literals; class StubFileRequest : public AsyncRequest { public: StubFileRequest(StubFileSource& fileSource_) - : fileSource(fileSource_) { - } + : fileSource(fileSource_) {} - ~StubFileRequest() override { - fileSource.remove(this); - } + ~StubFileRequest() override { fileSource.remove(this); } StubFileSource& fileSource; }; -StubFileSource::StubFileSource(ResponseType type_): - StubFileSource::StubFileSource(ResourceOptions().withTileServerOptions(TileServerOptions::MapTilerConfiguration()), ClientOptions(), type_) {} - -StubFileSource::StubFileSource(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_, ResponseType type_) - : type(type_), resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()) { +StubFileSource::StubFileSource(ResponseType type_) + : StubFileSource::StubFileSource( + ResourceOptions().withTileServerOptions(TileServerOptions::MapTilerConfiguration()), ClientOptions(), type_ + ) {} + +StubFileSource::StubFileSource( + const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_, ResponseType type_ +) + : type(type_), + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) { if (type == ResponseType::Synchronous) { return; } @@ -86,29 +89,29 @@ mapbox::base::Value StubFileSource::getProperty(const std::string& key) const { std::optional StubFileSource::defaultResponse(const Resource& resource) { switch (resource.kind) { - case Resource::Kind::Style: - if (!styleResponse) throw std::runtime_error("unexpected style request"); - return styleResponse(resource); - case Resource::Kind::Source: - if (!sourceResponse) throw std::runtime_error("unexpected source request"); - return sourceResponse(resource); - case Resource::Kind::Tile: - if (!tileResponse) throw std::runtime_error("unexpected tile request"); - return tileResponse(resource); - case Resource::Kind::Glyphs: - if (!glyphsResponse) throw std::runtime_error("unexpected glyphs request"); - return glyphsResponse(resource); - case Resource::Kind::SpriteJSON: - if (!spriteJSONResponse) throw std::runtime_error("unexpected sprite JSON request"); - return spriteJSONResponse(resource); - case Resource::Kind::SpriteImage: - if (!spriteImageResponse) throw std::runtime_error("unexpected sprite image request"); - return spriteImageResponse(resource); - case Resource::Kind::Image: - if (!imageResponse) throw std::runtime_error("unexpected image request"); - return imageResponse(resource); - case Resource::Kind::Unknown: - throw std::runtime_error("unknown resource type"); + case Resource::Kind::Style: + if (!styleResponse) throw std::runtime_error("unexpected style request"); + return styleResponse(resource); + case Resource::Kind::Source: + if (!sourceResponse) throw std::runtime_error("unexpected source request"); + return sourceResponse(resource); + case Resource::Kind::Tile: + if (!tileResponse) throw std::runtime_error("unexpected tile request"); + return tileResponse(resource); + case Resource::Kind::Glyphs: + if (!glyphsResponse) throw std::runtime_error("unexpected glyphs request"); + return glyphsResponse(resource); + case Resource::Kind::SpriteJSON: + if (!spriteJSONResponse) throw std::runtime_error("unexpected sprite JSON request"); + return spriteJSONResponse(resource); + case Resource::Kind::SpriteImage: + if (!spriteImageResponse) throw std::runtime_error("unexpected sprite image request"); + return spriteImageResponse(resource); + case Resource::Kind::Image: + if (!imageResponse) throw std::runtime_error("unexpected image request"); + return imageResponse(resource); + case Resource::Kind::Unknown: + throw std::runtime_error("unknown resource type"); } // The above switch is exhaustive, but placate GCC nonetheless: diff --git a/test/src/mbgl/test/stub_file_source.hpp b/test/src/mbgl/test/stub_file_source.hpp index 63c5ee08c52..1bad4a74d22 100644 --- a/test/src/mbgl/test/stub_file_source.hpp +++ b/test/src/mbgl/test/stub_file_source.hpp @@ -29,10 +29,10 @@ class StubFileSource : public FileSource { void setProperty(const std::string&, const mapbox::base::Value&) override; mapbox::base::Value getProperty(const std::string&) const override; - using ResponseFunction = std::function (const Resource&)>; + using ResponseFunction = std::function(const Resource&)>; // You can set the response callback on a global level by assigning this callback: - ResponseFunction response = [this] (const Resource& resource) { + ResponseFunction response = [this](const Resource& resource) { return defaultResponse(resource); }; diff --git a/test/src/mbgl/test/stub_geometry_tile_feature.hpp b/test/src/mbgl/test/stub_geometry_tile_feature.hpp index e77692fc72b..5cfec100385 100644 --- a/test/src/mbgl/test/stub_geometry_tile_feature.hpp +++ b/test/src/mbgl/test/stub_geometry_tile_feature.hpp @@ -6,39 +6,34 @@ namespace mbgl { class StubGeometryTileFeature : public GeometryTileFeature { public: StubGeometryTileFeature(PropertyMap properties_) - : properties(std::move(properties_)) { - } + : properties(std::move(properties_)) {} - StubGeometryTileFeature(FeatureIdentifier id_, FeatureType type_, GeometryCollection geometry_, PropertyMap properties_) + StubGeometryTileFeature( + FeatureIdentifier id_, FeatureType type_, GeometryCollection geometry_, PropertyMap properties_ + ) : properties(std::move(properties_)), id(std::move(id_)), type(type_), - geometry(std::move(geometry_)) { - } + geometry(std::move(geometry_)) {} StubGeometryTileFeature(FeatureType type_, GeometryCollection geometry_) - : type(type_), geometry(std::move(geometry_)) {} + : type(type_), + geometry(std::move(geometry_)) {} PropertyMap properties; FeatureIdentifier id; FeatureType type = FeatureType::Point; GeometryCollection geometry; - FeatureType getType() const override { - return type; - } + FeatureType getType() const override { return type; } - FeatureIdentifier getID() const override { - return id; - } + FeatureIdentifier getID() const override { return id; } std::optional getValue(const std::string& key) const override { return properties.count(key) ? properties.at(key) : std::optional(); } - const GeometryCollection& getGeometries() const override { - return geometry; - } + const GeometryCollection& getGeometries() const override { return geometry; } }; } // namespace mbgl diff --git a/test/src/mbgl/test/stub_layer_observer.hpp b/test/src/mbgl/test/stub_layer_observer.hpp index 0fa413aefe4..91f6b9d418a 100644 --- a/test/src/mbgl/test/stub_layer_observer.hpp +++ b/test/src/mbgl/test/stub_layer_observer.hpp @@ -14,5 +14,5 @@ class StubLayerObserver : public style::LayerObserver { if (layerChanged) layerChanged(layer); } - std::function layerChanged; + std::function layerChanged; }; diff --git a/test/src/mbgl/test/stub_map_observer.hpp b/test/src/mbgl/test/stub_map_observer.hpp index f93c0d64788..6967f8d7972 100644 --- a/test/src/mbgl/test/stub_map_observer.hpp +++ b/test/src/mbgl/test/stub_map_observer.hpp @@ -59,5 +59,4 @@ class StubMapObserver : public MapObserver { std::function onRegisterShadersCallback; }; - } // namespace mbgl diff --git a/test/src/mbgl/test/stub_render_source_observer.hpp b/test/src/mbgl/test/stub_render_source_observer.hpp index ff20fff80c4..67743c54a94 100644 --- a/test/src/mbgl/test/stub_render_source_observer.hpp +++ b/test/src/mbgl/test/stub_render_source_observer.hpp @@ -13,11 +13,10 @@ class StubRenderSourceObserver : public RenderSourceObserver { if (tileChanged) tileChanged(source, tileID); }; - void - onTileError(RenderSource& source, const OverscaledTileID& tileID, std::exception_ptr error) override { + void onTileError(RenderSource& source, const OverscaledTileID& tileID, std::exception_ptr error) override { if (tileError) tileError(source, tileID, error); } - std::function tileChanged; - std::function tileError; + std::function tileChanged; + std::function tileError; }; diff --git a/test/src/mbgl/test/stub_style_observer.hpp b/test/src/mbgl/test/stub_style_observer.hpp index b97911cdb07..051bd497b98 100644 --- a/test/src/mbgl/test/stub_style_observer.hpp +++ b/test/src/mbgl/test/stub_style_observer.hpp @@ -30,9 +30,9 @@ class StubStyleObserver : public style::Observer { if (resourceError) resourceError(error); }; - std::function sourceLoaded; - std::function sourceChanged; - std::function sourceError; - std::function sourceDescriptionChanged; - std::function resourceError; + std::function sourceLoaded; + std::function sourceChanged; + std::function sourceError; + std::function sourceDescriptionChanged; + std::function resourceError; }; diff --git a/test/src/mbgl/test/stub_tile_observer.hpp b/test/src/mbgl/test/stub_tile_observer.hpp index 43ae4d8360e..9df556a1b53 100644 --- a/test/src/mbgl/test/stub_tile_observer.hpp +++ b/test/src/mbgl/test/stub_tile_observer.hpp @@ -17,6 +17,6 @@ class StubTileObserver : public TileObserver { if (tileError) tileError(tile, error); } - std::function tileChanged; - std::function tileError; + std::function tileChanged; + std::function tileError; }; diff --git a/test/src/mbgl/test/test.cpp b/test/src/mbgl/test/test.cpp index 4c47094dbc4..5b37ba19131 100644 --- a/test/src/mbgl/test/test.cpp +++ b/test/src/mbgl/test/test.cpp @@ -8,7 +8,7 @@ namespace mbgl { int runTests(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); - + // In order to run specific tests // testing::GTEST_FLAG(filter) = "TileServerOptions*"; // testing::GTEST_FLAG(filter) = "MainResourceLoader.ResourceOptions"; diff --git a/test/src/mbgl/test/util.cpp b/test/src/mbgl/test/util.cpp index 74298926521..23444a51aed 100644 --- a/test/src/mbgl/test/util.cpp +++ b/test/src/mbgl/test/util.cpp @@ -15,14 +15,12 @@ #pragma warning(pop) #endif - namespace mbgl { namespace test { -void checkImage(const std::string& base, - const PremultipliedImage& actual, - double imageThreshold, - double pixelThreshold) { +void checkImage( + const std::string& base, const PremultipliedImage& actual, double imageThreshold, double pixelThreshold +) { #if !TEST_READ_ONLY if (getenv("UPDATE")) { util::write_file(base + "/expected.png", encodePNG(actual)); @@ -39,8 +37,7 @@ void checkImage(const std::string& base, } PremultipliedImage expected = decodeImage(expected_image); - PremultipliedImage diff { expected.size }; - + PremultipliedImage diff{expected.size}; #if !TEST_READ_ONLY util::write_file(base + "/actual.png", encodePNG(actual)); @@ -48,12 +45,14 @@ void checkImage(const std::string& base, ASSERT_EQ(expected.size, actual.size); - uint64_t pixels = mapbox::pixelmatch(actual.data.get(), - expected.data.get(), - expected.size.width, - expected.size.height, - diff.data.get(), - pixelThreshold); + uint64_t pixels = mapbox::pixelmatch( + actual.data.get(), + expected.data.get(), + expected.size.width, + expected.size.height, + diff.data.get(), + pixelThreshold + ); EXPECT_LE(static_cast(pixels) / (expected.size.width * expected.size.height), imageThreshold); diff --git a/test/storage/asset_file_source.test.cpp b/test/storage/asset_file_source.test.cpp index bb25a3acdab..efe9d36facd 100644 --- a/test/storage/asset_file_source.test.cpp +++ b/test/storage/asset_file_source.test.cpp @@ -29,7 +29,8 @@ TEST(AssetFileSource, Load) { class TestWorker { public: - TestWorker(ActorRef, mbgl::AssetFileSource* fs_) : fs(fs_) {} + TestWorker(ActorRef, mbgl::AssetFileSource* fs_) + : fs(fs_) {} void run(std::function endCallback) { const std::string asset("asset://nonempty"); @@ -43,11 +44,11 @@ TEST(AssetFileSource, Load) { endCallback(); request.reset(); } else { - request = fs->request({ mbgl::Resource::Unknown, asset }, requestCallback); + request = fs->request({mbgl::Resource::Unknown, asset}, requestCallback); } }; - request = fs->request({ mbgl::Resource::Unknown, asset }, requestCallback); + request = fs->request({mbgl::Resource::Unknown, asset}, requestCallback); } private: @@ -62,10 +63,11 @@ TEST(AssetFileSource, Load) { std::vector>> threads; for (unsigned i = 0; i < numThreads; ++i) { - std::unique_ptr> thread = - std::make_unique>("Test", &fs); + std::unique_ptr> thread = std::make_unique>("Test", &fs); - thread->actor().invoke(&TestWorker::run, [&] { if (!--completed) loop.stop(); }); + thread->actor().invoke(&TestWorker::run, [&] { + if (!--completed) loop.stop(); + }); threads.push_back(std::move(thread)); } @@ -87,7 +89,7 @@ TEST(AssetFileSource, EmptyFile) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://empty" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://empty"}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -103,7 +105,7 @@ TEST(AssetFileSource, NonEmptyFile) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://nonempty" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://nonempty"}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -119,7 +121,7 @@ TEST(AssetFileSource, NonExistentFile) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://does_not_exist" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://does_not_exist"}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); @@ -136,7 +138,7 @@ TEST(AssetFileSource, InvalidURL) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "test://wrong-scheme" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "test://wrong-scheme"}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::Other, res.error->reason); @@ -153,7 +155,7 @@ TEST(AssetFileSource, ReadDirectory) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://directory" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://directory"}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); @@ -170,7 +172,7 @@ TEST(AssetFileSource, URLEncoding) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://%6eonempty" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://%6eonempty"}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); diff --git a/test/storage/database_file_source.test.cpp b/test/storage/database_file_source.test.cpp index f9f538c2f5e..c7e12693097 100644 --- a/test/storage/database_file_source.test.cpp +++ b/test/storage/database_file_source.test.cpp @@ -12,8 +12,9 @@ using namespace mbgl; TEST(DatabaseFileSource, PauseResume) { util::RunLoop loop; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{} + ); dbfs->pause(); const Resource res{Resource::Unknown, "http://127.0.0.1:3000/test", {}, Resource::LoadingMethod::CacheOnly}; @@ -28,8 +29,9 @@ TEST(DatabaseFileSource, PauseResume) { TEST(DatabaseFileSource, VolatileResource) { util::RunLoop loop; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{} + ); Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test", {}, Resource::LoadingMethod::CacheOnly}; Response response{}; diff --git a/test/storage/http_file_source.test.cpp b/test/storage/http_file_source.test.cpp index 7e9ba966d72..0092bda2237 100644 --- a/test/storage/http_file_source.test.cpp +++ b/test/storage/http_file_source.test.cpp @@ -13,7 +13,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(Cancel)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - fs.request({ Resource::Unknown, "http://127.0.0.1:3000/test" }, [&](Response) { + fs.request({Resource::Unknown, "http://127.0.0.1:3000/test"}, [&](Response) { ADD_FAILURE() << "Callback should not be called"; }); @@ -24,7 +24,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP200)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/test" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/test"}, [&](Response res) { EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); EXPECT_EQ("Hello World!", *res.data); @@ -42,7 +42,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP404)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/doesnotexist" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/doesnotexist"}, [&](Response res) { ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); EXPECT_EQ("HTTP status code 404", res.error->message); @@ -61,7 +61,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTPTile404)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Tile, "http://127.0.0.1:3000/doesnotexist" }, [&](Response res) { + auto req = fs.request({Resource::Tile, "http://127.0.0.1:3000/doesnotexist"}, [&](Response res) { EXPECT_TRUE(res.noContent); EXPECT_FALSE(bool(res.error)); EXPECT_FALSE(bool(res.data)); @@ -79,7 +79,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP200EmptyData)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/empty-data" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/empty-data"}, [&](Response res) { EXPECT_FALSE(res.noContent); EXPECT_FALSE(bool(res.error)); EXPECT_EQ(*res.data, std::string()); @@ -97,7 +97,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP204)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/no-content" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/no-content"}, [&](Response res) { EXPECT_TRUE(res.noContent); EXPECT_FALSE(bool(res.error)); EXPECT_FALSE(bool(res.data)); @@ -115,7 +115,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP500)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/permanent-error" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/permanent-error"}, [&](Response res) { ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::Server, res.error->reason); EXPECT_EQ("HTTP status code 500", res.error->message); @@ -134,17 +134,19 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(ExpiresParsing)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, - "http://127.0.0.1:3000/test?modified=1420794326&expires=1420797926&etag=foo" }, [&](Response res) { - EXPECT_EQ(nullptr, res.error); - ASSERT_TRUE(res.data.get()); - EXPECT_EQ("Hello World!", *res.data); - EXPECT_EQ(Timestamp{ Seconds(1420797926) }, res.expires); - EXPECT_FALSE(res.mustRevalidate); - EXPECT_EQ(Timestamp{ Seconds(1420794326) }, res.modified); - EXPECT_EQ("foo", *res.etag); - loop.stop(); - }); + auto req = fs.request( + {Resource::Unknown, "http://127.0.0.1:3000/test?modified=1420794326&expires=1420797926&etag=foo"}, + [&](Response res) { + EXPECT_EQ(nullptr, res.error); + ASSERT_TRUE(res.data.get()); + EXPECT_EQ("Hello World!", *res.data); + EXPECT_EQ(Timestamp{Seconds(1420797926)}, res.expires); + EXPECT_FALSE(res.mustRevalidate); + EXPECT_EQ(Timestamp{Seconds(1420794326)}, res.modified); + EXPECT_EQ("foo", *res.etag); + loop.stop(); + } + ); loop.run(); } @@ -153,16 +155,18 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(CacheControlParsing)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/test?cachecontrol=max-age=120" }, [&](Response res) { - EXPECT_EQ(nullptr, res.error); - ASSERT_TRUE(res.data.get()); - EXPECT_EQ("Hello World!", *res.data); - EXPECT_GT(Seconds(2), util::abs(*res.expires - util::now() - Seconds(120))) << "Expiration date isn't about 120 seconds in the future"; - EXPECT_FALSE(res.mustRevalidate); - EXPECT_FALSE(bool(res.modified)); - EXPECT_FALSE(bool(res.etag)); - loop.stop(); - }); + auto req = + fs.request({Resource::Unknown, "http://127.0.0.1:3000/test?cachecontrol=max-age=120"}, [&](Response res) { + EXPECT_EQ(nullptr, res.error); + ASSERT_TRUE(res.data.get()); + EXPECT_EQ("Hello World!", *res.data); + EXPECT_GT(Seconds(2), util::abs(*res.expires - util::now() - Seconds(120))) + << "Expiration date isn't about 120 seconds in the future"; + EXPECT_FALSE(res.mustRevalidate); + EXPECT_FALSE(bool(res.modified)); + EXPECT_FALSE(bool(res.etag)); + loop.stop(); + }); loop.run(); } @@ -179,24 +183,25 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(Load)) { std::function req = [&](int i) { const auto current = number++; - reqs[i] = fs.request({ Resource::Unknown, - std::string("http://127.0.0.1:3000/load/") + util::toString(current) }, - [&, i, current](Response res) { - reqs[i].reset(); - EXPECT_EQ(nullptr, res.error); - ASSERT_TRUE(res.data.get()); - EXPECT_EQ(std::string("Request ") + util::toString(current), *res.data); - EXPECT_FALSE(bool(res.expires)); - EXPECT_FALSE(res.mustRevalidate); - EXPECT_FALSE(bool(res.modified)); - EXPECT_FALSE(bool(res.etag)); - - if (number <= max) { - req(i); - } else if (current == max) { - loop.stop(); + reqs[i] = fs.request( + {Resource::Unknown, std::string("http://127.0.0.1:3000/load/") + util::toString(current)}, + [&, i, current](Response res) { + reqs[i].reset(); + EXPECT_EQ(nullptr, res.error); + ASSERT_TRUE(res.data.get()); + EXPECT_EQ(std::string("Request ") + util::toString(current), *res.data); + EXPECT_FALSE(bool(res.expires)); + EXPECT_FALSE(res.mustRevalidate); + EXPECT_FALSE(bool(res.modified)); + EXPECT_FALSE(bool(res.etag)); + + if (number <= max) { + req(i); + } else if (current == max) { + loop.stop(); + } } - }); + ); }; for (int i = 0; i < concurrency; i++) { diff --git a/test/storage/local_file_source.test.cpp b/test/storage/local_file_source.test.cpp index 60655a469cf..c9f10d57319 100644 --- a/test/storage/local_file_source.test.cpp +++ b/test/storage/local_file_source.test.cpp @@ -21,11 +21,11 @@ namespace { std::string toAbsoluteURL(const std::string& fileName) { char buff[PATH_MAX + 1]; #ifdef _MSC_VER - char* cwd = _getcwd( buff, PATH_MAX + 1 ); + char* cwd = _getcwd(buff, PATH_MAX + 1); #else - char* cwd = getcwd( buff, PATH_MAX + 1 ); + char* cwd = getcwd(buff, PATH_MAX + 1); #endif - std::string url = { "file://" + std::string(cwd) + "/test/fixtures/storage/assets/" + fileName }; + std::string url = {"file://" + std::string(cwd) + "/test/fixtures/storage/assets/" + fileName}; assert(url.size() <= PATH_MAX); return url; } @@ -49,7 +49,7 @@ TEST(LocalFileSource, EmptyFile) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("empty") }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL("empty")}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -65,7 +65,7 @@ TEST(LocalFileSource, NonEmptyFile) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("nonempty") }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL("nonempty")}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -81,14 +81,15 @@ TEST(LocalFileSource, NonExistentFile) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("does_not_exist") }, [&](Response res) { - req.reset(); - ASSERT_NE(nullptr, res.error); - EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); - ASSERT_FALSE(res.data.get()); - // Do not assert on platform-specific error message. - loop.stop(); - }); + std::unique_ptr req = + fs.request({Resource::Unknown, toAbsoluteURL("does_not_exist")}, [&](Response res) { + req.reset(); + ASSERT_NE(nullptr, res.error); + EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); + ASSERT_FALSE(res.data.get()); + // Do not assert on platform-specific error message. + loop.stop(); + }); loop.run(); } @@ -98,7 +99,7 @@ TEST(LocalFileSource, InvalidURL) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "test://wrong-scheme" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "test://wrong-scheme"}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::Other, res.error->reason); @@ -115,7 +116,7 @@ TEST(LocalFileSource, ReadDirectory) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("directory") }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL("directory")}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); @@ -132,7 +133,7 @@ TEST(LocalFileSource, URLEncoding) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("%6eonempty") }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL("%6eonempty")}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -155,7 +156,7 @@ TEST(LocalFileSource, URLLimit) { delete[] filename; - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL(url) }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL(url)}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); #if defined(_MSC_VER) && !defined(__clang__) diff --git a/test/storage/main_resource_loader.test.cpp b/test/storage/main_resource_loader.test.cpp index 88012b58a6c..561a157263f 100644 --- a/test/storage/main_resource_loader.test.cpp +++ b/test/storage/main_resource_loader.test.cpp @@ -292,8 +292,9 @@ TEST(MainResourceLoader, OptionalNonExpired) { response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); dbfs->forward(optionalResource, response, [&] { req = fs.request(optionalResource, [&](Response res) { req.reset(); @@ -324,8 +325,9 @@ TEST(MainResourceLoader, OptionalExpired) { Response response; response.data = std::make_shared("Cached value"); response.expires = util::now() - 1h; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); std::unique_ptr req; dbfs->forward(optionalResource, response, [&] { req = fs.request(optionalResource, [&](Response res) { @@ -376,7 +378,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshEtagNotModified)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-same" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-same"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.priorEtag.emplace("snowfall"); @@ -387,8 +389,9 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshEtagNotModified)) { response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -413,7 +416,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshEtagModified)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-same" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-same"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.priorEtag.emplace("sunshine"); @@ -424,8 +427,9 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshEtagModified)) { response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -450,7 +454,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheFull)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-same" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-same"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; using namespace std::chrono_literals; @@ -460,8 +464,9 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheFull)) { response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -487,7 +492,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedNotModified) util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-modified" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-modified"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.priorModified.emplace(Seconds(1420070400)); // January 1, 2015 @@ -498,8 +503,9 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedNotModified) response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -525,7 +531,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedModified)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-modified" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-modified"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.priorModified.emplace(Seconds(1417392000)); // December 1, 2014 @@ -536,8 +542,9 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedModified)) { response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -559,24 +566,28 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedModified)) { TEST(MainResourceLoader, TEST_REQUIRES_SERVER(SetResourceTransform)) { util::RunLoop loop; MainResourceLoader resourceLoader(ResourceOptions{}, ClientOptions{}); - std::shared_ptr onlinefs = - FileSourceManager::get()->getFileSource(FileSourceType::Network, ResourceOptions{}, ClientOptions{}); + std::shared_ptr onlinefs = FileSourceManager::get()->getFileSource( + FileSourceType::Network, ResourceOptions{}, ClientOptions{} + ); // Translates the URL "localhost://test to http://127.0.0.1:3000/test Actor transform( - loop, [](Resource::Kind, const std::string& url, ResourceTransform::FinishedCallback cb) { + loop, + [](Resource::Kind, const std::string& url, ResourceTransform::FinishedCallback cb) { if (url == "localhost://test") { cb("http://127.0.0.1:3000/test"); } else { cb(url); } - }); + } + ); onlinefs->setResourceTransform( - {[actorRef = transform.self()]( - Resource::Kind kind, const std::string& url, ResourceTransform::FinishedCallback cb) { + {[actorRef = transform.self( + )](Resource::Kind kind, const std::string& url, ResourceTransform::FinishedCallback cb) { actorRef.invoke(&ResourceTransform::TransformCallback::operator(), kind, url, std::move(cb)); - }}); + }} + ); const Resource resource1{Resource::Unknown, "localhost://test"}; std::unique_ptr req; @@ -615,8 +626,9 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(SetResourceTransform)) { TEST(MainResourceLoader, SetResourceCachePath) { util::RunLoop loop; MainResourceLoader resourceLoader(ResourceOptions{}, ClientOptions{}); - std::shared_ptr fs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr fs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); auto dbfs = std::static_pointer_cast(fs); dbfs->setDatabasePath("./new_offline.db", [&loop] { loop.stop(); }); loop.run(); @@ -627,7 +639,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(RespondToStaleMustRevalidate)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-same" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-same"}; resource.loadingMethod = Resource::LoadingMethod::CacheOnly; // using namespace std::chrono_literals; @@ -640,8 +652,9 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(RespondToStaleMustRevalidate)) { response.mustRevalidate = true; response.etag.emplace("snowfall"); std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -693,7 +706,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(RespondToStaleMustRevalidate)) { EXPECT_LE(util::now(), *res.expires); EXPECT_TRUE(res.mustRevalidate); ASSERT_TRUE(res.modified); - EXPECT_EQ(Timestamp{ Seconds(1417392000) }, *res.modified); + EXPECT_EQ(Timestamp{Seconds(1417392000)}, *res.modified); ASSERT_TRUE(res.etag); EXPECT_EQ("snowfall", *res.etag); loop.stop(); @@ -713,10 +726,12 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CachedResourceLowPriority)) { using namespace std::chrono_literals; response.expires = util::now() - 1h; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); - std::shared_ptr onlineFs = - FileSourceManager::get()->getFileSource(FileSourceType::Network, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); + std::shared_ptr onlineFs = FileSourceManager::get()->getFileSource( + FileSourceType::Network, ResourceOptions{}, ClientOptions{} + ); // Put existing values into the cache. Resource resource1{Resource::Unknown, "http://127.0.0.1:3000/load/3", {}, Resource::LoadingMethod::All}; @@ -801,8 +816,9 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoDoubleDispatch)) { std::unique_ptr req; unsigned responseCount = 0u; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{} + ); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { EXPECT_EQ(nullptr, res.error); @@ -829,23 +845,19 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoDoubleDispatch)) { TEST(MainResourceLoader, ResourceOptions) { MainResourceLoader fs( ResourceOptions().withTileServerOptions( - TileServerOptions() - .withBaseURL("originalBaseURL") - .withUriSchemeAlias("originalAlias") - ), + TileServerOptions().withBaseURL("originalBaseURL").withUriSchemeAlias("originalAlias") + ), ClientOptions() ); - - fs.setResourceOptions(ResourceOptions() - .withTileServerOptions( - TileServerOptions() - .withBaseURL("updatedBaseURL") - .withUriSchemeAlias("updatedAlias") - ).clone() + + fs.setResourceOptions( + ResourceOptions() + .withTileServerOptions(TileServerOptions().withBaseURL("updatedBaseURL").withUriSchemeAlias("updatedAlias")) + .clone() ); - + auto updatedOptions = fs.getResourceOptions().tileServerOptions(); - + EXPECT_EQ(updatedOptions.baseURL(), "updatedBaseURL"); - EXPECT_EQ(updatedOptions.uriSchemeAlias(), "updatedAlias"); + EXPECT_EQ(updatedOptions.uriSchemeAlias(), "updatedAlias"); } diff --git a/test/storage/mbtiles_file_source.test.cpp b/test/storage/mbtiles_file_source.test.cpp index c3246844799..d432472a51b 100644 --- a/test/storage/mbtiles_file_source.test.cpp +++ b/test/storage/mbtiles_file_source.test.cpp @@ -8,12 +8,12 @@ #include #if defined(WIN32) -# include -# ifndef PATH_MAX -# define PATH_MAX MAX_PATH -# endif /* PATH_MAX */ +#include +#ifndef PATH_MAX +#define PATH_MAX MAX_PATH +#endif /* PATH_MAX */ #else -# include +#include #endif namespace { @@ -25,8 +25,7 @@ std::string toAbsoluteURL(const std::string &fileName) { #else char *cwd = getcwd(buff, PATH_MAX + 1); #endif - std::string url - = {"mbtiles://" + std::string(cwd) + "/test/fixtures/storage/mbtiles/" + fileName}; + std::string url = {"mbtiles://" + std::string(cwd) + "/test/fixtures/storage/mbtiles/" + fileName}; assert(url.size() <= PATH_MAX); return url; } @@ -49,8 +48,8 @@ TEST(MBTilesFileSource, AbsolutePath) { MBTilesFileSource mbtiles(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = mbtiles.request( - {Resource::Unknown, "mbtiles://not_absolute"}, [&](Response res) { + std::unique_ptr req = + mbtiles.request({Resource::Unknown, "mbtiles://not_absolute"}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::Other, res.error->reason); @@ -68,15 +67,15 @@ TEST(MBTilesFileSource, NonExistentFile) { MBTilesFileSource mbtiles(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = mbtiles.request( - {Resource::Unknown, toAbsoluteURL("does_not_exist")}, [&](Response res) { - req.reset(); - ASSERT_NE(nullptr, res.error); - EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); - EXPECT_NE((res.error->message).find("path not found"), std::string::npos); - ASSERT_FALSE(res.data.get()); - loop.stop(); - }); + std::unique_ptr req = + mbtiles.request({Resource::Unknown, toAbsoluteURL("does_not_exist")}, [&](Response res) { + req.reset(); + ASSERT_NE(nullptr, res.error); + EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); + EXPECT_NE((res.error->message).find("path not found"), std::string::npos); + ASSERT_FALSE(res.data.get()); + loop.stop(); + }); loop.run(); } @@ -87,14 +86,13 @@ TEST(MBTilesFileSource, TileJSON) { MBTilesFileSource mbtiles(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = mbtiles.request( - {Resource::Unknown, toAbsoluteURL("geography-class-png.mbtiles")}, [&](Response res) { + std::unique_ptr req = + mbtiles.request({Resource::Unknown, toAbsoluteURL("geography-class-png.mbtiles")}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); // basic test that TileJSON included a tile URL - EXPECT_NE((*res.data).find("geography-class-png.mbtiles?file={x}/{y}/{z}"), - std::string::npos); + EXPECT_NE((*res.data).find("geography-class-png.mbtiles?file={x}/{y}/{z}"), std::string::npos); loop.stop(); }); @@ -108,14 +106,17 @@ TEST(MBTilesFileSource, Tile) { MBTilesFileSource mbtiles(ResourceOptions::Default(), ClientOptions()); std::unique_ptr req = mbtiles.request( - Resource::tile(toAbsoluteURL("geography-class-png.mbtiles?file={z}/{x}/{y}.png"), 1.0, 0, 0, 0, Tileset::Scheme::XYZ), + Resource::tile( + toAbsoluteURL("geography-class-png.mbtiles?file={z}/{x}/{y}.png"), 1.0, 0, 0, 0, Tileset::Scheme::XYZ + ), [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); ASSERT_EQ(res.noContent, false); loop.stop(); - }); + } + ); loop.run(); } @@ -127,16 +128,17 @@ TEST(MBTilesFileSource, NonExistentTile) { MBTilesFileSource mbtiles(ResourceOptions::Default(), ClientOptions()); std::unique_ptr req = mbtiles.request( - Resource::tile(toAbsoluteURL("geography-class-png.mbtiles?file={z}/{x}/{y}.png"), 1.0, 0, 0, 4, Tileset::Scheme::XYZ), + Resource::tile( + toAbsoluteURL("geography-class-png.mbtiles?file={z}/{x}/{y}.png"), 1.0, 0, 0, 4, Tileset::Scheme::XYZ + ), [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_FALSE(res.data.get()); ASSERT_EQ(res.noContent, true); loop.stop(); - }); + } + ); loop.run(); } - - diff --git a/test/storage/offline.test.cpp b/test/storage/offline.test.cpp index eb7cbf705b1..82d3f3e4dc9 100644 --- a/test/storage/offline.test.cpp +++ b/test/storage/offline.test.cpp @@ -6,13 +6,14 @@ using namespace mbgl; using SourceType = mbgl::style::SourceType; - TEST(OfflineTilePyramidRegionDefinition, EncodeDecode) { - OfflineTilePyramidRegionDefinition region("maptiler://style", LatLngBounds::hull({ 37.6609, -122.5744 }, { 37.8271, -122.3204 }), 0, 20, 1.0, true); + OfflineTilePyramidRegionDefinition region( + "maptiler://style", LatLngBounds::hull({37.6609, -122.5744}, {37.8271, -122.3204}), 0, 20, 1.0, true + ); auto encoded = encodeOfflineRegionDefinition(region); auto decoded = decodeOfflineRegionDefinition(encoded).get(); - + EXPECT_EQ(decoded.styleURL, region.styleURL); EXPECT_EQ(decoded.minZoom, region.minZoom); EXPECT_EQ(decoded.maxZoom, region.maxZoom); @@ -27,7 +28,7 @@ TEST(OfflineGeometryRegionDefinition, EncodeDecode) { auto encoded = encodeOfflineRegionDefinition(region); auto decoded = decodeOfflineRegionDefinition(encoded).get(); - + EXPECT_EQ(decoded.styleURL, region.styleURL); EXPECT_EQ(decoded.minZoom, region.minZoom); EXPECT_EQ(decoded.maxZoom, region.maxZoom); diff --git a/test/storage/offline_database.test.cpp b/test/storage/offline_database.test.cpp index 297211610ea..5c26e16b23e 100644 --- a/test/storage/offline_database.test.cpp +++ b/test/storage/offline_database.test.cpp @@ -47,41 +47,41 @@ static std::shared_ptr randomString(size_t size) { } static FixtureLog::Message error(ResultCode code, const char* message) { - return { EventSeverity::Error, Event::Database, static_cast(code), message }; + return {EventSeverity::Error, Event::Database, static_cast(code), message}; } static MBGL_UNUSED FixtureLog::Message warning(ResultCode code, const char* message) { - return { EventSeverity::Warning, Event::Database, static_cast(code), message }; + return {EventSeverity::Warning, Event::Database, static_cast(code), message}; } static int databasePageCount(const std::string& path) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); - mapbox::sqlite::Statement stmt{ db, "pragma page_count" }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, "pragma page_count"}; + mapbox::sqlite::Query query{stmt}; query.run(); return query.get(0); } static int databaseUserVersion(const std::string& path) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); - mapbox::sqlite::Statement stmt{ db, "pragma user_version" }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, "pragma user_version"}; + mapbox::sqlite::Query query{stmt}; query.run(); return query.get(0); } static std::string databaseJournalMode(const std::string& path) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); - mapbox::sqlite::Statement stmt{ db, "pragma journal_mode" }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, "pragma journal_mode"}; + mapbox::sqlite::Query query{stmt}; query.run(); return query.get(0); } static int databaseSyncMode(const std::string& path) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); - mapbox::sqlite::Statement stmt{ db, "pragma synchronous" }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, "pragma synchronous"}; + mapbox::sqlite::Query query{stmt}; query.run(); return query.get(0); } @@ -89,8 +89,8 @@ static int databaseSyncMode(const std::string& path) { static std::vector databaseTableColumns(const std::string& path, const std::string& name) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); const auto sql = std::string("pragma table_info(") + name + ")"; - mapbox::sqlite::Statement stmt{ db, sql.c_str() }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, sql.c_str()}; + mapbox::sqlite::Query query{stmt}; std::vector columns; while (query.run()) { columns.push_back(query.get(1)); @@ -108,7 +108,7 @@ static int databaseAutoVacuum(const std::string& path) { namespace fixture { -const Resource resource{ Resource::Style, "maptiler://test" }; +const Resource resource{Resource::Style, "maptiler://test"}; const Resource tile = Resource::tile("maptiler://test", 1, 0, 0, 0, Tileset::Scheme::XYZ); const Response response = [] { Response res; @@ -124,7 +124,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(Create)) { FixtureLog log; deleteDatabaseFiles(); OfflineDatabase db(filename, fixture::tileServerOptions); - EXPECT_FALSE(bool(db.get({ Resource::Unknown, "maptiler://test" }))); + EXPECT_FALSE(bool(db.get({Resource::Unknown, "maptiler://test"}))); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -145,14 +145,14 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(CreateFail)) { EXPECT_EQ(0u, log.uncheckedCount()); // We can try to insert things into the cache, but since the cache database isn't open, it won't be stored. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(false, uint64_t(0)), db.put(res, fixture::response)); EXPECT_EQ(1u, log.count(warning(ResultCode::CantOpen, "Can't write resource: unable to open database file"))); EXPECT_EQ(0u, log.uncheckedCount()); } // We can also still "query" the database even though it is not open, and we will always get an empty result. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_FALSE(bool(db.get(res))); EXPECT_EQ(1u, log.count(warning(ResultCode::CantOpen, "Can't update timestamp: unable to open database file"))); EXPECT_EQ(1u, log.count(warning(ResultCode::CantOpen, "Can't read resource: unable to open database file"))); @@ -162,7 +162,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(CreateFail)) { // Now, we're "freeing up" some space on the disk, and try to insert and query again. This time, we should // be opening the datbase, creating the schema, and writing the data so that we can retrieve it again. fs.allowFileCreate(true); - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); auto result = db.get(res); EXPECT_EQ(0u, log.uncheckedCount()); @@ -175,7 +175,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(CreateFail)) { // accessed timestamp may fail without crashing. fs.allowFileCreate(false); fs.setWriteLimit(0); - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { auto result = db.get(res); EXPECT_EQ(1u, log.count(warning(ResultCode::CantOpen, "Can't update timestamp: unable to open database file"))); EXPECT_EQ(0u, log.uncheckedCount()); @@ -190,7 +190,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(CreateFail)) { // timestamp update. fs.allowFileCreate(true); fs.setWriteLimit(8192); - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { auto result = db.get(res); EXPECT_EQ(1u, log.count(warning(ResultCode::Full, "Can't update timestamp: database or disk is full"))); EXPECT_EQ(0u, log.uncheckedCount()); @@ -202,7 +202,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(CreateFail)) { // any disk I/O at all. fs.setWriteLimit(-1); fs.allowIO(false); - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { // First, try reading. auto result = db.get(res); EXPECT_EQ(1u, log.count(warning(ResultCode::Auth, "Can't update timestamp: authorization denied"))); @@ -231,15 +231,13 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(SchemaVersion)) { db.exec("PRAGMA user_version = 1"); } - { - OfflineDatabase db(filename, fixture::tileServerOptions); - } + { OfflineDatabase db(filename, fixture::tileServerOptions); } EXPECT_EQ(6, databaseUserVersion(filename)); OfflineDatabase db(filename, fixture::tileServerOptions); // Now try inserting and reading back to make sure we have a valid database. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); EXPECT_EQ(0u, log.uncheckedCount()); auto result = db.get(res); @@ -258,12 +256,17 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(Invalid)) { OfflineDatabase db(filename, fixture::tileServerOptions); // Checking two possibilities for the error string because it apparently changes between SQLite versions. - EXPECT_EQ(1u, log.count(error(ResultCode::NotADB, "Can't open database: file is encrypted or is not a database"), true) + - log.count(error(ResultCode::NotADB, "Can't open database: file is not a database"), true)); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + EXPECT_EQ( + 1u, + log.count(error(ResultCode::NotADB, "Can't open database: file is encrypted or is not a database"), true) + + log.count(error(ResultCode::NotADB, "Can't open database: file is not a database"), true) + ); + EXPECT_EQ( + 1u, log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"}) + ); // Now try inserting and reading back to make sure we have a valid database. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); EXPECT_EQ(0u, log.uncheckedCount()); auto result = db.get(res); @@ -277,7 +280,7 @@ TEST(OfflineDatabase, PutDoesNotStoreConnectionErrors) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Unknown, "http://example.com/" }; + Resource resource{Resource::Unknown, "http://example.com/"}; Response response; response.error = std::make_unique(Response::Error::Reason::Connection); @@ -291,7 +294,7 @@ TEST(OfflineDatabase, PutDoesNotStoreServerErrors) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Unknown, "http://example.com/" }; + Resource resource{Resource::Unknown, "http://example.com/"}; Response response; response.error = std::make_unique(Response::Error::Reason::Server); @@ -305,7 +308,7 @@ TEST(OfflineDatabase, PutResource) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Style, "http://example.com/" }; + Resource resource{Resource::Style, "http://example.com/"}; Response response; response.data = std::make_shared("first"); @@ -364,14 +367,8 @@ TEST(OfflineDatabase, PutTile) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Tile, "http://example.com/" }; - resource.tileData = Resource::TileData { - "http://example.com/", - 1, - 0, - 0, - 0 - }; + Resource resource{Resource::Tile, "http://example.com/"}; + resource.tileData = Resource::TileData{"http://example.com/", 1, 0, 0, 0}; Response response; response.data = std::make_shared("first"); @@ -399,7 +396,7 @@ TEST(OfflineDatabase, PutResourceNoContent) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Style, "http://example.com/" }; + Resource resource{Resource::Style, "http://example.com/"}; Response response; response.noContent = true; @@ -416,14 +413,8 @@ TEST(OfflineDatabase, PutTileNotFound) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Tile, "http://example.com/" }; - resource.tileData = Resource::TileData { - "http://example.com/", - 1, - 0, - 0, - 0 - }; + Resource resource{Resource::Tile, "http://example.com/"}; + resource.tileData = Resource::TileData{"http://example.com/", 1, 0, 0, 0}; Response response; response.noContent = true; @@ -439,24 +430,24 @@ TEST(OfflineDatabase, PutTileNotFound) { TEST(OfflineDatabase, CreateRegion) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); EXPECT_EQ(0u, log.uncheckedCount()); region->getDefinition().match( - [&](OfflineTilePyramidRegionDefinition& def) { - EXPECT_EQ(definition.styleURL, def.styleURL); - EXPECT_EQ(definition.bounds, def.bounds); - EXPECT_EQ(definition.minZoom, def.minZoom); - EXPECT_EQ(definition.maxZoom, def.maxZoom); - EXPECT_EQ(definition.pixelRatio, def.pixelRatio); - EXPECT_EQ(definition.includeIdeographs, def.includeIdeographs); - }, [](auto&) { - EXPECT_FALSE(false); - } + [&](OfflineTilePyramidRegionDefinition& def) { + EXPECT_EQ(definition.styleURL, def.styleURL); + EXPECT_EQ(definition.bounds, def.bounds); + EXPECT_EQ(definition.minZoom, def.minZoom); + EXPECT_EQ(definition.maxZoom, def.maxZoom); + EXPECT_EQ(definition.pixelRatio, def.pixelRatio); + EXPECT_EQ(definition.includeIdeographs, def.includeIdeographs); + }, + [](auto&) { EXPECT_FALSE(false); } ); EXPECT_EQ(metadata, region->getMetadata()); } @@ -464,12 +455,13 @@ TEST(OfflineDatabase, CreateRegion) { TEST(OfflineDatabase, UpdateMetadata) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); - OfflineRegionMetadata newmetadata {{ 4, 5, 6 }}; + OfflineRegionMetadata newmetadata{{4, 5, 6}}; db.updateMetadata(region->getID(), newmetadata); auto regions = db.listRegions().value(); EXPECT_EQ(regions.at(0).getMetadata(), newmetadata); @@ -480,8 +472,9 @@ TEST(OfflineDatabase, UpdateMetadata) { TEST(OfflineDatabase, ListRegions) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); @@ -491,17 +484,16 @@ TEST(OfflineDatabase, ListRegions) { EXPECT_EQ(region->getID(), regions.at(0).getID()); regions.at(0).getDefinition().match( - [&](OfflineTilePyramidRegionDefinition& def) { - EXPECT_EQ(definition.styleURL, def.styleURL); - EXPECT_EQ(definition.bounds, def.bounds); - EXPECT_EQ(definition.minZoom, def.minZoom); - EXPECT_EQ(definition.maxZoom, def.maxZoom); - EXPECT_EQ(definition.pixelRatio, def.pixelRatio); - EXPECT_EQ(definition.includeIdeographs, def.includeIdeographs); - }, - [&](auto&) { - EXPECT_FALSE(false); - }); + [&](OfflineTilePyramidRegionDefinition& def) { + EXPECT_EQ(definition.styleURL, def.styleURL); + EXPECT_EQ(definition.bounds, def.bounds); + EXPECT_EQ(definition.minZoom, def.minZoom); + EXPECT_EQ(definition.maxZoom, def.maxZoom); + EXPECT_EQ(definition.pixelRatio, def.pixelRatio); + EXPECT_EQ(definition.includeIdeographs, def.includeIdeographs); + }, + [&](auto&) { EXPECT_FALSE(false); } + ); EXPECT_EQ(metadata, regions.at(0).getMetadata()); EXPECT_EQ(0u, log.uncheckedCount()); @@ -510,13 +502,15 @@ TEST(OfflineDatabase, ListRegions) { TEST(OfflineDatabase, GetRegionDefinition) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false}; + OfflineRegionMetadata metadata{{1, 2, 3}}; EXPECT_EQ(0u, log.uncheckedCount()); auto region = db.createRegion(definition, metadata); - db.getRegionDefinition(region->getID())->match( + db.getRegionDefinition(region->getID()) + ->match( [&](OfflineTilePyramidRegionDefinition& result) { EXPECT_EQ(definition.styleURL, result.styleURL); EXPECT_EQ(definition.bounds, result.bounds); @@ -525,10 +519,8 @@ TEST(OfflineDatabase, GetRegionDefinition) { EXPECT_EQ(definition.pixelRatio, result.pixelRatio); EXPECT_EQ(definition.includeIdeographs, result.includeIdeographs); }, - [&](auto&) { - EXPECT_FALSE(false); - } - ); + [&](auto&) { EXPECT_FALSE(false); } + ); } // Disabled due to flakiness: https://github.com/mapbox/mapbox-gl-native/issues/14966 @@ -540,9 +532,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DISABLED_MaximumAmbientCacheSize)) { return util::read_file(filename).size(); }; - { - OfflineDatabase db(filename, fixture::tileServerOptions); - } + { OfflineDatabase db(filename, fixture::tileServerOptions); } size_t initialSize = util::read_file(filename).size(); size_t maximumSize = 50 * 1024 * 1024; @@ -554,20 +544,25 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DISABLED_MaximumAmbientCacheSize)) { OfflineDatabase db(filename, fixture::tileServerOptions); db.setMaximumAmbientCacheSize(maximumSize); // 50 MB - OfflineTilePyramidRegionDefinition definition{ "maptiler://masp/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "maptiler://masp/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); // Add 100 MB of resources (50/50 ambient/region) for (unsigned i = 0; i < 250; ++i) { - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambientTile, response); const Resource ambientStyle = Resource::style("maptiler://maps/ambient_style_" + std::to_string(i)); db.put(ambientStyle, response); - const Resource regionTile = Resource::tile("maptiler://tiles/tiles/region_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource regionTile = Resource::tile( + "maptiler://tiles/tiles/region_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.putRegionResource(region->getID(), regionTile, response); const Resource regionStyle = Resource::style("maptiler://maps/region_style_" + std::to_string(i)); @@ -622,7 +617,9 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DISABLED_MaximumAmbientCacheSize)) { // Add ~50 MB in ambient cache data. for (unsigned i = 0; i < 250; ++i) { - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambientTile, response); const Resource ambientStyle = Resource::style("maptiler://mas/ambient_style_" + std::to_string(i)); @@ -651,7 +648,9 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DISABLED_MaximumAmbientCacheSize)) { db.setMaximumAmbientCacheSize(0); for (unsigned i = 0; i < 5; ++i) { - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambientTile, response); ASSERT_FALSE(db.get(ambientTile)); @@ -667,15 +666,17 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DISABLED_MaximumAmbientCacheSize)) { } namespace { -std::list> generateResources(const std::string& tilePrefix, - const std::string& stylePrefix) { +std::list> generateResources( + const std::string& tilePrefix, const std::string& stylePrefix +) { static const auto responseData = randomString(512 * 1024); Response response; response.data = responseData; std::list> resources; for (unsigned i = 0; i < 50; ++i) { - resources.emplace_back(Resource::tile(tilePrefix + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ), - response); + resources.emplace_back( + Resource::tile(tilePrefix + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ), response + ); resources.emplace_back(Resource::style(stylePrefix + std::to_string(i)), response); } return resources; @@ -686,9 +687,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DeleteRegion)) { FixtureLog log; deleteDatabaseFiles(); - { - OfflineDatabase dbCreate(filename, fixture::tileServerOptions); - } + { OfflineDatabase dbCreate(filename, fixture::tileServerOptions); } size_t initialSize = util::read_file(filename).size(); @@ -698,15 +697,20 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DeleteRegion)) { OfflineDatabase db(filename, fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition{ "maptiler://maps/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "maptiler://maps/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region1 = db.createRegion(definition, metadata); auto region2 = db.createRegion(definition, metadata); OfflineRegionStatus status; - db.putRegionResources(region1->getID(), generateResources("maptiler://tiles/tiles/tile_1", "maptiler://maps/style_1"), status); - db.putRegionResources(region2->getID(), generateResources("maptiler://tiles/tiles/tile_2", "maptiler://maps/style_2"), status); + db.putRegionResources( + region1->getID(), generateResources("maptiler://tiles/tiles/tile_1", "maptiler://maps/style_1"), status + ); + db.putRegionResources( + region2->getID(), generateResources("maptiler://tiles/tiles/tile_2", "maptiler://maps/style_2"), status + ); const size_t sizeWithTwoRegions = util::read_file(filename).size(); db.runPackDatabaseAutomatically(false); @@ -756,7 +760,9 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(Pack)) { response.data = randomString(512 * 1024); for (unsigned i = 0; i < 50; ++i) { - const Resource tile = Resource::tile("maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource tile = Resource::tile( + "maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(tile, response); const Resource style = Resource::style("maptiler://maps/style_" + std::to_string(i)); @@ -786,20 +792,26 @@ TEST(OfflineDatabase, MapboxTileLimitExceeded) { response.data = randomString(4096); auto insertAmbientTile = [&](unsigned i) { - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambientTile, response); }; auto insertRegionTile = [&](int64_t regionID, uint64_t i) { - const Resource tile = Resource::tile("maptiler://tiles/tiles/region_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource tile = Resource::tile( + "maptiler://tiles/tiles/region_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.putRegionResource(regionID, tile, response); }; - OfflineTilePyramidRegionDefinition definition1{ "maptiler://maps/style1", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata1{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition1{ + "maptiler://maps/style1", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata1{{1, 2, 3}}; - OfflineTilePyramidRegionDefinition definition2{ "maptiler://maps/style2", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata2{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition2{ + "maptiler://maps/style2", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata2{{1, 2, 3}}; auto region1 = db.createRegion(definition1, metadata1); auto region2 = db.createRegion(definition2, metadata2); @@ -883,24 +895,31 @@ TEST(OfflineDatabase, Invalidate) { response.mustRevalidate = false; response.expires = util::now() + 1h; - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/tile_ambient", 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/tile_ambient", 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(ambientTile, response); - const Resource ambientStyle = Resource::style("maptiler://maps/style_ambient"); + const Resource ambientStyle = Resource::style("maptiler://maps/style_ambient"); db.put(ambientStyle, response); - OfflineTilePyramidRegionDefinition definition { "maptiler://maps/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "maptiler://maps/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region1 = db.createRegion(definition, metadata); - const Resource region1Tile = Resource::tile("maptiler://tiles/tiles/tile_offline_region1", 1.0, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource region1Tile = Resource::tile( + "maptiler://tiles/tiles/tile_offline_region1", 1.0, 0, 0, 0, Tileset::Scheme::XYZ + ); db.putRegionResource(region1->getID(), region1Tile, response); const Resource region1Style = Resource::style("maptiler://maps/style_offline_region1"); db.putRegionResource(region1->getID(), region1Style, response); auto region2 = db.createRegion(definition, metadata); - const Resource region2Tile = Resource::tile("maptiler://tiles/tiles/tile_offline_region2", 1.0, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource region2Tile = Resource::tile( + "maptiler://tiles/tiles/tile_offline_region2", 1.0, 0, 0, 0, Tileset::Scheme::XYZ + ); db.putRegionResource(region2->getID(), region2Tile, response); const Resource region2Style = Resource::style("maptiler://maps/style_offline_region2"); @@ -967,9 +986,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(ClearAmbientCache)) { FixtureLog log; deleteDatabaseFiles(); - { - OfflineDatabase dbCreate(filename, fixture::tileServerOptions); - } + { OfflineDatabase dbCreate(filename, fixture::tileServerOptions); } size_t initialSize = util::read_file(filename).size(); @@ -980,7 +997,9 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(ClearAmbientCache)) { OfflineDatabase db(filename, fixture::tileServerOptions); for (unsigned i = 0; i < 50; ++i) { - const Resource tile = Resource::tile("maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource tile = Resource::tile( + "maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.put(tile, response); const Resource style = Resource::style("maptiler://maps/style_" + std::to_string(i)); @@ -997,7 +1016,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(ClearAmbientCache)) { TEST(OfflineDatabase, CreateRegionInfiniteMaxZoom) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, false }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, false}; OfflineRegionMetadata metadata; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); @@ -1100,12 +1119,15 @@ TEST(OfflineDatabase, OfflineRegionDoesNotAffectAmbientCacheSize) { db.put(Resource::style("http://example.com/ambient1.json"s), response); OfflineTilePyramidRegionDefinition definition( - "http://example.com/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false); + "http://example.com/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ); auto region = db.createRegion(definition, OfflineRegionMetadata()); // 1MB of offline region data. for (std::size_t i = 0; i < 5; ++i) { - const Resource tile = Resource::tile("maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource tile = Resource::tile( + "maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ + ); db.putRegionResource(region->getID(), tile, response); const Resource style = Resource::style("maptiler://maps/style_" + std::to_string(i)); @@ -1126,7 +1148,7 @@ TEST(OfflineDatabase, PutRegionResourceDoesNotEvict) { OfflineDatabase db(":memory:", fixture::tileServerOptions); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, true }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, true}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); @@ -1154,7 +1176,7 @@ TEST(OfflineDatabase, PutFailsWhenEvictionInsuffices) { EXPECT_FALSE(db.put(Resource::style("http://example.com/big"), big).first); - EXPECT_EQ(1u, log.count({ EventSeverity::Info, Event::Database, -1, "Unable to make space for entry" })); + EXPECT_EQ(1u, log.count({EventSeverity::Info, Event::Database, -1, "Unable to make space for entry"})); EXPECT_EQ(0u, log.uncheckedCount()); EXPECT_FALSE(bool(db.get(Resource::style("http://example.com/big")))); @@ -1165,7 +1187,8 @@ TEST(OfflineDatabase, PutFailsWhenEvictionInsuffices) { TEST(OfflineDatabase, GetRegionCompletedStatus) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false }; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false}; OfflineRegionMetadata metadata; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); @@ -1189,7 +1212,9 @@ TEST(OfflineDatabase, GetRegionCompletedStatus) { EXPECT_EQ(0u, status2->completedTileCount); EXPECT_EQ(0u, status2->completedTileSize); - uint64_t tileSize = db.putRegionResource(region->getID(), Resource::tile("http://example.com/", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), response); + uint64_t tileSize = db.putRegionResource( + region->getID(), Resource::tile("http://example.com/", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), response + ); auto status3 = db.getRegionCompletedStatus(region->getID()); ASSERT_TRUE(status3); @@ -1206,7 +1231,7 @@ TEST(OfflineDatabase, HasRegionResource) { OfflineDatabase db(":memory:", fixture::tileServerOptions); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, true }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, true}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); @@ -1232,18 +1257,12 @@ TEST(OfflineDatabase, HasRegionResourceTile) { OfflineDatabase db(":memory:", fixture::tileServerOptions); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, false }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, false}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); - Resource resource { Resource::Tile, "http://example.com/" }; - resource.tileData = Resource::TileData { - "http://example.com/", - 1, - 0, - 0, - 0 - }; + Resource resource{Resource::Tile, "http://example.com/"}; + resource.tileData = Resource::TileData{"http://example.com/", 1, 0, 0, 0}; Response response; response.data = std::make_shared("first"); @@ -1260,13 +1279,13 @@ TEST(OfflineDatabase, HasRegionResourceTile) { EXPECT_EQ(5, *(db.hasRegionResource(resource))); EXPECT_EQ(0u, log.uncheckedCount()); - } TEST(OfflineDatabase, OfflineMapboxTileCount) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0 , true}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; OfflineRegionMetadata metadata; auto region1 = db.createRegion(definition, metadata); @@ -1323,13 +1342,12 @@ TEST(OfflineDatabase, OfflineMapboxTileCount) { EXPECT_EQ(0u, log.uncheckedCount()); } - TEST(OfflineDatabase, BatchInsertion) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, true }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, true}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); @@ -1357,7 +1375,7 @@ TEST(OfflineDatabase, BatchInsertionMapboxTileCountExceeded) { db.setOfflineMapboxTileCountLimit(1); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, false }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, false}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); @@ -1404,8 +1422,7 @@ TEST(OfflineDatabase, MigrateFromV2Schema) { } EXPECT_EQ(6, databaseUserVersion(filename)); - EXPECT_LT(databasePageCount(filename), - databasePageCount("test/fixtures/offline_database/v2.db")); + EXPECT_LT(databasePageCount(filename), databasePageCount("test/fixtures/offline_database/v2.db")); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1432,7 +1449,8 @@ TEST(OfflineDatabase, MigrateFromV3Schema) { } TEST(OfflineDatabase, MigrateFromV4Schema) { - // v4.db is a v4 database, migrated from v2 & v3. This database used `journal_mode = WAL` and `synchronous = NORMAL`. + // v4.db is a v4 database, migrated from v2 & v3. This database used `journal_mode = WAL` and `synchronous = + // NORMAL`. FixtureLog log; deleteDatabaseFiles(); util::copyFile(filename, "test/fixtures/offline_database/v4.db"); @@ -1458,7 +1476,6 @@ TEST(OfflineDatabase, MigrateFromV4Schema) { EXPECT_EQ(0u, log.uncheckedCount()); } - TEST(OfflineDatabase, MigrateFromV5Schema) { // v5.db is a v5 database, migrated from v2, v3 & v4. FixtureLog log; @@ -1477,24 +1494,28 @@ TEST(OfflineDatabase, MigrateFromV5Schema) { EXPECT_EQ(6, databaseUserVersion(filename)); - EXPECT_EQ((std::vector{"id", - "url_template", - "pixel_ratio", - "z", - "x", - "y", - "expires", - "modified", - "etag", - "data", - "compressed", - "accessed", - "must_revalidate"}), - databaseTableColumns(filename, "tiles")); + EXPECT_EQ( + (std::vector{ + "id", + "url_template", + "pixel_ratio", + "z", + "x", + "y", + "expires", + "modified", + "etag", + "data", + "compressed", + "accessed", + "must_revalidate"}), + databaseTableColumns(filename, "tiles") + ); EXPECT_EQ( (std::vector{ "id", "url", "kind", "expires", "modified", "etag", "data", "compressed", "accessed", "must_revalidate"}), - databaseTableColumns(filename, "resources")); + databaseTableColumns(filename, "resources") + ); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1534,15 +1555,32 @@ TEST(OfflineDatabase, DowngradeSchema) { EXPECT_EQ(6, databaseUserVersion(filename)); - EXPECT_EQ((std::vector{ "id", "url_template", "pixel_ratio", "z", "x", "y", - "expires", "modified", "etag", "data", "compressed", - "accessed", "must_revalidate" }), - databaseTableColumns(filename, "tiles")); - EXPECT_EQ((std::vector{ "id", "url", "kind", "expires", "modified", "etag", "data", - "compressed", "accessed", "must_revalidate" }), - databaseTableColumns(filename, "resources")); + EXPECT_EQ( + (std::vector{ + "id", + "url_template", + "pixel_ratio", + "z", + "x", + "y", + "expires", + "modified", + "etag", + "data", + "compressed", + "accessed", + "must_revalidate"}), + databaseTableColumns(filename, "tiles") + ); + EXPECT_EQ( + (std::vector{ + "id", "url", "kind", "expires", "modified", "etag", "data", "compressed", "accessed", "must_revalidate"}), + databaseTableColumns(filename, "resources") + ); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + EXPECT_EQ( + 1u, log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"}) + ); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1554,11 +1592,13 @@ TEST(OfflineDatabase, CorruptDatabaseOnOpen) { // This database is corrupt in a way that will prevent opening the database. OfflineDatabase db(filename, fixture::tileServerOptions); EXPECT_EQ(1u, log.count(error(ResultCode::Corrupt, "Can't open database: database disk image is malformed"), true)); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + EXPECT_EQ( + 1u, log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"}) + ); EXPECT_EQ(0u, log.uncheckedCount()); // Now try inserting and reading back to make sure we have a valid database. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); EXPECT_EQ(0u, log.uncheckedCount()); auto result = db.get(res); @@ -1584,11 +1624,13 @@ TEST(OfflineDatabase, CorruptDatabaseOnQuery) { // The first request fails because the database is corrupt and has to be recreated. EXPECT_EQ(std::nullopt, db.get(fixture::tile)); EXPECT_EQ(1u, log.count(error(ResultCode::Corrupt, "Can't read resource: database disk image is malformed"), true)); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + EXPECT_EQ( + 1u, log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"}) + ); EXPECT_EQ(0u, log.uncheckedCount()); // Now try inserting and reading back to make sure we have a valid database. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); EXPECT_EQ(0u, log.uncheckedCount()); auto result = db.get(res); @@ -1609,7 +1651,8 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DisallowedIO)) { // First, create a region object so that we can try deleting it later. OfflineTilePyramidRegionDefinition definition( - "maptiler://maps/style", LatLngBounds::hull({ 37.66, -122.57 }, { 37.83, -122.32 }), 0, 8, 2, false); + "maptiler://maps/style", LatLngBounds::hull({37.66, -122.57}, {37.83, -122.32}), 0, 8, 2, false + ); auto region = db.createRegion(definition, {}); ASSERT_TRUE(region); @@ -1651,7 +1694,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DisallowedIO)) { EXPECT_EQ(0u, log.uncheckedCount()); OfflineRegionStatus status; - db.putRegionResources(region->getID(), { std::make_tuple(fixture::resource, fixture::response) }, status); + db.putRegionResources(region->getID(), {std::make_tuple(fixture::resource, fixture::response)}, status); EXPECT_EQ(1u, log.count(warning(ResultCode::Auth, "Can't write region resources: authorization denied"))); EXPECT_EQ(0u, log.uncheckedCount()); @@ -1681,15 +1724,15 @@ TEST(OfflineDatabase, MergeDatabaseWithSingleRegion_New) { OfflineDatabase db(":memory:", fixture::tileServerOptions); EXPECT_EQ(0u, db.listRegions()->size()); - + OfflineDatabase db_sideload(filename_sideload, fixture::tileServerOptions); auto newRegionsCount = db_sideload.listRegions()->size(); - + auto result = db.mergeDatabase(filename_sideload); EXPECT_EQ(newRegionsCount, db.listRegions()->size()); auto regionId = result->front().getID(); - auto status = db.getRegionCompletedStatus(regionId); + auto status = db.getRegionCompletedStatus(regionId); EXPECT_EQ(398u, status->completedResourceCount); EXPECT_EQ(5u, status->completedTileCount); } @@ -1704,10 +1747,9 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithSingleRegion_Update)) { std::string tileURL = "maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg"; OfflineDatabase db1(filename_sideload, fixture::tileServerOptions); - auto originalTile = db1.getRegionResource( - Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); + auto originalTile = db1.getRegionResource(Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); auto originalStamp = originalTile->first.modified; - + OfflineDatabase db(filename, fixture::tileServerOptions); auto regions = db.listRegions(); EXPECT_EQ(1u, db.listRegions()->size()); @@ -1720,10 +1762,9 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithSingleRegion_Update)) EXPECT_EQ(395u, status->completedResourceCount); EXPECT_EQ(2u, status->completedTileCount); - //Verify the modified timestamp matches the tile in the sideloaded db. - auto updatedTile = db.getRegionResource( - Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); - + // Verify the modified timestamp matches the tile in the sideloaded db. + auto updatedTile = db.getRegionResource(Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); + auto updatedStamp = updatedTile->first.modified; EXPECT_EQ(*originalStamp, *updatedStamp); } @@ -1732,24 +1773,24 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithSingleRegion_Update)) TEST(OfflineDatabase, MergeDatabaseWithSingleRegion_NoUpdate) { deleteDatabaseFiles(); util::deleteFile(filename_sideload); - - //Swap sideload/main database from update test and ensure that an older tile is not copied over + + // Swap sideload/main database from update test and ensure that an older tile is not copied over util::copyFile(filename_sideload, "test/fixtures/offline_database/satellite_test.db"); util::copyFile(filename, "test/fixtures/offline_database/sideload_sat.db"); OfflineDatabase db(filename, fixture::tileServerOptions); - + std::string tileURL = "maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg"; auto originalTile = db.getRegionResource(Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); auto originalStamp = originalTile->first.modified; - + auto result = db.mergeDatabase(filename_sideload); EXPECT_EQ(1u, result->size()); EXPECT_EQ(2u, db.listRegions()->size()); - auto updatedTile = db.getRegionResource(Resource::tile(tileURL,1, 0, 0, 1, Tileset::Scheme::XYZ)); + auto updatedTile = db.getRegionResource(Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); - //Verify the modified timestamp matches the tile in the main db. + // Verify the modified timestamp matches the tile in the main db. EXPECT_EQ(originalStamp, updatedTile->first.modified); } @@ -1760,12 +1801,18 @@ TEST(OfflineDatabase, MergeDatabaseWithSingleRegion_AmbientTiles) { OfflineDatabase db(":memory:", fixture::tileServerOptions); auto result = db.mergeDatabase(filename_sideload); - EXPECT_TRUE(bool(db.hasRegionResource(Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 0, 0, 1, Tileset::Scheme::XYZ)))); + EXPECT_TRUE(bool(db.hasRegionResource( + Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 0, 0, 1, Tileset::Scheme::XYZ) + ))); - //Ambient resources should not be copied + // Ambient resources should not be copied EXPECT_FALSE(bool(db.hasRegionResource(Resource::style("maptiler://maps/streets")))); - EXPECT_FALSE(bool(db.hasRegionResource(Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 0, 1, 2, Tileset::Scheme::XYZ)))); - EXPECT_FALSE(bool(db.hasRegionResource(Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 1, 1, 2, Tileset::Scheme::XYZ)))); + EXPECT_FALSE(bool(db.hasRegionResource( + Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 0, 1, 2, Tileset::Scheme::XYZ) + ))); + EXPECT_FALSE(bool(db.hasRegionResource( + Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 1, 1, 2, Tileset::Scheme::XYZ) + ))); } TEST(OfflineDatabase, MergeDatabaseWithMultipleRegions_New) { @@ -1778,7 +1825,7 @@ TEST(OfflineDatabase, MergeDatabaseWithMultipleRegions_New) { auto result = db.mergeDatabase(filename_sideload); EXPECT_EQ(2u, result->size()); EXPECT_EQ(2u, db.listRegions()->size()); - + auto region1Id = result->front().getID(); auto status = db.getRegionCompletedStatus(region1Id); EXPECT_EQ(398u, status->completedResourceCount); @@ -1812,7 +1859,7 @@ TEST(OfflineDatabase, MergeDatabaseWithMultipleRegionsWithOverlap) { "FROM region_tiles " "JOIN tiles WHERE tile_id = id" }; // clang-format on - mapbox::sqlite::Query query { stmt }; + mapbox::sqlite::Query query{stmt}; query.run(); // Ensure multiple entries for tiles shared between regions @@ -1824,7 +1871,7 @@ TEST(OfflineDatabase, MergeDatabaseWithMultipleRegionsWithOverlap) { "FROM region_resources " "JOIN resources WHERE resource_id = id" }; // clang-format on - mapbox::sqlite::Query query { stmt }; + mapbox::sqlite::Query query{stmt}; query.run(); // Ensure multiple entries for resources shared between regions @@ -1842,7 +1889,7 @@ TEST(OfflineDatabase, MergeDatabaseWithSingleRegionTooManyNewTiles) { auto result = db.mergeDatabase(filename_sideload); EXPECT_FALSE(result); - EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Database, -1, "Mapbox tile limit exceeded" })); + EXPECT_EQ(1u, log.count({EventSeverity::Error, Event::Database, -1, "Mapbox tile limit exceeded"})); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1859,7 +1906,7 @@ TEST(OfflineDatabase, MergeDatabaseWithSingleRegionTooManyExistingTiles) { auto result = db.mergeDatabase(filename_sideload); EXPECT_THROW(std::rethrow_exception(result.error()), MapboxTileLimitExceededException); - EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Database, -1, "Mapbox tile limit exceeded" })); + EXPECT_EQ(1u, log.count({EventSeverity::Error, Event::Database, -1, "Mapbox tile limit exceeded"})); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1875,7 +1922,7 @@ TEST(OfflineDatabase, MergeDatabaseWithInvalidPath) { auto result = db.mergeDatabase(filename_sideload); EXPECT_FALSE(result); - EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Database, -1, "Merge database has incorrect user_version" })); + EXPECT_EQ(1u, log.count({EventSeverity::Error, Event::Database, -1, "Merge database has incorrect user_version"})); EXPECT_EQ(0u, log.uncheckedCount()); } #endif @@ -1891,7 +1938,14 @@ TEST(OfflineDatabase, MergeDatabaseWithInvalidDb) { auto result = db.mergeDatabase(filename_sideload); EXPECT_FALSE(result); - EXPECT_EQ(1u, log.count(error(ResultCode::Corrupt, "Can't attach database (test/fixtures/offline_database/offline_sideload.db) for merge: database disk image is malformed"))); + EXPECT_EQ( + 1u, + log.count(error( + ResultCode::Corrupt, + "Can't attach database (test/fixtures/offline_database/offline_sideload.db) for merge: " + "database disk image is malformed" + )) + ); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1899,7 +1953,7 @@ TEST(OfflineDatabase, MergeDatabaseWithInvalidDb) { TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithDiskFull)) { FixtureLog log; test::SQLite3TestFS fs; - + deleteDatabaseFiles(); util::deleteFile(filename_sideload); util::copyFile(filename, "test/fixtures/offline_database/satellite_test.db"); @@ -1912,7 +1966,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithDiskFull)) { auto result = db.mergeDatabase(filename_sideload); EXPECT_FALSE(result.has_value()); - EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Database, -1, "database or disk is full"})); + EXPECT_EQ(1u, log.count({EventSeverity::Error, Event::Database, -1, "database or disk is full"})); EXPECT_EQ(0u, log.uncheckedCount()); } #endif // __QT__ @@ -1938,7 +1992,9 @@ TEST(OfflineDatabase, ResetDatabase) { auto regions = db.listRegions().value(); EXPECT_EQ(0u, regions.size()); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + EXPECT_EQ( + 1u, log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"}) + ); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1976,11 +2032,15 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(UpdateDatabaseReadOnlyMode)) { OfflineDatabase db(filename, fixture::tileServerOptions); db.reopenDatabaseReadOnly(true /*readOnly*/); db.clearAmbientCache(); - EXPECT_EQ(1u, - log.count({EventSeverity::Error, - Event::Database, - -1, - "Can't clear ambient cache: Cannot modify database in read-only mode"})); + EXPECT_EQ( + 1u, + log.count( + {EventSeverity::Error, + Event::Database, + -1, + "Can't clear ambient cache: Cannot modify database in read-only mode"} + ) + ); EXPECT_EQ(0u, log.uncheckedCount()); } diff --git a/test/storage/offline_download.test.cpp b/test/storage/offline_download.test.cpp index 1f7c033d9bc..c423ca6d58d 100644 --- a/test/storage/offline_download.test.cpp +++ b/test/storage/offline_download.test.cpp @@ -34,7 +34,7 @@ static void deleteDatabaseFiles() { } static FixtureLog::Message warning(ResultCode code, const char* message) { - return { EventSeverity::Warning, Event::Database, static_cast(code), message }; + return {EventSeverity::Warning, Event::Database, static_cast(code), message}; } #endif @@ -52,15 +52,15 @@ class MockObserver : public OfflineRegionObserver { if (mapboxTileCountLimitExceededFn) mapboxTileCountLimitExceededFn(limit); } - std::function statusChangedFn; - std::function responseErrorFn; - std::function mapboxTileCountLimitExceededFn; + std::function statusChangedFn; + std::function responseErrorFn; + std::function mapboxTileCountLimitExceededFn; }; class OfflineTest { public: - OfflineTest(const std::string& path = ":memory:") : db(path, TileServerOptions::MapTilerConfiguration()) { - } + OfflineTest(const std::string& path = ":memory:") + : db(path, TileServerOptions::MapTilerConfiguration()) {} util::RunLoop loop; StubFileSource fileSource; @@ -68,14 +68,12 @@ class OfflineTest { std::size_t size = 0; auto createRegion() { - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 1.0, true }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 1.0, true}; OfflineRegionMetadata metadata; return db.createRegion(definition, metadata); } - auto invalidateRegion(int64_t region) { - return db.invalidateRegion(region); - } + auto invalidateRegion(int64_t region) { return db.invalidateRegion(region); } Response response(const std::string& path) { Response result; @@ -93,10 +91,14 @@ TEST(OfflineDownload, NoSubresources) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("empty.style.json"); }; @@ -104,7 +106,7 @@ TEST(OfflineDownload, NoSubresources) { auto observer = std::make_unique(); bool expectsInactiveStatus = false; - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { if (!expectsInactiveStatus) { expectsInactiveStatus = true; @@ -134,15 +136,19 @@ TEST(OfflineDownload, InlineSource) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("inline_source.style.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { const Resource::TileData& tile = *resource.tileData; EXPECT_EQ("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", tile.urlTemplate); EXPECT_EQ(1, tile.pixelRatio); @@ -154,7 +160,7 @@ TEST(OfflineDownload, InlineSource) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(1u, status.completedTileCount); EXPECT_EQ(2u, status.completedResourceCount); @@ -176,22 +182,26 @@ TEST(OfflineDownload, GeoJSONSource) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("geojson_source.style.json"); }; - test.fileSource.sourceResponse = [&] (const Resource& resource) { + test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/geojson.json", resource.url); return test.response("geojson.json"); }; auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(2u, status.completedResourceCount); EXPECT_EQ(test.size, status.completedResourceSize); @@ -212,41 +222,48 @@ TEST(OfflineDownload, Activate) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("style.json"); }; - test.fileSource.spriteImageResponse = [&] (const Resource& resource) { - EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.png" || - resource.url == "http://127.0.0.1:3000/sprite@2x.png"); + test.fileSource.spriteImageResponse = [&](const Resource& resource) { + EXPECT_TRUE( + resource.url == "http://127.0.0.1:3000/sprite.png" || resource.url == "http://127.0.0.1:3000/sprite@2x.png" + ); return test.response("sprite.png"); }; - test.fileSource.imageResponse = [&] (const Resource& resource) { + test.fileSource.imageResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/radar.gif", resource.url); return test.response("radar.gif"); }; - test.fileSource.spriteJSONResponse = [&] (const Resource& resource) { - EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.json" || - resource.url == "http://127.0.0.1:3000/sprite@2x.json"); + test.fileSource.spriteJSONResponse = [&](const Resource& resource) { + EXPECT_TRUE( + resource.url == "http://127.0.0.1:3000/sprite.json" || + resource.url == "http://127.0.0.1:3000/sprite@2x.json" + ); return test.response("sprite.json"); }; - test.fileSource.glyphsResponse = [&] (const Resource&) { + test.fileSource.glyphsResponse = [&](const Resource&) { return test.response("glyph.pbf"); }; - test.fileSource.sourceResponse = [&] (const Resource& resource) { + test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/streets.json", resource.url); return test.response("streets.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { const Resource::TileData& tile = *resource.tileData; EXPECT_EQ("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", tile.urlTemplate); EXPECT_EQ(1, tile.pixelRatio); @@ -258,10 +275,11 @@ TEST(OfflineDownload, Activate) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(status.completedTileCount, status.requiredTileCount); - EXPECT_EQ(264u, status.completedResourceCount); // 256 glyphs, 2 sprite images, 2 sprite jsons, 1 tile, 1 style, source, image + EXPECT_EQ(264u, status.completedResourceCount); // 256 glyphs, 2 sprite images, 2 sprite jsons, 1 tile, 1 + // style, source, image EXPECT_EQ(test.size, status.completedResourceSize); download.setState(OfflineRegionDownloadState::Inactive); @@ -290,42 +308,49 @@ TEST(OfflineDownload, ExcludeIdeographs) { auto region = test.createRegion(); ASSERT_TRUE(region); OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); - - test.fileSource.styleResponse = [&] (const Resource& resource) { + region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); + + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("style.json"); }; - - test.fileSource.spriteImageResponse = [&] (const Resource& resource) { - EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.png" || - resource.url == "http://127.0.0.1:3000/sprite@2x.png"); + + test.fileSource.spriteImageResponse = [&](const Resource& resource) { + EXPECT_TRUE( + resource.url == "http://127.0.0.1:3000/sprite.png" || resource.url == "http://127.0.0.1:3000/sprite@2x.png" + ); return test.response("sprite.png"); }; - - test.fileSource.imageResponse = [&] (const Resource& resource) { + + test.fileSource.imageResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/radar.gif", resource.url); return test.response("radar.gif"); }; - - test.fileSource.spriteJSONResponse = [&] (const Resource& resource) { - EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.json" || - resource.url == "http://127.0.0.1:3000/sprite@2x.json"); + + test.fileSource.spriteJSONResponse = [&](const Resource& resource) { + EXPECT_TRUE( + resource.url == "http://127.0.0.1:3000/sprite.json" || + resource.url == "http://127.0.0.1:3000/sprite@2x.json" + ); return test.response("sprite.json"); }; - - test.fileSource.glyphsResponse = [&] (const Resource&) { + + test.fileSource.glyphsResponse = [&](const Resource&) { return test.response("glyph.pbf"); }; - - test.fileSource.sourceResponse = [&] (const Resource& resource) { + + test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/streets.json", resource.url); return test.response("streets.json"); }; - - test.fileSource.tileResponse = [&] (const Resource& resource) { + + test.fileSource.tileResponse = [&](const Resource& resource) { const Resource::TileData& tile = *resource.tileData; EXPECT_EQ("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", tile.urlTemplate); EXPECT_EQ(1, tile.pixelRatio); @@ -334,15 +359,16 @@ TEST(OfflineDownload, ExcludeIdeographs) { EXPECT_EQ(0, tile.z); return test.response("0-0-0.vector.pbf"); }; - + auto observer = std::make_unique(); - - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(status.completedTileCount, status.requiredTileCount); - EXPECT_EQ(138u, status.completedResourceCount); // 130 glyphs, 2 sprite images, 2 sprite jsons, 1 tile, 1 style, source, image + EXPECT_EQ(138u, status.completedResourceCount); // 130 glyphs, 2 sprite images, 2 sprite jsons, 1 tile, 1 + // style, source, image EXPECT_EQ(test.size, status.completedResourceSize); - + download.setState(OfflineRegionDownloadState::Inactive); OfflineRegionStatus computedStatus = download.getStatus(); EXPECT_EQ(OfflineRegionDownloadState::Inactive, computedStatus.downloadState); @@ -353,14 +379,14 @@ TEST(OfflineDownload, ExcludeIdeographs) { EXPECT_EQ(status.completedTileCount, computedStatus.completedTileCount); EXPECT_EQ(status.completedTileSize, computedStatus.completedTileSize); EXPECT_TRUE(status.requiredResourceCountIsPrecise); - + test.loop.stop(); } }; - + download.setObserver(std::move(observer)); download.setState(OfflineRegionDownloadState::Active); - + test.loop.run(); } @@ -371,8 +397,12 @@ TEST(OfflineDownload, DoesNotFloodTheFileSourceWithRequests) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + fileSource + ); auto observer = std::make_unique(); @@ -394,8 +424,12 @@ TEST(OfflineDownload, GetStatusNoResources) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); OfflineRegionStatus status = download.getStatus(); EXPECT_EQ(OfflineRegionDownloadState::Inactive, status.downloadState); @@ -414,12 +448,14 @@ TEST(OfflineDownload, GetStatusStyleComplete) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); - test.db.putRegionResource(1, - Resource::style("http://127.0.0.1:3000/style.json"), - test.response("style.json")); + test.db.putRegionResource(1, Resource::style("http://127.0.0.1:3000/style.json"), test.response("style.json")); OfflineRegionStatus status = download.getStatus(); @@ -439,16 +475,16 @@ TEST(OfflineDownload, GetStatusStyleAndSourceComplete) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); - test.db.putRegionResource(1, - Resource::style("http://127.0.0.1:3000/style.json"), - test.response("style.json")); + test.db.putRegionResource(1, Resource::style("http://127.0.0.1:3000/style.json"), test.response("style.json")); - test.db.putRegionResource(1, - Resource::source("http://127.0.0.1:3000/streets.json"), - test.response("streets.json")); + test.db.putRegionResource(1, Resource::source("http://127.0.0.1:3000/streets.json"), test.response("streets.json")); OfflineRegionStatus status = download.getStatus(); @@ -468,10 +504,14 @@ TEST(OfflineDownload, RequestError) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); - - test.fileSource.styleResponse = [&] (const Resource&) { + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); + + test.fileSource.styleResponse = [&](const Resource&) { Response response; response.error = std::make_unique(Response::Error::Reason::Connection, "connection error"); return response; @@ -479,7 +519,7 @@ TEST(OfflineDownload, RequestError) { auto observer = std::make_unique(); - observer->responseErrorFn = [&] (Response::Error error) { + observer->responseErrorFn = [&](Response::Error error) { EXPECT_EQ(Response::Error::Reason::Connection, error.reason); EXPECT_EQ("connection error", error.message); test.loop.stop(); @@ -497,11 +537,15 @@ TEST(OfflineDownload, RequestErrorsAreRetried) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); - - test.fileSource.styleResponse = [&] (const Resource&) { - test.fileSource.styleResponse = [&] (const Resource&) { + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); + + test.fileSource.styleResponse = [&](const Resource&) { + test.fileSource.styleResponse = [&](const Resource&) { return test.response("empty.style.json"); }; @@ -512,7 +556,7 @@ TEST(OfflineDownload, RequestErrorsAreRetried) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(1u, status.completedResourceCount); test.loop.stop(); @@ -531,32 +575,36 @@ TEST(OfflineDownload, TileCountLimitExceededNoTileResponse) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); uint64_t tileLimit = 0; test.db.setOfflineMapboxTileCountLimit(tileLimit); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("mapbox_source.style.json"); }; -// test.fileSource.tileResponse = [&] (const Resource& resource) { -// EXPECT_EQ("maptiler://0-0-0.vector.pbf", resource.url); -// return test.response("0-0-0.vector.pbf"); -// }; + // test.fileSource.tileResponse = [&] (const Resource& resource) { + // EXPECT_EQ("maptiler://0-0-0.vector.pbf", resource.url); + // return test.response("0-0-0.vector.pbf"); + // }; auto observer = std::make_unique(); bool mapboxTileCountLimitExceededCalled = false; - observer->mapboxTileCountLimitExceededFn = [&] (uint64_t limit) { + observer->mapboxTileCountLimitExceededFn = [&](uint64_t limit) { EXPECT_FALSE(mapboxTileCountLimitExceededCalled); EXPECT_EQ(tileLimit, limit); mapboxTileCountLimitExceededCalled = true; }; - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (!mapboxTileCountLimitExceededCalled) { EXPECT_FALSE(status.complete()); EXPECT_EQ(OfflineRegionDownloadState::Active, status.downloadState); @@ -578,19 +626,23 @@ TEST(OfflineDownload, TileCountLimitExceededWithTileResponse) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); uint64_t tileLimit = 1; test.db.setOfflineMapboxTileCountLimit(tileLimit); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("mapbox_source.style.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { const Resource::TileData& tile = *resource.tileData; EXPECT_EQ("maptiler://{z}-{x}-{y}.vector.pbf", tile.urlTemplate); EXPECT_EQ(1, tile.pixelRatio); @@ -603,13 +655,13 @@ TEST(OfflineDownload, TileCountLimitExceededWithTileResponse) { auto observer = std::make_unique(); bool mapboxTileCountLimitExceededCalled = false; - observer->mapboxTileCountLimitExceededFn = [&] (uint64_t limit) { + observer->mapboxTileCountLimitExceededFn = [&](uint64_t limit) { EXPECT_FALSE(mapboxTileCountLimitExceededCalled); EXPECT_EQ(tileLimit, limit); mapboxTileCountLimitExceededCalled = true; }; - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (!mapboxTileCountLimitExceededCalled) { EXPECT_EQ(OfflineRegionDownloadState::Active, status.downloadState); } else { @@ -633,21 +685,26 @@ TEST(OfflineDownload, WithPreviouslyExistingTile) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("inline_source.style.json"); }; test.db.put( Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 0, 0, Tileset::Scheme::XYZ), - test.response("0-0-0.vector.pbf")); + test.response("0-0-0.vector.pbf") + ); auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(2u, status.completedResourceCount); EXPECT_EQ(test.size, status.completedResourceSize); @@ -668,20 +725,25 @@ TEST(OfflineDownload, ReactivatePreviouslyCompletedDownload) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("inline_source.style.json"); }; test.db.put( Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 0, 0, Tileset::Scheme::XYZ), - test.response("0-0-0.vector.pbf")); + test.response("0-0-0.vector.pbf") + ); auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { test.loop.stop(); } @@ -694,13 +756,17 @@ TEST(OfflineDownload, ReactivatePreviouslyCompletedDownload) { OfflineDownload redownload( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); std::vector statusesAfterReactivate; observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { statusesAfterReactivate.push_back(status); if (status.complete()) { test.loop.stop(); @@ -736,17 +802,21 @@ TEST(OfflineDownload, Deactivate) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("mapbox_source.style.json"); }; auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.downloadState == OfflineRegionDownloadState::Inactive) { test.loop.stop(); } else { @@ -766,46 +836,50 @@ TEST(OfflineDownload, AllOfflineRequestsHaveLowPriorityAndOfflineUsage) { ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("style.json"); }; - test.fileSource.spriteImageResponse = [&] (const Resource& resource) { + test.fileSource.spriteImageResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("sprite.png"); }; - test.fileSource.imageResponse = [&] (const Resource& resource) { + test.fileSource.imageResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("radar.gif"); }; - test.fileSource.spriteJSONResponse = [&] (const Resource& resource) { + test.fileSource.spriteJSONResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("sprite.json"); }; - test.fileSource.glyphsResponse = [&] (const Resource& resource) { + test.fileSource.glyphsResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("glyph.pbf"); }; - test.fileSource.sourceResponse = [&] (const Resource& resource) { + test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("streets.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("0-0-0.vector.pbf"); @@ -813,7 +887,7 @@ TEST(OfflineDownload, AllOfflineRequestsHaveLowPriorityAndOfflineUsage) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { test.loop.stop(); } @@ -831,7 +905,7 @@ TEST(OfflineDownload, DiskFull) { deleteDatabaseFiles(); test::SQLite3TestFS fs; - OfflineTest test{ filename_test_fs }; + OfflineTest test{filename_test_fs}; EXPECT_EQ(0u, log.uncheckedCount()); auto region = test.createRegion(); @@ -843,12 +917,16 @@ TEST(OfflineDownload, DiskFull) { OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); bool hasRequestedStyle = false; - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); hasRequestedStyle = true; return test.response("empty.style.json"); @@ -856,7 +934,7 @@ TEST(OfflineDownload, DiskFull) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { EXPECT_EQ(OfflineRegionDownloadState::Active, status.downloadState); EXPECT_EQ(0u, status.completedResourceCount); EXPECT_EQ(0u, status.completedResourceSize); @@ -864,7 +942,9 @@ TEST(OfflineDownload, DiskFull) { EXPECT_FALSE(status.complete()); if (hasRequestedStyle) { - EXPECT_EQ(1u, log.count(warning(ResultCode::Full, "Can't write region resources: database or disk is full"))); + EXPECT_EQ( + 1u, log.count(warning(ResultCode::Full, "Can't write region resources: database or disk is full")) + ); EXPECT_EQ(0u, log.uncheckedCount()); test.loop.stop(); } @@ -883,30 +963,33 @@ TEST(OfflineDownload, ResourceOfflineUsageUnset) { deleteDatabaseFiles(); test::SQLite3TestFS fs; - OfflineTest test{ filename_test_fs }; + OfflineTest test{filename_test_fs}; auto region = test.createRegion(); ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/inline_source.style.json", - LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/inline_source.style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false + ), + test.db, + test.fileSource + ); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("inline_source.style.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("0-0-0.vector.pbf"); }; auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { // Once download completes, invalidate region and try rendering map. // Resource requests must not have Offline usage tag. @@ -920,28 +1003,29 @@ TEST(OfflineDownload, ResourceOfflineUsageUnset) { test.loop.run(); std::shared_ptr stubfileSource = std::make_shared(); - stubfileSource->styleResponse = [&] (const Resource& resource) { + stubfileSource->styleResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.usage != Resource::Usage::Offline); return test.response("inline_source.style.json"); }; - stubfileSource->tileResponse = [&] (const Resource& resource) { + stubfileSource->tileResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.usage != Resource::Usage::Offline); return test.response("0-0-0.vector.pbf"); }; StubMapObserver mapObserver; - mapObserver.didFinishRenderingFrameCallback = [&] (MapObserver::RenderFrameStatus status) { + mapObserver.didFinishRenderingFrameCallback = [&](MapObserver::RenderFrameStatus status) { if (status.mode == MapObserver::RenderMode::Full) { test.loop.stop(); } }; - HeadlessFrontend frontend { 1 }; - MapAdapter map { frontend, mapObserver, stubfileSource, - MapOptions() - .withMapMode(MapMode::Continuous) - .withSize(frontend.getSize())}; + HeadlessFrontend frontend{1}; + MapAdapter map{ + frontend, + mapObserver, + stubfileSource, + MapOptions().withMapMode(MapMode::Continuous).withSize(frontend.getSize())}; map.getStyle().loadURL("http://127.0.0.1:3000/inline_source.style.json"); map.jumpTo(CameraOptions().withCenter(LatLng{0.0, 0.0}).withZoom(0)); @@ -954,11 +1038,14 @@ TEST(OfflineDownload, InterruptAndResume) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download(region->getID(), - OfflineTilePyramidRegionDefinition( - "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, - test.fileSource); + OfflineDownload download( + region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); @@ -966,8 +1053,9 @@ TEST(OfflineDownload, InterruptAndResume) { }; test.fileSource.spriteImageResponse = [&](const Resource& resource) { - EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.png" || - resource.url == "http://127.0.0.1:3000/sprite@2x.png"); + EXPECT_TRUE( + resource.url == "http://127.0.0.1:3000/sprite.png" || resource.url == "http://127.0.0.1:3000/sprite@2x.png" + ); return test.response("sprite.png"); }; @@ -977,12 +1065,16 @@ TEST(OfflineDownload, InterruptAndResume) { }; test.fileSource.spriteJSONResponse = [&](const Resource& resource) { - EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.json" || - resource.url == "http://127.0.0.1:3000/sprite@2x.json"); + EXPECT_TRUE( + resource.url == "http://127.0.0.1:3000/sprite.json" || + resource.url == "http://127.0.0.1:3000/sprite@2x.json" + ); return test.response("sprite.json"); }; - test.fileSource.glyphsResponse = [&](const Resource&) { return test.response("glyph.pbf"); }; + test.fileSource.glyphsResponse = [&](const Resource&) { + return test.response("glyph.pbf"); + }; test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/streets.json", resource.url); @@ -1035,23 +1127,36 @@ TEST(OfflineDownload, NoFreezingOnCachedTilesAndNewStyle) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download(region->getID(), - OfflineTilePyramidRegionDefinition( - "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 1.0, 1.0, 1.0, true), - test.db, - test.fileSource); + OfflineDownload download( + region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 1.0, 1.0, 1.0, true + ), + test.db, + test.fileSource + ); test.fileSource.setProperty(MAX_CONCURRENT_REQUESTS_KEY, 2u); - test.fileSource.styleResponse = [&](const Resource&) { return test.response("inline_source.style.json"); }; + test.fileSource.styleResponse = [&](const Resource&) { + return test.response("inline_source.style.json"); + }; // Number of resources must exceed MAX_CONCURRENT_REQUESTS_KEY - test.db.put(Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 0, 1, Tileset::Scheme::XYZ), - test.response("0-0-0.vector.pbf")); - test.db.put(Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 1, 1, Tileset::Scheme::XYZ), - test.response("0-0-0.vector.pbf")); - test.db.put(Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 1, 0, 1, Tileset::Scheme::XYZ), - test.response("0-0-0.vector.pbf")); - test.db.put(Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 1, 1, 1, Tileset::Scheme::XYZ), - test.response("0-0-0.vector.pbf")); + test.db.put( + Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 0, 1, Tileset::Scheme::XYZ), + test.response("0-0-0.vector.pbf") + ); + test.db.put( + Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 1, 1, Tileset::Scheme::XYZ), + test.response("0-0-0.vector.pbf") + ); + test.db.put( + Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 1, 0, 1, Tileset::Scheme::XYZ), + test.response("0-0-0.vector.pbf") + ); + test.db.put( + Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 1, 1, 1, Tileset::Scheme::XYZ), + test.response("0-0-0.vector.pbf") + ); auto observer = std::make_unique(); observer->statusChangedFn = [&](OfflineRegionStatus status) { @@ -1071,11 +1176,14 @@ TEST(OfflineDownload, NoFreezingOnNotFoundError) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download(region->getID(), - OfflineTilePyramidRegionDefinition( - "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, - test.fileSource); + OfflineDownload download( + region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true + ), + test.db, + test.fileSource + ); test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); @@ -1083,8 +1191,9 @@ TEST(OfflineDownload, NoFreezingOnNotFoundError) { }; test.fileSource.spriteImageResponse = [&](const Resource& resource) { - EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.png" || - resource.url == "http://127.0.0.1:3000/sprite@2x.png"); + EXPECT_TRUE( + resource.url == "http://127.0.0.1:3000/sprite.png" || resource.url == "http://127.0.0.1:3000/sprite@2x.png" + ); return test.response("sprite.png"); }; @@ -1099,7 +1208,9 @@ TEST(OfflineDownload, NoFreezingOnNotFoundError) { return response; }; - test.fileSource.glyphsResponse = [&](const Resource&) { return test.response("glyph.pbf"); }; + test.fileSource.glyphsResponse = [&](const Resource&) { + return test.response("glyph.pbf"); + }; test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/streets.json", resource.url); diff --git a/test/storage/online_file_source.test.cpp b/test/storage/online_file_source.test.cpp index f3662b978fd..731d36434f2 100644 --- a/test/storage/online_file_source.test.cpp +++ b/test/storage/online_file_source.test.cpp @@ -17,8 +17,9 @@ TEST(OnlineFileSource, Cancel) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); - fs->request({Resource::Unknown, "http://127.0.0.1:3000/test"}, - [&](Response) { ADD_FAILURE() << "Callback should not be called"; }); + fs->request({Resource::Unknown, "http://127.0.0.1:3000/test"}, [&](Response) { + ADD_FAILURE() << "Callback should not be called"; + }); loop.runOnce(); } @@ -27,10 +28,11 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(CancelMultiple)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/test" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test"}; - std::unique_ptr req2 = - fs->request(resource, [&](Response) { ADD_FAILURE() << "Callback should not be called"; }); + std::unique_ptr req2 = fs->request(resource, [&](Response) { + ADD_FAILURE() << "Callback should not be called"; + }); std::unique_ptr req = fs->request(resource, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); @@ -124,7 +126,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(Timeout)) { int counter = 0; - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/test?cachecontrol=max-age=1" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test?cachecontrol=max-age=1"}; std::unique_ptr req = fs->request(resource, [&](Response res) { counter++; EXPECT_EQ(nullptr, res.error); @@ -151,7 +153,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(RetryDelayOnExpiredTile)) { int counter = 0; - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/test?expires=10000" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test?expires=10000"}; std::unique_ptr req = fs->request(resource, [&](Response res) { counter++; EXPECT_EQ(nullptr, res.error); @@ -171,7 +173,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(RetryOnClockSkew)) { int counter = 0; - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/clockskew" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/clockskew"}; std::unique_ptr req1 = fs->request(resource, [&](Response res) { EXPECT_FALSE(res.mustRevalidate); switch (counter++) { @@ -199,18 +201,18 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(RespectPriorExpires)) { std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); // Very long expiration time, should never arrive. - Resource resource1{ Resource::Unknown, "http://127.0.0.1:3000/test" }; + Resource resource1{Resource::Unknown, "http://127.0.0.1:3000/test"}; resource1.priorExpires = util::now() + Seconds(100000); std::unique_ptr req1 = fs->request(resource1, [&](Response) { FAIL() << "Should never be called"; }); // No expiration time, should be requested immediately. - Resource resource2{ Resource::Unknown, "http://127.0.0.1:3000/test" }; + Resource resource2{Resource::Unknown, "http://127.0.0.1:3000/test"}; std::unique_ptr req2 = fs->request(resource2, [&](Response) { loop.stop(); }); // Very long expiration time, should never arrive. - Resource resource3{ Resource::Unknown, "http://127.0.0.1:3000/test" }; + Resource resource3{Resource::Unknown, "http://127.0.0.1:3000/test"}; resource3.priorExpires = util::now() + Seconds(100000); std::unique_ptr req3 = fs->request(resource3, [&](Response) { FAIL() << "Should never be called"; }); @@ -248,23 +250,25 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(Load)) { std::function req = [&](int i) { const auto current = number++; - reqs[i] = fs->request({Resource::Unknown, std::string("http://127.0.0.1:3000/load/") + util::toString(current)}, - [&, i, current](Response res) { - reqs[i].reset(); - EXPECT_EQ(nullptr, res.error); - ASSERT_TRUE(res.data.get()); - EXPECT_EQ(std::string("Request ") + util::toString(current), *res.data); - EXPECT_FALSE(bool(res.expires)); - EXPECT_FALSE(res.mustRevalidate); - EXPECT_FALSE(bool(res.modified)); - EXPECT_FALSE(bool(res.etag)); - - if (number <= max) { - req(i); - } else if (current == max) { - loop.stop(); - } - }); + reqs[i] = fs->request( + {Resource::Unknown, std::string("http://127.0.0.1:3000/load/") + util::toString(current)}, + [&, i, current](Response res) { + reqs[i].reset(); + EXPECT_EQ(nullptr, res.error); + ASSERT_TRUE(res.data.get()); + EXPECT_EQ(std::string("Request ") + util::toString(current), *res.data); + EXPECT_FALSE(bool(res.expires)); + EXPECT_FALSE(res.mustRevalidate); + EXPECT_FALSE(bool(res.modified)); + EXPECT_FALSE(bool(res.etag)); + + if (number <= max) { + req(i); + } else if (current == max) { + loop.stop(); + } + } + ); }; for (int i = 0; i < concurrency; i++) { @@ -284,7 +288,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusChange)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/delayed" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/delayed"}; // This request takes 200 milliseconds to answer. std::unique_ptr req = fs->request(resource, [&](Response res) { @@ -301,9 +305,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusChange)) { // After 50 milliseconds, we're going to trigger a NetworkStatus change. util::Timer reachableTimer; - reachableTimer.start(Milliseconds(50), Duration::zero(), [] () { - mbgl::NetworkStatus::Reachable(); - }); + reachableTimer.start(Milliseconds(50), Duration::zero(), []() { mbgl::NetworkStatus::Reachable(); }); loop.run(); } @@ -318,7 +320,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusChangePreempt)) { const auto start = Clock::now(); int counter = 0; - const Resource resource{ Resource::Unknown, "http://127.0.0.1:3001/test" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3001/test"}; std::unique_ptr req = fs->request(resource, [&](Response res) { const auto duration = std::chrono::duration(Clock::now() - start).count(); if (counter == 0) { @@ -345,9 +347,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusChangePreempt)) { // After 400 milliseconds, we're going to trigger a NetworkStatus change. util::Timer reachableTimer; - reachableTimer.start(Milliseconds(400), Duration::zero(), [] () { - mbgl::NetworkStatus::Reachable(); - }); + reachableTimer.start(Milliseconds(400), Duration::zero(), []() { mbgl::NetworkStatus::Reachable(); }); fs->resume(); loop.run(); @@ -357,13 +357,13 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusOnlineOffline)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/test" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test"}; EXPECT_EQ(NetworkStatus::Get(), NetworkStatus::Status::Online) << "Default status should be Online"; NetworkStatus::Set(NetworkStatus::Status::Offline); util::Timer onlineTimer; - onlineTimer.start(Milliseconds(100), Duration::zero(), [&] () { + onlineTimer.start(Milliseconds(100), Duration::zero(), [&]() { NetworkStatus::Set(NetworkStatus::Status::Online); }); @@ -441,7 +441,7 @@ TEST(OnlineFileSource, GetBaseURLAndApiKeyWhilePaused) { EXPECT_EQ(*fs->getProperty(API_KEY_KEY).getString(), apiKey); } -TEST(OnlineFileSource, ChangeAPIBaseURL){ +TEST(OnlineFileSource, ChangeAPIBaseURL) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); EXPECT_EQ(ResourceOptions::Default().tileServerOptions().baseURL(), *fs->getProperty(API_BASE_URL_KEY).getString()); @@ -453,10 +453,10 @@ TEST(OnlineFileSource, ChangeAPIBaseURL){ EXPECT_EQ(customURL, updatedTileServerOptions.baseURL()); } -TEST(OnlineFileSource, ChangeTileServerOptions){ +TEST(OnlineFileSource, ChangeTileServerOptions) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); - + TileServerOptions tileServerOptsChanged; tileServerOptsChanged.withApiKeyParameterName("apiKeyChanged") .withBaseURL("baseURLChanged") @@ -468,8 +468,7 @@ TEST(OnlineFileSource, ChangeTileServerOptions){ .withTileTemplate("tileTemplateChanged", "tileDomainChanged", {}) .withUriSchemeAlias("uriSchemeAliasChanged"); ResourceOptions resOpts; - resOpts.withApiKey("changedAPIKey") - .withTileServerOptions(tileServerOptsChanged); + resOpts.withApiKey("changedAPIKey").withTileServerOptions(tileServerOptsChanged); fs->setResourceOptions(resOpts.clone()); @@ -498,7 +497,6 @@ TEST(OnlineFileSource, ChangeTileServerOptions){ EXPECT_EQ(resOpts.tileServerOptions().styleVersionPrefix(), tileServerOptsChanged.styleVersionPrefix()); } - TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequests)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); @@ -529,7 +527,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequests)) { }); // Second regular priority request that should de-preoritize low priority request. - Resource regular2{ Resource::Unknown, "http://127.0.0.1:3000/load/3" }; + Resource regular2{Resource::Unknown, "http://127.0.0.1:3000/load/3"}; std::unique_ptr req_2 = fs->request(regular2, [&](Response) { response_counter++; req_2.reset(); @@ -540,7 +538,6 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequests)) { loop.run(); } - TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequestsMany)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); @@ -557,17 +554,18 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequestsMany)) { for (int num_reqs = 0; num_reqs < 20; num_reqs++) { if (num_reqs % 2 == 0) { std::unique_ptr req = fs->request( - {Resource::Unknown, "http://127.0.0.1:3000/load/" + std::to_string(num_reqs)}, [&](Response) { + {Resource::Unknown, "http://127.0.0.1:3000/load/" + std::to_string(num_reqs)}, + [&](Response) { response_counter++; if (response_counter <= 10) { // count the high priority requests that arrive late correctly correct_regular++; } - }); + } + ); collector.push_back(std::move(req)); - } - else { - Resource resource = { Resource::Unknown, "http://127.0.0.1:3000/load/" + std::to_string(num_reqs) }; + } else { + Resource resource = {Resource::Unknown, "http://127.0.0.1:3000/load/" + std::to_string(num_reqs)}; resource.setPriority(Resource::Priority::Low); std::unique_ptr req = fs->request(std::move(resource), [&](Response) { diff --git a/test/storage/resource.test.cpp b/test/storage/resource.test.cpp index e03f339a97f..4f37548b076 100644 --- a/test/storage/resource.test.cpp +++ b/test/storage/resource.test.cpp @@ -19,7 +19,9 @@ TEST(Resource, Source) { TEST(Resource, Tile) { using namespace mbgl; - Resource rasterTile = Resource::tile("http://example.com/{z}/{x}/{y}{ratio}.png", 2.0, 1, 2, 3, Tileset::Scheme::XYZ); + Resource rasterTile = Resource::tile( + "http://example.com/{z}/{x}/{y}{ratio}.png", 2.0, 1, 2, 3, Tileset::Scheme::XYZ + ); EXPECT_EQ(Resource::Kind::Tile, rasterTile.kind); EXPECT_EQ("http://example.com/3/1/2@2x.png", rasterTile.url); EXPECT_EQ("http://example.com/{z}/{x}/{y}{ratio}.png", rasterTile.tileData->urlTemplate); @@ -28,7 +30,9 @@ TEST(Resource, Tile) { EXPECT_EQ(2, rasterTile.tileData->y); EXPECT_EQ(3, rasterTile.tileData->z); - Resource vectorTile = Resource::tile("http://example.com/{prefix}/{z}/{x}/{y}.mvt", 2.0, 1, 2, 3, Tileset::Scheme::XYZ); + Resource vectorTile = Resource::tile( + "http://example.com/{prefix}/{z}/{x}/{y}.mvt", 2.0, 1, 2, 3, Tileset::Scheme::XYZ + ); EXPECT_EQ(Resource::Kind::Tile, vectorTile.kind); EXPECT_EQ("http://example.com/12/3/1/2.mvt", vectorTile.url); EXPECT_EQ("http://example.com/{prefix}/{z}/{x}/{y}.mvt", vectorTile.tileData->urlTemplate); diff --git a/test/storage/sqlite.test.cpp b/test/storage/sqlite.test.cpp index 1e2cc5488e4..4030231419f 100644 --- a/test/storage/sqlite.test.cpp +++ b/test/storage/sqlite.test.cpp @@ -11,8 +11,8 @@ TEST(SQLite, Statement) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(":memory:", mapbox::sqlite::ReadWriteCreate); db.exec("CREATE TABLE test (id INTEGER);"); - mapbox::sqlite::Statement stmt1{ db, "INSERT INTO test (id) VALUES (?1);" }; - mapbox::sqlite::Query query1{ stmt1 }; + mapbox::sqlite::Statement stmt1{db, "INSERT INTO test (id) VALUES (?1);"}; + mapbox::sqlite::Query query1{stmt1}; ASSERT_EQ(query1.lastInsertRowId(), 0); ASSERT_EQ(query1.changes(), 0u); query1.bind(1, 10); @@ -20,8 +20,8 @@ TEST(SQLite, Statement) { ASSERT_EQ(query1.lastInsertRowId(), 1); ASSERT_EQ(query1.changes(), 1u); - mapbox::sqlite::Statement stmt2{ db, "INSERT INTO test (id) VALUES (?1);" }; - mapbox::sqlite::Query query2{ stmt2 }; + mapbox::sqlite::Statement stmt2{db, "INSERT INTO test (id) VALUES (?1);"}; + mapbox::sqlite::Query query2{stmt2}; ASSERT_EQ(query2.lastInsertRowId(), 0); ASSERT_EQ(query2.changes(), 0u); query2.bind(1, 20); @@ -35,15 +35,18 @@ TEST(SQLite, TEST_REQUIRES_WRITE(TryOpen)) { // Should return a CANTOPEN exception when the database doesn't exist, // make sure all the backends behave the same way. - auto result = mapbox::sqlite::Database::tryOpen("test/fixtures/offline_database/foobar123.db", mapbox::sqlite::ReadOnly); + auto result = mapbox::sqlite::Database::tryOpen( + "test/fixtures/offline_database/foobar123.db", mapbox::sqlite::ReadOnly + ); ASSERT_TRUE(result.is()); ASSERT_EQ(result.get().code, mapbox::sqlite::ResultCode::CantOpen); EXPECT_EQ(0u, log.uncheckedCount()); } TEST(SQLite, CloseDatabaseWithPendingTransaction) { - auto db = std::make_unique(mapbox::sqlite::Database::open( - ":memory:", mapbox::sqlite::ReadWriteCreate)); + auto db = std::make_unique( + mapbox::sqlite::Database::open(":memory:", mapbox::sqlite::ReadWriteCreate) + ); mapbox::sqlite::Transaction transaction(*db); transaction.commit(); } @@ -51,8 +54,7 @@ TEST(SQLite, CloseDatabaseWithPendingTransaction) { TEST(SQLite, CloseMovedDatabaseWithPendingTransaction) { // Verifies that we can correctly commit a transaction even if we move the Database object to // another address. - auto db1 = mapbox::sqlite::Database::open(":memory:", - mapbox::sqlite::ReadWriteCreate); + auto db1 = mapbox::sqlite::Database::open(":memory:", mapbox::sqlite::ReadWriteCreate); std::unique_ptr db2; mapbox::sqlite::Transaction transaction(db1); db2 = std::make_unique(std::move(db1)); diff --git a/test/storage/sync_file_source.test.cpp b/test/storage/sync_file_source.test.cpp index 6ce2d26348d..4797494e9ef 100644 --- a/test/storage/sync_file_source.test.cpp +++ b/test/storage/sync_file_source.test.cpp @@ -20,7 +20,8 @@ class SyncFileSource : public FileSource { auto it = assets.find(resource.url); if (it == assets.end()) { response.error = std::make_unique( - Response::Error::Reason::NotFound, std::string{ "Not Found: " } + resource.url); + Response::Error::Reason::NotFound, std::string{"Not Found: "} + resource.url + ); } else { response.data = it->second; } @@ -41,11 +42,9 @@ class SyncFileSource : public FileSource { TEST(SyncFileSource, LoadSyncRender) { util::RunLoop loop; auto fs = std::make_shared(); - fs->add("maptiler://maps/streets", - util::read_file("test/fixtures/resources/source_vector.json")); - fs->add("maptiler://sprites/streets/sprite", - util::read_file("test/fixtures/resources/sprite.png")); - HeadlessFrontend frontend{ { 512, 512 }, 1.0 }; - MapAdapter map{ frontend, MapObserver::nullObserver(), fs, MapOptions() }; + fs->add("maptiler://maps/streets", util::read_file("test/fixtures/resources/source_vector.json")); + fs->add("maptiler://sprites/streets/sprite", util::read_file("test/fixtures/resources/sprite.png")); + HeadlessFrontend frontend{{512, 512}, 1.0}; + MapAdapter map{frontend, MapObserver::nullObserver(), fs, MapOptions()}; map.getStyle().loadJSON(util::read_file("test/fixtures/resources/style_vector.json")); } diff --git a/test/style/conversion/conversion_impl.test.cpp b/test/style/conversion/conversion_impl.test.cpp index 1a6c1a030c6..b561bf654a5 100644 --- a/test/style/conversion/conversion_impl.test.cpp +++ b/test/style/conversion/conversion_impl.test.cpp @@ -8,13 +8,13 @@ namespace conversion { class MockConvertible { public: MockConvertible() = default; - MockConvertible(int* counter_) : counter(counter_) {} + MockConvertible(int* counter_) + : counter(counter_) {} - MockConvertible(MockConvertible&& other) noexcept : counter(other.counter) {} + MockConvertible(MockConvertible&& other) noexcept + : counter(other.counter) {} - ~MockConvertible() { - ++*counter; - } + ~MockConvertible() { ++*counter; } int* counter = nullptr; }; @@ -22,58 +22,34 @@ class MockConvertible { template <> class ConversionTraits { public: - static bool isUndefined(const MockConvertible&) { - return false; - } + static bool isUndefined(const MockConvertible&) { return false; } - static bool isArray(const MockConvertible&) { - return false; - } + static bool isArray(const MockConvertible&) { return false; } - static bool isObject(const MockConvertible&) { - return false; - } + static bool isObject(const MockConvertible&) { return false; } - static std::size_t arrayLength(const MockConvertible&) { - return 0u; - } + static std::size_t arrayLength(const MockConvertible&) { return 0u; } - static MockConvertible arrayMember(const MockConvertible&, std::size_t) { - return {}; - } + static MockConvertible arrayMember(const MockConvertible&, std::size_t) { return {}; } - static std::optional objectMember(const MockConvertible&, const char *) { - return std::nullopt; - } + static std::optional objectMember(const MockConvertible&, const char*) { return std::nullopt; } template static std::optional eachMember(const MockConvertible&, Fn&&) { return std::nullopt; } - static std::optional toBool(const MockConvertible&) { - return std::nullopt; - } + static std::optional toBool(const MockConvertible&) { return std::nullopt; } - static std::optional toNumber(const MockConvertible&) { - return std::nullopt; - } + static std::optional toNumber(const MockConvertible&) { return std::nullopt; } - static std::optional toDouble(const MockConvertible&) { - return std::nullopt; - } + static std::optional toDouble(const MockConvertible&) { return std::nullopt; } - static std::optional toString(const MockConvertible&) { - return std::nullopt; - } + static std::optional toString(const MockConvertible&) { return std::nullopt; } - static std::optional toValue(const MockConvertible&) { - return std::nullopt; - } + static std::optional toValue(const MockConvertible&) { return std::nullopt; } - static std::optional toGeoJSON(const MockConvertible&, Error&) { - return std::nullopt; - } + static std::optional toGeoJSON(const MockConvertible&, Error&) { return std::nullopt; } }; } // namespace conversion diff --git a/test/style/conversion/function.test.cpp b/test/style/conversion/function.test.cpp index 5c96e5124b8..9471b02eab1 100644 --- a/test/style/conversion/function.test.cpp +++ b/test/style/conversion/function.test.cpp @@ -62,18 +62,27 @@ TEST(StyleConversion, CompositeFunctionExpression) { auto fn1 = parseFunction(R"(["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10])"); ASSERT_TRUE(fn1); - auto fn2 = parseFunction(R"(["coalesce", ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10], 0])"); + auto fn2 = + parseFunction(R"(["coalesce", ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10], 0])"); ASSERT_TRUE(fn2); - auto fn3 = parseFunction(R"(["let", "a", 0, ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10] ])"); + auto fn3 = parseFunction( + R"(["let", "a", 0, ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10] ])" + ); ASSERT_TRUE(fn3); - auto fn4 = parseFunction(R"(["coalesce", ["let", "a", 0, ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10]], 0])"); + auto fn4 = parseFunction( + R"(["coalesce", ["let", "a", 0, ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10]], 0])" + ); ASSERT_TRUE(fn4); - auto fn5 = parseFunction(R"(["coalesce", ["interpolate", ["linear"], ["number", ["get", "x"]], 0, ["zoom"], 10, 10], 0])"); + auto fn5 = + parseFunction(R"(["coalesce", ["interpolate", ["linear"], ["number", ["get", "x"]], 0, ["zoom"], 10, 10], 0])"); ASSERT_FALSE(fn5); - ASSERT_EQ(R"("zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.)", error.message); + ASSERT_EQ( + R"("zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.)", + error.message + ); } TEST(StyleConversion, TokenStrings) { @@ -88,12 +97,19 @@ TEST(StyleConversion, TokenStrings) { ASSERT_EQ(*convertTokenStringToExpression("{token}"), *toString(get(literal("token")))); ASSERT_EQ(*convertTokenStringToExpression("token {token}"), *concat(vec(literal("token "), get(literal("token"))))); ASSERT_EQ(*convertTokenStringToExpression("{token} token"), *concat(vec(get(literal("token")), literal(" token")))); - ASSERT_EQ(*convertTokenStringToExpression("{token} {token}"), *concat(vec(get(literal("token")), literal(" "), get(literal("token"))))); - ASSERT_EQ(*convertTokenStringToExpression("{token} {token"), *concat(vec(get(literal("token")), literal(" "), literal("{token")))); - ASSERT_EQ(*convertTokenStringToExpression("{token {token}"), *concat(vec(literal("{token "), get(literal("token"))))); + ASSERT_EQ( + *convertTokenStringToExpression("{token} {token}"), + *concat(vec(get(literal("token")), literal(" "), get(literal("token")))) + ); + ASSERT_EQ( + *convertTokenStringToExpression("{token} {token"), + *concat(vec(get(literal("token")), literal(" "), literal("{token"))) + ); + ASSERT_EQ( + *convertTokenStringToExpression("{token {token}"), *concat(vec(literal("{token "), get(literal("token")))) + ); } - TEST(StyleConversion, FormattedIdentityFunction) { // See https://github.com/mapbox/mapbox-gl-js/issues/7311 // We never introduced this bug on gl-native, but we _almost_ did @@ -102,7 +118,7 @@ TEST(StyleConversion, FormattedIdentityFunction) { auto parseFunction = [&](const std::string& json) { return convertJSON>(json, error, true, false); }; - + using namespace mbgl::style::expression::dsl; auto fn1 = parseFunction(R"({ "property": "name", "type": "identity" })"); diff --git a/test/style/conversion/geojson_options.test.cpp b/test/style/conversion/geojson_options.test.cpp index cc5341e6ee2..878d37fc1fd 100644 --- a/test/style/conversion/geojson_options.test.cpp +++ b/test/style/conversion/geojson_options.test.cpp @@ -11,15 +11,18 @@ using namespace mbgl::style::conversion; TEST(GeoJSONOptions, Basic) { Error error; std::optional converted = convertJSON("{}", error); - ASSERT_TRUE((bool) converted); + ASSERT_TRUE((bool)converted); } TEST(GeoJSONOptions, ErrorHandling) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "maxzoom": "should not be a string" - })JSON", error); - ASSERT_FALSE((bool) converted); + })JSON", + error + ); + ASSERT_FALSE((bool)converted); } TEST(GeoJSONOptions, RetainsDefaults) { @@ -43,7 +46,8 @@ TEST(GeoJSONOptions, RetainsDefaults) { TEST(GeoJSONOptions, FullConversion) { Error error; - GeoJSONOptions converted = *convertJSON(R"JSON({ + GeoJSONOptions converted = *convertJSON( + R"JSON({ "maxzoom": 1, "buffer": 2, "tolerance": 3, @@ -56,7 +60,9 @@ TEST(GeoJSONOptions, FullConversion) { "sum": [["+", ["accumulated"], ["get", "sum"]], ["get", "scalerank"]], "has_island": ["any", ["==", ["get", "featureclass"], "island"]] } - })JSON", error); + })JSON", + error + ); // GeoJSON-VT ASSERT_EQ(converted.minzoom, 0); diff --git a/test/style/conversion/layer.test.cpp b/test/style/conversion/layer.test.cpp index 079d7ce5a5f..248c98579ae 100644 --- a/test/style/conversion/layer.test.cpp +++ b/test/style/conversion/layer.test.cpp @@ -44,10 +44,8 @@ TEST(StyleConversion, LayerTransition) { } })JSON"); ASSERT_STREQ("background", layer->getTypeInfo()->type); - ASSERT_EQ(400ms, *static_cast(layer.get())->impl().paint - .get().options.duration); - ASSERT_EQ(500ms, *static_cast(layer.get())->impl().paint - .get().options.delay); + ASSERT_EQ(400ms, *static_cast(layer.get())->impl().paint.get().options.duration); + ASSERT_EQ(500ms, *static_cast(layer.get())->impl().paint.get().options.delay); } TEST(StyleConversion, SerializeDefaults) { diff --git a/test/style/conversion/light.test.cpp b/test/style/conversion/light.test.cpp index e49667f319a..cf522eb249a 100644 --- a/test/style/conversion/light.test.cpp +++ b/test/style/conversion/light.test.cpp @@ -25,7 +25,7 @@ TEST(StyleConversion, Light) { { auto light = parseLight("{}"); - ASSERT_TRUE((bool) light); + ASSERT_TRUE((bool)light); const mbgl::JSValue colorValue("blue"); light->setProperty("color", &colorValue); @@ -41,17 +41,21 @@ TEST(StyleConversion, Light) { ASSERT_EQ(light->getIntensity().asConstant(), 0.5); mbgl::JSValue::AllocatorType allocator; - const mbgl::JSValue positionValue(std::move(mbgl::JSValue(rapidjson::kArrayType).PushBack(1.f, allocator).PushBack(2.f, allocator).PushBack(3.f, allocator).Move())); + const mbgl::JSValue positionValue(std::move(mbgl::JSValue(rapidjson::kArrayType) + .PushBack(1.f, allocator) + .PushBack(2.f, allocator) + .PushBack(3.f, allocator) + .Move())); light->setProperty("position", &positionValue); ASSERT_FALSE(light->getPosition().isUndefined()); ASSERT_TRUE(light->getPosition().isConstant()); - std::array expected{{ 1.f, 2.f, 3.f }}; - ASSERT_EQ(light->getPosition().asConstant(), mbgl::style::Position({ expected })); + std::array expected{{1.f, 2.f, 3.f}}; + ASSERT_EQ(light->getPosition().asConstant(), mbgl::style::Position({expected})); } { auto light = parseLight(R"({"color":{"stops":[[14,"blue"],[16,"red"]]},"intensity":0.3,"position":[3,90,90]})"); - ASSERT_TRUE((bool) light); + ASSERT_TRUE((bool)light); ASSERT_TRUE(light->getAnchor().isUndefined()); ASSERT_FALSE(light->getAnchor().isConstant()); @@ -69,54 +73,54 @@ TEST(StyleConversion, Light) { ASSERT_FALSE(light->getPosition().isUndefined()); ASSERT_TRUE(light->getPosition().isConstant()); - std::array expected{{ 3, 90, 90 }}; - ASSERT_EQ(light->getPosition().asConstant(), mbgl::style::Position({ expected })); + std::array expected{{3, 90, 90}}; + ASSERT_EQ(light->getPosition().asConstant(), mbgl::style::Position({expected})); ASSERT_FALSE(light->getPosition().isExpression()); } { auto light = parseLight(R"({"color":"blue","intensity":0.3,"color-transition":{"duration":1000}})"); - ASSERT_TRUE((bool) light); + ASSERT_TRUE((bool)light); ASSERT_FALSE(light->getColor().isUndefined()); ASSERT_TRUE(light->getColor().isConstant()); ASSERT_FALSE(light->getColor().isExpression()); ASSERT_EQ(light->getColorTransition().duration, mbgl::Duration(mbgl::Milliseconds(1000))); - ASSERT_FALSE((bool) light->getColorTransition().delay); + ASSERT_FALSE((bool)light->getColorTransition().delay); } { auto light = parseLight(R"({"intensity":false})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be a number", error.message); } { auto light = parseLight(R"({"intensity":{"stops":[[15,"red"],[17,"blue"]]}})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be a number", error.message); } { auto light = parseLight(R"({"color":5})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be a string", error.message); } { auto light = parseLight(R"({"position":[0,5]})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be an array of 3 numbers", error.message); } { auto light = parseLight(R"({"anchor":"something"})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be a valid enumeration value", error.message); } } diff --git a/test/style/conversion/stringify.test.cpp b/test/style/conversion/stringify.test.cpp index 144c26aa9d4..89373166a8a 100644 --- a/test/style/conversion/stringify.test.cpp +++ b/test/style/conversion/stringify.test.cpp @@ -59,15 +59,15 @@ TEST(Stringify, Color) { } TEST(Stringify, Array) { - ASSERT_EQ(stringify(std::array {{ 1, 2 }}), "[1.0,2.0]"); + ASSERT_EQ(stringify(std::array{{1, 2}}), "[1.0,2.0]"); } TEST(Stringify, Vector) { - ASSERT_EQ(stringify(std::vector {{ 1, 2 }}), "[1.0,2.0]"); + ASSERT_EQ(stringify(std::vector{{1, 2}}), "[1.0,2.0]"); } TEST(Stringify, Map) { - ASSERT_EQ(stringify(std::unordered_map {{ "a", 1.0f }}), "{\"a\":1.0}"); + ASSERT_EQ(stringify(std::unordered_map{{"a", 1.0f}}), "{\"a\":1.0}"); } TEST(Stringify, Value) { @@ -84,53 +84,48 @@ TEST(Stringify, Filter) { TEST(Stringify, PropertyExpression) { using namespace mbgl::style::expression::dsl; - ASSERT_EQ(stringify(PropertyExpression( - interpolate( + ASSERT_EQ( + stringify(PropertyExpression(interpolate(linear(), zoom(), 0.0, literal(1.0), 1.0, literal(2.0)))), + "[\"interpolate\",[\"linear\"],[\"zoom\"],0.0,1.0,1.0,2.0]" + ); + + ASSERT_EQ( + stringify(PropertyExpression( + interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0)) + )), + "[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\",\"property\"]],0.0,1.0,1.0,2.0]" + ); + + ASSERT_EQ( + stringify(PropertyExpression(interpolate( linear(), zoom(), - 0.0, literal(1.0), - 1.0, literal(2.0) - ))), - "[\"interpolate\",[\"linear\"],[\"zoom\"],0.0,1.0,1.0,2.0]"); - - ASSERT_EQ(stringify(PropertyExpression( - interpolate( - exponential(2.0), - number(get("property")), - 0.0, literal(1.0), - 1.0, literal(2.0) - ))), - "[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\",\"property\"]],0.0,1.0,1.0,2.0]"); - - ASSERT_EQ(stringify(PropertyExpression( - interpolate( - linear(), - zoom(), - 0.0, interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0)), - 1.0, interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0)) + 0.0, + interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0)), + 1.0, + interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0)) ))), "[\"interpolate\"," - "[\"linear\"]," - "[\"zoom\"]," - "0.0,[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\",\"property\"]],0.0,1.0,1.0,2.0]," - "1.0,[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\",\"property\"]],0.0,1.0,1.0,2.0]]"); + "[\"linear\"]," + "[\"zoom\"]," + "0.0,[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\",\"property\"]],0.0,1.0,1.0,2.0]," + "1.0,[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\",\"property\"]],0.0,1.0,1.0,2.0]]" + ); } TEST(Stringify, PropertyValue) { using namespace mbgl::style::expression::dsl; ASSERT_EQ(stringify(PropertyValue(1)), "1.0"); - ASSERT_EQ(stringify(PropertyValue(PropertyExpression( - interpolate( - exponential(2.0), - zoom(), - 0.0, literal(1.0), - 1.0, literal(2.0) - )))), - "[\"interpolate\",[\"exponential\",2.0],[\"zoom\"],0.0,1.0,1.0,2.0]"); + ASSERT_EQ( + stringify(PropertyValue( + PropertyExpression(interpolate(exponential(2.0), zoom(), 0.0, literal(1.0), 1.0, literal(2.0))) + )), + "[\"interpolate\",[\"exponential\",2.0],[\"zoom\"],0.0,1.0,1.0,2.0]" + ); } TEST(Stringify, Layout) { - auto stringify = [] (const SymbolLayoutProperties::Unevaluated& layout) { + auto stringify = [](const SymbolLayoutProperties::Unevaluated& layout) { rapidjson::StringBuffer s; rapidjson::Writer writer(s); layout.stringify(writer); diff --git a/test/style/conversion/tileset.test.cpp b/test/style/conversion/tileset.test.cpp index 8812c475205..a203b6bd15a 100644 --- a/test/style/conversion/tileset.test.cpp +++ b/test/style/conversion/tileset.test.cpp @@ -11,87 +11,111 @@ using namespace mbgl::style::conversion; TEST(Tileset, Empty) { Error error; std::optional converted = convertJSON("{}", error); - EXPECT_FALSE((bool) converted); + EXPECT_FALSE((bool)converted); } TEST(Tileset, ErrorHandling) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": "should not be a string" - })JSON", error); - EXPECT_FALSE((bool) converted); + })JSON", + error + ); + EXPECT_FALSE((bool)converted); } TEST(Tileset, InvalidBounds) { { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [73, -180, -73, -120] - })JSON", error); + })JSON", + error + ); - EXPECT_FALSE((bool) converted); + EXPECT_FALSE((bool)converted); } { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [-120] - })JSON", error); + })JSON", + error + ); - EXPECT_FALSE((bool) converted); + EXPECT_FALSE((bool)converted); } { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": "should not be a string" - })JSON", error); + })JSON", + error + ); - EXPECT_FALSE((bool) converted); + EXPECT_FALSE((bool)converted); } } TEST(Tileset, ValidWorldBounds) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [-180, -90, 180, 90] - })JSON", error); - EXPECT_TRUE((bool) converted); + })JSON", + error + ); + EXPECT_TRUE((bool)converted); EXPECT_EQ(converted->bounds, LatLngBounds::hull({90, -180}, {-90, 180})); } TEST(Tileset, PointBounds) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [0, 0, 0, 0] - })JSON", error); - EXPECT_TRUE((bool) converted); + })JSON", + error + ); + EXPECT_TRUE((bool)converted); EXPECT_EQ(converted->bounds, LatLngBounds::hull({0, 0}, {0, 0})); } TEST(Tileset, BoundsAreClamped) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [-181.0000005,-90.000000006,180.00000000000006,91] - })JSON", error); - EXPECT_TRUE((bool) converted); + })JSON", + error + ); + EXPECT_TRUE((bool)converted); EXPECT_EQ(converted->bounds, LatLngBounds::hull({90, -180}, {-90, 180})); } TEST(Tileset, FullConversion) { Error error; - Tileset converted = *convertJSON(R"JSON({ + Tileset converted = *convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "scheme": "xyz", "minzoom": 1, "maxzoom": 2, "attribution": "mapbox", "bounds": [-180, -73, -120, 73] - })JSON", error); + })JSON", + error + ); EXPECT_EQ(converted.tiles[0], "http://mytiles"); EXPECT_EQ(converted.scheme, Tileset::Scheme::XYZ); diff --git a/test/style/expression/expression.test.cpp b/test/style/expression/expression.test.cpp index 85945fb5345..721d2c02222 100644 --- a/test/style/expression/expression.test.cpp +++ b/test/style/expression/expression.test.cpp @@ -19,7 +19,6 @@ #include #endif - using namespace mbgl; using namespace mbgl::style; @@ -27,16 +26,15 @@ TEST(Expression, IsExpression) { rapidjson::GenericDocument, rapidjson::CrtAllocator> spec; spec.Parse<0>(util::read_file("scripts/style-spec-reference/v8.json").c_str()); ASSERT_FALSE(spec.HasParseError()); - ASSERT_TRUE(spec.IsObject() && - spec.HasMember("expression_name") && - spec["expression_name"].IsObject() && - spec["expression_name"].HasMember("values") && - spec["expression_name"]["values"].IsObject()); + ASSERT_TRUE( + spec.IsObject() && spec.HasMember("expression_name") && spec["expression_name"].IsObject() && + spec["expression_name"].HasMember("values") && spec["expression_name"]["values"].IsObject() + ); const auto& allExpressions = spec["expression_name"]["values"]; - for(auto& entry : allExpressions.GetObject()) { - const std::string name { entry.name.GetString(), entry.name.GetStringLength() }; + for (auto& entry : allExpressions.GetObject()) { + const std::string name{entry.name.GetString(), entry.name.GetStringLength()}; JSDocument document; document.Parse<0>(R"([")" + name + R"("])"); const JSValue* expression = &document; @@ -45,7 +43,8 @@ TEST(Expression, IsExpression) { // TODO: "interpolate-lab": https://github.com/mapbox/mapbox-gl-native/issues/8720 if (name == "interpolate-hcl" || name == "interpolate-lab") { if (expression::isExpression(conversion::Convertible(expression))) { - ASSERT_TRUE(false) << "Expression name" << name << "is implemented - please update Expression.IsExpression test."; + ASSERT_TRUE(false) << "Expression name" << name + << "is implemented - please update Expression.IsExpression test."; } continue; } @@ -82,7 +81,6 @@ TEST_P(ExpressionEqualityTest, ExpressionEquality) { std::unique_ptr expression_b = parse(base + ".b.json", error); ASSERT_TRUE(expression_b) << GetParam() << ": " << error; - EXPECT_TRUE(*expression_a1 == *expression_a2); EXPECT_TRUE(*expression_a1 != *expression_b); } diff --git a/test/style/filter.test.cpp b/test/style/filter.test.cpp index ad397bfecaf..08d484f3aac 100644 --- a/test/style/filter.test.cpp +++ b/test/style/filter.test.cpp @@ -19,24 +19,26 @@ using namespace mbgl; using namespace mbgl::style; -bool filter(const char * json, - const PropertyMap& featureProperties = {{}}, - FeatureIdentifier featureId = {}, - FeatureType featureType = FeatureType::Point, - GeometryCollection featureGeometry = {}, - float zoom = 0.0f) { +bool filter( + const char* json, + const PropertyMap& featureProperties = {{}}, + FeatureIdentifier featureId = {}, + FeatureType featureType = FeatureType::Point, + GeometryCollection featureGeometry = {}, + float zoom = 0.0f +) { conversion::Error error; std::optional filter = conversion::convertJSON(json, error); EXPECT_TRUE(bool(filter)); EXPECT_EQ(error.message, ""); - - StubGeometryTileFeature feature { featureId, featureType, featureGeometry, featureProperties }; - expression::EvaluationContext context = { zoom, &feature }; - + + StubGeometryTileFeature feature{featureId, featureType, featureGeometry, featureProperties}; + expression::EvaluationContext context = {zoom, &feature}; + return (*filter)(context); } -void invalidFilter(const char * json) { +void invalidFilter(const char* json) { conversion::Error error; std::optional filter = conversion::convertJSON(json, error); EXPECT_FALSE(bool(filter)); @@ -45,27 +47,27 @@ void invalidFilter(const char * json) { void writeJSON(rapidjson::Writer& writer, const Value& value) { value.match( - [&] (const NullValue&) { writer.Null(); }, - [&] (bool b) { writer.Bool(b); }, - [&] (uint64_t t) { writer.Uint64(t); }, - [&] (int64_t t) { writer.Int64(t); }, - [&] (double f) { + [&](const NullValue&) { writer.Null(); }, + [&](bool b) { writer.Bool(b); }, + [&](uint64_t t) { writer.Uint64(t); }, + [&](int64_t t) { writer.Int64(t); }, + [&](double f) { // make sure integer values are stringified without trailing ".0". f == std::floor(f) ? writer.Int(static_cast(f)) : writer.Double(f); }, - [&] (const std::string& s) { writer.String(s); }, - [&] (const std::vector& arr) { + [&](const std::string& s) { writer.String(s); }, + [&](const std::vector& arr) { writer.StartArray(); - for(const auto& item : arr) { + for (const auto& item : arr) { writeJSON(writer, item); } writer.EndArray(); }, - [](const auto&) { - }); + [](const auto&) {} + ); } -std::string stringifyFilter(const char * json) { +std::string stringifyFilter(const char* json) { conversion::Error error; std::optional filter = conversion::convertJSON(json, error); EXPECT_TRUE(bool(filter)); @@ -81,33 +83,33 @@ std::string stringifyFilter(const char * json) { TEST(Filter, EqualsNull) { auto f = R"(["==", "foo", null])"; - ASSERT_TRUE(filter(f, {{ "foo", mapbox::feature::null_value }})); - - ASSERT_FALSE(filter(f, {{ "foo", int64_t(0) }})); - ASSERT_FALSE(filter(f, {{ "foo", int64_t(1) }})); - ASSERT_FALSE(filter(f, {{ "foo", std::string("0") }})); - ASSERT_FALSE(filter(f, {{ "foo", true }})); - ASSERT_FALSE(filter(f, {{ "foo", false }})); - ASSERT_FALSE(filter(f, {{ }})); + ASSERT_TRUE(filter(f, {{"foo", mapbox::feature::null_value}})); + + ASSERT_FALSE(filter(f, {{"foo", int64_t(0)}})); + ASSERT_FALSE(filter(f, {{"foo", int64_t(1)}})); + ASSERT_FALSE(filter(f, {{"foo", std::string("0")}})); + ASSERT_FALSE(filter(f, {{"foo", true}})); + ASSERT_FALSE(filter(f, {{"foo", false}})); + ASSERT_FALSE(filter(f, {{}})); } TEST(Filter, EqualsString) { auto f = R"(["==", "foo", "bar"])"; - ASSERT_TRUE(filter(f, {{ "foo", std::string("bar") }})); - ASSERT_FALSE(filter(f, {{ "foo", std::string("baz") }})); + ASSERT_TRUE(filter(f, {{"foo", std::string("bar")}})); + ASSERT_FALSE(filter(f, {{"foo", std::string("baz")}})); } TEST(Filter, EqualsNumber) { auto f = R"(["==", "foo", 0])"; - ASSERT_TRUE(filter(f, {{ "foo", int64_t(0) }})); - ASSERT_TRUE(filter(f, {{ "foo", uint64_t(0) }})); - ASSERT_TRUE(filter(f, {{ "foo", double(0) }})); - ASSERT_FALSE(filter(f, {{ "foo", int64_t(1) }})); - ASSERT_FALSE(filter(f, {{ "foo", uint64_t(1) }})); - ASSERT_FALSE(filter(f, {{ "foo", double(1) }})); - ASSERT_FALSE(filter(f, {{ "foo", std::string("0") }})); - ASSERT_FALSE(filter(f, {{ "foo", false }})); - ASSERT_FALSE(filter(f, {{ "foo", true }})); - ASSERT_FALSE(filter(f, {{ "foo", mapbox::feature::null_value }})); + ASSERT_TRUE(filter(f, {{"foo", int64_t(0)}})); + ASSERT_TRUE(filter(f, {{"foo", uint64_t(0)}})); + ASSERT_TRUE(filter(f, {{"foo", double(0)}})); + ASSERT_FALSE(filter(f, {{"foo", int64_t(1)}})); + ASSERT_FALSE(filter(f, {{"foo", uint64_t(1)}})); + ASSERT_FALSE(filter(f, {{"foo", double(1)}})); + ASSERT_FALSE(filter(f, {{"foo", std::string("0")}})); + ASSERT_FALSE(filter(f, {{"foo", false}})); + ASSERT_FALSE(filter(f, {{"foo", true}})); + ASSERT_FALSE(filter(f, {{"foo", mapbox::feature::null_value}})); ASSERT_FALSE(filter(f, {{}})); } @@ -133,70 +135,76 @@ TEST(Filter, InType) { TEST(Filter, InID) { auto f = R"(["in", "$id", "123", "1234", 1234])"; ASSERT_FALSE(filter(f)); - ASSERT_TRUE(filter(f, {{}}, { uint64_t(1234) })); - ASSERT_TRUE(filter(f, {{}}, { std::string("1234") })); - ASSERT_FALSE(filter(f, {{}}, { std::string("4321") })); + ASSERT_TRUE(filter(f, {{}}, {uint64_t(1234)})); + ASSERT_TRUE(filter(f, {{}}, {std::string("1234")})); + ASSERT_FALSE(filter(f, {{}}, {std::string("4321")})); } TEST(Filter, Any) { ASSERT_FALSE(filter("[\"any\"]")); - ASSERT_TRUE(filter("[\"any\", [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"any\", [\"==\", \"foo\", 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_TRUE(filter("[\"any\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_TRUE(filter("[\"any\", [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"any\", [\"==\", \"foo\", 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_TRUE(filter("[\"any\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); } TEST(Filter, AnyExpression) { ASSERT_FALSE(filter("[\"any\"]")); - ASSERT_TRUE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_TRUE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 0], [\"==\", [\"get\", \"foo\"], 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_TRUE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_TRUE(filter( + "[\"any\", [\"==\", [\"get\", \"foo\"], 0], [\"==\", [\"get\", \"foo\"], 1]]", + {{std::string("foo"), int64_t(1)}} + )); } TEST(Filter, All) { ASSERT_TRUE(filter("[\"all\"]", {{}})); - ASSERT_TRUE(filter("[\"all\", [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"all\", [\"==\", \"foo\", 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"all\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_TRUE(filter("[\"all\", [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"all\", [\"==\", \"foo\", 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"all\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); } TEST(Filter, AllExpression) { - ASSERT_TRUE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 0], [\"==\", [\"get\", \"foo\"], 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_TRUE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter( + "[\"all\", [\"==\", [\"get\", \"foo\"], 0], [\"==\", [\"get\", \"foo\"], 1]]", + {{std::string("foo"), int64_t(1)}} + )); } TEST(Filter, None) { ASSERT_TRUE(filter("[\"none\"]")); - ASSERT_FALSE(filter("[\"none\", [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_TRUE(filter("[\"none\", [\"==\", \"foo\", 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"none\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_FALSE(filter("[\"none\", [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_TRUE(filter("[\"none\", [\"==\", \"foo\", 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"none\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); } TEST(Filter, Has) { - ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{ std::string("foo"), int64_t(0) }})); - ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{ std::string("foo"), false }})); + ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{std::string("foo"), int64_t(1)}})); + ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{std::string("foo"), int64_t(0)}})); + ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{std::string("foo"), false}})); ASSERT_FALSE(filter("[\"has\", \"foo\"]")); ASSERT_FALSE(filter("[\"has\", \"$id\"]")); } TEST(Filter, NotHas) { - ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{ std::string("foo"), int64_t(0) }})); - ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{ std::string("foo"), false }})); + ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{std::string("foo"), int64_t(0)}})); + ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{std::string("foo"), false}})); ASSERT_TRUE(filter("[\"!has\", \"foo\"]")); } TEST(Filter, ID) { - FeatureIdentifier id1 { uint64_t{ 1234 } }; + FeatureIdentifier id1{uint64_t{1234}}; ASSERT_TRUE(filter("[\"==\", \"$id\", 1234]", {{}}, id1)); ASSERT_FALSE(filter("[\"==\", \"$id\", \"1234\"]", {{}}, id1)); - FeatureIdentifier id2 { std::string{ "1" } }; + FeatureIdentifier id2{std::string{"1"}}; ASSERT_FALSE(filter("[\"<\", \"$id\", \"0\"]", {{}}, id2)); ASSERT_TRUE(filter("[\"<\", \"$id\", \"1234\"]", {{}}, id2)); - ASSERT_FALSE(filter("[\"==\", \"$id\", 1234]", {{ "id", uint64_t(1234) }})); + ASSERT_FALSE(filter("[\"==\", \"$id\", 1234]", {{"id", uint64_t(1234)}})); } TEST(Filter, Expression) { @@ -224,11 +232,11 @@ TEST(Filter, LegacyProperty) { TEST(Filter, Serialize) { std::string json = R"(["any",["==","foo",0],["==","foo",1]])"; EXPECT_EQ(stringifyFilter(json.c_str()), std::string(json)); - + json = R"(["<=","two",2])"; EXPECT_EQ(stringifyFilter(json.c_str()), std::string(json)); - //Constant folding for Expression filters + // Constant folding for Expression filters json = R"(["==",["+",1,1],2])"; EXPECT_EQ(stringifyFilter(json.c_str()), std::string("true")); @@ -238,14 +246,18 @@ TEST(Filter, Serialize) { TEST(Filter, ExpressionLegacyMix) { conversion::Error error; - std::optional filter = conversion::convertJSON(R"(["any", ["all", ["==", ["geometry-type"], "LineString"]], ["==", "x", 1]])", error); + std::optional filter = conversion::convertJSON( + R"(["any", ["all", ["==", ["geometry-type"], "LineString"]], ["==", "x", 1]])", error + ); EXPECT_FALSE(bool(filter)); EXPECT_TRUE(error.message.size() > 0); } TEST(Filter, ZoomExpressionNested) { ASSERT_TRUE(filter(R"(["==", ["get", "two"], ["zoom"]])", {{"two", int64_t(2)}}, {}, FeatureType::Point, {}, 2.0f)); - ASSERT_FALSE(filter(R"(["==", ["get", "two"], ["+", ["zoom"], 1]])", {{"two", int64_t(2)}}, {}, FeatureType::Point, {}, 2.0f)); + ASSERT_FALSE( + filter(R"(["==", ["get", "two"], ["+", ["zoom"], 1]])", {{"two", int64_t(2)}}, {}, FeatureType::Point, {}, 2.0f) + ); } TEST(Filter, Internal) { diff --git a/test/style/properties.test.cpp b/test/style/properties.test.cpp index f3af1a92b27..23e725156e3 100644 --- a/test/style/properties.test.cpp +++ b/test/style/properties.test.cpp @@ -13,34 +13,22 @@ float evaluate(Transitioning>& property, Duration delta = D ZoomHistory zoomHistory; zoomHistory.update(0, TimePoint::min() + delta); - PropertyEvaluationParameters parameters { - zoomHistory, - TimePoint::min() + delta, - Duration::zero() - }; + PropertyEvaluationParameters parameters{zoomHistory, TimePoint::min() + delta, Duration::zero()}; - PropertyEvaluator evaluator { - parameters, - 0.0f - }; + PropertyEvaluator evaluator{parameters, 0.0f}; return property.evaluate(evaluator, parameters.now); } -PossiblyEvaluatedPropertyValue evaluateDataExpression(Transitioning>& property, Duration delta = Duration::zero()) { +PossiblyEvaluatedPropertyValue evaluateDataExpression( + Transitioning>& property, Duration delta = Duration::zero() +) { ZoomHistory zoomHistory; zoomHistory.update(0, TimePoint::min() + delta); - PropertyEvaluationParameters parameters { - zoomHistory, - TimePoint::min() + delta, - Duration::zero() - }; + PropertyEvaluationParameters parameters{zoomHistory, TimePoint::min() + delta, Duration::zero()}; - DataDrivenPropertyEvaluator evaluator { - parameters, - 0.0f - }; + DataDrivenPropertyEvaluator evaluator{parameters, 0.0f}; return property.evaluate(evaluator, parameters.now); } @@ -51,33 +39,20 @@ TEST(TransitioningPropertyValue, EvaluateDefaultValue) { } TEST(TransitioningPropertyValue, EvaluateUntransitionedConstant) { - Transitioning> property { - PropertyValue(1.0f), - Transitioning>(), - TransitionOptions(), - TimePoint::min() - }; + Transitioning> property{ + PropertyValue(1.0f), Transitioning>(), TransitionOptions(), TimePoint::min()}; ASSERT_EQ(1.0f, evaluate(property)); } TEST(TransitioningPropertyValue, EvaluateTransitionedConstantWithoutDelay) { TransitionOptions transition; - transition.duration = { 1000ms }; - - Transitioning> t0 { - PropertyValue(0.0f), - Transitioning>(), - TransitionOptions(), - TimePoint::min() - }; - - Transitioning> t1 { - PropertyValue(1.0f), - t0, - transition, - TimePoint::min() - }; + transition.duration = {1000ms}; + + Transitioning> t0{ + PropertyValue(0.0f), Transitioning>(), TransitionOptions(), TimePoint::min()}; + + Transitioning> t1{PropertyValue(1.0f), t0, transition, TimePoint::min()}; ASSERT_FLOAT_EQ(0.0f, evaluate(t1, 0ms)); ASSERT_FLOAT_EQ(0.823099f, evaluate(t1, 500ms)); @@ -86,22 +61,13 @@ TEST(TransitioningPropertyValue, EvaluateTransitionedConstantWithoutDelay) { TEST(TransitioningPropertyValue, EvaluateTransitionedConstantWithDelay) { TransitionOptions transition; - transition.delay = { 1000ms }; - transition.duration = { 1000ms }; - - Transitioning> t0 { - PropertyValue(0.0f), - Transitioning>(), - TransitionOptions(), - TimePoint::min() - }; - - Transitioning> t1 { - PropertyValue(1.0f), - t0, - transition, - TimePoint::min() - }; + transition.delay = {1000ms}; + transition.duration = {1000ms}; + + Transitioning> t0{ + PropertyValue(0.0f), Transitioning>(), TransitionOptions(), TimePoint::min()}; + + Transitioning> t1{PropertyValue(1.0f), t0, transition, TimePoint::min()}; ASSERT_FLOAT_EQ(0.0f, evaluate(t1, 0ms)); ASSERT_FLOAT_EQ(0.0f, evaluate(t1, 500ms)); @@ -112,27 +78,19 @@ TEST(TransitioningPropertyValue, EvaluateTransitionedConstantWithDelay) { TEST(TransitioningDataDrivenPropertyValue, Evaluate) { TransitionOptions transition; - transition.delay = { 1000ms }; - transition.duration = { 1000ms }; + transition.delay = {1000ms}; + transition.duration = {1000ms}; - Transitioning> t0 { - PropertyValue(0.0f), - Transitioning>(), - TransitionOptions(), - TimePoint::min() - }; + Transitioning> t0{ + PropertyValue(0.0f), Transitioning>(), TransitionOptions(), TimePoint::min()}; using namespace mbgl::style::expression::dsl; PropertyExpression expression(number(get("property_name"))); - Transitioning> t1 { - PropertyValue(expression), - t0, - transition, - TimePoint::min() - }; + Transitioning> t1{PropertyValue(expression), t0, transition, TimePoint::min()}; ASSERT_TRUE(evaluateDataExpression(t0, 0ms).isConstant()); - ASSERT_FALSE(evaluateDataExpression(t1, 0ms).isConstant()) << - "A paint property transition to a data-driven evaluates immediately to the final value (see https://github.com/mapbox/mapbox-gl-native/issues/8237)."; + ASSERT_FALSE(evaluateDataExpression(t1, 0ms).isConstant()) + << "A paint property transition to a data-driven evaluates immediately to the final value (see " + "https://github.com/mapbox/mapbox-gl-native/issues/8237)."; } diff --git a/test/style/property_expression.test.cpp b/test/style/property_expression.test.cpp index 8556a22dd54..5774eaf4845 100644 --- a/test/style/property_expression.test.cpp +++ b/test/style/property_expression.test.cpp @@ -35,13 +35,11 @@ float evaluate(PropertyValue value, float zoom) { return value.evaluate(PropertyEvaluator(PropertyEvaluationParameters(zoom), 0)); } -template -auto createOverride(expression::type::Type exprType, - PossiblyEvaluatedPropertyValue propValue, - std::string propName) { - return std::make_unique>(std::move(exprType), - std::move(propValue), - std::move(propName)); +template +auto createOverride( + expression::type::Type exprType, PossiblyEvaluatedPropertyValue propValue, std::string propName +) { + return std::make_unique>(std::move(exprType), std::move(propValue), std::move(propName)); } TEST(PropertyExpression, Constant) { @@ -63,74 +61,129 @@ TEST(PropertyExpression, Expression) { } TEST(PropertyExpression, Defaults) { - EXPECT_EQ(1.0f, PropertyExpression(number(get("property")), 0.0f) - .evaluate(oneInteger, 2.0f)); - EXPECT_EQ(1.0f, PropertyExpression(number(get("property")), 0.0f) - .evaluate(oneDouble, 2.0f)); - EXPECT_EQ(0.0f, PropertyExpression(number(get("property")), 0.0f) - .evaluate(oneString, 2.0f)); - EXPECT_EQ(2.0f, PropertyExpression(number(get("property"))) - .evaluate(oneString, 2.0f)); + EXPECT_EQ(1.0f, PropertyExpression(number(get("property")), 0.0f).evaluate(oneInteger, 2.0f)); + EXPECT_EQ(1.0f, PropertyExpression(number(get("property")), 0.0f).evaluate(oneDouble, 2.0f)); + EXPECT_EQ(0.0f, PropertyExpression(number(get("property")), 0.0f).evaluate(oneString, 2.0f)); + EXPECT_EQ(2.0f, PropertyExpression(number(get("property"))).evaluate(oneString, 2.0f)); } TEST(PropertyExpression, ZoomInterpolation) { - EXPECT_EQ(40.0f, PropertyExpression( - interpolate(linear(), zoom(), - 0.0, interpolate(linear(), number(get("property")), 1.0, literal(24.0)), - 1.5, interpolate(linear(), number(get("property")), 1.0, literal(36.0)), - 3.0, interpolate(linear(), number(get("property")), 1.0, literal(48.0)) - ), 0.0f) - .evaluate(2.0f, oneInteger, -1.0f)) << "Should interpolate between stops"; - - EXPECT_EQ(33.0, PropertyExpression( - interpolate(linear(), zoom(), - 5.0, interpolate(linear(), number(get("property")), 1.0, literal(33.0)), - 10.0, interpolate(linear(), number(get("property")), 1.0, literal(66.0)) - ), 0.0f) - .evaluate(0.0f, oneInteger, -1.0f)) << "Use first stop output for input values from -inf to first stop"; - - EXPECT_EQ(66.0, PropertyExpression( - interpolate(linear(), zoom(), - 0.0, interpolate(linear(), number(get("property")), 1.0, literal(33.0)), - 10.0, interpolate(linear(), number(get("property")), 1.0, literal(66.0)) - ), 0.0f) - .evaluate(20.0f, oneInteger, -1.0f)) << "Use last stop output for input values from last stop to +inf"; - - EXPECT_EQ(66.0f, PropertyExpression( - interpolate(linear(), zoom(), - 0.0, interpolate(linear(), number(get("property")), 1.0, literal(33.0)), - 10.0, interpolate(linear(), number(get("property")), 1.0, literal(66.0)) - ), 0.0f) - .evaluate(10.0f, oneInteger, -1.0f)) << "Should interpolate TO the last stop."; - - EXPECT_EQ(33.0f, PropertyExpression( - interpolate(linear(), zoom(), - 0.0, interpolate(linear(), number(get("property")), 1.0, literal(33.0)), - 10.0, interpolate(linear(), number(get("property")), 1.0, literal(66.0)) - ), 0.0f) - .evaluate(0.0f, oneInteger, -1.0f)) << "Should interpolate TO the first stop"; + EXPECT_EQ( + 40.0f, + PropertyExpression( + interpolate( + linear(), + zoom(), + 0.0, + interpolate(linear(), number(get("property")), 1.0, literal(24.0)), + 1.5, + interpolate(linear(), number(get("property")), 1.0, literal(36.0)), + 3.0, + interpolate(linear(), number(get("property")), 1.0, literal(48.0)) + ), + 0.0f + ) + .evaluate(2.0f, oneInteger, -1.0f) + ) << "Should interpolate between stops"; + + EXPECT_EQ( + 33.0, + PropertyExpression( + interpolate( + linear(), + zoom(), + 5.0, + interpolate(linear(), number(get("property")), 1.0, literal(33.0)), + 10.0, + interpolate(linear(), number(get("property")), 1.0, literal(66.0)) + ), + 0.0f + ) + .evaluate(0.0f, oneInteger, -1.0f) + ) << "Use first stop output for input values from -inf to first stop"; + + EXPECT_EQ( + 66.0, + PropertyExpression( + interpolate( + linear(), + zoom(), + 0.0, + interpolate(linear(), number(get("property")), 1.0, literal(33.0)), + 10.0, + interpolate(linear(), number(get("property")), 1.0, literal(66.0)) + ), + 0.0f + ) + .evaluate(20.0f, oneInteger, -1.0f) + ) << "Use last stop output for input values from last stop to +inf"; + + EXPECT_EQ( + 66.0f, + PropertyExpression( + interpolate( + linear(), + zoom(), + 0.0, + interpolate(linear(), number(get("property")), 1.0, literal(33.0)), + 10.0, + interpolate(linear(), number(get("property")), 1.0, literal(66.0)) + ), + 0.0f + ) + .evaluate(10.0f, oneInteger, -1.0f) + ) << "Should interpolate TO the last stop."; + + EXPECT_EQ( + 33.0f, + PropertyExpression( + interpolate( + linear(), + zoom(), + 0.0, + interpolate(linear(), number(get("property")), 1.0, literal(33.0)), + 10.0, + interpolate(linear(), number(get("property")), 1.0, literal(66.0)) + ), + 0.0f + ) + .evaluate(0.0f, oneInteger, -1.0f) + ) << "Should interpolate TO the first stop"; } TEST(PropertyExpression, Issue8460) { PropertyExpression fn1( - interpolate(linear(), zoom(), - 15.0, interpolate(linear(), number(get("property")), 1.0, literal(0.0)), - 15.2, interpolate(linear(), number(get("property")), 1.0, literal(600.0)) - ), 0.0f); - - EXPECT_NEAR( 0.0f, fn1.evaluate(15.0f, oneInteger, -1.0f), 0.00); + interpolate( + linear(), + zoom(), + 15.0, + interpolate(linear(), number(get("property")), 1.0, literal(0.0)), + 15.2, + interpolate(linear(), number(get("property")), 1.0, literal(600.0)) + ), + 0.0f + ); + + EXPECT_NEAR(0.0f, fn1.evaluate(15.0f, oneInteger, -1.0f), 0.00); EXPECT_NEAR(300.0f, fn1.evaluate(15.1f, oneInteger, -1.0f), 0.01); EXPECT_NEAR(600.0f, fn1.evaluate(15.2f, oneInteger, -1.0f), 0.00); EXPECT_NEAR(600.0f, fn1.evaluate(16.0f, oneInteger, -1.0f), 0.00); PropertyExpression fn2( - interpolate(linear(), zoom(), - 15.0, interpolate(linear(), number(get("property")), 1.0, literal(0.0)), - 15.2, interpolate(linear(), number(get("property")), 1.0, literal(300.0)), - 18.0, interpolate(linear(), number(get("property")), 1.0, literal(600.0)) - ), 0.0f); - - EXPECT_NEAR( 0.0f, fn2.evaluate(15.0f, oneInteger, -1.0f), 0.00); + interpolate( + linear(), + zoom(), + 15.0, + interpolate(linear(), number(get("property")), 1.0, literal(0.0)), + 15.2, + interpolate(linear(), number(get("property")), 1.0, literal(300.0)), + 18.0, + interpolate(linear(), number(get("property")), 1.0, literal(600.0)) + ), + 0.0f + ); + + EXPECT_NEAR(0.0f, fn2.evaluate(15.0f, oneInteger, -1.0f), 0.00); EXPECT_NEAR(150.0f, fn2.evaluate(15.1f, oneInteger, -1.0f), 0.01); EXPECT_NEAR(300.0f, fn2.evaluate(15.2f, oneInteger, -1.0f), 0.00); EXPECT_NEAR(385.71f, fn2.evaluate(16.0f, oneInteger, -1.0f), 0.01); @@ -140,8 +193,7 @@ TEST(PropertyExpression, Issue8460) { TEST(PropertyExpression, FormatSectionOverride) { using Value = expression::Value; - Value formattedSection = - std::unordered_map{ {"text-color", Value{Color::blue()}} }; + Value formattedSection = std::unordered_map{{"text-color", Value{Color::blue()}}}; auto ctx = expression::EvaluationContext(&oneDouble).withFormattedSection(&formattedSection); PossiblyEvaluatedPropertyValue constantValueRed(Color::red()); PossiblyEvaluatedPropertyValue constantValueGreen(Color::green()); @@ -272,9 +324,10 @@ TEST(PropertyExpression, WithinExpression) { // FeatureType::Point and FeatureType::LineString) { // testPoly is inside polygon, but will return false - Polygon testRing{{{-9.228515625, -17.560246503294888}, - {-2.4609375, -16.04581345375217}, - {-9.228515625, -17.560246503294888}}}; + Polygon testRing{ + {{-9.228515625, -17.560246503294888}, + {-2.4609375, -16.04581345375217}, + {-9.228515625, -17.560246503294888}}}; auto geoPoly = convertGeometry(testRing, canonicalTileID); StubGeometryTileFeature polyFeature(FeatureType::Polygon, geoPoly); @@ -293,8 +346,8 @@ TEST(PropertyExpression, WithinExpression) { auto geoLine1 = convertGeometry(testLine1, canonicalTileID); StubGeometryTileFeature lineFeature1(FeatureType::LineString, geoLine1); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature0).withCanonicalTileID(&canonicalTileID)); + auto evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature0).withCanonicalTileID(&canonicalTileID) + ); EXPECT_TRUE(evaluatedResult); evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature1).withCanonicalTileID(&canonicalTileID)); EXPECT_FALSE(evaluatedResult); @@ -302,7 +355,7 @@ TEST(PropertyExpression, WithinExpression) { // evaluation test with valid geojson source and valid point features { - auto getPointFeature = [&canonicalTileID](const Point& testPoint) -> StubGeometryTileFeature { + auto getPointFeature = [&canonicalTileID](const Point &testPoint) -> StubGeometryTileFeature { auto geoPoint = convertGeometry(testPoint, canonicalTileID); StubGeometryTileFeature pointFeature(FeatureType::Point, geoPoint); return pointFeature; @@ -310,8 +363,8 @@ TEST(PropertyExpression, WithinExpression) { // check `within` algorithm auto pointFeature = getPointFeature(Point(-10.72265625, -7.27529233637217)); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID)); + auto evaluatedResult = propExpr.evaluate(EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID) + ); EXPECT_FALSE(evaluatedResult); pointFeature = getPointFeature(Point(-7.646484374999999, -12.382928338487396)); @@ -418,8 +471,8 @@ TEST(PropertyExpression, WithinExpressionAntiMeridian) { auto geoLine1 = convertGeometry(testLine1, canonicalTileID); StubGeometryTileFeature lineFeature1(FeatureType::LineString, geoLine1); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature0).withCanonicalTileID(&canonicalTileID)); + auto evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature0).withCanonicalTileID(&canonicalTileID) + ); EXPECT_TRUE(evaluatedResult); evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature1).withCanonicalTileID(&canonicalTileID)); EXPECT_FALSE(evaluatedResult); @@ -439,7 +492,7 @@ TEST(PropertyExpression, WithinExpressionAntiMeridian) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - auto getPointFeature = [&canonicalTileID](const Point& testPoint) -> StubGeometryTileFeature { + auto getPointFeature = [&canonicalTileID](const Point &testPoint) -> StubGeometryTileFeature { auto geoPoint = convertGeometry(testPoint, canonicalTileID); StubGeometryTileFeature pointFeature(FeatureType::Point, geoPoint); return pointFeature; @@ -447,8 +500,8 @@ TEST(PropertyExpression, WithinExpressionAntiMeridian) { // check `within` algorithm auto pointFeature = getPointFeature(Point(177, 62.5)); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID)); + auto evaluatedResult = propExpr.evaluate(EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID) + ); EXPECT_TRUE(evaluatedResult); pointFeature = getPointFeature(Point(180, 62.5)); @@ -517,10 +570,10 @@ TEST(PropertyExpression, DistanceExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(491.307, evaluatedResult, 0.01); - } // Evaluation test with Point to MultiPoint distance @@ -539,13 +592,14 @@ TEST(PropertyExpression, DistanceExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - MultiPoint featurePoint{{24.931159615516663, 60.16733387258923}, - {24.936089515686035, 60.169033745694826}}; + MultiPoint featurePoint{ + {24.931159615516663, 60.16733387258923}, {24.936089515686035, 60.169033745694826}}; auto geoPoint = convertGeometry(featurePoint, canonicalTileID); StubGeometryTileFeature feature(FeatureType::Point, geoPoint); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&feature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&feature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(158.541, evaluatedResult, 0.01); } @@ -565,14 +619,16 @@ TEST(PropertyExpression, DistanceExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - LineString line{{24.93621826171875, 60.17131789507754}, - {24.941453933715817, 60.170229208170014}, - {24.941110610961914, 60.16850004304534}}; + LineString line{ + {24.93621826171875, 60.17131789507754}, + {24.941453933715817, 60.170229208170014}, + {24.941110610961914, 60.16850004304534}}; auto geoLine = convertGeometry(line, canonicalTileID); StubGeometryTileFeature lineFeature(FeatureType::LineString, geoLine); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(107.211, evaluatedResult, 0.01); } @@ -600,8 +656,9 @@ TEST(PropertyExpression, DistanceExpression) { auto geoLine = convertGeometry(lines, canonicalTileID); StubGeometryTileFeature lineFeature(FeatureType::LineString, geoLine); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(59.845, evaluatedResult, 0.01); } @@ -614,7 +671,8 @@ TEST(PropertyExpression, DistanceExpression) { [](const mapbox::feature::feature_collection &features) { return mbgl::Feature(features.front()).geometry; }, - [](const auto &) { return mapbox::geometry::empty(); }); + [](const auto &) { return mapbox::geometry::empty(); } + ); return StubGeometryTileFeature(type, convertGeometry(geometry, canonical)); }; @@ -629,7 +687,8 @@ TEST(PropertyExpression, DistanceExpression) { PropertyExpression propExpr(std::move(expression)); auto evaluatedResult = propExpr.evaluate( - EvaluationContext(&multiPointsFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiPointsFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(283.60, evaluatedResult, 0.1); } @@ -644,7 +703,8 @@ TEST(PropertyExpression, DistanceExpression) { PropertyExpression propExpr(std::move(expression)); auto evaluatedResult = propExpr.evaluate( - EvaluationContext(&multiLineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiLineFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(258.691, evaluatedResult, 0.01); // ----------------- switch feature and argument ----------------- @@ -657,7 +717,8 @@ TEST(PropertyExpression, DistanceExpression) { PropertyExpression propExpr1(std::move(expression1)); auto evaluatedResult1 = propExpr1.evaluate( - EvaluationContext(&multiPointsFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiPointsFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(258.691, evaluatedResult1, 0.01); } @@ -671,16 +732,18 @@ TEST(PropertyExpression, DistanceExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(180.408, evaluatedResult, 0.01); } // Evaluation test with MultiPoints to MutltiLineString distance { const auto multiPoints = mbgl::util::read_file("test/fixtures/geometry_data/multi_point_2.geojson"); - const auto multiLineFeature = - getFeature("multi_line_string_1.geojson", FeatureType::LineString, canonicalTileID); + const auto multiLineFeature = getFeature( + "multi_line_string_1.geojson", FeatureType::LineString, canonicalTileID + ); std::stringstream ss; ss << std::string(R"(["distance", )") << multiPoints << std::string(R"( ])"); auto expression = createExpression(ss.str().c_str()); @@ -688,15 +751,17 @@ TEST(PropertyExpression, DistanceExpression) { PropertyExpression propExpr(std::move(expression)); auto evaluatedResult = propExpr.evaluate( - EvaluationContext(&multiLineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiLineFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(937.632, evaluatedResult, 0.01); } // Evaluation test with LineString to MutltiLineString distance { const auto LineString1 = mbgl::util::read_file("test/fixtures/geometry_data/line_string_1.geojson"); - const auto multiLineFeature = - getFeature("multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID); + const auto multiLineFeature = getFeature( + "multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID + ); std::stringstream ss; ss << std::string(R"(["distance", )") << LineString1 << std::string(R"( ])"); auto expression = createExpression(ss.str().c_str()); @@ -704,15 +769,17 @@ TEST(PropertyExpression, DistanceExpression) { PropertyExpression propExpr(std::move(expression)); auto evaluatedResult = propExpr.evaluate( - EvaluationContext(&multiLineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiLineFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(17.511, evaluatedResult, 0.01); } // Evaluation test with MultiLineString to MutltiLineString distance { const auto multiLineString1 = mbgl::util::read_file("test/fixtures/geometry_data/multi_line_string_1.geojson"); - const auto multiLineFeature = - getFeature("multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID); + const auto multiLineFeature = getFeature( + "multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID + ); std::stringstream ss; ss << std::string(R"(["distance", )") << multiLineString1 << std::string(R"( ])"); auto expression = createExpression(ss.str().c_str()); @@ -720,7 +787,8 @@ TEST(PropertyExpression, DistanceExpression) { PropertyExpression propExpr(std::move(expression)); auto evaluatedResult = propExpr.evaluate( - EvaluationContext(&multiLineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiLineFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(384.109, evaluatedResult, 0.01); } @@ -735,12 +803,14 @@ TEST(PropertyExpression, DistanceExpression) { const auto multiPointFeature1 = getFeature("multi_point_3.geojson", FeatureType::Point, canonicalTileID); auto evaluatedResult = propExpr.evaluate( - EvaluationContext(&multiPointFeature1).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiPointFeature1).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(27.917, evaluatedResult, 0.01); const auto multiPointFeature2 = getFeature("multi_point_2.geojson", FeatureType::Point, canonicalTileID); evaluatedResult = propExpr.evaluate( - EvaluationContext(&multiPointFeature2).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiPointFeature2).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(0.0, evaluatedResult, 0.01); } @@ -753,16 +823,20 @@ TEST(PropertyExpression, DistanceExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - const auto multiLineFeature1 = - getFeature("multi_line_string_1.geojson", FeatureType::LineString, canonicalTileID); + const auto multiLineFeature1 = getFeature( + "multi_line_string_1.geojson", FeatureType::LineString, canonicalTileID + ); auto evaluatedResult = propExpr.evaluate( - EvaluationContext(&multiLineFeature1).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiLineFeature1).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(193.450, evaluatedResult, 0.01); - const auto multiLineFeature2 = - getFeature("multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID); - evaluatedResult = propExpr.evaluate(EvaluationContext(&multiLineFeature2).withCanonicalTileID(&canonicalTileID), - invalidResult); + const auto multiLineFeature2 = getFeature( + "multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID + ); + evaluatedResult = propExpr.evaluate( + EvaluationContext(&multiLineFeature2).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(0.0, evaluatedResult, 0.01); } @@ -775,16 +849,18 @@ TEST(PropertyExpression, DistanceExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - Polygon polygon{{{24.94171142578125, 60.16777419352904}, - {24.948577880859375, 60.16777419352904}, - {24.948577880859375, 60.170122472217564}, - {24.94171142578125, 60.170122472217564}, - {24.94171142578125, 60.16777419352904}}}; + Polygon polygon{ + {{24.94171142578125, 60.16777419352904}, + {24.948577880859375, 60.16777419352904}, + {24.948577880859375, 60.170122472217564}, + {24.94171142578125, 60.170122472217564}, + {24.94171142578125, 60.16777419352904}}}; auto geoPolygon = convertGeometry(polygon, canonicalTileID); StubGeometryTileFeature polygonFeature(FeatureType::Polygon, geoPolygon); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&polygonFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&polygonFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(203.876, evaluatedResult, 0.01); } @@ -799,7 +875,8 @@ TEST(PropertyExpression, DistanceExpression) { const auto multiPolygonFeature = getFeature("multi_polygon_2.geojson", FeatureType::Polygon, canonicalTileID); auto evaluatedResult = propExpr.evaluate( - EvaluationContext(&multiPolygonFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + EvaluationContext(&multiPolygonFeature).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(21.446, evaluatedResult, 0.01); } @@ -819,42 +896,48 @@ TEST(PropertyExpression, DistanceExpression) { PropertyExpression propExpr(std::move(expression)); // polygon1 is fully inside polygon - Polygon polygon1{{{24.941797256469727, 60.16850004304534}, - {24.94235515594482, 60.16850004304534}, - {24.94235515594482, 60.169439353910285}, - {24.941797256469727, 60.169439353910285}, - {24.941797256469727, 60.16850004304534}}}; + Polygon polygon1{ + {{24.941797256469727, 60.16850004304534}, + {24.94235515594482, 60.16850004304534}, + {24.94235515594482, 60.169439353910285}, + {24.941797256469727, 60.169439353910285}, + {24.941797256469727, 60.16850004304534}}}; auto geoPolygon1 = convertGeometry(polygon1, canonicalTileID); StubGeometryTileFeature polygonFeature1(FeatureType::Polygon, geoPolygon1); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&polygonFeature1).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&polygonFeature1).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(0.0, evaluatedResult, 0.01); // polygon2's line is intersecting polygon, but no point is inside polygon - Polygon polygon2{{{24.943385124206543, 60.166066249059554}, - {24.94596004486084, 60.166066249059554}, - {24.94596004486084, 60.1714246271462}, - {24.943385124206543, 60.1714246271462}, - {24.943385124206543, 60.166066249059554}}}; + Polygon polygon2{ + {{24.943385124206543, 60.166066249059554}, + {24.94596004486084, 60.166066249059554}, + {24.94596004486084, 60.1714246271462}, + {24.943385124206543, 60.1714246271462}, + {24.943385124206543, 60.166066249059554}}}; auto geoPolygon2 = convertGeometry(polygon2, canonicalTileID); StubGeometryTileFeature polygonFeature2(FeatureType::Polygon, geoPolygon2); - evaluatedResult = - propExpr.evaluate(EvaluationContext(&polygonFeature2).withCanonicalTileID(&canonicalTileID), invalidResult); + evaluatedResult = propExpr.evaluate( + EvaluationContext(&polygonFeature2).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(0.0, evaluatedResult, 0.01); // one of polygon3's point is inside polygon - Polygon polygon3{{{24.94797706604004, 60.1694607015724}, - {24.952354431152344, 60.1694607015724}, - {24.952354431152344, 60.17082692309542}, - {24.94797706604004, 60.17082692309542}, - {24.94797706604004, 60.1694607015724}}}; + Polygon polygon3{ + {{24.94797706604004, 60.1694607015724}, + {24.952354431152344, 60.1694607015724}, + {24.952354431152344, 60.17082692309542}, + {24.94797706604004, 60.17082692309542}, + {24.94797706604004, 60.1694607015724}}}; auto geoPolygon3 = convertGeometry(polygon3, canonicalTileID); StubGeometryTileFeature polygonFeature3(FeatureType::Polygon, geoPolygon3); - evaluatedResult = - propExpr.evaluate(EvaluationContext(&polygonFeature3).withCanonicalTileID(&canonicalTileID), invalidResult); + evaluatedResult = propExpr.evaluate( + EvaluationContext(&polygonFeature3).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(0.0, evaluatedResult, 0.01); // lineString1 is within polygon @@ -862,8 +945,9 @@ TEST(PropertyExpression, DistanceExpression) { auto geoLineString1 = convertGeometry(lineString1, canonicalTileID); StubGeometryTileFeature lineFeature1(FeatureType::LineString, geoLineString1); - evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature1).withCanonicalTileID(&canonicalTileID), invalidResult); + evaluatedResult = propExpr.evaluate( + EvaluationContext(&lineFeature1).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(0.0, evaluatedResult, 0.01); // lineString2 is intersecting the polygon but its points are outside the polygon @@ -871,8 +955,9 @@ TEST(PropertyExpression, DistanceExpression) { auto geoLineString2 = convertGeometry(lineString2, canonicalTileID); StubGeometryTileFeature lineFeature2(FeatureType::LineString, geoLineString2); - evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature2).withCanonicalTileID(&canonicalTileID), invalidResult); + evaluatedResult = propExpr.evaluate( + EvaluationContext(&lineFeature2).withCanonicalTileID(&canonicalTileID), invalidResult + ); EXPECT_NEAR(0.0, evaluatedResult, 0.01); } } diff --git a/test/style/source.test.cpp b/test/style/source.test.cpp index baee9e8144f..b1c3a971a28 100644 --- a/test/style/source.test.cpp +++ b/test/style/source.test.cpp @@ -61,54 +61,49 @@ class SourceTest { Transform transform; TransformState transformState; Style style{fileSource, 1}; - AnnotationManager annotationManager { style }; + AnnotationManager annotationManager{style}; ImageManager imageManager; GlyphManager glyphManager; TileParameters tileParameters(MapMode mapMode = MapMode::Continuous) { - return {1.0, - MapDebugOptions(), - transformState, - fileSource, - mapMode, - annotationManager.makeWeakPtr(), - imageManager, - glyphManager, - 0}; + return { + 1.0, + MapDebugOptions(), + transformState, + fileSource, + mapMode, + annotationManager.makeWeakPtr(), + imageManager, + glyphManager, + 0}; }; SourceTest() { // Squelch logging. Log::setObserver(std::make_unique()); - transform.resize({ 512, 512 }); + transform.resize({512, 512}); transform.jumpTo(CameraOptions().withCenter(LatLng()).withZoom(0.0)); transformState = transform.getState(); } - void run() { - loop.run(); - } + void run() { loop.run(); } - void end() { - loop.stop(); - } + void end() { loop.stop(); } }; TEST(Source, LoadingFail) { SourceTest test; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; - test.styleObserver.sourceError = [&] (Source& source, std::exception_ptr error) { + test.styleObserver.sourceError = [&](Source& source, std::exception_ptr error) { EXPECT_EQ("source", source.getID()); EXPECT_EQ("Failed by the test case", util::toString(error)); test.end(); @@ -124,14 +119,14 @@ TEST(Source, LoadingFail) { TEST(Source, LoadingCorrupt) { SourceTest test; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; response.data = std::make_unique("CORRUPTED"); return response; }; - test.styleObserver.sourceError = [&] (Source& source, std::exception_ptr error) { + test.styleObserver.sourceError = [&](Source& source, std::exception_ptr error) { EXPECT_EQ("source", source.getID()); EXPECT_EQ("Invalid value. at offset 0", util::toString(error)); test.end(); @@ -147,28 +142,29 @@ TEST(Source, LoadingCorrupt) { TEST(Source, RasterTileEmpty) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; }; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource& source_, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource& source_, const OverscaledTileID&) { EXPECT_EQ("source", source_.baseImpl->id); test.end(); }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -182,28 +178,29 @@ TEST(Source, RasterTileEmpty) { TEST(Source, RasterDEMTileEmpty) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; }; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterDEMSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource& source_, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource& source_, const OverscaledTileID&) { EXPECT_EQ("source", source_.baseImpl->id); test.end(); }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -217,7 +214,7 @@ TEST(Source, RasterDEMTileEmpty) { TEST(Source, VectorTileEmpty) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; @@ -226,21 +223,22 @@ TEST(Source, VectorTileEmpty) { LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; VectorSource source("source", tileset); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource& source_, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource& source_, const OverscaledTileID&) { EXPECT_EQ("source", source_.baseImpl->id); test.end(); }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -254,30 +252,30 @@ TEST(Source, VectorTileEmpty) { TEST(Source, RasterTileFail) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(SourceType::Raster, source_.baseImpl->type); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_EQ("Failed by the test case", util::toString(error)); - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(SourceType::Raster, source_.baseImpl->type); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_EQ("Failed by the test case", util::toString(error)); + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -289,30 +287,30 @@ TEST(Source, RasterTileFail) { TEST(Source, RasterDEMTileFail) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterDEMSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(SourceType::RasterDEM, source_.baseImpl->type); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_EQ("Failed by the test case", util::toString(error)); - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(SourceType::RasterDEM, source_.baseImpl->type); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_EQ("Failed by the test case", util::toString(error)); + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -324,32 +322,32 @@ TEST(Source, RasterDEMTileFail) { TEST(Source, VectorTileFail) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; VectorSource source("source", tileset); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(SourceType::Vector, source_.baseImpl->type); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_EQ("Failed by the test case", util::toString(error)); - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(SourceType::Vector, source_.baseImpl->type); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_EQ("Failed by the test case", util::toString(error)); + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -361,29 +359,31 @@ TEST(Source, VectorTileFail) { TEST(Source, RasterTileCorrupt) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.data = std::make_unique("CORRUPTED"); return response; }; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(source_.baseImpl->type, SourceType::Raster); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_TRUE(bool(error)); - // Not asserting on platform-specific error text. - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(source_.baseImpl->type, SourceType::Raster); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_TRUE(bool(error)); + // Not asserting on platform-specific error text. + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -395,29 +395,32 @@ TEST(Source, RasterTileCorrupt) { TEST(Source, RasterDEMTileCorrupt) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.data = std::make_unique("CORRUPTED"); return response; }; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties };; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; + ; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterDEMSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(source_.baseImpl->type, SourceType::RasterDEM); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_TRUE(bool(error)); - // Not asserting on platform-specific error text. - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(source_.baseImpl->type, SourceType::RasterDEM); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_TRUE(bool(error)); + // Not asserting on platform-specific error text. + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -429,7 +432,7 @@ TEST(Source, RasterDEMTileCorrupt) { TEST(Source, VectorTileCorrupt) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.data = std::make_unique("CORRUPTED"); return response; @@ -438,21 +441,23 @@ TEST(Source, VectorTileCorrupt) { LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; VectorSource source("source", tileset); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(source_.baseImpl->type, SourceType::Vector); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_EQ(util::toString(error), "unknown pbf field type exception"); - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(source_.baseImpl->type, SourceType::Vector); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_EQ(util::toString(error), "unknown pbf field type exception"); + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -464,26 +469,27 @@ TEST(Source, VectorTileCorrupt) { TEST(Source, RasterTileCancel) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { test.end(); return std::optional(); }; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource&, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource&, const OverscaledTileID&) { FAIL() << "Should never be called"; }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -497,26 +503,27 @@ TEST(Source, RasterTileCancel) { TEST(Source, RasterDEMTileCancel) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { test.end(); return std::optional(); }; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterDEMSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource&, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource&, const OverscaledTileID&) { FAIL() << "Should never be called"; }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -530,7 +537,7 @@ TEST(Source, RasterDEMTileCancel) { TEST(Source, VectorTileCancel) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { test.end(); return std::optional(); }; @@ -538,20 +545,21 @@ TEST(Source, VectorTileCancel) { LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; VectorSource source("source", tileset); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource&, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource&, const OverscaledTileID&) { FAIL() << "Should never be called"; }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -566,28 +574,31 @@ TEST(Source, RasterTileAttribution) { SourceTest test; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; - std::string mapboxOSM = ("© Mapbox " - "©️ OpenStreetMap"); + std::string mapboxOSM = + ("© Mapbox " + "©️ OpenStreetMap"); - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; }; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; - response.data = std::make_unique(R"TILEJSON({ "tilejson": "2.1.0", "attribution": ")TILEJSON" + - mapboxOSM + - R"TILEJSON(", "tiles": [ "tiles" ] })TILEJSON"); + response.data = std::make_unique( + R"TILEJSON({ "tilejson": "2.1.0", "attribution": ")TILEJSON" + mapboxOSM + + R"TILEJSON(", "tiles": [ "tiles" ] })TILEJSON" + ); return response; }; - test.styleObserver.sourceChanged = [&] (Source& source) { + test.styleObserver.sourceChanged = [&](Source& source) { EXPECT_EQ(mapboxOSM, source.getAttribution()); EXPECT_FALSE(mapboxOSM.find("©️ OpenStreetMap") == std::string::npos); test.end(); @@ -607,27 +618,29 @@ TEST(Source, RasterDEMTileAttribution) { SourceTest test; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; std::string mapbox = ("© Mapbox "); - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; }; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; - response.data = std::make_unique(R"TILEJSON({ "tilejson": "2.1.0", "attribution": ")TILEJSON" + - mapbox + - R"TILEJSON(", "tiles": [ "tiles" ] })TILEJSON"); + response.data = std::make_unique( + R"TILEJSON({ "tilejson": "2.1.0", "attribution": ")TILEJSON" + mapbox + + R"TILEJSON(", "tiles": [ "tiles" ] })TILEJSON" + ); return response; }; - test.styleObserver.sourceChanged = [&] (Source& source) { + test.styleObserver.sourceChanged = [&](Source& source) { EXPECT_EQ(mapbox, source.getAttribution()); test.end(); }; @@ -645,14 +658,16 @@ TEST(Source, RasterDEMTileAttribution) { TEST(Source, GeoJSonSourceUrlUpdate) { SourceTest test; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; - response.data = std::make_unique(R"({"geometry": {"type": "Point", "coordinates": [1.1, 1.1]}, "type": "Feature", "properties": {}})"); + response.data = std::make_unique( + R"({"geometry": {"type": "Point", "coordinates": [1.1, 1.1]}, "type": "Feature", "properties": {}})" + ); return response; }; - test.styleObserver.sourceDescriptionChanged = [&] (Source&) { + test.styleObserver.sourceDescriptionChanged = [&](Source&) { // Should be called (test will hang if it doesn't) test.end(); }; @@ -664,7 +679,7 @@ TEST(Source, GeoJSonSourceUrlUpdate) { source.loadDescription(*test.fileSource); // Schedule an update - test.loop.invoke([&] () { + test.loop.invoke([&]() { // Update the url source.setURL(std::string("http://source-url.ext")); }); @@ -675,13 +690,13 @@ TEST(Source, GeoJSonSourceUrlUpdate) { TEST(Source, ImageSourceImageUpdate) { SourceTest test; - test.fileSource->response = [&] (const Resource& resource) { + test.fileSource->response = [&](const Resource& resource) { EXPECT_EQ("http://url", resource.url); Response response; response.data = std::make_unique(util::read_file("test/fixtures/image/no_profile.png")); return response; }; - test.styleObserver.sourceChanged = [&] (Source&) { + test.styleObserver.sourceChanged = [&](Source&) { // Should be called (test will hang if it doesn't) test.end(); }; @@ -693,14 +708,14 @@ TEST(Source, ImageSourceImageUpdate) { // Load initial, so the source state will be loaded=true source.loadDescription(*test.fileSource); - PremultipliedImage rgba({ 1, 1 }); + PremultipliedImage rgba({1, 1}); rgba.data[0] = 255; rgba.data[1] = 254; rgba.data[2] = 253; rgba.data[3] = 0; // Schedule an update - test.loop.invoke([&] () { + test.loop.invoke([&]() { // Update the url source.setImage(std::move(rgba)); }); @@ -715,15 +730,16 @@ TEST(Source, CustomGeometrySourceSetTileData) { LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; - test.renderSourceObserver.tileChanged = [&] (RenderSource& source_, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource& source_, const OverscaledTileID&) { EXPECT_EQ("source", source_.baseImpl->id); test.end(); }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -731,9 +747,9 @@ TEST(Source, CustomGeometrySourceSetTileData) { renderSource->setObserver(&test.renderSourceObserver); renderSource->update(source.baseImpl, layers, true, true, test.tileParameters()); - test.loop.invoke([&] () { + test.loop.invoke([&]() { // Set Tile Data - source.setTileData(CanonicalTileID(0, 0, 0), GeoJSON{ FeatureCollection{} }); + source.setTileData(CanonicalTileID(0, 0, 0), GeoJSON{FeatureCollection{}}); }); test.run(); @@ -745,7 +761,8 @@ class FakeTileSource; class FakeTile : public Tile { public: FakeTile(FakeTileSource& source_, const OverscaledTileID& tileID) - : Tile(Tile::Kind::Geometry, tileID), source(source_) { + : Tile(Tile::Kind::Geometry, tileID), + source(source_) { renderable = true; } void setNecessity(TileNecessity necessity) override; @@ -763,21 +780,26 @@ class FakeTileSource : public RenderTileSetSource { MOCK_METHOD1(tileSetNecessity, void(TileNecessity)); MOCK_METHOD1(tileSetMinimumUpdateInterval, void(Duration)); - explicit FakeTileSource(Immutable impl_) : RenderTileSetSource(std::move(impl_)) {} - void updateInternal(const Tileset& tileset, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) override { - tilePyramid.update(layers, - needsRendering, - needsRelayout, - parameters, - *baseImpl, - util::tileSize_I, - tileset.zoomRange, - tileset.bounds, - [&](const OverscaledTileID& tileID) { return std::make_unique(*this, tileID); }); + explicit FakeTileSource(Immutable impl_) + : RenderTileSetSource(std::move(impl_)) {} + void updateInternal( + const Tileset& tileset, + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters + ) override { + tilePyramid.update( + layers, + needsRendering, + needsRelayout, + parameters, + *baseImpl, + util::tileSize_I, + tileset.zoomRange, + tileset.bounds, + [&](const OverscaledTileID& tileID) { return std::make_unique(*this, tileID); } + ); } const std::optional& getTileset() const override { @@ -871,9 +893,9 @@ TEST(Source, RenderTileSetSourceUpdate) { MOCK_METHOD0(mockedUpdateInternal, void()); - void updateInternal(const Tileset&, - const std::vector>&, - const bool, const bool, const TileParameters&) override { + void + updateInternal(const Tileset&, const std::vector>&, const bool, const bool, const TileParameters&) + override { mockedUpdateInternal(); } @@ -882,14 +904,15 @@ TEST(Source, RenderTileSetSourceUpdate) { } }; - VectorSource initialized("source", Tileset{ {"tiles"} }); + VectorSource initialized("source", Tileset{{"tiles"}}); initialized.loadDescription(*test.fileSource); - FakeRenderTileSetSource renderTilesetSource { initialized.baseImpl }; + FakeRenderTileSetSource renderTilesetSource{initialized.baseImpl}; LineLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = + makeMutable(staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; // Check that `updateInternal()` is called even if the updated source has not yet loaded description. EXPECT_CALL(renderTilesetSource, mockedUpdateInternal()).Times(2); @@ -904,7 +927,8 @@ TEST(Source, GeoJSONSourceTilesAfterDataReset) { SourceTest test; GeoJSONSource source("source"); auto geoJSONData = GeoJSONData::create(mapbox::geojson::parse( - R"({"geometry": {"type": "Point", "coordinates": [1.1, 1.1]}, "type": "Feature", "properties": {}})")); + R"({"geometry": {"type": "Point", "coordinates": [1.1, 1.1]}, "type": "Feature", "properties": {}})" + )); source.setGeoJSONData(geoJSONData); RenderGeoJSONSource renderSource{staticImmutableCast(source.baseImpl)}; @@ -975,6 +999,8 @@ TEST(Source, SetMaxParentOverscaleFactor) { EXPECT_EQ( 1u, log.count( - {EventSeverity::Warning, Event::Style, -1, "Parent tile overscale factor will cap prefetch delta to 3"})); + {EventSeverity::Warning, Event::Style, -1, "Parent tile overscale factor will cap prefetch delta to 3"} + ) + ); EXPECT_EQ(0u, log.uncheckedCount()); } diff --git a/test/style/style.test.cpp b/test/style/style.test.cpp index c02c274d893..cfcb145a1a7 100644 --- a/test/style/style.test.cpp +++ b/test/style/style.test.cpp @@ -23,7 +23,7 @@ TEST(Style, Properties) { util::RunLoop loop; auto fileSource = std::make_shared(); - Style::Impl style { fileSource, 1.0 }; + Style::Impl style{fileSource, 1.0}; style.loadJSON(R"STYLE({"name": "Test"})STYLE"); ASSERT_EQ("Test", style.getName()); @@ -34,7 +34,7 @@ TEST(Style, Properties) { style.loadJSON(R"STYLE({"bearing": 24})STYLE"); ASSERT_EQ("", style.getName()); - ASSERT_EQ(LatLng {}, *style.getDefaultCamera().center); + ASSERT_EQ(LatLng{}, *style.getDefaultCamera().center); ASSERT_EQ(24, *style.getDefaultCamera().bearing); style.loadJSON(R"STYLE({"zoom": 13.3})STYLE"); @@ -55,7 +55,7 @@ TEST(Style, Properties) { style.loadJSON(R"STYLE({"name": 23, "center": {}, "bearing": "north", "zoom": null, "pitch": "wide"})STYLE"); ASSERT_EQ("", style.getName()); - ASSERT_EQ(LatLng {}, *style.getDefaultCamera().center); + ASSERT_EQ(LatLng{}, *style.getDefaultCamera().center); ASSERT_EQ(0, *style.getDefaultCamera().zoom); ASSERT_EQ(0, *style.getDefaultCamera().bearing); ASSERT_EQ(0, *style.getDefaultCamera().pitch); @@ -65,12 +65,12 @@ TEST(Style, DuplicateSource) { util::RunLoop loop; auto fileSource = std::make_shared(); - Style::Impl style { fileSource, 1.0 }; + Style::Impl style{fileSource, 1.0}; style.loadJSON(util::read_file("test/fixtures/resources/style-unused-sources.json")); style.addSource(std::make_unique("sourceId", "mptiler://tiles/contours")); - + try { style.addSource(std::make_unique("sourceId", "mptiler://tiles/contours")); FAIL() << "Should not have been allowed to add a duplicate source id"; @@ -86,7 +86,7 @@ TEST(Style, RemoveSourceInUse) { Log::setObserver(std::unique_ptr(log)); auto fileSource = std::make_shared(); - Style::Impl style { fileSource, 1.0 }; + Style::Impl style{fileSource, 1.0}; style.loadJSON(util::read_file("test/fixtures/resources/style-unused-sources.json")); @@ -98,11 +98,11 @@ TEST(Style, RemoveSourceInUse) { ASSERT_EQ(nullptr, removed); ASSERT_NE(nullptr, style.getSource("sourceId")); - const FixtureLogObserver::LogMessage logMessage { - EventSeverity::Warning, - Event::General, - int64_t(-1), - "Source 'sourceId' is in use, cannot remove", + const FixtureLogObserver::LogMessage logMessage{ + EventSeverity::Warning, + Event::General, + int64_t(-1), + "Source 'sourceId' is in use, cannot remove", }; #if defined(WIN32) diff --git a/test/style/style_image.test.cpp b/test/style/style_image.test.cpp index 7bc58592417..28b79d34e34 100644 --- a/test/style/style_image.test.cpp +++ b/test/style/style_image.test.cpp @@ -8,7 +8,7 @@ using namespace mbgl; TEST(StyleImage, ZeroWidth) { try { - style::Image("test", PremultipliedImage({ 0, 16 }), 2.0f); + style::Image("test", PremultipliedImage({0, 16}), 2.0f); FAIL() << "Expected exception"; } catch (util::StyleImageException& ex) { EXPECT_STREQ("dimensions may not be zero", ex.what()); @@ -17,7 +17,7 @@ TEST(StyleImage, ZeroWidth) { TEST(StyleImage, ZeroHeight) { try { - style::Image("test", PremultipliedImage({ 16, 0 }), 2.0f); + style::Image("test", PremultipliedImage({16, 0}), 2.0f); FAIL() << "Expected exception"; } catch (util::StyleImageException& ex) { EXPECT_STREQ("dimensions may not be zero", ex.what()); @@ -26,7 +26,7 @@ TEST(StyleImage, ZeroHeight) { TEST(StyleImage, ZeroRatio) { try { - style::Image("test", PremultipliedImage({ 16, 16 }), 0.0f); + style::Image("test", PremultipliedImage({16, 16}), 0.0f); FAIL() << "Expected exception"; } catch (util::StyleImageException& ex) { EXPECT_STREQ("pixelRatio may not be <= 0", ex.what()); @@ -34,14 +34,14 @@ TEST(StyleImage, ZeroRatio) { } TEST(StyleImage, Retina) { - style::Image image("test", PremultipliedImage({ 32, 24 }), 2.0f); + style::Image image("test", PremultipliedImage({32, 24}), 2.0f); EXPECT_EQ(32u, image.getImage().size.width); EXPECT_EQ(24u, image.getImage().size.height); EXPECT_EQ(2, image.getPixelRatio()); } TEST(StyleImage, FractionalRatio) { - style::Image image("test", PremultipliedImage({ 20, 12 }), 1.5f); + style::Image image("test", PremultipliedImage({20, 12}), 1.5f); EXPECT_EQ(20u, image.getImage().size.width); EXPECT_EQ(12u, image.getImage().size.height); EXPECT_EQ(1.5, image.getPixelRatio()); @@ -111,7 +111,13 @@ TEST(StyleImage, InvalidContent) { TEST(StyleImage, StretchContent) { style::Image image( - "test", PremultipliedImage({16, 16}), 1, {{2.0f, 14.0f}}, {{0.0f, 4.0f}, {12.0f, 16.0f}}, style::ImageContent{2, 2, 14, 14}); + "test", + PremultipliedImage({16, 16}), + 1, + {{2.0f, 14.0f}}, + {{0.0f, 4.0f}, {12.0f, 16.0f}}, + style::ImageContent{2, 2, 14, 14} + ); EXPECT_EQ(16u, image.getImage().size.width); EXPECT_EQ(16u, image.getImage().size.height); EXPECT_EQ(1.0, image.getPixelRatio()); diff --git a/test/style/style_layer.test.cpp b/test/style/style_layer.test.cpp index 1417fd1d673..d758bbd03a1 100644 --- a/test/style/style_layer.test.cpp +++ b/test/style/style_layer.test.cpp @@ -37,13 +37,13 @@ using namespace std::literals::string_literals; namespace { -const auto color = Color { 1, 0, 0, 1 }; +const auto color = Color{1, 0, 0, 1}; const auto opacity = 1.0f; const auto radius = 1.0f; const auto blur = 1.0f; const auto pattern = PropertyValue{"foo"}; const auto antialias = false; -const auto translate = std::array {{ 0, 0 }}; +const auto translate = std::array{{0, 0}}; const auto translateAnchor = TranslateAnchorType::Map; const auto lineCap = LineCapType::Round; const auto lineJoin = LineJoinType::Miter; @@ -52,7 +52,7 @@ const auto roundLimit = 1.0f; const auto width = 1.0f; const auto gapWidth = 1.0f; const auto offset = 1.0f; -const auto dashArray = std::vector {}; +const auto dashArray = std::vector{}; const auto hueRotate = 1.0f; const auto brightness = 1.0f; const auto saturation = 1.0f; @@ -225,7 +225,7 @@ TEST(Layer, Observer) { // Notifies observer on filter change. bool filterChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); filterChanged = true; }; @@ -234,7 +234,7 @@ TEST(Layer, Observer) { // Notifies observer on visibility change. bool visibilityChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); visibilityChanged = true; }; @@ -243,7 +243,7 @@ TEST(Layer, Observer) { // Notifies observer on paint property change. bool paintPropertyChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); paintPropertyChanged = true; }; @@ -252,7 +252,7 @@ TEST(Layer, Observer) { // Notifies observer on layout property change. bool layoutPropertyChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); layoutPropertyChanged = true; }; @@ -261,7 +261,7 @@ TEST(Layer, Observer) { // Does not notify observer on no-op visibility change. visibilityChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); visibilityChanged = true; }; @@ -270,7 +270,7 @@ TEST(Layer, Observer) { // Does not notify observer on no-op paint property change. paintPropertyChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); paintPropertyChanged = true; }; @@ -279,7 +279,7 @@ TEST(Layer, Observer) { // Does not notify observer on no-op layout property change. layoutPropertyChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); layoutPropertyChanged = true; }; @@ -292,7 +292,7 @@ TEST(Layer, DuplicateLayer) { // Setup style auto fileSource = std::make_shared(); - Style::Impl style { fileSource, 1.0 }; + Style::Impl style{fileSource, 1.0}; style.loadJSON(util::read_file("test/fixtures/resources/style-unused-sources.json")); // Add initial layer @@ -328,7 +328,7 @@ TEST(Layer, IncompatibleLayer) { namespace { -template class PropertyValueType, typename LayoutType> +template